Skip to content

OpenReel Video - Professional browser-based video editor. Open source CapCut alternative. 100% browser-based, no installation, no cloud uploads, no watermarks.

TypeScript
5.2 KB
Raw Blame
#!/usr/bin/env python3
"""Dumps the decomposition of OpenColorIO's BuiltinTransform styles into the op schema of
packages/core/src/color/ocio/ops.ts, for the styles built only from matrices, exponents, log curves, ranges and the
fixed functions. Styles with LUT / grading-curve parts are listed with the part kinds so the analytic replacements in
builtins.ts can be matched to them. Output: JSON on stdout.

    python scripts/ocio/dump-builtins.py > builtins.json   (needs `pip install opencolorio numpy`)
    python scripts/ocio/dump-builtins.py --ts packages/core/src/color/ocio/builtins-data.ts

`--ts` writes the TypeScript table the runtime embeds: styles whose parts are in the op schema (a Lut1D part stays a
`unsupported` marker that builtins.ts replaces with an analytic curve where it has one), without the ACES 2.0 output
transform (a fixed function this runtime does not implement) and without the GradingRGBCurve based ACES 1.x output
transforms (builtins.ts evaluates those analytically).
"""
import json
import sys

import numpy as np
import PyOpenColorIO as ocio

INV = ocio.TRANSFORM_DIR_INVERSE


def rgb(v):
    return [float(x) for x in list(v)[:3]]


def op_of(t):
    inv = t.getDirection() == INV
    name = type(t).__name__
    if name == "MatrixTransform":
        m = np.array(t.getMatrix(), dtype=np.float64).reshape(4, 4)
        off = np.array(t.getOffset(), dtype=np.float64)
        m3 = m[:3, :3]
        o3 = off[:3]
        if np.any(m[:3, 3] != 0) or np.any(m[3, :3] != 0):
            raise ValueError("matrix mixes alpha")
        if inv:
            m3i = np.linalg.inv(m3)
            return {"k": "mat", "m": m3i.flatten().tolist(), "o": (-(m3i @ o3)).tolist()}
        return {"k": "mat", "m": m3.flatten().tolist(), "o": o3.tolist()}
    if name == "ExponentTransform":
        st = {ocio.NEGATIVE_CLAMP: "clamp", ocio.NEGATIVE_MIRROR: "mirror", ocio.NEGATIVE_PASS_THRU: "pass"}[t.getNegativeStyle()]
        return {"k": "exp", "g": rgb(t.getValue()), "style": st, "inv": inv}
    if name == "ExponentWithLinearTransform":
        st = {ocio.NEGATIVE_LINEAR: "linear", ocio.NEGATIVE_MIRROR: "mirror"}[t.getNegativeStyle()]
        return {"k": "explin", "g": rgb(t.getGamma()), "off": rgb(t.getOffset()), "style": st, "inv": inv}
    if name == "LogTransform":
        b = t.getBase()
        return {"k": "log", "base": b, "ls": [1, 1, 1], "lo": [0, 0, 0], "ns": [1, 1, 1], "no": [0, 0, 0], "brk": None, "lslope": None, "inv": inv}
    if name in ("LogAffineTransform", "LogCameraTransform"):
        d = {"k": "log", "base": t.getBase(), "ls": rgb(t.getLogSideSlopeValue()), "lo": rgb(t.getLogSideOffsetValue()),
             "ns": rgb(t.getLinSideSlopeValue()), "no": rgb(t.getLinSideOffsetValue()), "brk": None, "lslope": None, "inv": inv}
        if name == "LogCameraTransform":
            b = t.getLinSideBreakValue()
            d["brk"] = rgb(b) if b is not None and not any(np.isnan(x) for x in rgb(b)) else None
            try:
                s = t.getLinearSlopeValue()
                d["lslope"] = rgb(s) if s is not None and not any(np.isnan(x) for x in rgb(s)) else None
            except Exception:
                pass
        return d
    if name == "RangeTransform":
        def g(has, get):
            return float(get()) if has() else None
        return {"k": "range", "minIn": g(t.hasMinInValue, t.getMinInValue), "maxIn": g(t.hasMaxInValue, t.getMaxInValue),
                "minOut": g(t.hasMinOutValue, t.getMinOutValue), "maxOut": g(t.hasMaxOutValue, t.getMaxOutValue),
                "noclamp": t.getStyle() == ocio.RANGE_NO_CLAMP, "inv": inv}
    if name == "FixedFunctionTransform":
        style = str(t.getStyle()).split(".")[-1].replace("FIXED_FUNCTION_", "")
        return {"k": "fixed", "style": style, "params": [float(x) for x in t.getParams()], "inv": inv}
    return {"k": "unsupported", "part": name}


def main():
    reg = ocio.BuiltinTransformRegistry()
    cfg = ocio.Config.CreateRaw()
    out = {}
    for style, _desc in reg.getBuiltins():
        t = ocio.BuiltinTransform()
        t.setStyle(style)
        g = cfg.getProcessor(t).createGroupTransform()
        ops = []
        for x in g:
            try:
                ops.append(op_of(x))
            except Exception as e:  # noqa: BLE001
                ops.append({"k": "unsupported", "part": type(x).__name__, "error": str(e)})
        out[style] = ops
    if len(sys.argv) > 2 and sys.argv[1] == "--ts":
        def ok(v):
            return all(o["k"] != "unsupported" or o.get("part") == "Lut1DTransform" for o in v) and not any(o.get("style") == "ACES_OUTPUT_TRANSFORM_20" for o in v)
        keep = {k: v for k, v in out.items() if ok(v)}
        body = json.dumps(keep, separators=(",", ":"))
        with open(sys.argv[2], "w") as f:
            f.write("// Generated by scripts/ocio/dump-builtins.py from OpenColorIO %s. Do not edit.\n" % ocio.GetVersion())
            f.write("import type { Op } from \"./ops\";\n\n")
            f.write("/** OCIO BuiltinTransform style -> the ops it is made of (forward direction). */\n")
            f.write("export const BUILTIN_OPS: Readonly<Record<string, readonly Op[]>> = %s as unknown as Record<string, readonly Op[]>;\n" % body)
        return
    json.dump(out, sys.stdout, indent=None, separators=(",", ":"))


if __name__ == "__main__":
    main()