sskodje / ScreenRecorderLib

A .NET library for screen recording in Windows, using native Microsoft Media Foundation for realtime encoding to h264 video or PNG images.
MIT License
414 stars 94 forks source link

Preserving video for unexpected app crash/stop events #231

Closed ranwer-dev closed 1 year ago

ranwer-dev commented 1 year ago

Is it possible that we can prevent the corruption of recorded video in case of an app crash or any other such event? I have seen this behavior with FFmpeg, where if we press ctrl+c or close the command window forcefully, the playable video is still saved.

sskodje commented 1 year ago

The reason why a normal h264 file will get corrupted when you close the console or press ctrl-c is because Windows will forcefully terminate your application, so it can't finish up what it's doing. To prevent this, there's a couple things you can do.

If you enabled "fragmented mp4" in the encoder options, you will always get a valid video file, because it continuously writes metadata instead of doing it once in a second pass at the end of the recording. As it writes into "fragments" of some seconds length, you may end up missing a bit of the end.

You can also hook into the console or window, and delay termination of the process until cleanup is done. This is probably what FFmpeg does. This can't be done from a DLL, so it must be done in your app. You can do this with the SetConsoleCtrlHandler hook on console applications, or you can use Window closing event to delay exit and gracefully stop the recording. Note that this will not prevent a crash from corrupting the recording.

ranwer-dev commented 1 year ago

Is there any drawback from performance point of view to use fragmented mp4 option?

sskodje commented 1 year ago

I don't really know. I haven't noticed any major differences.