forked from kenzuya/unshackle
feat(tracks): add Audio bit_depth and sample_rate from manifests and carry them over remote
This commit is contained in:
@@ -410,6 +410,7 @@ class DASH:
|
||||
channels=self.get_audio_channels(adaptation_set, rep),
|
||||
joc=self.get_ddp_complexity_index(adaptation_set, rep),
|
||||
descriptive=self.is_descriptive(adaptation_set),
|
||||
sample_rate=self.get_sample_rate(get("audioSamplingRate")),
|
||||
)
|
||||
elif content_type == "text":
|
||||
track_type = Subtitle
|
||||
@@ -1507,6 +1508,12 @@ class DASH:
|
||||
for x in adaptation_set.findall("Role")
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def get_sample_rate(value: str | None) -> int | None:
|
||||
"""The audioSamplingRate in Hz; of a "min max" pair (ISO/IEC 23009-1) the max."""
|
||||
rate = (value or "").split()
|
||||
return int(rate[-1]) if rate and rate[-1].isdecimal() else None
|
||||
|
||||
@staticmethod
|
||||
def get_audio_channels(adaptation_set: Element, representation: Element | None) -> float | str | None:
|
||||
"""
|
||||
|
||||
@@ -335,6 +335,10 @@ class HLS:
|
||||
track_type: type[Audio] | type[Subtitle]
|
||||
if media.type == "AUDIO":
|
||||
track_type = Audio
|
||||
# BIT-DEPTH and SAMPLE-RATE (RFC 8216bis), which the m3u8 library keeps in extras
|
||||
resolution = {
|
||||
k: int(v) for k in ("bit_depth", "sample_rate") if str(v := media.extras.get(k, "")).isdecimal()
|
||||
}
|
||||
codec: Any = HLS.select_audio_codec(audio_codecs_by_group_id.get(media.group_id), media.uri)
|
||||
if media.channels:
|
||||
# the channel count, then /-separated coding (JOC) and usage identifiers (RFC 8216bis)
|
||||
@@ -376,6 +380,7 @@ class HLS:
|
||||
channels=media.channels,
|
||||
joc=joc,
|
||||
descriptive="public.accessibility.describes-video" in (media.characteristics or ""),
|
||||
**resolution,
|
||||
)
|
||||
if track_type is Audio
|
||||
else dict(
|
||||
|
||||
@@ -21,7 +21,7 @@ from requests import Session
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, PlayReady, Widevine
|
||||
from unshackle.core.manifests.dash import missing_language
|
||||
from unshackle.core.manifests.dash import DASH, missing_language
|
||||
from unshackle.core.manifests.ism_init import (
|
||||
build_init_segment,
|
||||
parse_codec_private_data_vui,
|
||||
@@ -369,6 +369,7 @@ class ISM:
|
||||
is_original_lang=bool(language and track_lang and str(track_lang) == str(language)),
|
||||
bitrate=ql.get("Bitrate"),
|
||||
channels=Audio.channels_from_count(ql.get("Channels")),
|
||||
sample_rate=DASH.get_sample_rate(ql.get("SamplingRate")),
|
||||
extra={"atmos": True} if (ql.get("HasAtmos") or "").lower() == "true" else None,
|
||||
descriptor=Track.Descriptor.ISM,
|
||||
drm=drm,
|
||||
|
||||
@@ -12,6 +12,7 @@ from rich.tree import Tree
|
||||
from unshackle.core.console import listing_panel
|
||||
from unshackle.core.music.extract import first_number, first_text, format_duration
|
||||
from unshackle.core.titles.music import Music, Song, release_song
|
||||
from unshackle.core.tracks.audio import Audio
|
||||
|
||||
|
||||
class MusicRenderer:
|
||||
@@ -54,6 +55,7 @@ class MusicRenderer:
|
||||
)
|
||||
)
|
||||
length = self.format_total_duration(getattr(music, "total_duration", None) or self.sum_duration(music))
|
||||
bit_depth, sample_rate = self.resolution(data, metadata)
|
||||
quality = self.quality_summary(
|
||||
first_text(
|
||||
getattr(music, "quality", None),
|
||||
@@ -63,6 +65,8 @@ class MusicRenderer:
|
||||
),
|
||||
lossless=self.as_bool(self.first_value(data.get("lossless"), metadata.get("lossless"))),
|
||||
hires=self.as_bool(self.first_value(data.get("hires"), metadata.get("hires"))),
|
||||
bit_depth=bit_depth,
|
||||
sample_rate=sample_rate,
|
||||
)
|
||||
|
||||
grid = Table.grid(padding=(0, 2))
|
||||
@@ -144,7 +148,10 @@ class MusicRenderer:
|
||||
data = song.data if isinstance(song.data, dict) else {}
|
||||
metadata = m if isinstance(m := data.get("metadata"), dict) else {}
|
||||
|
||||
quality = first_text(data.get("quality"), metadata.get("quality"), metadata.get("quality_label"))
|
||||
bit_depth, sample_rate = self.resolution(data, metadata)
|
||||
quality = first_text(
|
||||
data.get("quality"), metadata.get("quality"), metadata.get("quality_label")
|
||||
) or Audio.resolution_label(bit_depth, sample_rate)
|
||||
raw_duration = self.first_value(data.get("duration"), metadata.get("duration"))
|
||||
# an already-formatted duration ("3:45") does not parse as seconds, so show it as given
|
||||
duration = format_duration(raw_duration) or first_text(raw_duration)
|
||||
@@ -162,7 +169,7 @@ class MusicRenderer:
|
||||
badges.append(("E", "bold bright_red"))
|
||||
if self.as_bool(self.first_value(data.get("atmos"), metadata.get("atmos"))):
|
||||
badges.append(("Atmos", "magenta"))
|
||||
if self.is_hires_quality(quality):
|
||||
if self.is_hires_quality(quality, bit_depth, sample_rate):
|
||||
badges.append(("Hi-Res", "gold1"))
|
||||
|
||||
details = []
|
||||
@@ -265,19 +272,28 @@ class MusicRenderer:
|
||||
return f"{month_names[month - 1]} {day}, {year}"
|
||||
|
||||
@classmethod
|
||||
def quality_summary(cls, value: Any, *, lossless: bool = False, hires: bool = False) -> str:
|
||||
def quality_summary(
|
||||
cls,
|
||||
value: Any,
|
||||
*,
|
||||
lossless: bool = False,
|
||||
hires: bool = False,
|
||||
bit_depth: int | None = None,
|
||||
sample_rate: int | None = None,
|
||||
) -> str:
|
||||
text = str(value or "").strip()
|
||||
lowered = text.lower()
|
||||
hires = hires or cls.is_hires_quality("", bit_depth, sample_rate)
|
||||
if not text:
|
||||
if hires and lossless:
|
||||
return "Hi-Res Lossless"
|
||||
if lossless:
|
||||
return "Lossless"
|
||||
return ""
|
||||
return Audio.resolution_label(bit_depth, sample_rate)
|
||||
if "atmos" in lowered:
|
||||
return "Dolby Atmos"
|
||||
if any(codec in lowered for codec in ("flac", "alac", "wav", "aiff")):
|
||||
return "Hi-Res Lossless" if cls.is_hires_quality(text) else "Lossless"
|
||||
return "Hi-Res Lossless" if cls.is_hires_quality(text, bit_depth, sample_rate) else "Lossless"
|
||||
if "lossless" in lowered:
|
||||
return "Hi-Res Lossless" if "hi-res" in lowered or hires else "Lossless"
|
||||
if "aac" in lowered:
|
||||
@@ -287,21 +303,27 @@ class MusicRenderer:
|
||||
return text
|
||||
|
||||
@staticmethod
|
||||
def is_hires_quality(value: str) -> bool:
|
||||
"""Return True for a label above 16-bit or 48 kHz; a "k" before "b" is a bitrate ("256 kb/s"), not a rate."""
|
||||
def resolution(data: dict[str, Any], metadata: dict[str, Any]) -> tuple[int | None, int | None]:
|
||||
"""The `bit_depth` and `sample_rate` (Hz) a song's data gives, each None when absent."""
|
||||
bit_depth = int(first_number(data.get("bit_depth"), metadata.get("bit_depth")) or 0) or None
|
||||
sample_rate = int(first_number(data.get("sample_rate"), metadata.get("sample_rate")) or 0) or None
|
||||
return bit_depth, sample_rate
|
||||
|
||||
@staticmethod
|
||||
def is_hires_quality(value: str, bit_depth: int | None = None, sample_rate: int | None = None) -> bool:
|
||||
"""
|
||||
Return True above 16-bit or 48 kHz; a bit depth or sample rate that is given wins over the label.
|
||||
|
||||
In a label a "k" before "b" is a bitrate ("256 kb/s"), not a rate.
|
||||
"""
|
||||
lowered = value.lower()
|
||||
bit_depth = None
|
||||
sample_rate = None
|
||||
|
||||
bit_match = re.search(r"(?P<bits>\d+)\s*[- ]?bit", lowered)
|
||||
if bit_match:
|
||||
if bit_match and not bit_depth:
|
||||
bit_depth = int(bit_match.group("bits"))
|
||||
|
||||
sample_match = re.search(r"(?P<rate>\d+(?:\.\d+)?)\s*k(?!b)(?:hz)?", lowered)
|
||||
if sample_match:
|
||||
sample_rate = float(sample_match.group("rate"))
|
||||
|
||||
return bool((bit_depth and bit_depth > 16) or (sample_rate and sample_rate > 48))
|
||||
if sample_match and not sample_rate:
|
||||
sample_rate = int(float(sample_match.group("rate")) * 1000)
|
||||
return (bit_depth or 0) > 16 or (sample_rate or 0) > 48000
|
||||
|
||||
@staticmethod
|
||||
def sum_duration(music: Music) -> int:
|
||||
|
||||
@@ -56,6 +56,8 @@ MUSIC_DATA_KEYS = (
|
||||
"quality_label",
|
||||
"lossless",
|
||||
"hires",
|
||||
"bit_depth",
|
||||
"sample_rate",
|
||||
"atmos",
|
||||
"duration",
|
||||
"released_at",
|
||||
|
||||
@@ -136,6 +136,8 @@ class Audio(Track):
|
||||
channels: str | int | float | None = None,
|
||||
joc: int | None = None,
|
||||
descriptive: bool | int = False,
|
||||
bit_depth: int | None = None,
|
||||
sample_rate: int | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -151,6 +153,8 @@ class Audio(Track):
|
||||
not supported. All numbers and strings will be cast to float.
|
||||
joc: The number of Joint-Object-Coding Channels/Objects in the audio track.
|
||||
descriptive: Mark this audio as being descriptive audio for the blind.
|
||||
bit_depth: Bits per sample, e.g. 24. A manifest rarely states it, so a service sets it.
|
||||
sample_rate: Samples per second in Hz, e.g. 96000.
|
||||
|
||||
Note: If codec, bitrate, channels, or joc is not specified some checks may be
|
||||
skipped or assume a value. Specifying as much information as possible is highly
|
||||
@@ -166,6 +170,10 @@ class Audio(Track):
|
||||
raise TypeError(f"Expected channels to be a {str}, {int}, or {float}, not {channels!r}")
|
||||
if not isinstance(joc, (int, type(None))):
|
||||
raise TypeError(f"Expected joc to be a {int}, not {joc!r}")
|
||||
if not isinstance(bit_depth, (int, type(None))):
|
||||
raise TypeError(f"Expected bit_depth to be a {int}, not {bit_depth!r}")
|
||||
if not isinstance(sample_rate, (int, type(None))):
|
||||
raise TypeError(f"Expected sample_rate to be a {int}, not {sample_rate!r}")
|
||||
if not isinstance(descriptive, (bool, int)) or (isinstance(descriptive, int) and descriptive not in (0, 1)):
|
||||
raise TypeError(f"Expected descriptive to be a {bool} or bool-like {int}, not {descriptive!r}")
|
||||
|
||||
@@ -183,6 +191,8 @@ class Audio(Track):
|
||||
|
||||
self.joc = joc
|
||||
self.descriptive = bool(descriptive)
|
||||
self.bit_depth = bit_depth or None
|
||||
self.sample_rate = sample_rate or None
|
||||
|
||||
@property
|
||||
def atmos(self) -> bool:
|
||||
@@ -212,6 +222,7 @@ class Audio(Track):
|
||||
)
|
||||
),
|
||||
f"{self.bitrate // 1000} kb/s" if self.bitrate else None,
|
||||
self.resolution_label(self.bit_depth, self.sample_rate),
|
||||
self.get_track_name(),
|
||||
", ".join(self.edition) if self.edition else None,
|
||||
self.note,
|
||||
@@ -219,6 +230,12 @@ class Audio(Track):
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def resolution_label(bit_depth: int | None, sample_rate: int | None) -> str:
|
||||
"""The bit depth and sample rate in the form music services show, e.g. "24-bit / 96 kHz"; "" for neither."""
|
||||
parts = [f"{bit_depth}-bit" if bit_depth else "", f"{sample_rate / 1000:g} kHz" if sample_rate else ""]
|
||||
return " / ".join(filter(None, parts))
|
||||
|
||||
@staticmethod
|
||||
def parse_channels(channels: str | int | float) -> float | str:
|
||||
"""
|
||||
|
||||
@@ -418,6 +418,8 @@ class Tracks:
|
||||
track.joc,
|
||||
track.descriptive,
|
||||
track.bitrate,
|
||||
track.bit_depth,
|
||||
track.sample_rate,
|
||||
track.name,
|
||||
)
|
||||
return type(track), str(track.language), track.codec, track.forced, track.sdh, track.cc, track.name
|
||||
|
||||
@@ -732,6 +732,8 @@ def serialize_audio_track(track: Audio, include_url: bool = False, is_original:
|
||||
"atmos": track.atmos if hasattr(track, "atmos") else False,
|
||||
"joc": getattr(track, "joc", 0),
|
||||
"descriptive": track.descriptive if hasattr(track, "descriptive") else False,
|
||||
"bit_depth": track.bit_depth,
|
||||
"sample_rate": track.sample_rate,
|
||||
}
|
||||
result.update(serialize_track_common(track))
|
||||
if include_url:
|
||||
@@ -831,6 +833,8 @@ def deserialize_audio(data: dict[str, Any]) -> Audio:
|
||||
joc=joc,
|
||||
extra={"atmos": True} if joc is None and data.get("atmos") else None,
|
||||
descriptive=data.get("descriptive", False),
|
||||
bit_depth=data.get("bit_depth"),
|
||||
sample_rate=data.get("sample_rate"),
|
||||
)
|
||||
|
||||
|
||||
@@ -916,6 +920,8 @@ def track_to_dict(track: Track) -> dict[str, Any]:
|
||||
"channels": track.channels,
|
||||
"joc": track.joc,
|
||||
"descriptive": track.descriptive,
|
||||
"bit_depth": track.bit_depth,
|
||||
"sample_rate": track.sample_rate,
|
||||
}
|
||||
)
|
||||
elif isinstance(track, Subtitle):
|
||||
@@ -964,6 +970,8 @@ def track_from_dict(data: dict[str, Any]) -> Video | Audio | Subtitle:
|
||||
channels=data.get("channels"),
|
||||
joc=data.get("joc"),
|
||||
descriptive=data.get("descriptive", False),
|
||||
bit_depth=data.get("bit_depth"),
|
||||
sample_rate=data.get("sample_rate"),
|
||||
)
|
||||
return Subtitle(
|
||||
**export_track_kwargs(data),
|
||||
|
||||
@@ -341,10 +341,12 @@ class MUSIC_EXAMPLE(Service):
|
||||
# each track, plus `unavailable_reason` for a "Skipped:" line in place of it.
|
||||
# The tagger takes `release_date`, `composer`, `service` and the id/url pairs.
|
||||
data={
|
||||
# Audio has no bit_depth or sample_rate field, so the human-readable
|
||||
# quality string lives here. The renderer parses "24-bit"/"96 kHz" out
|
||||
# of it to decide the Hi-Res badge, and it becomes the COMMENT tag.
|
||||
# The human-readable quality string; it becomes the COMMENT tag.
|
||||
"quality": first_text(track.get("qualityLabel")),
|
||||
# Bits per sample and Hz. The renderer decides the Hi-Res badge from
|
||||
# these, and shows "24-bit / 96 kHz" when `quality` is empty.
|
||||
"bit_depth": track.get("bitDepth"),
|
||||
"sample_rate": track.get("sampleRate"),
|
||||
# `duration_seconds` reads seconds or milliseconds, because an API that
|
||||
# calls the field `durationMs` is as common as one that does not.
|
||||
"duration": duration_seconds(track.get("durationMs")),
|
||||
@@ -383,8 +385,8 @@ class MUSIC_EXAMPLE(Service):
|
||||
This is the whole music contract. Do not pick the best format here: hand the
|
||||
framework every option the account can fetch and let its normal audio
|
||||
selection (-a/--acodec, --abitrate, sort_audio, select_best_audio) choose.
|
||||
Since Audio has no bit_depth or sample_rate, `bitrate` is what separates a
|
||||
24-bit FLAC from a 16-bit FLAC, and it is what sort_audio ranks them by.
|
||||
`bitrate` is what sort_audio ranks two FLAC options by; `bit_depth` and
|
||||
`sample_rate` tell the user which is the 24-bit one.
|
||||
|
||||
MIGRATING FROM THE OLD MODEL: a music service used to return exactly one Audio
|
||||
track and do its own quality fallback inside an overridden Audio.download().
|
||||
@@ -427,10 +429,10 @@ class MUSIC_EXAMPLE(Service):
|
||||
# constant-bitrate AAC; use `--abitrate-range` for a FLAC.
|
||||
bitrate=stream["bitrate"],
|
||||
channels=stream.get("channels", 2),
|
||||
# `name` is the human-readable quality label. Audio has no
|
||||
# bit_depth or sample_rate, so this is the only place a user reads
|
||||
# "24-bit / 96 kHz" in the Available Tracks listing.
|
||||
name=first_text(stream.get("qualityLabel")) or None,
|
||||
# Bits per sample and Hz, as ints. The Available Tracks listing shows them as
|
||||
# "24-bit / 96 kHz", so do not write that into `name` as well.
|
||||
bit_depth=stream.get("bitDepth"),
|
||||
sample_rate=stream.get("sampleRate"),
|
||||
# A Track must have a language even where the catalogue gives none.
|
||||
# build_song falls back to the BCP-47 "undetermined" tag for that
|
||||
# reason, so mirror it here rather than guessing at English; a
|
||||
|
||||
Reference in New Issue
Block a user