import os import ui2 import libvendetta import libvendetta.mpv import math import time import json2 $if macos { import macos } // queues_dir is where saved queues live: /vendetta/queues. fn queues_dir() string { return os.join_path(config_base(), 'vendetta', 'queues') } // saved_queues lists the saved queue names, sorted. fn saved_queues() []string { mut names := []string{} mut files := os.ls(queues_dir()) or { return names } files.sort() for file in files { if file.ends_with('.json') { names << file.all_before_last('.json') } } return names } // save_queue writes the current queue under name. The name may not be empty // or escape the queues directory. fn (mut p Player) save_queue(name string) bool { mut clean := name.trim_space() if clean.len == 0 || clean.contains('/') || clean.contains('\\') || clean.contains('..') { p.notify('Queue name may not be empty or contain path separators.') return false } if p.queue.len == 0 { p.notify('The queue is empty.') return false } os.mkdir_all(queues_dir(), os.MkdirParams{}) or {} os.write_file(os.join_path(queues_dir(), '${clean}.json'), json2.encode(p.queue, json2.EncoderOptions{})) or { p.notify('Could not save the queue: ${err}') return false } return true } // load_queue_file reads a saved queue's paths. fn load_queue_file(name string) ?[]string { text := os.read_file(os.join_path(queues_dir(), '${name}.json')) or { return none } return json2.decode[[]string](text, json2.DecoderOptions{}) or { none } } // playlists_dir is where playlists live: /vendetta/playlists, // one m3u file per name. The format is mpv's own — the one its playlist // demuxer consumes and every other player reads — so a slot is not // vendetta's private state: mpv --playlist= plays it, other tools // write it, and a hand-edited file is simply a playlist. fn playlists_dir() string { return os.join_path(config_base(), 'vendetta', 'playlists') } // saved_playlists lists the playlist slot names, sorted. fn saved_playlists() []string { mut names := []string{} mut files := os.ls(playlists_dir()) or { return names } files.sort() for file in files { if file.ends_with('.m3u') { names << file.all_before_last('.m3u') } } return names } // save_playlist writes the current queue into slot name as a playlist: the // m3u header, then one plain entry per queue row — files as absolute paths // and links verbatim. No extensions tags, so the file means the same thing // in mpv, in every other player, and in a text editor. The name rules // mirror save_queue's. fn (p &Player) save_playlist(name string) bool { mut clean := name.trim_space() if clean.len == 0 || clean.contains('/') || clean.contains('\\') || clean.contains('..') { p.notify('Playlist name may not be empty or contain path separators.') return false } if p.queue.len == 0 { p.notify('The queue is empty.') return false } os.mkdir_all(playlists_dir(), os.MkdirParams{}) or {} mut lines := ['#EXTM3U'] for entry in p.queue { if entry.len > 0 { lines << entry } } os.write_file(os.join_path(playlists_dir(), '${clean}.m3u'), lines.join('\n') + '\n') or { p.notify('Could not save the playlist: ${err}') return false } return true } // parse_playlist_file reads a playlist file into its entries: m3u, so blanks // and '#' lines (EXTM3U, EXTINF) are comments, each remaining line is an // entry, a relative path resolves against the playlist's own directory like // mpv resolves them, and links ride through verbatim. fn parse_playlist_file(path string) ?[]string { text := os.read_file(path) or { return none } base_dir := os.dir(path) mut entries := []string{} for line in text.split_into_lines() { entry := line.trim_space() if entry.len == 0 || entry.starts_with('#') { continue } if os.is_abs_path(entry) { entries << entry } else { entries << os.abs_path(os.join_path(base_dir, entry)) } } return entries } // load_playlist_file reads a playlist slot's entries. fn load_playlist_file(name string) ?[]string { return parse_playlist_file(os.join_path(playlists_dir(), '${name}.m3u')) } // dialog_directory is where the open dialog starts: the user's Videos folder // when one is configured, otherwise the home directory. Linux, the BSDs and // Solaris read ~/.config/user-dirs.dirs, the same file every desktop tool // uses; Windows and macOS answer through videos_dir, each defined under its // own platform. fn dialog_directory() string { $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { mut lines := os.read_lines(os.join_path(os.home_dir(), '.config', 'user-dirs.dirs')) or { return os.home_dir() } for mut line in lines { line = line.trim_space() if line.starts_with('XDG_VIDEOS_DIR') && line.contains('=') { mut value := line.all_after('=').trim_space() value = value.trim_string_left('"').trim_string_right('"') value = value.replace('$HOME', os.home_dir()) if value.len > 0 && os.is_dir(value) { return value } } } return os.home_dir() } $else { if videos := videos_dir() { return videos } return os.home_dir() } } $if macos { #include fn C.dlsym(voidptr, &char) voidptr // SearchPathsFn is NSSearchPathForDirectoriesInDomains reached through a // pointer typed to return void*. Foundation's own prototype returns an // ObjC object, and the ARC rules the macOS C compiles under refuse to // hand that to V's void pointers without a bridged cast V cannot spell — // the direct call failed to compile. Reaching the function through dlsym // (the default scope answers, Foundation is linked) skips the conversion // the way mpv.v's GlxGetProcAddress skips its header. The array comes // back autoreleased, so holding it as a plain pointer is correct, and // everything asked of it afterwards goes through vlib macos, whose calls // bridge inside C. type SearchPathsFn = fn (directory u64, domain u64, expand bool) voidptr // videos_dir reads the Movies folder's path from Foundation, so a // library the user moved is honored; nil when macOS cannot name one. // NSMoviesDirectory is 17 and NSUserDomainMask 1 in the search-path // enums. It answers dialog_directory's shared videos_dir name. fn videos_dir() ?string { f := unsafe { SearchPathsFn(C.dlsym(unsafe { nil }, c'NSSearchPathForDirectoriesInDomains')) } if f == unsafe { nil } { return none } paths := f(17, 1, true) if paths == unsafe { nil } || macos.msg_u64(paths, 'count') == 0 { return none } dir := macos.utf8_string(macos.msg_id_u64(paths, 'objectAtIndex:', 0)) if dir.len == 0 || !os.is_dir(dir) { return none } return dir } } $if windows { // videos_dir reads the Videos library's known-folder path through // SHGetKnownFolderPath; nil when the shell cannot name one. It answers // dialog_directory's shared videos_dir name. fn videos_dir() ?string { // FOLDERID_Videos = {B4BFCC3A-DB2C-424C-B029-7FE99A87C641} folder_id := [ u8(0x3a), u8(0xcc), u8(0xbf), u8(0xb4), u8(0x2c), u8(0xdb), u8(0x4c), u8(0x24), u8(0xb0), u8(0x29), u8(0x7f), u8(0xe9), u8(0x9a), u8(0x87), u8(0xc6), u8(0x41), ] mut path := voidptr(unsafe { nil }) rc := C.SHGetKnownFolderPath(voidptr(&folder_id), 0, unsafe { nil }, &path) if rc != 0 || path == unsafe { nil } { return none } defer { C.CoTaskMemFree(path) } return unsafe { cstring_to_vstring(&u8(path)) } } fn C.SHGetKnownFolderPath(&u8, u32, voidptr, &voidptr) i32 fn C.CoTaskMemFree(voidptr) } $if android { // videos_dir is where users' videos live on an Android device: the // shared Movies folder. Seeing it needs the media permission the // packaged build's manifest asks for; none when the app runs in a // sandbox that cannot (scoped storage, no permission granted). It // answers dialog_directory's shared videos_dir name. fn videos_dir() ?string { dir := '/sdcard/Movies' if os.is_dir(dir) { return dir } return none } } // file_dialog_notice is what to tell a user whose platform has no file // dialog: Linux, the BSDs and Solaris shell out to zenity or kdialog and say // what to install; Windows, macOS and Android ship native pickers, so there // is nothing to say. fn file_dialog_notice() string { $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { return 'Install zenity or kdialog to open files with the file dialog.' } return '' } // open_dialog shows the platform file dialog, which is a separate window. // Windows and macOS get native pickers; Linux, the BSDs and Solaris need // zenity or kdialog, and without one the window explains what to install. fn (mut p Player) open_dialog() { if !ui2.file_dialog_supported() { notice := file_dialog_notice() if notice.len > 0 { p.notify(notice) } return } // request_file_dialog returns at once on Android, where the picker answers // later; the paths arrive here either way. ui2.request_file_dialog(ui2.FileDialogConfig{ title: 'Open video' // The picker would otherwise open in the process's working directory // and list whatever sits there. Start in the user's Videos folder // when xdg-user-dir knows one. directory: dialog_directory() filters: [ ui2.FileDialogFilter{ name: 'Video' extensions: ['mp4', 'mkv', 'webm', 'mov', 'avi', 'm4v'] }, ] }, fn [mut p] (paths []string) { libvendetta.video_debug_note('picker callback: ${paths}') if paths.len > 0 { p.load_or_prompt(paths) } libvendetta.video_debug_note('picker callback: load_or_prompt returned') }) } // load_or_prompt plays the paths right away when the queue is empty, and asks // whether to play now or add to the queue only when something is queued. fn (mut p Player) load_or_prompt(paths []string) { libvendetta.video_debug_note('load_or_prompt: enter') // The File > Default open setting decides what opening means; ask shows // the choice dialog every time. match p.open_mode { 'play' { p.load_paths(paths) return } 'queue' { p.add_to_queue(paths) return } else {} } if p.queue.len == 0 { p.load_paths(paths) return } p.queue_paths = paths.clone() p.queue_open = true } // add_to_queue appends paths to the queue and, once the renderer is up, to // mpv's playlist after the current file. fn (mut p Player) add_to_queue(paths []string) { if p.render_ctx != unsafe { nil } { for file in paths { p.queue << file p.queue_keys << p.queue_new_key() mpv.command_async(p.mpv_ctx, loadfile_base + u64(p.queue.len), ['loadfile', file, 'append-play']) } // The desktop's tracklist reads the playlist mirror, not the queue. p.playlist = p.queue.clone() p.queue_state_changed() } else { for file in paths { p.queue << file p.queue_keys << p.queue_new_key() } p.queue_state_changed() } } // load_paths plays the first path, replacing what is playing, and queues the rest. // The paths become the queue, so the panel lists them and the open prompt shows // from then on. Before the first frame there is no render context yet, so the // paths wait in startup and are loaded then. fn (mut p Player) load_paths(paths []string) { libvendetta.video_debug_note('load_paths: enter, render_ctx=${p.render_ctx}') p.playlist = paths.clone() p.queue = paths.clone() // The entries replace the queue wholesale: fresh keys for the rows, and // the drag / keyboard cursor state of the old queue means nothing. p.queue_reset_keys() p.playlist_index = 0 p.queue_state_changed() if p.render_ctx == unsafe { nil } { p.startup = paths.clone() return } // Playing now skips everything: drop the old playlist first. mpv.command_async(p.mpv_ctx, u64(80), ['playlist-clear']) for i, file in paths { flag := if i == 0 { 'replace' } else { 'append-play' } mpv.command_async(p.mpv_ctx, loadfile_base + u64(i), ['loadfile', file, flag]) } } // init_thumb creates the hidden thumbnail mpv instance, lazily: the saved // setting or --no-preview can skip it at start, and the View menu can turn // the preview on later. vo=null and ao=null keep it off the screen and the // audio path; pause=yes keeps a loaded file from decoding. fn (mut p Player) init_thumb() { if p.thumb_ctx != unsafe { nil } { return } p.thumb_ctx = mpv.create() if p.thumb_ctx != unsafe { nil } { mpv.set_option(p.thumb_ctx, 'vo', 'null') mpv.set_option(p.thumb_ctx, 'ao', 'null') mpv.set_option(p.thumb_ctx, 'audio', 'no') mpv.set_option(p.thumb_ctx, 'pause', 'yes') mpv.set_option(p.thumb_ctx, 'config', 'no') mpv.set_option(p.thumb_ctx, 'screenshot-format', 'jpeg') thumb_init_rc := mpv.initialize(p.thumb_ctx) if thumb_init_rc < 0 { mpv.destroy(p.thumb_ctx) p.thumb_ctx = unsafe { nil } eprintln('vendetta: thumbnail mpv: ${mpv.error_string(thumb_init_rc)}') } } } // thumb_dir is where this run's seek-preview frames go: a directory named for // the process, so exit can remove every frame the run left behind, the ones // from abandoned captures included. fn thumb_dir() string { return os.join_path(os.temp_dir(), 'vendetta-thumbs-${os.getpid()}') } // drop_thumb deletes a captured frame that nothing shows any more. fn drop_thumb(path string) { os.rm(path) or {} } // drop_shown_thumb deletes the frame on show and clears its path, so the popup // has nothing to draw. It runs when the frame stops matching what plays: a new // file, a closed file, or the preview switched off. fn (mut p Player) drop_shown_thumb() { drop_thumb(p.preview_show_path) p.preview_show_path = '' } // display_name is what the panels call a source: a file contributes its path // basename, a link the URL's target with the host standing in when there is // none, so the queue sidebar, the open prompt, the statistics line and the // MPRIS title fallback all read the same name off the same entry. fn display_name(source string, kind libvendetta.MediaKind) string { if kind == .link { return link_name(source) } return os.base(source) } // link_name reduces a link to what reads as its name: the URL's last segment // with '?' and everything after dropped, and the host stepping in for a bare // index — 'https://example.com/' and 'https://example.com/?listen=1' would // otherwise have no name at all. fn link_name(url string) string { tail := url.all_after_last('/').all_before('?') if tail.len == 0 { return url.all_after('://').all_before('/') } return tail } // load_thumb_file opens the playing file on the hidden thumbnail instance so // hover requests do not pay the file-open cost each time. fn (mut p Player) load_thumb_file() { if !p.show_preview || p.thumb_ctx == unsafe { nil } || p.thumb_path == p.current_path { return } // The frame on show was taken from the file that just stopped playing. p.drop_shown_thumb() // A live stream never earns a preview (it has no duration to seek to), // and the instance would download the live playlist alongside the real // player for as long as both play, starving its demuxer cache. Leave it // idle; the next regular file loads as usual. if p.current_kind == .link { return } p.thumb_path = p.current_path p.preview_state = 0 p.preview_visible = false mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace']) } // update_preview tracks the pointer over the seek bar. Once the pointer rests // in one spot briefly, request_thumb captures the frame there. fn (mut p Player) update_preview() { if !p.show_preview || !p.has_file || p.duration <= 0 || p.thumb_ctx == unsafe { nil } { p.preview_over = false p.preview_visible = false return } seek := libvendetta.control_bar(p.main_area(ui2.bounds()), p.duration).seek // The widget's pointer is already in the layout's space, below the menu bar. over := p.pointer_y >= seek.y && p.pointer_y <= seek.y + seek.height && p.pointer_x >= seek.x && p.pointer_x <= seek.x + seek.width p.preview_over = over if !over { p.preview_visible = false return } if p.preview_state != 0 { if time.ticks() - p.preview_t0 > thumb_timeout_ms { p.preview_state = 0 } return } // The seek slider is drawn without a thumb and with no padding, so the // pointer position maps straight onto its frame. hover := (p.pointer_x - seek.x) / seek.width * p.duration if math.abs(hover - p.preview_time) > 0.25 { p.preview_time = hover p.preview_t0 = time.ticks() p.preview_visible = false // the old frame no longer matches the position } if p.preview_visible { return } if time.ticks() - p.preview_t0 >= 150 { p.request_thumb() } } // request_thumb starts one capture on the hidden thumbnail instance: load the // file if it is new, then seek there. Each stage's reply keeps the pipeline // moving; see drain_thumb. fn (mut p Player) request_thumb() { p.preview_index++ // Every capture gets a file of its own: ui2 keeps a decoded image per path, // so a reused name would keep showing the first frame. os.mkdir_all(thumb_dir(), os.MkdirParams{}) or {} p.preview_pending_path = os.join_path(thumb_dir(), 'thumb_${p.preview_index}.jpg') p.preview_pending_time = p.preview_time p.preview_t0 = time.ticks() if p.thumb_path != p.current_path { p.preview_state = thumb_state_loading mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace']) return } p.preview_state = thumb_state_seeking mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek', '${p.preview_time:.3f}', 'absolute', 'exact']) } // drain_thumb reads the hidden thumbnail instance's queue so it never fills // up. Replies advance the capture pipeline; p.preview_state says what is // happening: 1 loading the file, 2 waiting for the seek, 3 waiting for the // screenshot, 0 idle. fn (mut p Player) drain_thumb() { if p.thumb_ctx == unsafe { nil } { return } for { ev := mpv.wait_event(p.thumb_ctx, 0) id := mpv.event_id(ev) if id == mpv.event_none { break } match id { mpv.event_file_loaded { if p.preview_state == thumb_state_loading { p.preview_state = thumb_state_seeking mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek', '${p.preview_pending_time:.3f}', 'absolute', 'exact']) } } mpv.event_command_reply { ud := mpv.event_reply_userdata(ev) if ud == thumb_seek_userdata && p.preview_state == thumb_state_seeking { p.preview_state = thumb_state_shooting os.rm(p.preview_pending_path) or {} mpv.command_async(p.thumb_ctx, thumb_shot_userdata, [ 'screenshot-to-file', p.preview_pending_path, 'video', ]) } if ud == thumb_shot_userdata && p.preview_state == thumb_state_shooting { p.preview_state = 0 p.show_thumb() } } else {} } } } // show_thumb displays the freshly rendered frame if it still matches where // the pointer is. fn (mut p Player) show_thumb() { p.preview_show_w = 16 p.preview_show_h = 9 if size := ui2.image_natural_size(p.preview_pending_path) { p.preview_show_w = size.width p.preview_show_h = size.height } p.preview_show_time = p.preview_pending_time // The frame this one replaces is no longer on show, so its file goes. The // popup takes the new path from the next build, which runs after this draw. if p.preview_show_path != p.preview_pending_path { drop_thumb(p.preview_show_path) } p.preview_show_path = p.preview_pending_path if p.preview_over && math.abs(p.preview_time - p.preview_pending_time) <= 0.25 { p.preview_visible = true } // The preview state was set inside this frame's gl-surface pass, after the // build; in on_demand mode with nothing else waking the loop — video // paused, pointer at rest — this ask is the frame that shows it. ui2.request_refresh() } // refresh_devices reads the audio output devices mpv can use. // MediaData carries the track, chapter and device lists read out of mpv on a // worker thread, so the render thread never waits on the core (a requirement // of the render API's advanced control: a synchronous read on the render // thread can deadlock mpv for good). with_devices says whether the worker // should read the output devices this round: asking mpv for the device list // initializes the whole audio output (its enumeration instantiates the // driver's context, libmpv calls pw_context_new for a pinned ao), which is // slow, can block a long time against a dead server, and rarely changes. The // file-load and track bursts therefore carry no devices; the device readers — // the start-up pass and the audio-device/ao writes — ask for them. // read_devices tells drain_media whether devices is a fresh list or merely // left unread: a read without the devices must keep the menu's last list. struct MediaData { tracks []Track chapters []Chapter devices []AudioDevice read_devices bool } // read_media_worker runs on its own thread. libmpv core calls are safe from // any thread but the one that renders. with_devices gates the device-list // read: that property initializes the audio output (mpv instantiates the // pinned ao's context to enumerate, pw_context_new for a pinned pipewire), // which can stop for a long time against a dead server and must not run // under the per-file bursts. fn read_media_worker(ctx voidptr, res chan MediaData, with_devices bool) { mut tracks := []Track{} count := (mpv.get_string(ctx, 'track-list/count') or { '0' }).int() for i in 0 .. count { base := 'track-list/${i}' kind := mpv.get_string(ctx, '${base}/type') or { '' } id := mpv.get_string(ctx, '${base}/id') or { '0' } title := mpv.get_string(ctx, '${base}/title') or { '' } lang := mpv.get_string(ctx, '${base}/lang') or { '' } selected := (mpv.get_string(ctx, '${base}/selected') or { 'no' }) == 'yes' mut label := if title.len > 0 { title } else { lang } if label.len == 0 { label = 'Track ${id}' } tracks << Track{ kind: kind id: id label: label selected: selected } } mut chapters := []Chapter{} chapter_count := (mpv.get_string(ctx, 'chapter-list/count') or { '0' }).int() for i in 0 .. chapter_count { title := mpv.get_string(ctx, 'chapter-list/${i}/title') or { 'Chapter ${i + 1}' } at := (mpv.get_string(ctx, 'chapter-list/${i}/time') or { '0' }).f64() chapters << Chapter{ title: title at: at } } mut devices := []AudioDevice{} if with_devices { device_count := (mpv.get_string(ctx, 'audio-device-list/count') or { '0' }).int() for i in 0 .. device_count { name := mpv.get_string(ctx, 'audio-device-list/${i}/name') or { '' } description := mpv.get_string(ctx, 'audio-device-list/${i}/description') or { name } devices << AudioDevice{ name: name description: description } } } res <- MediaData{ tracks: tracks chapters: chapters devices: devices read_devices: with_devices } } // refresh_media_async hands the property reads to a worker thread. When one // is already in flight, remember it: the selection properties change in bursts // while a file loads. with_devices asks the worker to read the output-device // list as well — that read instantiates the audio output, so it rides only on // the asks that expect the devices to have changed (start-up, an audio-server // switch), never on the per-file bursts. A true ask during an in-flight read // is sticky: the next read carries it once. fn (mut p Player) refresh_media_async(with_devices bool) { if with_devices { p.media_devices_wanted = true } if p.media_read_busy { p.media_dirty = true return } // Take the sticky device ask after the busy test: a true ask during an // in-flight read sticks in media_devices_wanted and rides the next one. p.media_read_busy = true read_devices := p.media_devices_wanted p.media_devices_wanted = false spawn read_media_worker(p.mpv_ctx, p.media_chan, read_devices) } // drain_media applies the finished reads. Non-blocking: called from the draw // loop. fn (mut p Player) drain_media() { for { mut data := MediaData{} if p.media_chan.try_pop(mut data) != .success { break } p.tracks = data.tracks p.chapters = data.chapters // The per-file reads skip the devices; only a read that asked for // them replaces the list, or every file load would empty the menu. if data.read_devices { p.devices = data.devices } p.media_read_busy = false ui2.set_menu_bar(p.menus()) if p.media_dirty { p.media_dirty = false p.refresh_media_async(false) } } }