module libvendetta import math import mpv import os import sokol.gfx import sokol.sapp import time import ui2 import wake // register_android_vm hands the NativeActivity's JavaVM to mpv's libavcodec, // which needs it for Android audio and hardware decoding. Without it mpv logs // that no Java virtual machine is registered and plays without them. $if android { fn register_android_vm() { act := unsafe { &os.NativeActivity(sapp.android_get_native_activity()) } if isnil(act) { return } mpv.register_java_vm(act.vm) } } $else { fn register_android_vm() {} } // Desktop GL on the Unix targets links the same Mesa libGL as Linux: the // headers sit in the default clang search path on FreeBSD, in xenocara's // /usr/X11R6 tree on OpenBSD, the base system's /usr/X11R7 on NetBSD, // dports' /usr/local on DragonFly, and plain /usr on Solaris — the trees // sokol's own flags put on the search paths the whole build shares (Solaris // needs none of that, its compiler already searches /usr). All take the // Linux include block. $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { #flag -lGL #flag -DGL_GLEXT_PROTOTYPES #include #include } $if windows { // Desktop GL on Windows: sokol's GL backend loads every entry point at // runtime (opengl32.dll only exports GL 1.1, and its static function // pointers in sokol_gfx.h collide with GL header declarations), so this // file declares no GL prototypes and includes no GL header. GL calls go // through mpv.wgl_proc, the same source mpv itself asks; the opengl32 // link flag lives in the mpv module next to that loader. } $if macos { // Desktop GL on macOS links the OpenGL framework, the way the Linux path // links -lGL: sokol's GL backend declares and calls the same functions // through , so this file includes it and runs its surface // texture work through the header like Linux does. The framework link // flag lives in the mpv module next to mpv's own proc resolver. The // deprecation marks Apple puts on GL functions are silenced the same // way sokol silences them. #define GL_SILENCE_DEPRECATION #include } $if android { // GLES 3 on Android links the NDK's GLESv3 the way the Linux path links // Mesa libGL: sokol's GL backend declares and calls the same functions // through , so this file includes it and runs its surface // texture work through the header like Linux does. The link flags live // in the mpv module next to mpv's own proc resolver, which is where the // Windows and macOS story keeps their link flags too. #include } // The macOS build is pinned to the paths the other platforms take. Without // ui2_custom_rendering, macOS defaults ui2 to its native AppKit backend, // which never calls the gl surface renderer the video arrives through; // without darwin_sokol_glcore33, macOS defaults sokol to Metal, which // cannot wrap the GL textures mpv draws into. Linux takes the custom // renderer without a define. Windows keeps sokol's default GL backend, so its // build passes only ui2_custom_rendering: darwin_sokol_glcore33 picks GL over // Metal on macOS and means nothing there. $if macos && !ui2_custom_rendering ? { $compile_error("the macOS build needs -d ui2_custom_rendering: vendetta's video surface reaches ui2's custom renderer, and macOS defaults ui2 to its AppKit backend") } $if macos && !darwin_sokol_glcore33 ? { $compile_error('the macOS build needs -d darwin_sokol_glcore33: mpv draws into OpenGL textures, and macOS defaults sokol to Metal') } const gl_color_buffer_bit = 0x00004000 const gl_scissor_test = 0x0c11 const gl_texture_2d = 0x0de1 const gl_texture_min_filter = 0x2801 const gl_texture_mag_filter = 0x2800 const gl_linear = 0x2601 const gl_rgba = 0x1908 const gl_rgba8 = 0x8058 const gl_unsigned_byte = 0x1401 const gl_framebuffer = 0x8d40 const gl_color_attachment0 = 0x8ce0 // One shim per GL entry point the surface's texture work needs, so the // surface code below stays platform-free. Linux, the BSDs, Solaris, macOS // and Android declare the C prototypes and call the linked GL; the // declarations only type-check the calls, because the C compiler takes the // real headers' prototypes (V emits no prototype for a file that includes // headers, the reason the const qualifiers those headers carry never // conflict). Windows cannot declare prototypes at all — sokol_gfx.h defines // every GL entry point as a static function pointer it loads itself, and // those static pointers collide with GL header declarations — so each shim // casts its name out of mpv.wgl_proc, the same source mpv's own render asks, // at call time. They all run on the surface's cold paths (allocate, clear, // release), so the per-call lookup costs nothing that matters. $if linux || freebsd || openbsd || netbsd || dragonfly || solaris || macos || android { fn C.glGenTextures(n i32, textures &u32) fn C.glDeleteTextures(n i32, textures &u32) fn C.glBindTexture(target u32, texture u32) fn C.glTexImage2D(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr) fn C.glTexParameteri(target u32, pname u32, param i32) fn C.glGenFramebuffers(n i32, framebuffers &u32) fn C.glDeleteFramebuffers(n i32, framebuffers &u32) fn C.glBindFramebuffer(target u32, framebuffer u32) fn C.glFramebufferTexture2D(target u32, attachment u32, textarget u32, texture u32, level i32) fn C.glClearColor(r f32, g f32, b f32, a f32) fn C.glClear(mask u32) fn C.glDisable(cap u32) fn C.glViewport(x i32, y i32, width i32, height i32) fn C.glColorMask(r u8, g u8, b u8, a u8) fn gl_gen_textures(n i32, textures &u32) { C.glGenTextures(n, textures) } fn gl_delete_textures(n i32, textures &u32) { C.glDeleteTextures(n, textures) } fn gl_bind_texture(target u32, texture u32) { C.glBindTexture(target, texture) } fn gl_tex_image_2d(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr) { C.glTexImage2D(target, level, internal_format, width, height, border, format, typ, pixels) } fn gl_tex_parameter_i(target u32, pname u32, param i32) { C.glTexParameteri(target, pname, param) } fn gl_gen_framebuffers(n i32, framebuffers &u32) { C.glGenFramebuffers(n, framebuffers) } fn gl_delete_framebuffers(n i32, framebuffers &u32) { C.glDeleteFramebuffers(n, framebuffers) } fn gl_bind_framebuffer(target u32, framebuffer u32) { C.glBindFramebuffer(target, framebuffer) } fn gl_framebuffer_texture_2d(target u32, attachment u32, textarget u32, texture u32, level i32) { C.glFramebufferTexture2D(target, attachment, textarget, texture, level) } fn gl_clear_color(r f32, g f32, b f32, a f32) { C.glClearColor(r, g, b, a) } fn gl_clear(mask u32) { C.glClear(mask) } // gl_prepare_mpv_target readies the state mpv draws with: ui2 leaves its own // scissor and viewport set, and mpv does not reset either, so the frame would // be clipped to, and scaled into, the last UI strip drawn. fn gl_prepare_mpv_target(w i32, h i32) { C.glColorMask(1, 1, 1, 1) C.glDisable(gl_scissor_test) C.glViewport(0, 0, w, h) } } $if windows { type GlGenTexturesProc = fn (i32, &u32) type GlDeleteTexturesProc = fn (i32, &u32) type GlBindTextureProc = fn (u32, u32) type GlTexImage2DProc = fn (u32, i32, i32, i32, i32, i32, u32, u32, voidptr) type GlTexParameteriProc = fn (u32, u32, i32) type GlGenFramebuffersProc = fn (i32, &u32) type GlDeleteFramebuffersProc = fn (i32, &u32) type GlBindFramebufferProc = fn (u32, u32) type GlFramebufferTexture2DProc = fn (u32, u32, u32, u32, i32) type GlClearColorProc = fn (f32, f32, f32, f32) type GlClearProc = fn (u32) fn gl_gen_textures(n i32, textures &u32) { GlGenTexturesProc(mpv.wgl_proc(c'glGenTextures'))(n, textures) } fn gl_delete_textures(n i32, textures &u32) { GlDeleteTexturesProc(mpv.wgl_proc(c'glDeleteTextures'))(n, textures) } fn gl_bind_texture(target u32, texture u32) { GlBindTextureProc(mpv.wgl_proc(c'glBindTexture'))(target, texture) } fn gl_tex_image_2d(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr) { GlTexImage2DProc(mpv.wgl_proc(c'glTexImage2D'))(target, level, internal_format, width, height, border, format, typ, pixels) } fn gl_tex_parameter_i(target u32, pname u32, param i32) { GlTexParameteriProc(mpv.wgl_proc(c'glTexParameteri'))(target, pname, param) } fn gl_gen_framebuffers(n i32, framebuffers &u32) { GlGenFramebuffersProc(mpv.wgl_proc(c'glGenFramebuffers'))(n, framebuffers) } fn gl_delete_framebuffers(n i32, framebuffers &u32) { GlDeleteFramebuffersProc(mpv.wgl_proc(c'glDeleteFramebuffers'))(n, framebuffers) } fn gl_bind_framebuffer(target u32, framebuffer u32) { GlBindFramebufferProc(mpv.wgl_proc(c'glBindFramebuffer'))(target, framebuffer) } fn gl_framebuffer_texture_2d(target u32, attachment u32, textarget u32, texture u32, level i32) { GlFramebufferTexture2DProc(mpv.wgl_proc(c'glFramebufferTexture2D'))(target, attachment, textarget, texture, level) } fn gl_clear_color(r f32, g f32, b f32, a f32) { GlClearColorProc(mpv.wgl_proc(c'glClearColor'))(r, g, b, a) } fn gl_clear(mask u32) { GlClearProc(mpv.wgl_proc(c'glClear'))(mask) } type GlDisableProc = fn (u32) type GlColorMaskProc = fn (u8, u8, u8, u8) type GlViewportProc = fn (i32, i32, i32, i32) fn gl_prepare_mpv_target(w i32, h i32) { GlColorMaskProc(mpv.wgl_proc(c'glColorMask'))(1, 1, 1, 1) GlDisableProc(mpv.wgl_proc(c'glDisable'))(gl_scissor_test) GlViewportProc(mpv.wgl_proc(c'glViewport'))(0, 0, w, h) } } // render_advanced_control reports whether mpv may prepare frames ahead through // its render thread. Android uses the plain render contract: the advanced mode's // threading rules are especially fragile around the first asynchronous file load. fn render_advanced_control() bool { $if android { return false } return true } // Surface is the framebuffer mpv draws the video into: a texture the size of // the .opengl element in pixels, with an FBO attached to it. struct Surface { mut: w i32 h i32 tex u32 fbo u32 // The (tex, w, h) triple ui2 has already registered, so the hand-off below // can skip repeats: ui2 matches an unchanged request and keeps the old // sokol image, and mpv keeps rendering into the same GL texture. handed_tex u32 handed_w i32 handed_h i32 } // resize (re)allocates the surface when the element's size in pixels changes. // It reports whether it did, since the new surface is empty until it is // rendered. fn (mut s Surface) resize(w i32, h i32) bool { if s.fbo != 0 && s.w == w && s.h == h { return false } s.release() s.w = w s.h = h gl_gen_textures(1, &s.tex) gl_bind_texture(gl_texture_2d, s.tex) gl_tex_image_2d(gl_texture_2d, 0, gl_rgba8, w, h, 0, gl_rgba, gl_unsigned_byte, unsafe { nil }) gl_tex_parameter_i(gl_texture_2d, gl_texture_min_filter, gl_linear) gl_tex_parameter_i(gl_texture_2d, gl_texture_mag_filter, gl_linear) gl_gen_framebuffers(1, &s.fbo) gl_bind_framebuffer(gl_framebuffer, s.fbo) gl_framebuffer_texture_2d(gl_framebuffer, gl_color_attachment0, gl_texture_2d, s.tex, 0) s.clear() gl_bind_framebuffer(gl_framebuffer, 0) return true } // clear paints the surface black, as when no file is open. fn (s Surface) clear() { if s.fbo == 0 { return } gl_bind_framebuffer(gl_framebuffer, s.fbo) gl_clear_color(0, 0, 0, 1) gl_clear(gl_color_buffer_bit) gl_bind_framebuffer(gl_framebuffer, 0) } fn (mut s Surface) release() { if s.fbo != 0 { gl_delete_framebuffers(1, &s.fbo) s.fbo = 0 } if s.tex != 0 { gl_delete_textures(1, &s.tex) s.tex = 0 } } // render is the entry the host's gl surface renderer calls for every element. // It draws only the widget's own surface id and ignores the rest, so the host // keeps one renderer for all its GL elements and routes by id. pub fn (mut p Player) render(id string, frame ui2.Rect, scale f64, height f64) { if id != video_surface_id { return } p.draw(frame, scale, height) } // draw runs after the host's UI has been drawn, with the GL context current. // The render context is created here, not at new(), because it needs that GL // context; the startup files load right after, so mpv finds somewhere to draw. fn (mut p Player) draw(frame ui2.Rect, scale f64, height f64) { // Under the render-stats probe, time the present: the mpv render call and // the swap block here, and the probe prints their duration per frame. mut draw_t0 := u64(0) $if render_stats_probe ? { draw_t0 = time.sys_mono_now() } _ = height if frame.width * scale < 1 || frame.height * scale < 1 { return } if p.render_ctx == unsafe { nil } { video_debug_note('draw: creating mpv render context') // Advanced control lets the core prepare frames ahead and decode // straight to a texture. Its price: this thread may never wait on the // core, which is why property reads drain from the event queue. // Linux, the BSDs and Solaris pass the X11 display along (sokol // picks its X11 backend on all of them, so sokol's handle is the // right one); Windows, macOS and Android pass no display // parameter — mpv's GL backend reads the context sokol has already // made current on this thread, and Android's EGL context is one of // those. $if linux || freebsd || openbsd || netbsd || dragonfly || solaris { p.render_ctx = mpv.render_context_create_gl_advanced(p.mpv_ctx, sapp.x11_get_display(), render_advanced_control()) } $else { p.render_ctx = mpv.render_context_create_gl_advanced(p.mpv_ctx, unsafe { nil }, render_advanced_control()) } if p.render_ctx == unsafe { nil } { eprintln('libvendetta: could not create the mpv render context') return } video_debug_note('draw: mpv render context created') // Required soon after creation with advanced control. The callback only // bumps a data-segment counter — its user_data carries this player's // wake slot, claimed before the relay spawns, so two players never wake // each other — and it reads p.paused so the ask it cannot see as a // frame tick is capped while the picture rests. p.wake_slot = wake.claim() mpv.render_context_set_update_callback(p.render_ctx, render_update_wake, voidptr(u64(p.wake_slot))) p.relay_stop = false p.relay_thread = spawn render_wake_relay(p) for i, file in p.startup { flag := if i == 0 { 'replace' } else { 'append-play' } video_debug_note('draw: loadfile ${file}') load_rc := mpv.command_async(p.mpv_ctx, u64(2 + i), ['loadfile', file, flag]) video_debug_note('draw: loadfile returned ${load_rc}') if load_rc < 0 { eprintln('libvendetta: loadfile ${file}: ${mpv.error_string(load_rc)}') } } } p.drain_events() resized := p.surface.resize(i32(frame.width * scale), i32(frame.height * scale)) $if video_debug ? { // Every geometry change logs: a scale or rotation while paused asks // exactly one frame, and a presents-divisor probe would sleep through // the only draw that shows the broken rect. window_h is the physical // framebuffer height, so the uncovered remainder of the window (the // clear-color band) is height minus the element's covered span. if resized || p.presents % 60 == 0 { eprintln('VIDEO_DEBUG draw frame=${frame.x:.2f},${frame.y:.2f} ${frame.width:.2f}x${frame.height:.2f} scale=${scale:.3f} surface=${p.surface.w}x${p.surface.h} window_h=${height:.1f} resized=${resized}') } } if p.clear_next { p.surface.clear() p.clear_next = false } p.present(p.surface.w, p.surface.h, resized) // ui2 draws the texture as a quad in its own pass, so the host's overlays // stay on top of the video. mpv changed GL state, so sokol must reset its // cache. The hand-off matters only when the texture object or its size // changes: a repeated request re-registers the same texture and asks ui2 // for a frame, and since this call comes from inside the frame ui2 asked // for, the ask would keep that ask going — build, hand-off, ask, forever, // burning a vsync's worth of CPU even with the picture paused. ui2 // consumes one request per frame in sync_gl_surface_textures, and the // frame this call belongs to already picked up the previous hand-off. if p.surface.tex != p.surface.handed_tex || p.surface.w != p.surface.handed_w || p.surface.h != p.surface.handed_h { ui2.set_gl_surface_texture(video_surface_id, p.surface.tex, int(p.surface.w), int(p.surface.h)) p.surface.handed_tex = p.surface.tex p.surface.handed_w = p.surface.w p.surface.handed_h = p.surface.h } gfx.reset_state_cache() // The glide rides on the frames it paints: its slider write asks for the // next frame, so playback keeps redrawing at the display rate and the ask // dies with a pause, a hidden strip or the option off. p.smooth_frame() $if render_stats_probe ? { draw_ms := f64(time.sys_mono_now() - draw_t0) / 1e6 eprintln('probe draw_present ${draw_ms:.1f}ms') } } // video_debug_readback samples the target immediately after mpv's render call, // while the result is still known to be in this surface. It is Android-only and // compiled only for -d video_debug. $if video_debug ? { $if android || linux { fn C.glReadPixels(x i32, y i32, width i32, height i32, format u32, typ u32, pixels voidptr) fn C.glGetFramebufferAttachmentParameteriv(target u32, attachment u32, pname u32, params &i32) fn C.glGetIntegerv(pname u32, data &i32) fn (p &Player) video_debug_readback(frame_flags u64, skip bool) { if p.presents % 30 != 0 { return } // GL state mpv left behind: its viewport and scissor decide how the // frame landed in the surface, and the draw binding says whether it // unbound the target. mut gl_state := [7]i32{} C.glGetIntegerv(0x0ba2, &gl_state[0]) C.glGetIntegerv(0x0c10, &gl_state[4]) C.glGetIntegerv(0x8ca6, &gl_state[6]) mut px := [24]u8{} gl_bind_framebuffer(gl_framebuffer, p.surface.fbo) for i, fy in [0.1, 0.3, 0.5, 0.7, 0.9] { C.glReadPixels(p.surface.w / 2, i32(f64(p.surface.h) * fy), 1, 1, gl_rgba, gl_unsigned_byte, &px[i * 4]) } C.glReadPixels(p.surface.w - 1, p.surface.h - 1, 1, 1, gl_rgba, gl_unsigned_byte, &px[20]) // Exact extent of the drawn content: one full-width row and one // full-height column, scanned for the first/last bright pixel. mut line_buf := []u8{len: p.surface.w * 4} mut col_buf := []u8{len: p.surface.h * 4} C.glReadPixels(0, p.surface.h / 2, p.surface.w, 1, gl_rgba, gl_unsigned_byte, unsafe { voidptr(&line_buf[0]) }) C.glReadPixels(p.surface.w / 2, 0, 1, p.surface.h, gl_rgba, gl_unsigned_byte, unsafe { voidptr(&col_buf[0]) }) mut x0 := p.surface.w mut x1 := 0 for x in 0 .. p.surface.w { b := x * 4 if line_buf[b] > 60 || line_buf[b + 1] > 60 || line_buf[b + 2] > 60 { if x < x0 { x0 = x } if x > x1 { x1 = x } } } mut y0 := p.surface.h mut y1 := 0 for y in 0 .. p.surface.h { b := y * 4 if col_buf[b] > 60 || col_buf[b + 1] > 60 || col_buf[b + 2] > 60 { if y < y0 { y0 = y } if y > y1 { y1 = y } } } eprintln('VIDEO_DEBUG dst-rect x[${x0}..${x1}] y[${y0}..${y1}] = ${x1 - x0 + 1}x${y1 - y0 + 1} of ${p.surface.w}x${p.surface.h}') // The center column sampled every 1/24th of the surface height, // as GL y (bottom origin): the color sequence against a striped // picture says how the frame mapped into the surface — a squashed // draw shows every source stripe, a truncated one stops early. mut ystep := p.surface.h / 24 if ystep < 1 { ystep = 1 } mut samples := []string{} for s in 0 .. 24 { b := s * ystep * 4 samples << '0x${col_buf[b + 2]:02x}${col_buf[b + 1]:02x}${col_buf[b]:02x}' } eprintln('VIDEO_DEBUG colscan glY0->${p.surface.h - 1}@${ystep} ${samples.join(' ')}') mut attached := i32(0) C.glGetFramebufferAttachmentParameteriv(gl_framebuffer, gl_color_attachment0, 0x8cd1, &attached) gl_bind_framebuffer(gl_framebuffer, 0) eprintln('VIDEO_DEBUG fbo tex=${p.surface.tex} attached=${attached} vp=${gl_state[0]},${gl_state[1]}x${gl_state[2]}x${gl_state[3]} scissor=${gl_state[4]},${gl_state[5]}x${gl_state[6]}x... drawfb=${gl_state[6]} paused=${p.paused} flags=${frame_flags} skip=${skip} 10%=${px[0]},${px[1]},${px[2]},${px[3]} 30%=${px[4]},${px[5]},${px[6]},${px[7]} 50%=${px[8]},${px[9]},${px[10]},${px[11]} 70%=${px[12]},${px[13]},${px[14]},${px[15]} 90%=${px[16]},${px[17]},${px[18]},${px[19]} tr=${px[20]},${px[21]},${px[22]},${px[23]}') } } $else { fn (p &Player) video_debug_readback(_ u64, _ bool) {} } } $else { fn (p &Player) video_debug_readback(_ u64, _ bool) {} } // present draws mpv's pending frame into the video surface. Every queued // frame is drawn: a client-side skip is invisible to mpv — the render call // consumes the frame and the swap report claims it was shown either way — so // skipping can only freeze the picture while mpv believes the display kept // up, which is how a slow machine ends up with long drop storms. mpv already // sheds what cannot be kept (decoder drops, vo throttling) and its vo thread // waits for this call to consume each frame, so drawing everything keeps the // pipeline moving at whatever pace the UI thread manages. // The one exception is a repeat: mpv re-queues the picture already on screen // for intermediate vsyncs, and drawing it again would only repeat the same // pixels, so the render call consumes it without a draw while the swap // report keeps its timing honest. A repeat may still not be skipped when the // surface it would land on was just reallocated — that surface is blank, so // the first repeat after a resize must be drawn for real or the video area // shows black until the next picture change. fn (mut p Player) present(w i32, h i32, resized bool) { p.presents++ flags := mpv.render_context_update(p.render_ctx) // A new surface is empty, and mpv only reports a frame when the picture // changes, so a still picture would stay blank until the next change. if !resized && flags & mpv.render_update_frame == 0 { return } info := mpv.render_context_frame_info(p.render_ctx) repeat := info.flags & mpv.render_frame_info_repeat != 0 skip := repeat && !resized if skip { p.repeat_skips++ } gl_prepare_mpv_target(w, h) render_rc := mpv.render_context_draw(p.render_ctx, p.surface.fbo, w, h, skip, p.cfg.block_target_time) p.video_debug_readback(info.flags, skip) if render_rc < 0 { eprintln('libvendetta: render: ${mpv.error_string(render_rc)}') } mpv.render_context_report_swap(p.render_ctx) if p.presents % 60 == 0 { p.video_debug_dump('periodic') } } // render_update_wake is the mpv render update callback, called on a libmpv // thread. It must never call mpv_render_* functions from here, and it must // stay off the GC heap too: a store the collector never sees becomes invisible // to the UI thread. So the callback only bumps a plain counter in data-segment // memory; render_wake_relay, a normal spawned thread, watches it and asks // ui2's loop for a frame. fn render_update_wake(user_data voidptr) { // The slot index rides in as the callback's user_data: a foreign thread // touching a GC-managed Player here would be invisible to the UI thread, // but a data-segment counter keyed by an integer is not. wake.bump(int(u64(user_data))) } // render_wake_relay forwards mpv's frame hand-offs to the UI loop. The wake // semaphore delivers each bump immediately, so the relay sleeps until mpv // actually has a frame instead of polling on a timer, and it only watches its // own player's slot — another embedded player's bumps go to their own relay. // // A frame tick asks ui2 for a paint, not a rebuild: the picture lands in the // GL surface the retained tree already draws, so the tree only has to rebuild // when something it declares changed — the elapsed label at a second // boundary, a control's show/hide — which apply_property and the event loop // ask for themselves. With advanced control, mpv fires the update callback // once per frame slot even while paused — the picture has not changed — so // while paused the paint rate is capped at one per second: slow enough to // drain mpv's event queue once, and soon enough for the still of a paused // seek and the notice line to show. mpv has somewhere to put the picture at // render updates; if it stops bumping, a later bump lands as the first ask // anyway. fn render_wake_relay(p &Player) { mut seen := u64(0) mut last_ask := i64(0) for { if p.relay_stop { return } if p.wake_slot < 0 { // The wake pool was exhausted at setup: nothing will ever bump // this relay awake, so poll instead — still a paint ask per // display frame, only without the semaphore's sleep between // frames. Players beyond the pool's capacity run this, and the // event-driven path above stays what every normal player uses. time.sleep(15 * time.millisecond) if p.paused && time.ticks() - last_ask < time.second { continue } last_ask = time.ticks() ui2.request_paint() continue } wake.wait(p.wake_slot) if p.relay_stop { return } cur := wake.current(p.wake_slot) if cur == seen { continue } seen = cur now := time.ticks() if p.paused && now - last_ask < time.second { continue } last_ask = now ui2.request_paint() } } // stop_relay parks the frame-relay thread for good. The flag plus one bump // empties its parked wait: the loop checks the flag before waiting and again // once it wakes, so a destroy cannot miss it, and the join keeps a // teardown-and-re-embed host from leaking a thread per cycle. fn (mut p Player) stop_relay() { if p.relay_stop { return } p.relay_stop = true // A claimed slot posts the bump that ends the parked wait; a fallback // relay (slot −1, the pool exhausted) sees the flag between polls. wake.bump(p.wake_slot) p.relay_thread.wait() } // The control line uses vendetta's own geometry: buttons are bar_button tall // (the play toggle and the seek steps a bit wider than tall), sliders and time // labels are bar_row tall, and the time labels are time_column_w wide so both // ends of the seek slider line up in columns. const bar_button = 27.0 const bar_button_play_w = bar_button + 10.0 const bar_button_seek_w = bar_button + 7.0 const bar_row = 20.0 const bar_height = bar_button + 3.0 const bar_pad = 2.0 const bar_gap = 4.0 const bar_time_w = 72.0 // An under-hour file renders its labels as mm:ss, five characters narrower // than the hh:mm:ss the wide column holds, so its columns follow fmt_time. // A file with no duration keeps the wide column: its elapsed label is free // to grow into the hours. const bar_time_short_w = 52.0 const bar_time_hour = 60.0 * 60.0 // The volume column plus its mute button and the gap before it mirror the // button cluster left of the elapsed label exactly; the seek slider sits // between the two columns, so only an exact mirror puts it at the strip's // centre. const bar_mute_w = 24.0 const bar_volume_w = bar_button_play_w + bar_button_seek_w * 2 + bar_gap * 2 - bar_mute_w - bar_gap const bar_time_pad = 20.0 const bar_time_gap = 5.0 // The time labels sit this far below the row's centre: the font's digits ride // high, so a centred label reads above the sliders beside it. const bar_time_nudge = 1.0 const bar_seek_min_w = 60.0 const bar_volume_min_w = 40.0 const bar_time_min_w = 56.0 // time_column_w is the width each time label needs for a file of the given // duration: fmt_time draws mm:ss until the total earns its hours column, so // the columns match what the labels will actually render. fn time_column_w(duration f64) f64 { return if duration >= 0 && duration < bar_time_hour { bar_time_short_w } else { bar_time_w } } // slider_frame is a slider's rect for a track of height h: a track taller than // the row grows the frame around its centre, so the whole track takes input. fn slider_frame(row ui2.Rect, h f64) ui2.Rect { if h <= row.height { return row } return ui2.rect(row.x, row.y - (h - row.height) / 2, row.width, h) } // A negative slider thumb_size draws no thumb; the bars are bare tracks. const seek_thumb_hidden = -1.0 // The overlay's hide deadline: after this many ms without pointer motion the // built frame hides the controls. The wake chain that delivers the ask // overshoots the deadline by hide_wake_margin_ms, so the build it wakes sees // the deadline passed and schedules the hide for real instead of re-arming. const hide_deadline_ms = 2500 const hide_wake_margin_ms = 250 // ControlBar holds the rects of every control, in the coordinates of the rect // control_bar was given. pub struct ControlBar { pub: seek_back ui2.Rect toggle ui2.Rect seek_forward ui2.Rect elapsed ui2.Rect seek ui2.Rect total ui2.Rect mute ui2.Rect volume ui2.Rect bar ui2.Rect } // control_bar lays the controls out left to right in the given rect's // coordinates: seek back, play, seek forward, elapsed, seek slider, total, // mute, volume. The seek slider takes the leftover width; in a narrow strip // the volume slider shrinks first, then the time columns. pub fn control_bar(b ui2.Rect, duration f64) ControlBar { bar_y := b.height - bar_height mid := bar_y + bar_height / 2 outer_gap := bar_gap + bar_time_pad mut volume_w := bar_volume_w mut time_w := time_column_w(duration) // The narrow floor follows the columns: the short labels give back the // same slack they saved. time_min_w := bar_time_min_w - (bar_time_w - time_w) mut seek_w := b.width - bar_pad * 2 - bar_button_play_w - bar_button_seek_w * 2 - time_w * 2 - volume_w - bar_mute_w - bar_gap * 3 - outer_gap * 2 - bar_time_gap * 2 if seek_w < bar_seek_min_w { shrink := math.min(bar_seek_min_w - seek_w, volume_w - bar_volume_min_w) if shrink > 0 { volume_w -= shrink seek_w += shrink } } if seek_w < bar_seek_min_w { shrink := math.min(bar_seek_min_w - seek_w, time_w - time_min_w) if shrink > 0 { time_w -= shrink seek_w += shrink * 2 } } if seek_w < 0 { seek_w = 0 } seek_back := ui2.rect(bar_pad, mid - bar_button / 2, bar_button_seek_w, bar_button) toggle := ui2.rect(seek_back.x + bar_button_seek_w + bar_gap, mid - bar_button / 2, bar_button_play_w, bar_button) seek_forward := ui2.rect(toggle.x + bar_button_play_w + bar_gap, mid - bar_button / 2, bar_button_seek_w, bar_button) elapsed := ui2.rect(seek_forward.x + bar_button_seek_w + outer_gap, mid - bar_row / 2 + bar_time_nudge, time_w, bar_row) seek := ui2.rect(elapsed.x + time_w + bar_time_gap, mid - bar_row / 2, seek_w, bar_row) total := ui2.rect(seek.x + seek_w + bar_time_gap, mid - bar_row / 2 + bar_time_nudge, time_w, bar_row) mute := ui2.rect(total.x + time_w + outer_gap, mid - bar_row / 2, bar_mute_w, bar_row) volume := ui2.rect(mute.x + bar_mute_w + bar_gap, mid - bar_row / 2, volume_w, bar_row) return ControlBar{ seek_back: seek_back toggle: toggle seek_forward: seek_forward elapsed: elapsed seek: seek total: total mute: mute volume: volume bar: ui2.rect(0, bar_y, b.width, bar_height) } } // control_box is the control strip's rect in frame-local coordinates (origin // top-left, y grows downward): the frame's bottom band, full width, in both // layouts. Overlay mode lets the video fill the frame behind it instead. fn control_box(frame ui2.Rect) ui2.Rect { return ui2.rect(0, frame.height - bar_height, frame.width, bar_height) } // strip_shown reports whether the control strip is visible in the frame the // widget last built: docked strips never hide, overlay strips show while the // pointer has moved within the rest deadline or rests near the strip. The // smooth bar's frame chain asks it, so a bar nobody sees costs no frames. fn (p &Player) strip_shown() bool { if !p.cfg.overlay { return true } if time.ticks() - p.last_motion < hide_deadline_ms { return true } strip := control_box(p.frame) // near is a legacy macro in Windows headers, so the local spells it out. return p.accepts(p.pointer_x, p.pointer_y) && p.pointer_y - p.frame.y > strip.y - 20 } // build returns the widget as one root element the host places in its tree // at the given frame. The root sits at frame, so everything inside it is // frame-local. The video fills the frame in overlay mode and sits above the // strip when docked. The strip is a backdrop view and its controls are its // children, so their rects are strip-local. Pointer coordinates given to the // widget are in the same space as the frame. pub fn (mut p Player) build(frame ui2.Rect) ui2.Element { p.frame = frame strip := control_box(frame) mut video_h := frame.height if !p.cfg.overlay { video_h = if frame.height - bar_height > 40 { frame.height - bar_height } else { 40.0 } } video_rect := ui2.rect(0, 0, frame.width, video_h) // Overlay controls hide on a rest deadline; docked controls never hide. controls_shown := p.strip_shown() mut children := [ui2.opengl(video_surface_id, video_rect)] if !controls_shown { return ui2.view(root_id, frame, ui2.BoxStyle{ transparent: true }, children) } bar := control_bar(ui2.rect(0, 0, strip.width, strip.height), p.duration) // The docked strip sits statically, so it takes its own colour; the // floating one keeps the plain backdrop. children << ui2.view('vd_strip', strip, ui2.BoxStyle{ bg: if p.cfg.overlay { p.palette.bg_dark } else { p.palette.bg_docked } }, build_controls(p, bar)) return ui2.view(root_id, frame, ui2.BoxStyle{ transparent: true }, children) } // The control strip's icons come from assets/icons: the Material Symbols the // SVGs there export raster to PNGs at 64 px (stb_image, what ui2 draws button // images through, cannot parse SVG). The keys are the roles the strip's // buttons play, not the files' names, so an icon can change under them. const strip_icon_names = ['play', 'pause', 'replay30', 'forward30', 'volume_up', 'volume_off'] // strip_icon_glyph names the Material glyph each icon role falls back to: a // build with no raster icons (`-d no_png_icons`) or a layout without the // assets bundle draws these, rendered from the fonts on every platform — // a missing PNG would otherwise come out as ui2's outline box. fn strip_icon_glyph(name string) string { return match name { 'play' { 'symbol:play.fill' } 'pause' { 'symbol:pause.fill' } 'replay30' { 'symbol:gobackward.30' } 'forward30' { 'symbol:goforward.30' } 'volume_up' { 'symbol:speaker.wave.2.fill' } 'volume_off' { 'symbol:speaker.slash.fill' } else { '' } } } // icon_bundle_dirs lists the places assets/icons ships: beside the executable // (the release layout zips assets/ next to the binary), in the module tree the // build came from, and the working directory. The first hit wins. fn icon_bundle_dirs() []string { return [ os.join_path(os.dir(os.executable()), 'assets', 'icons'), os.join_path(@VMODROOT, 'assets', 'icons'), os.join_path(os.getwd(), 'assets', 'icons'), ] } // resolve_strip_icons maps the icon roles to what the strip's buttons draw: // each bundled PNG's path, or '' where this layout has none (the buttons then // fall to the glyphs). `-d no_png_icons` compiles the resolution out entirely, // leaving the glyphs alone to carry the strip. fn resolve_strip_icons() map[string]string { mut icons := map[string]string{} $if no_png_icons ? { return icons } $else { for name in strip_icon_names { icons[name] = '' for dir_path in icon_bundle_dirs() { bundle_path := os.join_path(dir_path, name + '.png') if os.is_file(bundle_path) { icons[name] = bundle_path break } } } return icons } } // strip_icon is the string the button for `name` draws: the bundled PNG's // path, or the Material glyph the old build carried when the role has none. fn (p &Player) strip_icon(name string) string { if icon := p.icon_files[name] { if icon.len > 0 { return icon } } return strip_icon_glyph(name) } // build_controls returns the control elements in the strip's coordinates. // They are appended one at a time: the checker panics on array literals that // mix many of these constructor calls. fn build_controls(p &Player, bar ControlBar) []ui2.Element { button_box := ui2.BoxStyle{ bg: p.palette.btn_play radius: 6 } button_box_seek := ui2.BoxStyle{ bg: p.palette.btn_seek radius: 6 opacity: 0.8 } button_text := ui2.TextStyle{ color: p.palette.text_main size: 16 valign: .middle } label_text := ui2.TextStyle{ color: p.palette.text_muted size: 13 } elapsed_text := ui2.TextStyle{ ...label_text align: .right } // The seek and volume tracks share one height, kept inside the strip. slider_h := math.min(math.max(p.cfg.slider_h, 1.0), bar_height) mut children := []ui2.Element{} children << glyph_button('vd_seek_back', bar.seek_back, button_box_seek, button_text, p.strip_icon('replay30')) children << glyph_button('vd_toggle', bar.toggle, button_box, button_text, if p.paused { p.strip_icon('play') } else { p.strip_icon('pause') }) children << glyph_button('vd_seek_forward', bar.seek_forward, button_box_seek, button_text, p.strip_icon('forward30')) children << ui2.label('vd_elapsed', fmt_time(p.pos), bar.elapsed, elapsed_text) children << ui2.slider(ui2.SliderConfig{ id: 'vd_seek' frame: slider_frame(bar.seek, slider_h) min: 0 max: if p.duration > 0 { p.duration } else { 1.0 } // The glide's position, not the raw report: a rebuild lands between // reports, and seeding the thumb with the reported value would snap it // back to where the last report found it. value: if p.has_file { p.glide_pos() } else { 0.0 } padding: 0 value_track: true style: ui2.SliderStyle{ track_color: p.palette.slider_track value_track_color: p.palette.slider_value track_width: slider_h thumb_size: seek_thumb_hidden } }) children << ui2.label('vd_total', fmt_time(p.duration), bar.total, label_text) children << ui2.slider(ui2.SliderConfig{ id: 'vd_volume' frame: slider_frame(bar.volume, slider_h) min: 0 max: 100 value: p.volume padding: 0 value_track: true style: ui2.SliderStyle{ track_color: p.palette.slider_track value_track_color: if p.muted { p.palette.btn_secondary } else { p.palette.slider_value } track_width: slider_h thumb_size: seek_thumb_hidden } }) children << glyph_button('vd_volume_icon', bar.mute, ui2.BoxStyle{ bg: p.palette.btn_mute radius: 6 opacity: 0.8 }, button_text, if p.muted { p.strip_icon('volume_off') } else { p.strip_icon('volume_up') }) return children } // glyph_button builds an image-only control button from the string the icon // resolution hands it: a file path draws the rastered PNG as it is (no tint — // a theme cannot restyle it), a 'symbol:' name draws the glyph tinted by the // button's text style. fn glyph_button(id string, frame ui2.Rect, box_style ui2.BoxStyle, text_style ui2.TextStyle, icon string) ui2.Element { return ui2.Element{ ...ui2.button(id, '', frame, box_style, text_style) image_path: icon } }