Piping input AND output of ffmpeg in python

2020-05-24 06:11发布

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:'

标签: python ffmpeg
2条回答
看我几分像从前
2楼-- · 2020-05-24 06:55

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(_)
查看更多
▲ chillily
3楼-- · 2020-05-24 07:09

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.

查看更多
登录 后发表回答