Search code examples
curlffmpegmjpeg

Stream MJPEG to file, but keep only last x minutes


I'm looking to record a MJPEG stream on motion detected. But my motion detection notification is seconds later than the motion occurs.

To counter this, I want to record all the time, but only keep the last 2 minutes of footage.

Right now I'm downloading infinitely with cURL, but I'm stuck on how to have it trim the front of the file correctly to be 2 minutes.


Solution

  • Look at segment muxer from FFmpeg.

    With segment muxer it's possible to capture stream and write it to a number of separated files.

    The option you may be interested in is segment_wrap.

    From the documentation:

    segment_wrap limit
    
    Wrap around segment index once it reaches limit.
    

    So you can use ffmpeg in this way:

    ffmpeg -i URL -c copy -f segment -segment_time 120 -segment_wrap 2 out_file
    

    to write cyclically two files.

    The duration of each file is equal to the two minutes and in every moment of time you have at least last two minutes of video.

    Of course I understand that this solution is terrible but it's the only way to solve your problem with ffmpeg that I can offer.