vidsage-ffmpeg 0.1.0

FFmpeg integration for VidSage video processing
Documentation
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
//! VidSage FFmpeg - FFmpeg integration for VidSage

use chrono::{Duration as ChronoDuration, Utc};
use std::path::Path;
use std::process::{Command, Stdio};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command as TokioCommand;
use tracing::{debug, info};
use vidsage_core::video::metadata::{VideoFormat, VideoQuality};
use vidsage_core::video::processor::CompressionLevel;
use vidsage_core::video::VideoOutput;
use vidsage_core::{
    CoreError, ProcessOptions, ProcessingStatus, Result, VideoMetadata, VideoProcessor,
};
use which::which;

/// FFmpeg processor implementation
pub struct FFmpegProcessor {
    ffmpeg_path: String,
    ffprobe_path: String,
}

impl FFmpegProcessor {
    /// Create a new FFmpegProcessor instance
    pub fn new() -> Result<Self> {
        // Check if FFmpeg is installed
        let ffmpeg_path = which("ffmpeg")
            .map_err(|e| CoreError::VideoProcessingError(format!("FFmpeg not found: {}", e)))?;

        // Check if ffprobe is installed
        let ffprobe_path = which("ffprobe")
            .map_err(|e| CoreError::VideoProcessingError(format!("ffprobe not found: {}", e)))?;

        Ok(Self {
            ffmpeg_path: ffmpeg_path.to_string_lossy().to_string(),
            ffprobe_path: ffprobe_path.to_string_lossy().to_string(),
        })
    }

