1 //! Demuxer definitions.
2 pub use crate::frame::*;
3 pub use crate::io::byteio::*;
4 pub use crate::options::*;
6 /// A list specifying general demuxing errors.
7 #[derive(Debug,Clone,Copy,PartialEq)]
9 pub enum DemuxerError {
10 /// Reader got to end of stream.
12 /// Demuxer encountered empty container.
14 /// Demuxer encountered invalid input data.
16 /// Data reading error.
18 /// Feature is not implemented.
20 /// Allocation failed.
22 /// The operation should be repeated.
26 /// Operation cannot succeed in principle (e.g. seeking in a format not supporting seeking).
30 /// A specialised `Result` type for demuxing operations.
31 pub type DemuxerResult<T> = Result<T, DemuxerError>;
33 /// A trait for demuxing operations.
34 pub trait DemuxCore<'a>: NAOptionHandler {
35 /// Opens the input stream, reads required headers and prepares everything for packet demuxing.
36 fn open(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()>;
38 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket>;
39 /// Seeks to the requested time.
40 fn seek(&mut self, time: u64, seek_idx: &SeekIndex) -> DemuxerResult<()>;
43 /// An auxiliary trait to make bytestream reader read packet data.
44 pub trait NAPacketReader {
45 /// Reads input and constructs a packet containing it.
46 fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, keyframe: bool, size: usize) -> DemuxerResult<NAPacket>;
47 /// Reads input into already existing packet.
48 fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()>;
51 impl<'a> NAPacketReader for ByteReader<'a> {
52 fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, kf: bool, size: usize) -> DemuxerResult<NAPacket> {
53 let mut buf: Vec<u8> = Vec::with_capacity(size);
54 if buf.capacity() < size { return Err(DemuxerError::MemoryError); }
56 self.read_buf(buf.as_mut_slice())?;
57 let pkt = NAPacket::new(str, ts, kf, buf);
60 fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()> {
61 let mut refbuf = pkt.get_buffer();
62 let buf = refbuf.as_mut().unwrap();
63 self.read_buf(buf.as_mut_slice())?;
68 /// An auxiliary structure for operations with individual streams inside the container.
70 pub struct StreamManager {
71 streams: Vec<NAStreamRef>,
77 /// Constructs a new instance of `StreamManager`.
78 pub fn new() -> Self {
85 /// Returns stream iterator.
86 pub fn iter(&self) -> StreamIter { StreamIter::new(&self.streams) }
88 /// Adds a new stream.
89 pub fn add_stream(&mut self, stream: NAStream) -> Option<usize> {
90 let stream_num = self.streams.len();
91 let mut str = stream.clone();
92 str.set_num(stream_num);
93 self.streams.push(str.into_ref());
94 self.ignored.push(false);
97 /// Returns stream with the requested index.
98 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
99 if idx < self.streams.len() {
100 Some(self.streams[idx].clone())
105 /// Returns stream with the requested stream ID.
106 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
107 for i in 0..self.streams.len() {
108 if self.streams[i].get_id() == id {
109 return Some(self.streams[i].clone());
114 /// Returns the number of known streams.
115 pub fn get_num_streams(&self) -> usize { self.streams.len() }
116 /// Reports whether the stream is marked as ignored.
117 pub fn is_ignored(&self, idx: usize) -> bool {
120 } else if idx < self.ignored.len() {
126 /// Reports whether the stream with certain ID is marked as ignored.
127 pub fn is_ignored_id(&self, id: u32) -> bool {
128 for i in 0..self.streams.len() {
129 if self.streams[i].get_id() == id {
130 return self.ignored[i];
135 /// Marks requested stream as ignored.
136 pub fn set_ignored(&mut self, idx: usize) {
137 if idx < self.ignored.len() {
138 self.ignored[idx] = true;
142 /// Clears the ignored mark for the requested stream.
143 pub fn set_unignored(&mut self, idx: usize) {
144 if idx < self.ignored.len() {
145 self.ignored[idx] = false;
151 pub struct StreamIter<'a> {
152 streams: &'a [NAStreamRef],
156 impl<'a> StreamIter<'a> {
157 /// Constructs a new instance of `StreamIter`.
158 pub fn new(streams: &'a [NAStreamRef]) -> Self {
159 StreamIter { streams, pos: 0 }
163 impl<'a> Iterator for StreamIter<'a> {
164 type Item = NAStreamRef;
166 fn next(&mut self) -> Option<Self::Item> {
167 if self.pos >= self.streams.len() { return None; }
168 let ret = self.streams[self.pos].clone();
175 #[derive(Clone,Copy,PartialEq)]
176 pub enum SeekIndexMode {
177 /// No seeking index present.
179 /// Seeking index is present.
181 /// Seeking index should be constructed by the demuxer if possible.
185 impl Default for SeekIndexMode {
186 fn default() -> Self { SeekIndexMode::None }
189 /// A structure holding seeking information.
190 #[derive(Clone,Copy,Default)]
191 pub struct SeekEntry {
192 /// Time in milliseconds.
196 /// Position in file.
200 /// Seeking information for individual streams.
202 pub struct StreamSeekInfo {
205 /// Index is present.
207 /// Packet seeking information.
208 pub entries: Vec<SeekEntry>,
211 impl StreamSeekInfo {
212 /// Constructs a new `StreamSeekInfo` instance.
213 pub fn new(id: u32) -> Self {
220 /// Adds new seeking point.
221 pub fn add_entry(&mut self, entry: SeekEntry) {
222 self.entries.push(entry);
224 /// Searches for an appropriate seek position before requested time.
225 pub fn find_pos(&self, time: u64) -> Option<SeekEntry> {
226 if !self.entries.is_empty() {
227 // todo something faster like binary search
229 for entry in self.entries.iter() {
230 if entry.time <= time {
243 /// Structure for holding seeking point search results.
244 #[derive(Clone,Copy,Default)]
245 pub struct SeekIndexResult {
248 /// Position in file.
254 /// Seek information for the whole container.
256 pub struct SeekIndex {
257 /// Seek information for individual streams.
258 pub seek_info: Vec<StreamSeekInfo>,
259 /// Seeking index mode.
260 pub mode: SeekIndexMode,
261 /// Ignore index flag.
262 pub skip_index: bool,
266 /// Constructs a new `SeekIndex` instance.
267 pub fn new() -> Self { Self::default() }
268 pub fn add_stream(&mut self, id: u32) -> usize {
269 let ret = self.stream_id_to_index(id);
271 self.seek_info.push(StreamSeekInfo::new(id));
272 self.seek_info.len() - 1
277 /// Adds a new stream to the index.
278 pub fn stream_id_to_index(&self, id: u32) -> Option<usize> {
279 for (idx, str) in self.seek_info.iter().enumerate() {
286 /// Returns stream reference for provided stream ID.
287 pub fn get_stream_index(&mut self, id: u32) -> Option<&mut StreamSeekInfo> {
288 for str in self.seek_info.iter_mut() {
295 /// Adds seeking information to the index.
296 pub fn add_entry(&mut self, id: u32, entry: SeekEntry) {
297 let mut idx = self.stream_id_to_index(id);
299 idx = Some(self.add_stream(id));
301 self.seek_info[idx.unwrap()].add_entry(entry);
302 self.seek_info[idx.unwrap()].filled = true;
304 /// Searches for a seek position before requested time.
305 pub fn find_pos(&self, time: u64) -> Option<SeekIndexResult> {
307 for str in self.seek_info.iter() {
308 if !str.filled { continue; }
309 let res = str.find_pos(time);
310 if res.is_none() { continue; }
311 let res = res.unwrap();
313 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
314 } else if let Some(entry) = cand {
315 if res.pos < entry.pos {
316 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
324 /// Demuxer structure with auxiliary data.
325 pub struct Demuxer<'a> {
326 dmx: Box<dyn DemuxCore<'a> + 'a>,
327 streams: StreamManager,
331 impl<'a> Demuxer<'a> {
332 /// Constructs a new `Demuxer` instance.
333 fn new(dmx: Box<dyn DemuxCore<'a> + 'a>, str: StreamManager, seek_idx: SeekIndex) -> Self {
340 /// Returns a stream reference by its number.
341 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
342 self.streams.get_stream(idx)
344 /// Returns a stream reference by its ID.
345 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
346 self.streams.get_stream_by_id(id)
348 /// Reports the total number of streams.
349 pub fn get_num_streams(&self) -> usize {
350 self.streams.get_num_streams()
352 /// Returns a reference to the internal stream manager.
353 pub fn get_stream_manager(&self) -> &StreamManager {
356 /// Returns an iterator over streams.
357 pub fn get_streams(&self) -> StreamIter {
360 /// Returns 'ignored' marker for requested stream.
361 pub fn is_ignored_stream(&self, idx: usize) -> bool {
362 self.streams.is_ignored(idx)
364 /// Sets 'ignored' marker for requested stream.
365 pub fn set_ignored_stream(&mut self, idx: usize) {
366 self.streams.set_ignored(idx)
368 /// Clears 'ignored' marker for requested stream.
369 pub fn set_unignored_stream(&mut self, idx: usize) {
370 self.streams.set_unignored(idx)
373 /// Demuxes a new packet from the container.
374 pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
376 let res = self.dmx.get_frame(&mut self.streams);
377 if self.streams.no_ign || res.is_err() { return res; }
378 let res = res.unwrap();
379 let idx = res.get_stream().get_num();
380 if !self.is_ignored_stream(idx) {
385 /// Seeks to the requested time (in milliseconds) if possible.
386 pub fn seek(&mut self, time: u64) -> DemuxerResult<()> {
387 if self.seek_idx.skip_index {
388 return Err(DemuxerError::NotPossible);
390 self.dmx.seek(time, &self.seek_idx)
392 /// Returns internal seek index.
393 pub fn get_seek_index(&self) -> &SeekIndex {
398 impl<'a> NAOptionHandler for Demuxer<'a> {
399 fn get_supported_options(&self) -> &[NAOptionDefinition] {
400 self.dmx.get_supported_options()
402 fn set_options(&mut self, options: &[NAOption]) {
403 self.dmx.set_options(options);
405 fn query_option_value(&self, name: &str) -> Option<NAValue> {
406 self.dmx.query_option_value(name)
410 impl From<ByteIOError> for DemuxerError {
411 fn from(_: ByteIOError) -> Self { DemuxerError::IOError }
414 /// The trait for creating demuxers.
415 pub trait DemuxerCreator {
416 /// Creates new demuxer instance that will use `ByteReader` source as an input.
417 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a>;
418 /// Returns the name of current demuxer creator (equal to the container name it can demux).
419 fn get_name(&self) -> &'static str;
422 /// Creates demuxer for a provided bytestream.
423 pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> DemuxerResult<Demuxer<'a>> {
424 let mut dmx = dmxcr.new_demuxer(br);
425 let mut str = StreamManager::new();
426 let mut seek_idx = SeekIndex::new();
427 dmx.open(&mut str, &mut seek_idx)?;
428 Ok(Demuxer::new(dmx, str, seek_idx))
431 /// List of registered demuxers.
433 pub struct RegisteredDemuxers {
434 dmxs: Vec<&'static DemuxerCreator>,
437 impl RegisteredDemuxers {
438 /// Constructs a new `RegisteredDemuxers` instance.
439 pub fn new() -> Self {
440 Self { dmxs: Vec::new() }
442 /// Registers a new demuxer.
443 pub fn add_demuxer(&mut self, dmx: &'static DemuxerCreator) {
446 /// Searches for a demuxer that supports requested container format.
447 pub fn find_demuxer(&self, name: &str) -> Option<&DemuxerCreator> {
448 for &dmx in self.dmxs.iter() {
449 if dmx.get_name() == name {