forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

runner.rs245 lines, 7.9 KiBHistoryRawDownload
1//! Where a picture is decoded: on the calling thread, or on a worker thread of its own.
2//!
3//! With frame threads each picture gets one worker thread. The decoder sends the worker
4//! the picture's slices in decoding order, then its finish, and goes on with the next
5//! picture. The worker runs the slices on its [`PicJob`] and publishes each row as it
6//! becomes final ([`super::shared`]). A worker only waits for pictures decoded before its
7//! own (its references and collocated picture), and the decoder keeps at most `threads`
8//! pictures in flight, so the waits form no cycle.
9//!
10//! With one thread every picture is decoded inline: the same job, run on the calling
11//! thread as each slice arrives, so an error comes back from the call that caused it.
12//!
13//! A worker that fails (a corrupt slice, or a panic) marks its picture as failed in the
14//! shared picture, so anything waiting on it wakes with the error.
15
16use std::panic::{AssertUnwindSafe, catch_unwind};
17use std::sync::mpsc::{self, Receiver, Sender};
18use std::sync::{Arc, Condvar, Mutex, MutexGuard};
19use std::thread::JoinHandle;
20
21use super::picjob::{PicJob, SliceJob};
22use super::trace::{self, Phase};
23use ec_core::error::{Error, Result};
24
25fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
26 // The guarded values are plain data; a poisoned lock is still usable.
27 m.lock().unwrap_or_else(|e| e.into_inner())
28}
29
30/// The worker threads of the decoder, shared by the pictures in flight (frame threads)
31/// and the wavefront row workers of each picture. A picture always holds one thread while
32/// it is in flight; the rest of the budget is handed out as extra row workers by
33/// [`Budget::take_extra`], which never waits.
34#[derive(Debug)]
35pub struct Budget {
36 total: usize,
37 used: Mutex<BudgetUse>,
38}
39
40#[derive(Debug, Default)]
41struct BudgetUse {
42 pictures: usize,
43 extra: usize,
44}
45
46impl Budget {
47 /// A budget of `total` threads.
48 pub fn new(total: usize) -> Arc<Budget> {
49 Arc::new(Budget {
50 total: total.max(1),
51 used: Mutex::new(BudgetUse::default()),
52 })
53 }
54
55 /// Take up to `want` extra threads, as many as the threads no picture or row worker
56 /// is using allow. The threads are given back when the returned guard drops.
57 pub fn take_extra(self: &Arc<Self>, want: usize) -> ExtraThreads {
58 let mut used = lock(&self.used);
59 let free = self.total.saturating_sub(used.pictures + used.extra);
60 let n = want.min(free);
61 used.extra += n;
62 ExtraThreads {
63 budget: Arc::clone(self),
64 n,
65 }
66 }
67}
68
69/// Extra threads taken from a [`Budget`] for one picture's row workers.
70#[derive(Debug)]
71pub struct ExtraThreads {
72 budget: Arc<Budget>,
73 n: usize,
74}
75
76impl ExtraThreads {
77 /// How many extra threads were taken.
78 pub fn count(&self) -> usize {
79 self.n
80 }
81}
82
83impl Drop for ExtraThreads {
84 fn drop(&mut self) {
85 lock(&self.budget.used).extra -= self.n;
86 }
87}
88
89/// One picture's hold on the budget: taken when the picture is created, released when it
90/// is dropped (after its worker has finished, or with the inline job).
91#[derive(Debug)]
92pub struct PictureSlot {
93 budget: Arc<Budget>,
94}
95
96impl PictureSlot {
97 /// Take a picture's thread from `budget`.
98 pub fn new(budget: Arc<Budget>) -> PictureSlot {
99 lock(&budget.used).pictures += 1;
100 PictureSlot { budget }
101 }
102}
103
104impl Drop for PictureSlot {
105 fn drop(&mut self) {
106 lock(&self.budget.used).pictures -= 1;
107 }
108}
109
110/// The motion checksum of one picture (see [`super::Decoder::motion_checksum`]), set when
111/// the picture finishes. The value is `None` for a picture no slice ran in, and also for a
112/// picture that failed.
113#[derive(Debug, Default)]
114pub struct Checksum {
115 value: Mutex<Option<Option<u64>>>,
116 changed: Condvar,
117}
118
119impl Checksum {
120 /// Store the picture's value and wake the readers.
121 pub fn set(&self, value: Option<u64>) {
122 *lock(&self.value) = Some(value);
123 self.changed.notify_all();
124 }
125
126 /// Wait until the value is stored.
127 pub fn wait(&self) -> Option<u64> {
128 let mut value = lock(&self.value);
129 loop {
130 if let Some(v) = *value {
131 return v;
132 }
133 value = self.changed.wait(value).unwrap_or_else(|e| e.into_inner());
134 }
135 }
136}
137
138/// A message to a picture's worker.
139pub enum Msg {
140 /// Run this slice segment.
141 Slice(Box<SliceJob>),
142 /// The picture is complete: finish it and stop.
143 Finish,
144}
145
146/// The decoding of one picture, on the calling thread or on its own worker.
147pub enum Runner {
148 /// On the calling thread.
149 Inline {
150 /// The picture's job.
151 job: Box<PicJob>,
152 /// Set when the picture finishes.
153 checksum: Arc<Checksum>,
154 },
155 /// On a worker thread that owns the job.
156 Worker {
157 /// The queue of messages to the worker.
158 tx: Sender<Msg>,
159 /// The worker thread.
160 handle: JoinHandle<()>,
161 },
162}
163
164impl Runner {
165 /// Start the decoding of the picture of `job`. `threaded` gives it a worker thread.
166 pub fn start(job: PicJob, checksum: Arc<Checksum>, threaded: bool) -> Runner {
167 if !threaded {
168 return Runner::Inline {
169 job: Box::new(job),
170 checksum,
171 };
172 }
173 let (tx, rx) = mpsc::channel();
174 let handle = std::thread::spawn(move || run_worker(rx, job, checksum));
175 Runner::Worker { tx, handle }
176 }
177
178 /// Give the picture one slice segment. Inline, the slice runs now and its error is
179 /// returned; on a worker it is queued, and an error surfaces when the picture's
180 /// output is taken.
181 pub fn submit(&mut self, slice: SliceJob) -> Result<()> {
182 match self {
183 Runner::Inline { job, .. } => job.run_slice(slice),
184 Runner::Worker { tx, .. } => {
185 // A worker that is gone has already failed its picture.
186 let _ = tx.send(Msg::Slice(Box::new(slice)));
187 Ok(())
188 }
189 }
190 }
191
192 /// The picture is complete. Inline, it finishes now. A worker is told to finish and
193 /// goes on in the background; its handle is returned to be joined later.
194 pub fn finish(self) -> Option<JoinHandle<()>> {
195 match self {
196 Runner::Inline { mut job, checksum } => {
197 checksum.set(job.finish());
198 None
199 }
200 Runner::Worker { tx, handle } => {
201 let _ = tx.send(Msg::Finish);
202 Some(handle)
203 }
204 }
205 }
206}
207
208/// The body of a picture's worker thread. A failure, a panic, or a picture dropped before
209/// its finish marks the picture as failed, so that nothing waits on it forever.
210fn run_worker(rx: Receiver<Msg>, mut job: PicJob, checksum: Arc<Checksum>) {
211 let shared = Arc::clone(job.shared());
212 trace::set_role("picture");
213 let outcome = catch_unwind(AssertUnwindSafe(|| -> Result<Option<u64>> {
214 loop {
215 let idle = trace::now();
216 let msg = rx.recv();
217 trace::since(Phase::WaitMsg, idle);
218 let Ok(msg) = msg else { break };
219 let busy = trace::now();
220 match msg {
221 Msg::Slice(slice) => job.run_slice(*slice)?,
222 Msg::Finish => {
223 let sum = job.finish();
224 trace::since(Phase::Decode, busy);
225 return Ok(sum);
226 }
227 }
228 trace::since(Phase::Decode, busy);
229 }
230 Err(Error::corrupt(
231 "HEVC decode: a picture was dropped before it finished".to_string(),
232 ))
233 }));
234 match outcome {
235 Ok(Ok(sum)) => checksum.set(sum),
236 Ok(Err(e)) => {
237 shared.fail(&e.to_string());
238 checksum.set(None);
239 }
240 Err(_) => {
241 shared.fail("HEVC decode: the picture's worker thread panicked");
242 checksum.set(None);
243 }
244 }
245}