1
//! The core API for interacting with [`Mpv`].
2

            
3
use futures::StreamExt;
4
use serde::{Deserialize, Serialize};
5
use serde_json::Value;
6
use std::{collections::HashMap, fmt};
7
use tokio::{
8
    net::UnixStream,
9
    sync::{broadcast, mpsc, oneshot},
10
};
11

            
12
use crate::{
13
    ipc::{MpvIpc, MpvIpcCommand, MpvIpcEvent, MpvIpcResponse},
14
    message_parser::TypeHandler,
15
    Event, MpvError,
16
};
17

            
18
/// All possible commands that can be sent to mpv.
19
///
20
/// Not all commands are guaranteed to be implemented.
21
/// If something is missing, please open an issue.
22
///
23
/// You can also use the `run_command_raw` function to run commands
24
/// that are not implemented here.
25
///
26
/// See <https://mpv.io/manual/master/#list-of-input-commands> for
27
/// the upstream list of commands.
28
#[derive(Debug, Clone, Serialize, Deserialize)]
29
pub enum MpvCommand {
30
    LoadFile {
31
        file: String,
32
        option: PlaylistAddOptions,
33
    },
34
    LoadList {
35
        file: String,
36
        option: PlaylistAddOptions,
37
    },
38
    PlaylistClear,
39
    PlaylistMove {
40
        from: usize,
41
        to: usize,
42
    },
43
    Observe {
44
        id: usize,
45
        property: String,
46
    },
47
    PlaylistNext,
48
    PlaylistPrev,
49
    PlaylistRemove(usize),
50
    PlaylistShuffle,
51
    Quit,
52
    ScriptMessage(Vec<String>),
53
    ScriptMessageTo {
54
        target: String,
55
        args: Vec<String>,
56
    },
57
    Seek {
58
        seconds: f64,
59
        option: SeekOptions,
60
    },
61
    Stop,
62
    Unobserve(usize),
63
}
64

            
65
/// Helper trait to keep track of the string literals that mpv expects.
66
pub(crate) trait IntoRawCommandPart {
67
    fn into_raw_command_part(self) -> String;
68
}
69

            
70
/// Generic data type representing all possible data types that mpv can return.
71
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
72
pub enum MpvDataType {
73
    Array(Vec<MpvDataType>),
74
    Bool(bool),
75
    Double(f64),
76
    HashMap(HashMap<String, MpvDataType>),
77
    Null,
78
    MinusOne,
79
    Playlist(Playlist),
80
    String(String),
81
    Usize(usize),
82
}
83

            
84
/// A mpv playlist.
85
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86
pub struct Playlist(pub Vec<PlaylistEntry>);
87

            
88
/// A single entry in the mpv playlist.
89
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
90
pub struct PlaylistEntry {
91
    pub id: usize,
92
    pub filename: String,
93
    pub title: String,
94
    pub current: bool,
95
}
96

            
97
/// Options for [`MpvCommand::LoadFile`] and [`MpvCommand::LoadList`].
98
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
99
pub enum PlaylistAddOptions {
100
    Replace,
101
    Append,
102
}
103

            
104
impl IntoRawCommandPart for PlaylistAddOptions {
105
    fn into_raw_command_part(self) -> String {
106
        match self {
107
            PlaylistAddOptions::Replace => "replace".to_string(),
108
            PlaylistAddOptions::Append => "append".to_string(),
109
        }
110
    }
111
}
112

            
113
/// Options for [`MpvCommand::Seek`].
114
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
115
pub enum SeekOptions {
116
    Relative,
117
    Absolute,
118
    RelativePercent,
119
    AbsolutePercent,
120
}
121

            
122
impl IntoRawCommandPart for SeekOptions {
123
    fn into_raw_command_part(self) -> String {
124
        match self {
125
            SeekOptions::Relative => "relative".to_string(),
126
            SeekOptions::Absolute => "absolute".to_string(),
127
            SeekOptions::RelativePercent => "relative-percent".to_string(),
128
            SeekOptions::AbsolutePercent => "absolute-percent".to_string(),
129
        }
130
    }
131
}
132

            
133
/// A trait for specifying how to extract and parse a value returned through [`Mpv::get_property`].
134
pub trait GetPropertyTypeHandler: Sized {
135
    // TODO: fix this
136
    #[allow(async_fn_in_trait)]
137
    async fn get_property_generic(instance: &Mpv, property: &str) -> Result<Self, MpvError>;
138
}
139

            
140
impl<T> GetPropertyTypeHandler for T
141
where
142
    T: TypeHandler,
