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