From c1083c86d009d3be8fbabb4cb5820e53587d63c9 Mon Sep 17 00:00:00 2001 From: Breakthrough Date: Sat, 21 Nov 2026 22:51:47 -0500 Subject: [PATCH] [scanner] Extract motion event state machine from MotionScanner.scan() --- dvr_scan/scanner.py | 773 ++++++++++++++++++++----------- tests/test_event_tracker.py | 885 ++++++++++++++++++++++++++++++++++++ 2 files changed, 1387 insertions(+), 271 deletions(-) create mode 100644 tests/test_event_tracker.py diff --git a/dvr_scan/scanner.py b/dvr_scan/scanner.py index 612ffc0..2d68185 100644 --- a/dvr_scan/scanner.py +++ b/dvr_scan/scanner.py @@ -18,7 +18,7 @@ import sys import threading import typing as ty -from dataclasses import dataclass +from dataclasses import dataclass, field from enum import Enum from fractions import Fraction from pathlib import Path @@ -127,6 +127,417 @@ class DetectionResult: num_frames: int +@dataclass +class CompletedEvent: + """Motion event finalized by `MotionEventTracker`, along with its peak frame.""" + + event: MotionEvent + event_number: int + high_score: float + high_frame: ty.Any = None + + +@dataclass +class EventStep: + """Outputs produced by `MotionEventTracker.update()` for a single frame. + + Callers must always process outputs in order: `frames_before_event`, then + `completed_event` (if set), then `frames_after_event`. Frame lists may be populated + even when `completed_event` is `None` (continuing events emit to + `frames_before_event`; newly started events flush buffered frames to + `frames_after_event`). + """ + + frames_before_event: ty.List[ty.Any] = field(default_factory=list) + completed_event: ty.Optional[CompletedEvent] = None + frames_after_event: ty.List[ty.Any] = field(default_factory=list) + event_started: bool = False + max_events_reached: bool = False + + +_UNSET = object() + + +class MotionEventTracker: + """State machine tracking motion events, frame buffering, and peak-score frames. + + Pure timing and buffering logic with no threading, OpenCV, or video I/O + dependencies so it can be driven directly by `MotionScanner.scan()` or synthetic + unit tests. + """ + + def __init__( + self, + threshold: float, + min_event_len: FrameTimecode, + time_pre_event: FrameTimecode, + time_post_event: FrameTimecode, + frame_rate: float, + scan_start_time: ty.Optional[FrameTimecode] = None, + max_event_len: ty.Optional[FrameTimecode] = None, + merge_window: ty.Optional[FrameTimecode] = None, + frame_skip: int = 0, + max_events: int = 0, + ): + self._threshold: float = threshold + self._max_events: int = max_events + self._scan_start_time: FrameTimecode = ( + scan_start_time if scan_start_time is not None else FrameTimecode(0, frame_rate) + ) + + # Correct event length parameters to account for frame skip. The window and buffer + # sizes below are counts of *processed* frames; on VFR input they are approximations + # derived from the average framerate, but emitted event boundaries are always exact + # (PTS-based). + pre_event_len: int = time_pre_event.frame_num // (frame_skip + 1) + self._min_event_len: int = max(min_event_len.frame_num // (frame_skip + 1), 1) + + # Calculations below rely on min_event_len always being >= 1 (cannot be zero). + assert self._min_event_len >= 1, "min_event_len must be at least 1 frame" + + # Presentation duration of one source frame at the average framerate, and the + # span covered by one processed frame (including skipped frames). + self._frame_duration: float = 1.0 / float(frame_rate) + self._frame_step: float = self._frame_duration * (1 + frame_skip) + + # Ensure that we include the exact amount of time specified in `-tb`/`--time-before` + # when shifting the event start time. Instead of using `-l`/`--min-event-len` + # directly, we compensate for rounding errors when we corrected it for frame skip. + # This is important as this affects the number of frames we consider for the actual + # motion event. + self._start_event_shift: float = ( + time_pre_event.frame_num + self._min_event_len * (frame_skip + 1) + ) * self._frame_duration + + # Amount of time to include after the last frame with motion in each event. + self._post_event_duration: float = time_post_event.frame_num * self._frame_duration + + # Two groups of motion less than this far apart are merged into the same event. + # By default (auto / None) this is the same as the post-event duration, which matches + # the behavior of previous versions where -tp controlled merging (#195). + self._merge_window_duration: float = ( + self._post_event_duration + if merge_window is None + else merge_window.frame_num * self._frame_duration + ) + if self._post_event_duration > self._merge_window_duration: + logger.warning( + "time-post-event (%s) is larger than merge-window (%s), capping the " + "post-event padding to the merge window.", + time_post_event.get_timecode(), + merge_window.get_timecode(), + ) + self._post_event_duration = self._merge_window_duration + + # Length of buffer we require in memory to keep track of all frames for -l and -tb. + self._buff_len: int = pre_event_len + self._min_event_len + + # Upper bound on the length of each event (-Y/--max-event-length), in seconds. + # Events are split before any frame which would exceed it, so it must cover at least + # one processed frame (including skipped frames). + self._max_event_seconds: ty.Optional[float] = ( + max(max_event_len.seconds, self._frame_step) if max_event_len is not None else None + ) + + # Mutable tracking state. + self._in_motion_event: bool = False + self._max_events_reached: bool = False + self._event_start: ty.Optional[FrameTimecode] = None + self._last_event_end: FrameTimecode = self._scan_start_time + self._last_motion_time: FrameTimecode = self._scan_start_time + self._last_frame_time: FrameTimecode = self._scan_start_time + self._event_window: ty.List[float] = [] + self._buffered_frames: ty.List[ty.Tuple[FrameTimecode, ty.Any]] = [] + # Frames decoded after the post-event padding while waiting to see if motion + # resumes within the merge window. Flushed into the event if it does, otherwise + # they seed `_buffered_frames` for the next event. + self._post_motion_frames: ty.List[ty.Tuple[FrameTimecode, ty.Any]] = [] + self._events: ty.List[MotionEvent] = [] + self._high_score: float = 0 + self._high_frame: ty.Any = None + + @property + def events(self) -> ty.List[MotionEvent]: + """Completed motion events detected so far (returned as a shallow copy).""" + return list(self._events) + + @property + def in_motion_event(self) -> bool: + """Whether a motion event is currently in progress (including its merge window).""" + return self._in_motion_event + + @property + def active_event_count(self) -> int: + """Number of completed events plus one if an event is currently in progress.""" + return len(self._events) + (1 if self._in_motion_event else 0) + + @property + def max_events_reached(self) -> bool: + """Whether `max_events` was reached during frame processing.""" + return self._max_events_reached + + @property + def high_score(self) -> float: + """Peak motion score recorded for the current (or candidate) event.""" + return self._high_score + + @property + def high_frame(self) -> ty.Any: + """Frame associated with `high_score`, or `None` if no candidate is held.""" + return self._high_frame + + def _padded_end(self) -> FrameTimecode: + """Exact (PTS-based) end of the current event if it does not continue. + + Includes the post-event length time, compensation for skipped frames that could + have had motion, and the presentation duration of the last motion frame itself. + """ + return self._last_motion_time + (self._post_event_duration + self._frame_step) + + def _finish_event( + self, start: FrameTimecode, end: FrameTimecode, can_stop: bool = True + ) -> CompletedEvent: + """Record the in-progress event as ending at `end` and reset per-event state.""" + if end.seconds < start.seconds: + logger.debug("clamping event end %s to start %s", end, start) + end = start + event_number = 1 + len(self._events) + logger.debug("event %d high score %f", event_number, self._high_score) + completed = CompletedEvent( + event=MotionEvent(start=start, end=end), + event_number=event_number, + high_score=self._high_score, + high_frame=self._high_frame, + ) + # Reset even when thumbnails are off so the score/frame don't carry over into + # the next event (#267). + self._high_score = 0 + self._high_frame = None + self._events.append(completed.event) + self._last_event_end = end + if can_stop and self._max_events > 0 and len(self._events) >= self._max_events: + self._max_events_reached = True + return completed + + def _update_high_score( + self, score: float, above_threshold: bool, candidate_frame: ty.Any + ) -> None: + if above_threshold: + if score > self._high_score: + self._high_score = score + # Copy mutable frames (e.g. numpy arrays) since the encode thread draws + # overlays in-place on the original when writing events. + self._high_frame = ( + candidate_frame.copy() if hasattr(candidate_frame, "copy") else candidate_frame + ) + elif not self._in_motion_event: + # Outside of a motion event, a frame below the threshold means the current + # streak of frames can no longer start an event, so any thumbnail candidate + # captured from it must be discarded (#268). + self._high_score = 0 + self._high_frame = None + + def _compute_event_start(self, timecode: FrameTimecode) -> FrameTimecode: + """Compute the start timecode of a newly triggered event, trimming pre-roll if needed.""" + # Shift the event start back to include the pre-event and min-event windows, + # clamped so events never overlap the previous event or the start of the scan. + # Includes the presentation duration of this frame. + time_since_last_event = ( + timecode.seconds + self._frame_duration - self._last_event_end.seconds + ) + shift_amount = min(time_since_last_event, self._start_event_shift) + event_start = timecode + (self._frame_duration - shift_amount) + if event_start.seconds < self._scan_start_time.seconds: + event_start = self._scan_start_time + # -Y/--max-event-length also bounds the pre-roll: when the pre-event window is + # at least as long as the limit, start the event so the current frame (including + # skipped frames) still fits within it. + if ( + self._max_event_seconds is not None + and event_start.seconds + self._max_event_seconds < timecode.seconds + self._frame_step + ): + event_start = timecode + (self._frame_step - self._max_event_seconds) + self._buffered_frames = [ + (tc, payload) for tc, payload in self._buffered_frames if tc >= event_start + ] + return event_start + + def clear_buffers(self) -> None: + """Release buffered pre-event and merge-tail frames without altering peak state.""" + self._buffered_frames = [] + self._post_motion_frames = [] + + def _split_event_if_needed( + self, timecode: FrameTimecode, above_threshold: bool, step: EventStep + ) -> bool: + """Split the active event if `timecode` would exceed `-Y/--max-event-length`. + + Populates `step` with any held frames and the completed event. Returns `True` + if reaching `max_events` ended the scan immediately (caller should return `step`). + """ + if ( + not self._in_motion_event + or self._max_event_seconds is None + or (timecode + self._frame_step <= self._event_start + self._max_event_seconds) + ): + return False + + if above_threshold: + # Motion is ongoing, so frames held while waiting out the merge window + # belong to this event, which now ends exactly where the next begins. + step.frames_before_event.extend(payload for _, payload in self._post_motion_frames) + self._post_motion_frames = [] + split_end = timecode + else: + padded_end = self._padded_end() + split_end = timecode if timecode < padded_end else padded_end + step.completed_event = self._finish_event(self._event_start, split_end) + step.max_events_reached = self._max_events_reached + if self._max_events_reached: + self._in_motion_event = False + self.clear_buffers() + return True + if above_threshold: + self._event_start = timecode + self._buffered_frames = [] + self._event_window = [] + step.event_started = True + else: + self._buffered_frames = self._post_motion_frames[-self._buff_len :] + self._post_motion_frames = [] + self._in_motion_event = False + return False + + def update( + self, + timecode: FrameTimecode, + score: float, + frame: ty.Any = None, + *, + high_frame: ty.Any = _UNSET, + above_threshold: ty.Optional[bool] = None, + ) -> EventStep: + """Advance the state machine by one processed frame. + + Arguments: + timecode: Presentation timecode of the frame. + score: Filtered motion score for the frame. + frame: Optional frame payload to buffer/emit for streaming encoders (or `None` + when frame streaming is not needed). + high_frame: Optional frame object stored as the peak-score candidate when this + frame beats the current high score. Defaults to `frame`. + above_threshold: Optional explicit motion flag overriding `score >= threshold` + (used by `MotionScanner` to suppress the detector's first warmup frame). + """ + if self._max_events_reached: + return EventStep(max_events_reached=True) + + if high_frame is _UNSET: + high_frame = frame + if above_threshold is None: + above_threshold = score >= self._threshold + + self._last_frame_time = timecode + self._event_window.append(score) + self._event_window = self._event_window[-self._min_event_len :] + + step = EventStep() + + # Split events at -Y/--max-event-length before tracking the high score so the + # split frame counts towards the next event's thumbnail. + if self._split_event_if_needed(timecode, above_threshold, step): + return step + + self._update_high_score(score, above_threshold, high_frame) + + # Last frame was part of a motion event, or still within the merge window. + if self._in_motion_event: + hold_frame = False + padded_end = self._padded_end() + # If this frame still has motion, reset the merge window. + if above_threshold: + self._last_motion_time = timecode + # Motion resumed within the merge window, so any frames we held beyond + # the post-event padding are part of this event after all. + if self._post_motion_frames: + step.frames_before_event.extend( + payload for _, payload in self._post_motion_frames + ) + self._post_motion_frames = [] + # Otherwise, wait until the merge window has passed before ending this + # motion event and starting to look for a new one. + elif (timecode.seconds - self._last_motion_time.seconds) >= self._merge_window_duration: + self._in_motion_event = False + if frame is not None: + # The frame which ends the event is still part of its clip if it + # starts before the event's end (compared on exact PTS, as the + # window check above is subject to float rounding); otherwise it + # may fall within the next event's pre-event window. + if timecode < padded_end: + step.frames_before_event.append(frame) + else: + self._post_motion_frames.append((timecode, frame)) + step.completed_event = self._finish_event(self._event_start, padded_end) + step.max_events_reached = self._max_events_reached + if self._max_events_reached: + self.clear_buffers() + else: + # Frames held beyond the post-event padding are not part of this event, + # but may fall within the next event's pre-event window. + self._buffered_frames = self._post_motion_frames[-self._buff_len :] + self._post_motion_frames = [] + else: + # No motion, but still within the merge window. Frames inside the + # post-event padding are part of the output clip whether or not the + # event continues, so they can be sent for encoding right away; any + # frames past that point are held until we know. + hold_frame = timecode >= padded_end + + if self._in_motion_event and frame is not None: + if hold_frame: + self._post_motion_frames.append((timecode, frame)) + elif step.completed_event is not None: + step.frames_after_event.append(frame) + else: + step.frames_before_event.append(frame) + # Not already in a motion event, look for a new one. + else: + # Buffer the required amount of frames and overlay data until we find an event. + if frame is not None: + self._buffered_frames.append((timecode, frame)) + self._buffered_frames = self._buffered_frames[-self._buff_len :] + # Start a new event once all frames in the event window have motion. + if len(self._event_window) >= self._min_event_len and all( + s >= self._threshold for s in self._event_window + ): + self._in_motion_event = True + step.event_started = True + self._event_window = [] + self._last_motion_time = timecode + self._event_start = self._compute_event_start(timecode) + step.frames_after_event.extend(payload for _, payload in self._buffered_frames) + self._buffered_frames = [] + + return step + + def finish(self) -> ty.Optional[CompletedEvent]: + """Flush any in-progress motion event at end-of-stream and release buffered frames. + + Uses the last processed frame's presentation time plus its presentation duration + (including any skipped frames), clamped to the post-event padding when the stream + ends partway through the merge window. + """ + self.clear_buffers() + if not self._in_motion_event: + return None + self._in_motion_event = False + event_end = self._last_frame_time + self._frame_step + padded_end = self._padded_end() + if padded_end.seconds < event_end.seconds: + event_end = padded_end + return self._finish_event(self._event_start, event_end, can_stop=False) + + # TODO(#75): See if this needs to be tweaked for the CNT algorithm. def _recommended_kernel_size(frame_width: int, downscale_factor: int) -> int: corrected_width = round(frame_width / float(downscale_factor)) @@ -212,8 +623,7 @@ def __init__( # Thumbnail production (set_thumbnail_params) self._thumbnails = None - self._highscore = 0 - self._highframe = None + self._tracker: ty.Optional[MotionEventTracker] = None # Callbacks for UI integration self._scan_started = None @@ -234,6 +644,16 @@ def frame_rate(self) -> float: """Get the framerate of the currently loaded video(s).""" return self._input.framerate + @property + def _highscore(self) -> float: + """Current peak motion score tracked for the active/candidate event.""" + return self._tracker.high_score if self._tracker is not None else 0 + + @property + def _highframe(self) -> ty.Optional[np.ndarray]: + """Frame associated with `_highscore`, if any.""" + return self._tracker.high_frame if self._tracker is not None else None + def set_output( self, output_dir: ty.Optional[Path] = None, @@ -594,22 +1014,23 @@ def set_callbacks( self._scan_started = scan_started self._processed_frame = processed_frame + def _enqueue_frames( + self, encode_queue: queue.Queue, frames: ty.Iterable[EncodeFrameEvent] + ) -> None: + """Put frames onto `encode_queue`, stopping early if the scan is cancelled.""" + for encode_frame in frames: + # Since we're putting multiple items into the queue, we have to keep making + # sure the encode thread is running; otherwise the queue will never empty + # and we would block indefinitely waiting for a spot. + if self._stop.is_set(): + break + encode_queue.put(encode_frame) + def scan(self) -> ty.Optional[DetectionResult]: """Performs motion analysis on the MotionScanner's input video(s).""" self._stop.clear() self._max_events_reached = False - self._highscore = 0 - self._highframe = None - buffered_frames: ty.List[np.ndarray] = [] - # Frames decoded after the post-event padding while waiting to see if motion - # resumes within the merge window. Flushed into the event if it does, otherwise - # they seed `buffered_frames` for the next event. - post_motion_frames: ty.List[EncodeFrameEvent] = [] - event_window: ty.List[float] = [] - event_list: ty.List[MotionEvent] = [] - event_start = None - - in_motion_event = False + self._tracker = None frames_processed = 0 self._check_time_range() @@ -680,51 +1101,19 @@ def scan(self) -> ty.Optional[DetectionResult]: self._frame_skip, ) - # Correct event length parameters to account frame skip. The window and buffer sizes - # below are counts of *processed* frames; on VFR input they are approximations derived - # from the average framerate, but emitted event boundaries are always exact (PTS-based). - pre_event_len: int = self._time_before_event.frame_num // (self._frame_skip + 1) - min_event_len: int = max(self._min_event_len.frame_num // (self._frame_skip + 1), 1) - - # Calculations below rely on min_event_len always being >= 1 (cannot be zero) - assert min_event_len >= 1, "min_event_len must be at least 1 frame" - - # Presentation duration of one source frame at the average framerate. - frame_duration: float = 1.0 / float(self._input.framerate) - - # Ensure that we include the exact amount of time specified in `-tb`/`--time-before` when - # shifting the event start time. Instead of using `-l`/`--min-event-len` directly, we - # need to compensate for rounding errors when we corrected it for frame skip. This is - # important as this affects the number of frames we consider for the actual motion event. - start_event_shift: float = ( - self._time_before_event.frame_num + min_event_len * (self._frame_skip + 1) - ) * frame_duration - - # Amount of time to include after the last frame with motion in each event. - post_event_duration: float = self._post_event_len.frame_num * frame_duration - - # Two groups of motion less than this far apart are merged into the same event. - # By default (auto) this is the same as the post-event duration, which matches - # the behavior of previous versions where -tp controlled merging (#195). - merge_window_duration: float = ( - post_event_duration - if self._merge_window is None - else self._merge_window.frame_num * frame_duration + tracker = MotionEventTracker( + threshold=self._threshold, + min_event_len=self._min_event_len, + max_event_len=self._max_event_len, + time_pre_event=self._time_before_event, + time_post_event=self._post_event_len, + frame_rate=self._input.framerate, + scan_start_time=scan_start_time, + merge_window=self._merge_window, + frame_skip=self._frame_skip, + max_events=self._max_events, ) - if post_event_duration > merge_window_duration: - logger.warning( - "time-post-event (%s) is larger than merge-window (%s), capping the " - "post-event padding to the merge window.", - self._post_event_len.get_timecode(), - self._merge_window.get_timecode(), - ) - post_event_duration = merge_window_duration - - # Length of buffer we require in memory to keep track of all frames required for -l and -tb. - buff_len = pre_event_len + min_event_len - event_end = scan_start_time - last_motion_time = scan_start_time - last_frame_time = scan_start_time + self._tracker = tracker if self._bounding_box: self._bounding_box.set_corrections( @@ -749,13 +1138,6 @@ def scan(self) -> ty.Optional[DetectionResult]: progress_bar = FakeTqdmObject() if not self._show_progress else self._create_progress_bar() num_frames_to_process = self.frames_remaining - # Upper bound on the length of each event (-Y/--max-event-length), in seconds. Events - # are split before any frame which would exceed it, so it must cover at least one - # processed frame (including skipped frames). - max_event_seconds: float = max( - self._max_event_len.seconds, frame_duration * (1 + self._frame_skip) - ) - self._decode_thread_exception = None self._encode_thread_exception = None decode_queue = queue.Queue(MAX_DECODE_QUEUE_SIZE) @@ -765,26 +1147,19 @@ def scan(self) -> ty.Optional[DetectionResult]: ) encode_thread: ty.Optional[threading.Thread] = None - def finish_event( - start: FrameTimecode, end: FrameTimecode, can_stop: bool = True - ) -> FrameTimecode: - """Record the in-progress event as ending at `end` and send it to the encode - thread (after any of its frames). Returns the (clamped) end of the event.""" - if end.seconds < start.seconds: - logger.debug("clamping event end %s to start %s", end, start) - end = start - logger.debug("event %d high score %f" % (1 + len(event_list), self._highscore)) + def handle_completed_event(completed: CompletedEvent, stop_on_limit: bool = False) -> None: + """Write thumbnail, notify the encode thread, and stop if `max_events` was hit.""" + if self._stop.is_set(): + return if self._thumbnails == "highscore": - # This event has not been appended to event_list yet. - self._write_highscore_thumbnail(start, 1 + len(event_list)) - # Reset even when thumbnails are off so the score/frame don't carry over into - # the next event (#267). - self._highscore = 0 - self._highframe = None - event_list.append(MotionEvent(start=start, end=end)) + self._write_highscore_thumbnail( + completed.event.start, completed.event_number, completed.high_frame + ) + if self._stop.is_set(): + return if self._output_mode != OutputMode.SCAN_ONLY: - encode_queue.put(MotionEvent(start=start, end=end)) - if can_stop and self._max_events > 0 and len(event_list) >= self._max_events: + encode_queue.put(completed.event) + if stop_on_limit and not self._stop.is_set(): logger.info( "Stopping scan, reached maximum number of events (%d).", self._max_events, @@ -793,7 +1168,6 @@ def finish_event( # interruption. self._max_events_reached = True self._stop.set() - return end decode_thread.start() # Any exception below must still stop and join the decode/encode threads, so the @@ -822,20 +1196,16 @@ def finish_event( if self._scan_started: self._scan_started(num_frames=num_frames_to_process) - # TODO: The main scanning loop should be refactored into a state machine. The main - # loop has grown far too complicated and is difficult to maintain. while not self._stop.is_set(): if self._processed_frame: - num_events = len(event_list) - if in_motion_event: - num_events += 1 - self._processed_frame(progress_bar=progress_bar, num_events=num_events) + self._processed_frame( + progress_bar=progress_bar, num_events=tracker.active_event_count + ) # Keep polling decode queue until it's empty (signaled via None). frame: ty.Optional[DecodeEvent] = decode_queue.get() - if frame is None: + if frame is None or self._stop.is_set(): break assert frame.frame_bgr is not None - last_frame_time = frame.timecode frame_size = (frame.frame_bgr.shape[1], frame.frame_bgr.shape[0]) if frame_size != self._input.resolution: time = frame.timecode @@ -869,62 +1239,11 @@ def finish_event( frame_score = 0 above_threshold = frame_score >= self._threshold - event_window.append(frame_score) # The first frame fed to the detector can sometimes produce unreliable results # due to it not having any previous information to compare against. if not processed_first_frame: above_threshold = False processed_first_frame = True - event_window = event_window[-min_event_len:] - - # Split events at -Y/--max-event-length on the first frame which would extend - # them past it (including skipped frames). The event ends where this frame - # starts (no post-event padding is added), and if there is still motion, this - # frame starts the next event. Done before tracking the high score so this - # frame counts towards the next event's thumbnail. - if in_motion_event and ( - frame.timecode + frame_duration * (1 + self._frame_skip) - > event_start + max_event_seconds - ): - if above_threshold: - # Motion is ongoing, so frames held while waiting out the merge window - # belong to this event, which now ends exactly where the next begins. - for held_frame in post_motion_frames: - if self._stop.is_set(): - break - encode_queue.put(held_frame) - post_motion_frames = [] - split_end = frame.timecode - else: - padded_end = last_motion_time + ( - post_event_duration + frame_duration * (1 + self._frame_skip) - ) - split_end = frame.timecode if frame.timecode < padded_end else padded_end - event_end = finish_event(event_start, split_end) - buffered_frames = post_motion_frames[-buff_len:] - post_motion_frames = [] - if above_threshold and not self._stop.is_set(): - event_start = frame.timecode - buffered_frames = [] - event_window = [] - progress_bar.set_description( - PROGRESS_BAR_DESCRIPTION % (1 + len(event_list)), refresh=False - ) - else: - in_motion_event = False - - if above_threshold: - if frame_score > self._highscore: - self._highscore = frame_score - # Copy the frame since the encode thread draws overlays in-place on - # the original when writing events. - self._highframe = frame.frame_bgr.copy() - elif not in_motion_event: - # Outside of a motion event, a frame below the threshold means the current - # streak of frames can no longer start an event, so any thumbnail - # candidate captured from it must be discarded (#268). - self._highscore = 0 - self._highframe = None bounding_box = None # TODO: Only call clear() when we exit the current motion event. @@ -958,115 +1277,26 @@ def finish_event( else None ) - # Last frame was part of a motion event, or still within the merge window. - if in_motion_event: - hold_frame = False - # Exact (PTS-based) end of the event if it doesn't continue: the last frame - # with motion plus the post event length time. We also need to compensate - # for the number of frames that we skipped that could have had motion, and - # include the presentation duration of the last frame itself. - padded_end = last_motion_time + ( - post_event_duration + frame_duration * (1 + self._frame_skip) + if self._stop.is_set(): + break + + step = tracker.update( + timecode=frame.timecode, + score=frame_score, + frame=encode_frame, + high_frame=frame.frame_bgr, + above_threshold=above_threshold, + ) + self._enqueue_frames(encode_queue, step.frames_before_event) + if step.completed_event is not None: + handle_completed_event( + step.completed_event, stop_on_limit=step.max_events_reached ) - # If this frame still has motion, reset the merge window. - if above_threshold: - last_motion_time = frame.timecode - # Motion resumed within the merge window, so any frames we held - # beyond the post-event padding are part of this event after all. - for held_frame in post_motion_frames: - # We have to be careful here. Since we're putting multiple items - # into the queue, we have to keep making sure the encode thread - # is running. Otherwise, the queue will never empty we will block - # indefinitely here waiting for a spot. - if self._stop.is_set(): - break - encode_queue.put(held_frame) - post_motion_frames = [] - # Otherwise, we wait until the merge window has passed before ending - # this motion event and start looking for a new one. - elif ( - frame.timecode.seconds - last_motion_time.seconds - ) >= merge_window_duration: - in_motion_event = False - if encode_frame is not None: - # The frame which ends the event is still part of its clip if it - # starts before the event's end (compared on exact PTS, as the - # window check above is subject to float rounding); otherwise it - # may fall within the next event's pre-event window. - if frame.timecode < padded_end: - encode_queue.put(encode_frame) - else: - post_motion_frames.append(encode_frame) - event_end = finish_event(event_start, padded_end) - # Frames held beyond the post-event padding are not part of this - # event, but may fall within the next event's pre-event window. - buffered_frames = post_motion_frames[-buff_len:] - post_motion_frames = [] - else: - # No motion, but still within the merge window. Frames inside the - # post-event padding are part of the output clip whether or not the - # event continues, so they can be sent for encoding right away; any - # frames past that point are held until we know. - hold_frame = frame.timecode >= padded_end - - # Send frame to encode thread. - if in_motion_event and encode_frame is not None: - if hold_frame: - post_motion_frames.append(encode_frame) - else: - encode_queue.put(encode_frame) - # Not already in a motion event, look for a new one. - elif not self._stop.is_set(): - # Buffer the required amount of frames and overlay data until we find an - # event. - if encode_frame is not None: - buffered_frames.append(encode_frame) - buffered_frames = buffered_frames[-buff_len:] - # Start a new event once all frames in the event window have motion. - if len(event_window) >= min_event_len and all( - score >= self._threshold for score in event_window - ): - in_motion_event = True - progress_bar.set_description( - PROGRESS_BAR_DESCRIPTION % (1 + len(event_list)), refresh=False - ) - event_window = [] - last_motion_time = frame.timecode - - # Shift the event start back to include the pre-event and min-event - # windows, clamped so events never overlap the previous event or the - # start of the scan. Includes the presentation duration of this frame. - time_since_last_event = ( - frame.timecode.seconds + frame_duration - event_end.seconds - ) - shift_amount = min(time_since_last_event, start_event_shift) - event_start = frame.timecode + (frame_duration - shift_amount) - if event_start.seconds < scan_start_time.seconds: - event_start = scan_start_time - # -Y/--max-event-length also bounds the pre-roll: when the pre-event - # window is at least as long as the limit, start the event so the - # current frame (including skipped frames) still fits within it. - frame_step = frame_duration * (1 + self._frame_skip) - if ( - event_start.seconds + max_event_seconds - < frame.timecode.seconds + frame_step - ): - event_start = frame.timecode + (frame_step - max_event_seconds) - buffered_frames = [ - buffered_frame - for buffered_frame in buffered_frames - if buffered_frame.timecode >= event_start - ] - # Send buffered frames to encode thread. - for buffered_frame in buffered_frames: - # We have to be careful here. Since we're putting multiple items - # into the queue, we have to keep making sure the encode thread - # is running. Otherwise, the queue will never empty we will block - # indefinitely here waiting for a spot. - if self._stop.is_set(): - break - encode_queue.put(buffered_frame) - buffered_frames = [] + if step.event_started and not self._stop.is_set(): + progress_bar.set_description( + PROGRESS_BAR_DESCRIPTION % tracker.active_event_count, refresh=False + ) + self._enqueue_frames(encode_queue, step.frames_after_event) frames_processed += 1 + self._frame_skip progress_bar.update(1 + self._frame_skip) @@ -1081,20 +1311,14 @@ def finish_event( self._decode_thread_exception[2] ) - # Video ended, finished processing frames. If we're still in a motion event, - # compute the duration and ending timecode and add it to the event list. We can't - # query the input for a PTS at this point (OpenCV resets CAP_PROP_POS_MSEC to 0 at - # end of video), so use the last processed frame's exact presentation time plus - # its presentation duration (including any frames we skipped), clamped to the - # post-event padding when the video ends partway through the merge window. - if in_motion_event and not self._stop.is_set(): - event_end = last_frame_time + frame_duration * (1 + self._frame_skip) - padded_end = last_motion_time + ( - post_event_duration + frame_duration * (1 + self._frame_skip) - ) - if padded_end.seconds < event_end.seconds: - event_end = padded_end - finish_event(event_start, event_end, can_stop=False) + # Video ended, finished processing frames. Flush any in-progress motion event + # unless the scan was stopped early. We can't query the input for a PTS at this + # point (OpenCV resets CAP_PROP_POS_MSEC to 0 at end of video), so the tracker + # computes the end from the last processed frame's presentation time. + if not self._stop.is_set(): + completed = tracker.finish() + if completed is not None: + handle_completed_event(completed) # Push sentinel to queue, wait for encode thread, and re-raise any exceptions. if encode_thread is not None: @@ -1108,7 +1332,9 @@ def finish_event( self._stop.set() raise finally: - # No-ops on success, where both threads have already been joined above. + # Release buffered BGR frames even on cancel/exception, and ensure both + # worker threads are joined (no-ops on success). + tracker.clear_buffers() progress_bar.close() self._join_decode_thread(decode_thread, decode_queue) if encode_thread is not None: @@ -1126,7 +1352,7 @@ def finish_event( self._input.decode_failures, ) - return DetectionResult(event_list, frames_processed) + return DetectionResult(tracker.events, frames_processed) @staticmethod def _join_decode_thread(decode_thread: threading.Thread, decode_queue: queue.Queue): @@ -1203,14 +1429,19 @@ def _effective_frame_rate(self) -> float: ) return float(effective_framerate) - def _write_highscore_thumbnail(self, event_start: FrameTimecode, event_number: int): + def _write_highscore_thumbnail( + self, + event_start: FrameTimecode, + event_number: int, + high_frame: ty.Optional[np.ndarray], + ): """Save the highest-score frame of event `event_number` (starting at `event_start`) as a JPEG, named after the source video containing the event (or the combined output file's stem when -o is used, since per-event video files don't exist in that case). `event_number` comes from the scan loop rather than `self._num_events`, which is only advanced by the encode thread (and not at all in scan-only mode).""" - if self._highframe is None: + if high_frame is None: # Possible if the event was triggered before the detector stabilized # (e.g. an event starting on the first processed frame). logger.debug("no candidate frame for event %d, skipping thumbnail", event_number) @@ -1233,7 +1464,7 @@ def _write_highscore_thumbnail(self, event_start: FrameTimecode, event_number: i ) if self._output_dir: output_path = self._output_dir / output_path - cv2.imwrite(str(output_path), self._highframe) + cv2.imwrite(str(output_path), high_frame) def _create_encoder(self) -> ty.Optional[EventEncoder]: """Create the encoder used to write motion events based on the current output mode. diff --git a/tests/test_event_tracker.py b/tests/test_event_tracker.py new file mode 100644 index 0000000..c002cef --- /dev/null +++ b/tests/test_event_tracker.py @@ -0,0 +1,885 @@ +# +# DVR-Scan: Video Motion Event Detection & Extraction Tool +# -------------------------------------------------------------- +# [ Site: https://www.dvr-scan.com/ ] +# [ Repo: https://github.com/Breakthrough/DVR-Scan ] +# +# Copyright (C) 2016 Brandon Castellano . +# DVR-Scan is licensed under the BSD 2-Clause License; see the included +# LICENSE file, or visit one of the above pages for details. +# +"""Synthetic unit tests for `MotionEventTracker` (pure state machine, no video I/O).""" + +import logging +import typing as ty +from fractions import Fraction + +import numpy as np +import pytest +from scenedetect import FrameTimecode +from scenedetect.common import Timecode + +from dvr_scan.scanner import CompletedEvent, MotionEventTracker + + +def _pts(seconds: float, fps: float = 10.0) -> FrameTimecode: + """Create a microsecond PTS-backed `FrameTimecode` like `MotionScanner._presentation_time()`.""" + return FrameTimecode( + timecode=Timecode(pts=round(seconds * 1_000_000), time_base=Fraction(1, 1_000_000)), + fps=fps, + ) + + +def _make_tracker( + *, + fps: float = 10.0, + threshold: float = 0.5, + min_event_len: ty.Union[int, float, str] = 3, + time_pre_event: ty.Union[int, float, str] = 0, + time_post_event: ty.Union[int, float, str] = 0, + max_event_len: ty.Optional[ty.Union[int, float, str]] = None, + merge_window: ty.Optional[ty.Union[int, float, str]] = None, + frame_skip: int = 0, + max_events: int = 0, + scan_start_time: ty.Optional[FrameTimecode] = None, +) -> MotionEventTracker: + return MotionEventTracker( + threshold=threshold, + min_event_len=FrameTimecode(min_event_len, fps), + time_pre_event=FrameTimecode(time_pre_event, fps), + time_post_event=FrameTimecode(time_post_event, fps), + frame_rate=fps, + scan_start_time=scan_start_time if scan_start_time is not None else _pts(0.0, fps), + max_event_len=FrameTimecode(max_event_len, fps) if max_event_len is not None else None, + merge_window=FrameTimecode(merge_window, fps) if merge_window is not None else None, + frame_skip=frame_skip, + max_events=max_events, + ) + + +def _drive( + tracker: MotionEventTracker, + samples: ty.Sequence[ty.Tuple[FrameTimecode, float]], + *, + flush: bool = True, + stop_on_max_events: bool = True, +) -> ty.Tuple[ty.List[ty.Tuple[CompletedEvent, ty.List[FrameTimecode]]], ty.List[FrameTimecode]]: + """Feed `(timecode, score)` pairs into `tracker`, using each `timecode` as its frame payload. + + Returns `(recorded_events, orphan_frames)` where each recorded entry is + `(CompletedEvent, emitted_frame_timecodes)` in exact encoder order. + """ + recorded: ty.List[ty.Tuple[CompletedEvent, ty.List[FrameTimecode]]] = [] + current_frames: ty.List[FrameTimecode] = [] + + for tc, score in samples: + step = tracker.update(tc, score, frame=tc) + current_frames.extend(step.frames_before_event) + if step.completed_event is not None: + recorded.append((step.completed_event, current_frames)) + current_frames = [] + current_frames.extend(step.frames_after_event) + if stop_on_max_events and step.max_events_reached: + break + + if flush and not tracker.max_events_reached: + completed = tracker.finish() + if completed is not None: + recorded.append((completed, current_frames)) + current_frames = [] + + return recorded, current_frames + + +def _cfr_samples( + scores: ty.Sequence[float], + *, + fps: float = 10.0, + start_seconds: float = 0.0, + frame_skip: int = 0, +) -> ty.List[ty.Tuple[FrameTimecode, float]]: + step = (1 + frame_skip) / fps + return [(_pts(start_seconds + i * step, fps), score) for i, score in enumerate(scores)] + + +def _assert_frames_match_spans( + recorded: ty.List[ty.Tuple[CompletedEvent, ty.List[FrameTimecode]]], + all_timecodes: ty.Sequence[FrameTimecode], +) -> None: + """Every event's emitted frames must be exactly the processed frames in `[start, end)`.""" + for completed, frames in recorded: + start, end = completed.event.start, completed.event.end + assert end.seconds >= start.seconds + expected = [tc for tc in all_timecodes if start <= tc < end] + assert [tc.seconds for tc in frames] == [tc.seconds for tc in expected] + + +# --- Basic detection and min_event_len ---------------------------------------------------- + + +def test_single_event_meets_min_event_len(): + """A motion burst of at least `min_event_len` frames triggers one event with matching frames.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=3) + # Motion on frames 2, 3, 4, 5 (0.2s..0.5s); quiet before and after. + scores = [0.0, 0.0, 0.6, 0.8, 1.0, 0.7, 0.0, 0.0] + samples = _cfr_samples(scores, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + completed, frames = recorded[0] + assert completed.event_number == 1 + assert completed.event.start.seconds == pytest.approx(0.2) + assert completed.event.end.seconds == pytest.approx(0.6) + assert [tc.seconds for tc in frames] == pytest.approx([0.2, 0.3, 0.4, 0.5]) + assert tracker.events == [completed.event] + assert not tracker.in_motion_event + assert tracker.active_event_count == 1 + + +def test_sub_threshold_and_short_bursts_rejected(): + """Below-threshold scores and bursts shorter than `min_event_len` produce no events.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=4) + scores = [0.1, 0.49, 0.9, 0.8, 0.7, 0.4, 1.0, 1.0, 0.0, 0.9, 0.9, 0.9, 0.0] + samples = _cfr_samples(scores, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert recorded == [] + assert orphans == [] + assert tracker.events == [] + assert tracker.active_event_count == 0 + + +def test_zero_frames_and_eof_without_motion(): + """Calling `finish()` with no frames or only idle frames is a clean no-op.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2) + assert tracker.finish() is None + assert tracker.events == [] + + for tc, score in _cfr_samples([0.0, 0.2, 0.1], fps=10.0): + step = tracker.update(tc, score, frame=tc) + assert not step.frames_before_event + assert not step.frames_after_event + assert step.completed_event is None + assert not step.event_started + assert tracker.finish() is None + assert tracker.events == [] + + +def test_first_frame_suppressed_override(): + """Explicit `above_threshold=False` suppresses highscore on frame 0 while preserving window.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=1) + step = tracker.update(_pts(0.0), score=2.0, frame="f0", above_threshold=False) + assert step.event_started + assert step.frames_after_event == ["f0"] + assert tracker.high_score == 0 + assert tracker.high_frame is None + + completed = tracker.finish() + assert completed is not None + assert completed.high_score == 0 + assert completed.high_frame is None + + +# --- Pre-event and post-event padding & clamping ------------------------------------------ + + +def test_pre_event_padding_and_clamping_to_scan_start(): + """`time_pre_event` shifts start earlier and clamps to `scan_start_time` (zero or seeked).""" + # Unclamped pre-roll (motion at 0.5..0.7s, pre=0.3s -> start=0.2s). + tracker = _make_tracker(fps=10.0, min_event_len=2, time_pre_event=3, time_post_event=0) + samples = _cfr_samples([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.2) + assert recorded[0][0].event.end.seconds == pytest.approx(0.7) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + # Clamped at 0.0s (motion at 0.1..0.2s, pre=0.5s -> clamped to 0.0s). + tracker_zero = _make_tracker(fps=10.0, min_event_len=2, time_pre_event=5) + samples_zero = _cfr_samples([0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded_zero, _ = _drive(tracker_zero, samples_zero) + assert recorded_zero[0][0].event.start.seconds == pytest.approx(0.0) + _assert_frames_match_spans(recorded_zero, [tc for tc, _ in samples_zero]) + + # Clamped at non-zero seek start (5.0s). + tracker_seek = _make_tracker( + fps=10.0, min_event_len=2, time_pre_event=5, scan_start_time=_pts(5.0, 10.0) + ) + samples_seek = _cfr_samples([0.0, 1.0, 1.0, 0.0], fps=10.0, start_seconds=5.0) + recorded_seek, _ = _drive(tracker_seek, samples_seek) + assert recorded_seek[0][0].event.start.seconds == pytest.approx(5.0) + _assert_frames_match_spans(recorded_seek, [tc for tc, _ in samples_seek]) + + +def test_pre_event_clamps_to_previous_event_end(): + """Pre-event padding must never make an event overlap the end of the previous event.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_pre_event=5, time_post_event=0, merge_window=1 + ) + # Event 1: motion at 0.0, 0.1 -> ends at 0.2 when 0.2 is quiet (gap 0.1 >= merge_window 0.1). + # Event 2: motion at 0.3, 0.4 -> pre_event of 0.5s would want -0.2s, must clamp to 0.2s. + samples = _cfr_samples([1.0, 1.0, 0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 2 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.2) + assert recorded[1][0].event.start.seconds == pytest.approx(0.2) + assert recorded[1][0].event.end.seconds == pytest.approx(0.5) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_post_event_padding_and_eof_clamping(): + """`time_post_event` extends event end and clamps to stream end when video ends early.""" + # Enough trailing frames for full 0.3s post-event padding. + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=3) + samples = _cfr_samples([0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.1) + # Last motion at 0.2s + 0.1s frame duration + 0.3s post-event = 0.6s. + assert recorded[0][0].event.end.seconds == pytest.approx(0.6) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + # Stream ends after only 1 quiet frame (0.3s) during 0.5s post-event padding. + tracker_eof = _make_tracker(fps=10.0, min_event_len=2, time_post_event=5) + samples_eof = _cfr_samples([0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded_eof, orphans_eof = _drive(tracker_eof, samples_eof) + assert not orphans_eof + assert len(recorded_eof) == 1 + assert recorded_eof[0][0].event.start.seconds == pytest.approx(0.1) + assert recorded_eof[0][0].event.end.seconds == pytest.approx(0.4) + _assert_frames_match_spans(recorded_eof, [tc for tc, _ in samples_eof]) + + +# --- Decoupled merge_window --------------------------------------------------------------- + + +def test_merge_window_auto_matches_post_event(): + """`merge_window=None` behaves identically to `merge_window == time_post_event` (#195).""" + scores = [0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0] + samples = _cfr_samples(scores, fps=10.0) + + auto_recorded, _ = _drive( + _make_tracker(fps=10.0, min_event_len=2, time_post_event=3, merge_window=None), + samples, + ) + explicit_recorded, _ = _drive( + _make_tracker(fps=10.0, min_event_len=2, time_post_event=3, merge_window=3), + samples, + ) + assert [(c.event.start, c.event.end) for c, _ in auto_recorded] == [ + (c.event.start, c.event.end) for c, _ in explicit_recorded + ] + # The 2-frame quiet gap (0.3s, 0.4s) stays under the 0.3s merge window and merges on 0.5s; + # the 4-frame quiet gap (0.6s..0.9s) reaches 0.3s at 0.8s and splits into 2 events. + assert len(auto_recorded) == 2 + _assert_frames_match_spans(auto_recorded, [tc for tc, _ in samples]) + + +def test_merge_window_merges_and_flushes_held_frames(): + """Motion resuming past `time_post_event` in `merge_window` merges and flushes held frames.""" + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=1, merge_window=5) + # Motion at 0.0, 0.1 -> padded_end = 0.3s. + # Quiet at 0.2 (sent immediately, < 0.3), 0.3 & 0.4 (held in merge tail, >= 0.3). + # Motion resumes at 0.5 (0.5 - 0.1 = 0.4 < 0.5) -> held 0.3, 0.4 flushed in order! + # Quiet at 0.6..1.1 -> closes at 1.0 (1.0 - 0.5 = 0.5 >= 0.5), padded_end = 0.7s. + scores = [1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] + samples = _cfr_samples(scores, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + completed, frames = recorded[0] + assert completed.event.start.seconds == pytest.approx(0.0) + assert completed.event.end.seconds == pytest.approx(0.7) + assert [tc.seconds for tc in frames] == pytest.approx([0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6]) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_merge_window_splits_and_seeds_next_event_preroll(): + """When `merge_window` expires, held merge-tail frames seed the next event's pre-roll.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_pre_event=3, time_post_event=1, merge_window=4 + ) + # Event 1 motion at 0.0, 0.1 -> padded_end = 0.3s, expires at 0.5s (0.5 - 0.1 = 0.4s). + # Held merge-tail frames: 0.3, 0.4, plus closing frame 0.5 (>= 0.3) -> seed pre-roll buffer! + # Event 2 motion at 0.6, 0.7 -> with pre_event=0.3s, starts at 0.3s and includes 0.3, 0.4, 0.5! + scores = [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0] + samples = _cfr_samples(scores, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 2 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.3) + assert recorded[1][0].event.start.seconds == pytest.approx(0.3) + assert recorded[1][0].event.end.seconds == pytest.approx(0.9) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_post_event_greater_than_merge_window_capped_with_warning(caplog): + """`time_post_event > merge_window` warns and caps post-event padding to `merge_window`.""" + with caplog.at_level(logging.WARNING, logger="dvr_scan"): + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=5, merge_window=2) + assert "merge-window" in caplog.text + + samples = _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + assert not orphans + assert len(recorded) == 1 + # Last motion at 0.1s + 0.1s frame + 0.2s capped post-event = 0.4s. + assert recorded[0][0].event.end.seconds == pytest.approx(0.4) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_eof_during_merge_tail_clamps_to_post_event_padding(): + """EOF while waiting out `merge_window` past `padded_end` clamps to `padded_end`.""" + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=1, merge_window=100) + # Motion at 0.0, 0.1 -> padded_end = 0.3s; quiet frames 0.2..0.7 until EOF. + samples = _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.3) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +# --- max_event_length splitting ----------------------------------------------------------- + + +def test_max_event_length_split_with_continued_motion(): + """Continuous motion past `max_event_len` splits with no padding and immediate restart.""" + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=5, max_event_len="0.4s") + # 9 frames of continuous motion (0.0..0.8s) -> [0.0, 0.4), [0.4, 0.8), [0.8, 0.9). + samples = _cfr_samples([1.0] * 9, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 3 + spans = [(c.event.start.seconds, c.event.end.seconds) for c, _ in recorded] + assert spans == [ + pytest.approx((0.0, 0.4)), + pytest.approx((0.4, 0.8)), + pytest.approx((0.8, 0.9)), + ] + assert recorded[1][0].event.start == recorded[0][0].event.end + assert recorded[2][0].event.start == recorded[1][0].event.end + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_max_event_length_split_flushes_merge_tail_when_motion_resumes(): + """Resuming motion on the split frame flushes held merge-tail frames into the ending event.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=1, merge_window=10, max_event_len="0.5s" + ) + # Motion 0.0, 0.1 -> padded_end = 0.3s. + # Quiet 0.2 (emitted), 0.3 & 0.4 (held in merge tail). + # Motion resumes at 0.5 -> exceeds max_event_len=0.5s (0.5 + 0.1 > 0.0 + 0.5)! + # Held frames 0.3, 0.4 flush BEFORE event 1 completes as [0.0, 0.5), + # and frame 0.5 starts event 2 in frames_after_event! + samples = _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0, 1.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 2 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.5) + assert [tc.seconds for tc in recorded[0][1]] == pytest.approx([0.0, 0.1, 0.2, 0.3, 0.4]) + assert recorded[1][0].event.start.seconds == pytest.approx(0.5) + assert recorded[1][0].event.end.seconds == pytest.approx(0.6) + assert [tc.seconds for tc in recorded[1][1]] == pytest.approx([0.5]) + + +def test_max_event_length_split_without_motion_clamps_correctly(): + """A split on a quiet frame ends at `min(timecode, padded_end)` without starting a new event.""" + # Subcase A: split occurs BEFORE padded_end -> ends at timecode (0.3s < padded_end 0.7s). + tracker_early = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=5, max_event_len="0.3s" + ) + samples_early = _cfr_samples([1.0, 1.0, 0.0, 0.0], fps=10.0) + recorded_early, orphans_early = _drive(tracker_early, samples_early) + assert not orphans_early + assert len(recorded_early) == 1 + assert recorded_early[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded_early[0][0].event.end.seconds == pytest.approx(0.3) + _assert_frames_match_spans(recorded_early, [tc for tc, _ in samples_early]) + + # Subcase B: split occurs AFTER padded_end (during merge tail) -> ends at padded_end (0.3s). + tracker_late = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=1, merge_window=10, max_event_len="0.5s" + ) + samples_late = _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0, 0.0], fps=10.0) + recorded_late, orphans_late = _drive(tracker_late, samples_late) + assert not orphans_late + assert len(recorded_late) == 1 + assert recorded_late[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded_late[0][0].event.end.seconds == pytest.approx(0.3) + _assert_frames_match_spans(recorded_late, [tc for tc, _ in samples_late]) + + +def test_max_event_length_bounds_pre_roll(): + """When `time_pre_event >= max_event_len`, pre-roll is trimmed so the event fits the limit.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_pre_event="1.0s", time_post_event=0, max_event_len="0.3s" + ) + # Quiet 0.0..0.4s, motion at 0.5, 0.6s -> triggers on 0.6s (step ends at 0.7s). + # Unbounded pre-roll would start at 0.0s, but max_event_len=0.3s trims start to 0.4s. + samples = _cfr_samples([0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.4) + assert recorded[0][0].event.end.seconds == pytest.approx(0.7) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +# --- max_events early stop ---------------------------------------------------------------- + + +def test_max_events_stops_after_limit(): + """`max_events` sets `max_events_reached` on the limiting event and ignores further frames.""" + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=0, max_events=1) + # Two distinct motion bursts; only the first should be emitted. + samples = _cfr_samples([1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0], fps=10.0) + # Drive ALL samples without breaking early to verify tracker ignores post-limit frames too. + recorded, orphans = _drive(tracker, samples, stop_on_max_events=False) + + assert tracker.max_events_reached + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.2) + assert tracker.finish() is None + + +def test_max_events_stops_on_split(): + """Hitting `max_events` on a `max_event_len` split does not start or score a next event.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=1, max_event_len="0.3s", max_events=1 + ) + samples = _cfr_samples([1.0, 2.0, 1.0, 9.0, 9.0], fps=10.0) + recorded, orphans = _drive(tracker, samples, stop_on_max_events=False) + + assert tracker.max_events_reached + assert not tracker.in_motion_event + assert not orphans + assert len(recorded) == 1 + completed, frames = recorded[0] + assert completed.event.start.seconds == pytest.approx(0.0) + assert completed.event.end.seconds == pytest.approx(0.3) + assert completed.high_score == pytest.approx(2.0) + assert [tc.seconds for tc in frames] == pytest.approx([0.0, 0.1, 0.2]) + # Peak state must stay cleanly reset after stopping on a split. + assert tracker.high_score == 0 + assert tracker.high_frame is None + + +def test_eof_flush_does_not_set_max_events_reached(): + """Completing the Nth event at EOF via `finish()` must not flag early `max_events_reached`.""" + tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=0, max_events=1) + samples = _cfr_samples([1.0, 1.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + assert not tracker.max_events_reached + + +# --- VFR and frame_skip ------------------------------------------------------------------- + + +def test_vfr_merge_window_and_boundaries_use_pts(): + """Non-uniform frame intervals measure merge gaps and event spans in wall-clock PTS seconds.""" + # Average fps = 10.0, but actual frame timestamps have irregular intervals: + # Burst 1 at 0.0, 0.05, 0.10 (20 fps), quiet at 0.50 (gap 0.40s < 1.0s), + # resumes at 0.90 (gap 0.80s < 1.0s). + # Quiet at 2.10 (gap 1.20s >= 1.0s) closes event 1 at 0.90 + 0.20 + 0.10 = 1.20s. + # Burst 2 at 5.00, 5.40, 5.80 (2.5 fps), quiet at 7.00 (gap 1.20s >= 1.0s). + vfr_samples = [ + (_pts(0.00, 10.0), 1.0), + (_pts(0.05, 10.0), 1.0), + (_pts(0.10, 10.0), 1.0), + (_pts(0.50, 10.0), 0.0), + (_pts(0.90, 10.0), 1.0), + (_pts(2.10, 10.0), 0.0), + (_pts(5.00, 10.0), 1.0), + (_pts(5.40, 10.0), 1.0), + (_pts(5.80, 10.0), 1.0), + (_pts(7.00, 10.0), 0.0), + ] + tracker = _make_tracker( + fps=10.0, min_event_len=3, time_pre_event=0, time_post_event="0.2s", merge_window="1.0s" + ) + recorded, orphans = _drive(tracker, vfr_samples) + + assert not orphans + assert len(recorded) == 2 + # Event 1 merged across the 0.80s VFR gap and ended at 0.90 + 0.20 + 0.10 = 1.20s. + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(1.2) + # Event 2 reflects true VFR PTS (5.6..6.1s, not frame-count-derived timestamps). + assert recorded[1][0].event.start.seconds == pytest.approx(5.6) + assert recorded[1][0].event.end.seconds == pytest.approx(6.1) + assert [tc.seconds for tc in recorded[0][1]] == pytest.approx([0.0, 0.05, 0.1, 0.5, 0.9]) + + +def test_frame_skip_scales_window_and_frame_step(): + """`frame_skip` scales the processed-frame window and accounts for skipped frames.""" + # fps=10, frame_skip=1 -> processed frames every 0.2s (frame_step=0.2s). + # min_event_len=4 source frames -> 4 // 2 = 2 processed frames. + tracker = _make_tracker( + fps=10.0, + min_event_len=4, + time_pre_event=0, + time_post_event=2, + max_event_len="0.6s", + frame_skip=1, + ) + # Processed frames at 0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2. + # Trigger at 0.4s: start_event_shift = (0 + 2 * 2) * 0.1 = 0.4s -> start = 0.1s. + # At 0.6s: 0.6 + 0.2 > 0.1 + 0.6 -> splits! Event 1 = [0.1, 0.6), Event 2 starts at 0.6. + # At 1.0s: quiet (1.0 - 0.8 >= 0.2), padded_end = 0.8 + 0.2 + 0.2 = 1.2s. + # Frame 1.0 < 1.2 -> included in Event 2 before closing! + samples = _cfr_samples([0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0], fps=10.0, frame_skip=1) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 2 + assert recorded[0][0].event.start.seconds == pytest.approx(0.1) + assert recorded[0][0].event.end.seconds == pytest.approx(0.6) + assert recorded[1][0].event.start.seconds == pytest.approx(0.6) + assert recorded[1][0].event.end.seconds == pytest.approx(1.2) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +# --- Per-event highscore tracking & reset ------------------------------------------------- + + +def test_highscore_tracks_peak_and_resets_between_events(): + """Each event captures its own peak score and a copy of its peak frame, resetting afterwards.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2, time_post_event=0) + f0 = np.full((2, 2, 3), 10, dtype=np.uint8) + f1 = np.full((2, 2, 3), 20, dtype=np.uint8) + f2 = np.full((2, 2, 3), 30, dtype=np.uint8) + f3 = np.full((2, 2, 3), 40, dtype=np.uint8) + f4 = np.full((2, 2, 3), 50, dtype=np.uint8) + + # Event 1 peaks at score 5.0 (f1); Event 2 peaks at score 2.0 (f3) (lower than Event 1!). + inputs = [ + (_pts(0.0), 1.0, f0), + (_pts(0.1), 5.0, f1), + (_pts(0.2), 0.0, f2), # closes Event 1 + (_pts(0.3), 2.0, f3), + (_pts(0.4), 1.5, f4), + (_pts(0.5), 0.0, f2), # closes Event 2 + ] + completed_events: ty.List[CompletedEvent] = [] + for tc, score, arr in inputs: + step = tracker.update(tc, score, frame=arr) + if step.completed_event is not None: + completed_events.append(step.completed_event) + + # Mutate original arrays after processing to confirm tracker copied them. + f1[:] = 0 + f3[:] = 0 + + assert len(completed_events) == 2 + assert completed_events[0].high_score == pytest.approx(5.0) + assert np.all(completed_events[0].high_frame == 20) + assert completed_events[1].high_score == pytest.approx(2.0) + assert np.all(completed_events[1].high_frame == 40) + assert tracker.high_score == 0 + assert tracker.high_frame is None + + +def test_highscore_discarded_for_rejected_burst(): + """A high-scoring burst shorter than `min_event_len` must not pollute the next event (#268).""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=3, time_post_event=0) + # 2-frame spike with score 99.0 is rejected when frame 2 drops below threshold. + samples = [ + (_pts(0.0), 99.0, "spike0"), + (_pts(0.1), 50.0, "spike1"), + (_pts(0.2), 0.0, "quiet"), + (_pts(0.3), 1.0, "ev0"), + (_pts(0.4), 2.5, "ev1"), + (_pts(0.5), 1.2, "ev2"), + (_pts(0.6), 0.0, "end"), + ] + completed: ty.List[CompletedEvent] = [] + for tc, score, label in samples: + step = tracker.update(tc, score, frame=label) + if step.completed_event is not None: + completed.append(step.completed_event) + + assert len(completed) == 1 + assert completed[0].high_score == pytest.approx(2.5) + assert completed[0].high_frame == "ev1" + assert tracker.high_score == 0 + assert tracker.high_frame is None + + +def test_highscore_split_attributes_split_frame_to_next_event(): + """On a `max_event_len` split, the split frame's score counts toward the new event.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2, max_event_len="0.3s") + inputs = [ + (_pts(0.0), 1.0, "f0"), + (_pts(0.1), 3.0, "f1"), + (_pts(0.2), 2.0, "f2"), + # Split happens at 0.3s with huge score 99.0 -> must belong to Event 2, not Event 1! + (_pts(0.3), 99.0, "f3"), + (_pts(0.4), 1.0, "f4"), + ] + completed: ty.List[CompletedEvent] = [] + for tc, score, label in inputs: + step = tracker.update(tc, score, frame=label) + if step.completed_event is not None: + completed.append(step.completed_event) + final = tracker.finish() + assert final is not None + completed.append(final) + + assert len(completed) == 2 + assert completed[0].high_score == pytest.approx(3.0) + assert completed[0].high_frame == "f1" + assert completed[1].high_score == pytest.approx(99.0) + assert completed[1].high_frame == "f3" + + +def test_scan_only_mode_tracks_high_frame_without_buffering_payload(): + """Passing `frame=None` with `high_frame=...` emits no buffered frames but tracks peak frame.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2, time_post_event=0) + steps = [ + tracker.update(_pts(0.0), 1.0, frame=None, high_frame="img0"), + tracker.update(_pts(0.1), 4.0, frame=None, high_frame="img1"), + tracker.update(_pts(0.2), 0.0, frame=None, high_frame="img2"), + ] + assert all(not s.frames_before_event and not s.frames_after_event for s in steps) + completed = steps[2].completed_event + assert completed is not None + assert completed.high_score == pytest.approx(4.0) + assert completed.high_frame == "img1" + + +# --- EOF flush ---------------------------------------------------------------------------- + + +def test_eof_flush_while_active_in_motion(): + """EOF while actively detecting motion flushes the event ending at `last_frame + frame_step`.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2, time_post_event=5) + samples = _cfr_samples([0.0, 1.0, 2.0, 1.5], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + completed, frames = recorded[0] + assert completed.event.start.seconds == pytest.approx(0.1) + assert completed.event.end.seconds == pytest.approx(0.4) + assert completed.high_score == pytest.approx(2.0) + assert [tc.seconds for tc in frames] == pytest.approx([0.1, 0.2, 0.3]) + assert not tracker.in_motion_event + assert tracker.high_score == 0 + assert tracker.high_frame is None + + +# --- Buffer release, boundaries, and state invariants ------------------------------------- + + +def test_buffers_released_on_finish_max_events_and_clear_buffers(): + """Frame buffers must be released on finish(), max_events stop, and clear_buffers().""" + # Idle finish() clears pre-event buffered frames. + idle_tracker = _make_tracker(fps=10.0, min_event_len=3, time_pre_event=3) + for tc, score in _cfr_samples([0.0, 0.0, 0.0], fps=10.0): + idle_tracker.update(tc, score, frame=tc) + assert idle_tracker._buffered_frames + assert idle_tracker.finish() is None + assert idle_tracker._buffered_frames == [] + assert idle_tracker._post_motion_frames == [] + + # Active finish() during merge tail clears held post-motion frames. + active_tracker = _make_tracker(fps=10.0, min_event_len=2, time_post_event=1, merge_window=10) + for tc, score in _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0], fps=10.0): + active_tracker.update(tc, score, frame=tc) + assert active_tracker._post_motion_frames + assert active_tracker.finish() is not None + assert active_tracker._buffered_frames == [] + assert active_tracker._post_motion_frames == [] + + # max_events stop via merge-window close releases held frames rather than seeding pre-roll. + close_tracker = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=1, merge_window=3, max_events=1 + ) + for tc, score in _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0], fps=10.0): + close_tracker.update(tc, score, frame=tc) + assert close_tracker.max_events_reached + assert close_tracker._buffered_frames == [] + assert close_tracker._post_motion_frames == [] + + # max_events stop via quiet max_event_len split releases held frames too. + split_tracker = _make_tracker( + fps=10.0, + min_event_len=2, + time_post_event=1, + merge_window=10, + max_event_len="0.5s", + max_events=1, + ) + for tc, score in _cfr_samples([1.0, 1.0, 0.0, 0.0, 0.0, 0.0], fps=10.0): + split_tracker.update(tc, score, frame=tc) + assert split_tracker.max_events_reached + assert split_tracker._buffered_frames == [] + assert split_tracker._post_motion_frames == [] + + # clear_buffers() drops buffered frames while preserving high_score / high_frame. + cancel_tracker = _make_tracker(fps=10.0, min_event_len=3, time_pre_event=2) + cancel_tracker.update(_pts(0.0), 0.0, frame="f0") + cancel_tracker.update(_pts(0.1), 4.5, frame="f1") + assert cancel_tracker._buffered_frames + cancel_tracker.clear_buffers() + assert cancel_tracker._buffered_frames == [] + assert cancel_tracker._post_motion_frames == [] + assert cancel_tracker.high_score == pytest.approx(4.5) + assert cancel_tracker.high_frame == "f1" + + +def test_exact_threshold_boundary(): + """`score == threshold` triggers motion while strictly lower scores do not.""" + tracker = _make_tracker(fps=10.0, threshold=0.5, min_event_len=2, time_post_event=0) + samples = _cfr_samples([0.499999, 0.5, 0.5, 0.499999], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.1) + assert recorded[0][0].event.end.seconds == pytest.approx(0.3) + assert recorded[0][0].high_score == pytest.approx(0.5) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_default_scan_start_time_is_zero(): + """Omitting `scan_start_time` defaults to `FrameTimecode(0, frame_rate)`.""" + tracker = MotionEventTracker( + threshold=0.5, + min_event_len=FrameTimecode(2, 10.0), + time_pre_event=FrameTimecode(5, 10.0), + time_post_event=FrameTimecode(0, 10.0), + frame_rate=10.0, + ) + samples = _cfr_samples([0.0, 1.0, 1.0, 0.0], fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 1 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.3) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_quiet_max_event_length_split_during_merge_tail_seeds_next_preroll(): + """Held merge-tail frames after a quiet `max_event_len` split seed the next event's pre-roll.""" + tracker = _make_tracker( + fps=10.0, + min_event_len=2, + time_pre_event=3, + time_post_event=1, + merge_window=10, + max_event_len="0.5s", + ) + # Event 1 motion at 0.0, 0.1 -> padded_end = 0.3s. + # Quiet 0.2 (emitted), 0.3 & 0.4 (held in merge tail). + # Quiet 0.5 hits max_event_len (0.5 + 0.1 > 0.5) -> Event 1 ends at 0.3s, held frames + # 0.3, 0.4 seed _buffered_frames and 0.5 is appended to _buffered_frames. + # Motion at 0.6, 0.7 -> Event 2 starts at 0.3s with pre-roll frames 0.3, 0.4, 0.5, and + # quiet 0.8 hits max_event_len (0.3 + 0.5 = 0.8s) so Event 2 ends at 0.8s. + scores = [1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0] + samples = _cfr_samples(scores, fps=10.0) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 2 + assert recorded[0][0].event.start.seconds == pytest.approx(0.0) + assert recorded[0][0].event.end.seconds == pytest.approx(0.3) + assert recorded[1][0].event.start.seconds == pytest.approx(0.3) + assert recorded[1][0].event.end.seconds == pytest.approx(0.8) + assert [tc.seconds for tc in recorded[1][1]] == pytest.approx([0.3, 0.4, 0.5, 0.6, 0.7]) + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_max_event_length_floored_to_frame_step(): + """`max_event_len < frame_step` floors to `frame_step` so events cover at least one step.""" + # fps=10, frame_skip=1 -> frame_step = 0.2s, while requested max_event_len = 0.05s. + tracker = _make_tracker( + fps=10.0, + min_event_len=1, + time_pre_event=0, + time_post_event=0, + max_event_len="0.05s", + frame_skip=1, + ) + samples = _cfr_samples([1.0, 1.0, 1.0], fps=10.0, frame_skip=1) + recorded, orphans = _drive(tracker, samples) + + assert not orphans + assert len(recorded) == 3 + for completed, frames in recorded: + assert completed.event.end.seconds - completed.event.start.seconds == pytest.approx(0.2) + assert len(frames) == 1 + _assert_frames_match_spans(recorded, [tc for tc, _ in samples]) + + +def test_end_before_start_clamped_in_finish_event(): + """Non-monotonic timestamps yielding `end < start` clamp event end to start.""" + tracker = _make_tracker(fps=10.0, min_event_len=1, time_pre_event=0, time_post_event=0) + # Start event at 1.0s, then supply an out-of-order earlier frame at 0.5s before EOF. + tracker.update(_pts(1.0), 1.0, frame="f0") + tracker.update(_pts(0.5), 1.0, frame="f1") + completed = tracker.finish() + + assert completed is not None + assert completed.event.start.seconds == pytest.approx(1.0) + assert completed.event.end == completed.event.start + + +def test_active_event_count_while_in_progress(): + """`active_event_count` reflects completed events plus any active or split event.""" + tracker = _make_tracker( + fps=10.0, min_event_len=2, time_post_event=1, merge_window=2, max_event_len="0.4s" + ) + assert tracker.active_event_count == 0 + tracker.update(_pts(0.0), 1.0) + assert tracker.active_event_count == 0 + tracker.update(_pts(0.1), 1.0) # Event 1 starts + assert tracker.in_motion_event + assert tracker.active_event_count == 1 + tracker.update(_pts(0.2), 1.0) + tracker.update(_pts(0.3), 1.0) + tracker.update(_pts(0.4), 1.0) # Splits: Event 1 ends, Event 2 starts immediately + assert tracker.in_motion_event + assert len(tracker.events) == 1 + assert tracker.active_event_count == 2 + tracker.update(_pts(0.5), 0.0) # In Event 2 merge window + assert tracker.active_event_count == 2 + tracker.update(_pts(0.6), 0.0) + tracker.update(_pts(0.7), 0.0) # Event 2 closes + assert not tracker.in_motion_event + assert tracker.active_event_count == 2 + + +def test_events_property_returns_copy(): + """Mutating the list returned by `tracker.events` must not mutate internal tracker state.""" + tracker = _make_tracker(fps=10.0, min_event_len=1, time_post_event=0) + tracker.update(_pts(0.0), 1.0) + tracker.update(_pts(0.1), 0.0) + + snapshot = tracker.events + assert len(snapshot) == 1 + snapshot.clear() + assert len(tracker.events) == 1 + assert tracker.active_event_count == 1