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