forked from kenzuya/unshackle
fix(tracks): sniff attachment MIME from file bytes and keep ffmpeg autobsf on repack
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
Reference in New Issue
Block a user