decryptune 1.1.5__tar.gz → 1.1.7__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.5 → decryptune-1.1.7}/Cargo.lock +12 -12
  2. {decryptune-1.1.5 → decryptune-1.1.7}/Cargo.toml +1 -1
  3. {decryptune-1.1.5 → decryptune-1.1.7}/PKG-INFO +6 -4
  4. {decryptune-1.1.5 → decryptune-1.1.7}/README.md +5 -3
  5. {decryptune-1.1.5 → decryptune-1.1.7}/python/decryptune/__init__.py +37 -13
  6. decryptune-1.1.7/src/defrag.rs +331 -0
  7. {decryptune-1.1.5 → decryptune-1.1.7}/src/error.rs +4 -2
  8. {decryptune-1.1.5 → decryptune-1.1.7}/src/jpeg/decode.rs +1 -1
  9. {decryptune-1.1.5 → decryptune-1.1.7}/src/jpeg/encode.rs +7 -1
  10. {decryptune-1.1.5 → decryptune-1.1.7}/src/jpeg/tests.rs +11 -0
  11. {decryptune-1.1.5 → decryptune-1.1.7}/src/lib.rs +66 -16
  12. {decryptune-1.1.5 → decryptune-1.1.7}/src/process.rs +29 -4
  13. {decryptune-1.1.5 → decryptune-1.1.7}/tests/test_decryptune.py +138 -14
  14. {decryptune-1.1.5 → decryptune-1.1.7}/.gitattributes +0 -0
  15. {decryptune-1.1.5 → decryptune-1.1.7}/.github/workflows/build.yml +0 -0
  16. {decryptune-1.1.5 → decryptune-1.1.7}/.gitignore +0 -0
  17. {decryptune-1.1.5 → decryptune-1.1.7}/LICENSE +0 -0
  18. {decryptune-1.1.5 → decryptune-1.1.7}/pyproject.toml +0 -0
  19. {decryptune-1.1.5 → decryptune-1.1.7}/src/boxes.rs +0 -0
  20. {decryptune-1.1.5 → decryptune-1.1.7}/src/cover.rs +0 -0
  21. {decryptune-1.1.5 → decryptune-1.1.7}/src/input.rs +0 -0
  22. {decryptune-1.1.5 → decryptune-1.1.7}/src/jpeg/mod.rs +0 -0
  23. {decryptune-1.1.5 → decryptune-1.1.7}/src/meta.rs +0 -0
  24. {decryptune-1.1.5 → decryptune-1.1.7}/tests/fixtures/big.jpg +0 -0
  25. {decryptune-1.1.5 → decryptune-1.1.7}/tests/fixtures/odd420.jpg +0 -0
  26. {decryptune-1.1.5 → decryptune-1.1.7}/tests/fixtures/tiny.jpg +0 -0
@@ -4,9 +4,9 @@ version = 4
4
4
 
5
5
  [[package]]
6
6
  name = "aes"
7
- version = "0.9.3"
7
+ version = "0.9.4"
8
8
  source = "registry+https://github.com/rust-lang/crates.io-index"
