vendetta / libvendetta / lib.v
909 lines · 870 sloc · 32.78 KB · df3630998c857099c58814a775d080e37af0d23f
Raw
1// libvendetta is vendetta as an embeddable widget. A host owns the window and
2// the event loop: it gives us a rectangle, folds the element we build into its
3// screen, and forwards the events it wants us to see. Everything that assumed
4// owning the app is gone — no menu bar (ui2 keeps it as a process global), no
5// settings file, no thumbnails, no fullscreen: the host decides what the
6// window does.
7//
8// player := libvendetta.new(libvendetta.Config{})
9// ui2.set_gl_surface_renderer(fn [mut player] (id, frame, scale, height) {
10// player.render(id, frame, scale, height)
11// })
12// // in the host's build callback:
13// children << player.build(ui2.rect(0, 0, b.width - 300, b.height))
14// // in the host's event callback:
15// if event.starts_with('vd_') {
16// player.handle(event)
17// }
18module libvendetta
19
20import math
21import mpv
22import os
23import time
24import ui2
25import wake
26import x.progress
27
28// The vinix-dark palette vendetta compiles in, so the widget reads like the
29// standalone player without a theme file system behind it.
30const slider_track_dark = 0x334155
31const slider_value_blue = 0x3b82f6
32const btn_blue = 0x3b82f6
33const btn_secondary_slate = 0x64748b
34const text_main_white = u32(0xffffff)
35const text_muted_slate = 0xe2e8f0
36const bg_dark_night = 0x020617
37const bg_surface_slate = 0x1e293b
38
39// smooth_glide_cap bounds how far the smooth bar's glide may run ahead of the
40// last reported position, in seconds: a decoder that stalls its reports stops
41// the bar near where the picture is instead of letting it coast into the dark.
42const smooth_glide_cap = 0.5
43
44// Palette groups the colours the widget paints. Hosts that want the widget to
45// match their own look can set Player.palette; the default is vendetta's.
46pub struct Palette {
47pub mut:
48 slider_track u32 = slider_track_dark
49 slider_value u32 = slider_value_blue
50 btn_primary u32 = btn_blue
51 btn_secondary u32 = btn_secondary_slate
52 // The control strip's buttons: the play/pause toggle, the seek steps and
53 // the mute toggle. They default to the strip's backdrop, so the glyphs
54 // sit on the bar without boxes of their own; each keeps a field so a
55 // host can split them apart again.
56 btn_play u32 = btn_blue
57 btn_seek u32 = bg_dark_night
58 btn_mute u32 = bg_dark_night
59 text_main u32 = text_main_white
60 text_muted u32 = text_muted_slate
61 bg_dark u32 = bg_dark_night
62 bg_surface u32 = bg_surface_slate
63 // The strip's backdrop in docked mode, where it sits statically; the
64 // floating strip keeps bg_dark.
65 bg_docked u32 = bg_dark_night
66}
67
68// Config holds the knobs a host can turn at construction. The rest of the
69// widget's behaviour is vendetta's own, so a host gets a media player, not a
70// pile of settings.
71pub struct Config {
72pub mut:
73 // The control strip floats over the full-height video, or sits docked in
74 // a band below it.
75 overlay bool = true
76 // How far the seek buttons jump, in seconds.
77 seek_step f64 = 30
78 // How far one wheel or arrow key step moves the volume.
79 volume_step f64 = 5
80 // The height of the seek and volume tracks, in layout pixels: 1 up to the
81 // strip's 30. Read on every build.
82 slider_h f64 = 10
83 // Whether mpv's render call waits out each frame's target display time.
84 // Disabling it trades presentation pacing for a snappier UI thread.
85 block_target_time bool = true
86 // Which forwarded input reaches the widget: frame (only input over its
87 // frame; keys follow the pointer) or window (every forwarded event).
88 input_scope InputScope = InputScope.frame
89 // The audio server mpv's sound runs through, taken before mpv starts. A
90 // name pins it ('pulse', 'alsa', ...), 'auto' hands the choice to mpv's
91 // own autoprobing, and empty keeps the platform default: pulse on Linux
92 // (PipeWire's audio init blocks mpv's core, so it is avoided), mpv's own
93 // output on Windows and macOS (avfoundation there).
94 ao string
95 // pre_init receives mpv's handle after the widget's own options are set
96 // and before mpv starts, for the options mpv reads only at start.
97 pre_init fn (ctx voidptr) = unsafe { nil }
98 // on_event receives every mpv event after the widget has taken its own
99 // state from it, so a host can follow the properties it observes.
100 on_event fn (ev voidptr) = unsafe { nil }
101 // on_open receives every source load() is asked to open and may hand back a
102 // different one — the link hook, where a host resolves a page or playlist
103 // URL into the media URL mpv should actually fetch.
104 // None keeps the source. Whatever load() does with the result is what it
105 // would have done with the original: links reach mpv ungated, files keep
106 // their existence check.
107 on_open fn (path string) ?string = unsafe { nil }
108}
109
110// InputScope limits forwarded input to the widget's frame, or lets it act on
111// the whole window, so a host can embed the player without losing its own keys.
112pub enum InputScope {
113 frame
114 window
115}
116
117// Player is the embeddable player. Playback state is mirrored from observed
118// mpv properties, so hosts can read it directly between builds.
119pub struct Player {
120pub mut:
121 // Playback state mirrored from mpv.
122 has_file bool
123 pos f64
124 duration f64
125 paused bool
126 volume f64 = 100
127 max_volume f64 = 100
128 muted bool
129 speed f64 = 1
130 current_path string
131 // The kind of what current_path names — a link streams from the network,
132 // a file exists locally — decided once as each observed path lands. Hosts
133 // read this instead of searching paths for '://' on their own.
134 current_kind MediaKind
135 // The frame the host last built the widget into. Pointer handling maps
136 // window coordinates against it, so events keep working when the host
137 // moves or resizes the widget between builds.
138 frame ui2.Rect
139 pointer_x f64
140 pointer_y f64
141 last_motion i64
142 controls_wake u64
143 // The smooth seek bar: with it on and the file playing, the bar carries the
144 // reported position forward at playback speed and the window redraws at the
145 // display rate through paint-only frames. Off — the default — the bar moves
146 // only when a report lands and nothing else redraws either.
147 smooth_bar bool
148 // The wall clock of the last time-pos report the glide extrapolates from;
149 // zero until the first one lands.
150 smooth_anchor_t i64
151 palette Palette
152 cfg Config
153 mpv_ctx voidptr
154 render_ctx voidptr
155 // Sources queued before the first draw; they load once the render context
156 // exists, so mpv has somewhere to put the picture.
157 startup []string
158 clear_next bool
159 // Playback instrumentation for the -d playback_probe build: presents are
160 // the present() calls per second, and repeat_skips the mpv repeats
161 // consumed without a draw.
162 presents int
163 repeat_skips int
164 mistimed f64
165 vo_delayed f64
166mut:
167 surface Surface
168 // The open-shape override's memory of the config's choice: load() holds
169 // block_target_time down for links and restores the choice for files, so
170 // the knob keeps meaning what the config said.
171 block_target_time_saved bool
172 sync_fallback_done bool
173 sync_watch_t0 i64
174 mistimed_at_watch f64
175 vo_delayed_at_watch f64
176 // The frame-relay thread and its shutdown flag. The flag starts true:
177 // there is nothing to park until the first draw spawns the relay.
178 relay_stop bool = true
179 relay_thread thread
180 // The wake slot this player's render callback bumps. Claimed when the
181 // relay spawns, released on destroy: two embedded players then wake only
182 // their own relays instead of trading frame-rate asks.
183 wake_slot int = -1
184 // The strip's icon roles (play, pause, the seek steps, the volume states)
185 // resolved once in setup: the bundled PNG's path under assets/icons, or ''
186 // where the build carries none (`-d no_png_icons`, or no bundle on this
187 // layout) and the glyph fallback takes over. Builds read this.
188 icon_files map[string]string
189}
190
191// Observed property ids. The widget tracks the playback properties its
192// controls and the display-sync watch need, not the standalone player's full
193// statistics set. Events are matched by userdata, and a host may register
194// observers of its own on this context, so the widget's ids stay below 10:
195// hosts number their own observers from 1000 up.
196const obs_time_pos = u64(1)
197const obs_duration = u64(2)
198const obs_pause = u64(3)
199const obs_volume = u64(4)
200const obs_mute = u64(5)
201const obs_speed = u64(6)
202const obs_path = u64(7)
203const obs_mistimed = u64(8)
204const obs_vo_delayed = u64(9)
205
206// Reply userdata for the commands and writes below. Unique per kind so a
207// COMMAND_REPLY can tell them apart; the values follow the standalone
208// player's for the shared actions.
209const cmd_toggle_pause = u64(10)
210const cmd_slider_seek = u64(11)
211const cmd_volume = u64(12)
212const cmd_stop = u64(14)
213const cmd_mute = u64(16)
214const cmd_seek = u64(18)
215const cmd_loadfile = u64(20)
216const sync_fallback_userdata = u64(213)
217// The fallback watch tolerates short bursts of mis-timed or delayed frames
218// before stepping the sync mode down: a busy UI thread (GC pauses, a heavy
219// overlay) can easily hold the vo stage for tens of milliseconds, and
220// switching modes on that only churns mpv's own re-stabilization. The
221// thresholds are deliberately forgiving: mis-timing the watch can see takes
222// one pacing step to recover from, but a mode switch costs a resample.
223const sync_fallback_window_ms = 6000
224const sync_fallback_frames = 60
225
226// Element ids the widget builds. The vd_ prefix is the host's routing key.
227pub const video_surface_id = 'vd_video'
228const root_id = 'vd_root'
229
230// new builds a widget player. The render context is created on the first draw,
231// once the host's GL context is current.
232// hwdec_mode is the hwdec option for a player whose hardware decoding is on or
233// off. Android decodes through MediaCodec and copies each frame back, which is
234// the mode the render API can draw; mediacodec's zero-copy output has no surface
235// to land on here, and the frames stay black.
236pub fn hwdec_mode(on bool) string {
237 $if android {
238 return if on { 'mediacodec-copy' } else { 'no' }
239 }
240 return if on { 'auto-safe' } else { 'no' }
241}
242
243// video_debug_note marks a point on the file-open path when -d video_debug is
244// enabled; the no-op form keeps it out of normal builds.
245$if video_debug ? {
246 pub fn video_debug_note(note string) {
247 eprintln('VIDEO_DEBUG ${note}')
248 }
249} $else {
250 pub fn video_debug_note(_ string) {}
251}
252
253// video_debug_dump reports the properties that decide how mpv turns a decoded
254// frame into the surface. It is built only with -d video_debug, so a normal
255// player does not spend time converting properties or writing logcat lines.
256$if video_debug ? {
257 fn (p &Player) video_debug_dump(reason string) {
258 mut out := []string{}
259 for name in ['current-vo', 'video-codec', 'video-format', 'hwdec-current',
260 'video-params/pixelformat', 'video-sync', 'deband', 'vf', 'video-aspect-override',
261 'video-unscaled', 'video-crop', 'gpu-api', 'gpu-context'] {
262 value := mpv.get_string(p.mpv_ctx, name) or { '<none>' }
263 out << '${name}=${value}'
264 }
265 for name in ['width', 'height', 'dwidth', 'dheight', 'video-zoom', 'panscan', 'video-pan-x',
266 'video-pan-y', 'video-align-x', 'video-align-y', 'video-params/w', 'video-params/h',
267 'video-params/aspect', 'video-out-params/w', 'video-out-params/h', 'video-out-params/dw',
268 'video-out-params/dh', 'video-out-params/aspect', 'video-out-params/rotate',
269 'video-target-params/w', 'video-target-params/h', 'video-target-params/aspect',
270 'estimated-vf-fps', 'display-fps', 'time-pos', 'speed', 'osd-width', 'osd-height',
271 'osd-par'] {
272 if value := mpv.get_double(p.mpv_ctx, name) {
273 out << '${name}=${value:.4f}'
274 } else {
275 out << '${name}=<none>'
276 }
277 }
278 eprintln('VIDEO_DEBUG ${reason} surface=${p.surface.w}x${p.surface.h} ${out.join(' ')}')
279 }
280} $else {
281 fn (p &Player) video_debug_dump(_ string) {}
282}
283
284pub fn new(cfg Config) &Player {
285 mut p := &Player{}
286 p.setup(cfg)
287 return p
288}
289
290// setup starts mpv on a Player the host embeds, for hosts whose player is a
291// larger struct than the widget. It mirrors the standalone player's options.
292pub fn (mut p Player) setup(cfg Config) {
293 p.cfg = cfg
294 // The strip's icons resolve before any build reads them: a layout without
295 // the assets bundle leaves the roles empty, and draw.v's glyphs carry the
296 // buttons instead.
297 p.icon_files = resolve_strip_icons()
298 register_android_vm()
299 p.mpv_ctx = mpv.create()
300 if p.mpv_ctx == unsafe { nil } {
301 eprintln('libvendetta: mpv_create failed')
302 return
303 }
304 // vo=libmpv hands frames to the render API; without it mpv opens a window
305 // of its own. ao: mpv reads the audio server only before it starts, so the
306 // host's choice lands here — a named server written as is, 'auto' as an
307 // empty option, which is what mpv reads as its own autoprobing. Linux pins
308 // pulse when the host has no choice: PipeWire's audio init blocks mpv's
309 // core, so it is avoided.
310 mpv.set_option(p.mpv_ctx, 'vo', 'libmpv')
311 $if linux {
312 ao := if cfg.ao.len == 0 {
313 'pulse'
314 } else if cfg.ao == 'auto' {
315 ''
316 } else {
317 cfg.ao
318 }
319 mpv.set_option(p.mpv_ctx, 'ao', ao)
320 } $else $if android {
321 // mpv's own default list starts with pulse, which this platform does
322 // not have, so audiotrack is named unless the host chose another output.
323 ao_name := if cfg.ao.len == 0 || cfg.ao == 'auto' { 'audiotrack' } else { cfg.ao }
324 mpv.set_option(p.mpv_ctx, 'ao', ao_name)
325 } $else {
326 if cfg.ao.len > 0 && cfg.ao != 'auto' {
327 mpv.set_option(p.mpv_ctx, 'ao', cfg.ao)
328 }
329 }
330 mpv.set_option(p.mpv_ctx, 'keep-open', 'yes')
331 // Hardware decoding is the host's call, not the widget's: the app mirrors
332 // the saved setting right after setup, and a forced mode would silently
333 // override the user's toggle on every start (Android's mediacodec-copy
334 // did exactly that, re-enabling itself over an off setting).
335 // Display sync cannot measure the vsync rate with the libmpv video output:
336 // the player would wait forever for presentation feedback that never
337 // comes. Hand mpv the monitor's refresh rate, and leave audio sync alone
338 // where the rate cannot be detected (Wayland). Harmless while mpv stays
339 // on audio sync, which is where the fallback below takes over anyway.
340 rate := ui2.monitor_refresh_rate()
341 if rate > 0 {
342 mpv.set_option(p.mpv_ctx, 'display-fps-override', '${rate:.3f}')
343 }
344 $if video_debug ? {
345 // The shader-chain path logs reconfigures, pass compilation and GL
346 // errors at info/verbose; warn would carry none of that, and a
347 // corrupted GLES path shows up there before anything pixel-visible.
348 mpv.request_log_messages(p.mpv_ctx, 'v')
349 } $else {
350 mpv.request_log_messages(p.mpv_ctx, 'warn')
351 }
352 if !isnil(cfg.pre_init) {
353 cfg.pre_init(p.mpv_ctx)
354 }
355 init_rc := mpv.initialize(p.mpv_ctx)
356 if init_rc < 0 {
357 eprintln('libvendetta: initialize: ${mpv.error_string(init_rc)}')
358 }
359 mpv.observe_property(p.mpv_ctx, obs_time_pos, 'time-pos', mpv.format_double)
360 mpv.observe_property(p.mpv_ctx, obs_duration, 'duration', mpv.format_double)
361 mpv.observe_property(p.mpv_ctx, obs_pause, 'pause', mpv.format_flag)
362 mpv.observe_property(p.mpv_ctx, obs_volume, 'volume', mpv.format_double)
363 mpv.observe_property(p.mpv_ctx, obs_mute, 'mute', mpv.format_flag)
364 mpv.observe_property(p.mpv_ctx, obs_speed, 'speed', mpv.format_double)
365 mpv.observe_property(p.mpv_ctx, obs_path, 'path', mpv.format_string)
366 // The display-sync fallback watch reads the cumulative mis-timing
367 // counters across a window; both report their own property change.
368 mpv.observe_property(p.mpv_ctx, obs_mistimed, 'mistimed-frame-count', mpv.format_double)
369 mpv.observe_property(p.mpv_ctx, obs_vo_delayed, 'vo-delayed-frame-count', mpv.format_double)
370}
371
372// MediaKind separates the two shapes a playable source comes in, and carries
373// the answer wherever the shape matters. A link names something mpv fetches
374// itself — https://, rtsp://, even mpv's own dvd:// — and never exists on the
375// filesystem, so the local-file handling would always reject it; a file names
376// a local path that has to exist to play. The classification used to be
377// re-derived at every gate by searching the string for '://', which nothing in
378// the code pointed at; source_kind answers once and the rest reads or carries
379// the kind.
380pub enum MediaKind {
381 link
382 file
383}
384
385// source_kind decides what a source names by its protocol prefix: '://' after
386// at least one character makes it a link, anything else a file. It is the one
387// such search in the tree — every other step routes on the kind, handed in or
388// mirrored onto Player.current_kind as the path lands.
389pub fn source_kind(source string) MediaKind {
390 if source.index_('://') > 0 {
391 return .link
392 }
393 return .file
394}
395
396// load queues a file for playback. Before the first draw the file waits in the
397// startup list and loads as the render context comes up; afterwards it is
398// appended to mpv's playlist directly.
399//
400// The on_open hook runs first and may replace the source — the link hook,
401// where a host resolves a page or playlist URL into the media URL mpv should
402// open. The replacement faces the same gate the original would have.
403pub fn (mut p Player) load(path string) {
404 mut target := path
405 if !isnil(p.cfg.on_open) {
406 if v := p.cfg.on_open(path) {
407 target = v
408 }
409 }
410 // The shape is decided once, on the replaced source, and each gate below
411 // reads the kind instead of searching the string for '://' again.
412 kind := source_kind(target)
413 if kind == .link {
414 // Livestreams arrive in bursts with a variable frame rate, so mpv's
415 // target display time prediction drifts and the render call would block
416 // the UI thread waiting for a time that has already passed. Present
417 // immediately instead: mpv still sheds what cannot be shown. The override
418 // only holds while links are what is being opened — a local file
419 // restores the config's choice, so an explicit --no-block-target-time
420 // stays in effect there.
421 if p.cfg.block_target_time {
422 p.block_target_time_saved = true
423 p.cfg.block_target_time = false
424 }
425 } else {
426 if p.block_target_time_saved {
427 p.cfg.block_target_time = p.block_target_time_saved
428 p.block_target_time_saved = false
429 }
430 target = os.abs_path(target)
431 if !os.exists(target) {
432 eprintln('libvendetta: no such file: ${target}')
433 return
434 }
435 }
436 if p.render_ctx != unsafe { nil } {
437 video_debug_note('load: command_async append-play')
438 mpv.command_async(p.mpv_ctx, cmd_loadfile, ['loadfile', target, 'append-play'])
439 return
440 }
441 video_debug_note('load: queued for startup')
442 p.startup << target
443}
444
445// stop ends playback and leaves the last picture on the surface until the
446// next load clears it, the way keep-open does.
447pub fn (mut p Player) stop() {
448 if p.mpv_ctx != unsafe { nil } {
449 mpv.command_async(p.mpv_ctx, cmd_stop, ['stop'])
450 }
451 p.has_file = false
452 p.pos = 0
453 p.clear_next = true
454}
455
456// toggle_play pauses or resumes, for hosts driving the player programmatically.
457pub fn (mut p Player) toggle_play() {
458 if p.mpv_ctx != unsafe { nil } {
459 mpv.set_flag_async(p.mpv_ctx, cmd_toggle_pause, 'pause', !p.paused)
460 }
461}
462
463// set_overlay switches the control layout between the strip floating over the
464// full-height video and the docked strip below it. Config is built once at new(),
465// so a host that wants to change modes at runtime goes through this method.
466pub fn (mut p Player) set_overlay(overlay bool) {
467 p.cfg.overlay = overlay
468}
469
470// set_input_scope switches forwarded input between the widget's frame and the
471// whole window at runtime.
472pub fn (mut p Player) set_input_scope(scope InputScope) {
473 p.cfg.input_scope = scope
474}
475
476// destroy frees mpv. Call it after the host's window is gone; the render
477// context dies with it. The relay thread is parked for good first — a join
478// before the contexts die keeps a teardown-and-re-embed host from leaking a
479// thread per cycle — and a pending hide chain is cancelled so its callback
480// never fires on a torn-down player.
481pub fn (mut p Player) destroy() {
482 p.stop_relay()
483 if p.controls_wake != 0 {
484 ui2.cancel_timer(p.controls_wake)
485 p.controls_wake = 0
486 }
487 if p.wake_slot >= 0 {
488 wake.release(p.wake_slot)
489 p.wake_slot = -1
490 }
491 if p.render_ctx != unsafe { nil } {
492 mpv.render_context_free(p.render_ctx)
493 p.render_ctx = unsafe { nil }
494 }
495 if p.mpv_ctx != unsafe { nil } {
496 mpv.destroy(p.mpv_ctx)
497 p.mpv_ctx = unsafe { nil }
498 }
499}
500
501// handle runs an event whose id belongs to the widget. The host forwards any
502// id it does not consume itself; unknown ids are dropped, so a host can route
503// blindly.
504pub fn (mut p Player) handle(event string) {
505 match event {
506 'vd_toggle' {
507 p.toggle_play()
508 }
509 'vd_seek_back' {
510 if p.has_file {
511 mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '-${p.cfg.seek_step:.0f}'])
512 }
513 }
514 'vd_seek_forward' {
515 if p.has_file {
516 mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '${p.cfg.seek_step:.0f}'])
517 }
518 }
519 'vd_seek' {
520 if p.has_file {
521 // The release committed the drag's final value into the live
522 // map, and the build that event fires catches p.pos up on the
523 // next rebuild — so the live value is the authoritative one to
524 // seek to.
525 secs := ui2.slider_value('vd_seek')
526 mpv.command_async(p.mpv_ctx, cmd_slider_seek, ['seek', '${secs:.3f}', 'absolute'])
527 }
528 }
529 'vd_volume' {
530 mpv.set_double_async(p.mpv_ctx, cmd_volume, 'volume', ui2.slider_value('vd_volume'))
531 }
532 'vd_volume_icon' {
533 mpv.set_flag_async(p.mpv_ctx, cmd_mute, 'mute', !p.muted)
534 }
535 else {}
536 }
537}
538
539// key runs a forwarded keyboard shortcut: space pauses, the arrows seek and
540// step the volume, m mutes — mpc-qt's control keys without the window-level
541// ones (fullscreen, panels) a host would not want stolen.
542pub fn (mut p Player) key(k string) {
543 if !p.accepts(p.pointer_x, p.pointer_y) {
544 return
545 }
546 match k {
547 ' ' {
548 p.toggle_play()
549 }
550 'left' {
551 if p.has_file {
552 mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '-5'])
553 }
554 }
555 'right' {
556 if p.has_file {
557 mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '5'])
558 }
559 }
560 'up' {
561 p.nudge_volume(p.cfg.volume_step)
562 }
563 'down' {
564 p.nudge_volume(-p.cfg.volume_step)
565 }
566 'm' {
567 mpv.set_flag_async(p.mpv_ctx, cmd_mute, 'mute', !p.muted)
568 }
569 else {}
570 }
571}
572
573// pointer_moved tracks the pointer and arms the overlay hide timer. Motion the
574// input scope rejects still moves the tracked position, but does not wake the
575// controls.
576pub fn (mut p Player) pointer_moved(x f64, y f64) {
577 p.pointer_x = x
578 p.pointer_y = y
579 if !p.accepts(x, y) {
580 return
581 }
582 p.last_motion = time.ticks()
583 // The controls hide on a rest deadline that a built frame checks. Nothing
584 // asks for a rebuild on its own while the pointer is still, so one chained
585 // timer is the ask that lets a build see the deadline pass. Motion itself
586 // never re-arms: the live timer's callback checks the deadline on its own
587 // schedule and re-arms for the remainder, so continuous motion costs one
588 // timer per link instead of a thread spawn per move. Docked controls never
589 // hide, so docked mode never arms the chain — arming it would only fire a
590 // no-op rebuild some seconds after every motion burst. The chain is
591 // needed under continuous redraw too: the loop repaints the retained
592 // tree every frame but still only rebuilds on ask.
593 if p.cfg.overlay && p.controls_wake == 0 {
594 p.controls_wake = ui2.after(f64(hide_deadline_ms + hide_wake_margin_ms) / 1000.0, fn [mut p] () {
595 p.controls_wake_tick()
596 })
597 }
598}
599
600// controls_wake_tick runs on the UI thread when the chained hide timer fires.
601// While the pointer is still moving it re-arms for what remains of the
602// deadline; once the deadline has really passed it asks for the refresh that
603// runs the hide-build, and the chain dies until new motion arms it again.
604fn (mut p Player) controls_wake_tick() {
605 p.controls_wake = 0
606 rest := hide_deadline_ms + hide_wake_margin_ms - (time.ticks() - p.last_motion)
607 if rest > 0 {
608 p.controls_wake = ui2.after(f64(rest) / 1000.0, fn [mut p] () {
609 p.controls_wake_tick()
610 })
611 return
612 }
613 ui2.request_refresh()
614}
615
616// glide_pos is the position the seek bar shows with the smooth bar on: the
617// last reported position carried forward at the playback speed since that
618// report landed. The glide re-anchors on every report, so between reports it
619// adds only the time that has actually passed — a bar that agrees with mpv's
620// own report when the report arrives instead of stepping to it.
621fn (p &Player) glide_pos() f64 {
622 if !p.smooth_bar || p.paused || p.smooth_anchor_t == 0 {
623 return p.pos
624 }
625 mut elapsed := f64(time.ticks() - p.smooth_anchor_t) / 1000.0
626 if elapsed > smooth_glide_cap {
627 elapsed = smooth_glide_cap
628 }
629 v := p.pos + elapsed * p.speed
630 if p.duration > 0 && v > p.duration {
631 return p.duration
632 }
633 return v
634}
635
636// smooth_frame runs at the end of every rendered frame and is the glide's
637// driver: it shows the extrapolated position with a paint-only slider write
638// and asks for the next frame, so the window keeps painting at the display
639// rate while the option runs. Pausing, hiding the strip, or the option turning
640// off all stop the ask, which is what returns the window to strictly asked
641// redraws.
642fn (mut p Player) smooth_frame() {
643 if !p.smooth_bar || !p.has_file || p.paused || !p.strip_shown() {
644 return
645 }
646 v := p.glide_pos()
647 if ui2.slider_value('vd_seek') == v {
648 return
649 }
650 ui2.set_slider_value('vd_seek', v)
651 // The write already asked for one paint; this ask is the next link of the
652 // chain, and the scheduler coalesces the two.
653 ui2.request_paint()
654}
655
656// mouse_button turns a right-button press over the video into play/pause, the
657// way the standalone player does over its video area. Left and middle clicks
658// pass through to the controls untouched.
659pub fn (mut p Player) mouse_button(button int, down bool, x f64, y f64) {
660 if !down || button != 1 || !p.over_video(x, y) {
661 return
662 }
663 p.toggle_play()
664}
665
666// wheel steps the volume while the pointer is over the widget; elsewhere the
667// wheel belongs to the host.
668pub fn (mut p Player) wheel(_ f64, dy f64) {
669 if dy == 0 || !p.accepts(p.pointer_x, p.pointer_y) {
670 return
671 }
672 step := if dy > 0 { p.cfg.volume_step } else { -p.cfg.volume_step }
673 p.nudge_volume(step)
674}
675
676// nudge_volume moves the volume by delta and writes it to mpv, clamped to the
677// 0..100 range the widget exposes (the standalone player's max-volume dialog
678// has no place in an embeddable control bar).
679fn (mut p Player) nudge_volume(delta f64) {
680 v := math.min(math.max(p.volume + delta, 0), 100)
681 p.volume = v
682 mpv.set_double_async(p.mpv_ctx, cmd_volume, 'volume', v)
683}
684
685// inside_frame reports whether a window point lands on the widget's frame.
686fn (p &Player) inside_frame(x f64, y f64) bool {
687 return x >= p.frame.x && x < p.frame.x + p.frame.width
688 && y >= p.frame.y && y < p.frame.y + p.frame.height
689}
690
691// accepts reports whether input at a window point reaches the widget under the
692// configured scope: only inside the frame when localised, anywhere when global.
693fn (p &Player) accepts(x f64, y f64) bool {
694 return p.cfg.input_scope == InputScope.window || p.inside_frame(x, y)
695}
696
697// over_video reports whether a window point lands on the picture rather than
698// on the control strip.
699fn (p &Player) over_video(x f64, y f64) bool {
700 if !p.accepts(x, y) {
701 return false
702 }
703 strip := control_box(p.frame)
704 lx := x - p.frame.x
705 ly := y - p.frame.y
706 return !(lx >= strip.x && lx < strip.x + strip.width && ly >= strip.y
707 && ly < strip.y + strip.height)
708}
709
710// drain_events reads mpv's queue so it never fills up. Property changes
711// update the state the next build reads, and ones the controls display ask
712// ui2 for a rebuild themselves: the frame relay only paints, so without these
713// asks a paused seek or a volume change would not reach the strip until some
714// other ask happened to rebuild. Unlike the standalone player this touches no
715// ui2 globals beyond its own controls: no menu bar, no timers beyond the hide
716// deadline. A host that drains early, before its own per-frame work, may do
717// so; the render drains again and finds the queue empty.
718pub fn (mut p Player) drain_events() {
719 mut wants_build := false
720 for {
721 ev := mpv.wait_event(p.mpv_ctx, 0)
722 id := mpv.event_id(ev)
723 if id == mpv.event_none {
724 break
725 }
726 match id {
727 mpv.event_file_loaded {
728 p.has_file = true
729 p.video_debug_dump('file-loaded')
730 // A fresh file gets display sync again; the watch re-arms on
731 // the next drain with the new file's counter baseline.
732 p.sync_fallback_done = false
733 p.sync_watch_t0 = 0
734 // The seek slider's range and the labels come with the file.
735 wants_build = true
736 }
737 mpv.event_end_file {
738 $if debug_cadence ? {
739 eprintln('CAD end-file pos=${p.pos:.1f} paused=${p.paused}')
740 }
741 p.has_file = false
742 p.pos = 0
743 // Labels, the play icon and the empty seek track change.
744 wants_build = true
745 }
746 mpv.event_property_change {
747 if p.apply_property(ev) {
748 wants_build = true
749 }
750 }
751 mpv.event_shutdown {
752 eprintln('libvendetta: mpv shut down')
753 }
754 mpv.event_log_message {
755 eprintln('mpv: ${mpv.log_message_text(ev).trim_space()}')
756 }
757 else {}
758 }
759 if !isnil(p.cfg.on_event) {
760 p.cfg.on_event(ev)
761 }
762 }
763 // One ask for the whole drain, however many properties changed: mpv
764 // delivers bursts (a file load observes everything at once), and the
765 // scheduler coalesces anyway, so one ask per burst is enough.
766 if wants_build {
767 ui2.request_refresh()
768 }
769 p.watch_display_sync()
770}
771
772// apply_property takes one property change into the mirrored state and asks
773// ui2 for what the change needs. Per-frame values (time-pos) paint only: the
774// seek thumb moves through set_slider_value over the retained tree, and the
775// elapsed label waits for the whole second it displays. Tree-visible state —
776// the labels, the volume/mute controls, pause — escalates to a rebuild.
777// Returns whether a rebuild was asked for.
778fn (mut p Player) apply_property(ev voidptr) bool {
779 // Match on the reply userdata instead of the property name: the name is a
780 // string allocation per event, and time-pos alone fires per video frame.
781 id := mpv.event_reply_userdata(ev)
782 match id {
783 obs_time_pos {
784 if v := mpv.property_double(ev) {
785 // The seek thumb follows per frame through a paint-only write;
786 // the strip shows the whole second, so a rebuild is only
787 // needed when the displayed second changes. mpv raises
788 // time-pos repeatedly at the same position, so this keeps the
789 // escalation at one build per second of wall playback.
790 mut jumped := false
791 if int(v) != int(p.pos) {
792 jumped = true
793 }
794 p.pos = v
795 // The glide re-anchors on every report, so the next frames
796 // extrapolate from the position mpv just landed on.
797 p.smooth_anchor_t = time.ticks()
798 if p.has_file && ui2.slider_value('vd_seek') != v {
799 ui2.set_slider_value('vd_seek', v)
800 }
801 return jumped
802 }
803 }
804 obs_duration {
805 if v := mpv.property_double(ev) {
806 if v != p.duration {
807 p.duration = v
808 return true
809 }
810 }
811 }
812 obs_volume {
813 if v := mpv.property_double(ev) {
814 if v != p.volume {
815 p.volume = v
816 // No readout shows the number, so the thumb is the whole
817 // change: a paint-only write, held off during a drag by
818 // ui2.
819 if ui2.slider_value('vd_volume') != v {
820 ui2.set_slider_value('vd_volume', v)
821 }
822 }
823 }
824 }
825 obs_pause {
826 if v := mpv.property_flag(ev) {
827 if v != p.paused {
828 p.paused = v
829 return true
830 }
831 }
832 }
833 obs_mute {
834 if v := mpv.property_flag(ev) {
835 if v != p.muted {
836 p.muted = v
837 return true
838 }
839 }
840 }
841 obs_speed {
842 if v := mpv.property_double(ev) {
843 p.speed = v
844 }
845 }
846 obs_path {
847 if v := mpv.property_string(ev) {
848 p.current_path = v
849 // The kind rides every path that lands, so what mpv calls a
850 // link stays a link without another string search.
851 p.current_kind = source_kind(v)
852 }
853 }
854 obs_mistimed {
855 if v := mpv.property_double(ev) {
856 p.mistimed = v
857 }
858 }
859 obs_vo_delayed {
860 if v := mpv.property_double(ev) {
861 p.vo_delayed = v
862 }
863 }
864 else {}
865 }
866 return false
867}
868
869// watch_display_sync steps video-sync down to audio sync for the rest of the
870// file when the display-sync pacing collapses. On files the pipeline cannot
871// hold the render stage stalls, the counters climb by the second, and holding
872// display sync turns the file into a slideshow; audio sync then leaves mpv's
873// own drop machinery in charge. The counters are cumulative, so the watch
874// compares them across a window instead of looking at levels, and it re-arms
875// per file.
876fn (mut p Player) watch_display_sync() {
877 if !p.has_file || p.sync_fallback_done {
878 return
879 }
880 now := time.ticks()
881 if p.sync_watch_t0 == 0 {
882 p.sync_watch_t0 = now
883 p.mistimed_at_watch = p.mistimed
884 p.vo_delayed_at_watch = p.vo_delayed
885 return
886 }
887 if now - p.sync_watch_t0 < sync_fallback_window_ms {
888 return
889 }
890 climbed := p.mistimed - p.mistimed_at_watch > sync_fallback_frames
891 || p.vo_delayed - p.vo_delayed_at_watch > sync_fallback_frames
892 if climbed {
893 p.sync_fallback_done = true
894 mpv.command_async(p.mpv_ctx, sync_fallback_userdata, ['set', 'video-sync', 'audio'])
895 }
896 p.sync_watch_t0 = now
897 p.mistimed_at_watch = p.mistimed
898 p.vo_delayed_at_watch = p.vo_delayed
899}
900
901// fmt_time renders seconds as mm:ss, or hh:mm:ss once the hours column earns
902// its place.
903pub fn fmt_time(seconds f64) string {
904 d := time.Duration(i64(seconds * f64(time.second)))
905 if seconds >= 60 * 60 {
906 return progress.fmt_time(d, .hhmmss)
907 }
908 return progress.fmt_time(d, .mmss)
909}
910