1pub mod markers;
10
11use crate::{Error, Result};
12use markers::{Cod, Progression, Qcd, QuantStyle, Siz, SizComponent, Transform, marker};
13
14#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct MainHeader {
19 pub siz: Siz,
20 pub cod: Cod,
21 pub qcd: Qcd,
22}
23
24#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct TilePart<'a> {
29 pub tile_index: u16,
30 pub data: &'a [u8],
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct Codestream<'a> {
36 pub header: MainHeader,
37 pub tile_parts: Vec<TilePart<'a>>,
38}
39
40pub fn parse(bytes: &[u8]) -> Result<Codestream<'_>> {
47 let (header, sot_offset) = parse_main_header(bytes)?;
48 let tile_parts = walk_tile_parts(bytes, sot_offset)?;
49 Ok(Codestream { header, tile_parts })
50}
51
52fn walk_tile_parts(bytes: &[u8], sot_offset: usize) -> Result<Vec<TilePart<'_>>> {
60 let mut cur = Cursor::at(bytes, sot_offset);
61
62 if cur.u16()? != marker::SOT {
65 return Err(Error::Codestream(
66 "tile-part does not start with SOT".into(),
67 ));
68 }
69 let sot = decode_sot(segment(&mut cur)?)?;
70
71 if sot.tile_index != 0 {
74 return Err(Error::Unsupported(format!(
75 "tile index {}; the subset is a single tile",
76 sot.tile_index
77 )));
78 }
79 if sot.tile_part_index != 0 || sot.num_tile_parts > 1 {
80 return Err(Error::Unsupported(
81 "multiple tile-parts; the subset is a single tile-part".into(),
82 ));
83 }
84
85 loop {
88 let m = cur.u16()?;
89 match m {
90 marker::SOD => break,
91 marker::COM => {
92 segment(&mut cur)?;
93 }
94 marker::COD
95 | marker::COC
96 | marker::QCD
97 | marker::QCC
98 | marker::RGN
99 | marker::POC
100 | marker::TLM
101 | marker::PLT
102 | marker::SOP
103 | marker::EPH => {
104 return Err(Error::Unsupported(format!(
105 "tile-part header marker {m:#06X} is outside the Phase 1 subset"
106 )));
107 }
108 other => {
109 return Err(Error::Codestream(format!(
110 "unexpected marker {other:#06X} in tile-part header"
111 )));
112 }
113 }
114 }
115 let data_start = cur.pos;
116
117 let data_end = if sot.psot == 0 {
120 bytes
121 .len()
122 .checked_sub(2)
123 .filter(|&end| end >= data_start && read_u16(bytes, end) == Some(marker::EOC))
124 .ok_or_else(|| Error::Codestream("Psot=0 tile-part is not terminated by EOC".into()))?
125 } else {
126 let end = sot_offset
127 .checked_add(sot.psot as usize)
128 .filter(|&end| end <= bytes.len())
129 .ok_or_else(|| Error::Codestream("Psot overruns the codestream".into()))?;
130 if end < data_start {
131 return Err(Error::Codestream(
132 "Psot is shorter than the tile-part header".into(),
133 ));
134 }
135 end
136 };
137
138 let data = &bytes[data_start..data_end];
139
140 match read_u16(bytes, data_end) {
143 Some(marker::EOC) => {}
144 Some(marker::SOT) => {
145 return Err(Error::Unsupported(
146 "multiple tile-parts; the subset is a single tile-part".into(),
147 ));
148 }
149 Some(other) => {
150 return Err(Error::Codestream(format!(
151 "expected EOC after the tile-part, found {other:#06X}"
152 )));
153 }
154 None => return Err(Error::Codestream("missing EOC after the tile-part".into())),
155 }
156
157 Ok(vec![TilePart {
158 tile_index: sot.tile_index,
159 data,
160 }])
161}
162
163struct Sot {
166 tile_index: u16,
167 psot: u32,
168 tile_part_index: u8,
169 num_tile_parts: u8,
170}
171
172fn decode_sot(mut b: Cursor<'_>) -> Result<Sot> {
175 let tile_index = b.u16()?;
176 let psot = b.u32()?;
177 let tile_part_index = b.u8()?;
178 let num_tile_parts = b.u8()?;
179 b.expect_consumed("SOT")?;
180 Ok(Sot {
181 tile_index,
182 psot,
183 tile_part_index,
184 num_tile_parts,
185 })
186}
187
188fn read_u16(bytes: &[u8], pos: usize) -> Option<u16> {
192 let hi = *bytes.get(pos)?;
193 let lo = *bytes.get(pos + 1)?;
194 Some(u16::from_be_bytes([hi, lo]))
195}
196
197fn parse_main_header(bytes: &[u8]) -> Result<(MainHeader, usize)> {
203 let mut cur = Cursor::new(bytes);
204
205 if cur.u16()? != marker::SOC {
206 return Err(Error::Codestream(
207 "does not start with the SOC marker".into(),
208 ));
209 }
210 if cur.u16()? != marker::SIZ {
212 return Err(Error::Codestream(
213 "SIZ must be the first marker after SOC".into(),
214 ));
215 }
216 let siz = decode_siz(segment(&mut cur)?)?;
217
218 let mut cod = None;
219 let mut qcd = None;
220
221 let sot_offset = loop {
222 let m = cur.u16()?;
223 match m {
224 marker::SOT => break cur.pos - 2,
226
227 marker::COD => {
228 if cod.is_some() {
229 return Err(Error::Codestream("duplicate COD marker".into()));
230 }
231 cod = Some(decode_cod(segment(&mut cur)?)?);
232 }
233 marker::QCD => {
234 if qcd.is_some() {
235 return Err(Error::Codestream("duplicate QCD marker".into()));
236 }
237 qcd = Some(decode_qcd(segment(&mut cur)?)?);
238 }
239 marker::COM => {
241 segment(&mut cur)?;
242 }
243
244 marker::COC
246 | marker::QCC
247 | marker::RGN
248 | marker::POC
249 | marker::TLM
250 | marker::PLT
251 | marker::SOP
252 | marker::EPH => {
253 return Err(Error::Unsupported(format!(
254 "marker {m:#06X} is outside the Phase 1 subset"
255 )));
256 }
257
258 marker::SOD | marker::EOC => {
260 return Err(Error::Codestream(format!(
261 "unexpected marker {m:#06X} before any tile-part"
262 )));
263 }
264 other => {
265 return Err(Error::Codestream(format!(
266 "unknown marker {other:#06X} in main header"
267 )));
268 }
269 }
270 };
271
272 let cod = cod.ok_or_else(|| Error::Codestream("missing required COD marker".into()))?;
273 let qcd = qcd.ok_or_else(|| Error::Codestream("missing required QCD marker".into()))?;
274
275 Ok((MainHeader { siz, cod, qcd }, sot_offset))
276}
277
278const MAX_IMAGE_SAMPLES: u64 = 1 << 26;
285
286fn validate_geometry(siz: &Siz) -> Result<()> {
293 if siz.x_size == 0 || siz.y_size == 0 {
294 return Err(Error::Marker("SIZ declares a zero-size image".into()));
295 }
296 if siz.x_offset != 0 || siz.y_offset != 0 {
297 return Err(Error::Unsupported(format!(
298 "image offset ({}, {}); the Phase 1 subset is canvas-origin only",
299 siz.x_offset, siz.y_offset
300 )));
301 }
302 if siz.tile_x_offset != 0 || siz.tile_y_offset != 0 {
303 return Err(Error::Unsupported(format!(
304 "tile offset ({}, {}); the Phase 1 subset is canvas-origin only",
305 siz.tile_x_offset, siz.tile_y_offset
306 )));
307 }
308 if siz.tile_width == 0 || siz.tile_height == 0 {
309 return Err(Error::Marker("SIZ declares a zero-size tile".into()));
310 }
311 if (siz.tile_width as u64) < siz.x_size as u64 || (siz.tile_height as u64) < siz.y_size as u64 {
314 return Err(Error::Unsupported(
315 "tile smaller than the image (multi-tile grid); the Phase 1 subset is single-tile"
316 .into(),
317 ));
318 }
319 if siz.x_size as u64 * siz.y_size as u64 > MAX_IMAGE_SAMPLES {
320 return Err(Error::Unsupported(format!(
321 "image area {}×{} exceeds the Phase 1 decode guard of {MAX_IMAGE_SAMPLES} samples",
322 siz.x_size, siz.y_size
323 )));
324 }
325 Ok(())
326}
327
328fn decode_siz(mut b: Cursor<'_>) -> Result<Siz> {
331 let _rsiz = b.u16()?; let x_size = b.u32()?;
333 let y_size = b.u32()?;
334 let x_offset = b.u32()?;
335 let y_offset = b.u32()?;
336 let tile_width = b.u32()?;
337 let tile_height = b.u32()?;
338 let tile_x_offset = b.u32()?;
339 let tile_y_offset = b.u32()?;
340 let csiz = b.u16()?;
341
342 if csiz == 0 {
343 return Err(Error::Marker("SIZ declares zero components".into()));
344 }
345 if csiz != 1 {
346 return Err(Error::Unsupported(format!(
347 "{csiz} components; the Phase 1 subset is single-component"
348 )));
349 }
350
351 let mut components = Vec::with_capacity(csiz as usize);
352 for _ in 0..csiz {
353 let ssiz = b.u8()?;
354 let x_sampling = b.u8()?;
355 let y_sampling = b.u8()?;
356 components.push(SizComponent {
357 bit_depth: (ssiz & 0x7F) + 1,
358 signed: ssiz & 0x80 != 0,
359 x_sampling,
360 y_sampling,
361 });
362 }
363 b.expect_consumed("SIZ")?;
364
365 let siz = Siz {
366 x_size,
367 y_size,
368 x_offset,
369 y_offset,
370 tile_width,
371 tile_height,
372 tile_x_offset,
373 tile_y_offset,
374 components,
375 };
376 validate_geometry(&siz)?;
377 Ok(siz)
378}
379
380fn decode_cod(mut b: Cursor<'_>) -> Result<Cod> {
384 let scod = b.u8()?;
385 if scod & 0x01 != 0 {
387 return Err(Error::Unsupported(
388 "explicit precinct partition; the subset uses maximal precincts".into(),
389 ));
390 }
391 if scod & 0x06 != 0 {
392 return Err(Error::Unsupported(
393 "SOP/EPH error-resilience markers are out of the Phase 1 subset".into(),
394 ));
395 }
396
397 let progression = match b.u8()? {
398 0 => Progression::Lrcp,
399 p @ 1..=4 => {
400 return Err(Error::Unsupported(format!(
401 "progression order {p}; the subset is LRCP only"
402 )));
403 }
404 other => {
405 return Err(Error::Marker(format!("reserved progression order {other}")));
406 }
407 };
408
409 let layers = b.u16()?;
410 if layers != 1 {
411 return Err(Error::Unsupported(format!(
412 "{layers} quality layers; the subset is single-layer"
413 )));
414 }
415
416 let mct = b.u8()?;
417 if mct != 0 {
418 return Err(Error::Unsupported(
419 "multiple-component transform is out of the single-component subset".into(),
420 ));
421 }
422
423 let decomposition_levels = b.u8()?;
424 let code_block_width = b.u8()?;
425 let code_block_height = b.u8()?;
426 let code_block_style = b.u8()?;
427 let transform = match b.u8()? {
428 0 => Transform::Irreversible97,
429 1 => Transform::Reversible53,
430 other => return Err(Error::Marker(format!("reserved wavelet transform {other}"))),
431 };
432 b.expect_consumed("COD")?;
433
434 Ok(Cod {
435 progression,
436 layers,
437 decomposition_levels,
438 code_block_width,
439 code_block_height,
440 code_block_style,
441 transform,
442 precinct_sizes: Vec::new(),
445 })
446}
447
448fn decode_qcd(mut b: Cursor<'_>) -> Result<Qcd> {
451 let sqcd = b.u8()?;
452 let guard_bits = sqcd >> 5;
453 let style = match sqcd & 0x1F {
454 0 => QuantStyle::None,
455 1 => QuantStyle::ScalarDerived,
456 2 => QuantStyle::ScalarExpounded,
457 other => {
458 return Err(Error::Marker(format!(
459 "reserved quantization style {other}"
460 )));
461 }
462 };
463
464 let mut steps = Vec::new();
465 match style {
466 QuantStyle::None => {
469 if b.remaining() == 0 {
470 return Err(Error::Codestream("QCD carries no step entries".into()));
471 }
472 while b.remaining() > 0 {
473 let v = b.u8()?;
474 steps.push((v >> 3, 0));
475 }
476 }
477 QuantStyle::ScalarDerived | QuantStyle::ScalarExpounded => {
480 if b.remaining() == 0 || !b.remaining().is_multiple_of(2) {
481 return Err(Error::Codestream("QCD step table is truncated".into()));
482 }
483 if style == QuantStyle::ScalarDerived && b.remaining() != 2 {
484 return Err(Error::Codestream(
485 "derived QCD must carry exactly one step entry".into(),
486 ));
487 }
488 while b.remaining() > 0 {
489 let v = b.u16()?;
490 steps.push((((v >> 11) & 0x1F) as u8, v & 0x07FF));
491 }
492 }
493 }
494
495 Ok(Qcd {
496 style,
497 guard_bits,
498 steps,
499 })
500}
501
502fn segment<'a>(cur: &mut Cursor<'a>) -> Result<Cursor<'a>> {
508 let len = cur.u16()? as usize;
509 if len < 2 {
510 return Err(Error::Codestream("marker segment length below 2".into()));
511 }
512 let body = cur.take(len - 2)?;
513 Ok(Cursor::new(body))
514}
515
516struct Cursor<'a> {
519 buf: &'a [u8],
520 pos: usize,
521}
522
523impl<'a> Cursor<'a> {
524 fn new(buf: &'a [u8]) -> Self {
525 Self { buf, pos: 0 }
526 }
527
528 fn at(buf: &'a [u8], pos: usize) -> Self {
531 Self { buf, pos }
532 }
533
534 fn remaining(&self) -> usize {
535 self.buf.len() - self.pos
536 }
537
538 fn take(&mut self, n: usize) -> Result<&'a [u8]> {
539 if self.remaining() < n {
540 return Err(Error::Codestream("truncated marker segment".into()));
541 }
542 let slice = &self.buf[self.pos..self.pos + n];
543 self.pos += n;
544 Ok(slice)
545 }
546
547 fn u8(&mut self) -> Result<u8> {
548 Ok(self.take(1)?[0])
549 }
550
551 fn u16(&mut self) -> Result<u16> {
552 let b = self.take(2)?;
553 Ok(u16::from_be_bytes([b[0], b[1]]))
554 }
555
556 fn u32(&mut self) -> Result<u32> {
557 let b = self.take(4)?;
558 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
559 }
560
561 fn expect_consumed(&self, marker: &str) -> Result<()> {
564 if self.remaining() != 0 {
565 return Err(Error::Codestream(format!(
566 "{marker} segment has {} unexpected trailing byte(s)",
567 self.remaining()
568 )));
569 }
570 Ok(())
571 }
572}
573
574#[cfg(test)]
575mod tests;