Recherche avancée

Médias (1)

Mot : - Tags -/Christian Nold

Autres articles (107)

  • Demande de création d’un canal

    12 mars 2010, par

    En fonction de la configuration de la plateforme, l’utilisateur peu avoir à sa disposition deux méthodes différentes de demande de création de canal. La première est au moment de son inscription, la seconde, après son inscription en remplissant un formulaire de demande.
    Les deux manières demandent les mêmes choses fonctionnent à peu près de la même manière, le futur utilisateur doit remplir une série de champ de formulaire permettant tout d’abord aux administrateurs d’avoir des informations quant à (...)

  • La file d’attente de SPIPmotion

    28 novembre 2010, par

    Une file d’attente stockée dans la base de donnée
    Lors de son installation, SPIPmotion crée une nouvelle table dans la base de donnée intitulée spip_spipmotion_attentes.
    Cette nouvelle table est constituée des champs suivants : id_spipmotion_attente, l’identifiant numérique unique de la tâche à traiter ; id_document, l’identifiant numérique du document original à encoder ; id_objet l’identifiant unique de l’objet auquel le document encodé devra être attaché automatiquement ; objet, le type d’objet auquel (...)

  • Websites made ​​with MediaSPIP

    2 mai 2011, par

    This page lists some websites based on MediaSPIP.

Sur d’autres sites (12072)

  • How to set output file while using subprocess.Popen and hide cmd window at the same time ?

    2 mars 2021, par Nande

    I made a simple app that can convert video files using FFMpeg. I used Kivy for UI. I used os.system() to execute ffmpeg commands but while using this method, there is always a cmd window popping up. Therefore i am trying to use subprocess.Popen() to execute ffmpeg commands but i also want to save ffmpeg output to a text file.

    


    I tried this but it didn't work :

    


    subprocess.Popen(f"ffmpeg -i {path} -acodec {acodec} {output} > output.txt 2>&1", creationflags = 0x08000000, stdout="output.txt")


    


    FFMpeg converts the video but there is no output.txt file. This code works with os.system()

    


    How can i hide cmd window while saving output to a text file ?

    


    My full python code :

    


    import os
from signal import SIGINT
import psutil
from time import sleep
from threading import Thread
from kivy.config import Config
Config.set('graphics', 'resizable', False)
Config.set('graphics', 'width', '400')
Config.set('graphics', 'height', '330')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.properties import ObjectProperty

Window.clearcolor = (1, 1, 1, 1)

desktop = os.path.join(os.path.join(os.path.expanduser('~')), 'Desktop') + "\\"


def cmd(command):
    os.system(command)


def getpid(prcs):
    for proc in psutil.process_iter():
        try:
            pinf = proc.as_dict(attrs=["pid", "name"])
            if prcs.lower() in pinf["name"].lower():
                return pinf["pid"]
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            return False
    return False


# noinspection PyGlobalUndefined
def progress(app, path):
    app.root.prgrss_bar.value = 0
    app.root.prgrss_lbl.text = "Progress: %0"

    if not os.getcwd().endswith("ffmpeg"):
        os.chdir("ffmpeg")

    inputpath = app.root.label.text
    if inputpath.startswith("Choose"):
        return
    audio = app.root.audio.state
    video = app.root.video.state
    both = app.root.both.state

    global line1
    global line2

    if video == "down" or both == "down":
        command = f"ffprobe -v error -select_streams v:0 -show_entries stream=nb_frames -of default=nokey=1:noprint_wrappers=1 {inputpath} > output2.txt 2>&1"
        os.system(command)
        ffprobe = open("output2.txt", "r")
        frames = int(ffprobe.read())

        control = True
        while control:
            sleep(0.5)

            with open(path, "r") as f:
                for last_line in f:
                    pass
                line1 = last_line
            sleep(0.5)

            with open(path, "r") as f:
                for last_line in f:
                    pass
                line2 = last_line
            if line1 == line2:
                app.root.prgrss_bar.value = 100
                app.root.prgrss_lbl.text = "Progress: Finished"
                control = False
            else:
                try:
                    current_frame = int(line2.split("=")[1].split()[0])
                    percentage = int(current_frame / frames * 100)
                    text = f"Progress: %{percentage}"
                    app.root.prgrss_lbl.text = text
                    app.root.prgrss_bar.value = percentage
                    if percentage == 100:
                        control = False
                except ValueError or TypeError:
                    pass

    elif audio == "down":
        command = f"ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {app.root.label.text} > output2.txt 2>&1"
        os.system(command)
        ffprobe = open("output2.txt", "r")
        duration = round(float(ffprobe.read()), 2)
        control = True
        while control:
            sleep(0.5)
            with open(path, "r") as f:
                for last_line in f:
                    pass
                line1 = last_line
            sleep(0.5)

            with open(path, "r") as f:
                for last_line in f:
                    pass
                line2 = last_line
            if line1 == line2:
                app.root.prgrss_bar.value = 100
                app.root.prgrss_lbl.text = "Progress: Finished"
                control = False
            else:
                try:
                    current = line2.split("=")[2].split()[0].split(":")
                    seconds = round((int(current[0]) * 3600) + (int(current[1]) * 60) + float(current[2]), 2)
                    percentage = int(seconds / duration * 100)
                    text = f"Progress: %{percentage}"
                    app.root.prgrss_lbl.text = text
                    app.root.prgrss_bar.value = percentage
                    if percentage == 100:
                        control = False
                except ValueError or TypeError:
                    pass


