av1converter 3.0.0

Batch convert video files to AV1 with FFmpeg, from a terminal UI or a daemon with a web UI
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
use crate::analyzer::metadata::{Hdr10StaticMetadata, HdrType, VideoMetadata};
use crate::error::AppError;
use crate::tracks::{AudioTrack, SubtitleTrack};
use serde::Deserialize;
use serde_json::Value;
use std::io::Read;
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

const FFPROBE_TIMEOUT: Duration = Duration::from_mins(2);
const FFPROBE_STDOUT_LIMIT: u64 = 16 * 1024 * 1024;
const FFPROBE_STDERR_LIMIT: u64 = 4 * 1024 * 1024;

/// Full analysis result with all tracks
#[derive(Debug)]
pub struct AnalysisResult {
    pub metadata: VideoMetadata,
    pub audio_tracks: Vec<AudioTrack>,
    pub subtitle_tracks: Vec<SubtitleTrack>,
    pub source_identity: crate::queue::SourceIdentity,
}

/// Analyze a video file using ffprobe
pub fn analyze(input_path: &str, cancel: &AtomicBool) -> Result<AnalysisResult, AppError> {
    let source_identity = crate::queue::SourceIdentity::from_path(input_path)
        .map_err(|e| AppError::Analysis(format!("Could not inspect source: {e}")))?;
    let metadata = analyze_video_stream(input_path, cancel)?;
    let (audio_tracks, subtitle_tracks) = analyze_tracks(input_path, cancel)?;
    if !source_identity.matches_path(input_path) {
        return Err(AppError::Analysis(
            "Source changed while it was being analyzed; add it again".to_string(),
        ));
    }

    Ok(AnalysisResult {
        metadata,
        audio_tracks,
        subtitle_tracks,
        source_identity,
    })
}

/// Duration of the first video stream of the file as it stands on disk, from
/// the stream, its `DURATION` tag, or the container. `None` when ffprobe
/// cannot say.
pub fn probe_duration_secs(path: &str, cancel: &AtomicBool) -> Option<f64> {
    let args = [
        "-v",
        "error",
        "-select_streams",
        "V:0",
        "-show_entries",
        "stream=width,height,duration:stream_tags=DURATION:format=duration",
        "-of",
        "json",
        path,
    ];

    let output = run_ffprobe(&args, cancel).ok()?;
    let data: FfprobeOutput = serde_json::from_str(&output).ok()?;
    let stream = data.streams.into_iter().next()?;
    let secs = video_duration_secs(&stream, data.format.as_ref());
    (secs > 0.0).then_some(secs)
}

