decryptune 1.1.6__tar.gz → 1.1.8__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 (26) hide show
  1. {decryptune-1.1.6 → decryptune-1.1.8}/Cargo.lock +3 -3
  2. {decryptune-1.1.6 → decryptune-1.1.8}/Cargo.toml +1 -1
  3. {decryptune-1.1.6 → decryptune-1.1.8}/PKG-INFO +6 -4
  4. {decryptune-1.1.6 → decryptune-1.1.8}/README.md +5 -3
  5. {decryptune-1.1.6 → decryptune-1.1.8}/python/decryptune/__init__.py +14 -6
  6. decryptune-1.1.8/src/defrag.rs +347 -0
  7. {decryptune-1.1.6 → decryptune-1.1.8}/src/error.rs +4 -2
  8. {decryptune-1.1.6 → decryptune-1.1.8}/src/lib.rs +66 -16
  9. {decryptune-1.1.6 → decryptune-1.1.8}/src/process.rs +30 -5
  10. {decryptune-1.1.6 → decryptune-1.1.8}/tests/test_decryptune.py +241 -15
  11. {decryptune-1.1.6 → decryptune-1.1.8}/.gitattributes +0 -0
  12. {decryptune-1.1.6 → decryptune-1.1.8}/.github/workflows/build.yml +0 -0
  13. {decryptune-1.1.6 → decryptune-1.1.8}/.gitignore +0 -0
  14. {decryptune-1.1.6 → decryptune-1.1.8}/LICENSE +0 -0
  15. {decryptune-1.1.6 → decryptune-1.1.8}/pyproject.toml +0 -0
  16. {decryptune-1.1.6 → decryptune-1.1.8}/src/boxes.rs +0 -0
  17. {decryptune-1.1.6 → decryptune-1.1.8}/src/cover.rs +0 -0
  18. {decryptune-1.1.6 → decryptune-1.1.8}/src/input.rs +0 -0
  19. {decryptune-1.1.6 → decryptune-1.1.8}/src/jpeg/decode.rs +0 -0
  20. {decryptune-1.1.6 → decryptune-1.1.8}/src/jpeg/encode.rs +0 -0
  21. {decryptune-1.1.6 → decryptune-1.1.8}/src/jpeg/mod.rs +0 -0
  22. {decryptune-1.1.6 → decryptune-1.1.8}/src/jpeg/tests.rs +0 -0
  23. {decryptune-1.1.6 → decryptune-1.1.8}/src/meta.rs +0 -0
  24. {decryptune-1.1.6 → decryptune-1.1.8}/tests/fixtures/big.jpg +0 -0
  25. {decryptune-1.1.6 → decryptune-1.1.8}/tests/fixtures/odd420.jpg +0 -0
  26. {decryptune-1.1.6 → decryptune-1.1.8}/tests/fixtures/tiny.jpg +0 -0
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.6"
71
+ version = "1.1.8"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -289,9 +289,9 @@ dependencies = [
289
289
 
290
290
  [[package]]
291
291
  name = "target-lexicon"
292
- version = "0.13.5"
292
+ version = "0.13.6"
293
293
  source = "registry+https://github.com/rust-lang/crates.io-index"
294
- checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
294
+ checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da"
295
295
 
296
296
  [[package]]
297
297
  name = "tokio"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.6"
3
+ version = "1.1.8"
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.6
3
+ Version: 1.1.8
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -47,8 +47,10 @@ sp.proc(
47
47
  # date=..., album=..., genre=..., lyrics=..., composer=...,
48
48
  # track=..., track_total=..., disc=..., disc_total=...
49
49
  ),
50
- strict=True # raise (code 8, per-fragment chi² evidence) when a fragment
51
- ) # decrypts to statistical noise — a wrong/fake key
50
+ strict=True, # raise (code 8, per-fragment chi² evidence) when a fragment
51
+ # decrypts to statistical noise — a wrong/fake key
52
+ classic=True # rewrite a fragmented (fMP4) result as a regular MP4 —
53
+ ) # real sample tables, one mdat; audio is copied, not re-encoded
52
54
 
53
55
  # async twin — same options, same result:
54
56
  out_bytes = await sp.aproc(...)
@@ -60,7 +62,7 @@ Rules that hold for both `proc` and `aproc`:
60
62
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
61
63
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
62
64
  - 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–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).
65
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–15) 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) · `15` classic rewrite unsupported.
64
66
 
65
67
  ## Benchmark
66
68
 
@@ -30,8 +30,10 @@ sp.proc(
30
30
  # date=..., album=..., genre=..., lyrics=..., composer=...,
31
31
  # track=..., track_total=..., disc=..., disc_total=...
32
32
  ),
33
- strict=True # raise (code 8, per-fragment chi² evidence) when a fragment
34
- ) # decrypts to statistical noise — a wrong/fake key
33
+ strict=True, # raise (code 8, per-fragment chi² evidence) when a fragment
34
+ # decrypts to statistical noise — a wrong/fake key
35
+ classic=True # rewrite a fragmented (fMP4) result as a regular MP4 —
36
+ ) # real sample tables, one mdat; audio is copied, not re-encoded
35
37
 
36
38
  # async twin — same options, same result:
37
39
  out_bytes = await sp.aproc(...)
@@ -43,7 +45,7 @@ Rules that hold for both `proc` and `aproc`:
43
45
  - `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
44
46
  - `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
45
47
  - 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–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).
48
+ - Any problem raises `DecrypTuneError` with a stable numeric code (1–15) 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) · `15` classic rewrite unsupported.
47
49
 
48
50
  ## Benchmark
49
51
 
@@ -39,7 +39,7 @@ except ImportError as _imp_err:
39
39
  raise ImportError(f"staged extension {_lib} failed to load: {_load_err}") from _load_err
40
40
  sys.modules[f"{__name__}.decryptune"] = _native # register like a real submodule import
41
41
 
42
- __version__ = "1.1.6"
42
+ __version__ = "1.1.8"
43
43
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
44
44
 
45
45
 
@@ -63,7 +63,7 @@ class DecrypTuneError(Exception):
63
63
  # all error messages are authored by the native core (error.rs) — this wrapper
64
64
  # relays [code] + message; anything outside the known code range (or without a
65
65
  # [N] prefix) is not a native error and propagates unchanged
66
- _NATIVE_CODES: frozenset[int] = frozenset(range(1, 15)) # 14 = CoverTooLarge is the last
66
+ _NATIVE_CODES: frozenset[int] = frozenset(range(1, 16)) # 15 = ClassicUnsupported is the last (error.rs)
67
67
 
68
68
 
69
69
  def _to_err(exc: Exception) -> DecrypTuneError | None:
@@ -101,7 +101,8 @@ class DecrypTune:
101
101
  key: str | None = None,
102
102
  kid: str | None = None,
103
103
  meta: "TuneMeta | None" = None,
104
- strict: bool = False
104
+ strict: bool = False,
105
+ classic: bool = False
105
106
  ) -> bytes | None:
106
107
  """Decrypt, fix, write metadata, and optionally guard — one pass.
107
108
 
@@ -117,12 +118,18 @@ class DecrypTune:
117
118
  (JPEG/PNG); oversized JPEGs are downscaled to ≤1000px.
118
119
  - strict: when True (and key given), a fragment that decrypts to
119
120
  statistical noise (fake/rotated key) raises error 8.
121
+ - classic: rewrite a fragmented (fMP4) result as a regular MP4 —
122
+ real sample tables (stts/stsc/stsz/stco), one mdat, no moof/
123
+ sidx/mvex; durations and edit lists are fixed. Audio data is
124
+ copied, never re-encoded. A file without fragments passes
125
+ through unchanged. Raises error 15 when the layout cannot be
126
+ expressed as a classic MP4.
120
127
 
121
128
  Returns None when out is a path, bytes when out is None.
122
129
  All parameters are keyword-only.
123
130
  """
