Media encoding and muxing
Media encoding and muxing turn timestamped capture frames and audio samples into playable recording files. The system selects a codec and an available platform path, keeps media on one timeline, attaches the metadata needed for decoding, and writes complete files or fragments for later use.
This page is part of the recording and media engine. The capture and recording pipeline supplies timed inputs, while export and editor rendering consumes the resulting files and fragments.
Media output model
The media output layer has two related jobs. An encoder compresses raw video or audio into packets. A muxer places those packets with stream metadata and timing into a file format that a player can read.
Codec families
A codec defines how raw media becomes compressed packets. Video and audio use separate codecs because they have different data and timing needs.
| Media | Main codecs | Typical role |
|---|---|---|
| Video | H.264 | General recording and segmented playback. |
| Video | HEVC | Higher compression when the platform supports it. |
| Video | ProRes 4444 | High-quality MOV output with alpha support. |
| Audio | AAC | Audio in MP4 and fragmented MP4 output. |
| Audio | Opus | Stand-alone Ogg audio and audio rebuilt from fragments. |
The selected codec affects the required pixel or sample format, rate, keyframe behavior, and metadata. The output contract must therefore carry more than the codec name.
References: crates/…/h264.rs• L27-69 crates/…/hevc.rs• L23-48 crates/…/prores.rs• L44-57 crates/…/aac.rs• L34-43 crates/…/opus.rs• L15-33
Encoder selection
The H.264 and HEVC paths try a platform-appropriate encoder and fall back when the requested encoder is missing, cannot open, or fails its supported hardware pre-flight check. H.264 also avoids hardware for capture settings that exceed its estimated throughput. Software encoders remain the final path because they are available across more machines and can handle cases where hardware cannot keep up.
The choice also changes with the job. Live recording favors low delay and throughput. Export favors quality where the export path requests it. H.264 runs a cached hardware pre-flight check on supported Windows hardware paths and Linux NVIDIA or VA-API paths. The check encodes eight neutral-gray frames and decodes them with software to reject hardware sessions that open but produce empty, black, green, or otherwise invalid video. The result is cached for the settings that shape the session, so the check does not repeat for the same path.
Audio recording on macOS first tries AudioToolbox AAC unless the recording path requests FFmpeg AAC. If that encoder cannot open, the system falls back to FFmpeg AAC. Export uses the native path when available but keeps encoder priming in the output timeline, so an export does not lose input samples through recording-only trim rules.
Platform output paths also keep a session-level software fallback. On Windows, a Media Foundation H.264 session is validated before use and is disabled for later attempts after a recoverable hardware crash. The next setup then uses FFmpeg H.264 rather than repeatedly starting the failing transform. crates/…/win.rs• L204-325
References: crates/…/h264.rs• L191-294 crates/…/h264.rs• L1273-1409 crates/…/h264.rs• L1590-1877 crates/…/aac.rs• L64-132 crates/…/win.rs• L204-325
Format conversion
An encoder accepts only certain pixel or sample formats. When the capture format does not match, the media layer converts or scales the frame before it sends the frame to the codec. Audio passes through a resampler when the codec needs another sample rate, sample format, or channel layout.
Conversion is part of the media contract because it changes cost and sometimes dimensions. Even dimensions are used for common 4:2:0 video paths. The selected encoder reports its expected output format and size so platform capture code can provide a compatible frame when it can. RGB input is converted with BT.709 coefficients and the range expected by the encoded stream. On macOS, an H.264 VideoToolbox path can accept IOSurface-backed NV12 frames directly when no scaling is needed. Otherwise the system uses a software-input path.
On Windows, camera input may arrive as packed, planar, compressed, or bottom-up data. The native path uploads a compatible surface after any required row order or packed-pixel conversion. The FFmpeg path maps supported camera formats into FFmpeg frames and decodes MJPEG before encoding. This gives both encoder paths the same visible camera content even when the device layout differs. crates/…/win.rs• L1377-1637
Audio encoders choose a supported output rate at or above the input rate when possible. Opus reduces multi-channel input to stereo because voice capture does not need a surround channel map. The resampler then provides the format and rate that the codec can accept.
References: crates/…/colour.rs• L9-37 crates/…/h264.rs• L306-436 crates/…/h264.rs• L643-745 crates/…/prores.rs• L76-105 crates/…/aac.rs• L151-197 crates/…/opus.rs• L53-90 crates/…/win.rs• L1377-1637
Audio sample preparation
Audio is buffered after resampling so the encoder receives the frame sizes it expects. The buffer keeps the sample timeline when input blocks have different sizes or when the input rate does not divide evenly into the output rate.
Confirmed gaps become silence. Overlapping or rounded sample positions do not create a large false gap. At finish, the buffer drains its remaining samples and the encoder trims padding that a fixed-size native encoder adds beyond the input end. Native and FFmpeg AAC paths therefore place recording content at the same sample positions even when their priming differs.
References: crates/…/buffered_resampler.rs• L34-53 crates/…/buffered_resampler.rs• L64-102 crates/…/base.rs• L67-100 crates/…/aac.rs• L201-219
Timestamp model
Timestamps are the link between capture time and playback time. The media layer converts source timestamps into each encoder's time base, keeps packet order valid, and retains real gaps so video and audio do not move ahead of one another.
Frame presentation time
The presentation timestamp, or PTS, tells a player when to show a frame. The output pipeline first removes the recording's baseline and any paused time. It then keeps capture cadence where the source clock is trustworthy and bounds it against elapsed wall time when a source clock jumps or stops delivering frames. The encoder converts the result into integer ticks for its own time base.
The pipeline treats a source-clock glitch differently from a real delivery gap. A backward or spurious forward jump is repaired against the last valid time. A wall-clock-confirmed forward jump remains in the recording timeline. Repeated or otherwise invalid packet times are still corrected before they reach the container.
References: crates/…/core.rs• L1640-1674 crates/…/core.rs• L1737-2004 crates/…/base.rs• L86-186
Audio sample time
Audio timestamps use sample counts because one audio tick represents one sample at the encoder's output rate. The input timestamp is first expressed in the input sample rate. The resampler then maps the samples to the codec's output rate while keeping gaps and overlaps tied to the sample timeline.
The audio path buffers samples until it can provide frames of the size expected by the codec. It inserts silence for a real gap and drains its remaining samples at finish. This keeps short input blocks and non-standard rates from becoming a zero-length or incorrectly paced file.
Audio can start from the first captured frame or from the pipeline epoch. Device-backed audio uses the first frame as its ready point. Intermittent system audio can use the pipeline epoch so a late first sound does not move the start of every other track. crates/…/core.rs• L2280-2296
References: crates/…/base.rs• L150-186 crates/…/base.rs• L38-79 crates/…/buffered_resampler.rs• L104-277 crates/…/core.rs• L2280-2296
Gap and duration preservation
Capture can stop delivering frames while the recording timeline continues. Video keeps the capture-derived timestamp when it is valid and uses the wall clock to confirm real delivery gaps. Audio uses sample and wall-clock checks to distinguish a real silent interval from a bad source timestamp, then fills a confirmed gap with silence.
Pauses are removed from the shared output timeline rather than treated as missing media. The same pause state adjusts video and audio, so a resume does not add a pause-length offset to one track only. First-frame video and audio alignment can also trim leading audio samples or advance the audio timeline with silence when the two encoders start within the allowed alignment range. crates/…/core.rs• L170-260
Packet duration is as important as packet timestamp at a fragment boundary. The muxing paths derive a missing duration from the next packet when possible. If the next timestamp does not advance, they use the packet's own duration or the last known duration. At the end of a stream, they use a nominal video frame or audio block duration when available. This prevents a post-gap frame from playing during the gap when a fragmented container uses the last sample's duration.
When separate recording files are joined, the remuxer can preserve each file's original start time. It inserts the gap between file starts instead of forcing the next file to start at the prior file's end. Overlapping files still join without creating negative time.
References: crates/…/core.rs• L2011-2253 crates/…/core.rs• L898-1163 crates/…/base.rs• L217-277 crates/…/base.rs• L81-135 crates/…/segmented_stream.rs• L418-453 crates/…/remux.rs• L62-151
Timestamp handoff
The in-process and out-of-process muxers use the same timing idea even though they receive different packet forms. The in-process path gives frames to an FFmpeg output context. The out-of-process path sends encoded packet data with PTS, DTS, duration, and keyframe state across a framed protocol.
The out-of-process path must use the same time base that was declared during initialization. A mismatch changes the scale used by the muxer and can make the recording play much too fast or too slowly. The child converts the packet time base to the container stream time base only after it has assigned a usable duration.
References: crates/…/h264_packet.rs• L200-217 crates/…/oop_fragmented_m4s.rs• L301-352 crates/…/ffmpeg.rs• L770-822 crates/…/main.rs• L770-822
Media metadata
Media metadata describes how a player must interpret each stream. It is created when the encoder opens and travels with the container or with the fragment initialization data.
Stream description
The stream description includes the codec, dimensions, frame rate, sample rate, channel count, sample or pixel format, and time base. Video may also include codec extra data, which is the codec setup data such as parameter sets needed before packet data can be decoded.
The description must match the packets that follow it. For example, a standalone H.264 encoder reports its chosen codec, output size, frame rate, time base, and extra data before the packet stream is sent to the separate muxer.
References: crates/…/lib.rs• L52-90 crates/…/oop_muxer.rs• L98-126 crates/…/oop_fragmented_m4s.rs• L301-352
Color and sample properties
Video output records standard color properties so players can display captured pixels with the intended range and transfer behavior. The common H.264 and HEVC paths use BT.709 properties. ProRes uses the same declared color model for its alpha-capable output, while the conversion path preserves the range expected by the stream.
Audio metadata records the final channel layout and rate after resampling. AAC accounts for encoder priming differently for recording and export: recording aligns native AAC with the FFmpeg AAC timeline, while export keeps the input samples in a regular MP4 timeline.
References: crates/…/colour.rs• L9-37 crates/…/h264.rs• L752-772 crates/…/prores.rs• L130-157 crates/…/aac.rs• L104-219
Fragment metadata
Fragment metadata lets the recorder publish a segment only after its media is complete. The media layer reads the fragment's boxes and segment index to obtain its duration and size. When an index is not present, it can inspect the initialization segment and the complete sample runs to find the valid prefix.
The valid prefix must begin with a keyframe and must have contiguous decode times. A truncated tail is excluded from publication, while unrelated read errors remain errors rather than being mistaken for a short valid fragment. A simpler tail check also confirms that a file ends with a complete moof and mdat pair.
References: crates/…/fragment_metadata.rs• L8-32 crates/…/fragment_metadata.rs• L51-147 crates/…/fragment_prefix.rs• L401-481 crates/…/fragmented_mp4.rs• L8-29
Fragment manifest metadata
Segmented output has an initialization segment and media segments. The initialization segment carries the stream setup. The JSON manifest adds the segment names, indexes, durations, sizes, codec information, and whether the recording is complete.
The manifest is written during recording so another part of the system can discover completed media before the recording ends. It is written atomically, which prevents a reader from seeing a half-written document. Finalization adds the total duration and marks the manifest complete. Audio DASH publication also adjusts the first fragment's reported duration for AAC priming, and it can recover valid temporary or orphaned segments before final manifest creation.
References: crates/…/segmented_stream.rs• L103-139 crates/…/segmented_stream.rs• L460-508 crates/…/segmented_stream.rs• L674-704 crates/…/dash_audio.rs• L320-594
Muxing formats
The muxer chooses the container and write pattern for the consumer. A complete file is useful when a player needs one self-contained asset. Fragmented output is useful when recording, upload, recovery, or playback must begin before the full recording is done.
Complete media files
The regular FFmpeg file paths write a header, accept encoded packets, flush the encoders, and write a trailer. The trailer closes the container and records final indexes and duration.
The Ogg path uses Opus for audio-only output. It writes the container header before frames arrive, drains the encoder at finish, and then writes the trailer. It can also move packet writes behind a bounded writer so a short storage stall does not block the caller while preserving the output bytes and order.
| File form | Video | Audio | Purpose |
|---|---|---|---|
| MP4 | H.264 | Optional AAC | General recording output. |
| MOV | ProRes 4444 | None in this path | High-quality video output. |
| Ogg | None | Opus | Audio-only output. |
The MOV path changes the requested extension to .mov and treats a second finish call as an error. This gives the high-quality video path one clear end state before the trailer is written.
References: crates/…/mp4.rs• L44-81 crates/…/mp4.rs• L100-183 crates/…/mov.rs• L28-85 crates/…/ogg.rs• L33-97 crates/…/remux.rs• L416-490
Fragmented MP4
Fragmented MP4 stores an initialization section followed by independent media fragments. The fragments can be read as they arrive, and a valid initialization section lets a consumer interpret the later media data.
The recording layer uses fragmented MP4 for AAC audio files and for combined segmented streams. Audio configures time-based cuts and flushes packets so bytes become visible before finalization. Video publishes fragments at safe keyframe boundaries. Fragment inspection checks box structure, sample ranges, duration, and completeness before a segment becomes available to consumers.
References: crates/…/fragmented_audio.rs• L40-63 crates/…/fragmented_audio.rs• L116-155 crates/…/fragmented_mp4.rs• L8-29 crates/…/fragment_prefix.rs• L401-481
DASH-style segments
The DASH muxer writes an init.mp4 file and numbered .m4s media segments. Its timeline and template settings allow the segment list to describe media that is still being produced. The DASH muxer owns publication of its MPD manifest, so the output context does not open or truncate that manifest through a second file handle. Finalization verifies that the MPD is static and closed before the output is treated as complete.
The project also keeps a simpler JSON manifest for local discovery and recovery. Video and audio can use separate DASH segment encoders. Segment completion events identify the media type, index, duration, path, and file size so upload or playback code can consume finished pieces without scanning the directory. Audio writes this state atomically and can move valid .tmp segments into their final names during finish.
References: crates/…/dash_output.rs• L4-35 crates/…/segmented_stream.rs• L195-328 crates/…/segmented_stream.rs• L418-453 crates/…/dash_audio.rs• L161-227 crates/…/dash_audio.rs• L345-594
Packet transport protocol
The out-of-process path separates packet encoding from file muxing. The recording process sends initialization data first, then sends video or audio packets, and ends with a finish frame. Each packet carries its stream, timestamps, duration, flags, and encoded bytes.
The protocol has a magic value, version, length, and CRC check. These fields reject a wrong program or damaged stream before it can create a misleading media file. The protocol is an internal transport contract, not a playback format.
The child muxer reads this stream on a separate input thread and uses a bounded byte queue before it writes packets. A cancelled or closed input releases blocked producers and lets the child finish or report the protocol error instead of waiting forever.
References: crates/…/lib.rs• L4-20 crates/…/lib.rs• L185-237 crates/…/oop_muxer.rs• L233-279 crates/…/main.rs• L92-203 crates/…/main.rs• L233-305
Write-behind muxing
Write-behind muxing moves packet writes and finalization to a dedicated writer thread. It lets encoding and the recording runtime continue while storage handles a short write stall, while preserving packet order and the same bytes as inline muxing.
The queue has a byte budget rather than an unbounded item count. When the budget is full, the producer waits for storage. Finish first drains the queue and then writes the trailer or final manifest. If storage cannot drain or finalize within the bounded finish window, the system reports a storage stall and leaves the output in the recovery state instead of waiting without limit. A later recovery pass can still find data that reached disk.
macOS fragmented video uses this write-behind path. It can pass an IOSurface-backed frame directly to VideoToolbox, or use a software frame pool when the hardware input path is not available. The encoder also checks free space while it receives frames and stops accepting more media after the disk is exhausted. crates/…/macos_fragmented_m4s.rs• L295-469
References: crates/…/write_behind.rs• L1-20 crates/…/write_behind.rs• L103-220 crates/…/write_behind.rs• L429-512 crates/…/write_behind.rs• L527-627 crates/…/ogg.rs• L53-58 crates/…/macos_fragmented_m4s.rs• L295-469
Platform encoding paths
The recording output chooses a platform path when the host can provide a native media service or a hardware surface. All paths aim to produce the same high-level result: correctly timed media with a clear finish or a recoverable set of fragments.
macOS native path
The macOS native path uses AVFoundation's asset writer for MP4 recording. It accepts native sample buffers, asks VideoToolbox for H.264 output, and can resample audio to the rate accepted by the AAC writer. The screen and camera muxers feed bounded video and audio channels to dedicated workers, so capture can continue through short writer stalls without unbounded memory growth.
For segmented recording, macOS can pass IOSurface-backed NV12 buffers directly to a VideoToolbox encoder. When that path is not available, it converts the sample buffer into a software frame before encoding. AudioToolbox AAC is preferred for the FFmpeg fragmented-audio path when available, with FFmpeg AAC as the fallback.
The native MP4 path checks for free space before it starts and keeps checking while it receives frames. If storage runs out, it stops while the writer is still alive so finalization can preserve the MP4 index. Its stop path uses bounded worker waits; an audio timeout can preserve the file while truncating only the audio tail. crates/…/macos.rs• L41-64 crates/…/macos.rs• L723-855
The macOS fragmented video path uses a bounded input channel and a separate encoder thread. A full channel drops a frame and reports a high drop rate through pipeline health. Stop waits for the encoder and writer for a bounded time, then preserves a storage-stall or unfinished state for recovery instead of claiming a clean file. crates/…/macos_fragmented_m4s.rs• L105-160
References: crates/…/mp4.rs• L120-181 crates/…/mp4.rs• L241-418 crates/…/macos.rs• L41-64 crates/…/macos.rs• L330-855 crates/…/macos.rs• L994-1448 crates/…/macos_fragmented_m4s.rs• L278-327 crates/…/macos_fragmented_m4s.rs• L334-469 crates/…/h264.rs• L306-436 crates/…/aac.rs• L64-101
Windows native path
The Windows native path uses Media Foundation with Direct3D input for H.264 when the hardware transform opens and passes validation. It can scale the input while it prepares the format required by the encoder. If the hardware path fails, the recording output falls back to the FFmpeg software H.264 path.
The encoder uses frame pacing to turn an irregular or slow capture stream into the configured output rate. When capture is late, it can repeat the last usable frame with a new presentation time. It normalizes the first accepted timestamp to zero before writing samples, while the audio encoder uses the same output context.
The Windows fragmented path can also use FFmpeg H.264 directly. This gives the recording system a common segmented output model when native Media Foundation output is not the selected path. Camera input has a matching native and software path, with explicit handling for device pixel layout, row direction, and compressed MJPEG input. crates/…/win.rs• L343-477
References: crates/…/h264.rs• L236-276 crates/…/h264.rs• L354-436 crates/…/win.rs• L184-309 crates/…/win.rs• L343-477 crates/…/win.rs• L878-1043 crates/…/win_fragmented_m4s.rs• L319-347
Linux VA-API path
The Linux H.264 path can use VA-API on AMD and Intel GPUs. It creates NV12 hardware surfaces from a render node and transfers compatible software frames into those surfaces before encoding. NVIDIA devices use a separate encoder path, while unsupported or unavailable VA-API devices remain eligible for software fallback.
References: crates/…/vaapi.rs• L1-5 crates/…/vaapi.rs• L26-97 crates/…/vaapi.rs• L110-141
Out-of-process path
The out-of-process path runs the file muxer in crates/…/main.rs and keeps packet encoding in the recording process. This boundary isolates container writes from the capture process and allows the muxer to be restarted within a bounded budget.
The parent sends codec setup and packet timing through cap-muxer-protocol. The child builds the DASH output, rejects packets before the first video keyframe, derives missing durations, and writes the trailer at finish. It also reports protocol errors and disk-full errors through distinct process results, so a failed write becomes a recording health signal rather than an unexplained missing file.
References: crates/…/oop_fragmented_m4s.rs• L256-375 crates/…/main.rs• L233-305 crates/…/main.rs• L341-369 crates/…/main.rs• L568-822 crates/…/oop_muxer.rs• L481-537
Recording output lifecycle
The encoder and muxer form one lifecycle even when they run in different threads or processes. The lifecycle starts with stream setup, continues with packet writes, and ends only after buffered data and container state are closed.
Initialization
Initialization selects the codec and output settings before media packets are written. It adds each stream to the output, sets its time base and parameters, and writes the container header. A fragmented path must make its initialization segment available before consumers use its media segments.
References: crates/…/fragmented_audio.rs• L82-109 crates/…/segmented_stream.rs• L219-328 crates/…/dash_audio.rs• L161-241 crates/…/main.rs• L372-566
Packet writing
For each input frame, the encoder assigns time, performs any needed conversion, and emits zero or more compressed packets. The muxer places packets in stream order and uses keyframes to make video segment boundaries safe for playback.
When the output path is slower than capture, bounded queues protect the capture sources. The in-process segmented video path waits only for its stall budget before dropping a frame and reporting the drop rate. Native macOS and Windows paths use bounded channels as well. Windows pacing can reuse the last frame when capture is slow, while macOS fragmented encoding can drop queued frames when the channel is full. These choices protect memory while making overload visible instead of hiding it as a timing fix. crates/…/write_behind.rs• L379-419
The native macOS MP4 screen and camera paths also use bounded input channels. Their workers report queue pressure and dropped frames, retry briefly when the platform writer is not ready, and stop on fatal writer or disk errors. Finish waits for the workers before it asks the asset writer to close the MP4, with a longer audio drain window for instant recordings. crates/…/macos.rs• L116-270 crates/…/macos.rs• L416-666
Strict recording scopes require the segmented encoder thread to join before stop is confirmed. Less strict paths use a bounded drain window and preserve an incomplete result when the encoder or storage does not finish. crates/…/write_behind.rs• L379-419
References: crates/…/base.rs• L188-260 crates/…/h264.rs• L897-999 crates/…/segmented_stream.rs• L384-453 crates/…/write_behind.rs• L379-419 crates/…/core.rs• L647-755 crates/…/ffmpeg.rs• L435-461 crates/…/ffmpeg.rs• L548-674 crates/…/macos.rs• L705-855 crates/…/win.rs• L570-602
Finalization and recovery
Finalization flushes each encoder so delayed packets are not lost, writes the container trailer, and marks manifests complete. Segmented paths also find non-empty temporary or unlisted segments. They validate the fragment structure before preserving media from a stop during a write.
The media layer can assemble fragments through a logical FFmpeg input that reads several files as one stream. It can validate that the result contains a decodable video frame, probe seek points, and reject corrupt packets before publication. It can concatenate fragments into a regular file, merge separate video and audio files, or rescale a video-only track when a known timestamp-rate error needs repair.
Timestamp rescaling is limited to video-only repair. It uses a fine output time scale, rescales PTS, DTS, and duration, and restores monotonic DTS. Video and audio merging keeps separate stream metadata and repairs each stream's packet order independently.
Keyframe indexing supports this validation and later seek work. For MP4 and MOV files, the decoder can use the container sample table when the track has no presentation-time offsets and the index covers the stream. It scans packets instead when reordering, fragmented input, or incomplete coverage makes the table unsafe. Seeking uses the latest keyframe at or before the requested time, which avoids moving forward across variable-frame-rate gaps.
References: crates/…/segmented_stream.rs• L510-704 crates/…/dash_audio.rs• L446-594 crates/…/remux.rs• L325-401 crates/…/remux.rs• L1101-1325 crates/…/remux.rs• L1328-1438 crates/…/avassetreader.rs• L29-65 crates/…/avassetreader.rs• L181-287 crates/…/ffmpeg.rs• L253-280 crates/…/macos_fragmented_m4s.rs• L105-160 crates/…/win.rs• L506-520
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the encoder's declared codec, dimensions, rate, time base, and extra data aligned with the packet transport and the child muxer's stream setup.
- Keep timestamp units consistent across capture timestamps, encoder ticks, audio sample counts, packet durations, and manifest durations.
- Keep source-clock anomaly handling aligned with audio timing. A real delivery gap must stay in both tracks, while a clock glitch must not create false silence or a video step.
- Keep pause removal and first-frame A/V alignment aligned across video timestamps, audio sample trimming, and persisted track start times.
- Keep keyframe cadence aligned with the configured segment duration. A segment boundary without a usable video keyframe can make a fragment hard to start.
- Keep audio resampling, channel reduction, and priming metadata aligned with the samples actually sent. A rate, channel, or trim mismatch can change playback speed or shift content.
- Keep initialization segment creation and segment completion events aligned. Consumers must not receive a media segment before the setup data they need.
- Keep DASH MPD ownership aligned with the output context. A second file handle must not replace or truncate the manifest while the DASH muxer writes it.
- Keep native hardware fallback behavior aligned with the software encoder's input format and output dimensions.
- Keep macOS native MP4 disk preflight, live disk checks, worker drain, and writer finalization aligned. A stop after the writer dies can lose the MP4 index.
- Keep macOS native MP4 queue limits and frame-drop health signals aligned with the selected recording mode. A larger instant-mode buffer must not hide sustained overload or allow unbounded growth.
- Keep Windows frame pacing aligned with timestamp normalization. Reused frames must receive new output times without changing the source timeline contract.
- Keep camera pixel-format, stride, row-order, and compressed-frame handling aligned between native and software encoder paths.
- Keep hardware self-test scope aligned with every setting that can change the encode result. A cached pass must not be reused for a different codec option, frame rate, input format, or rate target.
- Keep fragment box and sample-table rules aligned with recovery. A fragment must not be published from a partial media tail or a non-contiguous decode timeline.
- Keep write-behind byte budgets and finish limits aligned with the recording stop budget. A stalled writer must return a recovery state instead of blocking the capture stop indefinitely.
- Keep packet-protocol version, stream indexes, flags, and time-base fields aligned between
cap-muxer-protocol, the parent process, andcap-muxer. - Keep manifest version and field meaning aligned with fragment recovery, upload, and playback consumers.
- Keep timestamp repair or validation rules aligned with the track type they are allowed to change. Video-only timestamp rescaling must not be used as an audio repair.
- Keep concat-list path rules aligned with the FFmpeg concat reader. Paths with quotes, newlines, non-text names, or URL-like prefixes must not change the selected fragment.
- Keep keyframe-index fast paths limited to tracks whose container timestamps represent presentation order. Reordered or fragmented tracks must continue to use packet scanning.
- Keep Ogg header creation, Opus flush, trailer writing, and optional write-behind output aligned so short or empty audio tracks remain valid and complete.
- Keep VA-API device selection aligned with the H.264 hardware contract. Render nodes without the needed driver must remain available for the correct fallback path.
- Keep disk-space health signals and encoder stop behavior aligned. Exhausted storage must not be reported as a clean recording finish.
- Keep bounded input queues and drop-rate health events aligned with the chosen platform path. A full queue must not become unbounded memory growth or a silent loss of media.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| Hardware encoder opens but produces invalid or empty video | The recording can contain black, green, or undecodable frames. | Cached neutral-gray encode/decode self-test on supported paths and software fallback. |
| Capture pixel format or size does not match the codec | Frame conversion fails or the encoder rejects the stream. | Conversion requirements, scaling, even dimensions, and output-size validation. |
| Input timestamps repeat or move backward | The container can reject packets or playback order can break. | Monotonic PTS and DTS correction plus source-clock anomaly repair. |
| A source-clock jump is mistaken for a real gap | Video advances or collapses without audio, causing A/V drift. | Compare source time with wall time and accept only wall-clock-confirmed gaps. |
| Pause offset is applied to one track but not the other | Resume creates a silent A/V shift. | Shared pause state and track-local timestamp adjustment. |
| Packet duration is missing at a fragment cut or stream end | A post-gap frame can play inside the gap or the last sample can have the wrong length. | Adjacent-DTS duration derivation, last-duration reuse, and nominal-duration fallback. |
| Audio input rate or channel count is not supported by the codec | Audio can play at the wrong speed, lose its channel map, or fail to start. | Buffered resampling and Opus stereo downmix with output-rate metadata. |
| Native AAC priming is treated as content time | Audio from different encoders can shift or end at different positions. | Recording trim alignment and export-specific priming policy. |
| Initialization segment is missing or too small | M4S media segments cannot be decoded by a consumer. | Init-segment validation and delayed completion notification. |
| Fragment has a truncated tail or invalid sample range | Recovery can publish media that cannot be decoded. | Box checks, complete moof/mdat checks, and valid-prefix inspection. |
| DASH output opens the MPD through a second file handle | Windows can replace or truncate the manifest while DASH writes it. | Let the DASH muxer own manifest I/O and verify a static closed MPD at finish. |
| MP4 or MOV is finished twice | The producer can send packets after the container has closed or hide the real stop state. | One-way finish state and explicit already-finished result. |
| macOS native MP4 starts with too little disk space | The writer can fail before it creates a recoverable MP4 index. | Start preflight requires headroom and live monitoring stops before writer death. |
| macOS native MP4 worker or storage remains stalled during finish | The output can lose its trailer or the audio tail can be incomplete. | Bounded worker waits, encoder finalization while the writer is alive, and explicit finish errors. |
| Write-behind storage remains stalled during drain or finalization | Stop returns without a complete trailer and the output needs recovery. | Bounded byte queue, bounded finish window, and recovery-state preservation. |
| Muxer subprocess receives bad framing or a damaged packet stream | The child stops before writing a usable output. | Version, length, CRC, and payload-size checks. |
| The muxer input queue is full or the reader closes without Finish | Producers can block, or the child can end without a clean final frame. | Bounded queue cancellation, graceful finish, and explicit process results. |
| Muxer process crashes or disk space is exhausted | Further packets are not written and the recording becomes degraded or incomplete. | Health events, bounded respawn, disk monitoring, and disk-full classification. |
| Encoder is not flushed before the trailer | Delayed packets or the last audio samples are missing. | Explicit encoder flush followed by trailer and manifest finalization. |
| A segmented encoder thread outlives a strict recording stop | Stop can report success while frames or the trailer are still pending. | Joined stop for strict scopes and a bounded finish result for other scopes. |
| A native Windows encoder crashes and remains selected | Later recordings can fail in the same hardware path. | Disable the failed Media Foundation encoder session and use FFmpeg fallback. |
| A camera buffer has an unsupported layout or wrong row order | The saved camera image is corrupt, flipped, or cannot be encoded. | Validate strides and dimensions, convert known layouts, and reject unsupported formats. |
| A Windows frame queue fills during capture | Frames are lost or memory grows without bound. | Bounded channel, frame pacing, drop-rate reporting, and software fallback where needed. |
| A recording has no decodable frame at a seek point | Playback or editor seeking can fail even when the container opens. | Decode probes at the start, interior, and near the end of the media. |
| A keyframe index uses decode timestamps for a reordered or fragmented track | Seeking can start at the wrong time or skip the image held at a variable-frame-rate gap. | Require safe non-reordered MP4/MOV coverage, otherwise scan packet PTS and seek to the prior keyframe time. |
| Ogg finish skips the Opus encoder or resampler remainder | Short input blocks or the final samples can be missing from the audio file. | Flush the encoder before writing the trailer. |
| No Ogg frame is received before finalization | A zero-byte output cannot be opened as a media file. | Write the Ogg header during initialization. |
| Linux selects a render node without a usable VA-API driver | Hardware H.264 setup fails or an unsuitable device is tried. | Filter render nodes by kernel driver and exclude NVIDIA, virtual, and unsupported nodes. |
Key files
| File | Why to read it |
|---|---|
| crates/…/core.rs | Defines the shared recording timeline, source-clock repair, pause handling, A/V start alignment, health events, disk monitoring, and bounded stop behavior. |
| crates/…/base.rs | Defines shared packet timing, timestamp normalization, duration repair, and flush behavior. |
| crates/…/h264.rs | Shows H.264 codec selection, hardware fallback and self-test, conversion, rate settings, and keyframe policy. |
| crates/…/vaapi.rs | Shows the Linux VA-API hardware surface path and render-node selection for H.264. |
| crates/…/hevc.rs | Shows the HEVC encoder contract and platform encoder priority. |
| crates/…/prores.rs | Shows the high-quality alpha-capable video path and its MOV format requirements. |
| crates/…/colour.rs | Shows the color conversion contract used before encoded video is tagged as BT.709. |
| crates/…/h264_packet.rs | Shows how encoded H.264 packets and their metadata leave the encoder. |
| crates/…/aac.rs | Shows AAC rate and format selection, recording versus export priming, native macOS preference, and packet output. |
| crates/…/opus.rs | Shows Opus rate selection and the stereo contract for multi-channel voice input. |
| crates/…/base.rs | Shows audio timestamp conversion, resampling, packet output, padding trim, and flush behavior. |
| crates/…/buffered_resampler.rs | Shows how audio blocks, rate changes, gaps, overlaps, and final samples stay on one timeline. |
| crates/…/mp4.rs | Shows complete MP4 stream assembly, audio submission, and trailer handling. |
| crates/…/mov.rs | Shows the complete ProRes MOV lifecycle and its one-way finish state. |
| crates/…/ogg.rs | Shows complete Opus-in-Ogg output, header and trailer lifecycle, and optional write-behind output. |
| crates/…/dash_audio.rs | Shows segmented AAC output, priming-aware durations, atomic manifests, recovery, and completion events. |
| crates/…/write_behind.rs | Shows bounded asynchronous packet writes, storage back pressure, finish limits, and recovery after a stall. |
| crates/…/fragment_metadata.rs | Shows how fragment duration, size, and media-box completeness are checked. |
| crates/…/fragment_prefix.rs | Shows recovery of the last complete sample prefix from fragmented MP4 media. |
| crates/…/dash_output.rs | Shows DASH output ownership of MPD file I/O and final manifest validation. |
| crates/…/segmented_stream.rs | Shows DASH-style video segments, initialization data, manifests, events, and recovery. |
| crates/…/remux.rs | Shows fragment concatenation, timeline-preserving assembly, media validation, timestamp repair, and video-audio assembly after recording. |
| crates/…/avassetreader.rs | Shows safe keyframe indexing and time-based seek selection for video decoding. |
| crates/…/lib.rs | Defines the internal stream setup and encoded-packet transport contract. |
| crates/…/main.rs | Shows the bounded packet handoff, fragmented output setup, duration repair, and process failure reporting. |
| crates/…/oop_muxer.rs | Shows subprocess startup, packet delivery, crash reporting, and finish behavior. |
| crates/…/ffmpeg.rs | Maps recording output choices to the FFmpeg encoders and muxers, including bounded queues, drop reporting, and strict finish behavior. |
| crates/…/macos.rs | Shows native macOS MP4 screen and camera output, disk-space protection, bounded worker queues, frame pressure, and finalization. |
| crates/…/macos_fragmented_m4s.rs | Shows macOS fragmented video input choice, write-behind output, disk checks, frame-drop health, and bounded finalization. |
| crates/…/win.rs | Shows Windows Media Foundation and FFmpeg selection, frame pacing, timestamp normalization, camera conversion, and complete or fragmented MP4 output. |
| crates/…/mp4.rs | Shows the macOS native MP4 and VideoToolbox path. |
| crates/…/h264.rs | Shows the Windows Media Foundation hardware H.264 path. |