class Window(Widget):

    @staticmethod
    def popup_open():
        popup = FolderPopup()
        popup.open()

    @staticmethod
    def exists_open():
        popup = Exists()
        popup.open()

    @staticmethod
    def choose_open():
        popup = ChooseFormat()
        popup.open()

    @staticmethod
    def path_popup():
        popup = ChoosePath()
        popup.open()

    @staticmethod
    def unsupported_audio():
        popup = UnsupportedAudio()
        popup.open()

    @staticmethod
    def no_video_format():
        popup = NoVideoFormat()
        popup.open()

    @staticmethod
    def no_process():
        popup = NoFFMPEGProcess()
        popup.open()

    def start(self, app):
        path = app.root.label.text
        if path.startswith("Choose"):
            self.path_popup()
            return

        outname = app.root.outname.text
        video_f = app.root.spinner.text
        audio_f = app.root.spinner2.text
        video = app.root.video.state
        audio = app.root.audio.state
        both = app.root.both.state

        audio_supported = {"MP4": ["AAC", "MP3", "Opus"],
                           "MKV": ["AAC", "MP3", "Opus"],
                           "MOV": ["AAC", "MP3"],
                           "AVI": ["AAC", "MP3"],
                           "WMV": ["AAC", "MP3"]}

        audio_ce = {"AAC": ["aac", ".m4a"],
                    "MP3": ["libmp3lame", ".mp3"],
                    "Opus": ["libopus", ".opus"],
                    "WAV": ["pcm_u8", ".wav"],
                    "Choose": ["Choose", "Choose"]}

        if not os.getcwd().endswith("ffmpeg"):
            os.chdir("ffmpeg")

        video_ext = video_f.lower()
        acodec = audio_ce[audio_f][0]
        audio_ext = audio_ce[audio_f][1]
        command = ""

        if (video == "normal" and audio == "normal" and both == "normal") or (
                video_f == "Choose" and audio_f == "Choose"):
            self.choose_open()
            return
        elif video == "down":
            if video_f == "Choose":
                self.no_video_format()
                return
            output = f"{desktop}{outname}.{video_ext}"
            if not os.path.exists(output):
                command += f"ffmpeg -i {path} -an {output} > output.txt 2>&1"
            else:
                self.exists_open()
                return
        elif audio == "down":
            output = f"{desktop}{outname}{audio_ext}"
            if not os.path.exists(output):
                command += f"ffmpeg -i {path} -vn -acodec {acodec} {output} > output.txt 2>&1"
            else:
                self.exists_open()
                return
        elif both == "down":
            if video_f == "Choose":
                self.no_video_format()
                return
            elif audio_f == "Choose":
                output = f"{desktop}{outname}.{video_ext}"
                if not os.path.exists(output):
                    command += f"ffmpeg -i {path} {output} > output.txt 2>&1"
                else:
                    self.exists_open()
                    return
            else:
                if audio_f not in audio_supported[video_f]:
                    self.unsupported_audio()
                    return
                else:
                    output = f"{desktop}{outname}.{video_ext}"
                    if not os.path.exists(output):
                        command += f"ffmpeg -i {path} -acodec {acodec} {output} > output.txt 2>&1"
                    else:
                        self.exists_open()
                        return

        thrd = Thread(target=cmd, args=(command,))
        thrd.start()
        print("Thread started.")

    def stop(self):
        pid = getpid("ffmpeg")
        if not pid:
            self.no_process()
        else:
            os.kill(pid, SIGINT)

    def test_open(self, app):
        if not os.getcwd().endswith("ffmpeg"):
            os.chdir("ffmpeg")

        video = app.root.label.text
        if video.startswith("Choose"):
            return self.path_popup()

        command = f"ffplay {video}"
        os.system(command)

    @staticmethod
    def check_progress(app):
        path = os.getcwd() + r"\output.txt"
        chkprgrss = Thread(target=progress, args=(app, path,))
        chkprgrss.start()