    /// Extract metadata from a video file using ffprobe
    async fn extract_metadata_with_ffprobe(&self, input: &Path) -> Result<VideoMetadata> {
        info!("Extracting metadata from: {:?}", input);

        // Build ffprobe command to get metadata in JSON format
        let output = Command::new(&self.ffprobe_path)
            .args([
                "-v",
                "quiet",
                "-print_format",
                "json",
                "-show_format",
                "-show_streams",
                input.to_str().unwrap(),
            ])
            .output()
            .map_err(|e| {
                CoreError::VideoProcessingError(format!("Failed to run ffprobe: {}", e))
            })?;

        if !output.status.success() {
            return Err(CoreError::VideoProcessingError(
                String::from_utf8_lossy(&output.stderr).to_string(),
            ));
        }

        // Parse JSON output
        let json: serde_json::Value = serde_json::from_slice(&output.stdout).map_err(|e| {
            CoreError::VideoProcessingError(format!("Failed to parse ffprobe output: {}", e))
        })?;

        // Extract video stream information
        let video_stream = json["streams"]
            .as_array()
            .ok_or_else(|| {
                CoreError::VideoProcessingError("No streams found in video".to_string())
            })?
            .iter()
            .find(|stream| stream["codec_type"].as_str() == Some("video"))
            .ok_or_else(|| CoreError::VideoProcessingError("No video stream found".to_string()))?;

        // Extract format information
        let format = json["format"].as_object().ok_or_else(|| {
            CoreError::VideoProcessingError("No format information found".to_string())
        })?;

        // Parse duration
        let duration_str = format["duration"].as_str().unwrap_or("0");
        let duration_secs = duration_str.parse::<f64>().map_err(|e| {
            CoreError::VideoProcessingError(format!("Failed to parse duration: {}", e))
        })?;
        let duration = ChronoDuration::seconds(duration_secs as i64);

        // Parse resolution
        let width = video_stream["width"].as_i64().unwrap_or(0) as u32;
        let height = video_stream["height"].as_i64().unwrap_or(0) as u32;

        // Parse file size
        let file_size = format["size"].as_i64().unwrap_or(0) as u64;

        // Parse bitrate
        let bitrate_str = format["bit_rate"].as_str().unwrap_or("0");
        let bitrate = bitrate_str.parse::<u32>().map_err(|e| {
            CoreError::VideoProcessingError(format!("Failed to parse bitrate: {}", e))
        })? / 1000; // Convert to kbps

        // Parse frame rate
        let frame_rate_str = video_stream["r_frame_rate"].as_str().unwrap_or("30/1");
        let frame_rate = parse_frame_rate(frame_rate_str).map_err(|e| {
            CoreError::VideoProcessingError(format!("Failed to parse frame rate: {}", e))
        })?;

        // Parse video codec
        let video_codec = video_stream["codec_name"]
            .as_str()
            .unwrap_or("unknown")
            .to_string();

        // Parse audio codec
        let audio_codec = json["streams"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .find(|stream| stream["codec_type"].as_str() == Some("audio"))
            .and_then(|stream| stream["codec_name"].as_str())
            .unwrap_or("unknown")
            .to_string();

        // Parse number of audio tracks
        let audio_tracks = json["streams"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .filter(|stream| stream["codec_type"].as_str() == Some("audio"))
            .count() as u32;

        // Parse audio bitrate
        let audio_bitrate = json["streams"]
            .as_array()
            .unwrap_or(&vec![])
            .iter()
            .find(|stream| stream["codec_type"].as_str() == Some("audio"))
            .and_then(|stream| stream["bit_rate"].as_str())
            .unwrap_or("0")
            .parse::<u32>()
            .unwrap_or(0)
            / 1000; // Convert to kbps

        // Determine video format from file extension
        let format = Path::new(input)
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| {
                let ext = ext.to_lowercase();
                match ext.as_str() {
                    "mp4" => VideoFormat::MP4,
                    "webm" => VideoFormat::WebM,
                    "avi" => VideoFormat::AVI,
                    "mov" => VideoFormat::MOV,
                    "mkv" => VideoFormat::MKV,
                    "flv" => VideoFormat::FLV,
                    _ => VideoFormat::Other,
                }
            })
            .unwrap_or(VideoFormat::Other);

        // Create VideoMetadata instance
        let metadata = VideoMetadata {
            id: vidsage_core::utils::helpers::generate_id(),
            title: Path::new(input)
                .file_stem()
                .and_then(|stem| stem.to_str())
                .unwrap_or("Unknown Video")
                .to_string(),
            duration,
            resolution: (width, height),
            format,
            file_size,
            bitrate,
            frame_rate,
            audio_tracks,
            audio_bitrate,
            video_codec,
            audio_codec,
            created_at: Utc::now(),
            updated_at: Utc::now(),
        };

        debug!("Extracted metadata: {:?}", metadata);
        Ok(metadata)
    }

    /// Build FFmpeg command for video processing
    fn build_process_command(
        &self,
        input: &Path,
        output: &Path,
        options: &ProcessOptions,
    ) -> Vec<String> {
        let mut args = vec![
            "-i".to_string(),
            input.to_str().unwrap().to_string(),
            "-y".to_string(), // Overwrite output file if it exists
        ];

        // Set video codec based on output format
        match options.format {
            VideoFormat::MP4 => args.extend(vec!["-c:v".to_string(), "libx264".to_string()]),
            VideoFormat::WebM => args.extend(vec!["-c:v".to_string(), "libvpx-vp9".to_string()]),
            _ => args.extend(vec!["-c:v".to_string(), "copy".to_string()]),
        }

        // Set video quality
        match options.quality {
            VideoQuality::Low => args.extend(vec!["-crf".to_string(), "30".to_string()]),
            VideoQuality::Medium => args.extend(vec!["-crf".to_string(), "23".to_string()]),
            VideoQuality::High => args.extend(vec!["-crf".to_string(), "17".to_string()]),
            VideoQuality::Ultra => args.extend(vec!["-crf".to_string(), "12".to_string()]),
            VideoQuality::Custom(bitrate) => args.extend(vec![
                "-b:v".to_string(),
                format!("{}k", bitrate).to_string(),
            ]),
        }

        // Set compression level
        match options.compression {
            CompressionLevel::Low => {
                args.extend(vec!["-preset".to_string(), "ultrafast".to_string()])
            },
            CompressionLevel::Medium => {
                args.extend(vec!["-preset".to_string(), "medium".to_string()])
            },
            CompressionLevel::High => args.extend(vec!["-preset".to_string(), "slow".to_string()]),
            CompressionLevel::Ultra => {
                args.extend(vec!["-preset".to_string(), "veryslow".to_string()])
            },
            CompressionLevel::Custom(_) => {
                args.extend(vec!["-preset".to_string(), "medium".to_string()])
            },
        }

        // Set output resolution if specified
        if let Some(resolution) = options.resolution {
            args.extend(vec![
                "-s".to_string(),
                format!("{}x{}", resolution.0, resolution.1).to_string(),
            ]);
        }

        // Set frame rate if specified
        if let Some(frame_rate) = options.frame_rate {
            args.extend(vec!["-r".to_string(), frame_rate.to_string()]);
        }

        // Set number of threads if specified
        if let Some(threads) = options.threads {
            args.extend(vec!["-threads".to_string(), threads.to_string()]);
        }

        // Add output file
        args.push(output.to_str().unwrap().to_string());

        args
    }
}

#[async_trait::async_trait]
impl VideoProcessor for FFmpegProcessor {
    async fn extract_metadata(&self, input: &Path) -> Result<VideoMetadata> {
        self.extract_metadata_with_ffprobe(input).await
    }

