]> git.nihav.org Git - nihav.git/blob - nihav-rad/src/demuxers/bink.rs
fix re-exports of crate submodules
[nihav.git] / nihav-rad / src / demuxers / bink.rs
1 use nihav_core::demuxers::*;
2 use nihav_core::io::byteio::ByteReader;
3
4 struct AudioTrack {
5 id: usize,
6 }
7
8 const BINK_AUD_FLAG_DCT: u8 = 0x10;
9 const BINK_AUD_FLAG_STEREO: u8 = 0x20;
10
11 impl AudioTrack {
12 fn new(strmgr: &mut StreamManager, srate: u32, flags: u8, str_id: usize, magic: &[u8; 4]) -> DemuxerResult<Self> {
13 let channels = if (flags & BINK_AUD_FLAG_STEREO) != 0 { 2 } else { 1 };
14 let codecname = if (flags & BINK_AUD_FLAG_DCT) != 0 {
15 "bink-audio-dct"
16 } else {
17 "bink-audio-rdft"
18 };
19 let ahdr = NAAudioInfo::new(srate, channels, SND_F32P_FORMAT, 1);
20 let mut edata: Vec<u8> = Vec::with_capacity(4);
21 edata.extend_from_slice(magic);
22 let ainfo = NACodecInfo::new(codecname, NACodecTypeInfo::Audio(ahdr), Some(edata));
23 let res = strmgr.add_stream(NAStream::new(StreamType::Audio, (str_id + 1) as u32, ainfo, 1, srate));
24 validate!(res.is_some());
25 let id = res.unwrap();
26 Ok(Self{ id })
27 }
28 }
29
30 struct BinkDemuxer<'a> {
31 src: &'a mut ByteReader<'a>,
32 cur_frame: usize,
33 frames: usize,
34 video_id: usize,
35 tb_num: u32,
36 tb_den: u32,
37 ainfo: Vec<AudioTrack>,
38 queued_packets: Vec<NAPacket>,
39 frame_pos: Vec<u32>,
40 }
41
42 macro_rules! mktag {
43 ($a:expr, $b:expr, $c:expr, $d:expr) => ({
44 (($a as u32) << 24) | (($b as u32) << 16) | (($c as u32) << 8) | ($d as u32)
45 });
46 ($arr:expr) => ({
47 (($arr[0] as u32) << 24) | (($arr[1] as u32) << 16) | (($arr[2] as u32) << 8) | ($arr[3] as u32)
48 });
49 }
50
51 impl<'a> DemuxCore<'a> for BinkDemuxer<'a> {
52 fn open(&mut self, strmgr: &mut StreamManager, seek_idx: &mut SeekIndex) -> DemuxerResult<()> {
53 let src = &mut self.src;
54 let mut magic: [u8; 4] = [0; 4];
55 src.read_buf(&mut magic)?;
56 let magic_tag = mktag!(magic);
57 validate!((magic_tag >= mktag!(b"BIKb") && magic_tag <= mktag!(b"BIKk")) ||
58 (magic_tag >= mktag!(b"KB2a") && magic_tag <= mktag!(b"KB2k")));
59 let fsize = (src.read_u32le()? as usize) + 8;
60 self.frames = src.read_u32le()? as usize;
61 let max_size = src.read_u32le()? as usize;
62 let _frames2 = src.read_u32le()? as usize;
63 let width = src.read_u32le()? as usize;
64 let height = src.read_u32le()? as usize;
65 let tb_den = src.read_u32le()?;
66 let tb_num = src.read_u32le()?;
67 validate!((width > 0) && (height > 0) && (width <= 7680) && (height <= 4800));
68 validate!((self.frames > 0) && (tb_num > 0) && (tb_den > 0) && (max_size < fsize));
69 self.tb_num = tb_num;
70 self.tb_den = tb_den;
71 let mut flags: [u8; 4] = [0; 4];
72 src.read_buf(&mut flags)?;
73 let mut edata: Vec<u8> = vec![0; 8];
74 let p0 = &mut edata[0..4];
75 p0.copy_from_slice(&magic);
76 let p1 = &mut edata[4..][..4];
77 p1.copy_from_slice(&flags);
78 let vhdr = NAVideoInfo::new(width, height, false, YUV420_FORMAT);
79 let codec = if magic[0] == b'K' && magic[1] == b'B' && magic[2] == b'2' { "bink2-video" } else { "bink-video" };
80 let vinfo = NACodecInfo::new(codec, NACodecTypeInfo::Video(vhdr), Some(edata));
81 let res = strmgr.add_stream(NAStream::new(StreamType::Video, 0, vinfo, self.tb_num, self.tb_den));
82 validate!(res.is_some());
83 self.video_id = res.unwrap();
84
85 let num_audio = src.read_u32le()? as usize;
86 if magic_tag >= mktag!(b"KB2i") {
87 src.read_skip(4)?;
88 }
89 validate!(num_audio < 256);
90 src.read_skip(num_audio * 4)?; // audio max output frame size?
91 self.ainfo = Vec::with_capacity(num_audio);
92 for i in 0..num_audio {
93 let srate = src.read_u24le()?;
94 let flags = src.read_byte()?;
95 validate!(srate > 0);
96 self.ainfo.push(AudioTrack::new(strmgr, srate, flags, i, &magic)?);
97 }
98 for _ in 0..num_audio {
99 let _trk_id = src.read_u32le()?;
100 }
101
102 seek_idx.mode = SeekIndexMode::Present;
103 seek_idx.add_stream(0);
104 self.frame_pos = Vec::with_capacity(self.frames + 1);
105 for fno in 0..=self.frames {
106 let pos = src.read_u32le()?;
107 self.frame_pos.push(pos);
108 if (pos & 1) != 0 {
109 let time = (fno as u64) * 1000 * (tb_num as u64) / (tb_den as u64);
110 seek_idx.seek_info[0].add_entry(SeekEntry { time, pts: fno as u64, pos: (pos & !1) as u64 });
111 }
112 }
113 validate!((src.tell() as u32) == (self.frame_pos[0] & !1));
114 seek_idx.seek_info[0].filled = true;
115
116 self.cur_frame = 0;
117
118 Ok(())
119 }
120 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
121 if !self.queued_packets.is_empty() {
122 let pkt = self.queued_packets.pop().unwrap();
123 return Ok(pkt);
124 }
125 if self.cur_frame >= self.frames { return Err(DemuxerError::EOF); }
126 let mut payload_size = ((self.frame_pos[self.cur_frame + 1] & !1) - (self.frame_pos[self.cur_frame] & !1)) as usize;
127 validate!(payload_size > self.ainfo.len() * 4);
128 for atrk in self.ainfo.iter() {
129 let size = self.src.read_u32le()? as usize;
130 validate!(payload_size > size + 4);
131 payload_size -= size + 4;
132
133 if size > 0 {
134 let strres = strmgr.get_stream(atrk.id);
135 validate!(strres.is_some());
136 let stream = strres.unwrap();
137 let ts = NATimeInfo::new(Some(self.cur_frame as u64), None, None, self.tb_num, self.tb_den);
138 let pkt = self.src.read_packet(stream.clone(), ts, true, size)?;
139 self.queued_packets.push(pkt);
140 }
141 }
142 self.queued_packets.reverse();
143
144 let strres = strmgr.get_stream(self.video_id);
145 validate!(strres.is_some());
146 let stream = strres.unwrap();
147 let keyframe = (self.frame_pos[self.cur_frame] & 1) != 0;
148 let ts = NATimeInfo::new(Some(self.cur_frame as u64), None, None, self.tb_num, self.tb_den);
149 let pkt = self.src.read_packet(stream.clone(), ts, keyframe, payload_size)?;
150
151 self.cur_frame += 1;
152
153 Ok(pkt)
154 }
155 fn seek(&mut self, time: u64, seek_idx: &SeekIndex) -> DemuxerResult<()> {
156 let ret = seek_idx.find_pos(time);
157 if ret.is_none() {
158 return Err(DemuxerError::SeekError);
159 }
160 let seek_info = ret.unwrap();
161 self.src.seek(SeekFrom::Start(seek_info.pos))?;
162 self.queued_packets.clear();
163 self.cur_frame = seek_info.pts as usize;
164 Ok(())
165 }
166 }
167
168 impl<'a> BinkDemuxer<'a> {
169 fn new(io: &'a mut ByteReader<'a>) -> Self {
170 Self {
171 src: io,
172 cur_frame: 0,
173 frames: 0,
174 video_id: 0,
175 tb_num: 0,
176 tb_den: 0,
177 ainfo: Vec::new(),
178 queued_packets: Vec::new(),
179 frame_pos: Vec::new(),
180 }
181 }
182 }
183
184
185 pub struct BinkDemuxerCreator { }
186
187 impl DemuxerCreator for BinkDemuxerCreator {
188 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
189 Box::new(BinkDemuxer::new(br))
190 }
191 fn get_name(&self) -> &'static str { "bink" }
192 }
193
194 #[cfg(test)]
195 mod test {
196 use super::*;
197 use std::fs::File;
198
199 #[test]
200 fn test_bink_demux() {
201 let mut file = File::open("assets/RAD/ActivisionLogo.bik").unwrap();
202 // let mut file = File::open("assets/RAD/original.bik").unwrap();
203 // let mut file = File::open("assets/RAD/Snd0a110c51.dee").unwrap();
204 // let mut file = File::open("assets/RAD/NEW.BIK").unwrap();
205 // let mut file = File::open("assets/RAD/ge_video_86l.bk2").unwrap();
206 let mut fr = FileReader::new_read(&mut file);
207 let mut br = ByteReader::new(&mut fr);
208 let mut dmx = BinkDemuxer::new(&mut br);
209 let mut sm = StreamManager::new();
210 let mut si = SeekIndex::new();
211 dmx.open(&mut sm, &mut si).unwrap();
212 loop {
213 let pktres = dmx.get_frame(&mut sm);
214 if let Err(e) = pktres {
215 if (e as i32) == (DemuxerError::EOF as i32) { break; }
216 panic!("error");
217 }
218 let pkt = pktres.unwrap();
219 println!("Got {}", pkt);
220 }
221 }
222 }