By default we use the (configurable) "q" key to handle window closing and exporting of the resulting video file. If by any chance the program crashes or if someone closes the window by any other means, the video is not encoded correctly.
It is suggested we handle this by using the method cv2.getWindowProperty('', cv2.WND_PROP_VISIBLE) which returns -1 if the window is no longer visible.
Possibly relevant:
https://stackoverflow.com/a/45564409