Skip to content

Latest commit

 

History

History
705 lines (612 loc) · 46.2 KB

spec.md

File metadata and controls

705 lines (612 loc) · 46.2 KB

hookdial v0.1 specification

Status: draft for review, 2026-11-28. This document fixes the behaviour of v0.1 and the interface of every module, so modules can be built and reviewed independently. Where a rule here and an implementation disagree, the implementation is wrong, or this document gets a reviewed change first.

tests/fixtures/expected.lua is part of this spec: it holds the exact params.parse() output for every fixture shader and whether each one loads on vo=gpu and vo=gpu-next.

1. What v0.1 does

hookdial is an mpv user script. For every shader in glsl-shaders it shows an on-screen list of sliders, one per tunable value, and applies changes live. It also reloads a shader when its file changes on disk.

  • //!PARAM values (float, int, uint, DEFINE, ENUM; DYNAMIC and CONSTANT qualifiers) are written to glsl-shader-opts, scoped <shader name>/<param>. No file is touched.
  • Shaders without //!PARAM get sliders for their numeric #define lines. A change writes a modified copy of the shader and swaps the copy into glsl-shaders. The original file is never written.
  • Hot reload: when switched on, edited shader files are copied and swapped in the same way.
  • Presets: save and load the values of one shader by name.
  • Errors: when a shader fails to parse or compile, the menu shows the shader name, the line in the user's file and the first line of the message.
  • Keyboard only. No mouse, no uosc, no A/B toggle, no config export (all v0.2).

2. mpv behaviour this design relies on

All verified on mpv v0.42.0-38 + libplacebo 7.391, both renderers, by live probe and by reading mpv at commit 50cc5c9d. Re-checked before every release by the integration suite.

