decryptune 1.1.0__tar.gz → 1.1.2__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.2"
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.2"
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.2
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.2"
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.2"
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());
@@ -311,6 +330,15 @@ fn proc<'py>(
311
330
  Ok(result.map(|bytes| PyBytes::new(py, &bytes).into_any()))
312
331
  }
313
332
 
333
+ // a worker panic must surface with its real message, not a fake error
334
+ fn join_err(join: tokio::task::JoinError) -> PyErr {
335
+ let msg: String = join.try_into_panic().ok()
336
+ .and_then(|p| p.downcast_ref::<&str>().map(|s| s.to_string())
337
+ .or_else(|| p.downcast_ref::<String>().cloned()))
338
+ .unwrap_or_else(|| "internal worker panic".into());
339
+ PyException::new_err(msg)
340
+ }
341
+
314
342
  // async twin of proc: native coroutine, CPU work off-GIL, async file writes
315
343
  #[pyfunction]
316
344
  #[pyo3(signature = (*, input, out=None, key=None, kid=None, meta=None, strict=false))]
@@ -332,21 +360,16 @@ fn aproc<'py>(
332
360
  pyo3_async_runtimes::tokio::future_into_py(py, async move {
333
361
  let processed: process::Processed = tokio::task::spawn_blocking(move || run(input, key, kid, core_meta, strict))
334
362
  .await
335
- .map_err(|join| {
336
- // a worker panic must surface with its real message, not a fake write error
337
- let msg = join.try_into_panic().ok()
338
- .and_then(|p| p.downcast_ref::<&str>().map(|s| s.to_string())
339
- .or_else(|| p.downcast_ref::<String>().cloned()))
340
- .unwrap_or_else(|| "internal worker panic".into());
341
- PyException::new_err(msg)
342
- })??;
363
+ .map_err(join_err)??;
343
364
  check_strict(&processed, key, strict)?;
344
365
  match output {
345
- // true async write — std::fs here would block a runtime worker
366
+ // write+rename run as ONE blocking task — a cancelled future cannot
367
+ // split the pair and leave a tmp behind (tokio::fs is spawn_blocking
368
+ // under the hood anyway, so this frees the worker just as well)
346
369
  Output::Path(p) => {
347
- let tmp: String = tmp_path(&p);
348
- tokio::fs::write(&tmp, &processed.data).await.map_err(|_| Err::WriteFailed)?;
349
- tokio::fs::rename(&tmp, &p).await.map_err(|_| Err::WriteFailed)?;
370
+ tokio::task::spawn_blocking(move || write_atomic(&p, &processed.data))
371
+ .await
372
+ .map_err(join_err)??;
350
373
  Ok(None)
351
374
  }
352
375
  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());
@@ -114,10 +114,10 @@ fn visit_moof(out: &mut Vec<u8>, data: &[u8], b: &Box) -> Plan {
114
114
 
115
115
  // gather: tfhd default first so trun fallback works in any order
116
116
  default_size = traf.iter().find(|t| t.is(b"tfhd"))
117
- .and_then(|t| parse_tfhd(data, t.content_start));
117
+ .and_then(|t| parse_tfhd(data, t.content_start, t.end));
118
118
  for t in &traf {
119
119
  match &t.typ {
120
- b"senc" if ivs.is_none() => ivs = parse_senc(data, t.content_start),
120
+ b"senc" if ivs.is_none() => ivs = parse_senc(data, t.content_start, t.end),
121
121
  b"trun" => sizes.extend(parse_trun_sizes(data, t.content_start, t.end, default_size)),
122
122
  _ => {}
123
123
  }
@@ -169,7 +169,15 @@ fn emit_mdat(
169
169
  plan : &Plan,
170
170
  strict : bool
171
171
  ) -> FragmentStat {
172
- write_header(out, b"mdat", m.end - m.content_start);
172
+ // a largesize (64-bit) mdat keeps its 64-bit header — a u32 rewrite would wrap
173
+ let content_len: usize = m.end - m.content_start;
174
+ if content_len + 8 > u32::MAX as usize || u32::from_be_bytes(data[m.start..m.start + 4].try_into().unwrap()) == 1 {
175
+ out.extend_from_slice(&1u32.to_be_bytes());
176
+ out.extend_from_slice(b"mdat");
177
+ out.extend_from_slice(&((content_len as u64) + 16).to_be_bytes());
178
+ } else {
179
+ write_header(out, b"mdat", content_len);
180
+ }
173
181
  let base: usize = out.len();
174
182
  out.extend_from_slice(&data[m.content_start..m.end]);
175
183
  let encrypted: bool = plan.ok;
@@ -203,7 +211,7 @@ fn has_chunk_offsets(children: &[u8], depth: usize) -> bool {
203
211
  && u32::from_be_bytes(children[child.content_start + 4..child.content_start + 8].try_into().unwrap()) > 0 => return true,
204
212
  b"co64" if child.end - child.content_start >= 12
205
213
  && 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")
214
+ typ if CONTAINERS.contains(&typ)
207
215
  && has_chunk_offsets(&children[child.content_start..child.end], depth + 1) => return true,
208
216
  _ => {}
209
217
  }
@@ -211,34 +219,35 @@ fn has_chunk_offsets(children: &[u8], depth: usize) -> bool {
211
219
  false
212
220
  }
213
221
 
214
- // default_sample_size from tfhd (flag 0x10), honoring preceding optional fields
215
- fn parse_tfhd(data: &[u8], start: usize) -> Option<u32> {
216
- if start + 8 > data.len() { return None; }
222
+ // default_sample_size from tfhd (flag 0x10), honoring preceding optional fields;
223
+ // every read stays inside the tfhd box — never spills into a sibling box
224
+ fn parse_tfhd(data: &[u8], start: usize, end: usize) -> Option<u32> {
225
+ if start + 8 > end { return None; }
217
226
  let flags: u32 = u32::from_be_bytes(data[start..start + 4].try_into().ok()?) & 0xFFFFFF;
218
227
  let mut pos: usize = start + 8; // version/flags + track_ID
219
228
  if flags & 0x1 != 0 { pos += 8; } // base_data_offset
220
229
  if flags & 0x2 != 0 { pos += 4; } // sample_description_index
221
230
  if flags & 0x8 != 0 { pos += 4; } // default_sample_duration
222
- if flags & 0x10 == 0 || pos + 4 > data.len() { return None; }
231
+ if flags & 0x10 == 0 || pos + 4 > end { return None; }
223
232
  Some(u32::from_be_bytes(data[pos..pos + 4].try_into().ok()?))
224
233
  }
225
234
 
226
235
  // IVs from senc; subsample entries (flag 0x2) are parsed over for IV alignment,
227
- // not applied — samples are fully encrypted
228
- fn parse_senc(data: &[u8], start: usize) -> Option<Vec<[u8; 16]>> {
229
- if start + 8 > data.len() { return None; }
236
+ // not applied — samples are fully encrypted; bounded by the box end, not the file
237
+ fn parse_senc(data: &[u8], start: usize, end: usize) -> Option<Vec<[u8; 16]>> {
238
+ if start + 8 > end { return None; }
230
239
  let flags: u32 = u32::from_be_bytes(data[start..start + 4].try_into().ok()?) & 0xFFFFFF;
231
240
  let count: usize = u32::from_be_bytes(data[start + 4..start + 8].try_into().ok()?) as usize;
232
- if count > (data.len() - start - 8) / 8 { return None; } // hostile count bound
241
+ if count > (end - start - 8) / 8 { return None; } // hostile count bound
233
242
  let mut pos: usize = start + 8;
234
243
  let mut ivs: Vec<[u8; 16]> = Vec::with_capacity(count);
235
244
  for _ in 0..count {
236
- if pos + 8 > data.len() { return None; }
245
+ if pos + 8 > end { return None; }
237
246
  let mut iv: [u8; 16] = [0u8; 16];
238
247
  iv[..8].copy_from_slice(&data[pos..pos + 8]);
239
248
  pos += 8;
240
249
  if flags & 0x2 != 0 {
241
- if pos + 2 > data.len() { return None; }
250
+ if pos + 2 > end { return None; }
242
251
  let sub: usize = u16::from_be_bytes(data[pos..pos + 2].try_into().ok()?) as usize;
243
252
  pos += 2 + sub * 6;
244
253
  }
@@ -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))
@@ -497,6 +532,60 @@ def test_hostile_truncated_sidx(sp, version, content_len):
497
532
  assert isinstance(sp.proc(input=hostile), bytes)
498
533
 
499
534
 
535
+ def test_mdat_largesize_preserved(sp, sample):
536
+ # a 64-bit (largesize) mdat must keep its 64-bit header — a u32 rewrite wraps
537
+ data, expected = sample
538
+ m = find(data, b"mdat")[0]
539
+ content = data[m[1] + 8:m[1] + m[2]]
540
+ large = data[:m[1]] + u32(1) + b"mdat" + struct.pack(">Q", len(content) + 16) + content + data[m[1] + m[2]:]
541
+ out = sp.proc(input=large, key=KEY_HEX)
542
+ pos = out.find(b"mdat") # type word; size field sits right before it
543
+ (size_field,) = struct.unpack_from(">I", out, pos - 4)
544
+ (size64,) = struct.unpack_from(">Q", out, pos + 4)
545
+ assert size_field == 1 and size64 == len(content) + 16
546
+ assert out[pos + 12:pos - 4 + size64] == b"".join(expected[1])
547
+
548
+
549
+ def test_senc_bounded_to_box(sp):
550
+ # senc declares 2 IVs but its box ends before them — the parser must not
551
+ # borrow bytes from the following mdat (would decrypt with garbage IVs
552
+ # and falsely fail strict); instead the fragment counts as partially plain
553
+ enc = ctr_crypt(KEY, bytes(8), bytes([0x5A]) * 40000)
554
+ moof = make_moof(1, [make_tfhd(), make_trun([20000, 20000], 0),
555
+ full_box(b"senc", 0, 0, u32(2))])
556
+ hostile = box(b"ftyp", b"M4A isom") + moof + box(b"mdat", enc) + make_moov()
557
+ out = sp.proc(input=hostile, key=KEY_HEX, strict=True) # must NOT raise code 8
558
+ m = find(out, b"mdat")[0]
559
+ assert out[m[1] + 8:m[1] + m[2]] == enc # untouched passthrough
560
+
561
+
562
+ def test_tfhd_truncated_no_readthrough(sp):
563
+ # tfhd claims the default-size flag but its box ends first — no panic,
564
+ # a coded outcome only (samples fall back to size 0 → undecrypted pass)
565
+ tfhd = full_box(b"tfhd", 0, 0x10, u32(1))
566
+ moof = make_moof(1, [tfhd, make_trun([100] * 4, 0, with_sizes=False),
567
+ make_senc([bytes(8)] * 4)])
568
+ hostile = box(b"ftyp", b"M4A isom") + moof + box(b"mdat", bytes(400))
569
+ try:
570
+ assert isinstance(sp.proc(input=hostile, key=KEY_HEX, strict=True), bytes)
571
+ except DecrypTuneError as e:
572
+ assert e.code in (4, 8)
573
+
574
+
575
+ def test_aproc_cancel_no_tmp_litter(sp, src_file, tmp_path):
576
+ # futures cancelled anywhere in the write path must never leave *.tmp behind
577
+ async def main():
578
+ tasks = [asyncio.create_task(sp.aproc(input=src_file, out=str(tmp_path / f"c{i}.m4a"), key=KEY_HEX))
579
+ for i in range(64)]
580
+ await asyncio.sleep(0.002)
581
+ for t in tasks:
582
+ t.cancel()
583
+ await asyncio.gather(*tasks, return_exceptions=True)
584
+
585
+ asyncio.run(main())
586
+ assert list(tmp_path.glob("*.tmp")) == []
587
+
588
+
500
589
  # ---- metadata ---------------------------------------------------------------
501
590
 
502
591
  def test_udta_first(sp, tagged):
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes