decryptune 1.1.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.
@@ -68,7 +68,7 @@ dependencies = [
68
68
 
69
69
  [[package]]
70
70
  name = "decryptune"
71
- version = "1.1.0"
71
+ version = "1.1.1"
72
72
  dependencies = [
73
73
  "aes",
74
74
  "ctr",
@@ -1,6 +1,6 @@
1
1
  [package]
2
2
  name = "decryptune"
3
- version = "1.1.0"
3
+ version = "1.1.1"
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.0
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
@@ -67,7 +67,7 @@ Rules that hold for both `proc` and `aproc`:
67
67
 
68
68
  ## Benchmark
69
69
 
70
- Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.0:
70
+ Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
71
71
 
72
72
  | scenario | result |
73
73
  |---|---|
@@ -50,7 +50,7 @@ Rules that hold for both `proc` and `aproc`:
50
50
 
51
51
  ## Benchmark
52
52
 
53
- Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.0:
53
+ Real 3.0MB fragmented track, Intel i7-11800H (8C/16T), WSL2, v1.1.1:
54
54
 
55
55
  | scenario | result |
56
56
  |---|---|
@@ -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.1.0"
19
+ __version__ = "1.1.1"
20
20
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
21
21
 
22
22
 
@@ -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.1.0"
11
+ __version__ = "1.1.1"
12
12
  __all__ = ["DecrypTune", "DecrypTuneError", "TuneMeta", "__version__"]
13
13
 
14
14
 
@@ -100,44 +100,75 @@ fn tmp_path(out_path: &str) -> String {
100
100
  format!("{}.{}.{}.tmp", out_path, std::process::id(), N.fetch_add(1, Ordering::Relaxed))
101
101
  }
102
102
 
103
- // 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)
104
105
  fn write_atomic(out_path: &str, data: &[u8]) -> Result<(), Err> {
105
106
  let tmp: String = tmp_path(out_path);
106
107
  std::fs::write(&tmp, data).map_err(|_| Err::WriteFailed)?;
107
- std::fs::rename(&tmp, out_path).map_err(|_| Err::WriteFailed)
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(())
108
113
  }
109
114
 
110
- fn parse_input(value: &Bound<'_, PyAny>) -> PyResult<Input> {
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> {
111
122
  Ok(if let Ok(b) = value.cast::<PyBytes>() {
112
- Input::Bytes(b.as_bytes().to_vec())
123
+ Extracted::Bytes(b.as_bytes().to_vec())
113
124
  } else if let Ok(b) = value.cast::<PyByteArray>() {
114
- Input::Bytes(b.to_vec())
125
+ Extracted::Bytes(b.to_vec())
115
126
  } else if let Ok(s) = value.cast::<PyString>() {
116
- Input::Path(s.to_str()?.to_string())
127
+ Extracted::Path(s.to_str()?.to_string())
117
128
  } else if let Ok(p) = value.call_method0("__fspath__") { // os.PathLike
118
- Input::Path(p.cast::<PyString>()?.to_str()?.to_string())
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
+ })
119
137
  } else {
120
138
  // exotic buffer (memoryview, …) — abi3 has no PyBuffer; memoryview()
121
139
  // accepts only real buffer objects (bytes(123) would mean 123 zero bytes!)
122
140
  match value.py().import("builtins")?.getattr("memoryview")?.call1((value,)) {
123
141
  Ok(mv) => {
124
142
  let b = mv.call_method0("tobytes")?;
125
- Input::Bytes(b.cast::<PyBytes>()?.as_bytes().to_vec())
143
+ Extracted::Bytes(b.cast::<PyBytes>()?.as_bytes().to_vec())
126
144
  }
127
- Err(_) => return Err(Err::BadInput.into())
145
+ Err(_) => return Err(bad.into()),
128
146
  }
129
147
  })
130
148
  }
131
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
+
132
157
  fn parse_output(out: Option<&Bound<'_, PyAny>>) -> PyResult<Output> {
133
158
  match out {
134
159
  None => Ok(Output::Return),
135
160
  Some(v) => {
136
- // same path handling as input — os.PathLike accepted too
137
161
  let path: String = if let Ok(s) = v.cast::<PyString>() {
138
162
  s.to_str()?.to_string()
139
- } else if let Ok(p) = v.call_method0("__fspath__") {
140
- p.cast::<PyString>()?.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
+ }
141
172
  } else {
142
173
  return Err(Err::BadOutput.into());
143
174
  };
@@ -246,22 +277,10 @@ fn resolve_meta(py: Python<'_>, meta: Option<&TuneMeta>) -> PyResult<Option<meta
246
277
  let Some(m) = meta else { return Ok(None) };
247
278
  let cover: Option<meta::RawCover> = match &m.cover {
248
279
  None => None,
249
- Some(obj) => {
250
- let bound = obj.bind(py);
251
- Some(if let Ok(b) = bound.cast::<PyBytes>() { meta::RawCover::Bytes(b.as_bytes().to_vec()) }
252
- else if let Ok(b) = bound.cast::<PyByteArray>() { meta::RawCover::Bytes(b.to_vec()) }
253
- else if let Ok(s) = bound.cast::<PyString>() { meta::RawCover::Path(s.to_str()?.to_string()) }
254
- else if let Ok(p) = bound.call_method0("__fspath__") { meta::RawCover::Path(p.cast::<PyString>()?.to_str()?.to_string()) }
255
- else {
256
- match py.import("builtins")?.getattr("memoryview")?.call1((bound,)) {
257
- Ok(mv) => {
258
- let b = mv.call_method0("tobytes")?;
259
- meta::RawCover::Bytes(b.cast::<PyBytes>()?.as_bytes().to_vec())
260
- }
261
- Err(_) => return Err(Err::BadCover.into())
262
- }
263
- })
264
- }
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
+ })
265
284
  };
266
285
  let non_zero: fn(Option<u32>) -> Option<u32> = |v| v.filter(|n| *n > 0);
267
286
  let non_empty: fn(&Option<String>) -> Option<String> = |v| v.clone().filter(|s| !s.is_empty());
@@ -346,7 +365,10 @@ fn aproc<'py>(
346
365
  Output::Path(p) => {
347
366
  let tmp: String = tmp_path(&p);
348
367
  tokio::fs::write(&tmp, &processed.data).await.map_err(|_| Err::WriteFailed)?;
349
- tokio::fs::rename(&tmp, &p).await.map_err(|_| Err::WriteFailed)?;
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
+ }
350
372
  Ok(None)
351
373
  }
352
374
  Output::Return => Ok(Some(processed.data))
@@ -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
- // rebuild moov so a freshly built udta/meta/ilst is the first child; any
144
- // pre-existing udta (with its ilst) is removed entirely
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(&fresh_ilst(meta)?);
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());
@@ -203,7 +203,7 @@ 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 matches!(typ, b"moov" | b"trak" | b"mdia" | b"minf" | b"stbl")
206
+ typ if CONTAINERS.contains(&typ)
207
207
  && has_chunk_offsets(&children[child.content_start..child.end], depth + 1) => return true,
208
208
  _ => {}
209
209
  }
@@ -416,6 +416,41 @@ def test_path_out_pathlib(sp, src_file, tmp_path):
416
416
  assert dst.read_bytes() == sp.proc(input=src_file, key=KEY_HEX)
417
417
 
418
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
+
419
454
  def test_error_tags_need_fragmented(sp):
420
455
  # a non-empty stco dangles once moov grows with tags -> refused
421
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