fix(hls): bridge a FairPlay playlist whose clear part has a METHOD=NONE tag and its own init segment

This commit is contained in:
imSp4rky
2026-12-01 18:32:31 -07:00
parent f680df7eff
commit e0880812d5
4 changed files with 121 additions and 10 deletions
+6 -2
View File
@@ -483,7 +483,10 @@ these conditions are true:
- The track has no DRM object.
- Every `EXT-X-KEY` of its media playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a DRM system
unshackle cannot license.
unshackle cannot license, or `METHOD=NONE`. A segment under `METHOD=NONE` must have an init segment
that no encrypted segment uses: a decrypter that reads the encrypted init segment decrypts the clear
samples too. A tag with `KEYFORMAT="identity"`, or with no `KEYFORMAT`, names no DRM system: each
encrypted segment also needs a tag of a DRM system.
- The configured CDM is a PlayReady or Widevine CDM.
- The init segment (`EXT-X-MAP`) of the track names a key ID in its `tenc` box. When the `tenc` key ID is all
zeros, the playlist must have one key URI, and each init segment under the key tag must give the same
@@ -510,7 +513,8 @@ on the track:
by the key ID, not with one that checks a header a packager signed. A platform can issue the
content key of one package of a title and refuse another. When a track carries a Widevine or PlayReady DRM
object and every `EXT-X-KEY` of its playlist is `SAMPLE-AES` or `SAMPLE-AES-CTR` for a key system
unshackle cannot license, `HLS.drop_unsupported_keys` removes the tags from the parsed playlist.
unshackle cannot license, or `METHOD=NONE` under the same condition, `HLS.drop_unsupported_keys` removes the
tags from the parsed playlist.
The download then licenses and decrypts the track with the DRM object of the track. This works for
one content key per track: the key changes of the playlist go with the tags. This limit also
applies to a DRM object that the download builds. Any other track stops with
+3
View File
@@ -82,6 +82,9 @@ appropriate one for each track.
for a DRM system that unshackle cannot license, such as FairPlay, unshackle reads the key ID from
the init segment and asks for the licence with your PlayReady or Widevine device. This works
only when the licence server of the platform also issues that content key for that DRM system. MPEG-TS SAMPLE-AES stops with an error.
Each key ID must name one content key: a playlist that encrypts two blocks with two content keys under
one key ID gives wrong frames. A clear part under `METHOD=NONE` must have its own init segment, or the
track stops with an error.
!!! info "Obtaining device files"
A `.wvd` or `.prd` encodes the private keys of a real client device. unshackle
+90 -3
View File
@@ -33,6 +33,7 @@ SKD_KEY = (
'#EXT-X-KEY:METHOD=SAMPLE-AES,URI="skd://keys.example/asset",'
'KEYFORMAT="com.apple.streamingkeydelivery",KEYFORMATVERSIONS="1"'
)
NONE_KEY = "#EXT-X-KEY:METHOD=NONE"
WIDEVINE_KEY = (
'#EXT-X-KEY:METHOD=SAMPLE-AES,URI="data:text/plain;base64,'
f'{PSSH.new(key_ids=[KID], system_id=PSSH.SystemId.Widevine).dumps()}",'
@@ -129,6 +130,36 @@ def test_a_key_tag_unshackle_can_read_keeps_every_tag(key_tag: str) -> None:
assert [segment.keys for segment in manifest.segments] == segment_keys
IDENTITY_KEY = '#EXT-X-KEY:METHOD=SAMPLE-AES,URI="https://keys.example/key"'
@pytest.mark.parametrize(
"text, unsupported",
[
pytest.param(playlist(IDENTITY_KEY), False, id="no-keyformat"),
pytest.param(playlist(f'{IDENTITY_KEY},KEYFORMAT="identity"'), False, id="identity"),
pytest.param(playlist(SKD_KEY), True, id="fairplay"),
pytest.param(playlist(IDENTITY_KEY, SKD_KEY), True, id="identity-beside-fairplay"),
pytest.param(
playlist(SKD_KEY).replace("seg0.m4s\n", f"seg0.m4s\n{IDENTITY_KEY}\n"), False, id="identity-later"
),
],
)
def test_only_a_key_tag_of_a_drm_system_is_unsupported(text: str, unsupported: bool) -> None:
"""An identity key file is the content key itself: no DRM system serves it."""
assert HLS.only_unsupported_keys(m3u8.loads(text)) is unsupported
def test_the_server_builds_no_stub_for_an_identity_sample_aes_track(tmp_path: Path, monkeypatch: Any) -> None:
monkeypatch.setattr("unshackle.core.tracks.track.utf8_text", lambda response: playlist(IDENTITY_KEY))
track = hls_video(tmp_path, playlist(IDENTITY_KEY))
probe = init_kid_probe(monkeypatch, KID)
assert not track.load_drm_from_playlist(InitServer(), bridge=True)
assert not track.drm
assert not probe.called
def test_a_playlist_with_no_key_tag_is_left_alone() -> None:
assert not HLS.drop_unsupported_keys(m3u8.loads(playlist()))
@@ -273,10 +304,15 @@ def encrypted_init(tenc: UUID, *pssh: UUID, piff: bool = False) -> bytes:
ZERO_INIT = encrypted_init(ZERO_KID, KID)
def stitched(*inits: str, keyed_from: int = 1) -> str:
"""A playlist with one discontinuity block for each init segment, where block ``keyed_from`` holds the key tag."""
def stitched(*inits: str, keyed_from: int = 1, clear_from: int | None = None) -> str:
"""A playlist with one discontinuity block for each init segment, where block ``keyed_from`` holds the key tag.
Block ``clear_from`` holds a METHOD=NONE tag.
"""
blocks = [f'#EXT-X-MAP:URI="{name}"\n#EXTINF:6.0,\n{i}.m4s\n' for i, name in enumerate(inits)]
blocks[keyed_from] = f"{SKD_KEY}\n{blocks[keyed_from]}"
if clear_from is not None:
blocks[clear_from] = f"{NONE_KEY}\n{blocks[clear_from]}"
body = "#EXT-X-DISCONTINUITY\n".join(blocks)
return f"#EXTM3U\n#EXT-X-VERSION:7\n#EXT-X-TARGETDURATION:6\n{body}#EXT-X-ENDLIST\n"
@@ -327,9 +363,59 @@ STITCHED_ZERO = [
["lead.mp4", "real.mp4"],
id="tag-on-the-clear-lead-of-a-real-tenc",
),
pytest.param(stitched("lead.mp4", "init.mp4", "lead.mp4", clear_from=2), {}, ["init.mp4"], id="method-none-tail"),
]
@pytest.mark.parametrize(
"text, bridged",
[
pytest.param(stitched("lead.mp4", "init.mp4", "lead.mp4", clear_from=2), True, id="tail-with-its-own-init"),
pytest.param(
stitched("lead.mp4", "init.mp4", "init.mp4", clear_from=2), False, id="tail-under-the-encrypted-init"
),
pytest.param(playlist(NONE_KEY), False, id="no-key"),
pytest.param(playlist(SKD_KEY, NONE_KEY), False, id="one-span-of-both"),
],
)
def test_a_method_none_tag_counts_only_when_no_encrypted_segment_shares_its_init(text: str, bridged: bool) -> None:
"""A decrypter that reads the encrypted init segment treats clear samples as encrypted and writes wrong frames."""
manifest = m3u8.loads(text)
assert HLS.drop_unsupported_keys(manifest) == bridged
assert (manifest.keys == [] and all(segment.keys == [] for segment in manifest.segments)) == bridged
def test_the_drm_of_the_service_licenses_a_track_with_a_method_none_tail(tmp_path: Path) -> None:
track = hls_video(tmp_path, stitched("lead.mp4", "init.mp4", "lead.mp4", clear_from=2))
track.drm = [drm_stub("playready", [KID.hex])]
licensed: list[UUID | None] = []
download(track, None, lambda drm, track_kid=None: licensed.append(track_kid), True, InitServer())
assert licensed == [KID]
def test_the_key_id_of_two_keys_comes_from_the_init_after_a_method_none_lead(tmp_path: Path) -> None:
text = stitched("lead.mp4", "real.mp4", "real.mp4", clear_from=0)
text = text.replace("#EXTINF:6.0,\n2.m4s", f"{SKD_KEY.replace('asset', 'other')}\n#EXTINF:6.0,\n2.m4s")
manifest = m3u8.loads(text, "https://example.test/media.m3u8")
session = InitServer(real=encrypted_init(KID))
assert HLS.get_bridge_kid(manifest, manifest.segments, hls_video(tmp_path, ""), session) == KID
assert session.requests == ["real.mp4"]
def test_a_method_none_tail_under_the_encrypted_init_is_refused(tmp_path: Path) -> None:
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
download(
hls_video(tmp_path, stitched("lead.mp4", "init.mp4", "init.mp4", clear_from=2)),
cdm_type_stub("playready"),
session=InitServer(),
)
@pytest.mark.parametrize("text, files, requests", STITCHED_ZERO)
def test_a_stitched_one_key_playlist_takes_the_key_id_that_every_encrypted_init_names(
tmp_path: Path, text: str, files: dict[str, bytes], requests: list[str]
@@ -457,6 +543,7 @@ def test_the_server_takes_the_same_key_id_of_a_stitched_playlist(
cdm_type_stub("playready"),
id="not-sample-encryption",
),
pytest.param(playlist(IDENTITY_KEY), KID, cdm_type_stub("playready"), id="identity-sample-aes"),
],
)
def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_download(
@@ -466,7 +553,7 @@ def test_a_track_with_no_drm_that_cannot_be_bridged_is_refused_before_the_downlo
probe = init_kid_probe(monkeypatch, kid)
session = InitServer()
with pytest.raises(NotImplementedError, match="com.apple.streamingkeydelivery"):
with pytest.raises(NotImplementedError, match="None of the key systems are supported: SAMPLE-AES"):
download(track, cdm, session=session)
assert not track.drm
+22 -5
View File
@@ -1528,10 +1528,10 @@ class HLS:
The pssh boxes count only in a one-key playlist, and with several init segments only as `get_stitched_kid` reads
them: an all-zero tenc takes any content key.
"""
keyed = [span for span in key_spans(manifest, segments) if span.init_section and span.keys]
keyed = [span for span in key_spans(manifest, segments) if span.init_section and HLS.encrypts(span.keys)]
if not keyed or not HLS.only_unsupported_keys(manifest):
return None
one_key = len({key.uri for key in manifest.keys if key}) == 1
one_key = len({key.uri for key in manifest.keys if key and key.method != "NONE"}) == 1
if any(b.init_section != a.init_section and not b.discontinuity for a, b in pairwise(segments)):
return None
init_sections: list[m3u8.model.InitializationSection] = []
@@ -1582,10 +1582,27 @@ class HLS:
def only_unsupported_keys(manifest: M3U8) -> bool:
"""Whether each EXT-X-KEY of `manifest`, at least one, is sample encryption of a DRM system unshackle cannot license.
Any other METHOD, such as AES-128 or AES-256, makes it false.
A METHOD=NONE tag also counts, unless a segment under it shares its init segment with an encrypted segment: a
decrypter that reads the encrypted init segment treats the clear samples as encrypted. Any other METHOD, such as
AES-128 or AES-256-GCM, makes it false. An identity KEYFORMAT, or none, names no DRM system, so each encrypted
segment also needs a tag with another KEYFORMAT.
"""
keys = [key for key in (manifest.keys or []) if key is not None]
return bool(keys) and all(key.method in ("SAMPLE-AES", "SAMPLE-AES-CTR") and not cenc_key(key) for key in keys)
keys = [key for key in (manifest.keys or []) if key is not None and key.method != "NONE"]
if not keys or not all(key.method in ("SAMPLE-AES", "SAMPLE-AES-CTR") and not cenc_key(key) for key in keys):
return False
spans = key_spans(manifest, manifest.segments)
clear_inits = [span.init_section for span in spans if any(key.method == "NONE" for key in span.keys if key)]
return all(
span.init_section not in clear_inits
and any((key.keyformat or "identity").lower() != "identity" for key in span.keys if key)
for span in spans
if HLS.encrypts(span.keys)
)
@staticmethod
def encrypts(keys: list[m3u8.model.Key]) -> bool:
"""Whether `keys` hold an EXT-X-KEY with a METHOD other than NONE."""
return any(key.method != "NONE" for key in keys if key)
@staticmethod
def drop_unsupported_keys(manifest: M3U8) -> bool: