decryptune 1.1.4__tar.gz → 1.1.6__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.1.4 → decryptune-1.1.6}/Cargo.lock +10 -10
- {decryptune-1.1.4 → decryptune-1.1.6}/Cargo.toml +1 -1
- {decryptune-1.1.4 → decryptune-1.1.6}/PKG-INFO +2 -2
- {decryptune-1.1.4 → decryptune-1.1.6}/README.md +1 -1
- {decryptune-1.1.4 → decryptune-1.1.6}/python/decryptune/__init__.py +25 -9
- {decryptune-1.1.4 → decryptune-1.1.6}/src/boxes.rs +36 -7
- {decryptune-1.1.4 → decryptune-1.1.6}/src/cover.rs +6 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/src/error.rs +4 -2
- {decryptune-1.1.4 → decryptune-1.1.6}/src/input.rs +7 -4
- {decryptune-1.1.4 → decryptune-1.1.6}/src/jpeg/decode.rs +28 -11
- {decryptune-1.1.4 → decryptune-1.1.6}/src/jpeg/encode.rs +7 -1
- {decryptune-1.1.4 → decryptune-1.1.6}/src/jpeg/tests.rs +43 -5
- {decryptune-1.1.4 → decryptune-1.1.6}/src/lib.rs +44 -18
- {decryptune-1.1.4 → decryptune-1.1.6}/src/meta.rs +7 -3
- {decryptune-1.1.4 → decryptune-1.1.6}/src/process.rs +279 -61
- decryptune-1.1.6/tests/fixtures/odd420.jpg +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/tests/test_decryptune.py +151 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/.gitattributes +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/.github/workflows/build.yml +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/.gitignore +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/LICENSE +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/pyproject.toml +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/src/jpeg/mod.rs +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/tests/fixtures/big.jpg +0 -0
- {decryptune-1.1.4 → decryptune-1.1.6}/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.
|
|
7
|
+
version = "0.9.4"
|
|
8
8
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
9
|
-
checksum = "
|
|
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.
|
|
71
|
+
version = "1.1.6"
|
|
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.
|
|
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.
|
|
142
|
+
version = "0.2.6"
|
|
143
143
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
144
|
-
checksum = "
|
|
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.
|
|
281
|
+
version = "3.0.10"
|
|
282
282
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
283
|
-
checksum = "
|
|
283
|
+
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
|
284
284
|
dependencies = [
|
|
285
285
|
"proc-macro2",
|
|
286
286
|
"quote",
|
|
@@ -295,9 +295,9 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
|
|
|
295
295
|
|
|
296
296
|
[[package]]
|
|
297
297
|
name = "tokio"
|
|
298
|
-
version = "1.54.
|
|
298
|
+
version = "1.54.1"
|
|
299
299
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
300
|
-
checksum = "
|
|
300
|
+
checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3"
|
|
301
301
|
dependencies = [
|
|
302
302
|
"pin-project-lite",
|
|
303
303
|
]
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: decryptune
|
|
3
|
-
Version: 1.1.
|
|
3
|
+
Version: 1.1.6
|
|
4
4
|
Classifier: Development Status :: 5 - Production/Stable
|
|
5
5
|
Classifier: Intended Audience :: Developers
|
|
6
6
|
Classifier: Programming Language :: Rust
|
|
@@ -60,7 +60,7 @@ Rules that hold for both `proc` and `aproc`:
|
|
|
60
60
|
- `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
|
|
61
61
|
- `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
|
|
62
62
|
- A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
|
|
63
|
-
- Any problem raises `DecrypTuneError` with a stable numeric code (1–
|
|
63
|
+
- Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
|
|
64
64
|
|
|
65
65
|
## Benchmark
|
|
66
66
|
|
|
@@ -43,7 +43,7 @@ Rules that hold for both `proc` and `aproc`:
|
|
|
43
43
|
- `out` is a path → the file is written **atomically** (tmp + rename) and `None` is returned; `out` is `None` → the processed `bytes` are returned.
|
|
44
44
|
- `key=None` → **fix-only pass**: headers sanitized, audio payload untouched.
|
|
45
45
|
- A `meta` **wipes** the existing tag block and rebuilds it solely from the given fields — `None` / `0` / empty values are skipped; without `meta` the original metadata passes through untouched.
|
|
46
|
-
- Any problem raises `DecrypTuneError` with a stable numeric code (1–
|
|
46
|
+
- Any problem raises `DecrypTuneError` with a stable numeric code (1–14) and a message authored in the native core: `1` invalid key · `2` invalid kid · `3` input not found · `4` not an MP4 · `6` write failed · `7` KID mismatch · `8` corrupt audio detected · `9` bad input type · `10` bad out type · `11` tags need a fragmented file · `12` bad cover · `13` cover file not found · `14` cover too large (max 32 MB).
|
|
47
47
|
|
|
48
48
|
## Benchmark
|
|
49
49
|
|
|
@@ -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
|
-
|
|
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.
|
|
42
|
+
__version__ = "1.1.6"
|
|
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
|
|
54
|
-
#
|
|
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
|
-
|
|
74
|
+
code: int = int(msg[1:end])
|
|
61
75
|
except ValueError:
|
|
62
|
-
|
|
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
|
|
|
@@ -11,10 +11,18 @@ impl Box {
|
|
|
11
11
|
pub fn is(&self, t: &[u8; 4]) -> bool { &self.typ == t }
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
// hostile box spam: each parsed box costs 32 bytes of vec, so an absurd
|
|
15
|
+
// structure would multiply the input size many-fold. Parsing stops at the cap;
|
|
16
|
+
// callers check saturation via len() == MAX_BOXES and treat the input as
|
|
17
|
+
// invalid or pass it through rather than copying a structure no real file has.
|
|
18
|
+
// 2M top-level boxes would already be a 64MB vec for a 16MB input.
|
|
19
|
+
pub const MAX_BOXES: usize = 2_000_000;
|
|
20
|
+
|
|
14
21
|
pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
|
|
15
22
|
let mut out: Vec<Box> = Vec::new();
|
|
16
23
|
let mut pos: usize = start;
|
|
17
24
|
while pos + 8 <= end {
|
|
25
|
+
if out.len() >= MAX_BOXES { break; }
|
|
18
26
|
let (size, hlen): (usize, usize) = match u32::from_be_bytes(data[pos..pos + 4].try_into().unwrap()) {
|
|
19
27
|
0 => (end - pos, 8),
|
|
20
28
|
1 if pos + 16 <= end => (u64::from_be_bytes(data[pos + 8..pos + 16].try_into().unwrap()) as usize, 16),
|
|
@@ -30,10 +38,23 @@ pub fn parse(data: &[u8], start: usize, end: usize) -> Vec<Box> {
|
|
|
30
38
|
out
|
|
31
39
|
}
|
|
32
40
|
|
|
41
|
+
// header length a box with this content size needs — content beyond the u32
|
|
42
|
+
// range switches to the 64-bit largesize form instead of wrapping the size
|
|
43
|
+
#[inline]
|
|
44
|
+
pub fn header_len(content_len: usize) -> usize {
|
|
45
|
+
if content_len + 8 > u32::MAX as usize { 16 } else { 8 }
|
|
46
|
+
}
|
|
47
|
+
|
|
33
48
|
#[inline]
|
|
34
49
|
pub fn write_header(out: &mut Vec<u8>, typ: &[u8; 4], content_len: usize) {
|
|
35
|
-
|
|
36
|
-
|
|
50
|
+
if content_len + 8 > u32::MAX as usize {
|
|
51
|
+
out.extend_from_slice(&1u32.to_be_bytes());
|
|
52
|
+
out.extend_from_slice(typ);
|
|
53
|
+
out.extend_from_slice(&((content_len as u64) + 16).to_be_bytes());
|
|
54
|
+
} else {
|
|
55
|
+
out.extend_from_slice(&((content_len + 8) as u32).to_be_bytes());
|
|
56
|
+
out.extend_from_slice(typ);
|
|
57
|
+
}
|
|
37
58
|
}
|
|
38
59
|
|
|
39
60
|
// output sink — Buf writes into an exactly-sized buffer, Count only measures.
|
|
@@ -59,15 +80,23 @@ impl Writer<'_> {
|
|
|
59
80
|
}
|
|
60
81
|
}
|
|
61
82
|
|
|
62
|
-
// 32-bit box header (size + fourcc)
|
|
83
|
+
// 32-bit box header (size + fourcc) — or the 64-bit largesize form when the
|
|
84
|
+
// content cannot be expressed in 32 bits (rebuilt >4GB containers)
|
|
63
85
|
pub fn header(&mut self, typ: &[u8; 4], content_len: usize) {
|
|
64
86
|
match self {
|
|
65
87
|
Writer::Buf { buf, pos } => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
88
|
+
if content_len + 8 > u32::MAX as usize {
|
|
89
|
+
buf[*pos..*pos + 4].copy_from_slice(&1u32.to_be_bytes());
|
|
90
|
+
buf[*pos + 4..*pos + 8].copy_from_slice(typ);
|
|
91
|
+
buf[*pos + 8..*pos + 16].copy_from_slice(&((content_len as u64) + 16).to_be_bytes());
|
|
92
|
+
*pos += 16;
|
|
93
|
+
} else {
|
|
94
|
+
buf[*pos..*pos + 4].copy_from_slice(&((content_len + 8) as u32).to_be_bytes());
|
|
95
|
+
buf[*pos + 4..*pos + 8].copy_from_slice(typ);
|
|
96
|
+
*pos += 8;
|
|
97
|
+
}
|
|
69
98
|
}
|
|
70
|
-
Writer::Count(n) => *n +=
|
|
99
|
+
Writer::Count(n) => *n += header_len(content_len)
|
|
71
100
|
}
|
|
72
101
|
}
|
|
73
102
|
}
|
|
@@ -9,12 +9,18 @@ use crate::meta::Cover;
|
|
|
9
9
|
use crate::Err;
|
|
10
10
|
|
|
11
11
|
const MAX_EDGE: u32 = 1000;
|
|
12
|
+
// a cover lands inside the ilst whole — 32MB is far above any real art and
|
|
13
|
+
// keeps a hostile "cover" from bloating the output file without bound
|
|
14
|
+
const MAX_COVER_BYTES: usize = 32 * 1024 * 1024;
|
|
12
15
|
|
|
13
16
|
pub(crate) fn is_jpeg(b: &[u8]) -> bool { b.len() >= 2 && b[0] == 0xFF && b[1] == 0xD8 }
|
|
14
17
|
pub(crate) fn is_png(b: &[u8]) -> bool { b.len() >= 8 && b[0..4] == [0x89, 0x50, 0x4E, 0x47] }
|
|
15
18
|
|
|
16
19
|
/// Validate and (when needed) downscale a cover image to fit MAX_EDGE.
|
|
17
20
|
pub(crate) fn prepare(raw: &[u8]) -> Result<Cover<'_>, Err> {
|
|
21
|
+
if raw.len() > MAX_COVER_BYTES {
|
|
22
|
+
return Err(Err::CoverTooLarge);
|
|
23
|
+
}
|
|
18
24
|
if is_png(raw) {
|
|
19
25
|
return Ok(Cover { data: Cow::Borrowed(raw), kind: 14 });
|
|
20
26
|
}
|
|
@@ -19,7 +19,8 @@ pub(crate) enum Err {
|
|
|
19
19
|
BadOutput = 10,
|
|
20
20
|
MetaNeedsFragmented = 11,
|
|
21
21
|
BadCover = 12,
|
|
22
|
-
CoverNotFound = 13 // additive: a missing cover path must not read as a missing input
|
|
22
|
+
CoverNotFound = 13, // additive: a missing cover path must not read as a missing input
|
|
23
|
+
CoverTooLarge = 14 // additive: an absurd cover must not flow into the ilst whole
|
|
23
24
|
}
|
|
24
25
|
|
|
25
26
|
impl Err {
|
|
@@ -37,7 +38,8 @@ impl Err {
|
|
|
37
38
|
Err::BadInput => "invalid input: expected bytes, bytearray, memoryview, or a path",
|
|
38
39
|
Err::BadOutput => "invalid out: expected a path or None",
|
|
39
40
|
Err::MetaNeedsFragmented => "metadata write requires a fragmented file (non-empty chunk offsets)",
|
|
40
|
-
Err::BadCover => "unsupported cover format: expected JPEG or PNG"
|
|
41
|
+
Err::BadCover => "unsupported cover format: expected JPEG or PNG",
|
|
42
|
+
Err::CoverTooLarge => "cover too large (max 32 MB)"
|
|
41
43
|
}
|
|
42
44
|
}
|
|
43
45
|
}
|
|
@@ -60,11 +60,13 @@ pub(crate) fn extract_bytes_or_path(value: &Bound<'_, PyAny>, bad: Err) -> PyRes
|
|
|
60
60
|
} else if let Ok(b) = value.cast::<PyByteArray>() {
|
|
61
61
|
Extracted::Bytes(b.to_vec()) // mutable — a copy is mandatory
|
|
62
62
|
} else if let Ok(s) = value.cast::<PyString>() {
|
|
63
|
-
|
|
63
|
+
// to_str fails only on lone surrogates (real on Windows via os.fsdecode) —
|
|
64
|
+
// the Rust core takes String paths only, so that input has no valid encoding
|
|
65
|
+
Extracted::Path(s.to_str().map_err(|_| bad)?.to_string())
|
|
64
66
|
} else if let Ok(p) = value.call_method0("__fspath__") { // os.PathLike
|
|
65
67
|
// fspath may legally return bytes — map that here, never a raw downcast error
|
|
66
68
|
Extracted::Path(if let Ok(s) = p.cast::<PyString>() {
|
|
67
|
-
s.to_str()?.to_string()
|
|
69
|
+
s.to_str().map_err(|_| bad)?.to_string()
|
|
68
70
|
} else if let Ok(b) = p.cast::<PyBytes>() {
|
|
69
71
|
String::from_utf8_lossy(b.as_bytes()).into_owned()
|
|
70
72
|
} else {
|
|
@@ -96,11 +98,12 @@ pub(crate) fn parse_output(out: Option<&Bound<'_, PyAny>>) -> PyResult<Output> {
|
|
|
96
98
|
None => Ok(Output::Return),
|
|
97
99
|
Some(v) => {
|
|
98
100
|
let path: String = if let Ok(s) = v.cast::<PyString>() {
|
|
99
|
-
|
|
101
|
+
// lone surrogates have no Rust-side String encoding — coded error, not a leak
|
|
102
|
+
s.to_str().map_err(|_| Err::BadOutput)?.to_string()
|
|
100
103
|
} else if let Ok(p) = v.call_method0("__fspath__") { // os.PathLike
|
|
101
104
|
// same fspath-bytes rule as input — a coded error, not a raw downcast
|
|
102
105
|
if let Ok(s) = p.cast::<PyString>() {
|
|
103
|
-
s.to_str()?.to_string()
|
|
106
|
+
s.to_str().map_err(|_| Err::BadOutput)?.to_string()
|
|
104
107
|
} else if let Ok(b) = p.cast::<PyBytes>() {
|
|
105
108
|
String::from_utf8_lossy(b.as_bytes()).into_owned()
|
|
106
109
|
} else {
|
|
@@ -6,9 +6,10 @@ use super::ZIGZAG;
|
|
|
6
6
|
use crate::Err;
|
|
7
7
|
|
|
8
8
|
// hostile SOF dimensions can demand multi-GB coefficient buffers before any
|
|
9
|
-
// entropy byte is read —
|
|
10
|
-
//
|
|
11
|
-
|
|
9
|
+
// entropy byte is read — covers are downscaled to 1000px anyway, so 64MP
|
|
10
|
+
// (8192²) is far beyond anything legitimate; at the old 256MP cap a ~1MB
|
|
11
|
+
// hostile JPEG forced ~1GB of buffers and seconds of IDCT
|
|
12
|
+
pub(super) const MAX_PIXELS: usize = 67_108_864; // 64 megapixels
|
|
12
13
|
|
|
13
14
|
struct HuffTable {
|
|
14
15
|
counts : [u8; 17], // symbols per code length 1..=16
|
|
@@ -18,15 +19,20 @@ struct HuffTable {
|
|
|
18
19
|
}
|
|
19
20
|
|
|
20
21
|
impl HuffTable {
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
// canonical code assignment with an overfull check: a table claiming more
|
|
23
|
+
// codes than a length's code space holds would overflow the u16 code and
|
|
24
|
+
// decode garbage downstream
|
|
25
|
+
fn build(counts: &[u8; 17], symbols: Vec<u8>) -> Result<HuffTable, Err> {
|
|
26
|
+
let (mut first_code, mut val_off, mut code, mut k): ([u16; 17], [usize; 17], u32, usize) = ([0; 17], [0; 17], 0, 0);
|
|
23
27
|
for len in 1..=16 {
|
|
24
|
-
first_code[len] = code;
|
|
28
|
+
first_code[len] = code as u16;
|
|
25
29
|
val_off[len] = k;
|
|
26
30
|
k += counts[len] as usize;
|
|
27
|
-
code
|
|
31
|
+
code += counts[len] as u32;
|
|
32
|
+
if code > (1u32 << len) { return Err(Err::BadCover); }
|
|
33
|
+
code <<= 1;
|
|
28
34
|
}
|
|
29
|
-
HuffTable { counts: *counts, first_code, val_off, symbols }
|
|
35
|
+
Ok(HuffTable { counts: *counts, first_code, val_off, symbols })
|
|
30
36
|
}
|
|
31
37
|
|
|
32
38
|
fn decode(&self, br: &mut BitReader<'_>) -> Result<u8, Err> {
|
|
@@ -34,7 +40,9 @@ impl HuffTable {
|
|
|
34
40
|
for len in 1..=16 {
|
|
35
41
|
code = (code << 1) | br.bit()? as i32;
|
|
36
42
|
let (fc, cnt): (i32, i32) = (self.first_code[len] as i32, self.counts[len] as i32);
|
|
37
|
-
|
|
43
|
+
// cnt > 0 keeps an empty length from matching via a negative diff
|
|
44
|
+
// (code below the canonical first code of a longer prefix)
|
|
45
|
+
if cnt > 0 && code >= fc && code - fc < cnt {
|
|
38
46
|
return Ok(self.symbols[self.val_off[len] + (code - fc) as usize]);
|
|
39
47
|
}
|
|
40
48
|
}
|
|
@@ -365,7 +373,12 @@ pub(crate) fn decode(raw: &[u8]) -> Result<(usize, usize, usize, Vec<u8>), Err>
|
|
|
365
373
|
counts[1..].copy_from_slice(&raw[p + 1..p + 17]);
|
|
366
374
|
let total: usize = counts[1..].iter().map(|&c| c as usize).sum();
|
|
367
375
|
if p + 17 + total > pos + seg { return Err(Err::BadCover); }
|
|
368
|
-
|
|
376
|
+
// a DC symbol is a magnitude category (0..=15): anything
|
|
377
|
+
// larger would underflow the bit reader's bit count
|
|
378
|
+
if tc == 0 && raw[p + 17..p + 17 + total].iter().any(|&s| s > 15) {
|
|
379
|
+
return Err(Err::BadCover);
|
|
380
|
+
}
|
|
381
|
+
let table: HuffTable = HuffTable::build(&counts, raw[p + 17..p + 17 + total].to_vec())?;
|
|
369
382
|
if tc == 0 { dcs[th] = Some(table); } else { acs[th] = Some(table); }
|
|
370
383
|
p += 17 + total;
|
|
371
384
|
}
|
|
@@ -592,9 +605,13 @@ fn upsample_h2v2(plane: &[u8], pw: usize, ph: usize, w: usize, oh: usize) -> Vec
|
|
|
592
605
|
for j in 0..oh.div_ceil(2) {
|
|
593
606
|
let cur = &plane[j.min(ph - 1) * pw..];
|
|
594
607
|
for dy in 0..2 {
|
|
608
|
+
// an odd output height ends on a dy=0 row; the below-blend pass
|
|
609
|
+
// would write row `oh` past the buffer, so it lands on `oh - 1`
|
|
610
|
+
// (libjpeg's bottom-edge replication)
|
|
611
|
+
let dst: usize = (2 * j + dy).min(oh - 1);
|
|
595
612
|
let orow: usize = if dy == 0 { j.saturating_sub(1).min(ph - 1) } else { (j + 1).min(ph - 1) };
|
|
596
613
|
let oth = &plane[orow * pw..];
|
|
597
|
-
let orow_out = &mut out[
|
|
614
|
+
let orow_out = &mut out[dst * w..dst * w + w];
|
|
598
615
|
let colsum = |i: usize| -> u32 { (cur[i.min(pw - 1)] as u32) * 3 + (oth[i.min(pw - 1)] as u32) };
|
|
599
616
|
let (c0, c1): (u32, u32) = (colsum(0), colsum(1));
|
|
600
617
|
orow_out[0] = ((c0 * 4 + 8) >> 4) as u8;
|
|
@@ -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
|
-
|
|
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 {
|
|
@@ -118,11 +118,49 @@ fn encode_edge_blocks() {
|
|
|
118
118
|
|
|
119
119
|
#[test]
|
|
120
120
|
fn hostile_huge_sof_rejected() {
|
|
121
|
-
//
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
121
|
+
// SOF claims must fail validation before any buffer is allocated — a
|
|
122
|
+
// 65535x65535 claim wants ~8GB of coefficient buffers, and 16384x16384
|
|
123
|
+
// (the old 256MP cap's boundary) still wants ~1GB
|
|
124
|
+
for (w, h) in [(0xFFFFu16, 0xFFFFu16), (16384u16, 16384u16)] {
|
|
125
|
+
let sof: [u8; 11] = [0, 11, 8, (h >> 8) as u8, h as u8, (w >> 8) as u8, w as u8, 1, 1, 0x11, 0];
|
|
126
|
+
let jpg: Vec<u8> = [&[0xFF, 0xD8, 0xFF, 0xC0][..], &sof, &[0xFF, 0xD9][..]].concat();
|
|
127
|
+
assert!(decode(&jpg).is_err(), "{w}x{h} not rejected");
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
#[test]
|
|
132
|
+
fn hostile_dht_rejected() {
|
|
133
|
+
// DC magnitude symbols above 15 would underflow the bit reader's count and
|
|
134
|
+
// overfull canonical tables would overflow the code book — both rejected
|
|
135
|
+
// at DHT parse time (a debug build once panicked on the first)
|
|
136
|
+
let dqt: Vec<u8> = [[0xFFu8, 0xDB].as_slice(), &67u16.to_be_bytes(), &[0x00], &[1u8; 64]].concat();
|
|
137
|
+
let sof: Vec<u8> = [[0xFFu8, 0xC0].as_slice(), &11u16.to_be_bytes(), &[8u8, 0, 16, 0, 16, 1, 1, 0x11, 0]].concat();
|
|
138
|
+
let ac: Vec<u8> = [[0xFFu8, 0xC4].as_slice(), &20u16.to_be_bytes(), &[0x10], &[1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], &[0]].concat();
|
|
139
|
+
let sos: Vec<u8> = [[0xFFu8, 0xDA].as_slice(), &8u16.to_be_bytes(), &[1u8, 1, 0, 0, 63, 0]].concat();
|
|
140
|
+
let dht = |class: u8, counts: &[u8], symbols: &[u8]| -> Vec<u8> {
|
|
141
|
+
[[0xFFu8, 0xC4].as_slice(), &((2 + 1 + 16 + symbols.len()) as u16).to_be_bytes(), &[class], counts, symbols].concat()
|
|
142
|
+
};
|
|
143
|
+
let counts_len1: [u8; 16] = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
|
144
|
+
let counts_overfull: [u8; 16] = [3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
|
145
|
+
let entropy_and_eoi = &[0x00u8, 0x00, 0xFF, 0xD9][..];
|
|
146
|
+
for bad_dht in [
|
|
147
|
+
dht(0x00, &counts_len1, &[200]), // DC symbol 200
|
|
148
|
+
dht(0x00, &counts_overfull, &[0, 1, 2, 3]), // 3 one-bit codes
|
|
149
|
+
] {
|
|
150
|
+
let jpg: Vec<u8> = [&[0xFF, 0xD8][..], &dqt, &sof, &bad_dht, &ac, &sos, entropy_and_eoi].concat();
|
|
151
|
+
assert!(decode(&jpg).is_err());
|
|
152
|
+
}
|
|
153
|
+
}
|
|
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());
|
|
126
164
|
}
|
|
127
165
|
|
|
128
166
|
// DUMP_ENC=1 + JPEG_FIXTURES: write our encode of the p444 reference so the
|
|
@@ -16,12 +16,26 @@ use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
16
16
|
use error::Err;
|
|
17
17
|
use input::{parse_input, parse_output, InputData, Output};
|
|
18
18
|
|
|
19
|
+
// strict [0-9a-fA-F] nibbles, decoded byte-wise: a multi-byte UTF-8 char can
|
|
20
|
+
// neither panic a char-boundary slice nor slip through from_str_radix, which
|
|
21
|
+
// would happily accept a sign-prefixed pair like "+f" as 0x0f
|
|
22
|
+
fn hex_nibble(b: u8) -> Option<u8> {
|
|
23
|
+
match b {
|
|
24
|
+
b'0'..=b'9' => Some(b - b'0'),
|
|
25
|
+
b'a'..=b'f' => Some(b - b'a' + 10),
|
|
26
|
+
b'A'..=b'F' => Some(b - b'A' + 10),
|
|
27
|
+
_ => None
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
fn parse_hex16(hex: &str) -> Result<[u8; 16], Err> {
|
|
20
|
-
let hex: &
|
|
32
|
+
let hex: &[u8] = hex.trim().as_bytes();
|
|
21
33
|
if hex.len() != 32 { return Err(Err::InvalidKey); }
|
|
22
34
|
let mut key: [u8; 16] = [0u8; 16];
|
|
23
35
|
for (i, b) in key.iter_mut().enumerate() {
|
|
24
|
-
|
|
36
|
+
let hi: u8 = hex_nibble(hex[i * 2]).ok_or(Err::InvalidKey)?;
|
|
37
|
+
let lo: u8 = hex_nibble(hex[i * 2 + 1]).ok_or(Err::InvalidKey)?;
|
|
38
|
+
*b = (hi << 4) | lo;
|
|
25
39
|
}
|
|
26
40
|
Ok(key)
|
|
27
41
|
}
|
|
@@ -44,14 +58,17 @@ fn tmp_path(out_path: &str) -> String {
|
|
|
44
58
|
format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
|
|
45
59
|
}
|
|
46
60
|
|
|
47
|
-
// write to <out>.<n>.tmp then rename — no partial outputs
|
|
61
|
+
// write to <out>.<n>.tmp, flush it to disk, then rename — no partial outputs
|
|
62
|
+
// on crash, and the rename cannot expose unflushed data after a power loss.
|
|
48
63
|
// create_new (O_CREAT|O_EXCL) refuses a symlink pre-placed at the predictable
|
|
49
64
|
// tmp name and fails on collision instead of clobbering an existing file
|
|
50
65
|
fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
|
|
51
66
|
let tmp: String = tmp_path(out_path);
|
|
52
67
|
let mut file: std::fs::File = std::fs::OpenOptions::new().write(true).create_new(true).open(&tmp)
|
|
53
68
|
.map_err(|_| Err::WriteFailed)?;
|
|
54
|
-
if file.write_all(data).is_err()
|
|
69
|
+
if file.write_all(data).is_err()
|
|
70
|
+
|| file.sync_data().is_err()
|
|
71
|
+
|| std::fs::rename(&tmp, out_path).is_err() {
|
|
55
72
|
let _ = std::fs::remove_file(&tmp);
|
|
56
73
|
return Err(Err::WriteFailed);
|
|
57
74
|
}
|
|
@@ -155,16 +172,6 @@ impl TuneMeta {
|
|
|
155
172
|
}
|
|
156
173
|
}
|
|
157
174
|
|
|
158
|
-
// parsed proc/aproc arguments — every Send piece is resolved under the GIL
|
|
159
|
-
// once, then moved wholesale into the worker
|
|
160
|
-
struct Args {
|
|
161
|
-
input : input::Input,
|
|
162
|
-
output : Output,
|
|
163
|
-
key : Option<[u8; 16]>,
|
|
164
|
-
kid : Option<String>,
|
|
165
|
-
core_meta: Option<meta::CoreMeta>
|
|
166
|
-
}
|
|
167
|
-
|
|
168
175
|
fn parse_args(
|
|
169
176
|
py : Python<'_>,
|
|
170
177
|
input: &Bound<'_, PyAny>,
|
|
@@ -182,6 +189,25 @@ fn parse_args(
|
|
|
182
189
|
})
|
|
183
190
|
}
|
|
184
191
|
|
|
192
|
+
// parse_args product with the has_key flag precomputed — measure/load never
|
|
193
|
+
// needs the key itself, only whether one was supplied (for the KID guard)
|
|
194
|
+
struct Args {
|
|
195
|
+
input : input::Input,
|
|
196
|
+
output : Output,
|
|
197
|
+
key : Option<[u8; 16]>,
|
|
198
|
+
kid : Option<String>,
|
|
199
|
+
core_meta: Option<meta::CoreMeta>
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
type ParsedArgs = (input::Input, Output, Option<[u8; 16]>, Option<String>, Option<meta::CoreMeta>, bool);
|
|
203
|
+
|
|
204
|
+
impl Args {
|
|
205
|
+
fn into_parts(self) -> ParsedArgs {
|
|
206
|
+
let has_key: bool = self.key.is_some();
|
|
207
|
+
(self.input, self.output, self.key, self.kid, self.core_meta, has_key)
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
185
211
|
// Python TuneMeta → Send CoreMeta: only raw byte copies and path strings happen under
|
|
186
212
|
// the GIL — cover disk read + JPEG prepare (decode/resize/encode) run in the worker
|
|
187
213
|
// None/0/empty fields mean "keep whatever the file already carries".
|
|
@@ -231,9 +257,9 @@ fn proc<'py>(
|
|
|
231
257
|
meta : Option<&TuneMeta>,
|
|
232
258
|
strict : bool
|
|
233
259
|
) -> PyResult<Option<Bound<'py, PyAny>>> {
|
|
234
|
-
let
|
|
260
|
+
let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
|
|
235
261
|
let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) =
|
|
236
|
-
py.detach(move || load_and_measure(input,
|
|
262
|
+
py.detach(move || load_and_measure(input, has_key, kid, core_meta)).map_err(PyErr::from)?;
|
|
237
263
|
let guarded: bool = strict && key.is_some();
|
|
238
264
|
|
|
239
265
|
match output {
|
|
@@ -293,12 +319,12 @@ fn aproc<'py>(
|
|
|
293
319
|
meta : Option<&TuneMeta>,
|
|
294
320
|
strict : bool
|
|
295
321
|
) -> PyResult<Bound<'py, PyAny>> {
|
|
296
|
-
let
|
|
322
|
+
let (input, output, key, kid, core_meta, has_key): ParsedArgs = parse_args(py, input, out, key, kid, meta)?.into_parts();
|
|
297
323
|
let guarded: bool = strict && key.is_some();
|
|
298
324
|
|
|
299
325
|
pyo3_async_runtimes::tokio::future_into_py(py, async move {
|
|
300
326
|
let (data, len, core_meta): (InputData, usize, Option<meta::CoreMeta>) = tokio::task::spawn_blocking(
|
|
301
|
-
move || load_and_measure(input,
|
|
327
|
+
move || load_and_measure(input, has_key, kid, core_meta),
|
|
302
328
|
).await.map_err(join_err)??;
|
|
303
329
|
match output {
|
|
304
330
|
Output::Path(p) => {
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
|
|
4
4
|
use std::borrow::Cow;
|
|
5
5
|
|
|
6
|
-
use crate::boxes::{parse, write_header, Writer};
|
|
6
|
+
use crate::boxes::{parse, write_header, Box, Writer};
|
|
7
7
|
use crate::Err;
|
|
8
8
|
|
|
9
9
|
pub(crate) struct Cover<'a> {
|
|
@@ -145,8 +145,12 @@ fn hdlr_box() -> Vec<u8> {
|
|
|
145
145
|
pub(crate) fn append_moov_with_meta(out: &mut Writer<'_>, children: &[u8], meta: &CoreMeta) -> Result<(), Err> {
|
|
146
146
|
// every old udta goes — keeping any would both leak stale tags and shadow the
|
|
147
147
|
// fresh subtree for the Windows handler (it reads only the first udta/meta)
|
|
148
|
-
let
|
|
149
|
-
|
|
148
|
+
let top: Vec<Box> = parse(children, 0, children.len());
|
|
149
|
+
if top.len() >= crate::boxes::MAX_BOXES {
|
|
150
|
+
return Err(Err::InvalidMp4); // saturated parse: the udta map would be wrong
|
|
151
|
+
}
|
|
152
|
+
let udta: Vec<(usize, usize)> = top.iter().filter(|c| c.is(b"udta"))
|
|
153
|
+
.map(|c| (c.start, c.end)).collect();
|
|
150
154
|
|
|
151
155
|
let mut ilst: Vec<u8> = Vec::new();
|
|
152
156
|
build_items(&mut ilst, meta)?;
|