9a69abb18c6d3d11c7b6a3241069be90e8706957
[nihav.git] / nihav-core / src / demuxers / mod.rs
1 //! Demuxer definitions.
2 pub use crate::frame::*;
3 pub use crate::io::byteio::*;
4 pub use crate::options::*;
5
6 /// A list specifying general demuxing errors.
7 #[derive(Debug,Clone,Copy,PartialEq)]
8 #[allow(dead_code)]
9 pub enum DemuxerError {
10 /// Reader got to end of stream.
11 EOF,
12 /// Demuxer encountered empty container.
13 NoSuchInput,
14 /// Demuxer encountered invalid input data.
15 InvalidData,
16 /// Data reading error.
17 IOError,
18 /// Feature is not implemented.
19 NotImplemented,
20 /// Allocation failed.
21 MemoryError,
22 /// The operation should be repeated.
23 TryAgain,
24 /// Seeking failed.
25 SeekError,
26 /// Operation cannot succeed in principle (e.g. seeking in a format not supporting seeking).
27 NotPossible,
28 }
29
30 /// A specialised `Result` type for demuxing operations.
31 pub type DemuxerResult<T> = Result<T, DemuxerError>;
32
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<()>;
37 /// Demuxes a packet.
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<()>;
41 }
42
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<()>;
49 }
50
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); }
55 buf.resize(size, 0);
56 self.read_buf(buf.as_mut_slice())?;
57 let pkt = NAPacket::new(str, ts, kf, buf);
58 Ok(pkt)
59 }
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())?;
64 Ok(())
65 }
66 }
67
68 /// An auxiliary structure for operations with individual streams inside the container.
69 #[derive(Default)]
70 pub struct StreamManager {
71 streams: Vec<NAStreamRef>,
72 ignored: Vec<bool>,
73 no_ign: bool,
74 }
75
76 impl StreamManager {
77 /// Constructs a new instance of `StreamManager`.
78 pub fn new() -> Self {
79 StreamManager {
80 streams: Vec::new(),
81 ignored: Vec::new(),
82 no_ign: true,
83 }
84 }
85 /// Returns stream iterator.
86 pub fn iter(&self) -> StreamIter { StreamIter::new(&self.streams) }
87
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);
95 Some(stream_num)
96 }
97 /// Adds a new stream from reference-counted object.
98 pub fn add_stream_ref(&mut self, stream: NAStreamRef) -> Option<usize> {
99 let stream_num = self.streams.len();
100 self.streams.push(stream);
101 self.ignored.push(false);
102 Some(stream_num)
103 }
104 /// Returns stream with the requested index.
105 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
106 if idx < self.streams.len() {
107 Some(self.streams[idx].clone())
108 } else {
109 None
110 }
111 }
112 /// Returns stream with the requested stream ID.
113 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
114 for i in 0..self.streams.len() {
115 if self.streams[i].get_id() == id {
116 return Some(self.streams[i].clone());
117 }
118 }
119 None
120 }
121 /// Returns the number of known streams.
122 pub fn get_num_streams(&self) -> usize { self.streams.len() }
123 /// Reports whether the stream is marked as ignored.
124 pub fn is_ignored(&self, idx: usize) -> bool {
125 if self.no_ign {
126 true
127 } else if idx < self.ignored.len() {
128 self.ignored[idx]
129 } else {
130 false
131 }
132 }
133 /// Reports whether the stream with certain ID is marked as ignored.
134 pub fn is_ignored_id(&self, id: u32) -> bool {
135 for i in 0..self.streams.len() {
136 if self.streams[i].get_id() == id {
137 return self.ignored[i];
138 }
139 }
140 false
141 }
142 /// Marks requested stream as ignored.
143 pub fn set_ignored(&mut self, idx: usize) {
144 if idx < self.ignored.len() {
145 self.ignored[idx] = true;
146 self.no_ign = false;
147 }
148 }
149 /// Clears the ignored mark for the requested stream.
150 pub fn set_unignored(&mut self, idx: usize) {
151 if idx < self.ignored.len() {
152 self.ignored[idx] = false;
153 }
154 }
155 }
156
157 /// Stream iterator.
158 pub struct StreamIter<'a> {
159 streams: &'a [NAStreamRef],
160 pos: usize,
161 }
162
163 impl<'a> StreamIter<'a> {
164 /// Constructs a new instance of `StreamIter`.
165 pub fn new(streams: &'a [NAStreamRef]) -> Self {
166 StreamIter { streams, pos: 0 }
167 }
168 }
169
170 impl<'a> Iterator for StreamIter<'a> {
171 type Item = NAStreamRef;
172
173 fn next(&mut self) -> Option<Self::Item> {
174 if self.pos >= self.streams.len() { return None; }
175 let ret = self.streams[self.pos].clone();
176 self.pos += 1;
177 Some(ret)
178 }
179 }
180
181 /// Seeking modes.
182 #[derive(Clone,Copy,PartialEq)]
183 pub enum SeekIndexMode {
184 /// No seeking index present.
185 None,
186 /// Seeking index is present.
187 Present,
188 /// Seeking index should be constructed by the demuxer if possible.
189 Automatic,
190 }
191
192 impl Default for SeekIndexMode {
193 fn default() -> Self { SeekIndexMode::None }
194 }
195
196 /// A structure holding seeking information.
197 #[derive(Clone,Copy,Default)]
198 pub struct SeekEntry {
199 /// Time in milliseconds.
200 pub time: u64,
201 /// PTS
202 pub pts: u64,
203 /// Position in file.
204 pub pos: u64,
205 }
206
207 /// Seeking information for individual streams.
208 #[derive(Clone)]
209 pub struct StreamSeekInfo {
210 /// Stream ID.
211 pub id: u32,
212 /// Index is present.
213 pub filled: bool,
214 /// Packet seeking information.
215 pub entries: Vec<SeekEntry>,
216 }
217
218 impl StreamSeekInfo {
219 /// Constructs a new `StreamSeekInfo` instance.
220 pub fn new(id: u32) -> Self {
221 Self {
222 id,
223 filled: false,
224 entries: Vec::new(),
225 }
226 }
227 /// Adds new seeking point.
228 pub fn add_entry(&mut self, entry: SeekEntry) {
229 self.entries.push(entry);
230 }
231 /// Searches for an appropriate seek position before requested time.
232 pub fn find_pos(&self, time: u64) -> Option<SeekEntry> {
233 if !self.entries.is_empty() {
234 // todo something faster like binary search
235 let mut cand = None;
236 for entry in self.entries.iter() {
237 if entry.time <= time {
238 cand = Some(*entry);
239 } else {
240 break;
241 }
242 }
243 cand
244 } else {
245 None
246 }
247 }
248 }
249
250 /// Structure for holding seeking point search results.
251 #[derive(Clone,Copy,Default)]
252 pub struct SeekIndexResult {
253 /// Packet PTS.
254 pub pts: u64,
255 /// Position in file.
256 pub pos: u64,
257 /// Stream ID.
258 pub str_id: u32,
259 }
260
261 /// Seek information for the whole container.
262 #[derive(Default)]
263 pub struct SeekIndex {
264 /// Seek information for individual streams.
265 pub seek_info: Vec<StreamSeekInfo>,
266 /// Seeking index mode.
267 pub mode: SeekIndexMode,
268 /// Ignore index flag.
269 pub skip_index: bool,
270 }
271
272 impl SeekIndex {
273 /// Constructs a new `SeekIndex` instance.
274 pub fn new() -> Self { Self::default() }
275 pub fn add_stream(&mut self, id: u32) -> usize {
276 let ret = self.stream_id_to_index(id);
277 if ret.is_none() {
278 self.seek_info.push(StreamSeekInfo::new(id));
279 self.seek_info.len() - 1
280 } else {
281 ret.unwrap()
282 }
283 }
284 /// Adds a new stream to the index.
285 pub fn stream_id_to_index(&self, id: u32) -> Option<usize> {
286 for (idx, str) in self.seek_info.iter().enumerate() {
287 if str.id == id {
288 return Some(idx);
289 }
290 }
291 None
292 }
293 /// Returns stream reference for provided stream ID.
294 pub fn get_stream_index(&mut self, id: u32) -> Option<&mut StreamSeekInfo> {
295 for str in self.seek_info.iter_mut() {
296 if str.id == id {
297 return Some(str);
298 }
299 }
300 None
301 }
302 /// Adds seeking information to the index.
303 pub fn add_entry(&mut self, id: u32, entry: SeekEntry) {
304 let mut idx = self.stream_id_to_index(id);
305 if idx.is_none() {
306 idx = Some(self.add_stream(id));
307 }
308 self.seek_info[idx.unwrap()].add_entry(entry);
309 self.seek_info[idx.unwrap()].filled = true;
310 }
311 /// Searches for a seek position before requested time.
312 pub fn find_pos(&self, time: u64) -> Option<SeekIndexResult> {
313 let mut cand = None;
314 for str in self.seek_info.iter() {
315 if !str.filled { continue; }
316 let res = str.find_pos(time);
317 if res.is_none() { continue; }
318 let res = res.unwrap();
319 if cand.is_none() {
320 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
321 } else if let Some(entry) = cand {
322 if res.pos < entry.pos {
323 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
324 }
325 }
326 }
327 cand
328 }
329 }
330
331 /// Demuxer structure with auxiliary data.
332 pub struct Demuxer<'a> {
333 dmx: Box<dyn DemuxCore<'a> + 'a>,
334 streams: StreamManager,
335 seek_idx: SeekIndex,
336 }
337
338 impl<'a> Demuxer<'a> {
339 /// Constructs a new `Demuxer` instance.
340 fn new(dmx: Box<dyn DemuxCore<'a> + 'a>, str: StreamManager, seek_idx: SeekIndex) -> Self {
341 Demuxer {
342 dmx,
343 streams: str,
344 seek_idx,
345 }
346 }
347 /// Returns a stream reference by its number.
348 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
349 self.streams.get_stream(idx)
350 }
351 /// Returns a stream reference by its ID.
352 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
353 self.streams.get_stream_by_id(id)
354 }
355 /// Reports the total number of streams.
356 pub fn get_num_streams(&self) -> usize {
357 self.streams.get_num_streams()
358 }
359 /// Returns a reference to the internal stream manager.
360 pub fn get_stream_manager(&self) -> &StreamManager {
361 &self.streams
362 }
363 /// Returns an iterator over streams.
364 pub fn get_streams(&self) -> StreamIter {
365 self.streams.iter()
366 }
367 /// Returns 'ignored' marker for requested stream.
368 pub fn is_ignored_stream(&self, idx: usize) -> bool {
369 self.streams.is_ignored(idx)
370 }
371 /// Sets 'ignored' marker for requested stream.
372 pub fn set_ignored_stream(&mut self, idx: usize) {
373 self.streams.set_ignored(idx)
374 }
375 /// Clears 'ignored' marker for requested stream.
376 pub fn set_unignored_stream(&mut self, idx: usize) {
377 self.streams.set_unignored(idx)
378 }
379
380 /// Demuxes a new packet from the container.
381 pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
382 loop {
383 let res = self.dmx.get_frame(&mut self.streams);
384 if self.streams.no_ign || res.is_err() { return res; }
385 let res = res.unwrap();
386 let idx = res.get_stream().get_num();
387 if !self.is_ignored_stream(idx) {
388 return Ok(res);
389 }
390 }
391 }
392 /// Seeks to the requested time (in milliseconds) if possible.
393 pub fn seek(&mut self, time: u64) -> DemuxerResult<()> {
394 if self.seek_idx.skip_index {
395 return Err(DemuxerError::NotPossible);
396 }
397 self.dmx.seek(time, &self.seek_idx)
398 }
399 /// Returns internal seek index.
400 pub fn get_seek_index(&self) -> &SeekIndex {
401 &self.seek_idx
402 }
403 }
404
405 impl<'a> NAOptionHandler for Demuxer<'a> {
406 fn get_supported_options(&self) -> &[NAOptionDefinition] {
407 self.dmx.get_supported_options()
408 }
409 fn set_options(&mut self, options: &[NAOption]) {
410 self.dmx.set_options(options);
411 }
412 fn query_option_value(&self, name: &str) -> Option<NAValue> {
413 self.dmx.query_option_value(name)
414 }
415 }
416
417 impl From<ByteIOError> for DemuxerError {
418 fn from(_: ByteIOError) -> Self { DemuxerError::IOError }
419 }
420
421 /// The trait for creating demuxers.
422 pub trait DemuxerCreator {
423 /// Creates new demuxer instance that will use `ByteReader` source as an input.
424 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a>;
425 /// Returns the name of current demuxer creator (equal to the container name it can demux).
426 fn get_name(&self) -> &'static str;
427 }
428
429 /// Creates demuxer for a provided bytestream.
430 pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> DemuxerResult<Demuxer<'a>> {
431 let mut dmx = dmxcr.new_demuxer(br);
432 let mut str = StreamManager::new();
433 let mut seek_idx = SeekIndex::new();
434 dmx.open(&mut str, &mut seek_idx)?;
435 Ok(Demuxer::new(dmx, str, seek_idx))
436 }
437
438 /// List of registered demuxers.
439 #[derive(Default)]
440 pub struct RegisteredDemuxers {
441 dmxs: Vec<&'static DemuxerCreator>,
442 }
443
444 impl RegisteredDemuxers {
445 /// Constructs a new `RegisteredDemuxers` instance.
446 pub fn new() -> Self {
447 Self { dmxs: Vec::new() }
448 }
449 /// Registers a new demuxer.
450 pub fn add_demuxer(&mut self, dmx: &'static DemuxerCreator) {
451 self.dmxs.push(dmx);
452 }
453 /// Searches for a demuxer that supports requested container format.
454 pub fn find_demuxer(&self, name: &str) -> Option<&DemuxerCreator> {
455 for &dmx in self.dmxs.iter() {
456 if dmx.get_name() == name {
457 return Some(dmx);
458 }
459 }
460 None
461 }
462 /// Provides an iterator over currently registered demuxers.
463 pub fn iter(&self) -> std::slice::Iter<&DemuxerCreator> {
464 self.dmxs.iter()
465 }
466 }