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
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
//! FFmpeg wrapper for video/audio processing operations
//!
//! This module provides a high-level interface to ffmpeg and ffprobe commands,
//! supporting video metadata extraction, frame extraction, thumbnail generation,
//! and independent process management. Each Ffmpeg instance owns its own
//! process resources, ensuring no state conflicts between parallel operations.
use crate::{
AudioMetadata, FrameExtractOptions, ImageMetadata, PersistentProcess, ThumbnailOptions,
VideoMetadata, hidden_cmd,
};
use std::{
env, fs,
io::{Read, Write},
path::{Path, PathBuf},
process::{Command, Stdio},
};
/// Find ffmpeg executable path
///
/// Search order:
/// 1. Tauri application bin directory (usually under `resources/bin` or `bin`)
/// 2. System PATH environment variable
/// 3. Fallback to "ffmpeg" command name
///
/// # Returns
/// * `Some(String)` - Found ffmpeg path
/// * `None` - ffmpeg not found
pub fn find_ffmpeg_path() -> Option<String> {
// 1. First check Tauri application bin directories
let possible_paths = get_tauri_bin_paths();
for path in possible_paths {
if path.exists() {
// Check ffmpeg executable in the directory
#[cfg(target_os = "windows")]
let ffmpeg_path = path.join("ffmpeg.exe");
#[cfg(not(target_os = "windows"))]
let ffmpeg_path = path.join("ffmpeg");
if ffmpeg_path.exists() && is_ffmpeg_executable(&ffmpeg_path) {
return Some(ffmpeg_path.to_string_lossy().to_string());
}
// Also check bin subdirectory (common in some packaging)
#[cfg(target_os = "windows")]
let ffmpeg_path2 = path.join("bin").join("ffmpeg.exe");
#[cfg(not(target_os = "windows"))]
let ffmpeg_path2 = path.join("bin").join("ffmpeg");
if ffmpeg_path2.exists() && is_ffmpeg_executable(&ffmpeg_path2) {
return Some(ffmpeg_path2.to_string_lossy().to_string());
}
}
}
// 2. Try system PATH environment variable
if let Ok(path_var) = env::var("PATH") {
for path in env::split_paths(&path_var) {
#[cfg(target_os = "windows")]
let ffmpeg_path = path.join("ffmpeg.exe");
#[cfg(not(target_os = "windows"))]
let ffmpeg_path = path.join("ffmpeg");
if ffmpeg_path.exists() && is_ffmpeg_executable(&ffmpeg_path) {
return Some(ffmpeg_path.to_string_lossy().to_string());
}
}
}
// 3. Fallback to using "ffmpeg" command name (rely on PATH resolution)
if is_ffmpeg_available("ffmpeg") {
return Some("ffmpeg".to_string());
}
None
}
/// Check if ffmpeg at given path is executable and working
fn is_ffmpeg_executable(path: &Path) -> bool {
if let Ok(output) = hidden_cmd(path.to_str().unwrap()).arg("-version").output() {
return output.status.success();
}
false
}
/// Check if ffmpeg is available via command name
fn is_ffmpeg_available(cmd: &str) -> bool {
hidden_cmd(cmd)
.arg("-version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Get possible Tauri application bin directory paths
fn get_tauri_bin_paths() -> Vec<PathBuf> {
let mut paths = Vec::new();
// Get current executable path
if let Ok(exe_path) = std::env::current_exe() {
if let Some(exe_dir) = exe_path.parent() {
// 1. Same directory as executable
paths.push(exe_dir.to_path_buf());
// 2. ../bin relative to executable
if let Some(parent) = exe_dir.parent() {
paths.push(parent.join("bin"));
}
// 3. ../Resources/bin relative to executable (macOS app bundle)
if let Some(parent) = exe_dir.parent() {
paths.push(parent.join("Resources").join("bin"));
}
}
}
// 4. Current working directory / bin
if let Ok(cwd) = env::current_dir() {
paths.push(cwd.join("bin"));
paths.push(cwd.join("resources").join("bin"));
}
// 5. Tauri typical paths
// When running as a Tauri app, the binary is in a specific location
if let Ok(exe_path) = std::env::current_exe() {
// For Tauri apps, the binary is usually in:
// - macOS: YourApp.app/Contents/MacOS/
// - Windows: target/release/ or the install directory
// - Linux: target/release/ or /usr/bin/
if let Some(exe_dir) = exe_path.parent() {
// Try to find bin directory relative to executable parent
// This handles common Tauri build structures
paths.push(exe_dir.join("bin"));
// For macOS app bundles: ../Resources/bin
if let Some(parent) = exe_dir.parent() {
paths.push(parent.join("Resources").join("bin"));
paths.push(parent.join("bin"));
}
}
}
// Remove duplicates
paths.sort();
paths.dedup();
paths
}
/// FFmpeg wrapper for video/audio processing operations
///
/// This struct provides a high-level interface to ffmpeg and ffprobe commands.
/// Each instance is independent and owns its own resources, making it safe
/// for parallel use in multi-threaded environments like sharded decoding.
///
/// # Important
/// - Each instance manages its own persistent process (if any)
/// - Instances are NOT shared between threads by default
/// - Use `Ffmpeg::new()` to create independent instances for each task
#[derive(Clone)]
pub struct Ffmpeg {
/// Path to the ffmpeg binary
pub bin_path: String,
/// Path to the ffprobe binary (derived from bin_path)
pub probe_path: String,
/// Persistent ffmpeg process for fast frame extraction
/// Each instance owns its own persistent process, preventing state conflicts
pub persistent: std::sync::Arc<std::sync::Mutex<Option<PersistentProcess>>>,
}
impl Default for Ffmpeg {
fn default() -> Self {
Self::new()
}
}
impl Ffmpeg {
/// Create a new Ffmpeg instance with automatic binary detection
///
/// Automatically searches for ffmpeg in:
/// 1. Tauri application bin directory
/// 2. System PATH environment variable
///
/// # Returns
/// A new independent Ffmpeg instance
///
/// # Panics
/// Panics if ffmpeg cannot be found in any of the searched locations
pub fn new() -> Self {
let bin_path = find_ffmpeg_path().expect(
"FFmpeg not found. Please install ffmpeg or place it in the application bin directory.",
);
// Derive ffprobe path from ffmpeg path
let probe_path = Self::derive_probe_path(&bin_path);
Self {
bin_path,
probe_path,
persistent: std::sync::Arc::new(std::sync::Mutex::new(None)),
}
}
/// Create a new Ffmpeg instance with custom binary path
///
/// # Arguments
/// * `path` - Custom path to the ffmpeg binary
///
/// # Returns
/// A new independent Ffmpeg instance with custom binary path
pub fn with_bin_path(path: &str) -> Self {
let bin_path = path.to_string();
let probe_path = Self::derive_probe_path(path);
Self {
bin_path,
probe_path,
persistent: std::sync::Arc::new(std::sync::Mutex::new(None)),
}
}
/// Derive ffprobe path from ffmpeg path
///
/// # Arguments
/// * `ffmpeg_path` - Path to ffmpeg executable
///
/// # Returns
/// Derived ffprobe path
fn derive_probe_path(ffmpeg_path: &str) -> String {
// If ffmpeg is "ffmpeg" (command name), use "ffprobe" as command name
if ffmpeg_path == "ffmpeg" {
return "ffprobe".to_string();
}
// Replace "ffmpeg" with "ffprobe" in the path
let path = Path::new(ffmpeg_path);
let dir = path.parent().unwrap_or(Path::new("."));
let file_name = path.file_name().unwrap_or_default().to_string_lossy();
#[cfg(target_os = "windows")]
let probe_name = file_name.replace("ffmpeg.exe", "ffprobe.exe");
#[cfg(not(target_os = "windows"))]
let probe_name = file_name.replace("ffmpeg", "ffprobe");
let probe_path = dir.join(probe_name);
if probe_path.exists() {
probe_path.to_string_lossy().to_string()
} else {
// If ffprobe not found in the same directory, try using command name
"ffprobe".to_string()
}
}
/// Initialize persistent ffmpeg process for fast frame extraction
///
/// Starts a persistent ffmpeg process in image2pipe mode, which allows
/// fast frame extraction without restarting ffmpeg for each frame.
///
/// # Important
/// - This process is owned by this instance only
/// - Not shared with other instances
/// - Will be automatically cleaned up when the instance is dropped
///
/// # Arguments
/// * `video_path` - Path to the video file to process
///
/// # Returns
/// * `Ok(())` on success
/// * `Err(String)` - Error message if initialization fails
pub fn init_persistent(&self, video_path: &str) -> Result<(), String> {
let mut guard = self.persistent.lock().unwrap();
// Check if we already have a persistent process for this video
if let Some(ref mut proc) = *guard {
if proc.video_path == video_path {
return Ok(());
}
// Different video, kill old process
let _ = proc.child.kill();
*guard = None;
}
// Start new persistent ffmpeg process
let mut child = hidden_cmd(&self.bin_path)
.args([
"-i",
video_path,
"-f",
"image2pipe",
"-vcodec",
"mjpeg",
"-q:v",
"2",
"-",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("Failed to start persistent ffmpeg: {}", e))?;
let stdin = child.stdin.take().ok_or("Failed to get stdin")?;
let stdout = child.stdout.take().ok_or("Failed to get stdout")?;
*guard = Some(PersistentProcess {
child,
stdin,
stdout,
video_path: video_path.to_string(),
});
Ok(())
}
/// Extract a frame from the persistent ffmpeg process at the given time
///
/// Uses the persistent ffmpeg process to extract a frame at the specified
/// timestamp. This is faster than starting a new ffmpeg process for each frame.
///
/// # Arguments
/// * `time` - Timestamp in seconds to extract the frame from
///
/// # Returns
/// * `Ok(Vec<u8>)` - JPEG image data
/// * `Err(String)` - Error message if extraction fails
pub fn extract_frame_persistent(&self, time: f64) -> Result<Vec<u8>, String> {
let mut guard = self.persistent.lock().unwrap();
let proc = guard
.as_mut()
.ok_or("Persistent process not initialized. Call init_persistent() first.")?;
// Send seek command to ffmpeg
let seek_cmd = format!("seek {} 2\n", time);
proc.stdin
.write_all(seek_cmd.as_bytes())
.map_err(|e| format!("Failed to send seek command: {}", e))?;
proc.stdin
.flush()
.map_err(|e| format!("Failed to flush stdin: {}", e))?;
// Read JPEG data from stdout
let mut buffer = Vec::new();
let mut temp = [0u8; 65536];
let mut found_jpeg = false;
loop {
let n = proc
.stdout
.read(&mut temp)
.map_err(|e| format!("Failed to read frame data: {}", e))?;
if n == 0 {
break;
}
buffer.extend_from_slice(&temp[..n]);
// Check for JPEG end marker
if buffer.len() > 2 {
let last_two = &buffer[buffer.len() - 2..];
if last_two == [0xFF, 0xD9] {
found_jpeg = true;
break;
}
}
}
if buffer.is_empty() {
return Err("No frame data received from persistent process".to_string());
}
Ok(buffer)
}
/// Clean up the persistent ffmpeg process
///
/// Terminates the persistent ffmpeg process if it is currently running.
/// This is automatically called when the instance is dropped, but can be
/// called manually to release resources earlier.
pub fn cleanup_persistent(&self) {
let mut guard = self.persistent.lock().unwrap();
if let Some(mut proc) = guard.take() {
let _ = proc.child.kill();
}
}
/// Check if ffmpeg is available on the system
///
/// # Returns
/// * `true` if ffmpeg is available and executable
/// * `false` otherwise
pub fn is_available(&self) -> bool {
hidden_cmd(&self.bin_path)
.arg("-version")
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
/// Get ffmpeg version string
///
/// # Returns
/// * `Some(String)` - The ffmpeg version string
/// * `None` - If ffmpeg is not available or version cannot be determined
pub fn get_version(&self) -> Option<String> {
let output = hidden_cmd(&self.bin_path).arg("-version").output().ok()?;
if !output.status.success() {
return None;
}
let version = String::from_utf8_lossy(&output.stdout);
version.lines().next().map(|s| s.to_string())
}
/// Get complete video metadata from file path
///
/// Uses ffprobe to extract comprehensive metadata including video properties,
/// stream information, and file format details.
///
/// # Arguments
/// * `path` - Path to the video file
///
/// # Returns
/// * `Ok(VideoMetadata)` - Complete video metadata
/// * `Err(String)` - Error message if metadata extraction fails
pub fn get_video_metadata(&self, path: &str) -> Result<VideoMetadata, String> {
let path_obj = Path::new(path);
if !path_obj.exists() {
return Err(format!("File not found: {}", path_obj.display()));
}
let output = hidden_cmd(&self.probe_path)
.args([
"-v",
"quiet",
"-print_format",
"json",
"-show_streams",
"-show_format",
"-show_entries",
"stream=index,codec_name,codec_type,width,height,r_frame_rate,pix_fmt,color_space,bit_depth,nb_frames",
"-show_entries",
"stream=codec_tag_string,profile,level,has_b_frames,refs",
"-show_entries",
"format=format_name,format_long_name,size,creation_time,tags",
path,
])
.output()
.map_err(|e| format!("Failed to run ffprobe: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ffprobe failed: {}", stderr));
}
let json: serde_json::Value = serde_json::from_slice(&output.stdout)
.map_err(|e| format!("Failed to parse ffprobe output: {}", e))?;
let mut metadata = VideoMetadata::from_json(&json, path)?;
if let Ok(count) = self.get_keyframe_count(path) {
metadata.keyframe_count = Some(count);
}
Ok(metadata)
}
/// Get audio metadata from file path
///
/// Extracts comprehensive audio metadata including core information,
/// quality parameters, and ID3 tags using ffprobe.
///
/// # Arguments
/// * `path` - Path to the audio file
///
/// # Returns
/// * `Ok(AudioMetadata)` - Complete audio metadata
/// * `Err(String)` - Error message if metadata extraction fails
pub fn get_audio_metadata(&self, path: &str) -> Result<AudioMetadata, String> {
let output = hidden_cmd(&self.probe_path)
.args([
"-v",
"quiet",
"-print_format",
"json",
"-show_streams",
"-show_format",
path,
])
.output()
.map_err(|e| format!("ffprobe failed: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ffprobe failed: {}", stderr));
}
let json: serde_json::Value = serde_json::from_slice(&output.stdout)
.map_err(|e| format!("Failed to parse ffprobe output: {}", e))?;
AudioMetadata::from_json(&json, path)
}
/// Get image metadata from file path
///
/// Extracts image metadata including dimensions, frame rate,
/// and duration. GIF files get special handling for duration and fps.
///
/// # Arguments
/// * `path` - Path to the image file
/// * `is_gif` - Whether the file is a GIF animation
///
/// # Returns
/// * `Ok(ImageMetadata)` - Image metadata
/// * `Err(String)` - Error message if metadata extraction fails
pub fn get_image_metadata(&self, path: &str, is_gif: bool) -> Result<ImageMetadata, String> {
let info = self.get_video_metadata(path)?;
let width = info.width;
let height = info.height;
let fps = if is_gif { info.fps } else { 1.0 };
let duration = if is_gif { info.duration.max(0.1) } else { 5.0 };
Ok(ImageMetadata {
width,
height,
fps,
duration,
})
}
/// Extract a single frame from video at given time as JPEG bytes
///
/// This function starts a new ffmpeg process for each extraction.
/// For repeated extractions, consider using the persistent process.
///
/// # Arguments
/// * `video_path` - Path to the video file
/// * `time` - Timestamp in seconds to extract the frame from
///
/// # Returns
/// * `Ok(Vec<u8>)` - JPEG image data
/// * `Err(String)` - Error message if extraction fails
pub fn extract_frame(&self, video_path: &str, time: f64) -> Result<Vec<u8>, String> {
let output = hidden_cmd(&self.bin_path)
.args([
"-ss",
&time.to_string(),
"-i",
video_path,
"-vframes",
"1",
"-f",
"image2pipe",
"-vcodec",
"mjpeg",
"-",
])
.output()
.map_err(|e| format!("FFmpeg failed: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg error: {}", stderr));
}
if output.stdout.is_empty() {
return Err("No frame data received".to_string());
}
Ok(output.stdout)
}
/// Get the number of keyframes in a video file
///
/// Uses multiple methods to count keyframes, falling back to alternative
/// approaches if the primary method fails.
///
/// # Arguments
/// * `path` - Path to the video file
///
/// # Returns
/// * `Ok(u64)` - Number of keyframes
/// * `Err(String)` - Error message if counting fails
pub fn get_keyframe_count(&self, path: &str) -> Result<u64, String> {
if !Path::new(path).exists() {
return Err(format!("File not found: {}", path));
}
// Method 1: Count keyframes from packet flags
let output = hidden_cmd(&self.probe_path)
.args([
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"packet=flags",
"-of",
"csv=p=0",
path,
])
.output()
.map_err(|e| format!("Failed to get keyframes: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ffprobe failed: {}", stderr));
}
let stdout = String::from_utf8_lossy(&output.stdout);
let count = stdout.lines().filter(|line| line.contains('K')).count();
// Method 2: Fallback to frame analysis
if count == 0 {
let output2 = hidden_cmd(&self.probe_path)
.args([
"-v",
"error",
"-select_streams",
"v:0",
"-show_entries",
"frame=key_frame",
"-of",
"csv=p=0",
path,
])
.output()
.map_err(|e| format!("Failed to get keyframes (method 2): {}", e))?;
if output2.status.success() {
let stdout2 = String::from_utf8_lossy(&output2.stdout);
let count2 = stdout2.lines().filter(|line| line.trim() == "1").count();
return Ok(count2 as u64);
}
}
// Method 3: Use ffmpeg filter
if count == 0 {
let output3 = hidden_cmd(&self.bin_path)
.args([
"-i",
path,
"-vf",
"select='eq(pict_type,I)'",
"-vsync",
"0",
"-f",
"null",
"-",
])
.stderr(std::process::Stdio::piped())
.output()
.map_err(|e| format!("Failed to get keyframes (method 3): {}", e))?;
if !output3.status.success() {
let stderr = String::from_utf8_lossy(&output3.stderr);
for line in stderr.lines() {
if let Some(idx) = line.find("frame=") {
let rest = &line[idx + 6..];
if let Some(end) = rest.find(' ') {
if let Ok(num) = rest[..end].trim().parse::<u64>() {
return Ok(num);
}
}
}
}
}
}
Ok(count as u64)
}
/// Get video metadata as JSON value
///
/// # Arguments
/// * `path` - Path to the video file
///
/// # Returns
/// * `Ok(serde_json::Value)` - Video metadata as JSON
/// * `Err(String)` - Error message if serialization fails
pub fn get_video_info_json(&self, path: &str) -> Result<serde_json::Value, String> {
let metadata = self.get_video_metadata(path)?;
serde_json::to_value(&metadata)
.map_err(|e| format!("Failed to serialize video metadata: {}", e))
}
/// Create an empty video with black screen
///
/// Generates a synthetic video file with a black screen using the lavfi filter.
/// Useful for testing and placeholder videos.
///
/// # Arguments
/// * `output_path` - Path where the output video will be saved
/// * `duration` - Duration in seconds
/// * `width` - Video width in pixels
/// * `height` - Video height in pixels
/// * `fps` - Frames per second
///
/// # Returns
/// * `Ok(String)` - The output path on success
/// * `Err(String)` - Error message if creation fails
pub fn create_empty_video(
&self,
output_path: &str,
duration: f64,
width: u32,
height: u32,
fps: f64,
) -> Result<String, String> {
let path = Path::new(output_path);
if let Some(parent) = path.parent() {
if !parent.exists() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create output directory: {}", e))?;
}
}
let args = vec![
"-f".to_string(),
"lavfi".to_string(),
"-i".to_string(),
format!(
"color=c=black:s={}x{}:d={}:r={}",
width, height, duration, fps
),
"-c:v".to_string(),
"libx264".to_string(),
"-preset".to_string(),
"ultrafast".to_string(),
"-crf".to_string(),
"23".to_string(),
"-pix_fmt".to_string(),
"yuv420p".to_string(),
"-y".to_string(),
output_path.to_string(),
];
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("Failed to create empty video: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg failed: {}", stderr));
}
Ok(output_path.to_string())
}
/// Get duration of a media file in seconds
///
/// # Arguments
/// * `path` - Path to the media file
///
/// # Returns
/// * `Ok(f64)` - Duration in seconds
/// * `Err(String)` - Error message if duration cannot be determined
pub fn get_duration(&self, path: &str) -> Result<f64, String> {
let metadata = self.get_video_metadata(path)?;
Ok(metadata.duration)
}
/// Validate if the given file is a valid video file
///
/// # Arguments
/// * `path` - Path to the file to validate
///
/// # Returns
/// * `true` if the file is a valid video file
/// * `false` otherwise
pub fn validate_video(&self, path: &str) -> bool {
self.get_video_metadata(path).is_ok()
}
/// Generate a thumbnail from video at specified time
///
/// Extracts a single frame from the video at the specified time and saves
/// it as an image file. The output format is determined by the output_path extension.
///
/// # Arguments
/// * `input_path` - Path to the input video file
/// * `options` - Thumbnail generation options (time, size, output path)
///
/// # Returns
/// * `Ok(String)` - Path to the generated thumbnail
/// * `Err(String)` - Error message if generation fails
pub fn generate_thumbnail(
&self,
input_path: &str,
options: &ThumbnailOptions,
) -> Result<String, String> {
let input = Path::new(input_path);
if !input.exists() {
return Err(format!("Input file not found: {}", input_path));
}
let output_path = match &options.output_path {
Some(p) => PathBuf::from(p),
None => {
let stem = input.file_stem().unwrap_or_default();
let parent = input.parent().unwrap_or(Path::new("."));
parent.join(format!("{}_thumb.png", stem.to_string_lossy()))
}
};
let mut args = vec![
"-i".to_string(),
input_path.to_string(),
"-ss".to_string(),
format!("{}", options.time),
"-vframes".to_string(),
"1".to_string(),
];
if let Some(width) = options.width {
if let Some(height) = options.height {
args.push(format!("-s={}x{}", width, height));
} else {
args.push(format!("-vf=scale={}:-1", width));
}
} else if let Some(height) = options.height {
args.push(format!("-vf=scale=-1:{}", height));
}
args.push("-y".to_string());
args.push(output_path.to_string_lossy().to_string());
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("Failed to generate thumbnail: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg failed: {}", stderr));
}
Ok(output_path.to_string_lossy().to_string())
}
/// Extract the first frame of a video
///
/// Saves the first frame of the video as an image file. Useful for
/// generating preview thumbnails or cover images.
///
/// # Arguments
/// * `input_path` - Path to the input video file
/// * `output_path` - Path where the extracted frame will be saved
/// * `width` - Optional output width
/// * `height` - Optional output height
///
/// # Returns
/// * `Ok(())` on success
/// * `Err(String)` - Error message if extraction fails
pub fn get_first_frame(
&self,
input_path: &str,
output_path: &str,
width: Option<u32>,
height: Option<u32>,
) -> Result<(), String> {
if !Path::new(input_path).exists() {
return Err(format!("Input file not found: {}", input_path));
}
if let Some(parent) = Path::new(output_path).parent() {
if !parent.exists() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create output directory: {}", e))?;
}
}
let mut args = vec![
"-i".to_string(),
input_path.to_string(),
"-ss".to_string(),
"0".to_string(),
"-vframes".to_string(),
"1".to_string(),
];
if let (Some(w), Some(h)) = (width, height) {
args.push("-vf".to_string());
args.push(format!(
"scale={}:{}:force_original_aspect_ratio=decrease,pad={}:{}:(ow-iw)/2:(oh-ih)/2",
w, h, w, h
));
} else if let Some(w) = width {
args.push("-vf".to_string());
args.push(format!("scale={}:-1", w));
} else if let Some(h) = height {
args.push("-vf".to_string());
args.push(format!("scale=-1:{}", h));
}
args.push("-y".to_string());
args.push(output_path.to_string());
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("Failed to extract first frame: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg failed: {}", stderr));
}
Ok(())
}
/// Extract the last frame of a video
///
/// Saves the last frame of the video as an image file. Useful for
/// end-of-video previews or thumbnails.
///
/// # Arguments
/// * `input_path` - Path to the input video file
/// * `output_path` - Path where the extracted frame will be saved
/// * `width` - Optional output width
/// * `height` - Optional output height
///
/// # Returns
/// * `Ok(())` on success
/// * `Err(String)` - Error message if extraction fails
pub fn get_last_frame(
&self,
input_path: &str,
output_path: &str,
width: Option<u32>,
height: Option<u32>,
) -> Result<(), String> {
if !Path::new(input_path).exists() {
return Err(format!("Input file not found: {}", input_path));
}
if let Some(parent) = Path::new(output_path).parent() {
if !parent.exists() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create output directory: {}", e))?;
}
}
let mut args = vec![
"-sseof".to_string(),
"-1".to_string(),
"-i".to_string(),
input_path.to_string(),
"-vframes".to_string(),
"1".to_string(),
];
if let (Some(w), Some(h)) = (width, height) {
args.push("-vf".to_string());
args.push(format!(
"scale={}:{}:force_original_aspect_ratio=decrease,pad={}:{}:(ow-iw)/2:(oh-ih)/2",
w, h, w, h
));
} else if let Some(w) = width {
args.push("-vf".to_string());
args.push(format!("scale={}:-1", w));
} else if let Some(h) = height {
args.push("-vf".to_string());
args.push(format!("scale=-1:{}", h));
}
args.push("-y".to_string());
args.push(output_path.to_string());
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("Failed to extract last frame: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg failed: {}", stderr));
}
Ok(())
}
/// Extract frames from video with custom options
///
/// Extracts multiple frames from a video file using the specified options.
/// Supports custom frame rate, dimensions, start time, and duration.
///
/// # Arguments
/// * `input_path` - Path to the input video file
/// * `options` - Frame extraction options
///
/// # Returns
/// * `Ok(Vec<String>)` - List of extracted frame file paths
/// * `Err(String)` - Error message if extraction fails
pub fn extract_frames(
&self,
input_path: &str,
options: &FrameExtractOptions,
) -> Result<Vec<String>, String> {
if !Path::new(input_path).exists() {
return Err(format!("Input file not found: {}", input_path));
}
let output_dir = Path::new(&options.output_dir);
if !output_dir.exists() {
fs::create_dir_all(output_dir)
.map_err(|e| format!("Failed to create output directory: {}", e))?;
}
let pattern = options
.filename_pattern
.as_deref()
.unwrap_or("frame_%04d.png");
let mut args = vec!["-i".to_string(), input_path.to_string()];
if let Some(start) = options.start {
args.push("-ss".to_string());
args.push(start.to_string());
}
if let Some(duration) = options.duration {
args.push("-t".to_string());
args.push(duration.to_string());
}
let mut vf_parts = Vec::new();
if let Some(fps) = options.fps {
vf_parts.push(format!("fps={}", fps));
}
if let (Some(w), Some(h)) = (options.width, options.height) {
vf_parts.push(format!(
"scale={}:{}:force_original_aspect_ratio=decrease",
w, h
));
} else if let Some(w) = options.width {
vf_parts.push(format!("scale={}:-1", w));
} else if let Some(h) = options.height {
vf_parts.push(format!("scale=-1:{}", h));
}
if !vf_parts.is_empty() {
args.push("-vf".to_string());
args.push(vf_parts.join(","));
}
if options.format == "jpg" || options.format == "jpeg" {
let quality = options.quality.unwrap_or(85);
args.push("-q:v".to_string());
args.push(quality.to_string());
}
let output_pattern = output_dir.join(pattern);
let output_str = output_pattern.to_string_lossy().to_string();
let final_pattern = if output_str.contains("%") {
output_str
} else {
let stem = Path::new(&output_str).file_stem().unwrap_or_default();
let parent = Path::new(&output_str).parent().unwrap_or(Path::new("."));
let ext_str = if options.format == "jpg" || options.format == "jpeg" {
"jpg"
} else {
"png"
};
parent
.join(format!("{}_%04d.{}", stem.to_string_lossy(), ext_str))
.to_string_lossy()
.to_string()
};
args.push("-y".to_string());
args.push(final_pattern.clone());
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("Failed to extract frames: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg failed: {}", stderr));
}
let mut extracted_files = Vec::new();
let pattern_base = if final_pattern.contains("%") {
let base = final_pattern.split("%04d").next().unwrap_or("");
base.to_string()
} else {
final_pattern.clone()
};
if let Ok(entries) = fs::read_dir(output_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
let name = path.file_name().unwrap_or_default().to_string_lossy();
if name.starts_with(&pattern_base) || name.contains("frame_") {
extracted_files.push(path.to_string_lossy().to_string());
}
}
}
}
extracted_files.sort();
Ok(extracted_files)
}
/// Get the total number of frames in a video file
///
/// # Arguments
/// * `input_path` - Path to the video file
///
/// # Returns
/// * `Ok(u64)` - Total number of frames
/// * `Err(String)` - Error message if counting fails
pub fn get_frame_count(&self, input_path: &str) -> Result<u64, String> {
if !Path::new(input_path).exists() {
return Err(format!("Input file not found: {}", input_path));
}
let output = hidden_cmd(&self.probe_path)
.args([
"-v",
"error",
"-select_streams",
"v:0",
"-count_packets",
"-show_entries",
"stream=nb_read_packets",
"-of",
"default=noprint_wrappers=1:nokey=1",
input_path,
])
.output()
.map_err(|e| format!("Failed to get frame count: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("ffprobe failed: {}", stderr));
}
let stdout = String::from_utf8_lossy(&output.stdout);
stdout
.trim()
.parse::<u64>()
.map_err(|e| format!("Failed to parse frame count: {}", e))
}
/// Reset the persistent ffmpeg process
///
/// Kills the current persistent process and starts a new one with the
/// specified video file.
///
/// # Arguments
/// * `video_path` - Path to the video file
///
/// # Returns
/// * `Ok(())` on success
/// * `Err(String)` - Error message if reset fails
pub fn reset_persistent(&self, video_path: &str) -> Result<(), String> {
// Clean up existing persistent process
let mut guard = self.persistent.lock().unwrap();
if let Some(mut proc) = guard.take() {
let _ = proc.child.kill();
}
drop(guard);
// Initialize new persistent process
self.init_persistent(video_path)?;
Ok(())
}
/// Extract a single frame at the specified timestamp from a video file
///
/// Saves a single frame from the video at the given timestamp to the
/// specified output path with optional scaling and quality control.
///
/// # Arguments
/// * `source_path` - Path to the source video file
/// * `timestamp` - Timestamp in seconds to extract the frame from
/// * `output_path` - Path where the extracted frame will be saved
/// * `width` - Optional output width (None = use original size)
/// * `height` - Optional output height (None = use original size)
/// * `quality` - JPEG quality (1-31, lower is better, default 2)
///
/// # Returns
/// * `Ok(())` on success
/// * `Err(String)` - Error message if extraction fails
pub fn extract_frame_at(
&self,
source_path: &str,
timestamp: f64,
output_path: &Path,
width: Option<f64>,
height: Option<f64>,
quality: Option<u32>,
) -> Result<(), String> {
if !Path::new(source_path).exists() {
return Err(format!("Source file not found: {}", source_path));
}
if let Some(parent) = output_path.parent() {
if !parent.exists() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create output directory: {}", e))?;
}
}
let mut args = vec![
"-ss".to_string(),
timestamp.to_string(),
"-i".to_string(),
source_path.to_string(),
"-vframes".to_string(),
"1".to_string(),
];
// Build scale filter: only add if width or height is Some
// If both are None, no scaling is applied (use original size)
let scale_filter = match (width, height) {
(Some(w), Some(h)) => Some(format!(
"scale={}:{}:force_original_aspect_ratio=decrease,pad={}:{}:(ow-iw)/2:(oh-ih)/2",
w, h, w, h
)),
(Some(w), None) => Some(format!("scale={}:-1", w)),
(None, Some(h)) => Some(format!("scale=-1:{}", h)),
(None, None) => None, // No scaling - use original size
};
if let Some(filter) = scale_filter {
args.push("-vf".to_string());
args.push(filter);
}
let q = quality.unwrap_or(2);
args.push("-q:v".to_string());
args.push(q.to_string());
args.push("-y".to_string());
args.push(output_path.to_string_lossy().to_string());
let output = hidden_cmd(&self.bin_path)
.args(&args)
.output()
.map_err(|e| format!("FFmpeg failed: {}", e))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("FFmpeg error: {}", stderr));
}
Ok(())
}
}
/// Automatic cleanup of persistent ffmpeg process when Ffmpeg instance is dropped
///
/// This ensures that no orphaned ffmpeg processes remain, even if the instance
/// is dropped abruptly. The cleanup is graceful (sends 'q' command) but also
/// forcefully kills the process if it doesn't exit within 1 second.
impl Drop for Ffmpeg {
fn drop(&mut self) {
let mut guard = self.persistent.lock().unwrap();
if let Some(mut proc) = guard.take() {
// Send quit command to gracefully terminate ffmpeg
let _ = proc.stdin.write_all(b"q\n");
let _ = proc.stdin.flush();
// Wait up to 1 second for graceful exit
let start = std::time::Instant::now();
while start.elapsed() < std::time::Duration::from_secs(1) {
if let Ok(Some(_)) = proc.child.try_wait() {
break;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
// Force kill the process if it's still running
let _ = proc.child.kill();
let _ = proc.child.wait();
// Explicitly drop stdin/stdout to release resources early
drop(proc.stdin);
drop(proc.stdout);
}
drop(guard);
}
}