forge
Explore
Log in

Don't you dare go Hollow

The decoder stops waiting for the encoder

Browse files at this commit

b728a45934a98257bc8a176ff5222ee4ebd466d6Ahmet Kaan GümüşParent: 50e3988
  • perf
    • the decoder stops waiting for the encoder
Show full message
⚡ perf(export): the decoder stops waiting for the encoder

An export decoded a picture, encoded it, decoded the next: two engines taking
turns, each idle while the other worked. The decode now runs on a thread of its
own and hands pictures over a channel two deep, so the encode of picture n
overlaps the decode of picture n + 1 -- and the bound is what keeps it honest,
since a decoder that ran ahead without one would hold a film's worth of 3 MB
pictures.

The thread is also where the plugin is opened: a VA-API session is not ours to
pass between threads, so the open happens there and its failure comes back down
the channel, which is why a vanished source and a codec with no decoder still
fail the export rather than looking like a clip that ran out.

A 1080p h264 minute exports at 93.3 fps against 73.4 (hardware encode) and
18.3 against 17.5 (software, where the encoder is the wall). The written file
is the same one: 1438 frames for the 60 s span, 59.977 s at 24000/1001, zero
errors decoding it back, and the round-trip tests hold on both seats.
crates/engine/src/export.rsmodified+119 -9
@@ -58,6 +58,7 @@ use std::fs::File;
58 use std::io::{BufWriter, Write};58 use std::io::{BufWriter, Write};
59 use std::path::{Path, PathBuf};59 use std::path::{Path, PathBuf};
60 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};60 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
61+use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
61 use std::sync::{Arc, Mutex};62 use std::sync::{Arc, Mutex};
62 use std::thread;63 use std::thread;
63 64
@@ -3142,14 +3143,40 @@ fn pop_av1<'a>(
3142 /// software: a hardware decode that fails after the first picture fails the3143 /// software: a hardware decode that fails after the first picture fails the
3143 /// export, which then deletes the half-written file.3144 /// export, which then deletes the half-written file.
3144 enum ClipDecoder {3145 enum ClipDecoder {
3145- Hw(HwSession),3146+ /// A stream, decoded on a thread of its own: the encode of picture *n* and
3146- Sw(SwDecoder),3147+ /// the decode of picture *n + 1* are the two halves an export used to do in
3148+ /// turns, each idle while the other worked. The channel is two pictures
3149+ /// deep, so the decoder runs no further ahead than that (a 1080p I420
3150+ /// picture is 3.1 MB) and a slow encoder still stops it.
3151+ ///
3152+ /// The thread is also where the plugin is *opened*: a VA-API session is not
3153+ /// ours to hand between threads ([`crate::decode::open_worker_deferred`]
3154+ /// keeps the same rule), which is why the open's error comes back down the
3155+ /// channel rather than out of [`ClipDecoder::open`].
3156+ Streamed(Streamed),
3147 /// A still image: one picture, handed out for as long as the span runs.3157 /// A still image: one picture, handed out for as long as the span runs.
3148 /// It is decoded here rather than in `run`'s loop for the same reason the3158 /// It is decoded here rather than in `run`'s loop for the same reason the
3149- /// other two are opened there -- the span's pictures come from one place.3159+ /// other two are opened there -- the span's pictures come from one place,
3160+ /// and no thread can make one picture arrive sooner.
3150 Still(crate::decode::Still),3161 Still(crate::decode::Still),
3151 }3162 }
3152 3163
3164+/// The receiving half of a decode thread, plus the picture it last handed out
3165+/// -- which is what lets `next` keep lending planes rather than moving them.
3166+struct Streamed {
3167+ frames: Receiver<crate::Result<Yuv>>,
3168+ current: Option<Yuv>,
3169+}
3170+
3171+/// One picture, owned, on its way from a decode thread to the encoder.
3172+struct Yuv {
3173+ y: Vec<u8>,
3174+ u: Vec<u8>,
3175+ v: Vec<u8>,
3176+ width: u32,
3177+ height: u32,
3178+}
3179+
3153 impl ClipDecoder {3180 impl ClipDecoder {
3154 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {3181 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
3155 // Before either decoder: an image is not a stream, so `start_frame`3182 // Before either decoder: an image is not a stream, so `start_frame`
@@ -3158,18 +3185,101 @@ impl ClipDecoder {
3158 if crate::is_image(path) {3185 if crate::is_image(path) {
3159 return Ok(Self::Still(crate::decode::Still::open(path)?));3186 return Ok(Self::Still(crate::decode::Still::open(path)?));
3160 }3187 }
3161- if !forced("VE_SW")3188+ let path = path.to_path_buf();
3162- && let Some(hw) = HwSession::open_at(path, start_frame)3189+ let (tx, frames) = sync_channel(2);
3163- {3190+ thread::Builder::new()
3164- return Ok(Self::Hw(hw));3191+ .name("export-decode".into())
3165- }3192+ .spawn(move || decode_stream(&path, start_frame, &tx))?;
3166- Ok(Self::Sw(SwDecoder::open(path, start_frame)?))3193+ Ok(Self::Streamed(Streamed {
3194+ frames,
3195+ current: None,
3196+ }))
3167 }3197 }
3168 3198
3169 /// The next picture as tightly packed I420, borrowed until the call after.3199 /// The next picture as tightly packed I420, borrowed until the call after.
3170 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {3200 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3171 match self {3201 match self {
3172 Self::Still(still) => Ok(Some(still.picture())),3202 Self::Still(still) => Ok(Some(still.picture())),
3203+ Self::Streamed(stream) => match stream.frames.recv() {
3204+ Ok(Ok(frame)) => {
3205+ let frame = stream.current.insert(frame);
3206+ Ok(Some((
3207+ &frame.y,
3208+ &frame.u,
3209+ &frame.v,
3210+ frame.width,
3211+ frame.height,
3212+ )))
3213+ }
3214+ Ok(Err(e)) => Err(e),
3215+ // The thread closed the channel: end of stream, and the only
3216+ // clean way it ends. Every failure came through as an `Err`
3217+ // above -- including the open's, which is why a file the
3218+ // plugin refuses still fails the export rather than looking
3219+ // like a clip that ran out.
3220+ Err(_) => Ok(None),
3221+ },
3222+ }
3223+ }
3224+}
3225+
3226+/// One span's decode, on its own thread: open the file (hardware if the plugin
3227+/// will have it, software otherwise) and send every picture until the encoder
3228+/// stops taking them.
3229+///
3230+/// Unlike playback there is no mid-clip fallback to software: a hardware decode
3231+/// that fails after the first picture fails the export, which then deletes the
3232+/// half-written file.
3233+fn decode_stream(path: &Path, start_frame: u32, tx: &SyncSender<crate::Result<Yuv>>) {
3234+ let opened = match forced("VE_SW") {
3235+ false => HwSession::open_at(path, start_frame).map(Pictures::Hw),
3236+ true => None,
3237+ };
3238+ let mut decoder = match opened {
3239+ Some(hw) => hw,
3240+ None => match SwDecoder::open(path, start_frame) {
3241+ Ok(sw) => Pictures::Sw(sw),
3242+ Err(e) => {
3243+ let _ = tx.send(Err(e));
3244+ return;
3245+ }
3246+ },
3247+ };
3248+ loop {
3249+ // Copied out of the decoder's own buffer, which it reuses for the next
3250+ // picture: one 3 MB memcpy per frame against the decode and the encode
3251+ // it lets overlap.
3252+ let frame = match decoder.next() {
3253+ Ok(Some((y, u, v, width, height))) => Yuv {
3254+ y: y.to_vec(),
3255+ u: u.to_vec(),
3256+ v: v.to_vec(),
3257+ width,
3258+ height,
3259+ },
3260+ Ok(None) => return,
3261+ Err(e) => {
3262+ let _ = tx.send(Err(e));
3263+ return;
3264+ }
3265+ };
3266+ // The consumer went away: the span ended early, or the export was
3267+ // cancelled. Either way there is nothing left to decode for.
3268+ if tx.send(Ok(frame)).is_err() {
3269+ return;
3270+ }
3271+ }
3272+}
3273+
3274+/// The two stream decoders, on the thread that opened them.
3275+enum Pictures {
3276+ Hw(HwSession),
3277+ Sw(SwDecoder),
3278+}
3279+
3280+impl Pictures {
3281+ fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3282+ match self {
3173 Self::Hw(hw) => hw.next_frame(),3283 Self::Hw(hw) => hw.next_frame(),
3174 Self::Sw(sw) => {3284 Self::Sw(sw) => {
3175 if !sw.advance()? {3285 if !sw.advance()? {