forked from dexterlb/mpvipc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mpvipc.go
285 lines (228 loc) · 7.05 KB
/
mpvipc.go
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
// Package mpvipc provides an interface for communicating with the mpv media
// player via it's JSON IPC interface
package mpvipc
import (
"bufio"
"encoding/json"
"fmt"
"net"
"sync"
)
// Connection represents a connection to a mpv IPC socket
type Connection struct {
client net.Conn
socketName string
lastRequest uint
waitingRequests map[uint]func(*CommandResult)
lastListener uint
eventListeners map[uint]func(*Event)
lock sync.Mutex
}
// Event represents an event received from mpv. For a list of all possible
// events, see https://mpv.io/manual/master/#list-of-events
type Event struct {
// Name is the only obligatory field: the name of the event
Name string `json:"event"`
// Reason is the reason for the event: currently used for the "end-file"
// event. When Name is "end-file", possible values of Reason are: "eof",
// "stop", "quit", "error", "redirect", "unknown"
Reason string `json:"reason"`
// Prefix is the log-message prefix (only if Name is "log-message")
Prefix string `json:"prefix"`
// Level is the loglevel for a log-message (only if Name is "log-message")
Level string `json:"level"`
// Text is the text of a log-message (only if Name is "log-message")
Text string `json:"text"`
// ID is the user-set property ID (on events triggered by observed
// properties)
ID uint `json:"id"`
// Data is the property value (on events triggered by observed properties)
Data interface{} `json:"data"`
// Error is present if Reason is "error."
Error string `json:"error"`
}
// NewConnection returns a Connection associated with the given unix socket
func NewConnection(socketName string) *Connection {
return &Connection{
socketName: socketName,
waitingRequests: make(map[uint]func(*CommandResult)),
eventListeners: make(map[uint]func(*Event)),
}
}
// Open connects to the socket. Returns an error if already connected.
// It also starts listening to events, so ListenForEvents() can be called
// afterwards.
func (c *Connection) Open() error {
c.lock.Lock()
defer c.lock.Unlock()
if c.client != nil {
return fmt.Errorf("already open")
}
client, err := dial(c.socketName)
if err != nil {
return fmt.Errorf("can't connect to mpv's socket: %s", err)
}
c.client = client
go c.listen()
return nil
}
// ListenForEvents adds the given event callback into the listener set. The
// returned callback will return the channel when called. The given callback
// will be called in the main loop that listens for events, so any work should
// be distributed to another thread.
func (c *Connection) ListenForEvents(onEvent func(*Event)) func() {
c.lock.Lock()
c.lastListener++
id := c.lastListener
c.eventListeners[id] = onEvent
c.lock.Unlock()
return func() {
c.lock.Lock()
delete(c.eventListeners, id)
c.lock.Unlock()
}
}
// Call calls an arbitrary command and returns its result. For a list of
// possible functions, see https://mpv.io/manual/master/#commands and
// https://mpv.io/manual/master/#list-of-input-commands
func (c *Connection) Call(arguments ...interface{}) (data interface{}, err error) {
finish := make(chan struct{})
callErr := c.CallAsync(func(v interface{}, e error) {
data, err = v, e
finish <- struct{}{}
}, arguments...)
if callErr != nil {
return nil, err
}
<-finish
return
}
// CallAsync does what Call does, but it does not block until there's a reply.
// If f is nil, then no reply is waited. f is called in the main loop, so it
// shouldn't do intensive work.
func (c *Connection) CallAsync(f func(v interface{}, err error), args ...interface{}) error {
c.lock.Lock()
if c.client == nil {
return fmt.Errorf("trying to send command on closed mpv client")
}
c.lastRequest++
id := c.lastRequest
if f != nil {
c.waitingRequests[id] = func(r *CommandResult) {
if r.Status == "success" {
f(r.Data, nil)
} else {
f(nil, fmt.Errorf("mpv error: %s", r.Status))
}
c.lock.Lock()
delete(c.waitingRequests, id)
c.lock.Unlock()
}
}
// Early copy the Conn so we can early release the mutex.
client := c.client
c.lock.Unlock()
message := commandRequest{Arguments: args, ID: id}
data, err := json.Marshal(message)
if err != nil {
return fmt.Errorf("can't encode command: %s", err)
}
data = append(data, '\n') // add termination
_, err = client.Write(data)
if err != nil {
return fmt.Errorf("can't write command: %s", err)
}
return err
}
// Set is a shortcut to Call("set_property", property, value)
func (c *Connection) Set(property string, value interface{}) error {
_, err := c.Call("set_property", property, value)
return err
}
// SetAsync sets the property asynchronously. The returned error will only cover
// sending. f is optional; if it is not nil, then it'll be called afterwards.
func (c *Connection) SetAsync(property string, value interface{}, f func(error)) error {
var asyncFn func(interface{}, error)
if f != nil {
asyncFn = func(_ interface{}, err error) { f(err) }
}
return c.CallAsync(asyncFn, "set_property", property, value)
}
// Get is a shortcut to Call("get_property", property)
func (c *Connection) Get(property string) (interface{}, error) {
value, err := c.Call("get_property", property)
return value, err
}
// Close closes the socket, disconnecting from mpv. It is safe to call Close()
// on an already closed connection.
func (c *Connection) Close() error {
c.lock.Lock()
defer c.lock.Unlock()
if c.client == nil {
return nil
}
err := c.client.Close()
c.eventListeners = make(map[uint]func(*Event))
c.lastListener = 0
c.waitingRequests = make(map[uint]func(*CommandResult))
c.lastRequest = 0
c.client = nil
return err
}
// IsClosed returns true if the connection is closed. There are several cases in
// which a connection is closed:
//
// 1. Close() has been called
//
// 2. The connection has been initialised but Open() hasn't been called yet
//
// 3. The connection terminated because of an error, mpv exiting or crashing
//
// It's ok to use IsClosed() to check if you need to reopen the connection
// before calling a command.
func (c *Connection) IsClosed() bool {
c.lock.Lock()
defer c.lock.Unlock()
return c.client == nil
}
type commandRequest struct {
Arguments []interface{} `json:"command"`
ID uint `json:"request_id"`
}
type CommandResult struct {
Status string `json:"error"`
Data interface{} `json:"data"`
ID uint `json:"request_id"`
}
func (c *Connection) checkResult(data []byte) {
result := CommandResult{}
if err := json.Unmarshal(data, &result); err != nil || result.Status == "" {
return // skip malformed data
}
c.lock.Lock()
request := c.waitingRequests[result.ID]
c.lock.Unlock()
if request != nil {
request(&result)
}
}
func (c *Connection) checkEvent(data []byte) {
event := Event{}
if err := json.Unmarshal(data, &event); err != nil || event.Name == "" {
return // skip malformed data
}
c.lock.Lock()
for _, listener := range c.eventListeners {
listener(&event)
}
c.lock.Unlock()
}
func (c *Connection) listen() {
scanner := bufio.NewScanner(c.client)
for scanner.Scan() {
data := scanner.Bytes()
c.checkEvent(data)
c.checkResult(data)
}
c.Close()
}