audio_container.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. """Shared magic-byte audio/AV container detection — the ONE sniffer for the codebase.
  2. Outbound (``tools/tts_tool.py``): TTS backends silently ignore the requested
  3. format (Edge emits MP3, Piper WAV), so the file is sniffed and its ``.ogg``
  4. extension repaired. Inbound (``gateway/platforms/base.py`` cache_audio_*,
  5. ``plugins/platforms/signal/adapter.py``): adapters pass wrong/guessed voice-note
  6. extensions (Telegram ``.oga``, iOS M4A-branded MP4), so the cache sniffs the
  7. real container for STT and players. Only audio/AV containers are claimed:
  8. RIFF/WEBP and other images return ``None`` so callers check images first.
  9. """
  10. from __future__ import annotations
  11. from typing import Optional
  12. # Container id -> canonical file extension.
  13. CONTAINER_TO_EXT = {c: f".{c}" for c in ("m4a", "mp4", "ogg", "flac", "wav", "mp3", "aac", "webm")}
  14. # MP4 ftyp brands that mean "this is audio" (iOS voice notes use M4A ).
  15. _MP4_AUDIO_BRANDS = (b"m4a ", b"m4b ")
  16. # Unambiguous fixed prefixes (checked after ftyp/RIFF, which need bytes 8-11).
  17. _PREFIX_CONTAINERS = ((b"OggS", "ogg"), (b"fLaC", "flac"), (b"ID3", "mp3"))
  18. def sniff_container(data: bytes) -> Optional[str]:
  19. """Return a CONTAINER_TO_EXT key from magic bytes, or ``None`` when unknown."""
  20. if len(data) >= 8 and data[4:8] == b"ftyp":
  21. # Brand at bytes 8-11: "M4A "/"M4B " are voice notes/audiobooks;
  22. # everything else (isom/mp42/avc1/qt) is video.
  23. if len(data) >= 12 and data[8:12].lower() in _MP4_AUDIO_BRANDS:
  24. return "m4a"
  25. return "mp4"
  26. for prefix, container in _PREFIX_CONTAINERS:
  27. if data.startswith(prefix):
  28. return container
  29. if len(data) >= 12 and data[:4] == b"RIFF" and data[8:12] == b"WAVE":
  30. return "wav"
  31. if len(data) >= 2 and data[0] == 0xFF and (data[1] & 0xE0) == 0xE0:
  32. # ``0xFF 0xFx`` sync word is shared by MP3 and ADTS AAC; bits 3-1 of
  33. # byte 1 disambiguate: ADTS has ID=0, layer=00 (mask 0xF6 -> 0xF0).
  34. return "aac" if (data[1] & 0xF6) == 0xF0 else "mp3"
  35. if data.startswith(b"\x1a\x45\xdf\xa3"):
  36. return "webm"
  37. return None
  38. def sniff_audio_ext(data: bytes, fallback_ext: str = ".ogg") -> str:
  39. """Return a container-matching extension, or ``fallback_ext`` when unknown.
  40. Callers *claim* audio, so generic MP4 maps to ``.m4a`` (payload is AAC regardless
  41. of brand; STT accepts both but voice-bubble routing keys off audio extensions)."""
  42. fallback = fallback_ext if fallback_ext.startswith(".") else f".{fallback_ext}"
  43. container = sniff_container(data)
  44. if container is None:
  45. return fallback
  46. return ".m4a" if container == "mp4" else CONTAINER_TO_EXT[container]