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
//! Endpoint used to manage a local ffmpeg executable.  Workflow steps can request FFMPEG be run
//! with specific parameters, and the endpoint will run it.  If the ffmpeg process stops before
//! being requested to stop, then the endpoint will ensure it gets re-run.

use futures::future::BoxFuture;
use futures::stream::FuturesUnordered;
use futures::{FutureExt, StreamExt};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::Duration;
use thiserror::Error;
use tokio::fs::{File, OpenOptions};
use tokio::io::AsyncWriteExt;
use tokio::sync::mpsc::{unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::time::sleep;
use tracing::{error, info, instrument};
use uuid::Uuid;

/// Requests of ffmpeg operations
#[derive(Debug)]
pub enum FfmpegEndpointRequest {
    /// Request that ffmpeg should be started with the specified parameters
    StartFfmpeg {
        /// A unique identifier to use for this ffmpeg operation.  Any further requests that should
        /// affect this ffmpeg operation should use this same identifier
        id: Uuid,

        /// The channel that the endpoint will send notifications on to notify the requester of
        /// changes in the ffmpeg operation.
        notification_channel: UnboundedSender<FfmpegEndpointNotification>,

        /// What parameters ffmpeg should be run with
        params: FfmpegParams,
    },

    /// Requests that the specified ffmpeg operation should be stopped
    StopFfmpeg {
        /// The identifier of the existing ffmpeg operation
        id: Uuid,
    },
}

/// Notifications of what's happening with an ffmpeg operation
#[derive(Debug)]
pub enum FfmpegEndpointNotification {
    FfmpegStarted,
    FfmpegStopped,
    FfmpegFailedToStart { cause: FfmpegFailureCause },
}

/// Reasons that ffmpeg may fail to start
#[derive(Debug)]
pub enum FfmpegFailureCause {
    /// The log file for ffmpeg's standard output could not be created
    LogFileCouldNotBeCreated(String, std::io::Error),

    /// ffmpeg was requested to be started with an identifier that matches an ffmpeg operation
    /// that's already being run.
    DuplicateId(Uuid),

    /// The ffmpeg process failed to start due to an issue with the executable itself
    FfmpegFailedToStart,
}

/// Error that occurs when starting the ffmpeg endpoint
#[derive(Error, Debug)]
pub enum FfmpegEndpointStartError {
    #[error("The ffmpeg executable '{0}' was not found")]
    FfmpegExecutableNotFound(String),

    #[error("Failed to create log directory")]
    LogDirectoryCreationFailure,

    #[error("The log directory '{0}' is an invalid path")]
    LogDirectoryInvalidPath(String),
}

/// H264 presets
#[derive(Clone, Debug, PartialEq)]
pub enum H264Preset {
    UltraFast,
    SuperFast,
    VeryFast,
    Faster,
    Fast,
    Medium,
    Slow,
    Slower,
    VerySlow,
}

/// Video transcode instructions
#[derive(Clone, Debug, PartialEq)]
pub enum VideoTranscodeParams {
    Copy,
    H264 { preset: H264Preset },
}

/// Audio transcode instructions
#[derive(Clone, Debug, PartialEq)]
pub enum AudioTranscodeParams {
    Copy,
    Aac,
}

/// Where should ffmpeg send the media
#[derive(Clone, Debug, PartialEq)]
pub enum TargetParams {
    /// Send the media stream to an RTMP server
    Rtmp { url: String },

    /// Save the media stream as an HLS playlist
    Hls {
        /// The directory the playlist should be saved to.
        path: String,

        /// How long (in seconds) should each segment be
        segment_length: u16,

        /// The maximum number of segments that should be in the playlist.  If none is specified
        /// than ffmpeg's default will be used
        max_entries: Option<u16>,
    },
}

/// The dimensions video should be scaled to
#[derive(Clone, Debug, PartialEq)]
pub struct VideoScale {
    pub width: u16,
    pub height: u16,
}

/// Parameters to pass to the ffmpeg process
#[derive(Clone, Debug, PartialEq)]
pub struct FfmpegParams {
    pub read_in_real_time: bool,
    pub input: String,
    pub video_transcode: VideoTranscodeParams,
    pub scale: Option<VideoScale>,
    pub audio_transcode: AudioTranscodeParams,
    pub bitrate_in_kbps: Option<u16>,
    pub target: TargetParams,
}

/// Starts a new ffmpeg endpoint, and returns the channel in which the newly created endpoint
/// can be communicated with
pub fn start_ffmpeg_endpoint(
    ffmpeg_exe_path: String,
    log_root: String,
) -> Result<UnboundedSender<FfmpegEndpointRequest>, FfmpegEndpointStartError> {
    let actor = Actor::new(ffmpeg_exe_path, log_root)?;
    let (sender, receiver) = unbounded_channel();

    tokio::spawn(actor.run(receiver));

    Ok(sender)
}

enum FutureResult {
    AllConsumersGone,
    NotificationChannelGone(Uuid),
    RequestReceived(
        FfmpegEndpointRequest,
        UnboundedReceiver<FfmpegEndpointRequest>,
    ),
    CheckProcess(Uuid),
}

struct FfmpegProcess {
    handle: Child,
    notification_channel: UnboundedSender<FfmpegEndpointNotification>,
}

struct Actor {
    ffmpeg_exe_path: String,
    log_path: PathBuf,
    futures: FuturesUnordered<BoxFuture<'static, FutureResult>>,
    processes: HashMap<Uuid, FfmpegProcess>,
}

impl Actor {
    fn new(ffmpeg_exe_path: String, log_root: String) -> Result<Self, FfmpegEndpointStartError> {
        let path = Path::new(ffmpeg_exe_path.as_str());
        if !path.is_file() {
            return Err(FfmpegEndpointStartError::FfmpegExecutableNotFound(
                ffmpeg_exe_path,
            ));
        }

        let mut path = PathBuf::from(log_root.as_str());
        if path.is_file() {
            // We expected the path to be a new or existing directory, not a file
            return Err(FfmpegEndpointStartError::LogDirectoryInvalidPath(log_root));
        }

        path.push("ffmpeg_stdout");
        if !path.exists() {
            if let Err(error) = std::fs::create_dir_all(&path) {
                error!(
                    "Could not create log directory '{}': {:?}",
                    path.display().to_string(),
                    error
                );
                return Err(FfmpegEndpointStartError::LogDirectoryCreationFailure);
            }
        }

        Ok(Actor {
            ffmpeg_exe_path,
            log_path: path,
            processes: HashMap::new(),
            futures: FuturesUnordered::new(),
        })
    }

    async fn run(mut self, receiver: UnboundedReceiver<FfmpegEndpointRequest>) {
        self.futures.push(wait_for_request(receiver).boxed());

        info!("Ffmpeg endpoint started");
        info!("Ffmpeg path: {}", self.ffmpeg_exe_path);
        while let Some(result) = self.futures.next().await {
            match result {
                FutureResult::AllConsumersGone => {
                    info!("All consumers gone");
                    break;
                }

                FutureResult::NotificationChannelGone(id) => {
                    self.handle_notification_channel_gone(id);
                }

                FutureResult::CheckProcess(id) => {
                    self.check_status(id);
                }

                FutureResult::RequestReceived(request, receiver) => {
                    self.futures.push(wait_for_request(receiver).boxed());
                    self.handle_request(request).await;
                }
            }
        }

        info!("Ffmpeg endpoint closing");

        for (id, process) in self.processes.drain() {
            stop_process(id, process);
        }
    }

    #[instrument(skip(self, id), fields(ffmpeg_id = ?id))]
    fn check_status(&mut self, id: Uuid) {
        let mut has_exited = false;
        if let Some(process) = self.processes.get_mut(&id) {
            has_exited = match process.handle.try_wait() {
                Ok(None) => false, // still running
                Ok(Some(status)) => {
                    info!("Ffmpeg process {} exited with status {}", id, status);
                    true
                }

                Err(e) => {
                    info!(
                        "Error attempting to get status for ffmpeg process {}: {}",
                        id, e
                    );
                    let _ = process.handle.kill();
                    true
                }
            };

            if !has_exited {
                self.futures.push(wait_for_next_check(id).boxed());
            }
        }

        if has_exited {
            let process = self.processes.remove(&id).unwrap();
            let _ = process
                .notification_channel
                .send(FfmpegEndpointNotification::FfmpegStopped);
        }
    }

    fn handle_notification_channel_gone(&mut self, id: Uuid) {
        info!(id = ?id, "Consumer for ffmpeg process {} is gone", id);
        if let Some(process) = self.processes.remove(&id) {
            stop_process(id, process);
        }
    }

    async fn handle_request(&mut self, request: FfmpegEndpointRequest) {
        match request {
            FfmpegEndpointRequest::StopFfmpeg { id } => {
                if let Some(process) = self.processes.remove(&id) {
                    stop_process(id, process);
                }
            }

            FfmpegEndpointRequest::StartFfmpeg {
                id,
                params,
                notification_channel,
            } => {
                if self.processes.contains_key(&id) {
                    let _ = notification_channel.send(
                        FfmpegEndpointNotification::FfmpegFailedToStart {
                            cause: FfmpegFailureCause::DuplicateId(id),
                        },
                    );

                    return;
                }

                let log_file_name = format!("{}.log", id.to_string());
                let log_path = self.log_path.as_path().join(log_file_name.as_str());
                let log_file_result = OpenOptions::new()
                    .append(true)
                    .create(true)
                    .open(log_path)
                    .await;

                let mut log_file = match log_file_result {
                    Ok(x) => x,
                    Err(e) => {
                        error!("Failed to create ffmpeg log file '{}'", log_file_name);
                        let _ = notification_channel.send(
                            FfmpegEndpointNotification::FfmpegFailedToStart {
                                cause: FfmpegFailureCause::LogFileCouldNotBeCreated(
                                    log_file_name.to_string(),
                                    e,
                                ),
                            },
                        );

                        return;
                    }
                };

                // Add a separator so we have a clear boundary when appending to an existing log file.
                // We will append if we re-use the same ffmpeg id multiple times.  This is usually done
                // to keep the logs from a restarting ffmpeg instance together.
                let _ = log_file
                    .write(b"\n\n------------------New Execution----------------\n\n")
                    .await;

                let handle = match self.start_ffmpeg(&id, &params, log_file) {
                    Ok(x) => x,
                    Err(e) => {
                        error!("Failed to start ffmpeg: {}", e);
                        let _ = notification_channel.send(
                            FfmpegEndpointNotification::FfmpegFailedToStart {
                                cause: FfmpegFailureCause::FfmpegFailedToStart,
                            },
                        );

                        return;
                    }
                };

                self.futures.push(wait_for_next_check(id.clone()).boxed());
                let _ = notification_channel.send(FfmpegEndpointNotification::FfmpegStarted);
                self.processes.insert(
                    id,
                    FfmpegProcess {
                        handle,
                        notification_channel: notification_channel.clone(),
                    },
                );

                self.futures.push(
                    wait_for_notification_channel_gone(id.clone(), notification_channel).boxed(),
                );
            }
        }
    }

    fn start_ffmpeg(
        &self,
        id: &Uuid,
        params: &FfmpegParams,
        mut log_file: File,
    ) -> Result<Child, std::io::Error> {
        let mut args = Vec::new();
        if params.read_in_real_time {
            args.push("-re".to_string());
        }

        args.push("-i".to_string());
        args.push(params.input.clone());

        args.push("-vcodec".to_string());
        match &params.video_transcode {
            VideoTranscodeParams::Copy => args.push("copy".to_string()),
            VideoTranscodeParams::H264 { preset } => {
                args.push("libx264".to_string());
                args.push("-preset".to_string());

                match preset {
                    H264Preset::UltraFast => args.push("ultrafast".to_string()),
                    H264Preset::SuperFast => args.push("superfast".to_string()),
                    H264Preset::VeryFast => args.push("veryfast".to_string()),
                    H264Preset::Faster => args.push("faster".to_string()),
                    H264Preset::Fast => args.push("fast".to_string()),
                    H264Preset::Medium => args.push("medium".to_string()),
                    H264Preset::Slow => args.push("slow".to_string()),
                    H264Preset::Slower => args.push("slower".to_string()),
                    H264Preset::VerySlow => args.push("veryslow".to_string()),
                }
            }
        }

        if let Some(bitrate) = &params.bitrate_in_kbps {
            let rate = format!("{}K", bitrate);
            args.push("-b:v".to_string());
            args.push(rate.clone());

            args.push("-minrate".to_string());
            args.push(rate.clone());

            args.push("-maxrate".to_string());
            args.push(rate.clone());
        }

        if let Some(scale) = &params.scale {
            args.push("-vf".to_string());
            args.push(format!("scale={}:{}", scale.width, scale.height));
        }

        args.push("-acodec".to_string());
        match &params.audio_transcode {
            AudioTranscodeParams::Copy => args.push("copy".to_string()),
            AudioTranscodeParams::Aac => args.push("aac".to_string()),
        }

        args.push("-f".to_string());
        match &params.target {
            TargetParams::Rtmp { url } => {
                args.push("flv".to_string());
                args.push(url.to_string());
            }

            TargetParams::Hls {
                path,
                max_entries,
                segment_length,
            } => {
                args.push("hls".to_string());

                args.push("-hls_time".to_string());
                args.push(segment_length.to_string());

                if let Some(entries) = max_entries {
                    args.push("-hls_list_size".to_string());
                    args.push(entries.to_string());
                }

                args.push(path.clone());
            }
        }

        args.push("-y".to_string()); // always overwrite
        args.push("-nostats".to_string());

        info!(
            ffmpeg_id = ?id,
            "Starting ffmpeg for id {} with the following arguments: {:?}",
            id, args
        );

        let mut command = Command::new(&self.ffmpeg_exe_path)
            .args(args)
            .stderr(Stdio::piped()) // ffmpeg seems to write output to stderr
            .spawn()?;

        if let Some(stderr) = command.stderr.take() {
            if let Ok(mut stdout) = tokio::process::ChildStderr::from_std(stderr) {
                tokio::spawn(async move {
                    let _ = tokio::io::copy(&mut stdout, &mut log_file).await;
                });
            }
        }

        Ok(command)
    }
}

fn stop_process(id: Uuid, mut process: FfmpegProcess) {
    info!(id = ?id, "Killing ffmpeg process {}", id);
    let _ = process.handle.kill();

    let _ = process
        .notification_channel
        .send(FfmpegEndpointNotification::FfmpegStopped);
}

async fn wait_for_request(mut receiver: UnboundedReceiver<FfmpegEndpointRequest>) -> FutureResult {
    match receiver.recv().await {
        Some(x) => FutureResult::RequestReceived(x, receiver),
        None => FutureResult::AllConsumersGone,
    }
}

async fn wait_for_next_check(id: Uuid) -> FutureResult {
    sleep(Duration::from_secs(5)).await;

    FutureResult::CheckProcess(id)
}

async fn wait_for_notification_channel_gone(
    id: Uuid,
    channel: UnboundedSender<FfmpegEndpointNotification>,
) -> FutureResult {
    channel.closed().await;

    FutureResult::NotificationChannelGone(id)
}