diff --git a/docs/dev/rest-api/endpoints.md b/docs/dev/rest-api/endpoints.md index 99607d89..a3676f8b 100644 --- a/docs/dev/rest-api/endpoints.md +++ b/docs/dev/rest-api/endpoints.md @@ -351,7 +351,7 @@ When you give both `season` and `episode`, the server combines them into a `"{se "id": "a-1", "codec": "EC3", "codec_display": "DDP", "bitrate": 640, "bitrate_bps": 640000, "channels": "5.1", "language": "en", "is_original": true, "is_original_lang": true, "atmos": false, "joc": 0, - "descriptive": false, "name": null, "track_name": "English", "needs_repack": false, "edition": [], + "descriptive": false, "bit_depth": null, "sample_rate": 48000, "name": null, "track_name": "English", "needs_repack": false, "edition": [], "note": null, "data": null, "drm": [], "descriptor": "DASH" } ], @@ -386,7 +386,7 @@ The server sorts tracks by bitrate, descending. Episodes the server cannot get g The `drm` array on a track is a list of `{type, pssh?, kids?, content_keys?, license_url?}` objects. -Every track carries the same fields as a local track: `is_original_lang`, `name`, `needs_repack`, `edition`, `note`, and `data`. `name` is the name the service set, or null. `note` is display text the service set, such as an encoding profile, or null: `--list` shows it, but the filename and the mux do not use it. `track_name` is the name `--list` shows and the mux writes to an audio or subtitle track: `name` when the service set one, else the name of the language (English, or in the language itself when the server sets `muxing.track_names: native`, or no name when it sets `none`), then the server's `muxing.original_label` on an original-language track, then the SDH, CC, Forced or Descriptive label. `bitrate` is in kb/s, and `bitrate_bps` gives the exact bits/s. `data` holds the part of the service-set `track.data` that fits in JSON, without the `hls`, `dash`, and `ism` parser keys. Audio keeps `is_original` and `atmos` for clients that read them, and adds the exact `joc` object count. +Every track carries the same fields as a local track: `is_original_lang`, `name`, `needs_repack`, `edition`, `note`, and `data`. `name` is the name the service set, or null. `note` is display text the service set, such as an encoding profile, or null: `--list` shows it, but the filename and the mux do not use it. `track_name` is the name `--list` shows and the mux writes to an audio or subtitle track: `name` when the service set one, else the name of the language (English, or in the language itself when the server sets `muxing.track_names: native`, or no name when it sets `none`), then the server's `muxing.original_label` on an original-language track, then the SDH, CC, Forced or Descriptive label. `bitrate` is in kb/s, and `bitrate_bps` gives the exact bits/s. `data` holds the part of the service-set `track.data` that fits in JSON, without the `hls`, `dash`, and `ism` parser keys. Audio keeps `is_original` and `atmos` for clients that read them, and adds the exact `joc` object count. Audio `bit_depth` and `sample_rate` (Hz) are integers, or null when the manifest and the service do not give them. | Status | Error code | Meaning | | --- | --- | --- | diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index d117003d..f7589c06 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -228,8 +228,10 @@ Each subclass adds its own required fields on top of `id_` and `service`: bitrate it offers for a `Song`**. The framework then selects one with its usual audio options, `-a`/`--acodec` and `--abitrate`, and its usual audio sorting. A movie or an episode uses the same options. `-q`/`--quality` sets the video height only and does not - apply to music. `Audio` has no `bit_depth` or `sample_rate` field. Therefore `bitrate` - separates a hi-res FLAC from a CD FLAC, and the audio sort already ranks it. + apply to music. The audio sort ranks a hi-res FLAC above a CD FLAC by `bitrate`. Set + `bit_depth` and `sample_rate` (Hz) on each `Audio` track, and `--list` shows them as + "24-bit / 96 kHz", so do not write that text into `name`. The same two keys in + `Song.data` give the Hi-Res badge in the release listing. A `Song` is an ordinary `Title` on the one generic download path. unshackle has no music-specific service API and no separate music download loop. The @@ -326,7 +328,9 @@ The value also goes to a `--remote` client. A track without it muxes everything ### `Audio` `Audio` adds `bitrate`, `channels`, `joc` (Joint Object Coding, the Atmos indicator), -and `descriptive`. `Audio.Codec` covers `AAC`, `AC3` (`DD`), `EC3` (`DD+`), `AC4`, +`descriptive`, `bit_depth` and `sample_rate` (Hz). DASH sets `sample_rate` from +`audioSamplingRate`, ISM from `SamplingRate`, and HLS sets both from the `BIT-DEPTH` and +`SAMPLE-RATE` attributes when the playlist has them. A service sets `bit_depth` itself. `Audio.Codec` covers `AAC`, `AC3` (`DD`), `EC3` (`DD+`), `AC4`, `OPUS`, `OGG` (Vorbis), `DTS`, `DTSX`, `DTSHD`, `MPEGH`, `AV3A` (Audio Vivid), `ALAC`, `FLAC`, and `MP3`. The `atmos` property is `True` when `joc` is set (or when `extra` flags it). diff --git a/docs/guide/downloading.md b/docs/guide/downloading.md index d02aef52..9e61f8b6 100644 --- a/docs/guide/downloading.md +++ b/docs/guide/downloading.md @@ -377,7 +377,8 @@ unshackle dl -a AAC -ab 320 EXAMPLE 81234567 !!! tip "Two FLAC tracks in one release" A service can offer both a CD FLAC and a hi-res FLAC. The two have the same codec, so the bitrate is what separates them. Use `--list` to read the bitrates, then give `-ab` - the one you want. + the one you want. When the service gives them, `--list` also shows the bit depth and + sample rate, such as "24-bit / 96 kHz". ## Languages diff --git a/tests/core/test_audio_resolution.py b/tests/core/test_audio_resolution.py new file mode 100644 index 00000000..fec34ef8 --- /dev/null +++ b/tests/core/test_audio_resolution.py @@ -0,0 +1,130 @@ +"""An audio track carries its bit depth and sample rate from the manifest or the service, and shows them.""" + +from __future__ import annotations + +import pytest + +from unshackle.core.manifests.dash import DASH +from unshackle.core.manifests.hls import HLS +from unshackle.core.manifests.ism import ISM +from unshackle.core.music.renderer import MusicRenderer +from unshackle.core.tracks import Audio, Tracks + + +def dash_audio(set_attrs: str = "", rep_attrs: str = "") -> Audio: + text = f""" + + + + + + + + +""" + (audio,) = DASH.from_text(text, "https://cdn.example/x.mpd").to_tracks(language="en").audio + return audio + + +@pytest.mark.parametrize( + ("set_attrs", "rep_attrs", "rate"), + [ + ("", ' audioSamplingRate="96000"', 96000), + (' audioSamplingRate="44100"', "", 44100), + (' audioSamplingRate="44100"', ' audioSamplingRate="192000"', 192000), + ("", ' audioSamplingRate="24000 48000"', 48000), + ("", "", None), + ("", ' audioSamplingRate="high"', None), + ("", ' audioSamplingRate="²"', None), + ], +) +def test_dash_reads_the_sample_rate(set_attrs: str, rep_attrs: str, rate: int | None) -> None: + audio = dash_audio(set_attrs, rep_attrs) + assert (audio.sample_rate, audio.bit_depth) == (rate, None) + + +def test_ism_reads_the_sample_rate() -> None: + text = """ + + + + + +""" + (audio,) = ISM.from_text(text, "https://cdn.example/x.ism/manifest").to_tracks().audio + assert (audio.sample_rate, audio.bit_depth) == (44100, None) + + +@pytest.mark.parametrize( + ("attrs", "expected"), + [(",BIT-DEPTH=24,SAMPLE-RATE=96000", (24, 96000)), ("", (None, None)), (",SAMPLE-RATE=x", (None, None))], +) +def test_hls_reads_bit_depth_and_sample_rate_when_the_playlist_states_them( + attrs: str, expected: tuple[int | None, int | None] +) -> None: + text = ( + "#EXTM3U\n" + f'#EXT-X-MEDIA:TYPE=AUDIO,GROUP-ID="a",NAME="x",LANGUAGE="en",CHANNELS="2",URI="a.m3u8"{attrs}\n' + '#EXT-X-STREAM-INF:BANDWIDTH=1000000,CODECS="avc1.640028,alac",AUDIO="a"\n' + "v.m3u8\n" + ) + (audio,) = HLS.from_text(text, "https://cdn.example/master.m3u8").to_tracks(language="en").audio + assert (audio.bit_depth, audio.sample_rate) == expected + + +@pytest.mark.parametrize( + ("bit_depth", "sample_rate", "label"), + [(24, 96000, "24-bit / 96 kHz"), (16, 44100, "16-bit / 44.1 kHz"), (None, 48000, "48 kHz"), (24, None, "24-bit")], +) +def test_the_listing_shows_bit_depth_and_sample_rate( + bit_depth: int | None, sample_rate: int | None, label: str +) -> None: + audio = Audio(url="https://cdn.example/a.flac", language="en", bit_depth=bit_depth, sample_rate=sample_rate) + assert f" | {label}" in str(audio) + + +def test_the_listing_shows_neither_when_unset() -> None: + assert "bit" not in str(Audio(url="https://cdn.example/a.flac", language="en")) + + +@pytest.mark.parametrize("value", ["24", 24.0]) +def test_a_bit_depth_that_is_not_an_int_is_refused(value: object) -> None: + with pytest.raises(TypeError): + Audio(url="https://cdn.example/a.flac", language="en", bit_depth=value) # type: ignore[arg-type] + + +@pytest.mark.parametrize( + ("label", "bit_depth", "sample_rate", "hires"), + [ + ("FLAC", 24, 48000, True), + ("FLAC", 16, 96000, True), + ("FLAC 24-bit/96kHz", 16, 44100, False), + ("FLAC 24-bit/96kHz", None, None, True), + ("FLAC 24-bit/44.1kHz", None, 44100, True), + ("16-bit / 96 kHz", 16, None, True), + ], +) +def test_hires_is_decided_by_the_fields_before_the_label( + label: str, bit_depth: int | None, sample_rate: int | None, hires: bool +) -> None: + assert MusicRenderer.is_hires_quality(label, bit_depth, sample_rate) is hires + + +def test_a_song_with_fields_and_no_quality_label_shows_them_with_the_badge() -> None: + from tests.core.test_music_renderer import song + + line = MusicRenderer().option_from_song(song(1, "A", None, data={"bit_depth": 24, "sample_rate": 96000})) + assert line.plain.startswith("24-bit / 96 kHz") + assert "Hi-Res" in line.plain + + +def test_the_header_reads_hires_from_the_fields() -> None: + assert MusicRenderer.quality_summary("FLAC", bit_depth=24, sample_rate=48000) == "Hi-Res Lossless" + assert MusicRenderer.quality_summary("FLAC", bit_depth=16, sample_rate=44100) == "Lossless" + assert MusicRenderer.quality_summary("", bit_depth=24, sample_rate=96000) == "24-bit / 96 kHz" + + +def test_tracks_that_differ_only_in_bit_depth_are_both_kept() -> None: + a, b = (Audio(id_=str(n), url="https://cdn.example/a.flac", language="en", bit_depth=n) for n in (16, 24)) + assert Tracks.signature(a) != Tracks.signature(b) diff --git a/tests/core/test_wire.py b/tests/core/test_wire.py index d39bf75c..7fd26916 100644 --- a/tests/core/test_wire.py +++ b/tests/core/test_wire.py @@ -131,7 +131,12 @@ def song() -> Song: disc=1, year=2022, language="en", - data={"release_date": "2022-01-02", "composer": "Example Composer", "metadata": {"comment": "nested"}}, + data={ + "release_date": "2022-01-02", + "composer": "Example Composer", + "sample_rate": 96000, + "metadata": {"comment": "nested"}, + }, album_artist="Example Band", release_type="single", total_tracks=12, @@ -205,6 +210,8 @@ def audio(**extra: Any) -> Audio: channels="5.1", joc=16, descriptive=True, + bit_depth=24, + sample_rate=48000, id_="audio-0001", ) fields.update(extra) @@ -283,6 +290,8 @@ def track_fields(track: Any) -> dict[str, Any]: joc=track.joc, atmos=track.atmos, descriptive=track.descriptive, + bit_depth=track.bit_depth, + sample_rate=track.sample_rate, ) elif isinstance(track, Subtitle): out.update(cc=track.cc, sdh=track.sdh, forced=track.forced) @@ -402,7 +411,12 @@ REST_SONG = { "lyrics_suffix": ".lrc", "artwork_url": "https://img.example/song.jpg", "position": 7, - "music_data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"}, + "music_data": { + "release_date": "2022-01-02", + "composer": "Example Composer", + "sample_rate": 96000, + "comment": "nested", + }, } META_EPISODE = { @@ -478,6 +492,8 @@ REST_AUDIO = { "atmos": True, "joc": 16, "descriptive": True, + "bit_depth": 24, + "sample_rate": 48000, "language": "en", "is_original_lang": False, "name": None, @@ -552,6 +568,8 @@ EXPORT_AUDIO = { "channels": 5.1, "joc": 16, "descriptive": True, + "bit_depth": 24, + "sample_rate": 48000, } EXPORT_SUBTITLE = { @@ -618,6 +636,8 @@ AUDIO_FIELDS = { "joc": 16, "atmos": True, "descriptive": True, + "bit_depth": 24, + "sample_rate": 48000, } SUBTITLE_FIELDS = { @@ -784,7 +804,12 @@ def test_build_title_from_rest_song() -> None: "id": "song-0001", "language": "en", "year": 2022, - "data": {"release_date": "2022-01-02", "composer": "Example Composer", "comment": "nested"}, + "data": { + "release_date": "2022-01-02", + "composer": "Example Composer", + "sample_rate": 96000, + "comment": "nested", + }, "name": "Example Song", **{key: REST_SONG[key] for key in SONG_FIELDS}, } @@ -921,6 +946,11 @@ def test_export_audio() -> None: assert list(audio().to_dict()) == list(EXPORT_AUDIO) +def test_export_audio_from_an_older_version_has_no_bit_depth_or_sample_rate() -> None: + old = {k: v for k, v in json_copy(EXPORT_AUDIO).items() if k not in ("bit_depth", "sample_rate")} + assert track_fields(track_from_dict(old)) == {**AUDIO_FIELDS, "bit_depth": None, "sample_rate": None} + + def test_export_subtitle() -> None: assert subtitle().to_dict() == EXPORT_SUBTITLE assert list(subtitle().to_dict()) == list(EXPORT_SUBTITLE) @@ -986,6 +1016,8 @@ def test_deserialize_a_track_from_an_older_server() -> None: "joc": None, "atmos": True, "descriptive": False, + "bit_depth": None, + "sample_rate": None, } odd_subtitle = deserialize_subtitle({"id": "s-old", "codec": "NOPE", "note": 5}) assert track_fields(odd_subtitle) == { diff --git a/unshackle/core/manifests/dash.py b/unshackle/core/manifests/dash.py index 86113c3c..44d0d81b 100644 --- a/unshackle/core/manifests/dash.py +++ b/unshackle/core/manifests/dash.py @@ -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: """ diff --git a/unshackle/core/manifests/hls.py b/unshackle/core/manifests/hls.py index 5dda1712..61cee1d0 100644 --- a/unshackle/core/manifests/hls.py +++ b/unshackle/core/manifests/hls.py @@ -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( diff --git a/unshackle/core/manifests/ism.py b/unshackle/core/manifests/ism.py index 8f2838d1..26988fda 100644 --- a/unshackle/core/manifests/ism.py +++ b/unshackle/core/manifests/ism.py @@ -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, diff --git a/unshackle/core/music/renderer.py b/unshackle/core/music/renderer.py index d3a01d95..575168df 100644 --- a/unshackle/core/music/renderer.py +++ b/unshackle/core/music/renderer.py @@ -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\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\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: diff --git a/unshackle/core/titles/music.py b/unshackle/core/titles/music.py index 162f5859..de547d29 100644 --- a/unshackle/core/titles/music.py +++ b/unshackle/core/titles/music.py @@ -56,6 +56,8 @@ MUSIC_DATA_KEYS = ( "quality_label", "lossless", "hires", + "bit_depth", + "sample_rate", "atmos", "duration", "released_at", diff --git a/unshackle/core/tracks/audio.py b/unshackle/core/tracks/audio.py index a905c891..43550891 100644 --- a/unshackle/core/tracks/audio.py +++ b/unshackle/core/tracks/audio.py @@ -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: """ diff --git a/unshackle/core/tracks/tracks.py b/unshackle/core/tracks/tracks.py index 7a1ede20..dc21f528 100644 --- a/unshackle/core/tracks/tracks.py +++ b/unshackle/core/tracks/tracks.py @@ -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 diff --git a/unshackle/core/wire.py b/unshackle/core/wire.py index 4b15a525..a7351ce9 100644 --- a/unshackle/core/wire.py +++ b/unshackle/core/wire.py @@ -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), diff --git a/unshackle/services/MUSIC_EXAMPLE/__init__.py b/unshackle/services/MUSIC_EXAMPLE/__init__.py index 6fe1be00..89b9e167 100644 --- a/unshackle/services/MUSIC_EXAMPLE/__init__.py +++ b/unshackle/services/MUSIC_EXAMPLE/__init__.py @@ -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