Skip to content

ALI-2358: GPU helper plays sound and says the file's tags - #3

Merged
michaelaguiar merged 41 commits into
mainfrom
ali-2358-gpu-media
Dec 2, 2026
Merged

michaelaguiar merged 41 commits into
mainfrom
ali-2358-gpu-media

Conversation

@michaelaguiar

Copy link
Copy Markdown
Member

Part of ALI-2358: Alias View plays video and music. This is stacked on #2, the GPU helper. It adds the two things the player UI needs from the helper: sound, and the file's tags for the music view.

What changes

  • Sound in the GPU jail. jail::gpu_arguments takes a third argument: sound_socket: Option<&Path>. With Some(jail::sound_socket()), the session's PulseAudio socket ($XDG_RUNTIME_DIR/pulse/native) is bound read-only at /sound-server, and PULSE_SERVER points at it. That's exactly what the CPU helper does. Use it with Audio::Pulse, which still plays through PipeWire (pipewire-pulse). The examples pass None and stay silent.
  • The file's tags. Once a file has loaded, the helper sends meta title …, meta artist … and meta album …, one message per tag the file has. parse_said returns Said::Meta(MetaField, String).
  • gpu_helper::clean_meta cleans every tag. The helper runs it before sending and parse_said runs it again, so the app never trusts the helper's cleaning. It:
    • removes control characters (Cc);
    • removes the bidirectional marks, overrides and isolates: U+061C, U+200E, U+200F, U+202A–U+202E, U+2066–U+2069;
    • removes U+2028, U+2029 and U+FEFF;
    • collapses runs of white space into one space and trims;
    • cuts the tag to 160 bytes (META_MAX) at a character boundary, so a message stays well inside the 256-byte packet.

Security

  • PipeWire's own socket (pipewire-0) is never bound. PipeWire's access module only limits clients it recognises as Flatpak, so a jailed client on that socket would reach the whole graph, screen casts and cameras included. Through pulse/native it reaches sound only.
  • Known limit, shared with the CPU helper: a client of the Pulse socket can record from the microphone. A hijacked helper could do that with sound on, as the CPU helper already can (see the note at the top of jail.rs). This PR adds no new access beyond what the software path has.
  • Nothing from ALI-2358 prototype: a jailed GPU helper that hands frames over as dmabufs #2's hardening is loosened. --disable-userns, the seccomp refusals, Landlock and the NVIDIA-only /proc are unchanged, and a test checks that --disable-userns and the jail's end are still there when sound is on.
  • Tags are the file's own text: hostile input. Both ends clean them, and the tests cover the caps, control characters and every bidi character listed.

Tests

  • tags_are_said_cleaned, control_and_bidi_characters_are_stripped, tags_are_capped_at_a_character_edge;
  • only_nvidia_gets_proc_and_its_devices now also covers the sound bind for every vendor.

cargo clippy --all-targets -D warnings and cargo test --lib pass.

Live check, still to do: sound from inside the GPU jail under Landlock and seccomp, against a private PulseAudio or PipeWire server with a null sink only, through Alias View's player.

After #2 merges

Retarget this PR's base to main.

One crate for Alias View, Gannet and Nitrate to play through libmpv:

- Player: libmpv opened at run time, the shared options, commands, and
  events for position, duration, pause, volume, mute, end and failure.
- SwRender and GlRender: libmpv's CPU and OpenGL render APIs.
- options::colour: the colour settings for each render path in one
  place. The CPU path keeps Gannet's BT.1886 relabel (ALI-2418).
- helper and jail: Gannet's jailed CPU player, with frames in shared
  memory, moved here so any app can use it.

Every app stops on a video's last frame instead of closing. Hardware
decoding tries NVDEC, VA-API and V4L2 by name. VDPAU is left out because
it stalls on H.264 4:4:4 on NVIDIA.

The colour tests play 51 clips of solid patches, made from Y'CbCr worked
out from source RGB and encoded losslessly. The clips cover range,
matrix, transfer tag, bit depth, chroma and codec. CI runs them on the CPU
renderer, and examples/colour-gpu.rs runs them on a graphics card.
- jail::own_exe no longer falls back to /proc/self/exe. bubblewrap resolves
  that path in its own process and binds itself, so a video opened after the
  app's file was removed ran bwrap as the helper and failed as a jail error.
  It now fails plainly instead.
- ordered-chapters and access-references are off. A Matroska file could
  otherwise make an unjailed player read other files for its chapters, and
  a playlist could name anything.
- When a file closes, the position and duration go back to 0 rather than
  keeping the last file's values (new helper test, which fails without
  this change).
- GlRender can't move between threads. Dropping it frees libmpv's GL state,
  which needs its context current.
- watch stops the player when try_wait fails, as its documentation says.
- start's documentation says the player dies with the thread that started it.
- The GPU bench skips a case only when the machine's encoder can't make it.
  A missing FFmpeg or a clip that fails its check is now a failure.
- The CPU colour setting's comment covers full-range video with no
  transfer tag too.
- The unused rustix process feature is removed.
- When a file closes, the end also goes back to not reached (Ended(false)),
  as the position and duration already do. Before, an app that had shown
  "ended" kept showing it with nothing loaded. The helper test now checks it,
  and fails without this.