/// Analyze the primary video stream
fn analyze_video_stream(input_path: &str, cancel: &AtomicBool) -> Result<VideoMetadata, AppError> {
    let args = [
        "-v",
        "error",
        "-select_streams",
        "V:0",
        "-show_entries",
        "stream=width,height,pix_fmt,color_primaries,color_transfer,color_space,codec_name,r_frame_rate,avg_frame_rate,bit_rate,duration:stream_tags=DURATION:stream_side_data_list:format=duration,bit_rate",
        "-of",
        "json",
        input_path,
    ];

    let output = run_ffprobe(&args, cancel)?;
    let data: FfprobeOutput = serde_json::from_str(&output)
        .map_err(|e| AppError::Analysis(format!("Failed to parse ffprobe output: {e}")))?;

    let stream = data
        .streams
        .into_iter()
        .next()
        .ok_or(AppError::NoVideoStream)?;

    // Check for Dolby Vision by inspecting the side_data_type field
    let dovi_entry = stream.side_data_list.as_ref().and_then(|list| {
        list.iter().find(|v| {
            v.get("side_data_type")
                .and_then(|t| t.as_str())
                .is_some_and(|t| {
                    t.eq_ignore_ascii_case("DOVI configuration record")
                        || t.contains("Dolby Vision")
                })
        })
    });
    let dv_profile = dovi_entry.and_then(|v| dovi_u8(v, "dv_profile"));
    let dv_bl_compat = dovi_entry.and_then(|v| dovi_u8(v, "dv_bl_signal_compatibility_id"));

    let hdr_type = hdr_type_of(
        dovi_entry.is_some(),
        dv_profile,
        stream.color_transfer.as_deref(),
    )?;

    // HDR10 static metadata: prefer container/stream-level side data; for
    // PQ/DV sources without it, probe the first frame (SEI-carried metadata)
    let mut hdr10_static = stream
        .side_data_list
        .as_deref()
        .and_then(parse_hdr10_static);
    if hdr10_static.is_none() && matches!(hdr_type, HdrType::Pq | HdrType::DolbyVision) {
        hdr10_static = probe_frame_hdr10_static(input_path, cancel);
    }

    // Parse frame rate. `avg_frame_rate` carries the playback rate;
    // `r_frame_rate` reports the field rate for interlaced streams and the
    // timebase ceiling for variable-frame-rate streams, and stands in only
    // when the average is absent or zero.
    let (frame_rate_num, frame_rate_den) = frame_rate_of(
        stream.avg_frame_rate.as_deref(),
        stream.r_frame_rate.as_deref(),
    );

    let duration_secs = video_duration_secs(&stream, data.format.as_ref());

    Ok(VideoMetadata {
        width: stream.width,
        height: stream.height,
        hdr_type,
        dv_profile,
        dv_bl_compat,
        hdr10_static,
        codec_name: stream.codec_name.unwrap_or_else(|| "unknown".to_string()),
        frame_rate_num,
        frame_rate_den,
        duration_secs,
    })
}

/// Read a small integer field from a DOVI configuration record.
fn dovi_u8(entry: &Value, key: &str) -> Option<u8> {
    let value = entry.get(key)?;
    if let Some(n) = value.as_u64() {
        return u8::try_from(n).ok();
    }
    value.as_str().and_then(|s| s.trim().parse::<u8>().ok())
}

/// Parse an ffprobe rational like `"35400/50000"` (or a plain number) to f64.
fn parse_rational(v: &Value) -> Option<f64> {
    if let Some(n) = v.as_f64() {
        return Some(n);
    }
    let s = v.as_str()?;
    if let Some((num, den)) = s.split_once('/') {
        let num = num.trim().parse::<f64>().ok()?;
        let den = den.trim().parse::<f64>().ok()?;
        if den != 0.0 {
            return Some(num / den);
        }
        return None;
    }
    s.trim().parse::<f64>().ok()
}

/// Extract HDR10 static metadata from a ffprobe `side_data_list`, if present.
fn parse_hdr10_static(side_data: &[Value]) -> Option<Hdr10StaticMetadata> {
    let mastering = side_data.iter().find(|v| {
        v.get("side_data_type")
            .and_then(|t| t.as_str())
            .is_some_and(|t| t.eq_ignore_ascii_case("Mastering display metadata"))
    })?;

    let coord = |key: &str| mastering.get(key).and_then(parse_rational);
    let red = (coord("red_x")?, coord("red_y")?);
    let green = (coord("green_x")?, coord("green_y")?);
    let blue = (coord("blue_x")?, coord("blue_y")?);
    let white_point = (coord("white_point_x")?, coord("white_point_y")?);
    let max_luminance = coord("max_luminance")?;
    let min_luminance = coord("min_luminance")?;

    let cll = side_data.iter().find(|v| {
        v.get("side_data_type")
            .and_then(|t| t.as_str())
            .is_some_and(|t| t.eq_ignore_ascii_case("Content light level metadata"))
    });
    let cll_val = |key: &str| {
        cll.and_then(|v| v.get(key))
            .and_then(Value::as_u64)
            .and_then(|n| u32::try_from(n).ok())
            .unwrap_or(0)
    };

    Some(Hdr10StaticMetadata {
        red,
        green,
        blue,
        white_point,
        max_luminance,
        min_luminance,
        max_cll: cll_val("max_content"),
        max_fall: cll_val("max_average"),
    })
}

