decryptune 1.1.2__tar.gz → 1.1.3__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.
@@ -44,75 +44,22 @@ jobs:
44
44
  echo "new version v$V — full build + release"
45
45
  fi
46
46
 
47
- # standalone zips: the raw cdylib is extracted from the manylinux wheel
48
- # (guarantees glibc 2.28 compat AND byte-identical binary with the wheel)
49
- build-linux:
47
+ # tests gate the release: pytest e2e against the built extension + codec
48
+ # unit tests (fixture-dependent pixel tests skip without JPEG_FIXTURES)
49
+ test:
50
50
  needs: verify
51
51
  if: needs.verify.outputs.release == 'true'
52
- strategy:
53
- fail-fast: false
54
- matrix:
55
- include:
56
- - runner: ubuntu-latest
57
- platform: linux-x86_64
58
- - runner: ubuntu-24.04-arm
59
- platform: linux-aarch64
60
- runs-on: ${{ matrix.runner }}
61
- steps:
62
- - uses: actions/checkout@v4
63
- - uses: PyO3/maturin-action@v1
64
- with:
65
- command: build
66
- args: --release --out wheelhouse
67
- manylinux: "2_28"
68
- - name: package binary + wrapper
69
- run: |
70
- python3 -m zipfile -e wheelhouse/decryptune-*.whl extracted/
71
- mkdir -p dist
72
- cp extracted/decryptune/decryptune.*.so dist/libdecryptune.so
73
- cp decryptune.py dist/
74
- cd dist
75
- python3 -m zipfile -c "decryptune-${{ matrix.platform }}.zip" libdecryptune.so decryptune.py
76
- - uses: actions/upload-artifact@v4
77
- with:
78
- retention-days: 3
79
- name: bin-${{ matrix.platform }}
80
- path: dist/*.zip
81
-
82
- # Windows zips: raw cargo build (the MSVC link has no undefined-symbol issue)
83
- build-native:
84
- needs: verify
85
- if: needs.verify.outputs.release == 'true'
86
- strategy:
87
- fail-fast: false
88
- matrix:
89
- include:
90
- - runner: windows-latest
91
- artifact: decryptune.dll
92
- rename: decryptune.pyd
93
- platform: windows-x86_64
94
- - runner: windows-11-arm
95
- artifact: decryptune.dll
96
- rename: decryptune.pyd
97
- platform: windows-aarch64
98
- runs-on: ${{ matrix.runner }}
52
+ runs-on: ubuntu-latest
99
53
  steps:
100
54
  - uses: actions/checkout@v4
101
55
  - uses: dtolnay/rust-toolchain@stable
102
- - run: cargo build --release
103
- - name: package binary + wrapper
104
- shell: bash
105
- run: |
106
- mkdir -p dist
107
- cp "target/release/${{ matrix.artifact }}" "dist/${{ matrix.rename || matrix.artifact }}"
108
- cp decryptune.py dist/
109
- cd dist
110
- python -m zipfile -c "decryptune-${{ matrix.platform }}.zip" "${{ matrix.rename || matrix.artifact }}" "decryptune.py"
111
- - uses: actions/upload-artifact@v4
112
- with:
113
- retention-days: 3
114
- name: bin-${{ matrix.platform }}
115
- path: dist/*.zip
56
+ # maturin develop needs a virtualenv — the runner's python is system-wide
57
+ - run: python3 -m venv .venv
58
+ - run: .venv/bin/pip install maturin pytest pycryptodome mutagen
59
+ - run: .venv/bin/maturin develop
60
+ # the checkout has no staged extension — test the installed wheel
61
+ - run: DECRYPTUNE_WHEEL=1 .venv/bin/python -m pytest tests/ -q
62
+ - run: cargo test --release
116
63
 
117
64
  # abi3 wheels: linux + windows (manylinux_2_28 for the widest glibc coverage)
118
65
  wheels:
@@ -164,7 +111,7 @@ jobs:
164
111
  path: dist/*.tar.gz
165
112
 
166
113
  release:
167
- needs: [verify, build-linux, build-native, wheels, sdist]
114
+ needs: [verify, test, wheels, sdist]
168
115
  if: ${{ !failure() && !cancelled() && needs.verify.outputs.release == 'true' }}
169
116
  runs-on: ubuntu-latest
170
117
  steps:
@@ -187,7 +134,7 @@ jobs:
187
134
  if gh release view "v$VERSION" --repo "$GITHUB_REPOSITORY" >/dev/null 2>&1; then
188
135
  gh release upload "v$VERSION" --repo "$GITHUB_REPOSITORY" --clobber rel/*
189
136
  else
190
- gh release create "v$VERSION" --repo "$GITHUB_REPOSITORY" --title "decryptune v$VERSION" --notes "decryptune v$VERSION — wheels + standalone binaries" rel/*
137
+ gh release create "v$VERSION" --repo "$GITHUB_REPOSITORY" --title "decryptune v$VERSION" --notes "decryptune v$VERSION — wheels for Linux and Windows + sdist" rel/*
191
138
  fi
192
139
 
193
140
  # PyPI: needs a Trusted Publisher configured on pypi.org
@@ -1,4 +1,5 @@
1
1
  # build artifacts
2
+ Cargo.lock
2
3
  target/
3
4
  build/
4
5
  dist/
@@ -68,12 +68,10 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.2"
71
+ version = "1.1.3"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
75
- "jpeg-decoder",
76
- "jpeg-encoder",
77
75
  "pyo3",
78
76
  "pyo3-async-runtimes",
79
77
  "tokio",
@@ -102,7 +100,7 @@ checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
102
100
  dependencies = [
103
101
  "proc-macro2",
104
102
  "quote",
105
- "syn 3.0.6",
103
+ "syn 3.0.9",
106
104
  ]
107
105
 
108
106
  [[package]]
@@ -141,30 +139,18 @@ dependencies = [
141
139
 
142
140
  [[package]]
143
141
  name = "inout"
144
- version = "0.2.2"
142
+ version = "0.2.4"
145
143
  source = "registry+https://github.com/rust-lang/crates.io-index"
146
- checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
144
+ checksum = "3ce983bb6fb399067d101fbfc9e74174e07e9f29a2bc679efefeb8c645819c3f"
147
145
  dependencies = [
148
146
  "hybrid-array",
149
147
  ]
150
148
 
151
- [[package]]
152
- name = "jpeg-decoder"
153
- version = "0.3.2"
154
- source = "registry+https://github.com/rust-lang/crates.io-index"
155
- checksum = "00810f1d8b74be64b13dbf3db89ac67740615d6c891f0e7b6179326533011a07"
156
-
157
- [[package]]
158
- name = "jpeg-encoder"
159
- version = "0.7.1"
160
- source = "registry+https://github.com/rust-lang/crates.io-index"
161
- checksum = "a0370574b86f7eca156b9f298392b5e69a23f8c86f3f865add60bbc2e79467a6"
162
-
163
149
  [[package]]
164
150
  name = "libc"
165
- version = "0.2.189"
151
+ version = "0.2.191"
166
152
  source = "registry+https://github.com/rust-lang/crates.io-index"
167
- checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
153
+ checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
168
154
 
169
155
  [[package]]
170
156
  name = "once_cell"
@@ -195,9 +181,9 @@ dependencies = [
195
181
 
196
182
  [[package]]
197
183
  name = "pyo3"
198
- version = "0.29.2"
184
+ version = "0.29.3"
199
185
  source = "registry+https://github.com/rust-lang/crates.io-index"
200
- checksum = "4688ddedf473e32662b9b067670129a8afb8c18e351482c70d62ba4a88171e8b"
186
+ checksum = "700d18fa267b73b9b521fd7e13580e2f446916f176cacee1ab63fcc8191f1655"
201
187
  dependencies = [
202
188
  "libc",
203
189
  "once_cell",
@@ -223,18 +209,18 @@ dependencies = [
223
209
 
224
210
  [[package]]
225
211
  name = "pyo3-build-config"
226
- version = "0.29.2"
212
+ version = "0.29.3"
227
213
  source = "registry+https://github.com/rust-lang/crates.io-index"
228
- checksum = "f41027e41b4bd03f6e60f9f417fe24a6341a6bb744edd62b6f709f2a52ea30e9"
214
+ checksum = "7b3fc0c4d08f6bb10e71fe39dfb9e2f59c6eb6854e22ec8092f50c69a4499adb"
229
215
  dependencies = [
230
216
  "target-lexicon",
231
217
  ]
232
218
 
233
219
  [[package]]
234
220
  name = "pyo3-ffi"
235
- version = "0.29.2"
221
+ version = "0.29.3"
236
222
  source = "registry+https://github.com/rust-lang/crates.io-index"
237
- checksum = "e591a95526fead067432c3b3a33fc74770b87b1e04e73671090d9c2055a2b327"
223
+ checksum = "dfc0b8e19df29aad7086cf977bb0c2a2f143e30567eb113e9cf72b62ca698330"
238
224
  dependencies = [
239
225
  "libc",
240
226
  "pyo3-build-config",
@@ -242,9 +228,9 @@ dependencies = [
242
228
 
243
229
  [[package]]
244
230
  name = "pyo3-macros"
245
- version = "0.29.2"
231
+ version = "0.29.3"
246
232
  source = "registry+https://github.com/rust-lang/crates.io-index"
247
- checksum = "73225868fc1cd84eef2c3c230ddb91273bf1de46aeb8a4248da76d32a0924a1c"
233
+ checksum = "6100e8a4b5eba53afaa5ed078364851a0b2499c553a44c31026b929049b49dc6"
248
234
  dependencies = [
249
235
  "proc-macro2",
250
236
  "pyo3-macros-backend",
@@ -254,9 +240,9 @@ dependencies = [
254
240
 
255
241
  [[package]]
256
242
  name = "pyo3-macros-backend"
257
- version = "0.29.2"
243
+ version = "0.29.3"
258
244
  source = "registry+https://github.com/rust-lang/crates.io-index"
259
- checksum = "571575aa3749fa6216757dd47d2a3e7ef360f329a40f0666a9fbd14889024952"
245
+ checksum = "6143877a16e82b5a727b7127ff4cd86858a24a28d745d72f43e6f227c7b1bdb3"
260
246
  dependencies = [
261
247
  "heck",
262
248
  "proc-macro2",
@@ -292,9 +278,9 @@ dependencies = [
292
278
 
293
279
  [[package]]
294
280
  name = "syn"
295
- version = "3.0.6"
281
+ version = "3.0.9"
296
282
  source = "registry+https://github.com/rust-lang/crates.io-index"
297
- checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
283
+ checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
298
284
  dependencies = [
299
285
  "proc-macro2",
300
286
  "quote",
@@ -309,9 +295,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
309
295
 
310
296
  [[package]]
311
297
  name = "tokio"
312
- version = "1.53.1"
298
+ version = "1.53.3"
313
299
  source = "registry+https://github.com/rust-lang/crates.io-index"
314
- checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"
300
+ checksum = "ce3335fa71841cda333a58d7615b03901380ecf09d59b3296d21f8bbac0dde4e"
315
301
  dependencies = [
316
302
  "pin-project-lite",
317
303
  ]
@@ -324,6 +310,6 @@ checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
324
310
 
325
311
  [[package]]
326
312
  name = "unicode-ident"
327
- version = "1.0.26"
313
+ version = "1.0.27"
328
314
  source = "registry+https://github.com/rust-lang/crates.io-index"
329
- checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
315
+ checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.2"
3
+ version = "1.1.3"
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"
@@ -19,8 +19,6 @@ ctr = "0.10" # CTR mode, pairs with aes
19
19
  pyo3 = { version = "0.29", features = ["extension-module", "abi3-py312"] }
20
20
  pyo3-async-runtimes = { version = "0.29", features = ["tokio-runtime"] }
21
21
  tokio = { version = "1.53", features = ["rt-multi-thread", "fs"] }
22
- jpeg-decoder = { version = "0.3", default-features = false }
23
- jpeg-encoder = { version = "0.7", default-features = false, features = ["std"] }
24
22
 
25
23
  [profile.release]
26
24
  opt-level = 3
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: decryptune
3
- Version: 1.1.2
3
+ Version: 1.1.3
4
4
  Classifier: Development Status :: 5 - Production/Stable
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Programming Language :: Rust
@@ -25,16 +25,13 @@ Fast, native M4A (fMP4/CENC) decryptor + MP4 sanitizer + iTunes tagger in one li
25
25
  pip install decryptune
26
26
  ```
27
27
 
28
- **Standalone (no install)** — keep `decryptune.py` next to the extension binary and pass its path: `DecrypTune("./libdecryptune.so")`
29
-
30
- From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release` — this is also the macOS path (it builds and runs the same; prebuilt wheels and zips ship for Linux and Windows).
28
+ From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release` — this is also the macOS path (it builds and runs the same; prebuilt wheels ship for Linux and Windows).
31
29
 
32
30
  ## Usage
33
31
 
34
32
  ```python
35
33
  from decryptune import DecrypTune, TuneMeta
36
34
 
37
- # bundled native module (wheel) — or DecrypTune("./libdecryptune.so")
38
35
  sp = DecrypTune()
39
36
 
40
37
  sp.proc(
@@ -67,15 +64,18 @@ Rules that hold for both `proc` and `aproc`:
67
64
 
68
65
  ## Benchmark
69
66
 
70
- Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
67
+ Native Windows 11 (windows-x86_64 wheel), Intel i7-11800H (8C/16T), Python 3.13, real 3.0MB fragmented track:
71
68
 
72
69
  | scenario | result |
73
70
  |---|---|
74
- | decrypt + fix, strict (bytes in/out) | 3.7 ms median — ~0.8 GB/s |
75
- | fix-only pass (no key) | 1.7 ms |
76
- | full tags + cover resize (877KB JPEG) | 101 ms |
77
- | 32 calls: sequential → `asyncio.gather` | 74 ms → 29 ms (**×2.5**) |
78
- | event-loop max lag under 8 concurrent heavy calls | < 4 ms |
71
+ | decrypt + fix, strict (bytes in/out) | 3.0 ms median — ~1.0 GB/s |
72
+ | fix-only pass (no key) | 1.0 ms |
73
+ | full tags + cover resize (877KB JPEG) | 219 ms |
74
+ | 32 calls: sequential → `asyncio.gather` (bytes) | 97 ms → 30 ms (**×3.3**) |
75
+ | 32 calls with path out (real writes) | 46 ms (**×2.1**) |
76
+ | event-loop max lag under 8 concurrent heavy calls | < 15 ms (Windows timer granularity) |
77
+
78
+ Fragment work (decrypt + strict evidence check) spreads across cores on large files: a 128MB fragmented file runs decrypt+strict in ~0.1s.
79
79
 
80
80
  ## License
81
81
 
@@ -8,16 +8,13 @@ Fast, native M4A (fMP4/CENC) decryptor + MP4 sanitizer + iTunes tagger in one li
8
8
  pip install decryptune
9
9
  ```
10
10
 
11
- **Standalone (no install)** — keep `decryptune.py` next to the extension binary and pass its path: `DecrypTune("./libdecryptune.so")`
12
-
13
- From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release` — this is also the macOS path (it builds and runs the same; prebuilt wheels and zips ship for Linux and Windows).
11
+ From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release` — this is also the macOS path (it builds and runs the same; prebuilt wheels ship for Linux and Windows).
14
12
 
15
13
  ## Usage
16
14
 
17
15
  ```python
18
16
  from decryptune import DecrypTune, TuneMeta
19
17
 
20
- # bundled native module (wheel) — or DecrypTune("./libdecryptune.so")
21
18
  sp = DecrypTune()
22
19
 
23
20
  sp.proc(
@@ -50,15 +47,18 @@ Rules that hold for both `proc` and `aproc`:
50
47
 
51
48
  ## Benchmark
52
49
 
53
- Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
50
+ Native Windows 11 (windows-x86_64 wheel), Intel i7-11800H (8C/16T), Python 3.13, real 3.0MB fragmented track:
54
51
 
55
52
  | scenario | result |
56
53
  |---|---|
57
- | decrypt + fix, strict (bytes in/out) | 3.7 ms median — ~0.8 GB/s |
58
- | fix-only pass (no key) | 1.7 ms |
59
- | full tags + cover resize (877KB JPEG) | 101 ms |
60
- | 32 calls: sequential → `asyncio.gather` | 74 ms → 29 ms (**×2.5**) |
61
- | event-loop max lag under 8 concurrent heavy calls | < 4 ms |
54
+ | decrypt + fix, strict (bytes in/out) | 3.0 ms median — ~1.0 GB/s |
55
+ | fix-only pass (no key) | 1.0 ms |
56
+ | full tags + cover resize (877KB JPEG) | 219 ms |
57
+ | 32 calls: sequential → `asyncio.gather` (bytes) | 97 ms → 30 ms (**×3.3**) |
58
+ | 32 calls with path out (real writes) | 46 ms (**×2.1**) |
59
+ | event-loop max lag under 8 concurrent heavy calls | < 15 ms (Windows timer granularity) |
60
+
61
+ Fragment work (decrypt + strict evidence check) spreads across cores on large files: a 128MB fragmented file runs decrypt+strict in ~0.1s.
62
62
 
63
63
  ## License
64
64
 
@@ -1,14 +1,35 @@
1
1
  """decryptune — fast, native M4A/CENC decryptor + MP4 sanitizer + iTunes tagger.
2
2
 
3
- Wheel distribution: the native extension ships INSIDE this package and is
4
- fixed at install time — no paths, nothing to swap. For the standalone
5
- workflow (extension file + path) use the decryptune.py wrapper from the source
6
- tree. Keep this file in sync with it (same API surface, loader differs).
3
+ The native extension ships INSIDE the wheel and is fixed at install time —
4
+ no paths, nothing to swap. From a source checkout (no bundled binary) the
5
+ package falls back to the staged extension beside the repo root.
7
6
  """
8
7
 
9
- from . import decryptune as _native
10
-
11
- __version__ = "1.1.2"
8
+ import importlib.machinery
9
+ import importlib.util
10
+ from pathlib import Path
11
+
12
+ try:
13
+ from . import decryptune as _native
14
+ except ImportError:
15
+ # source checkout: load the staged extension from the repo root (or beside
16
+ # the package); the loader requires PyInit_decryptune, so the module keeps
17
+ # that name. The candidate order is platform-aware — the repo may stage
18
+ # builds for several platforms side by side.
19
+ import sys
20
+
21
+ _names: tuple[str, ...] = ("decryptune.pyd",) if sys.platform == "win32" else \
22
+ ("libdecryptune.dylib",) if sys.platform == "darwin" else ("libdecryptune.so",)
23
+ _pkg = Path(__file__).resolve().parent
24
+ _candidates = [base / n for base in (_pkg.parent.parent, _pkg.parent, _pkg) for n in _names]
25
+ _lib = next((p for p in _candidates if p.exists()), None)
26
+ if _lib is None:
27
+ raise
28
+ _loader = importlib.machinery.ExtensionFileLoader("decryptune", str(_lib))
29
+ _native = importlib.util.module_from_spec(importlib.util.spec_from_loader("decryptune", _loader))
30
+ _loader.exec_module(_native)
31
+
32
+ __version__ = "1.1.3"
12
33
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
13
34
 
14
35
 
@@ -43,9 +64,9 @@ def _to_err(exc: Exception) -> DecrypTuneError | None:
43
64
 
44
65
 
45
66
  class DecrypTune:
46
- """Interface to the decryptune native extension bundled in this wheel.
67
+ """Interface to the decryptune native extension.
47
68
 
48
- The native module is fixed at install time — DecrypTune takes no path.
69
+ The native module is fixed at import time — DecrypTune takes no path.
49
70
  """
50
71
 
51
72
  __slots__ = ("_lib",)
@@ -35,3 +35,39 @@ pub fn write_header(out: &mut Vec<u8>, typ: &[u8; 4], content_len: usize) {
35
35
  out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
36
36
  out.extend_from_slice(typ);
37
37
  }
38
+
39
+ // output sink — Buf writes into an exactly-sized buffer, Count only measures.
40
+ // The measure pass runs the identical walk with the same sizing decisions, so
41
+ // the buffer can never over- or under-fill.
42
+ pub enum Writer<'a> {
43
+ Buf { buf: &'a mut [u8], pos: usize },
44
+ Count(usize)
45
+ }
46
+
47
+ impl Writer<'_> {
48
+ pub fn len(&self) -> usize {
49
+ match self { Writer::Buf { pos, .. } => *pos, Writer::Count(n) => *n }
50
+ }
51
+
52
+ pub fn put(&mut self, bytes: &[u8]) {
53
+ match self {
54
+ Writer::Buf { buf, pos } => {
55
+ buf[*pos..*pos + bytes.len()].copy_from_slice(bytes);
56
+ *pos += bytes.len();
57
+ }
58
+ Writer::Count(n) => *n += bytes.len()
59
+ }
60
+ }
61
+
62
+ // 32-bit box header (size + fourcc)
63
+ pub fn header(&mut self, typ: &[u8; 4], content_len: usize) {
64
+ match self {
65
+ Writer::Buf { buf, pos } => {
66
+ buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
67
+ buf[*pos + 4..*pos + 8].copy_from_slice(typ);
68
+ *pos += 8;
69
+ }
70
+ Writer::Count(n) => *n += 8
71
+ }
72
+ }
73
+ }
@@ -1,9 +1,10 @@
1
1
  // Cover prep: oversized JPEGs → area-average downscale to 1000px, q90 re-encode;
2
- // fitting covers and PNGs pass through byte-identical (minimal deps, no `image` crate)
2
+ // fitting covers and PNGs pass through zero-copy (no `image` crate, no external
3
+ // JPEG codec — decode and encode both live in crate::jpeg)
3
4
 
4
- use jpeg_decoder::{Decoder, ImageInfo, PixelFormat};
5
- use jpeg_encoder::{Encoder, ColorType};
5
+ use std::borrow::Cow;
6
6
 
7
+ use crate::jpeg;
7
8
  use crate::meta::Cover;
8
9
  use crate::Err;
9
10
 
@@ -13,37 +14,21 @@ pub(crate) fn is_jpeg(b: &[u8]) -> bool { b.len() >= 2 && b[0] == 0xFF && b[1] =
13
14
  pub(crate) fn is_png(b: &[u8]) -> bool { b.len() >= 8 && b[0..4] == [0x89, 0x50, 0x4E, 0x47] }
14
15
 
15
16
  /// Validate and (when needed) downscale a cover image to fit MAX_EDGE.
16
- pub(crate) fn prepare(raw: &[u8]) -> Result<Cover, Err> {
17
+ pub(crate) fn prepare(raw: &[u8]) -> Result<Cover<'_>, Err> {
17
18
  if is_png(raw) {
18
- return Ok(Cover { data: raw.to_vec(), kind: 14 });
19
+ return Ok(Cover { data: Cow::Borrowed(raw), kind: 14 });
19
20
  }
20
21
  if !is_jpeg(raw) {
21
22
  return Err(Err::BadCover);
22
23
  }
23
24
 
24
- let mut decoder: Decoder<&[u8]> = Decoder::new(raw);
25
- let pixels: Vec<u8> = decoder.decode().map_err(|_| Err::BadCover)?;
26
- let info: ImageInfo = decoder.info().ok_or(Err::BadCover)?;
27
- let (w, h): (u32, u32) = (info.width as u32, info.height as u32);
28
- if w == 0 || h == 0 { return Err(Err::BadCover); }
29
-
30
- // already fits — the original bytes pass through untouched
31
- if w <= MAX_EDGE && h <= MAX_EDGE {
32
- return Ok(Cover { data: raw.to_vec(), kind: 13 });
33
- }
34
-
35
- let (nw, nh): (u32, u32) = fit(w, h, MAX_EDGE);
36
- match info.pixel_format {
37
- PixelFormat::L8 => {
38
- let scaled = resize_area(&pixels, w, h, 1, nw, nh);
39
- Ok(Cover { data: encode_jpeg(&scaled, nw, nh, ColorType::Luma)?, kind: 13 })
40
- }
41
- PixelFormat::RGB24 => {
42
- let scaled = resize_area(&pixels, w, h, 3, nw, nh);
43
- Ok(Cover { data: encode_jpeg(&scaled, nw, nh, ColorType::Rgb)?, kind: 13 })
44
- }
45
- _ => Err(Err::BadCover), // CMYK covers are beyond scope
25
+ let (w, h, ch, pixels): (usize, usize, usize, Vec<u8>) = jpeg::decode(raw)?;
26
+ if w <= MAX_EDGE as usize && h <= MAX_EDGE as usize {
27
+ return Ok(Cover { data: Cow::Borrowed(raw), kind: 13 }); // fits — original bytes untouched
46
28
  }
29
+ let (nw, nh): (u32, u32) = fit(w as u32, h as u32, MAX_EDGE);
30
+ let scaled: Vec<u8> = resize_area(&pixels, w as u32, h as u32, ch, nw, nh);
31
+ Ok(Cover { data: Cow::Owned(jpeg::encode(&scaled, nw as usize, nh as usize, ch)?), kind: 13 })
47
32
  }
48
33
 
49
34
  /// Longest-edge fit: (nw, nh) ≤ max_edge preserving aspect ratio.
@@ -80,13 +65,3 @@ fn resize_area(src: &[u8], sw: u32, sh: u32, ch: usize, dw: u32, dh: u32) -> Vec
80
65
  }
81
66
  out
82
67
  }
83
-
84
- fn encode_jpeg(pixels: &[u8], w: u32, h: u32, color: ColorType) -> Result<Vec<u8>, Err> {
85
- let mut out: Vec<u8> = Vec::new();
86
- // q90 — visually lossless at 1000px; q100 bloats photographic covers ~3.5x
87
- let encoder: Encoder<&mut Vec<u8>> = Encoder::new(&mut out, 90);
88
- encoder
89
- .encode(pixels, w as u16, h as u16, color)
90
- .map_err(|_| Err::BadCover)?;
91
- Ok(out)
92
- }
@@ -0,0 +1,49 @@
1
+ // Stable numeric error-code contract — messages are authored here and relayed
2
+ // by Python as "[code] + message" verbatim.
3
+
4
+ use pyo3::exceptions::PyException;
5
+ use pyo3::prelude::*;
6
+
7
+ #[derive(Debug, Clone, Copy)]
8
+ #[allow(dead_code)] // DecryptFailed is part of the stable error-code contract
9
+ pub(crate) enum Err {
10
+ InvalidKey = 1,
11
+ InvalidKid = 2,
12
+ InputNotFound = 3,
13
+ InvalidMp4 = 4,
14
+ DecryptFailed = 5,
15
+ WriteFailed = 6,
16
+ KidMismatch = 7,
17
+ CorruptDetected = 8,
18
+ BadInput = 9,
19
+ BadOutput = 10,
20
+ MetaNeedsFragmented = 11,
21
+ BadCover = 12,
22
+ CoverNotFound = 13 // additive: a missing cover path must not read as a missing input
23
+ }
24
+
25
+ impl Err {
26
+ pub(crate) fn msg(self) -> &'static str {
27
+ match self {
28
+ Err::InvalidKey => "invalid key: must be 32 hex characters",
29
+ Err::InvalidKid => "invalid kid: must be 32 hex characters",
30
+ Err::InputNotFound => "input file not found",
31
+ Err::CoverNotFound => "cover file not found",
32
+ Err::InvalidMp4 => "input is not a valid MP4",
33
+ Err::DecryptFailed => "decrypt failed: corrupt or unsupported fragment",
34
+ Err::WriteFailed => "failed to write output file",
35
+ Err::KidMismatch => "key does not match this file (KID mismatch)",
36
+ Err::CorruptDetected => "decrypted audio is corrupt (wrong or fake key)",
37
+ Err::BadInput => "invalid input: expected bytes, bytearray, memoryview, or a path",
38
+ Err::BadOutput => "invalid out: expected a path or None",
39
+ Err::MetaNeedsFragmented => "metadata write requires a fragmented file (non-empty chunk offsets)",
40
+ Err::BadCover => "unsupported cover format: expected JPEG or PNG"
41
+ }
42
+ }
43
+ }
44
+
45
+ impl From<Err> for PyErr {
46
+ fn from(e: Err) -> PyErr {
47
+ PyException::new_err(format!("[{}] {}", e as i32, e.msg()))
48
+ }
49
+ }