fix(manifests): skip a DASH Representation or HLS variant with an unknown codec

This commit is contained in:
imSp4rky
2026-11-28 14:46:06 -07:00
parent 0bd5c4de4f
commit fd1b9254ee
5 changed files with 130 additions and 21 deletions
+4
View File
@@ -364,6 +364,10 @@ A typical `get_tracks` therefore looks like fetching the manifest text with
language. For HLS, `to_tracks` uses this fallback directly for the primary track, language. For HLS, `to_tracks` uses this fallback directly for the primary track,
because HLS variants carry no language. because HLS variants carry no language.
DASH and HLS `to_tracks` skip a Representation or variant whose codec unshackle does not
know, and log one warning with its codec string. They raise `ValueError` only when they skip at
least one and no track is left.
### Segment-filtering hooks ### Segment-filtering hooks
- **HLS**: set `track.OnSegmentFilter(segment)` to drop unwanted segments (ads/bumpers). - **HLS**: set `track.OnSegmentFilter(segment)` to drop unwanted segments (ads/bumpers).
+5 -1
View File
@@ -57,9 +57,13 @@ def test_index_lists_every_known_failure() -> None:
@pytest.mark.parametrize("entry", cases(INDEX)) @pytest.mark.parametrize("entry", cases(INDEX))
def test_manifest_parses_to_tracks(entry: dict[str, Any]) -> None: def test_manifest_parses_to_tracks(entry: dict[str, Any], caplog: pytest.LogCaptureFixture) -> None:
tracks = parse(entry) tracks = parse(entry)
assert not [
r for r in caplog.records if r.getMessage().startswith(("Skipped DASH Representation", "Skipped HLS variant"))
]
assert tracks.videos or tracks.audio or tracks.subtitles assert tracks.videos or tracks.audio or tracks.subtitles
for track in tracks: for track in tracks:
# HLS CODECS is only a SHOULD (RFC 8216 4.3.4.2), so an HLS track can honestly have none # HLS CODECS is only a SHOULD (RFC 8216 4.3.4.2), so an HLS track can honestly have none
+77
View File
@@ -0,0 +1,77 @@
import logging
import pytest
from langcodes import Language
from unshackle.core.manifests import DASH, HLS
MPD = """<?xml version="1.0"?>
<MPD xmlns="urn:mpeg:dash:schema:mpd:2011" type="static" mediaPresentationDuration="PT10S">
<Period>
<AdaptationSet contentType="video" mimeType="video/mp4" lang="en">
<SegmentTemplate media="$RepresentationID$/$Number$.m4s" initialization="$RepresentationID$/init.mp4" duration="2" />
<Representation id="v1" codecs="avc1.640028" bandwidth="5000000" width="1920" height="1080" />
<Representation id="v2" codecs="zzzz" bandwidth="4000000" width="1920" height="1080" />
</AdaptationSet>
<AdaptationSet contentType="audio" mimeType="audio/mp4" lang="en">
<SegmentTemplate media="$RepresentationID$/$Number$.m4s" initialization="$RepresentationID$/init.mp4" duration="2" />
<Representation id="a1" codecs="mp4a.40.2" bandwidth="128000" />
<Representation id="a2" codecs="zzzz" bandwidth="96000" />
</AdaptationSet>
<AdaptationSet contentType="text" mimeType="application/mp4" lang="en">
<SegmentTemplate media="$RepresentationID$/$Number$.m4s" initialization="$RepresentationID$/init.mp4" duration="2" />
<Representation id="t1" codecs="wvtt" bandwidth="1000" />
<Representation id="t2" codecs="zzzz" bandwidth="1000" />
</AdaptationSet>
<AdaptationSet contentType="text" mimeType="text/zzzz" lang="en">
<Representation id="t3" bandwidth="1000"><BaseURL>t3.zzzz</BaseURL></Representation>
</AdaptationSet>
</Period>
</MPD>"""
MASTER = """#EXTM3U
#EXT-X-STREAM-INF:BANDWIDTH=5000000,CODECS="avc1.640028,mp4a.40.2",RESOLUTION=1920x1080
good.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=4000000,CODECS="zzzz",RESOLUTION=1920x1080
bad.m3u8
#EXT-X-STREAM-INF:BANDWIDTH=3000000,CODECS="zzzz,mp4a.40.2",RESOLUTION=1920x1080
muxed.m3u8?sig=secret
#EXT-X-STREAM-INF:BANDWIDTH=128000,CODECS="mp4a.40.2"
audio.m3u8
"""
def test_dash_skips_each_representation_with_an_unknown_codec(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.WARNING, logger="DASH"):
tracks = DASH.from_text(MPD, url="https://cdn.example/manifest.mpd").to_tracks(language="en")
ids = [t.data["dash"]["representation_id"] for t in (*tracks.videos, *tracks.audio, *tracks.subtitles)]
assert ids == ["v1", "a1", "t1"]
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
assert warnings == [
f"Skipped DASH Representation '{i}': unsupported codec 'zzzz'" for i in ("v2", "a2", "t2", "t3")
]
def test_hls_skips_a_variant_with_an_unknown_codec(caplog: pytest.LogCaptureFixture) -> None:
with caplog.at_level(logging.WARNING, logger="HLS"):
tracks = HLS.from_text(MASTER, url="https://cdn.example/master.m3u8").to_tracks(Language.get("en"))
assert [str(v.url).rsplit("/", 1)[-1] for v in tracks.videos] == ["good.m3u8"]
assert [str(a.url).rsplit("/", 1)[-1] for a in tracks.audio] == ["audio.m3u8"]
warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
assert warnings == [
"Skipped HLS variant 'bad.m3u8': unsupported codec 'zzzz'",
"Skipped HLS variant 'muxed.m3u8': unsupported codec 'zzzz,mp4a.40.2'",
]
def test_dash_with_no_supported_codec_raises() -> None:
mpd = MPD.replace('codecs="avc1.640028"', 'codecs="zzzz"').replace('codecs="mp4a.40.2"', 'codecs="zzzz"')
mpd = mpd.replace('codecs="wvtt"', 'codecs="zzzz"')
with pytest.raises(ValueError, match="No DASH Representation has a supported codec: 7 skipped"):
DASH.from_text(mpd, url="https://cdn.example/manifest.mpd").to_tracks(language="en")
def test_hls_with_no_supported_codec_raises() -> None:
master = '#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=4000000,CODECS="zzzz"\nbad.m3u8\n'
with pytest.raises(ValueError, match="No HLS variant has a supported codec: 1 skipped"):
HLS.from_text(master, url="https://cdn.example/master.m3u8").to_tracks(Language.get("en"))
+23 -9
View File
@@ -300,6 +300,12 @@ class DASH:
All Track URLs will be a list of segment URLs. All Track URLs will be a list of segment URLs.
""" """
tracks = Tracks() tracks = Tracks()
skipped = 0
codec_types: dict[str, type[Video] | type[Audio] | type[Subtitle]] = {
"video": Video,
"audio": Audio,
"text": Subtitle,
}
filtered_period_ids: list[str] = [] filtered_period_ids: list[str] = []
@@ -340,29 +346,36 @@ class DASH:
if content_type == "application" and mime_type and "/mp4" not in mime_type: if content_type == "application" and mime_type and "/mp4" not in mime_type:
content_type = "text" content_type = "text"
try:
if mime_type == "application/mp4" or content_type == "application": if mime_type == "application/mp4" or content_type == "application":
# likely mp4-boxed subtitles # likely mp4-boxed subtitles
# TODO: It may not actually be subtitles # TODO: It may not actually be subtitles
try:
real_codec = Subtitle.Codec.from_mime(codecs or "") real_codec = Subtitle.Codec.from_mime(codecs or "")
content_type = "text" content_type = "text"
mime_type = f"application/mp4; codecs='{real_codec.value.lower()}'" mime_type = f"application/mp4; codecs='{real_codec.value.lower()}'"
except ValueError:
raise ValueError(
f"Unsupported content type '{content_type}' with codecs of '{codecs}'"
) from None
if content_type == "text" and mime_type and "/mp4" not in mime_type: if content_type == "text" and mime_type and "/mp4" not in mime_type:
# mimeType likely specifies the subtitle codec better than `codecs` # mimeType likely specifies the subtitle codec better than `codecs`
codecs = mime_type.split("/")[1] codecs = mime_type.split("/")[1]
codec_type = codec_types.get(content_type or "")
track_codec: Any = (
codec_type.Codec.from_codecs(codecs or ("vtt" if codec_type is Subtitle else ""))
if codec_type
else None
)
except ValueError:
logging.getLogger("DASH").warning(
f"Skipped DASH Representation '{rep.get('id')}': unsupported codec '{codecs or ''}'"
)
skipped += 1
continue
video_args: dict[str, Any] = {} video_args: dict[str, Any] = {}
track_type: type[Video] | type[Audio] | type[Subtitle] track_type: type[Video] | type[Audio] | type[Subtitle]
track_codec: Any # always the Codec of track_type, a pairing mypy cannot express
track_args: dict[str, Any] track_args: dict[str, Any]
if content_type == "video": if content_type == "video":
track_type = Video track_type = Video
track_codec = Video.Codec.from_codecs(codecs or "")
track_fps = get("frameRate") track_fps = get("frameRate")
if not track_fps and segment_base is not None: if not track_fps and segment_base is not None:
track_fps = segment_base.get("timescale") track_fps = segment_base.get("timescale")
@@ -388,7 +401,6 @@ class DASH:
video_args["stereo"] = Video.is_stereo(codecs, get("supplementalCodecs")) video_args["stereo"] = Video.is_stereo(codecs, get("supplementalCodecs"))
elif content_type == "audio": elif content_type == "audio":
track_type = Audio track_type = Audio
track_codec = Audio.Codec.from_codecs(codecs or "")
track_args = dict( track_args = dict(
bitrate=get("bandwidth") or None, bitrate=get("bandwidth") or None,
channels=self.get_audio_channels(adaptation_set, rep), channels=self.get_audio_channels(adaptation_set, rep),
@@ -397,7 +409,6 @@ class DASH:
) )
elif content_type == "text": elif content_type == "text":
track_type = Subtitle track_type = Subtitle
track_codec = Subtitle.Codec.from_codecs(codecs or "vtt")
track_args = dict( track_args = dict(
cc=self.is_closed_caption(adaptation_set), cc=self.is_closed_caption(adaptation_set),
sdh=self.is_sdh(adaptation_set), sdh=self.is_sdh(adaptation_set),
@@ -455,6 +466,9 @@ class DASH:
break break
if skipped and not tracks:
raise ValueError(f"No DASH Representation has a supported codec: {skipped} skipped")
tracks.manifest_url = self.url tracks.manifest_url = self.url
log_event( log_event(
+15 -5
View File
@@ -227,6 +227,7 @@ class HLS:
} }
) )
tracks = Tracks() tracks = Tracks()
skipped = 0
supplemental_codecs = self.supplemental_codecs_by_uri() supplemental_codecs = self.supplemental_codecs_by_uri()
@@ -236,12 +237,22 @@ class HLS:
] ]
for playlist, video_layout in zip(self.manifest.playlists, video_layouts, strict=False): for playlist, video_layout in zip(self.manifest.playlists, video_layouts, strict=False):
video_codec: Video.Codec | None = None video_codec: Video.Codec | None = None
audio_codec: Audio.Codec | None = None
primary_track_type: type[Audio] | type[Video] primary_track_type: type[Audio] | type[Video]
try: try:
# TODO: Any better way to figure out the primary track type? # TODO: Any better way to figure out the primary track type?
if playlist.stream_info.codecs: if playlist.stream_info.codecs:
video_codec = Video.Codec.from_codecs(playlist.stream_info.codecs) video_codec = Video.Codec.from_codecs(playlist.stream_info.codecs)
except ValueError: except ValueError:
with suppress(ValueError):
audio_codec = Audio.Codec.from_codecs(playlist.stream_info.codecs)
if audio_codec is None or playlist.stream_info.resolution:
logging.getLogger("HLS").warning(
f"Skipped HLS variant '{safe_display_url(playlist.uri)}': "
f"unsupported codec '{playlist.stream_info.codecs}'"
)
skipped += 1
continue
primary_track_type = Audio primary_track_type = Audio
else: else:
primary_track_type = Video primary_track_type = Video
@@ -263,11 +274,7 @@ class HLS:
primary_track_type( primary_track_type(
id_=hex(crc32(str(playlist).encode()))[2:], id_=hex(crc32(str(playlist).encode()))[2:],
url=urljoin(playlist.base_uri, playlist.uri), url=urljoin(playlist.base_uri, playlist.uri),
codec=( codec=cast(Any, video_codec or audio_codec),
cast(Any, primary_track_type.Codec.from_codecs(playlist.stream_info.codecs))
if playlist.stream_info.codecs
else None
),
language=language, # HLS manifests do not seem to have language info language=language, # HLS manifests do not seem to have language info
is_original_lang=True, # TODO: All we can do is assume Yes is_original_lang=True, # TODO: All we can do is assume Yes
bitrate=playlist.stream_info.average_bandwidth or playlist.stream_info.bandwidth, bitrate=playlist.stream_info.average_bandwidth or playlist.stream_info.bandwidth,
@@ -373,6 +380,9 @@ class HLS:
except Exception as e: except Exception as e:
logging.getLogger("HLS").debug(f"TS probe failed for {video.url}: {e!r}") logging.getLogger("HLS").debug(f"TS probe failed for {video.url}: {e!r}")
if skipped and not tracks:
raise ValueError(f"No HLS variant has a supported codec: {skipped} skipped")
if self.url: if self.url:
tracks.manifest_url = self.url tracks.manifest_url = self.url