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