forked from kenzuya/unshackle
1260 lines
51 KiB
Python
1260 lines
51 KiB
Python
import contextlib
|
|
import logging
|
|
import re
|
|
import shutil
|
|
import struct
|
|
import subprocess
|
|
from bisect import bisect_left, bisect_right
|
|
from collections import defaultdict
|
|
from collections.abc import Callable, Iterable, Sequence
|
|
from copy import copy
|
|
from dataclasses import dataclass
|
|
from enum import Enum
|
|
from functools import partial
|
|
from pathlib import Path
|
|
from typing import Any
|
|
from uuid import UUID
|
|
from zlib import crc32
|
|
|
|
import click
|
|
from langcodes import Language
|
|
from requests import Session
|
|
from requests.adapters import HTTPAdapter, Retry
|
|
|
|
from unshackle.core import binaries
|
|
from unshackle.core.cdm.choice import SYSTEMS
|
|
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
|
from unshackle.core.config import config
|
|
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
|
from unshackle.core.downloaders.requests import requests
|
|
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
|
from unshackle.core.drm.cbcs import SampleDecrypter
|
|
from unshackle.core.drm.cenc import cenc_key, init_kid
|
|
from unshackle.core.drm.verify import (
|
|
children,
|
|
find_child_box,
|
|
read_top_level_box,
|
|
senc_protects_samples,
|
|
walk,
|
|
)
|
|
from unshackle.core.events import events
|
|
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text
|
|
from unshackle.core.temp import low_free_space
|
|
from unshackle.core.tracks.segment_store import SegmentStore
|
|
from unshackle.core.utilities import language_name, log_event
|
|
from unshackle.core.utils import run_proxy
|
|
from unshackle.core.utils.subprocess import run_tool
|
|
|
|
DRM_PREFERENCE_TYPES: dict[str, type[Widevine] | type[PlayReady]] = {
|
|
"wv": Widevine,
|
|
"widevine": Widevine,
|
|
"pr": PlayReady,
|
|
"playready": PlayReady,
|
|
}
|
|
|
|
|
|
def direct_session(session: AnySession, proxy: str | None = None) -> Session:
|
|
"""requests.Session with copied headers/cookies and no proxy, or only ``proxy`` when given."""
|
|
new = Session()
|
|
if proxy:
|
|
run_proxy.pin(new)
|
|
new.proxies = {"http": proxy, "https": proxy}
|
|
headers = getattr(session, "headers", None)
|
|
if headers is not None:
|
|
try:
|
|
new.headers.update(dict(headers))
|
|
except Exception:
|
|
pass
|
|
cookies = getattr(session, "cookies", None)
|
|
if cookies is not None:
|
|
snapshot = getattr(cookies, "snapshot", None)
|
|
try:
|
|
if snapshot is None:
|
|
new.cookies.update(cookies)
|
|
else:
|
|
for cookie in snapshot():
|
|
new.cookies.set_cookie(copy(cookie)) # set_cookie edits a quoted value in place
|
|
except Exception:
|
|
pass
|
|
new.mount(
|
|
"https://",
|
|
HTTPAdapter(
|
|
max_retries=Retry(
|
|
total=5,
|
|
backoff_factor=0.2,
|
|
status_forcelist=[429, 500, 502, 503, 504],
|
|
retry_after_max=int(MAX_BACKOFF),
|
|
),
|
|
pool_maxsize=64,
|
|
pool_block=True,
|
|
),
|
|
)
|
|
new.mount("http://", new.adapters["https://"])
|
|
return new
|
|
|
|
|
|
def iter_top_level_boxes(path: Path) -> Iterable[tuple[bytes, int, int]]:
|
|
"""Yield (box_type, offset, size) for each top-level box, stopping at the first bad header."""
|
|
file_size = path.stat().st_size
|
|
with path.open("rb") as f:
|
|
offset = 0
|
|
while offset + 8 <= file_size:
|
|
f.seek(offset)
|
|
header = f.read(8)
|
|
if len(header) < 8:
|
|
return
|
|
size = int.from_bytes(header[:4], "big")
|
|
if size == 1:
|
|
large = f.read(8)
|
|
if len(large) < 8:
|
|
return
|
|
size = int.from_bytes(large, "big")
|
|
elif size == 0:
|
|
size = file_size - offset
|
|
if size < 8:
|
|
return
|
|
yield header[4:8], offset, size
|
|
offset += size
|
|
|
|
|
|
def strip_duplicate_init_boxes(src: Path, dst: Path) -> int:
|
|
"""Write src to dst without its repeated ftyp/moov pairs, returning how many it dropped.
|
|
|
|
An HLS track whose playlist carries a discontinuity gets a fresh EXT-X-MAP init for each
|
|
period, so the merged file holds one ftyp+moov per period. That plays, and mkvmerge takes
|
|
it, but MP4Box rejects the whole file with "Duplicate 'ftyp' detected!".
|
|
|
|
A packager stamps each init with the fetch time, so copies that describe the same format
|
|
still differ byte for byte. Only the stsd decides how samples decode, so this compares only
|
|
the stsd: a later moov with a different stsd is a real format change, and dropping it would
|
|
corrupt the output. In that case, and when there is no duplicate at all, this writes nothing,
|
|
returns 0, and leaves the caller with the original file.
|
|
"""
|
|
boxes = list(iter_top_level_boxes(src))
|
|
duplicates = [(t, o, s) for t, o, s in boxes if t in (b"ftyp", b"moov")]
|
|
if len(duplicates) <= 2:
|
|
return 0
|
|
|
|
with src.open("rb") as f:
|
|
stsds = set()
|
|
for box_type, offset, size in duplicates:
|
|
if box_type != b"moov":
|
|
continue
|
|
f.seek(offset)
|
|
stsd = find_child_box(f.read(size), b"stsd")
|
|
if stsd is None:
|
|
return 0
|
|
stsds.add(stsd)
|
|
if len(stsds) > 1:
|
|
return 0
|
|
|
|
dropped = 0
|
|
seen: set[bytes] = set()
|
|
with src.open("rb") as f, dst.open("wb") as out:
|
|
for box_type, offset, size in boxes:
|
|
if box_type in (b"ftyp", b"moov"):
|
|
if box_type in seen:
|
|
dropped += 1
|
|
continue
|
|
seen.add(box_type)
|
|
f.seek(offset)
|
|
remaining = size
|
|
while remaining:
|
|
chunk = f.read(min(remaining, 8 * 1024 * 1024))
|
|
if not chunk:
|
|
break
|
|
out.write(chunk)
|
|
remaining -= len(chunk)
|
|
return dropped
|
|
|
|
|
|
def fix_data_reference_indexes(path: Path) -> int:
|
|
"""Point each sample entry whose data_reference_index has no dref entry at entry 1, in place.
|
|
|
|
MP4Box refuses a sample of such an entry with "Bad Parameter", while mkvmerge ignores the index.
|
|
Returns how many entries it changed.
|
|
"""
|
|
moov_box = next(((offset, size) for kind, offset, size in iter_top_level_boxes(path) if kind == b"moov"), None)
|
|
if moov_box is None:
|
|
return 0
|
|
offset, size = moov_box
|
|
fixed = 0
|
|
with path.open("r+b") as f:
|
|
f.seek(offset)
|
|
moov = f.read(size)
|
|
for kind, body, end in walk(moov):
|
|
if kind != b"minf":
|
|
continue
|
|
dref = find_child_box(moov[body:end], b"dref")
|
|
refs = int.from_bytes(dref[12:16], "big") if dref and len(dref) >= 16 else 1
|
|
if not refs:
|
|
continue
|
|
for box, stsd, stsd_end in walk(moov, body, end):
|
|
if box != b"stsd":
|
|
continue
|
|
for _, entry, entry_end in children(moov, stsd + 8, stsd_end):
|
|
if entry_end - entry >= 8 and not 1 <= int.from_bytes(moov[entry + 6 : entry + 8], "big") <= refs:
|
|
f.seek(offset + entry + 6)
|
|
f.write(b"\x00\x01")
|
|
fixed += 1
|
|
return fixed
|
|
|
|
|
|
MPEGH_SAMPLE_ENTRIES = ("mha1", "mha2", "mhm1", "mhm2")
|
|
|
|
|
|
def prepare_for_mp4box(source: Path, candidate: Path, track_id: Any) -> Path:
|
|
"""Return the file MP4Box reads: ``candidate`` when repeated init boxes were dropped into it, else ``source``.
|
|
|
|
The returned file also has its sample entries pointed at data reference 1.
|
|
"""
|
|
dropped = strip_duplicate_init_boxes(source, candidate)
|
|
if dropped:
|
|
log_event(
|
|
"mux_mp4_init_deduplicated",
|
|
level="DEBUG",
|
|
message=f"Dropped {dropped} repeated init box(es) from {source.name} for MP4Box",
|
|
context={"track_id": track_id, "dropped": dropped},
|
|
)
|
|
else:
|
|
candidate.unlink(missing_ok=True)
|
|
prepared = candidate if dropped else source
|
|
repointed = fix_data_reference_indexes(prepared)
|
|
if repointed:
|
|
log_event(
|
|
"mux_mp4_dref_fixed",
|
|
level="DEBUG",
|
|
message=f"Pointed {repointed} sample entry(s) of {source.name} at data reference 1 for MP4Box",
|
|
context={"track_id": track_id, "entries": repointed},
|
|
)
|
|
return prepared
|
|
|
|
|
|
def has_mp4_only_audio_entry(path: Path) -> bool:
|
|
"""True if the MP4 holds a DTS-UHD (DTS:X Profile 2) or MPEG-H audio sample entry.
|
|
|
|
Matroska has no CodecID for DTS-UHD, so mkvmerge stores it as an A_QUICKTIME
|
|
passthrough and every reader reports the container fallback instead of the codec.
|
|
mkvmerge drops an MPEG-H track completely. A file this returns True for has to go
|
|
into MP4 to keep its audio.
|
|
|
|
Only "dtsx"/"dtsy" mean DTS-UHD. DTS:X Profile 1 rides inside DTS-HD Master Audio as
|
|
"dtsc"/"dtse"/"dtsh"/"dtsl", which Matroska maps to A_DTS and stores properly, so it
|
|
must not match here. Reading the entry rather than trusting the manifest keeps a
|
|
mislabelled codec from moving a Profile 1 track out of Matroska.
|
|
|
|
A 4CC scan scoped to the moov box, not a structural parse; the scoping avoids chance
|
|
byte collisions in mdat. Any read error -> False.
|
|
"""
|
|
try:
|
|
moov = read_top_level_box(path, b"moov")
|
|
except OSError:
|
|
return False
|
|
if not moov:
|
|
return False
|
|
for tok in (b"dtsx", b"dtsy", *(entry.encode() for entry in MPEGH_SAMPLE_ENTRIES)):
|
|
i = moov.find(tok, 4)
|
|
while i != -1:
|
|
size = int.from_bytes(moov[i - 4 : i], "big")
|
|
if 16 <= size <= len(moov) - (i - 4):
|
|
return True
|
|
i = moov.find(tok, i + 1)
|
|
return False
|
|
|
|
|
|
def moof_still_encrypted(moof: bytes) -> bool:
|
|
# senc only: a decrypter detaches just the atom it consumed, so a PIFF uuid can
|
|
# outlive a good decrypt. ISM arrives as senc via piff_senc_to_cenc.
|
|
# structural walk: a 4CC byte scan collides with trun payload
|
|
from unshackle.core.manifests.ism_init import iter_boxes
|
|
|
|
body = 16 if int.from_bytes(moof[:4], "big") == 1 else 8
|
|
for box_type, _, traf_body, traf_end in iter_boxes(moof, body, len(moof)):
|
|
if box_type != b"traf":
|
|
continue
|
|
for child, _usertype, child_body, child_end in iter_boxes(moof, traf_body, traf_end):
|
|
if child == b"senc" and senc_protects_samples(moof, child_body, child_end):
|
|
return True
|
|
return False
|
|
|
|
|
|
def assert_fragments_decrypted(path: Path) -> None:
|
|
"""Raise if any fragment survived decryption still carrying a sample-encryption box.
|
|
|
|
mp4decrypt strips senc from every fragment it processes and leaves it on the ones it
|
|
skips, so a survivor marks a silent skip. One cause is a tfhd.sample_description_index
|
|
dangling past the stsd entry count, which mp4decrypt reports as success (exit 0, no
|
|
stderr) while leaving the payload as ciphertext. Unlike has_encrypted_sample_entry
|
|
(moov-scoped) this is fragment-scoped. The moov comes out clean in that failure.
|
|
|
|
Only a standard senc counts as evidence. Some DASH titles ship a PIFF uuid beside it,
|
|
and a decrypter detaches only the atom it consumed, so that uuid outlives a good
|
|
decrypt. Counting it would condemn a healthy file.
|
|
|
|
The guarantee runs in one direction: a survivor proves a skip, while a clean pass is
|
|
only as good as the decrypter's own behaviour. shaka-packager (the default
|
|
`decryption` backend) remuxes into a single fragment and drops senc whether or not it
|
|
decrypted, so this cannot fire on shaka output. The walk does not use a buffer and reads
|
|
only box headers. It seeks over mdat and never reads it. A malformed box size aborts the
|
|
walk with a warning and returns normally, so a file this function cannot parse is
|
|
never escalated into a raise. The logged warning is the only signal of that. A caller
|
|
sees the same silent return it gets from a verified clean file.
|
|
"""
|
|
surviving = 0
|
|
total = 0
|
|
first_offset = None
|
|
try:
|
|
file_size = path.stat().st_size
|
|
with path.open("rb", buffering=0) as f:
|
|
start = 0
|
|
while start + 8 <= file_size:
|
|
f.seek(start)
|
|
header = f.read(8)
|
|
if len(header) < 8:
|
|
break
|
|
size = int.from_bytes(header[:4], "big")
|
|
box_header = 8
|
|
if size == 1:
|
|
large = f.read(8)
|
|
if len(large) < 8:
|
|
break
|
|
size = int.from_bytes(large, "big")
|
|
box_header = 16
|
|
elif size == 0:
|
|
size = file_size - start
|
|
if size < box_header or start + size > file_size:
|
|
logging.getLogger("track").warning(
|
|
f"{path.name}: malformed box size at offset {start}; cannot verify the "
|
|
"remaining fragments were decrypted."
|
|
)
|
|
break
|
|
if header[4:8] == b"moof":
|
|
total += 1
|
|
f.seek(start)
|
|
if moof_still_encrypted(f.read(size)):
|
|
surviving += 1
|
|
if first_offset is None:
|
|
first_offset = start
|
|
start += size
|
|
except Exception as e:
|
|
logging.getLogger("track").warning(f"{path.name}: fragment decryption check did not complete ({e}).")
|
|
return
|
|
if surviving:
|
|
log_event(
|
|
"decrypt_fragments_still_encrypted",
|
|
level="ERROR",
|
|
message=f"{surviving}/{total} fragments still encrypted after decryption",
|
|
file=path.name,
|
|
surviving=surviving,
|
|
total=total,
|
|
first_offset=first_offset,
|
|
)
|
|
raise ValueError(
|
|
f"{path.name}: {surviving}/{total} fragment(s) still encrypted after decryption, first at byte {first_offset}"
|
|
)
|
|
|
|
|
|
SAMPLE_PROBE_BYTES = 64 * 1024
|
|
SAMPLE_PROBE_LIMIT = 8 * 1024 * 1024
|
|
|
|
|
|
def parse_sidx(data: bytes, offset: int) -> tuple[int, list[tuple[int, int, int]]]:
|
|
"""Read a ``sidx`` box that starts at byte ``offset`` of its file.
|
|
|
|
Returns the timescale and one (start time, first byte, last byte) for each subsegment. The list
|
|
is empty when the box is not a ``sidx`` or when it points at more indexes and not at media.
|
|
"""
|
|
# read by hand: pymp4's Box.parse gives wrong results when two threads parse at once
|
|
size, header = int.from_bytes(data[:4], "big"), 32 if data[8:9] == b"\x00" else 40
|
|
count = int.from_bytes(data[header - 2 : header], "big")
|
|
if data[4:8] != b"sidx" or len(data) < header or min(size, len(data)) < header + 12 * count:
|
|
return 0, []
|
|
if header == 32:
|
|
timescale, start, first_offset = struct.unpack_from(">III", data, 16)
|
|
else:
|
|
timescale, start, first_offset = struct.unpack_from(">IQQ", data, 16)
|
|
byte = offset + size + first_offset
|
|
subsegments: list[tuple[int, int, int]] = []
|
|
for i in range(count):
|
|
word, duration = struct.unpack_from(">II", data, header + 12 * i)
|
|
if word >> 31:
|
|
return 0, []
|
|
subsegments.append((start, byte, byte + (word & 0x7FFFFFFF) - 1))
|
|
start += duration
|
|
byte += word & 0x7FFFFFFF
|
|
return timescale, subsegments
|
|
|
|
|
|
@dataclass
|
|
class DownloadContext:
|
|
"""Shared arguments passed to each manifest's ``download_track``."""
|
|
|
|
save_path: Path
|
|
save_dir: Path
|
|
progress: partial
|
|
session: AnySession | None = None
|
|
proxy: str | None = None
|
|
max_workers: int | None = None
|
|
adaptive_workers: bool = False
|
|
download_processes: int = 1
|
|
license_widevine: Callable | None = None
|
|
cdm: object | None = None
|
|
on_segments: Callable[["Track", list[Any]], None] | None = None
|
|
"""Called by the HLS step with a track and its wanted media segments, before they download."""
|
|
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None
|
|
"""The service's key or `cbcs.SampleDecrypter` for a 1-based `stsd` entry, for a track it decrypts itself."""
|
|
fairplay_bridge: bool = False
|
|
"""The service has a FairPlay bridge hook, so the HLS step may license a FairPlay-only track as PlayReady or Widevine."""
|
|
|
|
def ensure_session(self) -> AnySession:
|
|
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
|
session = self.session
|
|
if not session:
|
|
session = run_proxy.fallback_session()
|
|
elif not isinstance(session, (Session, RnetSession)):
|
|
raise TypeError(f"Expected session to be a {Session} or {RnetSession}, not {session!r}")
|
|
return session
|
|
|
|
|
|
class Track:
|
|
class Descriptor(Enum):
|
|
URL = 1
|
|
HLS = 2 # https://en.wikipedia.org/wiki/HTTP_Live_Streaming
|
|
DASH = 3 # https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
|
|
ISM = 4 # https://learn.microsoft.com/en-us/silverlight/smooth-streaming
|
|
|
|
sample_tail = 0
|
|
|
|
def __init__(
|
|
self,
|
|
url: str | list[str],
|
|
language: Language | str,
|
|
is_original_lang: bool = False,
|
|
descriptor: Descriptor = Descriptor.URL,
|
|
needs_repack: bool = False,
|
|
name: str | None = None,
|
|
drm: Iterable[DRM_T] | None = None,
|
|
edition: str | None = None,
|
|
note: str | None = None,
|
|
session: AnySession | None = None,
|
|
downloader: Callable | None = None,
|
|
downloader_args: dict | None = None,
|
|
from_file: Path | None = None,
|
|
data: dict | defaultdict | None = None,
|
|
id_: str | None = None,
|
|
extra: Any | None = None,
|
|
) -> None:
|
|
if not isinstance(url, (str, list)):
|
|
raise TypeError(f"Expected url to be a {str}, or list of {str}, not {type(url)}")
|
|
if not isinstance(language, (Language, str)):
|
|
raise TypeError(f"Expected language to be a {Language} or {str}, not {type(language)}")
|
|
if not isinstance(is_original_lang, bool):
|
|
raise TypeError(f"Expected is_original_lang to be a {bool}, not {type(is_original_lang)}")
|
|
if not isinstance(descriptor, Track.Descriptor):
|
|
raise TypeError(f"Expected descriptor to be a {Track.Descriptor}, not {type(descriptor)}")
|
|
if not isinstance(needs_repack, bool):
|
|
raise TypeError(f"Expected needs_repack to be a {bool}, not {type(needs_repack)}")
|
|
if not isinstance(name, (str, type(None))):
|
|
raise TypeError(f"Expected name to be a {str}, not {type(name)}")
|
|
if not isinstance(id_, (str, type(None))):
|
|
raise TypeError(f"Expected id_ to be a {str}, not {type(id_)}")
|
|
if not isinstance(edition, (str, list, type(None))):
|
|
raise TypeError(f"Expected edition to be a {str}, {list}, or None, not {type(edition)}")
|
|
if not isinstance(note, (str, type(None))):
|
|
raise TypeError(f"Expected note to be a {str}, not {type(note)}")
|
|
if downloader is not None and not callable(downloader):
|
|
raise TypeError(f"Expected downloader to be a {Callable}, not {type(downloader)}")
|
|
if not isinstance(downloader_args, (dict, type(None))):
|
|
raise TypeError(f"Expected downloader_args to be a {dict}, not {type(downloader_args)}")
|
|
if not isinstance(from_file, (Path, type(None))):
|
|
raise TypeError(f"Expected from_file to be a {Path}, not {type(from_file)}")
|
|
if not isinstance(data, (dict, defaultdict, type(None))):
|
|
raise TypeError(f"Expected data to be a {dict} or {defaultdict}, not {type(data)}")
|
|
|
|
invalid_urls = ", ".join({str(type(x)) for x in url if not isinstance(x, str)})
|
|
if invalid_urls:
|
|
raise TypeError(f"Expected all items in url to be a {str}, but found {invalid_urls}")
|
|
|
|
if drm is not None:
|
|
try:
|
|
iter(drm)
|
|
except TypeError:
|
|
raise TypeError(f"Expected drm to be an iterable, not {type(drm)}") from None
|
|
|
|
if downloader is None:
|
|
downloader = requests
|
|
|
|
self.path: Path | None = None
|
|
self.url = url
|
|
self.resolve_url: Callable[[], str] | None = None
|
|
self.language = language
|
|
self.is_original_lang = is_original_lang
|
|
self.descriptor = descriptor
|
|
self.needs_repack = needs_repack
|
|
self.name = name
|
|
self.drm = drm
|
|
self._drm_preference: str | None = None
|
|
self.edition: list[str] = [edition] if isinstance(edition, str) else (edition or [])
|
|
self.note = note
|
|
self.session = session
|
|
self.downloader = downloader
|
|
self.downloader_args = downloader_args
|
|
self.from_file = from_file
|
|
self._data: defaultdict[Any, Any] = defaultdict(dict)
|
|
self.data = data or {}
|
|
self.extra: Any = extra or {} # allow anything for extra, but default to a dict
|
|
|
|
if not id_:
|
|
this = copy(self)
|
|
if isinstance(self.url, str):
|
|
this.url = self.url.rsplit("?", maxsplit=1)[0]
|
|
checksum = crc32(repr(this).encode("utf8"))
|
|
id_ = hex(checksum)[2:]
|
|
|
|
self.id = id_
|
|
|
|
# TODO: Currently using OnFoo event naming, change to just segment_filter
|
|
self.OnSegmentFilter: Callable | None = None
|
|
self.sample_start: float = 0.0
|
|
self.sample_bytes: tuple[bytes, str] | None = None
|
|
|
|
def sample_slice(
|
|
self, starts: Sequence[float], timescale: float = 1, window: tuple[int, int] | None = None
|
|
) -> slice:
|
|
"""Return the slice of segments that hold ``window``, from the start time of each segment.
|
|
|
|
Sets ``sample_start`` to the start time of the first kept segment, in seconds. A video keeps
|
|
``sample_tail`` segments after the window: mkvmerge ends the cut only at a video keyframe, and
|
|
with no such keyframe the audio and the subtitles continue to their own end.
|
|
"""
|
|
self.sample_start = 0.0
|
|
if not window or not starts:
|
|
return slice(None)
|
|
low, high = (starts[0] + seconds * timescale for seconds in window)
|
|
if low > starts[-1] and len(starts) > 1:
|
|
raise click.ClickException("The title ends before the sample window starts, use an earlier --sample window")
|
|
first = max(bisect_right(starts, low) - 1, 0)
|
|
self.sample_start = (starts[first] - starts[0]) / timescale
|
|
return slice(first, max(bisect_left(starts, high) + self.sample_tail, first + 1))
|
|
|
|
def sample_byte_range(self, session: AnySession) -> tuple[bytes, str] | None:
|
|
"""Find the bytes of a one-file track that hold the sample window.
|
|
|
|
Reads the start of the file for a ``sidx`` box. Returns the bytes before that box, which hold
|
|
the init data, and the byte range of the window. Returns None when the file has no such index.
|
|
"""
|
|
if self.sample_bytes or not isinstance(self.url, str):
|
|
return self.sample_bytes
|
|
url = self.url
|
|
head = b""
|
|
|
|
def read_to(end: int) -> None:
|
|
nonlocal head
|
|
if end > len(head):
|
|
res = unrecorded(session, "get", url, headers={"Range": f"bytes={len(head)}-{end - 1}"})
|
|
if res.ok:
|
|
head += res.content
|
|
|
|
pos = 0
|
|
while pos < SAMPLE_PROBE_LIMIT:
|
|
if pos + 8 > len(head):
|
|
read_to(pos + SAMPLE_PROBE_BYTES)
|
|
if pos + 8 > len(head):
|
|
return None
|
|
size, kind = struct.unpack(">I4s", head[pos : pos + 8])
|
|
if size < 8:
|
|
return None
|
|
if kind != b"sidx":
|
|
pos += size
|
|
continue
|
|
read_to(pos + size)
|
|
timescale, subsegments = parse_sidx(head[pos : pos + size], pos)
|
|
if not subsegments:
|
|
return None
|
|
kept = subsegments[self.sample_slice([start for start, _, _ in subsegments], timescale, config.sample)]
|
|
self.sample_bytes = head[:pos], f"{kept[0][1]}-{kept[-1][2]}"
|
|
return self.sample_bytes
|
|
return None
|
|
|
|
def can_sample(self, session: AnySession) -> bool:
|
|
"""Return False when a sample cannot cut this track, because it is one file with no segment index."""
|
|
if self.descriptor == self.Descriptor.URL:
|
|
return bool(self.sample_byte_range(session))
|
|
if self.descriptor == self.Descriptor.DASH:
|
|
from unshackle.core.manifests import DASH
|
|
|
|
return DASH.has_segment_timing(self)
|
|
return True
|
|
|
|
def __repr__(self) -> str:
|
|
return "{name}({items})".format(
|
|
name=self.__class__.__name__, items=", ".join([f"{k}={repr(v)}" for k, v in self.__dict__.items()])
|
|
)
|
|
|
|
def __eq__(self, other: Any) -> bool:
|
|
return isinstance(other, Track) and self.id == other.id
|
|
|
|
@property
|
|
def language(self) -> Language:
|
|
"""The language the service tagged, parsed even when a service assigns a string or None later."""
|
|
return self._language
|
|
|
|
@language.setter
|
|
def language(self, value: Language | str | None) -> None:
|
|
self._language = Language.get(value or "und")
|
|
|
|
@property
|
|
def data(self) -> defaultdict[Any, Any]:
|
|
"""
|
|
Arbitrary track data dictionary.
|
|
|
|
This uses a defaultdict with a dict as the factory for easier
|
|
nested saving and safer exists-checks.
|
|
|
|
Reserved keys:
|
|
|
|
- "hls" used by the HLS class.
|
|
- playlist: m3u8.model.Playlist - The primary track information.
|
|
- media: m3u8.model.Media - The audio/subtitle track information.
|
|
- segment_durations: list[int] - A list of each segment's duration.
|
|
- playlist_text: str - The media playlist, set by a service that has its text and no
|
|
playlist URL. Its segment URIs resolve against the track URL.
|
|
- "dash" used by the DASH class.
|
|
- manifest: lxml.ElementTree - DASH MPD manifest.
|
|
- period: lxml.Element - The period of this track.
|
|
- adaptation_set: lxml.Element - The adaptation set of this track.
|
|
- representation: lxml.Element - The representation of this track.
|
|
- timescale: int - The timescale of the track's segments.
|
|
- segment_durations: list[int] - A list of each segment's duration.
|
|
|
|
A service can set:
|
|
|
|
- "own_stream_only": bool - Mux only the track of the same kind from the file: a video
|
|
without the audio its file holds, or an audio track without the video in its file.
|
|
|
|
You should not add, change, or remove any data within reserved keys.
|
|
You may use their data, but note that these values can change or be removed
|
|
at any point.
|
|
"""
|
|
return self._data
|
|
|
|
@data.setter
|
|
def data(self, value: dict | defaultdict) -> None:
|
|
if not isinstance(value, (dict, defaultdict)):
|
|
raise TypeError(f"Expected data to be a {dict} or {defaultdict}, not {type(value)}")
|
|
if isinstance(value, dict):
|
|
value = defaultdict(dict, **value)
|
|
self._data = value
|
|
|
|
@property
|
|
def drm_preference(self) -> str | None:
|
|
"""
|
|
DRM system this track must license with, one of the names in DRM_PREFERENCE_TYPES.
|
|
|
|
None (the default) lets the loaded CDM choose. Set it when the manifest advertises more
|
|
than one DRM system but only one of them licenses this track.
|
|
"""
|
|
return self._drm_preference
|
|
|
|
@drm_preference.setter
|
|
def drm_preference(self, value: str | None) -> None:
|
|
if value is None:
|
|
self._drm_preference = None
|
|
return
|
|
if not isinstance(value, str) or value.lower() not in DRM_PREFERENCE_TYPES:
|
|
raise ValueError(
|
|
f"Expected drm_preference to be one of {sorted(DRM_PREFERENCE_TYPES)} or None, not {value!r}"
|
|
)
|
|
self._drm_preference = value.lower()
|
|
|
|
def add_init_drm(self, init_data: bytes | None, cdm: object | None) -> None:
|
|
"""Add the Widevine and PlayReady DRM that the init segment carries and the track does not have.
|
|
|
|
A track with a different DRM type stays as it is. The DRM system that agrees with the CDM comes first.
|
|
"""
|
|
log = logging.getLogger("track")
|
|
held: list[DRM_T] = list(self.drm or [])
|
|
if not init_data or any(type(d) not in (Widevine, PlayReady) for d in held):
|
|
return
|
|
for system in self.pssh_order(cdm):
|
|
if any(type(d) is system for d in held):
|
|
continue
|
|
try:
|
|
held.append(system.from_init_data(init_data))
|
|
except (PlayReady.Exceptions.PSSHNotFound, Widevine.Exceptions.PSSHNotFound):
|
|
continue
|
|
except Exception as e:
|
|
if not held:
|
|
raise
|
|
log.debug(f"Could not read the {system.__name__} PSSH of the init segment: {e}")
|
|
if held:
|
|
self.drm = held
|
|
else:
|
|
log.debug("No PlayReady or Widevine PSSH was found for this track, is it DRM free?")
|
|
|
|
def prefers_playready(self, cdm: object | None) -> bool:
|
|
"""Whether to try PlayReady before Widevine. The track's preference wins over the loaded CDM."""
|
|
if self._drm_preference:
|
|
return DRM_PREFERENCE_TYPES[self._drm_preference] is PlayReady
|
|
return is_playready_cdm(cdm)
|
|
|
|
def pssh_order(self, cdm: object | None) -> tuple[type[Widevine] | type[PlayReady], ...]:
|
|
"""Widevine and PlayReady, in the order to look for their PSSH."""
|
|
return (PlayReady, Widevine) if self.prefers_playready(cdm) else (Widevine, PlayReady)
|
|
|
|
def drm_from_pssh(
|
|
self,
|
|
cdm: object | None,
|
|
read: Callable[[type[Widevine] | type[PlayReady]], DRM_T],
|
|
log: logging.Logger,
|
|
) -> None:
|
|
"""Set drm to the first DRM that `read` finds a PSSH for, in pssh_order."""
|
|
systems = self.pssh_order(cdm)
|
|
for system in systems:
|
|
try:
|
|
self.drm = [read(system)]
|
|
return
|
|
except system.Exceptions.PSSHNotFound:
|
|
continue
|
|
log.debug(f"No {systems[0].__name__} or {systems[1].__name__} PSSH was found for this track, is it DRM free?")
|
|
|
|
def ensure_url(self) -> None:
|
|
"""Set the URL from ``resolve_url`` when the track has none.
|
|
|
|
A service sets ``resolve_url`` when each URL costs a request, so only a track that is downloaded or sent to a
|
|
remote client asks for its URL.
|
|
"""
|
|
if not self.url and self.resolve_url:
|
|
self.url = self.resolve_url()
|
|
|
|
def download(
|
|
self,
|
|
session: AnySession,
|
|
prepare_drm: partial,
|
|
max_workers: int | None = None,
|
|
progress: partial | None = None,
|
|
*,
|
|
cdm: object | None = None,
|
|
no_proxy_download: bool = False,
|
|
proxy_download: str | None = None,
|
|
adaptive_workers: bool = False,
|
|
download_processes: int = 1,
|
|
on_segments: Callable[["Track", list[Any]], None] | None = None,
|
|
sample_decrypter: Callable[[int], bytes | SampleDecrypter] | None = None,
|
|
fairplay_bridge: bool = False,
|
|
) -> None:
|
|
"""Download and optionally Decrypt this Track, then emit TRACK_DOWNLOADED.
|
|
|
|
For a URL-descriptor Video or Audio track with no `drm` set, unshackle probes the DRM from the
|
|
track's init data and stores it on the track, so a service need not declare `drm` itself.
|
|
`sample_decrypter` and `fairplay_bridge` go on the DownloadContext.
|
|
"""
|
|
from unshackle.core.manifests import DASH, HLS, ISM, url
|
|
from unshackle.core.manifests.segment_pipeline import licensing
|
|
from unshackle.core.tracks.audio import Audio
|
|
from unshackle.core.tracks.subtitle import Subtitle
|
|
from unshackle.core.tracks.video import Video
|
|
|
|
assert isinstance(self, (Video, Audio, Subtitle)) and progress is not None
|
|
if DOWNLOAD_LICENCE_ONLY.is_set():
|
|
progress(downloaded="[yellow]SKIPPING")
|
|
|
|
if DOWNLOAD_CANCELLED.is_set():
|
|
progress(downloaded="[yellow]SKIPPED")
|
|
return
|
|
|
|
proxy = next(iter(session.proxies.values()), None)
|
|
|
|
dl_session = session
|
|
if no_proxy_download:
|
|
if proxy:
|
|
dl_session = direct_session(session)
|
|
proxy = None
|
|
elif proxy_download:
|
|
dl_session = direct_session(session, proxy_download)
|
|
proxy = proxy_download
|
|
|
|
track_type = self.__class__.__name__
|
|
save_path = config.directories.temp / f"{track_type}_{self.id}.mp4"
|
|
if isinstance(self, Subtitle):
|
|
assert self.codec
|
|
save_path = save_path.with_suffix(f".{self.codec.extension}")
|
|
|
|
if self.descriptor != self.Descriptor.URL:
|
|
save_dir = save_path.with_name(save_path.name + "_segments")
|
|
else:
|
|
save_dir = save_path.parent
|
|
|
|
store = SegmentStore(self, save_dir)
|
|
|
|
def abandon() -> None:
|
|
"""Stash or remove the output of a failed or cancelled download.
|
|
|
|
A cleanup error must not replace the error of the download.
|
|
"""
|
|
store.abandon()
|
|
with contextlib.suppress(OSError):
|
|
save_path.unlink(missing_ok=True)
|
|
|
|
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
|
if config.directories.temp.is_file():
|
|
raise ValueError(f"Temp Directory '{config.directories.temp}' must be a Directory, not a file")
|
|
|
|
config.directories.temp.mkdir(parents=True, exist_ok=True)
|
|
|
|
save_path.unlink(missing_ok=True)
|
|
store.restore()
|
|
|
|
try:
|
|
manifest_parsers: dict[Track.Descriptor, type[DASH] | type[HLS] | type[ISM]] = {
|
|
self.Descriptor.HLS: HLS,
|
|
self.Descriptor.DASH: DASH,
|
|
self.Descriptor.ISM: ISM,
|
|
}
|
|
ctx = DownloadContext(
|
|
save_path=save_path,
|
|
save_dir=save_dir,
|
|
progress=progress,
|
|
session=dl_session,
|
|
proxy=proxy,
|
|
max_workers=max_workers,
|
|
adaptive_workers=adaptive_workers,
|
|
download_processes=download_processes,
|
|
license_widevine=prepare_drm,
|
|
cdm=cdm,
|
|
on_segments=on_segments,
|
|
sample_decrypter=sample_decrypter,
|
|
fairplay_bridge=fairplay_bridge,
|
|
)
|
|
if self.descriptor in manifest_parsers:
|
|
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
|
elif self.descriptor == self.Descriptor.URL:
|
|
url.download_track(self, ctx, session)
|
|
|
|
if DOWNLOAD_CANCELLED.is_set():
|
|
return
|
|
|
|
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
|
assert self.path is not None
|
|
if self.path.stat().st_size <= 3: # Empty UTF-8 BOM == 3 bytes
|
|
raise OSError("Download failed, the downloaded file is empty.")
|
|
|
|
with licensing(ctx):
|
|
events.emit(events.Types.TRACK_DOWNLOADED, track=self)
|
|
except DownloadCancelled:
|
|
abandon()
|
|
progress(downloaded="[yellow]SKIPPED")
|
|
return
|
|
except (Exception, KeyboardInterrupt) as e:
|
|
if not DOWNLOAD_LICENCE_ONLY.is_set():
|
|
low_free_space(e)
|
|
abandon()
|
|
raise
|
|
|
|
def delete(self) -> None:
|
|
if self.path:
|
|
self.path.unlink()
|
|
self.path = None
|
|
|
|
def move(self, target: Path | str) -> Path:
|
|
"""
|
|
Move the Track's file from current location, to target location.
|
|
This will overwrite anything at the target path.
|
|
|
|
Raises:
|
|
TypeError: If the target argument is not the expected type.
|
|
ValueError: If track has no file to move, or the target does not exist.
|
|
OSError: If the file somehow failed to move.
|
|
|
|
Returns the new location of the track.
|
|
"""
|
|
if not isinstance(target, (str, Path)):
|
|
raise TypeError(f"Expected {target} to be a {Path} or {str}, not {type(target)}")
|
|
|
|
if not self.path:
|
|
raise ValueError("Track has no file to move")
|
|
|
|
if not isinstance(target, Path):
|
|
target = Path(target)
|
|
|
|
if not target.exists():
|
|
raise ValueError(f"Target file {repr(target)} does not exist")
|
|
|
|
moved_to = Path(shutil.move(self.path, target))
|
|
if moved_to.resolve() != target.resolve():
|
|
raise OSError(f"Failed to move {self.path} to {target}")
|
|
|
|
self.path = target
|
|
return target
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
"""The track in the export form; see ``wire.track_to_dict``."""
|
|
from unshackle.core.wire import track_to_dict
|
|
|
|
return track_to_dict(self)
|
|
|
|
@property
|
|
def mux_language(self) -> Language:
|
|
"""The language tag written to the output file."""
|
|
return self.language
|
|
|
|
def embedded_audio_name(self) -> str:
|
|
"""Name the audio a service keeps inside this track's file, by its language when the service set none."""
|
|
lang = self.data["audio_language"]
|
|
name = self.data.get("audio_language_name")
|
|
if not name and config.muxing.get("track_names") != "none":
|
|
name = language_name(Language.get(lang)) or lang
|
|
return self.with_original_label(name) or ""
|
|
|
|
def get_track_name(self) -> str | None:
|
|
"""Get the Track Name, or the name of its language when the service set none."""
|
|
name = self.name
|
|
if name is None and config.muxing.get("track_names") != "none":
|
|
name = language_name(self.mux_language)
|
|
return self.with_original_label(name)
|
|
|
|
def with_original_label(self, name: str | None) -> str | None:
|
|
"""Add `muxing.original_label` to the name of a track in the title's original language,
|
|
unless the name already contains the label's words."""
|
|
label = config.muxing.get("original_label")
|
|
label = label.strip() if isinstance(label, str) else ""
|
|
if not label or not self.is_original_lang:
|
|
return name
|
|
words = re.sub(r"[\W_]+", " ", label).strip() or label
|
|
if name and words.casefold() in name.casefold():
|
|
return name
|
|
return f"{name} {label}" if name else label
|
|
|
|
def get_drm_for_cdm(self, cdm: object | None) -> DRM_T | None:
|
|
"""Return the DRM matching the provided CDM, if available."""
|
|
if not self.drm:
|
|
return None
|
|
|
|
if self._drm_preference:
|
|
wanted = DRM_PREFERENCE_TYPES[self._drm_preference]
|
|
for drm in self.drm:
|
|
if isinstance(drm, wanted):
|
|
return drm
|
|
|
|
if is_widevine_cdm(cdm):
|
|
for drm in self.drm:
|
|
if isinstance(drm, Widevine):
|
|
return drm
|
|
elif is_playready_cdm(cdm):
|
|
playready = [drm for drm in self.drm if isinstance(drm, PlayReady)]
|
|
if playready:
|
|
playready[0].absorb(*playready[1:])
|
|
return playready[0]
|
|
|
|
return next(iter(self.drm))
|
|
|
|
def get_key_id(self, init_data: bytes | None = None, *args: Any, **kwargs: Any) -> UUID | None:
|
|
"""
|
|
Probe the DRM encryption Key ID (KID) for this specific track.
|
|
|
|
It can find the Key ID by probing the track with FFprobe for
|
|
`enc_key_id` data, as well as for mp4 `tenc` (Track Encryption)
|
|
boxes.
|
|
|
|
It explicitly ignores PSSH information like the `PSSH` box, as the box
|
|
is likely to contain multiple Key IDs that may or may not be for this
|
|
specific track.
|
|
|
|
To retrieve the initialization segment, this method calls :meth:`get_init_segment`
|
|
with the positional and keyword arguments. This method then uses the return value
|
|
of `get_init_segment` to find the Key ID.
|
|
|
|
Returns:
|
|
The Key ID as a UUID object, or None if unshackle cannot find the Key ID.
|
|
"""
|
|
if not init_data:
|
|
init_data = self.get_init_segment(*args, **kwargs)
|
|
if not isinstance(init_data, bytes):
|
|
raise TypeError(f"Expected init_data to be bytes, not {init_data!r}")
|
|
|
|
return init_kid(init_data)
|
|
|
|
def load_drm_if_needed(self, service: Any | None = None) -> bool:
|
|
"""
|
|
Load DRM information for this track if the parser deferred it.
|
|
|
|
Args:
|
|
service (Service | None): Service instance that can fetch track-specific DRM info
|
|
|
|
Returns:
|
|
True if the DRM loaded or is already present, False if the load failed
|
|
"""
|
|
if not getattr(self, "needs_drm_loading", False):
|
|
return bool(self.drm)
|
|
|
|
if self.drm:
|
|
self.needs_drm_loading = False
|
|
return True
|
|
|
|
if not service or not hasattr(service, "get_track_drm"):
|
|
return self.load_drm_from_playlist()
|
|
|
|
try:
|
|
track_drm = service.get_track_drm(self)
|
|
if track_drm:
|
|
self.drm = track_drm if isinstance(track_drm, list) else [track_drm]
|
|
self.needs_drm_loading = False
|
|
return True
|
|
except Exception as e:
|
|
raise ValueError(f"Failed to load DRM from service for track {self.id}: {e}") # noqa: B904
|
|
|
|
return self.load_drm_from_playlist()
|
|
|
|
def held_playlist(self) -> str | None:
|
|
"""The HLS media playlist text the track holds: ``data["hls"]["playlist_text"]``, else the ``from_file`` text."""
|
|
text = (self.data.get("hls") or {}).get("playlist_text")
|
|
if text is None and self.from_file:
|
|
text = self.from_file.read_text(encoding="utf-8")
|
|
return text
|
|
|
|
def playlist_text(self, session: Any, **kwargs: Any) -> str:
|
|
"""The HLS media playlist text the track holds, else the one at its URL; a response that is not ok raises."""
|
|
text = self.held_playlist()
|
|
if text is None:
|
|
assert isinstance(self.url, str)
|
|
response = session.get(self.url, **kwargs)
|
|
if not getattr(response, "ok", True):
|
|
raise ValueError(f"Failed to request the media playlist of track {self.id}: {response.status_code}")
|
|
text = utf8_text(response)
|
|
return text
|
|
|
|
def load_drm_from_playlist(self, session: Any = None, bridge: bool = False) -> bool:
|
|
"""Load the Widevine and PlayReady DRM of the EXT-X-KEY and EXT-X-SESSION-KEY tags of this track's playlist.
|
|
|
|
It skips a tag that gives no DRM, and raises ValueError when the fetch fails or when every such tag fails.
|
|
With ``bridge`` it builds both stubs for the key IDs that ``HLS.get_bridge_kids`` finds when no tag gives a DRM.
|
|
"""
|
|
if self.drm:
|
|
self.needs_drm_loading = False
|
|
return True
|
|
|
|
import m3u8
|
|
|
|
from unshackle.core.manifests.hls import HLS
|
|
|
|
session = self.session or session or run_proxy.fallback_session()
|
|
try:
|
|
assert isinstance(self.url, str)
|
|
playlist = m3u8.loads(self.playlist_text(session), self.url)
|
|
except Exception as e:
|
|
raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {e}") # noqa: B904
|
|
|
|
drm_list: list[DRM_T] = []
|
|
error: Exception | None = None
|
|
keys = playlist.keys or []
|
|
for key in [*keys, *(k for k in playlist.session_keys or [] if k not in keys)]:
|
|
if not cenc_key(key):
|
|
continue
|
|
try:
|
|
drm_list.append(HLS.get_drm_or_probe(key, playlist, self, probe_session=session))
|
|
except Exception as e:
|
|
logging.getLogger("track").debug(f"Skipping HLS key {key} of track {self.id}: {e!r}")
|
|
error = e
|
|
if error and not drm_list:
|
|
raise ValueError(f"Failed to load DRM from playlist for track {self.id}: {error}")
|
|
if bridge and not drm_list:
|
|
segments = [
|
|
s for s in playlist.segments if not (callable(self.OnSegmentFilter) and self.OnSegmentFilter(s))
|
|
]
|
|
if kids := HLS.get_bridge_kids(playlist, segments, self, session):
|
|
drm_list = [HLS.bridge_stub(system, kids) for system in SYSTEMS]
|
|
if drm_list:
|
|
self.drm = drm_list
|
|
self.needs_drm_loading = False
|
|
return True
|
|
return False
|
|
|
|
def get_init_segment(
|
|
self,
|
|
maximum_size: int = 20000,
|
|
url: str | None = None,
|
|
byte_range: str | None = None,
|
|
session: AnySession | None = None,
|
|
) -> bytes:
|
|
"""
|
|
Get the Track's initial segment data.
|
|
|
|
HLS and DASH tracks must explicitly give a URL to the init segment or file.
|
|
Give the byte-range for the init segment where possible.
|
|
|
|
If `byte_range` is not set, it will make a HEAD request and examine the size of
|
|
the file. If it cannot find the size, it will download up to the first
|
|
20KB only, which should contain the entirety of the init segment. You may
|
|
override this by changing the `maximum_size`.
|
|
|
|
The default maximum_size of 20000 (20KB) is a tried-and-tested value that
|
|
seems to work well across the board.
|
|
|
|
Parameters:
|
|
maximum_size: Size to assume as the response body length if byte-range is
|
|
not used, if unshackle cannot find the body size, or if the body size
|
|
is larger than it. Use a value of 20000 (20KB) or higher.
|
|
url: Explicit init map or file URL to probe from.
|
|
byte_range: Range of bytes to download from the explicit or implicit URL.
|
|
session: HTTP session context, for example authorization and headers.
|
|
"""
|
|
if not isinstance(maximum_size, int):
|
|
raise TypeError(f"Expected maximum_size to be an {int}, not {type(maximum_size)}")
|
|
if not isinstance(url, (str, type(None))):
|
|
raise TypeError(f"Expected url to be a {str}, not {type(url)}")
|
|
if not isinstance(byte_range, (str, type(None))):
|
|
raise TypeError(f"Expected byte_range to be a {str}, not {type(byte_range)}")
|
|
if not isinstance(session, (Session, RnetSession, type(None))):
|
|
raise TypeError(f"Expected session to be a {Session} or {RnetSession}, not {type(session)}")
|
|
|
|
if not url:
|
|
if self.descriptor != self.Descriptor.URL:
|
|
raise ValueError(f"An explicit URL must be provided for {self.descriptor.name} tracks")
|
|
if not self.url or not isinstance(self.url, str):
|
|
raise ValueError("An explicit URL must be provided as the track has no URL")
|
|
url = self.url
|
|
|
|
if not session:
|
|
session = run_proxy.fallback_session()
|
|
|
|
content_length = maximum_size
|
|
|
|
if byte_range:
|
|
if not isinstance(byte_range, str):
|
|
raise TypeError(f"Expected byte_range to be a str, not {byte_range!r}")
|
|
if not re.match(r"^\d+-\d+$", byte_range):
|
|
raise ValueError(f"The value of byte_range is unrecognized: '{byte_range}'")
|
|
start, end = byte_range.split("-")
|
|
if start > end:
|
|
raise ValueError(f"The start range cannot be greater than the end range: {start}>{end}")
|
|
else:
|
|
size_test = unrecorded(session, "head", url)
|
|
if "Content-Length" in size_test.headers:
|
|
content_length_header = int(size_test.headers["Content-Length"])
|
|
if content_length_header > 0:
|
|
content_length = min(content_length_header, maximum_size)
|
|
range_test = unrecorded(session, "head", url, headers={"Range": "bytes=0-1"})
|
|
if range_test.status_code == 206:
|
|
byte_range = f"0-{content_length - 1}"
|
|
|
|
init_data: bytes | None
|
|
if byte_range:
|
|
res = unrecorded(session, "get", url, headers={"Range": f"bytes={byte_range}"})
|
|
res.raise_for_status()
|
|
init_data = res.content
|
|
else:
|
|
init_data = None
|
|
s = unrecorded(session, "get", url, stream=True)
|
|
if not s.ok:
|
|
s.close()
|
|
raise ValueError(f"Track URI returned HTTP {s.status_code}")
|
|
for chunk in s.iter_content(content_length):
|
|
init_data = chunk
|
|
break
|
|
s.close()
|
|
if not init_data:
|
|
raise ValueError(f"Failed to read {content_length} bytes from the track URI.")
|
|
|
|
return init_data
|
|
|
|
def repackage(self, bsf_v: str | None = None) -> bool:
|
|
"""Remux the track with FFmpeg ``-c copy``.
|
|
|
|
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, 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.")
|
|
|
|
ffmpeg_bin = binaries.FFMPEG
|
|
if not ffmpeg_bin:
|
|
raise OSError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
|
|
|
|
original_path = self.path
|
|
output_path = original_path.with_stem(f"{original_path.stem}_repack")
|
|
|
|
def ffmpeg(bsf: str | None = None) -> None:
|
|
args: list[str | Path] = [
|
|
ffmpeg_bin,
|
|
"-nostdin",
|
|
"-hide_banner",
|
|
"-loglevel",
|
|
"error",
|
|
"-i",
|
|
original_path,
|
|
]
|
|
|
|
if hasattr(self, "data") and self.data.get("audio_language"):
|
|
audio_lang = self.data["audio_language"]
|
|
audio_name = self.embedded_audio_name()
|
|
args.extend(
|
|
[
|
|
"-metadata:s:a:0",
|
|
f"language={audio_lang}",
|
|
"-metadata:s:a:0",
|
|
f"title={audio_name}",
|
|
"-metadata:s:a:0",
|
|
f"handler_name={audio_name}",
|
|
]
|
|
)
|
|
|
|
args.extend(
|
|
[
|
|
"-map_metadata",
|
|
"-1",
|
|
"-fflags",
|
|
"+bitexact",
|
|
"-codec",
|
|
"copy",
|
|
"-strict",
|
|
"unofficial",
|
|
]
|
|
)
|
|
if bsf:
|
|
# ffmpeg exits 0 after dropping packets the bsf cannot parse
|
|
args.extend(["-bsf:v", bsf, "-xerror"])
|
|
args.append(str(output_path))
|
|
|
|
run_tool("FFmpeg", args, "ffmpeg repackage")
|
|
|
|
log_event(
|
|
"repackage",
|
|
level="DEBUG",
|
|
message=f"Repackaging {self.__class__.__name__} {original_path.name} with ffmpeg",
|
|
context={"track_type": self.__class__.__name__, "id": self.id, "file": original_path.name},
|
|
)
|
|
|
|
bsf_applied = False
|
|
try:
|
|
ffmpeg(bsf=bsf_v)
|
|
bsf_applied = bsf_v is not None
|
|
except subprocess.CalledProcessError:
|
|
if bsf_v is None:
|
|
raise
|
|
output_path.unlink(missing_ok=True)
|
|
ffmpeg()
|
|
|
|
original_path.unlink()
|
|
self.path = output_path
|
|
|
|
log_event(
|
|
"repackage_complete",
|
|
level="DEBUG",
|
|
message=f"Repackaged {self.__class__.__name__} -> {output_path.name}",
|
|
context={
|
|
"track_type": self.__class__.__name__,
|
|
"id": self.id,
|
|
"output": output_path.name,
|
|
"output_size": output_path.stat().st_size if output_path.exists() else 0,
|
|
},
|
|
)
|
|
return bsf_applied
|
|
|
|
|
|
__all__ = ("Track", "DownloadContext")
|