In a Python script I want to capture a webcam stream and save it to a video file on local harddisk, but I want to script to determine lifecycle of the video. For this I am using python-ffmpeg
library which is essentially a simple Python SDK around ffmpeg in a subprocess.
This is my snipped currently:
from time import sleep
import ffmpeg
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, overwrite_output=True, quiet=True)
_ = input("Press enter when finished.")
print("Shutting down in 3 seconds..")
sleep(3)
process.terminate()
This works fine. However, the process.terminate() is quite abrupt, since it essentially just kills the subprocess immediately. I've seen that this tends to cut off a few seconds of the video stream. I assume it is being written continuously and when killed whatever is already written remains.
Right now I have no control over the duration (of the.. buffer?). I'm just guessing it's around 3 seconds, hence my sleep call. Is there a way to configure this to ffmpeg?