9
- checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
9
+ checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1"
10
10
  dependencies = [
11
11
  "cipher",
12
12
  "cpubits",
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.5"
71
+ version = "1.1.7"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -100,7 +100,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
100
100
  dependencies = [
101
101
  "proc-macro2",
102
102
  "quote",
103
- "syn 3.0.9",
103
+ "syn 3.0.10",
104
104
  ]
105
105
 
106
106
  [[package]]
@@ -139,9 +139,9 @@ dependencies = [
139
139
 
140
140
  [[package]]
141
141
  name = "inout"
142
- version = "0.2.5"
142
+ version = "0.2.6"
143
143
  source = "registry+https://github.com/rust-lang/crates.io-index"
144
- checksum = "3b5cf4372d022092674a83b8febf5865f7a573cc0c5baec5e49c879b6a20978f"
144
+ checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9"
145
145
  dependencies = [
146
146
  "hybrid-array",
147
147
  ]
@@ -278,9 +278,9 @@ dependencies = [
278
278
 
279
279
  [[package]]
280
280
  name = "syn"
281
- version = "3.0.9"
281
+ version = "3.0.10"
282
282
  source = "registry+https://github.com/rust-lang/crates.io-index"
283
- checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
283
+ checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
284
284
  dependencies = [
285
285
  "proc-macro2",
286
286
  "quote",
@@ -289,15 +289,15 @@ 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"
298
- version = "1.54.0"
298
+ version = "1.54.1"
299
299
  source = "registry+https://github.com/rust-lang/crates.io-index"
300
- checksum = "a0c168a474b95bfecfe908a65d4bdffc523144b649a74c09c286afb35d53e0bc"
300
+ checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
301
301
  dependencies = [
302
302
  "pin-project-lite",
303
303
  ]
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.5"
3
+ version = "1.1.7"
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.5
3
+ Version: 1.1.7
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
 
@@ -11,11 +11,13 @@ from pathlib import Path
11
11
 
12
12
  try:
13
13
  from . import decryptune as _native
14
- except ImportError:
14
+ except ImportError as _imp_err:
15
15
  # source checkout: load the staged extension from the repo root (or beside
16
16
  # the package); the loader requires PyInit_decryptune, so the module keeps
17
17
  # that name. The candidate order is platform-aware — the repo may stage
18
- # builds for several platforms side by side.
18
+ # builds for several platforms side by side. A broken extension load
19
+ # (missing runtime DLL, arch mismatch) raises the SAME ImportError as a
20
+ # missing module, so the staged candidates are scanned before giving up.
19
21
  import sys
20
22
 
21
23
  _names: tuple[str, ...] = ("decryptune.pyd",) if sys.platform == "win32" else \
@@ -24,12 +26,20 @@ except ImportError:
24
26
  _candidates = [base / n for base in (_pkg.parent.parent, _pkg.parent, _pkg) for n in _names]
25
27
  _lib = next((p for p in _candidates if p.exists()), None)
26
28
  if _lib is None:
27
- raise
29
+ raise ImportError(
30
+ f"no staged native extension found (tried: {', '.join(map(str, _candidates))}); "
31
+ f"if the package is installed as a wheel, its bundled extension may have failed "
32
+ f"to load (missing runtime DLL, wrong arch): {_imp_err}"
33
+ ) from _imp_err
28
34
  _loader = importlib.machinery.ExtensionFileLoader("decryptune", str(_lib))
29
35
  _native = importlib.util.module_from_spec(importlib.util.spec_from_loader("decryptune", _loader))
30
- _loader.exec_module(_native)
36
+ try:
37
+ _loader.exec_module(_native)
38
+ except ImportError as _load_err:
39
+ raise ImportError(f"staged extension {_lib} failed to load: {_load_err}") from _load_err
40
+ sys.modules[f"{__name__}.decryptune"] = _native # register like a real submodule import
31
41
 
32
- __version__ = "1.1.5"
42
+ __version__ = "1.1.7"
33
43
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
34
44
 
35
45
 
@@ -50,16 +60,22 @@ class DecrypTuneError(Exception):
50
60
  return f"DecrypTuneError(code={self.code}, message={self.message!r})"
51
61
 
52
62
 
53
- # all error messages are authored by the native core — this wrapper relays [code] + message;
54
- # anything without a [N] prefix is not a native error and propagates unchanged
63
+ # all error messages are authored by the native core (error.rs) — this wrapper
64
+ # relays [code] + message; anything outside the known code range (or without a
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
67
+
68
+
55
69
  def _to_err(exc: Exception) -> DecrypTuneError | None:
56
70
  msg: str = str(exc)
57
71
  end: int = msg.find("]")
58
72
  if msg.startswith("[") and end != -1:
59
73
  try:
60
- return DecrypTuneError(int(msg[1:end]), msg[end + 1:].strip())
74
+ code: int = int(msg[1:end])
61
75
  except ValueError:
62
- pass
76
+ return None
77
+ if code in _NATIVE_CODES:
78
+ return DecrypTuneError(code, msg[end + 1:].strip())
63
79
  return None
64
80
 
65
81
 
@@ -85,7 +101,8 @@ class DecrypTune:
85
101
  key: str | None = None,
86
102
  kid: str | None = None,
87
103
  meta: "TuneMeta | None" = None,
88
- strict: bool = False
104
+ strict: bool = False,
105
+ classic: bool = False
89
106
  ) -> bytes | None:
90
107
  """Decrypt, fix, write metadata, and optionally guard — one pass.
91
108
 
@@ -101,12 +118,18 @@ class DecrypTune:
101
118
  (JPEG/PNG); oversized JPEGs are downscaled to ≤1000px.
102
119
  - strict: when True (and key given), a fragment that decrypts to
103
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.
104
127
 
105
128
  Returns None when out is a path, bytes when out is None.
106
129
  All parameters are keyword-only.
107
130
  """
108
131
  try:
109
- 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)
110
133
  except Exception as e:
111
134
  if (err := _to_err(e)) is not None:
112
135
  raise err from None
@@ -120,7 +143,8 @@ class DecrypTune:
120
143
  key: str | None = None,
121
144
  kid: str | None = None,
122
145
  meta: "TuneMeta | None" = None,
123
- strict: bool = False
146
+ strict: bool = False,
147
+ classic: bool = False
124
148
  ) -> bytes | None:
125
149
  """Async proc — same contract, keyword-only parameters.
126
150
 
@@ -131,7 +155,7 @@ class DecrypTune:
131
155
  blocks the event loop.
132
156
  """
133
157
  try:
134
- 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)
135
159
  except Exception as e:
136
160
  if (err := _to_err(e)) is not None:
137
161
  raise err from None
@@ -0,0 +1,331 @@
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;
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
137
+ fn rebuild(data: &[u8], start: usize, end: usize, tables: &Tables, movie_duration: u64, media_duration: u64) -> Result<Vec<u8>, Err> {
138
+ let children: Vec<Box> = parse(data, start, end);
139
+ if children.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
140
+ let mut out: Vec<u8> = Vec::new();
141
+ for b in &children {
142
+ match &b.typ {
143
+ b"mvex" | b"stts" | b"stsc" | b"stsz" | b"stco" | b"co64" | b"stz2" => {} // dropped — fragmentation markers or replaced tables
144
+ b"mvhd" => {
145
+ let body: Vec<u8> = patch_duration(data, b, 16, 24, movie_duration)?;
146
+ write_header(&mut out, b"mvhd", body.len());
147
+ out.extend_from_slice(&body);
148
+ }
149
+ b"mdhd" => {
150
+ let body: Vec<u8> = patch_duration(data, b, 16, 24, media_duration)?;
151
+ write_header(&mut out, b"mdhd", body.len());
152
+ out.extend_from_slice(&body);
153
+ }
154
+ b"tkhd" => {
155
+ let body: Vec<u8> = patch_duration(data, b, 20, 28, movie_duration)?;
156
+ write_header(&mut out, b"tkhd", body.len());
157
+ out.extend_from_slice(&body);
158
+ }
159
+ b"elst" => {
160
+ let body: Vec<u8> = fix_elst(data, b, movie_duration)?;
161
+ write_header(&mut out, b"elst", body.len());
162
+ out.extend_from_slice(&body);
163
+ }
164
+ b"stbl" => {
165
+ let mut inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration)?;
166
+ // the Tables fields hold box BODIES — wrap each in its header
167
+ write_header(&mut inner, b"stts", tables.stts.len());
168
+ inner.extend_from_slice(&tables.stts);
169
+ write_header(&mut inner, b"stsc", tables.stsc.len());
170
+ inner.extend_from_slice(&tables.stsc);
171
+ write_header(&mut inner, b"stsz", tables.stsz.len());
172
+ inner.extend_from_slice(&tables.stsz);
173
+ write_header(&mut inner, b"stco", tables.stco.len());
174
+ inner.extend_from_slice(&tables.stco);
175
+ write_header(&mut out, b"stbl", inner.len());
176
+ out.extend_from_slice(&inner);
177
+ }
178
+ typ if CONTAINERS.iter().any(|c| c == &typ) => {
179
+ let inner: Vec<u8> = rebuild(data, b.content_start, b.end, tables, movie_duration, media_duration)?;
180
+ write_header(&mut out, typ, inner.len());
181
+ out.extend_from_slice(&inner);
182
+ }
183
+ _ => out.extend_from_slice(&data[b.start..b.end])
184
+ }
185
+ }
186
+ Ok(out)
187
+ }
188
+
189
+ /// Rewrite fragmented MP4 bytes as a classic MP4. A file without moof boxes
190
+ /// is already classic and returns unchanged.
191
+ pub(crate) fn defragment(data: &[u8]) -> Result<Vec<u8>, Err> {
192
+ let top: Vec<Box> = parse(data, 0, data.len());
193
+ if top.is_empty() || top.len() >= MAX_BOXES { return Err(Err::ClassicUnsupported); }
194
+ if !top.iter().any(|b| b.is(b"moof")) { return Ok(data.to_vec()); }
195
+ let moov: &Box = top.iter().find(|b| b.is(b"moov")).ok_or(Err::ClassicUnsupported)?;
196
+ let children: Vec<Box> = parse(data, moov.content_start, moov.end);
197
+ if children.len() >= MAX_BOXES || children.iter().filter(|b| b.is(b"trak")).count() != 1 {
198
+ return Err(Err::ClassicUnsupported);
199
+ }
200
+ let mvhd: &Box = children.iter().find(|b| b.is(b"mvhd")).ok_or(Err::ClassicUnsupported)?;
201
+ let trak: &Box = children.iter().find(|b| b.is(b"trak")).ok_or(Err::ClassicUnsupported)?;
202
+ let trak_children: Vec<Box> = parse(data, trak.content_start, trak.end);
203
+ let mdia: &Box = trak_children.iter().find(|b| b.is(b"mdia")).ok_or(Err::ClassicUnsupported)?;
204
+ let mdia_children: Vec<Box> = parse(data, mdia.content_start, mdia.end);
205
+ let mdhd: &Box = mdia_children.iter().find(|b| b.is(b"mdhd")).ok_or(Err::ClassicUnsupported)?;
206
+ let movie_ts: u32 = timescale(&data[mvhd.content_start..mvhd.end])?;
207
+ let media_ts: u32 = timescale(&data[mdhd.content_start..mdhd.end])?;
208
+ if movie_ts == 0 || media_ts == 0 { return Err(Err::ClassicUnsupported); }
209
+
210
+ // walk the fragments: sample sizes, durations, and where the bytes are.
211
+ // base_data_offset defaults to the moof start; sample defaults cascade
212
+ // trex → tfhd → trun entry, exactly like the decrypt planner
213
+ let trex: Option<(u32, u32)> = trex_defaults(data, &top);
214
+ let (mut sizes, mut durations): (Vec<u32>, Vec<u32>) = (Vec::new(), Vec::new());
215
+ let mut chunks: Vec<ChunkRun> = Vec::new();
216
+ for moof in top.iter().filter(|b| b.is(b"moof")) {
217
+ let moof_children: Vec<Box> = parse(data, moof.content_start, moof.end);
218
+ for traf in &moof_children {
219
+ if !traf.is(b"traf") { continue; }
220
+ let subs: Vec<Box> = parse(data, traf.content_start, traf.end);
221
+ let mut base: usize = moof.start;
222
+ let mut dur: u32 = trex.map(|(d, _)| d).unwrap_or(0);
223
+ let mut size: u32 = trex.map(|(_, s)| s).unwrap_or(0);
224
+ let mut next: Option<usize> = None;
225
+ for sub in &subs {
226
+ match &sub.typ {
227
+ b"tfhd" => {
228
+ let flags: u32 = be32(data, sub.content_start, sub.end)? & 0xFFFFFF;
229
+ if sub.content_start + 8 > sub.end { return Err(Err::ClassicUnsupported); }
230
+ let mut q: usize = sub.content_start + 8; // version/flags + track_ID
231
+ if flags & 0x1 != 0 { // base_data_offset (absolute)
232
+ if q + 8 > sub.end { return Err(Err::ClassicUnsupported); }
233
+ let b64: u64 = u64::from_be_bytes(data[q..q + 8].try_into().unwrap());
234
+ if b64 > data.len() as u64 { return Err(Err::ClassicUnsupported); }
235
+ base = b64 as usize;
236
+ q += 8;
237
+ }
238
+ if flags & 0x2 != 0 { q += 4; } // sample_description_index — unused
239
+ if flags & 0x8 != 0 { dur = be32(data, q, sub.end)?; q += 4; }
240
+ if flags & 0x10 != 0 { size = be32(data, q, sub.end)?; q += 4; }
241
+ }
242
+ b"trun" => {
243
+ let flags: u32 = be32(data, sub.content_start, sub.end)? & 0xFFFFFF;
244
+ let count: usize = be32(data, sub.content_start + 4, sub.end)? as usize;
245
+ if count > MAX_SAMPLES { return Err(Err::ClassicUnsupported); }
246
+ let mut q: usize = sub.content_start + 8;
247
+ let data_start: usize;
248
+ if flags & 0x1 != 0 { // data_offset, signed, relative to base
249
+ let off: i32 = be32(data, q, sub.end)? as i32;
250
+ q += 4;
251
+ let abs: i64 = base as i64 + off as i64;
252
+ if abs < 0 || abs > data.len() as i64 { return Err(Err::ClassicUnsupported); }
253
+ data_start = abs as usize;
254
+ } else if let Some(n) = next {
255
+ data_start = n; // chained after the previous run in this moof
256
+ } else {
257
+ return Err(Err::ClassicUnsupported);
258
+ }
259
+ if flags & 0x4 != 0 { q += 4; } // first_sample_flags — unused
260
+ let mut run_len: usize = 0;
261
+ for _ in 0..count {
262
+ let mut d: u32 = dur;
263
+ let mut s: u32 = size;
264
+ if flags & 0x100 != 0 { d = be32(data, q, sub.end)?; q += 4; }
265
+ if flags & 0x200 != 0 { s = be32(data, q, sub.end)?; q += 4; }
266
+ if flags & 0x400 != 0 { q += 4; } // sample_flags — unused
267
+ if flags & 0x800 != 0 { q += 4; } // composition offsets — unused
268
+ if s == 0 { return Err(Err::ClassicUnsupported); } // a sample without bytes cannot be placed
269
+ sizes.push(s);
270
+ durations.push(d);
271
+ run_len += s as usize;
272
+ }
273
+ if data_start + run_len > data.len() { return Err(Err::ClassicUnsupported); }
274
+ if count > 0 {
275
+ chunks.push(ChunkRun { offset: data_start, len: run_len, samples: count });
276
+ next = Some(data_start + run_len);
277
+ }
278
+ }
279
+ _ => {}
280
+ }
281
+ }
282
+ }
283
+ }
284
+ if sizes.is_empty() { return Err(Err::ClassicUnsupported); }
285
+ let media_duration: u64 = durations.iter().map(|d| u64::from(*d)).sum();
286
+ if media_duration == 0 { return Err(Err::ClassicUnsupported); }
287
+ let movie_duration: u64 = media_duration * u64::from(movie_ts) / u64::from(media_ts);
288
+
289
+ // moov's size does not depend on the offset VALUES — size it with dummy
290
+ // offsets first, then place the data and rebuild with the real ones
291
+ let zeros: Vec<u32> = vec![0u32; chunks.len()];
292
+ let dummy: Tables = make_tables(&chunks, &zeros, &durations, &sizes);
293
+ let placeholder: Vec<u8> = rebuild(data, moov.content_start, moov.end, &dummy, movie_duration, media_duration)?;
294
+ let others_len: usize = top.iter()
295
+ .filter(|b| !matches!(&b.typ, b"moof" | b"mdat" | b"sidx" | b"moov"))
296
+ .map(|b| b.end - b.start)
297
+ .sum();
298
+ let data_start: usize = others_len + header_len(placeholder.len()) + placeholder.len() + 8; // moov box + mdat header
299
+ let total_audio: usize = chunks.iter().map(|c| c.len).sum();
300
+ if data_start + total_audio > u32::MAX as usize {
301
+ return Err(Err::ClassicUnsupported); // stco holds u32 offsets only (audio never gets there)
302
+ }
303
+ let mut offsets: Vec<u32> = Vec::with_capacity(chunks.len());
304
+ let mut pos: usize = data_start;
305
+ for c in &chunks {
306
+ offsets.push(pos as u32);
307
+ pos += c.len;
308
+ }
309
+ let tables: Tables = make_tables(&chunks, &offsets, &durations, &sizes);
310
+ let new_moov: Vec<u8> = rebuild(data, moov.content_start, moov.end, &tables, movie_duration, media_duration)?;
311
+ if new_moov.len() != placeholder.len() { return Err(Err::ClassicUnsupported); } // cannot happen — table sizes are value-independent
312
+
313
+ // unknown top-level boxes (free, top-level meta…) are kept verbatim;
314
+ // moof/mdat/sidx fold into the tables and the single output mdat
315
+ let mut out: Vec<u8> = Vec::with_capacity(data_start + total_audio);
316
+ for b in &top {
317
+ match &b.typ {
318
+ b"moof" | b"mdat" | b"sidx" => {}
319
+ b"moov" => {
320
+ write_header(&mut out, b"moov", new_moov.len());
321
+ out.extend_from_slice(&new_moov);
322
+ }
323
+ _ => out.extend_from_slice(&data[b.start..b.end])
324
+ }
325
+ }
326
+ write_header(&mut out, b"mdat", total_audio);
327
+ for c in &chunks {
328
+ out.extend_from_slice(&data[c.offset..c.offset + c.len]);
329
+ }
330
+ Ok(out)
331
+ }
@@ -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
  }
