Recherche avancée

Médias (3)

Mot : - Tags -/plugin

Autres articles (99)

  • Websites made ​​with MediaSPIP

    2 mai 2011, par

    This page lists some websites based on MediaSPIP.

  • Amélioration de la version de base

    13 septembre 2013

    Jolie sélection multiple
    Le plugin Chosen permet d’améliorer l’ergonomie des champs de sélection multiple. Voir les deux images suivantes pour comparer.
    Il suffit pour cela d’activer le plugin Chosen (Configuration générale du site > Gestion des plugins), puis de configurer le plugin (Les squelettes > Chosen) en activant l’utilisation de Chosen dans le site public et en spécifiant les éléments de formulaires à améliorer, par exemple select[multiple] pour les listes à sélection multiple (...)

  • Creating farms of unique websites

    13 avril 2011, par

    MediaSPIP platforms can be installed as a farm, with a single "core" hosted on a dedicated server and used by multiple websites.
    This allows (among other things) : implementation costs to be shared between several different projects / individuals rapid deployment of multiple unique sites creation of groups of like-minded sites, making it possible to browse media in a more controlled and selective environment than the major "open" (...)

Sur d’autres sites (9539)

  • How do I properly enable ffmpeg for matplotlib.animation ?

    7 mars 2017, par spanishgum

    I have covered a lot of ground on stack so far trying to get ffmpeg going so I can make a timelapse video.

    I am on a CentOS 7 machine, running python3.7.0a0.

    python3
    >>> import numpy as np
    >>> np.__version__
    '1.12.0'
    >>> import matplotlib as mpl
    >>> mpl.__version__
    '2.0.0'
    >>> import mpl_toolkits.basemap as base
    >>> base.__version__
    '1.0.7'

    I found this github gist on installing ffmpeg. I used the chromium source, and installed without a prefix option (using the default).

    I have confirmed that ffmpeg is installed, although I don’t know anything about testing whether it works.

    which ffmpeg
    /usr/local/bin/ffmpeg

    ffmpeg -version
    ffmpeg version N-83533-gada281d Copyright (c) 2000-2017 the FFmpeg dev elopers
    built with gcc 4.8.5 (GCC) 20150623 (Red Hat 4.8.5-11
    configuration:
    libavutil      55. 47.100 / 55. 47.100
    libavcodec     57. 80.100 / 57. 80.100
    libavformat    57. 66.102 / 57. 66.102
    libavdevice    57.  2.100 / 57.  2.100
    libavfilter     6. 73.100 /  6. 73.100
    libswscale      4.  3.101 /  4.  3.101
    libswresample   2.  4.100 /  2.  4.100

    I tried to run a few sample examples I found online :

    [1] http://matplotlib.org/examples/animation/basic_example_writer.html

    [2] http://stackoverflow.com/a/23098090/3454650

    Everything works fine up until I try to save the animation file.

    [1]

    anim.save('basic_animation.mp4', writer = FFwriter, fps=30, extra_args=['-vcodec', 'libx264'])

    [2]

    im_ani.save('im.mp4', writer=writer)

    I found here that explictly setting the path to ffmpeg might be necessary so I added this to the top of the test scripts :

    plt.rcParams['animation.ffmpeg_path'] = '/usr/local/bin/ffmpeg'

    I tried a few more tweaks in the code but always get the same response, which I do not know how to begin deciphering :

    Traceback (most recent call last):
     File "testanim.py", line 27, in <module>
       writer.grab_frame()
     File "/usr/local/lib/python3.7/contextlib.py", line 100, in __exit__
       self.gen.throw(type, value, traceback)
     File "/usr/local/lib/python3.7/site-packages/matplotlib/animation.py", line 256, in saving
       self.finish()
     File "/usr/local/lib/python3.7/site-packages/matplotlib/animation.py", line 276, in finish
       self.cleanup()
     File "/usr/local/lib/python3.7/site-packages/matplotlib/animation.py", line 311, in cleanup
       out, err = self._proc.communicate()
     File "/usr/local/lib/python3.7/subprocess.py", line 836, in communicate
       stdout, stderr = self._communicate(input, endtime, timeout)
     File "/usr/local/lib/python3.7/subprocess.py", line 1474, in _communicate
       selector.register(self.stdout, selectors.EVENT_READ)
     File "/usr/local/lib/python3.7/selectors.py", line 351, in register
       key = super().register(fileobj, events, data)
     File "/usr/local/lib/python3.7/selectors.py", line 237, in register
       key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data)
     File "/usr/local/lib/python3.7/selectors.py", line 224, in _fileobj_lookup
       return _fileobj_to_fd(fileobj)
     File "/usr/local/lib/python3.7/selectors.py", line 39, in _fileobj_to_fd
       "{!r}".format(fileobj)) from None
    ValueError: Invalid file object: &lt;_io.BufferedReader name=6>
    </module>

    Is there something with my configuration that is malformed ? I searched google for this error for some time but never found anything relevant to animations / ffmpeg. Any help would be greatly appreciated.


    UPDATE :

    @LordNeckBeard pointed me here : https://trac.ffmpeg.org/wiki/CompilationGuide/Centos

    I ran into problems with installing the x264 encoding dependency. Some files in libavcodec/*.c (in the make output) were reporting undefined references to several functions. After a wild goose chase found this : https://mailman.videolan.org/pipermail/x264-devel/2015-February/010971.html

    To fix the x264 installation, I simply added some configure flags :

    ./configure --enable-static --enable-shared --extra-ldflags="-lswresample -llzma"

    UPDATE :

    So everything installed fine after fixing the libx264 problems. I went ahead and copied the ffmpeg binary from the ffmpeg_build folder into /usr/local/bin/ffmpeg.

    After running the script I was getting problems where ffmpeg could not find the libx264 shared object. I think I will have to recompile everything using different prefixes. My intuition tells me there are old files laying around after I have messed with everything, using some configuration that is broken.

    So I decided maybe I should just try to use NUX : http://linoxide.com/linux-how-to/install-ffmpeg-centos-7/
    I installed ffmpeg using the new rpm, but to no avail. I still was not able to run ffmpeg because of a missing shared object.

    Finally, instead of usiong files copied into my /usr/local/bin folder, I ran ffmpeg directly from the build bin directory. Turns out that this does work properly !

    So in essence, if I want to install ffmpeg system wide, I need to manually compile from sources again but using a nonlocal prefix.

  • QTableWidget and QProcess - update table based on multiple process results

    9 mars 2017, par Spencer

    I have a python program that runs through a QTableWidget and for each item it runs a QProcess (an FFMPEG process to be exact). What I’m trying to do is update the "parent" cell when the process completes. Right now there is a for loop that goes through each row and launches a process for each, and connects the finished signal of that process to a "finished" function, which updates the QTableWidget cell. I’m just having trouble properly telling the function WHICH sell to update - right now I am passing it the index of the current row (seeing as it is being spawned by the for loop) but what happens is by the time the processes start to finish it will only get the last row in the table... I’m quite new to Python and PyQt so it is possible there is some fundamental thing I have wrong here !

    I tried passing the actual QTabelWidgetItem instead of the index but I got this error : "RuntimeError : wrapped C/C++ object of type QTableWidgetItem has been deleted"

    My code, the function "finished" and line #132 are the relevant ones :

    import sys, os, re
    from PyQt4 import QtGui, QtCore

    class BatchTable(QtGui.QTableWidget):
       def __init__(self, parent):
           super(BatchTable, self).__init__(parent)
           self.setAcceptDrops(True)
           self.setColumnCount(4)
           self.setColumnWidth(1,50)
           self.hideColumn(3)
           self.horizontalHeader().setStretchLastSection(True)
           self.setHorizontalHeaderLabels(QtCore.QString("Status;Alpha;File;Full Path").split(";"))

           self.doubleClicked.connect(self.removeProject)

       def removeProject(self, myItem):
           row = myItem.row()
           self.removeRow(row)

       def dragEnterEvent(self, e):
           if e.mimeData().hasFormat('text/uri-list'):
               e.accept()
           else:
               print "nope"
               e.ignore()

       def dragMoveEvent(self, e):
           e.accept()

       def dropEvent(self, e):
           if e.mimeData().hasUrls:
               for url in e.mimeData().urls():
                   chkBoxItem = QtGui.QTableWidgetItem()
                   chkBoxItem.setFlags(QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsEnabled)
                   chkBoxItem.setCheckState(QtCore.Qt.Unchecked)

                   rowPosition = self.rowCount()
                   self.insertRow(rowPosition)
                   self.setItem(rowPosition, 0, QtGui.QTableWidgetItem("Ready"))
                   self.setItem(rowPosition, 1, chkBoxItem)
                   self.setItem(rowPosition, 2, QtGui.QTableWidgetItem(os.path.split(str(url.toLocalFile()))[1]))
                   self.setItem(rowPosition, 3, QtGui.QTableWidgetItem(url.toLocalFile()))
                   self.item(rowPosition, 0).setBackgroundColor(QtGui.QColor(80, 180, 30))

    class ffmpegBatch(QtGui.QWidget):
       def __init__(self):
           super(ffmpegBatch, self).__init__()
           self.initUI()

       def initUI(self):

           self.edit = QtGui.QTextEdit()

           cmdGroup = QtGui.QGroupBox("Commandline arguments")
           fpsLbl = QtGui.QLabel("FPS:")
           self.fpsCombo = QtGui.QComboBox()
           self.fpsCombo.addItem("29.97")
           self.fpsCombo.addItem("23.976")
           hbox1 = QtGui.QHBoxLayout()
           hbox1.addWidget(fpsLbl)
           hbox1.addWidget(self.fpsCombo)
           cmdGroup.setLayout(hbox1)

           saveGroup = QtGui.QGroupBox("Output")
           self.outputLocation = QtGui.QLineEdit()
           self.browseBtn = QtGui.QPushButton("Browse")
           saveLocationBox = QtGui.QHBoxLayout()
           # Todo: add "auto-step up two folders" button
           saveLocationBox.addWidget(self.outputLocation)
           saveLocationBox.addWidget(self.browseBtn)
           saveGroup.setLayout(saveLocationBox)

           runBtn = QtGui.QPushButton("Run Batch Transcode")

           mainBox = QtGui.QVBoxLayout()
           self.table = BatchTable(self)
           # TODO: add "copy from clipboard" feature
           mainBox.addWidget(self.table)
           mainBox.addWidget(cmdGroup)
           mainBox.addWidget(saveGroup)
           mainBox.addWidget(runBtn)
           mainBox.addWidget(self.edit)

           self.setLayout(mainBox)
           self.setGeometry(300, 300, 600, 500)
           self.setWindowTitle('FFMPEG Batch Converter')

           # triggers/events
           runBtn.clicked.connect(self.run)

       def RepresentsInt(self, s):
           try:
               int(s)
               return True
           except ValueError:
               return False

       def run(self):
           if (self.outputLocation.text() == ''):
               return
           for projIndex in range(self.table.rowCount()):
               # collect some data
               ffmpeg_app = "C:\\Program Files\\ffmpeg-20150702-git-03b2b40-win64-static\\bin\\ffmpeg"
               frameRate = self.fpsCombo.currentText()
               inputFile = self.table.model().index(projIndex,3).data().toString()
               outputPath = self.outputLocation.text()
               outputPath = outputPath.replace("/", "\\")

               # format the input for ffmpeg
               # find how the exact number range, stored as 'd'
               imageName = os.path.split(str(inputFile))[1]
               imageName, imageExt = os.path.splitext(imageName)
               length = len(imageName)
               d = 0
               while (self.RepresentsInt(imageName[length-2:length-1]) == True):
                   length = length-1
                   d = d+1
               inputPath = os.path.split(str(inputFile))[0]
               inputFile = imageName[0:length-1]
               inputFile = inputPath + "/" + inputFile + "%" + str(d+1) + "d" + imageExt
               inputFile = inputFile.replace("/", "\\")

               # format the output
               outputFile = outputPath + "\\" + imageName[0:length-2] + ".mov"


               # build the commandline
               cmd = '"' + ffmpeg_app + '"' + ' -y -r ' + frameRate + ' -i ' + '"' + inputFile + '"' + ' -vcodec dnxhd -b:v 145M -vf colormatrix=bt601:bt709 -flags +ildct ' + '"' + outputFile + '"'

               # launch the process
               proc = QtCore.QProcess(self)
               proc.finished.connect(lambda: self.finished(projIndex))
               proc.setProcessChannelMode(proc.MergedChannels)
               proc.start(cmd)
               proc.readyReadStandardOutput.connect(lambda: self.readStdOutput(proc, projIndex, 100))
               self.table.setItem(projIndex, 0, QtGui.QTableWidgetItem("Running..."))
               self.table.item(projIndex, 0).setBackgroundColor(QtGui.QColor(110, 145, 30))

       def readStdOutput(self, proc, projIndex, total):
           currentLine = QtCore.QString(proc.readAllStandardOutput())
           currentLine = str(currentLine)
           frameEnd = currentLine.find("fps", 0, 15)
           if frameEnd != -1:
               m = re.search("\d", currentLine)
               if m:
                   frame = currentLine[m.start():frameEnd]
                   percent = (float(frame)/total)*100
                   print "Percent: " + str(percent)
                   self.edit.append(str(percent))
                   self.table.setItem(projIndex, 0, QtGui.QTableWidgetItem("Encoded: " + str(percent) + "%"))

       def finished(self, projIndex):
           # TODO: This isn't totally working properly for multiple processes (seems to get confused)
           print "A process completed"
           print self.sender().readAllStandardOutput()
           if self.sender().exitStatus() == 0:
               self.table.setItem(projIndex, 0, QtGui.QTableWidgetItem("Encoded"))
               self.table.item(projIndex, 0).setBackgroundColor(QtGui.QColor(45, 145, 240))


    def main():
       app = QtGui.QApplication(sys.argv)
       ex = ffmpegBatch()
       ex.show()
       sys.exit(app.exec_())

    if __name__ == '__main__':
       main()

    (And yes I do know that my percentage update is totally wrong right now, still working on that...)

  • Error decoding a simple audio file using FFmpeg library

    29 mars 2017, par satyres

    After successfuly compiling the latest version of FFmpeg library and generated .a library in Ubuntu I’ve been struggling now for more than a week to decode and play a simple mp3 file in Android without a success !
    I’ve followed this tutorial given by FFmpeg team in Github i’ve tried to use it in Android but no luck !
    here is the Native code.

    void Java_com_example_home_hellondk_MainActivity_audio_1decode_1example(JNIEnv * env, jobject obj, jstring file, jbyteArray array) {
       jboolean isfilenameCopy;
       const char * filename = ( * env) - > GetStringUTFChars(env, file, &amp;
           isfilenameCopy);
       jclass cls = ( * env) - > GetObjectClass(env, obj);
       jmethodID play = ( * env) - > GetMethodID(env, cls, "playSound", "([BI)V");
       AVCodec * codec;
       AVCodecContext * c = NULL;
       int len;
       FILE * f, * outfile;
       uint8_t inbuf[AUDIO_INBUF_SIZE + AV_INPUT_BUFFER_PADDING_SIZE];
       AVPacket avpkt;
       AVFrame * decoded_frame = NULL;

       av_init_packet( &amp; avpkt);

       printf("Decode audio file %s \n", filename);
       LOGE("Decode audio file %s\n", filename);
       /* find the MPEG audio decoder */
       codec = avcodec_find_decoder(AV_CODEC_ID_MP3);
       if (!codec) {
           fprintf(stderr, "Codec not found\n");
           LOGE("Codec not found\n");
           exit(1);
       }

       c = avcodec_alloc_context3(codec);
       if (!c) {
           fprintf(stderr, "Could not allocate audio codec context\n");
           LOGE("Could not allocate audio codec context\n");
           exit(1);
       }

       /* open it */
       if (avcodec_open2(c, codec, NULL) &lt; 0) {
           fprintf(stderr, "Could not open codec\n");
           LOGE("Could not open codec\n");
           exit(1);
       }

       f = fopen(filename, "rb");
       if (!f) {
           fprintf(stderr, "Could not open %s\n", filename);
           LOGE("Could not open %s\n", filename);
           exit(1);
       }


       /* decode until eof */
       avpkt.data = inbuf;
       avpkt.size = fread(inbuf, 1, AUDIO_INBUF_SIZE, f);

       while (avpkt.size > 0) {
           int i, ch;
           int got_frame = 0;

           if (!decoded_frame) {
               if (!(decoded_frame = av_frame_alloc())) {
                   fprintf(stderr, "Could not allocate audio frame\n");
                   LOGE("Could not allocate audio frame\n");
                   exit(1);
               }
           }

           len = avcodec_decode_audio4(c, decoded_frame, &amp; got_frame, &amp; avpkt);
           if (len &lt; 0) {
               fprintf(stderr, "Error while decoding\n");
               LOGE("Error while decoding\n");
               exit(1);
           }
           if (got_frame) {
               /* if a frame has been decoded, output it */
               int data_size = av_get_bytes_per_sample(c - > sample_fmt);
               if (data_size &lt; 0) {
                   /* This should not occur, checking just for paranoia */
                   fprintf(stderr, "Failed to calculate data size\n");
                   LOGE("Failed to calculate data size\n");
                   exit(1);
               }
               if (data_size > 0) {

                   jbyte * bytes = ( * env) - > GetByteArrayElements(env, array, NULL);
                   memcpy(bytes, decoded_frame, got_frame); //
                   ( * env) - > ReleaseByteArrayElements(env, array, bytes, 0);
                   ( * env) - > CallVoidMethod(env, obj, play, array, got_frame);
                   LOGE("DECODING ERROR5");
               }
           }
           avpkt.size -= len;
           avpkt.data += len;
           avpkt.dts =
               avpkt.pts = AV_NOPTS_VALUE;
           if (avpkt.size &lt; AUDIO_REFILL_THRESH) {
               /* Refill the input buffer, to avoid trying to decode
                * incomplete frames. Instead of this, one could also use
                * a parser, or use a proper container format through
                * libavformat. */
               memmove(inbuf, avpkt.data, avpkt.size);
               avpkt.data = inbuf;
               len = fread(avpkt.data + avpkt.size, 1,
                   AUDIO_INBUF_SIZE - avpkt.size, f);
               if (len > 0)
                   avpkt.size += len;
           }
       }


       fclose(f);

       avcodec_free_context( &amp; c);
       av_frame_free( &amp; decoded_frame);

    }

    The Java code :

    package com.example.home.hellondk;

    import android.media.AudioFormat;
    import android.media.AudioManager;
    import android.media.AudioTrack;
    import android.media.MediaPlayer;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.util.Log;

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;

    public class MainActivity extends AppCompatActivity {
       static {
           System.loadLibrary("MyLibraryPlayer");
       }
       public native void createEngine();

       public native void audio_decode_example(String outfilename, byte[] array);



       private AudioTrack track;
       private FileOutputStream os;

       @Override
       protected void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           setContentView(R.layout.activity_main);
           createEngine();

    /*        MediaPlayer mp = new MediaPlayer();
           mp.start();*/

           int bufSize = AudioTrack.getMinBufferSize(32000,
                   AudioFormat.CHANNEL_CONFIGURATION_STEREO,
                   AudioFormat.ENCODING_PCM_16BIT);

           track = new AudioTrack(AudioManager.STREAM_MUSIC,
                   32000,
                   AudioFormat.CHANNEL_CONFIGURATION_STEREO,
                   AudioFormat.ENCODING_PCM_16BIT,
                   bufSize,
                   AudioTrack.MODE_STREAM);

           byte[] bytes = new byte[bufSize];

           try {
               os = new FileOutputStream("/storage/emulated/0/Cloud Radio/a.out", false);
           } catch (FileNotFoundException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
      audio_decode_example("/storage/emulated/0/Cloud Radio/test.mp3", bytes);

       }

       void playSound(byte[] buf, int size) {
           //android.util.Log.v("ROHAUPT", "RAH Playing");
           if (track.getPlayState() != AudioTrack.PLAYSTATE_PLAYING)
               track.play();
           track.write(buf, 0, size);

           try {
               os.write(buf, 0, size);
           } catch (IOException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
       }
    }

    I always got this error : Error while decoding .
    i’ve tried to change the decoder "AV_CODEC_ID_MP3" no sucess !
    Thank you so much for your help.
    Kind regards