diff --git a/Cargo.toml b/Cargo.toml index 06e1089..574bf4e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -34,7 +34,19 @@ edition = "2024" # writer's emulation-prevention fix that shares that code) are # applied here verbatim -- upstream work carried early, not a # local invention, and the H.265 half of what makes edith's -# HEVC export run on the GPU +# HEVC export run on the GPU. +# And `video_frame/generic_dma_video_frame.rs` unmapped a DMA +# buffer by issuing one `CLFLUSH` per *byte* -- 64 per cache +# line, 3.1 million per 1080p picture, 6.2 ms of the 8.4 ms a +# hardware export spent per frame (measured on radeonsi +# 2026-08-13; upstream's own TODO asks for exactly this and +# reports a race that the mfence pair, not the redundancy, was +# always ordering). The same `drop` wrote its `munmap` as an +# unconsumed `.map()`, so no mapping was ever released and an +# encode session leaked 3 MB of address space per frame +# (2.2 GB over a 719-frame export). Both are fixed in place +# and marked LOCAL PATCH + # rusty_aac - its *decoder* runs the direct O(N²) IMDCT with a `cos` call per # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not diff --git a/crates/engine-hw/src/lib.rs b/crates/engine-hw/src/lib.rs index 33336ea..cd87b04 100644 --- a/crates/engine-hw/src/lib.rs +++ b/crates/engine-hw/src/lib.rs @@ -840,11 +840,19 @@ fn fix_slice_nal_headers(au: &mut [u8]) { /// One hardware H.264 encode session. /// -/// Input goes through a single reusable NV12 buffer object: the caller's I420 -/// planes are interleaved into it and the encoder imports it as a VA surface. -/// Reuse is safe because the encoder runs in blocking mode and every entry -/// point polls it before returning, so the GPU is finished with the buffer -/// before the next picture is written into it. +/// Input goes through [`enc_depth`] reusable NV12 buffer objects: the caller's +/// I420 planes are interleaved into the next one and the encoder imports it as a +/// VA surface. Reuse is safe because a buffer is only written again once the +/// access unit coded *from* it has been polled back -- the encoder runs in +/// blocking mode and a coded unit in hand means the GPU has finished reading its +/// input -- and [`EncSession::encode`] holds exactly that many pictures in +/// flight, no more. +/// +/// **Why more than one.** With a single buffer the picture had to be coded +/// before the next one could be written into it, so a frame cost the CPU's +/// interleave *plus* the GPU's encode end to end (6.7 ms + 2.5 ms at 1080p on +/// radeonsi, measured 2026-08-13). With two, the interleave of the next picture +/// runs while the GPU codes this one and the frame costs the longer of them. struct EncSession { /// Boxed because the three codecs are three types and everything past /// `encode` is the same trait: one session type serves them all, which is @@ -855,9 +863,18 @@ struct EncSession { /// differs: the H.264 driver leaves a *NAL* header byte at zero, and /// neither an HEVC access unit nor an AV1 temporal unit has that one. codec: EncCodec, - /// Owns the DRM node the buffer object below was allocated from. + /// Owns the DRM node the buffer objects below were allocated from. _gbm: gbm::Device, - frame: GenericDmaVideoFrame, + /// [`enc_depth`] input buffers, used round-robin. + frames: Vec, + /// How many of them there are, which is how many pictures may be in the + /// encoder at once. + depth: usize, + /// Which of them the next picture is written into. + slot: usize, + /// Pictures submitted whose access unit has not been polled back yet, which + /// is what says whether the buffer about to be written is free. + in_flight: usize, layout: FrameLayout, /// Macroblock-aligned surface size; `width`/`height` are what is encoded. coded: Resolution, @@ -870,6 +887,34 @@ struct EncSession { ready: VecDeque>, /// The access unit currently handed out, kept alive until the next call. out: Vec, + /// One padded output row, staged in ordinary memory and copied across whole + /// -- [`EncSession::upload`] says why. + row: Vec, +} + +/// How many pictures may be in the encoder at once. Two is what it takes to +/// overlap the CPU's interleave with the GPU's encode; more would buy nothing, +/// since the interleave is the longer of the two and a third buffer would only +/// hold a picture waiting for a lane that is never idle. +const ENC_DEPTH: usize = 2; + +/// How many pictures *this* seat may hold, which is [`ENC_DEPTH`] for H.264 and +/// one for the other two. +/// +/// Depth 2 means a submitted picture must hand its access unit back on the next +/// poll, and [`EncSession::encode`] treats a seat that does not as an error -- +/// it cannot write into a buffer the GPU may still be reading. That contract +/// was measured on the H.264 seat and only there. HEVC and AV1 on this plugin +/// are intra-only and go through the same driver, so they very probably behave +/// the same way; "very probably" is not what a hard error should rest on, and +/// the GPU has been unavailable since the measurement was possible. They keep +/// the old one-buffer behaviour -- the picture coded before the next is +/// written, exactly as every seat did before -- until someone measures them. +fn enc_depth(codec: EncCodec) -> usize { + match codec { + EncCodec::H264 => ENC_DEPTH, + EncCodec::Hevc | EncCodec::Av1 => 1, + } } /// Which codec an [`EncSession`] was opened for. Decided once, at the open, the @@ -1049,13 +1094,20 @@ impl EncSession { }; // Allocated at the aligned size, so the buffer's pitch is never smaller // than a padded row. - let frame = alloc_nv12(&gbm, coded, false).ok()?; - let layout = nv12_layout(coded, frame.get_plane_pitch()[0], false); + let depth = enc_depth(codec); + let frames: Vec<_> = (0..depth) + .map(|_| alloc_nv12(&gbm, coded, false)) + .collect::>() + .ok()?; + let layout = nv12_layout(coded, frames[0].get_plane_pitch()[0], false); Some(Self { encoder, codec, _gbm: gbm, - frame, + frames, + depth, + slot: 0, + in_flight: 0, layout, coded, width: width as usize, @@ -1064,21 +1116,38 @@ impl EncSession { drained: false, ready: VecDeque::new(), out: Vec::new(), + row: Vec::new(), }) } - /// Interleaves one packed I420 picture into the NV12 input buffer. + /// Interleaves one packed I420 picture into the NV12 input buffer `slot`. + /// + /// **Row at a time, through ordinary memory.** The mapping below is the + /// GPU's own buffer, which is write-combining: a store of a byte or two + /// costs a partial-buffer flush, while one `memcpy` of a whole row costs a + /// burst. Interleaving the chroma directly into it was 8.2 ms a picture at + /// 1080p against 6.7 ms staged (measured 2026-08-13 on radeonsi, alternating + /// the two paths frame by frame inside one export so the machine's load + /// weighed on both), and the picture is four fifths of what a hardware + /// export spends per frame. The padding is written the same way and for the + /// same reason: it used to be a four-byte second store per row. /// /// # Safety /// `src`'s planes must cover `height` (resp. `height / 2`) rows of their /// declared stride. - unsafe fn upload(&mut self, src: &VhFrame) -> Result<(), String> { + unsafe fn upload(&mut self, src: &VhFrame, slot: usize) -> Result<(), String> { let (w, h) = (self.width, self.height); let (cw, ch) = (w / 2, h / 2); let (aw, ah) = (self.coded.width as usize, self.coded.height as usize); - let pitch = self.frame.get_plane_pitch(); - let mapping = self.frame.map_mut()?; + // Two fields at once: the buffer is mapped for writing while the staging + // row is written into, and they are not the same field. + let Self { frames, row, .. } = self; + let frame = &mut frames[slot]; + let pitch = frame.get_plane_pitch(); + let mapping = frame.map_mut()?; let planes = mapping.get(); + row.resize(aw, 0); + let row_buf = &mut row[..]; { let mut dst = planes[0].borrow_mut(); for row in 0..ah { @@ -1086,11 +1155,11 @@ impl EncSession { let s = unsafe { std::slice::from_raw_parts(src.y.add(row.min(h - 1) * src.y_stride), w) }; - let dst = &mut dst[row * pitch[0]..row * pitch[0] + aw]; - dst[..w].copy_from_slice(s); + row_buf[..w].copy_from_slice(s); // Macroblock padding: replicate the edge rather than leave the // buffer's garbage there, which would cost bitrate for nothing. - dst[w..].fill(s[w - 1]); + row_buf[w..].fill(s[w - 1]); + dst[row * pitch[0]..row * pitch[0] + aw].copy_from_slice(row_buf); } } let mut dst = planes[1].borrow_mut(); @@ -1103,14 +1172,14 @@ impl EncSession { std::slice::from_raw_parts(src.v.add(src_row * src.v_stride), cw), ) }; - let dst = &mut dst[row * pitch[1]..row * pitch[1] + aw]; for x in 0..cw { - dst[2 * x] = u[x]; - dst[2 * x + 1] = v[x]; + row_buf[2 * x] = u[x]; + row_buf[2 * x + 1] = v[x]; } for x in w..aw { - dst[x] = dst[x - 2]; + row_buf[x] = row_buf[x - 2]; } + dst[row * pitch[1]..row * pitch[1] + aw].copy_from_slice(row_buf); } Ok(()) } @@ -1118,8 +1187,15 @@ impl EncSession { /// # Safety /// As [`EncSession::upload`]. unsafe fn encode(&mut self, src: &VhFrame, force_keyframe: bool) -> Result<(), String> { + // The buffer this picture is written into is the one whose own access + // unit is already in hand -- `in_flight` is held below `depth` at the + // end of every call, so the round-robin never catches the GPU up. At + // depth 1 that is the picture just coded, which is the one-buffer + // behaviour every seat had before ([`enc_depth`]). + let slot = self.slot; // SAFETY: caller contract, forwarded. - unsafe { self.upload(src)? }; + unsafe { self.upload(src, slot)? }; + self.slot = (self.slot + 1) % self.depth; let meta = FrameMetadata { timestamp: self.timestamp, layout: self.layout.clone(), @@ -1127,23 +1203,44 @@ impl EncSession { }; self.timestamp += 1; self.encoder - .encode(meta, self.frame.clone()) + .encode(meta, self.frames[slot].clone()) .map_err(|e| e.to_string())?; - self.collect() + self.in_flight += 1; + // ...and the picture before it is collected here rather than this one: + // that is the whole overlap, the GPU coding what was just submitted + // while the caller decodes and interleaves the next picture. + while self.in_flight >= self.depth { + if !self.pull()? { + // Blocking mode: a picture accepted and no coded unit for the + // one before it means the encoder is not answering, and the + // next upload would overwrite a buffer the GPU still reads. + return Err("the encoder took a picture and returned nothing coded".into()); + } + } + Ok(()) } /// Moves every access unit the encoder has finished into `ready`. fn collect(&mut self) -> Result<(), String> { - while let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? { - let mut au = coded.bitstream; - if self.codec == EncCodec::H264 { - fix_slice_nal_headers(&mut au); - } - self.ready.push_back(au); - } + while self.pull()? {} Ok(()) } + /// One finished access unit into `ready`; `false` where the encoder has + /// none to give. + fn pull(&mut self) -> Result { + let Some(coded) = self.encoder.poll().map_err(|e| e.to_string())? else { + return Ok(false); + }; + let mut au = coded.bitstream; + if self.codec == EncCodec::H264 { + fix_slice_nal_headers(&mut au); + } + self.ready.push_back(au); + self.in_flight = self.in_flight.saturating_sub(1); + Ok(true) + } + /// Hands the oldest finished access unit to the caller, or reports that /// there is none. fn take(&mut self, out: *mut *const u8, out_len: *mut usize) -> i32 { diff --git a/crates/engine/examples/bench.rs b/crates/engine/examples/bench.rs index 7672226..3e2b536 100644 --- a/crates/engine/examples/bench.rs +++ b/crates/engine/examples/bench.rs @@ -27,7 +27,15 @@ //! writing except the export destination it is handed. //! //! Env: `BENCH_TTFF_TIMEOUT` (s, default 180) how long a seek may wait for its -//! first frame, `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single +//! first frame, `BENCH_EXPORT_SPAN` (s, default 60) how much timeline one +//! export measurement covers, `BENCH_EXPORT_AUDIO` (unset) whether that +//! timeline carries its source's sound as well -- the row is named `_av` when +//! it does, because an export's wall clock is the audio pass plus the picture +//! and a picture-only number is not the thing a person waits for -- +//! `BENCH_EXPORT_ASTREAM` (default 0) which of the file's audio streams that +//! is, a film's second track often being the one no sample table can copy and +//! therefore the one that measures a re-encode, +//! `BENCH_EXPORT_CAP` (s, default 300) the wall clock any single //! export measurement may take, `BENCH_EXPORT_REPS` (default 5) how many times //! an export is repeated *if the cap leaves room* -- a 4K encode gets one //! capped rep, the small control gets five -- and `BENCH_KEEP` (unset) whether @@ -620,7 +628,12 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { "hevchw" => (Format::Hevc, false), _ => usage(), }; - let metric = format!("export_fps_{seat}"); + // The sound is opt-in and named in the row, so an `_av` number is never + // compared against a picture-only one: what it measures is the *export* -- + // audio pass, mux and all -- which is the only shape of the number a + // "twice real time" claim may be made from. + let with_audio = std::env::var_os("BENCH_EXPORT_AUDIO").is_some(); + let metric = format!("export_fps_{seat}{}", if with_audio { "_av" } else { "" }); let (meta, _) = match engine::demux::Demuxer::open(path) { Ok(opened) => opened, Err(e) => { @@ -628,7 +641,8 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { return; } }; - let span = ((meta.frame_rate * 60.0) as u32).min(meta.frame_count.max(1)); + let span = ((meta.frame_rate * env_f64("BENCH_EXPORT_SPAN", 60.0)) as u32) + .min(meta.frame_count.max(1)); let in_frame = (meta.frame_count / 10).min(meta.frame_count.saturating_sub(span)); let clip = Clip { start: 0, @@ -641,9 +655,16 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { fit: engine::scale::FitPolicy::default(), speed: Speed::NORMAL, }; + // The sound, where it was asked for, is the same clip on an audio lane: + // the very window the picture covers, so the two passes measure one export. + let mut lanes = vec![(LaneKind::Video, vec![clip.clone()])]; + if with_audio { + lanes.push((LaneKind::Audio, vec![clip])); + } + let stream = env_f64("BENCH_EXPORT_ASTREAM", 0.0) as usize; let project = match Project::from_parts( - vec![Source::new(path, 0)], - vec![(LaneKind::Video, vec![clip])], + vec![Source::new(path, stream)], + lanes, Vec::new(), Vec::new(), ) { @@ -669,7 +690,14 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { let handle = engine::export::start(project.clone(), meta, &out, &settings); let t = Instant::now(); let mut capped = false; + // The highest the bar was ever seen at, not wherever it happens to + // stand when the clock stops: an export publishes one bar from two + // stages, and a capped run's rate is derived from this number. Taking + // the maximum over the poll loop means a single unlucky read cannot + // under-report the work that was really done. + let mut peak = 0.0f64; while !handle.is_finished() { + peak = peak.max(f64::from(handle.progress())); if t.elapsed() >= cap { capped = true; handle.cancel(); @@ -679,7 +707,7 @@ fn export_bench(path: &Path, seat: &str, out_dir: &Path) { } // A cancel is answered at the worker's next checkpoint; the rate is // read from the progress at the moment the clock stopped either way. - let progress = f64::from(handle.progress()); + let progress = peak.max(f64::from(handle.progress())); let elapsed = t.elapsed().as_secs_f64(); let done = Instant::now() + Duration::from_secs(60); while !handle.is_finished() && Instant::now() < done { diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index daa130b..a3e84ad 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -303,6 +303,17 @@ pub struct ExportSettings { } struct Shared { + /// Fraction of the job done, in [`PROGRESS_SCALE`]ths. + /// + /// **Every stage that can run beside another writes this with `fetch_max`, + /// never `store`.** The sound and the picture are two threads publishing + /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band + /// pulls the bar backwards every time the other thread has already moved + /// it on, which is what a person sees as a progress bar that stutters + /// backwards -- 5,458 backward steps over one film export before this rule + /// was written down. A `store` is only correct where nothing else can be + /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and + /// the audio-only export ([`run_audio`]) that has no second thread. progress: AtomicU32, cancel: AtomicBool, finished: AtomicBool, @@ -1325,10 +1336,21 @@ fn encode_audio( * channels; let mut samples: Vec = Vec::with_capacity(total); for chunk in chunks { + // The only place a cancelled export can be answered before the whole + // timeline has been mixed. This pass runs on a thread of its own now + // ([`run`]), so without this a cancel left it mixing a feature film + // for minutes behind a job nobody is waiting for any more, writing + // into a `Shared` whose outcome was already settled. + cancelled(shared)?; samples.extend(chunk.samples); // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of // the three stages and the only one that can be counted as it goes. - shared.progress.store( + // + // `fetch_max` and not `store`, for the reason [`Shared::progress`] + // states: this runs on the audio thread while the picture publishes + // numbers above [`AUDIO_BAND`] from the other, and a `store` of this + // small one pulled the bar backwards 5,458 times over one film export. + shared.progress.fetch_max( (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, Ordering::Relaxed, ); @@ -1351,6 +1373,10 @@ fn encode_audio( // there is no resampler on this path, and inventing one to reach 48 kHz // would resample a whole timeline to satisfy a codec, which is a bigger // change to the sound than the codec is. + // ...and again before either encoder is entered: both of them run to the + // end of the mix without a checkpoint of their own, so this is the last + // moment a cancel costs seconds rather than the whole encode. + cancelled(shared)?; if mkv && audio.sample_rate == OPUS_RATE && channels == 2 @@ -1380,6 +1406,7 @@ fn encode_audio( // `next_packet` after `finish` yields packets until `Eof` and nothing else, // so the loop ends on the only error it can see. while let Ok(packet) = encoder.next_packet() { + cancelled(shared)?; packets.push(crate::AacPacket { bytes: packet.data, samples: packet.duration, @@ -1657,11 +1684,54 @@ fn window_fidelity( (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12)) } +/// The audio pass, running beside the picture: what [`run`] holds while it +/// encodes and joins where the file it is writing needs the track. +type AudioJob = thread::JoinHandle>>; + +/// The pass's answer, or the failure that is the export's failure. A panicked +/// audio thread reads as an error rather than as silence: an export that wrote +/// its picture and quietly no sound is the one outcome this must not have. +fn join_audio(job: AudioJob) -> crate::Result> { + job.join() + .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))? +} + +/// The encoder line a running export shows: the seat the picture is really +/// being written by, and what the sound is -- or that the sound is still being +/// worked out, which an overlapped audio pass is until it is collected. +fn publish_seats( + shared: &Shared, + seat: &str, + project: &Project, + settings: &ExportSettings, + sound: Option, + opus: bool, + waiting: bool, +) { + let audio = match waiting { + // Still mixing on the other thread. The same half-line the copied- + // picture path has always shown, and for the same reason: what is + // published is never a codec that did not run. + true => "working out the sound…", + false => measured_audio_label(project, settings.format, sound, opus), + }; + *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}")); +} + +fn params_of(track: &ExportAudio) -> AudioParams { + AudioParams { + freq_index: track.params.freq_index, + chan_conf: track.params.chan_conf, + sample_rate: track.params.sample_rate, + opus_pre_skip: track.opus_pre_skip, + } +} + fn run( project: &Project, meta: &VideoMeta, out: &Path, - shared: &Shared, + shared: &Arc, settings: &ExportSettings, ) -> crate::Result<()> { let total = project.timeline_frames(); @@ -1678,43 +1748,80 @@ fn run( eprintln!("export video: copy (source packets)"); *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into()); } - // ...then the audio: a track has to be declared when the muxer is created, - // which happens as soon as the first coded picture arrives -- and the - // Matroska muxer wants the packets themselves that early too, because it - // interleaves them into the clusters as it writes. Every video format gets - // the same track: none of them is picture-only any more. - let audio = copy_audio( - project, - meta, - audio_kbps_of(settings), - settings.format.is_mkv(), - shared, - )?; - let audio_params = audio.as_ref().map(|track| AudioParams { - freq_index: track.params.freq_index, - chan_conf: track.params.chan_conf, - sample_rate: track.params.sample_rate, - opus_pre_skip: track.opus_pre_skip, - }); + // ...then the audio, on a thread of its own, started before anything is + // opened for the picture. + // + // Where it is *waited* for is the whole of this: a Matroska file interleaves + // its audio into the clusters from the header on, so that path needs every + // packet before the first coded picture and there is nothing to overlap. An + // mp4 writes its audio track after the whole picture -- and now declares it + // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the + // picture's loop needs nothing at all from this until it has finished, and + // the mix, its encode and the encode of every frame run at once. An export + // used to cost the sound *plus* the picture; an mp4 one now costs the longer + // of the two. On this project's own film that is 168 s of AC-3 that no + // longer stands in front of 733 s of hardware H.264. + let audio_job = { + let (project, meta, settings, shared) = ( + project.clone(), + *meta, + settings.clone(), + Arc::clone(shared), + ); + thread::Builder::new() + .name("export-audio".into()) + .spawn(move || { + copy_audio( + &project, + &meta, + audio_kbps_of(&settings), + settings.format.is_mkv(), + &shared, + ) + })? + }; + // A Matroska file (and a copied one, whose muxer is the same) collects it + // here; an mp4 leaves it running and collects it under the picture below. + let mut audio_job = Some(audio_job); + // The condition is the *format*, and the copied-picture path below relies + // on that covering it too: `plan` hands its packets straight to a Matroska + // muxer, so it may only exist where this has already collected them -- + // which holds because [`CopyPlan::of`] returns `None` for every format + // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud + // because a copy plan for an mp4 would otherwise reach `plan.run` with the + // sound still being mixed on the other thread. + debug_assert!( + settings.format.is_mkv() || plan.is_none(), + "a copy plan outside Matroska would run before its sound is collected" + ); + let audio = match settings.format.is_mkv() { + true => join_audio(audio_job.take().expect("the job was just made"))?, + false => None, + }; + let audio_params = audio.as_ref().map(params_of); // What the track *is*, kept before the packets are handed to a muxer: the // encoder line names a copy or an encode and only `copy_audio` knows which. - let sound = audio.as_ref().map(|track| track.copied); + // `None` on the mp4 path until the pass is collected -- the line says it is + // still working the sound out, which is what it is doing. + let mut sound = audio.as_ref().map(|track| track.copied); // ...and *which* encoder, for the same line: the card predicts Opus from the // format alone and cannot know the mix's rate or width ([`audio_label`]), // while this is after the mix was opened, so it is the measured answer. - let opus = audio + let mut opus = audio .as_ref() .is_some_and(|track| track.opus_pre_skip.is_some()); // Taken by the Matroska muxer at creation; the mp4 one writes its track - // after the picture, so for that path this is still `Some` at the end. + // after the picture, so for that path this is filled in at the end. let mut packets = audio.map(|track| track.packets); // ...and the cues with them, for the same reason: the subtitle track is // declared in the header and its blocks are interleaved into the clusters, // so the muxer needs the lot before the first picture is written. let mut subs = export_subtitles(project, meta, settings); - // The sound is done, whichever way it went: the bar stands at the head of - // the picture's own share ([`AUDIO_BAND`]). - shared.progress.store(AUDIO_BAND, Ordering::Relaxed); + // Whatever the sound has reached, the picture's share starts here + // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what + // `fetch_max` below keeps true while an audio pass is still publishing its + // own third of that band from the other thread. + shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed); // Before an encoder is opened at all: a timeline nobody has touched, whose // sources this file can hold as they are, is written by copying their coded @@ -1781,12 +1888,17 @@ fn run( // Published *after* the seat is open, so a hardware encoder the driver // refused reads as the software one that took over rather than as the hope // it replaced -- and the sound says whether it was copied or encoded, which - // `copy_audio` decided a few lines up. - *shared.encoders.lock().unwrap() = Some(format!( - "{} · {}", - encoder.label(), - measured_audio_label(project, settings.format, sound, opus) - )); + // only `copy_audio` knows and, on the overlapped path, does not know yet. + let seat = encoder.label(); + publish_seats(shared, seat, project, settings, sound, opus, audio_job.is_some()); + // When the picture started, so the stage line below can say where under it + // the sound landed -- the one number that says whether the two passes + // really overlapped, in the same voice as `encode_audio`'s own timers. + let picture_started = std::time::Instant::now(); + // The sound, once the pass beside this one has finished with it: an mp4 + // declares its audio track and writes its packets after the picture, so + // this is where they arrive. + let mut late: Option = None; let mut muxer = None; let mut done = 0u32; let black = Black::new(meta); @@ -1873,6 +1985,27 @@ fn run( |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at; while done_here < span.len { cancelled(shared)?; + // The sound's failure is the export's, and it is heard the moment + // it happens rather than after the last frame: a mix this engine + // cannot decode used to refuse in seconds, before any picture was + // encoded, and an overlapped pass that reported only at the end + // would spend the whole encode first. Also where its measured + // codec reaches the line on screen. + if audio_job + .as_ref() + .is_some_and(thread::JoinHandle::is_finished) + { + late = join_audio(audio_job.take().expect("just seen to be there"))?; + sound = late.as_ref().map(|track| track.copied); + opus = late + .as_ref() + .is_some_and(|track| track.opus_pre_skip.is_some()); + publish_seats(shared, seat, project, settings, sound, opus, false); + eprintln!( + "export audio: done {:.1} s into the picture", + picture_started.elapsed().as_secs_f64() + ); + } let want = source_at(done_here); // How many timeline frames from here show that same picture: one at // real time, more when the clip is slowed or its file is slower @@ -1952,9 +2085,13 @@ fn run( )?; } done += 1; + // Forwards only: an audio pass still running beside this one + // publishes its own share of [`AUDIO_BAND`], and a bar that + // went backwards every time it did would be worse than one + // that stood still. shared .progress - .store(picture_progress(done, total), Ordering::Relaxed); + .fetch_max(picture_progress(done, total), Ordering::Relaxed); } done_here += repeats; } @@ -1985,7 +2122,28 @@ fn run( // turned out to be. let muxer = match muxer { Muxer::Mp4(mut mp4) => { - for packet in packets.into_iter().flatten() { + // The sound, collected where this file first needs it: it has been + // mixing and encoding under the whole picture, and an mp4 declares + // its audio track here rather than at the open precisely so that + // could happen ([`Mp4Muxer::add_audio_track`]). + let track = match audio_job.take() { + Some(job) => { + let track = join_audio(job)?; + // The picture finished first and this waited for the + // sound: the pair of stage lines is what says which of the + // two an export is really bounded by. + eprintln!( + "export audio: waited for after {:.1} s of picture", + picture_started.elapsed().as_secs_f64() + ); + track + } + None => late, + }; + if let Some(track) = &track { + mp4.add_audio_track(¶ms_of(track))?; + } + for packet in track.into_iter().flat_map(|track| track.packets) { mp4.write_audio_packet(&packet.bytes)?; } mp4.write_subtitles(&subs)?; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index e84df68..2f46bd5 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -268,44 +268,65 @@ impl Mp4Muxer { pic_param_set: video.pps.to_vec(), }), })?; - if let Some(audio) = audio { - // The one thing this writer must never do quietly: an `mp4a` sample - // entry declares AAC, so Opus packets in it would be a file that - // says one codec and holds another. `export` never asks -- Opus is - // written for Matroska alone -- and this is the backstop that keeps - // that true if a format is ever added on the other side. - if audio.opus_pre_skip.is_some() { - return Err("an Opus track in an mp4: this writer declares `mp4a` only".into()); - } - let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; - // The index's own rate, not `audio.sample_rate`: this is the clock - // an `stts` counts in and the `esds` states the index, so the two - // must not be able to disagree. - let sample_rate = freq_index.freq(); - writer.add_track(&TrackConfig { - track_type: TrackType::Audio, - timescale: sample_rate, - language: "und".to_string(), - media_conf: MediaConfig::AacConfig(AacConfig { - bitrate: 0, - profile: AudioObjectType::AacLowComplexity, - freq_index, - chan_conf: ChannelConfig::try_from(audio.chan_conf)?, - }), - })?; - } - - Ok(Self { + let mut muxer = Self { writer, frame_duration, - has_audio: audio.is_some(), + has_audio: false, entry, colr: colr_nclx(ColorDescription::output(video.height)), path: path.to_path_buf(), timescale, frames: 0, sub_names: Vec::new(), - }) + }; + if let Some(audio) = audio { + muxer.add_audio_track(audio)?; + } + Ok(muxer) + } + + /// Declares the AAC track, which an mp4 may do at any point before its + /// first packet is written: the sample table is built from the samples as + /// they are handed over, and this file's audio is handed over after the + /// whole picture ([`write_audio_packet`](Mp4Muxer::write_audio_packet)). + /// + /// That is what lets an export mix and encode its sound *while* it encodes + /// the picture rather than before it: the picture's loop no longer needs to + /// know the track's shape to start. Declaring it at the open, which is what + /// a caller that already has the sound does, writes the same file -- + /// `mp4 0.14` builds the movie box at `finish` from tracks in the order + /// they were added, and the samples themselves are written in the order the + /// caller writes them either way. + pub fn add_audio_track(&mut self, audio: &AudioParams) -> crate::Result<()> { + // The one thing this writer must never do quietly: an `mp4a` sample + // entry declares AAC, so Opus packets in it would be a file that says + // one codec and holds another. `export` never asks -- Opus is written + // for Matroska alone -- and this is the backstop that keeps that true + // if a format is ever added on the other side. + if audio.opus_pre_skip.is_some() { + return Err("an Opus track in an mp4: this writer declares `mp4a` only".into()); + } + if self.has_audio { + return Err("an mp4 declares its audio track once".into()); + } + let freq_index = SampleFreqIndex::try_from(audio.freq_index)?; + // The index's own rate, not `audio.sample_rate`: this is the clock an + // `stts` counts in and the `esds` states the index, so the two must not + // be able to disagree. + let sample_rate = freq_index.freq(); + self.writer.add_track(&TrackConfig { + track_type: TrackType::Audio, + timescale: sample_rate, + language: "und".to_string(), + media_conf: MediaConfig::AacConfig(AacConfig { + bitrate: 0, + profile: AudioObjectType::AacLowComplexity, + freq_index, + chan_conf: ChannelConfig::try_from(audio.chan_conf)?, + }), + })?; + self.has_audio = true; + Ok(()) } /// One coded picture, Annex-B framed. Parameter sets inside it are dropped diff --git a/scripts/bench.sh b/scripts/bench.sh index f052c2f..9a73fe6 100755 --- a/scripts/bench.sh +++ b/scripts/bench.sh @@ -47,11 +47,17 @@ TARGET=$(realpath -m "${CARGO_TARGET_DIR:-target}") # The plugins are their own build: `--example` selects example targets in every # package it is given, and a cdylib is not one, so `-p engine-hw --example # bench` built no plugin at all and every run measured software while the line -# below said otherwise. engine-audio is here for the same reason -- the play -# loop's underruns come from the device, and with no plugin there is no device. +# below said otherwise (measured 2026-08-13: the film's hardware export read +# 11.55 fps as silent software, 94.58 fps once the plugin was there). +# engine-audio is here for the same reason -- the play loop's underruns come +# from the device, and with no plugin there is no device. cargo build --release -p engine-hw -p engine-audio || exit 1 cargo build --release -p engine --example bench || exit 1 BENCH="$TARGET/release/examples/bench" +[ -f "$TARGET/release/libengine_hw.so" ] || { + echo "no libengine_hw.so in $TARGET/release: every hardware row would be software" >&2 + exit 1 +} # The plugin is looked for beside the running executable, and an example binary # lives one directory below the plugin: without this, hardware decode and # hardware encode silently fall back to software and the baseline is a lie. diff --git a/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs index bdb788f..1381b4b 100644 --- a/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs +++ b/vendor/cros-codecs/src/video_frame/generic_dma_video_frame.rs @@ -98,6 +98,12 @@ const Y_TILE_WIDTH: usize = Y_TILE_WIDTH_IN_SUBTILES * Y_SUBTILE_WIDTH; const Y_TILE_HEIGHT: usize = Y_TILE_HEIGHT_IN_SUBTILES * Y_SUBTILE_HEIGHT; const Y_TILE_SIZE: usize = Y_TILE_WIDTH * Y_TILE_HEIGHT; +/// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what one `CLFLUSH` covers, +/// and therefore the stride the unmap below walks a buffer with. 64 bytes on +/// every x86-64 part this runs on. +#[cfg(target_arch = "x86_64")] +const CACHE_LINE: usize = 64; + fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { let tiles_per_row = width / Y_TILE_WIDTH; for y in 0..height { @@ -123,6 +129,11 @@ fn detile_y_tile(dst: &mut [u8], src: &[u8], width: usize, height: usize) { pub struct DmaMapping<'a> { dma_handles: Vec>, addrs: Vec>, + /// LOCAL PATCH (see /Cargo.toml [patch.crates-io]): what `mmap` actually + /// returned and how much of it, which is what `munmap` has to be handed -- + /// `addrs` above are those bases plus a plane offset that is not required + /// to be page aligned, so unmapping *them* is EINVAL. + maps: Vec<(NonNull, usize)>, detiled_bufs: Vec>, lens: Vec, is_writable: bool, @@ -171,12 +182,14 @@ impl<'a> DmaMapping<'a> { // Offsets aren't guaranteed to page aligned, so we have to map the entire FD and then // do pointer arithmetic to get the right buffer. let mut addrs: Vec> = vec![]; + let mut maps: Vec<(NonNull, usize)> = vec![]; if borrowed_dma_handles.len() > 1 { for i in 0..offsets.len() { // SAFETY: This assumes that fd is a valid DMA buffer and that our lens and offsets // are correct. + let plane_size = lens[i] + offsets[i]; addrs.push(unsafe { - mmap( + let base = mmap( None, NonZeroUsize::new(lens[i] + offsets[i]) .ok_or("Attempted to map plane of length 0!")?, @@ -189,8 +202,9 @@ impl<'a> DmaMapping<'a> { borrowed_dma_handles[i].as_fd(), 0, ) - .map_err(|err| format!("Error mapping plane {err}"))? - .add(offsets[i]) + .map_err(|err| format!("Error mapping plane {err}"))?; + maps.push((base, plane_size)); + base.add(offsets[i]) }); } } else { @@ -212,6 +226,7 @@ impl<'a> DmaMapping<'a> { 0, ) .map_err(|err| format!("Error mapping plane {err}"))?; + maps.push((base_addr, total_size.get())); for i in 0..offsets.len() { addrs.push(base_addr.add(offsets[i])); } @@ -245,6 +260,7 @@ impl<'a> DmaMapping<'a> { Ok(DmaMapping { dma_handles: borrowed_dma_handles.clone(), addrs: addrs, + maps: maps, detiled_bufs: detiled_bufs, lens: lens.clone(), is_writable: is_writable, @@ -313,12 +329,29 @@ impl<'a> Drop for DmaMapping<'a> { _mm_mfence(); for (addr, len) in zip(self.addrs.iter(), self.lens.iter()) { - // TODO: We shouldn't actually have to flush every address, we should just - // flush the address at the beginning of each cache line. But, during testing - // this caused a race condition. - for offset in 0..*len { - _mm_clflush((addr.as_ptr() as *const u8).offset(offset as isize)); + // LOCAL PATCH (see /Cargo.toml [patch.crates-io]): a cache + // line at a time, which is the granularity CLFLUSH has -- + // flushing every byte issued 64 instructions per line and + // cost 6.2 ms per 1080p picture on radeonsi (measured + // 2026-08-13), four fifths of a hardware export's whole + // per-frame budget. The upstream TODO says exactly this and + // reports a race when it was tried; the mfence pair either + // side is what orders the flushes, and the sixty-four + // redundant flushes per line were never what did. + // A plane of no bytes has no line to flush, and the last-line + // flush below would touch the byte after the mapping. + // Upstream's byte loop flushed nothing at all for `0..0`, + // and this keeps that. + if *len == 0 { + continue; } + let base = addr.as_ptr() as *const u8; + for offset in (0..*len).step_by(CACHE_LINE) { + _mm_clflush(base.offset(offset as isize)); + } + // ...and the last line, where the length is not a multiple + // of one. + _mm_clflush(base.offset(len.saturating_sub(1) as isize)); } _mm_mfence(); @@ -326,7 +359,13 @@ impl<'a> Drop for DmaMapping<'a> { fence(Ordering::SeqCst); - let _ = zip(self.addrs.iter(), self.lens.iter()).map(|x| munmap(*x.0, *x.1).unwrap()); + // LOCAL PATCH: `map` on an iterator is lazy, so the unmap upstream + // writes here never ran -- every mapping leaked its address space + // (3 MB a picture through an encode session, 2.2 GB of VSZ over a + // 719-frame export, measured 2026-08-13). + for (addr, len) in self.maps.iter() { + let _ = munmap(*addr, *len); + } } } }