use std::time::Duration;
use super::ClipInfo;
pub(super) fn parse(json: &[u8]) -> Option<ClipInfo> {
let document: serde_json::Value = serde_json::from_slice(json).ok()?;
let no_streams = Vec::new();
let streams = document["streams"].as_array().unwrap_or(&no_streams);
let mut has_audio = false;
let mut dimensions: Option<(u32, u32)> = None;
let mut streamed: Option<f64> = None;
let mut pictured: Option<f64> = None;
let mut sounded: Option<f64> = None;
for stream in streams {
match stream["codec_type"].as_str() {
Some("audio") => {
has_audio = true;
if let Some(seconds) = seconds(stream["duration"].as_str()) {
sounded = Some(sounded.map_or(seconds, |longest| longest.max(seconds)));
}
}
Some("video") if stream["disposition"]["attached_pic"].as_u64() != Some(1) => {
if let Some(seconds) = seconds(stream["duration"].as_str()) {
pictured = Some(pictured.map_or(seconds, |longest| longest.max(seconds)));
}
if dimensions.is_none()
&& let (Some(width), Some(height)) =
(side(&stream["width"]), side(&stream["height"]))
{
dimensions = Some(upright(width, height, rotation(stream)));
}
}
_ => {}
}
if let Some(seconds) = seconds(stream["duration"].as_str()) {
streamed = Some(streamed.map_or(seconds, |longest| longest.max(seconds)));
}
}
let duration = seconds(document["format"]["duration"].as_str()).or(streamed)?;
let duration = Duration::try_from_secs_f64(duration).ok()?;
let stream_length = |seconds: Option<f64>| {
seconds
.and_then(|seconds| Duration::try_from_secs_f64(seconds).ok())
.map(|length| length.min(duration))
};
Some(ClipInfo {
duration,
dimensions,
has_audio,
picture: stream_length(pictured),
sound: stream_length(sounded),
bytes: 0,
})
}
fn side(value: &serde_json::Value) -> Option<u32> {
u32::try_from(value.as_u64()?).ok().filter(|side| *side > 0)
}
fn seconds(value: Option<&str>) -> Option<f64> {
let seconds: f64 = value?.parse().ok()?;
(seconds.is_finite() && seconds >= 0.0).then_some(seconds)
}
fn rotation(stream: &serde_json::Value) -> i64 {
let from_matrix = stream["side_data_list"]
.as_array()
.into_iter()
.flatten()
.find_map(|side_data| side_data["rotation"].as_f64());
if let Some(degrees) = from_matrix {
#[expect(
clippy::cast_possible_truncation,
reason = "a container's rotation is a whole number of degrees"
)]
return degrees.round() as i64;
}
stream["tags"]["rotate"]
.as_str()
.and_then(|tag| tag.parse().ok())
.unwrap_or(0)
}
fn upright(width: u32, height: u32, rotation: i64) -> (u32, u32) {
if rotation.rem_euclid(180) == 90 {
(height, width)
} else {
(width, height)
}
}
#[cfg(test)]
mod tests {
use super::*;
const CLIP: &str = r#"{
"streams": [
{"index": 0, "codec_type": "video", "width": 1280, "height": 720,
"tags": {}, "disposition": {"attached_pic": 0}},
{"index": 1, "codec_type": "audio", "tags": {},
"disposition": {"attached_pic": 0}}
],
"format": {"duration": "2.008000"}
}"#;
#[test]
fn a_clip_reports_its_duration_size_and_audio() {
let info = parse(CLIP.as_bytes()).expect("a clip is readable");
assert_eq!(info.duration, Duration::from_millis(2008));
assert_eq!(info.dimensions, Some((1280, 720)));
assert!(info.has_audio);
assert_eq!(info.sound, None);
let cover = r#"{
"streams": [
{"codec_type": "audio", "duration": "2.000000",
"disposition": {"attached_pic": 0}},
{"codec_type": "video", "width": 200, "height": 200,
"duration": "2.000000", "disposition": {"attached_pic": 1}}
],
"format": {"duration": "2.000000"}
}"#;
let info = parse(cover.as_bytes()).expect("an audio file is readable");
assert_eq!(info.dimensions, None, "a cover is not the file's video");
assert!(info.has_audio);
}
#[test]
fn a_quarter_turn_reports_the_upright_size() {
for (rotation, expected) in [(90, (720, 1280)), (-90, (720, 1280)), (270, (720, 1280))] {
let document = format!(
r#"{{"streams": [{{"codec_type": "video", "width": 1280, "height": 720,
"side_data_list": [{{"rotation": {rotation}}}]}}],
"format": {{"duration": "2.0"}}}}"#
);
let info = parse(document.as_bytes()).expect("a rotated clip is readable");
assert_eq!(info.dimensions, Some(expected), "rotation {rotation}");
}
let upside_down = br#"{"streams": [{"codec_type": "video", "width": 1280, "height": 720,
"side_data_list": [{"rotation": 180}]}],
"format": {"duration": "2.0"}}"#;
assert_eq!(
parse(upside_down).expect("readable").dimensions,
Some((1280, 720))
);
let tagged = br#"{"streams": [{"codec_type": "video", "width": 640, "height": 480,
"tags": {"rotate": "90"}}], "format": {"duration": "2.0"}}"#;
assert_eq!(
parse(tagged).expect("readable").dimensions,
Some((480, 640))
);
}
#[test]
fn what_ffprobe_cannot_name_is_undecodable() {
assert_eq!(parse(b"{\n\n}"), None);
assert_eq!(parse(b""), None);
assert_eq!(parse(b"not json at all"), None);
let empty = parse(br#"{"format": {"duration": "2.0"}}"#).expect("a timed container");
assert_eq!(empty.duration, Duration::from_secs(2));
assert_eq!(empty.dimensions, None);
assert!(!empty.has_audio);
let absurd = br#"{"streams": [{"codec_type": "video", "width": 2, "height": 2}],
"format": {"duration": "1e30"}}"#;
assert_eq!(parse(absurd), None, "a duration no Duration holds");
}
#[test]
fn a_stream_that_stops_early_reports_its_own_length() {
let document = br#"{
"streams": [
{"codec_type": "video", "width": 640, "height": 480, "duration": "5.000000"},
{"codec_type": "audio", "duration": "10.000000"}
],
"format": {"duration": "40.000000"}
}"#;
let info = parse(document).expect("a readable container");
assert_eq!(info.duration, Duration::from_secs(40));
assert_eq!(info.sound, Some(Duration::from_secs(10)));
assert_eq!(info.picture, Some(Duration::from_secs(5)));
}
#[test]
fn the_duration_falls_back_to_the_longest_stream() {
let document = br#"{
"streams": [
{"codec_type": "audio", "duration": "3.500000"},
{"codec_type": "audio", "duration": "4.250000"},
{"codec_type": "video", "width": 640, "height": 480, "duration": "N/A"}
],
"format": {"duration": "N/A"}
}"#;
let info = parse(document).expect("stream durations time the file");
assert_eq!(info.duration, Duration::from_millis(4250));
assert_eq!(info.dimensions, Some((640, 480)));
}
}