/// Probe the first video frame for SEI-carried HDR10 static metadata
/// (sources that don't expose it at container level). Best-effort.
fn probe_frame_hdr10_static(input_path: &str, cancel: &AtomicBool) -> Option<Hdr10StaticMetadata> {
    let args = [
        "-v",
        "error",
        "-select_streams",
        "V:0",
        "-read_intervals",
        "%+#1",
        "-show_entries",
        "frame_side_data_list",
        "-of",
        "json",
        input_path,
    ];

    let output = run_ffprobe(&args, cancel).ok()?;
    let data: FramesOutput = serde_json::from_str(&output).ok()?;
    data.frames
        .iter()
        .filter_map(|f| f.side_data_list.as_deref())
        .find_map(parse_hdr10_static)
}

/// Duration of the primary video stream: its own duration or Matroska
/// `DURATION` tag, else the container duration, which spans every stream.
fn video_duration_secs(stream: &VideoStream, format: Option<&FormatInfo>) -> f64 {
    let positive = |secs: f64| (secs.is_finite() && secs > 0.0).then_some(secs);
    stream
        .duration
        .as_deref()
        .and_then(|d| d.parse::<f64>().ok())
        .and_then(positive)
        .or_else(|| {
            stream
                .tags
                .as_ref()
                .and_then(|tags| tags.duration.as_deref())
                .and_then(parse_timestamp_secs)
                .and_then(positive)
        })
        .or_else(|| {
            format
                .and_then(|f| f.duration.as_deref())
                .and_then(|d| d.parse::<f64>().ok())
                .and_then(positive)
        })
        .unwrap_or(0.0)
}

/// Parse an `HH:MM:SS.fraction` timestamp into seconds.
fn parse_timestamp_secs(value: &str) -> Option<f64> {
    let mut parts = value.trim().split(':');
    let hours = parts.next()?.parse::<f64>().ok()?;
    let minutes = parts.next()?.parse::<f64>().ok()?;
    let seconds = parts.next()?.parse::<f64>().ok()?;
    parts
        .next()
        .is_none()
        .then_some(hours * 3600.0 + minutes * 60.0 + seconds)
}

/// The HDR type of a stream, from its Dolby Vision side data and colour
/// transfer.
///
/// Dolby Vision without a readable profile is refused.
fn hdr_type_of(
    has_dovi: bool,
    dv_profile: Option<u8>,
    color_transfer: Option<&str>,
) -> Result<HdrType, AppError> {
    if has_dovi {
        if dv_profile.is_none() {
            return Err(AppError::Analysis(
                "Dolby Vision detected but dv_profile is missing; cannot choose a safe encode path"
                    .to_string(),
            ));
        }
        return Ok(HdrType::DolbyVision);
    }
    Ok(match color_transfer {
        Some("smpte2084") => HdrType::Pq,
        Some("arib-std-b67") => HdrType::Hlg,
        _ => HdrType::Sdr,
    })
}

/// The average frame rate, falling back to the real one when the average is
/// absent or zero, and to `0/1` when neither parses.
fn frame_rate_of(average: Option<&str>, real: Option<&str>) -> (u32, u32) {
    [average, real]
        .into_iter()
        .map(parse_frame_rate)
        .find(|&(num, _)| num > 0)
        .unwrap_or((0, 1))
}

fn parse_frame_rate(rate_str: Option<&str>) -> (u32, u32) {
    rate_str
        .and_then(|s| {
            let parts: Vec<&str> = s.split('/').collect();
            if parts.len() == 2 {
                let num = parts[0].parse::<u32>().ok()?;
                let den = parts[1].parse::<u32>().ok()?;
                if den > 0 {
                    return Some((num, den));
                }
            }
            None
        })
        .unwrap_or((0, 1))
}

