ffmpegx 0.1.7

Rust bindings for FFmpeg, providing common features such as frame sequence decoding and PCM data encoding/decoding.
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
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
use serde::{Deserialize, Serialize};
use std::process::{Child, ChildStdin, ChildStdout};
use uuid::Uuid;
/// Persistent ffmpeg process for fast frame extraction
///
/// Holds the child process handles and state for a persistent ffmpeg
/// process that can extract frames without restarting for each request.
pub struct PersistentProcess {
    /// Child process handle
    pub child: Child,
    /// Standard input pipe for sending commands
    pub stdin: ChildStdin,
    /// Standard output pipe for receiving frame data
    pub stdout: ChildStdout,
    /// Path of the video file currently loaded in the process
    pub video_path: String,
}
/// Thumbnail generation options
///
/// Controls the parameters for extracting a single frame as a thumbnail
/// image, including timestamp, dimensions, and output path.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThumbnailOptions {
    /// Timestamp in seconds to extract the frame from
    pub time: f64,
    /// Optional output width in pixels
    pub width: Option<u32>,
    /// Optional output height in pixels
    pub height: Option<u32>,
    /// Optional custom output path
    pub output_path: Option<String>,
}
/// Frame extraction options for batch processing
///
/// Controls the parameters for extracting multiple frames from a video,
/// including frame rate, time range, dimensions, and output format.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameExtractOptions {
    /// Output directory for extracted frames
    pub output_dir: String,
    /// Optional filename pattern (e.g., "frame_%04d.png")
    pub filename_pattern: Option<String>,
    /// Optional target frame rate for the output sequence
    pub fps: Option<f64>,
    /// Optional start time in seconds
    pub start: Option<f64>,
    /// Optional duration in seconds
    pub duration: Option<f64>,
    /// Optional output width in pixels
    pub width: Option<u32>,
    /// Optional output height in pixels
    pub height: Option<u32>,
    /// Output image format ("jpg", "jpeg", or "png")
    pub format: String,
    /// Optional quality setting for JPEG (1-100)
    pub quality: Option<u32>,
}
/// Preview quality levels for frame extraction
///
/// Controls the trade-off between image quality and file size
/// when extracting preview frames.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PreviewQuality {
    /// Best quality, largest file size (q=2)
    Excellent,
    /// High quality (q=6)
    High,
    /// Medium quality (q=10)
    Medium,
    /// Low quality (q=15)
    Low,
    /// Lowest quality, smallest file size (q=20)
    VeryLow,
}
impl PreviewQuality {
    /// Convert quality level to ffmpeg q:v value
    ///
    /// Returns the numeric q value used by ffmpeg's JPEG encoder,
    /// where lower numbers mean better quality and larger file sizes.
    ///
    /// # Returns
    /// * `u32` - The q value (1-31)
    pub fn as_q_value(&self) -> u32 {
        match self {
            PreviewQuality::Excellent => 2,
            PreviewQuality::High => 6,
            PreviewQuality::Medium => 10,
            PreviewQuality::Low => 15,
            PreviewQuality::VeryLow => 20,
        }
    }
}
/// Basic metadata structure for video files
///
/// Contains essential video information including dimensions,
/// duration, frame rate, codec, and bitrate.
#[derive(Debug, Clone)]
pub struct BasicMetadata {
    /// Duration in seconds
    pub duration: f64,
    /// Video width in pixels
    pub width: f64,
    /// Video height in pixels
    pub height: f64,
    /// Frames per second
    pub fps: f64,
    /// Codec name
    pub codec: String,
    /// Bitrate in bits per second
    pub bitrate: u64,
}
/// Image metadata structure
///
/// Contains information about image files including dimensions,
/// frame rate, and duration (useful for animated images like GIFs).
#[derive(Debug, Clone)]
pub struct ImageMetadata {
    /// Image width in pixels
    pub width: f64,
    /// Image height in pixels
    pub height: f64,
    /// Frames per second (1.0 for static images)
    pub fps: f64,
    /// Duration in seconds (5.0 default for static images)
    pub duration: f64,
}
// Audio Metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioMetadata {
    // ===== Core Information =====
    pub duration: f64,    // Duration in seconds
    pub sample_rate: u32, // Sample rate in Hz
    pub channels: u32,    // Number of audio channels
    pub codec: String,    // Audio codec name
    pub file_size: u64,   // File size in bytes
    // ===== Audio Quality =====
    pub bit_depth: Option<u32>,         // Bit depth (16, 24, 32)
    pub bitrate: Option<u64>,           // Bitrate in bps
    pub sample_format: Option<String>,  // Sample format (fltp, s16p, etc.)
    pub channel_layout: Option<String>, // Channel layout (stereo, 5.1, etc.)
    // ===== ID3 Metadata =====
    pub title: Option<String>,     // Track title
    pub artist: Option<String>,    // Artist name
    pub album: Option<String>,     // Album name
    pub genre: Option<String>,     // Music genre
    pub year: Option<u32>,         // Release year
    pub track_number: Option<u32>, // Track number
}
impl AudioMetadata {
    /// Parse audio metadata from ffprobe JSON output
    ///
    /// Extracts all available audio metadata from the ffprobe JSON
    /// output, including core information, quality parameters, and ID3 tags.
    ///
    /// # Arguments
    /// * `json` - The parsed ffprobe JSON output
    /// * `path` - Path to the audio file (for reference)
    ///
    /// # Returns
    /// * `Ok(Self)` - Complete audio metadata
    /// * `Err(String)` - Error message if parsing fails
    pub fn from_json(json: &serde_json::Value, path: &str) -> Result<Self, String> {
        let streams = json["streams"].as_array().ok_or("No streams found")?;
        let audio_stream = streams
            .iter()
            .find(|s| s["codec_type"].as_str() == Some("audio"))
            .ok_or("No audio stream found")?;
        let format = &json["format"];
        let duration = format["duration"]
            .as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .or_else(|| format["duration"].as_f64())
            .or_else(|| {
                audio_stream["duration"]
                    .as_str()
                    .and_then(|s| s.parse::<f64>().ok())
            })
            .or_else(|| audio_stream["duration"].as_f64())
            .unwrap_or(0.0);
        let sample_rate = audio_stream["sample_rate"]
            .as_str()
            .and_then(|s| s.parse::<u32>().ok())
            .or_else(|| audio_stream["sample_rate"].as_u64().map(|v| v as u32))
            .unwrap_or(0);
        let channels = audio_stream["channels"]
            .as_u64()
            .map(|v| v as u32)
            .unwrap_or(0);
        let codec = audio_stream["codec_name"]
            .as_str()
            .unwrap_or("unknown")
            .to_string();
        let file_size = format["size"]
            .as_str()
            .and_then(|s| s.parse::<u64>().ok())
            .or_else(|| format["size"].as_u64())
            .unwrap_or(0);
        let bit_depth = audio_stream["bits_per_sample"]
            .as_str()
            .and_then(|s| s.parse::<u32>().ok())
            .or_else(|| audio_stream["bits_per_sample"].as_u64().map(|v| v as u32));
        let bitrate = format["bit_rate"]
            .as_str()
            .and_then(|s| s.parse::<u64>().ok())
            .or_else(|| format["bit_rate"].as_u64())
            .or_else(|| {
                audio_stream["bit_rate"]
                    .as_str()
                    .and_then(|s| s.parse::<u64>().ok())
            })
            .or_else(|| audio_stream["bit_rate"].as_u64());
        let sample_format = audio_stream["sample_fmt"].as_str().map(|s| s.to_string());
        let channel_layout = audio_stream["channel_layout"]
            .as_str()
            .map(|s| s.to_string());
        let tags = format["tags"].as_object();
        let title = tags
            .and_then(|t| t.get("TITLE"))
            .or_else(|| tags.and_then(|t| t.get("title")))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let artist = tags
            .and_then(|t| t.get("ARTIST"))
            .or_else(|| tags.and_then(|t| t.get("artist")))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let album = tags
            .and_then(|t| t.get("ALBUM"))
            .or_else(|| tags.and_then(|t| t.get("album")))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let genre = tags
            .and_then(|t| t.get("GENRE"))
            .or_else(|| tags.and_then(|t| t.get("genre")))
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());
        let year = tags
            .and_then(|t| t.get("DATE"))
            .or_else(|| tags.and_then(|t| t.get("date")))
            .or_else(|| tags.and_then(|t| t.get("YEAR")))
            .or_else(|| tags.and_then(|t| t.get("year")))
            .and_then(|v| v.as_str())
            .and_then(|s| s.parse::<u32>().ok());
        let track_number = tags
            .and_then(|t| t.get("TRACK"))
            .or_else(|| tags.and_then(|t| t.get("track")))
            .and_then(|v| v.as_str())
            .and_then(|s| s.parse::<u32>().ok());
        Ok(Self {
            duration,
            sample_rate,
            channels,
            codec,
            file_size,
            bit_depth,
            bitrate,
            sample_format,
            channel_layout,
            title,
            artist,
            album,
            genre,
            year,
            track_number,
        })
    }
    /// Serialize audio metadata to JSON
    ///
    /// # Returns
    /// * `Ok(serde_json::Value)` - Serialized metadata as JSON
    /// * `Err(String)` - Error message if serialization fails
    pub fn to_json(&self) -> Result<serde_json::Value, String> {
        serde_json::to_value(self).map_err(|e| format!("Failed to serialize audio metadata: {}", e))
    }
}
// Video Metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VideoMetadata {
    // ===== Core Video Information =====
    pub width: f64,            // Video width in pixels
    pub height: f64,           // Video height in pixels
    pub duration: f64,         // Duration in seconds
    pub fps: f64,              // Frames per second
    pub bitrate: u64,          // Bitrate in bps
    pub codec: String,         // Video codec name
    pub resource_path: String, // Path to the resource file
    // ===== Video Properties =====
    pub aspect_ratio: Option<String>, // Aspect ratio (16:9, 4:3, etc.)
    pub pixel_format: Option<String>, // Pixel format (yuv420p, etc.)
    pub color_space: Option<String>,  // Color space
    pub bit_depth: Option<u32>,       // Bit depth (8, 10, 12)
    pub frame_count: Option<u64>,     // Total number of frames
    pub keyframe_count: Option<u64>,  // Number of keyframes
    // ===== Embedded Audio Track =====
    pub has_audio: bool,                // Whether the video has an audio track
    pub audio_codec: Option<String>,    // Audio codec name
    pub audio_sample_rate: Option<u32>, // Audio sample rate in Hz
    pub audio_channels: Option<u32>,    // Number of audio channels
    pub audio_bitrate: Option<u64>,     // Audio bitrate in bps
    // ===== File Information =====
    pub file_size: Option<u64>,           // File size in bytes
    pub container_format: Option<String>, // Container format (mp4, avi, etc.)
    pub creation_time: Option<String>,    // File creation time
    pub tags: Option<serde_json::Value>,  // Metadata tags
    // ===== Stream Indexes =====
    pub video_stream_index: Option<u32>, // Video stream index
    pub audio_stream_index: Option<u32>, // Audio stream index
    // ===== Track Timeline =====
    pub track_start_time: f64,    // Track start time on timeline
    pub track_end_time: f64,      // Track end time on timeline
    pub internal_start_time: f64, // Internal start time within the media
    pub internal_end_time: f64,   // Internal end time within the media
    // ===== Track Identity =====
    pub track_id: String,                // Unique track identifier
    pub track_block_id: String,          // Unique track block identifier
    pub visible: bool,                   // Whether the track is visible
    pub resource_frames: Option<String>, // Path to extracted frames
}
impl VideoMetadata {
    /// Parse video metadata from ffprobe JSON output
    ///
    /// Extracts all available video metadata from the ffprobe JSON
    /// output, including core information, video properties, audio
    /// track information, and file metadata.
    ///
    /// # Arguments
    /// * `json` - The parsed ffprobe JSON output
    /// * `path` - Path to the video file
    ///
    /// # Returns
    /// * `Ok(Self)` - Complete video metadata
    /// * `Err(String)` - Error message if parsing fails
    pub fn from_json(json: &serde_json::Value, path: &str) -> Result<Self, String> {
        let streams = json["streams"].as_array().ok_or("No streams found")?;
        let video_stream = streams
            .iter()
            .find(|s| s["codec_type"].as_str() == Some("video"))
            .ok_or("No video stream found")?;
        let audio_stream = streams
            .iter()
            .find(|s| s["codec_type"].as_str() == Some("audio"));
        let format = &json["format"];
        let width = video_stream["width"].as_f64().unwrap_or(0.0) as f64;
        let height = video_stream["height"].as_f64().unwrap_or(0.0) as f64;
        let fps_str = video_stream["r_frame_rate"].as_str().unwrap_or("0/0");
        let fps = parse_fraction(fps_str).unwrap_or(0.0);
        let codec = video_stream["codec_name"]
            .as_str()
            .unwrap_or("unknown")
            .to_string();
        let frame_count = video_stream["nb_frames"]
            .as_str()
            .and_then(|s| s.parse::<u64>().ok());
        let file_size = format["size"].as_str().and_then(|s| s.parse::<u64>().ok());
        let duration_from_frames = frame_count
            .and_then(|fc| {
                if fps > 0.0 {
                    Some(fc as f64 / fps)
                } else {
                    None
                }
            })
            .unwrap_or(0.0);
        let duration = format["duration"]
            .as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .or_else(|| format["duration"].as_f64())
            .or_else(|| {
                video_stream["duration"]
                    .as_str()
                    .and_then(|s| s.parse::<f64>().ok())
            })
            .or_else(|| video_stream["duration"].as_f64())
            .or_else(|| {
                if duration_from_frames > 0.0 {
                    Some(duration_from_frames)
                } else {
                    None
                }
            })
            .unwrap_or(0.0);
        let bitrate = format["bit_rate"]
            .as_str()
            .and_then(|s| s.parse::<u64>().ok())
            .or_else(|| format["bit_rate"].as_u64())
            .or_else(|| {
                video_stream["bit_rate"]
                    .as_str()
                    .and_then(|s| s.parse::<u64>().ok())
            })
            .or_else(|| video_stream["bit_rate"].as_u64())
            .unwrap_or(0);
        let mut final_bitrate = bitrate;
        if final_bitrate == 0 {
            if let Some(size) = file_size {
                let dur = if duration > 0.0 {
                    duration
                } else {
                    duration_from_frames
                };
                if dur > 0.0 {
                    final_bitrate = ((size as f64 * 8.0) / dur) as u64;
                }
            }
        }
        let aspect_ratio = if width > 0.0 && height > 0.0 {
            let gcd = gcd(width as u64, height as u64);
            Some(format!("{}:{}", width / gcd as f64, height / gcd as f64))
        } else {
            None
        };
        let pixel_format = video_stream["pix_fmt"].as_str().map(|s| s.to_string());
        let color_space = video_stream["color_space"].as_str().map(|s| s.to_string());
        let bit_depth = video_stream["bit_depth"].as_u64().map(|v| v as u32);
        let video_index = video_stream["index"].as_u64().map(|v| v as u32);
        let audio_index = audio_stream.and_then(|s| s["index"].as_u64().map(|v| v as u32));
        let container_format = format["format_name"].as_str().map(|s| s.to_string());
        let creation_time = format["creation_time"].as_str().map(|s| s.to_string());
        let tags = if let Some(tags_obj) = format["tags"].as_object() {
            Some(serde_json::Value::Object(tags_obj.clone()))
        } else {
            None
        };
        let has_audio = audio_stream.is_some();
        let audio_codec = audio_stream
            .and_then(|s| s["codec_name"].as_str())
            .map(|s| s.to_string());
        let audio_sample_rate = audio_stream
            .and_then(|s| s["sample_rate"].as_str())
            .and_then(|s| s.parse::<u32>().ok());
        let audio_channels = audio_stream
            .and_then(|s| s["channels"].as_u64())
            .map(|v| v as u32);
        let audio_bitrate = audio_stream
            .and_then(|s| s["bit_rate"].as_str())
            .and_then(|s| s.parse::<u64>().ok());
        Ok(Self {
            width,
            height,
            duration: if duration > 0.0 {
                duration
            } else {
                duration_from_frames
            },
            fps,
            bitrate: final_bitrate,
            codec,
            resource_path: path.to_string(),
            aspect_ratio,
            pixel_format,
            color_space,
            bit_depth,
            frame_count,
            keyframe_count: None,
            has_audio,
            audio_codec,
            audio_sample_rate,
            audio_channels,
            audio_bitrate,
            file_size,
            container_format,
            creation_time,
            tags,
            video_stream_index: video_index,
            audio_stream_index: audio_index,
            track_start_time: 0.0,
            track_end_time: 0.0,
            internal_start_time: 0.0,
            internal_end_time: duration,
            track_id: Uuid::new_v4().to_string(),
            track_block_id: Uuid::new_v4().to_string(),
            visible: true,
            resource_frames: None,
        })
    }
    /// Serialize video metadata to JSON
    ///
    /// # Returns
    /// * `Ok(serde_json::Value)` - Serialized metadata as JSON
    /// * `Err(String)` - Error message if serialization fails
    pub fn to_json(&self) -> Result<serde_json::Value, String> {
        serde_json::to_value(self).map_err(|e| format!("Failed to serialize video metadata: {}", e))
    }
}
fn gcd(a: u64, b: u64) -> u64 {
    if b == 0 { a } else { gcd(b, a % b) }
}
pub fn parse_fraction(s: &str) -> Option<f64> {
    if s.contains('/') {
        let parts: Vec<&str> = s.split('/').collect();
        if parts.len() == 2 {
            let num = parts[0].parse::<f64>().ok()?;
            let den = parts[1].parse::<f64>().ok()?;
            if den != 0.0 {
                return Some(num / den);
            }
        }
        None
    } else {
        s.parse::<f64>().ok()
    }
}
/// Hardware acceleration backend options
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HwAccel {
    /// No hardware acceleration (software decoding)
    #[default]
    None,
    /// NVIDIA CUDA/NVDEC
    Cuda,
    /// Intel QuickSync
    Qsv,
    /// Intel VA-API (Linux)
    Vaapi,
    /// Apple VideoToolbox (macOS)
    Videotoolbox,
    /// AMD AMF (Windows)
    Amf,
    /// Vulkan
    Vulkan,
    /// DirectX 11 (Windows)
    D3d11va,
    /// DirectX 12 (Windows)
    D3d12va,
}
// ffmpegx/types.rs - HwAccel
impl HwAccel {
    /// Returns the ffmpeg -hwaccel argument value
    pub fn as_str(&self) -> &'static str {
        match self {
            HwAccel::None => "",
            HwAccel::Cuda => "cuda",
            HwAccel::Qsv => "qsv",
            HwAccel::Vaapi => "vaapi",
            HwAccel::Videotoolbox => "videotoolbox",
            HwAccel::Amf => "amf",
            HwAccel::Vulkan => "vulkan",
            HwAccel::D3d11va => "d3d11va",
            HwAccel::D3d12va => "d3d12va",
        }
    }
    /// Returns the ffmpeg -hwaccel_device argument value (device type)
    pub fn device_type(&self) -> Option<&'static str> {
        match self {
            HwAccel::Cuda => Some("cuda"),
            HwAccel::Qsv => Some("qsv"),
            HwAccel::Vaapi => Some("vaapi"),
            HwAccel::Videotoolbox => Some("videotoolbox"),
            HwAccel::Amf => Some("amf"),
            HwAccel::Vulkan => Some("vulkan"),
            HwAccel::D3d11va => Some("d3d11va"),
            HwAccel::D3d12va => Some("d3d12va"),
            HwAccel::None => None,
        }
    }
    /// Get all hardware acceleration backends supported by this FFmpeg binary
    pub fn get_supported_backends(ffmpeg_path: &str) -> Vec<HwAccel> {
        let output = std::process::Command::new(ffmpeg_path)
            .arg("-hwaccels")
            .output();
        let output_str = match output {
            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
            _ => return Vec::new(),
        };
        let mut supported = Vec::new();
        for line in output_str.lines() {
            let line = line.trim();
            // Skip the header line
            if line.contains("Hardware acceleration methods:") || line.is_empty() {
                continue;
            }
            // Each line may contain multiple backends separated by spaces
            for part in line.split_whitespace() {
                let backend = match part {
                    "cuda" => HwAccel::Cuda,
                    "qsv" => HwAccel::Qsv,
                    "vaapi" => HwAccel::Vaapi,
                    "videotoolbox" => HwAccel::Videotoolbox,
                    "amf" => HwAccel::Amf,
                    "vulkan" => HwAccel::Vulkan,
                    "d3d11va" => HwAccel::D3d11va,
                    "d3d12va" => HwAccel::D3d12va,
                    "dxva2" => HwAccel::D3d11va, // DXVA2 is legacy, use D3D11VA
                    "opencl" => continue,        // OpenCL is not a decoding hwaccel
                    _ => continue,
                };
                supported.push(backend);
            }
        }
        supported
    }
    /// Auto-detect the best available hardware acceleration backend
    pub fn auto_detect() -> Self {
        // First, get FFmpeg binary path
        let ffmpeg_path = match crate::core::find_ffmpeg_path() {
            Some(p) => p,
            None => return HwAccel::None,
        };
        let supported = Self::get_supported_backends(&ffmpeg_path);
        if supported.is_empty() {
            return HwAccel::None;
        }
        // Priority order per platform
        #[cfg(target_os = "windows")]
        {
            // Priority: Cuda > D3d12va > D3d11va > Qsv
            let priorities = [
                HwAccel::Cuda,
                HwAccel::D3d12va,
                HwAccel::D3d11va,
                HwAccel::Qsv,
            ];
            for backend in priorities {
                if supported.contains(&backend) {
                    return backend;
                }
            }
        }
        #[cfg(target_os = "linux")]
        {
            // Priority: Cuda > Vaapi > Qsv
            let priorities = [HwAccel::Cuda, HwAccel::Vaapi, HwAccel::Qsv];
            for backend in priorities {
                if supported.contains(&backend) {
                    return backend;
                }
            }
        }
        #[cfg(target_os = "macos")]
        {
            if supported.contains(&HwAccel::Videotoolbox) {
                return HwAccel::Videotoolbox;
            }
        }
        // Fallback to first supported
        supported.into_iter().next().unwrap_or(HwAccel::None)
    }
    /// Check if this hardware acceleration backend is supported by FFmpeg
    pub fn is_supported_by_ffmpeg(&self, ffmpeg_path: &str) -> bool {
        let supported = Self::get_supported_backends(ffmpeg_path);
        supported.contains(self)
    }
}
/// Output frame format for decoding
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormatTypeEnum {
    /// JPEG format (lossy, smaller file size)
    Jpg,
    /// PNG format (lossless, larger file size)
    Png,
}
impl OutputFormatTypeEnum {
    pub fn as_str(&self) -> &str {
        match self {
            OutputFormatTypeEnum::Jpg => "jpg",
            OutputFormatTypeEnum::Png => "png",
        }
    }
    pub fn as_string(&self) -> String {
        match self {
            OutputFormatTypeEnum::Jpg => "jpg".to_string(),
            OutputFormatTypeEnum::Png => "png".to_string(),
        }
    }
}
/// YUV frame data structure
#[derive(Debug, Clone)]
pub struct YuvFrame {
    /// Y plane data (luminance)
    pub y: Vec<u8>,
    /// U plane data (chrominance blue-difference)
    pub u: Vec<u8>,
    /// V plane data (chrominance red-difference)
    pub v: Vec<u8>,
    /// Frame width
    pub width: u32,
    /// Frame height
    pub height: u32,
    /// Pixel format
    pub format: PixelFormat,
    /// Presentation timestamp
    pub pts: f64,
}
/// Pixel format enumeration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PixelFormat {
    YUV420P,
    NV12,
    RGB24,
}
impl YuvFrame {
    /// Convert YUV to RGB (CPU, for debug/testing)
    pub fn to_rgb(&self) -> Vec<u8> {
        let w = self.width as usize;
        let h = self.height as usize;
        let mut rgb = vec![0u8; w * h * 3];
        for y in 0..h {
            for x in 0..w {
                let y_idx = y * w + x;
                let uv_idx = (y / 2) * (w / 2) + (x / 2);
                let y_val = self.y[y_idx] as f32;
                let u_val = self.u[uv_idx] as f32 - 128.0;
                let v_val = self.v[uv_idx] as f32 - 128.0;
                let r = (y_val + 1.402 * v_val).clamp(0.0, 255.0) as u8;
                let g = (y_val - 0.344 * u_val - 0.714 * v_val).clamp(0.0, 255.0) as u8;
                let b = (y_val + 1.772 * u_val).clamp(0.0, 255.0) as u8;
                let rgb_idx = (y * w + x) * 3;
                rgb[rgb_idx] = r;
                rgb[rgb_idx + 1] = g;
                rgb[rgb_idx + 2] = b;
            }
        }
        rgb
    }
    /// Get total data size in bytes
    pub fn data_size(&self) -> usize {
        self.y.len() + self.u.len() + self.v.len()
    }
    /// Get Y plane size
    pub fn y_size(&self) -> usize {
        self.y.len()
    }
    /// Get U plane size
    pub fn u_size(&self) -> usize {
        self.u.len()
    }
    /// Get V plane size
    pub fn v_size(&self) -> usize {
        self.v.len()
    }
}