Piping input AND output of ffmpeg in python

2020-05-24 07:01发布

问题:

I'm using ffmpeg to create a video, from a list of base64 encoded images that I pipe into ffmpeg.

Outputting to a file (using the attached code below) works perfectly, but what I would like to achieve is to get the output to a Python variable instead - meaning piping input and piping output but I can't seem to get it to work

My current code:

output = os.path.join(screenshots_dir, 'video1.mp4')

cmd_out = ['ffmpeg',
           '-y',  # (optional) overwrite output file if it exists
           '-f', 'image2pipe',
           '-vcodec', 'png',
           '-r', str(fps),  # frames per second
           '-i', '-',  # The input comes from a pipe
           '-vcodec', 'png',
           '-qscale', '0',
           output]

pipe = sp.Popen(cmd_out, stdin=sp.PIPE)

for screenshot in screenshot_list:
    im = Image.open(BytesIO(base64.b64decode(screenshot)))
    im.save(pipe.stdin, 'PNG')

pipe.stdin.close()
pipe.wait()

This results in a working mp4, but I would like to avoid saving to local.

Running the same code with changing output to '-' or 'pipe:1' and adding stdout=sp.PIPE results in an error

[NULL @ 0x2236000] Unable to find a suitable output format for 'pipe:'

回答1:

FFmpeg guesses the output muxer by checking the output extension. With a pipe, that doesn't exist, so it has to be expressly set. Add '-f', 'image2pipe' just before output.



回答2:

Try to add the following command after your sp.Popen :

output, _ = pipe.communicate()

I think you need to communicate it with the opened process. After that you can print it to make sure it worked :

print(_)


标签: python ffmpeg