143
{
144
968
    async fn get_property_generic(instance: &Mpv, property: &str) -> Result<T, MpvError> {
145
968
        instance
146
968
            .get_property_value(property)
147
967
            .await
148
967
            .and_then(T::get_value)
149
967
    }
150
}
151

            
152
/// A trait for specifying how to serialize and set a value through [`Mpv::set_property`].
153
pub trait SetPropertyTypeHandler<T> {
154
    // TODO: fix this
155
    #[allow(async_fn_in_trait)]
156
    async fn set_property_generic(instance: &Mpv, property: &str, value: T)
157
        -> Result<(), MpvError>;
158
}
159

            
160
impl<T> SetPropertyTypeHandler<T> for T
161
where
162
    T: Serialize,
163
{
164
1276
    async fn set_property_generic(
165
1276
        instance: &Mpv,
166
1276
        property: &str,
167
1276
        value: T,
168
1276
    ) -> Result<(), MpvError> {
169
1276
        let (res_tx, res_rx) = oneshot::channel();
170
1276
        let value = serde_json::to_value(value).map_err(MpvError::JsonParseError)?;
171

            
172
1276
        instance
173
1276
            .command_sender
174
1276
            .send((
175
1276
                MpvIpcCommand::SetProperty(property.to_owned(), value),
176
1276
                res_tx,
177
1276
            ))
178
            .await
179
1276
            .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
180

            
181
1276
        match res_rx.await {
182
1275
            Ok(MpvIpcResponse(response)) => response.map(|_| ()),
183
            Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
184
        }
185
1275
    }
186
}
187

            
188
/// The main struct for interacting with mpv.
189
///
190
/// This struct provides the core API for interacting with mpv.
191
/// These functions are the building blocks for the higher-level API provided by the `MpvExt` trait.
192
/// They can also be used directly to interact with mpv in a more flexible way, mostly returning JSON values.
193
///
194
/// The `Mpv` struct can be cloned freely, and shared anywhere.
195
/// It only contains a message passing channel to the tokio task that handles the IPC communication with mpv.
196
#[derive(Clone)]
197
pub struct Mpv {
198
    command_sender: mpsc::Sender<(MpvIpcCommand, oneshot::Sender<MpvIpcResponse>)>,
199
    broadcast_channel: broadcast::Sender<MpvIpcEvent>,
200
}
201

            
202
// TODO: Can we somehow provide a more useful Debug implementation?
203
impl fmt::Debug for Mpv {
204
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
205
        fmt.debug_struct("Mpv").finish()
206
    }
