vendetta / src / media.v
679 lines · 644 sloc · 22.59 KB · 77754ad9e6dc749afefba326ff89abc5ddd8c9c9
Raw
1import os
2import ui2
3import libvendetta
4import libvendetta.mpv
5import math
6import time
7import json2
8
9$if macos {
10 import macos
11}
12
13// queues_dir is where saved queues live: <config base>/vendetta/queues.
14fn queues_dir() string {
15 return os.join_path(config_base(), 'vendetta', 'queues')
16}
17
18// saved_queues lists the saved queue names, sorted.
19fn 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.
33fn (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.
52fn 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.
62fn playlists_dir() string {
63 return os.join_path(config_base(), 'vendetta', 'playlists')
64}
65
66// saved_playlists lists the playlist slot names, sorted.
67fn 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.
84fn (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.
112fn 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.
131fn 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.
140fn 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.
261fn 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.
271fn (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.
304fn (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.
329fn (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, u64(13 + p.queue.len), ['loadfile', file, 'append-play'])
335 }
336 // The desktop's tracklist reads the playlist mirror, not the queue.
337 p.playlist = p.queue.clone()
338 p.queue_state_changed()
339 } else {
340 for file in paths {
341 p.queue << file
342 p.queue_keys << p.queue_new_key()
343 }
344 p.queue_state_changed()
345 }
346}
347
348// load_paths plays the first path, replacing what is playing, and queues the rest.
349// The paths become the queue, so the panel lists them and the open prompt shows
350// from then on. Before the first frame there is no render context yet, so the
351// paths wait in startup and are loaded then.
352fn (mut p Player) load_paths(paths []string) {
353 libvendetta.video_debug_note('load_paths: enter, render_ctx=${p.render_ctx}')
354 p.playlist = paths.clone()
355 p.queue = paths.clone()
356 // The entries replace the queue wholesale: fresh keys for the rows, and
357 // the drag / keyboard cursor state of the old queue means nothing.
358 p.queue_reset_keys()
359 p.playlist_index = 0
360 p.queue_state_changed()
361 if p.render_ctx == unsafe { nil } {
362 p.startup = paths.clone()
363 return
364 }
365 // Playing now skips everything: drop the old playlist first.
366 mpv.command_async(p.mpv_ctx, u64(80), ['playlist-clear'])
367 for i, file in paths {
368 flag := if i == 0 { 'replace' } else { 'append-play' }
369 mpv.command_async(p.mpv_ctx, u64(13 + i), ['loadfile', file, flag])
370 }
371}
372
373// init_thumb creates the hidden thumbnail mpv instance, lazily: the saved
374// setting or --no-preview can skip it at start, and the View menu can turn
375// the preview on later. vo=null and ao=null keep it off the screen and the
376// audio path; pause=yes keeps a loaded file from decoding.
377fn (mut p Player) init_thumb() {
378 if p.thumb_ctx != unsafe { nil } {
379 return
380 }
381 p.thumb_ctx = mpv.create()
382 if p.thumb_ctx != unsafe { nil } {
383 mpv.set_option(p.thumb_ctx, 'vo', 'null')
384 mpv.set_option(p.thumb_ctx, 'ao', 'null')
385 mpv.set_option(p.thumb_ctx, 'audio', 'no')
386 mpv.set_option(p.thumb_ctx, 'pause', 'yes')
387 mpv.set_option(p.thumb_ctx, 'config', 'no')
388 mpv.set_option(p.thumb_ctx, 'screenshot-format', 'jpeg')
389 thumb_init_rc := mpv.initialize(p.thumb_ctx)
390 if thumb_init_rc < 0 {
391 mpv.destroy(p.thumb_ctx)
392 p.thumb_ctx = unsafe { nil }
393 eprintln('vendetta: thumbnail mpv: ${mpv.error_string(thumb_init_rc)}')
394 }
395 }
396}
397
398// display_name is what the panels call a source: a file contributes its path
399// basename, a link the URL's target with the host standing in when there is
400// none, so the queue sidebar, the open prompt, the statistics line and the
401// MPRIS title fallback all read the same name off the same entry.
402fn display_name(source string, kind libvendetta.MediaKind) string {
403 if kind == .link {
404 return link_name(source)
405 }
406 return os.base(source)
407}
408
409// link_name reduces a link to what reads as its name: the URL's last segment
410// with '?' and everything after dropped, and the host stepping in for a bare
411// index — 'https://example.com/' and 'https://example.com/?listen=1' would
412// otherwise have no name at all.
413fn link_name(url string) string {
414 tail := url.all_after_last('/').all_before('?')
415 if tail.len == 0 {
416 return url.all_after('://').all_before('/')
417 }
418 return tail
419}
420
421// load_thumb_file opens the playing file on the hidden thumbnail instance so
422// hover requests do not pay the file-open cost each time.
423fn (mut p Player) load_thumb_file() {
424 if !p.show_preview || p.thumb_ctx == unsafe { nil } || p.thumb_path == p.current_path {
425 return
426 }
427 // A live stream never earns a preview (it has no duration to seek to),
428 // and the instance would download the live playlist alongside the real
429 // player for as long as both play, starving its demuxer cache. Leave it
430 // idle; the next regular file loads as usual.
431 if p.current_kind == .link {
432 return
433 }
434 p.thumb_path = p.current_path
435 p.preview_state = 0
436 p.preview_visible = false
437 mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace'])
438}
439
440// update_preview tracks the pointer over the seek bar. Once the pointer rests
441// in one spot briefly, request_thumb captures the frame there.
442fn (mut p Player) update_preview() {
443 if !p.show_preview || !p.has_file || p.duration <= 0 || p.thumb_ctx == unsafe { nil } {
444 p.preview_over = false
445 p.preview_visible = false
446 return
447 }
448 b := ui2.bounds()
449 seek := libvendetta.control_bar(b, p.duration).seek
450 // The widget's pointer is already in the layout's space, below the menu bar.
451 over := p.pointer_y >= seek.y && p.pointer_y <= seek.y + seek.height
452 && p.pointer_x >= seek.x && p.pointer_x <= seek.x + seek.width
453 p.preview_over = over
454 if !over {
455 p.preview_visible = false
456 return
457 }
458 if p.preview_state != 0 {
459 if time.ticks() - p.preview_t0 > thumb_timeout_ms {
460 p.preview_state = 0
461 }
462 return
463 }
464 // The seek slider is drawn without a thumb and with no padding, so the
465 // pointer position maps straight onto its frame.
466 hover := (p.pointer_x - seek.x) / seek.width * p.duration
467 if math.abs(hover - p.preview_time) > 0.25 {
468 p.preview_time = hover
469 p.preview_t0 = time.ticks()
470 p.preview_visible = false // the old frame no longer matches the position
471 }
472 if p.preview_visible {
473 return
474 }
475 if time.ticks() - p.preview_t0 >= 150 {
476 p.request_thumb()
477 }
478}
479
480// request_thumb starts one capture on the hidden thumbnail instance: load the
481// file if it is new, then seek there. Each stage's reply keeps the pipeline
482// moving; see drain_thumb.
483fn (mut p Player) request_thumb() {
484 p.preview_index++
485 p.preview_pending_path = os.join_path(os.temp_dir(), 'vendetta_thumb_${p.preview_index}.jpg')
486 p.preview_pending_time = p.preview_time
487 p.preview_t0 = time.ticks()
488 if p.thumb_path != p.current_path {
489 p.preview_state = thumb_state_loading
490 mpv.command_async(p.thumb_ctx, thumb_load_userdata, ['loadfile', p.current_path, 'replace'])
491 return
492 }
493 p.preview_state = thumb_state_seeking
494 mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek', '${p.preview_time:.3f}', 'absolute',
495 'exact'])
496}
497
498// drain_thumb reads the hidden thumbnail instance's queue so it never fills
499// up. Replies advance the capture pipeline; p.preview_state says what is
500// happening: 1 loading the file, 2 waiting for the seek to be queued, 3
501// waiting for the seeked frame to reach the render API, 0 idle.
502// drain_thumb reads the hidden thumbnail instance's queue so it never fills
503// up. Replies advance the capture pipeline; p.preview_state says what is
504// happening: 1 loading the file, 2 waiting for the seek, 3 waiting for the
505// screenshot, 0 idle.
506fn (mut p Player) drain_thumb() {
507 if p.thumb_ctx == unsafe { nil } {
508 return
509 }
510 for {
511 ev := mpv.wait_event(p.thumb_ctx, 0)
512 id := mpv.event_id(ev)
513 if id == mpv.event_none {
514 break
515 }
516 match id {
517 mpv.event_file_loaded {
518 if p.preview_state == thumb_state_loading {
519 p.preview_state = thumb_state_seeking
520 mpv.command_async(p.thumb_ctx, thumb_seek_userdata, ['seek',
521 '${p.preview_pending_time:.3f}', 'absolute', 'exact'])
522 }
523 }
524 mpv.event_command_reply {
525 ud := mpv.event_reply_userdata(ev)
526 if ud == thumb_seek_userdata && p.preview_state == thumb_state_seeking {
527 p.preview_state = thumb_state_shooting
528 os.rm(p.preview_pending_path) or {}
529 mpv.command_async(p.thumb_ctx, thumb_shot_userdata, [
530 'screenshot-to-file',
531 p.preview_pending_path,
532 'video',
533 ])
534 }
535 if ud == thumb_shot_userdata && p.preview_state == thumb_state_shooting {
536 p.preview_state = 0
537 p.show_thumb()
538 }
539 }
540 else {}
541 }
542 }
543}
544
545// show_thumb displays the freshly rendered frame if it still matches where
546// the pointer is.
547fn (mut p Player) show_thumb() {
548 p.preview_show_w = 16
549 p.preview_show_h = 9
550 if size := ui2.image_natural_size(p.preview_pending_path) {
551 p.preview_show_w = size.width
552 p.preview_show_h = size.height
553 }
554 p.preview_show_time = p.preview_pending_time
555 p.preview_show_path = p.preview_pending_path
556 if p.preview_over && math.abs(p.preview_time - p.preview_pending_time) <= 0.25 {
557 p.preview_visible = true
558 }
559 // The preview state was set inside this frame's gl-surface pass, after the
560 // build; in on_demand mode with nothing else waking the loop — video
561 // paused, pointer at rest — this ask is the frame that shows it.
562 ui2.request_refresh()
563}
564
565// refresh_devices reads the audio output devices mpv can use.
566// MediaData carries the track, chapter and device lists read out of mpv on a
567// worker thread, so the render thread never waits on the core (a requirement
568// of the render API's advanced control: a synchronous read on the render
569// thread can deadlock mpv for good). with_devices says whether the worker
570// should read the output devices this round: asking mpv for the device list
571// initializes the whole audio output (its enumeration instantiates the
572// driver's context, libmpv calls pw_context_new for a pinned ao), which is
573// slow, can block a long time against a dead server, and rarely changes. The
574// file-load and track bursts therefore carry no devices; the device readers —
575// the start-up pass and the audio-device/ao writes — ask for them.
576struct MediaData {
577 tracks []Track
578 chapters []Chapter
579 devices []AudioDevice
580}
581
582// read_media_worker runs on its own thread. libmpv core calls are safe from
583// any thread but the one that renders. with_devices gates the device-list
584// read: that property initializes the audio output (mpv instantiates the
585// pinned ao's context to enumerate, pw_context_new for a pinned pipewire),
586// which can stop for a long time against a dead server and must not run
587// under the per-file bursts.
588fn read_media_worker(ctx voidptr, res chan MediaData, with_devices bool) {
589 mut tracks := []Track{}
590 count := (mpv.get_string(ctx, 'track-list/count') or { '0' }).int()
591 for i in 0 .. count {
592 base := 'track-list/${i}'
593 kind := mpv.get_string(ctx, '${base}/type') or { '' }
594 id := mpv.get_string(ctx, '${base}/id') or { '0' }
595 title := mpv.get_string(ctx, '${base}/title') or { '' }
596 lang := mpv.get_string(ctx, '${base}/lang') or { '' }
597 selected := (mpv.get_string(ctx, '${base}/selected') or { 'no' }) == 'yes'
598 mut label := if title.len > 0 { title } else { lang }
599 if label.len == 0 {
600 label = 'Track ${id}'
601 }
602 tracks << Track{
603 kind: kind
604 id: id
605 label: label
606 selected: selected
607 }
608 }
609 mut chapters := []Chapter{}
610 chapter_count := (mpv.get_string(ctx, 'chapter-list/count') or { '0' }).int()
611 for i in 0 .. chapter_count {
612 title := mpv.get_string(ctx, 'chapter-list/${i}/title') or { 'Chapter ${i + 1}' }
613 at := (mpv.get_string(ctx, 'chapter-list/${i}/time') or { '0' }).f64()
614 chapters << Chapter{
615 title: title
616 at: at
617 }
618 }
619 mut devices := []AudioDevice{}
620 if with_devices {
621 device_count := (mpv.get_string(ctx, 'audio-device-list/count') or { '0' }).int()
622 for i in 0 .. device_count {
623 name := mpv.get_string(ctx, 'audio-device-list/${i}/name') or { '' }
624 description := mpv.get_string(ctx, 'audio-device-list/${i}/description') or { name }
625 devices << AudioDevice{
626 name: name
627 description: description
628 }
629 }
630 }
631 res <- MediaData{
632 tracks: tracks
633 chapters: chapters
634 devices: devices
635 }
636}
637
638// refresh_media_async hands the property reads to a worker thread. When one
639// is already in flight, remember it: the selection properties change in bursts
640// while a file loads. with_devices asks the worker to read the output-device
641// list as well — that read instantiates the audio output, so it rides only on
642// the asks that expect the devices to have changed (start-up, an audio-server
643// switch), never on the per-file bursts. A true ask during an in-flight read
644// is sticky: the next read carries it once.
645fn (mut p Player) refresh_media_async(with_devices bool) {
646 if with_devices {
647 p.media_devices_wanted = true
648 }
649 if p.media_read_busy {
650 p.media_dirty = true
651 return
652 }
653 // Take the sticky device ask after the busy test: a true ask during an
654 // in-flight read sticks in media_devices_wanted and rides the next one.
655 p.media_read_busy = true
656 read_devices := p.media_devices_wanted
657 p.media_devices_wanted = false
658 spawn read_media_worker(p.mpv_ctx, p.media_chan, read_devices)
659}
660
661// drain_media applies the finished reads. Non-blocking: called from the draw
662// loop.
663fn (mut p Player) drain_media() {
664 for {
665 mut data := MediaData{}
666 if p.media_chan.try_pop(mut data) != .success {
667 break
668 }
669 p.tracks = data.tracks
670 p.chapters = data.chapters
671 p.devices = data.devices
672 p.media_read_busy = false
673 ui2.set_menu_bar(p.menus())
674 if p.media_dirty {
675 p.media_dirty = false
676 p.refresh_media_async(false)
677 }
678 }
679}
680