use std::fs::File;
use std::io::{Read, Seek, SeekFrom};
use std::path::Path;
use std::time::UNIX_EPOCH;
use alpha2_assets::{AudioStreamFacts, FrameRateEvidence};
use alpha2_container::{
AudioCodec, ContainerReader, DemuxError, TrackInfo, TrackKind, VideoCodec, VideoTrack,
};
use alpha2_media::{CancelToken, ColorMetadata, SampleAspectRatio};
use alpha2_model::{AudioStreamShape, MediaFingerprint, StreamTopology, VideoStreamShape};
use alpha2_time::FrameRate;
use serde::Serialize;
use sha2::{Digest, Sha256};
use crate::parameter_sets::{ParameterSetCodec, SequenceFacts, sequence_facts};
use crate::stills::{probe_still, still_format};
use crate::video_stream::to_media_time;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaProbe {
pub fingerprint: MediaFingerprint,
pub kind: ProbedKind,
pub has_audio: bool,
pub tracks: Vec<TrackFacts>,
pub audio_streams: Vec<AudioStreamFacts>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ProbedKind {
Video,
Audio,
Image,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TrackFacts {
pub kind: TrackFactsKind,
pub codec: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub duration_ticks: Option<i64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub title: Option<String>,
pub default: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub video: Option<VideoFacts>,
#[serde(skip_serializing_if = "Option::is_none")]
pub audio: Option<AudioFacts>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum TrackFactsKind {
Video,
Audio,
Other,
}
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VideoFacts {
pub coded_width: u32,
pub coded_height: u32,
pub rotation: u32,
pub mirror: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub sample_aspect_ratio: Option<Ratio>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bit_depth: Option<u32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub color: Option<ColorMetadata>,
#[serde(skip_serializing_if = "Option::is_none")]
pub nominal_frame_rate: Option<FrameRate>,
pub alpha: bool,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AudioFacts {
pub sample_rate: u32,
pub channels: u32,
#[serde(skip_serializing_if = "Option::is_none")]
pub bits_per_sample: Option<u16>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
pub struct Ratio {
pub num: u32,
pub den: u32,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProbeError {
Missing,
Unreadable(String),
Unsupported(String),
Cancelled,
}
impl std::fmt::Display for ProbeError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Missing => write!(formatter, "the file is missing"),
Self::Unreadable(reason) | Self::Unsupported(reason) => write!(formatter, "{reason}"),
Self::Cancelled => write!(formatter, "the probe was cancelled"),
}
}
}
impl std::error::Error for ProbeError {}
impl From<DemuxError> for ProbeError {
fn from(error: DemuxError) -> Self {
match error {
DemuxError::Unsupported(reason) => Self::Unsupported(reason),
error => Self::Unreadable(error.to_string()),
}
}
}
const HASH_BLOCK_BYTES: usize = 1 << 20;
const SNIFF_BYTES: u64 = 4096;
pub fn probe_file(path: &Path, hash: bool, cancel: &CancelToken) -> Result<MediaProbe, ProbeError> {
let metadata = match std::fs::metadata(path) {
Ok(metadata) if metadata.is_file() => metadata,
Ok(_) => return Err(ProbeError::Unreadable("the path is not a file".into())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
return Err(ProbeError::Missing);
}
Err(error) => return Err(unreadable(&error)),
};
let mut file = File::open(path).map_err(|error| unreadable(&error))?;
let mut head = Vec::new();
(&mut file)
.take(SNIFF_BYTES)
.read_to_end(&mut head)
.map_err(|error| unreadable(&error))?;
file.seek(SeekFrom::Start(0))
.map_err(|error| unreadable(&error))?;
let mut probe = if still_format(&head).is_some() {
probe_image(&mut file)?
} else {
let mut reader = alpha2_container::open_source(Box::new(file))?;
probe_container(reader.as_mut(), cancel)?
};
probe.fingerprint.byte_length = Some(metadata.len());
probe.fingerprint.modified_ms = metadata
.modified()
.ok()
.and_then(|time| time.duration_since(UNIX_EPOCH).ok())
.and_then(|since| i64::try_from(since.as_millis()).ok());
if hash {
probe.fingerprint.content_sha256 = Some(sha256(path, cancel)?);
}
Ok(probe)
}
pub fn sha256(path: &Path, cancel: &CancelToken) -> Result<String, ProbeError> {
let mut file = File::open(path).map_err(|error| match error.kind() {
std::io::ErrorKind::NotFound => ProbeError::Missing,
_ => unreadable(&error),
})?;
let mut hasher = Sha256::new();
let mut block = vec![0; HASH_BLOCK_BYTES];
loop {
if cancel.is_cancelled() {
return Err(ProbeError::Cancelled);
}
let read = match file.read(&mut block) {
Ok(0) => break,
Ok(read) => read,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(error) => return Err(unreadable(&error)),
};
hasher.update(&block[..read]);
}
Ok(hasher
.finalize()
.iter()
.fold(String::with_capacity(64), |mut hex, byte| {
use std::fmt::Write;
let _ = write!(hex, "{byte:02x}");
hex
}))
}
fn unreadable(error: &std::io::Error) -> ProbeError {
ProbeError::Unreadable(format!("cannot read the file: {error}"))
}
fn probe_image(file: &mut File) -> Result<MediaProbe, ProbeError> {
let mut bytes = Vec::new();
file.read_to_end(&mut bytes)
.map_err(|error| unreadable(&error))?;
let info = probe_still(&bytes).map_err(|error| ProbeError::Unreadable(error.to_string()))?;
let (width, height) = info.orientation.displayed_size(info.width, info.height);
Ok(MediaProbe {
fingerprint: MediaFingerprint {
streams: Some(StreamTopology {
video: Some(VideoStreamShape::new(width, height, None)),
audio: None,
}),
..MediaFingerprint::default()
},
kind: ProbedKind::Image,
has_audio: false,
tracks: vec![TrackFacts {
kind: TrackFactsKind::Video,
codec: info.format.as_str().to_ascii_lowercase(),
duration_ticks: None,
language: None,
title: None,
default: true,
video: Some(VideoFacts {
coded_width: info.width,
coded_height: info.height,
rotation: info.orientation.rotation.quarter_turns() * 90,
mirror: info.orientation.mirror,
sample_aspect_ratio: None,
bit_depth: None,
color: None,
nominal_frame_rate: None,
alpha: false,
}),
audio: None,
}],
audio_streams: Vec::new(),
})
}
#[derive(Clone, Copy, Debug)]
struct Span {
start: i64,
end: Option<i64>,
}
fn probe_container(
reader: &mut dyn ContainerReader,
cancel: &CancelToken,
) -> Result<MediaProbe, ProbeError> {
let tracks = reader.tracks().to_vec();
let video_index = reader.default_video();
let audio_index = reader
.default_audio()
.filter(|&index| tracks[index].audio.as_ref().is_some_and(decodable));
let mut spans = Vec::new();
let mut video_shape = None;
let mut color = None;
for (index, track) in tracks.iter().enumerate() {
match track.kind {
TrackKind::Video if Some(index) == video_index => {
let (span, rate) = video_presentation(reader, track, cancel)?;
spans.extend(span);
if let Some(video) = &track.video {
let sequence = sequence_of(video);
let (width, height) = visible_size(video, sequence.as_ref());
let aspect = sample_aspect_ratio(video, sequence.as_ref()).unwrap_or_default();
let (width, height) = aspect.square_pixel_size(width, height);
let (width, height) = video.orientation.displayed_size(width, height);
video_shape = Some(VideoStreamShape::new(width, height, rate));
color = declared_color(video, sequence.as_ref());
}
}
TrackKind::Video => spans.extend(first_video_presentation(reader, track, cancel)?),
TrackKind::Audio => spans.extend(audio_presentation(reader, track, cancel)?),
TrackKind::Other => {}
}
}
let audio_shape = audio_index
.and_then(|index| tracks[index].audio.as_ref())
.filter(|audio| audio.channels > 0 && audio.sample_rate > 0)
.map(|audio| AudioStreamShape::new(audio.channels, audio.sample_rate));
let has_audio = audio_shape.is_some();
let kind = if video_shape.is_some() {
ProbedKind::Video
} else if has_audio {
ProbedKind::Audio
} else {
return Err(ProbeError::Unsupported(
"the file has no video or audio track".into(),
));
};
let fingerprint = MediaFingerprint {
streams: Some(StreamTopology {
video: video_shape,
audio: audio_shape,
}),
duration_ticks: presentation_end(
&spans,
reader.file_duration().map(alpha2_time::MediaTime::ticks),
),
color,
..MediaFingerprint::default()
};
let audio_ordinal = audio_index.map(|index| {
tracks[..index]
.iter()
.filter(|track| track.kind == TrackKind::Audio)
.count()
});
let audio_streams = tracks
.iter()
.filter(|track| track.kind == TrackKind::Audio)
.enumerate()
.map(|(ordinal, track)| {
let mut facts = AudioStreamFacts::new(
track.audio.as_ref().map_or(0, |audio| audio.channels),
Some(ordinal) == audio_ordinal,
);
facts.codec = Some(track_codec(track));
facts.language.clone_from(&track.language);
facts.title.clone_from(&track.title);
facts
})
.collect();
Ok(MediaProbe {
fingerprint,
kind,
has_audio,
tracks: tracks.iter().map(track_facts).collect(),
audio_streams,
})
}
fn presentation_end(spans: &[Span], file_duration: Option<i64>) -> Option<i64> {
let start = spans.iter().map(|span| span.start).min()?;
let end = match file_duration {
Some(duration) => Some(start.saturating_add(duration)),
None => spans.iter().filter_map(|span| span.end).max(),
}?;
Some(end.max(0))
}
fn video_presentation(
reader: &mut dyn ContainerReader,
track: &TrackInfo,
cancel: &CancelToken,
) -> Result<(Option<Span>, Option<FrameRate>), ProbeError> {
reader.seek(track.id, i64::MIN)?;
let timescale = f64::from(track.timescale.max(1));
let mut evidence = FrameRateEvidence::new();
let mut first = None::<i64>;
while let Some(packet) = reader.next_packet(track.id)? {
if cancel.is_cancelled() {
return Err(ProbeError::Cancelled);
}
first = Some(first.map_or(packet.pts, |first| first.min(packet.pts)));
#[expect(
clippy::cast_precision_loss,
reason = "seconds need far fewer than 52 bits"
)]
let seconds = packet.pts as f64 / timescale;
if !evidence.push(seconds) {
break;
}
}
let span = first.map(|first| span_of(track, first));
Ok((span, evidence.rate()))
}
fn first_video_presentation(
reader: &mut dyn ContainerReader,
track: &TrackInfo,
cancel: &CancelToken,
) -> Result<Option<Span>, ProbeError> {
if cancel.is_cancelled() {
return Err(ProbeError::Cancelled);
}
reader.seek(track.id, i64::MIN)?;
let first = crate::video_stream::first_timestamps(reader, track)
.map_err(|error| ProbeError::Unreadable(error.to_string()))?
.into_iter()
.min();
Ok(first.map(|first| span_of(track, first)))
}
const fn decodable(audio: &alpha2_container::AudioTrack) -> bool {
!matches!(audio.codec, AudioCodec::Other(_))
}
fn audio_presentation(
reader: &mut dyn ContainerReader,
track: &TrackInfo,
cancel: &CancelToken,
) -> Result<Option<Span>, ProbeError> {
if cancel.is_cancelled() {
return Err(ProbeError::Cancelled);
}
reader.seek(track.id, i64::MIN)?;
let Some(packet) = reader.next_packet(track.id)? else {
return Ok(None);
};
let priming = track.audio.as_ref().map_or(0, |audio| {
rescale(
i64::from(audio.priming),
i64::from(track.timescale.max(1)),
i64::from(audio.sample_rate.max(1)),
)
});
Ok(Some(span_of(track, packet.pts.saturating_add(priming))))
}
fn span_of(track: &TrackInfo, first: i64) -> Span {
Span {
start: to_media_time(first, track.timescale).ticks(),
end: track
.duration
.map(|duration| to_media_time(first.saturating_add(duration), track.timescale).ticks()),
}
}
fn rescale(value: i64, numerator: i64, denominator: i64) -> i64 {
let scaled = i128::from(value) * i128::from(numerator) / i128::from(denominator.max(1));
i64::try_from(scaled).unwrap_or(i64::MAX)
}
fn sequence_of(video: &VideoTrack) -> Option<SequenceFacts> {
match video.codec {
VideoCodec::H264 => sequence_facts(ParameterSetCodec::H264, &video.codec_private),
VideoCodec::Hevc => sequence_facts(ParameterSetCodec::Hevc, &video.codec_private),
_ => None,
}
}
fn visible_size(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> (u32, u32) {
sequence
.and_then(|facts| facts.crop.visible())
.map_or((video.width, video.height), |rect| {
(rect.width, rect.height)
})
}
fn sample_aspect_ratio(
video: &VideoTrack,
sequence: Option<&SequenceFacts>,
) -> Option<SampleAspectRatio> {
video
.sample_aspect_ratio
.or_else(|| sequence.and_then(|facts| facts.vui.sample_aspect_ratio))
}
fn declared_color(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> Option<ColorMetadata> {
video
.color
.or_else(|| sequence.and_then(|facts| facts.vui.color))
}
fn bit_depth(video: &VideoTrack, sequence: Option<&SequenceFacts>) -> Option<u32> {
match video.codec {
VideoCodec::H264 | VideoCodec::Hevc => sequence.map(|facts| facts.bit_depth_luma),
VideoCodec::Vp9 => video
.codec_private
.get(6)
.map(|byte| u32::from(byte >> 4))
.filter(|depth| *depth > 0),
VideoCodec::Av1 => {
video
.codec_private
.get(2)
.map(|byte| match (byte & 0x40 != 0, byte & 0x20 != 0) {
(false, _) => 8,
(true, false) => 10,
(true, true) => 12,
})
}
_ => None,
}
}
fn track_facts(track: &TrackInfo) -> TrackFacts {
let video = track.video.as_ref().map(|video| {
let sequence = sequence_of(video);
VideoFacts {
coded_width: video.width,
coded_height: video.height,
rotation: video.orientation.rotation.quarter_turns() * 90,
mirror: video.orientation.mirror,
sample_aspect_ratio: sample_aspect_ratio(video, sequence.as_ref()).map(|ratio| Ratio {
num: ratio.num,
den: ratio.den,
}),
bit_depth: bit_depth(video, sequence.as_ref()),
color: declared_color(video, sequence.as_ref()),
nominal_frame_rate: video.frame_rate,
alpha: video.alpha,
}
});
TrackFacts {
kind: match track.kind {
TrackKind::Video => TrackFactsKind::Video,
TrackKind::Audio => TrackFactsKind::Audio,
TrackKind::Other => TrackFactsKind::Other,
},
codec: track_codec(track),
duration_ticks: track
.duration
.map(|duration| to_media_time(duration, track.timescale).ticks()),
language: track.language.clone(),
title: track.title.clone(),
default: track.default,
video,
audio: track.audio.as_ref().map(|audio| AudioFacts {
sample_rate: audio.sample_rate,
channels: audio.channels,
bits_per_sample: audio.bits_per_sample,
}),
}
}
fn track_codec(track: &TrackInfo) -> String {
if let Some(video) = &track.video {
return crate::video_stream::codec_name(video.codec);
}
let Some(audio) = &track.audio else {
return "unknown".into();
};
match audio.codec {
AudioCodec::Aac => "aac".into(),
AudioCodec::Mp3 => "mp3".into(),
AudioCodec::Opus => "opus".into(),
AudioCodec::Vorbis => "vorbis".into(),
AudioCodec::Flac => "flac".into(),
AudioCodec::Alac => "alac".into(),
AudioCodec::Pcm(format) => pcm_name(format),
AudioCodec::Ac3 => "ac3".into(),
AudioCodec::Eac3 => "eac3".into(),
AudioCodec::Dts => "dts".into(),
AudioCodec::Other(fourcc) => fourcc.to_string(),
}
}
fn pcm_name(format: alpha2_container::PcmFormat) -> String {
let kind = if format.float {
'f'
} else if format.signed {
's'
} else {
'u'
};
let endian = match (format.bits, format.big_endian) {
(8, _) => "",
(_, true) => "be",
(_, false) => "le",
};
format!("pcm_{kind}{}{endian}", format.bits)
}
#[cfg(test)]
#[path = "probe_tests.rs"]
mod tests;