Skip to main content

mediadecode_ffmpeg/
carrier.rs

1//! The carrier-strategy seam: which lane a demuxer or decoder captures
2//! into.
3//!
4//! This crate ships **two first-class carriers**, and neither is a
5//! feature flag on the other:
6//!
7//! * [`Owned`] captures into [`FfmpegBytes`](crate::FfmpegBytes) — every
8//!   byte copied once at the boundary into memory Rust owns. `Send +
9//!   Sync`, lifetime answerable to nobody, safe to fan out across a
10//!   graph. This is the default, and the lane the
11//!   [amputation contract][law] governs.
12//! * [`View`] captures into [`FfmpegBuffer`](crate::FfmpegBuffer) — a
13//!   refcounted view onto the allocation FFmpeg already made. `Send`
14//!   and **not** `Sync`, lifetime pinned to the backend's pools,
15//!   zero-copy.
16//!
17//! # Why a sealed seam and not an open trait
18//!
19//! A carrier strategy is not an extension point. Implementing one
20//! correctly means knowing what an `AVBufferRef` guarantees, which
21//! plane extents are initialised, and which of this crate's proofs run
22//! before a capture is allowed to happen — knowledge that lives in this
23//! crate and cannot be documented into a third party. A third strategy
24//! would also have to answer the questions this seam does not ask,
25//! because only two lanes exist to ask them of.
26//!
27//! So the trait is **sealed**: public to name and to bound on, closed
28//! to implement. If a third lane is ever wanted, it is added here,
29//! where it can be held to the same proofs — the seam being closed is
30//! what makes that a change to one file rather than a change to a
31//! contract.
32//!
33//! # Why the operations are not public either
34//!
35//! Sealing stopped outsiders *implementing* the seam. It did not stop
36//! them *calling* it, and for a while that was a hole with teeth: the
37//! operations take offsets, lengths and row geometry which the unsafe
38//! layer beneath them acts on, so their invariants live in the caller.
39//! `View::from_rows(1, 64, |_| &[0])` was safe code, compiled, and
40//! copied sixty-four bytes out of a one-byte slice.
41//!
42//! Two answers, applied together:
43//!
44//! * every operation moved onto the private supertrait in
45//!   [`sealed`], which no path outside this crate can name and
46//!   therefore no call outside this crate can reach. What stays public
47//!   is the *name* of a lane and the ability to bound on it — which is
48//!   all a consumer ever needed;
49//! * and where a length still arrives from a caller, it is **checked**
50//!   rather than asserted. A `debug_assert` is a note to the author; it
51//!   is not a bounds check, and it is not there at all in the profile
52//!   that matters.
53//!
54//! The rule the two share: an invariant that lives in the caller is an
55//! invariant the caller must be inside this crate to be trusted with.
56//!
57//! # Where the bound sits
58//!
59//! At the narrowest site each one can be written at, and no wider:
60//!
61//! * **Structural** on the types whose *fields* name `C::Buffer` —
62//!   [`CarrierDemuxer`](crate::demuxer::CarrierDemuxer) holds built
63//!   tracks, [`CarrierResampler`](crate::resampler::CarrierResampler)
64//!   holds a queue of frames. A struct whose field type is a projection
65//!   cannot be well-formed without the bound that gives the projection
66//!   meaning, so writing it there is not a choice.
67//! * **Behavioural** on the decoders, which carry `C` only as a
68//!   `PhantomData` marker: their struct declarations take a bare `C`
69//!   and the bound sits on the impls whose methods capture.
70//! * **Absent** from `*Extra`, `SideDataEntry` and every side-data
71//!   collector. Side data has no `AVBufferRef` to share, so both lanes
72//!   copy it and the parameter never reaches those types at all.
73//!
74//! The lanes are then named by alias rather than by a defaulted type
75//! parameter, because a default is used when a type is *written* and
76//! never inferred from a call — `Demuxer::open(path)` would have had no
77//! default to fall back on.
78//!
79//! [law]: mediadecode::adapter#the-d-seat-amputation-contract
80
81use ffmpeg_next::ffi::AVBufferRef;
82
83use crate::{FfmpegBytes, view::FfmpegBuffer};
84
85pub(crate) use ops::{BodyRoute, CarrierOps};
86
87pub(crate) mod sealed {
88  /// Closes [`super::FfmpegCarrier`] to outside implementations, and
89  /// **carries nothing**.
90  ///
91  /// An earlier round put the operations here, reasoning that a trait
92  /// no outside path can name is a trait no outside call can reach.
93  /// That was wrong in a way worth recording: associated items resolve
94  /// through a *bound*, not through a path, so downstream code written
95  /// as `fn f<C: FfmpegCarrier>()` type-checked `C::capture(..)` and
96  /// `C::from_rows(..)` perfectly well — the seal stopped
97  /// implementations and nothing else. The operations now live on
98  /// [`CarrierOps`](super::CarrierOps), which is **not** a supertrait
99  /// of anything public, so no bound a downstream crate can write
100  /// reaches them.
101  pub trait Sealed {}
102}
103
104pub(crate) mod ops {
105  use ffmpeg_next::ffi::AVBufferRef;
106
107  /// Which body a rebuilt `AVPacket` gets.
108  ///
109  /// The distinction exists because the two roads have different
110  /// exposure. A packet a caller is *handed* is a public
111  /// `ffmpeg_next::Packet`, and that type can lend `&mut [u8]` — so its
112  /// body must be storage nobody else can read, which means a copy on
113  /// either lane. A packet built to be **submitted and dropped** inside
114  /// one crate-private call never escapes to anywhere a `&mut` can be
115  /// taken from it, so the view lane may share there.
116  #[derive(Debug, Clone, Copy, PartialEq, Eq)]
117  pub enum BodyRoute {
118    /// The body is copied into storage the packet alone owns.
119    Copy,
120    /// The body may share the carrier's buffer, if this lane can prove
121    /// that is safe for a decoder to read. Only ever asked for from a
122    /// scoped submission.
123    Submission,
124  }
125
126  /// Every operation a lane performs — and the reason none of them is
127  /// reachable from outside this crate.
128  ///
129  /// This trait is deliberately **not** a supertrait of
130  /// [`FfmpegCarrier`](super::FfmpegCarrier). A supertrait would put
131  /// its items in scope for any bound that names the subtrait, and
132  /// `fn f<C: FfmpegCarrier>()` written in a downstream crate would
133  /// then type-check `C::from_rows(1, 64, |_| &[0])` — safe code, an
134  /// out-of-bounds read, in somebody else's crate. Sealing prevents
135  /// implementing; only an unreachable *bound* prevents calling.
136  ///
137  /// So the two are joined nowhere: `FfmpegCarrier` names a lane and
138  /// says what it carries, this says what it can do, and the functions
139  /// in this crate that need the second ask for it by a name no
140  /// downstream crate can write.
141  pub trait CarrierOps: super::FfmpegCarrier {
142    /// A carrier over no bytes.
143    ///
144    /// Allocation-free on both lanes; it is what an unpopulated plane
145    /// slot holds, and eight per frame is not a place to put a
146    /// failure mode.
147    fn empty() -> Self::Buffer;
148
149    /// A carrier over bytes that live outside any `AVBufferRef`.
150    ///
151    /// Subtitle rect text and a rect's own palette are plain
152    /// allocations with no refcount to share, so **both** lanes copy
153    /// here. The view lane says so rather than implying its whole road
154    /// is zero-copy.
155    ///
156    /// `None` when the copy cannot be allocated. Fallible on both lanes
157    /// so that neither can answer an allocation failure with an empty
158    /// carrier — a plane that silently became zero bytes is a frame
159    /// whose header is a lie.
160    fn from_bytes(bytes: &[u8]) -> Option<Self::Buffer>;
161
162    /// A carrier over `len` bytes at `offset` inside the live
163    /// `AVBufferRef` `buf`.
164    ///
165    /// The owned lane copies them out; the view lane takes a reference.
166    /// Either way the caller has already proved the extent lies inside
167    /// the buffer — this is the capture, not the judgement.
168    ///
169    /// Nothing may be assumed about the bytes **after** the captured
170    /// range: this is the road frame planes and palettes take. See
171    /// [`Self::capture_packet_payload`] for the one that may.
172    ///
173    /// `None` when the capture itself fails: an allocation on the owned
174    /// lane, a refcount on the view lane.
175    ///
176    /// # Safety
177    ///
178    /// `buf` must be a live `AVBufferRef`, and `offset + len` must be
179    /// within its `size`.
180    unsafe fn capture(buf: *mut AVBufferRef, offset: usize, len: usize) -> Option<Self::Buffer>;
181
182    /// [`Self::capture`] for a payload taken out of an `AVPacket`'s own
183    /// buffer.
184    ///
185    /// The only difference is what the carrier records about itself:
186    /// libavformat allocates `AV_INPUT_BUFFER_PADDING_SIZE` zeroed
187    /// bytes behind every packet it produces, and this is the one
188    /// capture that may claim them. That claim is what the send leg
189    /// checks before it shares anything with a decoder.
190    ///
191    /// # Safety
192    ///
193    /// As [`Self::capture`], and `buf` must be the buffer of an
194    /// `AVPacket` whose payload this range is.
195    unsafe fn capture_packet_payload(
196      buf: *mut AVBufferRef,
197      offset: usize,
198      len: usize,
199    ) -> Option<Self::Buffer>;
200
201    /// A carrier over `rows` runs of `row_bytes`, gathered from a
202    /// **padded** plane.
203    ///
204    /// Copied on **both** lanes, and this is the one place the view
205    /// lane cannot share on principle rather than on plumbing. A padded
206    /// plane is `linesize` wide and only its first `row_bytes` per row
207    /// are the decoder's output; the rest is allocator scratch that
208    /// nothing wrote. A carrier is an `AsRef<[u8]>`, so sharing the
209    /// padded span would form a slice over uninitialised memory —
210    /// undefined before a consumer reads a byte of it, and the same
211    /// information leak the owned lane refused when it stopped
212    /// exporting `linesize`.
213    ///
214    /// So a padded plane is compacted, on either lane, and arrives with
215    /// `row_bytes` as its stride. `None` when the gather cannot be
216    /// allocated, or when a row is not exactly `row_bytes` wide.
217    fn from_rows<'a>(
218      rows: usize,
219      row_bytes: usize,
220      row: impl FnMut(usize) -> &'a [u8],
221    ) -> Option<Self::Buffer>;
222
223    /// A capture claimed **before** the bytes exist, whose length is
224    /// settled after they do. See [`Self::reserve`].
225    type Reserved;
226
227    /// Claims `cap` bytes at `offset` inside `buf`, without reading
228    /// them.
229    ///
230    /// For a producer that allocates its own output frame and then
231    /// hands it to FFmpeg to fill — the resampler — this is what keeps
232    /// every fallible step on the *near* side of the conversion. `swr`
233    /// consumes its input as it runs, so a failure after it has run
234    /// leaves a session no caller can retry; reserving first and
235    /// committing after means the only thing left to do once the bytes
236    /// are there is name how many of them are real.
237    ///
238    /// The view lane takes its reference here — the refcount is what
239    /// can fail, and it fails before anything is consumed. The owned
240    /// lane reserves nothing and copies at [`Self::commit`], because
241    /// copying uninitialised capacity is exactly the read this crate
242    /// refuses everywhere else.
243    ///
244    /// # Safety
245    ///
246    /// `buf` must be a live `AVBufferRef`, `offset + cap` must be
247    /// within its `size`, and the buffer must stay alive until the
248    /// matching [`Self::commit`].
249    unsafe fn reserve(buf: *mut AVBufferRef, offset: usize, cap: usize) -> Option<Self::Reserved>;
250
251    /// Settles a [`Self::reserve`] at its true length. Infallible.
252    ///
253    /// # Safety
254    ///
255    /// `len` must be at most the `cap` the reservation was taken with,
256    /// those `len` bytes must now be initialised, and the buffer must
257    /// still be alive.
258    unsafe fn commit(reserved: Self::Reserved, len: usize) -> Self::Buffer;
259
260    /// Builds the body of an `AVPacket` on the way **into** a decoder.
261    ///
262    /// [`BodyRoute::Copy`] always copies, on either lane. Only
263    /// [`BodyRoute::Submission`] lets the view lane share, and only
264    /// where it can prove a decoder may read past the payload — see
265    /// `boundary::share_or_copy`.
266    ///
267    /// This is why the reverse builders are one family rather than
268    /// two: every judgement they make — the `TRUSTED` refusal, the
269    /// side-data caps, the send budget — is about sizes and shapes,
270    /// which are the same on both lanes. Only the body differs, and
271    /// only here.
272    fn packet_body(
273      body: &Self::Buffer,
274      route: BodyRoute,
275    ) -> std::result::Result<ffmpeg_next::Packet, ffmpeg_next::Error>;
276  }
277}
278
279/// How a lane turns FFmpeg's bytes into a carrier.
280///
281/// **Sealed, and almost empty by design.** Naming a lane, bounding on
282/// one, and asking what it carries are public; performing a capture is
283/// not. Every operation lives on a private trait that is *not* a
284/// supertrait of this one — see the [module docs](self) for why that
285/// distinction is the whole of the wall.
286///
287/// What a downstream crate can do — name a lane, hold the types
288/// parameterized by one, be generic over it, and drive either:
289///
290/// ```
291/// use mediadecode_ffmpeg::{FfmpegBuffer, FfmpegBytes, FfmpegCarrier, Owned, View};
292///
293/// // Name what a lane carries, and be generic over the lane.
294/// fn carried<C: FfmpegCarrier>(buffer: &C::Buffer) -> usize {
295///   buffer.as_ref().len()
296/// }
297/// let _: fn(&FfmpegBytes) -> usize = carried::<Owned>;
298/// let _: fn(&FfmpegBuffer) -> usize = carried::<View>;
299/// ```
300///
301/// Holding a lane-parameterized type generically — the public structs
302/// carry **only** this bound, so a consumer's own generic code can pass
303/// them around:
304///
305/// ```
306/// use mediadecode::demuxer::TrackInfo;
307/// use mediadecode_ffmpeg::{
308///   CarrierAudioStreamDecoder, CarrierDemuxer, CarrierVideoStreamDecoder, Ffmpeg,
309///   FfmpegCarrier, Owned, View,
310/// };
311///
312/// fn tracks_of<C: FfmpegCarrier>(demuxer: &CarrierDemuxer<C>) -> usize {
313///   // A field read is not an operation on the lane, so this is
314///   // exactly as generic as it looks.
315///   core::mem::size_of_val(demuxer)
316/// }
317///
318/// fn hold<C: FfmpegCarrier>(
319///   _demuxer: &CarrierDemuxer<C>,
320///   _audio: &CarrierAudioStreamDecoder<C>,
321///   _video: &CarrierVideoStreamDecoder<C>,
322/// ) {
323/// }
324///
325/// let _: fn(&CarrierDemuxer<View>) -> usize = tracks_of::<View>;
326/// let _: fn(&CarrierDemuxer<Owned>) -> usize = tracks_of::<Owned>;
327/// let _ = hold::<View>;
328/// let _ = hold::<Owned>;
329/// let _: fn() -> Vec<TrackInfo<Ffmpeg>> = || Vec::new();
330/// ```
331///
332/// And calling at either concrete lane, through the aliases or through
333/// the `Carrier*` names directly:
334///
335/// ```no_run
336/// use mediadecode::demuxer::Demuxer;
337/// use mediadecode_ffmpeg::{
338///   CarrierDemuxer, FfmpegDemuxer, FfmpegOwnedDemuxer, Owned, View,
339/// };
340///
341/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
342/// let mut viewed = FfmpegDemuxer::open("clip.mkv")?;
343/// let mut owned = CarrierDemuxer::<Owned>::open("clip.mkv")?;
344/// let _ = viewed.tracks().len();
345/// let _ = owned.next_packet()?;
346/// let _: fn(&std::path::Path) -> _ = CarrierDemuxer::<View>::open::<std::path::Path>;
347/// let _: fn(&std::path::Path) -> _ = FfmpegOwnedDemuxer::open::<std::path::Path>;
348/// # Ok(())
349/// # }
350/// ```
351///
352/// What no bound reaches is the **operations** — see below. Being
353/// generic over the lane and *driving* it are different asks: the
354/// second needs the operations, so a consumer writes lane-generic
355/// helpers over `C::Buffer` and instantiates the doors at the two
356/// concrete lanes. That is the trade the wall costs, and it is
357/// deliberate.
358///
359/// What it cannot, and must not be able to: every one of these takes an
360/// extent, a geometry or a provenance claim that only this crate is in
361/// a position to establish. `from_rows` is the sharpest — it is
362/// **safe**, and a caller who could reach it could ask for sixty-four
363/// bytes out of a one-byte row.
364///
365/// ```compile_fail,E0599
366/// use mediadecode_ffmpeg::FfmpegCarrier;
367/// fn downstream<C: FfmpegCarrier>() -> C::Buffer {
368///   C::empty()
369/// }
370/// ```
371///
372/// ```compile_fail,E0599
373/// use mediadecode_ffmpeg::FfmpegCarrier;
374/// fn downstream<C: FfmpegCarrier>(row: &[u8]) -> Option<C::Buffer> {
375///   C::from_rows(1, 64, |_| row)
376/// }
377/// ```
378///
379/// ```compile_fail,E0599
380/// use mediadecode_ffmpeg::FfmpegCarrier;
381/// unsafe fn downstream<C: FfmpegCarrier>(
382///   buf: *mut ffmpeg_next::ffi::AVBufferRef,
383/// ) -> Option<C::Buffer> {
384///   unsafe { C::capture(buf, 0, 64) }
385/// }
386/// ```
387///
388/// ```compile_fail,E0599
389/// use mediadecode_ffmpeg::FfmpegCarrier;
390/// unsafe fn downstream<C: FfmpegCarrier>(
391///   buf: *mut ffmpeg_next::ffi::AVBufferRef,
392/// ) -> Option<C::Buffer> {
393///   // The provenance claim: minting this downstream would let a frame
394///   // plane pass itself off as a padded packet payload.
395///   unsafe { C::capture_packet_payload(buf, 0, 64) }
396/// }
397/// ```
398///
399/// ```compile_fail,E0599
400/// use mediadecode_ffmpeg::FfmpegCarrier;
401/// unsafe fn downstream<C: FfmpegCarrier>(buf: *mut ffmpeg_next::ffi::AVBufferRef) {
402///   let reserved = unsafe { C::reserve(buf, 0, 64) };
403/// }
404/// ```
405///
406/// ```compile_fail,E0599
407/// use mediadecode_ffmpeg::FfmpegCarrier;
408/// unsafe fn downstream<C: FfmpegCarrier>(reserved: ()) -> C::Buffer {
409///   unsafe { C::commit(reserved, 64) }
410/// }
411/// ```
412///
413/// The generic bodies behind the per-lane faces are equally out of
414/// reach. They carry the operations' bound, so reaching one at a
415/// concrete lane would be a way around the wall that never names it:
416///
417/// ```compile_fail,E0624
418/// use mediadecode_ffmpeg::{CarrierAudioStreamDecoder, DecoderLimits, Owned};
419/// fn downstream(parameters: ffmpeg_next::codec::Parameters) {
420///   let _ = CarrierAudioStreamDecoder::<Owned>::open_impl(
421///     parameters,
422///     mediadecode::Timebase::default(),
423///     DecoderLimits::default(),
424///   );
425/// }
426/// ```
427///
428/// ```compile_fail,E0624
429/// use mediadecode_ffmpeg::{CarrierDemuxer, View};
430/// fn downstream() {
431///   let _ = CarrierDemuxer::<View>::open_impl("clip.mkv");
432/// }
433/// ```
434pub trait FfmpegCarrier: sealed::Sealed + Copy + Clone + core::fmt::Debug + 'static {
435  /// The carrier this lane produces.
436  ///
437  /// `Send` but not necessarily `Sync`: the view lane is `Send`-only,
438  /// and requiring `Sync` here would have closed the seam to it.
439  ///
440  /// A **type**, and the only thing on this trait — naming
441  /// `<View as FfmpegCarrier>::Buffer` tells a consumer what a lane
442  /// hands them, and tells them nothing they could misuse. Everything
443  /// that *acts* is on the private ops trait.
444  type Buffer: AsRef<[u8]> + Clone + Send + 'static;
445}
446
447/// The **owned** lane: every byte copied once at the boundary.
448///
449/// The default carrier, and the one the [amputation contract][law]
450/// governs. Frames and packets on this lane are `Send + Sync +
451/// 'static`, clone by refcount, and owe nothing to the decoder that
452/// produced them.
453///
454/// [law]: mediadecode::adapter#the-d-seat-amputation-contract
455#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
456pub struct Owned;
457
458/// The **view** lane: refcounted zero-copy handles onto FFmpeg's own
459/// allocations.
460///
461/// `Send` and not `Sync`, with a lifetime pinned to the backend's
462/// buffer pools — a frame held is a pool slot held. See
463/// [the carrier lanes][lanes] for the tradeoff table and for why graph
464/// traffic belongs on [`Owned`].
465///
466/// [lanes]: mediadecode::adapter#the-two-carrier-lanes
467#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
468pub struct View;
469
470impl sealed::Sealed for Owned {}
471impl sealed::Sealed for View {}
472
473impl FfmpegCarrier for Owned {
474  type Buffer = FfmpegBytes;
475}
476
477impl FfmpegCarrier for View {
478  type Buffer = FfmpegBuffer;
479}
480
481impl ops::CarrierOps for Owned {
482  fn empty() -> Self::Buffer {
483    FfmpegBytes::empty()
484  }
485
486  fn from_bytes(bytes: &[u8]) -> Option<Self::Buffer> {
487    Some(FfmpegBytes::copy_from_slice(bytes))
488  }
489
490  fn from_rows<'a>(
491    rows: usize,
492    row_bytes: usize,
493    row: impl FnMut(usize) -> &'a [u8],
494  ) -> Option<Self::Buffer> {
495    FfmpegBytes::from_rows(rows, row_bytes, row)
496  }
497
498  /// The plane's start. Nothing is claimed and nothing can fail:
499  /// this lane's cost is a copy, and the copy happens at `commit` once
500  /// the bytes are real.
501  type Reserved = *const u8;
502
503  unsafe fn reserve(buf: *mut AVBufferRef, offset: usize, _cap: usize) -> Option<Self::Reserved> {
504    // SAFETY: `buf` is live per the contract and `offset` is inside it.
505    let data = unsafe { (*buf).data };
506    if data.is_null() {
507      return None;
508    }
509    // SAFETY: `offset` is within the buffer per the contract.
510    Some(unsafe { data.add(offset).cast_const() })
511  }
512
513  unsafe fn commit(reserved: Self::Reserved, len: usize) -> Self::Buffer {
514    if len == 0 {
515      return FfmpegBytes::empty();
516    }
517    // SAFETY: the caller promises `len` initialised bytes from the
518    // reserved pointer, inside a buffer still alive.
519    FfmpegBytes::copy_from_slice(unsafe { core::slice::from_raw_parts(reserved, len) })
520  }
521
522  /// Both routes copy. This lane's carrier is Rust-owned memory with no
523  /// `AVBufferRef` behind it to hand back, so there is nothing to share
524  /// on either road and no distinction to draw.
525  fn packet_body(
526    body: &Self::Buffer,
527    _route: BodyRoute,
528  ) -> std::result::Result<ffmpeg_next::Packet, ffmpeg_next::Error> {
529    crate::boundary::try_packet_copy(body.as_ref())
530  }
531
532  unsafe fn capture(buf: *mut AVBufferRef, offset: usize, len: usize) -> Option<Self::Buffer> {
533    if len == 0 {
534      return Some(FfmpegBytes::empty());
535    }
536    // SAFETY: the caller proved `offset + len <= (*buf).size` against a
537    // live buffer, so the range is inside an allocation FFmpeg holds.
538    let bytes = unsafe {
539      let data = (*buf).data;
540      if data.is_null() {
541        return None;
542      }
543      core::slice::from_raw_parts(data.add(offset).cast_const(), len)
544    };
545    Some(FfmpegBytes::copy_from_slice(bytes))
546  }
547
548  /// Indistinguishable from [`capture`](Self::capture) here: this lane
549  /// copies the payload out, so what follows it in FFmpeg's allocation
550  /// is not a fact about the carrier.
551  unsafe fn capture_packet_payload(
552    buf: *mut AVBufferRef,
553    offset: usize,
554    len: usize,
555  ) -> Option<Self::Buffer> {
556    // SAFETY: the caller's contract is the one `capture` states.
557    unsafe { <Self as ops::CarrierOps>::capture(buf, offset, len) }
558  }
559}
560
561impl ops::CarrierOps for View {
562  fn empty() -> Self::Buffer {
563    FfmpegBuffer::empty()
564  }
565
566  fn from_bytes(bytes: &[u8]) -> Option<Self::Buffer> {
567    // No `AVBufferRef` to share, so this lane copies too — into one of
568    // its own, so the carrier type stays uniform.
569    FfmpegBuffer::copy_from_slice(bytes)
570  }
571
572  fn from_rows<'a>(
573    rows: usize,
574    row_bytes: usize,
575    row: impl FnMut(usize) -> &'a [u8],
576  ) -> Option<Self::Buffer> {
577    FfmpegBuffer::from_rows(rows, row_bytes, row)
578  }
579
580  /// The view itself, taken at full capacity. The refcount — the only
581  /// step that can fail — is therefore already paid when the bytes
582  /// arrive.
583  type Reserved = FfmpegBuffer;
584
585  unsafe fn reserve(buf: *mut AVBufferRef, offset: usize, cap: usize) -> Option<Self::Reserved> {
586    // SAFETY: the caller proved the extent; `view_of` proves it again.
587    // A reservation is over an output frame this crate allocated, not
588    // over a packet, so it carries no padding claim.
589    unsafe { FfmpegBuffer::view_of(buf, offset, cap, crate::view::Origin::Foreign) }
590  }
591
592  unsafe fn commit(mut reserved: Self::Reserved, len: usize) -> Self::Buffer {
593    // No bytes move: the reference is held already and this only names
594    // how much of it is real output. The capacity past `len` is
595    // untouched allocator memory, and narrowing here is what keeps it
596    // out of every span this carrier hands out.
597    reserved.shrink_to(len);
598    reserved
599  }
600
601  fn packet_body(
602    body: &Self::Buffer,
603    route: BodyRoute,
604  ) -> std::result::Result<ffmpeg_next::Packet, ffmpeg_next::Error> {
605    match route {
606      // **A packet handed to a caller never shares.** `ffmpeg_next::
607      // Packet` lends `&mut [u8]` through `data_mut`, and the carrier
608      // it was built from still lends `&[u8]` — two live references to
609      // one allocation, one of them mutable, from entirely safe code.
610      // Copying here is what makes that unconstructible.
611      BodyRoute::Copy => crate::boundary::try_packet_copy(body.as_ref()),
612      BodyRoute::Submission => crate::boundary::share_or_copy(body),
613    }
614  }
615
616  unsafe fn capture(buf: *mut AVBufferRef, offset: usize, len: usize) -> Option<Self::Buffer> {
617    // SAFETY: the caller proved the extent; `view_of` proves it again
618    // against the buffer's own `size`, because a constructor that
619    // trusts its arguments is one bad caller away from a view over
620    // somebody else's memory.
621    unsafe { FfmpegBuffer::view_of(buf, offset, len, crate::view::Origin::Foreign) }
622  }
623
624  unsafe fn capture_packet_payload(
625    buf: *mut AVBufferRef,
626    offset: usize,
627    len: usize,
628  ) -> Option<Self::Buffer> {
629    // SAFETY: as `capture`, with the caller additionally promising this
630    // range is an `AVPacket`'s payload — which is what entitles the
631    // carrier to claim the padding behind it. The caller has also
632    // already refused any buffer with more than one reference
633    // (`buffer::payload_of`), so nothing else can be writing here.
634    unsafe { FfmpegBuffer::view_of(buf, offset, len, crate::view::Origin::PacketPayload) }
635  }
636}