"""A service without ``get_fairplay_bridge_license`` leaves FairPlay-only tracks out of the selection.""" from __future__ import annotations import logging from types import SimpleNamespace from typing import Any import pytest from lxml import etree from pywidevine.pssh import PSSH from tests.core.test_hls_service_drm_keys import KID, SKD_KEY, WIDEVINE_KEY, playlist from tests.lang_selection import test_kind_only_selection as harness from unshackle.core.drm import Widevine, discovery from unshackle.core.title_source import KeyArrival from unshackle.core.titles import Episode from unshackle.core.tracks import Audio, Tracks, Video from unshackle.core.tracks.track import Track FAIRPLAY_CP = '' PLAYREADY_CP = '' WIDEVINE_CP = '' MP4_CP = '' PLAYREADY_KEY = ( '#EXT-X-KEY:METHOD=SAMPLE-AES-CTR,URI="data:text/plain;charset=UTF-16;base64,AAAA",' 'KEYFORMAT="com.microsoft.playready",KEYFORMATVERSIONS="1"' ) BASE = "https://cdn.example.test/" PLAYLISTS = { f"{BASE}2160.m3u8": playlist(SKD_KEY), f"{BASE}1080.m3u8": playlist(PLAYREADY_KEY), f"{BASE}a-fp.m3u8": playlist(SKD_KEY), f"{BASE}hdr.m3u8": playlist(PLAYREADY_KEY), f"{BASE}dv.m3u8": playlist(SKD_KEY), } class Playlists: """A session that serves the media playlists and notes each URL it gets.""" def __init__(self) -> None: self.urls: list[str] = [] def get(self, url: str, **_: Any) -> SimpleNamespace: self.urls.append(url) return SimpleNamespace(text=PLAYLISTS[url], ok=True) def dash_data(*protections: str) -> dict: adaptation_set = etree.fromstring(f"{''.join(protections)}") return {"dash": {"adaptation_set": adaptation_set, "representation": adaptation_set.find("Representation")}} def video( id_: str, height: int, descriptor: Track.Descriptor, data: dict | None = None, range_: Video.Range = Video.Range.SDR, ) -> Video: return Video( id_=id_, url=f"{BASE}{id_}.m3u8", language="en", codec=Video.Codec.HEVC, range_=range_, width=height * 16 // 9, height=height, bitrate=height * 10_000, descriptor=descriptor, data=data, ) class Example(harness.FakeService): """EXAMPLE: a FairPlay-only 2160p video and audio beside a 1080p video with a PlayReady tag; no bridge hook.""" def __init__(self, dash: bool = False) -> None: super().__init__({1: {}}) self.session = Playlists() self.dash = dash self.drm_on_2160: list | None = None def get_tracks(self, title: Episode) -> Tracks: tracks = super().get_tracks(title) if self.dash: tracks.videos = [ video("2160", 2160, Track.Descriptor.DASH, dash_data(MP4_CP, FAIRPLAY_CP)), video("1080", 1080, Track.Descriptor.DASH, dash_data(MP4_CP, PLAYREADY_CP)), ] else: tracks.videos = [video("2160", 2160, Track.Descriptor.HLS), video("1080", 1080, Track.Descriptor.HLS)] tracks.audio.insert( 0, Audio( id_="a-fp", url=f"{BASE}a-fp.m3u8", language="en", codec=Audio.Codec.AAC, bitrate=256_000, descriptor=Track.Descriptor.HLS, ), ) tracks.videos[0].drm = self.drm_on_2160 return tracks def __getattr__(self, name: str) -> Any: if name == "get_fairplay_bridge_license": raise AttributeError(name) return super().__getattr__(name) class Bridged(Example): """EXAMPLE with the hook.""" def get_fairplay_bridge_license(self, **_: Any) -> bytes: return b"" def run(monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, service: Example, **flags: Any) -> Any: return harness.run(monkeypatch, caplog, {1: {}}, service=service, log_level=logging.INFO, **flags) def test_without_the_hook_the_next_best_tracks_that_license_are_kept( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: service = Example() ids = run(monkeypatch, caplog, service) assert ids["video"] == ["1080"] assert ids["audio"] == ["a"] assert caplog.text.count("Left out 2 FairPlay-only tracks: FAKE has no FairPlay bridge hook") == 1 assert sorted(service.session.urls) == [f"{BASE}1080.m3u8", f"{BASE}2160.m3u8", f"{BASE}a-fp.m3u8"] def test_with_the_hook_the_fairplay_only_tracks_compete_and_nothing_is_probed( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: service = Bridged() ids = run(monkeypatch, caplog, service) assert ids["video"] == ["2160"] assert ids["audio"] == ["a-fp"] assert "FairPlay-only" not in caplog.text assert service.session.urls == [] def test_a_quality_with_only_fairplay_only_tracks_skips_with_the_existing_reason( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: assert run(monkeypatch, caplog, Example(), quality=[2160]) == 1 assert "Left out 2 FairPlay-only tracks" in caplog.text assert "Show S01E01: There's no 2160p Video Track..." in caplog.text def test_best_available_falls_back_to_the_track_that_licenses( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: ids = run(monkeypatch, caplog, Example(), quality=[2160], best_available=True) assert ids["video"] == ["1080"] @pytest.mark.parametrize(("service", "expected"), [(Example, "1080"), (Bridged, "2160")], ids=["no-hook", "hook"]) def test_a_dash_adaptation_set_with_only_a_fairplay_content_protection( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, service: type[Example], expected: str ) -> None: source = service(dash=True) ids = run(monkeypatch, caplog, source) assert ids["video"] == [expected] assert source.session.urls == [] def test_a_track_with_a_drm_object_costs_no_request( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: service = Example() service.drm_on_2160 = [Widevine(PSSH.new(key_ids=[KID], system_id=PSSH.SystemId.Widevine))] ids = run(monkeypatch, caplog, service) assert ids["video"] == ["2160"] assert f"{BASE}2160.m3u8" not in service.session.urls def test_list_probes_nothing_and_lists_every_track( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: service = Example() ids = run(monkeypatch, caplog, service, list_=True) assert ids["video"] == ["2160", "1080"] assert service.session.urls == [] @pytest.mark.parametrize( ("protections", "expected"), [ pytest.param((MP4_CP, FAIRPLAY_CP), True, id="fairplay"), pytest.param((FAIRPLAY_CP, WIDEVINE_CP), False, id="fairplay-and-widevine-without-pssh"), pytest.param((MP4_CP,), False, id="no-key-system"), pytest.param((), False, id="clear"), ], ) def test_dash_fairplay_only_reads_the_key_systems_of_the_content_protection( protections: tuple[str, ...], expected: bool ) -> None: assert discovery.fairplay_only(video("v", 1080, Track.Descriptor.DASH, dash_data(*protections))) is expected @pytest.mark.parametrize( ("text", "expected"), [(playlist(SKD_KEY), True), (playlist(SKD_KEY, WIDEVINE_KEY), False), (playlist(), False)], ids=["fairplay", "fairplay-and-widevine", "clear"], ) def test_hls_fairplay_only_reads_the_media_playlist(text: str, expected: bool) -> None: session = SimpleNamespace(get=lambda url, **_: SimpleNamespace(text=text, ok=True)) assert discovery.fairplay_only(video("v", 1080, Track.Descriptor.HLS), session) is expected class FairPlayAudio(Example): """EXAMPLE whose only audio track is FairPlay-only.""" def get_tracks(self, title: Episode) -> Tracks: tracks = super().get_tracks(title) tracks.audio = [audio for audio in tracks.audio if audio.id == "a-fp"] return tracks def test_a_kind_whose_selected_tracks_are_all_fairplay_only_skips_the_title( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: assert run(monkeypatch, caplog, FairPlayAudio()) == 1 assert "Show S01E01: Each selected audio track is FairPlay-only: FAKE has no FairPlay bridge hook" in caplog.text class Imported(Example): """An import: the export holds the content keys of each track, FairPlay-only ones too.""" @property def key_arrival(self) -> KeyArrival: return KeyArrival.EXPORT def test_an_import_keeps_the_fairplay_only_tracks_and_probes_nothing( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: service = Imported() ids = run(monkeypatch, caplog, service) assert ids["video"] == ["2160"] assert service.session.urls == [] class Hybrid(Example): """EXAMPLE with a 2160p HDR10 video that licenses and, unless ``dv`` is off, a FairPlay-only 2160p DV video.""" def __init__(self, dv: bool = True) -> None: super().__init__() self.dv = dv def get_tracks(self, title: Episode) -> Tracks: tracks = super().get_tracks(title) tracks.videos = [video("hdr", 2160, Track.Descriptor.HLS, range_=Video.Range.HDR10)] if self.dv: tracks.videos.append(video("dv", 2160, Track.Descriptor.HLS, range_=Video.Range.DV)) self.videos = tracks.videos return tracks def test_a_hybrid_that_loses_its_dolby_vision_track_flags_the_base_as_if_it_had_none( monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture ) -> None: harness.stub_hybrid(monkeypatch) flags = {"range_": [Video.Range.HYBRID, Video.Range.HDR10], "best_available": True} results = [] for service in (Hybrid(), Hybrid(dv=False)): ids = run(monkeypatch, caplog, service, **flags) hdr = service.videos[0] results.append((ids["video"], hdr.hybrid_ingredient, hdr.hybrid_base_only, hdr.native_hybrid)) assert results[0] == results[1] assert results[0][0] == ["hdr"] def test_a_widevine_pssh_in_the_dash_init_segment_makes_the_track_licensable(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(discovery, "drm_from_init_segment", lambda track, session=None: ["widevine"]) assert not discovery.fairplay_only(video("v", 1080, Track.Descriptor.DASH, dash_data(MP4_CP, FAIRPLAY_CP)))