Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully close an ffmpeg process running in background without corrupting the encoded video file?

I need to be able to stop it on demand. I tried to gracefully terminate the process with taskkill /im ffmpeg.exe but it doesn't work. If I force it with /f then the video file gets corrupted.

I think the alternatives could be:

  • To get the process handle and then send a q keystroke to the stdin of that process running in background.
  • To get the console back again so I can sent the input from the console.
  • To use PyHooks and/or Win32Api to read keypresses, if a combination is pressed, then write to the stdin of the process.

This is the code (rec.pyw) I used to create the ffmpeg.exe process, hidden:

import subprocess
import sys
import os

# Creation flags
DETACHED_PROCESS = 0x00000008
CREATE_NO_WINDOW = 0x08000000
CREATE_NEW_PROCESS_GROUP = 0x00000200

cmd = sys._MEIPASS + os.sep + 'ffmpeg.exe -f dshow -i video=screen-capture-recorder -vcodec libx264 -qp 0 -crf 0 -vf scale=1280x720 -preset ultrafast -an -y out.mp4'
r = subprocess.call(cmd.split(), shell=True) #creationflags=

Then I used pyinstaller to create an exe file with ffmpeg bundled:

pyinstaller --onefile --noconsole --add-binary ffmpeg.exe;. rec.pyw

I used the creationflags parameters because I've read that with a detached process I could create the window again. But I haven't found how.

Workaround

I've found that if I use .mkv instead of .mp4 the file doesn't get corrupted when killing the ffmpeg process from the task manager.


1 Answers

The following linked post taught me to cleanly stop ffmpeg from python by simulating a keypress of 'q':

How to stop ffmpeg remotely?

You create an empty file that you write 'q' to when you are ready to stop it.

To start the ffmpeg stream with python code, do this:

os.system("<stop /usr/bin/ffmpeg ...") 

When ready to stop ffmpeg in your python code, do this:

os.system("echo 'q' >stop") 
like image 87
Sean Miller Avatar answered Nov 18 '25 12:11

Sean Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!