1 use nihav_core::codecs::*;
2 use nihav_core::io::byteio::*;
5 const ADAPT_TABLE: [i32; 16] = [
6 230, 230, 230, 230, 307, 409, 512, 614,
7 768, 614, 512, 409, 307, 230, 230, 230
9 const ADAPT_COEFFS: [[i32; 2]; 7] = [
10 [ 256, 0 ], [ 512, -256 ], [ 0, 0 ], [ 192, 64 ],
11 [ 240, 0 ], [ 460, -208 ], [ 392, -232 ]
24 fn expand_nibble(&mut self, nibble: u8) -> i16 {
25 let mul = if (nibble & 8) == 0 { i32::from(nibble) } else { i32::from(nibble) - 16 };
26 let pred = self.calc_pred() + self.delta.wrapping_mul(mul);
27 self.update(pred.max(-0x8000).min(0x7FFF));
28 self.delta = (ADAPT_TABLE[nibble as usize].wrapping_mul(self.delta) >> 8).max(16);
31 fn calc_pred(&self) -> i32 {
32 self.sample1.wrapping_mul(self.coef1).wrapping_add(self.sample2.wrapping_mul(self.coef2)) >> 8
34 fn update(&mut self, new_samp: i32) {
35 self.sample2 = self.sample1;
36 self.sample1 = new_samp;
40 struct MSADPCMDecoder {
43 adapt_coeffs: Vec<[i32; 2]>,
51 ainfo: NAAudioInfo::new(0, 1, SND_S16P_FORMAT, 0),
52 chmap: NAChannelMap::new(),
53 adapt_coeffs: Vec::with_capacity(7),
60 impl NADecoder for MSADPCMDecoder {
61 #[allow(clippy::int_plus_one)]
62 fn init(&mut self, _supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()> {
63 if let NACodecTypeInfo::Audio(ainfo) = info.get_properties() {
64 self.block_len = ainfo.get_block_len();
65 let channels = ainfo.get_channels() as usize;
66 validate!(channels == 2 || channels == 1);
67 validate!(self.block_len >= 7 * channels + 1);
68 self.block_samps = (self.block_len / channels - 7) * 2 + 2;
69 self.ainfo = NAAudioInfo::new(ainfo.get_sample_rate(), channels as u8, SND_S16P_FORMAT, self.block_samps);
70 self.chmap = NAChannelMap::from_str(if channels == 1 { "C" } else { "L,R" }).unwrap();
71 self.adapt_coeffs.truncate(0);
72 if let Some(ref buf) = info.get_extradata() {
73 validate!(buf.len() >= 6);
74 validate!((buf.len() & 3) == 0);
75 let mut mr = MemoryReader::new_read(buf.as_slice());
76 let mut br = ByteReader::new(&mut mr);
77 let _smth = br.read_u16le()?;
78 let ncoeffs = br.read_u16le()? as usize;
79 validate!(buf.len() == ncoeffs * 4 + 4);
83 i32::from(br.read_u16le()? as i16),
84 i32::from(br.read_u16le()? as i16)];
85 self.adapt_coeffs.push(pair);
88 self.adapt_coeffs.extend_from_slice(&ADAPT_COEFFS);
92 Err(DecoderError::InvalidData)
95 fn decode(&mut self, _supp: &mut NADecoderSupport, pkt: &NAPacket) -> DecoderResult<NAFrameRef> {
96 let info = pkt.get_stream().get_info();
97 if let NACodecTypeInfo::Audio(_) = info.get_properties() {
98 let pktbuf = pkt.get_buffer();
99 let channels = self.chmap.num_channels();
100 validate!(!pktbuf.is_empty() && (pktbuf.len() % self.block_len) == 0);
101 let nblocks = pktbuf.len() / self.block_len;
102 let nsamples = nblocks * self.block_samps;
103 let abuf = alloc_audio_buffer(self.ainfo, nsamples, self.chmap.clone())?;
104 let mut adata = abuf.get_abuf_i16().unwrap();
105 let mut off = [adata.get_offset(0), adata.get_offset(1)];
106 let dst = adata.get_data_mut().unwrap();
108 let mut pred = [Predictor::default(), Predictor::default()];
110 for blk in pktbuf.chunks(self.block_len) {
111 let mut mr = MemoryReader::new_read(blk);
112 let mut br = ByteReader::new(&mut mr);
113 for ch in 0..channels {
114 let coef_idx = br.read_byte()? as usize;
115 validate!(coef_idx < self.adapt_coeffs.len());
116 pred[ch].coef1 = self.adapt_coeffs[coef_idx][0];
117 pred[ch].coef2 = self.adapt_coeffs[coef_idx][1];
119 for ch in 0..channels {
120 pred[ch].delta = i32::from(br.read_u16le()?);
122 for ch in 0..channels {
123 let samp = br.read_u16le()? as i16;
124 pred[ch].sample2 = i32::from(samp);
126 for ch in 0..channels {
127 let samp = br.read_u16le()? as i16;
128 pred[ch].sample1 = i32::from(samp);
130 for ch in 0..channels {
131 dst[off[ch]] = pred[ch].sample2 as i16;
132 dst[off[ch] + 1] = pred[ch].sample1 as i16;
136 while br.left() > 0 {
137 let idx = br.read_byte()?;
138 dst[off[0]] = pred[0].expand_nibble(idx >> 4);
140 dst[off[0]] = pred[0].expand_nibble(idx & 0xF);
144 while br.left() > 0 {
145 let idx = br.read_byte()?;
146 dst[off[0]] = pred[0].expand_nibble(idx >> 4);
148 dst[off[1]] = pred[1].expand_nibble(idx & 0xF);
153 let mut frm = NAFrame::new_from_pkt(pkt, info.replace_info(NACodecTypeInfo::Audio(self.ainfo)), abuf);
154 frm.set_duration(Some(nsamples as u64));
155 frm.set_keyframe(false);
158 Err(DecoderError::InvalidData)
161 fn flush(&mut self) {
165 impl NAOptionHandler for MSADPCMDecoder {
166 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
167 fn set_options(&mut self, _options: &[NAOption]) { }
168 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
171 pub fn get_decoder() -> Box<dyn NADecoder + Send> {
172 Box::new(MSADPCMDecoder::new())
176 struct MSADPCMEncoder {
177 stream: Option<NAStreamRef>,
185 const DEFAULT_BLOCK_LEN: usize = 256;
187 impl MSADPCMEncoder {
188 fn new() -> Self { Self::default() }
189 fn encode_packet(&mut self) -> EncoderResult<NAPacket> {
190 if self.samples.is_empty() {
191 return Err(EncoderError::TryAgain);
193 let len = (self.samples.len() / self.channels).min(self.block_len);
194 if len < self.block_len && !self.flush {
195 return Err(EncoderError::TryAgain);
199 return Err(EncoderError::TryAgain);
202 let mut dbuf = vec![0u8; Self::calc_block_size(len, self.channels)];
203 let mut mw = MemoryWriter::new_write(dbuf.as_mut_slice());
204 let mut bw = ByteWriter::new(&mut mw);
206 let mut best_idx = [0usize; 2];
207 for ch in 0..self.channels {
208 let mut best_dist = std::i64::MAX;
209 for i in 0..ADAPT_COEFFS.len() {
210 let dist = self.calc_dist(ch, i, len);
211 if dist < best_dist {
216 bw.write_byte(best_idx[ch] as u8)?;
218 let mut dec = [Predictor::default(), Predictor::default()];
219 for ch in 0..self.channels {
220 dec[ch].sample1 = i32::from(self.samples[ch + self.channels]);
221 dec[ch].sample2 = i32::from(self.samples[ch]);
222 dec[ch].coef1 = ADAPT_COEFFS[best_idx[ch]][0];
223 dec[ch].coef2 = ADAPT_COEFFS[best_idx[ch]][1];
225 let pred = dec[ch].calc_pred();
226 dec[ch].delta = ((i32::from(self.samples[ch + self.channels * 2]) - pred).abs() / 4).max(16);
231 for ch in 0..self.channels {
232 bw.write_u16le(dec[ch].delta as u16)?;
234 for ch in 0..self.channels {
235 bw.write_u16le(dec[ch].sample1 as u16)?;
237 for ch in 0..self.channels {
238 bw.write_u16le(dec[ch].sample2 as u16)?;
240 if self.channels == 1 {
241 for samps in self.samples.chunks(2).skip(1).take(len/2 - 1) {
242 let diff = i32::from(samps[0]) - dec[0].calc_pred();
243 let nib0 = Self::calculate_mul(dec[0].delta, diff);
244 dec[0].expand_nibble(nib0);
245 let diff = i32::from(samps[1]) - dec[0].calc_pred();
246 let nib1 = Self::calculate_mul(dec[0].delta, diff);
247 dec[0].expand_nibble(nib1);
248 bw.write_byte(nib0 * 16 + nib1)?;
251 for samps in self.samples.chunks(2).skip(2).take(len - 2) {
252 let diff = i32::from(samps[0]) - dec[0].calc_pred();
253 let nib0 = Self::calculate_mul(dec[0].delta, diff);
254 dec[0].expand_nibble(nib0);
255 let diff = i32::from(samps[1]) - dec[1].calc_pred();
256 let nib1 = Self::calculate_mul(dec[1].delta, diff);
257 dec[1].expand_nibble(nib1);
258 bw.write_byte(nib0 * 16 + nib1)?;
261 self.samples.drain(..len * self.channels);
263 let ts = NATimeInfo::new(None, None, Some(1), 1, self.srate);
264 Ok(NAPacket::new(self.stream.clone().unwrap(), ts, true, dbuf))
266 fn calc_dist(&self, ch: usize, idx: usize, len: usize) -> i64 {
268 let mut dec = Predictor {
269 sample2: i32::from(self.samples[ch]),
270 sample1: i32::from(self.samples[ch + self.channels]),
271 coef1: ADAPT_COEFFS[idx][0],
272 coef2: ADAPT_COEFFS[idx][1],
275 if self.channels == 1 {
276 for samp in self.samples.iter().skip(2).take(len - 2) {
277 let pred = dec.calc_pred();
279 let diff = i64::from(*samp) - i64::from(pred);
283 for samp in self.samples.chunks(2).skip(2).take(len - 2) {
284 let pred = dec.calc_pred();
286 let diff = i64::from(samp[ch]) - i64::from(pred);
292 fn calculate_mul(delta: i32, diff: i32) -> u8 {
293 ((diff / delta).max(-8).min(7) & 0xF) as u8
295 fn calc_block_size(nsamps: usize, channels: usize) -> usize {
296 (nsamps - 2) * channels / 2 + 7 * channels
300 impl NAEncoder for MSADPCMEncoder {
301 fn negotiate_format(&self, encinfo: &EncodeParameters) -> EncoderResult<EncodeParameters> {
302 match encinfo.format {
303 NACodecTypeInfo::None => {
304 let mut ofmt = EncodeParameters::default();
305 ofmt.format = NACodecTypeInfo::Audio(NAAudioInfo::new(0, 1, SND_S16_FORMAT, DEFAULT_BLOCK_LEN));
308 NACodecTypeInfo::Video(_) => Err(EncoderError::FormatError),
309 NACodecTypeInfo::Audio(ainfo) => {
310 let mut outinfo = ainfo;
311 outinfo.channels = outinfo.channels.min(2);
312 if outinfo.format != SND_S16P_FORMAT && outinfo.format != SND_S16_FORMAT {
313 outinfo.format = SND_S16_FORMAT;
315 if outinfo.block_len == 0 {
316 outinfo.block_len = DEFAULT_BLOCK_LEN;
318 if outinfo.block_len < 2 {
319 outinfo.block_len = 2;
321 if (outinfo.channels == 1) && ((outinfo.block_len & 1) == 1) {
322 outinfo.block_len += 1;
324 let mut ofmt = *encinfo;
325 ofmt.format = NACodecTypeInfo::Audio(outinfo);
330 fn init(&mut self, stream_id: u32, encinfo: EncodeParameters) -> EncoderResult<NAStreamRef> {
331 match encinfo.format {
332 NACodecTypeInfo::None => Err(EncoderError::FormatError),
333 NACodecTypeInfo::Video(_) => Err(EncoderError::FormatError),
334 NACodecTypeInfo::Audio(ainfo) => {
335 if ainfo.format != SND_S16P_FORMAT && ainfo.format != SND_S16_FORMAT {
336 return Err(EncoderError::FormatError);
338 if ainfo.channels != 1 && ainfo.channels != 2 {
339 return Err(EncoderError::FormatError);
341 if ainfo.block_len < 2 || ((ainfo.block_len * (ainfo.channels as usize)) & 1) != 0 {
342 return Err(EncoderError::FormatError);
344 self.channels = ainfo.channels as usize;
345 self.block_len = ainfo.block_len;
347 let soniton = NASoniton::new(4, 0);
348 let out_ainfo = NAAudioInfo::new(ainfo.sample_rate, ainfo.channels, soniton, Self::calc_block_size(self.block_len, self.channels));
349 let info = NACodecInfo::new("ms-adpcm", NACodecTypeInfo::Audio(out_ainfo), None);
350 let mut stream = NAStream::new(StreamType::Audio, stream_id, info, self.block_len as u32, ainfo.sample_rate, 0);
351 stream.set_num(stream_id as usize);
352 let stream = stream.into_ref();
354 self.stream = Some(stream.clone());
355 self.samples = Vec::with_capacity(self.block_len * self.channels);
356 self.srate = ainfo.sample_rate;
363 fn encode(&mut self, frm: &NAFrame) -> EncoderResult<()> {
364 let buf = frm.get_buffer();
365 if let Some(ref abuf) = buf.get_abuf_i16() {
366 let src = abuf.get_data();
367 let len = abuf.get_length();
368 let ch = abuf.get_chmap().num_channels();
369 if abuf.get_step() > 1 || ch == 1 {
370 self.samples.extend(src.iter().take(len * ch));
372 let (src0, src1) = src.split_at(abuf.get_stride());
373 self.samples.reserve(len * 2);
374 for (s0, s1) in src0.iter().take(len).zip(src1.iter()) {
375 self.samples.push(*s0);
376 self.samples.push(*s1);
381 Err(EncoderError::InvalidParameters)
384 fn get_packet(&mut self) -> EncoderResult<Option<NAPacket>> {
385 if let Ok(pkt) = self.encode_packet() {
391 fn flush(&mut self) -> EncoderResult<()> {
397 impl NAOptionHandler for MSADPCMEncoder {
398 fn get_supported_options(&self) -> &[NAOptionDefinition] { &[] }
399 fn set_options(&mut self, _options: &[NAOption]) { }
400 fn query_option_value(&self, _name: &str) -> Option<NAValue> { None }
403 pub fn get_encoder() -> Box<dyn NAEncoder + Send> {
404 Box::new(MSADPCMEncoder::new())
409 use nihav_core::codecs::*;
410 use nihav_core::demuxers::*;
411 use nihav_core::muxers::*;
412 use nihav_codec_support::test::dec_video::*;
413 use nihav_codec_support::test::enc_video::*;
415 use nihav_commonfmt::*;
416 #[cfg(feature="decoder_ms_adpcm")]
418 fn test_ms_adpcm_decoder() {
419 let mut dmx_reg = RegisteredDemuxers::new();
420 generic_register_all_demuxers(&mut dmx_reg);
421 let mut dec_reg = RegisteredDecoders::new();
422 ms_register_all_decoders(&mut dec_reg);
424 test_decoding("avi", "ms-adpcm", "assets/MS/dance.avi", None, &dmx_reg, &dec_reg,
425 ExpectedTestResult::MD5([0xf5e3fc84, 0xbcabc11c, 0x33c6874e, 0xe05ecd14]));
427 #[cfg(feature="encoder_ms_adpcm")]
429 fn test_ms_adpcm_encoder() {
430 let mut dmx_reg = RegisteredDemuxers::new();
431 generic_register_all_demuxers(&mut dmx_reg);
432 let mut dec_reg = RegisteredDecoders::new();
433 generic_register_all_decoders(&mut dec_reg);
434 ms_register_all_decoders(&mut dec_reg);
435 let mut mux_reg = RegisteredMuxers::new();
436 generic_register_all_muxers(&mut mux_reg);
437 let mut enc_reg = RegisteredEncoders::new();
438 ms_register_all_encoders(&mut enc_reg);
440 let dec_config = DecoderTestParams {
442 in_name: "assets/Indeo/laser05.avi",
443 stream_type: StreamType::Audio,
447 let enc_config = EncoderTestParams {
449 enc_name: "ms-adpcm",
450 out_name: "msadpcm.wav",
453 let dst_ainfo = NAAudioInfo {
456 format: SND_S16_FORMAT,
459 let enc_params = EncodeParameters {
460 format: NACodecTypeInfo::Audio(dst_ainfo),
467 test_encoding_md5(&dec_config, &enc_config, enc_params, &[],
468 &[0xe1591a1e, 0x816d0239, 0x4cc42291, 0x4e6b69cb]);