vendetta / libvendetta / draw.v
855 lines · 822 sloc · 35.22 KB · 77754ad9e6dc749afefba326ff89abc5ddd8c9c9
Raw
1module libvendetta
2
3import math
4import mpv
5import os
6import sokol.gfx
7import sokol.sapp
8import time
9import ui2
10import wake
11
12// register_android_vm hands the NativeActivity's JavaVM to mpv's libavcodec,
13// which needs it for Android audio and hardware decoding. Without it mpv logs
14// that no Java virtual machine is registered and plays without them.
15$if android {
16 fn register_android_vm() {
17 act := unsafe { &os.NativeActivity(sapp.android_get_native_activity()) }
18 if isnil(act) {
19 return
20 }
21 mpv.register_java_vm(act.vm)
22 }
23} $else {
24 fn register_android_vm() {}
25}
26
27// Desktop GL on the Unix targets links the same Mesa libGL as Linux: the
28// headers sit in the default clang search path on FreeBSD, in xenocara's
29// /usr/X11R6 tree on OpenBSD, the base system's /usr/X11R7 on NetBSD,
30// dports' /usr/local on DragonFly, and plain /usr on Solaris — the trees
31// sokol's own flags put on the search paths the whole build shares (Solaris
32// needs none of that, its compiler already searches /usr). All take the
33// Linux include block.
34$if linux || freebsd || openbsd || netbsd || dragonfly || solaris {
35 #flag -lGL
36 #flag -DGL_GLEXT_PROTOTYPES
37 #include <GL/gl.h>
38 #include <GL/glext.h>
39}
40$if windows {
41 // Desktop GL on Windows: sokol's GL backend loads every entry point at
42 // runtime (opengl32.dll only exports GL 1.1, and its static function
43 // pointers in sokol_gfx.h collide with GL header declarations), so this
44 // file declares no GL prototypes and includes no GL header. GL calls go
45 // through mpv.wgl_proc, the same source mpv itself asks; the opengl32
46 // link flag lives in the mpv module next to that loader.
47}
48$if macos {
49 // Desktop GL on macOS links the OpenGL framework, the way the Linux path
50 // links -lGL: sokol's GL backend declares and calls the same functions
51 // through <OpenGL/gl3.h>, so this file includes it and runs its surface
52 // texture work through the header like Linux does. The framework link
53 // flag lives in the mpv module next to mpv's own proc resolver. The
54 // deprecation marks Apple puts on GL functions are silenced the same
55 // way sokol silences them.
56 #define GL_SILENCE_DEPRECATION
57 #include <OpenGL/gl3.h>
58}
59$if android {
60 // GLES 3 on Android links the NDK's GLESv3 the way the Linux path links
61 // Mesa libGL: sokol's GL backend declares and calls the same functions
62 // through <GLES3/gl3.h>, so this file includes it and runs its surface
63 // texture work through the header like Linux does. The link flags live
64 // in the mpv module next to mpv's own proc resolver, which is where the
65 // Windows and macOS story keeps their link flags too.
66 #include <GLES3/gl3.h>
67}
68
69// The macOS build is pinned to the paths the other platforms take. Without
70// ui2_custom_rendering, macOS defaults ui2 to its native AppKit backend,
71// which never calls the gl surface renderer the video arrives through;
72// without darwin_sokol_glcore33, macOS defaults sokol to Metal, which
73// cannot wrap the GL textures mpv draws into. Linux takes the custom
74// renderer without a define, and Windows builds pass both defines the same
75// way the macOS command does.
76$if macos && !ui2_custom_rendering ? {
77 $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")
78}
79$if macos && !darwin_sokol_glcore33 ? {
80 $compile_error('the macOS build needs -d darwin_sokol_glcore33: mpv draws into OpenGL textures, and macOS defaults sokol to Metal')
81}
82
83const gl_color_buffer_bit = 0x00004000
84const gl_scissor_test = 0x0c11
85const gl_texture_2d = 0x0de1
86const gl_texture_min_filter = 0x2801
87const gl_texture_mag_filter = 0x2800
88const gl_linear = 0x2601
89
90const gl_rgba = 0x1908
91const gl_rgba8 = 0x8058
92const gl_unsigned_byte = 0x1401
93const gl_framebuffer = 0x8d40
94const gl_color_attachment0 = 0x8ce0
95
96// One shim per GL entry point the surface's texture work needs, so the
97// surface code below stays platform-free. Linux, the BSDs, Solaris, macOS
98// and Android declare the C prototypes and call the linked GL; the
99// declarations only type-check the calls, because the C compiler takes the
100// real headers' prototypes (V emits no prototype for a file that includes
101// headers, the reason the const qualifiers those headers carry never
102// conflict). Windows cannot declare prototypes at all — sokol_gfx.h defines
103// every GL entry point as a static function pointer it loads itself, and
104// those static pointers collide with GL header declarations — so each shim
105// casts its name out of mpv.wgl_proc, the same source mpv's own render asks,
106// at call time. They all run on the surface's cold paths (allocate, clear,
107// release), so the per-call lookup costs nothing that matters.
108$if linux || freebsd || openbsd || netbsd || dragonfly || solaris || macos || android {
109 fn C.glGenTextures(n i32, textures &u32)
110 fn C.glDeleteTextures(n i32, textures &u32)
111 fn C.glBindTexture(target u32, texture u32)
112 fn C.glTexImage2D(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr)
113 fn C.glTexParameteri(target u32, pname u32, param i32)
114 fn C.glGenFramebuffers(n i32, framebuffers &u32)
115 fn C.glDeleteFramebuffers(n i32, framebuffers &u32)
116 fn C.glBindFramebuffer(target u32, framebuffer u32)
117 fn C.glFramebufferTexture2D(target u32, attachment u32, textarget u32, texture u32, level i32)
118 fn C.glClearColor(r f32, g f32, b f32, a f32)
119 fn C.glClear(mask u32)
120 fn C.glDisable(cap u32)
121 fn C.glViewport(x i32, y i32, width i32, height i32)
122 fn C.glColorMask(r u8, g u8, b u8, a u8)
123
124 fn gl_gen_textures(n i32, textures &u32) { C.glGenTextures(n, textures) }
125 fn gl_delete_textures(n i32, textures &u32) { C.glDeleteTextures(n, textures) }
126 fn gl_bind_texture(target u32, texture u32) { C.glBindTexture(target, texture) }
127 fn gl_tex_image_2d(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr) {
128 C.glTexImage2D(target, level, internal_format, width, height, border, format, typ, pixels)
129 }
130 fn gl_tex_parameter_i(target u32, pname u32, param i32) {
131 C.glTexParameteri(target, pname, param)
132 }
133 fn gl_gen_framebuffers(n i32, framebuffers &u32) { C.glGenFramebuffers(n, framebuffers) }
134 fn gl_delete_framebuffers(n i32, framebuffers &u32) { C.glDeleteFramebuffers(n, framebuffers) }
135 fn gl_bind_framebuffer(target u32, framebuffer u32) { C.glBindFramebuffer(target, framebuffer) }
136 fn gl_framebuffer_texture_2d(target u32, attachment u32, textarget u32, texture u32, level i32) {
137 C.glFramebufferTexture2D(target, attachment, textarget, texture, level)
138 }
139 fn gl_clear_color(r f32, g f32, b f32, a f32) { C.glClearColor(r, g, b, a) }
140 fn gl_clear(mask u32) { C.glClear(mask) }
141 // gl_prepare_mpv_target readies the state mpv draws with: ui2 leaves its own
142 // scissor and viewport set, and mpv does not reset either, so the frame would
143 // be clipped to, and scaled into, the last UI strip drawn.
144 fn gl_prepare_mpv_target(w i32, h i32) {
145 C.glColorMask(1, 1, 1, 1)
146 C.glDisable(gl_scissor_test)
147 C.glViewport(0, 0, w, h)
148 }
149}
150$if windows {
151 type GlGenTexturesProc = fn (i32, &u32)
152 type GlDeleteTexturesProc = fn (i32, &u32)
153 type GlBindTextureProc = fn (u32, u32)
154 type GlTexImage2DProc = fn (u32, i32, i32, i32, i32, i32, u32, u32, voidptr)
155 type GlTexParameteriProc = fn (u32, u32, i32)
156 type GlGenFramebuffersProc = fn (i32, &u32)
157 type GlDeleteFramebuffersProc = fn (i32, &u32)
158 type GlBindFramebufferProc = fn (u32, u32)
159 type GlFramebufferTexture2DProc = fn (u32, u32, u32, u32, i32)
160 type GlClearColorProc = fn (f32, f32, f32, f32)
161 type GlClearProc = fn (u32)
162
163 fn gl_gen_textures(n i32, textures &u32) {
164 GlGenTexturesProc(mpv.wgl_proc(c'glGenTextures'))(n, textures)
165 }
166 fn gl_delete_textures(n i32, textures &u32) {
167 GlDeleteTexturesProc(mpv.wgl_proc(c'glDeleteTextures'))(n, textures)
168 }
169 fn gl_bind_texture(target u32, texture u32) {
170 GlBindTextureProc(mpv.wgl_proc(c'glBindTexture'))(target, texture)
171 }
172 fn gl_tex_image_2d(target u32, level i32, internal_format i32, width i32, height i32, border i32, format u32, typ u32, pixels voidptr) {
173 GlTexImage2DProc(mpv.wgl_proc(c'glTexImage2D'))(target, level, internal_format, width, height, border, format, typ, pixels)
174 }
175 fn gl_tex_parameter_i(target u32, pname u32, param i32) {
176 GlTexParameteriProc(mpv.wgl_proc(c'glTexParameteri'))(target, pname, param)
177 }
178 fn gl_gen_framebuffers(n i32, framebuffers &u32) {
179 GlGenFramebuffersProc(mpv.wgl_proc(c'glGenFramebuffers'))(n, framebuffers)
180 }
181 fn gl_delete_framebuffers(n i32, framebuffers &u32) {
182 GlDeleteFramebuffersProc(mpv.wgl_proc(c'glDeleteFramebuffers'))(n, framebuffers)
183 }
184 fn gl_bind_framebuffer(target u32, framebuffer u32) {
185 GlBindFramebufferProc(mpv.wgl_proc(c'glBindFramebuffer'))(target, framebuffer)
186 }
187 fn gl_framebuffer_texture_2d(target u32, attachment u32, textarget u32, texture u32, level i32) {
188 GlFramebufferTexture2DProc(mpv.wgl_proc(c'glFramebufferTexture2D'))(target, attachment, textarget, texture, level)
189 }
190 fn gl_clear_color(r f32, g f32, b f32, a f32) {
191 GlClearColorProc(mpv.wgl_proc(c'glClearColor'))(r, g, b, a)
192 }
193 fn gl_clear(mask u32) { GlClearProc(mpv.wgl_proc(c'glClear'))(mask) }
194 type GlDisableProc = fn (u32)
195 type GlColorMaskProc = fn (u8, u8, u8, u8)
196 type GlViewportProc = fn (i32, i32, i32, i32)
197 fn gl_prepare_mpv_target(w i32, h i32) {
198 GlColorMaskProc(mpv.wgl_proc(c'glColorMask'))(1, 1, 1, 1)
199 GlDisableProc(mpv.wgl_proc(c'glDisable'))(gl_scissor_test)
200 GlViewportProc(mpv.wgl_proc(c'glViewport'))(0, 0, w, h)
201 }
202}
203
204// render_advanced_control reports whether mpv may prepare frames ahead through
205// its render thread. Android uses the plain render contract: the advanced mode's
206// threading rules are especially fragile around the first asynchronous file load.
207fn render_advanced_control() bool {
208 $if android {
209 return false
210 }
211 return true
212}
213
214// Surface is the framebuffer mpv draws the video into: a texture the size of
215// the .opengl element in pixels, with an FBO attached to it.
216struct Surface {
217mut:
218 w i32
219 h i32
220 tex u32
221 fbo u32
222 // The (tex, w, h) triple ui2 has already registered, so the hand-off below
223 // can skip repeats: ui2 matches an unchanged request and keeps the old
224 // sokol image, and mpv keeps rendering into the same GL texture.
225 handed_tex u32
226 handed_w i32
227 handed_h i32
228}
229
230// resize (re)allocates the surface when the element's size in pixels changes.
231// It reports whether it did, since the new surface is empty until it is
232// rendered.
233fn (mut s Surface) resize(w i32, h i32) bool {
234 if s.fbo != 0 && s.w == w && s.h == h {
235 return false
236 }
237 s.release()
238 s.w = w
239 s.h = h
240 gl_gen_textures(1, &s.tex)
241 gl_bind_texture(gl_texture_2d, s.tex)
242 gl_tex_image_2d(gl_texture_2d, 0, gl_rgba8, w, h, 0, gl_rgba, gl_unsigned_byte, unsafe { nil })
243 gl_tex_parameter_i(gl_texture_2d, gl_texture_min_filter, gl_linear)
244 gl_tex_parameter_i(gl_texture_2d, gl_texture_mag_filter, gl_linear)
245 gl_gen_framebuffers(1, &s.fbo)
246 gl_bind_framebuffer(gl_framebuffer, s.fbo)
247 gl_framebuffer_texture_2d(gl_framebuffer, gl_color_attachment0, gl_texture_2d, s.tex, 0)
248 s.clear()
249 gl_bind_framebuffer(gl_framebuffer, 0)
250 return true
251}
252
253// clear paints the surface black, as when no file is open.
254fn (s Surface) clear() {
255 if s.fbo == 0 {
256 return
257 }
258 gl_bind_framebuffer(gl_framebuffer, s.fbo)
259 gl_clear_color(0, 0, 0, 1)
260 gl_clear(gl_color_buffer_bit)
261 gl_bind_framebuffer(gl_framebuffer, 0)
262}
263
264fn (mut s Surface) release() {
265 if s.fbo != 0 {
266 gl_delete_framebuffers(1, &s.fbo)
267 s.fbo = 0
268 }
269 if s.tex != 0 {
270 gl_delete_textures(1, &s.tex)
271 s.tex = 0
272 }
273}
274
275// render is the entry the host's gl surface renderer calls for every element.
276// It draws only the widget's own surface id and ignores the rest, so the host
277// keeps one renderer for all its GL elements and routes by id.
278pub fn (mut p Player) render(id string, frame ui2.Rect, scale f64, height f64) {
279 if id != video_surface_id {
280 return
281 }
282 p.draw(frame, scale, height)
283}
284
285// draw runs after the host's UI has been drawn, with the GL context current.
286// The render context is created here, not at new(), because it needs that GL
287// context; the startup files load right after, so mpv finds somewhere to draw.
288fn (mut p Player) draw(frame ui2.Rect, scale f64, height f64) {
289 // Under the render-stats probe, time the present: the mpv render call and
290 // the swap block here, and the probe prints their duration per frame.
291 mut draw_t0 := u64(0)
292 $if render_stats_probe ? {
293 draw_t0 = time.sys_mono_now()
294 }
295 _ = height
296 if frame.width * scale < 1 || frame.height * scale < 1 {
297 return
298 }
299 if p.render_ctx == unsafe { nil } {
300 video_debug_note('draw: creating mpv render context')
301 // Advanced control lets the core prepare frames ahead and decode
302 // straight to a texture. Its price: this thread may never wait on the
303 // core, which is why property reads drain from the event queue.
304 // Linux, the BSDs and Solaris pass the X11 display along (sokol
305 // picks its X11 backend on all of them, so sokol's handle is the
306 // right one); Windows, macOS and Android pass no display
307 // parameter — mpv's GL backend reads the context sokol has already
308 // made current on this thread, and Android's EGL context is one of
309 // those.
310 $if linux || freebsd || openbsd || netbsd || dragonfly || solaris {
311 p.render_ctx = mpv.render_context_create_gl_advanced(p.mpv_ctx, sapp.x11_get_display(), render_advanced_control())
312 } $else {
313 p.render_ctx = mpv.render_context_create_gl_advanced(p.mpv_ctx, unsafe { nil }, render_advanced_control())
314 }
315 if p.render_ctx == unsafe { nil } {
316 eprintln('libvendetta: could not create the mpv render context')
317 return
318 }
319 video_debug_note('draw: mpv render context created')
320 // Required soon after creation with advanced control. The callback only
321 // bumps a data-segment counter — its user_data carries this player's
322 // wake slot, claimed before the relay spawns, so two players never wake
323 // each other — and it reads p.paused so the ask it cannot see as a
324 // frame tick is capped while the picture rests.
325 p.wake_slot = wake.claim()
326 mpv.render_context_set_update_callback(p.render_ctx, render_update_wake,
327 voidptr(u64(p.wake_slot)))
328 p.relay_stop = false
329 p.relay_thread = spawn render_wake_relay(p)
330 for i, file in p.startup {
331 flag := if i == 0 { 'replace' } else { 'append-play' }
332 video_debug_note('draw: loadfile ${file}')
333 load_rc := mpv.command_async(p.mpv_ctx, u64(2 + i), ['loadfile', file, flag])
334 video_debug_note('draw: loadfile returned ${load_rc}')
335 if load_rc < 0 {
336 eprintln('libvendetta: loadfile ${file}: ${mpv.error_string(load_rc)}')
337 }
338 }
339 }
340 p.drain_events()
341 resized := p.surface.resize(i32(frame.width * scale), i32(frame.height * scale))
342 $if video_debug ? {
343 // Every geometry change logs: a scale or rotation while paused asks
344 // exactly one frame, and a presents-divisor probe would sleep through
345 // the only draw that shows the broken rect. window_h is the physical
346 // framebuffer height, so the uncovered remainder of the window (the
347 // clear-color band) is height minus the element's covered span.
348 if resized || p.presents % 60 == 0 {
349 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}')
350 }
351 }
352 if p.clear_next {
353 p.surface.clear()
354 p.clear_next = false
355 }
356 p.present(p.surface.w, p.surface.h, resized)
357 // ui2 draws the texture as a quad in its own pass, so the host's overlays
358 // stay on top of the video. mpv changed GL state, so sokol must reset its
359 // cache. The hand-off matters only when the texture object or its size
360 // changes: a repeated request re-registers the same texture and asks ui2
361 // for a frame, and since this call comes from inside the frame ui2 asked
362 // for, the ask would keep that ask going — build, hand-off, ask, forever,
363 // burning a vsync's worth of CPU even with the picture paused. ui2
364 // consumes one request per frame in sync_gl_surface_textures, and the
365 // frame this call belongs to already picked up the previous hand-off.
366 if p.surface.tex != p.surface.handed_tex
367 || p.surface.w != p.surface.handed_w || p.surface.h != p.surface.handed_h {
368 ui2.set_gl_surface_texture(video_surface_id, p.surface.tex, int(p.surface.w), int(p.surface.h))
369 p.surface.handed_tex = p.surface.tex
370 p.surface.handed_w = p.surface.w
371 p.surface.handed_h = p.surface.h
372 }
373 gfx.reset_state_cache()
374 // The glide rides on the frames it paints: its slider write asks for the
375 // next frame, so playback keeps redrawing at the display rate and the ask
376 // dies with a pause, a hidden strip or the option off.
377 p.smooth_frame()
378 $if render_stats_probe ? {
379 draw_ms := f64(time.sys_mono_now() - draw_t0) / 1e6
380 eprintln('probe draw_present ${draw_ms:.1f}ms')
381 }
382}
383
384// video_debug_readback samples the target immediately after mpv's render call,
385// while the result is still known to be in this surface. It is Android-only and
386// compiled only for -d video_debug.
387$if video_debug ? {
388 $if android || linux {
389 fn C.glReadPixels(x i32, y i32, width i32, height i32, format u32, typ u32, pixels voidptr)
390 fn C.glGetFramebufferAttachmentParameteriv(target u32, attachment u32, pname u32, params &i32)
391 fn C.glGetIntegerv(pname u32, data &i32)
392
393 fn (p &Player) video_debug_readback(frame_flags u64, skip bool) {
394 if p.presents % 30 != 0 {
395 return
396 }
397 // GL state mpv left behind: its viewport and scissor decide how the
398 // frame landed in the surface, and the draw binding says whether it
399 // unbound the target.
400 mut gl_state := [7]i32{}
401 C.glGetIntegerv(0x0ba2, &gl_state[0])
402 C.glGetIntegerv(0x0c10, &gl_state[4])
403 C.glGetIntegerv(0x8ca6, &gl_state[6])
404 mut px := [24]u8{}
405 gl_bind_framebuffer(gl_framebuffer, p.surface.fbo)
406 for i, fy in [0.1, 0.3, 0.5, 0.7, 0.9] {
407 C.glReadPixels(p.surface.w / 2, i32(f64(p.surface.h) * fy), 1, 1, gl_rgba,
408 gl_unsigned_byte, &px[i * 4])
409 }
410 C.glReadPixels(p.surface.w - 1, p.surface.h - 1, 1, 1, gl_rgba, gl_unsigned_byte,
411 &px[20])
412 // Exact extent of the drawn content: one full-width row and one
413 // full-height column, scanned for the first/last bright pixel.
414 mut line_buf := []u8{len: p.surface.w * 4}
415 mut col_buf := []u8{len: p.surface.h * 4}
416 C.glReadPixels(0, p.surface.h / 2, p.surface.w, 1, gl_rgba, gl_unsigned_byte,
417 unsafe { voidptr(&line_buf[0]) })
418 C.glReadPixels(p.surface.w / 2, 0, 1, p.surface.h, gl_rgba, gl_unsigned_byte,
419 unsafe { voidptr(&col_buf[0]) })
420 mut x0 := p.surface.w
421 mut x1 := 0
422 for x in 0 .. p.surface.w {
423 b := x * 4
424 if line_buf[b] > 60 || line_buf[b + 1] > 60 || line_buf[b + 2] > 60 {
425 if x < x0 {
426 x0 = x
427 }
428 if x > x1 {
429 x1 = x
430 }
431 }
432 }
433 mut y0 := p.surface.h
434 mut y1 := 0
435 for y in 0 .. p.surface.h {
436 b := y * 4
437 if col_buf[b] > 60 || col_buf[b + 1] > 60 || col_buf[b + 2] > 60 {
438 if y < y0 {
439 y0 = y
440 }
441 if y > y1 {
442 y1 = y
443 }
444 }
445 }
446 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}')
447 // The center column sampled every 1/24th of the surface height,
448 // as GL y (bottom origin): the color sequence against a striped
449 // picture says how the frame mapped into the surface — a squashed
450 // draw shows every source stripe, a truncated one stops early.
451 mut ystep := p.surface.h / 24
452 if ystep < 1 {
453 ystep = 1
454 }
455 mut samples := []string{}
456 for s in 0 .. 24 {
457 b := s * ystep * 4
458 samples << '0x${col_buf[b + 2]:02x}${col_buf[b + 1]:02x}${col_buf[b]:02x}'
459 }
460 eprintln('VIDEO_DEBUG colscan glY0->${p.surface.h - 1}@${ystep} ${samples.join(' ')}')
461 mut attached := i32(0)
462 C.glGetFramebufferAttachmentParameteriv(gl_framebuffer, gl_color_attachment0, 0x8cd1,
463 &attached)
464 gl_bind_framebuffer(gl_framebuffer, 0)
465 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]}')
466 }
467 } $else {
468 fn (p &Player) video_debug_readback(_ u64, _ bool) {}
469 }
470} $else {
471 fn (p &Player) video_debug_readback(_ u64, _ bool) {}
472}
473
474// present draws mpv's pending frame into the video surface. Every queued
475// frame is drawn: a client-side skip is invisible to mpv — the render call
476// consumes the frame and the swap report claims it was shown either way — so
477// skipping can only freeze the picture while mpv believes the display kept
478// up, which is how a slow machine ends up with long drop storms. mpv already
479// sheds what cannot be kept (decoder drops, vo throttling) and its vo thread
480// waits for this call to consume each frame, so drawing everything keeps the
481// pipeline moving at whatever pace the UI thread manages.
482// The one exception is a repeat: mpv re-queues the picture already on screen
483// for intermediate vsyncs, and drawing it again would only repeat the same
484// pixels, so the render call consumes it without a draw while the swap
485// report keeps its timing honest. A repeat may still not be skipped when the
486// surface it would land on was just reallocated — that surface is blank, so
487// the first repeat after a resize must be drawn for real or the video area
488// shows black until the next picture change.
489fn (mut p Player) present(w i32, h i32, resized bool) {
490 p.presents++
491 flags := mpv.render_context_update(p.render_ctx)
492 // A new surface is empty, and mpv only reports a frame when the picture
493 // changes, so a still picture would stay blank until the next change.
494 if !resized && flags & mpv.render_update_frame == 0 {
495 return
496 }
497 info := mpv.render_context_frame_info(p.render_ctx)
498 repeat := info.flags & mpv.render_frame_info_repeat != 0
499 skip := repeat && !resized
500 if skip {
501 p.repeat_skips++
502 }
503 gl_prepare_mpv_target(w, h)
504 render_rc := mpv.render_context_draw(p.render_ctx, p.surface.fbo, w, h, skip, p.cfg.block_target_time)
505 p.video_debug_readback(info.flags, skip)
506 if render_rc < 0 {
507 eprintln('libvendetta: render: ${mpv.error_string(render_rc)}')
508 }
509 mpv.render_context_report_swap(p.render_ctx)
510 if p.presents % 60 == 0 {
511 p.video_debug_dump('periodic')
512 }
513}
514
515// render_update_wake is the mpv render update callback, called on a libmpv
516// thread. It must never call mpv_render_* functions from here, and it must
517// stay off the GC heap too: a store the collector never sees becomes invisible
518// to the UI thread. So the callback only bumps a plain counter in data-segment
519// memory; render_wake_relay, a normal spawned thread, watches it and asks
520// ui2's loop for a frame.
521fn render_update_wake(user_data voidptr) {
522 // The slot index rides in as the callback's user_data: a foreign thread
523 // touching a GC-managed Player here would be invisible to the UI thread,
524 // but a data-segment counter keyed by an integer is not.
525 wake.bump(int(u64(user_data)))
526}
527
528// render_wake_relay forwards mpv's frame hand-offs to the UI loop. The wake
529// semaphore delivers each bump immediately, so the relay sleeps until mpv
530// actually has a frame instead of polling on a timer, and it only watches its
531// own player's slot — another embedded player's bumps go to their own relay.
532//
533// A frame tick asks ui2 for a paint, not a rebuild: the picture lands in the
534// GL surface the retained tree already draws, so the tree only has to rebuild
535// when something it declares changed — the elapsed label at a second
536// boundary, a control's show/hide — which apply_property and the event loop
537// ask for themselves. With advanced control, mpv fires the update callback
538// once per frame slot even while paused — the picture has not changed — so
539// while paused the paint rate is capped at one per second: slow enough to
540// drain mpv's event queue once, and soon enough for the still of a paused
541// seek and the notice line to show. mpv has somewhere to put the picture at
542// render updates; if it stops bumping, a later bump lands as the first ask
543// anyway.
544fn render_wake_relay(p &Player) {
545 mut seen := u64(0)
546 mut last_ask := i64(0)
547 for {
548 if p.relay_stop {
549 return
550 }
551 if p.wake_slot < 0 {
552 // The wake pool was exhausted at setup: nothing will ever bump
553 // this relay awake, so poll instead — still a paint ask per
554 // display frame, only without the semaphore's sleep between
555 // frames. Players beyond the pool's capacity run this, and the
556 // event-driven path above stays what every normal player uses.
557 time.sleep(15 * time.millisecond)
558 if p.paused && time.ticks() - last_ask < time.second {
559 continue
560 }
561 last_ask = time.ticks()
562 ui2.request_paint()
563 continue
564 }
565 wake.wait(p.wake_slot)
566 if p.relay_stop {
567 return
568 }
569 cur := wake.current(p.wake_slot)
570 if cur == seen {
571 continue
572 }
573 seen = cur
574 now := time.ticks()
575 if p.paused && now - last_ask < time.second {
576 continue
577 }
578 last_ask = now
579 ui2.request_paint()
580 }
581}
582
583// stop_relay parks the frame-relay thread for good. The flag plus one bump
584// empties its parked wait: the loop checks the flag before waiting and again
585// once it wakes, so a destroy cannot miss it, and the join keeps a
586// teardown-and-re-embed host from leaking a thread per cycle.
587fn (mut p Player) stop_relay() {
588 if p.relay_stop {
589 return
590 }
591 p.relay_stop = true
592 // A claimed slot posts the bump that ends the parked wait; a fallback
593 // relay (slot −1, the pool exhausted) sees the flag between polls.
594 wake.bump(p.wake_slot)
595 p.relay_thread.wait()
596}
597
598// The control line uses vendetta's own geometry: buttons are bar_button tall
599// (the play toggle and the seek steps a bit wider than tall), sliders and time
600// labels are bar_row tall, and the time labels are time_column_w wide so both
601// ends of the seek slider line up in columns.
602const bar_button = 27.0
603const bar_button_play_w = bar_button + 10.0
604const bar_button_seek_w = bar_button + 7.0
605const bar_row = 20.0
606const bar_height = bar_button + 3.0
607const bar_pad = 2.0
608const bar_gap = 4.0
609const bar_time_w = 72.0
610// An under-hour file renders its labels as mm:ss, five characters narrower
611// than the hh:mm:ss the wide column holds, so its columns follow fmt_time.
612// A file with no duration keeps the wide column: its elapsed label is free
613// to grow into the hours.
614const bar_time_short_w = 52.0
615const bar_time_hour = 60.0 * 60.0
616// The volume column plus its mute button and the gap before it mirror the
617// button cluster left of the elapsed label exactly; the seek slider sits
618// between the two columns, so only an exact mirror puts it at the strip's
619// centre.
620const bar_mute_w = 24.0
621const bar_volume_w = bar_button_play_w + bar_button_seek_w * 2 + bar_gap * 2 - bar_mute_w - bar_gap
622const bar_time_pad = 20.0
623const bar_time_gap = 5.0
624const bar_seek_min_w = 60.0
625const bar_volume_min_w = 40.0
626const bar_time_min_w = 56.0
627
628// time_column_w is the width each time label needs for a file of the given
629// duration: fmt_time draws mm:ss until the total earns its hours column, so
630// the columns match what the labels will actually render.
631fn time_column_w(duration f64) f64 {
632 return if duration >= 0 && duration < bar_time_hour { bar_time_short_w } else { bar_time_w }
633}
634
635// A negative slider thumb_size draws no thumb; the bars are bare tracks.
636const seek_thumb_hidden = -1.0
637
638// The overlay's hide deadline: after this many ms without pointer motion the
639// built frame hides the controls. The wake chain that delivers the ask
640// overshoots the deadline by hide_wake_margin_ms, so the build it wakes sees
641// the deadline passed and schedules the hide for real instead of re-arming.
642const hide_deadline_ms = 2500
643const hide_wake_margin_ms = 250
644
645// ControlBar holds the rects of every control, in the coordinates of the rect
646// control_bar was given.
647pub struct ControlBar {
648pub:
649 seek_back ui2.Rect
650 toggle ui2.Rect
651 seek_forward ui2.Rect
652 elapsed ui2.Rect
653 seek ui2.Rect
654 total ui2.Rect
655 mute ui2.Rect
656 volume ui2.Rect
657 bar ui2.Rect
658}
659
660// control_bar lays the controls out left to right in the given rect's
661// coordinates: seek back, play, seek forward, elapsed, seek slider, total,
662// mute, volume. The seek slider takes the leftover width; in a narrow strip
663// the volume slider shrinks first, then the time columns.
664@[live]
665pub fn control_bar(b ui2.Rect, duration f64) ControlBar {
666 bar_y := b.height - bar_height
667 mid := bar_y + bar_height / 2
668 outer_gap := bar_gap + bar_time_pad
669 mut volume_w := bar_volume_w
670 mut time_w := time_column_w(duration)
671 // The narrow floor follows the columns: the short labels give back the
672 // same slack they saved.
673 time_min_w := bar_time_min_w - (bar_time_w - time_w)
674 mut seek_w := b.width - bar_pad * 2 - bar_button_play_w - bar_button_seek_w * 2 - time_w * 2 -
675 volume_w - bar_mute_w - bar_gap * 3 - outer_gap * 2 - bar_time_gap * 2
676 if seek_w < bar_seek_min_w {
677 shrink := math.min(bar_seek_min_w - seek_w, volume_w - bar_volume_min_w)
678 if shrink > 0 {
679 volume_w -= shrink
680 seek_w += shrink
681 }
682 }
683 if seek_w < bar_seek_min_w {
684 shrink := math.min(bar_seek_min_w - seek_w, time_w - time_min_w)
685 if shrink > 0 {
686 time_w -= shrink
687 seek_w += shrink * 2
688 }
689 }
690 if seek_w < 0 {
691 seek_w = 0
692 }
693 seek_back := ui2.rect(bar_pad, mid - bar_button / 2, bar_button_seek_w, bar_button)
694 toggle := ui2.rect(seek_back.x + bar_button_seek_w + bar_gap, mid - bar_button / 2, bar_button_play_w, bar_button)
695 seek_forward := ui2.rect(toggle.x + bar_button_play_w + bar_gap, mid - bar_button / 2, bar_button_seek_w, bar_button)
696 elapsed := ui2.rect(seek_forward.x + bar_button_seek_w + outer_gap, mid - bar_row / 2, time_w, bar_row)
697 seek := ui2.rect(elapsed.x + time_w + bar_time_gap, mid - bar_row / 2, seek_w, bar_row)
698 total := ui2.rect(seek.x + seek_w + bar_time_gap, mid - bar_row / 2, time_w, bar_row)
699 mute := ui2.rect(total.x + time_w + outer_gap, mid - bar_row / 2, bar_mute_w, bar_row)
700 volume := ui2.rect(mute.x + bar_mute_w + bar_gap, mid - bar_row / 2, volume_w, bar_row)
701 return ControlBar{
702 seek_back: seek_back
703 toggle: toggle
704 seek_forward: seek_forward
705 elapsed: elapsed
706 seek: seek
707 total: total
708 mute: mute
709 volume: volume
710 bar: ui2.rect(0, bar_y, b.width, bar_height)
711 }
712}
713
714// control_box is the control strip's rect in frame-local coordinates (origin
715// top-left, y grows downward): the frame's bottom band, full width, in both
716// layouts. Overlay mode lets the video fill the frame behind it instead.
717fn control_box(frame ui2.Rect) ui2.Rect {
718 return ui2.rect(0, frame.height - bar_height, frame.width, bar_height)
719}
720
721// strip_shown reports whether the control strip is visible in the frame the
722// widget last built: docked strips never hide, overlay strips show while the
723// pointer has moved within the rest deadline or rests near the strip. The
724// smooth bar's frame chain asks it, so a bar nobody sees costs no frames.
725fn (p &Player) strip_shown() bool {
726 if !p.cfg.overlay {
727 return true
728 }
729 if time.ticks() - p.last_motion < hide_deadline_ms {
730 return true
731 }
732 strip := control_box(p.frame)
733 // near is a legacy macro in Windows headers, so the local spells it out.
734 return p.accepts(p.pointer_x, p.pointer_y) && p.pointer_y - p.frame.y > strip.y - 20
735}
736
737// build returns the widget as one root element the host places in its tree
738// at the given frame. The root sits at frame, so everything inside it is
739// frame-local. The video fills the frame in overlay mode and sits above the
740// strip when docked. The strip is a backdrop view and its controls are its
741// children, so their rects are strip-local. Pointer coordinates given to the
742// widget are in the same space as the frame.
743pub fn (mut p Player) build(frame ui2.Rect) ui2.Element {
744 p.frame = frame
745 strip := control_box(frame)
746 mut video_h := frame.height
747 if !p.cfg.overlay {
748 video_h = if frame.height - bar_height > 40 { frame.height - bar_height } else { 40.0 }
749 }
750 video_rect := ui2.rect(0, 0, frame.width, video_h)
751 // Overlay controls hide on a rest deadline; docked controls never hide.
752 controls_shown := p.strip_shown()
753 mut children := [ui2.opengl(video_surface_id, video_rect)]
754 if !controls_shown {
755 return ui2.view(root_id, frame, ui2.BoxStyle{ transparent: true }, children)
756 }
757 bar := control_bar(ui2.rect(0, 0, strip.width, strip.height), p.duration)
758 // The docked strip sits statically, so it takes its own colour; the
759 // floating one keeps the plain backdrop.
760 children << ui2.view('vd_strip', strip, ui2.BoxStyle{
761 bg: if p.cfg.overlay { p.palette.bg_dark } else { p.palette.bg_docked }
762 }, build_controls(p, bar))
763 return ui2.view(root_id, frame, ui2.BoxStyle{ transparent: true }, children)
764}
765
766// build_controls returns the control elements in the strip's coordinates.
767// They are appended one at a time: the checker panics on array literals that
768// mix many of these constructor calls.
769fn build_controls(p &Player, bar ControlBar) []ui2.Element {
770 button_box := ui2.BoxStyle{
771 bg: p.palette.btn_play
772 radius: 6
773 }
774 button_box_seek := ui2.BoxStyle{
775 bg: p.palette.btn_seek
776 radius: 6
777 opacity: 0.8
778 }
779 button_text := ui2.TextStyle{
780 color: p.palette.text_main
781 size: 16
782 valign: .middle
783 }
784 label_text := ui2.TextStyle{
785 color: p.palette.text_muted
786 size: 13
787 }
788 elapsed_text := ui2.TextStyle{
789 ...label_text
790 align: .right
791 }
792 mut children := []ui2.Element{}
793 children << glyph_button('vd_seek_back', bar.seek_back, button_box_seek, button_text, 'symbol:gobackward.30')
794 children << glyph_button('vd_toggle', bar.toggle, button_box, button_text, if p.paused {
795 'symbol:play.fill'
796 } else {
797 'symbol:pause.fill'
798 })
799 children << glyph_button('vd_seek_forward', bar.seek_forward, button_box_seek, button_text, 'symbol:goforward.30')
800 children << ui2.label('vd_elapsed', fmt_time(p.pos), bar.elapsed, elapsed_text)
801 children << ui2.slider(ui2.SliderConfig{
802 id: 'vd_seek'
803 frame: bar.seek
804 min: 0
805 max: if p.duration > 0 { p.duration } else { 1.0 }
806 // The glide's position, not the raw report: a rebuild lands between
807 // reports, and seeding the thumb with the reported value would snap it
808 // back to where the last report found it.
809 value: if p.has_file { p.glide_pos() } else { 0.0 }
810 padding: 0
811 value_track: true
812 style: ui2.SliderStyle{
813 track_color: p.palette.slider_track
814 value_track_color: p.palette.slider_value
815 track_width: 10.0
816 thumb_size: seek_thumb_hidden
817 }
818 })
819 children << ui2.label('vd_total', fmt_time(p.duration), bar.total, label_text)
820 children << ui2.slider(ui2.SliderConfig{
821 id: 'vd_volume'
822 frame: bar.volume
823 min: 0
824 max: 100
825 value: p.volume
826 padding: 0
827 value_track: true
828 style: ui2.SliderStyle{
829 track_color: p.palette.slider_track
830 value_track_color: if p.muted {
831 p.palette.btn_secondary
832 } else {
833 p.palette.slider_value
834 }
835 track_width: 10.0
836 thumb_size: seek_thumb_hidden
837 }
838 })
839 children << glyph_button('vd_volume_icon', bar.mute, ui2.BoxStyle{
840 bg: p.palette.btn_mute
841 radius: 6
842 opacity: 0.8
843 }, button_text, if p.muted { 'symbol:speaker.slash.fill' } else { 'symbol:speaker.wave.2.fill' })
844 return children
845}
846
847// glyph_button builds an image-only control button: the control line uses
848// symbol glyphs instead of text, sized by the button's rect and tinted by its
849// style.
850fn glyph_button(id string, frame ui2.Rect, box_style ui2.BoxStyle, text_style ui2.TextStyle, symbol string) ui2.Element {
851 return ui2.Element{
852 ...ui2.button(id, '', frame, box_style, text_style)
853 image_path: symbol
854 }
855}
856