| 1 | import os |
| 2 | import ui2 |
| 3 | import libvendetta |
| 4 | import libvendetta.mpv |
| 5 | import math |
| 6 | import time |
| 7 | import json2 |
| 8 | |
| 9 | $if macos { |
| 10 | import macos |
| 11 | } |
| 12 | |
| 13 | // queues_dir is where saved queues live: <config base>/vendetta/queues. |
| 14 | fn queues_dir() string { |
| 15 | return os.join_path(config_base(), 'vendetta', 'queues') |
| 16 | } |
| 17 | |
| 18 | // saved_queues lists the saved queue names, sorted. |
| 19 | fn saved_queues() []string { |
| 20 | mut names := []string{} |
| 21 | mut files := os.ls(queues_dir()) or { return names } |
| 22 | files.sort() |
| 23 | for file in files { |
| 24 | if file.ends_with('.json') { |
| 25 | names << file.all_before_last('.json') |
| 26 | } |
| 27 | } |
| 28 | return names |
| 29 | } |
| 30 | |
| 31 | // save_queue writes the current queue under name. The name may not be empty |
| 32 | // or escape the queues directory. |
| 33 | fn (mut p Player) save_queue(name string) bool { |
| 34 | mut clean := name.trim_space() |
| 35 | if clean.len == 0 || clean.contains('/') || clean.contains('\\') || clean.contains('..') { |
| 36 | p.notify('Queue name may not be empty or contain path separators.') |
| 37 | return false |
| 38 | } |
| 39 | if p.queue.len == 0 { |
| 40 | p.notify('The queue is empty.') |
| 41 | return false |
| 42 | } |
| 43 | os.mkdir_all(queues_dir(), os.MkdirParams{}) or {} |
| 44 | os.write_file(os.join_path(queues_dir(), '${clean}.json'), json2.encode(p.queue, json2.EncoderOptions{})) or { |
| 45 | p.notify('Could not save the queue: ${err}') |
| 46 | return false |
| 47 | } |
| 48 | return true |
| 49 | } |
| 50 | |
| 51 | // load_queue_file reads a saved queue's paths. |
| 52 | fn load_queue_file(name string) ?[]string { |
| 53 | text := os.read_file(os.join_path(queues_dir(), '${name}.json')) or { return none } |
| 54 | return json2.decode[[]string](text, json2.DecoderOptions{}) or { none } |
| 55 | } |
| 56 | |
| 57 | // playlists_dir is where playlists live: <config base>/vendetta/playlists, |
| 58 | // one m3u file per name. The format is mpv's own — the one its playlist |
| 59 | // demuxer consumes and every other player reads — so a slot is not |
| 60 | // vendetta's private state: mpv --playlist=<file> plays it, other tools |
| 61 | // write it, and a hand-edited file is simply a playlist. |
| 62 | fn playlists_dir() string { |
| 63 | return os.join_path(config_base(), 'vendetta', 'playlists') |
| 64 | } |
| 65 | |
| 66 | // saved_playlists lists the playlist slot names, sorted. |
| 67 | fn saved_playlists() []string { |
| 68 | mut names := []string{} |
| 69 | mut files := os.ls(playlists_dir()) or { return names } |
| 70 | files.sort() |
| 71 | for file in files { |
| 72 | if file.ends_with('.m3u') { |
| 73 | names << file.all_before_last('.m3u') |
| 74 | } |
| 75 | } |
| 76 | return names |
| 77 | } |
| 78 | |
| 79 | // save_playlist writes the current queue into slot name as a playlist: the |
| 80 | // m3u header, then one plain entry per queue row — files as absolute paths |
| 81 | // and links verbatim. No extensions tags, so the file means the same thing |
| 82 | // in mpv, in every other player, and in a text editor. The name rules |
| 83 | // mirror save_queue's. |
| 84 | fn (p &Player) save_playlist(name string) bool { |
| 85 | mut clean := name.trim_space() |
| 86 | if clean.len == 0 || clean.contains('/') || clean.contains('\\') || clean.contains('..') { |
| 87 | p.notify('Playlist name may not be empty or contain path separators.') |
| 88 | return false |
| 89 | } |
| 90 | if p.queue.len == 0 { |
| 91 | p.notify('The queue is empty.') |
| 92 | return false |
| 93 | } |
| 94 | os.mkdir_all(playlists_dir(), os.MkdirParams{}) or {} |
| 95 | mut lines := ['#EXTM3U'] |
| 96 | for entry in p.queue { |
| 97 | if entry.len > 0 { |
| 98 | lines << entry |
| 99 | } |
| 100 | } |
| 101 | os.write_file(os.join_path(playlists_dir(), '${clean}.m3u'), lines.join('\n') + '\n') or { |
| 102 | p.notify('Could not save the playlist: ${err}') |
| 103 | return false |
| 104 | } |
| 105 | return true |
| 106 | } |
| 107 | |
| 108 | // parse_playlist_file reads a playlist file into its entries: m3u, so blanks |
| 109 | // and '#' lines (EXTM3U, EXTINF) are comments, each remaining line is an |
| 110 | // entry, a relative path resolves against the playlist's own directory like |
| 111 | // mpv resolves them, and links ride through verbatim. |
| 112 | fn parse_playlist_file(path string) ?[]string { |
| 113 | text := os.read_file(path) or { return none } |
| 114 | base_dir := os.dir(path) |
| 115 | mut entries := []string{} |
| 116 | for line in text.split_into_lines() { |
| 117 | entry := line.trim_space() |
| 118 | if entry.len == 0 || entry.starts_with('#') { |
| 119 | continue |
| 120 | } |
| 121 | if os.is_abs_path(entry) { |
| 122 | entries << entry |
| 123 | } else { |
| 124 | entries << os.abs_path(os.join_path(base_dir, entry)) |
| 125 | } |
| 126 | } |
| 127 | return entries |
| 128 | } |
| 129 | |
| 130 | // load_playlist_file reads a playlist slot's entries. |
| 131 | fn load_playlist_file(name string) ?[]string { |
| 132 | return parse_playlist_file(os.join_path(playlists_dir(), '${name}.m3u')) |
| 133 | } |
| 134 | |
| 135 | // dialog_directory is where the open dialog starts: the user's Videos folder |
| 136 | // when one is configured, otherwise the home directory. Linux, the BSDs and |
| 137 | // Solaris read ~/.config/user-dirs.dirs, the same file every desktop tool |
| 138 | // uses; Windows and macOS answer through videos_dir, each defined under its |
| 139 | // own platform. |
| 140 | fn dialog_directory() string { |
| 141 | $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { |
| 142 | mut lines := os.read_lines(os.join_path(os.home_dir(), '.config', 'user-dirs.dirs')) or { |
| 143 | return os.home_dir() |
| 144 | } |
| 145 | for mut line in lines { |
| 146 | line = line.trim_space() |
| 147 | if line.starts_with('XDG_VIDEOS_DIR') && line.contains('=') { |
| 148 | mut value := line.all_after('=').trim_space() |
| 149 | value = value.trim_string_left('"').trim_string_right('"') |
| 150 | value = value.replace('$HOME', os.home_dir()) |
| 151 | if value.len > 0 && os.is_dir(value) { |
| 152 | return value |
| 153 | } |
| 154 | } |
| 155 | } |
| 156 | return os.home_dir() |
| 157 | } $else { |
| 158 | if videos := videos_dir() { |
| 159 | return videos |
| 160 | } |
| 161 | return os.home_dir() |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | $if macos { |
| 166 | #include <dlfcn.h> |
| 167 | |
| 168 | fn C.dlsym(voidptr, &char) voidptr |
| 169 | |
| 170 | // SearchPathsFn is NSSearchPathForDirectoriesInDomains reached through a |
| 171 | // pointer typed to return void*. Foundation's own prototype returns an |
| 172 | // ObjC object, and the ARC rules the macOS C compiles under refuse to |
| 173 | // hand that to V's void pointers without a bridged cast V cannot spell — |
| 174 | // the direct call failed to compile. Reaching the function through dlsym |
| 175 | // (the default scope answers, Foundation is linked) skips the conversion |
| 176 | // the way mpv.v's GlxGetProcAddress skips its header. The array comes |
| 177 | // back autoreleased, so holding it as a plain pointer is correct, and |
| 178 | // everything asked of it afterwards goes through vlib macos, whose calls |
| 179 | // bridge inside C. |
| 180 | type SearchPathsFn = fn (directory u64, domain u64, expand bool) voidptr |
| 181 | |
| 182 | // videos_dir reads the Movies folder's path from Foundation, so a |
| 183 | // library the user moved is honored; nil when macOS cannot name one. |
| 184 | // NSMoviesDirectory is 17 and NSUserDomainMask 1 in the search-path |
| 185 | // enums. It answers dialog_directory's shared videos_dir name. |
| 186 | fn videos_dir() ?string { |
| 187 | f := unsafe { SearchPathsFn(C.dlsym(unsafe { nil }, c'NSSearchPathForDirectoriesInDomains')) } |
| 188 | if f == unsafe { nil } { |
| 189 | return none |
| 190 | } |
| 191 | paths := f(17, 1, true) |
| 192 | if paths == unsafe { nil } || macos.msg_u64(paths, 'count') == 0 { |
| 193 | return none |
| 194 | } |
| 195 | dir := macos.utf8_string(macos.msg_id_u64(paths, 'objectAtIndex:', 0)) |
| 196 | if dir.len == 0 || !os.is_dir(dir) { |
| 197 | return none |
| 198 | } |
| 199 | return dir |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | $if windows { |
| 204 | // videos_dir reads the Videos library's known-folder path through |
| 205 | // SHGetKnownFolderPath; nil when the shell cannot name one. It answers |
| 206 | // dialog_directory's shared videos_dir name. |
| 207 | fn videos_dir() ?string { |
| 208 | // FOLDERID_Videos = {B4BFCC3A-DB2C-424C-B029-7FE99A87C641} |
| 209 | folder_id := [ |
| 210 | u8(0x3a), |
| 211 | u8(0xcc), |
| 212 | u8(0xbf), |
| 213 | u8(0xb4), |
| 214 | u8(0x2c), |
| 215 | u8(0xdb), |
| 216 | u8(0x4c), |
| 217 | u8(0x24), |
| 218 | u8(0xb0), |
| 219 | u8(0x29), |
| 220 | u8(0x7f), |
| 221 | u8(0xe9), |
| 222 | u8(0x9a), |
| 223 | u8(0x87), |
| 224 | u8(0xc6), |
| 225 | u8(0x41), |
| 226 | ] |
| 227 | mut path := voidptr(unsafe { nil }) |
| 228 | rc := C.SHGetKnownFolderPath(voidptr(&folder_id), 0, unsafe { nil }, &path) |
| 229 | if rc != 0 || path == unsafe { nil } { |
| 230 | return none |
| 231 | } |
| 232 | defer { |
| 233 | C.CoTaskMemFree(path) |
| 234 | } |
| 235 | return unsafe { cstring_to_vstring(&u8(path)) } |
| 236 | } |
| 237 | |
| 238 | fn C.SHGetKnownFolderPath(&u8, u32, voidptr, &voidptr) i32 |
| 239 | fn C.CoTaskMemFree(voidptr) |
| 240 | } |
| 241 | |
| 242 | $if android { |
| 243 | // videos_dir is where users' videos live on an Android device: the |
| 244 | // shared Movies folder. Seeing it needs the media permission the |
| 245 | // packaged build's manifest asks for; none when the app runs in a |
| 246 | // sandbox that cannot (scoped storage, no permission granted). It |
| 247 | // answers dialog_directory's shared videos_dir name. |
| 248 | fn videos_dir() ?string { |
| 249 | dir := '/sdcard/Movies' |
| 250 | if os.is_dir(dir) { |
| 251 | return dir |
| 252 | } |
| 253 | return none |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // file_dialog_notice is what to tell a user whose platform has no file |
| 258 | // dialog: Linux, the BSDs and Solaris shell out to zenity or kdialog and say |
| 259 | // what to install; Windows, macOS and Android ship native pickers, so there |
| 260 | // is nothing to say. |
| 261 | fn file_dialog_notice() string { |
| 262 | $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { |
| 263 | return 'Install zenity or kdialog to open files with the file dialog.' |
| 264 | } |
| 265 | return '' |
| 266 | } |
| 267 | |
| 268 | // open_dialog shows the platform file dialog, which is a separate window. |
| 269 | // Windows and macOS get native pickers; Linux, the BSDs and Solaris need |
| 270 | // zenity or kdialog, and without one the window explains what to install. |
| 271 | fn (mut p Player) open_dialog() { |
| 272 | if !ui2.file_dialog_supported() { |
| 273 | notice := file_dialog_notice() |
| 274 | if notice.len > 0 { |
| 275 | p.notify(notice) |
| 276 | } |
| 277 | return |
| 278 | } |
| 279 | // request_file_dialog returns at once on Android, where the picker answers |
| 280 | // later; the paths arrive here either way. |
| 281 | ui2.request_file_dialog(ui2.FileDialogConfig{ |
| 282 | title: 'Open video' |
| 283 | // The picker would otherwise open in the process's working directory |
| 284 | // and list whatever sits there. Start in the user's Videos folder |
| 285 | // when xdg-user-dir knows one. |
| 286 | directory: dialog_directory() |
| 287 | filters: [ |
| 288 | ui2.FileDialogFilter{ |
| 289 | name: 'Video' |
| 290 | extensions: ['mp4', 'mkv', 'webm', 'mov', 'avi', 'm4v'] |
| 291 | }, |
| 292 | ] |
| 293 | }, fn [mut p] (paths []string) { |
| 294 | libvendetta.video_debug_note('picker callback: ${paths}') |
| 295 | if paths.len > 0 { |
| 296 | p.load_or_prompt(paths) |
| 297 | } |
| 298 | libvendetta.video_debug_note('picker callback: load_or_prompt returned') |
| 299 | }) |
| 300 | } |
| 301 | |
| 302 | // load_or_prompt plays the paths right away when the queue is empty, and asks |
| 303 | // whether to play now or add to the queue only when something is queued. |
| 304 | fn (mut p Player) load_or_prompt(paths []string) { |
| 305 | libvendetta.video_debug_note('load_or_prompt: enter') |
| 306 | // The File > Default open setting decides what opening means; ask shows |
| 307 | // the choice dialog every time. |
| 308 | match p.open_mode { |
| 309 | 'play' { |
| 310 | p.load_paths(paths) |
| 311 | return |
| 312 | } |
| 313 | 'queue' { |
| 314 | p.add_to_queue(paths) |
| 315 | return |
| 316 | } |
| 317 | else {} |
| 318 | } |
| 319 | if p.queue.len == 0 { |
| 320 | p.load_paths(paths) |
| 321 | return |
| 322 | } |
| 323 | p.queue_paths = paths.clone() |
| 324 | p.queue_open = true |
| 325 | } |
| 326 | |
| 327 | // add_to_queue appends paths to the queue and, once the renderer is up, to |
| 328 | // mpv's playlist after the current file. |
| 329 | fn (mut p Player) add_to_queue(paths []string) { |
| 330 | if p.render_ctx != unsafe { nil } { |
| 331 | for file in paths { |
| 332 | p.queue << file |
| 333 | p.queue_keys << p.queue_new_key() |
| 334 | mpv.command_async(p.mpv_ctx, loadfile_base + u64(p.queue.len), ['loadfile', file, |
| 335 | 'append-play']) |
| 336 | } |
| 337 | // The desktop's tracklist reads the playlist mirror, not the queue. |
| 338 | p.playlist = p.queue.clone() |
| 339 | p.queue_state_changed() |
| 340 | } else { |
| 341 | for file in paths { |
| 342 | p.queue << file |
| 343 | p.queue_keys << p.queue_new_key() |
| 344 | } |
| 345 | p.queue_state_changed() |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | // load_paths plays the first path, replacing what is playing, and queues the rest. |
| 350 | // The paths become the queue, so the panel lists them and the open prompt shows |
| 351 | // from then on. Before the first frame there is no render context yet, so the |
| 352 | // paths wait in startup and are loaded then. |
| 353 | fn (mut p Player) load_paths(paths []string) { |
| 354 | libvendetta.video_debug_note('load_paths: enter, render_ctx=${p.render_ctx}') |
| 355 | p.playlist = paths.clone() |
| 356 | p.queue = paths.clone() |
| 357 | // The entries replace the queue wholesale: fresh keys for the rows, and |
| 358 | // the drag / keyboard cursor state of the old queue means nothing. |
| 359 | p.queue_reset_keys() |
| 360 | p.playlist_index = 0 |
| 361 | p.queue_state_changed() |
| 362 | if p.render_ctx == unsafe { nil } { |
| 363 | p.startup = paths.clone() |
| 364 | return |
| 365 | } |
| 366 | // Playing now skips everything: drop the old playlist first. |
| 367 | mpv.command_async(p.mpv_ctx, u64(80), ['playlist-clear']) |
| 368 | for i, file in paths { |
| 369 | flag := if i == 0 { 'replace' } else { 'append-play' } |
| 370 | mpv.command_async(p.mpv_ctx, loadfile_base + u64(i), ['loadfile', file, flag]) |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | // init_thumb creates the hidden thumbnail mpv instance, lazily: the saved |
| 375 | // setting or --no-preview can skip it at start, and the View menu can turn |
| 376 | // the preview on later. vo=null and ao=null keep it off the screen and the |
| 377 | // audio path; pause=yes keeps a loaded file from decoding. |
| 378 | fn (mut p Player) init_thumb() { |
| 379 | if p.thumb_ctx != unsafe { nil } { |
| 380 | return |
| 381 | } |
| 382 | p.thumb_ctx = mpv.create() |
| 383 | if p.thumb_ctx != unsafe { nil } { |
| 384 | mpv.set_option(p.thumb_ctx, 'vo', 'null') |
| 385 | mpv.set_option(p.thumb_ctx, 'ao', 'null') |
| 386 | mpv.set_option(p.thumb_ctx, 'audio', 'no') |
| 387 | mpv.set_option(p.thumb_ctx, 'pause', 'yes') |
| 388 | mpv.set_option(p.thumb_ctx, 'config', 'no') |
| 389 | mpv.set_option(p.thumb_ctx, 'screenshot-format', 'jpeg') |
| 390 | thumb_init_rc := mpv.initialize(p.thumb_ctx) |
| 391 | if thumb_init_rc < 0 { |
| 392 | mpv.destroy(p.thumb_ctx) |
| 393 | p.thumb_ctx = unsafe { nil } |
| 394 | eprintln('vendetta: thumbnail mpv: ${mpv.error_string(thumb_init_rc)}') |
| 395 | } |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | // thumb_dir is where this run's seek-preview frames go: a directory named for |
| 400 | // the process, so exit can remove every frame the run left behind, the ones |
| 401 | // from abandoned captures included. |
| 402 | fn thumb_dir() string { |
| 403 | return os.join_path(os.temp_dir(), 'vendetta-thumbs-${os.getpid()}') |
| 404 | } |
| 405 | |
| 406 | // drop_thumb deletes a captured frame that nothing shows any more. |
| 407 | fn drop_thumb(path string) { |
| 408 | os.rm(path) or {} |
| 409 | } |
| 410 | |
| 411 | // drop_shown_thumb deletes the frame on show and clears its path, so the popup |
| 412 | // has nothing to draw. It runs when the frame stops matching what plays: a new |
| 413 | // file, a closed file, or the preview switched off. |
| 414 | fn (mut p Player) drop_shown_thumb() { |
| 415 | drop_thumb(p.preview_show_path) |
| 416 | p.preview_show_path = '' |
| 417 | } |
| 418 | |
| 419 | // display_name is what the panels call a source: a file contributes its path |
| 420 | // basename, a link the URL's target with the host standing in when there is |
| 421 | // none, so the queue sidebar, the open prompt, the statistics line and the |
| 422 | // MPRIS title fallback all read the same name off the same entry. |
| 423 | fn display_name(source string, kind libvendetta.MediaKind) string { |
| 424 | if kind == .link { |
| 425 | return link_name(source) |
| 426 | } |
| 427 | return os.base(source) |
| 428 | } |
| 429 | |
| 430 | // link_name reduces a link to what reads as its name: the URL's last segment |
| 431 | // with '?' and everything after dropped, and the host stepping in for a bare |
| 432 | // index — 'https://example.com/' and 'https://example.com/?listen=1' would |
| 433 | // otherwise have no name at all. |
| 434 | fn link_name(url string) string { |
| 435 | tail := url.all_after_last('/').all_before('?') |
| 436 | if tail.len == 0 { |
| 437 | return url.all_after('://').all_before('/') |
| 438 | } |
| 439 | return tail |
| 440 | } |
| 441 | |
| 442 | // load_thumb_file opens the playing file on the hidden thumbnail instance so |
| 443 | // hover requests do not pay the file-open cost each time. |
| 444 | fn (mut p Player) load_thumb_file() { |
| 445 | if !p.show_preview || p.thumb_ctx == unsafe { nil } || p.thumb_path == p.current_path { |
| 446 | return |
| 447 | } |
| 448 | // The frame on show was taken from the file that just stopped playing. |
| 449 | p.drop_shown_thumb() |
| 450 | // A live stream never earns a preview (it has no duration to seek to), |
| 451 | // and the instance would download the live playlist alongside the real |
| 452 | // player for as long as both play, starving its demuxer cache. Leave it |
| 453 | // idle; the next regular file loads as usual. |
| 454 | if p.current_kind == .link { |
| 455 | return |
| 456 | } |
| 457 | p.thumb_path = p.current_path |
| 458 | p.preview_state = 0 |
| 459 | p.preview_visible = false |
| 460 | mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace']) |
| 461 | } |
| 462 | |
| 463 | // update_preview tracks the pointer over the seek bar. Once the pointer rests |
| 464 | // in one spot briefly, request_thumb captures the frame there. |
| 465 | fn (mut p Player) update_preview() { |
| 466 | if !p.show_preview || !p.has_file || p.duration <= 0 || p.thumb_ctx == unsafe { nil } { |
| 467 | p.preview_over = false |
| 468 | p.preview_visible = false |
| 469 | return |
| 470 | } |
| 471 | seek := libvendetta.control_bar(p.main_area(ui2.bounds()), p.duration).seek |
| 472 | // The widget's pointer is already in the layout's space, below the menu bar. |
| 473 | over := p.pointer_y >= seek.y && p.pointer_y <= seek.y + seek.height |
| 474 | && p.pointer_x >= seek.x && p.pointer_x <= seek.x + seek.width |
| 475 | p.preview_over = over |
| 476 | if !over { |
| 477 | p.preview_visible = false |
| 478 | return |
| 479 | } |
| 480 | if p.preview_state != 0 { |
| 481 | if time.ticks() - p.preview_t0 > thumb_timeout_ms { |
| 482 | p.preview_state = 0 |
| 483 | } |
| 484 | return |
| 485 | } |
| 486 | // The seek slider is drawn without a thumb and with no padding, so the |
| 487 | // pointer position maps straight onto its frame. |
| 488 | hover := (p.pointer_x - seek.x) / seek.width * p.duration |
| 489 | if math.abs(hover - p.preview_time) > 0.25 { |
| 490 | p.preview_time = hover |
| 491 | p.preview_t0 = time.ticks() |
| 492 | p.preview_visible = false // the old frame no longer matches the position |
| 493 | } |
| 494 | if p.preview_visible { |
| 495 | return |
| 496 | } |
| 497 | if time.ticks() - p.preview_t0 >= 150 { |
| 498 | p.request_thumb() |
| 499 | } |
| 500 | } |
| 501 | |
| 502 | // request_thumb starts one capture on the hidden thumbnail instance: load the |
| 503 | // file if it is new, then seek there. Each stage's reply keeps the pipeline |
| 504 | // moving; see drain_thumb. |
| 505 | fn (mut p Player) request_thumb() { |
| 506 | p.preview_index++ |
| 507 | // Every capture gets a file of its own: ui2 keeps a decoded image per path, |
| 508 | // so a reused name would keep showing the first frame. |
| 509 | os.mkdir_all(thumb_dir(), os.MkdirParams{}) or {} |
| 510 | p.preview_pending_path = os.join_path(thumb_dir(), 'thumb_${p.preview_index}.jpg') |
| 511 | p.preview_pending_time = p.preview_time |
| 512 | p.preview_t0 = time.ticks() |
| 513 | if p.thumb_path != p.current_path { |
| 514 | p.preview_state = thumb_state_loading |
| 515 | mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace']) |
| 516 | return |
| 517 | } |
| 518 | p.preview_state = thumb_state_seeking |
| 519 | mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek', '${p.preview_time:.3f}', 'absolute', |
| 520 | 'exact']) |
| 521 | } |
| 522 | |
| 523 | // drain_thumb reads the hidden thumbnail instance's queue so it never fills |
| 524 | // up. Replies advance the capture pipeline; p.preview_state says what is |
| 525 | // happening: 1 loading the file, 2 waiting for the seek, 3 waiting for the |
| 526 | // screenshot, 0 idle. |
| 527 | fn (mut p Player) drain_thumb() { |
| 528 | if p.thumb_ctx == unsafe { nil } { |
| 529 | return |
| 530 | } |
| 531 | for { |
| 532 | ev := mpv.wait_event(p.thumb_ctx, 0) |
| 533 | id := mpv.event_id(ev) |
| 534 | if id == mpv.event_none { |
| 535 | break |
| 536 | } |
| 537 | match id { |
| 538 | mpv.event_file_loaded { |
| 539 | if p.preview_state == thumb_state_loading { |
| 540 | p.preview_state = thumb_state_seeking |
| 541 | mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek', |
| 542 | '${p.preview_pending_time:.3f}', 'absolute', 'exact']) |
| 543 | } |
| 544 | } |
| 545 | mpv.event_command_reply { |
| 546 | ud := mpv.event_reply_userdata(ev) |
| 547 | if ud == thumb_seek_userdata && p.preview_state == thumb_state_seeking { |
| 548 | p.preview_state = thumb_state_shooting |
| 549 | os.rm(p.preview_pending_path) or {} |
| 550 | mpv.command_async(p.thumb_ctx, thumb_shot_userdata, [ |
| 551 | 'screenshot-to-file', |
| 552 | p.preview_pending_path, |
| 553 | 'video', |
| 554 | ]) |
| 555 | } |
| 556 | if ud == thumb_shot_userdata && p.preview_state == thumb_state_shooting { |
| 557 | p.preview_state = 0 |
| 558 | p.show_thumb() |
| 559 | } |
| 560 | } |
| 561 | else {} |
| 562 | } |
| 563 | } |
| 564 | } |
| 565 | |
| 566 | // show_thumb displays the freshly rendered frame if it still matches where |
| 567 | // the pointer is. |
| 568 | fn (mut p Player) show_thumb() { |
| 569 | p.preview_show_w = 16 |
| 570 | p.preview_show_h = 9 |
| 571 | if size := ui2.image_natural_size(p.preview_pending_path) { |
| 572 | p.preview_show_w = size.width |
| 573 | p.preview_show_h = size.height |
| 574 | } |
| 575 | p.preview_show_time = p.preview_pending_time |
| 576 | // The frame this one replaces is no longer on show, so its file goes. The |
| 577 | // popup takes the new path from the next build, which runs after this draw. |
| 578 | if p.preview_show_path != p.preview_pending_path { |
| 579 | drop_thumb(p.preview_show_path) |
| 580 | } |
| 581 | p.preview_show_path = p.preview_pending_path |
| 582 | if p.preview_over && math.abs(p.preview_time - p.preview_pending_time) <= 0.25 { |
| 583 | p.preview_visible = true |
| 584 | } |
| 585 | // The preview state was set inside this frame's gl-surface pass, after the |
| 586 | // build; in on_demand mode with nothing else waking the loop — video |
| 587 | // paused, pointer at rest — this ask is the frame that shows it. |
| 588 | ui2.request_refresh() |
| 589 | } |
| 590 | |
| 591 | // refresh_devices reads the audio output devices mpv can use. |
| 592 | // MediaData carries the track, chapter and device lists read out of mpv on a |
| 593 | // worker thread, so the render thread never waits on the core (a requirement |
| 594 | // of the render API's advanced control: a synchronous read on the render |
| 595 | // thread can deadlock mpv for good). with_devices says whether the worker |
| 596 | // should read the output devices this round: asking mpv for the device list |
| 597 | // initializes the whole audio output (its enumeration instantiates the |
| 598 | // driver's context, libmpv calls pw_context_new for a pinned ao), which is |
| 599 | // slow, can block a long time against a dead server, and rarely changes. The |
| 600 | // file-load and track bursts therefore carry no devices; the device readers — |
| 601 | // the start-up pass and the audio-device/ao writes — ask for them. |
| 602 | // read_devices tells drain_media whether devices is a fresh list or merely |
| 603 | // left unread: a read without the devices must keep the menu's last list. |
| 604 | struct MediaData { |
| 605 | tracks []Track |
| 606 | chapters []Chapter |
| 607 | devices []AudioDevice |
| 608 | read_devices bool |
| 609 | } |
| 610 | |
| 611 | // read_media_worker runs on its own thread. libmpv core calls are safe from |
| 612 | // any thread but the one that renders. with_devices gates the device-list |
| 613 | // read: that property initializes the audio output (mpv instantiates the |
| 614 | // pinned ao's context to enumerate, pw_context_new for a pinned pipewire), |
| 615 | // which can stop for a long time against a dead server and must not run |
| 616 | // under the per-file bursts. |
| 617 | fn read_media_worker(ctx voidptr, res chan MediaData, with_devices bool) { |
| 618 | mut tracks := []Track{} |
| 619 | count := (mpv.get_string(ctx, 'track-list/count') or { '0' }).int() |
| 620 | for i in 0 .. count { |
| 621 | base := 'track-list/${i}' |
| 622 | kind := mpv.get_string(ctx, '${base}/type') or { '' } |
| 623 | id := mpv.get_string(ctx, '${base}/id') or { '0' } |
| 624 | title := mpv.get_string(ctx, '${base}/title') or { '' } |
| 625 | lang := mpv.get_string(ctx, '${base}/lang') or { '' } |
| 626 | selected := (mpv.get_string(ctx, '${base}/selected') or { 'no' }) == 'yes' |
| 627 | mut label := if title.len > 0 { title } else { lang } |
| 628 | if label.len == 0 { |
| 629 | label = 'Track ${id}' |
| 630 | } |
| 631 | tracks << Track{ |
| 632 | kind: kind |
| 633 | id: id |
| 634 | label: label |
| 635 | selected: selected |
| 636 | } |
| 637 | } |
| 638 | mut chapters := []Chapter{} |
| 639 | chapter_count := (mpv.get_string(ctx, 'chapter-list/count') or { '0' }).int() |
| 640 | for i in 0 .. chapter_count { |
| 641 | title := mpv.get_string(ctx, 'chapter-list/${i}/title') or { 'Chapter ${i + 1}' } |
| 642 | at := (mpv.get_string(ctx, 'chapter-list/${i}/time') or { '0' }).f64() |
| 643 | chapters << Chapter{ |
| 644 | title: title |
| 645 | at: at |
| 646 | } |
| 647 | } |
| 648 | mut devices := []AudioDevice{} |
| 649 | if with_devices { |
| 650 | device_count := (mpv.get_string(ctx, 'audio-device-list/count') or { '0' }).int() |
| 651 | for i in 0 .. device_count { |
| 652 | name := mpv.get_string(ctx, 'audio-device-list/${i}/name') or { '' } |
| 653 | description := mpv.get_string(ctx, 'audio-device-list/${i}/description') or { name } |
| 654 | devices << AudioDevice{ |
| 655 | name: name |
| 656 | description: description |
| 657 | } |
| 658 | } |
| 659 | } |
| 660 | res <- MediaData{ |
| 661 | tracks: tracks |
| 662 | chapters: chapters |
| 663 | devices: devices |
| 664 | read_devices: with_devices |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | // refresh_media_async hands the property reads to a worker thread. When one |
| 669 | // is already in flight, remember it: the selection properties change in bursts |
| 670 | // while a file loads. with_devices asks the worker to read the output-device |
| 671 | // list as well — that read instantiates the audio output, so it rides only on |
| 672 | // the asks that expect the devices to have changed (start-up, an audio-server |
| 673 | // switch), never on the per-file bursts. A true ask during an in-flight read |
| 674 | // is sticky: the next read carries it once. |
| 675 | fn (mut p Player) refresh_media_async(with_devices bool) { |
| 676 | if with_devices { |
| 677 | p.media_devices_wanted = true |
| 678 | } |
| 679 | if p.media_read_busy { |
| 680 | p.media_dirty = true |
| 681 | return |
| 682 | } |
| 683 | // Take the sticky device ask after the busy test: a true ask during an |
| 684 | // in-flight read sticks in media_devices_wanted and rides the next one. |
| 685 | p.media_read_busy = true |
| 686 | read_devices := p.media_devices_wanted |
| 687 | p.media_devices_wanted = false |
| 688 | spawn read_media_worker(p.mpv_ctx, p.media_chan, read_devices) |
| 689 | } |
| 690 | |
| 691 | // drain_media applies the finished reads. Non-blocking: called from the draw |
| 692 | // loop. |
| 693 | fn (mut p Player) drain_media() { |
| 694 | for { |
| 695 | mut data := MediaData{} |
| 696 | if p.media_chan.try_pop(mut data) != .success { |
| 697 | break |
| 698 | } |
| 699 | p.tracks = data.tracks |
| 700 | p.chapters = data.chapters |
| 701 | // The per-file reads skip the devices; only a read that asked for |
| 702 | // them replaces the list, or every file load would empty the menu. |
| 703 | if data.read_devices { |
| 704 | p.devices = data.devices |
| 705 | } |
| 706 | p.media_read_busy = false |
| 707 | ui2.set_menu_bar(p.menus()) |
| 708 | if p.media_dirty { |
| 709 | p.media_dirty = false |
| 710 | p.refresh_media_async(false) |
| 711 | } |
| 712 | } |
| 713 | } |
| 714 | |