]> git.nihav.org Git - nihav.git/blob - nihav-rad/src/demuxers/bink.rs
cf576f3763346b4f65f70074534297c0f8d96f1c
[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, 0));
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, self.frames as u64));
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, ts, keyframe, payload_size)?;
150
151 self.cur_frame += 1;
152
153 Ok(pkt)
154 }
155 fn seek(&mut self, time: NATimePoint, 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 fn get_duration(&self) -> u64 { 0 }
167 }
168
169 impl<'a> NAOptionHandler for BinkDemuxer<'a> {
170 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
171 fn set_options(&mut self, _options: &[NAOption]) { }
172 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
173 }
174
175 impl<'a> BinkDemuxer<'a> {
176 fn new(io: &'a mut ByteReader<'a>) -> Self {
177 Self {
178 src: io,
179 cur_frame: 0,
180 frames: 0,
181 video_id: 0,
182 tb_num: 0,
183 tb_den: 0,
184 ainfo: Vec::new(),
185 queued_packets: Vec::new(),
186 frame_pos: Vec::new(),
187 }
188 }
189 }
190
191
192 pub struct BinkDemuxerCreator { }
193
194 impl DemuxerCreator for BinkDemuxerCreator {
195 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<dyn DemuxCore<'a> + 'a> {
196 Box::new(BinkDemuxer::new(br))
197 }
198 fn get_name(&self) -> &'static str { "bink" }
199 }
200
201 #[cfg(test)]
202 mod test {
203 use super::*;
204 use std::fs::File;
205
206 #[test]
207 fn test_bink_demux() {
208 // sample: https://samples.mplayerhq.hu/game-formats/bink/ActivisionLogo.bik
209 let mut file = File::open("assets/RAD/ActivisionLogo.bik").unwrap();
210 // let mut file = File::open("assets/RAD/original.bik").unwrap();
211 // let mut file = File::open("assets/RAD/Snd0a110c51.dee").unwrap();
212 // let mut file = File::open("assets/RAD/NEW.BIK").unwrap();
213 // let mut file = File::open("assets/RAD/ge_video_86l.bk2").unwrap();
214 let mut fr = FileReader::new_read(&mut file);
215 let mut br = ByteReader::new(&mut fr);
216 let mut dmx = BinkDemuxer::new(&mut br);
217 let mut sm = StreamManager::new();
218 let mut si = SeekIndex::new();
219 dmx.open(&mut sm, &mut si).unwrap();
220 loop {
221 let pktres = dmx.get_frame(&mut sm);
222 if let Err(e) = pktres {
223 if (e as i32) == (DemuxerError::EOF as i32) { break; }
224 panic!("error");
225 }
226 let pkt = pktres.unwrap();
227 println!("Got {}", pkt);
228 }
229 }
230 }