Our 20-Second Recording Said It Was 9 Hours Long: Timestamps and Lifetimes in a Windows.Graphics.Capture to MP4 Pipeline

The first time our Windows screen recorder produced a file that opened, the file said it was 32,059 seconds long. The recording had lasted twenty seconds. The video played for a moment, then the scrubber stretched out across nearly nine hours of nothing, and the audio was nowhere near the picture.
That number turned out to be the machine’s uptime. This post is about the Windows half of HappyRec, our free screen recorder, and the four timing and lifetime rules that turned Windows.Graphics.Capture plus MediaTranscoder into reliable MP4 files. If you are writing any capture-to-file pipeline on Windows in C#, every one of these will bite you sooner or later.
The pipeline
HappyRec for Windows is a native C# / WinUI 3 app, not Electron. That choice came from the voice changer: it is real-time audio processing, built from the same DSP sources as the Mac app and compiled into a small native DLL that C# calls directly. Keeping capture, audio and encoding in one native process means the frames and samples never cross a browser boundary, and the timing problems below are ours to solve rather than hidden inside a runtime we cannot change. The macOS version uses ScreenCaptureKit and AVAssetWriter. On Windows the equivalents are:
- Windows.Graphics.Capture for the screen, with the system
GraphicsCapturePickerchoosing a display or a window. The OS handles consent; there is no permission dialog to manage beyond handling a cancelled picker (PickSingleItemAsyncreturnsnull). - WASAPI (through NAudio) for the microphone, and WASAPI loopback for system audio.
- MediaStreamSource feeding MediaTranscoder, which encodes H.264 video and AAC audio into an MP4.
// HappyRec for Windows: one recording, start to file.
//
// GraphicsCapturePicker ─► GraphicsCaptureItem (display or window)
// │
// Direct3D11CaptureFramePool ─► FrameArrived ─► frame queue (max 4)
// │ │
// (optional) FrameCompositor: bubble, watermark, badge ─┤
// ▼
// WASAPI mic ─► voice changer ─► auto gain ─► audio queue ─► MediaStreamSource
// WASAPI loopback (system audio) ──mixed in──┘ │
// ▼
// MediaTranscoder ─► MP4 (H.264 + AAC)
MediaStreamSource is a pull model. The transcoder raises SampleRequested separately for the video stream and the audio stream, and you hand back one MediaStreamSample each time, with a timestamp. Everything below is about getting those timestamps and those sample lifetimes right.
Rule 1: SystemRelativeTime is measured from boot
Each Direct3D11CaptureFrame carries a SystemRelativeTime. It looks like exactly what you want: a precise timestamp for the frame. So the first version passed it straight into MediaStreamSample.CreateFromDirect3D11Surface.
The trouble is the origin. SystemRelativeTime counts from when the machine booted, not from when your recording started. On a PC that had been up for nearly nine hours, the first video frame was stamped at about 32,000 seconds. The audio, timed from its own sample count, started at zero. The muxer did what it was told: it laid the video out hours into the timeline, reported the file’s duration as the machine’s uptime, and put the audio at the beginning, nowhere near the picture.
The fix is to rebase on the first frame you actually receive:
private void OnFrameArrived(Direct3D11CaptureFramePool sender, object args)
{
var frame = sender.TryGetNextFrame();
if (frame is null) return;
lock (_lock)
{
// SystemRelativeTime is measured from boot, not from the start of
// the recording. Rebase on the first frame, otherwise every sample
// is stamped hours into the timeline and the muxed file reports a
// duration equal to the machine's uptime.
_videoBase ??= frame.SystemRelativeTime;
// Keep the queue shallow; encoding backpressure drops stale frames.
while (_frames.Count > 4) _frames.Dequeue().Dispose();
_frames.Enqueue(frame);
}
Signal(_videoSignal);
}
Then every video sample’s timestamp is frame.SystemRelativeTime - baseTime, which starts at zero like the audio does. Note the ??=: the base is set once per recording and reset to null when a new recording starts. A recorder that reuses its object and forgets that reset produces a second file that starts with a long frozen gap.
This bug is easy to miss in testing because it depends on uptime. A developer who reboots often sees a slightly odd offset. A user whose laptop has been sleeping and resuming for a week sees a file that claims to be days long.
Rule 2: A frame lives until the encoder says it is done
The capture frame pool is small, and frames are D3D11 textures owned by that pool. The natural instinct is to tidy up: create the sample from the frame’s surface, then Dispose() the frame straight away.
That returns the texture to the pool while the encoder is still reading it. The encoder reads the surface asynchronously, after your SampleRequested handler has returned. If the pool has already handed that texture to the capture system for the next frame, the encoder reads a texture that is being overwritten. You get torn or wrong frames, intermittently, depending on timing.
The rule: release the frame from MediaStreamSample.Processed, which fires when the encoder has finished with the sample.
var timestamp = frame.SystemRelativeTime - baseTime;
MediaStreamSample sample;
if (_compositor is not null)
{
// Burn the overlays in, then hand the composited target to the
// encoder and release the capture frame immediately.
var target = _compositor.Compose(frame.Surface, _item!.Size.Width, _item.Size.Height);
frame.Dispose();
var compositor = _compositor;
sample = MediaStreamSample.CreateFromDirect3D11Surface(target, timestamp);
sample.Processed += (_, _) => compositor.Recycle(target);
}
else
{
sample = MediaStreamSample.CreateFromDirect3D11Surface(frame.Surface, timestamp);
// The encoder reads the surface asynchronously, so the frame must stay
// alive until the sample is consumed - disposing it here returns the
// texture to the pool mid-encode.
sample.Processed += (_, _) => frame.Dispose();
}
args.Request.Sample = sample;
The same rule applies one level up. When a camera bubble, watermark or badge is enabled, the frame is drawn into a render target from a small pool kept by FrameCompositor. Now it is the composited target the encoder reads, so that target goes back to the compositor’s pool on Processed, and the original capture frame can be released immediately because nothing reads it any more.
The queue between FrameArrived and the encoder is capped at four frames. When encoding falls behind, the oldest frames are disposed and dropped. A dropped frame shows up as a tiny stutter. An unbounded queue shows up as memory climbing until something fails, usually far from the real cause.

