Recherche avancée

Médias (2)

Mot : - Tags -/doc2img

Autres articles (97)

  • MediaSPIP 0.1 Beta version

    25 avril 2011, par

    MediaSPIP 0.1 beta is the first version of MediaSPIP proclaimed as "usable".
    The zip file provided here only contains the sources of MediaSPIP in its standalone version.
    To get a working installation, you must manually install all-software dependencies on the server.
    If you want to use this archive for an installation in "farm mode", you will also need to proceed to other manual (...)

  • Multilang : améliorer l’interface pour les blocs multilingues

    18 février 2011, par

    Multilang est un plugin supplémentaire qui n’est pas activé par défaut lors de l’initialisation de MediaSPIP.
    Après son activation, une préconfiguration est mise en place automatiquement par MediaSPIP init permettant à la nouvelle fonctionnalité d’être automatiquement opérationnelle. Il n’est donc pas obligatoire de passer par une étape de configuration pour cela.

  • List of compatible distributions

    26 avril 2011, par

    The table below is the list of Linux distributions compatible with the automated installation script of MediaSPIP. Distribution nameVersion nameVersion number Debian Squeeze 6.x.x Debian Weezy 7.x.x Debian Jessie 8.x.x Ubuntu The Precise Pangolin 12.04 LTS Ubuntu The Trusty Tahr 14.04
    If you want to help us improve this list, you can provide us access to a machine whose distribution is not mentioned above or send the necessary fixes to add (...)

Sur d’autres sites (9336)

  • PHP and FFMPEG advice/sollution for a unknown issue

    20 octobre 2015, par sonam Sharma

    I am having a live video streaming website and I allow people to upload all the video files to the site till now everything is ok.

    What I am doing is that I am using FFMPEG to convert the video to mp4 and also get a image out of the video after 20 seconds.

    The code that I am using is that :

    require 'vendor/autoload.php';
           $getEXT_check=substr(@$_FILES['profileimage99']['name'],-3);
           if($getEXT_check !='mp4' && $getEXT_check !='MP4'){
           exec('ffmpeg -i '.$uploadfile.' -f mp4 -s 896x504 '.$new_flv.''); }
           //execute ffmpeg and create thumb
           exec('ffmpeg  -i '.$uploadfile.' -ss 00:00:20 -vframes 1  '.$new_image_path);
           $theduration=exec('ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 '.$uploadfile.' 2>&1');
           $theduration_val=round($theduration/60, 2);

    What issue I am having is that

    1. sometimes the code dosent extract the image out of video
    2. video conversation takes very long time for non mp4 video (I am not converting mp4 videos)

    Some info what I have done on server. During the development of site I installed ffmpeg on my pc and downloaded the vendor directory by composer.json file. But I have not done these things on my server I have a dedicated server from bluehost and have ffmpeg installed at this location.

    /usr/local/bin/ffmpeg
    /usr/local/bin/mplayer
    /usr/local/bin/mencoder
    /usr/bin/flvtool2
    /usr/local/bin/MP4Box
    /usr/local/bin/yamdi

    During uploading the site what I did is that I also uploaded the vendor directory and all the files and made the site live. I haven’t used any of the path as given by my server admin after asking.

    Please suggest me something where I am doing wrong.

  • 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()


    


  • FFmpeg python doesn't merge

    24 avril 2021, par MaLoLHDX

    I was making this youtube downloader GUI with Python : it asks for the URL, gives you a list with the possible quality settings and downloads the selected video file and the best audio file with youtube-dl. However, when I tell ffmpeg to merge the two separate downloaded files, it doesn't do anything and it doesn't say anything in the console either. Is there anything I'm missing ?

    


    Here's the relevant part of the code (starts at line 153) :

    


                #Adding input arguments for ffmpeg
            ffmpeg_video = ffmpeg.input(self.video_title)
            ffmpeg_audio = ffmpeg.input(self.audio_title)
            output_ffmpeg_title = './videos/' + self.youtube_title
            #Merging with ffmpeg
            out = ffmpeg.output(ffmpeg_video, ffmpeg_audio, output_ffmpeg_title, vcodec='copy', acodec='aac')
            out.run


    


    Here's the full code :

    


    import youtube_dl
import tkinter as tk
import operator
import ffmpeg
class GUI:
    def __init__(self):
        #Creating initial window
        self.window = tk.Tk()
        self.window.title('YTDL')
        self.window.geometry('300x70')
        
        self.urlbox = tk.Entry(self.window)
        self.urlbox.pack(padx=5,pady=5)
        #Creating download button, which will open the format selection window
        downbutton = tk.Button(self.window, text="Download", command= self.check_url)
        downbutton.pack(padx=5, pady=5)
        #Creating a variable to keep track of the point in the GUI options selection
        self.format_select_process = False
        
        self.window.mainloop()
    def check_url(self):
        #Saving selected URL to variable
        self.selected_url = self.urlbox.get()
        self.urlbox.delete(0, 'end')
        #If something was written in the URL box, try to go the next step
        if len(self.selected_url) != 0:
            self.get_formats(self.selected_url)
        else:
            print('URL box is empty!')
    def get_formats(self, x):
        with youtube_dl.YoutubeDL() as ydl:
            meta = ydl.extract_info(x, download=False)
            #Save formats from 'meta' to 'self.formats'
            self.formats = meta.get('formats', [meta])
            self.youtube_title = meta.get('title', [meta])
            #Creating two dictionaries for the list of format sizes and extensions
            self.f_list_size_dict = {}
            self.f_list_ext_dict = {}
            #Creating audio format list
            self.audio_format_list = []
        #For every format in self.formats, add its format, extension, fps and filesize to self.f_list
        for f in self.formats:
            self.f_list = '-' + f['format']+ ' -' + f['ext'] + ' -' + str(f['fps']) + ' ' + str(f['filesize'])
            if 'audio only' in f['format']:
                #Add an element to each dictonary whose name is the format ID and whose value is its filesize/extension
                self.f_list_size_dict[f['format'].split(' -')[0]] = f['filesize']
                self.f_list_ext_dict[f['format'].split(' -')[0]] = f['ext']
                #Add to the audio format list the current audio format ID
                self.audio_format_list.append(f['format'].split(' -')[0])
        print('Audio format list:')
        print(self.audio_format_list)
        print('Size list dict:')
        print(self.f_list_size_dict)
        print('Ext list size dict:')
        print(self.f_list_ext_dict)
        """
        #Making a new list which only contains the audio format IDs
        self.audio_format_list = str(self.f_list_size_dict.keys()).split('([')[1]
        self.audio_format_list = self.audio_format_list.split('])')[0]
        self.audio_format_list = self.audio_format_list.replace("'", "")
        self.audio_format_list = self.audio_format_list.split(', ')
        print('Cleaned up audio format list:')
        print(self.audio_format_list)
        """
        #Here the program starts looking for the best audio format
        #In the try block, the program gets the best audio format's ID from the size dict and extension from the ext dict
        #In the except block, the program gets the ID from the audio format list and the extension from the ext dict
        try:
            self.highest_audio = max(self.f_list_size_dict.items(), key=operator.itemgetter(1))[0]
            self.highest_audio_ext = self.f_list_ext_dict.get(self.highest_audio)
            print('Best audio format ID: ' + self.highest_audio)
            print('Best audio format extension: ' + self.highest_audio_ext)
        except:
            self.highest_audio = max(self.audio_format_list)
            self.highest_audio_ext = self.f_list_ext_dict.get(self.highest_audio)
            print(self.highest_audio)
            print(self.highest_audio_ext)
        #Going to next sted of the code, which renders the format choice window
        self.format_select()
    def format_select(self):
        self.window.withdraw()
        format_select_window = tk.Toplevel()
        format_select_window.attributes('-topmost', True)
        format_select_window.geometry("300x350")
        format_select_window_label = tk.Label(format_select_window, text="Select the video format")
        format_select_window_label.pack(padx=5, pady=5)
        format_select_window.protocol('WM_DELETE_WINDOW', lambda: exit())

        self.format_listbox = tk.Listbox(format_select_window, height=15, width=40, yscrollcommand=1)
        self.format_listbox.pack(padx=10, pady=10)
        for index, item in enumerate(self.f_list):
            self.f_list_lenght = index
        download_button = tk.Button(format_select_window, text='Download', command=self.download)
        download_button.pack(padx=10, pady=10)
        #Adding options to the listbox
        for f in self.formats:
            #If it is adding an audio only format, it will add the ID, filesize (if possible with try block) and extension
            if 'audio only' in f['format'] + ' ' + str(f['fps']) + ' FPS ' + f['ext']:
                try:
                    mb_filesize = round(f['filesize'] / 1024 / 1024, 2)
                    self.format_listbox.insert(self.f_list_lenght, f['format'] + ' ' + str(mb_filesize) + ' MiB  ' + f['ext']) 
                except:
                    self.format_listbox.insert(self.f_list_lenght, f['format'] + '  ' + f['ext'])
            #If it is adding a video format, it will add the ID, FPS, filesize (if possible with the try block) and extension
            else:
                try:
                    mb_filesize = round(f['filesize'] / 1024 / 1024, 2)
                    self.format_listbox.insert(self.f_list_lenght, f['format'] + ' ' + str(f['fps']) + ' FPS' + ' ' + str(mb_filesize) + ' MiB  ' + f['ext'])
                except:
                    self.format_listbox.insert(self.f_list_lenght, f['format'] + ' ' + str(f['fps']) + ' FPS  ' + f['ext'])
    def download(self):
        #Getting the list position of the selected format
        selected_format_list_position = self.format_listbox.curselection()
        #Getting the text of the selected format list item
        selected_format = self.format_listbox.get(selected_format_list_position)
        print('Selected format: ' + selected_format)
        #Cutting from the selected format list item text everything past ' -' to only get the format's ID
        selected_format_id = selected_format.split(' -')[0]
        print('Selected format ID: ' + selected_format_id)
        #Converting the ID to string
        final_selected_format_id = str(selected_format_id)
        print('Final selected format: ' + final_selected_format_id)
        #Cutting from the selected format list item text everything before '  ' to only get the extension
        final_ext = selected_format.split('  ')[1]
        print('Final video extension: ' + final_ext)
        if 'audio only' in selected_format:
            #Creating the download options dictionary (not working):
            #Setting the download location to the videos folder,
            #preventing the program from downloading a whole playlist,
            #telling youtube-dl to extract audio ('x'),
            #giving youtube-dl the requested format (which is only audio).
            self.ydl_opts = {'outtmpl':'./videos/%(title)s.%(ext)s', 'noplaylist': True, 'x': True, 'format': final_selected_format_id}
            #Downloading
            with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:
                ydl.download([self.selected_url])
        elif 'audio only' not in selected_format:
            #Adding '+bestaudio' to the selected format ID (which is only a video ID in this case)
            final_selected_format_id_video_audio = str(selected_format_id) + '+bestaudio'
            #Creating the download options dictionary:
            #Setting the download location to the videos folder,
            #preventing the program from downloading a whole playlist,
            #giving youtube-dl the requested format with audio.
            self.ydl_opts = {'outtmpl':'./videos/%(title)s.%(ext)s', 'noplaylist': True, 'format': final_selected_format_id_video_audio}
            #Predicting the video file title and location for future ffmpeg merge
            self.video_title = './videos/' + self.youtube_title + '.f' + str(selected_format_id) + '.' + final_ext
            print('Video file title: ' + self.video_title)
            #Predicting the audio file title and location for future ffmpeg merge
            self.audio_title = './videos/' + self.youtube_title + '.f' + str(self.highest_audio) + '.' + self.highest_audio_ext
            print('Audio file title: ' + self.audio_title)
            #Downloading with youtube-dl
            with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:
                ydl.download([self.selected_url])
            #Adding input arguments for ffmpeg
            ffmpeg_video = ffmpeg.input(self.video_title)
            ffmpeg_audio = ffmpeg.input(self.audio_title)
            output_ffmpeg_title = './videos/' + self.youtube_title
            #Merging with ffmpeg
            ffmpeg.output(ffmpeg_video, ffmpeg_audio, output_ffmpeg_title, vcodec='copy', acodec='aac')
GUI()


    


    If there is a better way of integrating ffmpeg with youtube-dl in Python, please tell me.