Fix invisible/flashing clock, map Protect's 8-camera preset, warn on gaps

Three separate faults made cameras "not load" and the clock misbehave.

Clock rendered as nothing, or flashed ~200ms/second. The time was drawn as
an ASS osd-overlay pushed over mpv IPC, but on mpv 0.35 + Mesa/V3D + sway an
OSD overlay is rendered only on the frame where its content *changes*. Every
layer reports success while this happens (mpv returns error:success,
vo-configured is true, and sway reports the window visible at the right
rect), so it looks like a stacking or font bug and is neither. Ruled out:
pushing at 20Hz (identical content is ignored, so it still only redrew when
the second flipped), osd-msg1, show-text, and --pause (mpv stops redrawing
entirely). Fonts were never the issue.

The time is now baked into every frame by a drawtext filter re-reading a
small file the ticker rewrites once a second, with two constraints that cost
real time to find and are pinned by tests:

- The canvas alpha must be > 0. A fully transparent canvas (black@0.0 with
  --alpha=yes) makes the glyphs inherit alpha 0 and the compositor draws
  nothing -- this was the original invisible clock. New clock
  background_opacity (default 0.45) is clamped in config *and* in args() so
  no code path can produce an invisible clock.
- Readahead must be off. drawtext stamps the time when a frame is
  *generated*, so buffering ahead makes the visible clock lag by the
  readahead and swallows text-file updates entirely.

Since the text now arrives through a file, the clock needs no IPC socket:
dropped --input-ipc-server, the ipcPath field, and the stale-socket removal.
assEscape goes with the ASS path.

`views import` produced layouts with holes. viewmap derived the grid from
the slot count alone and ignored Protect's `layout` field, so Protect's
asymmetric 8-camera preset (four 2x2 tiles plus a right column of four 1x1)
landed as 8 tiles in a 3x3 grid -- the bottom-right cell was simply empty
and rendered as a blank rectangle. That preset is now mapped exactly; other
counts keep the uniform GridForSlots fallback rather than guessing at
presets I have not observed. Import also warns when a mapping would leave
empty cells or references a camera missing from the config, so a silent hole
cannot reach the screen again.

Also:

- clock.corner gains bottom-center and top-center (centered horizontally,
  Margin still applies vertically).
- placeClock no longer re-issues `resize set` every tick. Re-asserting
  geometry on a correctly-sized window makes sway send a configure event,
  which makes mpv reallocate buffers and blank for a frame. New
  compositor.Raise re-asserts z-order only, which is all the 2s tick needs;
  geometry is re-placed only when it has actually drifted.
