]> git.nihav.org Git - nihav.git/blame - nihav-rad/src/demuxers/bink.rs
bink demuxer: skip unknown field in KB2i
[nihav.git] / nihav-rad / src / demuxers / bink.rs
CommitLineData
606c448e
KS
1use nihav_core::demuxers::*;
2use nihav_core::io::byteio::ByteReader;
3
c6c21059
KS
4struct AudioTrack {
5 id: usize,
6}
7
8const BINK_AUD_FLAG_DCT: u8 = 0x10;
9const BINK_AUD_FLAG_STEREO: u8 = 0x20;
10
11impl AudioTrack {
bce85425 12 fn new(strmgr: &mut StreamManager, srate: u32, flags: u8, str_id: usize, magic: &[u8; 4]) -> DemuxerResult<Self> {
c6c21059
KS
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);
bce85425
KS
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));
c6c21059
KS
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
30struct 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
42macro_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
51impl<'a> DemuxCore<'a> for BinkDemuxer<'a> {
52 fn open(&mut self, strmgr: &mut StreamManager) -> 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 let mut flags: [u8; 4] = [0; 4];
70 src.read_buf(&mut flags)?;
71 let mut edata: Vec<u8> = Vec::with_capacity(8);
72 edata.resize(8, 0);
73 let p0 = &mut edata[0..4];
74 p0.copy_from_slice(&magic);
75 let p1 = &mut edata[4..][..4];
76 p1.copy_from_slice(&flags);
77 let vhdr = NAVideoInfo::new(width, height, false, YUV420_FORMAT);
78 let codec = if magic[0] == b'K' && magic[1] == b'B' && magic[2] == b'2' { "bink2-video" } else { "bink-video" };
79 let vinfo = NACodecInfo::new(codec, NACodecTypeInfo::Video(vhdr), Some(edata));
80 let res = strmgr.add_stream(NAStream::new(StreamType::Video, 0, vinfo, self.tb_num, self.tb_den));
81 validate!(res.is_some());
82 self.video_id = res.unwrap();
83
84 let num_audio = src.read_u32le()? as usize;
ffdf2c7f
KS
85 if magic_tag >= mktag!(b"KB2i") {
86 src.read_skip(4)?;
87 }
c6c21059
KS
88 validate!(num_audio < 256);
89 src.read_skip(num_audio * 4)?; // audio max output frame size?
90 self.ainfo = Vec::with_capacity(num_audio);
91 for i in 0..num_audio {
92 let srate = src.read_u24le()?;
93 let flags = src.read_byte()?;
94 validate!(srate > 0);
bce85425 95 self.ainfo.push(AudioTrack::new(strmgr, srate, flags, i, &magic)?);
c6c21059
KS
96 }
97 for _ in 0..num_audio {
98 let _trk_id = src.read_u32le()?;
99 }
100
101 self.frame_pos = Vec::with_capacity(self.frames + 1);
102 for _ in 0..self.frames+1 {
103 let pos = src.read_u32le()?;
104 self.frame_pos.push(pos);
105 }
106 validate!((src.tell() as u32) == (self.frame_pos[0] & !1));
107
108 self.cur_frame = 0;
109
110 Ok(())
111 }
112 fn get_frame(&mut self, strmgr: &mut StreamManager) -> DemuxerResult<NAPacket> {
113 if !self.queued_packets.is_empty() {
114 let pkt = self.queued_packets.pop().unwrap();
115 return Ok(pkt);
116 }
117 if self.cur_frame >= self.frames { return Err(DemuxerError::EOF); }
118 let mut payload_size = ((self.frame_pos[self.cur_frame + 1] & !1) - (self.frame_pos[self.cur_frame] & !1)) as usize;
119 validate!(payload_size > self.ainfo.len() * 4);
120 for atrk in self.ainfo.iter() {
121 let size = self.src.read_u32le()? as usize;
122 validate!(payload_size > size + 4);
123 payload_size -= size + 4;
124
5faa5676
KS
125 if size > 0 {
126 let strres = strmgr.get_stream(atrk.id);
127 validate!(strres.is_some());
128 let stream = strres.unwrap();
129 let ts = NATimeInfo::new(Some(self.cur_frame as u64), None, None, self.tb_num, self.tb_den);
130 let pkt = self.src.read_packet(stream.clone(), ts, true, size)?;
131 self.queued_packets.push(pkt);
132 }
c6c21059
KS
133 }
134 self.queued_packets.reverse();
135
136 let strres = strmgr.get_stream(self.video_id);
137 validate!(strres.is_some());
138 let stream = strres.unwrap();
139 let keyframe = (self.frame_pos[self.cur_frame] & 1) != 0;
140 let ts = NATimeInfo::new(Some(self.cur_frame as u64), None, None, self.tb_num, self.tb_den);
141 let pkt = self.src.read_packet(stream.clone(), ts, keyframe, payload_size)?;
142
143 self.cur_frame += 1;
144
145 Ok(pkt)
146 }
147 #[allow(unused_variables)]
148 fn seek(&mut self, time: u64) -> DemuxerResult<()> {
149 Err(DemuxerError::NotImplemented)
150 }
151}
152
153impl<'a> BinkDemuxer<'a> {
154 fn new(io: &'a mut ByteReader<'a>) -> Self {
155 Self {
156 src: io,
157 cur_frame: 0,
158 frames: 0,
159 video_id: 0,
160 tb_num: 0,
161 tb_den: 0,
162 ainfo: Vec::new(),
163 queued_packets: Vec::new(),
164 frame_pos: Vec::new(),
165 }
166 }
167}
168
169
606c448e
KS
170pub struct BinkDemuxerCreator { }
171
172impl DemuxerCreator for BinkDemuxerCreator {
173 fn new_demuxer<'a>(&self, br: &'a mut ByteReader<'a>) -> Box<DemuxCore<'a> + 'a> {
c6c21059 174 Box::new(BinkDemuxer::new(br))
606c448e
KS
175 }
176 fn get_name(&self) -> &'static str { "bink" }
177}
178
c6c21059
KS
179#[cfg(test)]
180mod test {
181 use super::*;
182 use std::fs::File;
183
184 #[test]
185 fn test_bink_demux() {
186 let mut file = File::open("assets/RAD/ActivisionLogo.bik").unwrap();
187// let mut file = File::open("assets/RAD/original.bik").unwrap();
188// let mut file = File::open("assets/RAD/Snd0a110c51.dee").unwrap();
189// let mut file = File::open("assets/RAD/NEW.BIK").unwrap();
190// let mut file = File::open("assets/RAD/ge_video_86l.bk2").unwrap();
191 let mut fr = FileReader::new_read(&mut file);
192 let mut br = ByteReader::new(&mut fr);
193 let mut dmx = BinkDemuxer::new(&mut br);
194 let mut sm = StreamManager::new();
195 dmx.open(&mut sm).unwrap();
196 loop {
197 let pktres = dmx.get_frame(&mut sm);
198 if let Err(e) = pktres {
199 if (e as i32) == (DemuxerError::EOF as i32) { break; }
200 panic!("error");
201 }
202 let pkt = pktres.unwrap();
203 println!("Got {}", pkt);
204 }
205 }
206}