forked from kenzuya/unshackle
feat(core): add HDR Vivid hybrids and a MonaLisa command builder
This commit is contained in:
@@ -8,6 +8,7 @@ from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
from collections.abc import Callable, Sequence
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from uuid import UUID
|
||||
@@ -44,6 +45,8 @@ class MonaLisa:
|
||||
ticket: str | bytes,
|
||||
device_path: Path,
|
||||
tool_path: Path | None = None,
|
||||
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
|
||||
segment_decrypt: bool = True,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""
|
||||
@@ -53,6 +56,9 @@ class MonaLisa:
|
||||
ticket: PSSH value from service API (base64 string or raw bytes).
|
||||
device_path: Path to the CDM device file (.mld).
|
||||
tool_path: Optional path to an external decryption binary.
|
||||
command_builder: Optional callback `(tool_path, src, dst, kid_hex, key_hex) -> args`
|
||||
that builds the decryption CLI invocation (default: `-i src -o dst -k kid:key`).
|
||||
segment_decrypt: Whether the external tool supports per-segment decryption.
|
||||
**kwargs: Additional metadata stored in self.data.
|
||||
|
||||
Raises:
|
||||
@@ -65,6 +71,8 @@ class MonaLisa:
|
||||
self._ticket = ticket
|
||||
self._device_path = device_path
|
||||
self._tool_path = tool_path
|
||||
self._command_builder = command_builder
|
||||
self._segment_decrypt = segment_decrypt
|
||||
self._decrypted_segments: int = 0
|
||||
self._kid: UUID | None = None
|
||||
self._key: str | None = None
|
||||
@@ -96,6 +104,8 @@ class MonaLisa:
|
||||
ticket: str | bytes,
|
||||
device_path: Path,
|
||||
tool_path: Path | None = None,
|
||||
command_builder: Callable[[Path, Path, Path, str, str], Sequence[str | Path]] | None = None,
|
||||
segment_decrypt: bool = True,
|
||||
) -> MonaLisa:
|
||||
"""
|
||||
Make a MonaLisa DRM instance from a PSSH/ticket.
|
||||
@@ -104,6 +114,8 @@ class MonaLisa:
|
||||
ticket: PSSH value from service API.
|
||||
device_path: Path to the CDM device file (.mld).
|
||||
tool_path: Optional path to an external decryption binary.
|
||||
command_builder: Optional callback that builds the decryption CLI invocation.
|
||||
segment_decrypt: Whether the external tool supports per-segment decryption.
|
||||
|
||||
Returns:
|
||||
MonaLisa DRM instance with extracted keys.
|
||||
@@ -112,6 +124,8 @@ class MonaLisa:
|
||||
ticket=ticket,
|
||||
device_path=device_path,
|
||||
tool_path=tool_path,
|
||||
command_builder=command_builder,
|
||||
segment_decrypt=segment_decrypt,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -184,6 +198,19 @@ class MonaLisa:
|
||||
return {self._kid: self._key}
|
||||
return {}
|
||||
|
||||
@property
|
||||
def supports_segment_decrypt(self) -> bool:
|
||||
"""Whether the configured external tool supports per-segment decryption."""
|
||||
return self._segment_decrypt
|
||||
|
||||
@property
|
||||
def track_decrypted(self) -> bool:
|
||||
"""Whether the service already decrypted the whole track into one clear segment file.
|
||||
|
||||
The service can keep its merged ciphertext beside that file, and the merge leaves it out.
|
||||
"""
|
||||
return not self._segment_decrypt and self._decrypted_segments > 0
|
||||
|
||||
@property
|
||||
def key_pair(self) -> str:
|
||||
"""The formatted ``KID:KEY`` for CLI decryptors (32hex:32hex)."""
|
||||
@@ -199,13 +226,16 @@ class MonaLisa:
|
||||
segment_path: Path to the segment file to decrypt.
|
||||
output_path: Optional path for the decrypted output segment.
|
||||
"""
|
||||
self._execute_decrypt(segment_path, output_path)
|
||||
self._execute_decrypt(segment_path, output_path, timeout=60)
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def decrypt(self, path: Path, output_path: Path | None = None, *, is_segment: bool = False) -> None:
|
||||
"""
|
||||
Decrypt a media file (segment or track) using the configured CLI tool via subprocess.
|
||||
|
||||
A whole-track tool runs once on a service's own merged file, which the service gives an ``output_path``.
|
||||
The in-place calls of core after it do nothing.
|
||||
|
||||
Args:
|
||||
path: Path to the target file to decrypt.
|
||||
output_path: Optional path for the decrypted output file.
|
||||
@@ -222,8 +252,16 @@ class MonaLisa:
|
||||
return
|
||||
|
||||
self._execute_decrypt(path, output_path)
|
||||
if output_path and not self._segment_decrypt:
|
||||
self._decrypted_segments += 1
|
||||
|
||||
def _execute_decrypt(self, path: Path, output_path: Path | None = None) -> None:
|
||||
def _execute_decrypt(
|
||||
self,
|
||||
path: Path,
|
||||
output_path: Path | None = None,
|
||||
*,
|
||||
timeout: float | None = None,
|
||||
) -> None:
|
||||
"""Run the external tool into a temporary file, which replaces the target only on success."""
|
||||
if not path or not path.exists():
|
||||
raise ValueError(f"Target file does not exist: {path}")
|
||||
@@ -236,10 +274,13 @@ class MonaLisa:
|
||||
|
||||
target_output = output_path or path
|
||||
temp_out = target_output.with_stem(f"{target_output.stem}_decrypted")
|
||||
cmd: Sequence[str | Path] = [self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair]
|
||||
if self._command_builder:
|
||||
cmd = self._command_builder(self._tool_path, path, temp_out, self.kid.hex, self.key)
|
||||
run_step(
|
||||
[self._tool_path, "-i", path, "-o", temp_out, "-k", self.key_pair],
|
||||
cmd,
|
||||
output=temp_out,
|
||||
label=f"MonaLisa decryption of {path.name}",
|
||||
timeout=60,
|
||||
timeout=timeout,
|
||||
)
|
||||
temp_out.replace(target_output)
|
||||
|
||||
@@ -31,7 +31,7 @@ from unshackle.core import binaries
|
||||
from unshackle.core.cdm.detect import cdm_system, cdm_type_stub, is_playready_cdm, is_widevine_cdm
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.constants import DOWNLOAD_ALL_DRM, DOWNLOAD_LICENCE_ONLY, AnyTrack
|
||||
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, PlayReady, Widevine
|
||||
from unshackle.core.drm import DRM_T, ClearKey, ClearKeyCENC, MonaLisa, PlayReady, Widevine
|
||||
from unshackle.core.drm.cenc import (
|
||||
PLACEHOLDER_KIDS,
|
||||
PLAYREADY_ID,
|
||||
@@ -985,7 +985,7 @@ class HLS:
|
||||
]
|
||||
if not files:
|
||||
raise ValueError(f"None of the segment files for {segment_range} exist...")
|
||||
elif len(files) != range_len:
|
||||
elif len(files) != range_len and not (isinstance(drm, MonaLisa) and drm.track_decrypted):
|
||||
raise ValueError(f"Missing {range_len - len(files)} segment files for {segment_range}...")
|
||||
|
||||
if isinstance(drm, (Widevine, PlayReady)):
|
||||
@@ -998,6 +998,10 @@ class HLS:
|
||||
decrypt_track(drm, merged_path, license_widevine, decrypt=not segment_decrypter, track=track)
|
||||
check_decrypted(track, merged_path, drm)
|
||||
merged_path.rename(decrypted_path)
|
||||
elif isinstance(drm, MonaLisa) and not drm.supports_segment_decrypt:
|
||||
merge(to=merged_path, via=files, delete=True, include_map_data=not drm.track_decrypted)
|
||||
decrypt_track(drm, merged_path, license_widevine, track=track)
|
||||
merged_path.rename(decrypted_path)
|
||||
else:
|
||||
# AES segments must be decrypted individually before merging: each segment
|
||||
# likely carries its own 16-byte padding
|
||||
@@ -1141,6 +1145,8 @@ class HLS:
|
||||
return sorted(segments)
|
||||
|
||||
segments_to_merge = find_segments_recursively(save_dir)
|
||||
if isinstance(session_drm, MonaLisa) and session_drm.track_decrypted:
|
||||
segments_to_merge = [file for file in segments_to_merge if file.stem.isdigit()]
|
||||
|
||||
log_event(
|
||||
"manifest_hls_download_complete",
|
||||
|
||||
@@ -94,7 +94,7 @@ def missing_hybrid_error(bases: Sequence[Video], made: int) -> str | None:
|
||||
if made:
|
||||
return None
|
||||
if not bases:
|
||||
return "No HEVC HDR10 or HDR10+ track to make a hybrid from"
|
||||
return "No HEVC HDR10, HDR10+ or VIVID track to make a hybrid from"
|
||||
return f"Every hybrid failed ({', '.join(f'{v.height or 0}p' for v in bases)}), so the title has no hybrid file"
|
||||
|
||||
|
||||
@@ -247,8 +247,6 @@ def mux_title(
|
||||
hybrid_mux_pool = mux_pool if mux_concurrency == 1 else extra_mux_pool
|
||||
|
||||
if any(r == Video.Range.HYBRID for r in range_) and title.tracks.videos:
|
||||
log.info("Processing Hybrid HDR10+DV tracks...")
|
||||
|
||||
original_videos = list(title.tracks.videos)
|
||||
|
||||
standalone_videos = [v for v in original_videos if not v.hybrid_base_only]
|
||||
@@ -258,6 +256,8 @@ def mux_title(
|
||||
hybrid_bases, matching_dv = hybrid_plan(
|
||||
[v for v in original_videos if v.hybrid_ingredient], generate_dv
|
||||
)
|
||||
base_label = hybrid_bases[0].range.name if hybrid_bases else "HDR10"
|
||||
log.info(f"Processing Hybrid {base_label}+DV tracks...")
|
||||
hybrid_base_ids.update(v.id for v in hybrid_bases)
|
||||
hybrids_made = 0
|
||||
for video in (v for v in original_videos if v.native_hybrid):
|
||||
@@ -289,7 +289,7 @@ def mux_title(
|
||||
except PermissionError:
|
||||
pass # still in hybrid_temp_paths, so the final cleanup tries again
|
||||
|
||||
task_description = f"Multiplexing Hybrid HDR10+DV {resolution}p"
|
||||
task_description = f"Multiplexing Hybrid {hdr10_track.range.name}+DV {resolution}p"
|
||||
task_tracks = Tracks(title.tracks) + title.tracks.chapters + title.tracks.attachments
|
||||
|
||||
hybrid_track = deepcopy(hdr10_track)
|
||||
|
||||
@@ -18,6 +18,7 @@ from rich.rule import Rule
|
||||
from unshackle.core.cacher import Cacher
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.console import console, prompt_user, show_notice, show_qr
|
||||
from unshackle.core.constants import DownloadCancelled
|
||||
from unshackle.core.credential import Credential
|
||||
from unshackle.core.launch import launch_keys
|
||||
from unshackle.core.proxies.resolve import pick_proxy
|
||||
@@ -38,7 +39,7 @@ from unshackle.core.title_cacher import TitleCacher
|
||||
from unshackle.core.title_source import TitleSource
|
||||
from unshackle.core.titles import Title_T, Titles_T, remap_titles
|
||||
from unshackle.core.tracks import Chapters, Tracks
|
||||
from unshackle.core.tracks.video import Video
|
||||
from unshackle.core.tracks.video import HYBRID_BASE_RANGES, Video
|
||||
from unshackle.core.utils import run_proxy
|
||||
from unshackle.core.utils.ip_info import get_ip_info, verify_proxy_exit
|
||||
|
||||
@@ -320,15 +321,30 @@ class Service(TitleSource):
|
||||
|
||||
for range_val in ranges:
|
||||
if range_val == Video.Range.HYBRID:
|
||||
# HYBRID: fetch HDR10 first, then DV
|
||||
# HYBRID: fetch HDR10 first (VIVID when there is none), then DV
|
||||
for codec_val in codecs:
|
||||
hdr_error: ValueError | SystemExit | None = None
|
||||
try:
|
||||
hdr_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.HDR10)
|
||||
except (ValueError, SystemExit) as e:
|
||||
hdr_error, hdr_tracks = e, Tracks()
|
||||
if not any(v.range in HYBRID_BASE_RANGES for v in hdr_tracks.videos):
|
||||
try:
|
||||
vivid_tracks = fetch_fn(title, codec=codec_val, range_=Video.Range.VIVID)
|
||||
except DownloadCancelled:
|
||||
raise
|
||||
except (Exception, SystemExit) as e:
|
||||
self.log.debug(f"No HDR Vivid manifest for HYBRID: {e!r}")
|
||||
vivid_tracks = Tracks()
|
||||
if any(v.range == Video.Range.VIVID for v in vivid_tracks.videos):
|
||||
if not hdr_error:
|
||||
merge(hdr_tracks)
|
||||
hdr_error, hdr_tracks = None, vivid_tracks
|
||||
if hdr_error:
|
||||
if self.track_request.best_available:
|
||||
self.log.warning(f" - HDR10 not available for HYBRID, skipping ({e})")
|
||||
self.log.warning(f" - HDR10 not available for HYBRID, skipping ({hdr_error})")
|
||||
continue
|
||||
raise
|
||||
raise hdr_error
|
||||
merge(hdr_tracks)
|
||||
|
||||
try:
|
||||
|
||||
@@ -147,6 +147,8 @@ class Title:
|
||||
and profile.startswith(("dvhe.07", "dvhe.08"))
|
||||
):
|
||||
base_layer = "HDR"
|
||||
if "HDR Vivid" in primary_video_track.hdr_format:
|
||||
base_layer = DYNAMIC_RANGE_MAP["HDR Vivid"]
|
||||
if base_layer and base_layer != "DV":
|
||||
context["hdr"] += f".{base_layer}"
|
||||
elif (primary_video_track.hdr_format or "").startswith("HDR Vivid"):
|
||||
|
||||
@@ -7,6 +7,8 @@ import tempfile
|
||||
from collections import Counter
|
||||
from collections.abc import Iterable
|
||||
from concurrent import futures
|
||||
from contextlib import suppress
|
||||
from fractions import Fraction
|
||||
from itertools import pairwise
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
@@ -203,6 +205,16 @@ def hdr10plus_shots(metadata: dict, active_fraction: float = 1.0) -> list[dict]:
|
||||
return shots
|
||||
|
||||
|
||||
def frame_rates(video: "Video", stream: dict[str, Any]) -> list[float]:
|
||||
"""The average and base frame rates FFprobe read; [0.0] when it has none, or for a raw stream, which has no clock."""
|
||||
rates = []
|
||||
if not video.path or video.path.suffix.lower() not in (".hevc", ".h265", ".265"):
|
||||
for name in ("avg_frame_rate", "r_frame_rate"):
|
||||
with suppress(ValueError, ZeroDivisionError):
|
||||
rates.append(float(Fraction(stream.get(name) or "0")))
|
||||
return [rate for rate in rates if rate] or [0.0]
|
||||
|
||||
|
||||
class NoHDR10PlusMetadata(ValueError):
|
||||
"""A track labelled HDR10+ carries no HDR10+ metadata."""
|
||||
|
||||
@@ -212,13 +224,13 @@ class Hybrid:
|
||||
self.log = logging.getLogger("hybrid")
|
||||
|
||||
"""
|
||||
Takes the Dolby Vision and HDR10(+) streams out of the VideoTracks.
|
||||
It will then attempt to inject the Dolby Vision metadata layer to the HDR10(+) stream.
|
||||
Takes the Dolby Vision and HDR10(+) or PQ HDR Vivid streams out of the VideoTracks.
|
||||
It will then attempt to inject the Dolby Vision metadata layer to the base stream.
|
||||
If no DV track is available, it makes the DV from the HDR10+ metadata, or from the
|
||||
decoded video when there is no HDR10+ or no hdr10plus_tool.
|
||||
"""
|
||||
global directories
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks.video import HYBRID_BASE_RANGES, Video
|
||||
|
||||
self.videos = videos
|
||||
self.source = source
|
||||
@@ -228,16 +240,15 @@ class Hybrid:
|
||||
self.hdr10plus_to_dv = False
|
||||
self.hdr10plus_file = "HDR10Plus.json"
|
||||
|
||||
hdr10_track = next((v for v in videos if v.range == Video.Range.HDR10), None)
|
||||
hdr10p_track = next((v for v in videos if v.range == Video.Range.HDR10P), None)
|
||||
track_for_res = hdr10_track or hdr10p_track
|
||||
base_video = next((v for v in videos if v.range in HYBRID_BASE_RANGES), None)
|
||||
self.resolution = (
|
||||
f"{standard_resolution(track_for_res.width, track_for_res.height)}p"
|
||||
if track_for_res and track_for_res.height
|
||||
f"{standard_resolution(base_video.width, base_video.height)}p"
|
||||
if base_video and base_video.height
|
||||
else "Unknown"
|
||||
)
|
||||
base_label = base_video.range.name if base_video else "HDR10"
|
||||
|
||||
console.print(Padding(Rule(f"[rule.text]HDR10+DV Hybrid ({self.resolution})"), (1, 2)))
|
||||
console.print(Padding(Rule(f"[rule.text]{base_label}+DV Hybrid ({self.resolution})"), (1, 2)))
|
||||
|
||||
log_event(
|
||||
"hybrid_init",
|
||||
@@ -255,12 +266,13 @@ class Hybrid:
|
||||
if not video.path or not os.path.exists(video.path):
|
||||
raise ValueError(f"Video track {video.id} was not downloaded before injection.")
|
||||
|
||||
has_dv = any(video.range == Video.Range.DV for video in self.videos)
|
||||
has_hdr10 = any(video.range == Video.Range.HDR10 for video in self.videos)
|
||||
dv_video = next((v for v in videos if v.range == Video.Range.DV), None)
|
||||
has_dv = dv_video is not None
|
||||
has_hdr10p = any(video.range == Video.Range.HDR10P for video in self.videos)
|
||||
|
||||
if not has_hdr10 and not has_hdr10p:
|
||||
raise ValueError("No HDR10 or HDR10+ track available for hybrid processing.")
|
||||
if not base_video:
|
||||
raise ValueError("No HDR10, HDR10+ or VIVID track available for hybrid processing.")
|
||||
self.check_base(base_video, dv_video)
|
||||
|
||||
if not has_dv:
|
||||
self.hdr10plus_to_dv = has_hdr10p and bool(HDR10PlusTool)
|
||||
@@ -277,17 +289,14 @@ class Hybrid:
|
||||
if not save_path or not os.path.exists(save_path):
|
||||
raise ValueError(f"Video track {video.id} was not downloaded or path not found: {save_path}")
|
||||
|
||||
if video.range == Video.Range.HDR10:
|
||||
if video.range in HYBRID_BASE_RANGES:
|
||||
self.extract_stream(save_path, "HDR10")
|
||||
elif video.range == Video.Range.HDR10P:
|
||||
self.extract_stream(save_path, "HDR10")
|
||||
self.hdr_type = "HDR10+"
|
||||
self.hdr_type = "HDR10+" if video.range == Video.Range.HDR10P else video.range.name
|
||||
elif video.range == Video.Range.DV:
|
||||
if not os.path.isfile(config.directories.temp / "DV.hevc"):
|
||||
self.extract_stream(save_path, "DV")
|
||||
|
||||
base_video = next((v for v in videos if v.range in (Video.Range.HDR10, Video.Range.HDR10P)), None)
|
||||
area = self.detect_active_area(base_video.path) if base_video and base_video.path else None
|
||||
area = self.detect_active_area(base_video.path) if base_video.path else None
|
||||
|
||||
if not has_dv:
|
||||
# a base that failed earlier in this title can leave its edited RPUs, which level_5/level_6 reuse
|
||||
@@ -302,8 +311,7 @@ class Hybrid:
|
||||
self.hdr10plus_to_dv = False
|
||||
else:
|
||||
self.convert_hdr10plus_to_dv(area[1] if area else 1.0)
|
||||
if has_dv:
|
||||
dv_video = next(v for v in videos if v.range == Video.Range.DV)
|
||||
if dv_video:
|
||||
self.extract_rpu(dv_video)
|
||||
if os.path.isfile(config.directories.temp / "RPU_UNT.bin"):
|
||||
self.rpu_file = "RPU_UNT.bin"
|
||||
@@ -315,7 +323,7 @@ class Hybrid:
|
||||
self.measure_dv(area[0] if area else None)
|
||||
|
||||
self.level_6()
|
||||
if base_video and has_dv:
|
||||
if dv_video:
|
||||
self.align_rpu(base_video, dv_video)
|
||||
if area:
|
||||
self.level_5(area[0])
|
||||
@@ -349,6 +357,32 @@ class Hybrid:
|
||||
)
|
||||
self.log.info("✓ Injection Completed")
|
||||
|
||||
@staticmethod
|
||||
def check_base(base: "Video", dv: "Video | None") -> None:
|
||||
"""Raise ValueError for a VIVID base that is not PQ, a DV track made for HLG, or two frame rates.
|
||||
|
||||
The injected RPU is profile 8.1, which needs a PQ base, and dovi_tool exits 0 when the RPU count does
|
||||
not fit the base. The rates come from the files, because a manifest can give one rate for every track.
|
||||
"""
|
||||
from unshackle.core.tracks.video import HDR_TRANSFER, Video, same_frame_rate
|
||||
|
||||
vivid = base.range == Video.Range.VIVID
|
||||
if not vivid and not dv:
|
||||
return
|
||||
stream = base._probe_colour()
|
||||
transfer = stream.get("color_transfer")
|
||||
if vivid and transfer != HDR_TRANSFER[Video.Range.HDR10]:
|
||||
raise ValueError(f"A VIVID hybrid needs a PQ base, not {transfer or 'an untagged one'}")
|
||||
if not dv:
|
||||
return
|
||||
dv_stream = dv._probe_colour()
|
||||
compatibility = [data.get("dv_bl_signal_compatibility_id") for data in dv_stream.get("side_data_list", [])]
|
||||
if 4 in compatibility or dv_stream.get("color_transfer") == HDR_TRANSFER[Video.Range.HLG]:
|
||||
raise ValueError("The Dolby Vision track is profile 8.4 (HLG), and a hybrid needs a PQ one")
|
||||
base_rates, dv_rates = frame_rates(base, stream), frame_rates(dv, dv_stream)
|
||||
if not any(same_frame_rate(a, b) for a in base_rates for b in dv_rates):
|
||||
raise ValueError(f"The base has {base_rates[0]:g} fps and the Dolby Vision track {dv_rates[0]:g} fps")
|
||||
|
||||
def extract_stream(self, save_path: Path, type_: str) -> None:
|
||||
output = Path(config.directories.temp / f"{type_}.hevc")
|
||||
try:
|
||||
|
||||
@@ -16,7 +16,7 @@ from unshackle.core.tracks.audio import Audio
|
||||
from unshackle.core.tracks.chapter import Chapter
|
||||
from unshackle.core.tracks.chapters import Chapters
|
||||
from unshackle.core.tracks.tracks import Tracks, at_resolution, select_videos
|
||||
from unshackle.core.tracks.video import Video
|
||||
from unshackle.core.tracks.video import HDR10_RANGES, HYBRID_BASE_RANGES, Video
|
||||
from unshackle.core.utilities import (
|
||||
as_requested,
|
||||
embedded_audio_langs,
|
||||
@@ -31,8 +31,6 @@ from unshackle.core.utilities import (
|
||||
|
||||
log = logging.getLogger("download")
|
||||
|
||||
HYBRID_BASE_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
|
||||
|
||||
|
||||
def generated_dv_ranges(
|
||||
range_: Sequence[Video.Range], generate_dv: bool
|
||||
@@ -43,7 +41,7 @@ def generated_dv_ranges(
|
||||
the flag is off, HYBRID or DV is in the ranges, or no base range is. The service still gets the
|
||||
ranges the user gave, so it fetches no DV track.
|
||||
"""
|
||||
bases = [r for r in range_ if r in HYBRID_BASE_RANGES]
|
||||
bases = [r for r in range_ if r in HDR10_RANGES]
|
||||
if not generate_dv or not bases or Video.Range.HYBRID in range_ or Video.Range.DV in range_:
|
||||
return list(range_), []
|
||||
return [Video.Range.HYBRID, *(r for r in range_ if r not in bases)], bases
|
||||
@@ -217,7 +215,9 @@ class TrackSelection:
|
||||
title.tracks.select_video(lambda x: x.codec != Video.Codec.LCEVC)
|
||||
|
||||
if keep_videos and self.generated_dv_bases:
|
||||
title.tracks.videos = keep_generated_dv_bases(title.tracks.videos, self.generated_dv_bases)
|
||||
title.tracks.videos = keep_generated_dv_bases(
|
||||
title.tracks.videos, [*self.generated_dv_bases, *range_]
|
||||
)
|
||||
if not any(v.range in self.generated_dv_bases for v in title.tracks.videos):
|
||||
return Skip(f"There's no {', '.join(r.name for r in self.generated_dv_bases)} Video Track...")
|
||||
|
||||
@@ -305,16 +305,14 @@ class TrackSelection:
|
||||
has_hybrid = any(r == Video.Range.HYBRID for r in range_)
|
||||
non_hybrid_ranges: list[Video.Range] = [r for r in range_ if r != Video.Range.HYBRID]
|
||||
effective_quality = self.quality
|
||||
hybrid_pool, non_hybrid_tracks = Tracks.partition_hybrid_videos(title.tracks.videos, non_hybrid_ranges)
|
||||
if self.generated_dv_bases:
|
||||
hybrid_pool = [v for v in hybrid_pool if v.range in self.generated_dv_bases]
|
||||
if keep_videos and self.quality:
|
||||
missing_resolutions = []
|
||||
if has_hybrid:
|
||||
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
|
||||
title.tracks.videos, non_hybrid_ranges
|
||||
)
|
||||
# only ranges that can actually be delivered count towards "present"
|
||||
deliverable_pool = hybrid_candidate_tracks + [
|
||||
v for v in non_hybrid_tracks if v.range in non_hybrid_ranges
|
||||
]
|
||||
deliverable_pool = hybrid_pool + [v for v in non_hybrid_tracks if v.range in non_hybrid_ranges]
|
||||
for resolution in self.quality:
|
||||
if any(at_resolution(v, resolution) for v in deliverable_pool):
|
||||
continue
|
||||
@@ -326,9 +324,9 @@ class TrackSelection:
|
||||
effective_quality = []
|
||||
else:
|
||||
hybrid_filter = title.tracks.select_hybrid(
|
||||
hybrid_candidate_tracks, self.quality, worst=self.worst, generate_dv=self.generate_dv
|
||||
hybrid_pool, self.quality, worst=self.worst, generate_dv=self.generate_dv
|
||||
)
|
||||
hybrid_selected = list(filter(hybrid_filter, hybrid_candidate_tracks))
|
||||
hybrid_selected = list(filter(hybrid_filter, hybrid_pool))
|
||||
|
||||
if non_hybrid_ranges and non_hybrid_tracks:
|
||||
non_hybrid_selected = [
|
||||
@@ -372,6 +370,7 @@ class TrackSelection:
|
||||
hybrid_candidate_tracks, non_hybrid_tracks = Tracks.partition_hybrid_videos(
|
||||
title.tracks.videos, non_hybrid_ranges
|
||||
)
|
||||
hybrid_candidate_tracks = [v for v in hybrid_candidate_tracks if v in hybrid_pool]
|
||||
|
||||
hybrid_quality = effective_quality
|
||||
if not hybrid_quality:
|
||||
@@ -655,15 +654,15 @@ def select_best_audio(
|
||||
|
||||
|
||||
def select_hybrid_bases(videos: Sequence[Video]) -> list[Video]:
|
||||
"""The HDR10 or HDR10+ track that is the hybrid base for each height, tallest first.
|
||||
"""The HDR10+, HDR10 or VIVID track that is the hybrid base for each height, tallest first.
|
||||
|
||||
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. HDR10+ comes before
|
||||
HDR10 at one height.
|
||||
Only HEVC tracks qualify, because dovi_tool injects the RPU into an HEVC stream. Priority at one
|
||||
height is HDR10+ > HDR10 > VIVID.
|
||||
"""
|
||||
bases: dict[int, Video] = {}
|
||||
for video in sorted(
|
||||
(v for v in videos if v.range in HYBRID_BASE_RANGES and v.codec in (Video.Codec.HEVC, None)),
|
||||
key=lambda v: (v.height or 0, v.range == Video.Range.HDR10P),
|
||||
key=lambda v: (v.height or 0, -HYBRID_BASE_RANGES.index(v.range)),
|
||||
reverse=True,
|
||||
):
|
||||
bases.setdefault(video.height or 0, video)
|
||||
@@ -679,17 +678,19 @@ def hybrid_gate_failure(videos: Sequence[Video], generate_dv: bool) -> str | Non
|
||||
"""The message that stops HYBRID for these selected videos, or None when it can go on."""
|
||||
if any(v.native_hybrid for v in videos):
|
||||
return None
|
||||
hdr_tracks = [v for v in videos if v.range in HYBRID_BASE_RANGES]
|
||||
hdr_tracks = [
|
||||
v for v in videos if v.range in HYBRID_BASE_RANGES and (v.range != Video.Range.VIVID or v.hybrid_ingredient)
|
||||
]
|
||||
base_tracks = [v for v in hdr_tracks if v.codec in (Video.Codec.HEVC, None)]
|
||||
dv_tracks = [v for v in videos if v.range == Video.Range.DV]
|
||||
ranges = ", ".join(sorted(set(v.range.name for v in videos))) or "none"
|
||||
missing = f"HYBRID needs HDR10/HDR10+ and DV tracks, available ranges: {ranges}"
|
||||
missing = f"HYBRID needs HDR10/HDR10+/VIVID and DV tracks, available ranges: {ranges}"
|
||||
|
||||
if not hdr_tracks:
|
||||
return missing
|
||||
if not base_tracks:
|
||||
codecs = sorted(set(v.codec.name for v in hdr_tracks if v.codec))
|
||||
return f"HYBRID needs an HEVC HDR10/HDR10+ base, available codecs: {', '.join(codecs)}"
|
||||
return f"HYBRID needs an HEVC HDR10/HDR10+/VIVID base, available codecs: {', '.join(codecs)}"
|
||||
if not dv_tracks and not generate_dv:
|
||||
return f"{missing}; add --generate-dv to make DV"
|
||||
return None
|
||||
|
||||
@@ -35,7 +35,7 @@ from unshackle.core.tracks.track import (
|
||||
has_mp4_only_audio_entry,
|
||||
prepare_for_mp4box,
|
||||
)
|
||||
from unshackle.core.tracks.video import Video
|
||||
from unshackle.core.tracks.video import HDR10_RANGES, HYBRID_BASE_RANGES, Video, same_frame_rate
|
||||
from unshackle.core.utilities import (
|
||||
FPS,
|
||||
is_close_match,
|
||||
@@ -605,13 +605,28 @@ class Tracks:
|
||||
) -> tuple[list[Video], list[Video]]:
|
||||
"""Split videos into hybrid-ingredient candidates and the standalone-deliverable pool.
|
||||
|
||||
HDR10/HDR10+/DV tracks are hybrid ingredients. They only enter the standalone
|
||||
HDR10/HDR10+/VIVID/DV tracks are hybrid ingredients. They only enter the standalone
|
||||
pool when the user explicitly requested their range alongside HYBRID, so for
|
||||
example `-r HYBRID` muxes only the hybrid while `-r HYBRID,HDR10P` also delivers
|
||||
HDR10+. A 3D track is never an ingredient: dovi_tool does not handle a second view.
|
||||
A VIVID track to build on must be HEVC, PQ and of the frame rate of a DV track, with no HEVC
|
||||
HDR10 or HDR10+ track in the title: those always have the PQ base that the hybrid needs. Call it
|
||||
before a filter by height, or a VIVID track that another height rules out counts as a base.
|
||||
"""
|
||||
ingredient_ranges = (Video.Range.HDR10, Video.Range.HDR10P, Video.Range.DV)
|
||||
ingredient_ranges = (*HYBRID_BASE_RANGES, Video.Range.DV)
|
||||
hybrid_candidates = [v for v in videos if v.range in ingredient_ranges and not v.stereo]
|
||||
hevc = (Video.Codec.HEVC, None)
|
||||
dv_rates = [v.fps for v in hybrid_candidates if v.range == Video.Range.DV] or [None]
|
||||
has_pq_base = any(v.range in HDR10_RANGES and v.codec in hevc for v in hybrid_candidates)
|
||||
|
||||
def usable(v: Video) -> bool:
|
||||
if v.range != Video.Range.VIVID or v.finished_hybrid:
|
||||
return True
|
||||
if has_pq_base or v.hlg_base or v.codec not in hevc:
|
||||
return False
|
||||
return any(same_frame_rate(v.fps, rate) for rate in dv_rates)
|
||||
|
||||
hybrid_candidates = [v for v in hybrid_candidates if usable(v)]
|
||||
non_hybrid = [v for v in videos if v.range not in ingredient_ranges or v.range in non_hybrid_ranges]
|
||||
return hybrid_candidates, non_hybrid
|
||||
|
||||
@@ -633,7 +648,7 @@ class Tracks:
|
||||
) -> Callable[[Video], bool]:
|
||||
"""A filter for the hybrid ingredients of each resolution. It sets ``native_hybrid`` on every track.
|
||||
|
||||
A track that already carries DV and an HDR10 or HDR10+ base (DV+HDR10P, HDR10+DV, HDR10P+DV) is a finished
|
||||
A track that already carries DV and a PQ base (DV+HDR10P, HDR10+DV, HDR10P+DV, VIVID+DV) is a finished
|
||||
hybrid, so its resolution takes that track and no base. One that carries HDR10+ comes first. The other
|
||||
resolutions get a base only when a DV track can give it an RPU, or with ``generate_dv``. Each pick follows
|
||||
``pick_video``, and the DV track is the lowest one, the best of that height.
|
||||
@@ -654,9 +669,8 @@ class Tracks:
|
||||
|
||||
# Prefer HDR10+ over HDR10 as the base layer (preserves dynamic metadata).
|
||||
# Only an HEVC base qualifies, because dovi_tool injects the RPU into an HEVC stream.
|
||||
base_ranges = (Video.Range.HDR10P, Video.Range.HDR10)
|
||||
base_tracks = []
|
||||
for range_type in base_ranges:
|
||||
for range_type in HYBRID_BASE_RANGES:
|
||||
base_tracks = [
|
||||
v
|
||||
for v in tracks
|
||||
|
||||
@@ -230,6 +230,7 @@ class Video(Track):
|
||||
dv_compatible_bitstream: bool = False,
|
||||
hdr10plus: bool = False,
|
||||
hdr10_base: bool = False,
|
||||
hlg_base: bool = False,
|
||||
stereo: bool = False,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
@@ -252,6 +253,7 @@ class Video(Track):
|
||||
A zero denominator gives no fps.
|
||||
hdr10plus: The DV track also carries HDR10+ metadata. The HDR10+ probe sets it.
|
||||
hdr10_base: The DV track has an HDR10 base layer, as DV profile 8.1 does.
|
||||
hlg_base: The HDR Vivid track has an HLG base. The HDR10+ probe sets it.
|
||||
stereo: The track is stereoscopic 3D (MV-HEVC), with a second view for the other eye.
|
||||
|
||||
Note: If codec, bitrate, width, height, or fps is not specified, unshackle can
|
||||
@@ -308,6 +310,7 @@ class Video(Track):
|
||||
self.dv_compatible_bitstream = dv_compatible_bitstream
|
||||
self.hdr10plus = hdr10plus
|
||||
self.hdr10_base = hdr10_base
|
||||
self.hlg_base = hlg_base
|
||||
self.stereo = stereo
|
||||
self.hybrid_base_only = False
|
||||
self.hybrid_ingredient = False
|
||||
@@ -348,10 +351,10 @@ class Video(Track):
|
||||
|
||||
@property
|
||||
def finished_hybrid(self) -> bool:
|
||||
"""Whether the track already carries DV and an HDR10 or HDR10+ base, so ``-r HYBRID`` needs no build."""
|
||||
"""Whether the track carries DV and an HDR10, HDR10+ or PQ HDR Vivid base, so ``-r HYBRID`` needs no build."""
|
||||
if self.range == Video.Range.DV:
|
||||
return self.hdr10plus
|
||||
return self.dv_compatible_bitstream and self.range in (Video.Range.HDR10, Video.Range.HDR10P)
|
||||
return self.dv_compatible_bitstream and self.range in HYBRID_BASE_RANGES and not self.hlg_base
|
||||
|
||||
@property
|
||||
def range_label(self) -> str:
|
||||
@@ -612,7 +615,7 @@ class Video(Track):
|
||||
return [arg for flag, value in opts.items() for arg in (flag, f"{track_id}:{value}")]
|
||||
|
||||
def _probe_colour(self) -> dict[str, Any]:
|
||||
"""Return the FFprobe colour transfer and side data of the first video track, or {} when it cannot probe."""
|
||||
"""The FFprobe colour transfer, frame rates and side data of the first video track, or {} when it cannot probe."""
|
||||
if not binaries.FFProbe or not self.path or not self.path.exists():
|
||||
return {}
|
||||
probe_start = time.monotonic()
|
||||
@@ -627,7 +630,7 @@ class Video(Track):
|
||||
"-select_streams",
|
||||
"v:0",
|
||||
"-show_entries",
|
||||
"stream=color_transfer:stream_side_data",
|
||||
"stream=color_transfer,avg_frame_rate,r_frame_rate:stream_side_data",
|
||||
"-of",
|
||||
"json",
|
||||
str(self.path),
|
||||
@@ -802,10 +805,17 @@ class Video(Track):
|
||||
return True
|
||||
|
||||
|
||||
def same_frame_rate(a: float | None, b: float | None) -> bool:
|
||||
"""Whether two frame rates can be one encode (23.976 and 24 can); an unknown rate matches any."""
|
||||
return not a or not b or abs(float(a) - float(b)) <= 0.5
|
||||
|
||||
|
||||
PROBED_RANGES = {
|
||||
Video.Range.HDR10: (Video.Range.HDR10P, Video.Range.VIVID),
|
||||
Video.Range.HLG: (Video.Range.VIVID,),
|
||||
}
|
||||
HDR10_RANGES = (Video.Range.HDR10P, Video.Range.HDR10)
|
||||
HYBRID_BASE_RANGES = (*HDR10_RANGES, Video.Range.VIVID)
|
||||
HDR_TRANSFER = {
|
||||
Video.Range.HDR10: "smpte2084",
|
||||
Video.Range.HDR10P: "smpte2084",
|
||||
|
||||
@@ -233,11 +233,11 @@ def probe_dynamic_hdr(
|
||||
"""Relabel HEVC tracks by the dynamic HDR metadata of their first sample, and flag DV tracks with HDR10+.
|
||||
|
||||
HDR10+ SEI makes an HDR10 track HDR10P. CUVA SEI, or the ``cuvv`` registration of an MPEG-TS stream,
|
||||
makes an HDR10 or HLG track VIVID; ``PROBED_RANGES`` holds which label each range takes. A DV track
|
||||
keeps its DV range and gets ``hdr10plus`` set, so selection and hybrid pairing are unchanged. HDR10,
|
||||
HLG and DV are separate ladders. A ladder with one track per resolution is sampled at both ends first.
|
||||
Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a ladder is
|
||||
probed whole. The rules are in the ``hdr10plus_probe`` section of docs/reference/configuration/download.md.
|
||||
makes an HDR10 or HLG track VIVID, and an HLG one gets ``hlg_base``; ``PROBED_RANGES`` holds which label
|
||||
each range takes. A DV track keeps its DV range and gets ``hdr10plus`` set, so selection and hybrid pairing
|
||||
are unchanged. HDR10, HLG and DV are separate ladders. A ladder with one track per resolution is sampled at
|
||||
both ends first. Two tracks at one resolution can be an HDR10 and an HDR10+ encode side by side, so such a
|
||||
ladder is probed whole. The rules are in the ``hdr10plus_probe`` section of docs/reference/configuration/download.md.
|
||||
A failed probe never changes a label. ``workers`` caps the probes in flight, and ``on_start`` runs once
|
||||
before the first.
|
||||
"""
|
||||
@@ -299,6 +299,7 @@ def probe_dynamic_hdr(
|
||||
if video.range == Video.Range.DV:
|
||||
video.hdr10plus = video.hdr10plus or label == Video.Range.HDR10P
|
||||
elif label in PROBED_RANGES.get(video.range, ()):
|
||||
video.hlg_base = video.range == Video.Range.HLG
|
||||
video.range = label
|
||||
|
||||
|
||||
|
||||
@@ -685,6 +685,7 @@ def serialize_video_track(track: Video, include_url: bool = False) -> dict[str,
|
||||
"dv_compatible_bitstream": bool(getattr(track, "dv_compatible_bitstream", False)),
|
||||
"hdr10plus": bool(getattr(track, "hdr10plus", False)),
|
||||
"hdr10_base": bool(getattr(track, "hdr10_base", False)),
|
||||
"hlg_base": bool(getattr(track, "hlg_base", False)),
|
||||
"stereo": bool(getattr(track, "stereo", False)),
|
||||
}
|
||||
result.update(serialize_track_common(track))
|
||||
@@ -796,6 +797,7 @@ def deserialize_video(data: dict[str, Any]) -> Video:
|
||||
dv_compatible_bitstream=bool(data.get("dv_compatible_bitstream", False)),
|
||||
hdr10plus=bool(data.get("hdr10plus", False)),
|
||||
hdr10_base=bool(data.get("hdr10_base", False)),
|
||||
hlg_base=bool(data.get("hlg_base", False)),
|
||||
stereo=bool(data.get("stereo", False)),
|
||||
)
|
||||
|
||||
@@ -884,6 +886,7 @@ def track_to_dict(track: Track) -> dict[str, Any]:
|
||||
"dv_compatible_bitstream": track.dv_compatible_bitstream,
|
||||
"hdr10plus": track.hdr10plus,
|
||||
"hdr10_base": track.hdr10_base,
|
||||
"hlg_base": track.hlg_base,
|
||||
"stereo": track.stereo,
|
||||
}
|
||||
)
|
||||
@@ -932,6 +935,7 @@ def track_from_dict(data: dict[str, Any]) -> Video | Audio | Subtitle:
|
||||
dv_compatible_bitstream=data.get("dv_compatible_bitstream", False),
|
||||
hdr10plus=data.get("hdr10plus", False),
|
||||
hdr10_base=data.get("hdr10_base", False),
|
||||
hlg_base=data.get("hlg_base", False),
|
||||
stereo=data.get("stereo", False),
|
||||
)
|
||||
if kind is Audio:
|
||||
|
||||
Reference in New Issue
Block a user