124
131
  try:
125
- return self._lib.proc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
132
+ return self._lib.proc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict, classic=classic)
126
133
  except Exception as e:
127
134
  if (err := _to_err(e)) is not None:
128
135
  raise err from None
@@ -136,7 +143,8 @@ class DecrypTune:
136
143
  key: str | None = None,
137
144
  kid: str | None = None,
138
145
  meta: "TuneMeta | None" = None,
139
- strict: bool = False
146
+ strict: bool = False,
147
+ classic: bool = False
140
148
  ) -> bytes | None:
141
149
  """Async proc — same contract, keyword-only parameters.
142
150
 
@@ -147,7 +155,7 @@ class DecrypTune:
147
155
  blocks the event loop.
148
156
  """
149
157
  try:
150
- return await self._lib.aproc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
158
+ return await self._lib.aproc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict, classic=classic)
151
159
  except Exception as e:
152
160
  if (err := _to_err(e)) is not None:
153
161
  raise err from None
@@ -0,0 +1,347 @@
1
+ // Rewrite a fragmented MP4 (init segment + moof/mdat pairs) as a classic MP4:
2
+ // the moov's real sample tables (stts/stsc/stsz/stco) are rebuilt from the
3
+ // fragments, mvex/moof/sidx disappear, and all sample bytes land in one mdat.
4
+ // Audio data is byte-copied — never re-encoded. Scope: single audio track,
5
+ // which is the entire decryptune surface. Ported from a trusted HLS
6
+ // postprocessor and hardened for hostile input: every field read is bounded
7
+ // by its own box, sample data must lie inside the file, and the output is
8
+ // checked against the 32-bit chunk-offset limit before anything is written.
9
+
10
+ use crate::boxes::{header_len, parse, write_header, Box, MAX_BOXES};
11
+ use crate::process::{trex_defaults, MAX_TREE_DEPTH};
12
+ use crate::Err;
13
+
14
+ // containers the moov rebuild recurses into (mvex is dropped outright)
15
+ const CONTAINERS: [&[u8; 4]; 6] = [b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"];
16
+ const MAX_SAMPLES: usize = 1 << 22;
17
+
18
+ // one contiguous sample-data run referenced by a trun — one output chunk
19
+ struct ChunkRun {
20
+ offset : usize, // byte position inside the source buffer
21
+ len : usize,
22
+ samples: usize
23
+ }
24
+
25
+ // rebuilt sample tables, in stbl append order
26
+ struct Tables {
27
+ stts: Vec<u8>,
28
+ stsc: Vec<u8>,
29
+ stsz: Vec<u8>,
30
+ stco: Vec<u8>
31
+ }
32
+
33
+ fn be32(data: &[u8], pos: usize, end: usize) -> Result<u32, Err> {
34
+ if pos + 4 > end { return Err(Err::ClassicUnsupported); }
35
+ Ok(u32::from_be_bytes(data[pos..pos + 4].try_into().unwrap()))
36
+ }
37
+
38
+ fn timescale(payload: &[u8]) -> Result<u32, Err> {
39
+ // mvhd/mdhd share the prefix: ver/flags(4) creation(v0:4/v1:8)
40
+ // modification(v0:4/v1:8) timescale(4)
41
+ let version: u8 = *payload.first().ok_or(Err::ClassicUnsupported)?;
42
+ let off: usize = if version == 1 { 20 } else { 12 };
43
+ if off + 4 > payload.len() { return Err(Err::ClassicUnsupported); }
44
+ Ok(u32::from_be_bytes(payload[off..off + 4].try_into().unwrap()))
45
+ }
46
+
47
+ // rewrite the duration field of mvhd/mdhd (16/24) or tkhd (20/28); v0 values
48
+ // clamp to u32::MAX like every writer does — audio never gets near it
49
+ fn patch_duration(data: &[u8], b: &Box, off_v0: usize, off_v1: usize, value: u64) -> Result<Vec<u8>, Err> {
50
+ let payload: &[u8] = &data[b.content_start..b.end];
51
+ let version: u8 = *payload.first().ok_or(Err::ClassicUnsupported)?;
52
+ let (off, wide): (usize, bool) = if version == 1 { (off_v1, true) } else { (off_v0, false) };
53
+ let need: usize = off + if wide { 8 } else { 4 };
54
+ if need > payload.len() { return Err(Err::ClassicUnsupported); }
55
+ let mut out: Vec<u8> = payload.to_vec();
56
+ if wide {
57
+ out[off..off + 8].copy_from_slice(&value.to_be_bytes());
58
+ } else {
59
+ out[off..off + 4].copy_from_slice(&(value.min(u64::from(u32::MAX)) as u32).to_be_bytes());
60
+ }
61
+ Ok(out)
62
+ }
63
+
64
+ // fill a zero segment duration (normal for fragmented files) in a one-entry
65
+ // edit list — a zero elst duration makes players clip the track to nothing
66
+ fn fix_elst(data: &[u8], b: &Box, movie_duration: u64) -> Result<Vec<u8>, Err> {
67
+ let payload: &[u8] = &data[b.content_start..b.end];
68
+ if payload.len() < 8 { return Err(Err::ClassicUnsupported); }
69
+ let mut out: Vec<u8> = payload.to_vec();
70
+ let version: u8 = out[0];
71
+ let count: u32 = u32::from_be_bytes(out[4..8].try_into().unwrap());
72
+ if count != 1 { return Ok(out); }
73
+ if version == 1 {
74
+ if out.len() >= 16 && out[8..16] == [0u8; 8] {
75
+ out[8..16].copy_from_slice(&movie_duration.to_be_bytes());
76
+ }
77
+ } else if out.len() >= 12 && out[8..12] == [0u8; 4] {
78
+ out[8..12].copy_from_slice(&(movie_duration.min(u64::from(u32::MAX)) as u32).to_be_bytes());
79
+ }
80
+ Ok(out)
81
+ }
82
+
83
+ fn make_tables(chunks: &[ChunkRun], offsets: &[u32], durations: &[u32], sizes: &[u32]) -> Tables {
84
+ // stts: run-length encode the per-sample durations
85
+ let mut runs: Vec<(u32, u32)> = Vec::new();
86
+ for d in durations {
87
+ match runs.last_mut() {
88
+ Some(r) if r.1 == *d => r.0 += 1,
89
+ _ => runs.push((1, *d))
90
+ }
91
+ }
92
+ let mut stts: Vec<u8> = Vec::with_capacity(8 + runs.len() * 8);
93
+ stts.extend_from_slice(&0u32.to_be_bytes());
94
+ stts.extend_from_slice(&(runs.len() as u32).to_be_bytes());
95
+ for (n, d) in &runs {
96
+ stts.extend_from_slice(&n.to_be_bytes());
97
+ stts.extend_from_slice(&d.to_be_bytes());
98
+ }
99
+
100
+ // stsc: a new entry only where the per-chunk sample count changes
101
+ let mut stsc_entries: Vec<(u32, u32)> = Vec::new(); // (first_chunk, samples_per_chunk)
102
+ for (i, c) in chunks.iter().enumerate() {
103
+ let n: u32 = (i + 1) as u32;
104
+ if stsc_entries.last().map(|e| e.1) != Some(c.samples as u32) {
105
+ stsc_entries.push((n, c.samples as u32));
106
+ }
107
+ }
108
+ let mut stsc: Vec<u8> = Vec::with_capacity(8 + stsc_entries.len() * 12);
109
+ stsc.extend_from_slice(&0u32.to_be_bytes());
110
+ stsc.extend_from_slice(&(stsc_entries.len() as u32).to_be_bytes());
111
+ for (first, count) in &stsc_entries {
112
+ stsc.extend_from_slice(&first.to_be_bytes());
113
+ stsc.extend_from_slice(&count.to_be_bytes());
114
+ stsc.extend_from_slice(&1u32.to_be_bytes()); // sample_description_index
115
+ }
116
+
117
+ // stsz: a uniform table is 12 bytes instead of one entry per sample
118
+ let uniform: bool = sizes.iter().all(|s| *s == sizes[0]);
119
+ let mut stsz: Vec<u8> = Vec::with_capacity(12 + if uniform { 0 } else { sizes.len() * 4 });
120
+ stsz.extend_from_slice(&0u32.to_be_bytes());
121
+ stsz.extend_from_slice(&if uniform { sizes[0] } else { 0 }.to_be_bytes());
122
+ stsz.extend_from_slice(&(sizes.len() as u32).to_be_bytes());
123
+ if !uniform {
124
+ for s in sizes { stsz.extend_from_slice(&s.to_be_bytes()); }
125
+ }
126
+
127
+ let mut stco: Vec<u8> = Vec::with_capacity(8 + offsets.len() * 4);
128
+ stco.extend_from_slice(&0u32.to_be_bytes());
129
+ stco.extend_from_slice(&(offsets.len() as u32).to_be_bytes());
130
+ for o in offsets { stco.extend_from_slice(&o.to_be_bytes()); }
131
+
132
+ Tables { stts, stsc, stsz, stco }
133
+ }
134
+
135
+ // recursive moov rebuild — the only structural change is that mvex vanishes
136
+ // and the sample tables inside stbl are appended fresh. Hostile container
137
+ // nesting is depth-capped like the decrypt path's rebuild_container: without
138
+ // the cap, nested boxes recurse to a stack overflow (uncatchable)
139
+ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duration: u64, media_duration: u64, depth: usize) -> Result<Vec<u8>, Err> {
140
+ if depth > MAX_TREE_DEPTH { return Err(Err::ClassicUnsupported); }
141
+ let children: Vec<Box> = parse(data, start, end);
142
+ if children.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
143
+ let mut out: Vec<u8> = Vec::new();
144
+ for b in &children {
145
+ match &b.typ {
146
+ b"mvex" | b"stts" | b"stsc" | b"stsz" | b"stco" | b"co64" | b"stz2" => {} // dropped — fragmentation markers or replaced tables
147
+ b"mvhd" => {
148
+ let body: Vec<u8> = patch_duration(data, b, 16, 24, movie_duration)?;
149
+ write_header(&mut out, b"mvhd", body.len());
150
+ out.extend_from_slice(&body);
151
+ }
152
+ b"mdhd" => {
153
+ let body: Vec<u8> = patch_duration(data, b, 16, 24, media_duration)?;
154
+ write_header(&mut out, b"mdhd", body.len());
155
+ out.extend_from_slice(&body);
156
+ }
157
+ b"tkhd" => {
158
+ let body: Vec<u8> = patch_duration(data, b, 20, 28, movie_duration)?;
159
+ write_header(&mut out, b"tkhd", body.len());
160
+ out.extend_from_slice(&body);
161
+ }
162
+ b"elst" => {
163
+ let body: Vec<u8> = fix_elst(data, b, movie_duration)?;
164
+ write_header(&mut out, b"elst", body.len());
165
+ out.extend_from_slice(&body);
166
+ }
167
+ b"stbl" => {
168
+ let mut inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration, depth + 1)?;
169
+ // the Tables fields hold box BODIES — wrap each in its header
170
+ write_header(&mut inner, b"stts", tables.stts.len());
171
+ inner.extend_from_slice(&tables.stts);
172
+ write_header(&mut inner, b"stsc", tables.stsc.len());
173
+ inner.extend_from_slice(&tables.stsc);
174
+ write_header(&mut inner, b"stsz", tables.stsz.len());
175
+ inner.extend_from_slice(&tables.stsz);
176
+ write_header(&mut inner, b"stco", tables.stco.len());
177
+ inner.extend_from_slice(&tables.stco);
178
+ write_header(&mut out, b"stbl", inner.len());
179
+ out.extend_from_slice(&inner);
180
+ }
181
+ typ if CONTAINERS.iter().any(|c| c == &typ) => {
182
+ let inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration, depth + 1)?;
183
+ write_header(&mut out, typ, inner.len());
184
+ out.extend_from_slice(&inner);
185
+ }
186
+ _ => out.extend_from_slice(&data[b.start..b.end])
187
+ }
188
+ }
189
+ Ok(out)
190
+ }
191
+
192
+ /// Rewrite fragmented MP4 bytes as a classic MP4. `None` means the input has
193
+ /// no moof boxes — already classic — and no rewrite buffer is needed.
194
+ pub(crate) fn defragment(data: &[u8]) -> Result<Option<Vec<u8>>, Err> {
195
+ let top: Vec<Box> = parse(data, 0, data.len());
196
+ if top.is_empty() || top.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
197
+ if !top.iter().any(|b| b.is(b"moof")) { return Ok(None); }
198
+ let moov: &Box = top.iter().find(|b| b.is(b"moov")).ok_or(Err::ClassicUnsupported)?;
199
+ if top.iter().filter(|b| b.is(b"moov")).count() != 1 {
200
+ return Err(Err::ClassicUnsupported); // duplicate moovs would corrupt the offset math
201
+ }
202
+ let children: Vec<Box> = parse(data, moov.content_start, moov.end);
203
+ if children.len() >= MAX_BOXES || children.iter().filter(|b| b.is(b"trak")).count() != 1 {
204
+ return Err(Err::ClassicUnsupported);
205
+ }
206
+ let mvhd: &Box = children.iter().find(|b| b.is(b"mvhd")).ok_or(Err::ClassicUnsupported)?;
207
+ let trak: &Box = children.iter().find(|b| b.is(b"trak")).ok_or(Err::ClassicUnsupported)?;
208
+ let trak_children: Vec<Box> = parse(data, trak.content_start, trak.end);
209
+ let mdia: &Box = trak_children.iter().find(|b| b.is(b"mdia")).ok_or(Err::ClassicUnsupported)?;
210
+ let mdia_children: Vec<Box> = parse(data, mdia.content_start, mdia.end);
211
+ let mdhd: &Box = mdia_children.iter().find(|b| b.is(b"mdhd")).ok_or(Err::ClassicUnsupported)?;
212
+ let movie_ts: u32 = timescale(&data[mvhd.content_start..mvhd.end])?;
213
+ let media_ts: u32 = timescale(&data[mdhd.content_start..mdhd.end])?;
214
+ if movie_ts == 0 || media_ts == 0 { return Err(Err::ClassicUnsupported); }
215
+
216
+ // walk the fragments: sample sizes, durations, and where the bytes are.
217
+ // base_data_offset defaults to the moof start; sample defaults cascade
218
+ // trex → tfhd → trun entry, exactly like the decrypt planner
219
+ let trex: Option<(u32, u32)> = trex_defaults(data, &top);
220
+ let (mut sizes, mut durations): (Vec<u32>, Vec<u32>) = (Vec::new(), Vec::new());
221
+ let mut chunks: Vec<ChunkRun> = Vec::new();
222
+ for moof in top.iter().filter(|b| b.is(b"moof")) {
223
+ let moof_children: Vec<Box> = parse(data, moof.content_start, moof.end);
224
+ // a trun without data_offset continues the PREVIOUS run's data, chaining
225
+ // across trafs of the same moof — so `next` lives at the moof level
226
+ let mut next: Option<usize> = None;
227
+ for traf in &moof_children {
228
+ if !traf.is(b"traf") { continue; }
229
+ let subs: Vec<Box> = parse(data, traf.content_start, traf.end);
230
+ let mut base: usize = moof.start;
231
+ let mut dur: u32 = trex.map(|(d, _)| d).unwrap_or(0);
232
+ let mut size: u32 = trex.map(|(_, s)| s).unwrap_or(0);
233
+ for sub in &subs {
234
+ match &sub.typ {
235
+ b"tfhd" => {
236
+ let flags: u32 = be32(data, sub.content_start, sub.end)? & 0xFFFFFF;
237
+ if sub.content_start + 8 > sub.end { return Err(Err::ClassicUnsupported); }
238
+ let mut q: usize = sub.content_start + 8; // version/flags + track_ID
239
+ if flags & 0x1 != 0 { // base_data_offset (absolute)
240
+ if q + 8 > sub.end { return Err(Err::ClassicUnsupported); }
241
+ let b64: u64 = u64::from_be_bytes(data[q..q + 8].try_into().unwrap());
242
+ if b64 > data.len() as u64 { return Err(Err::ClassicUnsupported); }
243
+ base = b64 as usize;
244
+ q += 8;
245
+ }
246
+ if flags & 0x2 != 0 { q += 4; } // sample_description_index — unused
247
+ if flags & 0x8 != 0 { dur = be32(data, q, sub.end)?; q += 4; }
248
+ if flags & 0x10 != 0 { size = be32(data, q, sub.end)?; q += 4; }
249
+ }
250
+ b"trun" => {
251
+ let flags: u32 = be32(data, sub.content_start, sub.end)? & 0xFFFFFF;
252
+ let count: usize = be32(data, sub.content_start + 4, sub.end)? as usize;
253
+ if count > MAX_SAMPLES { return Err(Err::ClassicUnsupported); }
254
+ let mut q: usize = sub.content_start + 8;
255
+ let data_start: usize;
256
+ if flags & 0x1 != 0 { // data_offset, signed, relative to base
257
+ let off: i32 = be32(data, q, sub.end)? as i32;
258
+ q += 4;
259
+ let abs: i64 = base as i64 + off as i64;
260
+ if abs < 0 || abs > data.len() as i64 { return Err(Err::ClassicUnsupported); }
261
+ data_start = abs as usize;
262
+ } else if let Some(n) = next {
263
+ data_start = n; // chained after the previous run in this moof
264
+ } else {
265
+ return Err(Err::ClassicUnsupported);
266
+ }
267
+ if flags & 0x4 != 0 { q += 4; } // first_sample_flags — unused
268
+ let mut run_len: usize = 0;
269
+ for _ in 0..count {
270
+ let mut d: u32 = dur;
271
+ let mut s: u32 = size;
272
+ if flags & 0x100 != 0 { d = be32(data, q, sub.end)?; q += 4; }
273
+ if flags & 0x200 != 0 { s = be32(data, q, sub.end)?; q += 4; }
274
+ if flags & 0x400 != 0 { q += 4; } // sample_flags — unused
275
+ if flags & 0x800 != 0 { q += 4; } // composition offsets — unused
276
+ if s == 0 { return Err(Err::ClassicUnsupported); } // a sample without bytes cannot be placed
277
+ sizes.push(s);
278
+ durations.push(d);
279
+ run_len += s as usize;
280
+ }
281
+ if data_start + run_len > data.len() { return Err(Err::ClassicUnsupported); }
282
+ if count > 0 {
283
+ chunks.push(ChunkRun { offset: data_start, len: run_len, samples: count });
284
+ next = Some(data_start + run_len);
285
+ }
286
+ }
287
+ _ => {}
288
+ }
289
+ }
290
+ }
291
+ }
292
+ if sizes.is_empty() { return Err(Err::ClassicUnsupported); }
293
+ let media_duration: u64 = durations.iter().map(|d| u64::from(*d)).sum();
294
+ if media_duration == 0 { return Err(Err::ClassicUnsupported); }
295
+ // hostile timescales/durations can overflow the u64 product — the u128
296
+ // intermediate keeps it exact (the result itself always fits: it is at
297
+ // most media_duration, which came out of a u64 sum)
298
+ let movie_duration: u64 =
299
+ ((media_duration as u128 * u128::from(movie_ts)) / u128::from(media_ts)) as u64;
300
+
301
+ // moov's size does not depend on the offset VALUES — size it with dummy
302
+ // offsets first, then place the data and rebuild with the real ones
303
+ let zeros: Vec<u32> = vec![0u32; chunks.len()];
304
+ let dummy: Tables = make_tables(&chunks, &zeros, &durations, &sizes);
305
+ let placeholder: Vec<u8> = rebuild(data, moov.content_start, moov.end, &dummy, movie_duration, media_duration, 0)?;
306
+ let others_len: usize = top.iter()
307
+ .filter(|b| !matches!(&b.typ, b"moof" | b"mdat" | b"sidx" | b"moov"))
308
+ .map(|b| b.end - b.start)
309
+ .sum();
310
+ let data_start: usize = others_len + header_len(placeholder.len()) + placeholder.len() + 8; // moov box + mdat header
311
+ let total_audio: usize = chunks.iter().map(|c| c.len).sum();
312
+ // legit sample bytes are a subset of the input (disjoint runs), so the
313
+ // total can never exceed it — overlapping runs are malformed, and the cap
314
+ // also bounds the output allocation against hostile amplification
315
+ if total_audio > data.len() { return Err(Err::ClassicUnsupported); }
316
+ if data_start + total_audio > u32::MAX as usize {
317
+ return Err(Err::ClassicUnsupported); // stco holds u32 offsets only (audio never gets there)
318
+ }
319
+ let mut offsets: Vec<u32> = Vec::with_capacity(chunks.len());
320
+ let mut pos: usize = data_start;
321
+ for c in &chunks {
322
+ offsets.push(pos as u32);
323
+ pos += c.len;
324
+ }
325
+ let tables: Tables = make_tables(&chunks, &offsets, &durations, &sizes);
326
+ let new_moov: Vec<u8> = rebuild(data, moov.content_start, moov.end, &tables, movie_duration, media_duration, 0)?;
327
+ if new_moov.len() != placeholder.len() { return Err(Err::ClassicUnsupported); } // cannot happen — table sizes are value-independent
328
+
329
+ // unknown top-level boxes (free, top-level meta…) are kept verbatim;
330
+ // moof/mdat/sidx fold into the tables and the single output mdat
331
+ let mut out: Vec<u8> = Vec::with_capacity(data_start + total_audio);
332
+ for b in &top {
333
+ match &b.typ {
334
+ b"moof" | b"mdat" | b"sidx" => {}
335
+ b"moov" => {
336
+ write_header(&mut out, b"moov", new_moov.len());
337
+ out.extend_from_slice(&new_moov);
338
+ }
339
+ _ => out.extend_from_slice(&data[b.start..b.end])
340
+ }
341
+ }
342
+ write_header(&mut out, b"mdat", total_audio);
343
+ for c in &chunks {
344
+ out.extend_from_slice(&data[c.offset..c.offset + c.len]);
345
+ }
346
+ Ok(Some(out))
347
+ }
@@ -20,7 +20,8 @@ pub(crate) enum Err {
20
20
  MetaNeedsFragmented = 11,
21
21
  BadCover = 12,
22
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
+ CoverTooLarge = 14, // additive: an absurd cover must not flow into the ilst whole
24
+ ClassicUnsupported = 15 // additive: a fragmented layout the classic rewrite cannot express
24
25
  }
