decryptune 1.0.0__tar.gz → 1.1.1__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.
- {decryptune-1.0.0 → decryptune-1.1.1}/Cargo.lock +1 -1
- {decryptune-1.0.0 → decryptune-1.1.1}/Cargo.toml +1 -1
- {decryptune-1.0.0 → decryptune-1.1.1}/PKG-INFO +15 -26
- {decryptune-1.0.0 → decryptune-1.1.1}/README.md +14 -25
- {decryptune-1.0.0 → decryptune-1.1.1}/decryptune.py +12 -7
- {decryptune-1.0.0 → decryptune-1.1.1}/python/decryptune/__init__.py +11 -6
- {decryptune-1.0.0 → decryptune-1.1.1}/src/lib.rs +66 -30
- {decryptune-1.0.0 → decryptune-1.1.1}/src/meta.rs +6 -10
- {decryptune-1.0.0 → decryptune-1.1.1}/src/process.rs +7 -8
- {decryptune-1.0.0 → decryptune-1.1.1}/tests/test_decryptune.py +50 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/.gitattributes +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/.github/workflows/build.yml +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/.gitignore +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/LICENSE +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/pyproject.toml +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/src/boxes.rs +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/src/cover.rs +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/tests/fixtures/big.jpg +0 -0
- {decryptune-1.0.0 → decryptune-1.1.1}/tests/fixtures/tiny.jpg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: decryptune
|
|
3
|
-
Version: 1.
|
|
3
|
+
Version: 1.1.1
|
|
4
4
|
Classifier: Development Status :: 5 - Production/Stable
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: Programming Language :: Rust
|
|
@@ -21,20 +21,13 @@ Fast, native M4A (fMP4/CENC) decryptor + MP4 sanitizer + iTunes tagger in one li
|
|
|
21
21
|
|
|
22
22
|
## Install
|
|
23
23
|
|
|
24
|
-
**Wheel (recommended)** — the native module ships inside the package, fixed at install time:
|
|
25
|
-
|
|
26
24
|
```bash
|
|
27
|
-
pip install decryptune
|
|
25
|
+
pip install decryptune
|
|
28
26
|
```
|
|
29
27
|
|
|
30
|
-
**Standalone (no install)** — keep `decryptune.py` next to the extension binary:
|
|
28
|
+
**Standalone (no install)** — keep `decryptune.py` next to the extension binary and pass its path: `DecrypTune("./libdecryptune.so")`
|
|
31
29
|
|
|
32
|
-
|
|
33
|
-
from decryptune import DecrypTune
|
|
34
|
-
sp = DecrypTune("./libdecryptune.so")
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release`
|
|
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).
|
|
38
31
|
|
|
39
32
|
## Usage
|
|
40
33
|
|
|
@@ -57,7 +50,7 @@ sp.proc(
|
|
|
57
50
|
# date=..., album=..., genre=..., lyrics=..., composer=...,
|
|
58
51
|
# track=..., track_total=..., disc=..., disc_total=...
|
|
59
52
|
),
|
|
60
|
-
strict=True
|
|
53
|
+
strict=True # raise (code 8, per-fragment chi² evidence) when a fragment
|
|
61
54
|
) # decrypts to statistical noise — a wrong/fake key
|
|
62
55
|
|
|
63
56
|
# async twin — same options, same result:
|
|
@@ -70,23 +63,19 @@ Rules that hold for both `proc` and `aproc`:
|
|
|
70
63
|
- `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
|
|
71
64
|
- `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
|
|
72
65
|
- 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.
|
|
73
|
-
- Any problem raises `DecrypTuneError` with a stable numeric code (1–
|
|
74
|
-
|
|
75
|
-
## Build
|
|
66
|
+
- Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
|
|
76
67
|
|
|
77
|
-
|
|
78
|
-
cargo build --release && cp target/release/libdecryptune.so .
|
|
79
|
-
maturin build --release # → target/wheels/*.whl
|
|
80
|
-
```
|
|
81
|
-
|
|
82
|
-
## Tests
|
|
68
|
+
## Benchmark
|
|
83
69
|
|
|
84
|
-
|
|
85
|
-
python3 -m pytest tests/
|
|
86
|
-
DECRYPTUNE_WHEEL=1 python3 -m pytest tests/ # against the installed wheel
|
|
87
|
-
```
|
|
70
|
+
Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
|
|
88
71
|
|
|
89
|
-
|
|
72
|
+
| scenario | result |
|
|
73
|
+
|---|---|
|
|
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 |
|
|
90
79
|
|
|
91
80
|
## License
|
|
92
81
|
|
|
@@ -4,20 +4,13 @@ Fast, native M4A (fMP4/CENC) decryptor + MP4 sanitizer + iTunes tagger in one li
|
|
|
4
4
|
|
|
5
5
|
## Install
|
|
6
6
|
|
|
7
|
-
**Wheel (recommended)** — the native module ships inside the package, fixed at install time:
|
|
8
|
-
|
|
9
7
|
```bash
|
|
10
|
-
pip install decryptune
|
|
8
|
+
pip install decryptune
|
|
11
9
|
```
|
|
12
10
|
|
|
13
|
-
**Standalone (no install)** — keep `decryptune.py` next to the extension binary:
|
|
11
|
+
**Standalone (no install)** — keep `decryptune.py` next to the extension binary and pass its path: `DecrypTune("./libdecryptune.so")`
|
|
14
12
|
|
|
15
|
-
|
|
16
|
-
from decryptune import DecrypTune
|
|
17
|
-
sp = DecrypTune("./libdecryptune.so")
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
From source (needs Rust 1.85+ and Python 3.12+): `pip install maturin && maturin build --release`
|
|
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).
|
|
21
14
|
|
|
22
15
|
## Usage
|
|
23
16
|
|
|
@@ -40,7 +33,7 @@ sp.proc(
|
|
|
40
33
|
# date=..., album=..., genre=..., lyrics=..., composer=...,
|
|
41
34
|
# track=..., track_total=..., disc=..., disc_total=...
|
|
42
35
|
),
|
|
43
|
-
strict=True
|
|
36
|
+
strict=True # raise (code 8, per-fragment chi² evidence) when a fragment
|
|
44
37
|
) # decrypts to statistical noise — a wrong/fake key
|
|
45
38
|
|
|
46
39
|
# async twin — same options, same result:
|
|
@@ -53,23 +46,19 @@ Rules that hold for both `proc` and `aproc`:
|
|
|
53
46
|
- `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
|
|
54
47
|
- `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
|
|
55
48
|
- 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.
|
|
56
|
-
- Any problem raises `DecrypTuneError` with a stable numeric code (1–
|
|
57
|
-
|
|
58
|
-
## Build
|
|
49
|
+
- Any problem raises `DecrypTuneError` with a stable numeric code (1–13) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found.
|
|
59
50
|
|
|
60
|
-
|
|
61
|
-
cargo build --release && cp target/release/libdecryptune.so .
|
|
62
|
-
maturin build --release # → target/wheels/*.whl
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
## Tests
|
|
51
|
+
## Benchmark
|
|
66
52
|
|
|
67
|
-
|
|
68
|
-
python3 -m pytest tests/
|
|
69
|
-
DECRYPTUNE_WHEEL=1 python3 -m pytest tests/ # against the installed wheel
|
|
70
|
-
```
|
|
53
|
+
Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
|
|
71
54
|
|
|
72
|
-
|
|
55
|
+
| scenario | result |
|
|
56
|
+
|---|---|
|
|
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 |
|
|
73
62
|
|
|
74
63
|
## License
|
|
75
64
|
|
|
@@ -16,7 +16,7 @@ from importlib.machinery import ModuleSpec
|
|
|
16
16
|
from importlib.util import module_from_spec, spec_from_file_location
|
|
17
17
|
from types import ModuleType
|
|
18
18
|
|
|
19
|
-
__version__ = "1.
|
|
19
|
+
__version__ = "1.1.1"
|
|
20
20
|
__all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
|
|
21
21
|
|
|
22
22
|
|
|
@@ -37,8 +37,9 @@ class DecrypTuneError(Exception):
|
|
|
37
37
|
return f"DecrypTuneError(code={self.code}, message={self.message!r})"
|
|
38
38
|
|
|
39
39
|
|
|
40
|
-
# all error messages are authored by the native core — this wrapper relays [code] + message
|
|
41
|
-
|
|
40
|
+
# all error messages are authored by the native core — this wrapper relays [code] + message;
|
|
41
|
+
# anything without a [N] prefix is not a native error and propagates unchanged
|
|
42
|
+
def _to_err(exc: Exception) -> DecrypTuneError | None:
|
|
42
43
|
msg: str = str(exc)
|
|
43
44
|
end: int = msg.find("]")
|
|
44
45
|
if msg.startswith("[") and end != -1:
|
|
@@ -46,7 +47,7 @@ def _to_err(exc: Exception) -> DecrypTuneError:
|
|
|
46
47
|
return DecrypTuneError(int(msg[1:end]), msg[end + 1:].strip())
|
|
47
48
|
except ValueError:
|
|
48
49
|
pass
|
|
49
|
-
return
|
|
50
|
+
return None
|
|
50
51
|
|
|
51
52
|
|
|
52
53
|
_loaded: ModuleType | None = None # one native module per process — its pyclass
|
|
@@ -75,7 +76,7 @@ class DecrypTune:
|
|
|
75
76
|
"""Interface to the decryptune native extension.
|
|
76
77
|
|
|
77
78
|
Args:
|
|
78
|
-
lib_path: path to the compiled extension (.so on Linux
|
|
79
|
+
lib_path: path to the compiled extension (.so on Linux, .pyd on Windows)
|
|
79
80
|
"""
|
|
80
81
|
|
|
81
82
|
__slots__ = ("_lib",)
|
|
@@ -117,7 +118,9 @@ class DecrypTune:
|
|
|
117
118
|
try:
|
|
118
119
|
return self._lib.proc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
|
|
119
120
|
except Exception as e:
|
|
120
|
-
|
|
121
|
+
if (err := _to_err(e)) is not None:
|
|
122
|
+
raise err from None
|
|
123
|
+
raise
|
|
121
124
|
|
|
122
125
|
async def aproc(
|
|
123
126
|
self,
|
|
@@ -140,7 +143,9 @@ class DecrypTune:
|
|
|
140
143
|
try:
|
|
141
144
|
return await self._lib.aproc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
|
|
142
145
|
except Exception as e:
|
|
143
|
-
|
|
146
|
+
if (err := _to_err(e)) is not None:
|
|
147
|
+
raise err from None
|
|
148
|
+
raise
|
|
144
149
|
|
|
145
150
|
|
|
146
151
|
def TuneMeta(
|
|
@@ -8,7 +8,7 @@ tree. Keep this file in sync with it (same API surface, loader differs).
|
|
|
8
8
|
|
|
9
9
|
from . import decryptune as _native
|
|
10
10
|
|
|
11
|
-
__version__ = "1.
|
|
11
|
+
__version__ = "1.1.1"
|
|
12
12
|
__all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
|
|
13
13
|
|
|
14
14
|
|
|
@@ -29,8 +29,9 @@ class DecrypTuneError(Exception):
|
|
|
29
29
|
return f"DecrypTuneError(code={self.code}, message={self.message!r})"
|
|
30
30
|
|
|
31
31
|
|
|
32
|
-
# all error messages are authored by the native core — this wrapper relays [code] + message
|
|
33
|
-
|
|
32
|
+
# all error messages are authored by the native core — this wrapper relays [code] + message;
|
|
33
|
+
# anything without a [N] prefix is not a native error and propagates unchanged
|
|
34
|
+
def _to_err(exc: Exception) -> DecrypTuneError | None:
|
|
34
35
|
msg: str = str(exc)
|
|
35
36
|
end: int = msg.find("]")
|
|
36
37
|
if msg.startswith("[") and end != -1:
|
|
@@ -38,7 +39,7 @@ def _to_err(exc: Exception) -> DecrypTuneError:
|
|
|
38
39
|
return DecrypTuneError(int(msg[1:end]), msg[end + 1:].strip())
|
|
39
40
|
except ValueError:
|
|
40
41
|
pass
|
|
41
|
-
return
|
|
42
|
+
return None
|
|
42
43
|
|
|
43
44
|
|
|
44
45
|
class DecrypTune:
|
|
@@ -86,7 +87,9 @@ class DecrypTune:
|
|
|
86
87
|
try:
|
|
87
88
|
return self._lib.proc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
|
|
88
89
|
except Exception as e:
|
|
89
|
-
|
|
90
|
+
if (err := _to_err(e)) is not None:
|
|
91
|
+
raise err from None
|
|
92
|
+
raise
|
|
90
93
|
|
|
91
94
|
async def aproc(
|
|
92
95
|
self,
|
|
@@ -109,7 +112,9 @@ class DecrypTune:
|
|
|
109
112
|
try:
|
|
110
113
|
return await self._lib.aproc(input=input, out=out, key=key, kid=kid, meta=meta, strict=strict)
|
|
111
114
|
except Exception as e:
|
|
112
|
-
|
|
115
|
+
if (err := _to_err(e)) is not None:
|
|
116
|
+
raise err from None
|
|
117
|
+
raise
|
|
113
118
|
|
|
114
119
|
|
|
115
120
|
def TuneMeta(
|
|
@@ -42,7 +42,8 @@ enum Err {
|
|
|
42
42
|
BadInput = 9,
|
|
43
43
|
BadOutput = 10,
|
|
44
44
|
MetaNeedsFragmented = 11,
|
|
45
|
-
BadCover = 12
|
|
45
|
+
BadCover = 12,
|
|
46
|
+
CoverNotFound = 13 // additive: a missing cover path must not read as a missing input
|
|
46
47
|
}
|
|
47
48
|
|
|
48
49
|
impl Err {
|
|
@@ -51,6 +52,7 @@ impl Err {
|
|
|
51
52
|
Err::InvalidKey => "invalid key: must be 32 hex characters",
|
|
52
53
|
Err::InvalidKid => "invalid kid: must be 32 hex characters",
|
|
53
54
|
Err::InputNotFound => "input file not found",
|
|
55
|
+
Err::CoverNotFound => "cover file not found",
|
|
54
56
|
Err::InvalidMp4 => "input is not a valid MP4",
|
|
55
57
|
Err::DecryptFailed => "decrypt failed: corrupt or unsupported fragment",
|
|
56
58
|
Err::WriteFailed => "failed to write output file",
|
|
@@ -92,44 +94,86 @@ fn guard_kid(data: &[u8], kid: Option<&str>) -> Result<(), Err> {
|
|
|
92
94
|
}
|
|
93
95
|
|
|
94
96
|
// unique temp name — two concurrent writers to the same output must not collide
|
|
97
|
+
// (counter + pid: uniqueness across processes too, not just within one)
|
|
95
98
|
fn tmp_path(out_path: &str) -> String {
|
|
96
99
|
static N: AtomicU64 = AtomicU64::new(0);
|
|
97
|
-
format!("{}.{}.tmp", out_path, N.fetch_add(1, Ordering::Relaxed))
|
|
100
|
+
format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
|
|
98
101
|
}
|
|
99
102
|
|
|
100
|
-
// write to <out>.<n>.tmp then rename — no partial outputs on crash
|
|
103
|
+
// write to <out>.<n>.tmp then rename — no partial outputs on crash;
|
|
104
|
+
// a failed rename removes the tmp file (no litter in the output directory)
|
|
101
105
|
fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
|
|
102
106
|
let tmp: String = tmp_path(out_path);
|
|
103
107
|
std::fs::write(&tmp, data).map_err(|_| Err::WriteFailed)?;
|
|
104
|
-
std::fs::rename(&tmp, out_path).
|
|
108
|
+
if std::fs::rename(&tmp, out_path).is_err() {
|
|
109
|
+
let _ = std::fs::remove_file(&tmp);
|
|
110
|
+
return Err(Err::WriteFailed);
|
|
111
|
+
}
|
|
112
|
+
Ok(())
|
|
105
113
|
}
|
|
106
114
|
|
|
107
|
-
|
|
115
|
+
// the shared bytes/path dispatch: bytes | bytearray | str path | __fspath__ | memoryview
|
|
116
|
+
enum Extracted {
|
|
117
|
+
Bytes(Vec<u8>),
|
|
118
|
+
Path(String)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
fn extract_bytes_or_path(value: &Bound<'_, PyAny>, bad: Err) -> PyResult<Extracted> {
|
|
108
122
|
Ok(if let Ok(b) = value.cast::<PyBytes>() {
|
|
109
|
-
|
|
123
|
+
Extracted::Bytes(b.as_bytes().to_vec())
|
|
110
124
|
} else if let Ok(b) = value.cast::<PyByteArray>() {
|
|
111
|
-
|
|
125
|
+
Extracted::Bytes(b.to_vec())
|
|
112
126
|
} else if let Ok(s) = value.cast::<PyString>() {
|
|
113
|
-
|
|
127
|
+
Extracted::Path(s.to_str()?.to_string())
|
|
114
128
|
} else if let Ok(p) = value.call_method0("__fspath__") { // os.PathLike
|
|
115
|
-
|
|
129
|
+
// fspath may legally return bytes — map that here, never a raw downcast error
|
|
130
|
+
Extracted::Path(if let Ok(s) = p.cast::<PyString>() {
|
|
131
|
+
s.to_str()?.to_string()
|
|
132
|
+
} else if let Ok(b) = p.cast::<PyBytes>() {
|
|
133
|
+
String::from_utf8_lossy(b.as_bytes()).into_owned()
|
|
134
|
+
} else {
|
|
135
|
+
return Err(bad.into());
|
|
136
|
+
})
|
|
116
137
|
} else {
|
|
117
138
|
// exotic buffer (memoryview, …) — abi3 has no PyBuffer; memoryview()
|
|
118
139
|
// accepts only real buffer objects (bytes(123) would mean 123 zero bytes!)
|
|
119
140
|
match value.py().import("builtins")?.getattr("memoryview")?.call1((value,)) {
|
|
120
141
|
Ok(mv) => {
|
|
121
142
|
let b = mv.call_method0("tobytes")?;
|
|
122
|
-
|
|
143
|
+
Extracted::Bytes(b.cast::<PyBytes>()?.as_bytes().to_vec())
|
|
123
144
|
}
|
|
124
|
-
Err(_) => return Err(
|
|
145
|
+
Err(_) => return Err(bad.into()),
|
|
125
146
|
}
|
|
126
147
|
})
|
|
127
148
|
}
|
|
128
149
|
|
|
150
|
+
fn parse_input(value: &Bound<'_, PyAny>) -> PyResult<Input> {
|
|
151
|
+
Ok(match extract_bytes_or_path(value, Err::BadInput)? {
|
|
152
|
+
Extracted::Bytes(b) => Input::Bytes(b),
|
|
153
|
+
Extracted::Path(p) => Input::Path(p)
|
|
154
|
+
})
|
|
155
|
+
}
|
|
156
|
+
|
|
129
157
|
fn parse_output(out: Option<&Bound<'_, PyAny>>) -> PyResult<Output> {
|
|
130
158
|
match out {
|
|
131
|
-
None
|
|
132
|
-
Some(v) =>
|
|
159
|
+
None => Ok(Output::Return),
|
|
160
|
+
Some(v) => {
|
|
161
|
+
let path: String = if let Ok(s) = v.cast::<PyString>() {
|
|
162
|
+
s.to_str()?.to_string()
|
|
163
|
+
} else if let Ok(p) = v.call_method0("__fspath__") { // os.PathLike
|
|
164
|
+
// same fspath-bytes rule as input — a coded error, not a raw downcast
|
|
165
|
+
if let Ok(s) = p.cast::<PyString>() {
|
|
166
|
+
s.to_str()?.to_string()
|
|
167
|
+
} else if let Ok(b) = p.cast::<PyBytes>() {
|
|
168
|
+
String::from_utf8_lossy(b.as_bytes()).into_owned()
|
|
169
|
+
} else {
|
|
170
|
+
return Err(Err::BadOutput.into());
|
|
171
|
+
}
|
|
172
|
+
} else {
|
|
173
|
+
return Err(Err::BadOutput.into());
|
|
174
|
+
};
|
|
175
|
+
Ok(Output::Path(path))
|
|
176
|
+
}
|
|
133
177
|
}
|
|
134
178
|
}
|
|
135
179
|
|
|
@@ -202,6 +246,7 @@ struct TuneMeta {
|
|
|
202
246
|
#[pymethods]
|
|
203
247
|
impl TuneMeta {
|
|
204
248
|
#[new]
|
|
249
|
+
#[allow(clippy::too_many_arguments)] // 13 optional tag fields are the public API
|
|
205
250
|
#[pyo3(signature = (title=None, date=None, artists=None, isrc=None,
|
|
206
251
|
track=None, track_total=None, disc=None, disc_total=None,
|
|
207
252
|
album=None, genre=None, lyrics=None, composer=None, cover=None))]
|
|
@@ -232,22 +277,10 @@ fn resolve_meta(py: Python<'_>, meta: Option<&TuneMeta>) -> PyResult<Option<meta
|
|
|
232
277
|
let Some(m) = meta else { return Ok(None) };
|
|
233
278
|
let cover: Option<meta::RawCover> = match &m.cover {
|
|
234
279
|
None => None,
|
|
235
|
-
Some(obj) => {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
else if let Ok(s) = bound.cast::<PyString>() { meta::RawCover::Path(s.to_str()?.to_string()) }
|
|
240
|
-
else if let Ok(p) = bound.call_method0("__fspath__") { meta::RawCover::Path(p.cast::<PyString>()?.to_str()?.to_string()) }
|
|
241
|
-
else {
|
|
242
|
-
match py.import("builtins")?.getattr("memoryview")?.call1((bound,)) {
|
|
243
|
-
Ok(mv) => {
|
|
244
|
-
let b = mv.call_method0("tobytes")?;
|
|
245
|
-
meta::RawCover::Bytes(b.cast::<PyBytes>()?.as_bytes().to_vec())
|
|
246
|
-
}
|
|
247
|
-
Err(_) => return Err(Err::BadCover.into())
|
|
248
|
-
}
|
|
249
|
-
})
|
|
250
|
-
}
|
|
280
|
+
Some(obj) => Some(match extract_bytes_or_path(obj.bind(py), Err::BadCover)? {
|
|
281
|
+
Extracted::Bytes(b) => meta::RawCover::Bytes(b),
|
|
282
|
+
Extracted::Path(p) => meta::RawCover::Path(p)
|
|
283
|
+
})
|
|
251
284
|
};
|
|
252
285
|
let non_zero: fn(Option<u32>) -> Option<u32> = |v| v.filter(|n| *n > 0);
|
|
253
286
|
let non_empty: fn(&Option<String>) -> Option<String> = |v| v.clone().filter(|s| !s.is_empty());
|
|
@@ -332,7 +365,10 @@ fn aproc<'py>(
|
|
|
332
365
|
Output::Path(p) => {
|
|
333
366
|
let tmp: String = tmp_path(&p);
|
|
334
367
|
tokio::fs::write(&tmp, &processed.data).await.map_err(|_| Err::WriteFailed)?;
|
|
335
|
-
tokio::fs::rename(&tmp, &p).await.
|
|
368
|
+
if tokio::fs::rename(&tmp, &p).await.is_err() {
|
|
369
|
+
let _ = tokio::fs::remove_file(&tmp).await; // no tmp litter on a failed rename
|
|
370
|
+
return Err(Err::WriteFailed.into());
|
|
371
|
+
}
|
|
336
372
|
Ok(None)
|
|
337
373
|
}
|
|
338
374
|
Output::Return => Ok(Some(processed.data))
|
|
@@ -22,7 +22,7 @@ impl RawCover {
|
|
|
22
22
|
fn materialize(&self) -> Result<Cow<'_, [u8]>, Err> {
|
|
23
23
|
match self {
|
|
24
24
|
RawCover::Bytes(b) => Ok(Cow::Borrowed(b)),
|
|
25
|
-
RawCover::Path(p) => std::fs::read(p).map(Cow::Owned).map_err(|_| Err::
|
|
25
|
+
RawCover::Path(p) => std::fs::read(p).map(Cow::Owned).map_err(|_| Err::CoverNotFound)
|
|
26
26
|
}
|
|
27
27
|
}
|
|
28
28
|
}
|
|
@@ -112,12 +112,6 @@ fn build_items(meta: &CoreMeta) -> Result<Vec<u8>, Err> {
|
|
|
112
112
|
Ok(out)
|
|
113
113
|
}
|
|
114
114
|
|
|
115
|
-
// metadata is written from scratch: any pre-existing ilst is wiped and
|
|
116
|
-
// rebuilt solely from the caller's TuneMeta (deterministic, no merging)
|
|
117
|
-
fn fresh_ilst(meta: &CoreMeta) -> Result<Vec<u8>, Err> {
|
|
118
|
-
build_items(meta)
|
|
119
|
-
}
|
|
120
|
-
|
|
121
115
|
fn meta_box(ilst: &[u8]) -> Vec<u8> {
|
|
122
116
|
// hdlr in full ISO form (with pre_defined) — the Windows handler bails on short ones
|
|
123
117
|
let mut hdlr: Vec<u8> = Vec::new();
|
|
@@ -140,15 +134,17 @@ fn meta_box(ilst: &[u8]) -> Vec<u8> {
|
|
|
140
134
|
out
|
|
141
135
|
}
|
|
142
136
|
|
|
143
|
-
//
|
|
144
|
-
//
|
|
137
|
+
// metadata is written from scratch: any pre-existing ilst is wiped and rebuilt
|
|
138
|
+
// solely from the caller's TuneMeta (deterministic, no merging); the fresh
|
|
139
|
+
// udta/meta/ilst subtree goes first in moov — any pre-existing udta (with its
|
|
140
|
+
// ilst) is removed entirely
|
|
145
141
|
pub(crate) fn rebuild_moov_with_meta(children: &[u8], meta: &CoreMeta) -> Result<Vec<u8>, Err> {
|
|
146
142
|
// every old udta goes — keeping any would both leak stale tags and shadow the
|
|
147
143
|
// fresh subtree for the Windows handler (it reads only the first udta/meta)
|
|
148
144
|
let udta: Vec<(usize, usize)> = parse(children, 0, children.len())
|
|
149
145
|
.iter().filter(|c| c.is(b"udta")).map(|c| (c.start, c.end)).collect();
|
|
150
146
|
|
|
151
|
-
let new_meta: Vec<u8> = meta_box(&
|
|
147
|
+
let new_meta: Vec<u8> = meta_box(&build_items(meta)?);
|
|
152
148
|
|
|
153
149
|
// udta goes first in moov — the Windows MP4 handler reads only the first udta/meta subtree
|
|
154
150
|
let mut out: Vec<u8> = Vec::with_capacity(children.len() + new_meta.len());
|
|
@@ -87,11 +87,11 @@ pub fn process(data: &[u8], key: Option<&[u8; 16]>, strict: bool, meta: Option<&
|
|
|
87
87
|
// patch sidx referenced sizes in place, now that fragment deltas are known
|
|
88
88
|
for (frag_base, words) in &patches {
|
|
89
89
|
for (k, &off) in words.iter().enumerate() {
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
90
|
+
let fi: usize = frag_base + k;
|
|
91
|
+
if fi >= deltas.len() || deltas[fi] <= 0 || off + 4 > out.len() { continue; }
|
|
92
|
+
let d: u32 = (deltas[fi] as u64).min(0x7FFF_FFFF) as u32;
|
|
93
|
+
let word: u32 = u32::from_be_bytes(out[off..off + 4].try_into().unwrap());
|
|
94
|
+
let new: u32 = (word & 0x7FFF_FFFF).saturating_sub(d);
|
|
95
95
|
out[off..off + 4].copy_from_slice(&((word & 0x8000_0000) | (new & 0x7FFF_FFFF)).to_be_bytes());
|
|
96
96
|
}
|
|
97
97
|
}
|
|
@@ -203,9 +203,8 @@ fn has_chunk_offsets(children: &[u8], depth: usize) -> bool {
|
|
|
203
203
|
&& u32::from_be_bytes(children[child.content_start + 4..child.content_start + 8].try_into().unwrap()) > 0 => return true,
|
|
204
204
|
b"co64" if child.end - child.content_start >= 12
|
|
205
205
|
&& u64::from_be_bytes(children[child.content_start + 4..child.content_start + 12].try_into().unwrap()) > 0 => return true,
|
|
206
|
-
typ if
|
|
207
|
-
|
|
208
|
-
}
|
|
206
|
+
typ if CONTAINERS.contains(&typ)
|
|
207
|
+
&& has_chunk_offsets(&children[child.content_start..child.end], depth + 1) => return true,
|
|
209
208
|
_ => {}
|
|
210
209
|
}
|
|
211
210
|
}
|
|
@@ -401,6 +401,56 @@ def test_error_bad_cover(sp, src_file):
|
|
|
401
401
|
assert e.value.code == 12
|
|
402
402
|
|
|
403
403
|
|
|
404
|
+
def test_error_cover_missing(sp, src_file):
|
|
405
|
+
# additive code 13 — a missing cover path names the cover, not the input
|
|
406
|
+
with pytest.raises(DecrypTuneError) as e:
|
|
407
|
+
sp.proc(input=src_file, key=KEY_HEX, meta=TuneMeta(cover="no_such_cover.jpg"))
|
|
408
|
+
assert e.value.code == 13
|
|
409
|
+
assert "cover file not found" in e.value.message
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def test_path_out_pathlib(sp, src_file, tmp_path):
|
|
413
|
+
# out accepts os.PathLike exactly like input
|
|
414
|
+
dst = tmp_path / "out_pathlib.m4a"
|
|
415
|
+
assert sp.proc(input=src_file, out=dst, key=KEY_HEX) is None
|
|
416
|
+
assert dst.read_bytes() == sp.proc(input=src_file, key=KEY_HEX)
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
class _BytesPath:
|
|
420
|
+
"""os.fspath objects may legally return bytes — must behave like a str path."""
|
|
421
|
+
|
|
422
|
+
def __init__(self, p):
|
|
423
|
+
self.p = str(p)
|
|
424
|
+
|
|
425
|
+
def __fspath__(self):
|
|
426
|
+
return os.fsencode(self.p)
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def test_fspath_bytes_input_and_out(sp, src_file, tmp_path):
|
|
430
|
+
dst = tmp_path / "out_fspath.m4a"
|
|
431
|
+
assert sp.proc(input=_BytesPath(src_file), out=_BytesPath(dst), key=KEY_HEX) is None
|
|
432
|
+
assert dst.read_bytes() == sp.proc(input=src_file, key=KEY_HEX)
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def test_out_is_directory_no_tmp_litter(sp, src_file, tmp_path):
|
|
436
|
+
# rename onto an existing directory fails — the tmp file must not be left behind
|
|
437
|
+
out_dir = tmp_path / "outdir"
|
|
438
|
+
out_dir.mkdir()
|
|
439
|
+
with pytest.raises(DecrypTuneError) as e:
|
|
440
|
+
sp.proc(input=src_file, out=str(out_dir), key=KEY_HEX)
|
|
441
|
+
assert e.value.code == 6
|
|
442
|
+
assert list(tmp_path.glob("*.tmp")) == []
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
def test_aproc_out_is_directory_no_tmp_litter(sp, src_file, tmp_path):
|
|
446
|
+
out_dir = tmp_path / "aoutdir"
|
|
447
|
+
out_dir.mkdir()
|
|
448
|
+
with pytest.raises(DecrypTuneError) as e:
|
|
449
|
+
asyncio.run(sp.aproc(input=src_file, out=str(out_dir), key=KEY_HEX))
|
|
450
|
+
assert e.value.code == 6
|
|
451
|
+
assert list(tmp_path.glob("*.tmp")) == []
|
|
452
|
+
|
|
453
|
+
|
|
404
454
|
def test_error_tags_need_fragmented(sp):
|
|
405
455
|
# a non-empty stco dangles once moov grows with tags -> refused
|
|
406
456
|
stco = full_box(b"stco", 0, 0, u32(1) + u32(100))
|
|
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
|