python – Controlling buffer size for webcam video capture to file using ffmpeg

Instead of trying to control the buffer size, we have to close FFmpeg gracefully.

For closing FFmpeg gracefully, we may write 'q' to stdin pipe, as described in this post.

When we start recording, the following message appears: Press [q] to stop, [?] for help.
Writing 'q' to stdin simulates pressing the q key.

  • Open FFmpeg sub-process with pipe_stdin=True:

     process = ffmpeg.run_async(stream, cmd=APPLICATION, pipe_stdin=True, overwrite_output=True, quiet=True)
  • Write 'q' letter (with encode("GBK")) to stdin pipe, and “communicate()“:

  • Wait for FFmpeg sub-process to end:


Code sample:

from time import sleep
import ffmpeg
import signal

APPLICATION = "ffmpeg.exe"
CAMERA_NAME = "Sandberg USB Webcam Pro"

stream = ffmpeg.input(f"video={CAMERA_NAME}", format="dshow")   
stream = ffmpeg.output(stream, "output.mkv", preset="medium", c="copy")

if __name__ == "__main__":   
    process = ffmpeg.run_async(stream, cmd=APPLICATION, pipe_stdin=True, overwrite_output=True, quiet=True)
    _ = input("Press enter when finished.")
    #sleep(10) # Record 10 seconds for testing

When I used sleep(10) instead of _ = input, the recorded video duration was about 9 seconds.
I think it records 9 seconds and not 10 seconds because it takes FFmpeg about one second to be loaded and start execution.

Setting real-time buffer to 100M, and fflags="nobuffer" had no effect.


stream = ffmpeg.input(f"video={CAMERA_NAME}", rtbufsize="100M", format="dshow")


stream = ffmpeg.input(f"video={CAMERA_NAME}", fflags="nobuffer", format="dshow")

It looks like FFmpeg flushes the buffers when we write 'q', there is no data loss and the buffer size has no effect.

Read more here: Source link