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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
/*
 * MIT License
 *
 * termusic - Copyright (c) 2021 Larry Hao
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

// #![forbid(unsafe_code)]
#![recursion_limit = "2048"]
#![warn(clippy::all, clippy::correctness)]
#![warn(rust_2018_idioms)]
#![warn(clippy::pedantic)]
#[allow(clippy::pedantic)]
pub mod player {
    tonic::include_proto!("player");

    // implement transform function for easy use
    impl From<Duration> for std::time::Duration {
        fn from(value: Duration) -> Self {
            std::time::Duration::new(value.secs, value.nanos)
        }
    }

    impl From<std::time::Duration> for Duration {
        fn from(value: std::time::Duration) -> Self {
            Self {
                secs: value.as_secs(),
                nanos: value.subsec_nanos(),
            }
        }
    }
}

#[cfg(feature = "gst")]
mod gstreamer_backend;
#[cfg(feature = "mpv")]
mod mpv_backend;
#[cfg(feature = "rusty")]
mod rusty_backend;

mod discord;
mod mpris;
pub mod playlist;

use anyhow::{Context, Result};
use async_trait::async_trait;
use parking_lot::RwLock;
pub use playlist::{Playlist, Status};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Duration;
use termusiclib::config::{LastPosition, SeekStep, Settings};
use termusiclib::podcast::db::Database as DBPod;
use termusiclib::sqlite::DataBase;
use termusiclib::track::{MediaType, Track};
use termusiclib::utils::get_app_config_path;
use tokio::runtime::Handle;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};

#[macro_use]
extern crate log;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BackendSelect {
    #[cfg(feature = "mpv")]
    Mpv,
    #[cfg(feature = "rusty")]
    Rusty,
    #[cfg(feature = "gst")]
    GStreamer,
    /// Create a new Backend with default backend ordering
    ///
    /// Order:
    /// - [`RustyBackend`](rusty_backend::RustyBackend) (feature `rusty`)
    /// - [`GstreamerBackend`](gstreamer_backend::GStreamerBackend) (feature `gst`)
    /// - [`MpvBackend`](mpv_backend::MpvBackend) (feature `mpv`)
    /// - Compile Error
    #[default]
    Default,
}

/// Enum to choose backend at runtime
pub enum Backend {
    #[cfg(feature = "mpv")]
    Mpv(mpv_backend::MpvBackend),
    #[cfg(feature = "rusty")]
    Rusty(rusty_backend::RustyBackend),
    #[cfg(feature = "gst")]
    GStreamer(gstreamer_backend::GStreamerBackend),
}

pub type PlayerCmdReciever = UnboundedReceiver<PlayerCmd>;
pub type PlayerCmdSender = UnboundedSender<PlayerCmd>;

impl Backend {
    /// Create a new Backend based on `backend`([`BackendSelect`])
    fn new_select(backend: BackendSelect, config: &Settings, cmd_tx: PlayerCmdSender) -> Self {
        match backend {
            #[cfg(feature = "mpv")]
            BackendSelect::Mpv => Self::new_mpv(config, cmd_tx),
            #[cfg(feature = "rusty")]
            BackendSelect::Rusty => Self::new_rusty(config, cmd_tx),
            #[cfg(feature = "gst")]
            BackendSelect::GStreamer => Self::new_gstreamer(config, cmd_tx),
            BackendSelect::Default => Self::new_default(config, cmd_tx),
        }
    }

    /// Create a new Backend with default backend ordering
    ///
    /// For the order see [`BackendSelect::Default`]
    #[allow(unreachable_code)]
    fn new_default(config: &Settings, cmd_tx: PlayerCmdSender) -> Self {
        #[cfg(feature = "rusty")]
        return Self::new_rusty(config, cmd_tx);
        #[cfg(feature = "gst")]
        return Self::new_gstreamer(config, cmd_tx);
        #[cfg(feature = "mpv")]
        return Self::new_mpv(config, cmd_tx);

        #[cfg(not(any(feature = "rusty", feature = "gst", feature = "mpv")))]
        compile_error!("No useable backend feature!");
    }

    /// Explicitly choose Backend [`RustyBackend`](rusty_backend::RustyBackend)
    #[cfg(feature = "rusty")]
    fn new_rusty(config: &Settings, cmd_tx: PlayerCmdSender) -> Self {
        info!("Using Backend \"rusty\"");
        Self::Rusty(rusty_backend::RustyBackend::new(config, cmd_tx))
    }

    /// Explicitly choose Backend [`GstreamerBackend`](gstreamer_backend::GStreamerBackend)
    #[cfg(feature = "gst")]
    fn new_gstreamer(config: &Settings, cmd_tx: PlayerCmdSender) -> Self {
        info!("Using Backend \"GStreamer\"");
        Self::GStreamer(gstreamer_backend::GStreamerBackend::new(config, cmd_tx))
    }

    /// Explicitly choose Backend [`MpvBackend`](mpv_backend::MpvBackend)
    #[cfg(feature = "mpv")]
    fn new_mpv(config: &Settings, cmd_tx: PlayerCmdSender) -> Self {
        info!("Using Backend \"mpv\"");
        Self::Mpv(mpv_backend::MpvBackend::new(config, cmd_tx))
    }

    #[must_use]
    pub fn as_player(&self) -> &dyn PlayerTrait {
        match self {
            #[cfg(feature = "mpv")]
            Backend::Mpv(v) => v,
            #[cfg(feature = "rusty")]
            Backend::Rusty(v) => v,
            #[cfg(feature = "gst")]
            Backend::GStreamer(v) => v,
        }
    }

    #[must_use]
    pub fn as_player_mut(&mut self) -> &mut (dyn PlayerTrait + Send) {
        match self {
            #[cfg(feature = "mpv")]
            Backend::Mpv(v) => v,
            #[cfg(feature = "rusty")]
            Backend::Rusty(v) => v,
            #[cfg(feature = "gst")]
            Backend::GStreamer(v) => v,
        }
    }
}

#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum PlayerCmd {
    AboutToFinish,
    CycleLoop,
    Eos,
    GetProgress,
    PlaySelected,
    SkipPrevious,
    Pause,
    Play,
    ProcessID,
    Quit,
    ReloadConfig,
    ReloadPlaylist,
    SeekBackward,
    SeekForward,
    SkipNext,
    SpeedDown,
    SpeedUp,
    Tick,
    ToggleGapless,
    TogglePause,
    VolumeDown,
    VolumeUp,
}

pub type SharedSettings = Arc<RwLock<Settings>>;

#[allow(clippy::module_name_repetitions)]
pub struct GeneralPlayer {
    pub backend: Backend,
    pub playlist: Playlist,
    pub config: SharedSettings,
    pub current_track_updated: bool,
    pub mpris: mpris::Mpris,
    pub discord: discord::Rpc,
    pub db: DataBase,
    pub db_podcast: DBPod,
    pub cmd_tx: PlayerCmdSender,
}

impl GeneralPlayer {
    /// Create a new [`GeneralPlayer`], with the selected `backend`
    ///
    /// # Errors
    ///
    /// - if connecting to the database fails
    /// - if config path creation fails
    pub fn new_backend(
        backend: BackendSelect,
        config: Settings,
        cmd_tx: PlayerCmdSender,
    ) -> Result<Self> {
        let backend = Backend::new_select(backend, &config, cmd_tx.clone());

        let db_path = get_app_config_path().with_context(|| "failed to get podcast db path.")?;

        let db_podcast =
            DBPod::connect(&db_path).with_context(|| "error connecting to podcast db.")?;
        let db = DataBase::new(&config);

        let config = Arc::new(RwLock::new(config));
        let playlist = Playlist::new(config.clone()).unwrap_or_default();

        Ok(Self {
            backend,
            playlist,
            config,
            mpris: mpris::Mpris::new(cmd_tx.clone()),
            discord: discord::Rpc::default(),
            db,
            db_podcast,
            cmd_tx,
            current_track_updated: false,
        })
    }

    /// Create a new [`GeneralPlayer`], with the [`BackendSelect::Default`] backend
    ///
    /// # Errors
    ///
    /// - if connecting to the database fails
    /// - if config path creation fails
    pub fn new(config: Settings, cmd_tx: PlayerCmdSender) -> Result<Self> {
        Self::new_backend(BackendSelect::Default, config, cmd_tx)
    }

    fn get_player(&self) -> &dyn PlayerTrait {
        self.backend.as_player()
    }

    fn get_player_mut(&mut self) -> &mut (dyn PlayerTrait + Send) {
        self.backend.as_player_mut()
    }

    pub fn toggle_gapless(&mut self) -> bool {
        let new_gapless = !self.backend.as_player().gapless();
        self.backend.as_player_mut().set_gapless(new_gapless);
        self.config.write().player_gapless = new_gapless;
        new_gapless
    }

    /// Requires that the function is called on a thread with a entered tokio runtime
    pub fn start_play(&mut self) {
        if self.playlist.is_stopped() | self.playlist.is_paused() {
            self.playlist.set_status(Status::Running);
        }

        self.playlist.proceed();

        if let Some(track) = self.playlist.current_track() {
            let track = track.clone();

            info!("Starting Track {:#?}", track);

            if self.playlist.has_next_track() {
                self.playlist.set_next_track(None);
                self.current_track_updated = true;
                info!("gapless next track played");
                #[cfg(feature = "rusty")]
                #[allow(irrefutable_let_patterns)]
                if let Backend::Rusty(ref mut backend) = self.backend {
                    backend.message_on_end();
                }
                self.add_and_play_mpris_discord();
                return;
            }

            self.current_track_updated = true;
            let wait = async {
                self.add_and_play(&track).await;
            };
            Handle::current().block_on(wait);

            self.add_and_play_mpris_discord();
            self.player_restore_last_position();
            #[cfg(feature = "rusty")]
            #[allow(irrefutable_let_patterns)]
            if let Backend::Rusty(ref mut backend) = self.backend {
                backend.message_on_end();
            }
        }
    }

    fn add_and_play_mpris_discord(&mut self) {
        if let Some(track) = self.playlist.current_track() {
            let config = self.config.read();
            if config.player_use_mpris {
                self.mpris.add_and_play(track);
            }

            if config.player_use_discord {
                self.discord.update(track);
            }
        }
    }
    pub fn enqueue_next_from_playlist(&mut self) {
        if self.playlist.next_track().is_some() {
            return;
        }

        let track = match self.playlist.fetch_next_track() {
            Some(t) => t.clone(),
            None => return,
        };

        self.playlist.set_next_track(Some(&track));
        self.get_player_mut().enqueue_next(&track);

        info!("Next track enqueued: {:#?}", track);
    }

    pub fn next(&mut self) {
        if self.playlist.current_track().is_some() {
            info!("skip route 1 which is in most cases.");
            self.playlist.set_next_track(None);
            self.get_player_mut().skip_one();
        } else {
            info!("skip route 2 cause no current track.");
            self.stop();
            // if let Err(e) = crate::audio_cmd::<()>(PlayerCmd::StartPlay, false) {
            //     debug!("Error in skip route 2: {e}");
            // }
        }
    }
    pub fn previous(&mut self) {
        self.playlist.previous();
        self.playlist.proceed_false();
        self.next();
    }
    pub fn toggle_pause(&mut self) {
        match self.playlist.status() {
            Status::Running => {
                self.get_player_mut().pause();
                let config = self.config.read();
                if config.player_use_mpris {
                    self.mpris.pause();
                }
                if config.player_use_discord {
                    self.discord.pause();
                }
                self.playlist.set_status(Status::Paused);
            }
            Status::Stopped => {}
            Status::Paused => {
                self.get_player_mut().resume();
                let config = self.config.read();
                if config.player_use_mpris {
                    self.mpris.resume();
                }
                if config.player_use_discord {
                    let time_pos = self.get_player().position();
                    self.discord.resume(time_pos);
                }
                self.playlist.set_status(Status::Running);
            }
        }
    }

    pub fn pause(&mut self) {
        match self.playlist.status() {
            Status::Running => {
                self.get_player_mut().pause();
                let config = self.config.read();
                if config.player_use_mpris {
                    self.mpris.pause();
                }
                if config.player_use_discord {
                    self.discord.pause();
                }
                self.playlist.set_status(Status::Paused);
            }
            Status::Stopped | Status::Paused => {}
        }
    }

    pub fn play(&mut self) {
        match self.playlist.status() {
            Status::Running | Status::Stopped => {}
            Status::Paused => {
                self.get_player_mut().resume();
                let config = self.config.read();
                if config.player_use_mpris {
                    self.mpris.resume();
                }
                if config.player_use_discord {
                    let time_pos = self.get_player().position();
                    self.discord.resume(time_pos);
                }
                self.playlist.set_status(Status::Running);
            }
        }
    }
    /// # Panics
    ///
    /// if the underlying "seek" returns a error (which current never happens)
    pub fn seek_relative(&mut self, forward: bool) {
        let mut offset = match self.config.read().player_seek_step {
            SeekStep::Short => -5_i64,
            SeekStep::Long => -30,
            SeekStep::Auto => {
                if let Some(track) = self.playlist.current_track() {
                    if track.duration().as_secs() >= 600 {
                        -30
                    } else {
                        -5
                    }
                } else {
                    -5
                }
            }
        };
        if forward {
            offset = -offset;
        }
        self.get_player_mut()
            .seek(offset)
            .expect("Error in player seek.");
    }

    #[allow(clippy::cast_sign_loss)]
    pub fn player_save_last_position(&mut self) {
        match self.config.read().player_remember_last_played_position {
            LastPosition::Yes => {
                if let Some(track) = self.playlist.current_track() {
                    // let time_pos = self.player.position.lock().unwrap();
                    let time_pos = self.get_player().position();
                    match track.media_type {
                        MediaType::Music => self
                            .db
                            .set_last_position(track, time_pos.unwrap_or_default()),
                        MediaType::Podcast => {
                            self.db_podcast
                                .set_last_position(track, time_pos.unwrap_or_default());
                        }
                        MediaType::LiveRadio => {}
                    }
                }
            }
            LastPosition::No => {}
            LastPosition::Auto => {
                if let Some(track) = self.playlist.current_track() {
                    // 10 minutes
                    if track.duration().as_secs() >= 600 {
                        // let time_pos = self.player.position.lock().unwrap();
                        let time_pos = self.get_player().position();
                        match track.media_type {
                            MediaType::Music => self
                                .db
                                .set_last_position(track, time_pos.unwrap_or_default()),
                            MediaType::Podcast => {
                                self.db_podcast
                                    .set_last_position(track, time_pos.unwrap_or_default());
                            }
                            MediaType::LiveRadio => {}
                        }
                    }
                }
            }
        }
    }

    pub fn player_restore_last_position(&mut self) {
        let mut restored = false;
        let last_pos = self.config.read().player_remember_last_played_position;
        match last_pos {
            LastPosition::Yes => {
                if let Some(track) = self.playlist.current_track() {
                    match track.media_type {
                        MediaType::Music => {
                            if let Ok(last_pos) = self.db.get_last_position(track) {
                                self.get_player_mut().seek_to(last_pos);
                                restored = true;
                            }
                        }

                        MediaType::Podcast => {
                            if let Ok(last_pos) = self.db_podcast.get_last_position(track) {
                                self.get_player_mut().seek_to(last_pos);
                                restored = true;
                            }
                        }
                        MediaType::LiveRadio => {}
                    }
                }
            }
            LastPosition::No => {}
            LastPosition::Auto => {
                if let Some(track) = self.playlist.current_track() {
                    // 10 minutes
                    if track.duration().as_secs() >= 600 {
                        match track.media_type {
                            MediaType::Music => {
                                if let Ok(last_pos) = self.db.get_last_position(track) {
                                    self.get_player_mut().seek_to(last_pos);
                                    restored = true;
                                }
                            }

                            MediaType::Podcast => {
                                if let Ok(last_pos) = self.db_podcast.get_last_position(track) {
                                    self.get_player_mut().seek_to(last_pos);
                                    restored = true;
                                }
                            }
                            MediaType::LiveRadio => {}
                        }
                    }
                }
            }
        }

        if restored {
            if let Some(track) = self.playlist.current_track() {
                self.db.set_last_position(track, Duration::from_secs(0));
            }
        }
    }
}

#[async_trait]
impl PlayerTrait for GeneralPlayer {
    async fn add_and_play(&mut self, track: &Track) {
        self.get_player_mut().add_and_play(track).await;
    }
    fn volume(&self) -> Volume {
        self.get_player().volume()
    }
    fn volume_up(&mut self) -> Volume {
        self.get_player_mut().volume_up()
    }
    fn volume_down(&mut self) -> Volume {
        self.get_player_mut().volume_down()
    }
    fn set_volume(&mut self, volume: Volume) -> Volume {
        self.get_player_mut().set_volume(volume)
    }
    fn pause(&mut self) {
        self.playlist.set_status(Status::Paused);
        self.get_player_mut().pause();
    }
    fn resume(&mut self) {
        self.playlist.set_status(Status::Running);
        self.get_player_mut().resume();
    }
    fn is_paused(&self) -> bool {
        self.get_player().is_paused()
    }
    fn seek(&mut self, secs: i64) -> Result<()> {
        self.get_player_mut().seek(secs)
    }
    fn seek_to(&mut self, position: Duration) {
        self.get_player_mut().seek_to(position);
    }

    fn set_speed(&mut self, speed: Speed) -> Speed {
        self.get_player_mut().set_speed(speed)
    }

    fn speed_up(&mut self) -> Speed {
        self.get_player_mut().speed_up()
    }

    fn speed_down(&mut self) -> Speed {
        self.get_player_mut().speed_down()
    }

    fn speed(&self) -> Speed {
        self.get_player().speed()
    }

    fn stop(&mut self) {
        self.playlist.set_status(Status::Stopped);
        self.playlist.set_next_track(None);
        self.playlist.clear_current_track();
        self.get_player_mut().stop();
    }

    fn get_progress(&self) -> Option<PlayerProgress> {
        self.get_player().get_progress()
    }

    fn gapless(&self) -> bool {
        self.get_player().gapless()
    }

    fn set_gapless(&mut self, to: bool) {
        self.get_player_mut().set_gapless(to);
    }

    fn skip_one(&mut self) {
        self.get_player_mut().skip_one();
    }

    fn position(&self) -> Option<PlayerTimeUnit> {
        self.get_player().position()
    }

    fn enqueue_next(&mut self, track: &Track) {
        self.get_player_mut().enqueue_next(track);
    }
}

/// The primitive in which time (current position / total duration) will be stored as
pub type PlayerTimeUnit = Duration;

/// Struct to keep both values with a name, as tuples cannot have named fields
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PlayerProgress {
    pub position: Option<PlayerTimeUnit>,
    /// Total duration of the currently playing track, if there is a known total duration
    pub total_duration: Option<PlayerTimeUnit>,
}

impl From<crate::player::PlayerTime> for PlayerProgress {
    fn from(value: crate::player::PlayerTime) -> Self {
        Self {
            position: value.position.map(std::convert::Into::into),
            total_duration: value.total_duration.map(std::convert::Into::into),
        }
    }
}

impl From<PlayerProgress> for crate::player::PlayerTime {
    fn from(value: PlayerProgress) -> Self {
        Self {
            position: value.position.map(std::convert::Into::into),
            total_duration: value.total_duration.map(std::convert::Into::into),
        }
    }
}

pub type Volume = u16;
pub type Speed = i32;

#[allow(clippy::module_name_repetitions)]
#[async_trait]
pub trait PlayerTrait {
    /// Add the given track, skip to it (if not already) and start playing
    async fn add_and_play(&mut self, track: &Track);
    /// Get the currently set volume
    fn volume(&self) -> Volume;
    /// Step the volume up by a backend-set step amount
    ///
    /// Returns the new volume
    fn volume_up(&mut self) -> Volume;
    /// Step the volume down by a backend-set step amount
    ///
    /// Returns the new volume
    fn volume_down(&mut self) -> Volume;
    /// Set the volume to a specific amount.
    ///
    /// Returns the new volume
    fn set_volume(&mut self, volume: Volume) -> Volume;
    fn pause(&mut self);
    fn resume(&mut self);
    fn is_paused(&self) -> bool;
    /// Seek relatively to the current time
    ///
    /// # Errors
    ///
    /// Depending on different backend, there could be different errors during seek.
    fn seek(&mut self, secs: i64) -> Result<()>;
    // TODO: sync return types between "seek" and "seek_to"?
    /// Seek to a absolute position
    fn seek_to(&mut self, position: Duration);
    /// Get current track time position
    fn get_progress(&self) -> Option<PlayerProgress>;
    /// Set the speed to a specific amount.
    ///
    /// Returns the new speed
    fn set_speed(&mut self, speed: Speed) -> Speed;
    /// Step the speed up by a backend-set step amount
    ///
    /// Returns the new speed
    fn speed_up(&mut self) -> Speed;
    /// Step the speed down by a backend-set step amount
    ///
    /// Returns the new speed
    fn speed_down(&mut self) -> Speed;
    /// Get the currently set speed
    fn speed(&self) -> Speed;
    fn stop(&mut self);
    fn gapless(&self) -> bool;
    fn set_gapless(&mut self, to: bool);
    fn skip_one(&mut self);
    /// Quickly access the position.
    ///
    /// This should ALWAYS match up with [`PlayerTrait::get_progress`]'s `.position`!
    fn position(&self) -> Option<PlayerTimeUnit> {
        self.get_progress()?.position
    }
    /// Add the given URI to be played, but do not skip currently playing track
    fn enqueue_next(&mut self, track: &Track);
}