- README documents why the clock is drawn this way, the preset table and how
  to add another from `views dump`, and three troubleshooting entries for
  failure modes that all look like bugs: a blank tile whose mpv is running
  (a stale camera entry -- re-adopting a camera in Protect assigns a new id
  and often a slightly different name, and `discover` never prunes), cameras
  in `cameras:` not being on screen (only the active layout's tiles stream),
  and black bars inside tiles (non-16:9 grid cells; --panscan=1.0 crops to
  fill instead).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LYhTnkp7VzJ67THeicgfAQ
This commit is contained in:
Levi Woodard
2026-07-29 12:17:20 -06:00
parent caed091dc2
commit 81193f524c
10 changed files with 562 additions and 80 deletions

View File

@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"time"
@@ -15,18 +16,27 @@ import (
)
// Clock is a small always-on-top mpv window that renders the current local
// time. The window plays a fully transparent lavfi canvas (so the camera video
// shows through) and the time is drawn as an ASS overlay pushed over mpv's IPC
// once a second: white glyphs with a black outline, which stay legible over
// both bright (day) and dark (night) scenes without sampling the picture. The
// time is formatted in Go against a fixed timezone, so it does not depend on
// the host clock's zone and gets DST right.
// time: white glyphs with a black outline, which stay legible over both bright
// (day) and dark (night) scenes without sampling the picture. The time is
// formatted in Go against a fixed timezone, so it does not depend on the host
// clock's zone and gets DST right.
//
// The text is baked into the canvas by an ffmpeg drawtext filter reading
// textPath, which the ticker rewrites once a second (drawtext's reload=1 re-reads
// the file every frame). It is deliberately NOT drawn as an mpv OSD overlay:
// on mpv 0.35 + Mesa/V3D + sway, osd-overlay renders only on the single frame
// where its content changes, so an IPC-pushed clock appears for ~200ms a second
// and reads as a flashing clock. Baking the text into every frame is stable.
//
// Because the text is rendered when a frame is *generated*, the canvas must not
// be buffered ahead of display or the visible time lags — see args() for the
// cache flags that keep generation just-in-time.
type Clock struct {
cfg config.Clock
loc *time.Location
runDir string
ipcPath string
log *slog.Logger
cfg config.Clock
loc *time.Location
runDir string
textPath string
log *slog.Logger
mu sync.Mutex
cmd *exec.Cmd
@@ -39,13 +49,35 @@ func NewClock(cfg config.Clock, runDir string, log *slog.Logger) (*Clock, error)
if err != nil {
return nil, fmt.Errorf("clock timezone %q: %w", cfg.Timezone, err)
}
return &Clock{
cfg: cfg,
loc: loc,
runDir: runDir,
ipcPath: filepath.Join(runDir, "mpv-clock.sock"),
log: log.With("comp", "clock"),
}, nil
textPath := filepath.Join(runDir, "clock-text.txt")
// A ':' or '\' in the path would be read as filtergraph syntax and break the
// drawtext option rather than pointing at the file.
if strings.ContainsAny(textPath, `:\`) {
return nil, fmt.Errorf("clock text path %q contains a character that cannot be escaped in a filtergraph", textPath)
}
c := &Clock{
cfg: cfg,
loc: loc,
runDir: runDir,
textPath: textPath,
log: log.With("comp", "clock"),
}
// drawtext fails to initialise if the file is missing, which would take the
// whole window down, so seed it before mpv ever starts.
if err := c.writeText(); err != nil {
return nil, fmt.Errorf("seeding clock text: %w", err)
}
return c, nil
}
// writeText renders the current time and replaces textPath atomically, so
// drawtext never reads a half-written file.
func (c *Clock) writeText() error {
tmp := c.textPath + ".tmp"
if err := os.WriteFile(tmp, []byte(time.Now().In(c.loc).Format(c.cfg.Format)), 0o644); err != nil {
return err
}
return os.Rename(tmp, c.textPath)
}
// Title is the window title, so the compositor can match the clock by title.
@@ -62,12 +94,31 @@ func (c *Clock) PID() int {
}
func (c *Clock) args() []string {
// A transparent RGBA canvas at a few fps; the text is drawn via osd-overlay,
// so nothing needs to be escaped into the filtergraph. --alpha=yes lets the
// transparent areas composite over the camera windows behind it (if the
// compositor can't do alpha, the canvas is black and the outlined white
// text is still perfectly readable — it just gains a dark backing).
src := fmt.Sprintf("av://lavfi:color=c=black@0.0:s=%dx%d:r=4,format=rgba", c.cfg.Width, c.cfg.Height)
// A mostly-transparent RGBA canvas at a few fps; the text is drawn via
// osd-overlay, so nothing needs to be escaped into the filtergraph.
// --alpha=yes lets the canvas composite over the camera windows behind it.
//
// The canvas alpha must stay > 0. mpv blends the OSD into the canvas, and
// on a fully transparent one the text inherits alpha 0, so the compositor
// draws nothing at all and the clock silently vanishes (observed on
// Mesa/V3D + sway). BackgroundOpacity is clamped to a non-zero default in
// config; the dark backing it produces also keeps the white text legible
// against bright daytime scenes.
// Clamped here too, not just in config, so a Clock built by any other path
// still cannot render itself invisible.
opacity := c.cfg.BackgroundOpacity
if opacity <= 0 {
opacity = 0.45
} else if opacity > 1 {
opacity = 1
}
// borderw draws the black outline that keeps white glyphs readable against a
// bright scene; the text is centred on the canvas.
src := fmt.Sprintf(
"av://lavfi:color=c=black@%.3f:s=%dx%d:r=4,format=rgba,"+
"drawtext=textfile=%s:reload=1:fontsize=%d:fontcolor=white:"+
"borderw=3:bordercolor=black:x=(w-text_w)/2:y=(h-text_h)/2",
opacity, c.cfg.Width, c.cfg.Height, c.textPath, c.cfg.FontSize)
return []string{
"--no-config",
"--force-window=yes",
@@ -83,15 +134,23 @@ func (c *Clock) args() []string {
"--no-audio",
"--keepaspect=no",
"--alpha=yes",
// drawtext stamps the time when a frame is GENERATED, so any readahead
// shows a stale clock (buffering a few seconds ahead made the displayed
// time lag by that much and swallowed text updates entirely). Keep
// generation just-in-time.
"--cache=no",
"--demuxer-readahead-secs=0",
"--demuxer-max-bytes=64KiB",
"--profile=low-latency",
"--title=" + c.Title(),
"--input-ipc-server=" + c.ipcPath,
fmt.Sprintf("--geometry=%dx%d", c.cfg.Width, c.cfg.Height),
src,
}
}
// start launches the clock mpv. It needs no IPC socket: the time reaches the
// window through textPath, which drawtext re-reads every frame.
func (c *Clock) start(ctx context.Context) error {
_ = os.Remove(c.ipcPath)
cmd := exec.CommandContext(ctx, "mpv", c.args()...)
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
cmd.WaitDelay = 2 * time.Second
@@ -162,30 +221,11 @@ func (c *Clock) tick(ctx context.Context, done <-chan struct{}) {
}
}
// push renders the current time as ASS and sends it as an OSD overlay. an5
// centers it in the window; \bord gives the black outline, \1c/\3c set the
// white fill and black outline colors (ASS is &HBBGGRR&).
// push publishes the current time for the drawtext filter to pick up on its
// next frame. Failures are logged at warn, not debug: a clock that stops
// updating is silently wrong, which is worse than one that is visibly absent.
func (c *Clock) push() {
text := assEscape(time.Now().In(c.loc).Format(c.cfg.Format))
data := fmt.Sprintf(
`{\an5\fs%d\bord3\shad1\1c&HFFFFFF&\3c&H000000&\4c&H000000&\b1}%s`,
c.cfg.FontSize, text,
)
if _, err := ipcCommand(c.ipcPath, "osd-overlay", 1, "ass-events", data, 0, c.cfg.Height, 0, false, false); err != nil {
c.log.Debug("clock overlay update failed", "err", err)
if err := c.writeText(); err != nil {
c.log.Warn("clock text update failed", "path", c.textPath, "err", err)
}
}
// assEscape drops the few characters that are special in ASS override text, so
// an unusual time format string can't break rendering. These never appear in a
// rendered time, so dropping them is harmless.
func assEscape(s string) string {
r := make([]rune, 0, len(s))
for _, ch := range s {
if ch == '{' || ch == '}' || ch == '\\' {
continue
}
r = append(r, ch)
}
return string(r)
}