25
26
 
26
27
  impl Err {
@@ -39,7 +40,8 @@ impl Err {
39
40
  Err::BadOutput => "invalid out: expected a path or None",
40
41
  Err::MetaNeedsFragmented => "metadata write requires a fragmented file (non-empty chunk offsets)",
41
42
  Err::BadCover => "unsupported cover format: expected JPEG or PNG",
42
- Err::CoverTooLarge => "cover too large (max 32 MB)"
43
+ Err::CoverTooLarge => "cover too large (max 32 MB)",
44
+ Err::ClassicUnsupported => "cannot rewrite as a classic mp4 (unsupported or malformed fragmented layout)"
43
45
  }
44
46
  }
45
47
  }
@@ -1,5 +1,6 @@
1
1
  mod boxes;
2
2
  mod cover;
3
+ mod defrag;
3
4
  mod error;
4
5
  mod input;
5
6
  mod jpeg;
@@ -173,19 +174,21 @@ impl TuneMeta {
173
174
  }
174
175
 
175
176
  fn parse_args(
176
- py : Python<'_>,
177
- input: &Bound<'_, PyAny>,
178
- out : Option<&Bound<'_, PyAny>>,
179
- key : Option<&str>,
180
- kid : Option<&str>,
181
- meta : Option<&TuneMeta>
177
+ py : Python<'_>,
178
+ input : &Bound<'_, PyAny>,
179
+ out : Option<&Bound<'_, PyAny>>,
180
+ key : Option<&str>,
181
+ kid : Option<&str>,
182
+ meta : Option<&TuneMeta>,
183
+ classic: bool
182
184
  ) -> PyResult<Args> {
183
185
  Ok(Args {
184
186
  input : parse_input(input)?,
185
187
  output : parse_output(out)?,
186
188
  key : key.map(parse_hex16).transpose()?,
187
189
  kid : kid.map(|s| s.to_string()),
188
- core_meta: resolve_meta(py, meta)?
190
+ core_meta: resolve_meta(py, meta)?,
191
+ classic
189
192
  })
190
193
  }
