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
+144
View File
@@ -0,0 +1,144 @@
"""``Audio.to_music_container`` must turn a fragmented MP4 into a playable, taggable file.
Music titles never reach the muxer, so the downloaded fragmented MP4 is what the user gets.
Its ``mvhd`` states a length of zero, so a player stops after the first fragment. FLAC
inside an MP4 is also not a FLAC stream. Each test builds a real MP4 with FFmpeg and reads
the result back with mutagen, which reads the header only, exactly as a player does.
FFprobe cannot prove this, because it scans every fragment and reports the true length
either way.
"""
from __future__ import annotations
import shutil
import subprocess
from pathlib import Path
import mutagen
import pytest
from tests.core.test_music_tagger_roundtrip import make_song
from unshackle.core.music.tagger import write_music_metadata
from unshackle.core.tracks import Audio
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="requires ffmpeg")
def encode(path: Path, encoder: str, *extra_args: str) -> Path:
subprocess.run(
[
"ffmpeg",
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-f",
"lavfi",
"-i",
"sine=f=440:r=44100:d=6",
"-ac",
"2",
"-c:a",
encoder,
"-strict",
"-2", # flac and opus in mp4 are flagged experimental by the muxer
*extra_args,
str(path),
],
check=True,
)
return path
def fragmented_mp4(path: Path, encoder: str) -> Path:
return encode(path, encoder, "-movflags", "frag_keyframe+empty_moov+default_base_moof", "-frag_duration", "1000000")
def header_length(path: Path) -> float:
"""The length the file states in its header, which is what a player and the tagger read."""
return mutagen.File(path).info.length
@pytest.mark.parametrize(
("codec", "encoder", "extension"),
[
(Audio.Codec.AAC, "aac", ".m4a"),
(Audio.Codec.ALAC, "alac", ".m4a"),
(Audio.Codec.FLAC, "flac", ".flac"),
(Audio.Codec.OPUS, "libopus", ".opus"),
],
)
def test_remux_states_the_full_length_in_the_codec_container(
tmp_path: Path, codec: Audio.Codec, encoder: str, extension: str
) -> None:
source = fragmented_mp4(tmp_path / "track.mp4", encoder)
assert header_length(source) == 0.0, "the fixture must reproduce the fault the remux corrects"
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=codec)
track.path = source
assert track.to_music_container() is True
assert track.path.suffix == extension
assert not source.exists()
assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
assert write_music_metadata(track.path, make_song()).written, "the remuxed file must accept tags"
def test_flac_is_re_encoded_because_a_copy_states_no_length(tmp_path: Path) -> None:
"""A copy carries the source STREAMINFO over, whose sample count a fragmenting writer zeroes."""
source = fragmented_mp4(tmp_path / "track.mp4", "flac")
copied = tmp_path / "copied.flac"
subprocess.run(
[
"ffmpeg",
"-nostdin",
"-hide_banner",
"-loglevel",
"error",
"-y",
"-i",
str(source),
"-map",
"0:a:0",
"-c",
"copy",
str(copied),
],
check=True,
)
assert header_length(copied) == 0.0
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=Audio.Codec.FLAC)
track.path = source
track.to_music_container()
assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
assert mutagen.File(track.path).info.bits_per_sample == 16, "the re-encode must not change the sample format"
def test_dolby_digital_plus_falls_back_to_the_mp4_muxer(tmp_path: Path) -> None:
"""A .m4a name picks FFmpeg's ipod muxer, which refuses Dolby Digital Plus; the remux must not fail on it."""
source = encode(tmp_path / "track.mp4", "eac3", "-ar", "48000")
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=Audio.Codec.EC3)
track.path = source
assert track.to_music_container() is True
assert track.path.suffix == ".m4a"
assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
assert write_music_metadata(track.path, make_song()).written
def test_a_failed_remux_keeps_the_source_and_removes_its_partial_file(tmp_path: Path) -> None:
"""FFmpeg creates the output before it fails, and nothing else sweeps the temp directory."""
source = encode(tmp_path / "track.mp4", "pcm_s16le", "-f", "mov") # no MP4 muxer takes PCM
track = Audio(id_="a1", url="https://example.test/a1.mp4", language="en", codec=None)
track.path = source
with pytest.raises(subprocess.CalledProcessError):
track.to_music_container()
assert track.path == source and source.exists(), "a failed remux must keep the downloaded file"
assert not list(tmp_path.glob("track_music*")), "a failed remux must not leave a partial file"
@@ -0,0 +1,122 @@
"""A Song must end as a playable, correctly named, correctly tagged music file.
``remux_music_tracks`` (``unshackle/commands/dl.py``) is the hook the download loop runs
on every title after repack and before naming. These tests drive the real hook, then the
real naming, move, and tagging seams in the order ``dl.result()`` composes them. Only the
surrounding Click command does not run, because it needs a service, a CDM, and a network.
Every music-specific decision it makes lives in the seams driven here.
"""
from __future__ import annotations
import logging
import shutil
from pathlib import Path
import mutagen
import pytest
from mutagen.flac import FLAC
from pymediainfo import MediaInfo
from tests.core.test_music_container import fragmented_mp4, header_length
from tests.core.test_music_tagger_roundtrip import make_song
from unshackle.commands.dl import remux_music_tracks
from unshackle.core.config import config
from unshackle.core.tracks import Audio, Tracks
from unshackle.core.utils import tags
pytestmark = pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="requires ffmpeg")
log = logging.getLogger("test_music_remux_flow")
@pytest.fixture
def default_templates():
"""Pin the naming templates, because the suite shares the live global config."""
saved = (config.output_template, config.folder_templates, config.folder_template, config.tag_imdb_tmdb)
config.output_template = {"songs": "{track_number}. {title}"}
config.folder_templates = {}
config.folder_template = ""
config.tag_imdb_tmdb = False # keep provider lookups out of the test
yield
config.output_template, config.folder_templates, config.folder_template, config.tag_imdb_tmdb = saved
def make_audio(path: Path, codec: Audio.Codec, track_id: str) -> Audio:
track = Audio(id_=track_id, url=f"https://example.test/{track_id}.mp4", language="en", codec=codec)
track.path = path
return track
def test_the_hook_remuxes_every_audio_track_of_a_song(tmp_path: Path) -> None:
song = make_song()
song.tracks = Tracks(
[
make_audio(fragmented_mp4(tmp_path / "Audio_a1.mp4", "flac"), Audio.Codec.FLAC, "a1"),
make_audio(fragmented_mp4(tmp_path / "Audio_a2.mp4", "aac"), Audio.Codec.AAC, "a2"),
]
)
remux_music_tracks(song, log)
assert [t.path.suffix for t in song.tracks.audio] == [".flac", ".m4a"]
for track in song.tracks.audio:
assert header_length(track.path) == pytest.approx(6.0, abs=0.5)
def test_one_broken_track_warns_and_does_not_stop_the_rest(tmp_path: Path, caplog: pytest.LogCaptureFixture) -> None:
broken = tmp_path / "Audio_a1.mp4"
broken.write_bytes(b"") # ffmpeg cannot read this, so its remux must fail
song = make_song()
song.tracks = Tracks(
[
make_audio(broken, Audio.Codec.AAC, "a1"),
make_audio(fragmented_mp4(tmp_path / "Audio_a2.mp4", "aac"), Audio.Codec.AAC, "a2"),
]
)
with caplog.at_level(logging.WARNING, logger=log.name):
remux_music_tracks(song, log)
assert "Could not remux audio track a1" in caplog.text
assert song.tracks.audio[0].path == broken, "a failed remux must keep the downloaded file"
assert song.tracks.audio[1].path.suffix == ".m4a", "the failure must not stop the other tracks"
def test_a_non_song_title_is_left_alone(tmp_path: Path) -> None:
source = fragmented_mp4(tmp_path / "Audio_a1.mp4", "aac")
track = make_audio(source, Audio.Codec.AAC, "a1")
class NotASong:
tracks = Tracks([track])
remux_music_tracks(NotASong(), log)
assert track.path == source
def test_a_fragmented_flac_song_ends_playable_named_and_tagged(tmp_path: Path, default_templates: None) -> None:
"""The full post-download flow: hook, MediaInfo naming, final move, music tagging."""
song = make_song()
source = fragmented_mp4(tmp_path / "Audio_track-0001.mp4", "flac") # the downloader's naming scheme
track = make_audio(source, Audio.Codec.FLAC, "track-0001")
song.tracks = Tracks([track])
assert header_length(source) == 0.0, "the fixture must reproduce the fault the remux corrects"
remux_music_tracks(song, log)
# the naming and move seams, with the arguments dl.result() hands them
media_info = MediaInfo.parse(track.path)
final_dir = tmp_path / "downloads" / song.get_filename(media_info, show_service=False, folder=True)
final_dir.mkdir(parents=True)
final_path = final_dir / f"{song.get_filename(media_info, show_service=False)}{track.path.suffix}"
shutil.move(track.path, final_path)
tags.tag_file(final_path, song)
assert final_path == final_dir / "04.Example.Track.flac"
assert not source.exists(), "the fragmented source must be gone"
assert mutagen.File(final_path).info.length == pytest.approx(6.0, abs=0.5)
audio = FLAC(final_path)
assert audio["TITLE"] == ["Example Track"]
assert audio["ARTIST"] == ["Example Artist"]