import os import ui2 import libvendetta import libvendetta.mpv import flag as cliflag import time // The macOS build reaches ui2's custom renderer and sokol's GL backend only // through comptime defines: without them ui2 defaults macOS to its native // AppKit backend, whose API this file's window and stats calls are not part // of. This guard runs before the errors that missing define would raise // below, so the fix names itself. $if macos && !ui2_custom_rendering ? { $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)") } // footer_text is the help footer. Linux keeps the literal ~/.config form it // has always shown; the other platforms interpolate their own config // directory, and the separators follow the platform's path style. Android's // config base is the app's internal files directory, which config_base names. // window_refresh picks the window's redraw policy. On Android the on-demand policy // leaves playback unpainted between user events, so the window repaints at the // display rate there. fn window_refresh(player &Player) ui2.RefreshMode { $if android { return ui2.RefreshMode.continuous } if player.continuous { return ui2.RefreshMode.continuous } return ui2.RefreshMode.on_demand } fn footer_text() string { mut base := '~/.config/vendetta' mut sep := '/' $if android { base = '${config_base()}/vendetta' } $else { $if !linux { base = '${os.user_config_dir() or { os.home_dir() }}${sep}vendetta' } } $if windows { sep = '\\' } return 'video files open in order: the first plays, the rest queue up. themes live in ${base}${sep}themes, queues in ${base}${sep}queues, option presets in ${base}${sep}presets. examples: vendetta movie.mkv open a file vendetta https://example.com/live.m3u8 open a link vendetta --fullscreen --volume 20 a.mkv start fullscreen, quiet vendetta --start-at 1:30 --no-overlay b.mkv vendetta --mpv-opt hwdec=no --mpv-opt cache=yes c.mkv pass mpv options' } // Config maps the command line: --help and --theme are flags, and every // argument left over is a video file to open, so flags never end up in the // file list. struct Config { show_help bool @[long: help; short: h; xdoc: 'Show this help text and exit'] theme string @[xdoc: 'Theme file, without .toml, from ~/.config/vendetta/themes (default: the saved theme, else vendetta)'] volume f64 = -1 @[xdoc: 'Initial volume, 0 to 100 (default: the saved volume)'] mute bool @[xdoc: 'Start muted'] speed f64 = -1 @[xdoc: 'Playback speed, 0.01 to 100 (default: the saved speed)'] fullscreen bool @[xdoc: 'Start in fullscreen'] overlay bool @[xdoc: 'Start with overlay controls'] no_overlay bool @[long: 'no-overlay'; xdoc: 'Start without overlay controls'] loop_file bool @[long: 'loop'; xdoc: 'Loop the current file'] loop_playlist bool @[long: 'loop-playlist'; xdoc: 'Loop the playlist'] hwdec bool @[xdoc: 'Enable hardware decoding (default)'] no_hwdec bool @[long: 'no-hwdec'; xdoc: 'Disable hardware decoding'] deinterlace bool @[xdoc: 'Enable deinterlacing'] low_quality bool @[long: 'low-quality'; xdoc: 'Skip non-critical rendering (preview, panel refreshes) when frames run past the 60 Hz budget'] preview bool @[xdoc: 'Start with the seek-bar hover preview (default: the saved setting)'] 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)'] 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'] no_smooth_bar bool @[long: 'no-smooth-bar'; xdoc: 'Start with strictly asked redraws only: the bar steps to each position report mpv makes'] slider_height f64 = -1 @[long: 'slider-height'; xdoc: 'Height of the seek and volume bars in pixels, 1 to 30 (default: the saved setting)'] media_controls bool @[long: 'media-controls'; xdoc: 'Expose the desktop media controls (MPRIS on the session bus) (default: the saved setting)'] no_media_controls bool @[long: 'no-media-controls'; xdoc: 'Do not expose the desktop media controls'] 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)'] display_fps f64 = -1 @[long: 'display-fps'; xdoc: 'Display refresh rate for mpv display-sync, in Hz (default: detected from X11 RandR)'] 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.'] start_at string @[long: 'start-at'; xdoc: 'Start at a position: seconds or mm:ss (e.g. 90 or 1:30)'] sub_file string @[long: 'sub-file'; xdoc: 'Load an extra subtitle file'] 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.'] files []string @[tail] } // set_mpv_option sets an option and logs a warning when mpv rejects it: a // typo'd name or an outdated value would otherwise silently leave the default // in effect, changing playback behaviour with nothing in the log. It reports // whether mpv accepted the option. fn set_mpv_option(ctx voidptr, name string, value string) bool { rc := mpv.set_option(ctx, name, value) if rc < 0 { eprintln('vendetta: mpv option ${name}=${value}: ${mpv.error_string(rc)}') } return rc == 0 } // parse_mpv_option splits a --mpv-opt entry at its first = into the option // name and value, the way mpv reads its own --name=value. Values may contain // further = signs, so only the name is peeled off. fn parse_mpv_option(raw string) ?(string, string) { i := raw.index('=')? return raw[..i], raw[i + 1..] } // resolve_ao picks the audio server the player runs on: the --ao flag wins // over the saved choice, and anything the platform's server list cannot offer // falls back to mpv's autoprobing instead of forcing an output that would // fail to open. fn resolve_ao(saved string, from_cli string) string { names := audio_server_names() if from_cli.len > 0 { if from_cli in names { return from_cli } eprintln('vendetta: unknown audio server: ${from_cli} (available: ${names.join(', ')})') } return if saved in names { saved } else { 'auto' } } // apply_start_options sets the options the command line gives before mpv // starts, so even the ones that cannot change at runtime (vf, cache, vo...) // reach it. Options keep applying across sessions: the accepted entries seed // player.mpv_opts, which the saved settings mirror. An option given an empty // value unsets instead: it stops being carried in the saved settings, undoing // one set through Options > Set option.... fn apply_start_options(mut player &Player, ctx voidptr, cfg Config) { // Display sync cannot measure the vsync rate with the libmpv video output, // so the monitor's refresh rate is given on the command line for multi-monitor // and Wayland setups where detection cannot know which screen the window is on. if cfg.display_fps > 0 { set_mpv_option(ctx, 'display-fps-override', '${cfg.display_fps:.3f}') } for raw in cfg.mpv_opts { name, value := parse_mpv_option(raw) or { eprintln('vendetta: mpv-opt must be name=value: ${raw}') continue } // An empty value unsets: mpv gets the empty write (string options // clear, the rest refuse it with a warning above) and the option // leaves the configured set no matter what mpv said. if value.len == 0 { set_mpv_option(ctx, name, value) player.mpv_opts.delete(name) continue } if !set_mpv_option(ctx, name, value) { continue } player.mpv_opts[name] = value } } fn main() { migrate_legacy_config() cfg, _ := cliflag.to_struct[Config](os.args, skip: 1) or { eprintln('vendetta: ${err}') exit(1) } if cfg.show_help { println(cliflag.to_doc[Config]( name: 'Vendetta' version: '0.0.0' description: 'an mpv backed media player written in V' footer: footer_text() ) or { '' }) return } mut startup := []string{} for arg in cfg.files { // The shape of each argument is decided here, where it arrives, and // the branch reads the kind: a link has no filesystem existence to // check and abs_path would mangle the URL anyway, so it rides // verbatim; a file is made absolute and has to exist. if libvendetta.source_kind(arg) == .link { startup << arg continue } path := os.abs_path(arg) if os.exists(path) { startup << path } else { eprintln('vendetta: no such file: ${arg}') } } mut player := &Player{ queue: startup.clone() theme: default_theme() media_chan: chan MediaData{cap: 8} } // The queue sidebar's reorder container names rows with generated keys // (paths can repeat), so the startup queue is keyed before the first build. player.queue_reset_keys() // The last session's queue comes back when the command line opened // nothing: restored rows sit in the sidebar and mpv's playlist, and // nothing plays until a row is clicked or a later file serves the // entry (resume_pending_queue's plain appends, first frame). A start // with files passed on it belongs to the command line instead. if startup.len == 0 { player.restore_queue(load_queue_state().paths) } if !ui2.file_dialog_supported() { notice := file_dialog_notice() if notice.len > 0 { player.notify(notice) } } // The audio server resolves before the widget starts mpv: the --ao flag // outranks the saved choice, and a value this platform's server list // cannot offer demotes to mpv's autoprobing rather than forcing a server // that would fail to open. settings := load_settings() player.ao = resolve_ao(settings.ao, cfg.ao) // The widget starts mpv. vo=libmpv, keep-open and the display rate are its // defaults, plus the audio server resolved above; pre_init adds the // command line's own options before mpv starts, and on_event hands each // mpv event to the app's menus and lists. player.setup(libvendetta.Config{ block_target_time: !cfg.no_block_target_time input_scope: libvendetta.InputScope.window ao: player.ao pre_init: fn [mut player, cfg] (ctx voidptr) { apply_start_options(mut player, ctx, cfg) } on_event: fn [mut player] (ev voidptr) { player.on_mpv_event(ev) } }) if player.mpv_ctx == unsafe { nil } { eprintln('vendetta: mpv_create failed') return } // Hardware decoding on by default; the Playback menu can turn it off per // session. auto-safe skips methods the driver cannot actually deliver // (plain auto happily picks a broken Vulkan path). player.hwdec = true // Saved settings mirror into the player and mpv: volume, speed, the loop // flags, overlay modes, panel visibility and the picture overrides. player.apply_settings(settings) // Command line flags win over saved settings. player.apply_cli(cfg) player.sync_overlay() // Performance mode is the redraw budget's backstop: it takes the // continuous redraw away until it is turned off, whichever way the // session started with it. if player.low_quality { player.continuous = false } // The menu's mpv flag toggles show what mpv is actually doing, so the // state comes from the observed properties (mpv reports the current value // as soon as it is observed); nothing writes these options at start. mpv.observe_property(player.mpv_ctx, obs_aid, 'aid', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_sid, 'sid', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_vid, 'vid', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_audio_device, 'audio-device', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_ao, 'ao', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_playlist_pos, 'playlist-pos', mpv.format_string) // The media controls' own observers: time-pos announces jumps as Seeked // signals, duration joins the announcements when it arrives, and volume // follows every write (strip slider, keys, wheel, the menu). Only the // -d mpris build has a consumer, so the default build does not ask mpv // for these per-frame events. $if mpris ? { mpv.observe_property(player.mpv_ctx, obs_mpris_pos, 'time-pos', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_duration_mpris, 'duration', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_mpris_volume, 'volume', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_mpris_loop, 'loop-file', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_mpris_loop_playlist, 'loop-playlist', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_media_artist, 'metadata/by-key/artist', mpv.format_string) } // The window title carries the playing file's name, so media-title is // observed in every build (the mpris build's xesam:title reads the same // mirror that update_window_title consumes). mpv.observe_property(player.mpv_ctx, obs_media_title, 'media-title', mpv.format_string) // Playback statistics for the popup; each reports its own property change. mpv.observe_property(player.mpv_ctx, obs_fps, 'fps', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_vf_fps, 'estimated-vf-fps', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_display_fps, 'estimated-display-fps', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_avsync, 'avsync', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_avsync_change, 'total-avsync-change', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_vsync_jitter, 'vsync-jitter', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_vsync_ratio, 'vsync-ratio', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_video_speed_corr, 'video-speed-correction', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_audio_speed_corr, 'audio-speed-correction', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_decoder_dropped, 'decoder-frame-drop-count', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_display_dropped, 'drop-frame-count', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_video_bitrate, 'video-bitrate', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_audio_bitrate, 'audio-bitrate', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_cache_time, 'demuxer-cache-time', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_cache_duration, 'demuxer-cache-duration', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_cache_buffering, 'cache-buffering-state', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_video_w, 'video-params/w', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_video_h, 'video-params/h', mpv.format_double) mpv.observe_property(player.mpv_ctx, obs_hwdec_current, 'hwdec-current', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_interpolation, 'interpolation', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_pitch_correction, 'audio-pitch-correction', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_audio_exclusive, 'audio-exclusive', mpv.format_flag) // The picture-quality, dropping and pacing half of the menu's flag set; // observers seed them with mpv's values like the others. mpv.observe_property(player.mpv_ctx, obs_video_sync, 'video-sync', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_framedrop, 'framedrop', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_fast_decode, 'vd-lavc-fast', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_correct_downscaling, 'correct-downscaling', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_linear_downscaling, 'linear-downscaling', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_sigmoid_upscaling, 'sigmoid-upscaling', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_deband, 'deband', mpv.format_flag) mpv.observe_property(player.mpv_ctx, obs_dither, 'dither', mpv.format_string) mpv.observe_property(player.mpv_ctx, obs_blend_subtitles, 'blend-subtitles', mpv.format_string) for path in startup { player.load(path) } player.refresh_media_async(true) // This start-up pass also reads the output-device list the Audio menu's // submenu shows (see refresh_media_async for why later bursts skip it). // A hidden mpv instance dedicated to seek previews: it opens the playing // file with vo=null, stays paused, and answers hover requests with // screenshot-to-file, so the real playback position is never moved. The // saved setting or --no-preview skips it entirely: an idle instance // still holds a whole second mpv core, which low-end machines are // better off without. if player.show_preview { player.init_thumb() } ui2.set_menu_bar(player.menus()) ui2.on_key_event(fn [mut player] (ev ui2.KeyEvent) { // Alt on its own shows or hides the menu bar. Autorepeat is ignored, so holding // Alt does not flicker the bar. if (ev.code == .left_alt || ev.code == .right_alt) && !ev.repeat { player.set_menu_hidden(!player.menu_hidden()) } if player.settings_open { player.settings_key_event(ev) return } // The queue sidebar's rows move with Alt and the arrows (or Home / // End), the same move a drag performs. The key is consumed so the // plain-key handlers (the arrows seek and step the volume) never see // an Alt-combo the container answered. if step := player.queue_key(ev) { ui2.consume_key() if step.reveal { if offset := ui2.reorder_reveal_offset(player.queue_config(), step.state.active) { ui2.scroll_to_offset(ui2.reorder_scroll_id(queue_list_id), offset) } } } }) ui2.on_scroll(fn [mut player] (id string) { // The queue's rows scroll when they outgrow the panel; the offset // feeds the container's reveal computations back. if id == ui2.reorder_scroll_id(queue_list_id) { player.queue_scroll = ui2.scroll_offset(id) } }) ui2.on_pointer_move(fn [mut player] (x f64, y f64) { player.pointer_moved(x, y) }) ui2.on_key(fn [mut player] (key string) { $if debug_cadence ? { eprintln('CAD key: [${key}]') } player.handle_key(key) player.settings_changed() }) ui2.on_drop(fn [mut player] (ev ui2.DropEvent) { if ev.paths.len > 0 { player.load_or_prompt(ev.paths) } }) ui2.on_wheel(fn [mut player] (_ f64, dy f64) { player.wheel_volume(dy) }) ui2.on_mouse_button(fn [mut player] (button int, down bool, x f64, y f64) { player.mouse_button(button, down, x, y) }) ui2.set_gl_surface_renderer(fn [mut player] (id string, frame ui2.Rect, scale f64, height f64) { player.draw(id, frame, scale, height) }) // With -d render_stats_probe a worker prints what the frame scheduler and // the Boehm heap did each second, so idle behavior (wake rate, builds, // draws, coalescing, heap growth) can be checked against the claims about // on_demand mode without a debugger. render_stats() is documented as // thread-safe and never asks for a frame. $if render_stats_probe ? { spawn fn () { mut last := ui2.render_stats() for { time.sleep(time.second) s := ui2.render_stats() u := gc_heap_usage() 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') last = s } }() } // With -d playback_probe a worker prints mpv's pacing and drop counters // each second during playback, so a choppy file can be pinned to a stage: // decoded drops come from the decoder, displayed drops from mpv's vo // accounting, and the mistimed/vo-delayed counters climb when // display-sync pacing stalls. $if playback_probe ? { spawn fn [player] () { mut last_dec := f64(0) mut last_disp := f64(0) mut last_mist := f64(0) mut last_del := f64(0) mut last_pres := 0 mut last_rep := 0 for { time.sleep(time.second) d_dec := player.decoder_dropped - last_dec d_disp := player.display_dropped - last_disp d_mist := player.mistimed - last_mist d_del := player.vo_delayed - last_del d_pres := player.presents - last_pres d_rep := player.repeat_skips - last_rep 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}') last_dec = player.decoder_dropped last_disp = player.display_dropped last_mist = player.mistimed last_del = player.vo_delayed last_pres = player.presents last_rep = player.repeat_skips } }() } ui2.run_window_with_options(ui2.WindowOptions{ title: 'Vendetta' width: 800 height: 600 // The video surface is one textured rectangle filling the window, and // mpv dithers its own output: 4x antialiasing buys nothing visible // here while costing the iGPU a large slice of its frame budget. sample_count: 1 // The continuous loop rebuilt the whole element tree every vsync // regardless of what changed, which is most of why vendetta idled at // nearly a core's worth of CPU. In on_demand mode ui2 schedules the // window through its frame coordinator, so the tree is rebuilt by ask // only: mpv asks through the widget's render wake whenever it has a // frame, and input and ui2 timers ask for everything else. On X11 the // loop sleeps between asks too — sokol gates the swap on // present-on-demand, so an askless window draws and presents nothing // and the keep-alive waker is the only idle traffic apart from // callbacks the platform loop still counts. A paused or still picture // skips both the rebuild and the repaint; the statistics popup's // renderer line (or -d render_stats_probe) shows it. The widget keeps // to this by handing ui2 its texture once per change, not per frame: // a hand-off from inside the frame would schedule the next frame // itself and idle would never sleep. The View menu's Continuous redraw // row flips this policy at runtime — ui2 re-keys present-on-demand and // the X11 deadline hook for the new mode — and performance mode takes // the row away until it is turned off. refresh: window_refresh(player) // The queue lives in mpv's playlist, and mpv only reaches a file's end // when its render call keeps consuming frames — the render API's // queue fills and the core blocks on the vo stage otherwise. A window // parked on another workspace is iconified as far as X11 is concerned, // and an iconified window suspends its frames by default, so playback // would stall at the frame's edge the moment the user looked // elsewhere. Background frames keep the drains and the render call // running while hidden; ui2 still presents nothing until the window // is back. background: true }, fn [mut player] () ui2.Element { return player.view() }, fn [mut player] (event string) { player.handle(event) player.settings_changed() }) $if !android { player.save_settings() player.save_queue_state() if player.mpris != unsafe { nil } { player.mpris.mpris_free() } player.destroy() if player.thumb_ctx != unsafe { nil } { mpv.destroy(player.thumb_ctx) } // The thumbnail instance is gone, so no capture can still write a frame // here; the run's frames go with its directory. os.rmdir_all(thumb_dir()) or {} } }