- Player::load always passes a path libmpv reads as a file: a relative one
  gets "./" in front. A relative path shaped like "http://host/x" or
  "edl://..." would otherwise be fetched or built by libmpv.
A jailed helper draws with libmpv's OpenGL renderer into GBM buffers on the
compositor's card and passes their dmabufs to the app over a SOCK_SEQPACKET
socket. The buffers use layouts OpenGL can draw into, which EGL reports.
Hardware decoding gets the render node (VA-API) or CUDA (NVDEC).

The GPU jail adds the card's device files and /sys. On NVIDIA it also adds
/proc, which CUDA needs. Landlock then refuses opening anything outside /dev
for writing, so /proc/self/mem can't change code.

examples/gpu-play plays a file through the helper and prints frames, first
frame, dropped frames, CPU and memory. Prototype for ALI-2358; not for
merging as it is.
examples/gpu-show opens a window and attaches each frame's dmabuf with
linux-dmabuf. When the compositor releases a buffer, it goes back to the
helper. It measures what gpu-play does, end to end, for comparison with
mpv's own window in the same private headless weston.
The card's maker is read from /sys for the compositor's render node:
- NVIDIA decodes with NVDEC and gets its device files and /proc;
- AMD and Intel decode with VA-API on the render node;
- Apple and others try V4L2;
- every maker falls back to the CPU.
No maker gets another's devices.

On NVIDIA, /proc is a fresh one for the jail's own PID namespace.
lock_down_gpu_helper adds two locks on top: Landlock (writes only under /dev)
and a seccomp filter that refuses ptrace, process_vm_readv/writev,
pidfd_getfd and kcmp with EPERM. Tests show /proc/self/mem, ptrace and
process_vm_writev are refused, and that only NVIDIA gets /proc.

The GPU colour bench decodes the same way, for the card it runs on.
…y early

- lock_down now runs before the helper has any other thread. Landlock
  applies only to the thread that turns it on and the ones it starts
  later, and libmpv and the drivers start threads of their own.
- The seccomp filter is synced to every thread (TSYNC), like Gannet's.
- libmpv starts on its own thread while OpenGL starts on the card.
- The buffers are made when the video's size is known, before its first
  frame, so making them doesn't delay that frame.
- The player stays paused until the first frame is drawn, then plays.
- Each frame sent counts as presented (report_swap), for libmpv's timing.
Each clip also goes through the jailed GPU helper, with and without the
card's hardware decoding. Its first frame is read back from the dmabuf on
this side, as Alias View will show it. The bench checks it against the
source colours like every other path.
…lost

The end of a video was reported before that loop drew its last frame. The
measuring apps stop at the end, so they missed the final frame (149 of 150
at 4K). The frame now goes first.
- The jail points /lib64 at /usr/lib64 where a system has it (Debian, Fedora),
  not only at /usr/lib (Arch).
- The jail includes /etc/alternatives, which Debian's libraries link through
  (libmpv needs libblas there).
- Landlock is required only when the jail has /proc (NVIDIA). Proxmox's kernel
  has no Landlock. The seccomp filter is still required.
