decryptune 1.1.4__tar.gz → 1.1.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. {decryptune-1.1.4 → decryptune-1.1.5}/Cargo.lock +1 -1
  2. {decryptune-1.1.4 → decryptune-1.1.5}/Cargo.toml +1 -1
  3. {decryptune-1.1.4 → decryptune-1.1.5}/PKG-INFO +2 -2
  4. {decryptune-1.1.4 → decryptune-1.1.5}/README.md +1 -1
  5. {decryptune-1.1.4 → decryptune-1.1.5}/python/decryptune/__init__.py +1 -1
  6. {decryptune-1.1.4 → decryptune-1.1.5}/src/boxes.rs +36 -7
  7. {decryptune-1.1.4 → decryptune-1.1.5}/src/cover.rs +6 -0
  8. {decryptune-1.1.4 → decryptune-1.1.5}/src/error.rs +4 -2
  9. {decryptune-1.1.4 → decryptune-1.1.5}/src/input.rs +7 -4
  10. {decryptune-1.1.4 → decryptune-1.1.5}/src/jpeg/decode.rs +28 -11
  11. {decryptune-1.1.4 → decryptune-1.1.5}/src/jpeg/tests.rs +32 -5
  12. {decryptune-1.1.4 → decryptune-1.1.5}/src/lib.rs +44 -18
  13. {decryptune-1.1.4 → decryptune-1.1.5}/src/meta.rs +7 -3
  14. {decryptune-1.1.4 → decryptune-1.1.5}/src/process.rs +279 -61
  15. decryptune-1.1.5/tests/fixtures/odd420.jpg +0 -0
  16. {decryptune-1.1.4 → decryptune-1.1.5}/tests/test_decryptune.py +151 -0
  17. {decryptune-1.1.4 → decryptune-1.1.5}/.gitattributes +0 -0
  18. {decryptune-1.1.4 → decryptune-1.1.5}/.github/workflows/build.yml +0 -0
  19. {decryptune-1.1.4 → decryptune-1.1.5}/.gitignore +0 -0
  20. {decryptune-1.1.4 → decryptune-1.1.5}/LICENSE +0 -0
  21. {decryptune-1.1.4 → decryptune-1.1.5}/pyproject.toml +0 -0
  22. {decryptune-1.1.4 → decryptune-1.1.5}/src/jpeg/encode.rs +0 -0
  23. {decryptune-1.1.4 → decryptune-1.1.5}/src/jpeg/mod.rs +0 -0
  24. {decryptune-1.1.4 → decryptune-1.1.5}/tests/fixtures/big.jpg +0 -0
  25. {decryptune-1.1.4 → decryptune-1.1.5}/tests/fixtures/tiny.jpg +0 -0
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.4"
71
+ version = "1.1.5"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.4"
3
+ version = "1.1.5"
4
4
  edition = "2021"
5
5
  rust-version = "1.85"
6
6
  description = "Fast native M4A/fMP4 CENC decryptor, MP4 sanitizer and iTunes tagger, sync & async Python"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: decryptune
3
- Version: 1.1.4
3
+ Version: 1.1.5
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -60,7 +60,7 @@ Rules that hold for both `proc` and `aproc`:
60
60
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
61
61
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
62
62
  - A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
63
- - Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
63
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
64
64
 
65
65
  ## Benchmark
66
66
 
@@ -43,7 +43,7 @@ Rules that hold for both `proc` and `aproc`:
43
43
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
44
44
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
45
45
  - A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
46
- - Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
46
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
47
47
 
48
48
  ## Benchmark
49
49
 
@@ -29,7 +29,7 @@ except ImportError:
29
29
  _native = importlib.util.module_from_spec(importlib.util.spec_from_loader("decryptune", _loader))
30
30
  _loader.exec_module(_native)
31
31
 
32
- __version__ = "1.1.4"
32
+ __version__ = "1.1.5"
33
33
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
34
34
 
35
35
 
@@ -11,10 +11,18 @@ impl Box {
11
11
  pub fn is(&self, t: &[u8; 4]) -> bool { &self.typ == t }
12
12
  }
13
13
 
14
+ // hostile box spam: each parsed box costs 32 bytes of vec, so an absurd
15
+ // structure would multiply the input size many-fold. Parsing stops at the cap;
16
+ // callers check saturation via len() == MAX_BOXES and treat the input as
17
+ // invalid or pass it through rather than copying a structure no real file has.
18
+ // 2M top-level boxes would already be a 64MB vec for a 16MB input.
19
+ pub const MAX_BOXES: usize = 2_000_000;
20
+
14
21
  pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
15
22
  let mut out: Vec<Box> = Vec::new();
16
23
  let mut pos: usize = start;
17
24
  while pos + 8 <= end {
25
+ if out.len() >= MAX_BOXES { break; }
18
26
  let (size, hlen): (usize, usize) = match u32::from_be_bytes(data[pos..pos + 4].try_into().unwrap()) {
19
27
  0 => (end - pos, 8),
20
28
  1 if pos + 16 <= end => (u64::from_be_bytes(data[pos + 8..pos + 16].try_into().unwrap()) as usize, 16),
@@ -30,10 +38,23 @@ pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
30
38
  out
31
39
  }
32
40
 
41
+ // header length a box with this content size needs — content beyond the u32
42
+ // range switches to the 64-bit largesize form instead of wrapping the size
43
+ #[inline]
44
+ pub fn header_len(content_len: usize) -> usize {
45
+ if content_len + 8 > u32::MAX as usize { 16 } else { 8 }
46
+ }
47
+
33
48
  #[inline]
34
49
  pub fn write_header(out: &mut Vec<u8>, typ: &[u8; 4], content_len: usize) {
35
- out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
36
- out.extend_from_slice(typ);
50
+ if content_len + 8 > u32::MAX as usize {
51
+ out.extend_from_slice(&1u32.to_be_bytes());
52
+ out.extend_from_slice(typ);
53
+ out.extend_from_slice(&((content_len as u64) + 16).to_be_bytes());
54
+ } else {
55
+ out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
56
+ out.extend_from_slice(typ);
57
+ }
37
58
  }
38
59
 
39
60
  // output sink — Buf writes into an exactly-sized buffer, Count only measures.
@@ -59,15 +80,23 @@ impl Writer<'_> {
59
80
  }
60
81
  }
61
82
 
62
- // 32-bit box header (size + fourcc)
83
+ // 32-bit box header (size + fourcc) — or the 64-bit largesize form when the
84
+ // content cannot be expressed in 32 bits (rebuilt >4GB containers)
63
85
  pub fn header(&mut self, typ: &[u8; 4], content_len: usize) {
64
86
  match self {
65
87
  Writer::Buf { buf, pos } => {
66
- buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
67
- buf[*pos + 4..*pos + 8].copy_from_slice(typ);
68
- *pos += 8;
88
+ if content_len + 8 > u32::MAX as usize {
89
+ buf[*pos..*pos + 4].copy_from_slice(&1u32.to_be_bytes());
90
+ buf[*pos + 4..*pos + 8].copy_from_slice(typ);
91
+ buf[*pos + 8..*pos + 16].copy_from_slice(&((content_len as u64) + 16).to_be_bytes());
92
+ *pos += 16;
93
+ } else {
94
+ buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
95
+ buf[*pos + 4..*pos + 8].copy_from_slice(typ);
96
+ *pos += 8;
97
+ }
69
98
  }
70
- Writer::Count(n) => *n += 8
99
+ Writer::Count(n) => *n += header_len(content_len)
71
100
  }
72
101
  }
73
102
  }
@@ -9,12 +9,18 @@ use crate::meta::Cover;
9
9
  use crate::Err;
10
10
 
11
11
  const MAX_EDGE: u32 = 1000;
12
+ // a cover lands inside the ilst whole — 32MB is far above any real art and
13
+ // keeps a hostile "cover" from bloating the output file without bound
14
+ const MAX_COVER_BYTES: usize = 32 * 1024 * 1024;
12
15
 
13
16
  pub(crate) fn is_jpeg(b: &[u8]) -> bool { b.len() >= 2 && b[0] == 0xFF && b[1] == 0xD8 }
14
17
  pub(crate) fn is_png(b: &[u8]) -> bool { b.len() >= 8 && b[0..4] == [0x89, 0x50, 0x4E, 0x47] }
15
18
 
16
19
  /// Validate and (when needed) downscale a cover image to fit MAX_EDGE.
17
20
  pub(crate) fn prepare(raw: &[u8]) -> Result<Cover<'_>, Err> {
21
+ if raw.len() > MAX_COVER_BYTES {
22
+ return Err(Err::CoverTooLarge);
23
+ }
18
24
  if is_png(raw) {
19
25
  return Ok(Cover { data: Cow::Borrowed(raw), kind: 14 });
20
26
  }
