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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
mod error;
mod ffi;
mod format;
use error::{Error, Result};
use ffi::*;
pub use format::Format;
use core::marker::PhantomData;
use std::ffi::{c_void, CStr, CString};
use std::fmt;
use std::ops::Deref;
use std::time::Duration;
pub use ffi::mpv_handle;
pub struct Handle(*mut mpv_handle);
pub struct Client {
inner: Handle,
}
pub enum Event<'a> {
None,
Shutdown,
LogMessage, GetPropertyReply(Result<()>, u64, Property<'a>),
SetPropertyReply(Result<()>, u64),
CommandReply(Result<()>, u64), StartFile(StartFile<'a>),
EndFile, FileLoaded,
ClientMessage(ClientMessage<'a>),
VideoReconfig,
AudioReconfig,
Seek,
PlaybackRestart,
PropertyChange(u64, Property<'a>),
QueueOverflow,
Hook(u64, Hook<'a>),
}
pub struct Property<'a>(*const mpv_event_property, PhantomData<&'a ()>);
pub struct StartFile<'a>(*const mpv_event_start_file, PhantomData<&'a ()>);
pub struct ClientMessage<'a>(*const mpv_event_client_message, PhantomData<&'a ()>);
pub struct Hook<'a>(*const mpv_event_hook, PhantomData<&'a ()>);
macro_rules! mpv_result {
($f:expr) => {
match $f {
mpv_error::SUCCESS => Ok(()),
e => Err(Error::new(e)),
}
};
}
impl Handle {
pub fn from_ptr(ptr: *mut mpv_handle) -> Self {
assert!(!ptr.is_null());
Self(ptr)
}
pub fn create_client<S: AsRef<str>>(&self, name: S) -> Result<Client> {
let name = CString::new(name.as_ref())?;
Ok(Client {
inner: Handle::from_ptr(unsafe { mpv_create_client(self.0, name.as_ptr()) }),
})
}
pub fn create_weak_client<S: AsRef<str>>(&self, name: S) -> Result<Client> {
let name = CString::new(name.as_ref())?;
Ok(Client {
inner: Handle::from_ptr(unsafe { mpv_create_weak_client(self.0, name.as_ptr()) }),
})
}
pub fn wait_event(&self, timeout: f64) -> Event {
unsafe { Event::from_ptr(mpv_wait_event(self.0, timeout)) }
}
pub fn client_name(&self) -> &str {
unsafe { CStr::from_ptr(mpv_client_name(self.0)).to_str().unwrap_or("unknown") }
}
pub fn id(&self) -> i64 {
unsafe { mpv_client_id(self.0) }
}
pub fn command<I, S>(&self, args: I) -> Result<()>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let args: Vec<CString> = args.into_iter().map(|s| CString::new(s.as_ref()).unwrap()).collect();
let mut raw_args: Vec<*const i8> = args.iter().map(|s| s.as_ptr()).collect();
raw_args.push(std::ptr::null()); unsafe { mpv_result!(mpv_command(self.0, raw_args.as_ptr())) }
}
pub fn command_async<I, S>(&self, reply_userdata: u64, args: I) -> Result<()>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let args: Vec<CString> = args.into_iter().map(|s| CString::new(s.as_ref()).unwrap()).collect();
let mut raw_args: Vec<*const i8> = args.iter().map(|s| s.as_ptr()).collect();
raw_args.push(std::ptr::null()); unsafe { mpv_result!(mpv_command_async(self.0, reply_userdata, raw_args.as_ptr())) }
}
pub fn osd_message<S: AsRef<str>>(&self, text: S, duration: Duration) -> Result<()> {
self.command(&["show-text", text.as_ref(), &duration.as_millis().to_string()])
}
pub fn osd_message_async<S: AsRef<str>>(&self, reply_userdata: u64, text: S, duration: Duration) -> Result<()> {
self.command_async(
reply_userdata,
&["show-text", text.as_ref(), &duration.as_millis().to_string()],
)
}
pub fn set_property<T: Format, S: AsRef<str>>(&self, name: S, data: T) -> Result<()> {
let name = CString::new(name.as_ref())?;
data.to_mpv(|data| unsafe { mpv_result!(mpv_set_property(self.0, name.as_ptr(), T::MPV_FORMAT, data)) })
}
pub fn get_property<T: Format, S: AsRef<str>>(&self, name: S) -> Result<T> {
let name = CString::new(name.as_ref())?;
T::from_mpv(|data| unsafe { mpv_result!(mpv_get_property(self.0, name.as_ptr(), T::MPV_FORMAT, data)) })
}
pub fn observe_property<S: AsRef<str>>(&self, reply_userdata: u64, name: S, format: i32) -> Result<()> {
let name = CString::new(name.as_ref())?;
unsafe { mpv_result!(mpv_observe_property(self.0, reply_userdata, name.as_ptr(), format)) }
}
pub fn unobserve_property(&self, registered_reply_userdata: u64) -> Result<()> {
unsafe { mpv_result!(mpv_unobserve_property(self.0, registered_reply_userdata)) }
}
pub fn hook_add(&self, reply_userdata: u64, name: &str, priority: i32) -> Result<()> {
let name = CString::new(name)?;
unsafe { mpv_result!(mpv_hook_add(self.0, reply_userdata, name.as_ptr(), priority)) }
}
pub fn hook_continue(&self, id: u64) -> Result<()> {
unsafe { mpv_result!(mpv_hook_continue(self.0, id)) }
}
}
impl Client {
pub fn new() -> Self {
Self {
inner: Handle::from_ptr(unsafe { mpv_create() }),
}
}
pub fn initialize(&self) -> Result<()> {
unsafe { mpv_result!(mpv_initialize(self.inner.0)) }
}
}
impl Deref for Client {
type Target = Handle;
#[inline]
fn deref(&self) -> &Handle {
&self.inner
}
}
impl Drop for Client {
fn drop(&mut self) {
unsafe { mpv_destroy(self.inner.0) }
}
}
unsafe impl Send for Client {}
impl<'a> Event<'a> {
unsafe fn from_ptr(event: *const mpv_event) -> Event<'a> {
match (*event).event_id {
mpv_event_id::SHUTDOWN => Event::Shutdown,
mpv_event_id::LOG_MESSAGE => Event::LogMessage,
mpv_event_id::GET_PROPERTY_REPLY => Event::GetPropertyReply(
mpv_result!((*event).error),
(*event).reply_userdata,
Property::from_ptr((*event).data),
),
mpv_event_id::SET_PROPERTY_REPLY => {
Event::SetPropertyReply(mpv_result!((*event).error), (*event).reply_userdata)
}
mpv_event_id::COMMAND_REPLY => Event::CommandReply(mpv_result!((*event).error), (*event).reply_userdata),
mpv_event_id::START_FILE => Event::StartFile(StartFile::from_ptr((*event).data)),
mpv_event_id::END_FILE => Event::EndFile,
mpv_event_id::FILE_LOADED => Event::FileLoaded,
mpv_event_id::CLIENT_MESSAGE => Event::ClientMessage(ClientMessage::from_ptr((*event).data)),
mpv_event_id::VIDEO_RECONFIG => Event::VideoReconfig,
mpv_event_id::AUDIO_RECONFIG => Event::AudioReconfig,
mpv_event_id::SEEK => Event::Seek,
mpv_event_id::PLAYBACK_RESTART => Event::PlaybackRestart,
mpv_event_id::PROPERTY_CHANGE => {
Event::PropertyChange((*event).reply_userdata, Property::from_ptr((*event).data))
}
mpv_event_id::QUEUE_OVERFLOW => Event::QueueOverflow,
mpv_event_id::HOOK => Event::Hook((*event).reply_userdata, Hook::from_ptr((*event).data)),
_ => Event::None,
}
}
}
impl<'a> fmt::Display for Event<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let event = match *self {
Self::Shutdown => mpv_event_id::SHUTDOWN,
Self::LogMessage => mpv_event_id::LOG_MESSAGE,
Self::GetPropertyReply(..) => mpv_event_id::GET_PROPERTY_REPLY,
Self::SetPropertyReply(..) => mpv_event_id::SET_PROPERTY_REPLY,
Self::CommandReply(..) => mpv_event_id::COMMAND_REPLY,
Self::StartFile(..) => mpv_event_id::START_FILE,
Self::EndFile => mpv_event_id::END_FILE,
Self::FileLoaded => mpv_event_id::FILE_LOADED,
Self::ClientMessage(..) => mpv_event_id::CLIENT_MESSAGE,
Self::VideoReconfig => mpv_event_id::VIDEO_RECONFIG,
Self::AudioReconfig => mpv_event_id::AUDIO_RECONFIG,
Self::Seek => mpv_event_id::SEEK,
Self::PlaybackRestart => mpv_event_id::PLAYBACK_RESTART,
Self::PropertyChange(..) => mpv_event_id::PROPERTY_CHANGE,
Self::QueueOverflow => mpv_event_id::QUEUE_OVERFLOW,
Self::Hook(..) => mpv_event_id::HOOK,
_ => mpv_event_id::NONE,
};
f.write_str(unsafe {
CStr::from_ptr(mpv_event_name(event))
.to_str()
.unwrap_or("unknown event")
})
}
}
impl<'a> Property<'a> {
fn from_ptr(ptr: *const c_void) -> Self {
assert!(!ptr.is_null());
Self(ptr as *const mpv_event_property, PhantomData)
}
pub fn name(&self) -> &str {
unsafe { CStr::from_ptr((*self.0).name) }.to_str().unwrap_or("unknown")
}
pub fn data<T: Format>(&self) -> Option<T> {
unsafe {
if (*self.0).format == T::MPV_FORMAT {
T::from_ptr((*self.0).data).ok()
} else {
None
}
}
}
}
impl<'a> fmt::Display for Property<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name())
}
}
impl<'a> StartFile<'a> {
fn from_ptr(ptr: *const c_void) -> Self {
assert!(!ptr.is_null());
Self(ptr as *const mpv_event_start_file, PhantomData)
}
pub fn playlist_entry_id(&self) -> u64 {
unsafe { (*self.0).playlist_entry_id }
}
}
impl<'a> fmt::Display for StartFile<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.playlist_entry_id())
}
}
impl<'a> ClientMessage<'a> {
fn from_ptr(ptr: *const c_void) -> Self {
assert!(!ptr.is_null());
Self(ptr as *const mpv_event_client_message, PhantomData)
}
pub fn args(&self) -> Vec<String> {
unsafe {
let args = std::slice::from_raw_parts((*self.0).args, (*self.0).num_args as usize);
args.into_iter()
.map(|arg| CStr::from_ptr(*arg).to_str().unwrap().to_string())
.collect()
}
}
}
impl<'a> fmt::Display for ClientMessage<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("client-message")
}
}
impl<'a> Hook<'a> {
fn from_ptr(ptr: *const c_void) -> Self {
assert!(!ptr.is_null());
Self(ptr as *const mpv_event_hook, PhantomData)
}
pub fn name(&self) -> &str {
unsafe { CStr::from_ptr((*self.0).name).to_str().unwrap_or("unknown") }
}
pub fn id(&self) -> u64 {
unsafe { (*self.0).id }
}
}
impl<'a> fmt::Display for Hook<'a> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.name())
}
}