ayan_player_cli/
player.rs

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
use std::{
    io, process::{Command, Output},
    fmt::Display
};

use serde::{Deserialize, Serialize};

use crate::config::Configs;



#[derive(Debug, Serialize, Deserialize)]
pub enum PlayerType {
    MPV,
    VLC,
    Other,
}

impl Display for PlayerType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", match self {
            PlayerType::MPV => "mpv",
            PlayerType::VLC => "vlc",
            PlayerType::Other => "other",
        })
    }
}


impl PlayerType {
    pub fn build_command(&self, file: &str, config: &Configs) -> Command {
        let mut cmd = Command::new(match self {
            PlayerType::MPV => format!("mpv"),
            PlayerType::VLC => format!("vlc"),
            PlayerType::Other => format!("xdg-open"),
        });
        cmd.arg(file);
        self.build_volume(&config, &mut cmd);
        self.build_speed(&config, &mut cmd);
        cmd
    }

    fn build_volume(&self, config: &Configs, command: &mut Command) {
        match self {
            PlayerType::MPV => command.arg(format!("--volume={}", config.get_volume())),
            PlayerType::VLC => command.arg(format!(
                "--volume {}",
                (config.get_volume() / 100.0) * 256.0
            )),
            PlayerType::Other => command,
        };
    }
    fn build_speed(&self, config: &Configs, command: &mut Command) {
        match self {
            PlayerType::MPV => command.arg(format!("--speed={}", config.get_speed())),
            PlayerType::VLC => command.arg(format!("--rate {}", config.get_speed())),
            PlayerType::Other => command,
        };
    }
}

pub fn get_player_from_str(config: &str) -> PlayerType {
    let player_str = config.to_lowercase();
    if player_str == "mpv" {
        return PlayerType::MPV;
    } else if player_str == "vlc" {
        return PlayerType::VLC;
    } else {
        return PlayerType::Other;
    }
}

pub fn play(file: &str, config: &Configs) -> Result<Output, io::Error> {
    let mut cmd = config.player.build_command(file, &config);
    println!("Command used: {cmd:?}");
    let result = cmd.output();
    result
}