fix(music): remux songs into the container of their codec

A song skips the muxer, so the decrypted fragmented MP4 was the delivered file: its header states a length of zero and FLAC in an MP4 is not a FLAC stream, so playback stopped early and tagging failed.
This commit is contained in:
imSp4rky
2026-08-21 14:00:04 -06:00
parent 79cabc9a70
commit a4be2cd23a
6 changed files with 387 additions and 13 deletions
+11 -8
View File
@@ -36,10 +36,11 @@ try:
)
from mutagen.mp3 import MP3
from mutagen.mp4 import MP4, MP4Cover
from mutagen.oggopus import OggOpus
from mutagen.oggvorbis import OggVorbis
except ImportError: # pragma: no cover - optional tagging dependency
FLAC = Picture = None
MP3 = MP4 = MP4Cover = OggVorbis = None
MP3 = MP4 = MP4Cover = OggOpus = OggVorbis = None # type: ignore[assignment]
ID3NoHeaderError = Exception
APIC = COMM = TALB = TCOM = TCON = TCOP = TDRC = TIT2 = TPE1 = TPE2 = TPOS = TRCK = TSRC = TXXX = None
USLT = None
@@ -65,10 +66,10 @@ class MusicMetadataResult:
def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_md5: str = "") -> MusicMetadataResult:
"""Write normalized music metadata for FLAC, Ogg, MP3, and M4A/MP4 audio files."""
"""Write normalized music metadata for FLAC, Ogg, Opus, MP3, and M4A/MP4 audio files."""
path = Path(path)
extension = path.suffix.lower()
if extension not in {".flac", ".mp3", ".m4a", ".mp4", ".ogg"}:
if extension not in {".flac", ".mp3", ".m4a", ".mp4", ".ogg", ".opus"}:
return MusicMetadataResult(skipped=True, reason=f"Unsupported music metadata container: {extension}")
if extension == ".flac" and FLAC is None:
@@ -77,7 +78,7 @@ def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_m
return MusicMetadataResult(skipped=True, reason="install mutagen to write MP3 tags")
if extension in {".m4a", ".mp4"} and MP4 is None:
return MusicMetadataResult(skipped=True, reason="install mutagen to write MP4/M4A tags")
if extension == ".ogg" and OggVorbis is None:
if extension in {".ogg", ".opus"} and OggVorbis is None:
return MusicMetadataResult(skipped=True, reason="install mutagen to write Ogg tags")
tags = build_tag_values(song, source_md5=source_md5)
@@ -86,8 +87,8 @@ def write_music_metadata(path: Path, song: Any, *, session: Any = None, source_m
if extension == ".flac":
write_flac_tags(path, tags, cover_data, mime_type)
elif extension == ".ogg":
write_ogg_tags(path, tags, cover_data, mime_type)
elif extension in {".ogg", ".opus"}:
write_ogg_tags(path, tags, cover_data, mime_type, OggOpus if extension == ".opus" else OggVorbis)
elif extension == ".mp3":
write_mp3_tags(path, tags, cover_data, mime_type)
else:
@@ -180,8 +181,10 @@ def build_picture(cover_data: Optional[bytes], mime_type: str) -> Optional[Any]:
return picture
def write_ogg_tags(path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str) -> None:
audio = OggVorbis(path)
def write_ogg_tags(
path: Path, tags: dict[str, str], cover_data: Optional[bytes], mime_type: str, reader: Any = None
) -> None:
audio = (reader or OggVorbis)(path)
for key, value in tags.items():
audio[key] = [value]
picture = build_picture(cover_data, mime_type)
+73
View File
@@ -1,9 +1,11 @@
from __future__ import annotations
import math
import subprocess
from enum import Enum
from typing import Any, Optional, Union
from unshackle.core import binaries
from unshackle.core.tracks.track import Track
@@ -208,6 +210,77 @@ class Audio(Track):
return float(channels)
def to_music_container(self) -> bool:
"""Remux the track into the container of its codec, as a standalone audio file.
Music titles never reach the muxer, so the downloaded file is the delivered file, and
after decryption that is still a fragmented MP4. Its header states a length of zero, so
a player stops after the first fragment. FLAC inside an MP4 is also not a FLAC stream.
A rename cannot correct either fault. Returns True once the new file replaces the
downloaded one; every failure raises.
"""
if not self.path or not self.path.exists():
raise ValueError("Cannot remux a Track that has not been downloaded.")
if not binaries.FFMPEG:
raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
containers: dict[Optional[Audio.Codec], str] = {
Audio.Codec.FLAC: ".flac",
Audio.Codec.OPUS: ".opus",
Audio.Codec.OGG: ".ogg",
}
extension = containers.get(self.codec, ".m4a")
original_path = self.path
output_path = original_path.with_name(f"{original_path.stem}_music{extension}")
def ffmpeg(*extra_args: str) -> None:
subprocess.run(
[
str(binaries.FFMPEG),
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-i",
str(original_path),
"-map",
"0:a:0",
"-map_metadata",
"-1",
# a copy keeps the source STREAMINFO, whose sample count a fragmenting writer
# leaves at zero, so the FLAC states no length; the encoder writes a real one
*(["-c:a", "flac"] if extension == ".flac" else ["-c", "copy"]),
# the fragmented moov is what cuts playback short, so ask for one contiguous header
*(["-movflags", "+faststart"] if extension == ".m4a" else []),
*extra_args,
str(output_path),
],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
try:
ffmpeg()
except subprocess.CalledProcessError as e:
if b"not currently supported in container" not in e.stderr:
raise
# a .m4a name picks FFmpeg's ipod muxer, which refuses Dolby Digital Plus and the
# other codecs Apple never put in an M4A; the plain mp4 muxer accepts them
ffmpeg("-f", "mp4")
except subprocess.CalledProcessError:
# FFmpeg creates the output before it fails, and nothing sweeps the shared temp
# directory for it, so a failed run must remove its own partial file
output_path.unlink(missing_ok=True)
raise
original_path.unlink()
self.path = output_path
return True
def get_track_name(self) -> Optional[str]:
"""Return the base Track Name."""
track_name = super().get_track_name() or ""