Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 123 additions & 52 deletions src/bounded.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,69 +183,74 @@ pub fn decode_bounded(
}
let mut output = budget.zeroed(output_len, "RGB output")?;
let workers = Workers::new(grid.tiles.len(), max_job, &budget)?;
let mut next = 0;
while next < grid.tiles.len() {
let mut jobs = Vec::with_capacity(8);
while next < grid.tiles.len() && jobs.len() < workers.count() {
let tile = &grid.tiles[next];
let bytes = plan.job_bytes(next);
if bytes > budget.available() && !jobs.is_empty() {
break;
let mut start = |next: usize| -> Result<Job<'_, '_>> {
let tile = &grid.tiles[next];
let reservation = budget.reserve(plan.job_bytes(next), "tile workspace")?;
let mut payload = resample::zeroed(tile.payload_len)?;
index.read_item(tile.item, &mut source, &mut payload)?;
let (unit, region) = plan.unit(next);
let tile_area = plan.tile(next);
Ok(Job {
index: next,
tile,
origin: [tile_area.left, tile_area.top],
unit,
region,
decode: plan.decodes(next),
payload,
reservation,
})
};
let render = |job| render_job(job, layout, &color, &transform, yuv444.as_ref());
let mut finish = |result: TileResult| {
match &result.data {
TileData::Pixels(pixels) => {
let unit_width = result.unit.width as usize;
let left = (result.region.left + layout.left - result.unit.left) as usize;
let width = (result.region.right - result.region.left) as usize;
layout.place(
result.region,
|y| {
let row_start =
((y + layout.top - result.unit.top) as usize * unit_width + left) * 3;
&pixels[row_start..row_start + width * 3]
},
&mut output,
);
}
let reservation = budget.reserve(bytes, "tile workspace")?;
let mut payload = resample::zeroed(tile.payload_len)?;
index.read_item(tile.item, &mut source, &mut payload)?;
let (unit, region) = plan.unit(next);
let tile_area = plan.tile(next);
jobs.push(Job {
index: next,
tile,
origin: [tile_area.left, tile_area.top],
unit,
region,
decode: plan.decodes(next),
payload,
reservation,
});
next += 1;
TileData::Sums(sums) if !sums.is_empty() => {
accumulator.merge(result.region, sums, &mut output)
}
TileData::Sums(_) => {}
}
let render = |job| render_job(job, layout, &color, &transform, yuv444.as_ref());
let results = if let Some(edges) = &mut edges {
if (result.index + 1).is_multiple_of(grid.columns as usize) {
accumulator.finish_tile_row();
}
};
if let Some(edges) = &mut edges {
let mut next = 0;
while next < grid.tiles.len() {
let end = grid.tiles.len().min(next + workers.count());
let jobs = (next..end).map(&mut start).collect::<Result<Vec<_>>>()?;
next = end;
let mut decoded = workers
.map(jobs, decode_job)
.into_iter()
.collect::<Result<Vec<_>>>()?;
for job in &mut decoded {
job.halo = edges.advance(job.index, job.frame.as_ref(), job.tile.geometry)?;
}
workers.map(decoded, render)
} else {
workers.map(jobs, |job| decode_job(job).and_then(render))
};
for result in results {
let result = result?;
match &result.data {
TileData::Pixels(pixels) => {
for y in result.region.top..result.region.bottom {
for x in result.region.left..result.region.right {
let src = ((y + layout.top - result.unit.top) as usize
* result.unit.width as usize
+ (x + layout.left - result.unit.left) as usize)
* 3;
let dst = layout.pixel_index(x, y);
output[dst..dst + 3].copy_from_slice(&pixels[src..src + 3]);
}
}
}
TileData::Sums(sums) if !sums.is_empty() => {
accumulator.merge(result.region, sums, &mut output)
}
TileData::Sums(_) => {}
}
if (result.index + 1) % grid.columns as usize == 0 {
accumulator.finish_tile_row();
for result in workers.map(decoded, render) {
finish(result?);
}
}
} else {
workers.decode_in_order(
grid.tiles.len(),
start,
|job| decode_job(job).and_then(render),
finish,
)?;
}
Ok(BoundedRgbImage {
image: DecodedRgbImage {
Expand All @@ -259,6 +264,58 @@ pub fn decode_bounded(
})
}

fn decode_sequentially<J, R>(
count: usize,
mut start: impl FnMut(usize) -> Result<J>,
run: impl Fn(J) -> Result<R>,
mut finish: impl FnMut(R),
) -> Result<()> {
for next in 0..count {
finish(run(start(next)?)?);
}
Ok(())
}

#[cfg(feature = "parallel-grid")]
fn decode_in_order<J: Send, R: Send>(
pool: &rayon::ThreadPool,
count: usize,
mut start: impl FnMut(usize) -> Result<J>,
run: impl Fn(J) -> Result<R> + Sync,
mut finish: impl FnMut(R),
) -> Result<()> {
use std::collections::VecDeque;
use std::sync::mpsc::{Receiver, channel};

let workers = pool.current_num_threads();
let wait = |receiver: Receiver<Result<R>>| {
receiver
.recv()
.unwrap_or_else(|_| Err(BoundedDecodeError::Decode("tile worker panicked".into())))
};
pool.in_place_scope_fifo(|scope| {
let mut pending = VecDeque::with_capacity(workers);
for next in 0..count {
if pending.len() == workers
&& let Some(receiver) = pending.pop_front()
{
finish(wait(receiver)?);
}
let job = start(next)?;
let (sender, receiver) = channel();
let run = &run;
scope.spawn_fifo(move |_| {
let _ = sender.send(run(job));
});
pending.push_back(receiver);
}
for receiver in pending {
finish(wait(receiver)?);
}
Ok(())
})
}

struct Plan<'a, 'b> {
grid: &'b grid::Grid<'a>,
layout: resample::Layout,
Expand Down Expand Up @@ -389,6 +446,20 @@ impl Workers {
}
items.into_iter().map(f).collect()
}

fn decode_in_order<J: Send, R: Send>(
&self,
count: usize,
start: impl FnMut(usize) -> Result<J>,
run: impl Fn(J) -> Result<R> + Sync,
finish: impl FnMut(R),
) -> Result<()> {
#[cfg(feature = "parallel-grid")]
if let Some((pool, _)) = &self.pool {
return decode_in_order(pool, count, start, run, finish);
}
decode_sequentially(count, start, run, finish)
}
}

fn decode_tile(tile: &grid::Tile<'_>, payload: &[u8]) -> Result<DecodedFrame> {
Expand Down
1 change: 1 addition & 0 deletions src/bounded/memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ impl Budget {
}
}

#[cfg(any(feature = "parallel-grid", test))]
pub(super) fn available(&self) -> usize {
self.0.limit - self.0.used.load(Ordering::Relaxed)
}
Expand Down
34 changes: 34 additions & 0 deletions src/bounded/resample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use super::grid::Grid;
use super::memory::{Budget, Buffer};
use super::{BoundedDecodeError as Error, Result};

const PLACEMENT_BLOCK_ROWS: usize = 16;

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) struct Rectangle {
pub(super) left: u32,
Expand Down Expand Up @@ -198,6 +200,38 @@ impl Layout {
}
}

pub(super) fn place<'a>(
&self,
region: Region,
row: impl Fn(u32) -> &'a [u8],
output: &mut [u8],
) {
let [a, b, c, d] = self.matrix.map(isize::from);
let width = self.display_width as isize;
let step_x = (c * width + a) * 3;
let step_y = (d * width + b) * 3;
let origin = self.pixel_index(0, 0) as isize;
let index = |x: u32, y: u32| (origin + x as isize * step_x + y as isize * step_y) as usize;
if step_x == 3 {
for y in region.top..region.bottom {
let pixels = row(y);
let start = index(region.left, y);
output[start..start + pixels.len()].copy_from_slice(pixels);
}
return;
}
for top in (region.top..region.bottom).step_by(PLACEMENT_BLOCK_ROWS) {
let bottom = (top + PLACEMENT_BLOCK_ROWS as u32).min(region.bottom);
for x in region.left..region.right {
let source = (x - region.left) as usize * 3;
for y in top..bottom {
let start = index(x, y);
output[start..start + 3].copy_from_slice(&row(y)[source..source + 3]);
}
}
}
}

pub(super) fn pixel_index(&self, x: u32, y: u32) -> usize {
let [a, b, c, d] = self.matrix;
let dx = i64::from(a) * i64::from(x)
Expand Down
67 changes: 67 additions & 0 deletions src/bounded/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1916,3 +1916,70 @@ fn grid_dimensions_are_limited_to_500_megapixels() {
Err(BoundedDecodeError::Malformed("ispe differs from SPS"))
));
}

#[cfg(feature = "parallel-grid")]
#[test]
fn ordered_tile_decoding_refills_a_freed_slot_before_finishing_the_next_tile() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(2)
.build()
.unwrap();
let events = std::cell::RefCell::new(Vec::new());
decode_in_order(
&pool,
5,
|tile| {
events.borrow_mut().push(("start", tile));
Ok(tile)
},
|tile| {
if tile == 0 {
std::thread::sleep(std::time::Duration::from_millis(50));
}
Ok(tile)
},
|tile| events.borrow_mut().push(("finish", tile)),
)
.unwrap();
assert_eq!(
events.into_inner(),
[
("start", 0),
("start", 1),
("finish", 0),
("start", 2),
("finish", 1),
("start", 3),
("finish", 2),
("start", 4),
("finish", 3),
("finish", 4),
]
);
}

#[cfg(feature = "parallel-grid")]
#[test]
fn ordered_tile_decoding_propagates_tile_panics_alongside_tile_errors() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(2)
.build()
.unwrap();
for panicking in [0, 1] {
let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
decode_in_order(
&pool,
2,
Ok,
|tile| {
if tile == panicking {
panic!("tile {tile}");
}
Err::<(), _>(BoundedDecodeError::Malformed("tile"))
},
|()| {},
)
}));
assert!(outcome.is_err(), "tile {panicking}");
}
}