    async fn process_video(&self, input: &Path, options: ProcessOptions) -> Result<VideoOutput> {
        info!("Processing video: {:?} with options: {:?}", input, options);

        // Create output directory if it doesn't exist
        let output_dir = input.parent().unwrap_or(Path::new("."));
        std::fs::create_dir_all(output_dir).map_err(|e| {
            CoreError::VideoProcessingError(format!("Failed to create output directory: {}", e))
        })?;

        // Generate output file path
        let output_ext = match options.format {
            VideoFormat::MP4 => "mp4",
            VideoFormat::WebM => "webm",
            VideoFormat::AVI => "avi",
            VideoFormat::MOV => "mov",
            VideoFormat::MKV => "mkv",
            VideoFormat::FLV => "flv",
            VideoFormat::Other => "mp4",
        };

        let output_file_name = format!(
            "{}-processed.{}",
            input.file_stem().unwrap_or_default().to_str().unwrap(),
            output_ext
        );
        let output_path = output_dir.join(output_file_name);

        // Build FFmpeg command
        let args = self.build_process_command(input, &output_path, &options);
        debug!("FFmpeg command: {} {:?}", self.ffmpeg_path, args);

        // Start FFmpeg process
        let mut cmd = TokioCommand::new(&self.ffmpeg_path)
            .args(args)
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| {
                CoreError::VideoProcessingError(format!("Failed to start FFmpeg: {}", e))
            })?;

        // Read stderr to track progress
        let stderr = cmd.stderr.take().unwrap();
        let mut reader = BufReader::new(stderr).lines();

        // Wait for process to complete
        let output = tokio::spawn(async move {
            while let Some(line) = reader.next_line().await.unwrap() {
                debug!("FFmpeg stderr: {}", line);
            }
            cmd.wait().await
        })
        .await
        .unwrap()
        .map_err(|e| CoreError::VideoProcessingError(format!("FFmpeg process failed: {}", e)))?;

        if !output.success() {
            return Err(CoreError::VideoProcessingError(format!(
                "FFmpeg processing failed with exit code: {}",
                output.code().unwrap_or(-1)
            )));
        }

        // Extract metadata from processed video
        let metadata = self.extract_metadata_with_ffprobe(&output_path).await?;

        // Create VideoOutput instance
        let output = VideoOutput {
            metadata,
            processed_path: output_path.clone(),
            status: ProcessingStatus::Completed,
            processing_time: 0.0, // TODO: Calculate actual processing time
            original_path: input.to_path_buf(),
            audio_path: None,         // TODO: Implement audio extraction
            extracted_metadata: None, // Already extracted metadata
        };

        info!("Video processing completed successfully: {:?}", output_path);
        Ok(output)
    }

    async fn get_status(&self, _job_id: &str) -> Result<ProcessingStatus> {
        // TODO: Implement job status tracking
        Ok(ProcessingStatus::Completed)
    }

    async fn cancel_job(&self, _job_id: &str) -> Result<bool> {
        // TODO: Implement job cancellation
        Ok(true)
    }
}

/// Parse frame rate from FFprobe output
fn parse_frame_rate(frame_rate_str: &str) -> Result<f64> {
    if frame_rate_str.contains('/') {
        let parts: Vec<&str> = frame_rate_str.split('/').collect();
        if parts.len() == 2 {
            let numerator = parts[0].parse::<f64>().map_err(|e| {
                CoreError::VideoProcessingError(format!("Invalid frame rate: {}", e))
            })?;
            let denominator = parts[1].parse::<f64>().map_err(|e| {
                CoreError::VideoProcessingError(format!("Invalid frame rate: {}", e))
            })?;
            if denominator == 0.0 {
                return Ok(30.0); // Default to 30fps if denominator is 0
            }
            return Ok(numerator / denominator);
        }
    }

    frame_rate_str
        .parse::<f64>()
        .map_err(|e| CoreError::VideoProcessingError(format!("Invalid frame rate: {}", e)))
        .or(Ok(30.0))
}

/// Check if FFmpeg is installed
pub fn is_ffmpeg_installed() -> bool {
    which("ffmpeg").is_ok() && which("ffprobe").is_ok()
}

/// Get FFmpeg version
pub fn get_ffmpeg_version() -> Option<String> {
    let output = Command::new("ffmpeg").args(["-version"]).output().ok()?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        stdout.lines().next().map(|line| line.to_string())
    } else {
        None
    }
}