/// Analyze audio and subtitle tracks
fn analyze_tracks(
    input_path: &str,
    cancel: &AtomicBool,
) -> Result<(Vec<AudioTrack>, Vec<SubtitleTrack>), AppError> {
    let args = [
        "-v",
        "error",
        "-show_entries",
        "stream=index,codec_type,codec_name,channels,channel_layout,bit_rate,sample_rate:stream_tags=language,title",
        "-select_streams",
        "a",
        "-of",
        "json",
        input_path,
    ];

    let output = run_ffprobe(&args, cancel)?;
    let audio_data: AllStreamsOutput = serde_json::from_str(&output)
        .map_err(|e| AppError::Analysis(format!("Failed to parse ffprobe audio output: {e}")))?;

    let args_sub = [
        "-v",
        "error",
        "-show_entries",
        "stream=index,codec_type,codec_name:stream_tags=language,title:stream_disposition=forced",
        "-select_streams",
        "s",
        "-of",
        "json",
        input_path,
    ];

    let output_sub = run_ffprobe(&args_sub, cancel)?;
    let sub_data: AllStreamsOutput = serde_json::from_str(&output_sub)
        .map_err(|e| AppError::Analysis(format!("Failed to parse ffprobe subtitle output: {e}")))?;

    let mut audio_tracks = Vec::new();
    let mut subtitle_tracks = Vec::new();

    for (audio_index, stream) in audio_data.streams.into_iter().enumerate() {
        audio_tracks.push(AudioTrack {
            index: audio_index,
            language: stream.tags.as_ref().and_then(|t| t.language.clone()),
            codec: stream.codec_name.unwrap_or_else(|| "unknown".to_string()),
            channels: stream.channels,
            channel_layout: stream.channel_layout,
            title: stream.tags.as_ref().and_then(|t| t.title.clone()),
            bitrate: stream.bit_rate.and_then(|b| b.parse::<u64>().ok()),
            sample_rate: stream.sample_rate.and_then(|s| s.parse::<u32>().ok()),
        });
    }

    for (subtitle_index, stream) in sub_data.streams.into_iter().enumerate() {
        let forced = stream
            .disposition
            .as_ref()
            .and_then(|d| d.forced)
            .unwrap_or(0)
            != 0;

        subtitle_tracks.push(SubtitleTrack {
            index: subtitle_index,
            language: stream.tags.as_ref().and_then(|t| t.language.clone()),
            codec: stream.codec_name.unwrap_or_else(|| "unknown".to_string()),
            title: stream.tags.as_ref().and_then(|t| t.title.clone()),
            forced,
        });
    }

    Ok((audio_tracks, subtitle_tracks))
}

/// Pixel format of the first video stream of `path`. `None` when ffprobe
/// cannot say.
pub fn probe_video_pix_fmt(path: &str, cancel: &AtomicBool) -> Option<String> {
    let args = [
        "-v",
        "error",
        "-select_streams",
        "V:0",
        "-show_entries",
        "stream=pix_fmt",
        "-of",
        "default=noprint_wrappers=1:nokey=1",
        path,
    ];
    let output = run_ffprobe(&args, cancel).ok()?;
    let pix_fmt = output.lines().next()?.trim();
    (!pix_fmt.is_empty() && pix_fmt != "unknown").then(|| pix_fmt.to_string())
}

/// Streams of a file that an encode does not pick by track selection.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnselectableStreams {
    /// Attached pictures such as cover art.
    pub pictures: usize,
    /// Attachment streams such as fonts.
    pub attachments: usize,
    /// Video streams after the first, data streams, and streams of any other
    /// kind.
    pub other: usize,
}

/// Count the streams of `path` that track selection does not cover. `None`
/// when ffprobe cannot say.
pub fn probe_unselectable_streams(path: &str, cancel: &AtomicBool) -> Option<UnselectableStreams> {
    let args = [
        "-v",
        "error",
        "-show_entries",
        "stream=codec_type:stream_disposition=attached_pic",
        "-of",
        "json",
        path,
    ];
    let output = run_ffprobe(&args, cancel).ok()?;
    let data: AllStreamsOutput = serde_json::from_str(&output).ok()?;
    Some(unselectable_streams(&data.streams))
}