@@ -19,7 +19,8 @@ pub(crate) enum Err {
19
19
  BadOutput = 10,
20
20
  MetaNeedsFragmented = 11,
21
21
  BadCover = 12,
22
- CoverNotFound = 13 // additive: a missing cover path must not read as a missing input
22
+ CoverNotFound = 13, // additive: a missing cover path must not read as a missing input
23
+ CoverTooLarge = 14 // additive: an absurd cover must not flow into the ilst whole
23
24
  }
24
25
 
25
26
  impl Err {
@@ -37,7 +38,8 @@ impl Err {
37
38
  Err::BadInput => "invalid input: expected bytes, bytearray, memoryview, or a path",
38
39
  Err::BadOutput => "invalid out: expected a path or None",
39
40
  Err::MetaNeedsFragmented => "metadata write requires a fragmented file (non-empty chunk offsets)",
40
- Err::BadCover => "unsupported cover format: expected JPEG or PNG"
41
+ Err::BadCover => "unsupported cover format: expected JPEG or PNG",
42
+ Err::CoverTooLarge => "cover too large (max 32 MB)"
41
43
  }
42
44
  }
43
45
  }
@@ -60,11 +60,13 @@ pub(crate) fn extract_bytes_or_path(value: &Bound<'_, PyAny>, bad: Err) -> PyRes
60
60
  } else if let Ok(b) = value.cast::<PyByteArray>() {
61
61
  Extracted::Bytes(b.to_vec()) // mutable — a copy is mandatory
62
62
  } else if let Ok(s) = value.cast::<PyString>() {
63
- Extracted::Path(s.to_str()?.to_string())
63
+ // to_str fails only on lone surrogates (real on Windows via os.fsdecode) —
64
+ // the Rust core takes String paths only, so that input has no valid encoding
65
+ Extracted::Path(s.to_str().map_err(|_| bad)?.to_string())
64
66
  } else if let Ok(p) = value.call_method0("__fspath__") { // os.PathLike
65
67
  // fspath may legally return bytes — map that here, never a raw downcast error
66
68
  Extracted::Path(if let Ok(s) = p.cast::<PyString>() {
67
- s.to_str()?.to_string()
69
+ s.to_str().map_err(|_| bad)?.to_string()
68
70
  } else if let Ok(b) = p.cast::<PyBytes>() {
69
71
  String::from_utf8_lossy(b.as_bytes()).into_owned()
70
72
  } else {
@@ -96,11 +98,12 @@ pub(crate) fn parse_output(out: Option<&Bound<'_, PyAny>>) -> PyResult<Output> {
96
98
  None => Ok(Output::Return),
97
99
  Some(v) => {
98
100
  let path: String = if let Ok(s) = v.cast::<PyString>() {
99
- s.to_str()?.to_string()
101
+ // lone surrogates have no Rust-side String encoding — coded error, not a leak
102
+ s.to_str().map_err(|_| Err::BadOutput)?.to_string()
100
103
  } else if let Ok(p) = v.call_method0("__fspath__") { // os.PathLike
101
104
  // same fspath-bytes rule as input — a coded error, not a raw downcast
102
105
  if let Ok(s) = p.cast::<PyString>() {
103
- s.to_str()?.to_string()
106
+ s.to_str().map_err(|_| Err::BadOutput)?.to_string()
104
107
  } else if let Ok(b) = p.cast::<PyBytes>() {
105
108
  String::from_utf8_lossy(b.as_bytes()).into_owned()
106
109
  } else {
@@ -6,9 +6,10 @@ use super::ZIGZAG;
6
6
  use crate::Err;
7
7
 
8
8
  // hostile SOF dimensions can demand multi-GB coefficient buffers before any
9
- // entropy byte is read — no real cover comes close (a 150MP medium-format
10
- // shot sits 2x under this); anything above is a decompression bomb
11
- const MAX_PIXELS: usize = 268_435_456; // 256 megapixels
9
+ // entropy byte is read — covers are downscaled to 1000px anyway, so 64MP
10
+ // (8192²) is far beyond anything legitimate; at the old 256MP cap a ~1MB
11
+ // hostile JPEG forced ~1GB of buffers and seconds of IDCT
12
+ const MAX_PIXELS: usize = 67_108_864; // 64 megapixels
12
13
 
13
14
  struct HuffTable {
14
15
  counts : [u8; 17], // symbols per code length 1..=16
@@ -18,15 +19,20 @@ struct HuffTable {
18
19
  }
19
20
 
20
21
  impl HuffTable {
21
- fn build(counts: &[u8; 17], symbols: Vec<u8>) -> HuffTable {
22
- let (mut first_code, mut val_off, mut code, mut k): ([u16; 17], [usize; 17], u16, usize) = ([0; 17], [0; 17], 0, 0);
22
+ // canonical code assignment with an overfull check: a table claiming more
23
+ // codes than a length's code space holds would overflow the u16 code and
24
+ // decode garbage downstream
25
+ fn build(counts: &[u8; 17], symbols: Vec<u8>) -> Result<HuffTable, Err> {
26
+ let (mut first_code, mut val_off, mut code, mut k): ([u16; 17], [usize; 17], u32, usize) = ([0; 17], [0; 17], 0, 0);
23
27
  for len in 1..=16 {
24
- first_code[len] = code;
28
+ first_code[len] = code as u16;
25
29
  val_off[len] = k;
26
30
  k += counts[len] as usize;
27
- code = (code + counts[len] as u16) << 1;
31
+ code += counts[len] as u32;
32
+ if code > (1u32 << len) { return Err(Err::BadCover); }
33
+ code <<= 1;
28
34
  }
29
- HuffTable { counts: *counts, first_code, val_off, symbols }
35
+ Ok(HuffTable { counts: *counts, first_code, val_off, symbols })
30
36
  }
31
37
 
32
38
  fn decode(&self, br: &mut BitReader<'_>) -> Result<u8, Err> {
@@ -34,7 +40,9 @@ impl HuffTable {
34
40
  for len in 1..=16 {
35
41
  code = (code << 1) | br.bit()? as i32;
36
42
  let (fc, cnt): (i32, i32) = (self.first_code[len] as i32, self.counts[len] as i32);
37
- if code - fc < cnt {
43
+ // cnt > 0 keeps an empty length from matching via a negative diff
44
+ // (code below the canonical first code of a longer prefix)
45
+ if cnt > 0 && code >= fc && code - fc < cnt {
38
46
  return Ok(self.symbols[self.val_off[len] + (code - fc) as usize]);
39
47
  }
40
48
  }
@@ -365,7 +373,12 @@ pub(crate) fn decode(raw: &[u8]) -> Result<(usize, usize, usize, Vec<u8>), Err>
365
373
  counts[1..].copy_from_slice(&raw[p + 1..p + 17]);
366
374
  let total: usize = counts[1..].iter().map(|&c| c as usize).sum();
367
375
  if p + 17 + total > pos + seg { return Err(Err::BadCover); }
368
- let table: HuffTable = HuffTable::build(&counts, raw[p + 17..p + 17 + total].to_vec());
376
+ // a DC symbol is a magnitude category (0..=15): anything
377
+ // larger would underflow the bit reader's bit count
378
+ if tc == 0 && raw[p + 17..p + 17 + total].iter().any(|&s| s > 15) {
379
+ return Err(Err::BadCover);
380
+ }
381
+ let table: HuffTable = HuffTable::build(&counts, raw[p + 17..p + 17 + total].to_vec())?;
369
382
  if tc == 0 { dcs[th] = Some(table); } else { acs[th] = Some(table); }
370
383
  p += 17 + total;
371
384
  }
@@ -592,9 +605,13 @@ fn upsample_h2v2(plane: &[u8], pw: usize, ph: usize, w: usize, oh: usize) -> Vec
592
605
  for j in 0..oh.div_ceil(2) {
593
606
  let cur = &plane[j.min(ph - 1) * pw..];
594
607
  for dy in 0..2 {
608
+ // an odd output height ends on a dy=0 row; the below-blend pass
609
+ // would write row `oh` past the buffer, so it lands on `oh - 1`
610
+ // (libjpeg's bottom-edge replication)
611
+ let dst: usize = (2 * j + dy).min(oh - 1);
595
612
  let orow: usize = if dy == 0 { j.saturating_sub(1).min(ph - 1) } else { (j + 1).min(ph - 1) };
596
613
  let oth = &plane[orow * pw..];
597
- let orow_out = &mut out[(2 * j + dy) * w..(2 * j + dy) * w + w];
614
+ let orow_out = &mut out[dst * w..dst * w + w];
598
615
  let colsum = |i: usize| -> u32 { (cur[i.min(pw - 1)] as u32) * 3 + (oth[i.min(pw - 1)] as u32) };
599
616
  let (c0, c1): (u32, u32) = (colsum(0), colsum(1));
600
617
  orow_out[0] = ((c0 * 4 + 8) >> 4) as u8;
@@ -118,11 +118,38 @@ fn encode_edge_blocks() {
118
118
 
119
119
  #[test]
120
120
  fn hostile_huge_sof_rejected() {
121
- // a 65535x65535 SOF claim must fail validation before any buffer is
122
- // allocated — without the pixel cap this tries to reserve ~8GB
123
- let sof: [u8; 11] = [0, 11, 8, 0xFF, 0xFF, 0xFF, 0xFF, 1, 1, 0x11, 0];
124
- let jpg: Vec<u8> = [&[0xFF, 0xD8, 0xFF, 0xC0][..], &sof, &[0xFF, 0xD9][..]].concat();
125
- assert!(decode(&jpg).is_err());
121
+ // SOF claims must fail validation before any buffer is allocated — a
122
+ // 65535x65535 claim wants ~8GB of coefficient buffers, and 16384x16384
123
+ // (the old 256MP cap's boundary) still wants ~1GB
124
+ for (w, h) in [(0xFFFFu16, 0xFFFFu16), (16384u16, 16384u16)] {
125
+ let sof: [u8; 11] = [0, 11, 8, (h >> 8) as u8, h as u8, (w >> 8) as u8, w as u8, 1, 1, 0x11, 0];
126
+ let jpg: Vec<u8> = [&[0xFF, 0xD8, 0xFF, 0xC0][..], &sof, &[0xFF, 0xD9][..]].concat();
127
+ assert!(decode(&jpg).is_err(), "{w}x{h} not rejected");
128
+ }
129
+ }
130
+
131
+ #[test]
132
+ fn hostile_dht_rejected() {
133
+ // DC magnitude symbols above 15 would underflow the bit reader's count and
134
+ // overfull canonical tables would overflow the code book — both rejected
135
+ // at DHT parse time (a debug build once panicked on the first)
136
+ let dqt: Vec<u8> = [[0xFFu8, 0xDB].as_slice(), &67u16.to_be_bytes(), &[0x00], &[1u8; 64]].concat();
137
+ let sof: Vec<u8> = [[0xFFu8, 0xC0].as_slice(), &11u16.to_be_bytes(), &[8u8, 0, 16, 0, 16, 1, 1, 0x11, 0]].concat();
138
+ let ac: Vec<u8> = [[0xFFu8, 0xC4].as_slice(), &20u16.to_be_bytes(), &[0x10], &[1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], &[0]].concat();
139
+ let sos: Vec<u8> = [[0xFFu8, 0xDA].as_slice(), &8u16.to_be_bytes(), &[1u8, 1, 0, 0, 63, 0]].concat();
140
+ let dht = |class: u8, counts: &[u8], symbols: &[u8]| -> Vec<u8> {
141
+ [[0xFFu8, 0xC4].as_slice(), &((2 + 1 + 16 + symbols.len()) as u16).to_be_bytes(), &[class], counts, symbols].concat()
142
+ };
143
+ let counts_len1: [u8; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
144
+ let counts_overfull: [u8; 16] = [3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
145
+ let entropy_and_eoi = &[0x00u8, 0x00, 0xFF, 0xD9][..];
146
+ for bad_dht in [
147
+ dht(0x00, &counts_len1, &[200]), // DC symbol 200
148
+ dht(0x00, &counts_overfull, &[0, 1, 2, 3]), // 3 one-bit codes
149
+ ] {
150
+ let jpg: Vec<u8> = [&[0xFF, 0xD8][..], &dqt, &sof, &bad_dht, &ac, &sos, entropy_and_eoi].concat();
151
+ assert!(decode(&jpg).is_err());
152
+ }
126
153
  }
127
154
 
128
155
  // DUMP_ENC=1 + JPEG_FIXTURES: write our encode of the p444 reference so the
@@ -16,12 +16,26 @@ use std::sync::atomic::{AtomicU64, Ordering};
16
16
  use error::Err;
17
17
  use input::{parse_input, parse_output, InputData, Output};
18
18
 
19
+ // strict [0-9a-fA-F] nibbles, decoded byte-wise: a multi-byte UTF-8 char can
20
+ // neither panic a char-boundary slice nor slip through from_str_radix, which
21
+ // would happily accept a sign-prefixed pair like "+f" as 0x0f
22
+ fn hex_nibble(b: u8) -> Option<u8> {
23
+ match b {
24
+ b'0'..=b'9' => Some(b - b'0'),
25
+ b'a'..=b'f' => Some(b - b'a' + 10),
26
+ b'A'..=b'F' => Some(b - b'A' + 10),
27
+ _ => None
28
+ }
29
+ }
30
+
19
31
  fn parse_hex16(hex: &str) -> Result<[u8; 16], Err> {
20
- let hex: &str = hex.trim();
32
+ let hex: &[u8] = hex.trim().as_bytes();
21
33
  if hex.len() != 32 { return Err(Err::InvalidKey); }
22
34
  let mut key: [u8; 16] = [0u8; 16];
23
35
  for (i, b) in key.iter_mut().enumerate() {
24
- *b = u8::from_str_radix(&hex[i * 2..i * 2 + 2], 16).map_err(|_| Err::InvalidKey)?;
36
+ let hi: u8 = hex_nibble(hex[i * 2]).ok_or(Err::InvalidKey)?;
37
+ let lo: u8 = hex_nibble(hex[i * 2 + 1]).ok_or(Err::InvalidKey)?;
38
+ *b = (hi << 4) | lo;
25
39
  }
26
40
  Ok(key)
27
41
  }
@@ -44,14 +58,17 @@ fn tmp_path(out_path: &str) -> String {
44
58
  format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
45
59
  }
46
60
 
47
- // write to <out>.<n>.tmp then rename — no partial outputs on crash.
61
+ // write to <out>.<n>.tmp, flush it to disk, then rename — no partial outputs
62
+ // on crash, and the rename cannot expose unflushed data after a power loss.
48
63
  // create_new (O_CREAT|O_EXCL) refuses a symlink pre-placed at the predictable
49
64
  // tmp name and fails on collision instead of clobbering an existing file
50
65
  fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
51
66
  let tmp: String = tmp_path(out_path);
52
67
  let mut file: std::fs::File = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)
53
68
  .map_err(|_| Err::WriteFailed)?;
54
- if file.write_all(data).is_err() || std::fs::rename(&tmp, out_path).is_err() {
69
+ if file.write_all(data).is_err()
70
+ || file.sync_data().is_err()
71
+ || std::fs::rename(&tmp, out_path).is_err() {
55
72
  let _ = std::fs::remove_file(&tmp);
56
73
  return Err(Err::WriteFailed);
57
74
  }
@@ -155,16 +172,6 @@ impl TuneMeta {
155
172
  }
156
173
  }
157
174
 
158
- // parsed proc/aproc arguments — every Send piece is resolved under the GIL
159
- // once, then moved wholesale into the worker
160
- struct Args {
161
- input : input::Input,
162
- output : Output,
163
- key : Option<[u8; 16]>,
164
- kid : Option<String>,
165
- core_meta: Option<meta::CoreMeta>
166
- }
167
-
168
175
  fn parse_args(
169
176
  py : Python<'_>,
170
177
  input: &Bound<'_, PyAny>,
@@ -182,6 +189,25 @@ fn parse_args(
182
189
  })
183
190
  }
184
191
 
192
+ // parse_args product with the has_key flag precomputed — measure/load never
193
+ // needs the key itself, only whether one was supplied (for the KID guard)
194
+ struct Args {
195
+ input : input::Input,
196
+ output : Output,
197
+ key : Option<[u8; 16]>,
198
+ kid : Option<String>,
199
+ core_meta: Option<meta::CoreMeta>
200
+ }
201
+
202
+ type ParsedArgs = (input::Input, Output, Option<[u8; 16]>, Option<String>, Option<meta::CoreMeta>, bool);
203
+
204
+ impl Args {
205
+ fn into_parts(self) -> ParsedArgs {
206
+ let has_key: bool = self.key.is_some();
207
+ (self.input, self.output, self.key, self.kid, self.core_meta, has_key)
208
+ }
209
+ }
210
+
185
211
  // Python TuneMeta → Send CoreMeta: only raw byte copies and path strings happen under
186
212
  // the GIL — cover disk read + JPEG prepare (decode/resize/encode) run in the worker
187
213
  // None/0/empty fields mean "keep whatever the file already carries".
@@ -231,9 +257,9 @@ fn proc<'py>(
231
257
  meta : Option<&TuneMeta>,
232
258
  strict : bool
233
259
  ) -> PyResult<Option<Bound<'py, PyAny>>> {
234
- let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
260
+ let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
235
261
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) =
236
- py.detach(move || load_and_measure(input, key.is_some(), kid, core_meta)).map_err(PyErr::from)?;
262
+ py.detach(move || load_and_measure(input, has_key, kid, core_meta)).map_err(PyErr::from)?;
237
263
  let guarded: bool = strict && key.is_some();
238
264
 
239
265
  match output {
@@ -293,12 +319,12 @@ fn aproc<'py>(
293
319
  meta : Option<&TuneMeta>,
294
320
  strict : bool
295
321
  ) -> PyResult<Bound<'py, PyAny>> {
296
- let Args { input, output, key, kid, core_meta }: Args = parse_args(py, input, out, key, kid, meta)?;
322
+ let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
297
323
  let guarded: bool = strict && key.is_some();
298
324
 
299
325
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
300
326
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) = tokio::task::spawn_blocking(
301
- move || load_and_measure(input, key.is_some(), kid, core_meta),
327
+ move || load_and_measure(input, has_key, kid, core_meta),
302
328
  ).await.map_err(join_err)??;
303
329
  match output {
304
330
  Output::Path(p) => {
@@ -3,7 +3,7 @@
3
3
 
4
4
  use std::borrow::Cow;
5
5
 
6
- use crate::boxes::{parse, write_header, Writer};
6
+ use crate::boxes::{parse, write_header, Box, Writer};
7
7
  use crate::Err;
8
8
 
9
9
  pub(crate) struct Cover<'a> {
@@ -145,8 +145,12 @@ fn hdlr_box() -> Vec<u8> {
145
145
  pub(crate) fn append_moov_with_meta(out: &mut Writer<'_>, children: &[u8], meta: &CoreMeta) -> Result<(), Err> {
146
146
  // every old udta goes — keeping any would both leak stale tags and shadow the
147
147
  // fresh subtree for the Windows handler (it reads only the first udta/meta)
148
- let udta: Vec<(usize, usize)> = parse(children, 0, children.len())
149
- .iter().filter(|c| c.is(b"udta")).map(|c| (c.start, c.end)).collect();
148
+ let top: Vec<Box> = parse(children, 0, children.len());
149
+ if top.len() >= crate::boxes::MAX_BOXES {
150
+ return Err(Err::InvalidMp4); // saturated parse: the udta map would be wrong
151
+ }
152
+ let udta: Vec<(usize, usize)> = top.iter().filter(|c| c.is(b"udta"))
153
+ .map(|c| (c.start, c.end)).collect();
150
154
 
151
155
  let mut ilst: Vec<u8> = Vec::new();
152
156
  build_items(&mut ilst, meta)?;
@@ -1,9 +1,9 @@
1
1
  use std::ops::Range;
2
2
 
3
3
  use aes::Aes128;
4
- use ctr::cipher::{KeyIvInit, StreamCipher};
4
+ use ctr::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
5
5
 
6
- use crate::boxes::{parse, write_header, Box, Writer};
6
+ use crate::boxes::{header_len, parse, write_header, Box, Writer, MAX_BOXES};
7
7
  use crate::meta::{append_moov_with_meta, CoreMeta};
8
8
  use crate::Err;
9
9
 
@@ -11,9 +11,16 @@ type Aes128Ctr = ctr::Ctr128BE<Aes128>;
11
11
 
12
12
  const CONTAINERS: &[&[u8; 4]] = &[b"moov", b"trak", b"mdia", b"minf", b"stbl"];
13
13
  const MAX_TREE_DEPTH: usize = 16;
14
- // chi2 thresholds calibrated on real AAC tracks (structured ~3800..14000, noise ~210..340)
15
- const MIN_JUDGE_BYTES: usize = 16 * 1024; // below this, chi2 drowns in the df=255 noise floor
14
+ // chi2 thresholds calibrated on real AAC tracks (structured ~3800..14000 at
15
+ // 16KB, ~950+ at 4KB; noise is df-bound at ~210..340 for any size above ~1KB,
16
+ // so 500 splits clean from corrupt with margin on both sides down to 4KB)
17
+ const MIN_JUDGE_BYTES: usize = 4 * 1024;
16
18
  const CHI2_CORRUPT_BELOW: f64 = 500.0;
19
+ // hostile default-fill truns claim up to 2^32 samples for a few bytes of box;
20
+ // each claimed sample costs a u32 of sizes storage, so a handful of such truns
21
+ // in one traf would multiply the file size into an allocation abort. No real
22
+ // fragment carries anywhere near this many samples.
23
+ const MAX_SAMPLES: usize = 1 << 22; // 4M samples per fragment
17
24
  // fragment work is spread over threads only when it is large enough to pay
18
25
  // for the spawns (a small single-fragment track stays on one thread)
19
26
  const MIN_PAR_BYTES: usize = 8 * 1024 * 1024;
@@ -68,12 +75,13 @@ pub fn build(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&Co
68
75
  // every payload copy into a size add, so the length is exact by construction
69
76
  fn walk(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&CoreMeta>, out: &mut Writer<'_>) -> Result<Vec<Job>, Err> {
70
77
  let boxes: Vec<Box> = parse(data, 0, data.len());
71
- if boxes.is_empty() { return Err(Err::InvalidMp4); }
78
+ if boxes.is_empty() || boxes.len() >= MAX_BOXES { return Err(Err::InvalidMp4); }
72
79
 
73
80
  let mut deltas: Vec<i64> = Vec::new();
74
81
  let mut patches: Vec<(usize, Vec<usize>)> = Vec::new(); // (frag base, sidx word offsets)
75
82
  let mut jobs: Vec<Job> = Vec::new();
76
83
  let mut pending: Option<Range<usize>> = None; // queued passthrough run
84
+ let mut unpaired_moof: bool = false;
77
85
 
78
86
  let mut i = 0;
79
87
  while i < boxes.len() {
@@ -84,11 +92,16 @@ fn walk(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&CoreMet
84
92
  let plan: Plan = visit_moof(out, data, b);
85
93
  deltas.push((b.end - b.start) as i64 - plan.rebuilt_len as i64);
86
94
  if i + 1 < boxes.len() && boxes[i + 1].is(b"mdat") {
87
- if let Some(job) = stage_mdat(out, data, &boxes[i + 1], plan, key, strict) {
95
+ if let Some(job) = stage_mdat(out, data, &boxes[i + 1], plan, key, strict, unpaired_moof) {
88
96
  jobs.push(job);
89
97
  }
98
+ unpaired_moof = false;
90
99
  i += 2;
91
100
  } else {
101
+ // this fragment's payload is not adjacent — if a later mdat
102
+ // follows another moof, that mdat may hold samples of several
103
+ // fragments and no plan can be trusted on it
104
+ unpaired_moof = true;
92
105
  i += 1;
93
106
  }
94
107
  continue;
@@ -148,6 +161,8 @@ fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box) -> Plan {
148
161
  let mut ivs: Option<Vec<[u8; 16]>> = None;
149
162
  let mut sizes: Vec<u32> = Vec::new();
150
163
  let mut default_size: Option<u32> = None;
164
+ let mut oversized: bool = false;
165
+ let mut subsampled: bool = false;
151
166
 
152
167
  for child in parse(data, b.content_start, b.end) {
153
168
  if !child.is(b"traf") {
@@ -157,12 +172,26 @@ fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box) -> Plan {
157
172
  let traf: Vec<Box> = parse(data, child.content_start, child.end);
158
173
 
159
174
  // gather: tfhd default first so trun fallback works in any order
175
+ // (a saturated child count means box spam — nothing to decrypt)
176
+ if traf.len() >= MAX_BOXES { oversized = true; }
160
177
  default_size = traf.iter().find(|t| t.is(b"tfhd"))
161
178
  .and_then(|t| parse_tfhd(data, t.content_start, t.end));
162
179
  for t in &traf {
163
180
  match &t.typ {
164
- b"senc" if ivs.is_none() => ivs = parse_senc(data, t.content_start, t.end),
165
- b"trun" => sizes.extend(parse_trun_sizes(data, t.content_start, t.end, default_size)),
181
+ b"senc" if ivs.is_none() => {
182
+ if let Some((list, subs)) = parse_senc(data, t.content_start, t.end) {
183
+ ivs = Some(list);
184
+ subsampled = subs;
185
+ }
186
+ }
187
+ b"trun" if !oversized => {
188
+ sizes.extend(parse_trun_sizes(data, t.content_start, t.end, default_size));
189
+ if sizes.len() > MAX_SAMPLES { // many capped truns must not sum back into a bomb
190
+ sizes.clear();
191
+ oversized = true;
192
+ }
193
+ }
194
+ b"trun" => {}
166
195
  _ => {}
167
196
  }
168
197
  }
@@ -187,12 +216,17 @@ fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box) -> Plan {
187
216
  }
188
217
 
189
218
  // senc/trun count mismatch → partially plain fragment (part of the track is
190
- // stored in the clear); skip decryption for it
191
- let ok: bool = matches!(&ivs, Some(list) if !sizes.is_empty() && list.len() == sizes.len());
192
-
219
+ // stored in the clear); skip decryption for it. An oversized trun claim is
220
+ // treated the same way, and so is real subsample encryption — per-entry
221
+ // clear/protected ranges are not applied, so full-sample decryption would
222
+ // corrupt the clear bytes; the fragment passes through untouched instead.
223
+ let ok: bool = !oversized && !subsampled
224
+ && matches!(&ivs, Some(list) if !sizes.is_empty() && list.len() == sizes.len());
193
225
  out.header(b"moof", content.len());
194
226
  out.put(&content);
195
- Plan { ivs, sizes, default: default_size, ok, rebuilt_len: content.len() + 8 }
227
+ // the rebuilt moof's header may itself be largesize — the delta must count
228
+ // exactly what the writer emitted
229
+ Plan { ivs, sizes, default: default_size, ok, rebuilt_len: content.len() + header_len(content.len()) }
196
230
  }
197
231
 
198
232
  fn write_traf_trun(traf_out: &mut Vec<u8>, data: &[u8], t: &Box, removed: i64) {
@@ -200,29 +234,40 @@ fn write_traf_trun(traf_out: &mut Vec<u8>, data: &[u8], t: &Box, removed: i64) {
200
234
  traf_out.extend_from_slice(&patch_trun(data, t.content_start, t.end, removed));
201
235
  }
202
236
 
203
- // chi2 costs a full pass over the payload — paid per fragment in phase 2
204
- fn chi2(buf: &[u8]) -> f64 {
205
- let n: usize = buf.len();
206
- if n == 0 { return 0.0; }
207
- let mut hist: [[u64; 256]; CHI2_LANES] = [[0u64; 256]; CHI2_LANES];
237
+ // chi2 costs a full pass over the payload — paid per fragment in phase 2.
238
+ // The counting phase is factored out so parallel chunks can merge histograms
239
+ // additively and the statistic is computed once per fragment.
240
+ fn hist(buf: &[u8]) -> [u64; 256] {
241
+ let mut lanes: [[u64; 256]; CHI2_LANES] = [[0u64; 256]; CHI2_LANES];
208
242
  let (body, tail): (&[u8], &[u8]) = buf.split_at(buf.len() & !(CHI2_LANES - 1));
209
243
  for c in body.chunks_exact(CHI2_LANES) {
210
- for (l, &b) in c.iter().enumerate() { hist[l][b as usize] += 1; }
244
+ for (l, &b) in c.iter().enumerate() { lanes[l][b as usize] += 1; }
211
245
  }
212
- for &b in tail { hist[0][b as usize] += 1; }
246
+ for &b in tail { lanes[0][b as usize] += 1; }
213
247
  let mut total: [u64; 256] = [0u64; 256];
214
- for lane in &hist {
248
+ for lane in &lanes {
215
249
  for (t, &o) in total.iter_mut().zip(lane.iter()) { *t += o; }
216
250
  }
251
+ total
252
+ }
253
+
254
+ fn chi2_hist(h: &[u64; 256], n: usize) -> f64 {
255
+ if n == 0 { return 0.0; }
217
256
  let e: f64 = n as f64 / 256.0;
218
- total.iter().map(|&o| { let d: f64 = o as f64 - e; d * d / e }).sum()
257
+ h.iter().map(|&o| { let d: f64 = o as f64 - e; d * d / e }).sum()
258
+ }
259
+
260
+ fn chi2(buf: &[u8]) -> f64 {
261
+ let n: usize = buf.len();
262
+ if n == 0 { return 0.0; }
263
+ chi2_hist(&hist(buf), n)
219
264
  }
220
265
 
221
266
  // 16 sub-histograms break the same-bucket increment dependency chain (16
222
267
  // independent chains instead of one) — the scalar loop was the whole strict cost
223
268
  const CHI2_LANES: usize = 16;
224
269
 
225
- fn stage_mdat(out: &mut Writer<'_>, data: &[u8], m: &Box, plan: Plan, key: Option<&[u8; 16]>, strict: bool) -> Option<Job> {
270
+ fn stage_mdat(out: &mut Writer<'_>, data: &[u8], m: &Box, plan: Plan, key: Option<&[u8; 16]>, strict: bool, ambiguous: bool) -> Option<Job> {
226
271
  let content_len: usize = m.end - m.content_start;
227
272
  // a largesize (64-bit) mdat keeps its 64-bit header — a u32 rewrite would wrap
228
273
  if content_len + 8 > u32::MAX as usize || u32::from_be_bytes(data[m.start..m.start + 4].try_into().unwrap()) == 1 {
@@ -234,7 +279,6 @@ fn stage_mdat(out: &mut Writer<'_>, data: &[u8], m: &Box, plan: Plan, key: Optio
234
279
  }
235
280
  let base: usize = out.len();
236
281
  out.put(&data[m.content_start..m.end]);
237
- let encrypted: bool = plan.ok;
238
282
  // measure mode records no jobs — phase 2 never runs there
239
283
  let Writer::Buf { .. } = out else { return None };
240
284
  Some(Job {
@@ -242,47 +286,210 @@ fn stage_mdat(out: &mut Writer<'_>, data: &[u8], m: &Box, plan: Plan, key: Optio
242
286
  ivs : plan.ivs,
243
287
  sizes : plan.sizes,
244
288
  default : plan.default,
245
- encrypted,
246
- judged : encrypted && key.is_some() && strict && content_len >= MIN_JUDGE_BYTES
289
+ encrypted: plan.ok && !ambiguous,
290
+ judged : plan.ok && !ambiguous && key.is_some() && strict && content_len >= MIN_JUDGE_BYTES
247
291
  })
248
292
  }
249
293
 
250
- // phase 2: decrypt + judge every fragment. Small jobs stay on the calling
251
- // thread; large batches split across worker threads over the disjoint payload
252
- // ranges (the raw view is exclusive — `buf` is untouched elsewhere in the scope)
294
+ // phase 2: decrypt + judge every fragment. Small workloads stay on the calling
295
+ // thread; large ones split across worker threads over disjoint payload spans —
296
+ // across fragments when there are many, within a fragment when one is huge
297
+ // (histograms merge additively, so chi2 is identical to the serial pass)
253
298
  fn run_jobs(buf: &mut [u8], jobs: Vec<Job>, key: Option<&[u8; 16]>) -> Vec<FragmentStat> {
254
299
  if jobs.is_empty() { return Vec::new(); }
255
300
  let total: usize = jobs.iter().map(|j| j.range.len()).sum();
256
- let threads: usize = if key.is_some() && jobs.len() > 1 && total >= MIN_PAR_BYTES {
257
- std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).min(jobs.len())
258
- } else {
259
- 1
260
- };
261
- let mut stats: Vec<FragmentStat> = if threads == 1 {
262
- jobs.iter().map(|job| decrypt_job(&mut buf[job.range.clone()], job, key)).collect()
263
- } else {
264
- // the buffer base crosses threads as a usize — disjoint capture would
265
- // otherwise hoist the raw pointer out of any wrapper and break Send
266
- let base: usize = buf.as_ptr() as usize;
267
- let chunk: usize = jobs.len().div_ceil(threads);
268
- std::thread::scope(|s| {
269
- let handles: Vec<_> = jobs.chunks(chunk)
270
- .map(|group| s.spawn(move || -> Vec<FragmentStat> {
271
- group.iter().map(|job| {
272
- let piece: &mut [u8] = unsafe {
273
- std::slice::from_raw_parts_mut((base + job.range.start) as *mut u8, job.range.len())
274
- };
275
- decrypt_job(piece, job, key)
276
- }).collect()
277
- }))
278
- .collect();
279
- handles.into_iter().flat_map(|h| h.join().expect("decrypt worker panicked")).collect()
280
- })
281
- };
301
+ let cores: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
302
+ if !key.is_some() || total < MIN_PAR_BYTES || cores == 1 {
303
+ return jobs.iter().map(|job| decrypt_job(&mut buf[job.range.clone()], job, key)).collect();
304
+ }
305
+
306
+ let chunks: Vec<Chunk<'_>> = jobs.iter().enumerate()
307
+ .flat_map(|(i, job)| job_chunks(i, job, (cores * job.range.len()).div_ceil(total)))
308
+ .collect();
309
+ // the buffer base crosses threads as a usize — disjoint capture would
310
+ // otherwise hoist the raw pointer out of any wrapper and break Send.
311
+ // Each worker folds its same-job chunk runs into one Verdict, so nothing
312
+ // per-chunk crosses back except split-job partials
313
+ let base: usize = buf.as_ptr() as usize;
314
+ let folded: Vec<Vec<(usize, Verdict)>> = std::thread::scope(|s| {
315
+ let per: usize = chunks.len().div_ceil(cores).max(1);
316
+ let handles: Vec<_> = chunks.chunks(per)
317
+ .map(|group| s.spawn(move || -> Vec<(usize, Verdict)> {
318
+ let mut out: Vec<(usize, Verdict)> = Vec::new();
319
+ let mut i: usize = 0;
320
+ while i < group.len() {
321
+ let j: usize = group[i].job;
322
+ let first_start: usize = group[i].start;
323
+ let mut acc: [u64; 256] = [0u64; 256];
324
+ let mut complete: bool = false;
325
+ while i < group.len() && group[i].job == j {
326
+ let c: &Chunk<'_> = &group[i];
327
+ if let Some(h) = run_chunk(unsafe {
328
+ std::slice::from_raw_parts_mut((base + c.start) as *mut u8, c.len)
329
+ }, c, key) {
330
+ for (a, &o) in acc.iter_mut().zip(h.iter()) { *a += o; }
331
+ }
332
+ complete = c.last;
333
+ i += 1;
334
+ }
335
+ let bytes: usize = group[i - 1].start + group[i - 1].len - first_start;
336
+ out.push((j, if complete {
337
+ Verdict::Chi2(chi2_hist(&acc, bytes))
338
+ } else {
339
+ Verdict::Partial(acc.into())
340
+ }));
341
+ }
342
+ out
343
+ }))
344
+ .collect();
345
+ handles.into_iter().map(|h| h.join().expect("decrypt worker panicked")).collect()
346
+ });
347
+
348
+ let mut partials: Vec<Option<[u64; 256]>> = Vec::new();
349
+ let mut stats: Vec<FragmentStat> = jobs.iter().map(|job| FragmentStat {
350
+ index: 0, encrypted: job.encrypted, bytes: job.range.len(), chi2: f64::NAN,
351
+ corrupt: if !job.encrypted { Some(false) } else if !job.judged { None } else { Some(false) }
352
+ }).collect();
353
+ for group in &folded {
354
+ for (j, v) in group {
355
+ match v {
356
+ Verdict::Chi2(c) => stats[*j].chi2 = *c,
357
+ Verdict::Partial(h) => {
358
+ if jobs[*j].judged {
359
+ while partials.len() <= *j { partials.push(None); }
360
+ match &mut partials[*j] {
361
+ Some(acc) => for (a, &o) in acc.iter_mut().zip(h.iter()) { *a += o; },
362
+ slot @ None => *slot = Some(*h.clone()),
363
+ }
364
+ }
365
+ }
366
+ }
367
+ }
368
+ }
369
+ for (j, job) in jobs.iter().enumerate() {
370
+ if job.judged {
371
+ // NaN = no complete verdict landed in any worker (or the job's
372
+ // chunks split across workers — its partial was merged instead)
373
+ let chi2: f64 = if stats[j].chi2.is_nan() {
374
+ partials.get(j).and_then(|h| h.as_ref()).map_or(0.0, |h| chi2_hist(h, job.range.len()))
375
+ } else {
376
+ stats[j].chi2
377
+ };
378
+ stats[j].chi2 = chi2;
379
+ stats[j].corrupt = Some(chi2 < CHI2_CORRUPT_BELOW);
380
+ }
381
+ }
282
382
  for (i, f) in stats.iter_mut().enumerate() { f.index = i; }
283
383
  stats
284
384
  }
285
385
 
386
+ // one byte span of a fragment: disjoint from every other chunk's span, so the
387
+ // AES writes and the chi2 histogram never cross threads. `sample` is the resume
388
+ // point — the sample containing the span's first byte and the offset inside it
389
+ // (CTR keystream blocks are addressable, so a span may start mid-sample) — or
390
+ // None when the span holds only ciphertext tail. `live_len` caps decryption at
391
+ // the serial loop's break point; the rest of the span is untouched payload.
392
+ // `last` marks the fragment's final chunk so a worker can fold per-job results.
393
+ struct Chunk<'a> {
394
+ job : usize,
395
+ start : usize, // absolute byte offset inside the output buffer
396
+ len : usize,
397
+ judged : bool,
398
+ last : bool,
399
+ sample : Option<(usize, usize)>,
400
+ live_len: usize,
401
+ ivs : &'a [[u8; 16]],
402
+ sizes : &'a [u32],
403
+ default: Option<u32>
404
+ }
405
+
406
+ // a worker's folded result for one job: the final statistic when the job's
407
+ // chunks all landed in this group, or a partial histogram to merge upstream
408
+ // (only jobs split across group boundaries carry one — rare, hence boxed)
409
+ enum Verdict {
410
+ Chi2(f64),
411
+ Partial(std::boxed::Box<[u64; 256]>),
412
+ }
413
+
414
+ // split one fragment into `want` byte spans. The serial loop's break rule (the
415
+ // first zero-size or overflowing sample ends the fragment's stream) is baked
416
+ // into the live prefix; spans past it carry no resume point and only histogram
417
+ fn job_chunks<'a>(idx: usize, job: &'a Job, want: usize) -> Vec<Chunk<'a>> {
418
+ let plain = |start: usize, len: usize, sample: Option<(usize, usize)>, live_len: usize| Chunk {
419
+ job: idx, start, len, judged: job.judged, last: false, sample, live_len,
420
+ ivs: job.ivs.as_deref().unwrap_or(&[]), sizes: &job.sizes, default: job.default
421
+ };
422
+ if !job.encrypted {
423
+ return vec![plain(job.range.start, job.range.len(), None, 0)];
424
+ }
425
+ let want = want.max(1);
426
+ if want == 1 { // common case: the whole fragment on one worker, serial rules
427
+ let live = live_prefix(job);
428
+ return vec![plain(job.range.start, job.range.len(), Some((0, 0)), live)];
429
+ }
430
+ let live_end: usize = live_prefix(job);
431
+ let ivs: &[[u8; 16]] = job.ivs.as_deref().unwrap_or(&[]);
432
+ // byte offset of each live sample's start (live_prefix guarantees the same
433
+ // break rule, so offsets are strictly increasing below live_end)
434
+ let mut offsets: Vec<usize> = Vec::new();
435
+ let mut pos: usize = 0;
436
+ for &sz in job.sizes.iter().take(ivs.len()) {
437
+ let sz: usize = if sz == 0 { job.default.unwrap_or(0) } else { sz } as usize;
438
+ if sz == 0 || pos + sz > job.range.len() { break; }
439
+ offsets.push(pos);
440
+ pos += sz;
441
+ }
442
+ let span: usize = job.range.len().div_ceil(want);
443
+ let mut chunks: Vec<Chunk<'a>> = Vec::new();
444
+ for k in 0..want {
445
+ let s: usize = k * span;
446
+ if s >= job.range.len() { break; }
447
+ let len: usize = span.min(job.range.len() - s);
448
+ let sample: Option<(usize, usize)> = if s >= live_end {
449
+ None
450
+ } else {
451
+ let si: usize = offsets.partition_point(|&o| o <= s).max(1) - 1;
452
+ Some((si, s - offsets[si]))
453
+ };
454
+ chunks.push(plain(job.range.start + s, len, sample, live_end.saturating_sub(s).min(len)));
455
+ }
456
+ if let Some(c) = chunks.last_mut() { c.last = true; }
457
+ chunks
458
+ }
459
+
460
+ // byte length of the serial decrypt loop's live prefix for one fragment
461
+ fn live_prefix(job: &Job) -> usize {
462
+ let ivs: &[[u8; 16]] = job.ivs.as_deref().unwrap_or(&[]);
463
+ let mut pos: usize = 0;
464
+ for (iv, &sz) in ivs.iter().zip(job.sizes.iter()) {
465
+ let _ = iv;
466
+ let sz: usize = if sz == 0 { job.default.unwrap_or(0) } else { sz } as usize;
467
+ if sz == 0 || pos + sz > job.range.len() { break; }
468
+ pos += sz;
469
+ }
470
+ pos
471
+ }
472
+
473
+ // decrypt one chunk's span (resuming mid-sample via the CTR counter) and
474
+ // histogram it when judged
475
+ fn run_chunk(buf: &mut [u8], chunk: &Chunk<'_>, key: Option<&[u8; 16]>) -> Option<[u64; 256]> {
476
+ if let (Some(k), Some((mut s, mut skip))) = (key, chunk.sample) {
477
+ let mut pos: usize = 0;
478
+ while pos < chunk.live_len && s < chunk.sizes.len() {
479
+ let sz: usize = if chunk.sizes[s] == 0 { chunk.default.unwrap_or(0) } else { chunk.sizes[s] } as usize;
480
+ if sz == 0 { break; } // serial break rule — a live prefix never contains one
481
+ let take: usize = (sz - skip).min(chunk.live_len - pos).min(buf.len() - pos);
482
+ let mut cipher: Aes128Ctr = Aes128Ctr::new(k.into(), (&chunk.ivs[s]).into());
483
+ if skip > 0 { cipher.seek(skip as u64); }
484
+ cipher.apply_keystream(&mut buf[pos..pos + take]);
485
+ pos += take;
486
+ skip = 0;
487
+ s += 1;
488
+ }
489
+ }
490
+ if chunk.judged { Some(hist(buf)) } else { None }
491
+ }
492
+
286
493
  fn decrypt_job(buf: &mut [u8], job: &Job, key: Option<&[u8; 16]>) -> FragmentStat {
287
494
  if job.encrypted {
288
495
  if let (Some(ivs), Some(key)) = (&job.ivs, key) {
@@ -331,15 +538,17 @@ fn parse_tfhd(data: &[u8], start: usize, end: usize) -> Option<u32> {
331
538
  Some(u32::from_be_bytes(data[pos..pos + 4].try_into().ok()?))
332
539
  }
333
540
 
334
- // IVs from senc; subsample entries (flag 0x2) are parsed over for IV alignment,
335
- // not applied — samples are fully encrypted; bounded by the box end, not the file
336
- fn parse_senc(data: &[u8], start: usize, end: usize) -> Option<Vec<[u8; 16]>> {
541
+ // IVs from senc plus whether real subsample entries exist (flags 0x2 with a
542
+ // non-empty per-entry table): subsample ranges are parsed for IV alignment
543
+ // only — bounded by the box end, never the file
544
+ fn parse_senc(data: &[u8], start: usize, end: usize) -> Option<(Vec<[u8; 16]>, bool)> {
337
545
  if start + 8 > end { return None; }
338
546
  let flags: u32 = u32::from_be_bytes(data[start..start + 4].try_into().ok()?) & 0xFFFFFF;
339
547
  let count: usize = u32::from_be_bytes(data[start + 4..start + 8].try_into().ok()?) as usize;
340
548
  if count > (end - start - 8) / 8 { return None; } // hostile count bound
341
549
  let mut pos: usize = start + 8;
342
550
  let mut ivs: Vec<[u8; 16]> = Vec::with_capacity(count);
551
+ let mut subsampled: bool = false;
343
552
  for _ in 0..count {
344
553
  if pos + 8 > end { return None; }
345
554
  let mut iv: [u8; 16] = [0u8; 16];
@@ -348,11 +557,12 @@ fn parse_senc(data: &[u8], start: usize, end: usize) -> Option<Vec<[u8; 16]>> {
348
557
  if flags & 0x2 != 0 {
349
558
  if pos + 2 > end { return None; }
350
559
  let sub: usize = u16::from_be_bytes(data[pos..pos + 2].try_into().ok()?) as usize;
560
+ if sub > 0 { subsampled = true; }
351
561
  pos += 2 + sub * 6;
352
562
  }
353
563
  ivs.push(iv);
354
564
  }
355
- Some(ivs)
565
+ Some((ivs, subsampled))
356
566
  }
357
567
 
358
568
  fn parse_trun_sizes(data: &[u8], start: usize, end: usize, default: Option<u32>) -> Vec<u32> {
@@ -369,11 +579,12 @@ fn parse_trun_sizes(data: &[u8], start: usize, end: usize, default: Option<u32>)
369
579
  (if flags & 0x800 != 0 { 4 } else { 0 });
370
580
  let size_off: usize = if flags & 0x100 != 0 { 4usize } else { 0 };
371
581
  // hostile count bound: an entry table cannot exceed the box; a default
372
- // fill cannot exceed a quarter of the file (one u32 size each)
582
+ // fill cannot exceed a quarter of the file (one u32 size each) nor the
583
+ // per-fragment sample cap
373
584
  let count: usize = if flags & 0x200 != 0 && stride != 0 {
374
585
  count.min(end.saturating_sub(pos) / stride) // pos may sit past end on hostile flags
375
586
  } else {
376
- count.min(data.len() / 4)
587
+ count.min(data.len() / 4).min(MAX_SAMPLES)
377
588
  };
378
589
  if flags & 0x200 == 0 || stride == 0 {
379
590
  return vec![default.unwrap_or(0); count];
@@ -425,8 +636,15 @@ fn patch_sidx(out: &mut [u8], deltas: &[i64], patches: &[(usize, Vec<usize>)]) {
425
636
  }
426
637
 
427
638
  fn rebuild_container(data: &[u8], start: usize, end: usize, depth: usize) -> Vec<u8> {
639
+ let children: Vec<Box> = parse(data, start, end);
640
+ if children.len() >= MAX_BOXES {
641
+ // box spam: skip sanitizing this container entirely — the raw bytes
642
+ // pass through and any stray pssh inside stays (a 2M-child moov is
643
+ // hostile by definition; sanitizing it is not worth the memory)
644
+ return data[start..end].to_vec();
645
+ }
428
646
  let mut out: Vec<u8> = Vec::new();
429
- for child in parse(data, start, end) {
647
+ for child in &children {
430
648
  match &child.typ {
431
649
  b"pssh" => {}
432
650
  b"stsd" => {
@@ -358,6 +358,36 @@ def test_error_invalid_kid(sp, src_file):
358
358
  assert e.value.code == 2
359
359
 
360
360
 
361
+ def test_error_key_multibyte_utf8(sp, src_file):
362
+ # exactly 32 BYTES with a 2-byte char at an odd offset — the hex decoder
363
+ # must reject it with code 1, not panic on a char-boundary slice
364
+ for bad in ("a" * 29 + "Ω" + "b", "a" * 27 + "Ω" + "bbb"):
365
+ with pytest.raises(DecrypTuneError) as e:
366
+ sp.proc(input=src_file, key=bad)
367
+ assert e.value.code == 1
368
+ with pytest.raises(DecrypTuneError) as e:
369
+ sp.proc(input=src_file, key=KEY_HEX, kid=bad)
370
+ assert e.value.code == 2
371
+
372
+
373
+ def test_error_key_sign_prefixed(sp, src_file):
374
+ # from_str_radix accepts "+f" as 0x0f — the nibble decoder must not
375
+ with pytest.raises(DecrypTuneError) as e:
376
+ sp.proc(input=src_file, key="+f" * 16)
377
+ assert e.value.code == 1
378
+
379
+
380
+ def test_error_surrogate_path(sp, src_file):
381
+ # os.fsdecode on Windows can produce lone surrogates — a coded input error,
382
+ # never a raw UnicodeEncodeError
383
+ with pytest.raises(DecrypTuneError) as e:
384
+ sp.proc(input="D:\\bad\udce9path.mp4")
385
+ assert e.value.code == 9
386
+ with pytest.raises(DecrypTuneError) as e:
387
+ sp.proc(input=src_file, out="D:\\bad\udce9out.m4a")
388
+ assert e.value.code == 10
389
+
390
+
361
391
  def test_error_missing_input(sp, tmp_path):
362
392
  with pytest.raises(DecrypTuneError) as e:
363
393
  sp.proc(input=str(tmp_path / "missing.m4a"), key=KEY_HEX)
@@ -388,6 +418,32 @@ def test_error_invalid_out_type(sp, src_file):
388
418
  assert e.value.code == 10
389
419
 
390
420
 
421
+ def test_trun_sample_cap_bomb(sp):
422
+ # 200 default-fill truns each claiming 2^32-1 samples: the sizes vec once
423
+ # scaled with the FILE size per trun (~6.4GB from this 32MB file, an
424
+ # allocation abort). The per-fragment sample cap marks the fragment
425
+ # oversized → plain passthrough, identical to the no-key pass.
426
+ ftyp = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom")
427
+ traf = box(b"tfhd", u32(0x10) + u32(1) + u32(64))
428
+ traf += (box(b"trun", u32(0) + u32(0xFFFFFFFF)) * 200)
429
+ moof = box(b"moof", box(b"mfhd", u32(0) + u32(1)) + box(b"traf", traf))
430
+ data = ftyp + moof + box(b"mdat", b"\x00" * 65536)
431
+ data += box(b"free", b"\x00" * (32 * 1024 * 1024 - len(data)))
432
+ data += make_moov()
433
+ out = sp.proc(input=data, key=KEY_HEX, strict=True)
434
+ assert out == sp.proc(input=data)
435
+
436
+
437
+ def test_box_spam_rejected(sp):
438
+ # 3M top-level boxes: parse vec saturation now fails the file outright
439
+ # (coded 4) instead of materializing ~96MB of box structures
440
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + \
441
+ (u32(8) + b"free") * 3_000_000
442
+ with pytest.raises(DecrypTuneError) as e:
443
+ sp.proc(input=data)
444
+ assert e.value.code == 4
445
+
446
+
391
447
  def test_error_bad_cover(sp, src_file):
392
448
  with pytest.raises(DecrypTuneError) as e:
393
449
  sp.proc(input=src_file, key=KEY_HEX, meta=TuneMeta(cover=b"notanimage"))
@@ -402,6 +458,15 @@ def test_error_cover_missing(sp, src_file):
402
458
  assert "cover file not found" in e.value.message
403
459
 
404
460
 
461
+ def test_error_cover_too_large(sp, src_file):
462
+ # additive code 14 — covers land inside the ilst whole, so an absurd one
463
+ # must be refused instead of bloating the output without bound
464
+ with pytest.raises(DecrypTuneError) as e:
465
+ sp.proc(input=src_file, key=KEY_HEX, meta=TuneMeta(cover=b"\x89PNG\r\n\x1a\n" + bytes(33 * 1024 * 1024)))
466
+ assert e.value.code == 14
467
+ assert "cover too large" in e.value.message
468
+
469
+
405
470
  def test_path_out_pathlib(sp, src_file, tmp_path):
406
471
  # out accepts os.PathLike exactly like input
407
472
  dst = tmp_path / "out_pathlib.m4a"
@@ -516,6 +581,80 @@ def test_strict(sp, sample):
516
581
  assert "fragments:" in str(e.value) and "chi2=" in str(e.value)
517
582
 
518
583
 
584
+ def test_strict_judges_4kb_fragments(sp):
585
+ # the judge floor used to sit at 16KB, so a fake-key file of 4KB fragments
586
+ # slipped through strict with every fragment unjudged; 4KB is now judged
587
+ # (noise stays df-bound at ~255, structured 4KB fragments score ~950+)
588
+ parts, sizes = [], []
589
+ for f in range(100):
590
+ iv = struct.pack(">H", f) + bytes([1, 2, 3, 4, 5, 6])
591
+ enc = ctr_crypt(KEY, iv, bytes([0x11]) * 4096)
592
+ moof = make_moof(f + 1, [make_tfhd(), make_trun([4096], 0), make_senc([iv])])
593
+ i = moof.find(b"trun")
594
+ moof = moof[:i + 12] + i32(len(moof) + 8) + moof[i + 16:]
595
+ parts.append(mof := moof + box(b"mdat", enc))
596
+ sizes.append(len(mof))
597
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + make_sidx(sizes) + b"".join(parts) + make_moov()
598
+ with pytest.raises(DecrypTuneError) as e:
599
+ sp.proc(input=data, key=FAKE_KEY_HEX, strict=True)
600
+ assert e.value.code == 8
601
+ out = sp.proc(input=data, key=KEY_HEX, strict=True) # the real key still passes
602
+ assert sp.proc(input=out) == out
603
+
604
+
605
+ def test_single_huge_fragment_strict(sp):
606
+ # one 9MB fragment crosses the parallel gate with a single job — the
607
+ # sample-aligned chunk splitter must produce byte-identical output and the
608
+ # same strict verdict as the serial path
609
+ iv = bytes([9, 8, 7, 6, 5, 4, 3, 2])
610
+ payload = bytes([0x5A * (9 * 1024 * 1024 // 1024) & 0xFF]) * (9 * 1024 * 1024)
611
+ enc = ctr_crypt(KEY, iv, payload)
612
+ moof = make_moof(1, [make_tfhd(), make_trun([len(payload)], 0), make_senc([iv])])
613
+ i = moof.find(b"trun")
614
+ moof = moof[:i + 12] + i32(len(moof) + 8) + moof[i + 16:]
615
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + \
616
+ moof + box(b"mdat", enc) + make_moov()
617
+ out = sp.proc(input=data, key=KEY_HEX, strict=True)
618
+ assert out == sp.proc(input=data, key=KEY_HEX)
619
+ assert sp.proc(input=out) == out
620
+ with pytest.raises(DecrypTuneError) as e:
621
+ sp.proc(input=data, key=FAKE_KEY_HEX, strict=True)
622
+ assert e.value.code == 8
623
+
624
+
625
+ def test_shared_mdat_not_decrypted(sp):
626
+ # moof,moof,mdat: the payload is not adjacent to the first fragment, so no
627
+ # plan can be trusted on it — both fragments pass through undecrypted
628
+ # instead of the second fragment's plan mis-decrypting the shared mdat
629
+ def frag(seq, iv):
630
+ moof = make_moof(seq, [make_tfhd(), make_trun([64], 0), make_senc([iv])])
631
+ i = moof.find(b"trun")
632
+ return moof[:i + 12] + i32(len(moof) + 8) + moof[i + 16:]
633
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + \
634
+ frag(1, bytes([1, 2, 3, 4, 5, 6, 7, 8])) + \
635
+ frag(2, bytes([9, 8, 7, 6, 5, 4, 3, 2])) + \
636
+ box(b"mdat", ctr_crypt(KEY, bytes([9, 8, 7, 6, 5, 4, 3, 2]), bytes([0x22]) * 64)) + \
637
+ make_moov()
638
+ assert sp.proc(input=data, key=KEY_HEX, strict=True) == sp.proc(input=data)
639
+
640
+
641
+ def test_subsample_encrypted_passthrough(sp):
642
+ # real subsample entries (flags 0x2, non-empty tables) mean partially clear
643
+ # samples — full-sample decryption would corrupt the clear bytes, so the
644
+ # fragment passes through instead of decrypting wrongly
645
+ iv = bytes([5, 5, 5, 5, 5, 5, 5, 5])
646
+ senc = box(b"senc", u32(0x00000002) + u32(1) + iv +
647
+ u16(1) + u16(2) + u32(6)) # one entry: 2 clear + 6 protected
648
+ moof = make_moof(1, [make_tfhd(), make_trun([64], 0)])
649
+ i = moof.find(b"trun")
650
+ moof = moof[:i + 12] + i32(len(moof) + 8) + moof[i + 16:]
651
+ traf_pos = moof.find(make_senc([iv]))
652
+ moof = moof[:traf_pos] + senc + moof[traf_pos + len(make_senc([iv])):]
653
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + \
654
+ moof + box(b"mdat", ctr_crypt(KEY, iv, bytes([0x33]) * 64)) + make_moov()
655
+ assert sp.proc(input=data, key=KEY_HEX, strict=True) == sp.proc(input=data)
656
+
657
+
519
658
  def test_fuzz_no_native_panics(sp, sample):
520
659
  data, _ = sample
521
660
  random.seed(42)
@@ -685,6 +824,18 @@ def test_cover_passthrough(sp, sample):
685
824
  assert cov[16:struct.unpack_from(">I", cov, 0)[0]] == tiny
686
825
 
687
826
 
827
+ def test_cover_odd_height_420(sp, sample):
828
+ # 1100x1099 4:2:0 — the fancy h2v2 upsampler once wrote one row past the
829
+ # output buffer for odd heights (the most common JPEG layout) and panicked
830
+ data, _ = sample
831
+ tagged = sp.proc(input=data, key=KEY_HEX, meta=TuneMeta(cover=os.path.join(FIXTURES, "odd420.jpg")))
832
+ cov = ilst_items(tagged)[b"covr"][0]
833
+ csize = struct.unpack_from(">I", cov, 0)[0]
834
+ assert struct.unpack_from(">I", cov, 8)[0] == 13
835
+ w, h = jpeg_dims(cov[16:csize])
836
+ assert max(w, h) <= 1000 and min(w, h) == 999
837
+
838
+
688
839
  def test_cover_bytearray(sp, sample):
689
840
  data, _ = sample
690
841
  with open(os.path.join(FIXTURES, "tiny.jpg"), "rb") as f:
File without changes
File without changes
File without changes
File without changes
File without changes