2 use nihav_core::codecs::*;
3 use nihav_core::demuxers::*;
4 use nihav_registry::detect;
5 use nihav_core::io::byteio::ByteReader;
8 pub struct FullRegister {
9 pub dmx_reg: RegisteredDemuxers,
10 pub rdmx_reg: RegisteredRawDemuxers,
11 pub pkt_reg: RegisteredPacketisers,
12 pub dec_reg: RegisteredDecoders,
16 pub fn new() -> Self {
17 let mut dmx_reg = RegisteredDemuxers::new();
18 nihav_register_all_demuxers(&mut dmx_reg);
19 let mut rdmx_reg = RegisteredRawDemuxers::new();
20 nihav_register_all_raw_demuxers(&mut rdmx_reg);
21 let mut dec_reg = RegisteredDecoders::new();
22 nihav_register_all_decoders(&mut dec_reg);
23 let mut pkt_reg = RegisteredPacketisers::new();
24 nihav_register_all_packetisers(&mut pkt_reg);
25 Self { dmx_reg, rdmx_reg, pkt_reg, dec_reg }
29 pub struct RawStreamCtx<'a> {
31 pkt: Box<dyn NAPacketiser + Send>,
32 br: &'a mut ByteReader<'a>,
37 impl<'a> RawStreamCtx<'a> {
38 fn new(stream: NAStreamRef, packetiser: Box<dyn NAPacketiser + Send>, br: &'a mut ByteReader<'a>) -> Self {
39 let mut seek = SeekIndex::new();
41 Self { stream, pkt: packetiser, br, pts: 0, seek }
43 fn account_for_packet(&mut self, packet: &mut NAPacket) {
44 let pos = self.br.tell() - (self.pkt.bytes_left() as u64);
45 if packet.get_pts().is_none() && packet.get_duration().is_some() {
46 packet.ts.pts = Some(self.pts);
48 if packet.is_keyframe() {
49 let pts = packet.get_pts().unwrap_or(self.pts);
50 let time = NATimeInfo::ts_to_time(pts, 1000, self.stream.tb_num, self.stream.tb_den);
51 let in_range = if let Some(last) = self.seek.seek_info[0].entries.last() {
57 self.seek.add_entry(0, SeekEntry { time, pts, pos });
60 self.pts += packet.get_duration().unwrap_or(0);
62 fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
63 let mut buf = [0; 1048576];
65 match self.pkt.get_packet(self.stream.clone()) {
66 Ok(Some(mut packet)) => {
67 self.account_for_packet(&mut packet);
71 Err(DecoderError::ShortData) => {},
72 _ => return Err(DemuxerError::InvalidData),
74 match self.br.read_buf_some(&mut buf) {
76 self.pkt.add_data(&buf[..size]);
79 match self.pkt.get_packet(self.stream.clone()) {
80 Ok(Some(mut packet)) => {
81 self.account_for_packet(&mut packet);
84 Ok(None) | Err(DecoderError::ShortData) => return Err(DemuxerError::EOF),
85 _ => return Err(DemuxerError::InvalidData),
93 pub enum DemuxerObject<'a> {
96 Raw(RawDemuxer<'a>, Vec<Option<Box<dyn NAPacketiser + Send>>>, bool),
97 RawStream(RawStreamCtx<'a>),
100 impl<'a> DemuxerObject<'a> {
101 pub fn create(br: &'a mut ByteReader<'a>, reg: &FullRegister, name: &str, force_dmx: Option<&str>, is_raw: bool, opts: &[NAOption]) -> DemuxerObject<'a> {
103 let res = detect::detect_format(name, br);
104 if let Some(dmx_name) = force_dmx {
105 println!("forcing demuxer {} on {}", dmx_name, name);
106 if let Some(dmx_fact) = reg.dmx_reg.find_demuxer(dmx_name) {
107 br.seek(SeekFrom::Start(0)).unwrap();
108 let dmx = create_demuxer_with_options(dmx_fact, br, opts).unwrap();
109 return DemuxerObject::Normal(dmx);
111 return DemuxerObject::None
114 let (dmx_name, _) = res.unwrap_or(("", detect::DetectionScore::No));
115 if !dmx_name.is_empty() {
116 println!("trying demuxer {} on {}", dmx_name, name);
117 if let Some(dmx_fact) = reg.dmx_reg.find_demuxer(dmx_name) {
118 br.seek(SeekFrom::Start(0)).unwrap();
119 let dmx = create_demuxer_with_options(dmx_fact, br, opts).unwrap();
120 return DemuxerObject::Normal(dmx);
123 if !dmx_name.is_empty() {
124 println!("trying raw demuxer {} on {}", dmx_name, name);
125 if let Some(rdmx_fact) = reg.rdmx_reg.find_demuxer(dmx_name) {
126 br.seek(SeekFrom::Start(0)).unwrap();
127 let dmx = create_raw_demuxer_with_options(rdmx_fact, br, opts).unwrap();
128 let mut pkts = Vec::new();
129 for stream in dmx.get_streams() {
130 if let Some(pcreate) = reg.pkt_reg.find_packetiser(stream.get_info().get_name()) {
131 let mut packetiser = (pcreate)();
132 packetiser.attach_stream(stream);
133 pkts.push(Some(packetiser));
138 return DemuxerObject::Raw(dmx, pkts, false);
141 for rdmx in reg.rdmx_reg.iter() {
142 if rdmx.check_format(br) {
143 println!("detected {} as {}", name, rdmx.get_name());
144 br.seek(SeekFrom::Start(0)).unwrap();
145 let dmx = create_raw_demuxer_with_options(*rdmx, br, opts).unwrap();
146 let mut pkts = Vec::new();
147 for stream in dmx.get_streams() {
148 if let Some(pcreate) = reg.pkt_reg.find_packetiser(stream.get_info().get_name()) {
149 let packetiser = (pcreate)();
150 pkts.push(Some(packetiser));
155 return DemuxerObject::Raw(dmx, pkts, false);
159 br.seek(SeekFrom::Start(0)).unwrap();
160 let mut buf = vec![0; 1048576];
161 let size = br.read_buf_some(&mut buf).unwrap();
162 br.seek(SeekFrom::Start(0)).unwrap();
165 for pinfo in reg.pkt_reg.iter() {
166 let mut packetiser = (pinfo.get_packetiser)();
167 packetiser.add_data(&buf[..size]);
168 if packetiser.parse_stream(0).is_ok() {
173 if !pname.is_empty() {
174 println!("found raw stream of type {} for {}", pname, name);
175 let pcreate = reg.pkt_reg.find_packetiser(pname).unwrap();
176 let mut packetiser = (pcreate)();
177 packetiser.add_data(&buf[..size]);
178 let stream = packetiser.parse_stream(0).unwrap();
180 DemuxerObject::RawStream(RawStreamCtx::new(stream, packetiser, br))
185 pub fn is_none(&self) -> bool {
186 matches!(*self, DemuxerObject::None)
188 pub fn get_duration(&self) -> u64 {
190 DemuxerObject::Normal(ref dmx) => dmx.get_duration(),
191 DemuxerObject::Raw(ref dmx, _, _) => dmx.get_duration(),
192 DemuxerObject::RawStream(ref ctx) => {
193 NATimeInfo::ts_to_time(ctx.stream.duration, 1000, ctx.stream.tb_num, ctx.stream.tb_den)
198 pub fn get_num_streams(&self) -> usize {
200 DemuxerObject::None => 0,
201 DemuxerObject::Normal(ref dmx) => dmx.get_num_streams(),
202 DemuxerObject::Raw(ref dmx, _, _) => dmx.get_num_streams(),
203 DemuxerObject::RawStream(_) => 1,
206 pub fn get_stream(&self, idx: usize) -> Option<NAStreamRef> {
208 DemuxerObject::Normal(ref dmx) => dmx.get_stream(idx),
209 DemuxerObject::Raw(ref dmx, _, _) => dmx.get_stream(idx),
210 DemuxerObject::RawStream(ref ctx) if idx == 0 => Some(ctx.stream.clone()),
214 pub fn get_frame(&mut self) -> DemuxerResult<NAPacket> {
216 DemuxerObject::Normal(ref mut dmx) => dmx.get_frame(),
217 DemuxerObject::Raw(ref mut dmx, ref mut packetisers, ref mut eof) => {
219 let mut has_some = false;
220 for (stream, p) in dmx.get_streams().zip(packetisers.iter_mut()) {
221 if let Some(ref mut pkts) = p {
222 match pkts.get_packet(stream.clone()) {
223 Ok(Some(pkt)) => return Ok(pkt),
224 Ok(None) | Err(DecoderError::ShortData) => {
230 println!("packetisation error {:?}", err);
231 return Err(DemuxerError::InvalidData);
234 has_some |= p.is_some();
238 return Err(DemuxerError::EOF);
240 if let Ok(data) = dmx.get_data() {
241 let id = data.get_stream().get_id();
242 for (i, stream) in dmx.get_streams().enumerate() {
243 if stream.get_id() == id {
244 if let Some(ref mut pkts) = packetisers[i] {
245 pkts.add_data(&data.get_buffer());
255 DemuxerObject::RawStream(ref mut ctx) => ctx.get_frame(),
259 pub fn seek(&mut self, seek_time: NATimePoint) -> DemuxerResult<()> {
261 DemuxerObject::Normal(ref mut dmx) => dmx.seek(seek_time),
262 DemuxerObject::Raw(ref mut dmx, _, _) => dmx.seek(seek_time),
263 DemuxerObject::RawStream(ref mut ctx) => {
264 if seek_time == NATimePoint::None {
265 return Err(DemuxerError::SeekError);
267 if let Some(last) = ctx.seek.seek_info[0].entries.last() {
268 let in_index = match seek_time {
269 NATimePoint::None => unreachable!(),
270 NATimePoint::PTS(pts) => last.pts >= pts,
271 NATimePoint::Milliseconds(ms) => last.time >= ms,
274 if let Some(result) = ctx.seek.find_pos(seek_time) {
275 ctx.br.seek(SeekFrom::Start(result.pos))?;
276 ctx.pts = result.pts;
282 if let Some(last) = ctx.seek.seek_info[0].entries.last() {
283 ctx.br.seek(SeekFrom::Start(last.pos))?;
288 while let Ok(pkt) = ctx.get_frame() {
289 if !pkt.ts.less_than(seek_time) && !pkt.ts.equal(seek_time) {
292 if pkt.is_keyframe() {
293 key_pts = pkt.get_pts().unwrap_or(0);
296 let result = ctx.seek.find_pos(NATimePoint::PTS(key_pts)).unwrap();
297 ctx.br.seek(SeekFrom::Start(result.pos))?;
298 ctx.pts = result.pts;
302 _ => Err(DemuxerError::NotImplemented),
307 pub fn detect_tags(br: &mut ByteReader) -> (bool, u64, Option<u64>) {
308 let mut is_raw = false;
312 // check for ID3v{2-4}
313 let mut buf = [0; 5];
315 if br.peek_buf(&mut buf).is_err() {
318 if &buf[0..3] == b"ID3" && buf[3] > 0 && buf[3] < 5 && buf[4] == 0 { //ID3 tag found, must be a raw stream
319 br.read_skip(6).unwrap();
322 let b = br.read_byte().unwrap();
324 println!("Invalid ID3 size");
327 size = (size << 7) | u64::from(b);
330 br.read_skip(size as usize).unwrap();
331 while let Ok(0) = br.read_byte() {
334 br.seek(SeekFrom::Start(start)).unwrap();
341 br.seek(SeekFrom::End(-128)).unwrap();
343 br.peek_buf(&mut buf[..3]).unwrap();
344 if &buf[0..3] == b"TAG" {
346 // check for Lyrics v2
347 let mut sig = [0; 9];
348 br.seek(SeekFrom::End(-128 - 9)).unwrap();
349 br.peek_buf(&mut sig).unwrap();
350 if &sig == b"LYRICS200" {
351 br.seek(SeekFrom::Current(-6)).unwrap();
352 let mut sizestr = [0; 6];
353 br.peek_buf(&mut sizestr).unwrap();
354 if let Ok(sstr) = std::str::from_utf8(&sizestr) {
355 if let Ok(size) = sstr.parse::<u64>() {
356 end = Some(br.tell() - size);
362 let mut buf = [0; 8];
363 if let Some(off) = end {
364 br.seek(SeekFrom::Start(off - 32)).unwrap();
366 br.seek(SeekFrom::End(-32)).unwrap();
369 br.read_buf(&mut buf).unwrap();
370 if &buf == b"APETAGEX" {
371 let ver = br.read_u32le().unwrap();
372 let size = u64::from(br.read_u32le().unwrap());
373 let _items = br.read_u32le().unwrap();
374 let flags = br.read_u32le().unwrap();
375 if ver == 1000 || (flags & 0x80000000) == 0 {
376 end = Some(off - size + 32);
378 end = Some(off - size);
381 // check for MusicMatch tag
382 let ret = if let Some(endpos) = end {
383 br.seek(SeekFrom::Start(endpos - 0x30))
385 br.seek(SeekFrom::End(-0x30))
387 if ret.is_ok() && br.tell() > (0x2000 - 0x30) {
388 let mut buf = [0; 19];
389 br.peek_buf(&mut buf).unwrap();
390 if &buf == b"Brava Software Inc." {
391 br.seek(SeekFrom::Current(-20)).unwrap();
392 let mut mm_start = u64::from(br.read_u32le().unwrap());
393 if mm_start > 4 && mm_start + 0x2000 <= br.tell() {
394 let diff = (br.tell() - mm_start) & 3;
396 mm_start -= 4 - diff;
398 end = Some(mm_start);