1use std::io::Read;
21
22use crate::format::{err, DecodeError};
23
24pub const LEVEL3_BEAMS: usize = 720;
27const BEAM_WIDTH: f64 = 0.5;
28
29const HEADER_BYTES: usize = 18;
30const DESCRIPTION_BYTES: usize = 102;
31const PACKET_DIGITAL_RADIAL: u16 = 16;
32
33const MAX_BODY_BYTES: u64 = 16 << 20;
37
38const EPOCH_DAY_ZERO: i64 = -86_400;
40
41const PRODUCTS: [(u16, &str, u32, i16, i16, i16); 2] = [
45 (153, "n0b", 1840, -320, 5, 254),
46 (154, "n0g", 1200, -635, 5, 254),
47];
48
49#[derive(Debug, Clone, PartialEq)]
51pub struct Level3Sweep {
52 pub product_code: u16,
54 pub gates: u32,
56 pub scan_time: i64,
59 pub elevation: f32,
61 pub latitude: f64,
62 pub longitude: f64,
63 pub height_m: f64,
64 pub vcp: i16,
65 pub volume_number: i16,
66 pub elevation_number: i16,
67 pub codes: Vec<u8>,
70}
71
72fn be_i16(data: &[u8], offset: usize) -> Option<i16> {
73 let bytes = data.get(offset..offset.checked_add(2)?)?;
74 Some(i16::from_be_bytes([bytes[0], bytes[1]]))
75}
76
77fn be_u16(data: &[u8], offset: usize) -> Option<u16> {
78 be_i16(data, offset).map(|value| value as u16)
79}
80
81fn halfword(block: &[u8], number: usize) -> i16 {
84 let offset = (number - 10) * 2;
85 i16::from_be_bytes([block[offset], block[offset + 1]])
86}
87
88fn word(block: &[u8], number: usize) -> u32 {
90 let offset = (number - 10) * 2;
91 u32::from_be_bytes([
92 block[offset],
93 block[offset + 1],
94 block[offset + 2],
95 block[offset + 3],
96 ])
97}
98
99fn find(data: &[u8], needle: &[u8], from: usize) -> Option<usize> {
100 data.get(from..)?
101 .windows(needle.len())
102 .position(|window| window == needle)
103 .map(|position| position + from)
104}
105
106fn skip_wmo_heading(data: &[u8]) -> Result<usize, DecodeError> {
109 if data.len() < 4 || !data[..4].iter().all(u8::is_ascii_alphabetic) {
110 return Ok(0);
111 }
112 let malformed = || err("Level 3 file has a malformed WMO heading");
113 let first = find(data, b"\r\r\n", 0).ok_or_else(malformed)?;
114 let second = find(data, b"\r\r\n", first + 3).ok_or_else(malformed)?;
115 if second > 64 {
116 return Err(malformed());
117 }
118 Ok(second + 3)
119}
120
121pub fn read_level3(data: &[u8]) -> Result<Level3Sweep, DecodeError> {
123 let start = skip_wmo_heading(data)?;
124 let description = data
125 .get(start + HEADER_BYTES..start + HEADER_BYTES + DESCRIPTION_BYTES)
126 .filter(|block| halfword(block, 10) == -1)
127 .ok_or_else(|| err("Level 3 file has no product description block"))?;
128 let code = halfword(description, 16);
129 let &(product_code, product, gates, minimum, increment, levels) = PRODUCTS
130 .iter()
131 .find(|entry| i32::from(entry.0) == i32::from(code))
132 .ok_or_else(|| {
133 err(format!(
134 "Level 3 product {code} is not one this product carries"
135 ))
136 })?;
137 let thresholds = (
138 halfword(description, 31),
139 halfword(description, 32),
140 halfword(description, 33),
141 );
142 if thresholds != (minimum, increment, levels) {
143 return Err(err(format!(
144 "Level 3 {product} thresholds {thresholds:?} are not the codebook (min, step, levels) {:?}",
145 (minimum, increment, levels)
146 )));
147 }
148 let days = i64::from(halfword(description, 21));
149 let seconds = i64::from(word(description, 22));
150 let scan_time = EPOCH_DAY_ZERO + days * 86_400 + seconds;
151
152 let raw = &data[start + HEADER_BYTES + DESCRIPTION_BYTES..];
153 let decompressed;
154 let body = match halfword(description, 51) {
155 0 => raw,
156 1 => {
157 decompressed = bunzip(raw, product)?;
158 &decompressed[..]
159 }
160 other => {
161 return Err(err(format!(
162 "Level 3 {product} uses compression method {other}"
163 )))
164 }
165 };
166 let codes = read_radials(body, gates as usize, product)?;
167 Ok(Level3Sweep {
168 product_code,
169 gates,
170 scan_time,
171 elevation: f32::from(halfword(description, 30)) / 10.0,
172 latitude: f64::from(word(description, 11) as i32) / 1000.0,
173 longitude: f64::from(word(description, 13) as i32) / 1000.0,
174 height_m: f64::from(halfword(description, 15)) * 0.3048,
175 vcp: halfword(description, 18),
176 volume_number: halfword(description, 20),
177 elevation_number: halfword(description, 29),
178 codes,
179 })
180}
181
182fn bunzip(raw: &[u8], product: &str) -> Result<Vec<u8>, DecodeError> {
184 let mut body = Vec::new();
185 bzip2::read::MultiBzDecoder::new(raw)
186 .take(MAX_BODY_BYTES + 1)
187 .read_to_end(&mut body)
188 .map_err(|error| err(format!("Level 3 {product} symbology is not bzip2: {error}")))?;
189 if body.len() as u64 > MAX_BODY_BYTES {
190 return Err(err(format!(
191 "Level 3 {product} symbology exceeds {MAX_BODY_BYTES} bytes"
192 )));
193 }
194 Ok(body)
195}
196
197fn read_radials(body: &[u8], gates: usize, product: &str) -> Result<Vec<u8>, DecodeError> {
200 if body.len() < 16 || be_i16(body, 0) != Some(-1) || be_i16(body, 2) != Some(1) {
201 return Err(err(format!(
202 "Level 3 {product} has no product symbology block"
203 )));
204 }
205 if be_i16(body, 8) != Some(1) || be_i16(body, 10) != Some(-1) {
206 return Err(err(format!(
207 "Level 3 {product} symbology must hold exactly one layer"
208 )));
209 }
210 let truncated = || err(format!("Level 3 {product} radial data is truncated"));
211 let offset = 16;
213 let packet = be_u16(body, offset).ok_or_else(truncated)?;
214 if packet != PACKET_DIGITAL_RADIAL {
215 return Err(err(format!(
216 "Level 3 {product} carries packet {packet}, not a digital radial array"
217 )));
218 }
219 let first_bin = be_i16(body, offset + 2).ok_or_else(truncated)?;
220 let bins = be_i16(body, offset + 4).ok_or_else(truncated)?;
221 let radials = be_i16(body, offset + 12).ok_or_else(truncated)?;
222 if first_bin != 0 || i64::from(bins) != gates as i64 {
223 return Err(err(format!(
224 "Level 3 {product} has {bins} gates from {first_bin}, not {gates} from 0"
225 )));
226 }
227 let mut codes = vec![0u8; LEVEL3_BEAMS * gates];
228 let mut filled = [false; LEVEL3_BEAMS];
229 let mut position = offset + 14;
230 for _ in 0..radials.max(0) {
231 let length = be_i16(body, position).ok_or_else(truncated)?;
232 let start_angle = be_i16(body, position + 2).ok_or_else(truncated)?;
233 let delta_angle = be_i16(body, position + 4).ok_or_else(truncated)?;
234 position += 6;
235 let length = usize::try_from(length).map_err(|_| truncated())?;
239 let end = position.checked_add(gates).ok_or_else(truncated)?;
240 let values = body.get(position..end).ok_or_else(truncated)?;
241 position = position.checked_add(length).ok_or_else(truncated)?;
242 let centre =
243 ((f64::from(start_angle) + f64::from(delta_angle) / 2.0) / 10.0).rem_euclid(360.0);
244 let beam = ((centre / BEAM_WIDTH).floor() as usize) % LEVEL3_BEAMS;
247 if filled[beam] {
248 return Err(err(format!(
249 "Level 3 {product} has two radials in beam {beam}"
250 )));
251 }
252 filled[beam] = true;
253 codes[beam * gates..(beam + 1) * gates].copy_from_slice(values);
254 }
255 Ok(codes)
256}