- GBM buffers with a second plane (Intel's compressed CCS layouts) are skipped,
  and GBM is asked again.
- gpu-play says how the helper ended when it ends before the clip does.
# Conflicts:
#	.github/workflows/ci.yml
#	Cargo.lock
#	Cargo.toml
#	examples/colour-gpu.rs
#	src/ffi.rs
#	src/helper.rs
#	src/jail.rs
#	src/lib.rs
#	src/options.rs
#	src/render.rs
A helper that has been taken over could make a user namespace inside the
jail, get privileges back there, and mount a procfs of its own to reach
/proc/self/mem, even with no /proc granted. The GPU jail now runs with
bubblewrap's --unshare-user --disable-userns. The helper's seccomp filter
also refuses mount, umount2, unshare, setns and pivot_root, as Gannet's
player filter does.

New tests show both refusals, and each fails without its change:
- unshare --user fails inside the jail but works outside it;
- unshare and mount return EPERM under the filter.
NVDEC still plays inside the jail.
- jail::gpu_arguments takes the sound socket, bound read-only as for the CPU helper. Use
  it with Audio::Pulse. PipeWire's own socket is never bound.
- The player says the file's title, artist and album once it has loaded, as meta messages.
  gpu_helper::clean_meta takes out control characters and bidirectional overrides, isolates
  and marks, and cuts each tag to 160 bytes. parse_said cleans them again on the app's side.
A jailed helper can't write a log file anywhere. With debug (gpu_helper::
start's new flag, GPU_PLAY_DEBUG=1 in gpu-play), it sends libmpv's log lines
as log messages. It also reports how long OpenGL, libmpv and libmpv's
renderer took to start, and the average time to finish a frame. Player gains
on_log for the log lines.
bubblewrap's --disable-userns writes /proc/sys/user/max_user_namespaces,
which is read-only in an LXC container, so the GPU jail wouldn't start in
one. The jail keeps --unshare-user and drops --disable-userns. The helper's
seccomp filter now does that job:
- clone with any CLONE_NEW* flag gets EPERM;
- clone3 gets ENOSYS, as under Flatpak, so libc falls back to clone;
- on x86-64, x32 system calls get EPERM, as they'd get past the numbers;
- mount, umount2, unshare, setns and pivot_root stay refused.

A new test runs the test program inside the GPU jail. There, before the
filter, unshare --user works; after it, unshare --user, clone with
CLONE_NEWUSER and clone3 are refused, and processes and threads still
start. The test fails with the clone rules removed, and with the filter
removed. NVDEC still plays inside the jail.
A song with no cover art has no first frame, and the helper waited for one before
unpausing, so it never played. With no video, it now starts as soon as it's loaded.
…ftware

libmpv falls back to the CPU only when the hardware decoder reports an
error. On the Proxmox box's Intel UHD 770, iHD stopped giving 1080p frames
after 5 to 8 without one, and libmpv reported the end of the file.

When a file ends more than a second short of its known length while
hardware decoding is in use, the helper now sets hwdec to no. libmpv then
starts the decoder again in software where the picture stopped, and the
video plays on. This happens once per file, and the helper says "decoder
software" again. A file that really is shorter than its stated length
costs one start in software before it ends there too.

A unit test covers when it falls back. The fallback itself was checked
on the desktop by forcing it at the real end of the 1080p clip with a
seek back to 1 s: NVDEC played to the end, then software played on from
1 s to the end (272 frames), with no end reported in between.
The helper passed one render node descriptor to both GBM/EGL and libmpv,
whose VA-API interop calls vaGetDisplayDRM on it. GEM buffer handles
belong to the open file, so Mesa and iHD shared one handle table: a handle
one closes is gone for the other. That fits the Intel UHD 770 run, where
1080p H.264 stopped after a few frames with iHD's "Failed to end picture
decode issue: 23" (VA_STATUS_ERROR_DECODING_ERROR) inside the helper only.
Plain mpv in the same container uses vaGetDisplayWl, which opens the node
itself, so its decoder has a file of its own.

The helper now opens the node again by name, under /dev/dri, before it
locks down, and gives that to libmpv; OpenGL keeps the app's descriptor.
If that open fails, the shared one is used as before.

Not yet confirmed on Intel: that needs another Proxmox run. NVDEC and
software playback are unchanged on the desktop. A new test checks the
reopened node is the same card with a file description of its own.
@michaelaguiar

Copy link
Copy Markdown
Member Author

Review round 1 (fresh-context reviewer, code-review high), on this PR's own commits: f2e44d4, de46ea7 and the jail-test conflict resolution in fd8ddc3.

No findings to fix in this PR. The reviewer confirmed:

  • gpu_arguments adds only the read-only pulse/native bind and PULSE_SERVER. It never binds pipewire-0, and loosens nothing from ALI-2358 prototype: a jailed GPU helper that hands frames over as dmabufs #2.
  • clean_meta and parse_said strip and cap as described, and the longest meta message stays under the 256-byte packet.
  • A song with no cover art now starts on load, and cover art still goes through the frame path.

Declined (P3): strip more invisible characters (U+200B–200D, U+2060, U+00AD, the tag characters U+E0000–E007F). Those can't reorder text or break the line, which is what the cleaning guards against. ZWNJ and ZWJ are needed in Persian and Indic text and in emoji sequences, and tag characters make up subdivision flags. Stripping them would damage real titles for little gain.

Outside this PR: the reviewer's skill also reported items in #2's code, which this PR doesn't touch. I passed them to the session working on #2 and haven't checked them here.

The head is now b14bb9e: #2's de0ac55 and cead247 are merged in. make check passes (fmt, clippy -D warnings, all tests).

- A new size draws the frame again while paused or stopped, as the CPU
  helper does. Checked on the desktop: paused, then sent a new size, and
  a 960x540 buffer and frame followed.
- A frame that comes while the app holds every buffer is drawn once one is
  given back, instead of being lost.
- nouveau is no longer taken for NVIDIA: only NVIDIA's own driver gets
  NVDEC and the jail's /proc. A card with NVIDIA's PCI number on another
  driver decodes in software.
- The app's `buffer` check takes only XRGB8888, and a row at most 64 KiB
  longer than its pixels.
- Volume from the app is kept within 0 to 100.
- A debug log line is cut to the packet size in bytes, not characters, so
  a long line with non-ASCII text isn't dropped.
- The GPU jail test skips where there's no /dev/dri, which the jail binds.
- gpu-show stops when the helper goes without a word. Killing the helper's
  bubblewrap mid-clip now ends gpu-show at once; before, it waited until
  it was killed.
`gpu_helper::start_warm` starts a player with no file: OpenGL, libmpv and
its renderer start at once, and it says `hello` when they're ready.
`gpu_helper::load` then gives it the file, as a descriptor on a `load`
message. `start` is unchanged. A player started warm keeps the file
loaded last, and the one before, open while libmpv may read them.

gpu-play's `--warm` times the first frame from when the file is given.
No shader cache is added to the jail.
CI's clippy (Rust 1.100) refuses the indexed loop over the slots as
needless_range_loop. The loop now walks the held flags with enumerate.
- A second file loaded into a warm helper starts afresh. Its decoder is
  announced again, and its size and frames don't carry over from the last
  file; these reset when libmpv says the file is loaded, as the last
  file's frame can still be drawn until then. Hardware decoding comes
  back if the last file fell back to software. Checked by loading the
  clip twice into one warm helper: both said "decoder nvdec" and played
  every frame.
- A `load` while another waits replaces it, so the newest file chosen
  plays. Before, it was dropped with no answer.
- The seccomp filter also refuses the newer mount API (fsopen, fsconfig,
  fsmount, fspick, move_mount, open_tree, mount_setattr, open_tree_attr),
  which can make a procfs without `mount`.
- An NVIDIA card whose driver can't be read is taken to run NVIDIA's own
  again; only nouveau decodes in software without the NVIDIA grants.
About half of songs with cover art never started: no frame was drawn, so
the helper never unpaused. A cover is one frame, queued as soon as the
video is set up. The helper's `VideoChanged` handling asks libmpv for
the size, which waits on libmpv's core, while the core waits for this
thread to draw the frame. libmpv gives up after 200 ms, keeps the frame
on screen, and stops flagging it as new, so the draw was skipped and
nothing woke the loop again.

When playback starts or restarts, the helper now draws the current frame
whatever the flag says. With cover art on (in a local test build of
gpu-play, jailed, on NVIDIA), a FLAC with a 600x600 PNG cover showed its
frame in 2 of 10 runs before and 12 of 12 after. 1080p video plays as
before.
…58-gpu-media

# Conflicts:
#	src/gpu_helper.rs
The helpers read the picture's size, and the GPU helper its decoder and
dropped-frame counts, with blocking gets on their render thread. A get
waits on libmpv's core, and the core can be waiting in the video output
for that same thread to draw. libmpv gives up after 200 ms and drops the
frame's "new" flag. A song's cover lost its only frame that way, and the
same could happen to a video that changes size mid-stream.

The player now watches dwidth, dheight, hwdec-current, frame-drop-count
and vo-delayed-frame-count, as new events: Width, Height, Decoder,
DecoderDrops and LateFrames. The CPU and GPU helpers use them and no
longer ask for them. The GPU helper settles the size once per batch of
events, as width and height arrive separately, so no buffers are made for
a half-changed size. It names the decoder once a frame is drawn and
libmpv has said which decoder it is. The draw on every playback start
(7f6a58d) stays as a second guard.

Checked on the desktop (NVIDIA, jailed):
- A FLAC with a cover (cover art on, in a local test build of gpu-play)
  showed its frame in 12 of 12 runs. The stall before its first frame went
  from about 400 ms to about 200 ms.
- A clip that changes from 640x360 to 1280x720 mid-stream played all 120
  frames. It makes no buffers at an in-between size.
- The 1080p clip's first frame is unchanged (652 to 681 ms).
…58-gpu-media

# Conflicts:
#	src/gpu_helper.rs
@michaelaguiar

Copy link
Copy Markdown
Member Author

Known regression at 1a4b3bf: don't take this head as good.

Since #2's a8024d8, which moved the helper's own reads to observed properties, this PR's three blocking player.get("metadata/by-key/…") calls in Loaded run on the render thread. They now deadlock against libmpv's VO, which is waiting for the cover frame.

In the private weston with private PipeWire:

alias-playback Songs with cover art that play
74c8c87 6 of 6
1a4b3bf 1 of 8
1a4b3bf with the tag reads removed 6 of 6

Fix, coming: #2's async-calls change will add a non-blocking string read. The tag reads will move to it, and meta will be sent from the reply. Alias View stays pinned at 74c8c87 until then.

A thread that draws for libmpv can't wait on libmpv's core: the core may
be waiting in the video output for that thread to draw. libmpv then gives
up after 200 ms and drops the frame's "new" flag. Every start had that
stall, and a cover could lose its only frame to it.

- Requests are now async. command, load, load_fd, set_paused, play,
  the seeks, set_volume and set_muted return once libmpv has the request,
  through mpv_command_async. A request libmpv turns down comes back as
  Event::Refused(Request), where Request is Command, Load, Pause, Seek,
  Volume or Mute. The helpers say `cantplay` for a refused load.
- play() reads the end from the last watched eof-reached, not with a get.
- Player::ask(name, id) reads a property as text without waiting.
  Event::Answered(id) says the answer is ready, and Player::answer(id)
  takes it as an Option<String>. Event stays Copy.
- Loaded { video } keeps its shape. It now comes when libmpv answers an
  async read of `vid`, a moment after the file is loaded, so it can arrive
  after the first Width and Height.
- The GPU helper resets each file's decoder, frames and fallback when it
  asks libmpv to load the file, no longer on Loaded.
- libmpv reports the picture's size only once its core is free, and the
  core waits for the first frame to be drawn. So while the size isn't
  known yet, the GPU helper draws a new frame at the window's size (libmpv
  keeps the picture's shape, with borders), then again at the picture's
  own size once that arrives.
- Fixes from review round 2:
  - A restart owes a draw once the size is settled in the same batch,
    not before it.
  - The CPU helper settles the size once per batch too.

Measured on the desktop (NVIDIA, jailed). The "render() not being called
or stuck" stall is gone from every run, and no first frame is dropped.
- First frame, cold: 1080p H.264 472-530 ms (was 652-714), 4K HEVC
  493-537 ms (was 669-754).
- First frame, warm: 72 ms at 1080p.
- A FLAC with a cover: shown in 12 of 12 runs, first frame 446-509 ms
  (was 651-787).
- Pause and seek during playback are as before: pause 0-67 ms, seek
  63-100 ms to the reported state.
- A clip that changes size mid-stream plays every frame.
Answers to `ask` waited in a map until taken, with nothing to stop the
map growing, or to stop a late answer about the last file being taken
for the next one under a reused id.

Each load now starts a new generation and drops untaken answers. An
answer carries the generation it was asked in, and one from an earlier
generation is turned away with no Answered event. At most 64 answers
wait untaken; beyond that, answer() gives None. Reply ids now keep their
kind in the top 4 bits, then the generation, then the caller's id.

A new test asks for a property, loads another file before reading the
answer, and checks that the late answer is turned away and an untaken one
is dropped on load. It fails without the generation and the clearing.
The three tag reads were blocking gets on the drawing thread, which stalled a song's cover
art once #2's own reads stopped waiting (a8024d8). They're now asked with Player::ask on
Loaded, and each is said as meta when Event::Answered brings it; one that's missing or
empty says nothing. Loaded may now come after the first frame; the novideo start still
only begins playback when there's no picture.
- The internal `vid` read behind Loaded now carries the load generation
  too. Its answer is turned away if another load was asked for since, so a
  late "no picture" about the last file isn't reported for the new one.
- A load request bumps the generation and clears the answers under the
  answers lock, and an answer is checked and stored under it. An `ask` on
  another thread can't land between the two.
- `ask`'s documentation now says what the generation covers. An answer
  asked for before a later load request is turned away. One asked for
  after the request but before libmpv opens the file can still be about
  the last file, so ask once Loaded has come.
- A restart that comes while the picture's size is still unknown is kept
  until the size is known, so its draw isn't lost across batches.
… loading

A late Loaded about the previous file can still come after a new load. A Loaded without
video now asks the video track (vid) without waiting, and only an answer of no, which
belongs to the file now loading (df646d2), says novideo and starts sound alone. A file
that has already drawn a frame never does.
…reading a dmabuf

Gpu::new now holds the GBM device, EGL display and context in a guard that frees them if a later step or lookup fails. read_dmabuf checks glCheckFramebufferStatus and returns an error instead of a zeroed buffer.
@michaelaguiar
michaelaguiar added this pull request to stack #4 December 2, 2026 22:37
@michaelaguiar
michaelaguiar marked this pull request as ready for review December 2, 2026 22:37
Base automatically changed from ali-2358-gpu-helper to main December 2, 2026 22:37
michaelaguiar added a commit that referenced this pull request Dec 2, 2026
…bufs (#2)

* ALI-2420: The shared libmpv playback crate, with colour tests

One crate for Alias View, Gannet and Nitrate to play through libmpv:

- Player: libmpv opened at run time, the shared options, commands, and
  events for position, duration, pause, volume, mute, end and failure.
- SwRender and GlRender: libmpv's CPU and OpenGL render APIs.
- options::colour: the colour settings for each render path in one
  place. The CPU path keeps Gannet's BT.1886 relabel (ALI-2418).
- helper and jail: Gannet's jailed CPU player, with frames in shared
  memory, moved here so any app can use it.

Every app stops on a video's last frame instead of closing. Hardware
decoding tries NVDEC, VA-API and V4L2 by name. VDPAU is left out because
it stalls on H.264 4:4:4 on NVIDIA.

The colour tests play 51 clips of solid patches, made from Y'CbCr worked
out from source RGB and encoded losslessly. The clips cover range,
matrix, transfer tag, bit depth, chroma and codec. CI runs them on the CPU
renderer, and examples/colour-gpu.rs runs them on a graphics card.

* Review fixes: jailed exe, hidden file reads, stale duration, GL thread

- jail::own_exe no longer falls back to /proc/self/exe. bubblewrap resolves
  that path in its own process and binds itself, so a video opened after the
  app's file was removed ran bwrap as the helper and failed as a jail error.
  It now fails plainly instead.
- ordered-chapters and access-references are off. A Matroska file could
  otherwise make an unjailed player read other files for its chapters, and
  a playlist could name anything.
- When a file closes, the position and duration go back to 0 rather than
  keeping the last file's values (new helper test, which fails without
  this change).
- GlRender can't move between threads. Dropping it frees libmpv's GL state,
  which needs its context current.
- watch stops the player when try_wait fails, as its documentation says.
- start's documentation says the player dies with the thread that started it.
- The GPU bench skips a case only when the machine's encoder can't make it.
  A missing FFmpeg or a clip that fails its check is now a failure.
- The CPU colour setting's comment covers full-range video with no
  transfer tag too.
- The unused rustix process feature is removed.

* Review fixes: clear the end with the file, and always load a file

- When a file closes, the end also goes back to not reached (Ended(false)),
  as the position and duration already do. Before, an app that had shown
  "ended" kept showing it with nothing loaded. The helper test now checks it,
  and fails without this.
- Player::load always passes a path libmpv reads as a file: a relative one
  gets "./" in front. A relative path shaped like "http://host/x" or
  "edl://..." would otherwise be fetched or built by libmpv.

* GPU helper prototype: libmpv on the card, frames handed over as dmabufs

A jailed helper draws with libmpv's OpenGL renderer into GBM buffers on the
compositor's card and passes their dmabufs to the app over a SOCK_SEQPACKET
socket. The buffers use layouts OpenGL can draw into, which EGL reports.
Hardware decoding gets the render node (VA-API) or CUDA (NVDEC).

The GPU jail adds the card's device files and /sys. On NVIDIA it also adds
/proc, which CUDA needs. Landlock then refuses opening anything outside /dev
for writing, so /proc/self/mem can't change code.

examples/gpu-play plays a file through the helper and prints frames, first
frame, dropped frames, CPU and memory. Prototype for ALI-2358; not for
merging as it is.

* GPU helper prototype: show its dmabufs on a compositor

examples/gpu-show opens a window and attaches each frame's dmabuf with
linux-dmabuf. When the compositor releases a buffer, it goes back to the
helper. It measures what gpu-play does, end to end, for comparison with
mpv's own window in the same private headless weston.

* GPU helper: hardware decoding and jail grants chosen per card maker

The card's maker is read from /sys for the compositor's render node:
- NVIDIA decodes with NVDEC and gets its device files and /proc;
- AMD and Intel decode with VA-API on the render node;
- Apple and others try V4L2;
- every maker falls back to the CPU.
No maker gets another's devices.

On NVIDIA, /proc is a fresh one for the jail's own PID namespace.
lock_down_gpu_helper adds two locks on top: Landlock (writes only under /dev)
and a seccomp filter that refuses ptrace, process_vm_readv/writev,
pidfd_getfd and kcmp with EPERM. Tests show /proc/self/mem, ptrace and
process_vm_writev are refused, and that only NVIDIA gets /proc.

The GPU colour bench decodes the same way, for the card it runs on.

* GPU helper: lock down first, start libmpv beside OpenGL, buffers ready early

- lock_down now runs before the helper has any other thread. Landlock
  applies only to the thread that turns it on and the ones it starts
  later, and libmpv and the drivers start threads of their own.
- The seccomp filter is synced to every thread (TSYNC), like Gannet's.
- libmpv starts on its own thread while OpenGL starts on the card.
- The buffers are made when the video's size is known, before its first
  frame, so making them doesn't delay that frame.
- The player stays paused until the first frame is drawn, then plays.
- Each frame sent counts as presented (report_swap), for libmpv's timing.

* GPU colour bench: Alias View's own path, the jailed helper's dmabufs

Each clip also goes through the jailed GPU helper, with and without the
card's hardware decoding. Its first frame is read back from the dmabuf on
this side, as Alias View will show it. The bench checks it against the
source colours like every other path.

* GPU helper: draw before reporting the state, so the last frame isn't lost

The end of a video was reported before that loop drew its last frame. The
measuring apps stop at the end, so they missed the final frame (149 of 150
at 4K). The frame now goes first.

* GPU helper: run on Debian and on Intel (found on the Proxmox UHD 770)

- The jail points /lib64 at /usr/lib64 where a system has it (Debian, Fedora),
  not only at /usr/lib (Arch).
- The jail includes /etc/alternatives, which Debian's libraries link through
  (libmpv needs libblas there).
- Landlock is required only when the jail has /proc (NVIDIA). Proxmox's kernel
  has no Landlock. The seccomp filter is still required.
- GBM buffers with a second plane (Intel's compressed CCS layouts) are skipped,
  and GBM is asked again.
- gpu-play says how the helper ended when it ends before the clip does.

* GPU jail: no new user namespaces, no mounts

A helper that has been taken over could make a user namespace inside the
jail, get privileges back there, and mount a procfs of its own to reach
/proc/self/mem, even with no /proc granted. The GPU jail now runs with
bubblewrap's --unshare-user --disable-userns. The helper's seccomp filter
also refuses mount, umount2, unshare, setns and pivot_root, as Gannet's
player filter does.

New tests show both refusals, and each fails without its change:
- unshare --user fails inside the jail but works outside it;
- unshare and mount return EPERM under the filter.
NVDEC still plays inside the jail.

* GPU helper: a debug mode that sends libmpv's log and start-up timings

A jailed helper can't write a log file anywhere. With debug (gpu_helper::
start's new flag, GPU_PLAY_DEBUG=1 in gpu-play), it sends libmpv's log lines
as log messages. It also reports how long OpenGL, libmpv and libmpv's
renderer took to start, and the average time to finish a frame. Player gains
on_log for the log lines.

* GPU jail: seccomp instead of --disable-userns, so it starts in LXC

bubblewrap's --disable-userns writes /proc/sys/user/max_user_namespaces,
which is read-only in an LXC container, so the GPU jail wouldn't start in
one. The jail keeps --unshare-user and drops --disable-userns. The helper's
seccomp filter now does that job:
- clone with any CLONE_NEW* flag gets EPERM;
- clone3 gets ENOSYS, as under Flatpak, so libc falls back to clone;
- on x86-64, x32 system calls get EPERM, as they'd get past the numbers;
- mount, umount2, unshare, setns and pivot_root stay refused.

A new test runs the test program inside the GPU jail. There, before the
filter, unshare --user works; after it, unshare --user, clone with
CLONE_NEWUSER and clone3 are refused, and processes and threads still
start. The test fails with the clone rules removed, and with the filter
removed. NVDEC still plays inside the jail.

* GPU helper: hardware decoding that ends a file early falls back to software

libmpv falls back to the CPU only when the hardware decoder reports an
error. On the Proxmox box's Intel UHD 770, iHD stopped giving 1080p frames
after 5 to 8 without one, and libmpv reported the end of the file.

When a file ends more than a second short of its known length while
hardware decoding is in use, the helper now sets hwdec to no. libmpv then
starts the decoder again in software where the picture stopped, and the
video plays on. This happens once per file, and the helper says "decoder
software" again. A file that really is shorter than its stated length
costs one start in software before it ends there too.

A unit test covers when it falls back. The fallback itself was checked
on the desktop by forcing it at the real end of the 1080p clip with a
seek back to 1 s: NVDEC played to the end, then software played on from
1 s to the end (272 frames), with no end reported in between.

* GPU helper: VA-API gets the card opened again, not OpenGL's descriptor

The helper passed one render node descriptor to both GBM/EGL and libmpv,
whose VA-API interop calls vaGetDisplayDRM on it. GEM buffer handles
belong to the open file, so Mesa and iHD shared one handle table: a handle
one closes is gone for the other. That fits the Intel UHD 770 run, where
1080p H.264 stopped after a few frames with iHD's "Failed to end picture
decode issue: 23" (VA_STATUS_ERROR_DECODING_ERROR) inside the helper only.
Plain mpv in the same container uses vaGetDisplayWl, which opens the node
itself, so its decoder has a file of its own.

The helper now opens the node again by name, under /dev/dri, before it
locks down, and gives that to libmpv; OpenGL keeps the app's descriptor.
If that open fails, the shared one is used as before.

Not yet confirmed on Intel: that needs another Proxmox run. NVDEC and
software playback are unchanged on the desktop. A new test checks the
reopened node is the same card with a file description of its own.

* GPU helper: fixes from #3's review

- A new size draws the frame again while paused or stopped, as the CPU
  helper does. Checked on the desktop: paused, then sent a new size, and
  a 960x540 buffer and frame followed.
- A frame that comes while the app holds every buffer is drawn once one is
  given back, instead of being lost.
- nouveau is no longer taken for NVIDIA: only NVIDIA's own driver gets
  NVDEC and the jail's /proc. A card with NVIDIA's PCI number on another
  driver decodes in software.
- The app's `buffer` check takes only XRGB8888, and a row at most 64 KiB
  longer than its pixels.
- Volume from the app is kept within 0 to 100.
- A debug log line is cut to the packet size in bytes, not characters, so
  a long line with non-ASCII text isn't dropped.
- The GPU jail test skips where there's no /dev/dri, which the jail binds.
- gpu-show stops when the helper goes without a word. Killing the helper's
  bubblewrap mid-clip now ends gpu-show at once; before, it waited until
  it was killed.

* GPU helper prototype: start warm, before a file is chosen

`gpu_helper::start_warm` starts a player with no file: OpenGL, libmpv and
its renderer start at once, and it says `hello` when they're ready.
`gpu_helper::load` then gives it the file, as a descriptor on a `load`
message. `start` is unchanged. A player started warm keeps the file
loaded last, and the one before, open while libmpv may read them.

gpu-play's `--warm` times the first frame from when the file is given.
No shader cache is added to the jail.

* GPU helper: make buffers with an iterator, for Rust 1.100's clippy

CI's clippy (Rust 1.100) refuses the indexed loop over the slots as
needless_range_loop. The loop now walks the held flags with enumerate.

* GPU helper: fixes from the first review round of #2

- A second file loaded into a warm helper starts afresh. Its decoder is
  announced again, and its size and frames don't carry over from the last
  file; these reset when libmpv says the file is loaded, as the last
  file's frame can still be drawn until then. Hardware decoding comes
  back if the last file fell back to software. Checked by loading the
  clip twice into one warm helper: both said "decoder nvdec" and played
  every frame.
- A `load` while another waits replaces it, so the newest file chosen
  plays. Before, it was dropped with no answer.
- The seccomp filter also refuses the newer mount API (fsopen, fsconfig,
  fsmount, fspick, move_mount, open_tree, mount_setattr, open_tree_attr),
  which can make a procfs without `mount`.
- An NVIDIA card whose driver can't be read is taken to run NVIDIA's own
  again; only nouveau decodes in software without the NVIDIA grants.

* GPU helper: draw the current frame when playback starts, so covers show

About half of songs with cover art never started: no frame was drawn, so
the helper never unpaused. A cover is one frame, queued as soon as the
video is set up. The helper's `VideoChanged` handling asks libmpv for
the size, which waits on libmpv's core, while the core waits for this
thread to draw the frame. libmpv gives up after 200 ms, keeps the frame
on screen, and stops flagging it as new, so the draw was skipped and
nothing woke the loop again.

When playback starts or restarts, the helper now draws the current frame
whatever the flag says. With cover art on (in a local test build of
gpu-play, jailed, on NVIDIA), a FLAC with a 600x600 PNG cover showed its
frame in 2 of 10 runs before and 12 of 12 after. 1080p video plays as
before.

* Player: watch the picture's size, decoder and dropped frames

The helpers read the picture's size, and the GPU helper its decoder and
dropped-frame counts, with blocking gets on their render thread. A get
waits on libmpv's core, and the core can be waiting in the video output
for that same thread to draw. libmpv gives up after 200 ms and drops the
frame's "new" flag. A song's cover lost its only frame that way, and the
same could happen to a video that changes size mid-stream.

The player now watches dwidth, dheight, hwdec-current, frame-drop-count
and vo-delayed-frame-count, as new events: Width, Height, Decoder,
DecoderDrops and LateFrames. The CPU and GPU helpers use them and no
longer ask for them. The GPU helper settles the size once per batch of
events, as width and height arrive separately, so no buffers are made for
a half-changed size. It names the decoder once a frame is drawn and
libmpv has said which decoder it is. The draw on every playback start
(7f6a58d) stays as a second guard.

Checked on the desktop (NVIDIA, jailed):
- A FLAC with a cover (cover art on, in a local test build of gpu-play)
  showed its frame in 12 of 12 runs. The stall before its first frame went
  from about 400 ms to about 200 ms.
- A clip that changes from 640x360 to 1280x720 mid-stream played all 120
  frames. It makes no buffers at an in-between size.
- The 1080p clip's first frame is unchanged (652 to 681 ms).

* Player: requests and reads that never wait on libmpv's core

A thread that draws for libmpv can't wait on libmpv's core: the core may
be waiting in the video output for that thread to draw. libmpv then gives
up after 200 ms and drops the frame's "new" flag. Every start had that
stall, and a cover could lose its only frame to it.

- Requests are now async. command, load, load_fd, set_paused, play,
  the seeks, set_volume and set_muted return once libmpv has the request,
  through mpv_command_async. A request libmpv turns down comes back as
  Event::Refused(Request), where Request is Command, Load, Pause, Seek,
  Volume or Mute. The helpers say `cantplay` for a refused load.
- play() reads the end from the last watched eof-reached, not with a get.
- Player::ask(name, id) reads a property as text without waiting.
  Event::Answered(id) says the answer is ready, and Player::answer(id)
  takes it as an Option<String>. Event stays Copy.
- Loaded { video } keeps its shape. It now comes when libmpv answers an
  async read of `vid`, a moment after the file is loaded, so it can arrive
  after the first Width and Height.
- The GPU helper resets each file's decoder, frames and fallback when it
  asks libmpv to load the file, no longer on Loaded.
- libmpv reports the picture's size only once its core is free, and the
  core waits for the first frame to be drawn. So while the size isn't
  known yet, the GPU helper draws a new frame at the window's size (libmpv
  keeps the picture's shape, with borders), then again at the picture's
  own size once that arrives.
- Fixes from review round 2:
  - A restart owes a draw once the size is settled in the same batch,
    not before it.
  - The CPU helper settles the size once per batch too.

Measured on the desktop (NVIDIA, jailed). The "render() not being called
or stuck" stall is gone from every run, and no first frame is dropped.
- First frame, cold: 1080p H.264 472-530 ms (was 652-714), 4K HEVC
  493-537 ms (was 669-754).
- First frame, warm: 72 ms at 1080p.
- A FLAC with a cover: shown in 12 of 12 runs, first frame 446-509 ms
  (was 651-787).
- Pause and seek during playback are as before: pause 0-67 ms, seek
  63-100 ms to the reported state.
- A clip that changes size mid-stream plays every frame.

* Player: answers belong to the file they were asked about

Answers to `ask` waited in a map until taken, with nothing to stop the
map growing, or to stop a late answer about the last file being taken
for the next one under a reused id.

Each load now starts a new generation and drops untaken answers. An
answer carries the generation it was asked in, and one from an earlier
generation is turned away with no Answered event. At most 64 answers
wait untaken; beyond that, answer() gives None. Reply ids now keep their
kind in the top 4 bits, then the generation, then the caller's id.

A new test asks for a property, loads another file before reading the
answer, and checks that the late answer is turned away and an untaken one
is dropped on load. It fails without the generation and the clearing.

* Player and GPU helper: fixes from review round 3

- The internal `vid` read behind Loaded now carries the load generation
  too. Its answer is turned away if another load was asked for since, so a
  late "no picture" about the last file isn't reported for the new one.
- A load request bumps the generation and clears the answers under the
  answers lock, and an answer is checked and stored under it. An `ask` on
  another thread can't land between the two.
- `ask`'s documentation now says what the generation covers. An answer
  asked for before a later load request is turned away. One asked for
  after the request but before libmpv opens the file can still be about
  the last file, so ask once Loaded has come.
- A restart that comes while the picture's size is still unknown is kept
  until the size is known, so its draw isn't lost across batches.

* Release GPU setup on every error path and check the framebuffer when reading a dmabuf

Gpu::new now holds the GBM device, EGL display and context in a guard that frees them if a later step or lookup fails. read_dmabuf checks glCheckFramebufferStatus and returns an error instead of a zeroed buffer.
@michaelaguiar

Copy link
Copy Markdown
Member Author

Merged main into the branch after #2's squash merge (a250832), keeping this branch's side of the conflicts. a250832's tree is identical to #2's final head 6c0187c, which this branch already contained, so the merge commit 69975c1 has the same tree as 4a05f2c and the PR's diff against main is unchanged. The earlier review rounds still apply.

@michaelaguiar
michaelaguiar merged commit fef4a47 into main Dec 2, 2026
1 check passed
@michaelaguiar
michaelaguiar deleted the ali-2358-gpu-media branch December 3, 2026 00:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant