Skip to content

ONVIF Motion Recording: Pre-Detection Buffer Not Functional #371

@origin2000

Description

@origin2000

Problem
When ONVIF motion recording triggers, recordings have a long and uncontrollable pre-roll ( more than 2 minutes) because start_mp4_recording_with_trigger() opens a fresh RTSP connection to go2rtc, which delivers from the start of its own internal segment buffer regardless of the configured pre_detection_buffer value.

Current State (from source audit)
The architecture for a proper fix already exists but is incomplete:

  • packet_buffer_t and feed_packet_to_event_buffer() are implemented and correct
  • motion_recording_context_t already holds a packet_buffer_t *buffer and the full state machine (BUFFERING → RECORDING → FINALIZING)
  • However, flush_packet_callback() in onvif_motion_recording.c is a stub that only logs — no packets are actually written
  • feed_packet_to_event_buffer() has no callers outside its own file — the buffer is allocated but never filled
  • The flush happens before the mp4_writer exists, so even a real callback would have nothing to write to

The working reference is unified_detection_thread.c, which runs a persistent RTSP reader per stream, fills packet_buffer continuously, and flushes directly into an mp4_writer on detection — no new go2rtc connection needed.

Proposed Fix
Port the unified_detection_thread approach to the ONVIF recording path:

  1. Add a persistent feeder thread per ONVIF stream (permanent RTSP connection to go2rtc)
  2. Feed every packet into the existing packet_buffer via feed_packet_to_event_buffer()
  3. Implement the real flush_packet_callback (using mp4_writer_initialize + mp4_writer_write_packet, same pattern as UDT)
  4. On motion event: create mp4_writer first, flush buffer, then continue writing live packets directly — no new RTSP connection

This completes Phase 2 of ONVIF_MOTION_RECORDING.md (Buffer Management).

Question
Are you OK with me submitting a PR for this? Happy to align on anything before I start.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions