forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

shared.rs238 lines, 8.5 KiBHistoryRawDownload
1//! The part of a picture that other pictures read while it is still being decoded.
2//!
3//! With frame threads a later picture predicts from an earlier one that another
4//! worker is still reconstructing. A [`SharedPic`] is the handoff between the two:
5//!
6//! - The samples live in an `RwLock<DecodedPicture>`. The worker that decodes the
7//! picture copies a CTB row into it only once that row is final (after the in-loop
8//! filters, see [`super::rowfilter`]). Rows are published top to bottom, so the
9//! published region is always a prefix of the picture.
10//! - The collocated motion ([`ColField`]) is filled per CTB row as the rows are
11//! parsed, in the same way.
12//! - A `Mutex` holds the progress counters and a `Condvar` wakes the readers when a
13//! counter moves. A reader waits for the rows it needs and then takes a read lock,
14//! so no lock is held across a wait. The writer never waits while it holds a lock.
15//!
16//! A failed picture records its error here, which wakes every waiter with an error.
17//! Waiting never reads the samples of an unfinished row.
18
19use std::sync::{Condvar, Mutex, MutexGuard, RwLock, RwLockReadGuard};
20
21use super::motion_field::{ColField, MotionField};
22use crate::decode::DecodedPicture;
23use ec_core::error::{Error, Result};
24
25/// Progress counters and the failure of a picture.
26#[derive(Debug, Default)]
27struct Progress {
28 /// Luma rows whose samples are final (a prefix of the picture).
29 rows: usize,
30 /// Luma rows whose collocated motion is in [`SharedPic::col`].
31 col_rows: usize,
32 /// Every row is final, or the picture failed.
33 done: bool,
34 /// The first failure of the picture.
35 error: Option<String>,
36}
37
38/// A picture whose samples and collocated motion are published row by row.
39#[derive(Debug)]
40pub struct SharedPic {
41 /// Luma width.
42 pub width: usize,
43 /// Luma height.
44 pub height: usize,
45 planes: RwLock<DecodedPicture>,
46 col: RwLock<ColField>,
47 progress: Mutex<Progress>,
48 changed: Condvar,
49}
50
51fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
52 // A poisoned lock only means another thread panicked while holding it; the
53 // counters it guards are plain integers, so the value is still usable.
54 m.lock().unwrap_or_else(|e| e.into_inner())
55}
56
57impl SharedPic {
58 /// The storage of a `width` by `height` picture of POC `poc`. With `pixels`
59 /// false no sample planes are allocated (the motion-only decode).
60 pub fn new(
61 poc: i32,
62 width: usize,
63 height: usize,
64 bit_depth: (u32, u32),
65 pixels: bool,
66 chroma_format_idc: u32,
67 ) -> SharedPic {
68 let planes = if pixels {
69 let (sx, sy) = crate::decode::chroma_shifts(chroma_format_idc);
70 let cw = width.div_ceil(1 << sx);
71 let ch = height.div_ceil(1 << sy);
72 DecodedPicture {
73 width,
74 height,
75 bit_depth: bit_depth.0,
76 bit_depth_c: bit_depth.1,
77 chroma_format_idc,
78 y: vec![0; width * height],
79 cb: vec![0; cw * ch],
80 cr: vec![0; cw * ch],
81 }
82 } else {
83 DecodedPicture {
84 width,
85 height,
86 bit_depth: 8,
87 bit_depth_c: 8,
88 chroma_format_idc,
89 y: Vec::new(),
90 cb: Vec::new(),
91 cr: Vec::new(),
92 }
93 };
94 SharedPic {
95 width,
96 height,
97 planes: RwLock::new(planes),
98 col: RwLock::new(ColField::new(poc, width, height)),
99 progress: Mutex::new(Progress::default()),
100 changed: Condvar::new(),
101 }
102 }
103
104 /// A finished picture with the given samples and no motion: a generated picture (8.3.3).
105 pub fn from_planes(poc: i32, planes: DecodedPicture) -> SharedPic {
106 let (width, height) = (planes.width, planes.height);
107 SharedPic {
108 width,
109 height,
110 planes: RwLock::new(planes),
111 col: RwLock::new(ColField::new(poc, width, height)),
112 progress: Mutex::new(Progress {
113 rows: height,
114 col_rows: height,
115 done: true,
116 error: None,
117 }),
118 changed: Condvar::new(),
119 }
120 }
121
122 /// Wait until at least `rows` luma rows are final. Returns the picture's failure
123 /// instead when it has one.
124 pub fn wait_rows(&self, rows: usize) -> Result<()> {
125 let t = super::trace::now();
126 let r = self.wait_for(rows, |p| p.rows);
127 super::trace::since(super::trace::Phase::WaitRows, t);
128 r
129 }
130
131 /// Wait until the collocated motion of at least `rows` luma rows is published.
132 pub fn wait_col_rows(&self, rows: usize) -> Result<()> {
133 self.wait_for(rows, |p| p.col_rows)
134 }
135
136 /// Wait for the whole picture (samples and motion) and return its samples.
137 pub fn snapshot(&self) -> Result<std::sync::Arc<DecodedPicture>> {
138 self.wait_rows(usize::MAX)?;
139 let planes = self.planes.read().unwrap_or_else(|e| e.into_inner());
140 let mut out = planes.clone();
141 if out.chroma_format_idc == 0 {
142 // The decoder keeps dummy chroma planes of a 4:0:0 picture; the output has none.
143 out.cb = Vec::new();
144 out.cr = Vec::new();
145 }
146 Ok(std::sync::Arc::new(out))
147 }
148
149 /// The published samples. Only rows below the last [`wait_rows`](Self::wait_rows)
150 /// result are meaningful.
151 pub fn read_planes(&self) -> RwLockReadGuard<'_, DecodedPicture> {
152 self.planes.read().unwrap_or_else(|e| e.into_inner())
153 }
154
155 /// The published collocated motion.
156 pub fn read_col(&self) -> RwLockReadGuard<'_, ColField> {
157 self.col.read().unwrap_or_else(|e| e.into_inner())
158 }
159
160 /// Copy the final luma rows `from..to` (and the chroma rows of the same area) of
161 /// `src` into the published planes, then publish them. `src` has this picture's
162 /// dimensions. A picture without planes only moves the counter.
163 pub fn publish_rows(&self, src: &DecodedPicture, to: usize) {
164 let from = lock(&self.progress).rows;
165 if to <= from {
166 return;
167 }
168 if !src.y.is_empty() {
169 let w = self.width;
170 let mut planes = self.planes.write().unwrap_or_else(|e| e.into_inner());
171 let (sx, sy) = planes.chroma_shifts();
172 let cw = w.div_ceil(1 << sx);
173 let (cf, ct) = (from >> sy, to.div_ceil(1 << sy));
174 planes.y[from * w..to * w].copy_from_slice(&src.y[from * w..to * w]);
175 planes.cb[cf * cw..ct * cw].copy_from_slice(&src.cb[cf * cw..ct * cw]);
176 planes.cr[cf * cw..ct * cw].copy_from_slice(&src.cr[cf * cw..ct * cw]);
177 }
178 self.advance(|p| p.rows = to);
179 }
180
181 /// Publish the collocated motion of the luma rows up to `to`, read from `field`
182 /// (the motion field of this picture; rows already published are skipped).
183 pub fn publish_col(&self, field: &MotionField, to: usize) {
184 let from = lock(&self.progress).col_rows;
185 if to <= from {
186 return;
187 }
188 self.col
189 .write()
190 .unwrap_or_else(|e| e.into_inner())
191 .fill_rows(field, from, to);
192 self.advance(|p| p.col_rows = to);
193 }
194
195 /// The picture is complete: every row is final and its motion is published.
196 pub fn complete(&self) {
197 self.advance(|p| {
198 p.rows = self.height;
199 p.col_rows = self.height;
200 p.done = true;
201 });
202 }
203
204 /// The picture failed. Waiters are released with `message`.
205 pub fn fail(&self, message: &str) {
206 self.advance(|p| {
207 p.done = true;
208 if p.error.is_none() {
209 p.error = Some(message.to_string());
210 }
211 });
212 }
213
214 /// Wait until the picture is complete (or failed).
215 pub fn wait_done(&self) -> Result<()> {
216 self.wait_rows(usize::MAX)
217 }
218
219 fn advance(&self, f: impl FnOnce(&mut Progress)) {
220 let mut p = lock(&self.progress);
221 f(&mut p);
222 drop(p);
223 self.changed.notify_all();
224 }
225
226 fn wait_for(&self, want: usize, got: impl Fn(&Progress) -> usize) -> Result<()> {
227 let mut p = lock(&self.progress);
228 loop {
229 if let Some(e) = &p.error {
230 return Err(Error::corrupt(format!("HEVC decode: {e}")));
231 }
232 if p.done || got(&p) >= want {
233 return Ok(());
234 }
235 p = self.changed.wait(p).unwrap_or_else(|e| e.into_inner());
236 }
237 }
238}