1use crate::format::{crc32, ChunkEntry, GroupEntry, Predictor, TileGeometry, VariableEntry};
15
16use crate::encode::errors::{EncodeError, Result};
17
18pub const GROUP_LENGTH: usize = 6;
19
20pub fn encode_residual(current: &[u8], base: &[u8]) -> Result<Vec<u8>> {
21 if current.len() != base.len() {
22 return Err(EncodeError::conversion("plane lengths differ"));
23 }
24 Ok(current
25 .iter()
26 .zip(base)
27 .map(|(value, anchor)| value.wrapping_sub(*anchor))
28 .collect())
29}
30
31pub fn split_segments(offsets: &[i64]) -> Result<Vec<Vec<i64>>> {
35 if offsets.windows(2).any(|pair| pair[1] <= pair[0]) {
36 return Err(EncodeError::conversion(
37 "forecast hours must be unique and ascending",
38 ));
39 }
40 let Some(&first) = offsets.first() else {
41 return Err(EncodeError::conversion("time axis is empty"));
42 };
43 let mut segments = vec![vec![first]];
44 let mut step: Option<i64> = None;
45 for pair in offsets.windows(2) {
46 let (previous, current) = (pair[0], pair[1]);
47 if step.is_some_and(|step| current - previous != step) {
48 segments.push(vec![current]);
49 } else {
50 segments.last_mut().expect("non-empty").push(current);
51 }
52 step = Some(current - previous);
53 }
54 Ok(segments)
55}
56
57pub fn group_forecast_hours(offsets: &[i64]) -> Result<Vec<Vec<i64>>> {
61 Ok(split_segments(offsets)?
62 .into_iter()
63 .flat_map(|segment| {
64 segment
65 .chunks(GROUP_LENGTH)
66 .map(<[i64]>::to_vec)
67 .collect::<Vec<_>>()
68 })
69 .collect())
70}
71
72pub fn tile_stack(planes: &[&[u8]], geometry: &TileGeometry, tile: u32) -> Result<Vec<u8>> {
78 let (row, column) = geometry.origin(tile);
79 let (height, width) = geometry.shape(tile);
80 let grid_width = geometry.width as usize;
81 let mut block = Vec::with_capacity(planes.len() * height as usize * width as usize);
82 for plane in planes {
83 if plane.len() != grid_width * geometry.height as usize {
84 return Err(EncodeError::conversion("plane does not match the grid"));
85 }
86 for line in 0..height as usize {
87 let start = (row as usize + line) * grid_width + column as usize;
88 block.extend_from_slice(&plane[start..start + width as usize]);
89 }
90 }
91 Ok(block)
92}
93
94pub fn encode_chunk(block: &mut [u8], predictor: Predictor, stride: usize) -> Result<()> {
101 match predictor {
102 Predictor::Raw => Ok(()),
103 Predictor::Previous => {
104 let frames = block.len() / stride.max(1);
107 for frame in (1..frames).rev() {
108 let (previous, current) = block.split_at_mut(frame * stride);
109 let previous = &previous[(frame - 1) * stride..];
110 for (target, base) in current[..stride].iter_mut().zip(previous.iter()) {
111 *target = target.wrapping_sub(*base);
112 }
113 }
114 Ok(())
115 }
116 other => Err(EncodeError::conversion(format!(
117 "predictor {other:?} is not valid in a v2 chunk"
118 ))),
119 }
120}
121
122pub fn build_chunks<'a>(
131 offsets: &[i64],
132 variables: &[VariableEntry],
133 plane: &dyn Fn(i64, u8) -> Result<&'a [u8]>,
134 geometry: &TileGeometry,
135) -> Result<(Vec<GroupEntry>, Vec<(ChunkEntry, Vec<u8>)>)> {
136 let mut groups = Vec::new();
137 let mut chunks = Vec::new();
138 let mut first_frame = 0u16;
139 for group in group_forecast_hours(offsets)? {
140 groups.push(GroupEntry {
141 first_frame,
142 frame_count: group.len() as u8,
143 });
144 first_frame += group.len() as u16;
145 let frames: Vec<Vec<&[u8]>> = variables
148 .iter()
149 .map(|variable| {
150 group
151 .iter()
152 .map(|offset| plane(*offset, variable.variable_id))
153 .collect::<Result<Vec<_>>>()
154 })
155 .collect::<Result<_>>()?;
156 for tile in 0..geometry.count() {
157 let (height, width) = geometry.shape(tile);
158 let stride = height as usize * width as usize;
159 for (variable, planes) in variables.iter().zip(&frames) {
160 let mut block = tile_stack(planes, geometry, tile)?;
161 let entry = ChunkEntry {
164 compressed_length: 0,
165 crc32: crc32(&block),
166 };
167 encode_chunk(&mut block, variable.predictor, stride)?;
168 chunks.push((entry, block));
169 }
170 }
171 }
172 Ok((groups, chunks))
173}