aboutsummaryrefslogtreecommitdiffstats
path: root/nihav-core/src/demuxers/mod.rs
blob: 902fbba4db578fd74bc05e3e2a32fed22fb41012 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
pub use crate::frame::*;
pub use crate::io::byteio::*;

#[derive(Debug,Clone,Copy,PartialEq)]
#[allow(dead_code)]
pub enum DemuxerError {
    EOF,
    NoSuchInput,
    InvalidData,
    IOError,
    NotImplemented,
    MemoryError,
    TryAgain,
}

pub type DemuxerResult<T> = Result<T, DemuxerError>;

pub trait DemuxCore<'a> {
    fn open(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<()>;
    fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket>;
    fn seek(&mut self, time: u64) -> DemuxerResult<()>;
}

pub trait NAPacketReader {
    fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, keyframe: bool, size: usize) -> DemuxerResult<NAPacket>;
    fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()>;
}

impl<'a> NAPacketReader for ByteReader<'a> {
    fn read_packet(&mut self, str: NAStreamRef, ts: NATimeInfo, kf: bool, size: usize) -> DemuxerResult<NAPacket> {
        let mut buf: Vec<u8> = Vec::with_capacity(size);
        if buf.capacity() < size { return Err(DemuxerError::MemoryError); }
        buf.resize(size, 0);
        self.read_buf(buf.as_mut_slice())?;
        let pkt = NAPacket::new(str, ts, kf, buf);
        Ok(pkt)
    }
    fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()> {
        let mut refbuf = pkt.get_buffer();
        let buf = refbuf.as_mut().unwrap();
        self.read_buf(buf.as_mut_slice())?;
        Ok(())
    }
}

#[derive(Default)]
pub struct StreamManager {
    streams: Vec<NAStreamRef>,
    ignored: Vec<bool>,
    no_ign:  bool,
}

impl StreamManager {
    pub fn new() -> Self {
        StreamManager {
            streams: Vec::new(),
            ignored: Vec::new(),
            no_ign:  true,
        }
    }
    pub fn iter(&self) -> StreamIter { StreamIter::new(&self.streams) }

    pub fn add_stream(&mut self, stream: NAStream) -> Option<usize> {
        let stream_num = self.streams.len();
        let mut str = stream.clone();
        str.set_num(stream_num);
        self.streams.push(str.into_ref());
        self.ignored.push(false);
        Some(stream_num)
    }
    pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
        if idx < self.streams.len() {
            Some(self.streams[idx].clone())
        } else {
            None
        }
    }
    pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
        for i in 0..self.streams.len() {
            if self.streams[i].get_id() == id {
                return Some(self.streams[i].clone());
            }
        }
        None
    }
    pub fn get_num_streams(&self) -> usize { self.streams.len() }
    pub fn is_ignored(&self, idx: usize) -> bool {
        if self.no_ign {
            true
        } else if idx < self.ignored.len() {
            self.ignored[idx]
        } else {
            false
        }
    }
    pub fn is_ignored_id(&self, id: u32) -> bool {
        for i in 0..self.streams.len() {
            if self.streams[i].get_id() == id {
                return self.ignored[i];
            }
        }
        false
    }
    pub fn set_ignored(&mut self, idx: usize) {
        if idx < self.ignored.len() {
            self.ignored[idx] = true;
            self.no_ign = false;
        }
    }
    pub fn set_unignored(&mut self, idx: usize) {
        if idx < self.ignored.len() {
            self.ignored[idx] = false;
        }
    }
}

pub struct StreamIter<'a> {
    streams:    &'a [NAStreamRef],
    pos:        usize,
}

impl<'a> StreamIter<'a> {
    pub fn new(streams: &'a [NAStreamRef]) -> Self {
        StreamIter { streams, pos: 0 }
    }
}

impl<'a> Iterator for StreamIter<'a> {
    type Item = NAStreamRef;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.streams.len() { return None; }
        let ret = self.streams[self.pos].clone();
        self.pos += 1;
        Some(ret)
    }
}

pub struct Demuxer<'a> {
    dmx:        Box<dyn DemuxCore<'a> + 'a>,
    streams:    StreamManager,
}

impl<'a> Demuxer<'a> {
    fn new(dmx: Box<dyn DemuxCore<'a> + 'a>, str: StreamManager) -> Self {
        Demuxer {
            dmx,
            streams:    str,
        }
    }
    pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
        self.streams.get_stream(idx)
    }
    pub fn get_stream_by_id(&self, id: u32) -> Option<NAStreamRef> {
        self.streams.get_stream_by_id(id)
    }
    pub fn get_num_streams(&self) -> usize {
        self.streams.get_num_streams()
    }
    pub fn get_streams(&self) -> StreamIter {
        self.streams.iter()
    }
    pub fn is_ignored_stream(&self, idx: usize) -> bool {
        self.streams.is_ignored(idx)
    }
    pub fn set_ignored_stream(&mut self, idx: usize) {
        self.streams.set_ignored(idx)
    }
    pub fn set_unignored_stream(&mut self, idx: usize) {
        self.streams.set_unignored(idx)
    }

    pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
        loop {
            let res = self.dmx.get_frame(&mut self.streams);
            if self.streams.no_ign || res.is_err() { return res; }
            let res = res.unwrap();
            let idx = res.get_stream().get_num();
            if !self.is_ignored_stream(idx) {
                return Ok(res);
            }
        }
    }
    pub fn seek(&mut self, time: u64) -> DemuxerResult<()> {
        self.dmx.seek(time)
    }
}

impl From<ByteIOError> for DemuxerError {
    fn from(_: ByteIOError) -> Self { DemuxerError::IOError }
}

///The structure used to create demuxers.
pub trait DemuxerCreator {
    /// Create new demuxer instance that will use `ByteReader` source as an input.
    fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a>;
    /// Get the name of current demuxer creator.
    fn get_name(&self) -> &'static str;
}

pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> DemuxerResult<Demuxer<'a>> {
    let mut dmx = dmxcr.new_demuxer(br);
    let mut str = StreamManager::new();
    dmx.open(&mut str)?;
    Ok(Demuxer::new(dmx, str))
}

#[derive(Default)]
pub struct RegisteredDemuxers {
    dmxs:   Vec<&'static DemuxerCreator>,
}

impl RegisteredDemuxers {
    pub fn new() -> Self {
        Self { dmxs: Vec::new() }
    }
    pub fn add_demuxer(&mut self, dmx: &'static DemuxerCreator) {
        self.dmxs.push(dmx);
    }
    pub fn find_demuxer(&self, name: &str) -> Option<&DemuxerCreator> {
        for &dmx in self.dmxs.iter() {
            if dmx.get_name() == name {
                return Some(dmx);
            }
        }
        None
    }
}