Skip to content

vodesfunc.analysis.descale

MetricMode

Bases: CustomStrEnum

Error metric for comparing source and reconstructed luma.

Source code in vodesfunc/analysis/descale.py
class MetricMode(CustomStrEnum):
    """Error metric for comparing source and reconstructed luma."""

    MAE = "MAE"
    MSE = "MSE"
    RMSE = "RMSE"
    SOBEL_NORMALIZED = "SOBEL_NORMALIZED"

get_descale_ranges

get_descale_ranges(candidates: Sequence[RescaleTarget], *, avg_error_thr: float, ind_error_thr: float, scene_starts: Iterable[int] | None = None, metric_mode: MetricMode | str = MetricMode.SOBEL_NORMALIZED, mask: MaskLike | None = None, borders_aware: BorderCrop | None = None, pixel_error_thr: float = 0.01, filename: str | PathLike[str] | None = None, progress: bool = True) -> list[list[tuple[int, int]]]

Find the scenes that best match each descale candidate.

Build all candidates from the same clip using RescaleBuilder (with descale() / descale_raw()) or vsscale.Rescale.
The unique candidate with the lowest mean error wins if both its mean and peak frame error meet their limits.

Example usage:

    targets = [
        RescaleBuilder(src).descale_raw(Bicubic(0, 1), 960, 540, src_width=960, src_left=-0.0625, src_top=-0.0625, src_height=540),
        RescaleBuilder(src).descale(Lanczos(3), 960, 540),
    ]

    results = get_descale_ranges(targets, avg_error_thr=0.04, ind_error_thr=0.06)

To get the final output from a list of targets, see vodesfunc.apply_ranges.

Parameters:

Name Type Description Default
candidates Sequence[RescaleTarget]

Configured RescaleBuilder or vsscale.Rescale targets, in the order that ranges should be returned.

required
avg_error_thr float

Maximum mean scene error in the selected metric's units.

required
ind_error_thr float

Maximum individual frame error in the selected metric's units.

required
scene_starts Iterable[int] | None

Zero-based scene starts. None detects cuts with SCXvid and an empty iterable uses one scene.

None
metric_mode MetricMode | str

Error metric used to compare the source and reconstructed luma. Defaults to MetricMode.SOBEL_NORMALIZED, the original descale_analysis score.

SOBEL_NORMALIZED
mask MaskLike | None

Optional per-pixel scoring mask applied to the selected metric. Pass vsmasktools.Sobel to weight edges.

None
borders_aware BorderCrop | None

Border crop used for scoring, or True to use each kernel's radius. Defaults to 10 pixels for SOBEL_NORMALIZED and 8 for other metrics.

None
pixel_error_thr float

Pixel differences at or below this value are ignored for SOBEL_NORMALIZED.

0.01
filename str | PathLike[str] | None

Save or reuse a TOML file of ranges. Relative names use the working directory. Delete the file to rerun analysis after changing the source, targets, or settings.

None
progress bool

Display a progress bar during analysis.

True

Returns:

Type Description
list[list[tuple[int, int]]]

One list of frame ranges per candidate for vstools.replace_ranges() or similar.