191
194
 
@@ -196,15 +199,16 @@ struct Args {
196
199
  output : Output,
197
200
  key : Option<[u8; 16]>,
198
201
  kid : Option<String>,
199
- core_meta: Option<meta::CoreMeta>
202
+ core_meta: Option<meta::CoreMeta>,
203
+ classic : bool
200
204
  }
201
205
 
202
- type ParsedArgs = (input::Input, Output, Option<[u8; 16]>, Option<String>, Option<meta::CoreMeta>, bool);
206
+ type ParsedArgs = (input::Input, Output, Option<[u8; 16]>, Option<String>, Option<meta::CoreMeta>, bool, bool);
203
207
 
204
208
  impl Args {
205
209
  fn into_parts(self) -> ParsedArgs {
206
210
  let has_key: bool = self.key.is_some();
207
- (self.input, self.output, self.key, self.kid, self.core_meta, has_key)
211
+ (self.input, self.output, self.key, self.kid, self.core_meta, has_key, self.classic)
208
212
  }
209
213
  }
210
214
 
@@ -247,7 +251,8 @@ fn resolve_meta(py: Python<'_>, meta: Option<&TuneMeta>) -> PyResult<Option<meta
247
251
  // Decrypt, fix, write metadata, optionally guard against fake keys — one pass.
248
252
  // All parameters keyword-only; returns None (path out) or bytes (no out).
249
253
  #[pyfunction]
250
- #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false))]
254
+ #[allow(clippy::too_many_arguments)] // the keyword-only signature is the public API
255
+ #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false, classic=false))]
251
256
  fn proc<'py>(
252
257
  py : Python<'py>,
253
258
  input : &Bound<'py, PyAny>,
@@ -255,9 +260,10 @@ fn proc<'py>(
255
260
  key : Option<&str>,
256
261
  kid : Option<&str>,
257
262
  meta : Option<&TuneMeta>,
258
- strict : bool
263
+ strict : bool,
264
+ classic: bool
259
265
  ) -> PyResult<Option<Bound<'py, PyAny>>> {