@@ -9,7 +9,7 @@ use crate::Err;
9
9
  // entropy byte is read — covers are downscaled to 1000px anyway, so 64MP
10
10
  // (8192²) is far beyond anything legitimate; at the old 256MP cap a ~1MB
11
11
  // hostile JPEG forced ~1GB of buffers and seconds of IDCT
12
- const MAX_PIXELS: usize = 67_108_864; // 64 megapixels
12
+ pub(super) const MAX_PIXELS: usize = 67_108_864; // 64 megapixels
13
13
 
14
14
  struct HuffTable {
15
15
  counts : [u8; 17], // symbols per code length 1..=16
@@ -106,6 +106,9 @@ impl EncTable {
106
106
  }
107
107
 
108
108
  fn put(&self, bw: &mut BitWriter, sym: usize) {
109
+ // a symbol absent from the table has len 0 — put() would silently
110
+ // emit NOTHING and the stream would corrupt without an error
111
+ debug_assert!(self.lens[sym] != 0, "Huffman symbol {sym} missing from its table");
109
112
  bw.put(self.codes[sym] as u32, self.lens[sym] as u32);
110
113
  }
111
114
  }
@@ -248,7 +251,10 @@ fn push_dht(out: &mut Vec<u8>, class_id: u8, bits: &[u8; 16], vals: &[u8]) {
248
251
 
249
252
  /// Encode gray (ch=1) or RGB (ch=3) pixels into baseline JPEG bytes.
250
253
  pub(crate) fn encode(pix: &[u8], w: usize, h: usize, ch: usize) -> Result<Vec<u8>, Err> {
251
- if w == 0 || h == 0 || (ch != 1 && ch != 3) || pix.len() < w * h * ch { return Err(Err::BadCover); }
254
+ // dims must fit the u16 SOF0 fields and the shared 64MP cap — range-checked
255
+ // BEFORE any size math so the width×height products can never overflow
256
+ // (callers pre-cap at 1000px; this is the encoder's own defense)
257
+ if w == 0 || h == 0 || w > 0xFFFF || h > 0xFFFF || w * h > super::decode::MAX_PIXELS || (ch != 1 && ch != 3) || pix.len() < w * h * ch { return Err(Err::BadCover); }
252
258
  let (y, cb, cr): (Vec<u8>, Vec<u8>, Vec<u8>) = if ch == 1 {
253
259
  (pix.to_vec(), Vec::new(), Vec::new())
254
260
  } else {
@@ -152,6 +152,17 @@ fn hostile_dht_rejected() {
152
152
  }
153
153
  }
154
154
 
155
+ #[test]
156
+ fn hostile_encode_dims_rejected() {
157
+ // SOF0 stores dimensions in u16 fields — a wider dim used to truncate
158
+ // silently and produce a corrupt file; the pixel cap is shared with the
159
+ // decoder. All rejected BEFORE any allocation
160
+ assert!(encode(&[0u8; 4], 70_000, 1, 1).is_err()); // over the u16 field
161
+ assert!(encode(&[0u8; 4], 1, 70_000, 3).is_err()); // over the u16 field
162
+ assert!(encode(&[0u8; 4], 10_000, 10_000, 1).is_err()); // over the 64MP cap
163
+ assert!(encode(&[0u8; 1], 0, 0, 1).is_err());
164
+ }
165
+
155
166
  // DUMP_ENC=1 + JPEG_FIXTURES: write our encode of the p444 reference so the
156
167
  // local Pillow PSNR checker can score it against the same pristine source
157
168
  #[test]
@@ -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 = defrag::defragment(&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> = defrag::defragment(&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 = defrag::defragment(&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> = defrag::defragment(&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
@@ -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,26 @@ 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)
61
+ def make_trun(sizes, data_offset, with_sizes=True, durations=None):
62
+ flags = 0x1 | (0x200 if with_sizes else 0) | (0x100 if durations else 0)
63
63
  body = u32(len(sizes)) + i32(data_offset)
64
- if with_sizes:
65
- body += b"".join(u32(s) for s in sizes)
64
+ for i in range(len(sizes)):
65
+ if durations:
66
+ body += u32(durations[i])
67
+ if with_sizes:
68
+ body += u32(sizes[i])
66
69
  return full_box(b"trun", 0, flags, body)
67
70
 
68
71
 
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
72
+ def make_tfhd(default_size=None, default_duration=None):
73
+ payload, flags = u32(1), 0
74
+ if default_duration is not None: # 0x8 precedes 0x10 per spec
75
+ flags |= 0x8
76
+ payload += u32(default_duration)
77
+ if default_size is not None:
78
+ flags |= 0x10
79
+ payload += u32(default_size)
80
+ return full_box(b"tfhd", 0, flags, payload)
73
81
 
74
82
 
75
83
  def make_saiz(count):
@@ -86,6 +94,17 @@ def make_moof(seq, traf_children):
86
94
  return box(b"moof", mfhd + traf)
87
95
 
88
96
 
97
+ def set_offset(moof, off):
98
+ """Point the first trun's data_offset at a byte position (relative to moof start)."""
99
+ i = moof.find(b"trun") # position of the type string
100
+ return moof[:i + 12] + i32(off) + moof[i + 16:]
101
+
102
+
103
+ def make_trex(default_size=0):
104
+ # ver/flags + track_ID + default_sample_description_index + duration + size
105
+ return full_box(b"trex", 0, 0, u32(1) + u32(0) + u32(0) + u32(default_size))
106
+
107
+
89
108
  def make_esds():
90
109
  asc = b"\x12\x10"
91
110
  dsc = bytes([0x05, len(asc)]) + asc
@@ -121,7 +140,7 @@ def make_stsd():
121
140
  return full_box(b"stsd", 0, 0, body)
122
141
 
123
142
 
124
- def make_moov():
143
+ def make_moov(extra=b""):
125
144
  mvhd = full_box(b"mvhd", 0, 0,
126
145
  u32(0) + u32(0) + u32(1000) + u32(12000) + u32(0x10000) +
127
146
  u16(0x0100) + u16(0) + bytes(8) + bytes(36) + bytes(24) + u32(2))
@@ -142,7 +161,7 @@ def make_moov():
142
161
  mdia = box(b"mdia", mdhd + hdlr + minf)
143
162
  trak = box(b"trak", tkhd + mdia)
144
163
  pssh = full_box(b"pssh", 0, 0, bytes(16) + u32(0) + u32(0))
145
- return box(b"moov", mvhd + trak + pssh)
164
+ return box(b"moov", mvhd + trak + pssh + extra)
146
165
 
147
166
 
148
167
  def make_sidx(ref_sizes):
@@ -172,10 +191,6 @@ def build_sample_file():
172
191
  enc = [ctr_crypt(KEY, ivs[i], plain[i]) for i in range(n)]
173
192
 
174
193
  # 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
194
  moof1 = make_moof(1, [make_tfhd(), make_trun(sizes, 0), make_senc(ivs),
180
195
  make_saiz(n), make_saio()])
181
196
  moof2 = make_moof(2, [make_tfhd(), make_trun(sizes, 0)])
@@ -313,6 +328,115 @@ def assert_decrypted(out, expected_plain):
313
328
  assert b"mp4a" in mc and b"esds" in mc
314
329
 
315
330
 
331
+ def test_trex_default_size_decrypts(sp):
332
+ """Sample sizes declared only in mvex/trex must still decrypt — the ISO
333
+ default cascade is trex (file) → tfhd (fragment) → trun (per entry), and
334
+ CMAF/DASH muxers rely on the trex layer. Before the fix such fragments
335
+ produced zero-size samples and silently passed through unencrypted."""
336
+ n, size = 4, 20000
337
+ iv = bytes([9, 0xA, 3, 4, 5, 6, 7, 8])
338
+ chunks = [bytes([(0x11 * (i + 1)) & 0xFF]) * size for i in range(n)] # distinct per sample
339
+ enc = b"".join(ctr_crypt(KEY, iv, c) for c in chunks)
340
+ plain = b"".join(chunks)
341
+ moof = make_moof(1, [make_tfhd(), make_trun([size] * n, 0, with_sizes=False), make_senc([iv] * n)])
342
+ moof = set_offset(moof, len(moof) + 8)
343
+ mvex = box(b"mvex", make_trex(default_size=size))
344
+ data = (box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom") +
345
+ moof + box(b"mdat", enc) + make_moov(extra=mvex))
346
+ out = sp.proc(input=data, key=KEY_HEX, strict=True)
347
+ frag = find(out, b"moof")[0]
348
+ content = out[frag[1] + 8:frag[1] + frag[2]]
349
+ assert b"senc" not in content
350
+ mdat = find(out, b"mdat")[0]
351
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == plain
352
+
353
+
354
+ def build_classic_source():
355
+ """ftyp + [enc frag] + [plain frag] + moov with explicit durations/sizes —
356
+ material for the classic rewrite (both fragments carry 4 × 20000B samples)."""
357
+ ftyp = box(b"ftyp", b"M4A " + u32(0) + b"M4A " + b"mp42" + b"isom")
358
+ n, size, dur = 4, 20000, 1024
359
+ plain = [bytes([(0x21 * i) & 0xFF]) * size for i in range(1, n + 1)]
360
+ ivs = [bytes([j, 0xB, 1, 2, 3, 4, 5, 6]) for j in range(n)]
361
+ enc = [ctr_crypt(KEY, ivs[i], plain[i]) for i in range(n)]
362
+ moof1 = make_moof(1, [make_tfhd(default_duration=dur), make_trun([size] * n, 0, durations=[dur] * n), make_senc(ivs)])
363
+ moof2 = make_moof(2, [make_tfhd(default_duration=dur), make_trun([size] * n, 0, durations=[dur] * n)])
364
+ moof1 = set_offset(moof1, len(moof1) + 8)
365
+ moof2 = set_offset(moof2, len(moof2) + 8)
366
+ data = ftyp + moof1 + box(b"mdat", b"".join(enc)) + moof2 + box(b"mdat", b"".join(plain)) + make_moov()
367
+ return data, plain
368
+
369
+
370
+ def find_deep(d, start, end, typ):
371
+ """Recursively search a moov subtree; return (pos, size) of the first match."""
372
+ pos = start
373
+ while pos + 8 <= end:
374
+ (size,) = struct.unpack_from(">I", d, pos)
375
+ t = d[pos + 4:pos + 8]
376
+ if size == 0:
377
+ size = end - pos
378
+ if size < 8 or pos + size > end:
379
+ return None
380
+ if t == typ:
381
+ return pos, size
382
+ if t in (b"moov", b"trak", b"mdia", b"minf", b"stbl", b"edts"):
383
+ hit = find_deep(d, pos + 8, pos + size, typ)
384
+ if hit:
385
+ return hit
386
+ pos += size
387
+ return None
388
+
389
+
390
+ def has_box(d, start, end, typ):
391
+ return find_deep(d, start, end, typ) is not None
392
+
393
+
394
+ def test_classic_rewrite(sp):
395
+ """classic=True folds the fragments into a regular MP4: real sample
396
+ tables, one mdat, no moof/mvex — byte-identical audio, playable by
397
+ taggers that only understand classic MP4."""
398
+ data, plain = build_classic_source()
399
+ out = sp.proc(input=data, key=KEY_HEX, strict=True, classic=True)
400
+ top = [t for t, _, _ in walk(out)]
401
+ assert b"moof" not in top and b"sidx" not in top
402
+ assert top.count(b"mdat") == 1
403
+ mdat = find(out, b"mdat")[0]
404
+ assert out[mdat[1] + 8:mdat[1] + mdat[2]] == b"".join(plain) * 2
405
+
406
+ moov = find(out, b"moov")[0]
407
+ assert not has_box(out, moov[1], moov[1] + moov[2], b"mvex")
408
+ assert not has_box(out, moov[1], moov[1] + moov[2], b"pssh")
409
+ for tbl in (b"stts", b"stsc", b"stsz", b"stco"):
410
+ assert has_box(out, moov[1], moov[1] + moov[2], tbl), tbl
411
+ # mvhd v0 duration = 8 samples × 1024 @44100 in the 1000 movie timescale
412
+ (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)
413
+ assert mvhd_dur == 8 * 1024 * 1000 // 44100
414
+ # the two chunk offsets point exactly at the mdat content
415
+ stco = find_deep(out, moov[1], moov[1] + moov[2], b"stco")
416
+ assert stco is not None
417
+ (count,) = struct.unpack_from(">I", out, stco[0] + 12)
418
+ assert count == 2
419
+ assert struct.unpack_from(">II", out, stco[0] + 16) == (mdat[1] + 8, mdat[1] + 8 + 80000)
420
+ # mdhd v0 duration = 8 × 1024 in the 44100 media timescale (mutagen is
421
+ # not used here — the synthetic esds descriptor is a toy it rejects)
422
+ mdhd = find_deep(out, moov[1], moov[1] + moov[2], b"mdhd")
423
+ (mdhd_dur,) = struct.unpack_from(">I", out, mdhd[0] + 8 + 16)
424
+ assert mdhd_dur == 8 * 1024
425
+
426
+
427
+ def test_classic_passthrough_on_classic_input(sp):
428
+ """A file without moof boxes is already classic — classic=True must be a no-op."""
429
+ data, _ = build_classic_source()
430
+ classic = sp.proc(input=data, key=KEY_HEX, classic=True)
431
+ assert sp.proc(input=classic) == sp.proc(input=classic, classic=True)
432
+
433
+
434
+ def test_classic_aproc_parity(sp):
435
+ data, _ = build_classic_source()
436
+ out = asyncio.run(sp.aproc(input=data, key=KEY_HEX, classic=True))
437
+ assert out == sp.proc(input=data, key=KEY_HEX, classic=True)
438
+
439
+
316
440
  # ---- fixtures ---------------------------------------------------------------
317
441
 
318
442
  @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