fn unselectable_streams(streams: &[RawStream]) -> UnselectableStreams {
    let mut counts = UnselectableStreams {
        pictures: 0,
        attachments: 0,
        other: 0,
    };
    let mut videos = 0usize;
    for stream in streams {
        let picture = stream
            .disposition
            .as_ref()
            .and_then(|d| d.attached_pic)
            .unwrap_or(0)
            != 0;
        match stream.codec_type.as_deref() {
            _ if picture => counts.pictures += 1,
            Some("video") => videos += 1,
            Some("audio" | "subtitle") => {}
            Some("attachment") => counts.attachments += 1,
            _ => counts.other += 1,
        }
    }
    counts.other += videos.saturating_sub(1);
    counts
}

/// Run ffprobe with arguments
fn run_ffprobe(args: &[&str], cancel: &AtomicBool) -> Result<String, AppError> {
    let mut command = Command::new("ffprobe");
    command.args(args);
    let output = run_command(&mut command, cancel, FFPROBE_TIMEOUT)?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(AppError::Analysis(format!("ffprobe failed: {stderr}")));
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Run a probe, aborting it on cancellation or once `timeout` elapses.
fn run_command(
    command: &mut Command,
    cancel: &AtomicBool,
    timeout: Duration,
) -> Result<std::process::Output, AppError> {
    if cancel.load(Ordering::Acquire) {
        return Err(AppError::Cancelled);
    }
    command.stdout(Stdio::piped()).stderr(Stdio::piped());
    let (mut child, _child) = crate::utils::child::spawn(command)
        .map_err(|e| AppError::Analysis(format!("Failed to execute ffprobe: {e}")))?;
    let mut stdout = child.stdout.take().expect("piped stdout");
    let mut stderr = child.stderr.take().expect("piped stderr");
    let stdout_reader = std::thread::spawn(move || read_capped(&mut stdout, FFPROBE_STDOUT_LIMIT));
    let stderr_reader = std::thread::spawn(move || read_capped(&mut stderr, FFPROBE_STDERR_LIMIT));
    let started = Instant::now();
    let status = loop {
        if cancel.load(Ordering::Acquire) || started.elapsed() >= timeout {
            let cancelled = cancel.load(Ordering::Acquire);
            crate::utils::child::kill_and_wait(&mut child);
            let _ = stdout_reader.join();
            let _ = stderr_reader.join();
            return Err(if cancelled {
                AppError::Cancelled
            } else {
                AppError::Analysis("ffprobe timed out".to_string())
            });
        }
        match child.try_wait() {
            Ok(Some(status)) => {
                crate::utils::child::ChildGuard::unregister(child.id());
                break status;
            }
            Ok(None) => std::thread::sleep(Duration::from_millis(50)),
            Err(e) => {
                crate::utils::child::kill_and_wait(&mut child);
                let _ = stdout_reader.join();
                let _ = stderr_reader.join();
                return Err(AppError::Analysis(format!(
                    "Failed to wait for ffprobe: {e}"
                )));
            }
        }
    };
    let (stdout, stdout_limited) = stdout_reader
        .join()
        .map_err(|_| AppError::Analysis("ffprobe stdout reader panicked".to_string()))?
        .map_err(|e| AppError::Analysis(format!("Failed to read ffprobe stdout: {e}")))?;
    let (stderr, stderr_limited) = stderr_reader
        .join()
        .map_err(|_| AppError::Analysis("ffprobe stderr reader panicked".to_string()))?
        .map_err(|e| AppError::Analysis(format!("Failed to read ffprobe stderr: {e}")))?;
    if stdout_limited || stderr_limited {
        return Err(AppError::Analysis(
            "ffprobe produced too much output; refusing to exhaust memory".to_string(),
        ));
    }
    Ok(std::process::Output {
        status,
        stdout,
        stderr,
    })
}

fn read_capped(reader: &mut impl Read, limit: u64) -> std::io::Result<(Vec<u8>, bool)> {
    let mut bytes = Vec::new();
    reader.take(limit + 1).read_to_end(&mut bytes)?;
    let exceeded = bytes.len() as u64 > limit;
    if exceeded {
        bytes.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
    }
    Ok((bytes, exceeded))
}

// JSON deserialization structures

#[derive(Debug, Deserialize)]
struct FfprobeOutput {
    streams: Vec<VideoStream>,
    format: Option<FormatInfo>,
}

#[derive(Debug, Deserialize)]
struct FormatInfo {
    duration: Option<String>,
}

#[derive(Debug, Deserialize)]
struct VideoStream {
    width: u32,
    height: u32,
    codec_name: Option<String>,
    color_transfer: Option<String>,
    r_frame_rate: Option<String>,
    avg_frame_rate: Option<String>,
    side_data_list: Option<Vec<Value>>,
    duration: Option<String>,
    tags: Option<VideoTags>,
}

#[derive(Debug, Deserialize)]
struct VideoTags {
    #[serde(rename = "DURATION")]
    duration: Option<String>,
}

#[derive(Debug, Deserialize)]
struct FramesOutput {
    #[serde(default)]
    frames: Vec<FrameInfo>,
}

#[derive(Debug, Deserialize)]
struct FrameInfo {
    side_data_list: Option<Vec<Value>>,
}

#[derive(Debug, Deserialize)]
struct AllStreamsOutput {
    streams: Vec<RawStream>,
}

#[derive(Debug, Deserialize)]
struct RawStream {
    codec_type: Option<String>,
    codec_name: Option<String>,
    channels: Option<u16>,
    channel_layout: Option<String>,
    bit_rate: Option<String>,
    sample_rate: Option<String>,
    tags: Option<StreamTags>,
    disposition: Option<StreamDisposition>,
}

#[derive(Debug, Deserialize)]
struct StreamTags {
    language: Option<String>,
    title: Option<String>,
}

/// Stream disposition flags
#[derive(Debug, Deserialize)]
struct StreamDisposition {
    forced: Option<u8>,
    attached_pic: Option<u8>,
}

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

    /// Dolby Vision decides the type when its profile is readable, and is
    /// refused when it is not; otherwise the colour transfer decides.
    #[test]
    fn the_hdr_type_follows_dolby_vision_then_the_colour_transfer() {
        assert_eq!(
            hdr_type_of(true, Some(8), Some("smpte2084")).unwrap(),
            HdrType::DolbyVision
        );
        assert_eq!(
            hdr_type_of(true, Some(5), None).unwrap(),
            HdrType::DolbyVision
        );
        assert!(matches!(
            hdr_type_of(true, None, Some("smpte2084")),
            Err(AppError::Analysis(_))
        ));
        assert_eq!(
            hdr_type_of(false, None, Some("smpte2084")).unwrap(),
            HdrType::Pq
        );
        assert_eq!(
            hdr_type_of(false, None, Some("arib-std-b67")).unwrap(),
            HdrType::Hlg
        );
        assert_eq!(
            hdr_type_of(false, None, Some("bt709")).unwrap(),
            HdrType::Sdr
        );
        assert_eq!(hdr_type_of(false, None, None).unwrap(), HdrType::Sdr);
        // A profile with no side data is not Dolby Vision.
        assert_eq!(hdr_type_of(false, Some(8), None).unwrap(), HdrType::Sdr);
    }

    /// A well-formed `num/den` parses; anything else reads as unknown.
    #[test]
    fn frame_rates_parse_only_as_a_positive_fraction() {
        assert_eq!(parse_frame_rate(Some("24000/1001")), (24000, 1001));
        assert_eq!(parse_frame_rate(Some("25/1")), (25, 1));
        assert_eq!(parse_frame_rate(Some("0/0")), (0, 1));
        assert_eq!(parse_frame_rate(Some("30/0")), (0, 1));
        assert_eq!(parse_frame_rate(Some("30")), (0, 1));
        assert_eq!(parse_frame_rate(Some("-30/1")), (0, 1));
        assert_eq!(parse_frame_rate(Some("a/b")), (0, 1));
        assert_eq!(parse_frame_rate(Some("")), (0, 1));
        assert_eq!(parse_frame_rate(None), (0, 1));
    }

    /// The real frame rate stands in only when the average gives nothing.
    #[test]
    fn the_real_frame_rate_only_fills_in_for_a_missing_average() {
        assert_eq!(
            frame_rate_of(Some("24000/1001"), Some("60/1")),
            (24000, 1001)
        );
        assert_eq!(frame_rate_of(Some("0/0"), Some("60/1")), (60, 1));
        assert_eq!(frame_rate_of(None, Some("60/1")), (60, 1));
        assert_eq!(frame_rate_of(Some("nonsense"), Some("60/1")), (60, 1));
        assert_eq!(frame_rate_of(None, None), (0, 1));
        assert_eq!(frame_rate_of(Some("0/0"), Some("0/0")), (0, 1));
    }

    #[test]
    fn unselectable_streams_count_extra_video_data_pictures_and_attachments() {
        let json = r#"{
            "stream_groups": [{"streams": [{"codec_type": "video"}, {"codec_type": "data"}]}],
            "streams": [
                {"codec_type": "video", "disposition": {"attached_pic": 0}},
                {"codec_type": "audio", "disposition": {"attached_pic": 0}},
                {"codec_type": "subtitle", "disposition": {"attached_pic": 0}},
                {"codec_type": "video", "disposition": {"attached_pic": 1}},
                {"codec_type": "attachment"},
                {"codec_type": "video", "disposition": {"attached_pic": 0}},
                {"codec_type": "data", "disposition": {"attached_pic": 0}}
            ]
        }"#;
        let data: AllStreamsOutput = serde_json::from_str(json).unwrap();
        assert_eq!(
            unselectable_streams(&data.streams),
            UnselectableStreams {
                pictures: 1,
                attachments: 1,
                other: 2,
            }
        );
    }

    #[test]
    fn a_single_video_stream_with_audio_and_subtitles_has_nothing_unselectable() {
        let json = r#"{"streams": [
            {"codec_type": "video", "disposition": {"attached_pic": 0}},
            {"codec_type": "audio", "disposition": {"attached_pic": 0}},
            {"codec_type": "subtitle", "disposition": {"attached_pic": 0}}
        ]}"#;
        let data: AllStreamsOutput = serde_json::from_str(json).unwrap();
        assert_eq!(
            unselectable_streams(&data.streams),
            UnselectableStreams {
                pictures: 0,
                attachments: 0,
                other: 0,
            }
        );
    }

    #[test]
    fn parses_hdr10_static_from_real_ffprobe_json() {
        // Captured from `ffprobe -show_entries stream_side_data_list` (FFmpeg 8)
        let side_data: Vec<Value> = serde_json::from_str(
            r#"[
                {"side_data_type": "Content light level metadata",
                 "max_content": 1000, "max_average": 400},
                {"side_data_type": "Mastering display metadata",
                 "red_x": "35400/50000", "red_y": "14600/50000",
                 "green_x": "8500/50000", "green_y": "39850/50000",
                 "blue_x": "6550/50000", "blue_y": "2300/50000",
                 "white_point_x": "15635/50000", "white_point_y": "16450/50000",
                 "min_luminance": "50/10000", "max_luminance": "10000000/10000"}
            ]"#,
        )
        .unwrap();

        let hdr10 = parse_hdr10_static(&side_data).unwrap();
        assert!((hdr10.red.0 - 0.708).abs() < 1e-9);
        assert!((hdr10.green.1 - 0.797).abs() < 1e-9);
        assert!((hdr10.max_luminance - 1000.0).abs() < 1e-9);
        assert!((hdr10.min_luminance - 0.005).abs() < 1e-9);
        assert_eq!(hdr10.max_cll, 1000);
        assert_eq!(hdr10.max_fall, 400);
        assert_eq!(hdr10.svt_content_light().as_deref(), Some("1000,400"));
        assert_eq!(
            hdr10.svt_mastering_display(),
            "G(0.17000,0.79700)B(0.13100,0.04600)R(0.70800,0.29200)\
             WP(0.31270,0.32900)L(1000.0000,0.0050)"
        );
    }

    /// A Matroska video stream carries its length only as a tag; the container
    /// duration also spans an audio track that runs past the video.
    #[test]
    fn source_duration_is_the_video_stream_not_the_container() {
        let parse = |json: &str| {
            let data: FfprobeOutput = serde_json::from_str(json).unwrap();
            let stream = data.streams.into_iter().next().unwrap();
            video_duration_secs(&stream, data.format.as_ref())
        };
        let mkv = r#"{"streams": [{"width": 320, "height": 240,
            "tags": {"DURATION": "00:01:40.000000000"}}],
            "format": {"duration": "104.005000"}}"#;
        assert!((parse(mkv) - 100.0).abs() < 1e-9);

        let mp4 = r#"{"streams": [{"width": 320, "height": 240, "duration": "99.5"}],
            "format": {"duration": "104.0"}}"#;
        assert!((parse(mp4) - 99.5).abs() < 1e-9);

        let untagged = r#"{"streams": [{"width": 320, "height": 240}],
            "format": {"duration": "104.0"}}"#;
        assert!((parse(untagged) - 104.0).abs() < 1e-9);

        let infinite = r#"{"streams": [{"width": 320, "height": 240,
            "tags": {"DURATION": "inf:00:00"}}],
            "format": {"duration": "104.0"}}"#;
        assert!((parse(infinite) - 104.0).abs() < 1e-9);
    }

    #[test]
    fn dovi_record_carries_the_base_layer_compatibility_id() {
        let entry: Value = serde_json::from_str(
            r#"{"side_data_type": "DOVI configuration record", "dv_profile": 8, "dv_bl_signal_compatibility_id": 4}"#,
        )
        .unwrap();
        assert_eq!(dovi_u8(&entry, "dv_profile"), Some(8));
        assert_eq!(dovi_u8(&entry, "dv_bl_signal_compatibility_id"), Some(4));
        let as_string: Value = serde_json::from_str(
            r#"{"side_data_type": "DOVI configuration record", "dv_profile": "5"}"#,
        )
        .unwrap();
        assert_eq!(dovi_u8(&as_string, "dv_profile"), Some(5));
    }

    #[test]
    fn missing_mastering_display_yields_none() {
        let side_data: Vec<Value> = serde_json::from_str(
            r#"[{"side_data_type": "DOVI configuration record", "dv_profile": 8}]"#,
        )
        .unwrap();
        assert!(parse_hdr10_static(&side_data).is_none());
    }

    #[test]
    fn probe_output_reader_stops_at_its_memory_limit() {
        let mut input = std::io::Cursor::new(b"12345");
        let (bytes, exceeded) = read_capped(&mut input, 4).unwrap();
        assert_eq!(bytes, b"1234");
        assert!(exceeded);
    }

    /// Cancellation is reported as its own error, not as an stderr message.
    #[test]
    fn a_cancelled_probe_reports_cancellation_exactly() {
        let cancel = AtomicBool::new(true);
        let error =
            run_command(&mut Command::new("ffprobe"), &cancel, FFPROBE_TIMEOUT).unwrap_err();
        assert!(matches!(error, AppError::Cancelled));
    }

    #[cfg(unix)]
    #[test]
    fn probe_process_is_killed_at_its_deadline() {
        let mut command = Command::new("sh");
        command.args(["-c", "exec sleep 5"]);
        let cancel = AtomicBool::new(false);
        let error = run_command(&mut command, &cancel, Duration::from_millis(10)).unwrap_err();
        assert!(error.to_string().contains("timed out"));
    }
}