Can't read corrupted MP4 file (moov atom missing) with VideoCapture

OpenCV 4.5.0

I have a problem when I create a VideoCapture() object for a video MP4 which is corrupted (an thus has a missing moov atom).

The videos are generated using GStreamer, and I cannot avoid certain cases when a corrupted video file is generated (from early stopping a pipeline). So I need to address these corrupted files in the file reading process.

Here is the code in question.

    cap = cv2.VideoCapture(str(vid_path))
    logging.info("Capture generated?")
    # Check if camera opened successfully, and if the video has frames
    if not cap.isOpened() or cap.get(cv2.CAP_PROP_FRAME_COUNT) < 1:
        # VIDEO IS CORRUPTED! NEEDS TO RELEASE AND DELETE THE VIDEO!
        logging.error("Error opening video file %s", vid_path)
        cap.release()
        raise IOError(f"Error opening video file {vid_path}")

  # Video is not corrupted... Do some processing
  cap.release()
  return

Particularly, the problem does not arise every time the code is run. Sometimes, it does not block and correctly goes through the “if condition” raising the exception, but other times it gets stuck in the cap=cv2.VideoCapture and does not print the following line (“Capture generated?”).

I have been studying this problem, and it seems like it does not happen on the first instance of when a corrupted file is created, but rather after several have been encountered. So I speculate that there is a bug in the way that a VideoCapture is created or – very likely – released when a corrupted video is encountered.

Getting VideoCapture fixed may take time, but meanwhile you could spawn from your app some external too to check the file - including another instance of Python that would try the file with VideoCapture and report back, or just delete the file.

that’s an issue with your writing process. the file is simply corrupted and unreadable.

that’s not an issue with OpenCV or ffmpeg. it is logically impossible to read that file. nothing can read it. not without serious assumptions about its format. no library can just do that.

please present those corrupted files, as well as detailed steps to how these files were created and how they ended up corrupted.

all your corrupted files are unsalvageable.

quick fix: don’t use mp4/mov. use mpeg transport stream. .MTS, .ts, …