class FolderPopup(Popup):
    dosya = ObjectProperty(None)
    desktop = desktop

    @staticmethod
    def no_path_submit():
        popup = NoPathSubmit()
        popup.open()

    def buton(self, app):

        try:
            app.root.label.text = self.dosya.selection[0]
            self.dismiss()
        except:
            self.no_path_submit()


class Exists(Popup):
    def buton(self):
        self.dismiss()


class ChooseFormat(Popup):
    def buton(self):
        self.dismiss()


class ChoosePath(Popup):
    def buton(self):
        self.dismiss()


class UnsupportedAudio(Popup):
    def buton(self):
        self.dismiss()


class NoVideoFormat(Popup):
    def buton(self):
        self.dismiss()


class NoPathSubmit(Popup):
    def buton(self):
        self.dismiss()


class NoFFMPEGProcess(Popup):
    def buton(self):
        self.dismiss()


class GUI(App):
    def build(self):
        return Window()


if __name__ == "__main__":
    GUI().run()


    


  • Anomalie #2901 : Bug lié au navigateur IceWeasel - Ajout de documents à un article

    23 juin 2013, par Eric BERTHOMIER

    Bonjour Redmine,

    moi même informaticien, j’ai fait beaucoup de tests, je suis parti
    - avec un site web vierge installé par copie du contenu d’un fichier zip
    et
    - avec un site web vierge installé par le script php

    L’Upload fonctionne avec Firefox (le vrai) sous Linux (LiveCD Parted
    Magic) et sous Windows (avec Firefox).

    @+
    Eric

    Le 10/11/2012 11:28, a écrit :

    La demande #2901 a été mise à jour par b b.

    Salut, j’ai peut être une piste car j’ai déjà dépanné des gens qui
    rencontraient ce problème. Peux-tu vérifier que la table
    spip_types_documents de ton site est bien renseignée (en la comparant
    avec une installation de la même version sur laquelle l’upload
    fonctionne). Il semble que certaines personnes rencontrent un problème
    d’upgrade de la base sur cette table. Si cette table n’est pas bien
    renseignée, SPIP ne peut pas vérifier que le document que tu tentes
    d’uploader est autorisé.


    Anomalie #2901 : Bug lié au navigateur IceWeasel - Ajout de documents à
    un article

    • Auteur : Eric BERTHOMIER
    • Statut : Nouveau
    • Priorité : Normal
    • Assigné à :
    • Catégorie :
    • Version cible :
    • Resolution :
    • Navigateur :

    Bonjour à tous,

    sur le navigateur IceWeasel (Debian)
    Mozilla/5.0 (X11 ; U ; Linux i686 ; fr ; rv:1.9.1.16) Gecko/20121020
    Iceweasel/3.5.16 (like Firefox/3.5.16)

    L’ajout d’un document à un article n’aboutit jamais sur la version SPIP
    3.0.5. Elle fonctionnait correctement sur la version 2.

    Je ne peux dire si le bug est SPIP ou Navigateur ...

    Je reste à votre disposition pour tout test.

    Merci d’avance et bon courage.


    Vous recevez ce mail car vous êtes impliqués sur ce projet.
    Pour changer les préférences d’envoi de mail, allez sur
    http://core.spip.org/my/account

  • MediaCodec - save timing info for ffmpeg ?

    18 novembre 2014, par Mark

    I have a requirement to encrypt video before it hits the disk. It seems on Android the only way to do this is to use MediaCodec, and encrypt and save the raw h264 elementary streams. (The MediaRecorder and Muxer classes operate on FileDescriptors, not an OutputStream, so I can’t wrap it with a CipherOutputStream).

    Using the grafika code as a base, I’m able to save a raw h264 elementary stream by replacing the Muxer in the VideoEncoderCore class with a WriteableByteChannel, backed by a CipherOutputStream (code below, minus the CipherOutputStream).

    If I take the resulting output file over to the desktop I’m able to use ffmpeg to mux the h264 stream to a playable mp4 file. What’s missing however is timing information. ffmpeg always assumes 25fps. What I’m looking for is a way to save the timing info, perhaps to a separate file, that I can use to give ffmpeg the right information on the desktop.

    I’m not doing audio yet, but I can imagine I’ll need to do the same thing there, if I’m to have any hope of remotely accurate syncing.

    FWIW, I’m a total newbie here, and I really don’t know much of anything about SPS, NAL, Atoms, etc.

    /*
    * Copyright 2014 Google Inc. All rights reserved.
    *
    * Licensed under the Apache License, Version 2.0 (the "License");
    * you may not use this file except in compliance with the License.
    * You may obtain a copy of the License at
    *
    *      http://www.apache.org/licenses/LICENSE-2.0
    *
    * Unless required by applicable law or agreed to in writing, software
    * distributed under the License is distributed on an "AS IS" BASIS,
    * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    * See the License for the specific language governing permissions and
    * limitations under the License.
    */


    import android.media.MediaCodec;
    import android.media.MediaCodecInfo;
    import android.media.MediaFormat;
    import android.util.Log;
    import android.view.Surface;

    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.nio.channels.WritableByteChannel;

    /**
    * This class wraps up the core components used for surface-input video encoding.
    * <p>
    * Once created, frames are fed to the input surface.  Remember to provide the presentation
    * time stamp, and always call drainEncoder() before swapBuffers() to ensure that the
    * producer side doesn't get backed up.
    * </p><p>
    * This class is not thread-safe, with one exception: it is valid to use the input surface
    * on one thread, and drain the output on a different thread.
    */
    public class VideoEncoderCore {
       private static final String TAG = MainActivity.TAG;
       private static final boolean VERBOSE = false;

       // TODO: these ought to be configurable as well
       private static final String MIME_TYPE = "video/avc";    // H.264 Advanced Video Coding
       private static final int FRAME_RATE = 30;               // 30fps
       private static final int IFRAME_INTERVAL = 5;           // 5 seconds between I-frames

       private Surface mInputSurface;
       private MediaCodec mEncoder;
       private MediaCodec.BufferInfo mBufferInfo;
       private int mTrackIndex;
       //private MediaMuxer mMuxer;
       //private boolean mMuxerStarted;
       private WritableByteChannel outChannel;

       /**
        * Configures encoder and muxer state, and prepares the input Surface.
        */
       public VideoEncoderCore(int width, int height, int bitRate, File outputFile)
               throws IOException {
           mBufferInfo = new MediaCodec.BufferInfo();

           MediaFormat format = MediaFormat.createVideoFormat(MIME_TYPE, width, height);

           // Set some properties.  Failing to specify some of these can cause the MediaCodec
           // configure() call to throw an unhelpful exception.
           format.setInteger(MediaFormat.KEY_COLOR_FORMAT,
                   MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface);
           format.setInteger(MediaFormat.KEY_BIT_RATE, bitRate);
           format.setInteger(MediaFormat.KEY_FRAME_RATE, FRAME_RATE);
           format.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, IFRAME_INTERVAL);
           if (VERBOSE) Log.d(TAG, "format: " + format);

           // Create a MediaCodec encoder, and configure it with our format.  Get a Surface
           // we can use for input and wrap it with a class that handles the EGL work.
           mEncoder = MediaCodec.createEncoderByType(MIME_TYPE);
           mEncoder.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
           mInputSurface = mEncoder.createInputSurface();
           mEncoder.start();

           // Create a MediaMuxer.  We can't add the video track and start() the muxer here,
           // because our MediaFormat doesn't have the Magic Goodies.  These can only be
           // obtained from the encoder after it has started processing data.
           //
           // We're not actually interested in multiplexing audio.  We just want to convert
           // the raw H.264 elementary stream we get from MediaCodec into a .mp4 file.
           //mMuxer = new MediaMuxer(outputFile.toString(),
           //        MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4);

           mTrackIndex = -1;
           //mMuxerStarted = false;
           outChannel = Channels.newChannel(new BufferedOutputStream(new FileOutputStream(outputFile)));
       }

       /**
        * Returns the encoder's input surface.
        */
       public Surface getInputSurface() {
           return mInputSurface;
       }

       /**
        * Releases encoder resources.
        */
       public void release() {
           if (VERBOSE) Log.d(TAG, "releasing encoder objects");
           if (mEncoder != null) {
               mEncoder.stop();
               mEncoder.release();
               mEncoder = null;
           }
           try {
               outChannel.close();
           }
           catch (Exception e) {
               Log.e(TAG,"Couldn't close output stream.");
           }
       }

       /**
        * Extracts all pending data from the encoder and forwards it to the muxer.
        * </p><p>
        * If endOfStream is not set, this returns when there is no more data to drain.  If it
        * is set, we send EOS to the encoder, and then iterate until we see EOS on the output.
        * Calling this with endOfStream set should be done once, right before stopping the muxer.
        * </p><p>
        * We're just using the muxer to get a .mp4 file (instead of a raw H.264 stream).  We're
        * not recording audio.
        */
       public void drainEncoder(boolean endOfStream) {
           final int TIMEOUT_USEC = 10000;
           if (VERBOSE) Log.d(TAG, "drainEncoder(" + endOfStream + ")");

           if (endOfStream) {
               if (VERBOSE) Log.d(TAG, "sending EOS to encoder");
               mEncoder.signalEndOfInputStream();
           }

           ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
           while (true) {
               int encoderStatus = mEncoder.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
               if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
                   // no output available yet
                   if (!endOfStream) {
                       break;      // out of while
                   } else {
                       if (VERBOSE) Log.d(TAG, "no output available, spinning to await EOS");
                   }
               } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
                   // not expected for an encoder
                   encoderOutputBuffers = mEncoder.getOutputBuffers();
               } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
                   // should happen before receiving buffers, and should only happen once
                   //if (mMuxerStarted) {
                   //    throw new RuntimeException("format changed twice");
                   //}
                   MediaFormat newFormat = mEncoder.getOutputFormat();
                   Log.d(TAG, "encoder output format changed: " + newFormat);

                   // now that we have the Magic Goodies, start the muxer
                   //mTrackIndex = mMuxer.addTrack(newFormat);
                   //mMuxer.start();
                   //mMuxerStarted = true;
               } else if (encoderStatus &lt; 0) {
                   Log.w(TAG, "unexpected result from encoder.dequeueOutputBuffer: " +
                           encoderStatus);
                   // let's ignore it
               } else {
                   ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
                   if (encodedData == null) {
                       throw new RuntimeException("encoderOutputBuffer " + encoderStatus +
                               " was null");
                   }

                   /*
                      FFMPEG needs this info.
                   if ((mBufferInfo.flags &amp; MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                       // The codec config data was pulled out and fed to the muxer when we got
                       // the INFO_OUTPUT_FORMAT_CHANGED status.  Ignore it.
                       if (VERBOSE) Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG");
                       mBufferInfo.size = 0;
                   }
                   */

                   if (mBufferInfo.size != 0) {
                       /*
                       if (!mMuxerStarted) {
                           throw new RuntimeException("muxer hasn't started");
                       }
                       */

                       // adjust the ByteBuffer values to match BufferInfo (not needed?)
                       encodedData.position(mBufferInfo.offset);
                       encodedData.limit(mBufferInfo.offset + mBufferInfo.size);

                       try {
                           outChannel.write(encodedData);
                       }
                       catch (Exception e) {
                           Log.e(TAG,"Error writing output.",e);
                       }
                       if (VERBOSE) {
                           Log.d(TAG, "sent " + mBufferInfo.size + " bytes to muxer, ts=" +
                                   mBufferInfo.presentationTimeUs);
                       }
                   }

                   mEncoder.releaseOutputBuffer(encoderStatus, false);

                   if ((mBufferInfo.flags &amp; MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                       if (!endOfStream) {
                           Log.w(TAG, "reached end of stream unexpectedly");
                       } else {
                           if (VERBOSE) Log.d(TAG, "end of stream reached");
                       }
                       break;      // out of while
                   }
               }
           }
       }
    }
    </p>