Rule 3: Audio time comes from the sample count
Video timestamps come from the capture system. Audio timestamps should not come from a clock at all. The microphone delivers a known number of samples per second (48,000 here). If you count them, you know exactly where in the timeline each chunk belongs, with no drift from timers or thread scheduling:
private void OnMicFrames(ReadOnlyMemory<float> frames)
{
var span = frames.Span;
int offset = 0;
// The first LatencySamples of voice-changer output are the DSP's priming
// delay; dropping them lines the processed voice up with the video.
if (_audioSkipRemaining > 0)
{
int skip = Math.Min(_audioSkipRemaining, span.Length);
_audioSkipRemaining -= skip;
offset = skip;
if (offset == span.Length) return;
}
// Audio time comes from the sample count, not from a wall clock.
var time = TimeSpan.FromSeconds((double)_audioSamplesSeen / MicPipeline.SampleRate);
int count = span.Length - offset;
_audioSamplesSeen += count;
var chunk = span.Slice(offset, count).ToArray();
if (_systemAudio is not null) MixSystemAudio(chunk);
lock (_lock) _audio.Enqueue((chunk, time));
Signal(_audioSignal);
}
Two details in there matter.
The voice changer has a priming delay. HappyRec runs the microphone through a real-time voice changer (the same Signalsmith Stretch DSP the Mac app uses, built as a small native DLL). Like any block-based DSP, its output starts with a fixed number of samples of latency. If you stamp the very first output sample as time zero, the voice trails the picture by that latency for the whole recording. Dropping exactly LatencySamples at the start lines them up.
System audio is mixed in, not added as a track. Desktop audio from WASAPI loopback runs in real time at the same rate as the microphone, so it is buffered and mixed into the voice chunk before it is queued. The file has one audio track. Keeping the voice track first in the file is an invariant we carry across Mac and Windows, so the two apps produce files with the same layout.
A practical warning about loopback: WASAPI emits no packets at all while nothing is playing. A recorder tested on a silent desktop looks as if system audio is broken. It is only empty. Always test it with something actually playing.
Rule 4: Tell the encoder exactly what you want
MediaEncodingProfile.CreateMp4(quality) gives you a sensible profile, and it is tempting to change only the frame rate and keep the rest. We did that at first and the files played fine. Then a media inspector showed the AAC track claiming a bitrate of 750 bits per second, on a track that was really around 184 kbps. Nothing broke during playback, but bad metadata is the kind of thing that breaks uploads, editors and streaming platforms later. Setting the audio properties explicitly fixed it:
var videoProps = VideoEncodingProperties.CreateUncompressed(
MediaEncodingSubtypes.Bgra8, (uint)_item.Size.Width, (uint)_item.Size.Height);
var videoDesc = new VideoStreamDescriptor(videoProps);
// 16-bit PCM rather than float: Media Foundation's AAC encoder takes
// integer PCM natively. Samples are converted in OnSampleRequested.
_voiceDesc = new AudioStreamDescriptor(
AudioEncodingProperties.CreatePcm(MicPipeline.SampleRate, 1, 16));
// Voice/mic is the first (and, while mixing, only) audio track.
_mss = new MediaStreamSource(videoDesc, _voiceDesc) { BufferTime = TimeSpan.Zero };
_mss.SampleRequested += OnSampleRequested;
var profile = MediaEncodingProfile.CreateMp4(Quality);
profile.Video!.FrameRate.Numerator = (uint)FramesPerSecond;
profile.Video.FrameRate.Denominator = 1;
profile.Video.Bitrate = Bitrate;
// Set the audio encoding explicitly: leaving it to CreateMp4's default
// writes nonsense esds bitrate metadata (observed: 750 bps on a
// 184 kbps track).
profile.Audio = AudioEncodingProperties.CreateAac(MicPipeline.SampleRate, 1, 128_000);
Three choices in there are deliberate:
- The source audio is 16-bit integer PCM, not float. Media Foundation’s AAC encoder takes integer PCM natively, so the float samples from the audio pipeline are converted when each sample is handed over. Declaring float and hoping the pipeline inserts a converter is less predictable.
BufferTime = TimeSpan.Zero. The source does its own queueing; lettingMediaStreamSourceadd a buffer on top only adds latency and makes the stop behaviour harder to reason about.- Bitrates are set for screens, not cameras. Screen content is mostly text and hard edges. H.264 at camera-footage bitrates smears small text, and a watermark is exactly the kind of small text people notice.
// Screen content is mostly text and hard edges, which H.264 smears at the
// bitrates that suit camera footage - these run well above video defaults
// so the watermark and UI text stay crisp.
private static readonly (string Label, VideoEncodingQuality Quality, uint Bitrate)[] Qualities =
{
("720p", VideoEncodingQuality.HD720p, 10_000_000),
("1080p", VideoEncodingQuality.HD1080p, 20_000_000),
("4K", VideoEncodingQuality.Uhd2160p, 60_000_000),
};
The end of the stream is a decision, not an accident
One more timing rule, smaller but just as nasty. In the first build, SampleRequested returned a null sample whenever its queue happened to be empty. A null sample means end of stream. At the start of a recording, before the first frames had arrived, the queue was briefly empty, so the transcoder decided the stream was over. The file was a fraction of a second long.
The handler now takes a deferral and waits for data. It only reports end of stream when the queue is drained and recording has stopped:
// Queue drained. Only now is an empty queue meaningful.
if (!_running)
{
args.Request.Sample = null; // genuine end of stream
return;
}
// The timeout makes a missed signal self-healing rather than a hang.
await signal.WaitAsync(TimeSpan.FromMilliseconds(50)).ConfigureAwait(false);
The 50 ms timeout is there so that a missed signal costs 50 ms instead of hanging the encoder forever.

