From 3868928d982ca5fdc7b700b274f2dbe855b8bb73 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Wed, 2 Dec 2026 14:50:15 -0700 Subject: [PATCH] fix(tracks): sniff attachment MIME from file bytes and keep ffmpeg autobsf on repack --- tests/core/test_repackage_aac.py | 64 ++++++++++++++++++++++++++++ tests/core/test_tool_failed.py | 18 -------- tests/tracks/test_attachment_mime.py | 60 ++++++++++++++++++++++++++ unshackle/core/music/tagger.py | 15 ++----- unshackle/core/tracks/attachment.py | 50 +++++++++++++++++----- unshackle/core/tracks/track.py | 28 +++++------- unshackle/core/tracks/video.py | 2 +- 7 files changed, 179 insertions(+), 58 deletions(-) create mode 100644 tests/core/test_repackage_aac.py create mode 100644 tests/tracks/test_attachment_mime.py diff --git a/tests/core/test_repackage_aac.py b/tests/core/test_repackage_aac.py new file mode 100644 index 00000000..2a055d55 --- /dev/null +++ b/tests/core/test_repackage_aac.py @@ -0,0 +1,64 @@ +"""Repackaging an MPEG-TS with ADTS AAC into MP4 runs one clean FFmpeg pass.""" + +from __future__ import annotations + +import json +import subprocess +from collections.abc import Callable, Iterator +from pathlib import Path + +import pytest +from langcodes import Language + +from unshackle.core import binaries +from unshackle.core.tracks import Video +from unshackle.core.utilities import close_debug_logger, init_debug_logger + +pytestmark = pytest.mark.skipif(binaries.FFMPEG is None, reason="requires ffmpeg") + + +@pytest.fixture +def tool_run_levels(tmp_path: Path) -> Iterator[Callable[[], list[str]]]: + """Enable the debug log; the fixture value reads the levels of its tool_run records.""" + log = tmp_path / "debug.jsonl" + init_debug_logger(log_path=log, enabled=True) + + def levels() -> list[str]: + close_debug_logger() + entries = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] + return [e["level"] for e in entries if e["operation"] == "tool_run"] + + yield levels + close_debug_logger() + + +def video_at(path: Path) -> Video: + video = Video(url="https://cdn.example/v.mp4", language=Language.get("en")) + video.path = path + return video + + +def test_adts_aac_repackages_in_one_pass_with_no_error_record( + tmp_path: Path, tool_run_levels: Callable[[], list[str]] +) -> None: + source = tmp_path / "v.mp4" + subprocess.run( + [str(binaries.FFMPEG), "-nostdin", "-v", "error", "-y"] + + ["-f", "lavfi", "-i", "testsrc2=size=160x90:rate=24:duration=1", "-f", "lavfi", "-i", "sine=duration=1"] + + ["-c:v", "mpeg4", "-c:a", "aac", "-f", "mpegts", str(source)], + check=True, + ) + video = video_at(source) + video.repackage() + + assert video.path and video.path.stat().st_size > 0 + assert tool_run_levels() == ["DEBUG"] + + +def test_a_real_repackage_failure_still_logs_an_error(tmp_path: Path, tool_run_levels: Callable[[], list[str]]) -> None: + source = tmp_path / "v.mp4" + source.write_bytes(b"not media") + with pytest.raises(subprocess.CalledProcessError): + video_at(source).repackage() + + assert tool_run_levels() == ["ERROR"] diff --git a/tests/core/test_tool_failed.py b/tests/core/test_tool_failed.py index 0da542c8..d89e68a7 100644 --- a/tests/core/test_tool_failed.py +++ b/tests/core/test_tool_failed.py @@ -107,24 +107,6 @@ def test_a_repackage_failure_names_the_ffmpeg_reason(tmp_path: Path, monkeypatch track.repackage() -@POSIX_STUBS -def test_a_malformed_aac_repackage_retries_with_the_adts_filter( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -) -> None: - script = ( - 'case "$*" in *aac_adtstoasc*) for last; do :; done; echo ok > "$last"; exit 0;; esac\n' - "echo 'Malformed AAC bitstream detected' >&2; exit 1" - ) - monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", script)) - track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC) - track.path = tmp_path / "a.mp4" - track.path.write_bytes(b"audio") - - track.repackage() - - assert track.path == tmp_path / "a_repack.mp4" and track.path.read_text() == "ok\n" - - @POSIX_STUBS def test_a_subtitleedit_failure_names_the_reason_it_wrote_to_stdout( tmp_path: Path, monkeypatch: pytest.MonkeyPatch diff --git a/tests/tracks/test_attachment_mime.py b/tests/tracks/test_attachment_mime.py new file mode 100644 index 00000000..f0ab0bc9 --- /dev/null +++ b/tests/tracks/test_attachment_mime.py @@ -0,0 +1,60 @@ +"""An attachment with no given MIME type takes it from the file signature before the suffix.""" + +from __future__ import annotations + +import importlib +from collections.abc import Iterator +from pathlib import Path + +import pytest + +from unshackle.core.config import config +from unshackle.core.tracks.attachment import Attachment + +downloader = importlib.import_module("unshackle.core.downloaders.requests") +PNG = b"\x89PNG\r\n\x1a\n" + bytes(32) +JPEG = b"\xff\xd8\xff\xe0" + bytes(32) + + +def test_a_png_saved_as_jpg_is_image_png(tmp_path: Path) -> None: + path = tmp_path / "thumb.jpg" + path.write_bytes(PNG) + assert Attachment(path=path).mime_type == "image/png" + + +def test_an_unknown_signature_falls_back_to_the_suffix(tmp_path: Path) -> None: + path = tmp_path / "font.ttf" + path.write_bytes(b"junk" * 8) + assert Attachment(path=path).mime_type == "application/x-truetype-font" + + +def test_a_given_mime_type_stays(tmp_path: Path) -> None: + path = tmp_path / "thumb.jpg" + path.write_bytes(PNG) + assert Attachment(path=path, mime_type="image/jpeg").mime_type == "image/jpeg" + + +@pytest.fixture +def png_download(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + def fake_download(url: str, path: Path, **kwargs: object) -> Iterator[dict]: + path.write_bytes(PNG) + yield {} + + monkeypatch.setattr(config.directories, "temp", tmp_path) + monkeypatch.setattr(downloader, "download", fake_download) + + +@pytest.mark.usefixtures("png_download") +@pytest.mark.parametrize("mime_type", [None, "image/jpeg"]) +def test_a_url_attachment_takes_the_type_of_the_downloaded_file(mime_type: str | None) -> None: + """The suffix type also arrives as a given type when a remote server sends the attachment.""" + attachment = Attachment(url="https://cdn.example/thumb.jpg", mime_type=mime_type) + attachment.download() + assert attachment.mime_type == "image/png" + + +@pytest.mark.usefixtures("png_download") +def test_a_url_attachment_keeps_a_given_type_that_is_not_the_suffix_type() -> None: + attachment = Attachment(url="https://cdn.example/thumb.jpg", mime_type="image/x-example") + attachment.download() + assert attachment.mime_type == "image/x-example" diff --git a/unshackle/core/music/tagger.py b/unshackle/core/music/tagger.py index 24b98770..203c9390 100644 --- a/unshackle/core/music/tagger.py +++ b/unshackle/core/music/tagger.py @@ -14,6 +14,7 @@ from unshackle.core import binaries from unshackle.core.config import config from unshackle.core.session import AnySession from unshackle.core.titles.music import song_metadata +from unshackle.core.tracks.attachment import mime_from_bytes from unshackle.core.utils.collections import as_list from unshackle.core.utils.subprocess import log_tool_run @@ -337,7 +338,7 @@ def download_cover(session: AnySession | None, artwork_url: str) -> tuple[bytes if not data: return None, "" content_type = str(response.headers.get("Content-Type") or "").split(";")[0].strip().lower() - return data, mime_from_image(data, content_type or "image/jpeg") + return data, mime_from_bytes(data) or content_type or "image/jpeg" except Exception as error: log.debug("Music cover download failed for %s: %s", artwork_url, error) return None, "" @@ -350,7 +351,7 @@ def attachment_cover(song: Any) -> tuple[bytes | None, str]: path = getattr(attachment, "path", None) if path and Path(path).exists() and str(getattr(attachment, "mime_type", "")).startswith("image/"): data = Path(path).read_bytes() - return data, mime_from_image(data, attachment.mime_type) + return data, mime_from_bytes(data) or attachment.mime_type return None, "" @@ -438,16 +439,6 @@ def as_bool(*values: Any) -> bool: return False -def mime_from_image(data: bytes, fallback: str = "image/jpeg") -> str: - if data.startswith(b"\x89PNG\r\n\x1a\n"): - return "image/png" - if data.startswith(b"\xff\xd8\xff"): - return "image/jpeg" - if data.startswith(b"RIFF") and b"WEBP" in data[:16]: - return "image/webp" - return fallback - - def split_number_pair(value: str) -> tuple[int, int]: if not value: return 0, 0 diff --git a/unshackle/core/tracks/attachment.py b/unshackle/core/tracks/attachment.py index 9fd96517..e0fba833 100644 --- a/unshackle/core/tracks/attachment.py +++ b/unshackle/core/tracks/attachment.py @@ -12,6 +12,36 @@ from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY from unshackle.core.session import AnySession from unshackle.core.utils import run_proxy +SUFFIX_MIME = { + ".ttf": "application/x-truetype-font", + ".otf": "application/vnd.ms-opentype", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".png": "image/png", +} +SIGNATURE_MIME = ( + (b"\x89PNG\r\n\x1a\n", "image/png"), + (b"\xff\xd8\xff", "image/jpeg"), + (b"OTTO", "application/vnd.ms-opentype"), + (b"\x00\x01\x00\x00", "application/x-truetype-font"), +) + + +def mime_from_bytes(data: bytes) -> str | None: + """The image or font MIME type that the first bytes of a file show, or None.""" + if data[:4] == b"RIFF" and data[8:12] == b"WEBP": + return "image/webp" + return next((mime for signature, mime in SIGNATURE_MIME if data.startswith(signature)), None) + + +def file_mime(path: Path) -> str | None: + with path.open("rb") as f: + return mime_from_bytes(f.read(12)) + + +def suffix_mime(name: Path) -> str | None: + return SUFFIX_MIME.get(name.suffix.lower()) or mimetypes.guess_type(name)[0] + class Attachment: def __init__( @@ -31,7 +61,7 @@ class Attachment: You must give either path or url. If name is not provided it will use the file name (without extension). - If mime_type is not provided, it will try to guess it. + If mime_type is not provided, it comes from the file signature, else from the suffix. Args: path: Path to an existing file. @@ -76,15 +106,10 @@ class Attachment: mime_type = (mime_type or "").strip() or None description = (description or "").strip() or None + if not mime_type and path is not None: + mime_type = file_mime(path) if not mime_type: - suffix = path.suffix.lower() if path is not None else Path(file_name).suffix.lower() - mime_type = { - ".ttf": "application/x-truetype-font", - ".otf": "application/vnd.ms-opentype", - ".jpg": "image/jpeg", - ".jpeg": "image/jpeg", - ".png": "image/png", - }.get(suffix, mimetypes.guess_type(file_name if path is None else path)[0]) + mime_type = suffix_mime(path or Path(file_name)) if not mime_type: raise ValueError("The attachment mime-type could not be automatically detected.") @@ -100,7 +125,10 @@ class Attachment: no_proxy_download: bool = False, proxy_download: str | None = None, ) -> None: - """Download a URL-backed attachment to the temp directory with the same retries as a track.""" + """Download a URL-backed attachment to the temp directory with the same retries as a track. + + A type equal to the suffix type can be a guess, also one a remote server sent, so the file signature replaces it. + """ if self.path is not None or not self.url or DOWNLOAD_LICENCE_ONLY.is_set(): return @@ -125,6 +153,8 @@ class Attachment: raise if download_path.exists(): self.path = download_path + if self.mime_type == suffix_mime(download_path): + self.mime_type = file_mime(download_path) or self.mime_type def __repr__(self) -> str: return "{name}({items})".format( diff --git a/unshackle/core/tracks/track.py b/unshackle/core/tracks/track.py index 707d2a95..33d54df7 100644 --- a/unshackle/core/tracks/track.py +++ b/unshackle/core/tracks/track.py @@ -1162,10 +1162,11 @@ class Track: A given ``bsf_v`` goes into the same pass as ``-bsf:v``, which normalises video VUI colour metadata without a second full-file remux. Repackaging is mandatory. The - bitstream filter is best-effort: if the combined pass fails, and it is not the - AAC-retry case, unshackle tries it again once without ``bsf_v`` so the remux still - succeeds. Returns True if unshackle applied the requested ``bsf_v`` (always False - when ``bsf_v`` is None, because the caller requested nothing). + bitstream filter is best-effort: if the combined pass fails, unshackle tries it again + once without ``bsf_v`` so the remux still succeeds, and the caller falls back to + ``normalize_vui``. Returns True if unshackle applied + the requested ``bsf_v`` (always False when ``bsf_v`` is None, because the caller + requested nothing). """ if not self.path or not self.path.exists(): raise ValueError("Cannot repackage a Track that has not been downloaded.") @@ -1177,7 +1178,7 @@ class Track: original_path = self.path output_path = original_path.with_stem(f"{original_path.stem}_repack") - def ffmpeg(extra_args: list[str] | None = None, bsf: str | None = None) -> None: + def ffmpeg(bsf: str | None = None) -> None: args: list[str | Path] = [ ffmpeg_bin, "-nostdin", @@ -1186,7 +1187,6 @@ class Track: "error", "-i", original_path, - *(extra_args or []), ] if hasattr(self, "data") and self.data.get("audio_language"): @@ -1208,7 +1208,7 @@ class Track: "-map_metadata", "-1", "-fflags", - "bitexact", + "+bitexact", "-codec", "copy", "-strict", @@ -1233,17 +1233,11 @@ class Track: try: ffmpeg(bsf=bsf_v) bsf_applied = bsf_v is not None - except subprocess.CalledProcessError as e: - if b"Malformed AAC bitstream detected" in e.stderr: - ffmpeg(["-y", "-bsf:a", "aac_adtstoasc"], bsf=bsf_v) - bsf_applied = bsf_v is not None - elif bsf_v is not None: - # Repack is mandatory, the VUI bitstream filter is best-effort: retry - # without it so the remux still succeeds; caller falls back to normalize_vui. - output_path.unlink(missing_ok=True) - ffmpeg() - else: + except subprocess.CalledProcessError: + if bsf_v is None: raise + output_path.unlink(missing_ok=True) + ffmpeg() original_path.unlink() self.path = output_path diff --git a/unshackle/core/tracks/video.py b/unshackle/core/tracks/video.py index 0426bc26..eafa73a8 100644 --- a/unshackle/core/tracks/video.py +++ b/unshackle/core/tracks/video.py @@ -787,7 +787,7 @@ class Video(Track): "-map_metadata", "-1", "-fflags", - "bitexact", + "+bitexact", "-bsf:v", f"filter_units=remove_types=6,h264_metadata=sei_user_data={uuid}+{encoding_settings}", "-codec",