Compare commits

...
2 Commits
Author SHA1 Message Date
imSp4rky b3a6db915b fix(cli): report broken command/service loads once and cleanly
Loaders raised at import time, and since Python does not cache a failed import, every command importing services re-ran and re-reported the same errors. Build the registry once, collect failures into LOAD_ERRORS, and surface them via a single click.ClickException at the list/get chokepoints so the message renders once without a traceback or cascade.
2026-05-25 19:50:11 -06:00
imSp4rky 5e3ffdeaa1 fix(hybrid): correct static L6 source and reset stale L5 active area
level_6() read MaxCLL/MaxFALL from the dovi_tool L1 line (dynamic per-shot content-light peak) and baked it into the static L6 field, so displays tone-map to a phantom peak and HDR brightness breaks. Read MaxCLL/MaxFALL from the static L6 block instead (mastering display parse unchanged), falling back to the HDR10 base stream only when the RPU has no L6 block. Add sanitize_l6() to clamp MaxCLL to the mastering-display peak and MaxFALL to MaxCLL (0 = "unknown" preserved); also applied to the HDR10+ -> DV path.

level_5() early-returned when cropdetect found no bars on the base, leaving whatever L5 offsets the DV source carried. When DV and HDR10 geometry differ (e.g. a letterboxed DV injected into an already-cropped base) the stale offsets rode through and signalled phantom bars. Always write the detected active area, including zeros, so stale source L5 resets to the full base frame.
2026-05-25 17:04:50 -06:00
3 changed files with 150 additions and 16 deletions
+50 -1
View File
@@ -1,3 +1,5 @@
import logging
from pathlib import Path
from typing import Optional from typing import Optional
import click import click
@@ -5,11 +7,56 @@ import click
from unshackle.core.config import config from unshackle.core.config import config
from unshackle.core.utilities import import_module_by_path from unshackle.core.utilities import import_module_by_path
log = logging.getLogger("commands")
_COMMANDS = sorted( _COMMANDS = sorted(
(path for path in config.directories.commands.glob("*.py") if path.stem.lower() != "__init__"), key=lambda x: x.stem (path for path in config.directories.commands.glob("*.py") if path.stem.lower() != "__init__"), key=lambda x: x.stem
) )
_MODULES = {path.stem: getattr(import_module_by_path(path), path.stem) for path in _COMMANDS}
def load_command(path: Path) -> object:
"""Load one command module, returning its stem-named attribute.
Raises a concise, single-line error naming the command and the real cause so
a broken command never surfaces as a raw traceback pointing at the loader.
"""
try:
module = import_module_by_path(path)
except Exception as e:
raise RuntimeError(f"{path.stem}: failed to import — {type(e).__name__}: {e} ({path})") from e
try:
return getattr(module, path.stem)
except AttributeError as e:
raise RuntimeError(
f"{path.stem}: no object named '{path.stem}' found in {path} — it must match the filename"
) from e
def load_commands(paths: list[Path]) -> tuple[dict[str, object], list[str]]:
"""Load every command, returning the good ones plus a list of load errors.
Importing this module must never raise (it runs at CLI startup, before Rich
is installed, so a raise here prints an ugly pre-setup traceback). Instead we
collect failures and surface them once, cleanly, when the CLI is used.
"""
modules: dict[str, object] = {}
errors: list[str] = []
for path in paths:
try:
modules[path.stem] = load_command(path)
except Exception as e:
errors.append(str(e))
return modules, errors
_MODULES, LOAD_ERRORS = load_commands(_COMMANDS)
def check_load_errors() -> None:
"""Raise a single clean error if any command failed to load."""
if LOAD_ERRORS:
joined = "\n".join(f" - {err}" for err in LOAD_ERRORS)
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} command(s):\n{joined}")
class Commands(click.MultiCommand): class Commands(click.MultiCommand):
@@ -17,10 +64,12 @@ class Commands(click.MultiCommand):
def list_commands(self, ctx: click.Context) -> list[str]: def list_commands(self, ctx: click.Context) -> list[str]:
"""Returns a list of command names from the command filenames.""" """Returns a list of command names from the command filenames."""
check_load_errors()
return [x.stem.replace("_", "-") for x in _COMMANDS] return [x.stem.replace("_", "-") for x in _COMMANDS]
def get_command(self, ctx: click.Context, name: str) -> Optional[click.Command]: def get_command(self, ctx: click.Context, name: str) -> Optional[click.Command]:
"""Load the command code and return the main click command function.""" """Load the command code and return the main click command function."""
check_load_errors()
module = _MODULES.get(name) or _MODULES.get(name.replace("-", "_")) module = _MODULES.get(name) or _MODULES.get(name.replace("-", "_"))
if not module: if not module:
raise click.ClickException(f"Unable to find command by the name '{name}'") raise click.ClickException(f"Unable to find command by the name '{name}'")
+57 -2
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
import logging
import re import re
from pathlib import Path from pathlib import Path
@@ -9,6 +10,8 @@ from unshackle.core.config import config
from unshackle.core.service import Service from unshackle.core.service import Service
from unshackle.core.utilities import import_module_by_path from unshackle.core.utilities import import_module_by_path
log = logging.getLogger("services")
_service_dirs = config.directories.services _service_dirs = config.directories.services
if not isinstance(_service_dirs, list): if not isinstance(_service_dirs, list):
_service_dirs = [_service_dirs] _service_dirs = [_service_dirs]
@@ -18,9 +21,59 @@ _SERVICES = sorted(
key=lambda x: x.parent.stem, key=lambda x: x.parent.stem,
) )
_MODULES = {path.parent.stem: getattr(import_module_by_path(path), path.parent.stem) for path in _SERVICES}
_ALIASES = {tag: getattr(module, "ALIASES") for tag, module in _MODULES.items()} def load_service(path: Path) -> object:
"""Load one Service module, returning its tag-named class.
Raises a concise, single-line error naming the Service and the real cause so
a broken Service never surfaces as a raw traceback pointing at the loader.
"""
tag = path.parent.stem
try:
module = import_module_by_path(path)
except Exception as e:
raise RuntimeError(f"{tag}: failed to import — {type(e).__name__}: {e} ({path})") from e
try:
return getattr(module, tag)
except AttributeError as e:
raise RuntimeError(
f"{tag}: no class named '{tag}' found in {path} — the class name must match the directory name"
) from e
def load_services(paths: list[Path]) -> tuple[dict[str, object], list[str]]:
"""Load every Service, returning the good ones plus a list of load errors.
Importing this module must never raise: it is imported by several commands,
and a failed import is not cached by Python, so raising here would re-run and
re-report for every command. Instead we collect failures and let the caller
surface them once, cleanly, at the point services are actually used.
"""
modules: dict[str, object] = {}
errors: list[str] = []
for path in paths:
try:
modules[path.parent.stem] = load_service(path)
except Exception as e:
errors.append(str(e))
return modules, errors
_MODULES, LOAD_ERRORS = load_services(_SERVICES)
_ALIASES = {tag: getattr(module, "ALIASES", ()) for tag, module in _MODULES.items()}
def check_load_errors() -> None:
"""Raise a single clean error if any Service failed to load.
Called when services are actually needed (listing/resolving) so the message
is rendered once by Click, without a traceback and without cascading through
every command that imports this module.
"""
if LOAD_ERRORS:
joined = "\n".join(f" - {err}" for err in LOAD_ERRORS)
raise click.ClickException(f"Failed to load {len(LOAD_ERRORS)} service(s):\n{joined}")
class Services(click.MultiCommand): class Services(click.MultiCommand):
@@ -64,10 +117,12 @@ class Services(click.MultiCommand):
if remote_tag not in tags: if remote_tag not in tags:
tags.append(remote_tag) tags.append(remote_tag)
return tags return tags
check_load_errors()
return Services.get_tags() return Services.get_tags()
def get_command(self, ctx: click.Context, name: str) -> click.Command: def get_command(self, ctx: click.Context, name: str) -> click.Command:
"""Load the Service and return the Click CLI method.""" """Load the Service and return the Click CLI method."""
check_load_errors()
tag = Services.get_tag(name) tag = Services.get_tag(name)
import_file = ctx.params.get("import_file") or (ctx.parent and ctx.parent.params.get("import_file")) import_file = ctx.params.get("import_file") or (ctx.parent and ctx.parent.params.get("import_file"))
+43 -13
View File
@@ -6,6 +6,7 @@ import re
import subprocess import subprocess
import sys import sys
from pathlib import Path from pathlib import Path
from typing import Optional
from rich.padding import Padding from rich.padding import Padding
from rich.rule import Rule from rich.rule import Rule
@@ -341,11 +342,7 @@ class Hybrid:
for crop in crop_results: for crop in crop_results:
crop_counts[crop] = crop_counts.get(crop, 0) + 1 crop_counts[crop] = crop_counts.get(crop, 0) + 1
most_common = max(crop_counts, key=crop_counts.get) most_common = max(crop_counts, key=crop_counts.get)
left, top, right, bottom = most_common left, top, right, bottom = most_common # frame instead of leaving phantom bars from the source.
# If all borders are 0 there's nothing to correct
if left == 0 and top == 0 and right == 0 and bottom == 0:
return
l5_json = { l5_json = {
"active_area": { "active_area": {
@@ -390,8 +387,24 @@ class Hybrid:
) )
self.rpu_file = "RPU_L5.bin" self.rpu_file = "RPU_L5.bin"
@staticmethod
def sanitize_l6(
max_mdl: Optional[int], min_mdl: Optional[int], max_cll: Optional[int], max_fall: Optional[int]
) -> tuple[Optional[int], Optional[int], Optional[int], Optional[int]]:
"""Clamp static L6 values to a valid relationship.
MaxCLL must not exceed the mastering-display peak (some sources, e.g. ATV
HDR10+, ship MaxCLL 10000 on a 1000-nit master), and MaxFALL must not exceed
MaxCLL. A value of 0 means "unknown" and is preserved as-is.
"""
if max_mdl and max_cll and max_cll > max_mdl:
max_cll = max_mdl
if max_cll and max_fall and max_fall > max_cll:
max_fall = max_cll
return max_mdl, min_mdl, max_cll, max_fall
def level_6(self): def level_6(self):
"""Edit RPU Level 6 values using actual luminance data from the RPU.""" """Edit RPU Level 6 values using the static L6 luminance data from the RPU."""
if os.path.isfile(config.directories.temp / "RPU_L6.bin"): if os.path.isfile(config.directories.temp / "RPU_L6.bin"):
return return
@@ -413,17 +426,33 @@ class Hybrid:
max_mdl = None max_mdl = None
min_mdl = None min_mdl = None
in_l6 = False
for line in info_text.splitlines(): for line in info_text.splitlines():
if "RPU content light level (L1):" in line: stripped = line.strip()
parts = line.split("MaxCLL:")[1].split(",") if "L6 metadata" in stripped:
max_cll = int(float(parts[0].strip().split()[0])) in_l6 = True
if len(parts) > 1 and "MaxFALL:" in parts[1]: if stripped.startswith("RPU mastering display:"):
max_fall = int(float(parts[1].split("MaxFALL:")[1].strip().split()[0])) mastering = stripped.split(":", 1)[1].strip()
elif "RPU mastering display:" in line:
mastering = line.split(":", 1)[1].strip()
min_lum, max_lum = mastering.split("/")[0], mastering.split("/")[1].split(" ")[0] min_lum, max_lum = mastering.split("/")[0], mastering.split("/")[1].split(" ")[0]
min_mdl = int(float(min_lum) * 10000) min_mdl = int(float(min_lum) * 10000)
max_mdl = int(float(max_lum)) max_mdl = int(float(max_lum))
elif in_l6 and "MaxCLL:" in stripped and max_cll is None:
max_cll = int(float(stripped.split("MaxCLL:")[1].split("nits")[0].strip().rstrip(",")))
if "MaxFALL:" in stripped:
max_fall = int(float(stripped.split("MaxFALL:")[1].split("nits")[0].strip().rstrip(",")))
if any(v is None for v in (max_cll, max_fall, max_mdl, min_mdl)):
base_max_mdl, base_min_mdl, base_cll, base_fall = self._probe_hdr_metadata()
if max_cll is None:
max_cll = base_cll
if max_fall is None:
max_fall = base_fall
if max_mdl is None:
max_mdl = base_max_mdl
if min_mdl is None:
min_mdl = base_min_mdl
max_mdl, min_mdl, max_cll, max_fall = self.sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)
if any(v is None for v in (max_cll, max_fall, max_mdl, min_mdl)): if any(v is None for v in (max_cll, max_fall, max_mdl, min_mdl)):
if self.debug_logger: if self.debug_logger:
@@ -638,6 +667,7 @@ class Hybrid:
with console.status("Converting HDR10+ metadata to Dolby Vision...", spinner="dots"): with console.status("Converting HDR10+ metadata to Dolby Vision...", spinner="dots"):
# Extract actual HDR metadata from the source stream # Extract actual HDR metadata from the source stream
max_mdl, min_mdl, max_cll, max_fall = self._probe_hdr_metadata() max_mdl, min_mdl, max_cll, max_fall = self._probe_hdr_metadata()
max_mdl, min_mdl, max_cll, max_fall = self.sanitize_l6(max_mdl, min_mdl, max_cll, max_fall)
# First create the extra metadata JSON for dovi_tool # First create the extra metadata JSON for dovi_tool
extra_metadata = { extra_metadata = {