vendetta / src / main.v
491 lines · 481 sloc · 24.22 KB · d81505db14fa82ca3fd312aab073a648c7b38fbc
Raw
1import os
2import ui2
3import libvendetta
4import libvendetta.mpv
5import flag as cliflag
6import time
7
8// The macOS build reaches ui2's custom renderer and sokol's GL backend only
9// through comptime defines: without them ui2 defaults macOS to its native
10// AppKit backend, whose API this file's window and stats calls are not part
11// of. This guard runs before the errors that missing define would raise
12// below, so the fix names itself.
13$if macos && !ui2_custom_rendering ? {
14 $compile_error("the macOS build needs -d ui2_custom_rendering: vendetta renders through ui2's custom GL renderer, and macOS defaults ui2 to its AppKit backend (see AGENTS.md: v -os macos -d ui2_custom_rendering -d darwin_sokol_glcore33 -o vendetta src)")
15}
16
17// footer_text is the help footer. Linux keeps the literal ~/.config form it
18// has always shown; the other platforms interpolate their own config
19// directory, and the separators follow the platform's path style. Android's
20// config base is the app's internal files directory, which config_base names.
21// window_refresh picks the window's redraw policy. On Android the on-demand policy
22// leaves playback unpainted between user events, so the window repaints at the
23// display rate there.
24fn window_refresh(player &Player) ui2.RefreshMode {
25 $if android {
26 return ui2.RefreshMode.continuous
27 }
28 if player.continuous {
29 return ui2.RefreshMode.continuous
30 }
31 return ui2.RefreshMode.on_demand
32}
33
34fn footer_text() string {
35 mut base := '~/.config/vendetta'
36 mut sep := '/'
37 $if android {
38 base = '${config_base()}/vendetta'
39 } $else {
40 $if !linux {
41 base = '${os.user_config_dir() or { os.home_dir() }}${sep}vendetta'
42 }
43 }
44 $if windows {
45 sep = '\\'
46 }
47 return 'video files open in order: the first plays, the rest queue up.
48themes live in ${base}${sep}themes, queues in ${base}${sep}queues,
49option presets in ${base}${sep}presets.
50
51examples:
52 vendetta movie.mkv open a file
53 vendetta https://example.com/live.m3u8 open a link
54 vendetta --fullscreen --volume 20 a.mkv start fullscreen, quiet
55 vendetta --start-at 1:30 --no-overlay b.mkv
56 vendetta --mpv-opt hwdec=no --mpv-opt cache=yes c.mkv pass mpv options'
57}
58
59// Config maps the command line: --help and --theme are flags, and every
60// argument left over is a video file to open, so flags never end up in the
61// file list.
62struct Config {
63 show_help bool @[long: help; short: h; xdoc: 'Show this help text and exit']
64 theme string @[xdoc: 'Theme file, without .toml, from ~/.config/vendetta/themes (default: the saved theme, else vendetta)']
65 volume f64 = -1 @[xdoc: 'Initial volume, 0 to 100 (default: the saved volume)']
66 mute bool @[xdoc: 'Start muted']
67 speed f64 = -1 @[xdoc: 'Playback speed, 0.01 to 100 (default: the saved speed)']
68 fullscreen bool @[xdoc: 'Start in fullscreen']
69 overlay bool @[xdoc: 'Start with overlay controls']
70 no_overlay bool @[long: 'no-overlay'; xdoc: 'Start without overlay controls']
71 loop_file bool @[long: 'loop'; xdoc: 'Loop the current file']
72 loop_playlist bool @[long: 'loop-playlist'; xdoc: 'Loop the playlist']
73 hwdec bool @[xdoc: 'Enable hardware decoding (default)']
74 no_hwdec bool @[long: 'no-hwdec'; xdoc: 'Disable hardware decoding']
75 deinterlace bool @[xdoc: 'Enable deinterlacing']
76 low_quality bool @[long: 'low-quality'; xdoc: 'Skip non-critical rendering (preview, panel refreshes) when frames run past the 60 Hz budget']
77 preview bool @[xdoc: 'Start with the seek-bar hover preview (default: the saved setting)']
78 no_preview bool @[long: 'no-preview'; xdoc: 'Start without the seek-bar hover preview, and never create the hidden thumbnail mpv instance (saves memory on low-end machines)']
79 smooth_bar bool @[long: 'smooth-bar'; xdoc: 'Start with the smooth seek bar: while the file plays, the UI redraws at the display rate so the bar glides between mpv\'s position reports']
80 no_smooth_bar bool @[long: 'no-smooth-bar'; xdoc: 'Start with strictly asked redraws only: the bar steps to each position report mpv makes']
81 slider_height f64 = -1 @[long: 'slider-height'; xdoc: 'Height of the seek and volume bars in pixels, 1 to 30 (default: the saved setting)']
82 media_controls bool @[long: 'media-controls'; xdoc: 'Expose the desktop media controls (MPRIS on the session bus) (default: the saved setting)']
83 no_media_controls bool @[long: 'no-media-controls'; xdoc: 'Do not expose the desktop media controls']
84 ao string @[long: 'ao'; xdoc: 'Audio server: auto (mpv\'s autoprobing) or a named output, e.g. pipewire, pulse, alsa (default: the saved audio server)']
85 display_fps f64 = -1 @[long: 'display-fps'; xdoc: 'Display refresh rate for mpv display-sync, in Hz (default: detected from X11 RandR)']
86 no_block_target_time bool @[long: 'no-block-target-time'; xdoc: 'Present as soon as a frame is consumed instead of waiting inside the render call for mpv\'s target display time (the default). Try it if the UI feels unresponsive during playback.']
87 start_at string @[long: 'start-at'; xdoc: 'Start at a position: seconds or mm:ss (e.g. 90 or 1:30)']
88 sub_file string @[long: 'sub-file'; xdoc: 'Load an extra subtitle file']
89 mpv_opts []string @[long: 'mpv-opt'; xdoc: 'Set an mpv option, name=value; may be repeated (e.g. --mpv-opt hwdec=no --mpv-opt cache=yes). Applied before mpv starts, so non-runtime options like vf also work. The options vendetta mirrors itself (volume, speed, hwdec, loops, the audio server) follow the dedicated flags instead. An empty value unsets the option, dropping it from the saved settings.']
90 files []string @[tail]
91}
92
93// set_mpv_option sets an option and logs a warning when mpv rejects it: a
94// typo'd name or an outdated value would otherwise silently leave the default
95// in effect, changing playback behaviour with nothing in the log. It reports
96// whether mpv accepted the option.
97fn set_mpv_option(ctx voidptr, name string, value string) bool {
98 rc := mpv.set_option(ctx, name, value)
99 if rc < 0 {
100 eprintln('vendetta: mpv option ${name}=${value}: ${mpv.error_string(rc)}')
101 }
102 return rc == 0
103}
104
105// parse_mpv_option splits a --mpv-opt entry at its first = into the option
106// name and value, the way mpv reads its own --name=value. Values may contain
107// further = signs, so only the name is peeled off.
108fn parse_mpv_option(raw string) ?(string, string) {
109 i := raw.index('=')?
110 return raw[..i], raw[i + 1..]
111}
112
113// resolve_ao picks the audio server the player runs on: the --ao flag wins
114// over the saved choice, and anything the platform's server list cannot offer
115// falls back to mpv's autoprobing instead of forcing an output that would
116// fail to open.
117fn resolve_ao(saved string, from_cli string) string {
118 names := audio_server_names()
119 if from_cli.len > 0 {
120 if from_cli in names {
121 return from_cli
122 }
123 eprintln('vendetta: unknown audio server: ${from_cli} (available: ${names.join(', ')})')
124 }
125 return if saved in names { saved } else { 'auto' }
126}
127
128// apply_start_options sets the options the command line gives before mpv
129// starts, so even the ones that cannot change at runtime (vf, cache, vo...)
130// reach it. Options keep applying across sessions: the accepted entries seed
131// player.mpv_opts, which the saved settings mirror. An option given an empty
132// value unsets instead: it stops being carried in the saved settings, undoing
133// one set through Options > Set option....
134fn apply_start_options(mut player &Player, ctx voidptr, cfg Config) {
135 // Display sync cannot measure the vsync rate with the libmpv video output,
136 // so the monitor's refresh rate is given on the command line for multi-monitor
137 // and Wayland setups where detection cannot know which screen the window is on.
138 if cfg.display_fps > 0 {
139 set_mpv_option(ctx, 'display-fps-override', '${cfg.display_fps:.3f}')
140 }
141 for raw in cfg.mpv_opts {
142 name, value := parse_mpv_option(raw) or {
143 eprintln('vendetta: mpv-opt must be name=value: ${raw}')
144 continue
145 }
146 // An empty value unsets: mpv gets the empty write (string options
147 // clear, the rest refuse it with a warning above) and the option
148 // leaves the configured set no matter what mpv said.
149 if value.len == 0 {
150 set_mpv_option(ctx, name, value)
151 player.mpv_opts.delete(name)
152 continue
153 }
154 if !set_mpv_option(ctx, name, value) {
155 continue
156 }
157 player.mpv_opts[name] = value
158 }
159}
160
161fn main() {
162 migrate_legacy_config()
163 cfg, _ := cliflag.to_struct[Config](os.args, skip: 1) or {
164 eprintln('vendetta: ${err}')
165 exit(1)
166 }
167 if cfg.show_help {
168 println(cliflag.to_doc[Config](
169 name: 'Vendetta'
170 version: '0.0.0'
171 description: 'an mpv backed media player written in V'
172 footer: footer_text()
173 ) or { '' })
174 return
175 }
176 mut startup := []string{}
177 for arg in cfg.files {
178 // The shape of each argument is decided here, where it arrives, and
179 // the branch reads the kind: a link has no filesystem existence to
180 // check and abs_path would mangle the URL anyway, so it rides
181 // verbatim; a file is made absolute and has to exist.
182 if libvendetta.source_kind(arg) == .link {
183 startup << arg
184 continue
185 }
186 path := os.abs_path(arg)
187 if os.exists(path) {
188 startup << path
189 } else {
190 eprintln('vendetta: no such file: ${arg}')
191 }
192 }
193 mut player := &Player{
194 queue: startup.clone()
195 theme: default_theme()
196 media_chan: chan MediaData{cap: 8}
197 }
198 // The queue sidebar's reorder container names rows with generated keys
199 // (paths can repeat), so the startup queue is keyed before the first build.
200 player.queue_reset_keys()
201 // The last session's queue comes back when the command line opened
202 // nothing: restored rows sit in the sidebar and mpv's playlist, and
203 // nothing plays until a row is clicked or a later file serves the
204 // entry (resume_pending_queue's plain appends, first frame). A start
205 // with files passed on it belongs to the command line instead.
206 if startup.len == 0 {
207 player.restore_queue(load_queue_state().paths)
208 }
209 if !ui2.file_dialog_supported() {
210 notice := file_dialog_notice()
211 if notice.len > 0 {
212 player.notify(notice)
213 }
214 }
215 // The audio server resolves before the widget starts mpv: the --ao flag
216 // outranks the saved choice, and a value this platform's server list
217 // cannot offer demotes to mpv's autoprobing rather than forcing a server
218 // that would fail to open.
219 settings := load_settings()
220 player.ao = resolve_ao(settings.ao, cfg.ao)
221 // The widget starts mpv. vo=libmpv, keep-open and the display rate are its
222 // defaults, plus the audio server resolved above; pre_init adds the
223 // command line's own options before mpv starts, and on_event hands each
224 // mpv event to the app's menus and lists.
225 player.setup(libvendetta.Config{
226 block_target_time: !cfg.no_block_target_time
227 input_scope: libvendetta.InputScope.window
228 ao: player.ao
229 pre_init: fn [mut player, cfg] (ctx voidptr) {
230 apply_start_options(mut player, ctx, cfg)
231 }
232 on_event: fn [mut player] (ev voidptr) {
233 player.on_mpv_event(ev)
234 }
235 })
236 if player.mpv_ctx == unsafe { nil } {
237 eprintln('vendetta: mpv_create failed')
238 return
239 }
240 // Hardware decoding on by default; the Playback menu can turn it off per
241 // session. auto-safe skips methods the driver cannot actually deliver
242 // (plain auto happily picks a broken Vulkan path).
243 player.hwdec = true
244 // Saved settings mirror into the player and mpv: volume, speed, the loop
245 // flags, overlay modes, panel visibility and the picture overrides.
246 player.apply_settings(settings)
247 // Command line flags win over saved settings.
248 player.apply_cli(cfg)
249 player.sync_overlay()
250 // Performance mode is the redraw budget's backstop: it takes the
251 // continuous redraw away until it is turned off, whichever way the
252 // session started with it.
253 if player.low_quality {
254 player.continuous = false
255 }
256 // The menu's mpv flag toggles show what mpv is actually doing, so the
257 // state comes from the observed properties (mpv reports the current value
258 // as soon as it is observed); nothing writes these options at start.
259 mpv.observe_property(player.mpv_ctx, obs_aid, 'aid', mpv.format_string)
260 mpv.observe_property(player.mpv_ctx, obs_sid, 'sid', mpv.format_string)
261 mpv.observe_property(player.mpv_ctx, obs_vid, 'vid', mpv.format_string)
262 mpv.observe_property(player.mpv_ctx, obs_audio_device, 'audio-device', mpv.format_string)
263 mpv.observe_property(player.mpv_ctx, obs_ao, 'ao', mpv.format_string)
264 mpv.observe_property(player.mpv_ctx, obs_playlist_pos, 'playlist-pos', mpv.format_string)
265 // The media controls' own observers: time-pos announces jumps as Seeked
266 // signals, duration joins the announcements when it arrives, and volume
267 // follows every write (strip slider, keys, wheel, the menu). Only the
268 // -d mpris build has a consumer, so the default build does not ask mpv
269 // for these per-frame events.
270 $if mpris ? {
271 mpv.observe_property(player.mpv_ctx, obs_mpris_pos, 'time-pos', mpv.format_double)
272 mpv.observe_property(player.mpv_ctx, obs_duration_mpris, 'duration', mpv.format_double)
273 mpv.observe_property(player.mpv_ctx, obs_mpris_volume, 'volume', mpv.format_double)
274 mpv.observe_property(player.mpv_ctx, obs_mpris_loop, 'loop-file', mpv.format_string)
275 mpv.observe_property(player.mpv_ctx, obs_mpris_loop_playlist, 'loop-playlist', mpv.format_string)
276 mpv.observe_property(player.mpv_ctx, obs_media_artist, 'metadata/by-key/artist', mpv.format_string)
277 }
278 // The window title carries the playing file's name, so media-title is
279 // observed in every build (the mpris build's xesam:title reads the same
280 // mirror that update_window_title consumes).
281 mpv.observe_property(player.mpv_ctx, obs_media_title, 'media-title', mpv.format_string)
282 // Playback statistics for the popup; each reports its own property change.
283 mpv.observe_property(player.mpv_ctx, obs_fps, 'fps', mpv.format_double)
284 mpv.observe_property(player.mpv_ctx, obs_vf_fps, 'estimated-vf-fps', mpv.format_double)
285 mpv.observe_property(player.mpv_ctx, obs_display_fps, 'estimated-display-fps', mpv.format_double)
286 mpv.observe_property(player.mpv_ctx, obs_avsync, 'avsync', mpv.format_double)
287 mpv.observe_property(player.mpv_ctx, obs_avsync_change, 'total-avsync-change', mpv.format_double)
288 mpv.observe_property(player.mpv_ctx, obs_vsync_jitter, 'vsync-jitter', mpv.format_double)
289 mpv.observe_property(player.mpv_ctx, obs_vsync_ratio, 'vsync-ratio', mpv.format_double)
290 mpv.observe_property(player.mpv_ctx, obs_video_speed_corr, 'video-speed-correction', mpv.format_double)
291 mpv.observe_property(player.mpv_ctx, obs_audio_speed_corr, 'audio-speed-correction', mpv.format_double)
292 mpv.observe_property(player.mpv_ctx, obs_decoder_dropped, 'decoder-frame-drop-count', mpv.format_double)
293 mpv.observe_property(player.mpv_ctx, obs_display_dropped, 'drop-frame-count', mpv.format_double)
294 mpv.observe_property(player.mpv_ctx, obs_video_bitrate, 'video-bitrate', mpv.format_double)
295 mpv.observe_property(player.mpv_ctx, obs_audio_bitrate, 'audio-bitrate', mpv.format_double)
296 mpv.observe_property(player.mpv_ctx, obs_cache_time, 'demuxer-cache-time', mpv.format_double)
297 mpv.observe_property(player.mpv_ctx, obs_cache_duration, 'demuxer-cache-duration', mpv.format_double)
298 mpv.observe_property(player.mpv_ctx, obs_cache_buffering, 'cache-buffering-state', mpv.format_double)
299 mpv.observe_property(player.mpv_ctx, obs_video_w, 'video-params/w', mpv.format_double)
300 mpv.observe_property(player.mpv_ctx, obs_video_h, 'video-params/h', mpv.format_double)
301 mpv.observe_property(player.mpv_ctx, obs_hwdec_current, 'hwdec-current', mpv.format_string)
302 mpv.observe_property(player.mpv_ctx, obs_interpolation, 'interpolation', mpv.format_flag)
303 mpv.observe_property(player.mpv_ctx, obs_pitch_correction, 'audio-pitch-correction', mpv.format_flag)
304 mpv.observe_property(player.mpv_ctx, obs_audio_exclusive, 'audio-exclusive', mpv.format_flag)
305 // The picture-quality, dropping and pacing half of the menu's flag set;
306 // observers seed them with mpv's values like the others.
307 mpv.observe_property(player.mpv_ctx, obs_video_sync, 'video-sync', mpv.format_string)
308 mpv.observe_property(player.mpv_ctx, obs_framedrop, 'framedrop', mpv.format_string)
309 mpv.observe_property(player.mpv_ctx, obs_fast_decode, 'vd-lavc-fast', mpv.format_flag)
310 mpv.observe_property(player.mpv_ctx, obs_correct_downscaling, 'correct-downscaling', mpv.format_flag)
311 mpv.observe_property(player.mpv_ctx, obs_linear_downscaling, 'linear-downscaling', mpv.format_flag)
312 mpv.observe_property(player.mpv_ctx, obs_sigmoid_upscaling, 'sigmoid-upscaling', mpv.format_flag)
313 mpv.observe_property(player.mpv_ctx, obs_deband, 'deband', mpv.format_flag)
314 mpv.observe_property(player.mpv_ctx, obs_dither, 'dither', mpv.format_string)
315 mpv.observe_property(player.mpv_ctx, obs_blend_subtitles, 'blend-subtitles', mpv.format_string)
316 for path in startup {
317 player.load(path)
318 }
319 player.refresh_media_async(true)
320 // This start-up pass also reads the output-device list the Audio menu's
321 // submenu shows (see refresh_media_async for why later bursts skip it).
322 // A hidden mpv instance dedicated to seek previews: it opens the playing
323 // file with vo=null, stays paused, and answers hover requests with
324 // screenshot-to-file, so the real playback position is never moved. The
325 // saved setting or --no-preview skips it entirely: an idle instance
326 // still holds a whole second mpv core, which low-end machines are
327 // better off without.
328 if player.show_preview {
329 player.init_thumb()
330 }
331 ui2.set_menu_bar(player.menus())
332 ui2.on_key_event(fn [mut player] (ev ui2.KeyEvent) {
333 // Alt on its own shows or hides the menu bar. Autorepeat is ignored, so holding
334 // Alt does not flicker the bar.
335 if (ev.code == .left_alt || ev.code == .right_alt) && !ev.repeat {
336 player.set_menu_hidden(!player.menu_hidden())
337 }
338 if player.settings_open {
339 player.settings_key_event(ev)
340 return
341 }
342 // The queue sidebar's rows move with Alt and the arrows (or Home /
343 // End), the same move a drag performs. The key is consumed so the
344 // plain-key handlers (the arrows seek and step the volume) never see
345 // an Alt-combo the container answered.
346 if step := player.queue_key(ev) {
347 ui2.consume_key()
348 if step.reveal {
349 if offset := ui2.reorder_reveal_offset(player.queue_config(), step.state.active) {
350 ui2.scroll_to_offset(ui2.reorder_scroll_id(queue_list_id), offset)
351 }
352 }
353 }
354 })
355 ui2.on_scroll(fn [mut player] (id string) {
356 // The queue's rows scroll when they outgrow the panel; the offset
357 // feeds the container's reveal computations back.
358 if id == ui2.reorder_scroll_id(queue_list_id) {
359 player.queue_scroll = ui2.scroll_offset(id)
360 }
361 })
362 ui2.on_pointer_move(fn [mut player] (x f64, y f64) {
363 player.pointer_moved(x, y)
364 })
365 ui2.on_key(fn [mut player] (key string) {
366 $if debug_cadence ? {
367 eprintln('CAD key: [${key}]')
368 }
369 player.handle_key(key)
370 player.settings_changed()
371 })
372 ui2.on_drop(fn [mut player] (ev ui2.DropEvent) {
373 if ev.paths.len > 0 {
374 player.load_or_prompt(ev.paths)
375 }
376 })
377 ui2.on_wheel(fn [mut player] (_ f64, dy f64) {
378 player.wheel_volume(dy)
379 })
380 ui2.on_mouse_button(fn [mut player] (button int, down bool, x f64, y f64) {
381 player.mouse_button(button, down, x, y)
382 })
383 ui2.set_gl_surface_renderer(fn [mut player] (id string, frame ui2.Rect, scale f64, height f64) {
384 player.draw(id, frame, scale, height)
385 })
386 // With -d render_stats_probe a worker prints what the frame scheduler and
387 // the Boehm heap did each second, so idle behavior (wake rate, builds,
388 // draws, coalescing, heap growth) can be checked against the claims about
389 // on_demand mode without a debugger. render_stats() is documented as
390 // thread-safe and never asks for a frame.
391 $if render_stats_probe ? {
392 spawn fn () {
393 mut last := ui2.render_stats()
394 for {
395 time.sleep(time.second)
396 s := ui2.render_stats()
397 u := gc_heap_usage()
398 eprintln('probe callbacks=${s.callbacks - last.callbacks} requests=${s.requests - last.requests} builds=${s.builds - last.builds} draws=${s.draws - last.draws} coalesced=${s.coalesced - last.coalesced} pending=${s.pending} reasons=${s.pending_reasons} anim=${s.animation_active} deadline=${s.next_deadline} presentation=${s.presentation_required} heap=${u.heap_size / 1048576}MiB alloc_total=${u.total_bytes / 1048576}MiB unmapped=${u.unmapped_bytes / 1048576}MiB')
399 last = s
400 }
401 }()
402 }
403 // With -d playback_probe a worker prints mpv's pacing and drop counters
404 // each second during playback, so a choppy file can be pinned to a stage:
405 // decoded drops come from the decoder, displayed drops from mpv's vo
406 // accounting, and the mistimed/vo-delayed counters climb when
407 // display-sync pacing stalls.
408 $if playback_probe ? {
409 spawn fn [player] () {
410 mut last_dec := f64(0)
411 mut last_disp := f64(0)
412 mut last_mist := f64(0)
413 mut last_del := f64(0)
414 mut last_pres := 0
415 mut last_rep := 0
416 for {
417 time.sleep(time.second)
418 d_dec := player.decoder_dropped - last_dec
419 d_disp := player.display_dropped - last_disp
420 d_mist := player.mistimed - last_mist
421 d_del := player.vo_delayed - last_del
422 d_pres := player.presents - last_pres
423 d_rep := player.repeat_skips - last_rep
424 eprintln('probe drops dec=${d_dec:.0f}/s disp=${d_disp:.0f}/s | pres=${d_pres}/s rep=${d_rep}/s | mistimed=${d_mist:.0f}/s delayed=${d_del:.0f}/s | sync=${player.video_sync} hwdec=${player.hwdec_current} disp_fps=${player.display_fps:.0f} vf_fps=${player.vf_fps:.1f} paused=${player.paused} pos=${player.pos:.0f}')
425 last_dec = player.decoder_dropped
426 last_disp = player.display_dropped
427 last_mist = player.mistimed
428 last_del = player.vo_delayed
429 last_pres = player.presents
430 last_rep = player.repeat_skips
431 }
432 }()
433 }
434 ui2.run_window_with_options(ui2.WindowOptions{
435 title: 'Vendetta'
436 width: 800
437 height: 600
438 // The video surface is one textured rectangle filling the window, and
439 // mpv dithers its own output: 4x antialiasing buys nothing visible
440 // here while costing the iGPU a large slice of its frame budget.
441 sample_count: 1
442 // The continuous loop rebuilt the whole element tree every vsync
443 // regardless of what changed, which is most of why vendetta idled at
444 // nearly a core's worth of CPU. In on_demand mode ui2 schedules the
445 // window through its frame coordinator, so the tree is rebuilt by ask
446 // only: mpv asks through the widget's render wake whenever it has a
447 // frame, and input and ui2 timers ask for everything else. On X11 the
448 // loop sleeps between asks too — sokol gates the swap on
449 // present-on-demand, so an askless window draws and presents nothing
450 // and the keep-alive waker is the only idle traffic apart from
451 // callbacks the platform loop still counts. A paused or still picture
452 // skips both the rebuild and the repaint; the statistics popup's
453 // renderer line (or -d render_stats_probe) shows it. The widget keeps
454 // to this by handing ui2 its texture once per change, not per frame:
455 // a hand-off from inside the frame would schedule the next frame
456 // itself and idle would never sleep. The View menu's Continuous redraw
457 // row flips this policy at runtime — ui2 re-keys present-on-demand and
458 // the X11 deadline hook for the new mode — and performance mode takes
459 // the row away until it is turned off.
460 refresh: window_refresh(player)
461 // The queue lives in mpv's playlist, and mpv only reaches a file's end
462 // when its render call keeps consuming frames — the render API's
463 // queue fills and the core blocks on the vo stage otherwise. A window
464 // parked on another workspace is iconified as far as X11 is concerned,
465 // and an iconified window suspends its frames by default, so playback
466 // would stall at the frame's edge the moment the user looked
467 // elsewhere. Background frames keep the drains and the render call
468 // running while hidden; ui2 still presents nothing until the window
469 // is back.
470 background: true
471 }, fn [mut player] () ui2.Element {
472 return player.view()
473 }, fn [mut player] (event string) {
474 player.handle(event)
475 player.settings_changed()
476 })
477 $if !android {
478 player.save_settings()
479 player.save_queue_state()
480 if player.mpris != unsafe { nil } {
481 player.mpris.mpris_free()
482 }
483 player.destroy()
484 if player.thumb_ctx != unsafe { nil } {
485 mpv.destroy(player.thumb_ctx)
486 }
487 // The thumbnail instance is gone, so no capture can still write a frame
488 // here; the run's frames go with its directory.
489 os.rmdir_all(thumb_dir()) or {}
490 }
491}
492