forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

wpp.rs664 lines, 23.7 KiBHistoryRawDownload
1//! Wavefront parallel decoding of a slice segment (H.265 9.3.1 and 9.3.2.2) for pictures
2//! with `entropy_coding_sync_enabled_flag`.
3//!
4//! The segment starts at the first CTB of a row and its substreams start at the rows
5//! after it, so each row can be parsed and reconstructed by its own worker, from its own
6//! substream, once the row above is two CTBs ahead: the contexts after CTB 1 of the row
7//! above start the row, and the CTBs of the row above that a CTB reads (its left, above,
8//! above-left and above-right neighbours) are final by then.
9//!
10//! Each row works on a band of the picture: its own maps and samples, plus a copy of the
11//! last sample, unit and CTB row of the row above. The row above publishes that copy as
12//! each of its CTBs completes, on the [`Board`]. When the segment is done the bands are
13//! merged back in row order: the samples and maps, the motion cells and their checksum,
14//! and then the in-loop filter callbacks, which therefore run in the same order as a
15//! serial parse.
16
17use std::panic::{AssertUnwindSafe, catch_unwind};
18use std::sync::atomic::{AtomicUsize, Ordering};
19use std::sync::{Condvar, Mutex, MutexGuard};
20
21use super::{MotionSource, SliceStats, new_parser, trailing_bits_ok};
22use crate::cabac::{CabacDecoder, Contexts};
23use crate::dec::inter::InterRefs;
24use crate::dec::motion_field::{FieldCell, MotionField, SliceMotion};
25use crate::dec::pic::{BlockInfo, CtbInfo, PicState, SliceFilter};
26use crate::dec::tiles::TileScan;
27use crate::dec::trace::{self, Phase};
28use ec_core::error::{Error, Result};
29use ec_h265_syntax::slice::{SliceHeader, SliceType};
30use ec_h265_syntax::{Pps, Sps};
31
32fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
33 // The guarded values are plain data; a poisoned lock is still usable.
34 m.lock().unwrap_or_else(|e| e.into_inner())
35}
36
37/// What a finished CTB row publishes for the row below it: its last sample row, unit row
38/// and CTB entries, and the contexts after its CTB 1.
39#[derive(Default)]
40struct Slot {
41 /// CTBs of the row completed, in order.
42 done: usize,
43 luma: Vec<u16>,
44 cb: Vec<u16>,
45 cr: Vec<u16>,
46 units: Vec<BlockInfo>,
47 cells: Vec<Option<FieldCell>>,
48 ctb: Vec<CtbInfo>,
49 wpp: Option<Contexts>,
50}
51
52#[derive(Default)]
53struct BoardState {
54 slots: Vec<Slot>,
55 failed: Option<String>,
56}
57
58/// The rows' published state of one segment. A row waits on the board for the row above.
59struct Board {
60 state: Mutex<BoardState>,
61 changed: Condvar,
62 cols: usize,
63 ctb_log2: u32,
64 width: usize,
65 height: usize,
66 w4: usize,
67 /// The log2 chroma subsampling `(sub_x, sub_y)`.
68 sub_x: u32,
69 sub_y: u32,
70}
71
72impl Board {
73 fn new(pic: &PicState) -> Board {
74 Board {
75 state: Mutex::new(BoardState {
76 slots: (0..pic.ctb_rows).map(|_| Slot::default()).collect(),
77 failed: None,
78 }),
79 changed: Condvar::new(),
80 cols: pic.ctb_cols,
81 ctb_log2: pic.ctb_log2,
82 width: pic.width,
83 height: pic.height,
84 w4: pic.w4,
85 sub_x: pic.sub_x(),
86 sub_y: pic.sub_y(),
87 }
88 }
89
90 /// Mark the segment failed and wake every waiter.
91 fn fail(&self, why: &str) {
92 let mut st = lock(&self.state);
93 if st.failed.is_none() {
94 st.failed = Some(why.to_string());
95 }
96 self.changed.notify_all();
97 }
98
99 /// Publish the row above a segment that starts a row: its state as the picture
100 /// holds it now, which is final because the earlier segments are complete.
101 fn prefill(&self, ry: usize, pic: &PicState, field: &MotionField) {
102 // The same bottom rows of CTB row `ry` that `leave` publishes.
103 let ctb = 1usize << self.ctb_log2;
104 let y0 = ry << self.ctb_log2;
105 let cw = self.width.div_ceil(1 << self.sub_x);
106 let mut st = lock(&self.state);
107 let slot = &mut st.slots[ry];
108 if pic.has_pixels() {
109 let lr = (y0 + ctb - 1) - pic.origin_y;
110 slot.luma = pic.planes.y[lr * self.width..(lr + 1) * self.width].to_vec();
111 let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c;
112 slot.cb = pic.planes.cb[lc * cw..(lc + 1) * cw].to_vec();
113 slot.cr = pic.planes.cr[lc * cw..(lc + 1) * cw].to_vec();
114 }
115 let ur = (y0 + ctb - 4) / 4;
116 let band_row = ur - pic.origin_unit / 4;
117 slot.units = pic.info[band_row * self.w4..(band_row + 1) * self.w4].to_vec();
118 slot.cells = field.cell_row(ur).to_vec();
119 slot.ctb = pic.ctb[ry * self.cols..(ry + 1) * self.cols].to_vec();
120 slot.wpp = pic.carry.wpp.clone();
121 slot.done = self.cols;
122 self.changed.notify_all();
123 }
124
125 /// Before CTB `x` of row `ry`: wait until the row above is two CTBs ahead (or done),
126 /// copy in what the CTB reads from it, and return the row's starting contexts when
127 /// `x` is 0 (the contexts the row above stored after its CTB 1).
128 fn enter(
129 &self,
130 ry: usize,
131 x: usize,
132 pic: &mut PicState,
133 motion: &mut dyn MotionSource,
134 ) -> Result<Option<Contexts>> {
135 if ry == 0 {
136 return Ok(None);
137 }
138 let ctb = 1usize << self.ctb_log2;
139 let cols = self.cols;
140 let need = (x + 2).min(cols);
141 let mut st = lock(&self.state);
142 let t = trace::now();
143 loop {
144 if let Some(why) = &st.failed {
145 return Err(Error::corrupt(format!("HEVC slice (wavefront): {why}")));
146 }
147 if st.slots[ry - 1].done >= need {
148 break;
149 }
150 st = self.changed.wait(st).unwrap_or_else(|e| e.into_inner());
151 }
152 trace::since(Phase::WaitSync, t);
153 let slot = &st.slots[ry - 1];
154 let k0 = x.saturating_sub(1);
155 let k1 = (x + 1).min(cols - 1);
156 let cw = self.width.div_ceil(1 << self.sub_x);
157 for k in k0..=k1 {
158 let (a, b) = (k * ctb, ((k + 1) * ctb).min(self.width));
159 let (ca, cb_end) = (
160 (k * ctb) >> self.sub_x,
161 (((k + 1) * ctb) >> self.sub_x).min(cw),
162 );
163 if pic.has_pixels() {
164 pic.planes.y[a..b].copy_from_slice(&slot.luma[a..b]);
165 pic.planes.cb[ca..cb_end].copy_from_slice(&slot.cb[ca..cb_end]);
166 pic.planes.cr[ca..cb_end].copy_from_slice(&slot.cr[ca..cb_end]);
167 }
168 let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4));
169 pic.info[ua..ub].copy_from_slice(&slot.units[ua..ub]);
170 pic.ctb[(ry - 1) * cols + k] = slot.ctb[k];
171 }
172 let unit_row = (ry << self.ctb_log2) / 4 - 1;
173 let field = motion
174 .band_cells()
175 .ok_or_else(|| Error::corrupt("HEVC slice (wavefront): a row without a motion band"))?;
176 for k in k0..=k1 {
177 let (ua, ub) = (k * ctb / 4, ((k + 1) * ctb / 4).min(self.w4));
178 field.cell_row_mut(unit_row)[ua..ub].copy_from_slice(&slot.cells[ua..ub]);
179 }
180 Ok((x == 0).then(|| slot.wpp.clone()).flatten())
181 }
182
183 /// After CTB `x` of row `ry` is complete: publish what the row below reads. `wpp` is
184 /// the contexts after CTB 1, when `x` is 1.
185 fn leave(
186 &self,
187 ry: usize,
188 x: usize,
189 pic: &PicState,
190 motion: &mut dyn MotionSource,
191 wpp: Option<&Contexts>,
192 ) -> Result<()> {
193 let ctb = 1usize << self.ctb_log2;
194 let y0 = ry << self.ctb_log2;
195 let full = y0 + ctb <= self.height;
196 let (a, b) = (x * ctb, ((x + 1) * ctb).min(self.width));
197 let cw = self.width.div_ceil(1 << self.sub_x);
198 let (ca, cb_end) = (
199 (x * ctb) >> self.sub_x,
200 (((x + 1) * ctb) >> self.sub_x).min(cw),
201 );
202 let (ua, ub) = (x * ctb / 4, ((x + 1) * ctb / 4).min(self.w4));
203 let field = if full {
204 Some(motion.band_cells().ok_or_else(|| {
205 Error::corrupt("HEVC slice (wavefront): a row without a motion band")
206 })?)
207 } else {
208 None
209 };
210 let mut st = lock(&self.state);
211 let slot = &mut st.slots[ry];
212 if slot.ctb.is_empty() {
213 slot.units = vec![BlockInfo::default(); self.w4];
214 slot.cells = vec![None; self.w4];
215 slot.ctb = vec![CtbInfo::default(); self.cols];
216 slot.luma = vec![0; self.width];
217 slot.cb = vec![0; cw];
218 slot.cr = vec![0; cw];
219 }
220 if full {
221 // Band rows: the sample rows and unit row of the CTB row's last rows.
222 if pic.has_pixels() {
223 let lr = (y0 + ctb - 1) - pic.origin_y;
224 slot.luma[a..b]
225 .copy_from_slice(&pic.planes.y[lr * self.width + a..lr * self.width + b]);
226 let lc = ((y0 >> self.sub_y) + (ctb >> self.sub_y) - 1) - pic.origin_c;
227 slot.cb[ca..cb_end].copy_from_slice(&pic.planes.cb[lc * cw + ca..lc * cw + cb_end]);
228 slot.cr[ca..cb_end].copy_from_slice(&pic.planes.cr[lc * cw + ca..lc * cw + cb_end]);
229 }
230 let ur = (y0 + ctb - 4) / 4;
231 let band_row = ur - pic.origin_unit / 4;
232 slot.units[ua..ub]
233 .copy_from_slice(&pic.info[band_row * self.w4 + ua..band_row * self.w4 + ub]);
234 if let Some(field) = field {
235 slot.cells[ua..ub].copy_from_slice(&field.cell_row(ur)[ua..ub]);
236 }
237 }
238 // The CTB entry is always kept, so that the row below sees the slice and tile of
239 // every CTB it may read.
240 slot.ctb[x] = pic.ctb[ry * self.cols + x];
241 if let Some(c) = wpp {
242 slot.wpp = Some(c.clone());
243 }
244 slot.done = x + 1;
245 self.changed.notify_all();
246 Ok(())
247 }
248
249 /// The contexts a row stored after its CTB 1, taken once the segment is done.
250 fn take_wpp(&self, ry: usize) -> Option<Contexts> {
251 lock(&self.state).slots[ry].wpp.take()
252 }
253}
254
255/// The state of one CTB row's parse, as the row's [`Link`] sees it.
256struct Link<'b> {
257 board: &'b Board,
258 ry: usize,
259}
260
261/// What the row loop asks of its neighbours: the board reads and publications.
262trait RowSync {
263 fn enter(
264 &mut self,
265 pic: &mut PicState,
266 motion: &mut dyn MotionSource,
267 x: usize,
268 ) -> Result<Option<Contexts>>;
269 fn leave(
270 &mut self,
271 pic: &PicState,
272 motion: &mut dyn MotionSource,
273 x: usize,
274 wpp: Option<&Contexts>,
275 ) -> Result<()>;
276}
277
278impl RowSync for Link<'_> {
279 fn enter(
280 &mut self,
281 pic: &mut PicState,
282 motion: &mut dyn MotionSource,
283 x: usize,
284 ) -> Result<Option<Contexts>> {
285 self.board.enter(self.ry, x, pic, motion)
286 }
287
288 fn leave(
289 &mut self,
290 pic: &PicState,
291 motion: &mut dyn MotionSource,
292 x: usize,
293 wpp: Option<&Contexts>,
294 ) -> Result<()> {
295 self.board.leave(self.ry, x, pic, motion, wpp)
296 }
297}
298
299/// The values every row of the segment shares.
300struct SegConsts {
301 slice_qp: i32,
302 fresh: Contexts,
303 slice_index: u16,
304 slice_addr: u32,
305}
306
307/// What one row's parse hands back.
308struct RowOut {
309 stats: SliceStats,
310 contexts: Contexts,
311 last_qp: i32,
312 trailing_ok: bool,
313}
314
315/// One finished row: its band and what it parsed.
316struct RowDone {
317 ry: usize,
318 band: PicState,
319 field: MotionField,
320 out: RowOut,
321}
322
323/// Parse one CTB row of the segment from `data` (the row's substream, to the end of the
324/// slice data). `row_len` is the substream's length when another row follows it.
325#[allow(clippy::too_many_arguments)] // the row's inputs and its neighbours
326fn parse_row(
327 sps: &Sps,
328 pps: &Pps,
329 header: &SliceHeader,
330 pic: &mut PicState,
331 motion: &mut dyn MotionSource,
332 refs: Option<&InterRefs>,
333 seg: &SegConsts,
334 data: &[u8],
335 ry: usize,
336 last: bool,
337 row_len: Option<usize>,
338 sync: &mut dyn RowSync,
339) -> Result<RowOut> {
340 let cols = pic.ctb_cols;
341 let ctb_log2 = pic.ctb_log2;
342 let ctb = 1usize << ctb_log2;
343 let sao = header.sao_luma || header.sao_chroma;
344 let mut p = new_parser(sps, pps, header, pic, refs, motion, seg.slice_qp);
345 let mut dec = CabacDecoder::new(data, seg.fresh.clone());
346 let mut ended = false;
347 for x in 0..cols {
348 let rs = ry * cols + x;
349 let (x0, y0) = (x << ctb_log2, ry << ctb_log2);
350 {
351 let info = p
352 .pic
353 .ctb
354 .get_mut(rs)
355 .ok_or_else(|| Error::corrupt("HEVC slice: CTB address past the picture"))?;
356 *info = CtbInfo {
357 slice: seg.slice_index,
358 slice_addr: seg.slice_addr,
359 tile: 0,
360 sao: info.sao,
361 };
362 }
363 p.stats.ctus += 1;
364 let wpp_ctx = sync.enter(&mut *p.pic, &mut *p.motion, x)?;
365 if x == 0 {
366 // 9.3.1: a row syncs from the row above when its CTB 1 is available.
367 let top_right =
368 p.pic
369 .available(x0, y0, (x0 + ctb) as isize, y0 as isize - ctb as isize);
370 dec.contexts = match (top_right, wpp_ctx) {
371 (true, Some(saved)) => saved,
372 _ => seg.fresh.clone(),
373 };
374 p.last_qp = seg.slice_qp;
375 }
376 if sao {
377 p.sao(&mut dec, rs, x, ry)?;
378 }
379 p.coding_quadtree(&mut dec, x0, y0, ctb_log2, 0, &mut |_| {})?;
380 // 9.3.2.2: the wavefront storage after the second CTB of a row.
381 let stored = (x == 1 && cols > 1).then(|| dec.contexts.clone());
382 sync.leave(&*p.pic, &mut *p.motion, x, stored.as_ref())?;
383 if dec.decode_terminate() != 0 {
384 if !last {
385 return Err(Error::corrupt(
386 "HEVC slice syntax: the segment ended inside a wavefront row before its last substream",
387 ));
388 }
389 ended = true;
390 break;
391 }
392 if x + 1 == cols {
393 if last {
394 return Err(Error::corrupt(
395 "HEVC slice syntax: slice data continues past the last wavefront substream",
396 ));
397 }
398 if dec.decode_terminate() != 1 {
399 return Err(Error::corrupt(
400 "HEVC slice syntax: end_of_subset_one_bit was not set at a substream boundary",
401 ));
402 }
403 if row_len.is_some_and(|len| dec.byte_position_aligned() != len) {
404 return Err(Error::corrupt(
405 "HEVC slice syntax: a wavefront substream does not end at its entry point",
406 ));
407 }
408 }
409 }
410 if last && !ended {
411 return Err(Error::corrupt(
412 "HEVC slice syntax: end_of_slice_segment_flag 0 after the last CTB of the picture",
413 ));
414 }
415 let trailing_ok = last && trailing_bits_ok(data, dec.bits_read());
416 let stats = std::mem::take(&mut p.stats);
417 Ok(RowOut {
418 stats,
419 contexts: dec.contexts.clone(),
420 last_qp: p.last_qp,
421 trailing_ok,
422 })
423}
424
425/// Whether a slice segment can run wavefront rows in parallel: a wavefront picture without
426/// tiles, a segment that starts a CTB row, and entry points for the rows after its first.
427pub(in crate::dec) fn can_run(
428 pps: &Pps,
429 header: &SliceHeader,
430 cols: usize,
431 ctb_rows: usize,
432 starts: &[usize],
433 data_len: usize,
434) -> bool {
435 if !pps.entropy_coding_sync_enabled || pps.tiles_enabled || starts.is_empty() {
436 return false;
437 }
438 let addr = header.segment_address as usize;
439 let rows = starts.len() + 1;
440 addr.is_multiple_of(cols)
441 && addr / cols + rows <= ctb_rows
442 && starts.windows(2).all(|w| w[0] < w[1])
443 && starts.iter().all(|&s| s > 0 && s < data_len)
444}
445
446/// Parse a slice segment whose rows run on up to `workers` threads (the calling thread
447/// included). `starts` are the data offsets of the substreams after the first. Errors
448/// and results match the serial parse: the same maps, samples, motion and checksum, and
449/// `rows` is called for each row in order, after the row's motion is final.
450#[allow(clippy::too_many_arguments)] // the segment, the picture it decodes into and its motion
451pub(in crate::dec) fn parse_segment(
452 sps: &Sps,
453 pps: &Pps,
454 header: &SliceHeader,
455 data: &[u8],
456 starts: &[usize],
457 pic: &mut PicState,
458 source: &mut SliceMotion<'_>,
459 refs: Option<&InterRefs>,
460 workers: usize,
461 rows: &mut dyn FnMut(&mut PicState, usize),
462) -> Result<SliceStats> {
463 let cols = pic.ctb_cols;
464 let ctb_rows = pic.ctb_rows;
465 let ctb_log2 = pic.ctb_log2;
466 let ctb = 1usize << ctb_log2;
467 let ry0 = header.segment_address as usize / cols;
468 let nrows = starts.len() + 1;
469 if !can_run(pps, header, cols, ctb_rows, starts, data.len()) || ry0 + nrows > ctb_rows {
470 return Err(Error::corrupt(
471 "HEVC slice (wavefront): the segment's substreams do not match its rows",
472 ));
473 }
474 // 6.5.1 and the slice's entry in the picture's slice list, as the serial parse sets them.
475 pic.tiles = TileScan::from_pps(pps, cols, ctb_rows)?;
476 if !header.dependent_slice_segment {
477 pic.carry.slice_addr = header.segment_address as usize;
478 }
479 let slice_index = u16::try_from(pic.slices.len()).map_err(|_| {
480 Error::unsupported("HEVC slice syntax: slice count", "more than 65535 slices")
481 })?;
482 pic.slices.push(SliceFilter {
483 deblock_disabled: header.deblocking_filter_disabled,
484 beta_offset_div2: header.beta_offset_div2,
485 tc_offset_div2: header.tc_offset_div2,
486 loop_filter_across_slices: header.loop_filter_across_slices_enabled,
487 sao_luma: header.sao_luma,
488 sao_chroma: header.sao_chroma,
489 });
490 let slice_qp = 26 + pps.init_qp_minus26 + header.qp_delta;
491 let init_type = match header.slice_type {
492 SliceType::I => 0,
493 SliceType::P => 1 + u8::from(header.cabac_init),
494 SliceType::B => 2 - u8::from(header.cabac_init),
495 };
496 let seg = SegConsts {
497 slice_qp,
498 fresh: Contexts::for_init_type(slice_qp, init_type),
499 slice_index,
500 slice_addr: pic.carry.slice_addr as u32,
501 };
502
503 let board = Board::new(pic);
504 if ry0 > 0 {
505 board.prefill(ry0 - 1, pic, &*source.field);
506 }
507 let pixels = pic.has_pixels();
508 let next = AtomicUsize::new(0);
509 let lists = source.lists;
510 let cur_poc = source.cur_poc;
511 let slice = source.slice;
512 let global: &PicState = pic;
513 let field_global: &MotionField = &*source.field;
514 let col = source.col.clone();
515
516 // One row: its band, its motion band, and the parse of the row's substream.
517 let do_row = |ry: usize| -> Result<RowDone> {
518 let i = ry - ry0;
519 let last = i + 1 == nrows;
520 let y0 = ry << ctb_log2;
521 let bound = usize::from(ry > 0);
522 let own = ctb.min(global.height - y0);
523 let mut band = global.band(y0, own, pixels);
524 let mut field = field_global.band((y0 - 4 * bound) / 4, bound + own.div_ceil(4));
525 let row_start = if i == 0 { 0 } else { starts[i - 1] };
526 let row_len = (!last).then(|| starts[i] - row_start);
527 let row_data = data
528 .get(row_start..)
529 .ok_or_else(|| Error::corrupt("HEVC slice (wavefront): a substream past the data"))?;
530 let mut motion = SliceMotion::new(
531 sps,
532 pps,
533 header,
534 lists,
535 cur_poc,
536 &mut field,
537 col.clone(),
538 slice,
539 );
540 let mut link = Link { board: &board, ry };
541 let out = parse_row(
542 sps,
543 pps,
544 header,
545 &mut band,
546 &mut motion,
547 refs,
548 &seg,
549 row_data,
550 ry,
551 last,
552 row_len,
553 &mut link,
554 )?;
555 Ok(RowDone {
556 ry,
557 band,
558 field,
559 out,
560 })
561 };
562 // The rows are taken in order, so a row only ever waits on a row another worker has
563 // already taken. A failing row fails the segment, which wakes every waiter.
564 let run = || -> Result<Vec<RowDone>> {
565 let mut done = Vec::new();
566 loop {
567 let i = next.fetch_add(1, Ordering::SeqCst);
568 if i >= nrows {
569 break;
570 }
571 let ry = ry0 + i;
572 let t = trace::now();
573 let outcome = catch_unwind(AssertUnwindSafe(|| do_row(ry)));
574 trace::since(Phase::Decode, t);
575 match outcome {
576 Ok(Ok(row)) => done.push(row),
577 Ok(Err(e)) => {
578 board.fail(&e.to_string());
579 return Err(e);
580 }
581 Err(_) => {
582 board.fail("the row's worker panicked");
583 return Err(Error::corrupt("HEVC slice (wavefront): a row panicked"));
584 }
585 }
586 }
587 Ok(done)
588 };
589 let results: Vec<Result<Vec<RowDone>>> = std::thread::scope(|s| {
590 let helpers: Vec<_> = (1..workers.clamp(1, nrows))
591 .map(|_| {
592 s.spawn(|| {
593 trace::set_role("wpp-helper");
594 run()
595 })
596 })
597 .collect();
598 let mut all = vec![run()];
599 for h in helpers {
600 all.push(h.join().unwrap_or_else(|_| {
601 Err(Error::corrupt("HEVC slice (wavefront): a worker panicked"))
602 }));
603 }
604 all
605 });
606 let mut rows_done = Vec::with_capacity(nrows);
607 for r in results {
608 rows_done.extend(r?);
609 }
610 rows_done.sort_by_key(|r| r.ry);
611 if rows_done.len() != nrows {
612 return Err(Error::corrupt(
613 "HEVC slice (wavefront): a row was not parsed",
614 ));
615 }
616
617 // Merge the bands back in row order, running the per-row callbacks as a serial parse does.
618 let mut stats = SliceStats::default();
619 let mut last_out: Option<(Contexts, i32)> = None;
620 for done in rows_done {
621 let ry = done.ry;
622 let y0 = ry << ctb_log2;
623 let bound = usize::from(ry > 0);
624 let own = ctb.min(pic.height - y0);
625 let (sx, sy) = (pic.sub_x(), pic.sub_y());
626 let own_c = own.div_ceil(1 << sy);
627 let cw = pic.width.div_ceil(1 << sx);
628 if pixels {
629 let w = pic.width;
630 pic.planes.y[y0 * w..(y0 + own) * w]
631 .copy_from_slice(&done.band.planes.y[bound * w..(bound + own) * w]);
632 let (c0, c1) = (y0 >> sy, (y0 >> sy) + own_c);
633 pic.planes.cb[c0 * cw..c1 * cw]
634 .copy_from_slice(&done.band.planes.cb[bound * cw..(bound + own_c) * cw]);
635 pic.planes.cr[c0 * cw..c1 * cw]
636 .copy_from_slice(&done.band.planes.cr[bound * cw..(bound + own_c) * cw]);
637 }
638 let u0 = y0 / 4;
639 let units = own.div_ceil(4);
640 pic.info[u0 * pic.w4..(u0 + units) * pic.w4]
641 .copy_from_slice(&done.band.info[bound * pic.w4..(bound + units) * pic.w4]);
642 let (k0, k1) = (ry * cols, (ry + 1) * cols);
643 pic.ctb[k0..k1].copy_from_slice(&done.band.ctb[k0..k1]);
644 source.field.merge_band(&done.field, u0);
645 // A row the segment ends inside is finished by the next segment (serially), so
646 // its motion and filter rows wait for that: publish only complete rows.
647 if done.out.stats.ctus == cols {
648 source.row_done(pic, y0 + ctb);
649 rows(pic, ry);
650 }
651 stats.ctus += done.out.stats.ctus;
652 stats.trailing_bits_ok = done.out.trailing_ok;
653 last_out = Some((done.out.contexts, done.out.last_qp));
654 }
655 let Some((contexts, last_qp)) = last_out else {
656 return Err(Error::corrupt("HEVC slice (wavefront): no row was parsed"));
657 };
658 if let Some(wpp) = (ry0..ry0 + nrows).rev().find_map(|ry| board.take_wpp(ry)) {
659 pic.carry.wpp = Some(wpp);
660 }
661 pic.carry.ds = Some(contexts);
662 pic.carry.last_qp = last_qp;
663 Ok(stats)
664}