style: turn on ruff UP and B rules and fix every finding

This commit is contained in:
imSp4rky
2026-11-25 16:34:09 -07:00
parent 1a63076df2
commit d8058a3610
264 changed files with 2950 additions and 2966 deletions
+172 -177
View File
@@ -9,11 +9,12 @@ import re
import shutil
import subprocess
import time
from collections.abc import Callable
from contextlib import suppress
from functools import partial
from itertools import accumulate
from pathlib import Path
from typing import Any, BinaryIO, Callable, Optional, Union, cast
from typing import Any, BinaryIO, cast
from urllib.parse import urljoin, urlparse
from uuid import UUID
from zlib import crc32
@@ -61,9 +62,9 @@ class HLS:
def __init__(
self,
manifest: M3U8,
session: Optional[Union[Session, RnetSession]] = None,
url: Optional[str] = None,
raw_text: Optional[str] = None,
session: Session | RnetSession | None = None,
url: str | None = None,
raw_text: str | None = None,
) -> None:
if not manifest:
raise ValueError("HLS manifest must be provided.")
@@ -78,7 +79,7 @@ class HLS:
self.raw_text = raw_text
@classmethod
def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS:
def from_url(cls, url: str, session: Session | RnetSession | None = None, **args: Any) -> HLS:
if not url:
raise requests.URLRequired("HLS manifest URL must be provided.")
if not isinstance(url, str):
@@ -149,9 +150,7 @@ class HLS:
return out
@staticmethod
def select_audio_codec(
candidates: Optional[list[tuple[str, Audio.Codec]]], uri: Optional[str]
) -> Optional[Audio.Codec]:
def select_audio_codec(candidates: list[tuple[str, Audio.Codec]] | None, uri: str | None) -> Audio.Codec | None:
"""
Choose the Audio Codec of one rendition from the codecs its variant declares.
@@ -184,7 +183,7 @@ class HLS:
)
return candidates[0][1]
def to_tracks(self, language: Optional[Union[str, Language]]) -> Tracks:
def to_tracks(self, language: str | Language | None) -> Tracks:
"""
Convert a Variant Playlist M3U(8) document to Video, Audio and Subtitle Track objects.
@@ -236,8 +235,8 @@ class HLS:
(raw.get("stream_info") or {}).get("req_video_layout")
for raw in (getattr(self.manifest, "data", None) or {}).get("playlists", [])
]
for playlist, video_layout in zip(self.manifest.playlists, video_layouts):
video_codec: Optional[Video.Codec] = None
for playlist, video_layout in zip(self.manifest.playlists, video_layouts, strict=False):
video_codec: Video.Codec | None = None
primary_track_type: type[Audio] | type[Video]
try:
# TODO: Any better way to figure out the primary track type?
@@ -397,8 +396,8 @@ class HLS:
@staticmethod
def probe_ts_info(
variant_url: str, session: Optional[Union[Session, RnetSession]] = None
) -> Optional[tuple[int, int, Video.Codec]]:
variant_url: str, session: Session | RnetSession | None = None
) -> tuple[int, int, Video.Codec] | None:
"""Probe the first TS segment of a variant playlist to extract resolution and codec."""
if not session:
session = run_proxy.fallback_session()
@@ -417,7 +416,7 @@ class HLS:
return HLS.parse_ts_video_info(data)
@staticmethod
def parse_ts_video_info(data: bytes) -> Optional[tuple[int, int, Video.Codec]]:
def parse_ts_video_info(data: bytes) -> tuple[int, int, Video.Codec] | None:
"""Parse H.264/H.265 NAL units from TS segment data to extract resolution and codec."""
class _BitReader:
@@ -572,10 +571,10 @@ class HLS:
@staticmethod
def resolve_segment_key(
segment_keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
segment_keys: list[m3u8.model.SessionKey | m3u8.model.Key],
cdm: object,
drm_preference: Optional[str] = None,
) -> Optional[m3u8.Key]:
drm_preference: str | None = None,
) -> m3u8.Key | None:
"""Pick the EXT-X-KEY for a segment, preferring one the CDM can handle."""
if cdm:
cdm_segment_keys = HLS.filter_keys_for_cdm(segment_keys, cdm, drm_preference)
@@ -585,7 +584,7 @@ class HLS:
@staticmethod
def fetch_init_section(
session: Union[Session, RnetSession],
session: Session | RnetSession,
init_section: m3u8.model.InitializationSection,
range_offset: int,
) -> tuple[bytes, int]:
@@ -610,9 +609,9 @@ class HLS:
@staticmethod
def single_init_no_rotation(
wanted_segments: list[Any],
initial_key: Optional[m3u8.Key],
initial_key: m3u8.Key | None,
cdm: object,
drm_preference: Optional[str] = None,
drm_preference: str | None = None,
) -> bool:
"""Whether every wanted segment shares one init segment and one EXT-X-KEY, with no discontinuity.
@@ -826,8 +825,8 @@ class HLS:
},
)
map_data: Optional[tuple[m3u8.model.InitializationSection, bytes]] = None
segment_decrypter: Optional[SegmentDecrypter] = None
map_data: tuple[m3u8.model.InitializationSection, bytes] | None = None
segment_decrypter: SegmentDecrypter | None = None
if use_segment_decrypt or use_rolling_merge:
init_section = wanted_segments[0].init_section
init_content, _ = HLS.fetch_init_section(session, init_section, 0)
@@ -844,7 +843,7 @@ class HLS:
"HLS",
urls,
segment_save_dir,
"{i:0%d}{ext}" % len(str(len(urls))),
f"{{i:0{len(str(len(urls)))}}}{{ext}}",
rolling=use_rolling_merge,
init=map_data[1] if map_data else None,
decrypter=segment_decrypter,
@@ -887,10 +886,140 @@ class HLS:
# First segment's Media Sequence Number - used as the AES-128 IV when EXT-X-KEY has
# no explicit IV (RFC 8216 §5.2), where each segment's IV is its sequence number.
media_sequence_start = getattr(master, "media_sequence", None) or 0
encryption_data: Optional[tuple[Optional[m3u8.Key], DRM_T]] = None
encryption_data: tuple[m3u8.Key | None, DRM_T] | None = None
if session_drm:
encryption_data = (initial_drm_key, session_drm)
def merge(to: Path, via: list[Path], delete: bool = False, include_map_data: bool = False) -> None:
"""
Merge all files to a given path, optionally including map data.
Parameters:
to: The output file with all merged data.
via: List of files to merge, in sequence.
delete: Delete each source file after this function merges it.
include_map_data: Whether to include the init map data.
"""
prepend = include_map_data and map_data and map_data[1]
if len(via) == 1 and not prepend and delete:
try:
os.replace(via[0], to)
return
except OSError:
pass
with open(to, "wb") as x:
if prepend:
assert map_data is not None
x.write(map_data[1])
for file in via:
with open(file, "rb") as segment:
shutil.copyfileobj(segment, x, 1024 * 1024)
x.flush()
if delete:
file.unlink()
def decrypt(include_this_segment: bool) -> Path | None:
"""
Decrypt all segments that uses the currently set DRM.
This function merges every segment of this DRM together in sequence, adds
the init data (if any) at the start, and then deletes the segment files. It
then decrypts the merged file. The merged and decrypted file names state the
range of segments the file holds.
Parameters:
include_this_segment: Whether to include the current segment in the
list of segments to merge and decrypt. This should be False if
decrypting on EXT-X-KEY changes, or True when decrypting on the
last segment.
Returns the decrypted path.
"""
nonlocal map_data
assert encryption_data is not None
drm = encryption_data[1]
first_segment_i = next(
(int(file.stem) for file in sorted(segment_save_dir.iterdir()) if file.stem.isdigit()), None
)
last_segment_i = max(0, i - int(not include_this_segment))
if first_segment_i is None or first_segment_i > last_segment_i:
return None
range_len = (last_segment_i - first_segment_i) + 1
segment_range = f"{str(first_segment_i).zfill(name_len)}-{str(last_segment_i).zfill(name_len)}"
ext = get_extension(wanted_segments[last_segment_i].uri) or ""
merged_path = segment_save_dir / f"{segment_range}{ext}"
decrypted_path = segment_save_dir / f"{merged_path.stem}_decrypted{merged_path.suffix}"
files = [
file
for file in sorted(segment_save_dir.iterdir())
if file.stem.isdigit() and first_segment_i <= int(file.stem) <= last_segment_i
]
if not files:
raise ValueError(f"None of the segment files for {segment_range} exist...")
elif len(files) != range_len:
raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
if isinstance(drm, (Widevine, PlayReady)):
if segment_decrypter:
if not map_data:
raise ValueError("Segment decryption needs an EXT-X-MAP init segment.")
assert decrypted_init is not None
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)
merged_path.rename(decrypted_path)
else:
# AES segments must be decrypted individually before merging: each segment
# likely carries its own 16-byte padding
key_obj = encryption_data[0]
# AES-128 with no explicit IV: each segment's IV is its media sequence
# number (RFC 8216 §5.2). Without this the engine used a zero IV and the
# output decrypted to garbage.
seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
for file in files:
if seq_iv and isinstance(drm, ClearKey) and file.stem.isdigit():
download_i = int(file.stem)
seq = getattr(wanted_segments[download_i], "media_sequence", None)
if seq is None:
seq = media_sequence_start + download_i
drm.iv = int(seq).to_bytes(16, "big")
drm.decrypt(file)
merge(to=merged_path, via=files, delete=True, include_map_data=True)
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=decrypted_path)
return decrypted_path
def merge_discontinuity(include_this_segment: bool, include_map_data: bool = True) -> None:
"""
Merge all segments of the discontinuity.
The caller must download every segment file of this discontinuity first.
The caller must also decrypt them, when they need decryption.
Parameters:
include_this_segment: Whether to include the current segment in the
list of segments to merge and decrypt. This should be False if
decrypting on EXT-X-KEY changes, or True when decrypting on the
last segment.
include_map_data: Whether to prepend the init map data before the
segment files when merging.
"""
last_segment_i = max(0, i - int(not include_this_segment))
files = [
file
for file in sorted(segment_save_dir.iterdir())
if int(file.stem.replace("_decrypted", "").split("-")[-1]) <= last_segment_i
]
if files:
to_dir = segment_save_dir.parent
to_path = to_dir / f"{str(discon_i).zfill(name_len)}{files[-1].suffix}"
merge(to=to_path, via=files, delete=True, include_map_data=include_map_data)
i = -1
for real_i, segment in enumerate(master.segments):
if segment not in unwanted_segments:
@@ -898,136 +1027,6 @@ class HLS:
is_last_segment = (real_i + 1) == len(master.segments)
def merge(to: Path, via: list[Path], delete: bool = False, include_map_data: bool = False) -> None:
"""
Merge all files to a given path, optionally including map data.
Parameters:
to: The output file with all merged data.
via: List of files to merge, in sequence.
delete: Delete each source file after this function merges it.
include_map_data: Whether to include the init map data.
"""
prepend = include_map_data and map_data and map_data[1]
if len(via) == 1 and not prepend and delete:
try:
os.replace(via[0], to)
return
except OSError:
pass
with open(to, "wb") as x:
if prepend:
assert map_data is not None
x.write(map_data[1])
for file in via:
with open(file, "rb") as segment:
shutil.copyfileobj(segment, x, 1024 * 1024)
x.flush()
if delete:
file.unlink()
def decrypt(include_this_segment: bool) -> Optional[Path]:
"""
Decrypt all segments that uses the currently set DRM.
This function merges every segment of this DRM together in sequence, adds
the init data (if any) at the start, and then deletes the segment files. It
then decrypts the merged file. The merged and decrypted file names state the
range of segments the file holds.
Parameters:
include_this_segment: Whether to include the current segment in the
list of segments to merge and decrypt. This should be False if
decrypting on EXT-X-KEY changes, or True when decrypting on the
last segment.
Returns the decrypted path.
"""
nonlocal map_data
assert encryption_data is not None
drm = encryption_data[1]
first_segment_i = next(
(int(file.stem) for file in sorted(segment_save_dir.iterdir()) if file.stem.isdigit()), None
)
last_segment_i = max(0, i - int(not include_this_segment))
if first_segment_i is None or first_segment_i > last_segment_i:
return None
range_len = (last_segment_i - first_segment_i) + 1
segment_range = f"{str(first_segment_i).zfill(name_len)}-{str(last_segment_i).zfill(name_len)}"
ext = get_extension(wanted_segments[last_segment_i].uri) or ""
merged_path = segment_save_dir / f"{segment_range}{ext}"
decrypted_path = segment_save_dir / f"{merged_path.stem}_decrypted{merged_path.suffix}"
files = [
file
for file in sorted(segment_save_dir.iterdir())
if file.stem.isdigit() and first_segment_i <= int(file.stem) <= last_segment_i
]
if not files:
raise ValueError(f"None of the segment files for {segment_range} exist...")
elif len(files) != range_len:
raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
if isinstance(drm, (Widevine, PlayReady)):
if segment_decrypter:
if not map_data:
raise ValueError("Segment decryption needs an EXT-X-MAP init segment.")
assert decrypted_init is not None
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)
merged_path.rename(decrypted_path)
else:
# AES segments must be decrypted individually before merging: each segment
# likely carries its own 16-byte padding
key_obj = encryption_data[0]
# AES-128 with no explicit IV: each segment's IV is its media sequence
# number (RFC 8216 §5.2). Without this the engine used a zero IV and the
# output decrypted to garbage.
seq_iv = isinstance(drm, ClearKey) and not (key_obj and key_obj.iv)
for file in files:
if seq_iv and isinstance(drm, ClearKey) and file.stem.isdigit():
download_i = int(file.stem)
seq = getattr(wanted_segments[download_i], "media_sequence", None)
if seq is None:
seq = media_sequence_start + download_i
drm.iv = int(seq).to_bytes(16, "big")
drm.decrypt(file)
merge(to=merged_path, via=files, delete=True, include_map_data=True)
events.emit(events.Types.TRACK_DECRYPTED, track=track, drm=drm, segment=decrypted_path)
return decrypted_path
def merge_discontinuity(include_this_segment: bool, include_map_data: bool = True) -> None:
"""
Merge all segments of the discontinuity.
The caller must download every segment file of this discontinuity first.
The caller must also decrypt them, when they need decryption.
Parameters:
include_this_segment: Whether to include the current segment in the
list of segments to merge and decrypt. This should be False if
decrypting on EXT-X-KEY changes, or True when decrypting on the
last segment.
include_map_data: Whether to prepend the init map data before the
segment files when merging.
"""
last_segment_i = max(0, i - int(not include_this_segment))
files = [
file
for file in sorted(segment_save_dir.iterdir())
if int(file.stem.replace("_decrypted", "").split("-")[-1]) <= last_segment_i
]
if files:
to_dir = segment_save_dir.parent
to_path = to_dir / f"{str(discon_i).zfill(name_len)}{files[-1].suffix}"
merge(to=to_path, via=files, delete=True, include_map_data=include_map_data)
if segment not in unwanted_segments:
if isinstance(track, Subtitle):
segment_file_ext = get_extension(segment.uri) or ""
@@ -1195,7 +1194,7 @@ class HLS:
return plain
@staticmethod
def merge_segments(segments: list[Path], save_path: Path, progress: Optional[Any] = None) -> int:
def merge_segments(segments: list[Path], save_path: Path, progress: Any | None = None) -> int:
"""
Concatenate Segments using FFmpeg concat with binary fallback.
@@ -1301,9 +1300,7 @@ class HLS:
return save_path.stat().st_size
@staticmethod
def parse_session_data_keys(
manifest: M3U8, session: Optional[Union[Session, RnetSession]] = None
) -> list[m3u8.model.Key]:
def parse_session_data_keys(manifest: M3U8, session: Session | RnetSession | None = None) -> list[m3u8.model.Key]:
"""Parse the `com.apple.hls.keys` `EXT-X-SESSION-DATA` entry into `Key` objects."""
keys: list[m3u8.model.Key] = []
@@ -1355,10 +1352,10 @@ class HLS:
@staticmethod
def filter_keys_for_cdm(
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
keys: list[m3u8.model.SessionKey | m3u8.model.Key],
cdm: object,
drm_preference: Optional[str] = None,
) -> list[Union[m3u8.model.SessionKey, m3u8.model.Key]]:
drm_preference: str | None = None,
) -> list[m3u8.model.SessionKey | m3u8.model.Key]:
"""
Filter EXT-X-KEY entries to only include those matching the CDM type.
@@ -1389,10 +1386,10 @@ class HLS:
@staticmethod
def alternate_drm(
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]],
keys: list[m3u8.model.SessionKey | m3u8.model.Key],
chosen: DRM_T,
session: Optional[Union[Session, RnetSession]] = None,
kid: Optional[UUID] = None,
session: Session | RnetSession | None = None,
kid: UUID | None = None,
) -> list[DRM_T]:
"""Build the Widevine or PlayReady DRM that the EXT-X-KEY entries offer next to ``chosen``.
@@ -1412,9 +1409,9 @@ class HLS:
def get_track_kid_from_init(
master: M3U8,
track: AnyTrack,
session: Union[Session, RnetSession],
init_section: Optional[m3u8.model.InitializationSection] = None,
) -> Optional[UUID]:
session: Session | RnetSession,
init_section: m3u8.model.InitializationSection | None = None,
) -> UUID | None:
"""
Extract the track's Key ID from an init segment (EXT-X-MAP), by default the first in the playlist.
@@ -1445,7 +1442,7 @@ class HLS:
return None
@staticmethod
def get_supported_key(keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]]) -> Optional[m3u8.Key]:
def get_supported_key(keys: list[m3u8.model.SessionKey | m3u8.model.Key]) -> m3u8.Key | None:
"""
Get the first DRM system unshackle can use from the given `EXT-X-KEY` entries.
@@ -1484,9 +1481,9 @@ class HLS:
@staticmethod
def get_drm(
key: Union[m3u8.model.SessionKey, m3u8.model.Key],
session: Optional[Union[Session, RnetSession]] = None,
kid: Optional[UUID] = None,
key: m3u8.model.SessionKey | m3u8.model.Key,
session: Session | RnetSession | None = None,
kid: UUID | None = None,
) -> DRM_T:
"""
Convert HLS EXT-X-KEY data to an initialized DRM object.
@@ -1534,11 +1531,11 @@ class HLS:
@staticmethod
def get_drm_or_probe(
key: Union[m3u8.model.SessionKey, m3u8.model.Key],
key: m3u8.model.SessionKey | m3u8.model.Key,
master: M3U8,
track: AnyTrack,
session: Optional[Union[Session, RnetSession]] = None,
init_section: Optional[m3u8.model.InitializationSection] = None,
session: Session | RnetSession | None = None,
init_section: m3u8.model.InitializationSection | None = None,
probe_session: Any = None,
) -> DRM_T:
"""
@@ -1557,9 +1554,7 @@ class HLS:
return HLS.get_drm(key, session, kid=kid)
@staticmethod
def get_all_drm(
keys: list[Union[m3u8.model.SessionKey, m3u8.model.Key]], proxy: Optional[str] = None
) -> list[DRM_T]:
def get_all_drm(keys: list[m3u8.model.SessionKey | m3u8.model.Key], proxy: str | None = None) -> list[DRM_T]:
"""
Convert HLS EXT-X-KEY data to initialized DRM objects.