-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmpv.go
More file actions
354 lines (315 loc) · 10.4 KB
/
Copy pathmpv.go
File metadata and controls
354 lines (315 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package main
/*
#cgo pkg-config: mpv
#include <mpv/client.h>
#include <mpv/render.h>
#include <stdlib.h>
// Forward declaration of the Go-exported callback.
void goRenderUpdate(void *ctx);
// Build the init params for the software renderer: mpv draws each frame into a
// plain memory buffer we supply, so unlike the OpenGL Render API no GL context,
// get_proc_address callback or native display handle is needed, and the render
// calls carry no thread affinity requirements.
static mpv_render_param *make_sw_init_params() {
mpv_render_param *params = calloc(3, sizeof(mpv_render_param));
params[0].type = MPV_RENDER_PARAM_API_TYPE;
params[0].data = MPV_RENDER_API_TYPE_SW;
static int yes = 1;
params[1].type = MPV_RENDER_PARAM_ADVANCED_CONTROL;
params[1].data = &yes;
params[2].type = 0;
params[2].data = NULL;
return params;
}
// Render the current frame into buf as packed "rgb0": bytes r, g, b and one
// unused byte per pixel, rows top to bottom. That is exactly Go's image.RGBA
// layout, so the buffer can be handed to Fyne as a canvas.Shader texture
// without any conversion. The 4th byte is left uninitialized by mpv, so the
// sampling shader must ignore alpha. The target size is the video's display
// size, so mpv needs no scaling and adds no black bars of its own; fitting the
// frame into the widget is left to the shader.
static int render_to_buffer(mpv_render_context *ctx, void *buf, int w, int h) {
int size[2];
size[0] = w;
size[1] = h;
size_t stride = (size_t)w * 4;
char *format = "rgb0";
mpv_render_param params[5];
params[0].type = MPV_RENDER_PARAM_SW_SIZE;
params[0].data = size;
params[1].type = MPV_RENDER_PARAM_SW_FORMAT;
params[1].data = format;
params[2].type = MPV_RENDER_PARAM_SW_STRIDE;
params[2].data = &stride;
params[3].type = MPV_RENDER_PARAM_SW_POINTER;
params[3].data = buf;
params[4].type = 0;
params[4].data = NULL;
return mpv_render_context_render(ctx, params);
}
static void set_update_callback(mpv_render_context *ctx, void *go_ctx) {
mpv_render_context_set_update_callback(ctx, goRenderUpdate, go_ctx);
}
*/
import "C"
import (
"fmt"
"image"
"runtime/cgo"
"strconv"
"sync"
"sync/atomic"
"unsafe"
)
// mpvPlayer drives a libmpv instance and renders its video into a memory
// buffer via the software Render API. Frames are exposed as image.RGBA, ready
// to be used as a canvas.Shader texture.
type mpvPlayer struct {
mpv *C.mpv_handle
render *C.mpv_render_context
needsPaint atomic.Bool
onUpdate func() // called (from any thread) when a new frame is ready
self cgo.Handle // stable handle passed to C callbacks
buf []byte // frame buffer in rgb0 layout, reused while the size is stable
bufW int
bufH int
stop chan struct{} // closed to stop the event loop
stopOnce sync.Once
done chan struct{} // closed when the event loop has exited
}
func newMPVPlayer(file string) (*mpvPlayer, error) {
h := C.mpv_create()
if h == nil {
return nil, fmt.Errorf("mpv_create failed")
}
if err := checkMPV(C.mpv_initialize(h)); err != nil {
C.mpv_terminate_destroy(h)
return nil, err
}
// Let mpv choose hardware decoding when available. With software rendering
// the decoded frames are copied back to system memory for us; that is the
// price for not needing any GL interop.
setOption(h, "hwdec", "auto-safe")
setOption(h, "vo", "libmpv")
p := &mpvPlayer{mpv: h, stop: make(chan struct{}), done: make(chan struct{})}
p.self = cgo.NewHandle(p)
// The software renderer has no GL context to bind to, so the render context
// can be created right here instead of lazily on a painter thread.
params := C.make_sw_init_params()
var rctx *C.mpv_render_context
if err := checkMPV(C.mpv_render_context_create(&rctx, p.mpv, params)); err != nil {
C.free(unsafe.Pointer(params))
p.self.Delete()
C.mpv_terminate_destroy(h)
return nil, err
}
C.free(unsafe.Pointer(params))
p.render = rctx
C.set_update_callback(rctx, unsafe.Pointer(uintptr(p.self)))
// Drain mpv's event queue continuously. This is mandatory: libmpv buffers
// events (including internal wakeups) in a fixed-size queue, and if the
// client never consumes them the queue fills up and mpv throttles/stalls
// playback - which shows up as "plays a few seconds, then pauses, then
// resumes". Consuming events keeps the pipeline flowing.
go p.eventLoop()
// Start playback now that the render context exists.
p.command("loadfile", file)
return p, nil
}
// eventLoop drains mpv's event queue until the player is closed. mpv_wait_event
// must be called from a single thread; this goroutine owns that duty.
func (p *mpvPlayer) eventLoop() {
defer close(p.done)
for {
select {
case <-p.stop:
return
default:
}
// Block up to 100ms waiting for the next event. Returning periodically
// lets us observe the stop signal even when no events arrive.
ev := C.mpv_wait_event(p.mpv, C.double(0.1))
if ev == nil {
continue
}
switch ev.event_id {
case C.MPV_EVENT_NONE:
// Timeout, nothing to do.
case C.MPV_EVENT_SHUTDOWN:
return
}
}
}
// SetOnUpdate registers a callback invoked whenever mpv signals a new frame.
func (p *mpvPlayer) SetOnUpdate(fn func()) { p.onUpdate = fn }
// Frame renders the latest video frame into the player's buffer and returns it
// as an image ready to upload as a texture, or nil when no new frame has been
// produced since the last call. It must be called from a single thread at a
// time; the Video widget calls it on Fyne's main thread (via fyne.Do), which is
// also where the painter uploads textures, so the shared buffer is never
// accessed concurrently.
//
// A fresh image header wraps the reused buffer on every call: the painter
// re-uploads a shader texture only when handed a different image than the last
// one, so returning the same *image.RGBA pointer every time would leave the
// first frame on screen forever.
func (p *mpvPlayer) Frame() *image.RGBA {
if p.render == nil || !p.needsPaint.Swap(false) {
return nil
}
if C.mpv_render_context_update(p.render)&C.MPV_RENDER_UPDATE_FRAME == 0 {
return nil
}
w, h := p.displaySize()
if w <= 0 || h <= 0 {
return nil
}
if w != p.bufW || h != p.bufH {
p.buf = make([]byte, w*h*4)
p.bufW, p.bufH = w, h
}
if err := checkMPV(C.render_to_buffer(p.render, unsafe.Pointer(&p.buf[0]), C.int(w), C.int(h))); err != nil {
return nil
}
return &image.RGBA{Pix: p.buf, Stride: w * 4, Rect: image.Rect(0, 0, w, h)}
}
// Aspect returns the display aspect ratio (width / height) of the current
// video, or 0 if it is not yet known.
func (p *mpvPlayer) Aspect() float32 {
w, h := p.displaySize()
if h <= 0 {
return 0
}
return float32(w) / float32(h)
}
// displaySize returns the video's display dimensions in pixels - after aspect
// ratio and rotation correction - or zeros before the first frame is decoded.
// Rendering at this size keeps the frame at the display aspect, so no bars are
// baked into the pixels and the shader sees a clean frame to letterbox itself.
func (p *mpvPlayer) displaySize() (int, int) {
w, errW := p.getPropertyDouble("dwidth")
h, errH := p.getPropertyDouble("dheight")
if errW != nil || errH != nil {
return 0, 0
}
return int(w), int(h)
}
// Play resumes playback.
func (p *mpvPlayer) Play() { p.setPropertyFlag("pause", false) }
// Pause halts playback, leaving the current frame shown.
func (p *mpvPlayer) Pause() { p.setPropertyFlag("pause", true) }
// TogglePause flips the paused state and returns the new paused value.
func (p *mpvPlayer) TogglePause() bool {
paused := !p.IsPaused()
p.setPropertyFlag("pause", paused)
return paused
}
// IsPaused reports whether playback is currently paused.
func (p *mpvPlayer) IsPaused() bool {
v, err := p.getPropertyFlag("pause")
return err == nil && v
}
// Position returns the current playback time in seconds.
func (p *mpvPlayer) Position() float64 {
v, _ := p.getPropertyDouble("time-pos")
return v
}
// Duration returns the total media length in seconds, or 0 if unknown.
func (p *mpvPlayer) Duration() float64 {
v, _ := p.getPropertyDouble("duration")
return v
}
// SeekTo jumps to an absolute position in seconds.
func (p *mpvPlayer) SeekTo(seconds float64) {
p.command("seek", strconv.FormatFloat(seconds, 'f', 3, 64), "absolute")
}
// Close stops playback and releases all mpv resources. Safe to call once.
func (p *mpvPlayer) Close() {
// Stop the event loop and wait for it to exit before destroying the handle,
// so it never calls mpv_wait_event on a freed handle.
if p.stop != nil {
p.stopOnce.Do(func() { close(p.stop) })
<-p.done
}
if p.render != nil {
C.mpv_render_context_free(p.render)
p.render = nil
}
if p.mpv != nil {
C.mpv_terminate_destroy(p.mpv)
p.mpv = nil
}
if p.self != 0 {
p.self.Delete()
p.self = 0
}
p.buf = nil
}
func (p *mpvPlayer) getPropertyDouble(name string) (float64, error) {
if p.mpv == nil {
return 0, fmt.Errorf("mpv closed")
}
cn := C.CString(name)
defer C.free(unsafe.Pointer(cn))
var val C.double
if err := checkMPV(C.mpv_get_property(p.mpv, cn, C.MPV_FORMAT_DOUBLE, unsafe.Pointer(&val))); err != nil {
return 0, err
}
return float64(val), nil
}
func (p *mpvPlayer) getPropertyFlag(name string) (bool, error) {
if p.mpv == nil {
return false, fmt.Errorf("mpv closed")
}
cn := C.CString(name)
defer C.free(unsafe.Pointer(cn))
var val C.int
if err := checkMPV(C.mpv_get_property(p.mpv, cn, C.MPV_FORMAT_FLAG, unsafe.Pointer(&val))); err != nil {
return false, err
}
return val != 0, nil
}
func (p *mpvPlayer) setPropertyFlag(name string, value bool) {
if p.mpv == nil {
return
}
cn := C.CString(name)
defer C.free(unsafe.Pointer(cn))
var val C.int
if value {
val = 1
}
C.mpv_set_property(p.mpv, cn, C.MPV_FORMAT_FLAG, unsafe.Pointer(&val))
}
func (p *mpvPlayer) command(args ...string) {
cargs := make([]*C.char, len(args)+1)
for i, a := range args {
cargs[i] = C.CString(a)
}
cargs[len(args)] = nil
C.mpv_command(p.mpv, &cargs[0])
for i := range args {
C.free(unsafe.Pointer(cargs[i]))
}
}
func setOption(h *C.mpv_handle, name, value string) {
cn := C.CString(name)
cv := C.CString(value)
defer C.free(unsafe.Pointer(cn))
defer C.free(unsafe.Pointer(cv))
C.mpv_set_option_string(h, cn, cv)
}
func checkMPV(status C.int) error {
if status >= 0 {
return nil
}
return fmt.Errorf("mpv error: %s", C.GoString(C.mpv_error_string(status)))
}
//export goRenderUpdate
func goRenderUpdate(ctx unsafe.Pointer) {
p := cgo.Handle(uintptr(ctx)).Value().(*mpvPlayer)
p.needsPaint.Store(true)
if p.onUpdate != nil {
p.onUpdate()
}
}