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
use super::{owned::*, AVResult};
use crate::ffi::*;
use std::fmt::Debug;
use std::path::Path;
#[derive(Copy, Clone, Default, Debug)]
pub struct FrameInfo {
pub codec_id: AVCodecID,
pub codec_type: AVMediaType,
}
pub struct FrameIter<'a> {
reader: &'a mut SimpleReader,
frame_infos: Vec<FrameInfo>,
}
impl<'a> Iterator for FrameIter<'a> {
type Item = (AVPacketOwned, FrameInfo);
fn next(&mut self) -> Option<Self::Item> {
if let Some(frame) = self.reader.read_frame() {
let stream_index = frame.stream_index as usize;
Some((frame, self.frame_infos[stream_index]))
} else {
None
}
}
}
impl<'a> FrameIter<'a> {
pub fn new(reader: &'a mut SimpleReader) -> Self {
let frame_infos: Vec<FrameInfo> = reader
.streams()
.iter()
.map(|stream| {
if let Some(codecpar) = stream.codecpar() {
FrameInfo {
codec_id: codecpar.codec_id,
codec_type: codecpar.codec_type,
}
} else {
FrameInfo::default()
}
})
.collect();
Self {
reader,
frame_infos,
}
}
}
/// Simple Reader for Demuxing Media Files.
#[derive(Debug)]
pub struct SimpleReader {
ctx: AVFormatContextOwned,
bsfs: Vec<AVBSFContextOwned>,
time_base: Option<AVRational>,
}
impl SimpleReader {
/// Create a new simple reader.
/// # Arguments
/// * `path` - Path of the input file.
/// * `format_options` - The options for demuxing format,like: movfragement.
/// * `time_unit` - Convert the pts, dts or duration to specified time unit,
// For example: convert to `us` unit: `time_unit=1000000`.
/// # Panics
///
pub fn open<P>(path: P, format_options: Option<&str>, time_unit: Option<i32>) -> AVResult<Self>
where
P: AsRef<Path> + Sized,
{
let ctx = AVFormatContextOwned::with_input(path, format_options)?;
let mut bsfs: Vec<AVBSFContextOwned> = vec![];
for stream in ctx.streams() {
if let Some(codecpar) = stream.codecpar() {
let filter_name = match codecpar.codec_tag {
AV_CODEC_TAG_AVC1 => "h264_mp4toannexb",
AV_CODEC_TAG_HEV1 | AV_CODEC_TAG_HVC1 => "hevc_mp4toannexb",
_ => "null",
};
let mut bsf = AVBSFContextOwned::new(filter_name)?;
bsf.prepare(Some(codecpar))?;
bsfs.push(bsf);
}
}
Ok(Self {
ctx,
bsfs,
time_base: time_unit.map(|x| AVRational::new(1, x)),
})
}
/// Returns the total stream bitrate in bit/s, 0 if not available.
pub fn bit_rate(&self) -> i64 {
self.ctx.bit_rate
}
/// Returns the duration of the stream.
pub fn duration(&self) -> i64 {
self.ctx.duration
}
/// Returns a list to describe the frame for each stream.
pub fn frame_infos(&self) -> Vec<FrameInfo> {
self.streams()
.iter()
.map(|stream| {
if let Some(codecpar) = stream.codecpar() {
FrameInfo {
codec_id: codecpar.codec_id,
codec_type: codecpar.codec_type,
}
} else {
FrameInfo::default()
}
})
.collect()
}
// Returns an iterator over the frames.
pub fn frames(&mut self) -> FrameIter<'_> {
FrameIter::new(self)
}
/// Return the next frame of a stream.
pub fn read_frame(&mut self) -> Option<AVPacketOwned> {
'outer: loop {
// Fetch frames from bitstream filter first.
for bsf in self.bsfs.iter_mut() {
match bsf.receive_packet() {
Ok(packet) => {
return Some(packet);
}
Err(err) => match err {
AVBSFError::Again => {}
AVBSFError::Reason(_) => {}
},
}
}
// Read frame from I/O context.
if let Some(mut packet) = self.ctx.read_frame() {
let stream_index = packet.stream_index as usize;
// Convert pts, dts, duratin to user specified.
if let (Some(out_time_base), Some(stream)) =
(self.time_base, self.ctx.streams().get(stream_index))
{
let in_time_base = stream.time_base;
let pts = unsafe {
av_rescale_q_rnd(
packet.pts,
in_time_base,
out_time_base,
AVRounding::new().near_inf().pass_min_max(),
)
};
let dts = unsafe {
av_rescale_q_rnd(
packet.dts,
in_time_base,
out_time_base,
AVRounding::new().near_inf().pass_min_max(),
)
};
let duration =
unsafe { av_rescale_q(packet.duration, in_time_base, out_time_base) };
packet.pts = pts;
packet.dts = dts;
packet.duration = duration;
}
// Send to bitstream filter.
if self.bsfs[stream_index].send_packet(&mut packet).is_err() {
break 'outer;
}
} else {
break 'outer;
}
}
None
}
/// Returns the position of the first frame of the component.
pub fn start_time(&self) -> i64 {
self.ctx.start_time
}
/// Returns then stream at index of the file.
pub fn stream(&self, index: usize) -> Option<&AVStream> {
self.streams().get(index).copied()
}
/// Returns a list of all streams in the file.
pub fn streams(&self) -> &[&AVStream] {
self.ctx.streams()
}
}