forked from kenzuya/unshackle
refactor(tracks): make complete_track the one finish step for every track kind
This commit is contained in:
@@ -689,7 +689,7 @@ See the [DRM & CDM reference](../guide/drm-and-cdm.md) for the full picture.
|
||||
Override any of these to react to pipeline stages (all no-ops by default):
|
||||
`on_segment_downloaded`, `on_track_downloaded`, `on_track_decrypted`,
|
||||
`on_track_repacked`, `on_track_multiplex`. `on_track_downloaded` runs once per track, after
|
||||
unshackle decrypted the `drm` of the track. Also override `search()` to yield
|
||||
unshackle decrypted the track and after `on_track_decrypted`. Also override `search()` to yield
|
||||
`SearchResult` objects for `unshackle search`.
|
||||
|
||||
!!! warning "Set `ANONYMOUS_SEARCH` only for a search that needs no account"
|
||||
|
||||
@@ -449,9 +449,9 @@ process can use. For these, set no `drm` on the track and override two methods:
|
||||
full-sample cbcs only, not pattern encryption.
|
||||
|
||||
When the download of the track ends, unshackle calls `unshackle.core.drm.cbcs.decrypt_file`, and
|
||||
the progress row shows "Decrypting". Your `on_track_downloaded` runs before this and gets the
|
||||
encrypted file. `decrypt_file` writes the plaintext back in place and removes the
|
||||
protection boxes, so the muxer reads a clear file. In a remote session `get_sample_decrypter`
|
||||
the progress row shows "Decrypting". `decrypt_file` writes the plaintext back in place and removes the
|
||||
protection boxes, so the muxer reads a clear file. Then your `on_track_decrypted` runs with `drm` set
|
||||
to `None`, and after it your `on_track_downloaded` runs and gets the clear file. In a remote session `get_sample_decrypter`
|
||||
runs on the server: the client sends the samples through the `samples` route, so a decrypter
|
||||
that needs a process on the server also works for a remote client.
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from concurrent.futures import Future
|
||||
from functools import partial
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
@@ -254,9 +255,9 @@ def no_decrypt(monkeypatch, mark: bytes = b"") -> list[tuple[object, bool]]:
|
||||
if mark:
|
||||
path.write_bytes(mark + path.read_bytes())
|
||||
|
||||
for module in (segment_pipeline, hls_module, track_module):
|
||||
for module in (segment_pipeline, hls_module):
|
||||
monkeypatch.setattr(module, "decrypt_track", decrypt_track)
|
||||
monkeypatch.setattr(module, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(segment_pipeline, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
return calls
|
||||
|
||||
|
||||
@@ -509,6 +510,64 @@ def test_track_downloaded_fires_once_on_the_decrypted_file(
|
||||
assert (head == MARK) == encrypted
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"kind, merge_segments",
|
||||
[("dash", True), ("hls", False), ("hls", True), ("ism", True), ("url", False)],
|
||||
ids=["dash", "hls-post-merge", "hls-rolling", "ism", "url"],
|
||||
)
|
||||
def test_a_service_sample_decrypt_runs_before_track_downloaded(server, tmp_path, monkeypatch, kind, merge_segments):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
monkeypatch.setattr(config, "merge_segments", merge_segments)
|
||||
monkeypatch.setattr(segment_pipeline, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
entries: list[int] = []
|
||||
|
||||
def decrypt_file(path, key_for):
|
||||
entries.append(key_for(None, SimpleNamespace(index=1)))
|
||||
path.write_bytes(MARK + path.read_bytes())
|
||||
|
||||
monkeypatch.setattr(segment_pipeline.cbcs, "decrypt_file", decrypt_file)
|
||||
order: list[tuple[str, object]] = []
|
||||
|
||||
def downloaded(track):
|
||||
order.append(("downloaded", track.path.read_bytes()[: len(MARK)]))
|
||||
|
||||
def decrypted(track, drm, segment):
|
||||
order.append(("decrypted", drm))
|
||||
|
||||
events.subscribe(events.Types.TRACK_DOWNLOADED, downloaded)
|
||||
events.subscribe(events.Types.TRACK_DECRYPTED, decrypted)
|
||||
try:
|
||||
make_track(server, kind, encrypted=False).download(
|
||||
requests.Session(),
|
||||
partial(lambda *a, **kw: None),
|
||||
progress=partial(lambda **kw: None),
|
||||
sample_decrypter=lambda entry: f"key{entry}",
|
||||
)
|
||||
finally:
|
||||
events.unsubscribe(events.Types.TRACK_DOWNLOADED, downloaded)
|
||||
events.unsubscribe(events.Types.TRACK_DECRYPTED, decrypted)
|
||||
|
||||
assert entries == ["key1"]
|
||||
assert order == [("decrypted", None), ("downloaded", MARK)]
|
||||
|
||||
|
||||
def test_a_url_track_decrypts_with_its_track_kid(server, tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
monkeypatch.setattr(track_module.Track, "get_key_id", lambda *a, **kw: KID)
|
||||
monkeypatch.setattr(segment_pipeline, "assert_fragments_decrypted", lambda *a, **kw: None)
|
||||
kids: list[UUID | None] = []
|
||||
|
||||
def decrypt_track(drm, path, licence=None, track_kid=None, decrypt=True, track=None):
|
||||
kids.append(track_kid)
|
||||
|
||||
monkeypatch.setattr(segment_pipeline, "decrypt_track", decrypt_track)
|
||||
make_track(server, "url", encrypted=True).download(
|
||||
requests.Session(), partial(lambda *a, **kw: None), progress=partial(lambda **kw: None)
|
||||
)
|
||||
|
||||
assert kids == [KID]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kind", ["dash", "hls", "ism", "url"])
|
||||
def test_a_failing_track_downloaded_hook_fails_the_track_and_removes_its_file(server, tmp_path, monkeypatch, kind):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
|
||||
@@ -16,6 +16,7 @@ from tests.core.test_all_drm import playready, widevine
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.drm import ClearKey, ClearKeyCENC, ClearKeyCTR, MonaLisa, verify
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.manifests import segment_pipeline
|
||||
from unshackle.core.manifests.segment_pipeline import (
|
||||
RollingMerge,
|
||||
check_merged,
|
||||
@@ -356,6 +357,53 @@ def test_complete_track_after_segment_decryption_only_checks(tmp_path, seen, no_
|
||||
assert [name for name, _ in seen] == ["decrypted"]
|
||||
|
||||
|
||||
def test_complete_track_passes_the_track_kid_and_flags_a_repack(tmp_path, seen, monkeypatch):
|
||||
kids: list[UUID | None] = []
|
||||
monkeypatch.setattr(verify, "DECRYPT_HOOK", lambda drm, path, licence, kid, decrypt, track: kids.append(kid))
|
||||
monkeypatch.setattr(segment_pipeline, "has_encrypted_sample_entry", lambda path: True)
|
||||
ctx = make_ctx(tmp_path)
|
||||
ctx.save_path.write_bytes(b"merged")
|
||||
drm = FakeDRM(seen)
|
||||
track = SimpleNamespace(path=None, drm=[drm], needs_repack=False)
|
||||
|
||||
complete_track(track, ctx, drm, kid=KID) # type: ignore[arg-type]
|
||||
|
||||
assert kids == [KID]
|
||||
assert track.needs_repack
|
||||
|
||||
|
||||
def test_complete_track_runs_the_service_sample_decrypter(tmp_path, seen, monkeypatch):
|
||||
asked: list[int] = []
|
||||
|
||||
def decrypt_file(path, key_for):
|
||||
key_for(None, SimpleNamespace(index=2))
|
||||
path.write_bytes(b"clear:" + path.read_bytes())
|
||||
|
||||
monkeypatch.setattr(segment_pipeline.cbcs, "decrypt_file", decrypt_file)
|
||||
ctx = make_ctx(tmp_path, sample_decrypter=lambda entry: asked.append(entry) or b"k" * 16)
|
||||
ctx.save_path.write_bytes(b"merged")
|
||||
track = SimpleNamespace(path=None, drm=None, needs_repack=False)
|
||||
|
||||
complete_track(track, ctx, None) # type: ignore[arg-type]
|
||||
|
||||
assert asked == [2]
|
||||
assert seen == [("decrypted", None)]
|
||||
assert ctx.save_path.read_bytes() == b"clear:merged"
|
||||
assert ctx.statuses == ["Decrypting", "Decrypted", "Downloaded"]
|
||||
assert not track.needs_repack
|
||||
|
||||
|
||||
def test_complete_track_skips_the_sample_decrypter_after_a_cancel(tmp_path, seen):
|
||||
ctx = make_ctx(tmp_path, sample_decrypter=lambda entry: pytest.fail("decrypter asked after a cancel"))
|
||||
ctx.save_path.write_bytes(b"partial")
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
|
||||
complete_track(SimpleNamespace(path=None, drm=None), ctx, None) # type: ignore[arg-type]
|
||||
|
||||
assert seen == []
|
||||
assert ctx.save_path.read_bytes() == b"partial"
|
||||
|
||||
|
||||
def test_complete_track_without_drm_skips_the_decryption(tmp_path, seen):
|
||||
ctx = make_ctx(tmp_path)
|
||||
ctx.save_path.write_bytes(b"merged")
|
||||
|
||||
@@ -95,9 +95,24 @@ def test_the_source_defaults_leave_a_track_alone() -> None:
|
||||
assert svc.get_playready_license(challenge=b"", title=None, track=None) is None # type: ignore[arg-type]
|
||||
with pytest.raises(NotImplementedError):
|
||||
svc.get_sample_decrypter(None, 1) # type: ignore[arg-type]
|
||||
assert svc.sample_decrypter(None) is None # type: ignore[arg-type]
|
||||
svc.close()
|
||||
|
||||
|
||||
def test_a_source_that_decrypts_samples_hands_its_decrypter_for_the_track() -> None:
|
||||
class Decrypting(ExampleService):
|
||||
def decrypts_samples(self, track: Any) -> bool:
|
||||
return track == "EXAMPLE"
|
||||
|
||||
def get_sample_decrypter(self, track: Any, entry: int) -> bytes:
|
||||
return f"{track}:{entry}".encode()
|
||||
|
||||
svc = object.__new__(Decrypting)
|
||||
decrypter = svc.sample_decrypter("EXAMPLE") # type: ignore[arg-type]
|
||||
assert decrypter is not None and decrypter(2) == b"EXAMPLE:2"
|
||||
assert svc.sample_decrypter("OTHER") is None # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_a_playready_stub_names_every_kid() -> None:
|
||||
stub = drm_stub("playready", KIDS)
|
||||
assert isinstance(stub, PlayReady)
|
||||
|
||||
@@ -190,15 +190,14 @@ def test_downloaders_route_through_the_hook(monkeypatch: pytest.MonkeyPatch) ->
|
||||
"""Every real decrypt site calls decrypt_track, so the dl hook sees it."""
|
||||
import inspect
|
||||
|
||||
from unshackle.core.manifests import dash, hls, ism, segment_pipeline
|
||||
from unshackle.core.manifests import dash, hls, ism, segment_pipeline, url
|
||||
from unshackle.core.tracks import track
|
||||
|
||||
for module in (segment_pipeline, hls, track):
|
||||
for module in (segment_pipeline, hls):
|
||||
assert "decrypt_track(" in inspect.getsource(module), module.__name__
|
||||
# DASH and ISM decrypt through the pipeline's complete_track, which calls decrypt_track
|
||||
for module in (dash, ism):
|
||||
for module in (dash, hls, ism, url):
|
||||
assert "complete_track(" in inspect.getsource(module), module.__name__
|
||||
for module in (dash, hls, ism, segment_pipeline, track):
|
||||
for module in (dash, hls, ism, segment_pipeline, track, url):
|
||||
src = inspect.getsource(module)
|
||||
assert "drm.decrypt(save_path)" not in src and "drm.decrypt(merged_path)" not in src, module.__name__
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from unshackle.core.tracks.track import has_encrypted_sample_entry
|
||||
from unshackle.core.drm.verify import has_encrypted_sample_entry
|
||||
|
||||
|
||||
def box(fmt: bytes, payload: bytes = b"") -> bytes:
|
||||
|
||||
@@ -58,11 +58,11 @@ from unshackle.core.downloaders import (
|
||||
from unshackle.core.drm import (
|
||||
WHOLE_FILE_DRM,
|
||||
MonaLisa,
|
||||
cbcs,
|
||||
own_kids,
|
||||
verify,
|
||||
)
|
||||
from unshackle.core.drm.key_resolution import ContentKeyResolver
|
||||
from unshackle.core.drm.verify import has_encrypted_sample_entry
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.export_name import ExportNamer, move_export, plural, season_episodes, title_label
|
||||
from unshackle.core.launch import LaunchKeys, launch, load_service_config
|
||||
@@ -90,12 +90,7 @@ from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.attachment import Attachment
|
||||
from unshackle.core.tracks.selection import Skip, TrackSelection, generated_dv_ranges
|
||||
from unshackle.core.tracks.subtitle_convert import PYCAPTION_WRITERS, SUBSTATION, build_ass_style
|
||||
from unshackle.core.tracks.track import (
|
||||
Track,
|
||||
assert_fragments_decrypted,
|
||||
fix_data_reference_indexes,
|
||||
has_encrypted_sample_entry,
|
||||
)
|
||||
from unshackle.core.tracks.track import Track, assert_fragments_decrypted, fix_data_reference_indexes
|
||||
from unshackle.core.utilities import (
|
||||
find_font_with_fallbacks,
|
||||
get_debug_logger,
|
||||
@@ -2267,20 +2262,8 @@ class dl:
|
||||
download_processes=download_processes,
|
||||
progress=progress_callables[i],
|
||||
on_segments=disk_check.add_segments if disk_check else None,
|
||||
sample_decrypter=service.sample_decrypter(track),
|
||||
)
|
||||
if (
|
||||
track.path
|
||||
and service.decrypts_samples(track)
|
||||
and not DOWNLOAD_CANCELLED.is_set()
|
||||
and not DOWNLOAD_LICENCE_ONLY.is_set()
|
||||
):
|
||||
progress = progress_callables[i]
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
cbcs.decrypt_file(
|
||||
track.path, lambda _l, entry: service.get_sample_decrypter(track, entry.index)
|
||||
)
|
||||
assert_fragments_decrypted(track.path)
|
||||
progress(downloaded="Decrypted", completed=100, total=100)
|
||||
# DRM-free and HLS-ClearKey tracks never reach prepare_drm, so export here.
|
||||
# drm=None on purpose: licensed tracks already recorded their DRM/keys
|
||||
# in prepare_drm, and write_export merges via setdefault.
|
||||
|
||||
@@ -39,8 +39,9 @@ from unshackle.core.events import events
|
||||
from unshackle.core.manifests.dash import PeriodRebase, mdhd_timescale, missing_language, rebase_webvtt_files
|
||||
from unshackle.core.manifests.segment_pipeline import (
|
||||
append_segment,
|
||||
check_decrypted,
|
||||
check_merged,
|
||||
decrypt_output,
|
||||
complete_track,
|
||||
fetch_segments,
|
||||
license_drm,
|
||||
licensing,
|
||||
@@ -48,7 +49,7 @@ from unshackle.core.manifests.segment_pipeline import (
|
||||
from unshackle.core.session import RnetResponse, RnetSession, unrecorded, utf8_text
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Tracks, Video
|
||||
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore
|
||||
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track, assert_fragments_decrypted
|
||||
from unshackle.core.tracks.track import DRM_PREFERENCE_TYPES, Track
|
||||
from unshackle.core.utilities import get_extension, is_close_match, log_event, try_ensure_utf8
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.redact import safe_display_url
|
||||
@@ -871,10 +872,7 @@ class HLS:
|
||||
"downloader": "requests",
|
||||
},
|
||||
)
|
||||
if session_drm:
|
||||
decrypt_output(track, ctx, session_drm, decrypt=not segment_decrypter)
|
||||
progress(downloaded="Downloaded", completed=100, total=100)
|
||||
track.path = save_path
|
||||
complete_track(track, ctx, session_drm, decrypt=not segment_decrypter)
|
||||
return
|
||||
|
||||
progress(total=total_segments, completed=0, downloaded="Merging")
|
||||
@@ -969,7 +967,7 @@ class HLS:
|
||||
map_data = (map_data[0], decrypted_init)
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=True)
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
|
||||
assert_fragments_decrypted(merged_path)
|
||||
check_decrypted(track, merged_path, drm)
|
||||
merged_path.rename(decrypted_path)
|
||||
else:
|
||||
# AES segments must be decrypted individually before merging: each segment
|
||||
@@ -1161,12 +1159,9 @@ class HLS:
|
||||
|
||||
store.complete()
|
||||
|
||||
progress(downloaded="Downloaded", completed=100, total=100)
|
||||
|
||||
track.path = save_path
|
||||
|
||||
if session_drm:
|
||||
track.drm = None
|
||||
complete_track(track, ctx, None)
|
||||
|
||||
@staticmethod
|
||||
def discontinuity_starts(wanted_segments: list[Any]) -> list[float]:
|
||||
|
||||
@@ -16,9 +16,10 @@ from typing import Any, BinaryIO
|
||||
from uuid import UUID
|
||||
|
||||
from unshackle.core.constants import DOWNLOAD_CANCELLED, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, WHOLE_FILE_DRM, ClearKeyCENC, ClearKeyCTR, MonaLisa, PlayReady, Widevine, cbcs
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter
|
||||
from unshackle.core.drm.verify import decrypt_track
|
||||
from unshackle.core.drm.verify import decrypt_track, has_encrypted_sample_entry
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
from unshackle.core.session import AnySession
|
||||
@@ -28,17 +29,21 @@ from unshackle.core.tracks.track import assert_fragments_decrypted
|
||||
from unshackle.core.utilities import log_event, try_ensure_utf8
|
||||
|
||||
|
||||
def text_subtitle_bytes(data: bytes) -> bytes:
|
||||
"""`data` as UTF-8, with the ‎ and ‏ entities as their characters."""
|
||||
return (
|
||||
try_ensure_utf8(data)
|
||||
.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
|
||||
|
||||
def append_segment(dst: BinaryIO, segment_file: Path, is_text_subtitle: bool) -> None:
|
||||
"""Append one segment file to the output, with the text subtitle fixups when they apply."""
|
||||
if is_text_subtitle:
|
||||
segment_data = try_ensure_utf8(segment_file.read_bytes())
|
||||
segment_data = (
|
||||
segment_data.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
dst.write(segment_data)
|
||||
dst.write(text_subtitle_bytes(segment_file.read_bytes()))
|
||||
else:
|
||||
with open(segment_file, "rb") as src:
|
||||
shutil.copyfileobj(src, dst, 1024 * 1024)
|
||||
@@ -256,36 +261,70 @@ def check_merged(merger: RollingMerge, total: int, track: AnyTrack, ctx: Downloa
|
||||
raise FileNotFoundError(error_msg)
|
||||
|
||||
|
||||
def decrypt_output(track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True) -> None:
|
||||
"""Decrypt ctx.save_path through decrypt_track, check every fragment, and emit TRACK_DECRYPTED.
|
||||
def check_decrypted(track: AnyTrack, path: Path, drm: DRM_T | None) -> None:
|
||||
"""Raise if a fragment of `path` still carries encryption, and mark the track for a repack when its moov does.
|
||||
|
||||
A whole-file cipher leaves no fragments to check. An encrypted sample entry that survives the decrypt
|
||||
would lock the muxer to a generic codec.
|
||||
"""
|
||||
if not isinstance(drm, WHOLE_FILE_DRM):
|
||||
assert_fragments_decrypted(path)
|
||||
if has_encrypted_sample_entry(path):
|
||||
track.needs_repack = True
|
||||
|
||||
|
||||
def decrypt_output(
|
||||
track: AnyTrack, ctx: DownloadContext, drm: DRM_T, decrypt: bool = True, kid: UUID | None = None
|
||||
) -> None:
|
||||
"""Decrypt ctx.save_path through decrypt_track, check it, and emit TRACK_DECRYPTED.
|
||||
|
||||
`decrypt=False` means a SegmentDecrypter already decrypted the segments, so only the check runs.
|
||||
"""
|
||||
ctx.progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, decrypt=decrypt, track=track)
|
||||
assert_fragments_decrypted(ctx.save_path)
|
||||
decrypt_track(drm, ctx.save_path, ctx.license_widevine, kid, decrypt=decrypt, track=track)
|
||||
check_decrypted(track, ctx.save_path, drm)
|
||||
track.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=None)
|
||||
|
||||
|
||||
def complete_track(track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True) -> None:
|
||||
"""Hand the merged file to the track, decrypt it, and remove the segment directory."""
|
||||
def decrypt_samples(track: AnyTrack, ctx: DownloadContext, decrypter: Callable[[int], bytes | SampleDecrypter]) -> None:
|
||||
"""Decrypt ctx.save_path with the service sample decrypter, check it, and emit TRACK_DECRYPTED with no DRM."""
|
||||
cbcs.decrypt_file(ctx.save_path, lambda _layout, entry: decrypter(entry.index))
|
||||
check_decrypted(track, ctx.save_path, None)
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=None, segment=None)
|
||||
|
||||
|
||||
def complete_track(
|
||||
track: AnyTrack, ctx: DownloadContext, drm: DRM_T | None, decrypt: bool = True, kid: UUID | None = None
|
||||
) -> None:
|
||||
"""Hand the merged file to the track, decrypt it, and remove the segment directory.
|
||||
|
||||
The track decrypts with `drm` (key ID `kid`), with the service sample decrypter of ctx, or both.
|
||||
"""
|
||||
track.path = ctx.save_path
|
||||
|
||||
samples = None if DOWNLOAD_CANCELLED.is_set() else ctx.sample_decrypter
|
||||
if drm or samples:
|
||||
ctx.progress(downloaded="Decrypting", completed=0, total=None)
|
||||
if drm:
|
||||
decrypt_output(track, ctx, drm, decrypt)
|
||||
decrypt_output(track, ctx, drm, decrypt, kid)
|
||||
if samples:
|
||||
decrypt_samples(track, ctx, samples)
|
||||
if drm or samples:
|
||||
ctx.progress(downloaded="Decrypted", completed=100, total=100)
|
||||
|
||||
SegmentStore(track, ctx.save_dir).complete()
|
||||
ctx.progress(downloaded="Downloaded")
|
||||
ctx.progress(downloaded="Downloaded", completed=100, total=100)
|
||||
|
||||
|
||||
__all__ = (
|
||||
"RollingMerge",
|
||||
"append_segment",
|
||||
"check_decrypted",
|
||||
"check_merged",
|
||||
"text_subtitle_bytes",
|
||||
"complete_track",
|
||||
"decrypt_output",
|
||||
"decrypt_samples",
|
||||
"fetch_segments",
|
||||
"license_drm",
|
||||
"licensing",
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The download step of a URL track: one file, fetched whole or cut to the sample window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import logging
|
||||
import shutil
|
||||
|
||||
import click
|
||||
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import (
|
||||
DOWNLOAD_ALL_DRM,
|
||||
DOWNLOAD_CANCELLED,
|
||||
DOWNLOAD_LICENCE_ONLY,
|
||||
AnyTrack,
|
||||
DownloadCancelled,
|
||||
)
|
||||
from unshackle.core.drm import WHOLE_FILE_DRM, PlayReady, Widevine
|
||||
from unshackle.core.manifests.segment_pipeline import complete_track, license_drm, text_subtitle_bytes
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.tracks import Audio, DownloadContext, Subtitle, Video
|
||||
|
||||
|
||||
def download_track(track: AnyTrack, ctx: DownloadContext, session: AnySession) -> None:
|
||||
"""Find the DRM of the track, license it, download the file and hand it to complete_track.
|
||||
|
||||
`session` reads the init and the KID, ctx.session downloads the file. A failure shows FAILED and cancels
|
||||
the pending track downloads.
|
||||
"""
|
||||
log = logging.getLogger("track")
|
||||
progress = ctx.progress
|
||||
save_path = ctx.save_path
|
||||
media = isinstance(track, (Video, Audio))
|
||||
try:
|
||||
track.ensure_url()
|
||||
if (
|
||||
DOWNLOAD_ALL_DRM.is_set()
|
||||
and media
|
||||
and not {Widevine, PlayReady} <= {type(d) for d in track.drm or []}
|
||||
and all(type(d) in (Widevine, PlayReady) for d in track.drm or [])
|
||||
):
|
||||
track.add_init_drm(track.get_init_segment(session=session), ctx.cdm)
|
||||
elif not track.drm and media:
|
||||
track.drm_from_pssh(ctx.cdm, lambda system: system.from_track(track, session), log)
|
||||
|
||||
drm = track.get_drm_for_cdm(ctx.cdm) if track.drm else None
|
||||
track_kid = track.get_key_id(session=session) if drm and not isinstance(drm, WHOLE_FILE_DRM) else None
|
||||
if drm:
|
||||
license_drm(track, drm, ctx, track_kid)
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
dl_session = ctx.ensure_session()
|
||||
sample_range = None
|
||||
if config.sample and media:
|
||||
sample_range = track.sample_byte_range(dl_session)
|
||||
if not sample_range:
|
||||
raise click.ClickException("--sample cannot cut this track: it is one file with no segment index.")
|
||||
for status_update in track.downloader(
|
||||
urls=[{"url": track.url, "headers": {"Range": f"bytes={sample_range[1]}"}}] if sample_range else track.url,
|
||||
output_dir=save_path.parent,
|
||||
filename=save_path.name,
|
||||
headers=dl_session.headers,
|
||||
cookies=dl_session.cookies,
|
||||
proxy=ctx.proxy,
|
||||
max_workers=ctx.max_workers,
|
||||
session=dl_session,
|
||||
adaptive=ctx.adaptive_workers,
|
||||
processes=ctx.download_processes,
|
||||
):
|
||||
if not status_update.get("file_downloaded"):
|
||||
downloaded = status_update.get("downloaded")
|
||||
if downloaded and downloaded.endswith("/s"):
|
||||
status_update["downloaded"] = f"URL {downloaded}"
|
||||
progress(**status_update)
|
||||
|
||||
if sample_range:
|
||||
media_path = save_path.with_name(f"{save_path.name}.media")
|
||||
save_path.replace(media_path)
|
||||
with save_path.open("wb") as joined, media_path.open("rb") as body:
|
||||
joined.write(sample_range[0])
|
||||
shutil.copyfileobj(body, joined)
|
||||
with contextlib.suppress(OSError):
|
||||
media_path.unlink()
|
||||
|
||||
complete_track(track, ctx, drm, kid=track_kid)
|
||||
|
||||
if isinstance(track, Subtitle) and track.codec and track.codec.name not in ("fVTT", "fTTML"):
|
||||
save_path.write_bytes(text_subtitle_bytes(save_path.read_bytes()))
|
||||
except KeyboardInterrupt:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[yellow]CANCELLED")
|
||||
raise
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except Exception:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[red]FAILED")
|
||||
raise
|
||||
|
||||
|
||||
__all__ = ("download_track",)
|
||||
@@ -4,7 +4,9 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from abc import ABCMeta, abstractmethod
|
||||
from collections.abc import Callable
|
||||
from enum import Enum
|
||||
from functools import partial
|
||||
from http.cookiejar import CookieJar
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple, Protocol
|
||||
@@ -249,11 +251,15 @@ class TitleSource(metaclass=ABCMeta):
|
||||
def get_sample_decrypter(self, track: AnyTrack, entry: int) -> bytes | SampleDecrypter:
|
||||
"""The content key, or a `cbcs.SampleDecrypter`, for `stsd` entry `entry` (1-based) of `track`.
|
||||
|
||||
unshackle calls this only for a track `decrypts_samples` names. A remote session runs it on the
|
||||
server, so a decrypter that needs a local process works for remote clients too.
|
||||
unshackle calls this only for a track `decrypts_samples` names, before TRACK_DOWNLOADED. A remote session
|
||||
runs it on the server, so a decrypter that needs a local process works for remote clients too.
|
||||
"""
|
||||
raise NotImplementedError(f"{self.__class__.__name__} does not decrypt samples")
|
||||
|
||||
def sample_decrypter(self, track: AnyTrack) -> Callable[[int], bytes | SampleDecrypter] | None:
|
||||
"""`get_sample_decrypter` for `track`, when `decrypts_samples` names it."""
|
||||
return partial(self.get_sample_decrypter, track) if self.decrypts_samples(track) else None
|
||||
|
||||
# Optional Event methods
|
||||
|
||||
def on_segment_downloaded(self, track: AnyTrack, segment: Path) -> None:
|
||||
@@ -267,20 +273,20 @@ class TitleSource(metaclass=ABCMeta):
|
||||
|
||||
def on_track_downloaded(self, track: AnyTrack) -> None:
|
||||
"""
|
||||
Called once when a Track has finished downloading, after unshackle decrypted its `drm`.
|
||||
Called once when a Track has finished downloading, after unshackle decrypted it.
|
||||
In a licence-only run the track has no file.
|
||||
|
||||
Parameters:
|
||||
track: The downloaded Track object.
|
||||
"""
|
||||
|
||||
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T, segment: m3u8.Segment | None = None) -> None:
|
||||
def on_track_decrypted(self, track: AnyTrack, drm: DRM_T | None, segment: m3u8.Segment | None = None) -> None:
|
||||
"""
|
||||
Called when a Track has finished decrypting.
|
||||
|
||||
Parameters:
|
||||
track: The decrypted Track object.
|
||||
drm: The DRM object it decrypted with.
|
||||
drm: The DRM object it decrypted with. None for a track `get_sample_decrypter` decrypted.
|
||||
segment: The decrypted HLS segment information. None for DASH and ISM tracks and
|
||||
for an HLS track that merged during the download (merge_segments).
|
||||
"""
|
||||
|
||||
@@ -22,6 +22,7 @@ from subtitle_filter import Subtitles
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm.cbcs import SampleDecrypter
|
||||
from unshackle.core.session import AnySession
|
||||
from unshackle.core.tracks.track import Track
|
||||
from unshackle.core.utilities import PYMP4_LOCK, try_ensure_utf8, with_script
|
||||
@@ -245,6 +246,7 @@ class Subtitle(Track):
|
||||
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,
|
||||
) -> None:
|
||||
super().download(
|
||||
session,
|
||||
@@ -257,6 +259,7 @@ class Subtitle(Track):
|
||||
adaptive_workers=adaptive_workers,
|
||||
download_processes=download_processes,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
)
|
||||
if not self.path:
|
||||
return
|
||||
|
||||
+13
-107
@@ -1,5 +1,4 @@
|
||||
import contextlib
|
||||
import html
|
||||
import logging
|
||||
import re
|
||||
import shutil
|
||||
@@ -25,15 +24,14 @@ from requests.adapters import HTTPAdapter, Retry
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.cdm.detect import is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled
|
||||
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, WHOLE_FILE_DRM, PlayReady, Widevine
|
||||
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,
|
||||
decrypt_track,
|
||||
find_child_box,
|
||||
has_encrypted_sample_entry,
|
||||
read_top_level_box,
|
||||
senc_protects_samples,
|
||||
walk,
|
||||
@@ -41,7 +39,7 @@ from unshackle.core.drm.verify import (
|
||||
from unshackle.core.events import events
|
||||
from unshackle.core.session import MAX_BACKOFF, AnySession, RnetSession, unrecorded, utf8_text
|
||||
from unshackle.core.tracks.segment_store import SegmentStore
|
||||
from unshackle.core.utilities import language_name, log_event, try_ensure_utf8
|
||||
from unshackle.core.utilities import language_name, log_event
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.subprocess import run_tool
|
||||
|
||||
@@ -401,6 +399,8 @@ class DownloadContext:
|
||||
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."""
|
||||
|
||||
def ensure_session(self) -> AnySession:
|
||||
"""Return the HTTP session, or a new ``Session`` if none was set."""
|
||||
@@ -729,14 +729,16 @@ class Track:
|
||||
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,
|
||||
) -> None:
|
||||
"""Download and optionally Decrypt this Track.
|
||||
"""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` decrypts a track the service decrypts itself (see DownloadContext).
|
||||
"""
|
||||
from unshackle.core.manifests import DASH, HLS, ISM
|
||||
from unshackle.core.manifests.segment_pipeline import license_drm, licensing
|
||||
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
|
||||
@@ -749,8 +751,6 @@ class Track:
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
return
|
||||
|
||||
log = logging.getLogger("track")
|
||||
|
||||
proxy = next(iter(session.proxies.values()), None)
|
||||
|
||||
dl_session = session
|
||||
@@ -811,106 +811,12 @@ class Track:
|
||||
license_widevine=prepare_drm,
|
||||
cdm=cdm,
|
||||
on_segments=on_segments,
|
||||
sample_decrypter=sample_decrypter,
|
||||
)
|
||||
if self.descriptor in manifest_parsers:
|
||||
manifest_parsers[self.descriptor].download_track(track=self, ctx=ctx)
|
||||
elif self.descriptor == self.Descriptor.URL:
|
||||
try:
|
||||
self.ensure_url()
|
||||
if (
|
||||
DOWNLOAD_ALL_DRM.is_set()
|
||||
and track_type in ("Video", "Audio")
|
||||
and not {Widevine, PlayReady} <= {type(d) for d in self.drm or []}
|
||||
and all(type(d) in (Widevine, PlayReady) for d in self.drm or [])
|
||||
):
|
||||
self.add_init_drm(self.get_init_segment(session=session), cdm)
|
||||
elif not self.drm and track_type in ("Video", "Audio"):
|
||||
self.drm_from_pssh(cdm, lambda system: system.from_track(self, session), log)
|
||||
|
||||
if self.drm:
|
||||
drm = self.get_drm_for_cdm(cdm)
|
||||
track_kid = None if isinstance(drm, WHOLE_FILE_DRM) else self.get_key_id(session=session)
|
||||
license_drm(self, drm, ctx, track_kid)
|
||||
else:
|
||||
drm = None
|
||||
|
||||
if DOWNLOAD_LICENCE_ONLY.is_set():
|
||||
progress(downloaded="[yellow]SKIPPED")
|
||||
else:
|
||||
sample_range = None
|
||||
if config.sample and track_type in ("Video", "Audio"):
|
||||
sample_range = self.sample_byte_range(dl_session)
|
||||
if not sample_range:
|
||||
raise click.ClickException(
|
||||
"--sample cannot cut this track: it is one file with no segment index."
|
||||
)
|
||||
for status_update in self.downloader(
|
||||
urls=[{"url": self.url, "headers": {"Range": f"bytes={sample_range[1]}"}}]
|
||||
if sample_range
|
||||
else self.url,
|
||||
output_dir=save_path.parent,
|
||||
filename=save_path.name,
|
||||
headers=dl_session.headers,
|
||||
cookies=dl_session.cookies,
|
||||
proxy=proxy,
|
||||
max_workers=max_workers,
|
||||
session=dl_session,
|
||||
adaptive=adaptive_workers,
|
||||
processes=download_processes,
|
||||
):
|
||||
file_downloaded = status_update.get("file_downloaded")
|
||||
if not file_downloaded:
|
||||
downloaded = status_update.get("downloaded")
|
||||
if downloaded and downloaded.endswith("/s"):
|
||||
status_update["downloaded"] = f"URL {downloaded}"
|
||||
progress(**status_update)
|
||||
|
||||
if sample_range:
|
||||
media_path = save_path.with_name(f"{save_path.name}.media")
|
||||
save_path.replace(media_path)
|
||||
with save_path.open("wb") as joined, media_path.open("rb") as media:
|
||||
joined.write(sample_range[0])
|
||||
shutil.copyfileobj(media, joined)
|
||||
with contextlib.suppress(OSError):
|
||||
media_path.unlink()
|
||||
|
||||
self.path = save_path
|
||||
|
||||
if drm:
|
||||
progress(downloaded="Decrypting", completed=0, total=None)
|
||||
decrypt_track(drm, save_path, prepare_drm, track_kid, track=self)
|
||||
if not isinstance(drm, WHOLE_FILE_DRM):
|
||||
assert_fragments_decrypted(save_path)
|
||||
self.drm = None
|
||||
events.emit(events.Types.TRACK_DECRYPTED, track=self, drm=drm, segment=None)
|
||||
progress(downloaded="Decrypted", completed=100, total=100)
|
||||
# residual encv/enca => decrypt tool skipped/failed; force a repack so the
|
||||
# muxer isn't first-FourCC-locked to a generic (encrypted) codec. OR-in only.
|
||||
if has_encrypted_sample_entry(save_path):
|
||||
self.needs_repack = True
|
||||
|
||||
if isinstance(self, Subtitle) and self.codec and self.codec.name not in ("fVTT", "fTTML"):
|
||||
track_data = self.path.read_bytes()
|
||||
track_data = try_ensure_utf8(track_data)
|
||||
track_data = (
|
||||
track_data.decode("utf8")
|
||||
.replace("‎", html.unescape("‎"))
|
||||
.replace("‏", html.unescape("‏"))
|
||||
.encode("utf8")
|
||||
)
|
||||
self.path.write_bytes(track_data)
|
||||
|
||||
progress(downloaded="Downloaded")
|
||||
except KeyboardInterrupt:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[yellow]CANCELLED")
|
||||
raise
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except Exception:
|
||||
DOWNLOAD_CANCELLED.set()
|
||||
progress(downloaded="[red]FAILED")
|
||||
raise
|
||||
url.download_track(self, ctx, session)
|
||||
|
||||
if DOWNLOAD_CANCELLED.is_set():
|
||||
return
|
||||
|
||||
Reference in New Issue
Block a user