Overlays must never break the recording
The camera bubble, the watermark and the badge are drawn onto each frame by the compositor, on the encoder’s worker thread. During development, the compositor once read the bubble window’s position through a WinUI object. WinRT UI objects belong to the UI thread, so that threw RPC_E_WRONG_THREAD. The exception escaped Compose, the sample was null, the stream ended, and the muxer failed with “Sink could not create valid output file because required headers were not provided”. That error points nowhere near the real cause.
Two changes came out of that. The bubble’s position is read with plain Win32 calls on a window handle cached at construction, which is safe from any thread. And the compositor wraps each overlay so that a fault in one degrades to “no overlay on this frame” rather than “no recording”. A cosmetic bug should cost cosmetics, never the user’s file.
Three more Windows traps that are not about time
The timing rules produced the most confusing files, but they were not the only surprises in the first real Windows build. Three more are worth knowing if you are building a WinUI 3 desktop app of any kind, recorder or not.
AppWindow.Resize takes physical pixels
The recorder window has a fixed layout, so the app sizes it at start-up. AppWindow.Resize looks like it takes the same units as the XAML layout. It does not: it takes physical pixels. On a display scaled to 150%, passing layout units straight through produced a window two-thirds of the width the layout needed, and the right-hand column was silently clipped. Nothing logged an error; the controls were simply not visible.
Scaling by GetDpiForWindow(hwnd) / 96.0 fixes the width, but then overshoots in the other direction. A 760-unit-tall window becomes 1,140 physical pixels at 150%, which is taller than a 1080p panel. So the helper also clamps the result to the monitor’s work area (which excludes the taskbar) and centres the window. The same call is then correct on a 4K display and on a small laptop running at high scaling, which is exactly the hardware people record tutorials on.
XAML raises events while it is still parsing
Setting a property in XAML can raise that control’s change event during parsing, before fields declared further down the file have been assigned. We hit this twice: IsChecked="True" on a toggle raised its Checked handler, and Minimum="1" on a slider coerced its default value and raised ValueChanged. Each handler touched a field that did not exist yet.
The result was not a helpful NullReferenceException with a line number. WinUI turned it into a stowed exception (0xC000027B) and the app simply closed. The fix is boring: set initial state in the constructor after InitializeComponent, or null-guard every field a change handler touches. Because exceptions during window construction leave nothing on the console, the app also writes them to a crash log in the temp folder, so the next one is readable.
Draw a bitmap on the device that created it
The camera bubble can show a logo image instead of the webcam. The first version loaded that image as a Win2D CanvasBitmap on the shared device, then drew it in a drawing session from a different control. The process died with D2DERR_WRONG_RESOURCE_DOMAIN: no managed exception, just a crash in a system DLL. Win2D resources belong to the device that created them, so the bitmap has to be created from the drawing session’s own resource creator.
None of these three would show up on a developer machine running at 100% scaling with a debugger attached. All three show up on an ordinary user’s laptop on day one.
How to test a capture pipeline like this
Most of these bugs pass a quick test. Here is what catches them:
- Test on a machine that has been up for a while. Better still, log the first frame’s
SystemRelativeTime. If it is not small, you need the rebase. - Read the file, do not just play it. Check the container’s duration against your stopwatch, and check each track’s declared bitrate. A file can play and still be wrong.
- Clap at the start. A sharp sound with a visible hand movement shows audio offset instantly. Do it at the start and at the end of a long recording to see drift.
- Record something with fine text at every quality. That is what users record, and it is what low bitrates ruin first.
- Test system audio with sound actually playing, and test it once with silence, so you know what “empty” looks like.
- Stop quickly and stop late. A one-second recording exercises the end-of-stream logic; a long one exercises the queue caps.
The short version
- Rebase
SystemRelativeTimeon the first frame. It counts from boot. - Release capture frames and render targets from
MediaStreamSample.Processed, not when you create the sample. - Derive audio time from the sample count, and drop the DSP’s priming latency.
- Set the AAC properties explicitly instead of trusting
CreateMp4‘s default. - Only return a null sample when recording has stopped and the queue is empty.
- Keep overlay faults inside the overlay.
HappyRec is our free screen recorder for Mac and Windows, with a Chrome and Edge extension for recording from the browser. See what it does, or talk to us about building yours.