260
- let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
266
+ let (input, output, key, kid, core_meta, has_key, classic): ParsedArgs = parse_args(py, input, out, key, kid, meta, classic)?.into_parts();
261
267
  let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) =
262
268
  py.detach(move || load_and_measure(input, has_key, kid, core_meta)).map_err(PyErr::from)?;
263
269
  let guarded: bool = strict && key.is_some();
@@ -271,11 +277,32 @@ fn proc<'py>(
271
277
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
272
278
  wipe_key(&mut key);
273
279
  check_strict(&fragments, guarded)?;
280
+ if classic {
281
+ buf = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
282
+ }
274
283
  write_atomic(&p, &buf)?;
275
284
  Ok(())
276
285
  })?;
277
286
  Ok(None)
278
287
  }
288
+ Output::Return if classic => {
289
+ // the classic rewrite changes the length, so the zero-copy path
290
+ // does not apply — build into a Vec, rewrite, then hand out bytes
291
+ let (final_buf, fragments): (Vec<u8>, Vec<process::FragmentStat>) = py.detach(
292
+ move || -> PyResult<(Vec<u8>, Vec<process::FragmentStat>)> {
293
+ let mut key: Option<[u8; 16]> = key;
294
+ let mut buf: Vec<u8> = vec![0u8; len];
295
+ let fragments: Vec<process::FragmentStat> =
296
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
297
+ wipe_key(&mut key);
298
+ let classic_buf: Vec<u8> = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
299
+ Ok((classic_buf, fragments))
300
+ },
301
+ )?;
302
+ check_strict(&fragments, guarded)?;
303
+ let bytes: Bound<'py, PyBytes> = PyBytes::new(py, &final_buf);
304
+ Ok(Some(bytes.into_any()))
305
+ }
279
306
  Output::Return => {
280
307
  // build straight into the freshly allocated Python bytes — no
281
308
  // intermediate copy; the object is exclusively owned until the
@@ -309,7 +336,8 @@ fn join_err(join: tokio::task::JoinError) -> PyErr {
309
336
 
310
337
  // async twin of proc: native coroutine, CPU work off-GIL, async file writes
311
338
  #[pyfunction]
312
- #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false))]
339
+ #[allow(clippy::too_many_arguments)] // the keyword-only signature is the public API
340
+ #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false, classic=false))]
313
341
  fn aproc<'py>(
314
342
  py : Python<'py>,
315
343
  input : &Bound<'py, PyAny>,
@@ -317,9 +345,10 @@ fn aproc<'py>(
317
345
  key : Option<&str>,
318
346
  kid : Option<&str>,
319
347
  meta : Option<&TuneMeta>,
320
- strict : bool
348
+ strict : bool,
349
+ classic: bool
321
350
  ) -> PyResult<Bound<'py, PyAny>> {
322
- let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
351
+ let (input, output, key, kid, core_meta, has_key, classic): ParsedArgs = parse_args(py, input, out, key, kid, meta, classic)?.into_parts();
323
352
  let guarded: bool = strict && key.is_some();
324
353
 
325
354
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
@@ -337,11 +366,32 @@ fn aproc<'py>(
337
366
  process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
338
367
  wipe_key(&mut key);
339
368
  check_strict(&fragments, guarded)?;
369
+ if classic {
370
+ buf = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
371
+ }
340
372
  write_atomic(&p, &buf)?;
341
373
  Ok(())
342
374
  }).await.map_err(join_err)??;
343
375
  Ok(None)
344
376
  }