Source code in vodesfunc/analysis/descale.py
def get_descale_ranges(
    candidates: Sequence[RescaleTarget],
    *,
    avg_error_thr: float,
    ind_error_thr: float,
    scene_starts: Iterable[int] | None = None,
    metric_mode: MetricMode | str = MetricMode.SOBEL_NORMALIZED,
    mask: MaskLike | None = None,
    borders_aware: BorderCrop | None = None,
    pixel_error_thr: float = 0.01,
    filename: str | PathLike[str] | None = None,
    progress: bool = True,
) -> list[list[tuple[int, int]]]:
    """
    Find the scenes that best match each descale candidate.

    Build all candidates from the same clip using `RescaleBuilder` (with `descale()` / `descale_raw()`) or `vsscale.Rescale`.<br>
    The unique candidate with the lowest mean error wins if both its mean and peak frame error meet their limits.

    Example usage:
    ```py
        targets = [
            RescaleBuilder(src).descale_raw(Bicubic(0, 1), 960, 540, src_width=960, src_left=-0.0625, src_top=-0.0625, src_height=540),
            RescaleBuilder(src).descale(Lanczos(3), 960, 540),
        ]

        results = get_descale_ranges(targets, avg_error_thr=0.04, ind_error_thr=0.06)
    ```

    To get the final output from a list of targets, see `vodesfunc.apply_ranges`.

    :param candidates:      Configured `RescaleBuilder` or `vsscale.Rescale` targets, in the order that ranges should be returned.
    :param avg_error_thr:   Maximum mean scene error in the selected metric's units.
    :param ind_error_thr:   Maximum individual frame error in the selected metric's units.
    :param scene_starts:    Zero-based scene starts. None detects cuts with SCXvid and an empty iterable uses one scene.
    :param metric_mode:     Error metric used to compare the source and reconstructed luma.
                            Defaults to MetricMode.SOBEL_NORMALIZED, the original descale_analysis score.
    :param mask:            Optional per-pixel scoring mask applied to the selected metric.
                            Pass vsmasktools.Sobel to weight edges.
    :param borders_aware:   Border crop used for scoring, or True to use each kernel's radius.
                            Defaults to 10 pixels for SOBEL_NORMALIZED and 8 for other metrics.
    :param pixel_error_thr: Pixel differences at or below this value are ignored for SOBEL_NORMALIZED.
    :param filename:        Save or reuse a TOML file of ranges. Relative names use the working directory.
                            Delete the file to rerun analysis after changing the source, targets, or settings.
    :param progress:        Display a progress bar during analysis.

    :return: One list of frame ranges per candidate for `vstools.replace_ranges()` or similar.
    """
    source = _get_source(candidates[0])
    if not (avg_error_thr >= 0 and ind_error_thr >= 0):
        raise CustomValueError("Error thresholds must be nonnegative.", get_descale_ranges)

    metric_mode = MetricMode.from_param(metric_mode.upper(), (get_descale_ranges, "metric_mode"))
    use_sobel_score = metric_mode is MetricMode.SOBEL_NORMALIZED
    if use_sobel_score and (pixel_error_thr < 0 or not isfinite(pixel_error_thr)):
        raise CustomValueError("The pixel error threshold must be finite and nonnegative.", get_descale_ranges)
    if borders_aware is None:
        borders_aware = 10 if use_sobel_score else 8

    _validate_targets(candidates, get_descale_ranges)

    cache = Path(filename) if filename else None
    if cache is not None and cache.exists():
        return _load_ranges(cache, source, len(candidates), get_descale_ranges)

    luma = _get_luma(candidates[0])
    scenes: Sequence[tuple[int, int]] | None = list(pairwise(_get_scene_boundaries(source, scene_starts))) if scene_starts is not None else None
    mask_args = {}
    is_sobel_mask = mask is Sobel or type(mask) is Sobel or (isinstance(mask, str) and mask.strip().lower() == "sobel")
    if is_sobel_mask and not hasattr(vs.core, "edgemasks"):
        mask_args["use_expr"] = True
    norm_mask = normalize_mask(mask, luma, luma, func=get_descale_ranges, **mask_args) if mask is not None else None
    sobel_stats = luma.std.Sobel().std.PlaneStats(prop="Sobel") if use_sobel_score else None
    scenes, candidate_scores = _get_scene_scores(
        source, candidates, scenes, metric_mode, norm_mask, borders_aware, sobel_stats, pixel_error_thr, progress
    )

    ranges: list[list[tuple[int, int]]] = [[] for _ in candidates]
    for (start, stop), scores in zip(scenes, zip(*candidate_scores, strict=True), strict=True):
        index, (mean, peak) = min(enumerate(scores), key=lambda item: item[1][0])
        if mean <= avg_error_thr and peak <= ind_error_thr and sum(avg == mean for avg, _ in scores) == 1:
            ranges[index].append((start, stop - 1))

    ranges = [normalize_ranges(source, candidate_ranges, exclusive=False) for candidate_ranges in ranges]
    if cache is not None:
        _write_ranges(cache, candidates, ranges)
    return ranges