
Recherche avancée
Médias (2)
-
SPIP - plugins - embed code - Exemple
2 septembre 2013, par
Mis à jour : Septembre 2013
Langue : français
Type : Image
-
Publier une image simplement
13 avril 2011, par ,
Mis à jour : Février 2012
Langue : français
Type : Video
Autres articles (111)
-
Websites made with MediaSPIP
2 mai 2011, parThis page lists some websites based on MediaSPIP.
-
Creating farms of unique websites
13 avril 2011, parMediaSPIP 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" (...) -
Publier sur MédiaSpip
13 juin 2013Puis-je poster des contenus à partir d’une tablette Ipad ?
Oui, si votre Médiaspip installé est à la version 0.2 ou supérieure. Contacter au besoin l’administrateur de votre MédiaSpip pour le savoir
Sur d’autres sites (6489)
-
How to set output file while using subprocess.Popen and hide cmd window at the same time ?
2 mars 2021, par NandeI 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 usesubprocess.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()



-
How to write to fifo in while loop and read in continuous process
18 avril 2019, par Russ_ellI’m running 3 multiprocess while loops that each write to seperate fifo’s , that are read by a continuously running ffmpeg process. This runs for the first loop of each process then stops.
The code below is one of the write loops ( the other two are pretty much the same ), and the read process.
def dubv():
while True:
print('loop')
file, dur = getFile('vocal')
fx = (
AudioEffectsChain()
.delay()
)
songvfx = fx(file)
with open('/tmp/pipe2.fifo', 'wb') as p1:
print('open s fifo')
p1.write(songvfx.T.tobytes())
p1.close()
print('close s fifo')
del songvfx
def mixer():
command4 = [
'ffmpeg',
'-nostdin',
'-re',
'-y',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe1.fifo',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe2.fifo',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe3.fifo',
'-filter_complex', '[0][1][2]amix=inputs=3:dropout_transition=3[map]',
'-map', '[map]',
'-c:a', 'libmp3lame',
'-b:a', '320k',
'-f', 'mp3',
'icecast://source:hackme@localhost:8000/test'
]
o = open('/tmp/pipe1.fifo', 'rb')
o2 = open('/tmp/pipe2.fifo', 'rb')
o3 = open('/tmp/pipe3.fifo', 'rb')
mix = sp.Popen(command4, stdin=DEVNULL, bufsize=4096)
mix.wait()I’d like the write process to write to fifo2 , then loop and continue writing to fifo2 , to be read in the mixer process continuously.
EDIT :
I think the problem is coming from the reader closing as the loop runs once , then runs round the loop , open the fifo but never prints ’close s fifo’ again , so i presume it cant write to the file ?
EDIT 2 :
I have resolved this by moving the fifo close out of the loop. My writer is now
def dubv():
with open('/tmp/pipe2.fifo', 'wb') as p2:
while True:
print('loop')
file, dur = getFile('vocal')
fx = (
AudioEffectsChain()
.delay()
)
songvfx = fx(file)
p2.write(songvfx.T.tobytes())
del songvfx
time.sleep(2)
p2.close()
print('close s fifo')and the reader doesn’t open the fifo files as ffmpeg seems to deal with this.
def mixer():
command4 = [
'ffmpeg',
'-re',
'-y',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe1.fifo',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe2.fifo',
'-thread_queue_size', '4096',
'-ac', '2',
'-ar', '44100',
'-f', 'f32le',
'-i', '/tmp/pipe3.fifo',
'-filter_complex', '[0][1][2]amix=inputs=3:dropout_transition=3[map]',
'-map', '[map]',
'-c:a', 'libmp3lame',
'-b:a', '320k',
'-f', 'mp3',
'icecast://source:hackme@localhost:8000/test'
]
mix = sp.Popen(command4, stdin=DEVNULL, bufsize=4096)
mix.wait()If anybody see a ’better’ solution please comment.
Thank you
-
ffmpeg conversion fails for 640x360 video size
12 novembre 2015, par user3132858Can somebody advice how I can fix the ffmpeg error below :
Array ( [0] => ffmpeg version 2.0.1 Copyright (c) 2000-2013 the FFmpeg developers
[1] => built on Nov 11 2015 12:17:12 with gcc 4.4.7 (GCC) 20120313 (Red Hat 4.4.7-16) [2]
=> configuration: --enable-gpl --enable-version3 --enable-shared --enable-nonfree
--enable-postproc --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb
--enable-libopencore-amrwb --enable-libtheora --enable-libvorbis --enable-libvpx
--enable-libx264 --enable-libxvid [3] => libavutil 52. 38.100 / 52. 38.100 [4]
=> libavcodec 55. 18.102 / 55. 18.102 [5] => libavformat 55. 12.100 / 55. 12.100 [6]
=> libavdevice 55. 3.100 / 55. 3.100 [7] => libavfilter 3. 79.101 / 3. 79.101 [8]
=> libswscale 2. 3.100 / 2. 3.100 [9] => libswresample 0. 17.102 / 0. 17.102 [10]
=> libpostproc 52. 3.100 / 52. 3.100 [11] => Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '3.mov': [12]
=> Metadata: [13] => major_brand : qt [14] => minor_version : 537199360 [15] => compatible_brands: qt [16]
=> creation_time : 2005-10-17 22:54:32 [17] => Duration: 00:01:25.50, start: 0.000000,
bitrate: 307 kb/s [18] => Stream #0:0(eng): Video: mpeg4 (Simple Profile) (mp4v / 0x7634706D),
yuv420p, 640x480 [SAR 1:1 DAR 4:3], 261 kb/s, 10 fps, 10 tbr, 3k tbn, 25 tbc [19]
=> Metadata: [20] => creation_time : 2005-10-17 22:54:33 [21] => handler_name :
Apple Video Media Handler [22] => Stream #0:1(eng): Audio: aac (mp4a / 0x6134706D),
32000 Hz, mono, fltp, 43 kb/s [23] => Metadata: [24] => creation_time : 2005-10-17 22:54:34 [25]
=> handler_name : Apple Sound Media Handler [26] => [libx264 @ 0x19fbb00] using SAR=944/945 [27]
=> [libx264 @ 0x19fbb00] using cpu capabilities: MMX2 SSE2Fast SSSE3 SSE4.2 AVX [28]
=> Output #0, mp4, to '4.mp4': [29] => Metadata: [30] => major_brand : qt [31]
=> minor_version : 537199360 [32] => compatible_brands: qt [33] => Stream #0:0
(eng): Video: h264, yuv420p, 630x472 [SAR 944:945 DAR 4:3], q=-1--1, 900 kb/s, 90k tbn,
10 tbc [34] => Metadata: [35] => creation_time : 2005-10-17 22:54:33 [36]
=> handler_name : Apple Video Media Handler [37] => Stream #0:1(eng): Audio: aac, 32000 Hz,
mono, fltp, 128 kb/s [38] => Metadata: [39] => creation_time : 2005-10-17 22:54:34 [40]
=> handler_name : Apple Sound Media Handler [41] => Stream mapping: [42]
=> Stream #0:0 -> #0:0 (mpeg4 -> libx264) [43] => Stream #0:1 -> #0:1 (aac -> aac) [44]
=> Error while opening encoder for output stream #0:0 - maybe incorrect parameters
such as bit_rate, rate, width or height )This is my code :
$width=640;
$height=360;
$aspect=round($width/$height, 1);
$command = "/usr/bin/ffmpeg -threads 1 -y -i 3.mov -vf \"scale=min(1\,gt(iw\,".$width.")+gt(ih\,".$height.")) * (gte(a\,".$aspect.")*".$width." + \
lt(a\,".$aspect.")*((".$height."*iw)/ih)) + not(min(1\,gt(iw\,".$width.")+gt(ih\,".$height.")))*iw : \
min(1\,gt(iw\,".$width.")+gt(ih\,".$height.")) * (lte(a\,".$aspect.")*".$height." + \
gt(a\,".$aspect.")*((".$width."*ih)/iw)) + not(min(1\,gt(iw\,".$width.")+gt(ih\,".$height.")))*ih\" -b:v 900k -acodec aac -strict -2 -ab 96k 4.mp4 ";It is rather strange but when I change the width and height parameters to 300 and 200 respectively, the command executes, the error appears when the width x height is 640x360.
Any ideas of what might be wrong ?
UPDATE : I am pretty sure the error has got something to do with the audio encoding. If I change the
-ab 96k
part to-c:a copy
, command executes.
I cannot however use-c:a copy
because for some audio formats the video does not play on mobile devices. Therefore i need the audio settings to be fixed and the same for all videos.