377
+ Output::Return if classic => {
378
+ // the classic rewrite changes the length — build into a Vec,
379
+ // rewrite, then hand out fresh bytes
380
+ let (final_buf, fragments): (Vec<u8>, Vec<process::FragmentStat>) = tokio::task::spawn_blocking(
381
+ move || -> PyResult<(Vec<u8>, Vec<process::FragmentStat>)> {
382
+ let mut key: Option<[u8; 16]> = key;
383
+ let mut buf: Vec<u8> = vec![0u8; len];
384
+ let fragments: Vec<process::FragmentStat> =
385
+ process::build(data.bytes(), key.as_ref(), strict, core_meta.as_ref(), &mut buf)?;
386
+ wipe_key(&mut key);
387
+ let classic_buf: Vec<u8> = match defrag::defragment(&buf)? { Some(v) => v, None => buf };
388
+ Ok((classic_buf, fragments))
389
+ },
390
+ ).await.map_err(join_err)??;
391
+ check_strict(&fragments, guarded)?;
392
+ let result: Py<PyBytes> = Python::attach(|py| PyBytes::new(py, &final_buf).unbind());
393
+ Ok(Some(result))
394
+ }
345
395
  Output::Return => {
346
396
  // allocate the result under a brief GIL attach, then build off-GIL
347
397
  // straight into its buffer — no intermediate copy. The PyBytes
@@ -10,7 +10,7 @@ use crate::Err;
10
10
  type Aes128Ctr = ctr::Ctr128BE<Aes128>;
11
11
 
12
12
  const CONTAINERS: &[&[u8; 4]] = &[b"moov", b"trak", b"mdia", b"minf", b"stbl"];
13
- const MAX_TREE_DEPTH: usize = 16;
13
+ pub(crate) const MAX_TREE_DEPTH: usize = 16;
14
14
  // chi2 thresholds calibrated on real AAC tracks (structured ~3800..14000 at
15
15
  // 16KB, ~950+ at 4KB; noise is df-bound at ~210..340 for any size above ~1KB,
16
16
  // so 500 splits clean from corrupt with margin on both sides down to 4KB)
@@ -76,6 +76,8 @@ pub fn build(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&Co
76
76
  fn walk(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&CoreMeta>, out: &mut Writer<'_>) -> Result<Vec<Job>, Err> {
77
77
  let boxes: Vec<Box> = parse(data, 0, data.len());
78
78
  if boxes.is_empty() || boxes.len() >= MAX_BOXES { return Err(Err::InvalidMp4); }
79
+ let trex_size: Option<u32> = trex_defaults(data, &boxes)
80
+ .and_then(|(_, sz)| if sz == 0 { None } else { Some(sz) });
79
81
 
80
82
  let mut deltas: Vec<i64> = Vec::new();
81
83
  let mut patches: Vec<(usize, Vec<usize>)> = Vec::new(); // (frag base, sidx word offsets)
@@ -89,7 +91,7 @@ fn walk(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&CoreMet
89
91
  match &b.typ {
90
92
  b"moof" => {
91
93
  flush(out, data, &mut pending);
92
- let plan: Plan = visit_moof(out, data, b);
94
+ let plan: Plan = visit_moof(out, data, b, trex_size);
93
95
  deltas.push((b.end - b.start) as i64 - plan.rebuilt_len as i64);
94
96
  if i + 1 < boxes.len() && boxes[i + 1].is(b"mdat") {
95
97
  if let Some(job) = stage_mdat(out, data, &boxes[i + 1], plan, key, strict, unpaired_moof) {
@@ -156,7 +158,7 @@ fn flush(out: &mut Writer<'_>, data: &[u8], pending: &mut Option<Range<usize>>)
156
158
  if let Some(r) = pending.take() { out.put(&data[r.start..r.end]); }
157
159
  }
158
160
 
159
- fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box) -> Plan {
161
+ fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box, trex_size: Option<u32>) -> Plan {
160
162
  let mut content: Vec<u8> = Vec::new();
161
163
  let mut ivs: Option<Vec<[u8; 16]>> = None;
162
164
  let mut sizes: Vec<u32> = Vec::new();
@@ -172,10 +174,13 @@ fn visit_moof(out: &mut Writer<'_>, data: &[u8], b: &Box) -> Plan {
172
174
  let traf: Vec<Box> = parse(data, child.content_start, child.end);
173
175
 
174
176
  // gather: tfhd default first so trun fallback works in any order
175
- // (a saturated child count means box spam — nothing to decrypt)
177
+ // (a saturated child count means box spam — nothing to decrypt);
178
+ // the mvex/trex file default fills whatever tfhd leaves unset
176
179
  if traf.len() >= MAX_BOXES { oversized = true; }
177
180
  default_size = traf.iter().find(|t| t.is(b"tfhd"))
178
- .and_then(|t| parse_tfhd(data, t.content_start, t.end));
181
+ .and_then(|t| parse_tfhd(data, t.content_start, t.end))
182
+ .filter(|v| *v != 0)
183
+ .or(trex_size);
179
184
  for t in &traf {
180
185
  match &t.typ {
181
186
  b"senc" if ivs.is_none() => {
@@ -525,6 +530,26 @@ fn has_chunk_offsets(children: &[u8], depth: usize) -> bool {
525
530
  false
526
531
  }
527
532
 
533
+ // file-level sample defaults from the first mvex/trex — the ISO 14496-12
534
+ // cascade is trex (file) → tfhd (fragment) → trun (per entry), and CMAF/DASH
535
+ // muxers rely on the trex layer. Scope: the first trex — the fragmented
536
+ // surface here is single-audio-track. 0 means "unspecified" per spec
537
+ pub(crate) fn trex_defaults(data: &[u8], top: &[Box]) -> Option<(u32, u32)> {
538
+ let moov: &Box = top.iter().find(|b| b.is(b"moov"))?;
539
+ for child in parse(data, moov.content_start, moov.end) {
540
+ if !child.is(b"mvex") { continue; }
541
+ for t in parse(data, child.content_start, child.end) {
542
+ if t.is(b"trex") && t.content_start + 20 <= t.end {
543
+ // ver/flags(4) track_ID(4) desc_index(4) duration(4) size(4)
544
+ let d: u32 = u32::from_be_bytes(data[t.content_start + 12..t.content_start + 16].try_into().unwrap());
545
+ let s: u32 = u32::from_be_bytes(data[t.content_start + 16..t.content_start + 20].try_into().unwrap());
546
+ return Some((d, s));
547
+ }
548
+ }
549
+ }
550
+ None
551
+ }
552
+
528
553
  // default_sample_size from tfhd (flag 0x10), honoring preceding optional fields;
529
554
  // every read stays inside the tfhd box — never spills into a sibling box
530
555
  fn parse_tfhd(data: &[u8], start: usize, end: usize) -> Option<u32> {
@@ -58,18 +58,28 @@ def make_senc(ivs):
58
58
  return full_box(b"senc", 0, 0, body)
59
59
 
60
60
 
61
- def make_trun(sizes, data_offset, with_sizes=True):
62
- flags = 0x1 | (0x200 if with_sizes else 0)
63
- body = u32(len(sizes)) + i32(data_offset)
64
- if with_sizes:
65
- body += b"".join(u32(s) for s in sizes)
61
+ def make_trun(sizes, data_offset, with_sizes=True, durations=None, with_offset=True):
62
+ flags = (0x1 if with_offset else 0) | (0x200 if with_sizes else 0) | (0x100 if durations else 0)
63
+ body = u32(len(sizes))
64
+ if with_offset:
65
+ body += i32(data_offset)
66
+ for i in range(len(sizes)):
67
+ if durations:
68
+ body += u32(durations[i])
69
+ if with_sizes:
70
+ body += u32(sizes[i])
66
71
  return full_box(b"trun", 0, flags, body)
67
72
 
68
73
 
69
- def make_tfhd(default_size=None):
70
- if default_size is None:
71
- return full_box(b"tfhd", 0, 0, u32(1)) # track_ID only
72
- return full_box(b"tfhd", 0, 0x10, u32(1) + u32(default_size)) # + default_sample_size
74
+ def make_tfhd(default_size=None, default_duration=None):
75
+ payload, flags = u32(1), 0
76
+ if default_duration is not None: # 0x8 precedes 0x10 per spec
77
+ flags |= 0x8
78
+ payload += u32(default_duration)
79
+ if default_size is not None:
80
+ flags |= 0x10
81
+ payload += u32(default_size)
82
+ return full_box(b"tfhd", 0, flags, payload)
73
83
 
74
84
 
75
85
  def make_saiz(count):
@@ -86,6 +96,17 @@ def make_moof(seq, traf_children):
86
96
  return box(b"moof", mfhd + traf)
87
97
 
88
98
 
99
+ def set_offset(moof, off):
100
+ """Point the first trun's data_offset at a byte position (relative to moof start)."""
101
+ i = moof.find(b"trun") # position of the type string
102
+ return moof[:i + 12] + i32(off) + moof[i + 16:]
103
+
104
+
105
+ def make_trex(default_size=0):
106
+ # ver/flags + track_ID + default_sample_description_index + duration + size
107
+ return full_box(b"trex", 0, 0, u32(1) + u32(0) + u32(0) + u32(default_size))
108
+
109
+
89
110
  def make_esds():
90
111
  asc = b"\x12\x10"
91
112
  dsc = bytes([0x05, len(asc)]) + asc
@@ -121,7 +142,7 @@ def make_stsd():
121
142
  return full_box(b"stsd", 0, 0, body)
122
143
 
123
144
 
124
- def make_moov():
145
+ def make_moov(extra=b""):
125
146
  mvhd = full_box(b"mvhd", 0, 0,
126
147
  u32(0) + u32(0) + u32(1000) + u32(12000) + u32(0x10000) +
127
148
  u16(0x0100) + u16(0) + bytes(8) + bytes(36) + bytes(24) + u32(2))
@@ -142,7 +163,7 @@ def make_moov():
142
163
  mdia = box(b"mdia", mdhd + hdlr + minf)
143
164
  trak = box(b"trak", tkhd + mdia)
144
165
  pssh = full_box(b"pssh", 0, 0, bytes(16) + u32(0) + u32(0))
145
- return box(b"moov", mvhd + trak + pssh)
166
+ return box(b"moov", mvhd + trak + pssh + extra)
146
167
 
147
168
 
148
169
  def make_sidx(ref_sizes):
@@ -172,10 +193,6 @@ def build_sample_file():
172
193
  enc = [ctr_crypt(KEY, ivs[i], plain[i]) for i in range(n)]
173
194
 
174
195
  # trun data_offset: first byte of sample data relative to moof start
175
- def set_offset(moof, off):
176
- i = moof.find(b"trun") # position of the type string
177
- return moof[:i + 12] + i32(off) + moof[i + 16:]
178
-
179
196
  moof1 = make_moof(1, [make_tfhd(), make_trun(sizes, 0), make_senc(ivs),
180
197
  make_saiz(n), make_saio()])
181
198
  moof2 = make_moof(2, [make_tfhd(), make_trun(sizes, 0)])
@@ -313,6 +330,215 @@ def assert_decrypted(out, expected_plain):
313
330
  assert b"mp4a" in mc and b"esds" in mc
314
331
 
315
332
 
333
+ def test_trex_default_size_decrypts(sp):
334
+ """Sample sizes declared only in mvex/trex must still decrypt — the ISO
335
+ default cascade is trex (file) → tfhd (fragment) → trun (per entry), and
336
+ CMAF/DASH muxers rely on the trex layer. Before the fix such fragments
337
+ produced zero-size samples and silently passed through unencrypted."""
338
+ n, size = 4, 20000
339
+ iv = bytes([9, 0xA, 3, 4, 5, 6, 7, 8])
340
+ chunks = [bytes([(0x11 * (i + 1)) & 0xFF]) * size for i in range(n)] # distinct per sample
341
+ enc = b"".join(ctr_crypt(KEY, iv, c) for c in chunks)
342
+ plain = b"".join(chunks)
343
+ moof = make_moof(1, [make_tfhd(), make_trun([size] * n, 0, with_sizes=False), make_senc([iv] * n)])
344
+ moof = set_offset(moof, len(moof) + 8)
345
+ mvex = box(b"mvex", make_trex(default_size=size))
346
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
347
+ moof + box(b"mdat", enc) + make_moov(extra=mvex))
348
+ out = sp.proc(input=data, key=KEY_HEX, strict=True)
349
+ frag = find(out, b"moof")[0]
350
+ content = out[frag[1] + 8:frag[1] + frag[2]]
351
+ assert b"senc" not in content
352
+ mdat = find(out, b"mdat")[0]
353
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == plain
354
+
355
+
356
+ def build_classic_source():
357
+ """ftyp + [enc frag] + [plain frag] + moov with explicit durations/sizes —
358
+ material for the classic rewrite (both fragments carry 4 × 20000B samples)."""
359
+ ftyp = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom")
360
+ n, size, dur = 4, 20000, 1024
361
+ plain = [bytes([(0x21 * i) & 0xFF]) * size for i in range(1, n + 1)]
362
+ ivs = [bytes([j, 0xB, 1, 2, 3, 4, 5, 6]) for j in range(n)]
363
+ enc = [ctr_crypt(KEY, ivs[i], plain[i]) for i in range(n)]
364
+ moof1 = make_moof(1, [make_tfhd(default_duration=dur), make_trun([size] * n, 0, durations=[dur] * n), make_senc(ivs)])
365
+ moof2 = make_moof(2, [make_tfhd(default_duration=dur), make_trun([size] * n, 0, durations=[dur] * n)])
366
+ moof1 = set_offset(moof1, len(moof1) + 8)
367
+ moof2 = set_offset(moof2, len(moof2) + 8)
368
+ data = ftyp + moof1 + box(b"mdat", b"".join(enc)) + moof2 + box(b"mdat", b"".join(plain)) + make_moov()
369
+ return data, plain
370
+
371
+
372
+ def find_deep(d, start, end, typ):
373
+ """Recursively search a moov subtree; return (pos, size) of the first match."""
374
+ pos = start
375
+ while pos + 8 <= end:
376
+ (size,) = struct.unpack_from(">I", d, pos)
377
+ t = d[pos + 4:pos + 8]
378
+ if size == 0:
379
+ size = end - pos
380
+ if size < 8 or pos + size > end:
381
+ return None
382
+ if t == typ:
383
+ return pos, size
384
+ if t in (b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"):
385
+ hit = find_deep(d, pos + 8, pos + size, typ)
386
+ if hit:
387
+ return hit
388
+ pos += size
389
+ return None
390
+
391
+
392
+ def has_box(d, start, end, typ):
393
+ return find_deep(d, start, end, typ) is not None
394
+
395
+
396
+ def test_classic_rewrite(sp):
397
+ """classic=True folds the fragments into a regular MP4: real sample
398
+ tables, one mdat, no moof/mvex — byte-identical audio, playable by
399
+ taggers that only understand classic MP4."""
400
+ data, plain = build_classic_source()
401
+ out = sp.proc(input=data, key=KEY_HEX, strict=True, classic=True)
402
+ top = [t for t, _, _ in walk(out)]
403
+ assert b"moof" not in top and b"sidx" not in top
404
+ assert top.count(b"mdat") == 1
405
+ mdat = find(out, b"mdat")[0]
406
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == b"".join(plain) * 2
407
+
408
+ moov = find(out, b"moov")[0]
409
+ assert not has_box(out, moov[1], moov[1] + moov[2], b"mvex")
410
+ assert not has_box(out, moov[1], moov[1] + moov[2], b"pssh")
411
+ for tbl in (b"stts", b"stsc", b"stsz", b"stco"):
412
+ assert has_box(out, moov[1], moov[1] + moov[2], tbl), tbl
413
+ # mvhd v0 duration = 8 samples × 1024 @44100 in the 1000 movie timescale
414
+ (mvhd_dur,) = struct.unpack_from(">I", out, moov[1] + 8 + 8 + 16) # moov hdr(8) + mvhd hdr(8) + ver/flags(4) + creation(4) + modification(4)
415
+ assert mvhd_dur == 8 * 1024 * 1000 // 44100
416
+ # the two chunk offsets point exactly at the mdat content
417
+ stco = find_deep(out, moov[1], moov[1] + moov[2], b"stco")
418
+ assert stco is not None
419
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
420
+ assert count == 2
421
+ assert struct.unpack_from(">II", out, stco[0] + 16) == (mdat[1] + 8, mdat[1] + 8 + 80000)
422
+ # mdhd v0 duration = 8 × 1024 in the 44100 media timescale (mutagen is
423
+ # not used here — the synthetic esds descriptor is a toy it rejects)
424
+ mdhd = find_deep(out, moov[1], moov[1] + moov[2], b"mdhd")
425
+ (mdhd_dur,) = struct.unpack_from(">I", out, mdhd[0] + 8 + 16)
426
+ assert mdhd_dur == 8 * 1024
427
+
428
+
429
+ def test_classic_passthrough_on_classic_input(sp):
430
+ """A file without moof boxes is already classic — classic=True must be a no-op."""
431
+ data, _ = build_classic_source()
432
+ classic = sp.proc(input=data, key=KEY_HEX, classic=True)
433
+ assert sp.proc(input=classic) == sp.proc(input=classic, classic=True)
434
+
435
+
436
+ def test_classic_aproc_parity(sp):
437
+ data, _ = build_classic_source()
438
+ out = asyncio.run(sp.aproc(input=data, key=KEY_HEX, classic=True))
439
+ assert out == sp.proc(input=data, key=KEY_HEX, classic=True)
440
+
441
+
442
+ def test_classic_moov_first(sp):
443
+ """The real-file layout: moov FIRST, then the fragments (moov-at-end was
444
+ the only shape the earlier tests covered — a typo in the fragment walk
445
+ silently produced empty sample tables there and only broke moov-first
446
+ files, i.e. every real track)."""
447
+ data, plain = build_classic_source()
448
+ ftyp = find(data, b"ftyp")[0]
449
+ moov = find(data, b"moov")[0]
450
+ moofs, mdats = find(data, b"moof"), find(data, b"mdat")
451
+ reordered = (data[ftyp[1]:ftyp[1] + ftyp[2]] + data[moov[1]:moov[1] + moov[2]] +
452
+ b"".join(data[m[1]:m[1] + m[2]] + data[d[1]:d[1] + d[2]] for m, d in zip(moofs, mdats)))
453
+ out = sp.proc(input=reordered, key=KEY_HEX, strict=True, classic=True)
454
+ mdat = find(out, b"mdat")[0]
455
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == b"".join(plain) * 2
456
+ moov2 = find(out, b"moov")[0]
457
+ stco = find_deep(out, moov2[1], moov2[1] + moov2[2], b"stco")
458
+ assert stco is not None
459
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
460
+ assert count == 2
461
+
462
+
463
+ def test_error_classic_unsupported(sp):
464
+ """A fragmented layout the rewrite cannot express raises coded error 15 —
465
+ wrapped as DecrypTuneError like every other native code (the [N] relay
466
+ range must cover it)."""
467
+ size = 20000
468
+ moof = make_moof(1, [make_tfhd(), make_trun([size] * 2, 0)])
469
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
470
+ set_offset(moof, 99999999) + box(b"mdat", bytes(size * 2)) + make_moov()) # data outside the file
471
+ try:
472
+ sp.proc(input=data, classic=True)
473
+ raise AssertionError("classic rewrite accepted impossible offsets")
474
+ except DecrypTuneError as e:
475
+ assert e.code == 15, e
476
+
477
+
478
+ def test_classic_chained_trafs(sp):
479
+ """A trun without data_offset continues the previous run's data, chaining
480
+ across trafs of the same moof (ISO 14496-12) — the second traf here relies
481
+ on it. Without the moof-level chain this layout was refused with error 15."""
482
+ size, dur = 20000, 1024
483
+ blob = bytes([(0x33 + i) & 0xFF for i in range(size * 4)]) # 4 samples × 20000
484
+ traf1 = box(b"traf", make_tfhd(default_duration=dur) +
485
+ make_trun([size] * 2, 0, durations=[dur] * 2)) # offset patched below
486
+ traf2 = box(b"traf", make_tfhd(default_duration=dur) +
487
+ make_trun([size] * 2, 0, durations=[dur] * 2, with_offset=False))
488
+ moof = box(b"moof", full_box(b"mfhd", 0, 0, u32(1)) + traf1 + traf2)
489
+ moof = set_offset(moof, len(moof) + 8) # traf1's run starts at the mdat content
490
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
491
+ moof + box(b"mdat", blob) + make_moov())
492
+ out = sp.proc(input=data, classic=True)
493
+ mdat = find(out, b"mdat")[0]
494
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == blob # both trafs' samples, in order
495
+ moov = find(out, b"moov")[0]
496
+ stco = find_deep(out, moov[1], moov[1] + moov[2], b"stco")
497
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
498
+ assert count == 2
499
+ assert struct.unpack_from(">II", out, stco[0] + 16) == (mdat[1] + 8, mdat[1] + 8 + 40000)
500
+
501
+
502
+ def test_classic_deep_nesting_rejected(sp):
503
+ """Deeply nested containers would recurse the rewrite to a stack overflow
504
+ (uncatchable SIGSEGV) — the depth guard refuses them exactly like the
505
+ decrypt path's rebuild_container. The nest is built in O(n): each level
506
+ prepends an 8-byte trak header, so level k is k concatenated headers."""
507
+ moov = make_moov()
508
+ trak_pos = 8 + 108 # moov header + the 108-byte mvhd
509
+ (trak_size,) = struct.unpack_from(">I", moov, trak_pos)
510
+ n = 100_000
511
+ nested = b"".join(u32(8 * k) + b"trak" for k in range(n, 0, -1))
512
+ moov = (moov[:trak_pos] + u32(trak_size + len(nested)) + moov[trak_pos + 4:trak_pos + 8] +
513
+ nested + moov[trak_pos + 8:])
514
+ (moov_size,) = struct.unpack_from(">I", moov, 0)
515
+ moov = u32(moov_size + len(nested)) + moov[4:]
516
+ data = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") + make_moof(1, [make_tfhd(), make_trun([2048] * 2, 0)]) + box(b"mdat", bytes(4096)) + moov
517
+ try:
518
+ sp.proc(input=data, classic=True)
519
+ raise AssertionError("deep nesting accepted")
520
+ except DecrypTuneError as e:
521
+ assert e.code == 15, e
522
+
523
+
524
+ def test_classic_overlapping_chunks_rejected(sp):
525
+ """Hostile truns can all reference the same byte range — the summed output
526
+ used to inflate toward the 32-bit cap and force a huge allocation. Legit
527
+ sample bytes never exceed the input, so overlap is rejected."""
528
+ moofs = []
529
+ for seq in range(500):
530
+ m = make_moof(seq + 1, [make_tfhd(default_size=4096, default_duration=1024),
531
+ make_trun([4096] * 64, 0, with_sizes=False)])
532
+ moofs.append(set_offset(m, 100)) # every fragment claims the same bytes
533
+ ftyp = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom")
534
+ data = ftyp + b"".join(moofs) + make_moov()
535
+ try:
536
+ sp.proc(input=data, classic=True)
537
+ raise AssertionError("overlapping chunks accepted")
538
+ except DecrypTuneError as e:
539
+ assert e.code == 15, e
540
+
541
+
316
542
  # ---- fixtures ---------------------------------------------------------------
317
543
 
318
544
  @pytest.fixture(scope="session")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes