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