OpenZilo 0.6.3__py3-none-any.whl

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.
openzilo/_codec.py ADDED
@@ -0,0 +1,813 @@
1
+ # SPDX-License-Identifier: MPL-2.0
2
+ """Recording formats (Speex, OP2C Opus) and WAV conversion."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import os
7
+ import shutil
8
+ import struct
9
+ import subprocess
10
+ import time
11
+ from collections.abc import Callable, Mapping
12
+ from dataclasses import dataclass
13
+ from datetime import datetime
14
+ from pathlib import Path
15
+ from typing import Any
16
+
17
+ from ._errors import AudioDecodeError, OpusDecoderUnavailable, SpeexDecoderUnavailable
18
+
19
+
20
+ _FFMPEG_TIMEOUT_S = 30.0
21
+ DEFAULT_SAMPLE_RATE = 16000
22
+ DEFAULT_CHANNELS = 1
23
+ DEFAULT_BIT_DEPTH = 16
24
+ DEFAULT_SPEEX_FRAME_SIZE = 320
25
+ DEFAULT_SPEEX_MAX_PACKET_SIZE = 540
26
+ DEFAULT_SPEEX_QUALITY = 3
27
+ LEGACY_OUTER_FRAME_SIZE = 1026
28
+ SPEEX_BITS_SIZE_BY_QUALITY = {
29
+ 1: 10,
30
+ 2: 15,
31
+ 3: 20,
32
+ 4: 20,
33
+ 5: 28,
34
+ 6: 28,
35
+ 7: 38,
36
+ 8: 38,
37
+ 9: 46,
38
+ 10: 46,
39
+ }
40
+
41
+
42
+ @dataclass(frozen=True)
43
+ class PcmConfig:
44
+ sample_rate: int = DEFAULT_SAMPLE_RATE
45
+ channels: int = DEFAULT_CHANNELS
46
+ bit_depth: int = DEFAULT_BIT_DEPTH
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class SpeexDecodeResult:
51
+ pcm_bytes: bytes
52
+ pcm_config: PcmConfig
53
+ source_type: str = "speex"
54
+ source_extension: str = "spx"
55
+ packet_count: int = 0
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class OpusDecodeResult:
60
+ pcm_bytes: bytes
61
+ pcm_config: PcmConfig
62
+ source_type: str = "opus-stereo"
63
+ source_extension: str = "op2c"
64
+ packet_count: int = 0
65
+
66
+
67
+ @dataclass(frozen=True)
68
+ class PlayableAudio:
69
+ bytes: bytes
70
+ extension: str
71
+ mime: str
72
+ play_mode: str
73
+ label: str
74
+ pcm_config: PcmConfig | None = None
75
+ source_type: str = "raw"
76
+ source_extension: str = "bin"
77
+ source_mime: str = "application/octet-stream"
78
+ description: str = ""
79
+
80
+
81
+ @dataclass(frozen=True)
82
+ class AudioBundle:
83
+ raw_path: Path
84
+ raw_file_name: str
85
+ play_path: Path
86
+ play_file_name: str
87
+ play_mode: str
88
+ format_label: str
89
+ play_description: str
90
+ pcm_summary: str
91
+ raw_size: int
92
+ play_size: int
93
+ source_type: str
94
+ source_extension: str
95
+
96
+
97
+ SpeexDecoder = Callable[[bytes, Mapping[str, Any]], SpeexDecodeResult]
98
+
99
+
100
+ def _ensure_bytes(value: Any) -> bytes:
101
+ if value is None:
102
+ return b""
103
+ if isinstance(value, bytes):
104
+ return value
105
+ if isinstance(value, bytearray):
106
+ return bytes(value)
107
+ if isinstance(value, memoryview):
108
+ return value.tobytes()
109
+ return bytes(value)
110
+
111
+
112
+ def _pad2(value: int) -> str:
113
+ return str(int(value)).zfill(2)
114
+
115
+
116
+ def normalize_pcm_config(config: PcmConfig | Mapping[str, Any] | None = None) -> PcmConfig:
117
+ if isinstance(config, PcmConfig):
118
+ return config
119
+ source = dict(config or {})
120
+ sample_rate = int(
121
+ source.get("sampleRate", source.get("sample_rate", DEFAULT_SAMPLE_RATE))
122
+ or DEFAULT_SAMPLE_RATE
123
+ )
124
+ channels = int(source.get("channels", DEFAULT_CHANNELS) or DEFAULT_CHANNELS)
125
+ bit_depth = int(
126
+ source.get("bitDepth", source.get("bit_depth", DEFAULT_BIT_DEPTH))
127
+ or DEFAULT_BIT_DEPTH
128
+ )
129
+ return PcmConfig(
130
+ sample_rate=max(1, sample_rate),
131
+ channels=2 if channels > 1 else 1,
132
+ bit_depth=8 if bit_depth == 8 else 16,
133
+ )
134
+
135
+
136
+ def format_pcm_config(config: PcmConfig | Mapping[str, Any] | None = None) -> str:
137
+ value = normalize_pcm_config(config)
138
+ return f"{value.sample_rate}Hz / {value.channels}ch / {value.bit_depth}bit"
139
+
140
+
141
+ def build_base_name(
142
+ file_index: int,
143
+ metadata: Mapping[str, Any] | None = None,
144
+ *,
145
+ now_ms: int | None = None,
146
+ ) -> str:
147
+ source = metadata or {}
148
+ record_time = int(source.get("recordTime", source.get("record_time", 0)) or 0)
149
+ base_time_ms = (
150
+ record_time * 1000
151
+ if record_time
152
+ else int(now_ms if now_ms is not None else time.time() * 1000)
153
+ )
154
+ date = datetime.fromtimestamp(base_time_ms / 1000.0)
155
+ suffix_ms = int(now_ms if now_ms is not None else time.time() * 1000)
156
+ return (
157
+ f"openzilo-{int(file_index):03d}-"
158
+ f"{date.year}{_pad2(date.month)}{_pad2(date.day)}-"
159
+ f"{_pad2(date.hour)}{_pad2(date.minute)}{_pad2(date.second)}-"
160
+ f"{suffix_ms}"
161
+ )
162
+
163
+
164
+ def build_audio_bundle_paths(
165
+ file_index: int,
166
+ metadata: Mapping[str, Any] | None = None,
167
+ *,
168
+ output_path: str | os.PathLike[str] | None = None,
169
+ output_dir: str | os.PathLike[str] | None = None,
170
+ now_ms: int | None = None,
171
+ ) -> tuple[Path, Path]:
172
+ if output_path:
173
+ path = Path(output_path)
174
+ suffix = path.suffix.lower()
175
+ if suffix == ".wav":
176
+ return path.with_suffix(".bin"), path
177
+ if suffix == ".bin":
178
+ return path, path.with_suffix(".wav")
179
+ return path.with_suffix(".bin"), path.with_suffix(".wav")
180
+
181
+ base_dir = Path(output_dir or ".")
182
+ base_name = build_base_name(file_index, metadata, now_ms=now_ms)
183
+ return base_dir / f"{base_name}.bin", base_dir / f"{base_name}.wav"
184
+
185
+
186
+ def build_wav_from_pcm(
187
+ input_bytes: Any,
188
+ config: PcmConfig | Mapping[str, Any] | None = None,
189
+ ) -> bytes:
190
+ pcm_bytes = _ensure_bytes(input_bytes)
191
+ pcm_config = normalize_pcm_config(config)
192
+ block_align = (pcm_config.channels * pcm_config.bit_depth) // 8
193
+ byte_rate = pcm_config.sample_rate * block_align
194
+ header = bytearray(44)
195
+ header[0:4] = b"RIFF"
196
+ struct.pack_into("<I", header, 4, 36 + len(pcm_bytes))
197
+ header[8:12] = b"WAVE"
198
+ header[12:16] = b"fmt "
199
+ struct.pack_into("<I", header, 16, 16)
200
+ struct.pack_into("<H", header, 20, 1)
201
+ struct.pack_into("<H", header, 22, pcm_config.channels)
202
+ struct.pack_into("<I", header, 24, pcm_config.sample_rate)
203
+ struct.pack_into("<I", header, 28, byte_rate)
204
+ struct.pack_into("<H", header, 32, block_align)
205
+ struct.pack_into("<H", header, 34, pcm_config.bit_depth)
206
+ header[36:40] = b"data"
207
+ struct.pack_into("<I", header, 40, len(pcm_bytes))
208
+ return bytes(header) + pcm_bytes
209
+
210
+
211
+ def _read_ascii(data: bytes, start: int, length: int) -> str:
212
+ return data[start : start + length].decode("ascii", errors="ignore")
213
+
214
+
215
+ def _find_ascii(data: bytes, target: str, max_scan_length: int | None = None) -> int:
216
+ limit = min(len(data), max_scan_length or len(data))
217
+ return data[:limit].find(target.encode("ascii"))
218
+
219
+
220
+ def is_wav(data: bytes) -> bool:
221
+ return len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WAVE"
222
+
223
+
224
+ def is_ogg_speex(data: bytes) -> bool:
225
+ return len(data) >= 36 and data[:4] == b"OggS" and (
226
+ _read_ascii(data, 28, 8) == "Speex "
227
+ or _find_ascii(data, "Speex ", 128) != -1
228
+ )
229
+
230
+
231
+ def pick_speex_mode(sample_rate: int) -> int:
232
+ if sample_rate <= 8000:
233
+ return 0
234
+ if sample_rate <= 16000:
235
+ return 1
236
+ return 2
237
+
238
+
239
+ def pick_frame_size(sample_rate: int) -> int:
240
+ if sample_rate <= 8000:
241
+ return 160
242
+ if sample_rate <= 16000:
243
+ return 320
244
+ return 640
245
+
246
+
247
+ def pick_bits_size(
248
+ quality: int = DEFAULT_SPEEX_QUALITY,
249
+ bits_size: int | None = None,
250
+ ) -> int:
251
+ if bits_size and bits_size > 0:
252
+ return int(bits_size)
253
+ return SPEEX_BITS_SIZE_BY_QUALITY.get(int(quality or DEFAULT_SPEEX_QUALITY), 20)
254
+
255
+
256
+ def _is_padding_byte(value: int) -> bool:
257
+ return value in (0x00, 0xFF)
258
+
259
+
260
+ def parse_packetized_speex_stream(
261
+ data: Any,
262
+ *,
263
+ max_packet_size: int = DEFAULT_SPEEX_MAX_PACKET_SIZE,
264
+ allow_framed_blocks: bool = True,
265
+ framed_block_size: int = LEGACY_OUTER_FRAME_SIZE,
266
+ ) -> list[bytes] | None:
267
+ source = _ensure_bytes(data)
268
+ max_size = max(1, int(max_packet_size or DEFAULT_SPEEX_MAX_PACKET_SIZE))
269
+
270
+ def parse_block(start: int, end: int) -> list[bytes] | None:
271
+ packets: list[bytes] = []
272
+ offset = start
273
+ while offset + 2 <= end:
274
+ packet_length = struct.unpack_from("<H", source, offset)[0]
275
+ if not packet_length:
276
+ break
277
+ if packet_length > max_size or offset + 2 + packet_length > end:
278
+ return None
279
+ packets.append(source[offset + 2 : offset + 2 + packet_length])
280
+ offset += 2 + packet_length
281
+ if not packets:
282
+ return None
283
+ if any(not _is_padding_byte(item) for item in source[offset:end]):
284
+ return None
285
+ return packets
286
+
287
+ direct = parse_block(0, len(source))
288
+ if direct:
289
+ return direct
290
+ if not allow_framed_blocks:
291
+ return None
292
+
293
+ block_size = max(1, int(framed_block_size or LEGACY_OUTER_FRAME_SIZE))
294
+ if len(source) <= block_size:
295
+ return None
296
+
297
+ packets: list[bytes] = []
298
+ for start in range(0, len(source), block_size):
299
+ block = parse_block(start, min(len(source), start + block_size))
300
+ if not block:
301
+ return None
302
+ packets.extend(block)
303
+ return packets
304
+
305
+
306
+ def split_raw_speex_packets(
307
+ data: Any,
308
+ *,
309
+ quality: int = DEFAULT_SPEEX_QUALITY,
310
+ bits_size: int | None = None,
311
+ ) -> list[bytes] | None:
312
+ source = _ensure_bytes(data)
313
+ size = pick_bits_size(quality=quality, bits_size=bits_size)
314
+ if len(source) < size or len(source) % size != 0:
315
+ return None
316
+ return [source[offset : offset + size] for offset in range(0, len(source), size)]
317
+
318
+
319
+ def _ogg_crc(data: bytes) -> int:
320
+ crc = 0
321
+ for value in data:
322
+ crc ^= value << 24
323
+ for _ in range(8):
324
+ if crc & 0x80000000:
325
+ crc = ((crc << 1) ^ 0x04C11DB7) & 0xFFFFFFFF
326
+ else:
327
+ crc = (crc << 1) & 0xFFFFFFFF
328
+ return crc & 0xFFFFFFFF
329
+
330
+
331
+ def _packet_lacing(packet: bytes) -> list[int]:
332
+ length = len(packet)
333
+ lacing: list[int] = []
334
+ while length >= 255:
335
+ lacing.append(255)
336
+ length -= 255
337
+ lacing.append(length)
338
+ return lacing
339
+
340
+
341
+ def _build_ogg_page(
342
+ packet: bytes,
343
+ *,
344
+ header_type: int,
345
+ granule_position: int,
346
+ serial: int,
347
+ sequence: int,
348
+ ) -> bytes:
349
+ lacing = _packet_lacing(packet)
350
+ if len(lacing) > 255:
351
+ raise ValueError("single Ogg page cannot contain this packet")
352
+ header = bytearray(
353
+ struct.pack(
354
+ "<4sBBQIIIB",
355
+ b"OggS",
356
+ 0,
357
+ header_type & 0xFF,
358
+ max(0, int(granule_position)),
359
+ serial & 0xFFFFFFFF,
360
+ sequence & 0xFFFFFFFF,
361
+ 0,
362
+ len(lacing),
363
+ )
364
+ )
365
+ page = bytes(header) + bytes(lacing) + packet
366
+ checksum = _ogg_crc(page)
367
+ return page[:22] + struct.pack("<I", checksum) + page[26:]
368
+
369
+
370
+ def build_ogg_speex(
371
+ packets: list[bytes],
372
+ *,
373
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
374
+ serial: int = 0x564F5247,
375
+ ) -> bytes:
376
+ config = normalize_pcm_config(pcm_config)
377
+ frame_size = pick_frame_size(config.sample_rate)
378
+ mode = pick_speex_mode(config.sample_rate)
379
+ version = b"speex-1.2.1"
380
+ version = version + b"\x00" * (20 - len(version))
381
+ speex_header = struct.pack(
382
+ "<8s20s13i",
383
+ b"Speex ",
384
+ version,
385
+ 1,
386
+ 80,
387
+ config.sample_rate,
388
+ mode,
389
+ 4,
390
+ 1,
391
+ -1,
392
+ frame_size,
393
+ 0,
394
+ 1,
395
+ 0,
396
+ 0,
397
+ 0,
398
+ )
399
+ vendor = b"openzilo-python"
400
+ comments = struct.pack("<I", len(vendor)) + vendor + struct.pack("<I", 0)
401
+
402
+ pages = [
403
+ _build_ogg_page(
404
+ speex_header,
405
+ header_type=2,
406
+ granule_position=0,
407
+ serial=serial,
408
+ sequence=0,
409
+ ),
410
+ _build_ogg_page(
411
+ comments,
412
+ header_type=0,
413
+ granule_position=0,
414
+ serial=serial,
415
+ sequence=1,
416
+ ),
417
+ ]
418
+
419
+ granule = 0
420
+ for index, packet in enumerate(packets):
421
+ granule += frame_size
422
+ pages.append(
423
+ _build_ogg_page(
424
+ packet,
425
+ header_type=4 if index == len(packets) - 1 else 0,
426
+ granule_position=granule,
427
+ serial=serial,
428
+ sequence=index + 2,
429
+ )
430
+ )
431
+ return b"".join(pages)
432
+
433
+
434
+ def normalize_decoded_speex_pcm(
435
+ pcm_bytes: bytes,
436
+ *,
437
+ packet_count: int,
438
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
439
+ ) -> bytes:
440
+ config = normalize_pcm_config(pcm_config)
441
+ count = max(0, int(packet_count or 0))
442
+ if not pcm_bytes or count <= 0:
443
+ return pcm_bytes
444
+
445
+ bytes_per_sample = max(1, config.bit_depth // 8)
446
+ frame_bytes = pick_frame_size(config.sample_rate) * config.channels * bytes_per_sample
447
+ expected_bytes = frame_bytes * count
448
+ if frame_bytes <= 0 or len(pcm_bytes) <= expected_bytes:
449
+ return pcm_bytes
450
+
451
+ decoded_bytes_per_packet = len(pcm_bytes) // count
452
+ if len(pcm_bytes) % count != 0 or decoded_bytes_per_packet % frame_bytes != 0:
453
+ return pcm_bytes
454
+
455
+ return b"".join(
456
+ pcm_bytes[offset : offset + frame_bytes]
457
+ for offset in range(0, len(pcm_bytes), decoded_bytes_per_packet)
458
+ )
459
+
460
+
461
+ def _decode_ogg_with_ffmpeg(
462
+ ogg_bytes: bytes,
463
+ *,
464
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
465
+ ffmpeg_path: str = "ffmpeg",
466
+ codec: str = "Speex",
467
+ ) -> bytes:
468
+ config = normalize_pcm_config(pcm_config)
469
+ unavailable = SpeexDecoderUnavailable if codec == "Speex" else OpusDecoderUnavailable
470
+ if not shutil.which(ffmpeg_path) and os.path.sep not in ffmpeg_path:
471
+ raise unavailable(
472
+ f"ffmpeg is required to decode {codec}. Install ffmpeg or pass --ffmpeg."
473
+ )
474
+ command = [
475
+ ffmpeg_path,
476
+ "-hide_banner",
477
+ "-loglevel",
478
+ "error",
479
+ "-f",
480
+ "ogg",
481
+ "-i",
482
+ "pipe:0",
483
+ "-f",
484
+ "s16le" if config.bit_depth == 16 else "u8",
485
+ "-ac",
486
+ str(config.channels),
487
+ "-ar",
488
+ str(config.sample_rate),
489
+ "pipe:1",
490
+ ]
491
+ if codec == "Opus":
492
+ command.insert(1, "-xerror")
493
+ try:
494
+ completed = subprocess.run(
495
+ command,
496
+ input=ogg_bytes,
497
+ stdout=subprocess.PIPE,
498
+ stderr=subprocess.PIPE,
499
+ check=False,
500
+ timeout=_FFMPEG_TIMEOUT_S,
501
+ )
502
+ except subprocess.TimeoutExpired as exc:
503
+ raise AudioDecodeError(f"ffmpeg {codec} decode timed out after {_FFMPEG_TIMEOUT_S:g} seconds") from exc
504
+ except FileNotFoundError as exc:
505
+ raise unavailable(
506
+ f"ffmpeg is required to decode {codec}. Install ffmpeg or pass --ffmpeg."
507
+ ) from exc
508
+
509
+ if completed.returncode != 0:
510
+ error_text = completed.stderr.decode("utf-8", errors="replace").strip()
511
+ raise AudioDecodeError(f"ffmpeg {codec} decode failed: {error_text[:500]}")
512
+ return completed.stdout
513
+
514
+
515
+ def decode_ogg_speex_with_ffmpeg(
516
+ ogg_bytes: bytes,
517
+ *,
518
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
519
+ ffmpeg_path: str = "ffmpeg",
520
+ ) -> bytes:
521
+ return _decode_ogg_with_ffmpeg(ogg_bytes, pcm_config=pcm_config, ffmpeg_path=ffmpeg_path)
522
+
523
+
524
+ def decode_speex_to_pcm(
525
+ data: Any,
526
+ *,
527
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
528
+ quality: int = DEFAULT_SPEEX_QUALITY,
529
+ bits_size: int | None = None,
530
+ allow_framed_blocks: bool = False,
531
+ ffmpeg_path: str = "ffmpeg",
532
+ speex_decoder: SpeexDecoder | None = None,
533
+ ) -> SpeexDecodeResult:
534
+ source = _ensure_bytes(data)
535
+ if not source:
536
+ raise AudioDecodeError("Speex data is empty")
537
+
538
+ config = normalize_pcm_config(pcm_config)
539
+ options = {
540
+ "pcm_config": config,
541
+ "quality": quality,
542
+ "bits_size": bits_size,
543
+ "allow_framed_blocks": allow_framed_blocks,
544
+ "ffmpeg_path": ffmpeg_path,
545
+ }
546
+ if speex_decoder:
547
+ return speex_decoder(source, options)
548
+
549
+ if is_ogg_speex(source):
550
+ pcm = decode_ogg_speex_with_ffmpeg(
551
+ source,
552
+ pcm_config=config,
553
+ ffmpeg_path=ffmpeg_path,
554
+ )
555
+ return SpeexDecodeResult(
556
+ pcm_bytes=pcm,
557
+ pcm_config=config,
558
+ source_type="ogg-speex",
559
+ source_extension="spx",
560
+ )
561
+
562
+ packets = parse_packetized_speex_stream(
563
+ source,
564
+ allow_framed_blocks=allow_framed_blocks,
565
+ )
566
+ source_type = "packet-speex"
567
+ if not packets:
568
+ packets = split_raw_speex_packets(
569
+ source,
570
+ quality=quality,
571
+ bits_size=bits_size,
572
+ )
573
+ source_type = "raw-speex"
574
+ if not packets:
575
+ raise AudioDecodeError("bin data does not look like packetized or raw Speex")
576
+
577
+ ogg = build_ogg_speex(packets, pcm_config=config)
578
+ pcm = decode_ogg_speex_with_ffmpeg(ogg, pcm_config=config, ffmpeg_path=ffmpeg_path)
579
+ pcm = normalize_decoded_speex_pcm(pcm, packet_count=len(packets), pcm_config=config)
580
+ return SpeexDecodeResult(
581
+ pcm_bytes=pcm,
582
+ pcm_config=config,
583
+ source_type=source_type,
584
+ source_extension="spx",
585
+ packet_count=len(packets),
586
+ )
587
+
588
+
589
+ _OP2C_HEADER = struct.pack("<4sHHHH", b"OP2C", 1, 2, 16000, 320)
590
+
591
+
592
+ def _validate_opus_packet(packet: bytes, *, channels: int = 2) -> None:
593
+ if not 1 <= len(packet) <= 100:
594
+ raise AudioDecodeError("Opus packet length must be 1..100 bytes")
595
+ toc = packet[0]
596
+ if channels not in (1, 2) or bool(toc & 4) != (channels == 2):
597
+ raise AudioDecodeError("Opus packet channels do not match the recording")
598
+ # Same TOC duration calculation as libopus opus_packet_get_samples_per_frame.
599
+ if toc & 0x80:
600
+ samples = (16000 << ((toc >> 3) & 3)) // 400
601
+ elif toc & 0x60 == 0x60:
602
+ samples = 320 if toc & 8 else 160
603
+ else:
604
+ mode = (toc >> 3) & 3
605
+ samples = 960 if mode == 3 else (16000 << mode) // 100
606
+ code = toc & 3
607
+ if code == 3 and len(packet) < 2:
608
+ raise AudioDecodeError("Truncated Opus frame count")
609
+ frames = 1 if code == 0 else (packet[1] & 63 if code == 3 else 2)
610
+ if samples * frames != 320:
611
+ raise AudioDecodeError("Opus packet must contain 20 ms per channel")
612
+
613
+
614
+ def _opus_recording_channels(source: bytes) -> int:
615
+ if len(source) < 12:
616
+ raise AudioDecodeError("Unsupported or truncated OP2C header")
617
+ magic, version, channels, rate, frames = struct.unpack_from("<4sHHHH", source)
618
+ if magic != b"OP2C" or version != 1 or channels not in (1, 2) or (rate, frames) != (16000, 320):
619
+ raise AudioDecodeError("Unsupported OP2C header")
620
+ return channels
621
+
622
+
623
+ def parse_opus_recording(data: Any) -> list[bytes]:
624
+ """Parse version-1, 16 kHz mono/stereo OP2C; reject truncation and padding."""
625
+ source = _ensure_bytes(data)
626
+ channels = _opus_recording_channels(source)
627
+ packets = []
628
+ offset = 12
629
+ while offset < len(source):
630
+ if len(source) - offset < 2:
631
+ raise AudioDecodeError("Truncated Opus packet length")
632
+ length = struct.unpack_from("<H", source, offset)[0]
633
+ offset += 2
634
+ if not 1 <= length <= 100 or offset + length > len(source):
635
+ raise AudioDecodeError("Invalid or truncated Opus packet")
636
+ packet = source[offset:offset + length]
637
+ _validate_opus_packet(packet, channels=channels)
638
+ packets.append(packet)
639
+ offset += length
640
+ return packets
641
+
642
+
643
+ def build_opus_recording(packets: list[bytes], *, channels: int = 2) -> bytes:
644
+ """Package consecutive mono/stereo 20 ms Opus packets as an OP2C file."""
645
+ if isinstance(channels, bool) or channels not in (1, 2):
646
+ raise ValueError("channels must be 1 or 2")
647
+ chunks = [struct.pack("<4sHHHH", b"OP2C", 1, channels, 16000, 320)]
648
+ for packet in packets:
649
+ packet = bytes(packet)
650
+ _validate_opus_packet(packet, channels=channels)
651
+ chunks.append(struct.pack("<H", len(packet)) + packet)
652
+ return b"".join(chunks)
653
+
654
+
655
+ def decode_opus_to_pcm(data: Any, *, ffmpeg_path: str = "ffmpeg") -> OpusDecodeResult:
656
+ """Decode OP2C into 16 kHz mono/stereo signed 16-bit PCM."""
657
+ packets = parse_opus_recording(data)
658
+ channels = _opus_recording_channels(_ensure_bytes(data))
659
+ config = PcmConfig(sample_rate=16000, channels=channels, bit_depth=16)
660
+ if not packets:
661
+ return OpusDecodeResult(b"", config, packet_count=0, source_type="opus-mono" if channels == 1 else "opus-stereo")
662
+ # Ogg Opus granules always use 48 kHz. OP2C has no pre-skip metadata;
663
+ # preserve every decoded sample just like the firmware reference decoder.
664
+ header = struct.pack("<8sBBHIhB", b"OpusHead", 1, channels, 0, 16000, 0, 0)
665
+ vendor = b"openzilo-python"
666
+ tags = b"OpusTags" + struct.pack("<I", len(vendor)) + vendor + struct.pack("<I", 0)
667
+ pages = [
668
+ _build_ogg_page(header, header_type=2, granule_position=0, serial=0x4F503243, sequence=0),
669
+ _build_ogg_page(tags, header_type=0, granule_position=0, serial=0x4F503243, sequence=1),
670
+ ]
671
+ for index, packet in enumerate(packets):
672
+ pages.append(_build_ogg_page(
673
+ packet, header_type=4 if index == len(packets) - 1 else 0,
674
+ granule_position=(index + 1) * 960, serial=0x4F503243, sequence=index + 2,
675
+ ))
676
+ pcm = _decode_ogg_with_ffmpeg(
677
+ b"".join(pages), pcm_config=config, ffmpeg_path=ffmpeg_path, codec="Opus",
678
+ )
679
+ if len(pcm) != len(packets) * 320 * channels * 2:
680
+ raise AudioDecodeError("Opus decoder returned an unexpected PCM length")
681
+ return OpusDecodeResult(pcm, config, packet_count=len(packets), source_type="opus-mono" if channels == 1 else "opus-stereo")
682
+
683
+
684
+ def build_playable_audio(
685
+ data: Any,
686
+ *,
687
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
688
+ quality: int = DEFAULT_SPEEX_QUALITY,
689
+ bits_size: int | None = None,
690
+ allow_framed_blocks: bool = False,
691
+ ffmpeg_path: str = "ffmpeg",
692
+ speex_decoder: SpeexDecoder | None = None,
693
+ ) -> PlayableAudio:
694
+ source = _ensure_bytes(data)
695
+ if is_wav(source):
696
+ return PlayableAudio(
697
+ bytes=source,
698
+ extension="wav",
699
+ mime="audio/wav",
700
+ play_mode="direct",
701
+ label="WAV",
702
+ source_type="wav",
703
+ source_extension="wav",
704
+ source_mime="audio/wav",
705
+ description="Detected WAV audio; saved directly.",
706
+ )
707
+
708
+ if source.startswith(b"OP2C"):
709
+ decoded_opus = decode_opus_to_pcm(source, ffmpeg_path=ffmpeg_path)
710
+ return PlayableAudio(
711
+ bytes=build_wav_from_pcm(decoded_opus.pcm_bytes, decoded_opus.pcm_config),
712
+ extension="wav", mime="audio/wav", play_mode="opus-decode", label="WAV",
713
+ pcm_config=decoded_opus.pcm_config, source_type=decoded_opus.source_type,
714
+ source_extension="op2c", source_mime="application/octet-stream",
715
+ description=f"Decoded Opus as 16 kHz, {decoded_opus.pcm_config.channels}-channel, 16-bit WAV.",
716
+ )
717
+
718
+ decoded = decode_speex_to_pcm(
719
+ source,
720
+ pcm_config=pcm_config,
721
+ quality=quality,
722
+ bits_size=bits_size,
723
+ allow_framed_blocks=allow_framed_blocks,
724
+ ffmpeg_path=ffmpeg_path,
725
+ speex_decoder=speex_decoder,
726
+ )
727
+ wav_bytes = build_wav_from_pcm(decoded.pcm_bytes, decoded.pcm_config)
728
+ return PlayableAudio(
729
+ bytes=wav_bytes,
730
+ extension="wav",
731
+ mime="audio/wav",
732
+ play_mode="speex-decode",
733
+ label="WAV",
734
+ pcm_config=decoded.pcm_config,
735
+ source_type=decoded.source_type,
736
+ source_extension=decoded.source_extension,
737
+ source_mime="audio/x-speex",
738
+ description=f"Decoded Speex and wrapped as WAV. {format_pcm_config(decoded.pcm_config)}",
739
+ )
740
+
741
+
742
+ def decode_audio_to_wav(
743
+ data: Any,
744
+ *,
745
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
746
+ quality: int = DEFAULT_SPEEX_QUALITY,
747
+ bits_size: int | None = None,
748
+ allow_framed_blocks: bool = False,
749
+ ffmpeg_path: str = "ffmpeg",
750
+ speex_decoder: SpeexDecoder | None = None,
751
+ ) -> bytes:
752
+ """Decode ring recording bytes into WAV bytes."""
753
+ return build_playable_audio(
754
+ data,
755
+ pcm_config=pcm_config,
756
+ quality=quality,
757
+ bits_size=bits_size,
758
+ allow_framed_blocks=allow_framed_blocks,
759
+ ffmpeg_path=ffmpeg_path,
760
+ speex_decoder=speex_decoder,
761
+ ).bytes
762
+
763
+
764
+ def save_audio_bundle(
765
+ *,
766
+ file_index: int,
767
+ data: Any,
768
+ metadata: Mapping[str, Any] | None = None,
769
+ output_path: str | os.PathLike[str] | None = None,
770
+ output_dir: str | os.PathLike[str] | None = None,
771
+ pcm_config: PcmConfig | Mapping[str, Any] | None = None,
772
+ quality: int = DEFAULT_SPEEX_QUALITY,
773
+ bits_size: int | None = None,
774
+ allow_framed_blocks: bool = False,
775
+ ffmpeg_path: str = "ffmpeg",
776
+ speex_decoder: SpeexDecoder | None = None,
777
+ ) -> AudioBundle:
778
+ raw_bytes = _ensure_bytes(data)
779
+ raw_path, play_path = build_audio_bundle_paths(
780
+ file_index,
781
+ metadata,
782
+ output_path=output_path,
783
+ output_dir=output_dir,
784
+ )
785
+ raw_path.parent.mkdir(parents=True, exist_ok=True)
786
+ play_path.parent.mkdir(parents=True, exist_ok=True)
787
+ raw_path.write_bytes(raw_bytes)
788
+
789
+ playable = build_playable_audio(
790
+ raw_bytes,
791
+ pcm_config=pcm_config,
792
+ quality=quality,
793
+ bits_size=bits_size,
794
+ allow_framed_blocks=allow_framed_blocks,
795
+ ffmpeg_path=ffmpeg_path,
796
+ speex_decoder=speex_decoder,
797
+ )
798
+ play_path.write_bytes(playable.bytes)
799
+
800
+ return AudioBundle(
801
+ raw_path=raw_path,
802
+ raw_file_name=raw_path.name,
803
+ play_path=play_path,
804
+ play_file_name=play_path.name,
805
+ play_mode=playable.play_mode,
806
+ format_label=playable.label,
807
+ play_description=playable.description,
808
+ pcm_summary=format_pcm_config(playable.pcm_config or pcm_config),
809
+ raw_size=len(raw_bytes),
810
+ play_size=len(playable.bytes),
811
+ source_type=playable.source_type,
812
+ source_extension=playable.source_extension,
813
+ )