Pre-Event Recording in C#: Save the 10 Seconds Before a Motion Alarm from an IP Camera
A motion alarm fires at 14:30:07 and the recorder starts writing at 14:30:07. The clip shows what happened after the trigger; the part you actually needed, the person walking into the frame, was over before the file was
A motion alarm fires at 14:30:07 and the recorder starts writing at 14:30:07. The clip shows what happened after the trigger; the part you actually needed, the person walking into the frame, was over before the file was opened.
There are three ways to record an event from a camera:
| Approach | What the clip contains | Cost |
|---|---|---|
| Start recording at the trigger | Only what happens after the trigger | Cheap, but always late |
| Record 24/7, cut clips later | Everything | Constant disk writes, storage to rotate, a cutting step |
| Pre-event buffer | The last N seconds before the trigger, then live | A few MB of RAM per camera, disk writes only for events |
Security DVRs and NVRs use the third one. This post builds it in C#: the application keeps the last N seconds of encoded video and audio from an IP camera in memory, and when motion (or an alarm input, or an API call) fires, it writes those seconds to the file first and keeps recording live until the scene has been quiet for a few seconds.
What we build
A WPF window that:
- shows the camera live (RTSP IP camera or a local webcam);
- runs motion detection on every frame, without OpenCV;
- keeps the last 10 seconds of H.264 and AAC in a ring buffer;
- on motion, saves
motion_<time>.mp4that starts 10 seconds before the motion and ends 5 seconds after the last motion; - also records on a button press, and can stop or extend a clip by hand.
Everything below is taken from the Pre-Event Recording WPF demo, so you can open the finished project next to this post.
Packages
<PackageReference Include="VisioForge.DotNet.MediaBlocks" Version="2026.11.23" />
<!-- Windows x64 native runtime -->
<PackageReference Include="VisioForge.CrossPlatform.Core.Windows.x64" Version="2026.11.16" />
<PackageReference Include="VisioForge.CrossPlatform.Libav.Windows.x64.UPX" Version="2026.11.16" />
The same pipeline runs on macOS, Linux, Android and iOS with that platform's runtime package; only the UI around it changes.
How the buffer behaves
The core is PreEventRecordingBlock. It is a sink: it sits at the end of the encoding branch and accepts encoded video and, optionally, encoded audio. Its State moves through these values:
Idle --pipeline starts--> Buffering --TriggerRecording--> Recording --> PostEventRecording --timer ends--> Buffering
^ |
+--------------------- StopRecording ---------------+
StopBuffering --> Stopped (buffer cleared) --StartBuffering--> Buffering
Buffering. Encoded frames go into a ring buffer in managed memory. Frames older than PreEventDuration are evicted; if you set MaxBufferBytes, frames are also evicted when the buffer grows past that size. Nothing touches the disk.
Recording. TriggerRecording(filename) takes the buffer from its earliest video keyframe, so the file starts on a frame a player can decode. It builds an output branch (muxer and file sink) on the fly, writes the buffered frames into it, and keeps appending the live frames.
Post-event. When PostEventDuration runs out, the file is finalized and the block goes back to buffering. ExtendRecording() resets that timer while the trigger is still active, and a second TriggerRecording during a recording does the same: it extends the current file instead of opening a new one.
Step 1: initialize the SDK
Once per process, before the first pipeline, and released when the window closes:
public MainWindow()
{
InitializeComponent();
VisioForgeX.InitSDK();
}
private void Window_Closing(object sender, CancelEventArgs e)
{
VisioForgeX.DestroySDK(); // after the pipeline is stopped, see step 6
}
Step 2: build the pipeline
The video goes from the camera through the motion detector into a tee. One branch of the tee is the preview, the other is encoded to H.264 and fed into the pre-event block. The audio does the same through an AAC encoder. The preview is raw video, so watching costs no encoding; only the recording branch is encoded, once, whether or not anything is ever saved.
using VisioForge.Core;
using VisioForge.Core.MediaBlocks;
using VisioForge.Core.MediaBlocks.AudioEncoders;
using VisioForge.Core.MediaBlocks.AudioRendering;
using VisioForge.Core.MediaBlocks.Sinks;
using VisioForge.Core.MediaBlocks.Sources;
using VisioForge.Core.MediaBlocks.Special;
using VisioForge.Core.MediaBlocks.VideoEncoders;
using VisioForge.Core.MediaBlocks.VideoProcessing;
using VisioForge.Core.MediaBlocks.VideoRendering;
using VisioForge.Core.Types;
using VisioForge.Core.Types.Events;
using VisioForge.Core.Types.X.PreEventRecording;
using VisioForge.Core.Types.X.Sources;
using VisioForge.Core.Types.X.VideoEffects;
private MediaBlocksPipeline _pipeline;
private MotionDetectionBlock _motionDetector;
private MotionDetectionBlockSettings _motionSettings;
private PreEventRecordingBlock _preEventBlock;
private string _outputFolder;
private async Task StartAsync()
{
_outputFolder = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyVideos), "PreEventRecording");
Directory.CreateDirectory(_outputFolder);
_pipeline = new MediaBlocksPipeline();
_pipeline.OnError += (s, e) => Log($"[Error] {e.Message}");
// 1. The IP camera, with its audio
var rtspSettings = await RTSPSourceSettings.CreateAsync(
new Uri("rtsp://camera-ip:554/stream1"), "user", "password", audioEnabled: true);
var rtspSource = new RTSPSourceBlock(rtspSettings);
// 2. Motion detection by frame differencing, no OpenCV
_motionSettings = new MotionDetectionBlockSettings
{
MotionThreshold = 5,
CompareGreyscale = true,
GridWidth = 8,
GridHeight = 8
};
_motionDetector = new MotionDetectionBlock(_motionSettings);
_motionDetector.OnMotionDetected += OnMotionDetected;
// 3. Preview and the recording branch
var videoTee = new TeeBlock(2, MediaBlockPadMediaType.Video);
var videoRenderer = new VideoRendererBlock(_pipeline, VideoView1);
var h264Encoder = new H264EncoderBlock(); // a hardware encoder when the machine has one
// 4. The pre-event buffer: 10 s before the trigger, 5 s after the last one
_preEventBlock = new PreEventRecordingBlock(new PreEventRecordingSettings
{
PreEventDuration = TimeSpan.FromSeconds(10),
PostEventDuration = TimeSpan.FromSeconds(5)
}, "mp4mux");
_preEventBlock.OnRecordingStarted += (s, e) => Log($"Recording started: {e.Filename}");
_preEventBlock.OnRecordingStopped += (s, e) => Log($"Saved: {e.Filename}");
_preEventBlock.OnStateChanged += (s, e) => Log($"State: {e.State}");
// Video: camera -> motion -> tee -> [preview, H.264 -> pre-event]
_pipeline.Connect(rtspSource, _motionDetector);
_pipeline.Connect(_motionDetector, videoTee);
_pipeline.Connect(videoTee, videoRenderer);
_pipeline.Connect(videoTee, h264Encoder);
_pipeline.Connect(h264Encoder.Output, _preEventBlock.VideoInput);
// Audio: camera audio -> tee -> [speakers, AAC -> pre-event]
var audioTee = new TeeBlock(2, MediaBlockPadMediaType.Audio);
var aacEncoder = new AACEncoderBlock();
_pipeline.Connect(rtspSource.AudioOutput, audioTee.Input);
_pipeline.Connect(audioTee, new AudioRendererBlock());
_pipeline.Connect(audioTee, aacEncoder);
_pipeline.Connect(aacEncoder.Output, _preEventBlock.AudioInput);
await _pipeline.StartAsync(); // buffering starts with the first encoded frames
}
A local webcam instead of an IP camera. Replace the source with SystemVideoSourceBlock and take the audio from a SystemAudioSourceBlock; the rest of the pipeline stays the same:
var device = (await DeviceEnumerator.Shared.VideoSourcesAsync()).First();
var videoSource = new SystemVideoSourceBlock(new VideoCaptureDeviceSourceSettings(device));
var mic = (await DeviceEnumerator.Shared.AudioSourcesAsync()).First();
var audioSource = new SystemAudioSourceBlock(mic.CreateSourceSettings(null));
_pipeline.Connect(audioSource, audioTee);
No audio at all. Set _preEventBlock.AudioEnabled = false before the pipeline starts and connect only the video input. With audio enabled and nothing connected to AudioInput, every trigger is refused: the block waits for a first audio sample that never comes.
Step 3: trigger, extend, stop
The motion detector raises OnMotionDetected with a Level for every analysed frame. Motion while buffering starts a clip; motion during a clip pushes its end out, so one person crossing the yard gives one file, not five:
private void OnMotionDetected(object sender, MotionDetectionEventArgs e)
{
if (_preEventBlock == null || e.Level < _motionSettings.MotionThreshold)
{
return;
}
switch (_preEventBlock.State)
{
case PreEventRecordingState.Buffering:
_preEventBlock.TriggerRecording(
Path.Combine(_outputFolder, $"motion_{DateTime.Now:yyyyMMdd_HHmmss}.mp4"));
break;
case PreEventRecordingState.Recording:
case PreEventRecordingState.PostEventRecording:
_preEventBlock.ExtendRecording();
break;
}
}
Any other event source calls the same method: an alarm input on the camera, a door sensor, a REST endpoint, a button.
// Save now, with the 10 seconds before
_preEventBlock.TriggerRecording(Path.Combine(_outputFolder, $"event_{DateTime.Now:yyyyMMdd_HHmmss}.mp4"));
// Keep the current clip open for another PostEventDuration
_preEventBlock.ExtendRecording();
// Close the current clip now and go back to buffering
_preEventBlock.StopRecording();
Two behaviours to know:
-
Right after start, a trigger is refused.
TriggerRecordingdoes nothing until the first encoded video sample has arrived and, with audio enabled, the first audio sample too. There is nothing to write yet. - Right after start, the pre-event part is short. The buffer fills in real time: a trigger 3 seconds after start can only give 3 seconds of history.
Step 4: events come on worker threads
OnRecordingStarted, OnRecordingStopped and OnStateChanged are raised one at a time, in the order the changes happened, but not on the UI thread, and a handler can run after the pipeline has stopped. Marshal before touching controls:
_preEventBlock.OnRecordingStarted += (s, e) =>
Dispatcher.Invoke(() => lbRecFile.Text = $"File: {e.Filename}");
OnRecordingStopped is the moment the file is complete: the place to upload it, index it or send a notification.
Step 5: watch the buffer
BufferTotalBytes and BufferedDuration tell you, while the pipeline runs, that the buffer is filling and evicting as configured. The demo polls them twice a second:
_statusTimer = new System.Timers.Timer(500);
_statusTimer.Elapsed += (s, e) =>
{
var state = _preEventBlock.State;
var kb = _preEventBlock.BufferTotalBytes / 1024.0;
var seconds = _preEventBlock.BufferedDuration.TotalSeconds;
Dispatcher.Invoke(() => lbBufferStats.Text = $"{state}: {kb:F1} KB, {seconds:F1} s");
};
_statusTimer.Start();
BufferedDuration that stays near zero means no encoded frames are reaching the block: check the encoder branch and, with audio enabled, the audio branch.
Step 6: stop cleanly
An MP4 file is playable only once its muxer has finalized it. Await the pipeline stop before disposing it, so a clip that is being recorded is closed properly:
private async Task StopAsync()
{
_statusTimer?.Stop();
_statusTimer?.Dispose();
await _pipeline.StopAsync();
_pipeline.Dispose();
_pipeline = null;
_motionDetector.OnMotionDetected -= OnMotionDetected;
_preEventBlock = null;
}
To pause buffering without tearing the pipeline down (a privacy mode, a schedule), call StopBuffering(): it clears the buffer and leaves the block in Stopped, across pipeline restarts, until StartBuffering().
How much memory
The buffer holds encoded data, so its size is the bitrate times the duration. Per camera, with 128 kbps AAC:
| Video bitrate | 10 s | 30 s | 60 s |
|---|---|---|---|
| 2 Mbps (720p) | 2.7 MB | 8 MB | 16 MB |
| 4 Mbps (1080p) | 5.2 MB | 15.5 MB | 31 MB |
| 8 Mbps (1080p, high quality / 4K low) | 10.2 MB | 30.5 MB | 61 MB |
Sixteen 1080p cameras with 30 seconds each is about 250 MB. In a multi-camera system set MaxBufferBytes as a hard ceiling per camera, so a camera that suddenly raises its bitrate cannot take the process down:
var settings = new PreEventRecordingSettings
{
PreEventDuration = TimeSpan.FromSeconds(30),
PostEventDuration = TimeSpan.FromSeconds(10),
MaxBufferBytes = 50 * 1024 * 1024 // 50 MB, oldest frames go first
};
The keyframe interval matters too. The clip starts on the earliest keyframe in the buffer, so the real pre-event part can be up to one GOP shorter than PreEventDuration: with a keyframe every 2 seconds, within 2 seconds of it.
MP4, MPEG-TS or MKV
The second constructor argument chooses the container:
| Muxer | File | When |
|---|---|---|
"mp4mux" (default) |
.mp4 |
Plays everywhere: browsers, phones, players |
"mpegtsmux" |
.ts |
Unattended recorders: a clip cut short by a crash or power loss stays playable |
"matroskamux" |
.mkv |
Editing and archiving tools that prefer Matroska |
var preEventBlock = new PreEventRecordingBlock(settings, "mpegtsmux");
preEventBlock.TriggerRecording(@"D:\events\event_001.ts");
When a clip looks wrong
| Symptom | Cause |
|---|---|
| No file after a trigger right after start | No encoded sample had arrived yet; the trigger was refused |
The clip has less history than PreEventDuration
|
The buffer had not filled yet, or the clip started on an earlier keyframe boundary |
| One long file instead of several | Each trigger during a recording extends it; call StopRecording() first for a new file |
| A clip from a crashed run does not play | MP4 was never finalized; use MPEG-TS for unattended systems |
| Every trigger is ignored, no microphone connected |
AudioEnabled is still true with no audio connected |
| Memory grows with many cameras | Long PreEventDuration at high bitrate; set MaxBufferBytes
|
Wrapping up
Pre-event recording is a buffer of encoded frames, a keyframe-aware flush and a timer. With PreEventRecordingBlock it is a few lines on top of a normal capture pipeline, and the motion detector, preview and recording share one camera connection.
- Runnable project: PreEventRecording demo on GitHub (RTSP camera or webcam, motion trigger, manual trigger, extend, buffer status)
- Reference and the latest version of this guide: Pre-event recording for IP cameras in C#
Written and checked against VisioForge.DotNet.MediaBlocks 2026.11.23.
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ full credit and traffic to the original publisher.