207
}
208

            
209
impl Mpv {
210
    /// Connect to a unix socket, hosted by mpv, at the given path.
211
    /// This is the inteded way of creating a new [`Mpv`] instance.
212
6
    pub async fn connect(socket_path: &str) -> Result<Mpv, MpvError> {
213
6
        log::debug!("Connecting to mpv socket at {}", socket_path);
214

            
215
6
        let socket = match UnixStream::connect(socket_path).await {
216
6
            Ok(stream) => Ok(stream),
217
            Err(err) => Err(MpvError::MpvSocketConnectionError(err.to_string())),
218
        }?;
219

            
220
6
        Self::connect_socket(socket).await
221
6
    }
222

            
223
    /// Connect to an existing [`UnixStream`].
224
    /// This is an alternative to [`Mpv::connect`], if you already have a [`UnixStream`] available.
225
    ///
226
    /// Internally, this is used for testing purposes.
227
42
    pub async fn connect_socket(socket: UnixStream) -> Result<Mpv, MpvError> {
228
21
        let (com_tx, com_rx) = mpsc::channel(100);
229
21
        let (ev_tx, _) = broadcast::channel(100);
230
21
        let ipc = MpvIpc::new(socket, com_rx, ev_tx.clone());
231
21

            
232
21
        log::debug!("Starting IPC handler");
233
21
        tokio::spawn(ipc.run());
234
21

            
235
21
        Ok(Mpv {
236
21
            command_sender: com_tx,
237
21
            broadcast_channel: ev_tx,
238
21
        })
239
21
    }
240

            
241
    /// Disconnect from the mpv socket.
242
    ///
243
    /// Note that this will also kill communication for all other clones of this instance.
244
    /// It will not kill the mpv process itself - for that you should use [`MpvCommand::Quit`]
245
    /// or run [`MpvExt::kill`](crate::MpvExt::kill).
246
    pub async fn disconnect(&self) -> Result<(), MpvError> {
247
        let (res_tx, res_rx) = oneshot::channel();
248
        self.command_sender
249
            .send((MpvIpcCommand::Exit, res_tx))
250
            .await
251
            .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
252

            
253
        match res_rx.await {
254
            Ok(MpvIpcResponse(response)) => response.map(|_| ()),
255
            Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
256
        }
257
    }
258

            
259
    /// Create a new stream, providing [`Event`]s from mpv.
260
    ///
261
    /// This is intended to be used with [`MpvCommand::Observe`] and [`MpvCommand::Unobserve`]
262
    /// (or [`MpvExt::observe_property`] and [`MpvExt::unobserve_property`] respectively).
263
10
    pub async fn get_event_stream(&self) -> impl futures::Stream<Item = Result<Event, MpvError>> {
264
5
        tokio_stream::wrappers::BroadcastStream::new(self.broadcast_channel.subscribe()).map(
265
14
            |event| match event {
266
14
                Ok(event) => crate::event_parser::parse_event(event),
267
                Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
268
14
            },
269
5
        )
270
5
    }
271

            
272
    /// Run a custom command.
273
    /// This should only be used if the desired command is not implemented
274
    /// with [`MpvCommand`].
275
12
    pub async fn run_command_raw(
276
12
        &self,
277
12
        command: &str,
278
12
        args: &[&str],
279
12
    ) -> Result<Option<Value>, MpvError> {
280
6
        let command = Vec::from(
281
6
            [command]
282
6
                .iter()
283
6
                .chain(args.iter())
284
6
                .map(|s| s.to_string())
285
6
                .collect::<Vec<String>>()
286
6
                .as_slice(),
287
6
        );
288
6
        let (res_tx, res_rx) = oneshot::channel();
289
6
        self.command_sender
290
6
            .send((MpvIpcCommand::Command(command), res_tx))
291
            .await
292
6
            .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
293

            
294
6
        match res_rx.await {
295
6
            Ok(MpvIpcResponse(response)) => response,
296
            Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
297
        }
298
6
    }
299

            
300
    /// Helper function to ignore the return value of a command, and only check for errors.
301
12
    async fn run_command_raw_ignore_value(
302
12
        &self,
303
12
        command: &str,
304
12
        args: &[&str],
305
12
    ) -> Result<(), MpvError> {
306
6
        self.run_command_raw(command, args).await.map(|_| ())
307
6
    }
308

            
309
    /// # Description
310
    ///
311
    /// Runs mpv commands. The arguments are passed as a String-Vector reference:
312
    ///
313
    /// ## Input arguments
314
    ///
315
    /// - **command**   defines the mpv command that should be executed
316
    /// - **args**      a slice of `&str`'s which define the arguments
317
    ///
318
    /// # Example
319
    /// ```
320
    /// use mpvipc::{Mpv, MpvError};
321
    ///
322
    /// #[tokio::main]
323
    /// async fn main() -> Result<(), MpvError> {
324
    ///     let mpv = Mpv::connect("/tmp/mpvsocket").await?;
325
    ///
326
    ///     //Run command 'playlist-shuffle' which takes no arguments
327
    ///     mpv.run_command(MpvCommand::PlaylistShuffle).await?;
328
    ///
329
    ///     //Run command 'seek' which in this case takes two arguments
330
    ///     mpv.run_command(MpvCommand::Seek {
331
    ///         seconds: 0f64,
332
    ///         option: SeekOptions::Absolute,
333
    ///     }).await?;
334
    ///     Ok(())
335
    /// }
336
    /// ```
337
22
    pub async fn run_command(&self, command: MpvCommand) -> Result<(), MpvError> {
338
11
        log::trace!("Running command: {:?}", command);
339
11
        let result = match command {
340
            MpvCommand::LoadFile { file, option } => {
341
                self.run_command_raw_ignore_value(
342
                    "loadfile",
343
                    &[file.as_ref(), option.into_raw_command_part().as_str()],
344
                )
345
                .await
346
            }
347
            MpvCommand::LoadList { file, option } => {
348
                self.run_command_raw_ignore_value(
349
                    "loadlist",
350
                    &[file.as_ref(), option.into_raw_command_part().as_str()],
351
                )
352
                .await
353
            }
354
5
            MpvCommand::Observe { id, property } => {
355
5
                let (res_tx, res_rx) = oneshot::channel();
356
5
                self.command_sender
357
5
                    .send((MpvIpcCommand::ObserveProperty(id, property), res_tx))
358
                    .await
359
5
                    .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
360

            
361
5
                match res_rx.await {
362
5
                    Ok(MpvIpcResponse(response)) => response.map(|_| ()),
363
                    Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
364
                }
365
            }
366
            MpvCommand::PlaylistClear => {
367
                self.run_command_raw_ignore_value("playlist-clear", &[])
368
                    .await
369
            }
370
            MpvCommand::PlaylistMove { from, to } => {
371
                self.run_command_raw_ignore_value(
372
                    "playlist-move",
373
                    &[&from.to_string(), &to.to_string()],
374
                )
375
                .await
376
            }
377
            MpvCommand::PlaylistNext => {
378
                self.run_command_raw_ignore_value("playlist-next", &[])
379
                    .await
380
            }
381
            MpvCommand::PlaylistPrev => {
382
                self.run_command_raw_ignore_value("playlist-prev", &[])
383
                    .await
384
            }
385
            MpvCommand::PlaylistRemove(id) => {
386
                self.run_command_raw_ignore_value("playlist-remove", &[&id.to_string()])
387
                    .await
388
            }
389
            MpvCommand::PlaylistShuffle => {
390
                self.run_command_raw_ignore_value("playlist-shuffle", &[])
391
                    .await
392
            }
393
6
            MpvCommand::Quit => self.run_command_raw_ignore_value("quit", &[]).await,
394
            MpvCommand::ScriptMessage(args) => {
395
                let str_args: Vec<_> = args.iter().map(String::as_str).collect();
396
                self.run_command_raw_ignore_value("script-message", &str_args)
397
                    .await
398
            }
399
            MpvCommand::ScriptMessageTo { target, args } => {
400
                let mut cmd_args: Vec<_> = vec![target.as_str()];
401
                let mut str_args: Vec<_> = args.iter().map(String::as_str).collect();
402
                cmd_args.append(&mut str_args);
403
                self.run_command_raw_ignore_value("script-message-to", &cmd_args)
404
                    .await
405
            }
406
            MpvCommand::Seek { seconds, option } => {
407
                self.run_command_raw_ignore_value(
408
                    "seek",
409
                    &[
410
                        &seconds.to_string(),
411
                        option.into_raw_command_part().as_str(),
412
                    ],
413
                )
414
                .await
415
            }
416
            MpvCommand::Stop => self.run_command_raw_ignore_value("stop", &[]).await,
417
            MpvCommand::Unobserve(id) => {
418
                let (res_tx, res_rx) = oneshot::channel();
419
                self.command_sender
420
                    .send((MpvIpcCommand::UnobserveProperty(id), res_tx))
421
                    .await
422
                    .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
423

            
424
                match res_rx.await {
425
                    Ok(MpvIpcResponse(response)) => response.map(|_| ()),
426
                    Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
427
                }
428
            }
429
        };
430
11
        log::trace!("Command result: {:?}", result);
431
11
        result
432
11
    }
433

            
434
    /// # Description
435
    ///
436
    /// Retrieves the property value from mpv.
437
    ///
438
    /// ## Supported types
439
    /// - `String`
440
    /// - `bool`
441
    /// - `HashMap<String, String>` (e.g. for the 'metadata' property)
442
    /// - `Vec<PlaylistEntry>` (for the 'playlist' property)
443
    /// - `usize`
444
    /// - `f64`
445
    ///
446
    /// ## Input arguments
447
    ///
448
    /// - **property** defines the mpv property that should be retrieved
449
    ///
450
    /// # Example
451
    /// ```
452
    /// use mpvipc::{Mpv, MpvError};
453
    ///
454
    /// #[tokio::main]
455
    /// async fn main() -> Result<(), MpvError> {
456
    ///     let mpv = Mpv::connect("/tmp/mpvsocket").await?;
457
    ///     let paused: bool = mpv.get_property("pause").await?;
458
    ///     let title: String = mpv.get_property("media-title").await?;
459
    ///     Ok(())
460
    /// }
461
    /// ```
462
968
    pub async fn get_property<T: GetPropertyTypeHandler>(
463
968
        &self,
464
968
        property: &str,
465
968
    ) -> Result<T, MpvError> {
466
968
        T::get_property_generic(self, property).await
467
967
    }
468

            
469
    /// # Description
470
    ///
471
    /// Retrieves the property value from mpv.
472
    /// The result is always of type String, regardless of the type of the value of the mpv property
473
    ///
474
    /// ## Input arguments
475
    ///
476
    /// - **property** defines the mpv property that should be retrieved
477
    ///
478
    /// # Example
479
    ///
480
    /// ```
481
    /// use mpvipc::{Mpv, MpvError};
482
    ///
483
    /// #[tokio::main]
484
    /// async fn main() -> Result<(), MpvError> {
485
    ///     let mpv = Mpv::connect("/tmp/mpvsocket").await?;
486
    ///     let title = mpv.get_property_string("media-title").await?;
487
    ///     Ok(())
488
    /// }
489
    /// ```
490
1936
    pub async fn get_property_value(&self, property: &str) -> Result<Value, MpvError> {
491
968
        let (res_tx, res_rx) = oneshot::channel();
492
968
        self.command_sender
493
968
            .send((MpvIpcCommand::GetProperty(property.to_owned()), res_tx))
494
            .await
495
968
            .map_err(|err| MpvError::InternalConnectionError(err.to_string()))?;
496

            
497
968
        match res_rx.await {
498
967
            Ok(MpvIpcResponse(response)) => {
499
967
                response.and_then(|value| value.ok_or(MpvError::MissingMpvData))
500
            }
501
            Err(err) => Err(MpvError::InternalConnectionError(err.to_string())),
502
        }
503
967
    }
504

            
505
    /// # Description
506
    ///
507
    /// Sets the mpv property _`<property>`_ to _`<value>`_.
508
    ///
509
    /// ## Supported types
510
    /// - `String`
511
    /// - `bool`
512
    /// - `f64`
513
    /// - `usize`
514
    ///
515
    /// ## Input arguments
516
    ///
517
    /// - **property** defines the mpv property that should be retrieved
518
    /// - **value** defines the value of the given mpv property _`<property>`_
519
    ///
520
    /// # Example
521
    /// ```
522
    /// use mpvipc::{Mpv, MpvError};
523
    /// async fn main() -> Result<(), MpvError> {
524
    ///     let mpv = Mpv::connect("/tmp/mpvsocket").await?;
525
    ///     mpv.set_property("pause", true).await?;
526
    ///     Ok(())
527
    /// }
528
    /// ```
529
1276
    pub async fn set_property<T: SetPropertyTypeHandler<T>>(
530
1276
        &self,
531
1276
        property: &str,
532
1276
        value: T,
533
1276
    ) -> Result<(), MpvError> {
534
1276
        T::set_property_generic(self, property, value).await
535
1275
    }
536
}