mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-28 03:45:09 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f26f9bcbe2 | ||
|
|
ead88fe066 | ||
|
|
b4d422459c | ||
|
|
cda8120b6d |
@@ -53,6 +53,7 @@ from unshackle.core.titles import Movie, Movies, Series, Song, Title_T
|
|||||||
from unshackle.core.titles.episode import Episode
|
from unshackle.core.titles.episode import Episode
|
||||||
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
from unshackle.core.tracks import Audio, Subtitle, Tracks, Video
|
||||||
from unshackle.core.tracks.attachment import Attachment
|
from unshackle.core.tracks.attachment import Attachment
|
||||||
|
from unshackle.core.tracks.dv_fixup import apply_dv_fixup
|
||||||
from unshackle.core.tracks.hybrid import Hybrid
|
from unshackle.core.tracks.hybrid import Hybrid
|
||||||
from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger,
|
from unshackle.core.utilities import (find_font_with_fallbacks, get_debug_logger, get_system_fonts, init_debug_logger,
|
||||||
is_close_match, suggest_font_packages, time_elapsed_since)
|
is_close_match, suggest_font_packages, time_elapsed_since)
|
||||||
@@ -2309,6 +2310,13 @@ class dl:
|
|||||||
# we don't want to fill up the log with "Repacked x track"
|
# we don't want to fill up the log with "Repacked x track"
|
||||||
self.log.info("Repacked one or more tracks with FFMPEG")
|
self.log.info("Repacked one or more tracks with FFMPEG")
|
||||||
|
|
||||||
|
with console.status("Normalizing video VUI..."):
|
||||||
|
for track in title.tracks.videos:
|
||||||
|
try:
|
||||||
|
track.normalize_vui()
|
||||||
|
except Exception as e: # noqa: BLE001
|
||||||
|
self.log.warning(f"VUI normalization skipped for {track.id}: {e}")
|
||||||
|
|
||||||
muxed_paths = []
|
muxed_paths = []
|
||||||
muxed_audio_codecs: dict[Path, Optional[Audio.Codec]] = {}
|
muxed_audio_codecs: dict[Path, Optional[Audio.Codec]] = {}
|
||||||
append_audio_codec_suffix = True
|
append_audio_codec_suffix = True
|
||||||
@@ -2433,6 +2441,9 @@ class dl:
|
|||||||
else:
|
else:
|
||||||
# Normal mode: process each video track separately
|
# Normal mode: process each video track separately
|
||||||
for video_track in title.tracks.videos or [None]:
|
for video_track in title.tracks.videos or [None]:
|
||||||
|
if video_track and getattr(video_track, "dv_compatible_bitstream", False):
|
||||||
|
apply_dv_fixup(video_track)
|
||||||
|
|
||||||
task_description = "Multiplexing"
|
task_description = "Multiplexing"
|
||||||
if video_track:
|
if video_track:
|
||||||
if len(quality) > 1:
|
if len(quality) > 1:
|
||||||
|
|||||||
@@ -853,6 +853,10 @@ class DASH:
|
|||||||
def get_video_range(
|
def get_video_range(
|
||||||
codecs: str, all_supplemental_props: list[Element], all_essential_props: list[Element]
|
codecs: str, all_supplemental_props: list[Element], all_essential_props: list[Element]
|
||||||
) -> Video.Range:
|
) -> Video.Range:
|
||||||
|
# TODO: Detect Dolby Vision composite streams in DASH manifests (DV RPU embedded but
|
||||||
|
# primary codec is plain hvc1, signaled via a separate AdaptationSet/Representation
|
||||||
|
# with DV codec strings or DolbyVisionConfigurationBox). When found, mark the track
|
||||||
|
# with dv_compatible_bitstream=True so DVFixup runs pre-mux. No DASH samples seen yet.
|
||||||
if codecs.startswith(("dva1", "dvav", "dvhe", "dvh1")):
|
if codecs.startswith(("dva1", "dvav", "dvhe", "dvh1")):
|
||||||
return Video.Range.DV
|
return Video.Range.DV
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import html
|
|||||||
import json
|
import json
|
||||||
import logging
|
import logging
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
@@ -36,8 +37,14 @@ from unshackle.core.utilities import get_debug_logger, get_extension, is_close_m
|
|||||||
|
|
||||||
|
|
||||||
class HLS:
|
class HLS:
|
||||||
|
SUPP_CODECS_RE = re.compile(r'SUPPLEMENTAL-CODECS="([^"]+)"', re.IGNORECASE)
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self, manifest: M3U8, session: Optional[Union[Session, RnetSession]] = None, url: Optional[str] = None
|
self,
|
||||||
|
manifest: M3U8,
|
||||||
|
session: Optional[Union[Session, RnetSession]] = None,
|
||||||
|
url: Optional[str] = None,
|
||||||
|
raw_text: Optional[str] = None,
|
||||||
):
|
):
|
||||||
if not manifest:
|
if not manifest:
|
||||||
raise ValueError("HLS manifest must be provided.")
|
raise ValueError("HLS manifest must be provided.")
|
||||||
@@ -49,6 +56,7 @@ class HLS:
|
|||||||
self.manifest = manifest
|
self.manifest = manifest
|
||||||
self.session = session or Session()
|
self.session = session or Session()
|
||||||
self.url = url
|
self.url = url
|
||||||
|
self.raw_text = raw_text
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS:
|
def from_url(cls, url: str, session: Optional[Union[Session, RnetSession]] = None, **args: Any) -> HLS:
|
||||||
@@ -78,7 +86,7 @@ class HLS:
|
|||||||
|
|
||||||
master = m3u8.loads(content, uri=url)
|
master = m3u8.loads(content, uri=url)
|
||||||
|
|
||||||
return cls(master, session, url=url)
|
return cls(master, session, url=url, raw_text=content)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_text(cls, text: str, url: str) -> HLS:
|
def from_text(cls, text: str, url: str) -> HLS:
|
||||||
@@ -94,7 +102,31 @@ class HLS:
|
|||||||
|
|
||||||
master = m3u8.loads(text, uri=url)
|
master = m3u8.loads(text, uri=url)
|
||||||
|
|
||||||
return cls(master)
|
return cls(master, raw_text=text)
|
||||||
|
|
||||||
|
def supplemental_codecs_by_uri(self) -> dict[str, str]:
|
||||||
|
"""Map each variant URI to its SUPPLEMENTAL-CODECS value.
|
||||||
|
|
||||||
|
python-m3u8 drops this attribute, so we re-parse the raw text to recover it for
|
||||||
|
Dolby Vision composite detection (dvh1.08.x advertised only in SUPPLEMENTAL-CODECS
|
||||||
|
while primary CODECS stays plain hvc1).
|
||||||
|
"""
|
||||||
|
if not self.raw_text:
|
||||||
|
return {}
|
||||||
|
out: dict[str, str] = {}
|
||||||
|
lines = self.raw_text.splitlines()
|
||||||
|
for i, line in enumerate(lines):
|
||||||
|
if not line.startswith("#EXT-X-STREAM-INF"):
|
||||||
|
continue
|
||||||
|
supp_match = self.SUPP_CODECS_RE.search(line)
|
||||||
|
if not supp_match:
|
||||||
|
continue
|
||||||
|
for j in range(i + 1, len(lines)):
|
||||||
|
uri = lines[j].strip()
|
||||||
|
if uri and not uri.startswith("#"):
|
||||||
|
out[uri] = supp_match.group(1)
|
||||||
|
break
|
||||||
|
return out
|
||||||
|
|
||||||
def to_tracks(self, language: Union[str, Language]) -> Tracks:
|
def to_tracks(self, language: Union[str, Language]) -> Tracks:
|
||||||
"""
|
"""
|
||||||
@@ -126,6 +158,9 @@ class HLS:
|
|||||||
)
|
)
|
||||||
tracks = Tracks()
|
tracks = Tracks()
|
||||||
|
|
||||||
|
supplemental_codecs = self.supplemental_codecs_by_uri()
|
||||||
|
dv_supp_prefixes = ("dva1", "dvav", "dvhe", "dvh1")
|
||||||
|
|
||||||
for playlist in self.manifest.playlists:
|
for playlist in self.manifest.playlists:
|
||||||
audio_group = playlist.stream_info.audio
|
audio_group = playlist.stream_info.audio
|
||||||
audio_codec: Optional[Audio.Codec] = None
|
audio_codec: Optional[Audio.Codec] = None
|
||||||
@@ -146,6 +181,26 @@ class HLS:
|
|||||||
else:
|
else:
|
||||||
primary_track_type = Video
|
primary_track_type = Video
|
||||||
|
|
||||||
|
primary_codecs = (playlist.stream_info.codecs or "").lower()
|
||||||
|
primary_has_dv = any(codec.split(".")[0] in dv_supp_prefixes for codec in primary_codecs.split(","))
|
||||||
|
|
||||||
|
supp_codecs_str = supplemental_codecs.get(playlist.uri, "")
|
||||||
|
supp_dv_codec: Optional[str] = None
|
||||||
|
for codec in supp_codecs_str.lower().split(","):
|
||||||
|
token = codec.strip().split("/")[0]
|
||||||
|
if token.split(".")[0] in dv_supp_prefixes:
|
||||||
|
supp_dv_codec = token
|
||||||
|
break
|
||||||
|
|
||||||
|
video_range = (
|
||||||
|
Video.Range.DV if primary_has_dv else Video.Range.from_m3u_range_tag(playlist.stream_info.video_range)
|
||||||
|
)
|
||||||
|
# DV-composite track: primary codec is plain HEVC but SUPPLEMENTAL-CODECS advertises
|
||||||
|
# a DV codec. Range stays whatever VIDEO-RANGE signaled (HDR10/HLG/SDR); DVFixup will
|
||||||
|
# restore DV signaling post-download. Services that know their encoder embeds HDR10+
|
||||||
|
# SEI must override `range` themselves (see services/ATV).
|
||||||
|
dv_compatible_bitstream = primary_track_type is Video and not primary_has_dv and supp_dv_codec is not None
|
||||||
|
|
||||||
tracks.add(
|
tracks.add(
|
||||||
primary_track_type(
|
primary_track_type(
|
||||||
id_=hex(crc32(str(playlist).encode()))[2:],
|
id_=hex(crc32(str(playlist).encode()))[2:],
|
||||||
@@ -164,18 +219,14 @@ class HLS:
|
|||||||
# video track args
|
# video track args
|
||||||
**(
|
**(
|
||||||
dict(
|
dict(
|
||||||
range_=Video.Range.DV
|
range_=video_range,
|
||||||
if any(
|
|
||||||
codec.split(".")[0] in ("dva1", "dvav", "dvhe", "dvh1")
|
|
||||||
for codec in (playlist.stream_info.codecs or "").lower().split(",")
|
|
||||||
)
|
|
||||||
else Video.Range.from_m3u_range_tag(playlist.stream_info.video_range),
|
|
||||||
width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None,
|
width=playlist.stream_info.resolution[0] if playlist.stream_info.resolution else None,
|
||||||
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
|
height=playlist.stream_info.resolution[1] if playlist.stream_info.resolution else None,
|
||||||
fps=playlist.stream_info.frame_rate,
|
fps=playlist.stream_info.frame_rate,
|
||||||
closed_captions=cc_by_group_id.get(
|
closed_captions=cc_by_group_id.get(
|
||||||
(playlist.stream_info.closed_captions or "").strip('"'), []
|
(playlist.stream_info.closed_captions or "").strip('"'), []
|
||||||
),
|
),
|
||||||
|
dv_compatible_bitstream=dv_compatible_bitstream,
|
||||||
)
|
)
|
||||||
if primary_track_type is Video
|
if primary_track_type is Video
|
||||||
else {}
|
else {}
|
||||||
|
|||||||
@@ -61,7 +61,21 @@ class Title:
|
|||||||
returned dict with their specific fields (e.g., season/episode).
|
returned dict with their specific fields (e.g., season/episode).
|
||||||
"""
|
"""
|
||||||
primary_video_track = next(iter(media_info.video_tracks), None)
|
primary_video_track = next(iter(media_info.video_tracks), None)
|
||||||
primary_audio_track = next(iter(media_info.audio_tracks), None)
|
original_lang_tag = (
|
||||||
|
str(self.language).split("-")[0].lower() if self.language else ""
|
||||||
|
)
|
||||||
|
primary_audio_track = None
|
||||||
|
if original_lang_tag:
|
||||||
|
primary_audio_track = next(
|
||||||
|
(
|
||||||
|
t
|
||||||
|
for t in media_info.audio_tracks
|
||||||
|
if t.language and t.language.split("-")[0].lower() == original_lang_tag
|
||||||
|
),
|
||||||
|
None,
|
||||||
|
)
|
||||||
|
if primary_audio_track is None:
|
||||||
|
primary_audio_track = next(iter(media_info.audio_tracks), None)
|
||||||
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
unique_audio_languages = len({x.language.split("-")[0] for x in media_info.audio_tracks if x.language})
|
||||||
|
|
||||||
context: dict[str, Any] = {
|
context: dict[str, Any] = {
|
||||||
@@ -143,8 +157,6 @@ class Title:
|
|||||||
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
channel_count = primary_audio_track.channel_s or primary_audio_track.channels or 0
|
||||||
channels = float(channel_count)
|
channels = float(channel_count)
|
||||||
|
|
||||||
features = primary_audio_track.format_additionalfeatures or ""
|
|
||||||
|
|
||||||
has_atmos = any(
|
has_atmos = any(
|
||||||
"JOC" in (t.format_additionalfeatures or "") or t.joc for t in media_info.audio_tracks
|
"JOC" in (t.format_additionalfeatures or "") or t.joc for t in media_info.audio_tracks
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""
|
||||||
|
DV fixup for HLS composite HEVC streams.
|
||||||
|
|
||||||
|
Some services deliver DV Profile 8.1 in a stream whose primary CODECS is plain
|
||||||
|
hvc1, with DV advertised only via SUPPLEMENTAL-CODECS. The fMP4 carries DV RPU NALs but
|
||||||
|
the container does not signal DV, so muxing produces an MKV that mediainfo and DV-capable
|
||||||
|
TVs see as plain HDR10/HDR10+.
|
||||||
|
|
||||||
|
A dovi_tool extract-rpu / inject-rpu round-trip rewrites the bitstream so it is recognised
|
||||||
|
as DV after muxing. HDR10+ SEI NALs and HDR10 base layer signaling survive untouched.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from rich.padding import Padding
|
||||||
|
from rich.rule import Rule
|
||||||
|
|
||||||
|
from unshackle.core.binaries import FFMPEG, DoviTool
|
||||||
|
from unshackle.core.config import config
|
||||||
|
from unshackle.core.console import console
|
||||||
|
from unshackle.core.utilities import get_debug_logger
|
||||||
|
from unshackle.core.utils import dovi
|
||||||
|
from unshackle.core.utils.subprocess import run_step
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from unshackle.core.tracks import Video
|
||||||
|
|
||||||
|
|
||||||
|
class DVFixup:
|
||||||
|
"""Round-trip a DV-composite HEVC track through dovi_tool to restore DV signaling."""
|
||||||
|
|
||||||
|
def __init__(self, video: "Video") -> None:
|
||||||
|
self.log = logging.getLogger("dv-fixup")
|
||||||
|
self.debug_logger = get_debug_logger()
|
||||||
|
self.video = video
|
||||||
|
|
||||||
|
if not DoviTool:
|
||||||
|
raise EnvironmentError("dovi_tool is required for DV-composite fixup but was not found.")
|
||||||
|
if not FFMPEG:
|
||||||
|
raise EnvironmentError("ffmpeg is required for DV-composite fixup but was not found.")
|
||||||
|
if not video.path or not Path(video.path).exists():
|
||||||
|
raise ValueError(f"Video track {video.id} was not downloaded before DV fixup.")
|
||||||
|
|
||||||
|
def run(self) -> Path:
|
||||||
|
"""Execute the fixup. Returns the DV-signaled HEVC path, or the original
|
||||||
|
source path on any failure so muxing can proceed with the as-downloaded file."""
|
||||||
|
source = Path(self.video.path)
|
||||||
|
height = self.video.height or 0
|
||||||
|
console.print(Padding(Rule(f"[rule.text]DV Composite Fixup ({height}p)"), (1, 2)))
|
||||||
|
|
||||||
|
fixed_hevc = source.with_name(f"{self.video.id}.dv.hevc")
|
||||||
|
if fixed_hevc.exists() and fixed_hevc.stat().st_size > 0:
|
||||||
|
self.log.info("✓ DV signaling already restored (reusing existing fixup)")
|
||||||
|
return fixed_hevc
|
||||||
|
|
||||||
|
tmp = config.directories.temp
|
||||||
|
tmp.mkdir(parents=True, exist_ok=True)
|
||||||
|
suffix = f"{self.video.id}_{height or 'na'}"
|
||||||
|
raw_hevc = tmp / f"dvfix_{suffix}.hevc"
|
||||||
|
rpu = tmp / f"dvfix_{suffix}_rpu.bin"
|
||||||
|
|
||||||
|
try:
|
||||||
|
run_step(
|
||||||
|
[FFMPEG, "-nostdin", "-y", "-i", source, "-c:v", "copy", "-f", "hevc", raw_hevc],
|
||||||
|
status="Demuxing HEVC bitstream...",
|
||||||
|
output=raw_hevc,
|
||||||
|
label="ffmpeg demux",
|
||||||
|
)
|
||||||
|
dovi.extract_rpu_with_fallback(raw_hevc, rpu)
|
||||||
|
dovi.inject_rpu(raw_hevc, rpu, fixed_hevc, status="Re-injecting DV RPU with proper signaling...")
|
||||||
|
except Exception as e:
|
||||||
|
self.log.warning(f"DV fixup failed ({e}); muxing source as-is.")
|
||||||
|
if self.debug_logger:
|
||||||
|
self.debug_logger.log(
|
||||||
|
level="WARNING",
|
||||||
|
operation="dv_fixup",
|
||||||
|
message="DV fixup failed; falling back to source",
|
||||||
|
context={"error": str(e), "source": str(source)},
|
||||||
|
)
|
||||||
|
for leftover in (raw_hevc, rpu, fixed_hevc):
|
||||||
|
leftover.unlink(missing_ok=True)
|
||||||
|
return source
|
||||||
|
|
||||||
|
for leftover in (raw_hevc, rpu):
|
||||||
|
leftover.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
self.log.info("✓ DV signaling restored")
|
||||||
|
if self.debug_logger:
|
||||||
|
self.debug_logger.log(
|
||||||
|
level="INFO",
|
||||||
|
operation="dv_fixup",
|
||||||
|
message="DV fixup complete",
|
||||||
|
context={"source": str(source), "output": str(fixed_hevc)},
|
||||||
|
success=True,
|
||||||
|
)
|
||||||
|
return fixed_hevc
|
||||||
|
|
||||||
|
|
||||||
|
def apply_dv_fixup(video: "Video") -> None:
|
||||||
|
"""Run DV fixup on `video` if flagged as DV-composite. Updates `video.path` in place
|
||||||
|
and deletes the original source file so the standard mux cleanup handles the new path."""
|
||||||
|
if not getattr(video, "dv_compatible_bitstream", False):
|
||||||
|
return
|
||||||
|
if not video.path or not Path(video.path).exists():
|
||||||
|
return
|
||||||
|
original = Path(video.path)
|
||||||
|
fixed = DVFixup(video).run()
|
||||||
|
if fixed != original:
|
||||||
|
video.path = fixed
|
||||||
|
original.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = ("DVFixup", "apply_dv_fixup")
|
||||||
+78
-181
@@ -10,10 +10,12 @@ from pathlib import Path
|
|||||||
from rich.padding import Padding
|
from rich.padding import Padding
|
||||||
from rich.rule import Rule
|
from rich.rule import Rule
|
||||||
|
|
||||||
from unshackle.core.binaries import FFMPEG, DoviTool, FFProbe, HDR10PlusTool
|
from unshackle.core.binaries import FFMPEG, FFProbe, HDR10PlusTool
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.console import console
|
from unshackle.core.console import console
|
||||||
from unshackle.core.utilities import get_debug_logger
|
from unshackle.core.utilities import get_debug_logger
|
||||||
|
from unshackle.core.utils import dovi
|
||||||
|
from unshackle.core.utils.subprocess import run_step
|
||||||
|
|
||||||
|
|
||||||
class Hybrid:
|
class Hybrid:
|
||||||
@@ -138,51 +140,27 @@ class Hybrid:
|
|||||||
Path.unlink(config.directories.temp / "dv.mkv")
|
Path.unlink(config.directories.temp / "dv.mkv")
|
||||||
Path.unlink(config.directories.temp / "HDR10.hevc", missing_ok=True)
|
Path.unlink(config.directories.temp / "HDR10.hevc", missing_ok=True)
|
||||||
Path.unlink(config.directories.temp / "DV.hevc", missing_ok=True)
|
Path.unlink(config.directories.temp / "DV.hevc", missing_ok=True)
|
||||||
Path.unlink(config.directories.temp / f"{self.rpu_file}", missing_ok=True)
|
for rpu_name in ("RPU.bin", "RPU_UNT.bin", "RPU_L5.bin", "RPU_L6.bin"):
|
||||||
Path.unlink(config.directories.temp / "RPU_L6.bin", missing_ok=True)
|
Path.unlink(config.directories.temp / rpu_name, missing_ok=True)
|
||||||
Path.unlink(config.directories.temp / "RPU_L5.bin", missing_ok=True)
|
|
||||||
Path.unlink(config.directories.temp / "L5.json", missing_ok=True)
|
Path.unlink(config.directories.temp / "L5.json", missing_ok=True)
|
||||||
Path.unlink(config.directories.temp / "L6.json", missing_ok=True)
|
Path.unlink(config.directories.temp / "L6.json", missing_ok=True)
|
||||||
|
|
||||||
def ffmpeg_simple(self, save_path, output):
|
|
||||||
"""Simple ffmpeg execution without progress tracking"""
|
|
||||||
p = subprocess.run(
|
|
||||||
[
|
|
||||||
str(FFMPEG) if FFMPEG else "ffmpeg",
|
|
||||||
"-nostdin",
|
|
||||||
"-i",
|
|
||||||
str(save_path),
|
|
||||||
"-c:v",
|
|
||||||
"copy",
|
|
||||||
str(output),
|
|
||||||
"-y", # overwrite output
|
|
||||||
],
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
|
||||||
return p
|
|
||||||
|
|
||||||
def extract_stream(self, save_path, type_):
|
def extract_stream(self, save_path, type_):
|
||||||
output = Path(config.directories.temp / f"{type_}.hevc")
|
output = Path(config.directories.temp / f"{type_}.hevc")
|
||||||
|
try:
|
||||||
with console.status(f"Extracting {type_} stream...", spinner="dots"):
|
run_step(
|
||||||
result = self.ffmpeg_simple(save_path, output)
|
[FFMPEG or "ffmpeg", "-nostdin", "-y", "-i", save_path, "-c:v", "copy", output],
|
||||||
|
status=f"Extracting {type_} stream...",
|
||||||
if result.returncode:
|
output=output,
|
||||||
output.unlink(missing_ok=True)
|
label=f"ffmpeg extract {type_}",
|
||||||
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_extract_stream",
|
operation="hybrid_extract_stream",
|
||||||
message=f"Failed extracting {type_} stream",
|
message=f"Failed extracting {type_} stream",
|
||||||
context={
|
context={"type": type_, "input": str(save_path), "output": str(output), "error": str(e)},
|
||||||
"type": type_,
|
|
||||||
"input": str(save_path),
|
|
||||||
"output": str(output),
|
|
||||||
"returncode": result.returncode,
|
|
||||||
"stderr": (result.stderr or b"").decode(errors="replace"),
|
|
||||||
"stdout": (result.stdout or b"").decode(errors="replace"),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
self.log.error(f"x Failed extracting {type_} stream")
|
self.log.error(f"x Failed extracting {type_} stream")
|
||||||
sys.exit(1)
|
sys.exit(1)
|
||||||
@@ -202,48 +180,30 @@ class Hybrid:
|
|||||||
):
|
):
|
||||||
return
|
return
|
||||||
|
|
||||||
with console.status(
|
rpu_name = "RPU_UNT" if untouched else "RPU"
|
||||||
f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream...", spinner="dots"
|
rpu_path = config.directories.temp / f"{rpu_name}.bin"
|
||||||
):
|
dv_stream = config.directories.temp / "DV.hevc"
|
||||||
extraction_args = [str(DoviTool)]
|
spinner = f"Extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream..."
|
||||||
if not untouched:
|
|
||||||
extraction_args += ["-m", "3"]
|
|
||||||
extraction_args += [
|
|
||||||
"extract-rpu",
|
|
||||||
config.directories.temp / "DV.hevc",
|
|
||||||
"-o",
|
|
||||||
config.directories.temp / f"{'RPU' if not untouched else 'RPU_UNT'}.bin",
|
|
||||||
]
|
|
||||||
|
|
||||||
rpu_extraction = subprocess.run(
|
try:
|
||||||
extraction_args,
|
dovi.extract_rpu(dv_stream, rpu_path, mode=None if untouched else 3, status=spinner)
|
||||||
stdout=subprocess.PIPE,
|
except RuntimeError as e:
|
||||||
stderr=subprocess.PIPE,
|
stderr_text = str(e)
|
||||||
)
|
|
||||||
|
|
||||||
rpu_name = "RPU" if not untouched else "RPU_UNT"
|
|
||||||
if rpu_extraction.returncode:
|
|
||||||
Path.unlink(config.directories.temp / f"{rpu_name}.bin")
|
|
||||||
stderr_text = rpu_extraction.stderr.decode(errors="replace") if rpu_extraction.stderr else ""
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_extract_rpu",
|
operation="hybrid_extract_rpu",
|
||||||
message=f"Failed extracting{' untouched ' if untouched else ' '}RPU",
|
message=f"Failed extracting{' untouched ' if untouched else ' '}RPU",
|
||||||
context={
|
context={"untouched": untouched, "error": stderr_text},
|
||||||
"untouched": untouched,
|
|
||||||
"returncode": rpu_extraction.returncode,
|
|
||||||
"stderr": stderr_text,
|
|
||||||
"args": [str(a) for a in extraction_args],
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
if b"MAX_PQ_LUMINANCE" in rpu_extraction.stderr:
|
if "MAX_PQ_LUMINANCE" in stderr_text:
|
||||||
self.extract_rpu(video, untouched=True)
|
self.extract_rpu(video, untouched=True)
|
||||||
elif b"Invalid PPS index" in rpu_extraction.stderr:
|
return
|
||||||
|
if "Invalid PPS index" in stderr_text:
|
||||||
raise ValueError("Dolby Vision VideoTrack seems to be corrupt")
|
raise ValueError("Dolby Vision VideoTrack seems to be corrupt")
|
||||||
else:
|
raise ValueError(f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream")
|
||||||
raise ValueError(f"Failed extracting{' untouched ' if untouched else ' '}RPU from Dolby Vision stream")
|
|
||||||
elif self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="DEBUG",
|
level="DEBUG",
|
||||||
operation="hybrid_extract_rpu",
|
operation="hybrid_extract_rpu",
|
||||||
@@ -399,34 +359,22 @@ class Hybrid:
|
|||||||
with open(l5_path, "w") as f:
|
with open(l5_path, "w") as f:
|
||||||
json.dump(l5_json, f, indent=4)
|
json.dump(l5_json, f, indent=4)
|
||||||
|
|
||||||
with console.status("Editing RPU Level 5 active area...", spinner="dots"):
|
try:
|
||||||
result = subprocess.run(
|
dovi.editor(
|
||||||
[
|
config.directories.temp / self.rpu_file,
|
||||||
str(DoviTool),
|
l5_path,
|
||||||
"editor",
|
config.directories.temp / "RPU_L5.bin",
|
||||||
"-i",
|
status="Editing RPU Level 5 active area...",
|
||||||
str(config.directories.temp / self.rpu_file),
|
label="dovi_tool editor (L5)",
|
||||||
"-j",
|
|
||||||
str(l5_path),
|
|
||||||
"-o",
|
|
||||||
str(config.directories.temp / "RPU_L5.bin"),
|
|
||||||
],
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if result.returncode:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_level5",
|
operation="hybrid_level5",
|
||||||
message="Failed editing RPU Level 5 values",
|
message="Failed editing RPU Level 5 values",
|
||||||
context={
|
context={"error": str(e)},
|
||||||
"returncode": result.returncode,
|
|
||||||
"stderr": (result.stderr or b"").decode(errors="replace"),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
Path.unlink(config.directories.temp / "RPU_L5.bin", missing_ok=True)
|
|
||||||
raise ValueError("Failed editing RPU Level 5 values")
|
raise ValueError("Failed editing RPU Level 5 values")
|
||||||
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
@@ -447,20 +395,16 @@ class Hybrid:
|
|||||||
if os.path.isfile(config.directories.temp / "RPU_L6.bin"):
|
if os.path.isfile(config.directories.temp / "RPU_L6.bin"):
|
||||||
return
|
return
|
||||||
|
|
||||||
with console.status("Reading RPU luminance metadata...", spinner="dots"):
|
try:
|
||||||
result = subprocess.run(
|
with console.status("Reading RPU luminance metadata...", spinner="dots"):
|
||||||
[str(DoviTool), "info", "-i", str(config.directories.temp / self.rpu_file), "-s"],
|
info_text = dovi.info_summary(config.directories.temp / self.rpu_file)
|
||||||
capture_output=True,
|
except RuntimeError as e:
|
||||||
text=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
if result.returncode != 0:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_level6",
|
operation="hybrid_level6",
|
||||||
message="Failed reading RPU metadata for Level 6 values",
|
message="Failed reading RPU metadata for Level 6 values",
|
||||||
context={"returncode": result.returncode, "stderr": (result.stderr or "")},
|
context={"error": str(e)},
|
||||||
)
|
)
|
||||||
raise ValueError("Failed reading RPU metadata for Level 6 values")
|
raise ValueError("Failed reading RPU metadata for Level 6 values")
|
||||||
|
|
||||||
@@ -469,7 +413,7 @@ class Hybrid:
|
|||||||
max_mdl = None
|
max_mdl = None
|
||||||
min_mdl = None
|
min_mdl = None
|
||||||
|
|
||||||
for line in result.stdout.splitlines():
|
for line in info_text.splitlines():
|
||||||
if "RPU content light level (L1):" in line:
|
if "RPU content light level (L1):" in line:
|
||||||
parts = line.split("MaxCLL:")[1].split(",")
|
parts = line.split("MaxCLL:")[1].split(",")
|
||||||
max_cll = int(float(parts[0].strip().split()[0]))
|
max_cll = int(float(parts[0].strip().split()[0]))
|
||||||
@@ -506,34 +450,22 @@ class Hybrid:
|
|||||||
with open(l6_path, "w") as f:
|
with open(l6_path, "w") as f:
|
||||||
json.dump(level6_data, f, indent=4)
|
json.dump(level6_data, f, indent=4)
|
||||||
|
|
||||||
with console.status("Editing RPU Level 6 values...", spinner="dots"):
|
try:
|
||||||
result = subprocess.run(
|
dovi.editor(
|
||||||
[
|
config.directories.temp / self.rpu_file,
|
||||||
str(DoviTool),
|
l6_path,
|
||||||
"editor",
|
config.directories.temp / "RPU_L6.bin",
|
||||||
"-i",
|
status="Editing RPU Level 6 values...",
|
||||||
str(config.directories.temp / self.rpu_file),
|
label="dovi_tool editor (L6)",
|
||||||
"-j",
|
|
||||||
str(l6_path),
|
|
||||||
"-o",
|
|
||||||
str(config.directories.temp / "RPU_L6.bin"),
|
|
||||||
],
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if result.returncode:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_level6",
|
operation="hybrid_level6",
|
||||||
message="Failed editing RPU Level 6 values",
|
message="Failed editing RPU Level 6 values",
|
||||||
context={
|
context={"error": str(e)},
|
||||||
"returncode": result.returncode,
|
|
||||||
"stderr": (result.stderr or b"").decode(errors="replace"),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
Path.unlink(config.directories.temp / "RPU_L6.bin", missing_ok=True)
|
|
||||||
raise ValueError("Failed editing RPU Level 6 values")
|
raise ValueError("Failed editing RPU Level 6 values")
|
||||||
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
@@ -555,38 +487,22 @@ class Hybrid:
|
|||||||
if os.path.isfile(config.directories.temp / self.hevc_file):
|
if os.path.isfile(config.directories.temp / self.hevc_file):
|
||||||
return
|
return
|
||||||
|
|
||||||
with console.status(f"Injecting Dolby Vision metadata into {self.hdr_type} stream...", spinner="dots"):
|
try:
|
||||||
inject_cmd = [
|
dovi.inject_rpu(
|
||||||
str(DoviTool),
|
|
||||||
"inject-rpu",
|
|
||||||
"-i",
|
|
||||||
config.directories.temp / "HDR10.hevc",
|
config.directories.temp / "HDR10.hevc",
|
||||||
"--rpu-in",
|
|
||||||
config.directories.temp / self.rpu_file,
|
config.directories.temp / self.rpu_file,
|
||||||
]
|
config.directories.temp / self.hevc_file,
|
||||||
|
status=f"Injecting Dolby Vision metadata into {self.hdr_type} stream...",
|
||||||
inject_cmd.extend(["-o", config.directories.temp / self.hevc_file])
|
label="dovi_tool inject-rpu",
|
||||||
|
|
||||||
inject = subprocess.run(
|
|
||||||
inject_cmd,
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if inject.returncode:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_inject_rpu",
|
operation="hybrid_inject_rpu",
|
||||||
message="Failed injecting Dolby Vision metadata into HDR10 stream",
|
message="Failed injecting Dolby Vision metadata into HDR10 stream",
|
||||||
context={
|
context={"error": str(e)},
|
||||||
"returncode": inject.returncode,
|
|
||||||
"stderr": (inject.stderr or b"").decode(errors="replace"),
|
|
||||||
"stdout": (inject.stdout or b"").decode(errors="replace"),
|
|
||||||
"cmd": [str(a) for a in inject_cmd],
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
Path.unlink(config.directories.temp / self.hevc_file)
|
|
||||||
raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream")
|
raise ValueError("Failed injecting Dolby Vision metadata into HDR10 stream")
|
||||||
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
@@ -611,35 +527,29 @@ class Hybrid:
|
|||||||
if not HDR10PlusTool:
|
if not HDR10PlusTool:
|
||||||
raise ValueError("HDR10Plus_tool not found. Please install it to use HDR10+ to DV conversion.")
|
raise ValueError("HDR10Plus_tool not found. Please install it to use HDR10+ to DV conversion.")
|
||||||
|
|
||||||
with console.status("Extracting HDR10+ metadata...", spinner="dots"):
|
try:
|
||||||
# HDR10Plus_tool needs raw HEVC stream
|
run_step(
|
||||||
extraction = subprocess.run(
|
|
||||||
[
|
[
|
||||||
str(HDR10PlusTool),
|
HDR10PlusTool,
|
||||||
"extract",
|
"extract",
|
||||||
str(config.directories.temp / "HDR10.hevc"),
|
config.directories.temp / "HDR10.hevc",
|
||||||
"-o",
|
"-o",
|
||||||
str(config.directories.temp / self.hdr10plus_file),
|
config.directories.temp / self.hdr10plus_file,
|
||||||
],
|
],
|
||||||
stdout=subprocess.PIPE,
|
status="Extracting HDR10+ metadata...",
|
||||||
stderr=subprocess.PIPE,
|
output=config.directories.temp / self.hdr10plus_file,
|
||||||
|
label="hdr10plus_tool extract",
|
||||||
)
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if extraction.returncode:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_extract_hdr10plus",
|
operation="hybrid_extract_hdr10plus",
|
||||||
message="Failed extracting HDR10+ metadata",
|
message="Failed extracting HDR10+ metadata",
|
||||||
context={
|
context={"error": str(e)},
|
||||||
"returncode": extraction.returncode,
|
|
||||||
"stderr": (extraction.stderr or b"").decode(errors="replace"),
|
|
||||||
"stdout": (extraction.stdout or b"").decode(errors="replace"),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
raise ValueError("Failed extracting HDR10+ metadata")
|
raise ValueError("Failed extracting HDR10+ metadata")
|
||||||
|
|
||||||
# Check if the extracted file has content
|
|
||||||
file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file)
|
file_size = os.path.getsize(config.directories.temp / self.hdr10plus_file)
|
||||||
if file_size == 0:
|
if file_size == 0:
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
@@ -744,33 +654,20 @@ class Hybrid:
|
|||||||
with open(config.directories.temp / "extra.json", "w") as f:
|
with open(config.directories.temp / "extra.json", "w") as f:
|
||||||
json.dump(extra_metadata, f, indent=2)
|
json.dump(extra_metadata, f, indent=2)
|
||||||
|
|
||||||
# Generate DV RPU from HDR10+ metadata
|
try:
|
||||||
conversion = subprocess.run(
|
dovi.generate_from_hdr10plus(
|
||||||
[
|
config.directories.temp / "extra.json",
|
||||||
str(DoviTool),
|
config.directories.temp / self.hdr10plus_file,
|
||||||
"generate",
|
config.directories.temp / "RPU.bin",
|
||||||
"-j",
|
label="dovi_tool generate",
|
||||||
str(config.directories.temp / "extra.json"),
|
|
||||||
"--hdr10plus-json",
|
|
||||||
str(config.directories.temp / self.hdr10plus_file),
|
|
||||||
"-o",
|
|
||||||
str(config.directories.temp / "RPU.bin"),
|
|
||||||
],
|
|
||||||
stdout=subprocess.PIPE,
|
|
||||||
stderr=subprocess.PIPE,
|
|
||||||
)
|
)
|
||||||
|
except RuntimeError as e:
|
||||||
if conversion.returncode:
|
|
||||||
if self.debug_logger:
|
if self.debug_logger:
|
||||||
self.debug_logger.log(
|
self.debug_logger.log(
|
||||||
level="ERROR",
|
level="ERROR",
|
||||||
operation="hybrid_convert_hdr10plus",
|
operation="hybrid_convert_hdr10plus",
|
||||||
message="Failed converting HDR10+ to Dolby Vision",
|
message="Failed converting HDR10+ to Dolby Vision",
|
||||||
context={
|
context={"error": str(e)},
|
||||||
"returncode": conversion.returncode,
|
|
||||||
"stderr": (conversion.stderr or b"").decode(errors="replace"),
|
|
||||||
"stdout": (conversion.stdout or b"").decode(errors="replace"),
|
|
||||||
},
|
|
||||||
)
|
)
|
||||||
raise ValueError("Failed converting HDR10+ to Dolby Vision")
|
raise ValueError("Failed converting HDR10+ to Dolby Vision")
|
||||||
|
|
||||||
|
|||||||
@@ -228,6 +228,7 @@ class Video(Track):
|
|||||||
fps: Optional[Union[str, int, float]] = None,
|
fps: Optional[Union[str, int, float]] = None,
|
||||||
scan_type: Optional[Video.ScanType] = None,
|
scan_type: Optional[Video.ScanType] = None,
|
||||||
closed_captions: Optional[list[dict[str, Any]]] = None,
|
closed_captions: Optional[list[dict[str, Any]]] = None,
|
||||||
|
dv_compatible_bitstream: bool = False,
|
||||||
**kwargs: Any,
|
**kwargs: Any,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""
|
"""
|
||||||
@@ -294,6 +295,7 @@ class Video(Track):
|
|||||||
self.scan_type = scan_type
|
self.scan_type = scan_type
|
||||||
self.closed_captions: list[dict[str, Any]] = closed_captions or []
|
self.closed_captions: list[dict[str, Any]] = closed_captions or []
|
||||||
self.needs_duration_fix = False
|
self.needs_duration_fix = False
|
||||||
|
self.dv_compatible_bitstream = dv_compatible_bitstream
|
||||||
|
|
||||||
def __str__(self) -> str:
|
def __str__(self) -> str:
|
||||||
return " | ".join(
|
return " | ".join(
|
||||||
@@ -365,6 +367,67 @@ class Video(Track):
|
|||||||
self.path = output_path
|
self.path = output_path
|
||||||
original_path.unlink()
|
original_path.unlink()
|
||||||
|
|
||||||
|
def normalize_vui(self) -> bool:
|
||||||
|
"""Rewrite SPS VUI colour metadata to match ``self.range``.
|
||||||
|
|
||||||
|
Some services ship HDR10/HLG bitstreams with stale BT.709 VUI, which makes
|
||||||
|
downstream tools mis-classify the file. The manifest-derived range is the
|
||||||
|
source of truth. Skips SDR, DV, and HYBRID. Returns True if the bitstream
|
||||||
|
was rewritten.
|
||||||
|
"""
|
||||||
|
if not self.path or not self.path.exists():
|
||||||
|
return False
|
||||||
|
if self.codec not in (Video.Codec.AVC, Video.Codec.HEVC):
|
||||||
|
return False
|
||||||
|
if self.range in (Video.Range.SDR, Video.Range.DV, Video.Range.HYBRID):
|
||||||
|
return False
|
||||||
|
|
||||||
|
vui = {
|
||||||
|
Video.Range.HDR10: (9, 16, 9),
|
||||||
|
Video.Range.HDR10P: (9, 16, 9),
|
||||||
|
Video.Range.HLG: (9, 18, 9),
|
||||||
|
}.get(self.range)
|
||||||
|
if not vui:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not binaries.FFMPEG:
|
||||||
|
raise EnvironmentError('FFmpeg executable "ffmpeg" was not found but is required for this call.')
|
||||||
|
|
||||||
|
primaries, transfer, matrix = vui
|
||||||
|
filter_key = {Video.Codec.AVC: "h264_metadata", Video.Codec.HEVC: "hevc_metadata"}[self.codec]
|
||||||
|
bsf = (
|
||||||
|
f"{filter_key}=colour_primaries={primaries}"
|
||||||
|
f":transfer_characteristics={transfer}"
|
||||||
|
f":matrix_coefficients={matrix}"
|
||||||
|
)
|
||||||
|
|
||||||
|
original_path = self.path
|
||||||
|
output_path = original_path.with_stem(f"{original_path.stem}_vui")
|
||||||
|
try:
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
binaries.FFMPEG,
|
||||||
|
"-hide_banner",
|
||||||
|
"-loglevel",
|
||||||
|
"error",
|
||||||
|
"-i",
|
||||||
|
str(original_path),
|
||||||
|
"-codec",
|
||||||
|
"copy",
|
||||||
|
"-bsf:v",
|
||||||
|
bsf,
|
||||||
|
str(output_path),
|
||||||
|
],
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
except subprocess.CalledProcessError:
|
||||||
|
output_path.unlink(missing_ok=True)
|
||||||
|
return False
|
||||||
|
|
||||||
|
self.path = output_path
|
||||||
|
original_path.unlink()
|
||||||
|
return True
|
||||||
|
|
||||||
def ccextractor(
|
def ccextractor(
|
||||||
self, track_id: Any, out_path: Union[Path, str], language: Language, original: bool = False
|
self, track_id: Any, out_path: Union[Path, str], language: Language, original: bool = False
|
||||||
) -> Optional[Subtitle]:
|
) -> Optional[Subtitle]:
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
"""Thin wrappers around dovi_tool subcommands used by DVFixup and Hybrid.
|
||||||
|
|
||||||
|
Centralises argv construction, status spinners, and error handling so callers do not
|
||||||
|
re-implement subprocess plumbing per call site. Each wrapper:
|
||||||
|
|
||||||
|
- Resolves `binaries.DoviTool` and raises EnvironmentError if missing.
|
||||||
|
- Delegates to `core.utils.subprocess.run_step` for execution, output validation, and
|
||||||
|
stderr-tail RuntimeError on failure.
|
||||||
|
- Returns captured stderr so callers can inspect specific failure modes (e.g. the
|
||||||
|
MAX_PQ_LUMINANCE retry path in extract_rpu).
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from unshackle.core import binaries
|
||||||
|
from unshackle.core.utils.subprocess import run_step
|
||||||
|
|
||||||
|
|
||||||
|
def _require_dovi_tool() -> str:
|
||||||
|
if not binaries.DoviTool:
|
||||||
|
raise EnvironmentError("dovi_tool executable was not found but is required.")
|
||||||
|
return str(binaries.DoviTool)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_rpu(
|
||||||
|
source: Path,
|
||||||
|
output: Path,
|
||||||
|
*,
|
||||||
|
mode: Optional[int] = 3,
|
||||||
|
status: Optional[str] = "Extracting DV RPU...",
|
||||||
|
label: str = "dovi_tool extract-rpu",
|
||||||
|
) -> bytes:
|
||||||
|
"""Extract DV RPU NALs from a raw HEVC stream. `mode=None` skips the -m flag (untouched)."""
|
||||||
|
tool = _require_dovi_tool()
|
||||||
|
args: list = [tool]
|
||||||
|
if mode is not None:
|
||||||
|
args += ["-m", str(mode)]
|
||||||
|
args += ["extract-rpu", source, "-o", output]
|
||||||
|
return run_step(args, status=status, output=output, label=label)
|
||||||
|
|
||||||
|
|
||||||
|
def inject_rpu(
|
||||||
|
source: Path,
|
||||||
|
rpu: Path,
|
||||||
|
output: Path,
|
||||||
|
*,
|
||||||
|
status: Optional[str] = "Re-injecting DV RPU...",
|
||||||
|
label: str = "dovi_tool inject-rpu",
|
||||||
|
) -> bytes:
|
||||||
|
"""Inject a DV RPU back into a raw HEVC stream, producing DV-signaled output."""
|
||||||
|
tool = _require_dovi_tool()
|
||||||
|
return run_step(
|
||||||
|
[tool, "inject-rpu", "-i", source, "--rpu-in", rpu, "-o", output],
|
||||||
|
status=status,
|
||||||
|
output=output,
|
||||||
|
label=label,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def editor(
|
||||||
|
source: Path,
|
||||||
|
json_spec: Path,
|
||||||
|
output: Path,
|
||||||
|
*,
|
||||||
|
status: Optional[str] = "Editing DV RPU...",
|
||||||
|
label: str = "dovi_tool editor",
|
||||||
|
) -> bytes:
|
||||||
|
"""Apply a JSON edit spec to an RPU file."""
|
||||||
|
tool = _require_dovi_tool()
|
||||||
|
return run_step(
|
||||||
|
[tool, "editor", "-i", source, "-j", json_spec, "-o", output],
|
||||||
|
status=status,
|
||||||
|
output=output,
|
||||||
|
label=label,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def info_summary(rpu: Path) -> str:
|
||||||
|
"""Return the textual summary (`dovi_tool info -i ... -s`) for an RPU file."""
|
||||||
|
tool = _require_dovi_tool()
|
||||||
|
p = subprocess.run([tool, "info", "-i", str(rpu), "-s"], capture_output=True, text=True)
|
||||||
|
if p.returncode != 0:
|
||||||
|
raise RuntimeError(f"dovi_tool info failed: {(p.stderr or '')[-400:]}")
|
||||||
|
return p.stdout
|
||||||
|
|
||||||
|
|
||||||
|
def generate_from_hdr10plus(
|
||||||
|
extra_json: Path,
|
||||||
|
hdr10plus_json: Path,
|
||||||
|
output: Path,
|
||||||
|
*,
|
||||||
|
status: Optional[str] = "Generating DV RPU from HDR10+ metadata...",
|
||||||
|
label: str = "dovi_tool generate",
|
||||||
|
) -> bytes:
|
||||||
|
"""Build a DV RPU from extracted HDR10+ metadata + an extra JSON descriptor."""
|
||||||
|
tool = _require_dovi_tool()
|
||||||
|
return run_step(
|
||||||
|
[tool, "generate", "-j", extra_json, "--hdr10plus-json", hdr10plus_json, "-o", output],
|
||||||
|
status=status,
|
||||||
|
output=output,
|
||||||
|
label=label,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def extract_rpu_with_fallback(source: Path, output: Path, *, label: str = "dovi_tool extract-rpu") -> bytes:
|
||||||
|
"""Try `-m 3` first; on MAX_PQ_LUMINANCE error, retry untouched (no -m). Returns stderr.
|
||||||
|
|
||||||
|
Used when the caller wants automatic normalization but cannot abort if the source
|
||||||
|
rejects mode-3 conversion.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
return extract_rpu(source, output, mode=3, label=label)
|
||||||
|
except RuntimeError as e:
|
||||||
|
if "MAX_PQ_LUMINANCE" not in str(e):
|
||||||
|
raise
|
||||||
|
return extract_rpu(source, output, mode=None, status="Extracting DV RPU (untouched)...", label=label)
|
||||||
|
|
||||||
|
|
||||||
|
__all__ = (
|
||||||
|
"extract_rpu",
|
||||||
|
"extract_rpu_with_fallback",
|
||||||
|
"inject_rpu",
|
||||||
|
"editor",
|
||||||
|
"info_summary",
|
||||||
|
"generate_from_hdr10plus",
|
||||||
|
)
|
||||||
@@ -1,9 +1,10 @@
|
|||||||
import json
|
import json
|
||||||
import subprocess
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Union
|
from typing import Optional, Sequence, Union
|
||||||
|
|
||||||
from unshackle.core import binaries
|
from unshackle.core import binaries
|
||||||
|
from unshackle.core.console import console
|
||||||
|
|
||||||
|
|
||||||
def ffprobe(uri: Union[bytes, Path]) -> dict:
|
def ffprobe(uri: Union[bytes, Path]) -> dict:
|
||||||
@@ -23,3 +24,34 @@ def ffprobe(uri: Union[bytes, Path]) -> dict:
|
|||||||
except subprocess.CalledProcessError:
|
except subprocess.CalledProcessError:
|
||||||
return {}
|
return {}
|
||||||
return json.loads(ff.stdout.decode("utf8"))
|
return json.loads(ff.stdout.decode("utf8"))
|
||||||
|
|
||||||
|
|
||||||
|
def run_step(
|
||||||
|
args: Sequence[Union[str, Path]],
|
||||||
|
*,
|
||||||
|
status: Optional[str] = None,
|
||||||
|
output: Optional[Path] = None,
|
||||||
|
label: str = "subprocess step",
|
||||||
|
) -> bytes:
|
||||||
|
"""Run a CLI step that writes to `output` (when provided). Returns stderr bytes.
|
||||||
|
|
||||||
|
Raises RuntimeError with the stderr tail when the process exits non-zero, or when
|
||||||
|
`output` is given and does not exist / is empty after the run.
|
||||||
|
"""
|
||||||
|
if output is not None:
|
||||||
|
output.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
str_args = [str(a) for a in args]
|
||||||
|
if status:
|
||||||
|
with console.status(status, spinner="dots"):
|
||||||
|
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||||
|
else:
|
||||||
|
p = subprocess.run(str_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
|
||||||
|
|
||||||
|
stderr = p.stderr or b""
|
||||||
|
bad_output = output is not None and (not output.exists() or output.stat().st_size == 0)
|
||||||
|
if p.returncode or bad_output:
|
||||||
|
if output is not None:
|
||||||
|
output.unlink(missing_ok=True)
|
||||||
|
raise RuntimeError(f"{label} failed: {stderr.decode(errors='replace')[-400:]}")
|
||||||
|
return stderr
|
||||||
|
|||||||
Reference in New Issue
Block a user