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