Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions scenedetect/backends/opencv.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,35 @@
)


def _is_interrupted_recording(path: str) -> bool:
"""True if `path` is an MP4/MOV with media data (mdat) but no complete index (moov), which is
what a camera leaves when recording is cut off (e.g. the battery dies). OpenCV only logs
"moov atom not found" in that case, so the top-level boxes are walked to tell."""
try:
size = os.path.getsize(path)
with open(path, "rb") as file:
pos, seen_mdat = 0, False
while pos + 8 <= size:
file.seek(pos)
header = file.read(16)
box_size, box_type = int.from_bytes(header[:4], "big"), header[4:8]
if pos == 0 and box_type != b"ftyp":
return False
if box_size == 1 and len(header) == 16:
box_size = int.from_bytes(header[8:16], "big")
elif box_size == 0:
box_size = size - pos
if box_size < 8:
return False
if box_type == b"moov":
return pos + box_size > size
seen_mdat = seen_mdat or box_type == b"mdat"
pos += box_size
return seen_mdat
except OSError:
return False


def _get_capture_api(path: str) -> int:
"""API preference to use when opening `path` with `cv2.VideoCapture`. This exists as a
workaround for https://scenedetect.com/issue/575, where certain versions of the opencv-python
Expand Down Expand Up @@ -392,6 +421,14 @@ def _open_capture(self, frame_rate: FrameRate | None = None):

cap = cv2.VideoCapture(self._path_or_device, capture_api)
if not cap.isOpened():
if isinstance(self._path_or_device, str) and _is_interrupted_recording(
self._path_or_device
):
raise VideoOpenFailure(
"Video file has no index (moov atom): the recording was probably interrupted "
"before it was saved, for example because the camera lost power. The video "
"data may still be in the file.\n"
)
raise VideoOpenFailure(
"Ensure file is valid video and system dependencies are up to date.\n"
)
Expand Down
13 changes: 13 additions & 0 deletions tests/test_backend_opencv.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from scenedetect import ContentDetector, SceneManager
from scenedetect.backends.opencv import VideoCaptureAdapter, VideoStreamCv2
from scenedetect.video_stream import VideoOpenFailure

GROUND_TRUTH_CAPTURE_ADAPTER_TEST = [1, 90, 210]
GROUND_TRUTH_CAPTURE_ADAPTER_CALLBACK_TEST = [180, 394]
Expand Down Expand Up @@ -133,3 +134,15 @@ def test_decode_failures_exposed(corrupt_video_file: str):
pass
assert adapter.decode_failures == adapter._decode_failures
assert adapter.decode_failures >= 0


def test_open_interrupted_recording(test_video_file: str, tmp_path):
"""A recording cut off before its moov atom was written is reported as such."""
with open(test_video_file, "rb") as file:
data = file.read()
interrupted = tmp_path / "interrupted.mp4"
interrupted.write_bytes(data[: len(data) // 2])
with pytest.raises(VideoOpenFailure, match="moov atom"):
VideoStreamCv2(str(interrupted))
# A complete file still opens.
assert VideoStreamCv2(test_video_file).frame_rate > 0