Fact Evidence
glsl-shader-opts applies on the next frame, no reload, on both renderers, also while paused. Probe T2, T3; integration suite
Scoping name/param=value: name is the file's basename with only the last extension removed (mp_strip_ext). Case-sensitive. update_user_shader_opts (gpu/video.c), update_hook_opts (gpu_next/video.c), split_ext (misc/path_utils.c)
Entries apply in list order and the last matching entry wins; scoped and unscoped entries are treated alike. Same functions: one loop over all entries, each overwriting
Identical keys never coexist in glsl-shader-opts: setting a/x=1,b/y=2,a/x=3 reads back as b/y=2,a/x=3 (the later entry replaces the earlier and moves to the end). parse_keyvalue_list, options/m_option.c:1866-1873; checked live by the reviewer
An ENUM value may be given by name or by index. Out-of-range values are rejected with an error, not clamped. resolve_shader_enum_name, parse_shader_param_value; gpu-next matches hp->names
mpv caches shader text by path string until the renderer is destroyed. Same path = old text, even after remove + re-add. Probe T5, T6; load_cached_file, load_hook
A new path string is re-read. A copy with the same basename and a different last extension (name.hd4242x9) is re-read and still matches name/param. Probe T7–T11
Text before the first //! is skipped. A body (hook code, or text after a PARAM default) ends at the next //! anywhere, also mid-line inside a // comment, and that //! starts the next block. In a run of header lines each line must start with //! and is one whole directive, so //!DESC see //!HOOK is fine. user_shaders.c:662 (skip), :513 and :180 (bstr_split_tok), :400-403 (headers); broken_inline_directive fails and mixed loads on both
Text between a PARAM default and the next //! is ignored by vo=gpu but parsed as part of the value by libplacebo, which then rejects the shader. param_trailing_text fixture: loads on gpu, fails on gpu-next ("Failed parsing variable data")
vo=gpu accepts only float, int, DEFINE and ENUM; CONSTANT, DYNAMIC and uint make the whole shader fail. parse_param in gpu/user_shaders.c; param_constant, param_dynamic, param_uint fixtures
Names mpv fills in itself: PTS, chroma_offset_x, chroma_offset_y, min_luma, max_luma, max_cll, max_fall, scene_max_r, scene_max_g, scene_max_b, scene_avg, max_pq_y, avg_pq_y. gpu_get_auto_param (gpu/utils.c)
Compile errors arrive at level error as input:N: error: ..., followed by a dump of the generated source as [ N] text lines that includes the user's code verbatim. Parse errors on gpu-next arrive as a message, then Failed to parse user shader: and a dump of the user's file; on vo=gpu as one line with no file name. tests/fixtures/logs/*.jsonl

3. Package layout

hookdial/            the script folder users copy to ~~/scripts/ (mpv loads main.lua)
  main.lua           wiring: options, bindings, observers, timers; the only controller
  params.lua         pure: parse shader text; rewrite #define values
  opts.lua           pure: shader names, glsl-shader-opts keys and strings
  model.lua          pure: shaders, values, stepping, rows for the UI
  presets.lua        pure: preset store and fitting presets to a shader
  api.lua            pure: commands and published state for other scripts (docs/api.md)
  errors.lua         pure: turn mpv log messages into error events
  reload.lua         mpv: shader copies, glsl-shaders swaps, file polling
  ui_osd.lua         mpv: the built-in ASS overlay (its render function is pure)
tests/
  runner.lua         unit test runner, runs inside mpv (vo=null)
  unit/test_*.lua    unit tests, one file per module
  fixtures/          shaders, expected.lua, captured logs
  tools/             fixture_check.lua, census.lua, cost.lua (real renderer, local only)
docs/spec.md         this file

"Pure" means the module never touches mp, mp.utils, io or os, and keeps no global state. It takes strings and tables and returns strings and tables. Every pure module must be fully testable under tests/runner.lua with vo=null.

The script name is hookdial (from the folder name). So the options file is script-opts/hookdial.conf, bindings are script-binding hookdial/<name>, and messages go to script-message-to hookdial <name>.

4. Data flow

glsl-shaders ──read files──> params.parse ──> model ──rows──> ui_osd ──actions──> main
                                                ^                                   │
glsl-shader-opts (user's) ──opts.parse_list─────┘                                   │
                                                                                    v
             model change ──> opts.build ──> set glsl-shader-opts      (//!PARAM values)
                         └──> params.rewrite_defines ──> reload.copy + reload.swap   (#defines)
file edited ──reload poll──> reload.copy + reload.swap ──> model:reload_shader
mpv log ──errors:feed──> event ──> model:set_status ──> rows

main.lua is the only module that calls side-effecting functions of other modules. Modules do not require each other, except that model may require params and opts.

5. Module interfaces

Types used below:

  • Param: one entry of parse().params, shape as in expected.lua.
  • Define: one entry of parse().defines.
  • Entry: { key = "name/param", value = "0.5" }, one item of glsl-shader-opts.
  • Values: { params = { [name] = number|string }, defines = { [name] = number } }. ENUM params are stored by name (string); everything else as a number.

5.1 params (pure) — task 8, Claude

params.AUTO_NAMES                       -- set: { PTS = true, chroma_offset_x = true, ... }
params.parse(text) -> Result            -- never raises; problems go into Result.errors
params.rewrite_defines(text, values) -> text
params.format_number(value, is_int) -> string

parse rules:

  1. Strip a leading UTF-8 BOM. Lines end at \n; a trailing \r is removed from each line. Line numbers are 1-based in the original file. "Starts with" below means after leading whitespace is trimmed.
  2. Block structure, as in mpv (section 2): text before the first //! in the file is ignored. From there the file is a sequence of blocks. A block is a run of header lines (lines that start with //!; each whole line is one directive) followed by a body. A body ends at the next //! anywhere in the text, even mid-line; the text from that //! to the end of its line is the first header line of the next block.
  3. A PARAM block starts with the header //!PARAM <name> (name = the rest of the line, trimmed) and takes the headers that follow: DESC <text>, TYPE <type>, MINIMUM <n>, MAXIMUM <n>. Any other header in the block is unknown_directive. In the body, blank lines are skipped and the first other line is the default value. For an ENUM, every non-blank line up to the next line that starts with //! is an enum name. For other types, any non-blank text after the default and before the next //! is trailing_text.
  4. TYPE grammar: [ENUM] (DEFINE | [DYNAMIC | CONSTANT] (float | int | uint)). Result type is "float", "int", "uint" or "define"; qualifier is "dynamic", "constant" or nil. ENUM with anything but int or DEFINE is enum_type. An unknown type is bad_type. A body line reached before any TYPE is missing_type.
  5. Values: float parses as a decimal number; int, uint and define must be integers (1.5 is bad_value, as in mpv). Bounds must parse (bad_bound). A default outside its bounds is bad_value. uint without MINIMUM reports min = 0. ENUM: default = 0, min = 0, max = #enum - 1; MINIMUM and MAXIMUM are not reported (avoid them in ENUM params: vo=gpu keeps a given MINIMUM and then rejects lower indexes).
  6. A second PARAM with an existing name is duplicate and is dropped.
  7. Names in AUTO_NAMES go to auto (declaration order), not params.
  8. A PARAM block that reaches the end of the file without a default (or, for ENUM, without a name) is missing_value.
  9. Errors are { kind, line, message }. line per kind: bad_type, enum_type → the TYPE line; bad_bound → the MINIMUM or MAXIMUM line; unknown_directive → that header line; bad_value → the value line; trailing_text → the first non-blank line after the default; missing_type, missing_value, duplicate → the //!PARAM line. message is free text for people; tests compare only kind and line.
  10. After an error the param is dropped and parsing resumes at the next line that starts with //!PARAM, //!HOOK, //!TEXTURE or //!BUFFER, so every error in the file is reported (mpv stops at the first). Exception: trailing_text keeps the param, because vo=gpu loads that shader; the model treats trailing_text as an error only on gpu-next.
  11. requires_gpu_next is true if any param has a qualifier or type uint (gpu_next_reason = "params": vo=gpu rejects the file), or if the shader calls libplacebo's linearize() or delinearize() outside comments without defining a function of that name (gpu_next_reason = "builtin", gpu_next_builtin = the name: vo=gpu loads the file but the GLSL does not compile). On vo=gpu the menu shows such a shader as "needs vo=gpu-next", and mpv's errors for it are marked expected by errors and not reported again.

#define rules (collected for every shader; the model decides whether to show them):

  1. Only lines inside the body of a HOOK block count; mpv discards text before the first header and after a PARAM default, so a slider there would do nothing. A line matching ^%s*#%s*define%s+NAME where NAME is [A-Za-z_][A-Za-z0-9_]*.
  2. NAME directly followed by ( → skipped, reason macro.
  3. The rest of the line is split at the first //: the text after it, trimmed, is desc (nil if empty); the text before it, trimmed, is the value.
  4. The value must be a plain decimal number, otherwise reason expression. In regex notation: [+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?. Lua patterns have no alternation, so implement it as: split off an optional exponent with ^(.-)([eE][+-]?%d+)$, then accept the mantissa if it matches ^[+-]?%d+%.?%d*$ or ^[+-]?%.%d+$. is_int is true when there is no . and no exponent.
  5. NAME in this list (case-insensitive) → reason constant: PI, M_PI, TAU, TWO_PI, HALF_PI, E, EPS, EPSILON, FLT_EPSILON, FLT_MAX, FLT_MIN, INF, INFINITY, NAN.
  6. The same NAME on several lines with the same numeric value → one Define with all line numbers in lines. Different values, or a number on one line and an expression on another → reason conflict (reported once, at the first line).
  7. Bounds from desc: [lo, hi] gives min and max; [>lo] gives min with min_exclusive = true; [>=lo] gives min; [<hi] gives max with max_exclusive = true; [<=hi] gives max. Anything else: no bounds.
  8. skipped_defines entries are { name, reason, line }, in file order.

rewrite_defines(text, values): for each name in values that parse(text) lists as a Define, replace the value on every line in lines, keeping everything else on the line (spacing, comment) and the file's line endings. Unknown names are ignored.

format_number(v, is_int): int → string.format("%d", v) after rounding. Float → %.6g; if the result contains neither . nor e, append .0 (GLSL needs a float literal; 1 would be an int and can fail to compile).

5.2 opts (pure) — task 8, Claude

opts.shader_name(path) -> string            -- basename, last extension removed, mpv's rule
opts.key(shader_name, param_name) -> string -- "name/param"
opts.format_value(param, value) -> string   -- ENUM: the name; int/uint/define: "%d"; float: "%.9g"
opts.parse_list(str) -> { Entry }           -- from mp.get_property("glsl-shader-opts")
opts.normalize(entries) -> { Entry }        -- mpv's rule: a repeated key replaces the earlier one and moves to the end
opts.build(baseline, ours) -> string        -- for mp.set_property("glsl-shader-opts", ...)
opts.effective(baseline, shader_name, param_name) -> string|nil
opts.same(a, b) -> bool                     -- entry lists equal after normalize
  • shader_name: leading dots of the basename are skipped before looking for the last dot; a name with no extension, or ending in a dot, is returned unchanged. Both / and \ separate directories (mpv treats \ as a separator only on Windows; a Linux file name containing \ is not supported).
  • Floats use %.9g so a value clamped to a bound never prints above that bound (mpv rejects out-of-range values instead of clamping).
  • build returns normalize(baseline .. ours) joined as k=v,k=v: the user's own entries in their order, then ours. Because mpv's last match wins, our scoped values override the user's while the menu has changed them. The string form is used, not the native map, because a Lua table has no order.
  • effective returns the value mpv would use from the baseline alone: the last entry whose key is name/param or bare param.

The baseline is the user's own glsl-shader-opts, kept in hookdial's memory. main reads it at startup. Because identical keys collapse, mpv's property may not show a user entry while hookdial overrides the same key; the copy in memory is what lets a reset bring the user's value back. Before every write, and when it rebuilds, main compares parse_list(current) with the list it last wrote using opts.same; if they differ, someone else changed it, and the new baseline is the current list minus the entries hookdial last wrote (same key and value). Where one of those hid a user entry with the same key, the user's entry is carried over from the old baseline. So hookdial never writes over a change made from outside, even with the menu closed.

5.3 model (pure) — task 8, Claude

local m = model.new(config)        -- config: { defines = "auto"|"always"|"never", vo = "gpu"|"gpu-next" }
m:load(shaders, baseline)          -- shaders: { { path, source, text } }, baseline: { Entry }
m:reload_shader(i, text)           -- after hot reload; keeps values whose name and type still exist
m:rows() -> { Row }
m:step(id, direction, size) -> Change|nil     -- id = Row.id; direction -1|1; size "fine"|"normal"|"coarse"
m:set(id, value) -> Change|nil                -- typed value (number, or enum name)
m:reset(id) -> Change|nil                     -- a param row resets one value, a shader row all of them
m:values(i) -> Values                         -- current values of shader i (for presets)
m:apply(i, values) -> Change|nil              -- values already fitted by presets.fit
m:schema(i) -> { params = { [name] = Param }, defines = { [name] = Define } }
m:opts_entries() -> { Entry }                 -- every //!PARAM value that differs from its default
m:define_values(i) -> { [name] = number }|nil -- nil when shader i has no changed #define
m:set_status(i, status, message)              -- status nil | "failed" | "reloading"
m:set_pending(id, flag)                       -- marks a row pending while main debounces its recompile
model.next_selectable(rows, from, delta) -> index

path is the string in glsl-shaders (it may be a hookdial copy), source is the real file (see reload.source_of), text is its content or nil when it can't be read.

Change = { opts = bool, rewrite = shader index|nil, recompile = bool }. opts means glsl-shader-opts must be rebuilt; rewrite means that shader needs a new copy made with params.rewrite_defines; recompile means the change makes mpv recompile (CONSTANT and DEFINE params, all #defines), so main debounces it by recompile_delay.

Row, the contract every UI adapter renders:

{
  id = "1/p/gain",            -- stable across rows() calls: "<i>" shader, "<i>/p/<name>", "<i>/d/<name>", "<i>/m/<n>"
  kind = "shader" | "param" | "define" | "message",
  shader = 1,                 -- index into the loaded shader list
  name = "gain",              -- param or define name; nil for shader and message rows
  label = "gain",             -- what to display; shader rows: the shader name
  value_text = "1.00",        -- nil for shader and message rows
  fraction = 0.5,             -- 0..1 position for a bar; nil when unbounded or not a value
  desc = "Output gain",       -- may be nil
  changed = false,            -- value differs from the default
  pending = false,            -- a debounced change is waiting to be applied
  status = nil,               -- nil | "failed" | "unsupported" | "reloading" | "ambiguous"
  message = nil,              -- text for status and message rows
  selectable = true,
}

Rows come in shader order: a shader row, then its param rows (declaration order), then its define rows. Defines are shown when config.defines is "always", or "auto" and the shader has no params. A shader with parse errors, or one that needs gpu-next while vo is gpu (status "unsupported"), shows a message row instead of value rows. Two loaded shaders with the same name get status "ambiguous" (their sliders would change both). A shader whose text is nil shows a message row "cannot read ".

The "default" of a param, for changed and reset, is opts.effective(baseline, ...) when the user's own glsl-shader-opts sets it, else the shader's declared default.

Stepping:

  • Float with both bounds: normal step (max − min) / 100; fine = normal / 10; coarse = normal × 10.
  • Float with one or no bound: base = 10^(floor(log10(|default|)) − 1), or 0.01 when the default is 0; normal = base, fine = base / 10, coarse = base × 10.
  • int, uint, define, int #define: normal and fine 1; coarse max(1, round((max − min) / 10)) with both bounds, else 10.
  • ENUM: one name per step, any size.
  • decimals = min(6, max(0, -floor(log10(fine)))) (fine 0.0062832 → 3, fine 0.01 → 2, fine 1 → 0).
  • After a step, round to decimals places (avoids 0.30000000000000004), then clamp to the bounds. With min_exclusive the lowest value is min + fine; with max_exclusive the highest is max − fine.
  • value_text: floats with decimals places, ints as integers, ENUMs as their name. fraction is (value − min) / (max − min), or ENUM index / (#enum − 1); it is nil when either bound is missing, when max = min, or for a one-name ENUM.
  • vo = "gpu" ignores trailing_text errors (vo=gpu loads those shaders); on gpu-next they make the shader fail like any other parse error.

5.4 presets (pure) — task 9, Mistral agent

presets.new() -> Store
presets.from_table(tbl) -> Store, { warning }    -- from utils.parse_json output; never raises
presets.to_table(store) -> tbl                   -- ready for utils.format_json
presets.names(store, shader_name) -> { name }    -- sorted, case-insensitive
presets.get(store, shader_name, name) -> Values|nil   -- a deep copy
presets.put(store, shader_name, name, values)    -- raises on an invalid name
presets.remove(store, shader_name, name) -> bool
presets.fit(values, schema) -> Values, { skipped }

File (read and written by main at ~~/script-opts/hookdial-presets.json):

{ "version": 1,
  "presets": { "param_float": { "dim": { "params": { "gain": "0.6" }, "defines": [] } } } }
  • Keyed by shader name, so presets follow a shader that moves folders. Shader and preset names are case-sensitive keys; names sorts them case-insensitively, ties by byte order.
  • Preset names are trimmed and must be 1–64 bytes. put raises "invalid preset name" otherwise. put on an existing name overwrites it.
  • Numbers are written as strings formatted %.9g, because mpv's utils.format_json prints floats with %f and would turn 1e-7 into 0.000000. ENUM values are written as their name.
  • mpv's format_json writes an empty table as []; from_table treats an empty array as an empty map wherever a map is expected.
  • from_table: a non-table input gives an empty store with no warning (first run). A table whose version is not 1, including a missing version, gives an empty store and the warning "unsupported presets version <v>". Dropped with one warning each: a shader entry whose key is not a non-empty string or whose value is not a table; a preset whose name is invalid (as for put), whose value is not a table, or whose params or defines is present but not a table; a second preset whose name equals another after trimming; a single value that is not a string or number (the rest of its preset is kept). from_table does not know the shaders, so it keeps every string and number exactly as written (an ENUM name may look like a number); fit converts them.
  • get and remove trim the name like put. put raises with no position prefix.
  • fit(values, schema) (schema as from model:schema(i)): drops names the shader no longer has (reason = "unknown"). Numeric params and defines take a number or a string tonumber accepts; anything else, NaN and infinities are "bad_value". An ENUM takes an exact name first, then an integer (number or string) as an index; anything else is "bad_value". Integer types are rounded; numbers are clamped to the bounds, and a value that lands on an exclusive bound is "bad_value". skipped entries are { kind = "param"|"define", name, reason }, params first, each kind sorted by name.

5.5 errors (pure) — task 11, Mistral agent

local c = errors.new(shaders, clock)  -- shaders: { { name, source, text, parse } } currently loaded
                                      -- clock: function returning seconds (main passes mp.get_time);
                                      -- nil means a clock that always returns 0
c:set_shaders(shaders)
c:feed(msg) -> { Event }        -- msg = { prefix, level, text } exactly as mpv's log-message event
c:flush() -> { Event }          -- close any open dump; main calls it 100 ms after the last message
errors.format(event) -> string  -- "param_float: line 12: syntax error, unexpected RETURN, ..."

Event = { kind = "compile"|"parse", shader = name|nil, source = path|nil, line = n|nil, message }. parse in each shader entry is its params.parse() result.

Only messages at level error or fatal are looked at. Each line is classified by its exact prefix and text, in this order; anything not listed is dropped. Line texts below are shown without the trailing newline, which feed must strip.

Prefix Line Meaning
any vo/... [ N] text (regex ^%[%s*(%d+)%]%s?(.*)$) a dump line; belongs to the open dump
any vo/... Backtrace:, #<n> 0x..., blank, shaderc output:, Failed creating render pass for dispatch, Failed executing hook, disabling noise, dropped (the last two follow a gpu-next compile error)
vo/gpu-next/libplacebo, or vo/gpu/<backend> (d3d11, vulkan, opengl, …) input:N: error: <msg> starts a compile error
same shaderc compile status ..., GLSL source:, vertex shader source:, fragment shader source:, compute shader source: structure of the compile error's dump; the section headers name the dump section that follows
vo/gpu-next/libplacebo Failed to parse user shader: ends a gpu-next parse error; a dump of the user's file follows
vo/gpu-next/libplacebo any other line a candidate message for a gpu-next parse error; the first candidate since the last event is kept (Failed parsing variable data: 1.0 is followed by a continuation line, #define not_in_any_pass 2.0, which is just another candidate)
exactly vo/gpu the message formats of user_shaders.c: Unrecognized PARAM TYPE: '...'!, Missing type for param '...', Unrecognized command '...'!, Error while parsing PARAM ...!, ENUM parameter '...' ..., Missing initial parameter value!, Expected PARAM header!, Shader defines too many parameters!, Value of ... for option '<p>' out of range [...], Invalid value for option '<p>': '...', and for hooks and textures Error while parsing <HEADER>! (OFFSET, WIDTH, HEIGHT, WHEN, COMPONENTS, COMPUTE, SIZE), Error while parsing TEXTURE body: ..., Passes may only hook/bind up to N textures!, Invalid COMPONENTS: N, Unrecognized/unavailable FORMAT name: '...'! (also a format the backend lacks, e.g. rgba16f on d3d11), Unrecognized FILTER: '...'!, Unrecognized BORDER: '...'!, No FORMAT specified., The specified texture format cannot be filtered!, Shader TEXTURE size mismatch: ... a vo=gpu parse error, complete in one line

Mapping an event to a shader:

  • Compile error: take line N of the dump (on gpu-next from the fragment shader source: section, or compute shader source: for a compute pass; on vo=gpu the GLSL source: section), trim trailing space, and find a shader whose text has a line equal to it (also trimmed). Score each candidate by the run of consecutive dump lines through N that line up with consecutive lines of the shader's text. A run counts when it has at least three lines or covers a whole body (the shader lines just outside it are //! directives or the ends of the file); the longest run wins, ties go to the first shader and its first line. This keeps a line two shaders share (a return, a brace) from naming the wrong one. That gives shader, source and the user's line. No match: shader and line stay nil, the message is kept. When shaderc reports several errors before the dump, the first is kept.
  • gpu-next parse error: the shader whose lines match the dump after Failed to parse user shader:. line stays nil (libplacebo doesn't say).
  • vo=gpu parse error: no dump and no file name. If the message names a param (only Missing type for param '<p>', ENUM parameter '<p>', Value of ... for option '<p>' and Invalid value for option '<p>' do; the quoted text of Unrecognized command and Unrecognized PARAM TYPE is not a param) and exactly one loaded shader declares a param of that name, that shader. Otherwise, if exactly one loaded shader has parse errors or requires gpu-next, that shader. Otherwise nil. Value of ... out of range and Invalid value for option are also what mpv logs for a bad glsl-shader-opts value; hookdial never writes one (it clamps), so these are treated as parse errors of the shader that declares <p>.
  • An event is emitted when the dump that completes it ends: on the next line that is not a dump line, or on flush(). A gpu-next candidate message with no Failed to parse user shader: after it is not a shader error and is dropped by flush().
  • message for a compile error is the text after error: , with a leading '' : (an empty token) removed and runs of spaces collapsed: input:81: error: '' : syntax error, unexpected RETURN → syntax error, unexpected RETURN. Other messages are the line as logged, without the trailing newline.
  • errors.format(event): "<shader>: line <n>: <message>"; without a line "<shader>: <message>"; without a shader "unknown shader: <message>".
  • The same (shader, line, message) within 2 seconds of clock() is reported once: with --log-file, vo=gpu printed each parse error twice (at renderer init and again on reconfigure).
  • libplacebo logs a compile error for a given shader text only once; the same text loaded again fails without a message. main therefore keeps, per source file, the last 8 texts that failed with their messages (state.failed_text), and a swap to one of them restores its failed status instead of clearing it. The memory is dropped when current-vo switches renderer, which compiles afresh.

Tests: feeding each tests/fixtures/logs/<vo>.<fixture>.jsonl, with that fixture as the only loaded shader, then calling flush(), must produce exactly one event naming it; for broken_glsl the line is 12 on both renderers (expected.lua, compile_error_line).

Only the shaderc format (input:N:) is verified (Windows, d3d11, both renderers). OpenGL drivers print their own formats (0:N(c): error, 0(N) : error); recognise those best effort, untested until someone sends a log. The compute-pass dump header is unverified.

main subscribes with mp.enable_messages("error") and the log-message event, feeds only vo/... prefixes, and calls flush() 100 ms after the last one.

5.6 reload (mpv) — task 8, Claude

local r = reload.new({ mp = mp, utils = utils, dir = path, session = pid, interval = s })
                                    -- dir nil or "" = reload.temp_dir(); interval = poll_interval
r:read(path) -> text|nil            -- whole file, after expand-path (~~ etc.)
r:copy(source, text) -> path|nil, err  -- <dir>/<basename without ext>.hd<session>x<hash>; written
                                    -- even when it exists, to refresh its time for cleanup
r:swap(index, path, old) -> bool    -- replaces entry index of glsl-shaders with path; when old is
                                    -- given and entry index is not old, the entry equal to old;
                                    -- false when there is none. A copy that leaves the list is deleted.
r:prune() -> n                      -- delete copies not in glsl-shaders now (a failed swap, or
                                    -- an outside change dropped them); main calls it on every
                                    -- glsl-shaders change
r:ensure_dir(dir) -> true | false, err  -- create dir and missing parents (subprocess mkdir:
                                    -- mpv's Lua has no mkdir); main uses it for ~~/script-opts
r:list_shaders(dir) -> { rel }      -- .glsl and .hook files in dir and its direct subfolders,
                                    -- relative ("sub/x.glsl"), hidden ones skipped, sorted
                                    -- without case; {} when dir can't be read (the picker)
reload.is_absolute(path) -> bool    -- false for the relative path expand-path gives ~~ under --no-config
r:caused(list) -> bool              -- list is one of the last 8 lists swap set
r:source_of(path) -> path           -- the real file behind a hookdial copy; identity otherwise
r:is_ours(path) -> bool
r:watch(sources, on_change)         -- sources = { { source, text } }; poll every interval; on_change(i, text)
r:poll()                            -- one polling step (the timer calls it; tests call it directly)
r:loaded(i, text)                   -- the text last loaded for watched entry i (after a forced reload)
r:is_watching() -> bool
r:unwatch()
r:cleanup()                         -- delete this session's copies, and others older than 24 h
  • Copies keep the shader's name: param_float.glsl becomes <dir>/param_float.hd4242x6ac127ad0897ad23 (4242 = mpv's pid, then 16 hex digits hashed from the source path and the copy's text). mpv's scoping strips the last extension, so param_float/gain still applies (probe T9–T11).
  • The name is content-addressed because mpv on gpu-next keeps memory for every distinct shader text (about 135 KB) and every distinct path (about 45 KB) it has loaded, until it quits; measured on mpv 0.42. A name per change made a long #define drag grow the player without bound. The same values now give the same path and text, which cost nothing the second time, and #define floats are rounded to their fine step, so the set of texts is finite. The hash is two 32-bit rolling hashes in plain arithmetic, exact in doubles on Lua 5.1, 5.2 and LuaJIT.
  • dir is the system temp folder (TEMP, TMP or TMPDIR, else /tmp), used flat, so no directory is created (mpv's Lua API has no mkdir). Option copy_dir overrides it with an existing folder. cleanup deletes only files matching %.hd%d+x%x+$ (old x<gen> names match too).
  • The copy keeps every other byte of the shader, so line numbers in errors still match the user's file.
  • swap sets the whole list with mp.set_property_native("glsl-shaders", list) and records it, so main can ignore the property change it caused.
  • Polling: compare utils.file_info(source) mtime and size with the last seen pair. On a change, wait for one more poll with the same pair (editors write in steps), then read the file; if the text equals the text last loaded, do nothing. A missing file (mid atomic save) is skipped for that poll.
  • Limitations, documented in the README: two saves within one second with the same size are missed; mpv keeps every generation's text in memory until the renderer is destroyed (a few KB per reload); user keybindings that toggle a shader by its original path stop matching once hookdial has swapped in a copy.

5.7 UI adapter contract and ui_osd — task 10, Mistral agent

Every adapter (ui_osd now, ui_uosc in v0.2) has the same interface:

local ui = adapter.new({ mp = mp, options = opts, on_action = function(action) end })
ui:open(view)
ui:update(view)       -- full view; adapters may diff internally
ui:close()
ui:is_open() -> bool

view = { title = "hookdial", rows = { Row }, selected = index, footer = "string" }.

Actions sent to on_action:

{ type = "move", delta = 1 }      -- -1/1 arrows, ±max_rows PgUp/PgDn, ±math.huge Home/End
{ type = "adjust", direction = 1, size = "normal" }   -- Left/Right; Shift = coarse; Ctrl = fine
{ type = "reset" }                -- r
{ type = "reset_shader" }         -- R
{ type = "enter_value" }          -- Enter: main asks for an exact value with mp.input.get
{ type = "preset_save" }          -- s
{ type = "preset_load" }          -- l
{ type = "preset_delete" }        -- d
{ type = "toggle_watch" }         -- w
{ type = "change_shader" }        -- c: pick a shader to replace the selected row's shader
{ type = "add_shader" }           -- a: pick a shader to add after the others
{ type = "remove_shader" }        -- x: remove the selected row's shader from glsl-shaders
{ type = "close" }                -- Esc

The adapter owns input while open: it adds these as forced key bindings on open and removes all of them on close. Only the arrow keys, PgUp and PgDn repeat when held.

  • The adapter never changes state itself. Esc only sends close; main then calls ui:close(). Selection is owned by main, which moves it with model.next_selectable and calls update.
  • Exact values and presets go through mpv's console, not the adapter: for enter_value, preset_save, preset_load and preset_delete, main calls ui:close(), asks with mp.input.get (a value or a preset name) or mp.input.select (pick a preset to load or delete), applies the result, and calls ui:open(view) again when the console closes, whether it was submitted or cancelled. change_shader and add_shader work the same way with mp.input.select over r:list_shaders(shader_dir).

ui_osd specifics:

ui_osd.render(view, layout) -> string      -- pure: the ASS text; layout = { width, height, font_size, max_rows, first }
ui_osd.window(count, selected, max_rows, first) -> first, last   -- pure: visible row range
  • Scrolling: window keeps the previous first (nil on open) unless the selection falls outside first .. first + max_rows - 1; then it scrolls by the smallest amount that brings the selection back in. On open, the selection is placed as close to the top as the list allows. first is always clamped so the window never runs past the end of the list (after the list shrinks, too). With no rows, window returns 1, 0. The adapter stores the returned first and passes it to the next call.

  • One mp.create_osd_overlay("ass-events") overlay. It is laid out in a space 720 lines high (res_y = 720, res_x = 720 * w / h from osd-dimensions), so font_size means "at 720p" and libass scales it to the window; re-rendered on resize. When the OSD has no size yet (w or h is 0, as with vo=null) it uses 1280x720.

  • Panel at the left edge, semi-transparent background, rows scrolled so the selection stays visible. Param and define rows: label, a bar showing fraction (no bar when nil), value text. Changed values in an accent colour, pending values dimmed, status rows in a warning colour. Under the list: the selected row's desc, the key hints and view.footer. Text that would not fit (estimated by ui_osd.measure, since libass gives scripts no font metrics) is shortened with an ellipsis by ui_osd.fit, and \clip to the panel stays as a backstop; labels stop before the bar. A shader row followed by a message row of the same shader does not repeat the message.

  • All text passes through an ASS escape: { and } get a backslash, newlines become \N, and a backslash is followed by U+2060 WORD JOINER as mpv's escape-ass does (ASS has no backslash escape, so C:\new would otherwise read as a line break).

5.8 main — task 8, Claude

Bindings (remappable in input.conf):

Binding Default key Does
hookdial/toggle Alt+h open or close the menu
hookdial/watch none switch hot reload on or off
hookdial/reload none reload all shaders now
hookdial/pick none pick one shader from shader_dir to replace every loaded one, or "(no shader)"; the menu stays closed

Alt+h is unbound in mpv's default input.conf and built-in scripts (checked at 50cc5c9d).

Script messages: toggle, open, close, reload, watch on|off|toggle, plus the API commands in section 5.9. The property user-data/hookdial/open is true while the menu holds the keyboard, else false.

Options (script-opts/hookdial.conf):

Option Default Meaning
watch no start with hot reload on
poll_interval 0.5 seconds between file checks
recompile_delay 0.15 debounce for changes that recompile
defines auto auto, always or never show #define sliders
copy_dir (empty) existing folder for shader copies; empty = system temp
shader_dir ~~/shaders folder the picker lists (and its direct subfolders)
font_size 22 overlay font size at 720p
max_rows 18 rows visible before scrolling

Behaviour:

  • The menu reads shader files when it opens and when glsl-shaders changes from outside; nothing is read while the menu is closed and hot reload is off.
  • current-vo is observed; a change rebuilds the model with the new vo.
  • After any opts change, glsl-shader-opts is set once to opts.build(baseline, m:opts_entries()).
  • Debounced changes are coalesced per shader: the last value wins.
  • Presets file writes: write <file>.tmp, remove the old file, rename (Windows can't rename over an existing file).
  • The picker puts <shader_dir>/<rel> into glsl-shaders as written (so ~~ stays), and marks files already loaded (compared after expand-path, made absolute against the working folder, without case on Windows). change_shader replaces the entry in place, so a chain keeps its order; with no shader loaded it adds. It finds the entry again by path when the console closes, since the list may have changed meanwhile. Pending values are applied before the list is read (applying a #define swaps in a new copy and deletes the old one, so an earlier read could name a deleted file). After setting the list, main rebuilds at once (so the menu reopens on the new shaders) and selects the new shader's row; the glsl-shaders observer skips its rebuild when the model already matches the list. Values changed on a replaced shader are not carried to the new one (values are kept by source file).
  • On shutdown: r:cleanup(). hookdial does not put original paths back into glsl-shaders, because mpv would serve their cached old text.
  • Values survive a rebuild (menu reopened, list or renderer changed): before rebuilding, main keeps the values that differ from their default, per source file, and re-applies them through presets.fit, except params whose value in the user's own glsl-shader-opts changed since. A shader that leaves the list loses its values. Turning watch on and reload rebuild first when glsl-shaders changed while nothing tracked it.
  • reload.caused consumes the list it matches and older ones, so a toggle that recreates an earlier list is seen as a change from outside. Error statuses are kept per source file and cleared when that shader is swapped.
  • vo/... error messages logged before the first load (up to 2000) are kept and fed to the collector right after it, so errors from mpv's start show on the right shader. Later events with no shader show in the footer.

5.9 api (pure) — task 20, Claude

The user-facing contract is docs/api.md; this section is the module interface.

api.VERSION                    -- 1; published as user-data/hookdial/api_version
api.parse(op, args)            -> cmd | nil, message
api.find_shader(m, ref)        -> index | nil, message   (name or 1-based index)
api.value_id(m, i, name)       -> row id | nil, message  (param first; "p/" or "d/" picks)
api.snapshot(m, files)         -> array for user-data/hookdial/shaders
model:describe(i)              -> every value of shader i, params and #defines, ENUMs by name;
                                  a #define's type is "int" when is_int, else "float"

main registers one script message per command in api.parse, runs it against the model (rebuilding first when glsl-shaders is stale) and logs a warning for anything invalid. Value changes go through the same handle path as the menu, so debouncing, copies and glsl-shader-opts behave identically. Preset commands share save_preset, load_preset and delete_preset with the menu.

  • publish on sets state.publishing; from then on the model is kept current like with the menu open (the glsl-shaders, current-vo and glsl-shader-opts observers rebuild) and every refresh() and rebuild() sets user-data/hookdial/shaders. publish off deletes the property.
  • user-data/hookdial/watching is set on every watch change; last_error on every error event that is not expected.

6. Files hookdial writes

File When
<temp>/<name>.hd<pid>x<hash> each new set of #define values and each hot reload; deleted on exit
~~/script-opts/hookdial-presets.json on preset save or delete

It never writes the user's shader files or mpv.conf.

7. Testing

  • Unit tests: tests/run.ps1 or tests/run.sh (both run mpv with vo=null, and first check that a failing test exits 1). One tests/unit/test_<module>.lua per module.
  • Pure modules' tests use the fixtures through t.fixture(); params tests compare params.parse() with expected.lua for every fixture (errors compared by kind and line).
  • tests/tools/fixture_check.lua re-checks the loads column against a real renderer and can re-capture the logs (fixture_check-write_logs=yes). Run it on both renderers before a release and after updating mpv.
  • tests/tools/cost.lua (run by cost.ps1) measures each shader in a folder with mpv's vo-passes timers: the frame's GPU time with the shader minus without it, and the shader's own passes, in a shrinking and an enlarging scenario. Timings are for the GPU it ran on.
  • The integration suite (tests/integration/run.ps1 or run.sh, task 12) runs the real script on vo=gpu-next and vo=gpu against a flat grey frame (lavfi color), drives it with script messages and key presses, and reads the centre pixel of a screenshot-raw video (which includes glsl-shaders). It checks live //!PARAM values, the user's own glsl-shader-opts as default and reset, a paused redraw, #define copies, hot reload, a compile error's line, CONSTANT recompiles (gpu-next) and that no copies are left after exit. It needs a GPU and a desktop session, so it runs locally before each release and after updating mpv, not in CI.

8. Rules for contributors and agents

  • Lua 5.1 subset (mpv may be built with Lua 5.1 or LuaJIT): no goto, no integer division //, no bitwise operators, no table.unpack (use unpack).
  • Every module is local M = {} ... return M; no globals. luacheck config is in the repo.
  • Pure modules never require mp. Tests must not depend on a GPU.
  • Only touch the files your task names. Open a pull request; never push to main.
  • A change to an interface in section 5 updates this document in the same pull request.

9. Open questions

  • Answered: a glsl-shader-opts change and a glsl-shaders swap (a #define copy or a hot reload) both redraw the frame while paused, on both renderers (VOCTRL_UPDATE_RENDER_OPTS sets want_redraw, vo_gpu.c and vo_gpu_next.c; the integration suite sees vo-passes change with the menu closed after a flat idle baseline). main forces no redraw.
  • Shaders that load on one renderer but not the other: v0.1 shows the error, plus "needs vo=gpu-next" from the model. A hint to switch renderer is a v0.2 idea.
  • OpenGL driver error formats (section 5.5) need real logs from Linux or macOS users.