Skip to main content

ez_ffmpeg/core/writer/
mod.rs

1//! Push raw video frames from Rust code into a full FFmpeg pipeline.
2//!
3//! [`VideoWriter`](crate::VideoWriter) is a narrow, ergonomic facade over the
4//! crate's existing [`Output`](crate::Output) surface: you build frames in
5//! memory (any packed or planar `AVPixelFormat` — `rgba`, `rgb24`, `gray8`,
6//! `yuv420p`, `nv12`, …, delivered as tightly packed plane bytes) and push
7//! them in, and they flow through the ordinary filter → encode → mux
8//! pipeline. Because the destination is a plain [`Output`](crate::Output),
9//! the writer accepts any video encoder and container the linked FFmpeg build
10//! supports for that pairing, plus filter chains (one video input, one video
11//! output, with a directed input-to-output path), GPU frame pipelines, and
12//! RTMP targets. Out of scope: stream maps are rejected, and video
13//! stream-copy does not apply (frames are raw, so they are always encoded).
14//!
15//! **Experimental:** this API is new in 0.14 and its surface may still be
16//! refined in minor releases while it settles.
17//!
18//! ```no_run
19//! use ez_ffmpeg::{Output, VideoWriter};
20//!
21//! # fn render(_i: usize) -> Vec<u8> { vec![0u8; 1920 * 1080 * 4] }
22//! // Pick an encoder explicitly: with a bare "out.mp4" the linked FFmpeg
23//! // build chooses the container default (H.264 when libx264 is compiled
24//! // in, otherwise mpeg4 at a low default bitrate).
25//! let out = Output::from("out.mp4").set_video_codec("mpeg4").set_video_qscale(5);
26//! let mut writer = VideoWriter::builder(1920, 1080).fps(30, 1).open(out)?;
27//! for i in 0..300 {
28//!     writer.write_owned(render(i))?; // one RGBA frame, tightly packed
29//! }
30//! writer.finish()?; // drains the encoder, finalizes the container
31//! # Ok::<(), ez_ffmpeg::error::Error>(())
32//! ```
33//!
34//! # Scope (v1)
35//!
36//! - **Constant frame rate, video only.** Every pushed frame advances exactly
37//!   `den/num` seconds; there is no per-frame PTS and no audio. `write` takes
38//!   `&mut self` so the total frame order is fixed at compile time.
39//! - **Tight packing.** A frame is exactly
40//!   [`frame_size`](crate::VideoWriter::frame_size) bytes:
41//!   `av_image_get_buffer_size(pix_fmt, w, h, 1)`, planes concatenated in
42//!   descriptor order with no row padding.
43//!
44//! # How it works
45//!
46//! There is no demuxer and no decoder: the builder assembles a pipeline whose
47//! single filtergraph (`buffersrc → [filter_desc | null] → buffersink`) is fed
48//! directly by a frame-source worker. Pushed frames cross an in-process
49//! bounded channel to that worker, which copies them plane-by-plane into
50//! pooled `AVFrame`s and hands them to the filtergraph — exactly where a
51//! decoder would. End of stream is an explicit in-band marker the worker
52//! enqueues when ingress closes, so frames still buffered inside filters
53//! (e.g. `reverse`) are flushed with correct tail timing. Teardown order is
54//! owned by [`VideoWriter`](crate::VideoWriter):
55//!
56//! - [`finish`](crate::VideoWriter::finish) closes ingress (the worker emits
57//!   the EOF marker), then calls `wait()` — the authoritative way to retrieve
58//!   the pipeline's first error.
59//! - [`Drop`] does the same and logs any error; it may block until the encoder
60//!   drains, so prefer `finish()` when you need the result.
61//! - [`abort`](crate::VideoWriter::abort) discards the export (closes ingress,
62//!   then `abort()`s the scheduler); the partial output is not guaranteed
63//!   playable.
64//!
65//! # Memory
66//!
67//! Only the **ingress** queue is bounded, by frame count: `queue_capacity`
68//! frames (an exact `frame_size` copy per slot with
69//! [`write`](crate::VideoWriter::write); the caller's `Vec` as provided with
70//! [`write_owned`](crate::VideoWriter::write_owned)), plus a bounded handful
71//! of in-flight frames in the internal channels.
72//! Filters that buffer (`reverse`, `tpad`, …), the codec's lookahead, and
73//! output I/O can each hold further data with no global limit — exactly as
74//! they do in any other job of this crate.
75//!
76//! # FFmpeg versions
77//!
78//! Works on every FFmpeg release this crate supports (7.1–8.x); it opens no
79//! input format context, so no version-specific probing behavior applies.
80
81use std::ffi::CString;
82use std::sync::atomic::{AtomicUsize, Ordering};
83use std::sync::Arc;
84use std::time::Duration;
85
86use crossbeam_channel::{SendTimeoutError, Sender};
87use ffmpeg_sys_next::AVPixelFormat::AV_PIX_FMT_NONE;
88use ffmpeg_sys_next::{
89    av_get_pix_fmt, av_image_get_buffer_size, av_pix_fmt_desc_get, AVPixelFormat,
90    AV_PIX_FMT_FLAG_HWACCEL,
91};
92
93use crate::core::context::ffmpeg_context::build_writer_context;
94use crate::core::context::frame_source::FrameSourceParams;
95use crate::core::context::output::Output;
96use crate::core::scheduler::ffmpeg_scheduler::{is_stopping, FfmpegScheduler, Running};
97use crate::error::OpenOutputError;
98
99/// Ingress memory budget used to derive the default queue depth.
100const QUEUE_BUDGET_BYTES: usize = 64 * 1024 * 1024;
101
102/// How long `write` parks on a full queue before re-checking the pipeline
103/// status. Backpressure, not a busy loop: the crossbeam fast path returns
104/// immediately when there is room.
105const SEND_POLL: Duration = Duration::from_millis(100);
106
107/// Errors raised while validating a [`VideoWriterBuilder`] or opening its
108/// pipeline. Reachable through [`crate::error::Error::Writer`]; it is exported
109/// from [`crate::error`] rather than the crate root to keep the root surface to
110/// the three settled writer types.
111#[non_exhaustive]
112#[derive(Debug, thiserror::Error)]
113pub enum WriterError {
114    /// Width or height is zero or exceeds `i32::MAX`.
115    #[error("invalid dimensions {width}x{height}")]
116    InvalidDimensions { width: u32, height: u32 },
117
118    /// The pixel-format name is not known to `av_get_pix_fmt`.
119    #[error("unknown pixel format '{0}'")]
120    UnknownPixelFormat(String),
121
122    /// A hardware pixel format (e.g. `cuda`, `vaapi`) cannot be filled from a
123    /// CPU byte buffer.
124    #[error("hardware pixel format '{0}' cannot be pushed from CPU memory")]
125    HardwarePixelFormat(String),
126
127    /// `fps(num, den)` had a non-positive component.
128    #[error("invalid fps {num}/{den}: both must be positive")]
129    InvalidFps { num: i32, den: i32 },
130
131    /// `queue_capacity(0)` was requested.
132    #[error("queue_capacity must be >= 1")]
133    ZeroQueueCapacity,
134
135    /// The built pipeline consumes no video from the pushed frames (a
136    /// `disable_video()` output). Without this check `write` would block
137    /// forever against a live-but-unconsumed receiver.
138    #[error("output consumes no video stream from the pushed frames")]
139    NoVideoDestination,
140
141    /// The `filter_desc` graph does not consume exactly one video input and
142    /// produce exactly one video output. A second input pad would have no
143    /// producer (the pipeline would buffer forever waiting for it) and a
144    /// second output pad would have no destination.
145    #[error(
146        "filter_desc must have exactly one video input pad and one video \
147         output pad; found {input_pads} input pad(s) ({video_input_pads} \
148         video) and {output_pads} output pad(s) ({video_output_pads} video)"
149    )]
150    FilterShape {
151        input_pads: usize,
152        video_input_pads: usize,
153        output_pads: usize,
154        video_output_pads: usize,
155    },
156
157    /// The `filter_desc` parses into more than one disconnected filter
158    /// component (e.g. `"nullsink;color=..."`). The pushed frames would feed
159    /// one part while an unrelated part feeds (or starves) the encoder — an
160    /// unbounded side source could even keep the job from ever finishing.
161    #[error("filter_desc must be a single connected graph; found {components} disconnected parts")]
162    DisconnectedFilterGraph { components: usize },
163
164    /// The `filter_desc` is connected, but no directed path leads from its
165    /// input pad to its output pad (e.g.
166    /// `"color,split[out][aux];[aux][in]overlay,nullsink"`): the pushed
167    /// frames drain into a sink while an unrelated branch feeds the encoder,
168    /// so they could never influence the encoded output — and an unbounded
169    /// side source would keep the job from ever finishing.
170    ///
171    /// This check works at FILTER granularity: it follows links between
172    /// filters, not streams within a filter. A filter that internally routes
173    /// distinct streams between pad pairs (multi-stream `concat` is the
174    /// notable case) can therefore pass it while still steering the pushed
175    /// frames into a sink leg — libavfilter exposes no static per-pad
176    /// dataflow to validate against. Such a graph has to be constructed
177    /// deliberately and stands on the same footing as any other
178    /// `filter_desc` whose declared routing is what runs.
179    #[error(
180        "filter_desc has no directed path from its input pad to its output \
181         pad; the pushed frames could not influence the encoded output"
182    )]
183    UnreachableFilterOutput,
184
185    /// The [`Output`] carries stream maps (`add_stream_map` /
186    /// `add_stream_map_with_copy`). The writer's single video stream is the
187    /// only stream there is, so maps have nothing to select; rejecting them
188    /// beats silently ignoring them.
189    #[error("stream maps are not supported by VideoWriter; the pushed frames are the only stream")]
190    StreamMapsUnsupported,
191}
192
193/// Errors returned by [`VideoWriter::write`] / [`VideoWriter::write_owned`].
194#[non_exhaustive]
195#[derive(Debug, thiserror::Error)]
196pub enum PushError {
197    /// The frame was not exactly [`VideoWriter::frame_size`] bytes.
198    #[error("frame has {got} bytes, expected exactly {expected} (tightly packed)")]
199    InvalidSize { expected: usize, got: usize },
200
201    /// The pipeline stopped accepting frames (a worker failed, an [`Output`]
202    /// limit such as `set_max_video_frames` completed the job early, or
203    /// teardown began). Call [`VideoWriter::finish`] for the authoritative
204    /// result: the underlying error if one occurred, or `Ok` when the
205    /// pipeline closed after completing normally.
206    #[error("pipeline closed; call finish() to retrieve the pipeline result")]
207    PipelineClosed,
208}
209
210/// Pushes raw video frames from Rust code into a full FFmpeg pipeline. See the
211/// [module documentation](self) for the frame contract and teardown semantics.
212///
213/// **Experimental:** new in 0.14; the surface may still be refined.
214pub struct VideoWriter {
215    /// `None` once ingress is closed by `finish`/`abort`/`Drop`.
216    sender: Option<Sender<Vec<u8>>>,
217    /// `None` once consumed by `finish`/`abort`, so `Drop` is a no-op afterward.
218    scheduler: Option<FfmpegScheduler<Running>>,
219    frame_size: usize,
220    /// The scheduler status atomic, polled by `write` to fail fast when the
221    /// pipeline is stopping rather than blocking on a full queue forever.
222    status: Arc<AtomicUsize>,
223}
224
225// Send: a writer can move to a dedicated producer thread. Not Sync: `write`
226// takes `&mut self`, which already forbids concurrent producers.
227impl VideoWriter {
228    /// Starts a builder. Width and height are positional so they cannot be
229    /// forgotten.
230    pub fn builder(width: u32, height: u32) -> VideoWriterBuilder {
231        VideoWriterBuilder::new(width, height)
232    }
233
234    /// Exact number of bytes one frame must contain:
235    /// `av_image_get_buffer_size(pix_fmt, width, height, 1)` (tight packing).
236    pub fn frame_size(&self) -> usize {
237        self.frame_size
238    }
239
240    /// Pushes one frame, copying the borrowed slice into an owned buffer.
241    /// Blocks while the internal queue is full (backpressure).
242    pub fn write(&mut self, frame: &[u8]) -> Result<(), PushError> {
243        if frame.len() != self.frame_size {
244            return Err(PushError::InvalidSize {
245                expected: self.frame_size,
246                got: frame.len(),
247            });
248        }
249        self.enqueue(frame.to_vec())
250    }
251
252    /// Pushes one owned frame; the `Vec` is moved into the pipeline, saving
253    /// the borrow-copy that [`write`](Self::write) performs. The pipeline
254    /// still copies the bytes once, plane-by-plane, into an aligned `AVFrame`
255    /// on the worker thread. `frame.len()` must equal
256    /// [`frame_size`](Self::frame_size); the `Vec` is queued as-is, so any
257    /// spare `capacity` beyond its length stays allocated while it waits.
258    pub fn write_owned(&mut self, frame: Vec<u8>) -> Result<(), PushError> {
259        if frame.len() != self.frame_size {
260            return Err(PushError::InvalidSize {
261                expected: self.frame_size,
262                got: frame.len(),
263            });
264        }
265        self.enqueue(frame)
266    }
267
268    fn enqueue(&mut self, frame: Vec<u8>) -> Result<(), PushError> {
269        // Check the terminal state before sending: probing it only after a send
270        // timeout could still admit one frame in the window between the
271        // terminal publish and the queue draining.
272        if is_stopping(self.status.load(Ordering::Acquire)) {
273            return Err(PushError::PipelineClosed);
274        }
275        let sender = match &self.sender {
276            Some(sender) => sender,
277            None => return Err(PushError::PipelineClosed),
278        };
279        let mut msg = frame;
280        loop {
281            match sender.send_timeout(msg, SEND_POLL) {
282                Ok(()) => return Ok(()),
283                Err(SendTimeoutError::Timeout(returned)) => {
284                    // Full queue = backpressure. Re-check status so a pipeline
285                    // that dies while we are parked wakes us instead of hanging.
286                    if is_stopping(self.status.load(Ordering::Acquire)) {
287                        return Err(PushError::PipelineClosed);
288                    }
289                    msg = returned;
290                }
291                Err(SendTimeoutError::Disconnected(_)) => return Err(PushError::PipelineClosed),
292            }
293        }
294    }
295
296    /// Closes ingress (the frame source emits its end-of-stream marker),
297    /// drains the encoder, finalizes the container, and returns the first
298    /// authoritative pipeline error. This is the result path — a `write` that
299    /// returned [`PushError::PipelineClosed`] resolves here, either to the
300    /// real cause or to `Ok` when the pipeline closed after completing
301    /// normally (e.g. an [`Output`] frame limit was reached).
302    pub fn finish(mut self) -> crate::error::Result<()> {
303        self.sender = None; // drop the sender → the frame source observes EOF
304        match self.scheduler.take() {
305            Some(scheduler) => scheduler.wait(),
306            None => Ok(()),
307        }
308    }
309
310    /// Discards the export: drops ingress, then hard-aborts the scheduler. For
311    /// "user cancelled" flows where the output is not wanted.
312    ///
313    /// Caveat: `abort()` blocks until every worker releases its slot (no fixed
314    /// time bound) and may skip the encoder flush / muxer trailer, so the
315    /// partial file is not guaranteed playable. Use [`finish`](Self::finish) to
316    /// finalize.
317    pub fn abort(mut self) {
318        self.sender = None;
319        if let Some(scheduler) = self.scheduler.take() {
320            scheduler.abort();
321        }
322    }
323}
324
325impl Drop for VideoWriter {
326    fn drop(&mut self) {
327        // Close ingress first, then wait: the dropped sender is what lets the
328        // frame source emit EOF and exit, so the worker join can complete.
329        self.sender = None;
330        if let Some(scheduler) = self.scheduler.take() {
331            if let Err(e) = scheduler.wait() {
332                log::error!("VideoWriter dropped without finish(); pipeline error: {e}");
333            }
334        }
335    }
336}
337
338/// Builder for a [`VideoWriter`]. Required parameters (width, height) are
339/// positional; everything else has a default.
340pub struct VideoWriterBuilder {
341    width: u32,
342    height: u32,
343    pixel_format: String,
344    fps_num: i32,
345    fps_den: i32,
346    queue_capacity: Option<usize>,
347    filter_desc: Option<String>,
348}
349
350impl VideoWriterBuilder {
351    fn new(width: u32, height: u32) -> Self {
352        Self {
353            width,
354            height,
355            pixel_format: "rgba".to_string(),
356            fps_num: 30,
357            fps_den: 1,
358            queue_capacity: None,
359            filter_desc: None,
360        }
361    }
362
363    /// Any non-hardware `AVPixelFormat` name (`av_get_pix_fmt`). Default:
364    /// `"rgba"`. Frames are tightly packed, planes concatenated in descriptor
365    /// order (e.g. `yuv420p` = Y then U then V).
366    pub fn pixel_format(mut self, fmt: impl Into<String>) -> Self {
367        self.pixel_format = fmt.into();
368        self
369    }
370
371    /// Frame rate as `num/den`. Default `(30, 1)`; NTSC rates like
372    /// `fps(30000, 1001)` are supported. Every written frame advances exactly
373    /// `den/num` seconds.
374    pub fn fps(mut self, num: i32, den: i32) -> Self {
375        self.fps_num = num;
376        self.fps_den = den;
377        self
378    }
379
380    /// Queue depth in frames. Default: `max(1, min(4, 64 MiB / frame_size))`, so
381    /// large frames do not silently reserve a lot of memory. The queue is
382    /// count-bounded: with [`write`](VideoWriter::write) each slot holds an
383    /// exact `frame_size` copy (`capacity × frame_size` bytes total); with
384    /// [`write_owned`](VideoWriter::write_owned) each slot holds the caller's
385    /// `Vec` as provided, including any spare capacity it carries.
386    pub fn queue_capacity(mut self, frames: usize) -> Self {
387        self.queue_capacity = Some(frames);
388        self
389    }
390
391    /// Optional FFmpeg filter chain between the pushed frames and the encoder,
392    /// e.g. `"hue=s=0"` or `"pad=ceil(iw/2)*2:ceil(ih/2)*2"` (an odd-size
393    /// remedy). Must be a single connected graph
394    /// ([`WriterError::DisconnectedFilterGraph`] otherwise) consuming exactly
395    /// one video input and producing exactly one video output
396    /// ([`WriterError::FilterShape`] otherwise), with the output downstream
397    /// of the input ([`WriterError::UnreachableFilterOutput`] otherwise).
398    ///
399    /// Generator filters embedded in the graph (`color`, `testsrc`, …) are
400    /// allowed as long as the pushed frames still reach the output — e.g.
401    /// compositing over a generated background with
402    /// `"color=...[bg];[in][bg]overlay=shortest=1"`. The same rules as the
403    /// FFmpeg CLI apply: a graph built to outlive the pushed stream (an
404    /// `overlay` without `shortest=1`, a `concat` onto an unbounded
405    /// generator) keeps running after [`finish`](VideoWriter::finish) closes
406    /// the input, until the generator ends or the job is aborted — that is
407    /// the semantics asked for, not a writer malfunction.
408    ///
409    /// The validation is best-effort at filter granularity (see
410    /// [`WriterError::UnreachableFilterOutput`]): a description that
411    /// deliberately routes the pushed stream into a sink through a
412    /// stream-routing filter (multi-stream `concat`, …) runs exactly as
413    /// declared, like it would in the CLI.
414    pub fn filter_desc(mut self, desc: impl Into<String>) -> Self {
415        self.filter_desc = Some(desc.into());
416        self
417    }
418
419    /// Builds the pipeline and starts it, returning without waiting for the
420    /// first frame. `output` carries the [`Output`] capabilities that make
421    /// sense for a single pushed video stream: codec, codec options, format,
422    /// format options (`movflags`…), write/seek callbacks, frame pipelines
423    /// (wgpu…), bitrate, qscale, frame limits. Stream maps are the exception
424    /// and are rejected ([`WriterError::StreamMapsUnsupported`]) — there is
425    /// only one stream to map. A format that cannot actually carry the video
426    /// stream is not second-guessed at build time: it surfaces as a pipeline
427    /// error from [`finish`](VideoWriter::finish), like any other muxer
428    /// failure.
429    pub fn open(self, output: impl Into<Output>) -> crate::error::Result<VideoWriter> {
430        if self.width == 0
431            || self.height == 0
432            || self.width > i32::MAX as u32
433            || self.height > i32::MAX as u32
434        {
435            return Err(WriterError::InvalidDimensions {
436                width: self.width,
437                height: self.height,
438            }
439            .into());
440        }
441        if self.fps_num <= 0 || self.fps_den <= 0 {
442            return Err(WriterError::InvalidFps {
443                num: self.fps_num,
444                den: self.fps_den,
445            }
446            .into());
447        }
448        let (pix_fmt, frame_size) =
449            resolve_source_format(&self.pixel_format, self.width, self.height)?;
450        let queue_capacity = match self.queue_capacity {
451            Some(0) => return Err(WriterError::ZeroQueueCapacity.into()),
452            Some(n) => n,
453            None => adaptive_capacity(frame_size),
454        };
455
456        let params = FrameSourceParams {
457            width: self.width as i32,
458            height: self.height as i32,
459            pix_fmt,
460            fps_num: self.fps_num,
461            fps_den: self.fps_den,
462        };
463
464        let (ctx, sender) = match build_writer_context(
465            params,
466            queue_capacity,
467            self.filter_desc.as_deref(),
468            output.into(),
469        ) {
470            Ok(built) => built,
471            // disable_video()/streamless output: the build detects that the
472            // pushed frames have no destination. Translate to the
473            // writer-facing cause.
474            Err(crate::error::Error::OpenOutput(OpenOutputError::NotContainStream)) => {
475                return Err(WriterError::NoVideoDestination.into());
476            }
477            Err(e) => return Err(e),
478        };
479
480        // Clone the status before the context moves into the scheduler; new()
481        // clones the same Arc internally, so no accessor is needed.
482        let status = ctx.scheduler_status.clone();
483        let scheduler = FfmpegScheduler::new(ctx);
484        let scheduler = scheduler.start()?;
485
486        Ok(VideoWriter {
487            sender: Some(sender),
488            scheduler: Some(scheduler),
489            frame_size,
490            status,
491        })
492    }
493}
494
495/// Default queue depth: cap the ingress buffer at `QUEUE_BUDGET_BYTES` while
496/// keeping at least one and at most four frames. `frame_size >= 1` is
497/// guaranteed by the caller, so the division never traps.
498fn adaptive_capacity(frame_size: usize) -> usize {
499    (QUEUE_BUDGET_BYTES / frame_size).clamp(1, 4)
500}
501
502/// Resolves and validates the pixel format plus the tightly-packed frame size
503/// for it at `width`x`height`. Rejects unknown and hardware formats.
504/// `width`/`height` are already known positive and `<= i32::MAX`.
505fn resolve_source_format(
506    pixel_format: &str,
507    width: u32,
508    height: u32,
509) -> Result<(AVPixelFormat, usize), WriterError> {
510    let cstr = CString::new(pixel_format)
511        .map_err(|_| WriterError::UnknownPixelFormat(pixel_format.to_string()))?;
512    // SAFETY: `cstr` is a valid NUL-terminated string for the duration of the
513    // call; av_get_pix_fmt only reads it.
514    let pix_fmt = unsafe { av_get_pix_fmt(cstr.as_ptr()) };
515    if pix_fmt == AV_PIX_FMT_NONE {
516        return Err(WriterError::UnknownPixelFormat(pixel_format.to_string()));
517    }
518    // SAFETY: pix_fmt is a valid, non-NONE format; av_pix_fmt_desc_get returns a
519    // static descriptor or null.
520    let desc = unsafe { av_pix_fmt_desc_get(pix_fmt) };
521    if !desc.is_null() && unsafe { (*desc).flags } & (AV_PIX_FMT_FLAG_HWACCEL as u64) != 0 {
522        return Err(WriterError::HardwarePixelFormat(pixel_format.to_string()));
523    }
524    // SAFETY: pix_fmt is valid; dimensions are within i32 range.
525    let size = unsafe { av_image_get_buffer_size(pix_fmt, width as i32, height as i32, 1) };
526    if size <= 0 {
527        return Err(WriterError::UnknownPixelFormat(pixel_format.to_string()));
528    }
529    Ok((pix_fmt, size as usize))
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535
536    fn frame_size_of(fmt: &str, w: u32, h: u32) -> Result<usize, WriterError> {
537        resolve_source_format(fmt, w, h).map(|(_, size)| size)
538    }
539
540    #[test]
541    fn frame_size_matches_ffmpeg_for_common_formats() {
542        // rgba/rgb24/gray8: exact, no padding.
543        assert_eq!(frame_size_of("rgba", 64, 48).unwrap(), 64 * 48 * 4);
544        assert_eq!(frame_size_of("rgb24", 64, 48).unwrap(), 64 * 48 * 3);
545        assert_eq!(frame_size_of("gray8", 64, 48).unwrap(), 64 * 48);
546        // yuv420p: Y + U/4 + V/4 = w*h*3/2 for even dimensions.
547        assert_eq!(frame_size_of("yuv420p", 64, 48).unwrap(), 64 * 48 * 3 / 2);
548        // nv12: same total as yuv420p.
549        assert_eq!(frame_size_of("nv12", 64, 48).unwrap(), 64 * 48 * 3 / 2);
550    }
551
552    #[test]
553    fn yuv420p_odd_height_rounds_chroma_up() {
554        // Odd height: chroma planes use ceil(h/2). 64x49: Y=64*49, each chroma
555        // plane = 32*25, total = 64*49 + 2*(32*25).
556        let expected = 64 * 49 + 2 * (32 * 25);
557        assert_eq!(frame_size_of("yuv420p", 64, 49).unwrap(), expected);
558    }
559
560    #[test]
561    fn unknown_pixel_format_is_rejected() {
562        assert!(matches!(
563            frame_size_of("definitely_not_a_format", 16, 16),
564            Err(WriterError::UnknownPixelFormat(_))
565        ));
566    }
567
568    #[test]
569    fn hardware_pixel_format_is_rejected() {
570        // cuda is a hwaccel format when the build knows it; if av_get_pix_fmt
571        // does not recognize it, UnknownPixelFormat is the honest answer. Either
572        // way it must not be accepted as a CPU push format.
573        assert!(matches!(
574            frame_size_of("cuda", 16, 16),
575            Err(WriterError::HardwarePixelFormat(_)) | Err(WriterError::UnknownPixelFormat(_))
576        ));
577    }
578
579    #[test]
580    fn adaptive_capacity_scales_with_frame_size() {
581        // Small frame: capped at 4.
582        assert_eq!(adaptive_capacity(1), 4);
583        assert_eq!(adaptive_capacity(1024), 4);
584        // 1080p rgba (~7.9 MiB): 64 MiB / 7.9 MiB = 8 → clamped to 4.
585        assert_eq!(adaptive_capacity(1920 * 1080 * 4), 4);
586        // 4K rgba (~31.6 MiB): floor(64 / 31.6) = 2.
587        assert_eq!(adaptive_capacity(3840 * 2160 * 4), 2);
588        // Frame larger than the whole budget: at least 1.
589        assert_eq!(adaptive_capacity(QUEUE_BUDGET_BYTES * 2), 1);
590    }
591
592    #[test]
593    fn invalid_dimensions_and_fps_are_rejected_at_open() {
594        use crate::Output;
595        let out = || Output::from("/dev/null").set_video_codec("mpeg4");
596        assert!(matches!(
597            VideoWriter::builder(0, 48).open(out()),
598            Err(crate::error::Error::Writer(
599                WriterError::InvalidDimensions { .. }
600            ))
601        ));
602        assert!(matches!(
603            VideoWriter::builder(64, 48).fps(0, 1).open(out()),
604            Err(crate::error::Error::Writer(WriterError::InvalidFps { .. }))
605        ));
606        assert!(matches!(
607            VideoWriter::builder(64, 48).queue_capacity(0).open(out()),
608            Err(crate::error::Error::Writer(WriterError::ZeroQueueCapacity))
609        ));
610        assert!(matches!(
611            VideoWriter::builder(64, 48)
612                .pixel_format("nope")
613                .open(out()),
614            Err(crate::error::Error::Writer(
615                WriterError::UnknownPixelFormat(_)
616            ))
617        ));
618    }
619
620    /// Compile-time proof that `?` composes across `write` and `finish` in a
621    /// function returning `crate::error::Result` (the `From<PushError>` /
622    /// `From<WriterError>` conversions exist).
623    #[allow(dead_code)]
624    fn error_composition(writer: &mut VideoWriter, frame: &[u8]) -> crate::error::Result<()> {
625        writer.write(frame)?;
626        Ok(())
627    }
628
629    #[test]
630    fn push_error_display_reports_sizes() {
631        let e = PushError::InvalidSize {
632            expected: 12288,
633            got: 100,
634        };
635        assert!(e.to_string().contains("12288"));
636        assert!(e.to_string().contains("100"));
637    }
638
639    /// Teardown liveness with the producer still alive: the frame-source
640    /// worker sits in no wake set, so scheduler teardown must reach it purely
641    /// through its 100 ms status polls. Drop the running scheduler (or
642    /// abort()) while the ingress sender is still held and no EOF was ever
643    /// signalled — the RunningGuard's join must complete anyway. A regression
644    /// here (e.g. an untimed recv) hangs, so the join runs under a watchdog.
645    #[test]
646    fn scheduler_teardown_completes_with_live_ingress_sender() {
647        use crate::core::context::ffmpeg_context::build_writer_context;
648        use ffmpeg_sys_next::AVPixelFormat::AV_PIX_FMT_RGBA;
649
650        for (label, abort) in [("drop", false), ("abort", true)] {
651            let out = std::env::temp_dir().join(format!(
652                "ez_ffmpeg_writer_sender_held_{label}_{}.mp4",
653                std::process::id()
654            ));
655            let params = FrameSourceParams {
656                width: 64,
657                height: 48,
658                pix_fmt: AV_PIX_FMT_RGBA,
659                fps_num: 30,
660                fps_den: 1,
661            };
662            let (ctx, sender) = build_writer_context(
663                params,
664                2,
665                None,
666                Output::from(out.to_str().unwrap()).set_video_codec("mpeg4"),
667            )
668            .expect("writer context");
669            let scheduler = FfmpegScheduler::new(ctx).start().expect("start");
670            // Put the worker mid-stream so it holds a pooled frame path, not
671            // just an idle recv.
672            sender
673                .send(vec![0u8; 64 * 48 * 4])
674                .expect("worker must be consuming");
675
676            let (tx, rx) = std::sync::mpsc::channel();
677            std::thread::spawn(move || {
678                if abort {
679                    scheduler.abort();
680                } else {
681                    drop(scheduler);
682                }
683                let _ = tx.send(());
684            });
685            // Hang-detection watchdog, generous for loaded machines: the
686            // property is that teardown completes at all, not how fast.
687            rx.recv_timeout(Duration::from_secs(30))
688                .unwrap_or_else(|_| panic!("{label}: teardown hung with a live ingress sender"));
689            drop(sender);
690        }
691    }
692}