1 //! Demuxer definitions.
2 pub use crate::frame::*;
3 pub use crate::io::byteio::*;
5 /// A list specifying general demuxing errors.
6 #[derive(Debug,Clone,Copy,PartialEq)]
8 pub enum DemuxerError {
9 /// Reader got to end of stream.
11 /// Demuxer encountered empty container.
13 /// Demuxer encountered invalid input data.
15 /// Data reading error.
17 /// Feature is not implemented.
19 /// Allocation failed.
21 /// The operation should be repeated.
25 /// Operation cannot succeed in principle (e.g. seeking in a format not supporting seeking).
29 /// A specialised `Result` type for demuxing operations.
30 pub type DemuxerResult<T> = Result<T, DemuxerError>;
32 /// A trait for demuxing operations.
33 pub trait DemuxCore<'a> {
34 /// Opens the input stream, reads required headers and prepares everything for packet demuxing.
35 fn open(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()>;
37 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket>;
38 /// Seeks to the requested time.
39 fn seek(&mut self, time: u64, seek_idx: &SeekIndex) -> DemuxerResult<()>;
42 /// An auxiliary trait to make bytestream reader read packet data.
43 pub trait NAPacketReader {
44 /// Reads input and constructs a packet containing it.
45 fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, keyframe: bool, size: usize) -> DemuxerResult<NAPacket>;
46 /// Reads input into already existing packet.
47 fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()>;
50 impl<'a> NAPacketReader for ByteReader<'a> {
51 fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, kf: bool, size: usize) -> DemuxerResult<NAPacket> {
52 let mut buf: Vec<u8> = Vec::with_capacity(size);
53 if buf.capacity() < size { return Err(DemuxerError::MemoryError); }
55 self.read_buf(buf.as_mut_slice())?;
56 let pkt = NAPacket::new(str, ts, kf, buf);
59 fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()> {
60 let mut refbuf = pkt.get_buffer();
61 let buf = refbuf.as_mut().unwrap();
62 self.read_buf(buf.as_mut_slice())?;
67 /// An auxiliary structure for operations with individual streams inside the container.
69 pub struct StreamManager {
70 streams: Vec<NAStreamRef>,
76 /// Constructs a new instance of `StreamManager`.
77 pub fn new() -> Self {
84 /// Returns stream iterator.
85 pub fn iter(&self) -> StreamIter { StreamIter::new(&self.streams) }
87 /// Adds a new stream.
88 pub fn add_stream(&mut self, stream: NAStream) -> Option<usize> {
89 let stream_num = self.streams.len();
90 let mut str = stream.clone();
91 str.set_num(stream_num);
92 self.streams.push(str.into_ref());
93 self.ignored.push(false);
96 /// Returns stream with the requested index.
97 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
98 if idx < self.streams.len() {
99 Some(self.streams[idx].clone())
104 /// Returns stream with the requested stream ID.
105 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
106 for i in 0..self.streams.len() {
107 if self.streams[i].get_id() == id {
108 return Some(self.streams[i].clone());
113 /// Returns the number of known streams.
114 pub fn get_num_streams(&self) -> usize { self.streams.len() }
115 /// Reports whether the stream is marked as ignored.
116 pub fn is_ignored(&self, idx: usize) -> bool {
119 } else if idx < self.ignored.len() {
125 /// Reports whether the stream with certain ID is marked as ignored.
126 pub fn is_ignored_id(&self, id: u32) -> bool {
127 for i in 0..self.streams.len() {
128 if self.streams[i].get_id() == id {
129 return self.ignored[i];
134 /// Marks requested stream as ignored.
135 pub fn set_ignored(&mut self, idx: usize) {
136 if idx < self.ignored.len() {
137 self.ignored[idx] = true;
141 /// Clears the ignored mark for the requested stream.
142 pub fn set_unignored(&mut self, idx: usize) {
143 if idx < self.ignored.len() {
144 self.ignored[idx] = false;
150 pub struct StreamIter<'a> {
151 streams: &'a [NAStreamRef],
155 impl<'a> StreamIter<'a> {
156 /// Constructs a new instance of `StreamIter`.
157 pub fn new(streams: &'a [NAStreamRef]) -> Self {
158 StreamIter { streams, pos: 0 }
162 impl<'a> Iterator for StreamIter<'a> {
163 type Item = NAStreamRef;
165 fn next(&mut self) -> Option<Self::Item> {
166 if self.pos >= self.streams.len() { return None; }
167 let ret = self.streams[self.pos].clone();
174 #[derive(Clone,Copy,PartialEq)]
175 pub enum SeekIndexMode {
176 /// No seeking index present.
178 /// Seeking index is present.
180 /// Seeking index should be constructed by the demuxer if possible.
184 impl Default for SeekIndexMode {
185 fn default() -> Self { SeekIndexMode::None }
188 /// A structure holding seeking information.
189 #[derive(Clone,Copy,Default)]
190 pub struct SeekEntry {
191 /// Time in milliseconds.
195 /// Position in file.
199 /// Seeking information for individual streams.
201 pub struct StreamSeekInfo {
204 /// Index is present.
206 /// Packet seeking information.
207 pub entries: Vec<SeekEntry>,
210 impl StreamSeekInfo {
211 /// Constructs a new `StreamSeekInfo` instance.
212 pub fn new(id: u32) -> Self {
219 /// Adds new seeking point.
220 pub fn add_entry(&mut self, entry: SeekEntry) {
221 self.entries.push(entry);
223 /// Searches for an appropriate seek position before requested time.
224 pub fn find_pos(&self, time: u64) -> Option<SeekEntry> {
225 if !self.entries.is_empty() {
226 // todo something faster like binary search
228 for entry in self.entries.iter() {
229 if entry.time <= time {
242 /// Structure for holding seeking point search results.
243 #[derive(Clone,Copy,Default)]
244 pub struct SeekIndexResult {
247 /// Position in file.
253 /// Seek information for the whole container.
255 pub struct SeekIndex {
256 /// Seek information for individual streams.
257 pub seek_info: Vec<StreamSeekInfo>,
258 /// Seeking index mode.
259 pub mode: SeekIndexMode,
260 /// Ignore index flag.
261 pub skip_index: bool,
265 /// Constructs a new `SeekIndex` instance.
266 pub fn new() -> Self { Self::default() }
267 pub fn add_stream(&mut self, id: u32) -> usize {
268 let ret = self.stream_id_to_index(id);
270 self.seek_info.push(StreamSeekInfo::new(id));
271 self.seek_info.len() - 1
276 /// Adds a new stream to the index.
277 pub fn stream_id_to_index(&self, id: u32) -> Option<usize> {
278 for (idx, str) in self.seek_info.iter().enumerate() {
285 /// Returns stream reference for provided stream ID.
286 pub fn get_stream_index(&mut self, id: u32) -> Option<&mut StreamSeekInfo> {
287 for str in self.seek_info.iter_mut() {
294 /// Adds seeking information to the index.
295 pub fn add_entry(&mut self, id: u32, entry: SeekEntry) {
296 let mut idx = self.stream_id_to_index(id);
298 idx = Some(self.add_stream(id));
300 self.seek_info[idx.unwrap()].add_entry(entry);
301 self.seek_info[idx.unwrap()].filled = true;
303 /// Searches for a seek position before requested time.
304 pub fn find_pos(&self, time: u64) -> Option<SeekIndexResult> {
306 for str in self.seek_info.iter() {
307 if !str.filled { continue; }
308 let res = str.find_pos(time);
309 if res.is_none() { continue; }
310 let res = res.unwrap();
312 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
313 } else if let Some(entry) = cand {
314 if res.pos < entry.pos {
315 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
323 /// Demuxer structure with auxiliary data.
324 pub struct Demuxer<'a> {
325 dmx: Box<dyn DemuxCore<'a> + 'a>,
326 streams: StreamManager,
330 impl<'a> Demuxer<'a> {
331 /// Constructs a new `Demuxer` instance.
332 fn new(dmx: Box<dyn DemuxCore<'a> + 'a>, str: StreamManager, seek_idx: SeekIndex) -> Self {
339 /// Returns a stream reference by its number.
340 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
341 self.streams.get_stream(idx)
343 /// Returns a stream reference by its ID.
344 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
345 self.streams.get_stream_by_id(id)
347 /// Reports the total number of streams.
348 pub fn get_num_streams(&self) -> usize {
349 self.streams.get_num_streams()
351 /// Returns a reference to the internal stream manager.
352 pub fn get_stream_manager(&self) -> &StreamManager {
355 /// Returns an iterator over streams.
356 pub fn get_streams(&self) -> StreamIter {
359 /// Returns 'ignored' marker for requested stream.
360 pub fn is_ignored_stream(&self, idx: usize) -> bool {
361 self.streams.is_ignored(idx)
363 /// Sets 'ignored' marker for requested stream.
364 pub fn set_ignored_stream(&mut self, idx: usize) {
365 self.streams.set_ignored(idx)
367 /// Clears 'ignored' marker for requested stream.
368 pub fn set_unignored_stream(&mut self, idx: usize) {
369 self.streams.set_unignored(idx)
372 /// Demuxes a new packet from the container.
373 pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
375 let res = self.dmx.get_frame(&mut self.streams);
376 if self.streams.no_ign || res.is_err() { return res; }
377 let res = res.unwrap();
378 let idx = res.get_stream().get_num();
379 if !self.is_ignored_stream(idx) {
384 /// Seeks to the requested time (in milliseconds) if possible.
385 pub fn seek(&mut self, time: u64) -> DemuxerResult<()> {
386 if self.seek_idx.skip_index {
387 return Err(DemuxerError::NotPossible);
389 self.dmx.seek(time, &self.seek_idx)
391 /// Returns internal seek index.
392 pub fn get_seek_index(&self) -> &SeekIndex {
397 impl From<ByteIOError> for DemuxerError {
398 fn from(_: ByteIOError) -> Self { DemuxerError::IOError }
401 /// The trait for creating demuxers.
402 pub trait DemuxerCreator {
403 /// Creates new demuxer instance that will use `ByteReader` source as an input.
404 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a>;
405 /// Returns the name of current demuxer creator (equal to the container name it can demux).
406 fn get_name(&self) -> &'static str;
409 /// Creates demuxer for a provided bytestream.
410 pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> DemuxerResult<Demuxer<'a>> {
411 let mut dmx = dmxcr.new_demuxer(br);
412 let mut str = StreamManager::new();
413 let mut seek_idx = SeekIndex::new();
414 dmx.open(&mut str, &mut seek_idx)?;
415 Ok(Demuxer::new(dmx, str, seek_idx))
418 /// List of registered demuxers.
420 pub struct RegisteredDemuxers {
421 dmxs: Vec<&'static DemuxerCreator>,
424 impl RegisteredDemuxers {
425 /// Constructs a new `RegisteredDemuxers` instance.
426 pub fn new() -> Self {
427 Self { dmxs: Vec::new() }
429 /// Registers a new demuxer.
430 pub fn add_demuxer(&mut self, dmx: &'static DemuxerCreator) {
433 /// Searches for a demuxer that supports requested container format.
434 pub fn find_demuxer(&self, name: &str) -> Option<&DemuxerCreator> {
435 for &dmx in self.dmxs.iter() {
436 if dmx.get_name() == name {