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
#![allow(clippy::uninlined_format_args)]

/// Progress event
mod progress_event;

/// The command builder
mod builder;

/// Encoder info
mod encoder;

pub use self::{
    builder::Builder,
    encoder::{
        Encoder,
        FromLineError as EncoderFromLineError,
    },
    progress_event::{
        LineBuilderError,
        ProgressEvent,
    },
};
use std::process::ExitStatus;

/// The error type
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Failed to spawn a process
    #[error("failed to spawn a process")]
    ProcessSpawn(#[source] std::io::Error),

    /// The input file was not specified
    #[error("missing input file")]
    MissingInput,

    /// The output file was not specified
    #[error("missing output file")]
    MissingOutput,

    /// An IO error occured
    #[error("io error")]
    Io(#[source] std::io::Error),

    /// The output file already exists
    #[error("output file already exists")]
    OutputAlreadyExists,

    /// Failed to construct a progress event
    #[error("invalid progress event")]
    InvalidProgressEvent(#[from] crate::progress_event::LineBuilderError),

    /// An exit status was invalid
    #[error("invalid exit status '{0}'")]
    InvalidExitStatus(ExitStatus),

    /// Failed to convert bytes to a str
    #[error(transparent)]
    InvalidUtf8Str(std::str::Utf8Error),

    /// Invalid encoder
    #[error("failed to parse encoder line")]
    InvalidEncoderLine(#[from] EncoderFromLineError),
}

/// An Event
#[derive(Debug)]
pub enum Event {
    /// A progress event
    Progress(ProgressEvent),

    /// The process exit status
    ExitStatus(ExitStatus),

    /// An unknown line
    Unknown(String),
}

/// Get encoders that this ffmpeg supports
pub async fn get_encoders() -> Result<Vec<Encoder>, Error> {
    let output = tokio::process::Command::new("ffmpeg")
        .arg("-hide_banner")
        .arg("-encoders")
        .output()
        .await
        .map_err(Error::Io)?;

    if !output.status.success() {
        return Err(Error::InvalidExitStatus(output.status));
    }

    let stdout_str = std::str::from_utf8(&output.stdout).map_err(Error::InvalidUtf8Str)?;
    Ok(stdout_str
        .lines()
        .map(|line| line.trim())
        .skip_while(|line| *line != "------")
        .skip(1)
        .map(Encoder::from_line)
        .collect::<Result<_, _>>()?)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio_stream::StreamExt;

    // https://ottverse.com/free-hls-m3u8-test-urls/
    const SAMPLE_M3U8: &str =
        "https://devimages.apple.com.edgekey.net/iphone/samples/bipbop/bipbopall.m3u8";

    #[tokio::test]
    async fn transcode_m3u8() {
        let mut stream = Builder::new()
            .audio_codec("copy")
            .video_codec("copy")
            .input(SAMPLE_M3U8)
            .output("transcode_m3u8.mp4")
            .overwrite(true)
            .spawn()
            .expect("failed to spawn ffmpeg");

        while let Some(maybe_event) = stream.next().await {
            match maybe_event {
                Ok(Event::Progress(event)) => {
                    println!("Progress Event: {:#?}", event);
                }
                Ok(Event::ExitStatus(exit_status)) => {
                    println!("FFMpeg exited: {:?}", exit_status);
                }
                Ok(Event::Unknown(line)) => {
                    //  panic!("{:?}", event);
                    dbg!(line);
                }
                Err(e) => {
                    panic!("Error: {}", e);
                }
            }
        }
    }

    #[tokio::test]
    #[ignore]
    async fn reencode_m3u8() {
        let mut stream = Builder::new()
            .audio_codec("libopus")
            .video_codec("vp9")
            .input(SAMPLE_M3U8)
            .output("reencode_m3u8.webm")
            .overwrite(true)
            .spawn()
            .expect("failed to spawn ffmpeg");

        while let Some(maybe_event) = stream.next().await {
            match maybe_event {
                Ok(Event::Progress(event)) => {
                    println!("Progress Event: {:#?}", event);
                }
                Ok(Event::ExitStatus(exit_status)) => {
                    println!("FFMpeg exited: {:?}", exit_status);
                }
                Ok(Event::Unknown(line)) => {
                    //  panic!("{:?}", event);
                    dbg!(line);
                }
                Err(e) => {
                    panic!("Error: {}", e);
                }
            }
        }
    }

    #[tokio::test]
    async fn ffmpeg_get_encoders() {
        let encoders = get_encoders().await.expect("failed to get encoders");

        dbg!(encoders);
    }
}