use NATimePoint for seeking
[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.
24d99894 40 fn seek(&mut self, time: NATimePoint, 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 }
b3247252
KS
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 }
ab683361 104 /// Returns stream with the requested index.
70910ac3 105 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
20ef4353
KS
106 if idx < self.streams.len() {
107 Some(self.streams[idx].clone())
108 } else {
109 None
110 }
111 }
ab683361 112 /// Returns stream with the requested stream ID.
70910ac3 113 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
20ef4353
KS
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 }
ab683361 121 /// Returns the number of known streams.
66116504 122 pub fn get_num_streams(&self) -> usize { self.streams.len() }
ab683361 123 /// Reports whether the stream is marked as ignored.
bcfeae48
KS
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 }
ab683361 133 /// Reports whether the stream with certain ID is marked as ignored.
ce52b3b5
KS
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 }
ab683361 142 /// Marks requested stream as ignored.
bcfeae48
KS
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 }
ab683361 149 /// Clears the ignored mark for the requested stream.
bcfeae48
KS
150 pub fn set_unignored(&mut self, idx: usize) {
151 if idx < self.ignored.len() {
152 self.ignored[idx] = false;
153 }
154 }
155}
156
ab683361 157/// Stream iterator.
bcfeae48 158pub struct StreamIter<'a> {
e243ceb4 159 streams: &'a [NAStreamRef],
bcfeae48
KS
160 pos: usize,
161}
162
163impl<'a> StreamIter<'a> {
ab683361 164 /// Constructs a new instance of `StreamIter`.
e243ceb4
KS
165 pub fn new(streams: &'a [NAStreamRef]) -> Self {
166 StreamIter { streams, pos: 0 }
bcfeae48
KS
167 }
168}
169
170impl<'a> Iterator for StreamIter<'a> {
70910ac3 171 type Item = NAStreamRef;
bcfeae48
KS
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
ab683361 181/// Seeking modes.
33b5a8f0
KS
182#[derive(Clone,Copy,PartialEq)]
183pub enum SeekIndexMode {
ab683361 184 /// No seeking index present.
33b5a8f0 185 None,
ab683361 186 /// Seeking index is present.
33b5a8f0 187 Present,
ab683361 188 /// Seeking index should be constructed by the demuxer if possible.
33b5a8f0
KS
189 Automatic,
190}
191
192impl Default for SeekIndexMode {
193 fn default() -> Self { SeekIndexMode::None }
194}
195
ab683361 196/// A structure holding seeking information.
33b5a8f0
KS
197#[derive(Clone,Copy,Default)]
198pub struct SeekEntry {
ab683361
KS
199 /// Time in milliseconds.
200 pub time: u64,
201 /// PTS
33b5a8f0 202 pub pts: u64,
ab683361 203 /// Position in file.
33b5a8f0
KS
204 pub pos: u64,
205}
206
ab683361 207/// Seeking information for individual streams.
33b5a8f0
KS
208#[derive(Clone)]
209pub struct StreamSeekInfo {
ab683361 210 /// Stream ID.
33b5a8f0 211 pub id: u32,
ab683361 212 /// Index is present.
33b5a8f0 213 pub filled: bool,
ab683361 214 /// Packet seeking information.
33b5a8f0
KS
215 pub entries: Vec<SeekEntry>,
216}
217
218impl StreamSeekInfo {
ab683361 219 /// Constructs a new `StreamSeekInfo` instance.
4cfb5dd4 220 pub fn new(id: u32) -> Self {
33b5a8f0 221 Self {
4cfb5dd4 222 id,
33b5a8f0
KS
223 filled: false,
224 entries: Vec::new(),
225 }
226 }
ab683361 227 /// Adds new seeking point.
33b5a8f0
KS
228 pub fn add_entry(&mut self, entry: SeekEntry) {
229 self.entries.push(entry);
230 }
ab683361 231 /// Searches for an appropriate seek position before requested time.
24d99894
KS
232 pub fn find_pos(&self, time: NATimePoint) -> Option<SeekEntry> {
233 if time == NATimePoint::None {
234 return None;
235 }
33b5a8f0
KS
236 if !self.entries.is_empty() {
237// todo something faster like binary search
4cfb5dd4
KS
238 let mut cand = None;
239 for entry in self.entries.iter() {
24d99894
KS
240 match time {
241 NATimePoint::Milliseconds(ms) => {
242 if entry.time <= ms {
243 cand = Some(*entry);
244 } else {
245 break;
246 }
247 },
248 NATimePoint::PTS(pts) => {
249 if entry.pts <= pts {
250 cand = Some(*entry);
251 } else {
252 break;
253 }
254 },
255 NATimePoint::None => unreachable!(),
256 };
33b5a8f0 257 }
4cfb5dd4 258 cand
33b5a8f0
KS
259 } else {
260 None
261 }
262 }
263}
264
ab683361 265/// Structure for holding seeking point search results.
33b5a8f0
KS
266#[derive(Clone,Copy,Default)]
267pub struct SeekIndexResult {
ab683361 268 /// Packet PTS.
33b5a8f0 269 pub pts: u64,
ab683361 270 /// Position in file.
33b5a8f0 271 pub pos: u64,
ab683361 272 /// Stream ID.
33b5a8f0
KS
273 pub str_id: u32,
274}
275
ab683361 276/// Seek information for the whole container.
33b5a8f0
KS
277#[derive(Default)]
278pub struct SeekIndex {
ab683361 279 /// Seek information for individual streams.
33b5a8f0 280 pub seek_info: Vec<StreamSeekInfo>,
ab683361 281 /// Seeking index mode.
33b5a8f0 282 pub mode: SeekIndexMode,
ab683361 283 /// Ignore index flag.
9da33f04 284 pub skip_index: bool,
33b5a8f0
KS
285}
286
287impl SeekIndex {
ab683361 288 /// Constructs a new `SeekIndex` instance.
33b5a8f0 289 pub fn new() -> Self { Self::default() }
6492988d
KS
290 pub fn add_stream(&mut self, id: u32) -> usize {
291 let ret = self.stream_id_to_index(id);
292 if ret.is_none() {
4cfb5dd4 293 self.seek_info.push(StreamSeekInfo::new(id));
6492988d
KS
294 self.seek_info.len() - 1
295 } else {
296 ret.unwrap()
33b5a8f0
KS
297 }
298 }
ab683361 299 /// Adds a new stream to the index.
33b5a8f0
KS
300 pub fn stream_id_to_index(&self, id: u32) -> Option<usize> {
301 for (idx, str) in self.seek_info.iter().enumerate() {
302 if str.id == id {
303 return Some(idx);
304 }
305 }
306 None
307 }
ab683361 308 /// Returns stream reference for provided stream ID.
4cfb5dd4
KS
309 pub fn get_stream_index(&mut self, id: u32) -> Option<&mut StreamSeekInfo> {
310 for str in self.seek_info.iter_mut() {
311 if str.id == id {
312 return Some(str);
313 }
314 }
315 None
316 }
ab683361 317 /// Adds seeking information to the index.
6492988d
KS
318 pub fn add_entry(&mut self, id: u32, entry: SeekEntry) {
319 let mut idx = self.stream_id_to_index(id);
320 if idx.is_none() {
321 idx = Some(self.add_stream(id));
322 }
323 self.seek_info[idx.unwrap()].add_entry(entry);
324 self.seek_info[idx.unwrap()].filled = true;
325 }
ab683361 326 /// Searches for a seek position before requested time.
24d99894 327 pub fn find_pos(&self, time: NATimePoint) -> Option<SeekIndexResult> {
33b5a8f0
KS
328 let mut cand = None;
329 for str in self.seek_info.iter() {
330 if !str.filled { continue; }
4cfb5dd4
KS
331 let res = str.find_pos(time);
332 if res.is_none() { continue; }
333 let res = res.unwrap();
33b5a8f0 334 if cand.is_none() {
4cfb5dd4 335 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
33b5a8f0 336 } else if let Some(entry) = cand {
4cfb5dd4
KS
337 if res.pos < entry.pos {
338 cand = Some(SeekIndexResult { pts: res.pts, pos: res.pos, str_id: str.id });
33b5a8f0
KS
339 }
340 }
341 }
342 cand
343 }
344}
345
ab683361 346/// Demuxer structure with auxiliary data.
bcfeae48 347pub struct Demuxer<'a> {
6011e201 348 dmx: Box<dyn DemuxCore<'a> + 'a>,
bcfeae48 349 streams: StreamManager,
33b5a8f0 350 seek_idx: SeekIndex,
bcfeae48
KS
351}
352
353impl<'a> Demuxer<'a> {
ab683361 354 /// Constructs a new `Demuxer` instance.
33b5a8f0 355 fn new(dmx: Box<dyn DemuxCore<'a> + 'a>, str: StreamManager, seek_idx: SeekIndex) -> Self {
bcfeae48 356 Demuxer {
e243ceb4 357 dmx,
bcfeae48 358 streams: str,
33b5a8f0 359 seek_idx,
bcfeae48
KS
360 }
361 }
ab683361 362 /// Returns a stream reference by its number.
70910ac3 363 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
bcfeae48
KS
364 self.streams.get_stream(idx)
365 }
ab683361 366 /// Returns a stream reference by its ID.
70910ac3 367 pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
bcfeae48
KS
368 self.streams.get_stream_by_id(id)
369 }
ab683361 370 /// Reports the total number of streams.
bcfeae48
KS
371 pub fn get_num_streams(&self) -> usize {
372 self.streams.get_num_streams()
373 }
cacc0c44
KS
374 /// Returns a reference to the internal stream manager.
375 pub fn get_stream_manager(&self) -> &StreamManager {
376 &self.streams
377 }
ab683361 378 /// Returns an iterator over streams.
bcfeae48
KS
379 pub fn get_streams(&self) -> StreamIter {
380 self.streams.iter()
381 }
ab683361 382 /// Returns 'ignored' marker for requested stream.
bcfeae48
KS
383 pub fn is_ignored_stream(&self, idx: usize) -> bool {
384 self.streams.is_ignored(idx)
385 }
ab683361 386 /// Sets 'ignored' marker for requested stream.
bcfeae48
KS
387 pub fn set_ignored_stream(&mut self, idx: usize) {
388 self.streams.set_ignored(idx)
389 }
ab683361 390 /// Clears 'ignored' marker for requested stream.
bcfeae48
KS
391 pub fn set_unignored_stream(&mut self, idx: usize) {
392 self.streams.set_unignored(idx)
393 }
394
ab683361 395 /// Demuxes a new packet from the container.
bcfeae48
KS
396 pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
397 loop {
398 let res = self.dmx.get_frame(&mut self.streams);
399 if self.streams.no_ign || res.is_err() { return res; }
400 let res = res.unwrap();
401 let idx = res.get_stream().get_num();
402 if !self.is_ignored_stream(idx) {
403 return Ok(res);
404 }
405 }
406 }
24d99894
KS
407 /// Seeks to the requested time if possible.
408 pub fn seek(&mut self, time: NATimePoint) -> DemuxerResult<()> {
9da33f04
KS
409 if self.seek_idx.skip_index {
410 return Err(DemuxerError::NotPossible);
411 }
33b5a8f0
KS
412 self.dmx.seek(time, &self.seek_idx)
413 }
ab683361 414 /// Returns internal seek index.
33b5a8f0
KS
415 pub fn get_seek_index(&self) -> &SeekIndex {
416 &self.seek_idx
bcfeae48 417 }
5869fd63
KS
418}
419
787b8d03
KS
420impl<'a> NAOptionHandler for Demuxer<'a> {
421 fn get_supported_options(&self) -> &[NAOptionDefinition] {
422 self.dmx.get_supported_options()
423 }
424 fn set_options(&mut self, options: &[NAOption]) {
425 self.dmx.set_options(options);
426 }
427 fn query_option_value(&self, name: &str) -> Option<NAValue> {
428 self.dmx.query_option_value(name)
429 }
430}
431
5869fd63
KS
432impl From<ByteIOError> for DemuxerError {
433 fn from(_: ByteIOError) -> Self { DemuxerError::IOError }
434}
435
ab683361 436/// The trait for creating demuxers.
eb71d98f 437pub trait DemuxerCreator {
ab683361 438 /// Creates new demuxer instance that will use `ByteReader` source as an input.
6011e201 439 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a>;
ab683361 440 /// Returns the name of current demuxer creator (equal to the container name it can demux).
eb71d98f
KS
441 fn get_name(&self) -> &'static str;
442}
443
ab683361 444/// Creates demuxer for a provided bytestream.
bcfeae48
KS
445pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> DemuxerResult<Demuxer<'a>> {
446 let mut dmx = dmxcr.new_demuxer(br);
447 let mut str = StreamManager::new();
33b5a8f0
KS
448 let mut seek_idx = SeekIndex::new();
449 dmx.open(&mut str, &mut seek_idx)?;
450 Ok(Demuxer::new(dmx, str, seek_idx))
bcfeae48 451}
5641dccf 452
ab683361 453/// List of registered demuxers.
e243ceb4 454#[derive(Default)]
5641dccf
KS
455pub struct RegisteredDemuxers {
456 dmxs: Vec<&'static DemuxerCreator>,
457}
458
459impl RegisteredDemuxers {
ab683361 460 /// Constructs a new `RegisteredDemuxers` instance.
5641dccf
KS
461 pub fn new() -> Self {
462 Self { dmxs: Vec::new() }
463 }
ab683361 464 /// Registers a new demuxer.
5641dccf
KS
465 pub fn add_demuxer(&mut self, dmx: &'static DemuxerCreator) {
466 self.dmxs.push(dmx);
467 }
ab683361 468 /// Searches for a demuxer that supports requested container format.
5641dccf
KS
469 pub fn find_demuxer(&self, name: &str) -> Option<&DemuxerCreator> {
470 for &dmx in self.dmxs.iter() {
471 if dmx.get_name() == name {
472 return Some(dmx);
473 }
474 }
475 None
476 }
cec53b88
KS
477 /// Provides an iterator over currently registered demuxers.
478 pub fn iter(&self) -> std::slice::Iter<&DemuxerCreator> {
479 self.dmxs.iter()
480 }
1a967e6b 481}