// libvendetta is vendetta as an embeddable widget. A host owns the window and // the event loop: it gives us a rectangle, folds the element we build into its // screen, and forwards the events it wants us to see. Everything that assumed // owning the app is gone — no menu bar (ui2 keeps it as a process global), no // settings file, no thumbnails, no fullscreen: the host decides what the // window does. // // player := libvendetta.new(libvendetta.Config{}) // ui2.set_gl_surface_renderer(fn [mut player] (id, frame, scale, height) { // player.render(id, frame, scale, height) // }) // // in the host's build callback: // children << player.build(ui2.rect(0, 0, b.width - 300, b.height)) // // in the host's event callback: // if event.starts_with('vd_') { // player.handle(event) // } module libvendetta import math import mpv import os import time import ui2 import wake import x.progress // The vinix-dark palette vendetta compiles in, so the widget reads like the // standalone player without a theme file system behind it. const slider_track_dark = 0x334155 const slider_value_blue = 0x3b82f6 const btn_blue = 0x3b82f6 const btn_secondary_slate = 0x64748b const text_main_white = u32(0xffffff) const text_muted_slate = 0xe2e8f0 const bg_dark_night = 0x020617 const bg_surface_slate = 0x1e293b // smooth_glide_cap bounds how far the smooth bar's glide may run ahead of the // last reported position, in seconds: a decoder that stalls its reports stops // the bar near where the picture is instead of letting it coast into the dark. const smooth_glide_cap = 0.5 // Palette groups the colours the widget paints. Hosts that want the widget to // match their own look can set Player.palette; the default is vendetta's. pub struct Palette { pub mut: slider_track u32 = slider_track_dark slider_value u32 = slider_value_blue btn_primary u32 = btn_blue btn_secondary u32 = btn_secondary_slate // The control strip's buttons: the play/pause toggle, the seek steps and // the mute toggle. They default to the strip's backdrop, so the glyphs // sit on the bar without boxes of their own; each keeps a field so a // host can split them apart again. btn_play u32 = btn_blue btn_seek u32 = bg_dark_night btn_mute u32 = bg_dark_night text_main u32 = text_main_white text_muted u32 = text_muted_slate bg_dark u32 = bg_dark_night bg_surface u32 = bg_surface_slate // The strip's backdrop in docked mode, where it sits statically; the // floating strip keeps bg_dark. bg_docked u32 = bg_dark_night } // Config holds the knobs a host can turn at construction. The rest of the // widget's behaviour is vendetta's own, so a host gets a media player, not a // pile of settings. pub struct Config { pub mut: // The control strip floats over the full-height video, or sits docked in // a band below it. overlay bool = true // How far the seek buttons jump, in seconds. seek_step f64 = 30 // How far one wheel or arrow key step moves the volume. volume_step f64 = 5 // Whether mpv's render call waits out each frame's target display time. // Disabling it trades presentation pacing for a snappier UI thread. block_target_time bool = true // Which forwarded input reaches the widget: frame (only input over its // frame; keys follow the pointer) or window (every forwarded event). input_scope InputScope = InputScope.frame // The audio server mpv's sound runs through, taken before mpv starts. A // name pins it ('pulse', 'alsa', ...), 'auto' hands the choice to mpv's // own autoprobing, and empty keeps the platform default: pulse on Linux // (PipeWire's audio init blocks mpv's core, so it is avoided), mpv's own // output on Windows and macOS (avfoundation there). ao string // pre_init receives mpv's handle after the widget's own options are set // and before mpv starts, for the options mpv reads only at start. pre_init fn (ctx voidptr) = unsafe { nil } // on_event receives every mpv event after the widget has taken its own // state from it, so a host can follow the properties it observes. on_event fn (ev voidptr) = unsafe { nil } // on_open receives every source load() is asked to open and may hand back a // different one — the link hook, where a host resolves a page or playlist // URL into the media URL mpv should actually fetch. // None keeps the source. Whatever load() does with the result is what it // would have done with the original: links reach mpv ungated, files keep // their existence check. on_open fn (path string) ?string = unsafe { nil } } // InputScope limits forwarded input to the widget's frame, or lets it act on // the whole window, so a host can embed the player without losing its own keys. pub enum InputScope { frame window } // Player is the embeddable player. Playback state is mirrored from observed // mpv properties, so hosts can read it directly between builds. pub struct Player { pub mut: // Playback state mirrored from mpv. has_file bool pos f64 duration f64 paused bool volume f64 = 100 max_volume f64 = 100 muted bool speed f64 = 1 current_path string // The kind of what current_path names — a link streams from the network, // a file exists locally — decided once as each observed path lands. Hosts // read this instead of searching paths for '://' on their own. current_kind MediaKind // The frame the host last built the widget into. Pointer handling maps // window coordinates against it, so events keep working when the host // moves or resizes the widget between builds. frame ui2.Rect pointer_x f64 pointer_y f64 last_motion i64 controls_wake u64 // The smooth seek bar: with it on and the file playing, the bar carries the // reported position forward at playback speed and the window redraws at the // display rate through paint-only frames. Off — the default — the bar moves // only when a report lands and nothing else redraws either. smooth_bar bool // The wall clock of the last time-pos report the glide extrapolates from; // zero until the first one lands. smooth_anchor_t i64 palette Palette cfg Config mpv_ctx voidptr render_ctx voidptr // Sources queued before the first draw; they load once the render context // exists, so mpv has somewhere to put the picture. startup []string clear_next bool // Playback instrumentation for the -d playback_probe build: presents are // the present() calls per second, and repeat_skips the mpv repeats // consumed without a draw. presents int repeat_skips int mistimed f64 vo_delayed f64 mut: surface Surface // The open-shape override's memory of the config's choice: load() holds // block_target_time down for links and restores the choice for files, so // the knob keeps meaning what the config said. block_target_time_saved bool sync_fallback_done bool sync_watch_t0 i64 mistimed_at_watch f64 vo_delayed_at_watch f64 // The frame-relay thread and its shutdown flag. The flag starts true: // there is nothing to park until the first draw spawns the relay. relay_stop bool = true relay_thread thread // The wake slot this player's render callback bumps. Claimed when the // relay spawns, released on destroy: two embedded players then wake only // their own relays instead of trading frame-rate asks. wake_slot int = -1 } // Observed property ids. The widget tracks the playback properties its // controls and the display-sync watch need, not the standalone player's full // statistics set. Events are matched by userdata, and a host may register // observers of its own on this context, so the widget's ids stay below 10: // hosts number their own observers from 1000 up. const obs_time_pos = u64(1) const obs_duration = u64(2) const obs_pause = u64(3) const obs_volume = u64(4) const obs_mute = u64(5) const obs_speed = u64(6) const obs_path = u64(7) const obs_mistimed = u64(8) const obs_vo_delayed = u64(9) // Reply userdata for the commands and writes below. Unique per kind so a // COMMAND_REPLY can tell them apart; the values follow the standalone // player's for the shared actions. const cmd_toggle_pause = u64(10) const cmd_slider_seek = u64(11) const cmd_volume = u64(12) const cmd_stop = u64(14) const cmd_mute = u64(16) const cmd_seek = u64(18) const cmd_loadfile = u64(20) const sync_fallback_userdata = u64(213) // The fallback watch tolerates short bursts of mis-timed or delayed frames // before stepping the sync mode down: a busy UI thread (GC pauses, a heavy // overlay) can easily hold the vo stage for tens of milliseconds, and // switching modes on that only churns mpv's own re-stabilization. The // thresholds are deliberately forgiving: mis-timing the watch can see takes // one pacing step to recover from, but a mode switch costs a resample. const sync_fallback_window_ms = 6000 const sync_fallback_frames = 60 // Element ids the widget builds. The vd_ prefix is the host's routing key. pub const video_surface_id = 'vd_video' const root_id = 'vd_root' // new builds a widget player. The render context is created on the first draw, // once the host's GL context is current. // hwdec_mode is the hwdec option for a player whose hardware decoding is on or // off. Android decodes through MediaCodec and copies each frame back, which is // the mode the render API can draw; mediacodec's zero-copy output has no surface // to land on here, and the frames stay black. pub fn hwdec_mode(on bool) string { $if android { return if on { 'mediacodec-copy' } else { 'no' } } return if on { 'auto-safe' } else { 'no' } } // video_debug_note marks a point on the file-open path when -d video_debug is // enabled; the no-op form keeps it out of normal builds. $if video_debug ? { pub fn video_debug_note(note string) { eprintln('VIDEO_DEBUG ${note}') } } $else { pub fn video_debug_note(_ string) {} } // video_debug_dump reports the properties that decide how mpv turns a decoded // frame into the surface. It is built only with -d video_debug, so a normal // player does not spend time converting properties or writing logcat lines. $if video_debug ? { fn (p &Player) video_debug_dump(reason string) { mut out := []string{} for name in ['current-vo', 'video-codec', 'video-format', 'hwdec-current', 'video-params/pixelformat', 'video-sync', 'deband', 'vf', 'video-aspect-override', 'video-unscaled', 'video-crop', 'gpu-api', 'gpu-context'] { value := mpv.get_string(p.mpv_ctx, name) or { '' } out << '${name}=${value}' } for name in ['width', 'height', 'dwidth', 'dheight', 'video-zoom', 'panscan', 'video-pan-x', 'video-pan-y', 'video-align-x', 'video-align-y', 'video-params/w', 'video-params/h', 'video-params/aspect', 'video-out-params/w', 'video-out-params/h', 'video-out-params/dw', 'video-out-params/dh', 'video-out-params/aspect', 'video-out-params/rotate', 'video-target-params/w', 'video-target-params/h', 'video-target-params/aspect', 'estimated-vf-fps', 'display-fps', 'time-pos', 'speed', 'osd-width', 'osd-height', 'osd-par'] { if value := mpv.get_double(p.mpv_ctx, name) { out << '${name}=${value:.4f}' } else { out << '${name}=' } } eprintln('VIDEO_DEBUG ${reason} surface=${p.surface.w}x${p.surface.h} ${out.join(' ')}') } } $else { fn (p &Player) video_debug_dump(_ string) {} } pub fn new(cfg Config) &Player { mut p := &Player{} p.setup(cfg) return p } // setup starts mpv on a Player the host embeds, for hosts whose player is a // larger struct than the widget. It mirrors the standalone player's options. pub fn (mut p Player) setup(cfg Config) { p.cfg = cfg register_android_vm() p.mpv_ctx = mpv.create() if p.mpv_ctx == unsafe { nil } { eprintln('libvendetta: mpv_create failed') return } // vo=libmpv hands frames to the render API; without it mpv opens a window // of its own. ao: mpv reads the audio server only before it starts, so the // host's choice lands here — a named server written as is, 'auto' as an // empty option, which is what mpv reads as its own autoprobing. Linux pins // pulse when the host has no choice: PipeWire's audio init blocks mpv's // core, so it is avoided. mpv.set_option(p.mpv_ctx, 'vo', 'libmpv') $if linux { ao := if cfg.ao.len == 0 { 'pulse' } else if cfg.ao == 'auto' { '' } else { cfg.ao } mpv.set_option(p.mpv_ctx, 'ao', ao) } $else $if android { // mpv's own default list starts with pulse, which this platform does // not have, so audiotrack is named unless the host chose another output. ao_name := if cfg.ao.len == 0 || cfg.ao == 'auto' { 'audiotrack' } else { cfg.ao } mpv.set_option(p.mpv_ctx, 'ao', ao_name) } $else { if cfg.ao.len > 0 && cfg.ao != 'auto' { mpv.set_option(p.mpv_ctx, 'ao', cfg.ao) } } mpv.set_option(p.mpv_ctx, 'keep-open', 'yes') // Hardware decoding is the host's call, not the widget's: the app mirrors // the saved setting right after setup, and a forced mode would silently // override the user's toggle on every start (Android's mediacodec-copy // did exactly that, re-enabling itself over an off setting). // Display sync cannot measure the vsync rate with the libmpv video output: // the player would wait forever for presentation feedback that never // comes. Hand mpv the monitor's refresh rate, and leave audio sync alone // where the rate cannot be detected (Wayland). Harmless while mpv stays // on audio sync, which is where the fallback below takes over anyway. rate := ui2.monitor_refresh_rate() if rate > 0 { mpv.set_option(p.mpv_ctx, 'display-fps-override', '${rate:.3f}') } $if video_debug ? { // The shader-chain path logs reconfigures, pass compilation and GL // errors at info/verbose; warn would carry none of that, and a // corrupted GLES path shows up there before anything pixel-visible. mpv.request_log_messages(p.mpv_ctx, 'v') } $else { mpv.request_log_messages(p.mpv_ctx, 'warn') } if !isnil(cfg.pre_init) { cfg.pre_init(p.mpv_ctx) } init_rc := mpv.initialize(p.mpv_ctx) if init_rc < 0 { eprintln('libvendetta: initialize: ${mpv.error_string(init_rc)}') } mpv.observe_property(p.mpv_ctx, obs_time_pos, 'time-pos', mpv.format_double) mpv.observe_property(p.mpv_ctx, obs_duration, 'duration', mpv.format_double) mpv.observe_property(p.mpv_ctx, obs_pause, 'pause', mpv.format_flag) mpv.observe_property(p.mpv_ctx, obs_volume, 'volume', mpv.format_double) mpv.observe_property(p.mpv_ctx, obs_mute, 'mute', mpv.format_flag) mpv.observe_property(p.mpv_ctx, obs_speed, 'speed', mpv.format_double) mpv.observe_property(p.mpv_ctx, obs_path, 'path', mpv.format_string) // The display-sync fallback watch reads the cumulative mis-timing // counters across a window; both report their own property change. mpv.observe_property(p.mpv_ctx, obs_mistimed, 'mistimed-frame-count', mpv.format_double) mpv.observe_property(p.mpv_ctx, obs_vo_delayed, 'vo-delayed-frame-count', mpv.format_double) } // MediaKind separates the two shapes a playable source comes in, and carries // the answer wherever the shape matters. A link names something mpv fetches // itself — https://, rtsp://, even mpv's own dvd:// — and never exists on the // filesystem, so the local-file handling would always reject it; a file names // a local path that has to exist to play. The classification used to be // re-derived at every gate by searching the string for '://', which nothing in // the code pointed at; source_kind answers once and the rest reads or carries // the kind. pub enum MediaKind { link file } // source_kind decides what a source names by its protocol prefix: '://' after // at least one character makes it a link, anything else a file. It is the one // such search in the tree — every other step routes on the kind, handed in or // mirrored onto Player.current_kind as the path lands. pub fn source_kind(source string) MediaKind { if source.index_('://') > 0 { return .link } return .file } // load queues a file for playback. Before the first draw the file waits in the // startup list and loads as the render context comes up; afterwards it is // appended to mpv's playlist directly. // // The on_open hook runs first and may replace the source — the link hook, // where a host resolves a page or playlist URL into the media URL mpv should // open. The replacement faces the same gate the original would have. pub fn (mut p Player) load(path string) { mut target := path if !isnil(p.cfg.on_open) { if v := p.cfg.on_open(path) { target = v } } // The shape is decided once, on the replaced source, and each gate below // reads the kind instead of searching the string for '://' again. kind := source_kind(target) if kind == .link { // Livestreams arrive in bursts with a variable frame rate, so mpv's // target display time prediction drifts and the render call would block // the UI thread waiting for a time that has already passed. Present // immediately instead: mpv still sheds what cannot be shown. The override // only holds while links are what is being opened — a local file // restores the config's choice, so an explicit --no-block-target-time // stays in effect there. if p.cfg.block_target_time { p.block_target_time_saved = true p.cfg.block_target_time = false } } else { if p.block_target_time_saved { p.cfg.block_target_time = p.block_target_time_saved p.block_target_time_saved = false } target = os.abs_path(target) if !os.exists(target) { eprintln('libvendetta: no such file: ${target}') return } } if p.render_ctx != unsafe { nil } { video_debug_note('load: command_async append-play') mpv.command_async(p.mpv_ctx, cmd_loadfile, ['loadfile', target, 'append-play']) return } video_debug_note('load: queued for startup') p.startup << target } // stop ends playback and leaves the last picture on the surface until the // next load clears it, the way keep-open does. pub fn (mut p Player) stop() { if p.mpv_ctx != unsafe { nil } { mpv.command_async(p.mpv_ctx, cmd_stop, ['stop']) } p.has_file = false p.pos = 0 p.clear_next = true } // toggle_play pauses or resumes, for hosts driving the player programmatically. pub fn (mut p Player) toggle_play() { if p.mpv_ctx != unsafe { nil } { mpv.set_flag_async(p.mpv_ctx, cmd_toggle_pause, 'pause', !p.paused) } } // set_overlay switches the control layout between the strip floating over the // full-height video and the docked strip below it. Config is built once at new(), // so a host that wants to change modes at runtime goes through this method. pub fn (mut p Player) set_overlay(overlay bool) { p.cfg.overlay = overlay } // set_input_scope switches forwarded input between the widget's frame and the // whole window at runtime. pub fn (mut p Player) set_input_scope(scope InputScope) { p.cfg.input_scope = scope } // destroy frees mpv. Call it after the host's window is gone; the render // context dies with it. The relay thread is parked for good first — a join // before the contexts die keeps a teardown-and-re-embed host from leaking a // thread per cycle — and a pending hide chain is cancelled so its callback // never fires on a torn-down player. pub fn (mut p Player) destroy() { p.stop_relay() if p.controls_wake != 0 { ui2.cancel_timer(p.controls_wake) p.controls_wake = 0 } if p.wake_slot >= 0 { wake.release(p.wake_slot) p.wake_slot = -1 } if p.render_ctx != unsafe { nil } { mpv.render_context_free(p.render_ctx) p.render_ctx = unsafe { nil } } if p.mpv_ctx != unsafe { nil } { mpv.destroy(p.mpv_ctx) p.mpv_ctx = unsafe { nil } } } // handle runs an event whose id belongs to the widget. The host forwards any // id it does not consume itself; unknown ids are dropped, so a host can route // blindly. pub fn (mut p Player) handle(event string) { match event { 'vd_toggle' { p.toggle_play() } 'vd_seek_back' { if p.has_file { mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '-${p.cfg.seek_step:.0f}']) } } 'vd_seek_forward' { if p.has_file { mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '${p.cfg.seek_step:.0f}']) } } 'vd_seek' { if p.has_file { // The release committed the drag's final value into the live // map, and the build that event fires catches p.pos up on the // next rebuild — so the live value is the authoritative one to // seek to. secs := ui2.slider_value('vd_seek') mpv.command_async(p.mpv_ctx, cmd_slider_seek, ['seek', '${secs:.3f}', 'absolute']) } } 'vd_volume' { mpv.set_double_async(p.mpv_ctx, cmd_volume, 'volume', ui2.slider_value('vd_volume')) } 'vd_volume_icon' { mpv.set_flag_async(p.mpv_ctx, cmd_mute, 'mute', !p.muted) } else {} } } // key runs a forwarded keyboard shortcut: space pauses, the arrows seek and // step the volume, m mutes — mpc-qt's control keys without the window-level // ones (fullscreen, panels) a host would not want stolen. pub fn (mut p Player) key(k string) { if !p.accepts(p.pointer_x, p.pointer_y) { return } match k { ' ' { p.toggle_play() } 'left' { if p.has_file { mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '-5']) } } 'right' { if p.has_file { mpv.command_async(p.mpv_ctx, cmd_seek, ['seek', '5']) } } 'up' { p.nudge_volume(p.cfg.volume_step) } 'down' { p.nudge_volume(-p.cfg.volume_step) } 'm' { mpv.set_flag_async(p.mpv_ctx, cmd_mute, 'mute', !p.muted) } else {} } } // pointer_moved tracks the pointer and arms the overlay hide timer. Motion the // input scope rejects still moves the tracked position, but does not wake the // controls. pub fn (mut p Player) pointer_moved(x f64, y f64) { p.pointer_x = x p.pointer_y = y if !p.accepts(x, y) { return } p.last_motion = time.ticks() // The controls hide on a rest deadline that a built frame checks. Nothing // asks for a rebuild on its own while the pointer is still, so one chained // timer is the ask that lets a build see the deadline pass. Motion itself // never re-arms: the live timer's callback checks the deadline on its own // schedule and re-arms for the remainder, so continuous motion costs one // timer per link instead of a thread spawn per move. Docked controls never // hide, so docked mode never arms the chain — arming it would only fire a // no-op rebuild some seconds after every motion burst. The chain is // needed under continuous redraw too: the loop repaints the retained // tree every frame but still only rebuilds on ask. if p.cfg.overlay && p.controls_wake == 0 { p.controls_wake = ui2.after(f64(hide_deadline_ms + hide_wake_margin_ms) / 1000.0, fn [mut p] () { p.controls_wake_tick() }) } } // controls_wake_tick runs on the UI thread when the chained hide timer fires. // While the pointer is still moving it re-arms for what remains of the // deadline; once the deadline has really passed it asks for the refresh that // runs the hide-build, and the chain dies until new motion arms it again. fn (mut p Player) controls_wake_tick() { p.controls_wake = 0 rest := hide_deadline_ms + hide_wake_margin_ms - (time.ticks() - p.last_motion) if rest > 0 { p.controls_wake = ui2.after(f64(rest) / 1000.0, fn [mut p] () { p.controls_wake_tick() }) return } ui2.request_refresh() } // glide_pos is the position the seek bar shows with the smooth bar on: the // last reported position carried forward at the playback speed since that // report landed. The glide re-anchors on every report, so between reports it // adds only the time that has actually passed — a bar that agrees with mpv's // own report when the report arrives instead of stepping to it. fn (p &Player) glide_pos() f64 { if !p.smooth_bar || p.paused || p.smooth_anchor_t == 0 { return p.pos } mut elapsed := f64(time.ticks() - p.smooth_anchor_t) / 1000.0 if elapsed > smooth_glide_cap { elapsed = smooth_glide_cap } v := p.pos + elapsed * p.speed if p.duration > 0 && v > p.duration { return p.duration } return v } // smooth_frame runs at the end of every rendered frame and is the glide's // driver: it shows the extrapolated position with a paint-only slider write // and asks for the next frame, so the window keeps painting at the display // rate while the option runs. Pausing, hiding the strip, or the option turning // off all stop the ask, which is what returns the window to strictly asked // redraws. fn (mut p Player) smooth_frame() { if !p.smooth_bar || !p.has_file || p.paused || !p.strip_shown() { return } v := p.glide_pos() if ui2.slider_value('vd_seek') == v { return } ui2.set_slider_value('vd_seek', v) // The write already asked for one paint; this ask is the next link of the // chain, and the scheduler coalesces the two. ui2.request_paint() } // mouse_button turns a right-button press over the video into play/pause, the // way the standalone player does over its video area. Left and middle clicks // pass through to the controls untouched. pub fn (mut p Player) mouse_button(button int, down bool, x f64, y f64) { if !down || button != 1 || !p.over_video(x, y) { return } p.toggle_play() } // wheel steps the volume while the pointer is over the widget; elsewhere the // wheel belongs to the host. pub fn (mut p Player) wheel(_ f64, dy f64) { if dy == 0 || !p.accepts(p.pointer_x, p.pointer_y) { return } step := if dy > 0 { p.cfg.volume_step } else { -p.cfg.volume_step } p.nudge_volume(step) } // nudge_volume moves the volume by delta and writes it to mpv, clamped to the // 0..100 range the widget exposes (the standalone player's max-volume dialog // has no place in an embeddable control bar). fn (mut p Player) nudge_volume(delta f64) { v := math.min(math.max(p.volume + delta, 0), 100) p.volume = v mpv.set_double_async(p.mpv_ctx, cmd_volume, 'volume', v) } // inside_frame reports whether a window point lands on the widget's frame. fn (p &Player) inside_frame(x f64, y f64) bool { return x >= p.frame.x && x < p.frame.x + p.frame.width && y >= p.frame.y && y < p.frame.y + p.frame.height } // accepts reports whether input at a window point reaches the widget under the // configured scope: only inside the frame when localised, anywhere when global. fn (p &Player) accepts(x f64, y f64) bool { return p.cfg.input_scope == InputScope.window || p.inside_frame(x, y) } // over_video reports whether a window point lands on the picture rather than // on the control strip. fn (p &Player) over_video(x f64, y f64) bool { if !p.accepts(x, y) { return false } strip := control_box(p.frame) lx := x - p.frame.x ly := y - p.frame.y return !(lx >= strip.x && lx < strip.x + strip.width && ly >= strip.y && ly < strip.y + strip.height) } // drain_events reads mpv's queue so it never fills up. Property changes // update the state the next build reads, and ones the controls display ask // ui2 for a rebuild themselves: the frame relay only paints, so without these // asks a paused seek or a volume change would not reach the strip until some // other ask happened to rebuild. Unlike the standalone player this touches no // ui2 globals beyond its own controls: no menu bar, no timers beyond the hide // deadline. A host that drains early, before its own per-frame work, may do // so; the render drains again and finds the queue empty. pub fn (mut p Player) drain_events() { mut wants_build := false for { ev := mpv.wait_event(p.mpv_ctx, 0) id := mpv.event_id(ev) if id == mpv.event_none { break } match id { mpv.event_file_loaded { p.has_file = true p.video_debug_dump('file-loaded') // A fresh file gets display sync again; the watch re-arms on // the next drain with the new file's counter baseline. p.sync_fallback_done = false p.sync_watch_t0 = 0 // The seek slider's range and the labels come with the file. wants_build = true } mpv.event_end_file { $if debug_cadence ? { eprintln('CAD end-file pos=${p.pos:.1f} paused=${p.paused}') } p.has_file = false p.pos = 0 // Labels, the play icon and the empty seek track change. wants_build = true } mpv.event_property_change { if p.apply_property(ev) { wants_build = true } } mpv.event_shutdown { eprintln('libvendetta: mpv shut down') } mpv.event_log_message { eprintln('mpv: ${mpv.log_message_text(ev).trim_space()}') } else {} } if !isnil(p.cfg.on_event) { p.cfg.on_event(ev) } } // One ask for the whole drain, however many properties changed: mpv // delivers bursts (a file load observes everything at once), and the // scheduler coalesces anyway, so one ask per burst is enough. if wants_build { ui2.request_refresh() } p.watch_display_sync() } // apply_property takes one property change into the mirrored state and asks // ui2 for what the change needs. Per-frame values (time-pos) paint only: the // seek thumb moves through set_slider_value over the retained tree, and the // elapsed label waits for the whole second it displays. Tree-visible state — // the labels, the volume/mute controls, pause — escalates to a rebuild. // Returns whether a rebuild was asked for. fn (mut p Player) apply_property(ev voidptr) bool { // Match on the reply userdata instead of the property name: the name is a // string allocation per event, and time-pos alone fires per video frame. id := mpv.event_reply_userdata(ev) match id { obs_time_pos { if v := mpv.property_double(ev) { // The seek thumb follows per frame through a paint-only write; // the strip shows the whole second, so a rebuild is only // needed when the displayed second changes. mpv raises // time-pos repeatedly at the same position, so this keeps the // escalation at one build per second of wall playback. mut jumped := false if int(v) != int(p.pos) { jumped = true } p.pos = v // The glide re-anchors on every report, so the next frames // extrapolate from the position mpv just landed on. p.smooth_anchor_t = time.ticks() if p.has_file && ui2.slider_value('vd_seek') != v { ui2.set_slider_value('vd_seek', v) } return jumped } } obs_duration { if v := mpv.property_double(ev) { if v != p.duration { p.duration = v return true } } } obs_volume { if v := mpv.property_double(ev) { if v != p.volume { p.volume = v // No readout shows the number, so the thumb is the whole // change: a paint-only write, held off during a drag by // ui2. if ui2.slider_value('vd_volume') != v { ui2.set_slider_value('vd_volume', v) } } } } obs_pause { if v := mpv.property_flag(ev) { if v != p.paused { p.paused = v return true } } } obs_mute { if v := mpv.property_flag(ev) { if v != p.muted { p.muted = v return true } } } obs_speed { if v := mpv.property_double(ev) { p.speed = v } } obs_path { if v := mpv.property_string(ev) { p.current_path = v // The kind rides every path that lands, so what mpv calls a // link stays a link without another string search. p.current_kind = source_kind(v) } } obs_mistimed { if v := mpv.property_double(ev) { p.mistimed = v } } obs_vo_delayed { if v := mpv.property_double(ev) { p.vo_delayed = v } } else {} } return false } // watch_display_sync steps video-sync down to audio sync for the rest of the // file when the display-sync pacing collapses. On files the pipeline cannot // hold the render stage stalls, the counters climb by the second, and holding // display sync turns the file into a slideshow; audio sync then leaves mpv's // own drop machinery in charge. The counters are cumulative, so the watch // compares them across a window instead of looking at levels, and it re-arms // per file. fn (mut p Player) watch_display_sync() { if !p.has_file || p.sync_fallback_done { return } now := time.ticks() if p.sync_watch_t0 == 0 { p.sync_watch_t0 = now p.mistimed_at_watch = p.mistimed p.vo_delayed_at_watch = p.vo_delayed return } if now - p.sync_watch_t0 < sync_fallback_window_ms { return } climbed := p.mistimed - p.mistimed_at_watch > sync_fallback_frames || p.vo_delayed - p.vo_delayed_at_watch > sync_fallback_frames if climbed { p.sync_fallback_done = true mpv.command_async(p.mpv_ctx, sync_fallback_userdata, ['set', 'video-sync', 'audio']) } p.sync_watch_t0 = now p.mistimed_at_watch = p.mistimed p.vo_delayed_at_watch = p.vo_delayed } // fmt_time renders seconds as mm:ss, or hh:mm:ss once the hours column earns // its place. pub fn fmt_time(seconds f64) string { d := time.Duration(i64(seconds * f64(time.second))) if seconds >= 60 * 60 { return progress.fmt_time(d, .hhmmss) } return progress.fmt_time(d, .mmss) }