lib.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. //! A decoder for the Nellymoser Asao audio format.
  2. //!
  3. //! Copyright (c) 2021 relrelb
  4. //! Based on code from the nelly2pcm and FFmpeg projects:
  5. //! Copyright (c) 2007 a840bda5870ba11f19698ff6eb9581dfb0f95fa5,
  6. //! 539459aeb7d425140b62a3ec7dbf6dc8e408a306, and
  7. //! 520e17cd55896441042b14df2566a6eb610ed444
  8. //! Copyright (c) 2007 Loic Minier <lool at dooz.org>
  9. //! Benjamin Larsson
  10. mod tables;
  11. use bitstream_io::{read::BitRead, BitReader, LittleEndian};
  12. use once_cell::sync::Lazy;
  13. use rustdct::{mdct::Mdct, DctPlanner};
  14. use std::{
  15. io::{Cursor, Read},
  16. sync::Arc,
  17. };
  18. use tables::*;
  19. const NELLY_BLOCK_LEN: usize = 64;
  20. const NELLY_HEADER_BITS: usize = 116;
  21. const NELLY_DETAIL_BITS: i32 = 198;
  22. const NELLY_BUF_LEN: usize = 128;
  23. const NELLY_FILL_LEN: usize = 124;
  24. const NELLY_BIT_CAP: i16 = 6;
  25. const NELLY_BASE_OFF: i32 = 4228;
  26. const NELLY_BASE_SHIFT: i16 = 19;
  27. const NELLY_SAMPLES: usize = NELLY_BUF_LEN * 2;
  28. static MDCT: Lazy<Arc<dyn Mdct<f32>>> =
  29. Lazy::new(|| DctPlanner::new().plan_mdct(NELLY_BUF_LEN, window));
  30. pub struct Decoder<R: Read> {
  31. reader: R,
  32. sample_rate: u32,
  33. state: [f32; NELLY_BUF_LEN],
  34. scratch: Vec<f32>,
  35. cur_frame: [f32; NELLY_SAMPLES],
  36. cur_sample: usize,
  37. }
  38. impl<R: Read> Decoder<R> {
  39. pub fn new(reader: R, sample_rate: u32) -> Self {
  40. Self {
  41. reader,
  42. sample_rate,
  43. state: [0.0; NELLY_BUF_LEN],
  44. scratch: vec![0.0; MDCT.get_scratch_len()],
  45. cur_frame: [0f32; NELLY_SAMPLES], // TODO: make uninitialized?
  46. cur_sample: 0,
  47. }
  48. }
  49. pub fn sample_rate(&self) -> u32 {
  50. self.sample_rate
  51. }
  52. fn next_frame(&mut self) -> Option<()> {
  53. let mut block = [0u8; NELLY_BLOCK_LEN];
  54. self.reader.read_exact(&mut block).ok()?;
  55. self.cur_frame = self.decode_block(&block);
  56. self.cur_sample = 0;
  57. Some(())
  58. }
  59. fn decode_block(&mut self, block: &[u8; NELLY_BLOCK_LEN]) -> [f32; NELLY_SAMPLES] {
  60. let mut buf = [0f32; NELLY_BUF_LEN];
  61. let mut pows = [0f32; NELLY_BUF_LEN];
  62. {
  63. let mut reader = BitReader::endian(Cursor::new(&block), LittleEndian);
  64. let mut val = NELLY_INIT_TABLE[reader.read::<u8>(6).unwrap() as usize] as f32;
  65. let mut ptr: usize = 0;
  66. for (i, x) in NELLY_BAND_SIZES_TABLE.iter().enumerate() {
  67. if i > 0 {
  68. val += NELLY_DELTA_TABLE[reader.read::<u8>(5).unwrap() as usize] as f32;
  69. }
  70. let pval = (val / 2048.0).exp2();
  71. for _ in 0..*x {
  72. buf[ptr] = val;
  73. pows[ptr] = pval;
  74. ptr += 1;
  75. }
  76. }
  77. }
  78. let bits = {
  79. let mut max = buf.iter().fold(0, |a, &b| a.max(b as i32));
  80. let mut shift = headroom(&mut max) - 16;
  81. let mut sbuf = [0i16; NELLY_BUF_LEN];
  82. for i in 0..NELLY_FILL_LEN {
  83. sbuf[i] = signed_shift(buf[i] as i32, shift as i32) as i16;
  84. sbuf[i] = ((3 * sbuf[i] as i32) >> 2) as i16;
  85. }
  86. let mut sum: i32 = sbuf.iter().map(|&s| s as i32).sum();
  87. shift += 11;
  88. let shift_saved = shift;
  89. sum -= NELLY_DETAIL_BITS << shift;
  90. shift += headroom(&mut sum);
  91. let mut small_off = (NELLY_BASE_OFF * (sum >> 16)) >> 15;
  92. shift = shift_saved - (NELLY_BASE_SHIFT + shift - 31);
  93. small_off = signed_shift(small_off, shift as i32);
  94. let mut bitsum = sum_bits(sbuf, shift_saved, small_off as i16);
  95. if bitsum != NELLY_DETAIL_BITS {
  96. let mut off = bitsum - NELLY_DETAIL_BITS;
  97. shift = 0;
  98. while off.abs() <= 16383 {
  99. off *= 2;
  100. shift += 1;
  101. }
  102. off = (off * NELLY_BASE_OFF) >> 15;
  103. shift = shift_saved - (NELLY_BASE_SHIFT + shift - 15);
  104. off = signed_shift(off, shift as i32);
  105. let mut last_off = small_off;
  106. let mut last_bitsum = bitsum;
  107. let mut last_j = 0;
  108. for j in 1..20 {
  109. last_off = small_off;
  110. small_off += off;
  111. last_bitsum = bitsum;
  112. last_j = j;
  113. bitsum = sum_bits(sbuf, shift_saved, small_off as i16);
  114. if (bitsum - NELLY_DETAIL_BITS) * (last_bitsum - NELLY_DETAIL_BITS) <= 0 {
  115. break;
  116. }
  117. }
  118. let mut big_off;
  119. let mut big_bitsum;
  120. let mut small_bitsum;
  121. if bitsum > NELLY_DETAIL_BITS {
  122. big_off = small_off;
  123. small_off = last_off;
  124. big_bitsum = bitsum;
  125. small_bitsum = last_bitsum;
  126. } else {
  127. big_off = last_off;
  128. big_bitsum = last_bitsum;
  129. small_bitsum = bitsum;
  130. }
  131. while bitsum != NELLY_DETAIL_BITS && last_j <= 19 {
  132. off = (big_off + small_off) >> 1;
  133. bitsum = sum_bits(sbuf, shift_saved, off as i16);
  134. if bitsum > NELLY_DETAIL_BITS {
  135. big_off = off;
  136. big_bitsum = bitsum;
  137. } else {
  138. small_off = off;
  139. small_bitsum = bitsum;
  140. }
  141. last_j += 1;
  142. }
  143. if (big_bitsum - NELLY_DETAIL_BITS).abs()
  144. >= (small_bitsum - NELLY_DETAIL_BITS).abs()
  145. {
  146. bitsum = small_bitsum;
  147. } else {
  148. small_off = big_off;
  149. bitsum = big_bitsum;
  150. }
  151. }
  152. let mut bits = [0i32; NELLY_BUF_LEN];
  153. for i in 0..NELLY_FILL_LEN {
  154. let mut tmp = sbuf[i] as i32 - small_off;
  155. tmp = ((tmp >> (shift_saved - 1)) + 1) >> 1;
  156. bits[i] = tmp.clamp(0, NELLY_BIT_CAP as i32);
  157. }
  158. if bitsum > NELLY_DETAIL_BITS {
  159. let mut i = 0;
  160. let mut tmp = 0;
  161. while tmp < NELLY_DETAIL_BITS {
  162. tmp += bits[i];
  163. i += 1;
  164. }
  165. bits[i - 1] -= tmp - NELLY_DETAIL_BITS;
  166. while i < NELLY_FILL_LEN {
  167. bits[i] = 0;
  168. i += 1;
  169. }
  170. }
  171. bits
  172. };
  173. let mut samples = [0f32; NELLY_SAMPLES];
  174. for i in 0..2 {
  175. let mut reader = BitReader::endian(Cursor::new(&block), LittleEndian);
  176. reader
  177. .skip(NELLY_HEADER_BITS as u32 + i * NELLY_DETAIL_BITS as u32)
  178. .unwrap();
  179. let input: Vec<f32> = (0..NELLY_BUF_LEN).map(|j| if j >= NELLY_FILL_LEN {
  180. 0.0
  181. } else if bits[j] <= 0 {
  182. std::f32::consts::FRAC_1_SQRT_2
  183. } else {
  184. let v = reader.read::<u8>(bits[j] as u32).unwrap();
  185. NELLY_DEQUANTIZATION_TABLE[((1 << bits[j]) - 1 + v) as usize] as f32
  186. } * pows[j]).collect();
  187. let slice = &mut samples[i as usize * NELLY_BUF_LEN..(i as usize + 1) * NELLY_BUF_LEN];
  188. for (i, x) in self.state.iter_mut().enumerate() {
  189. slice[i] = *x;
  190. *x = 0.0;
  191. }
  192. MDCT.process_imdct_with_scratch(&input, slice, &mut self.state, &mut self.scratch);
  193. }
  194. samples
  195. }
  196. }
  197. #[inline]
  198. fn signed_shift(i: i32, shift: i32) -> i32 {
  199. if shift > 0 {
  200. i << shift
  201. } else {
  202. i >> -shift
  203. }
  204. }
  205. fn sum_bits(buf: [i16; NELLY_BUF_LEN], shift: i16, off: i16) -> i32 {
  206. buf[0..NELLY_FILL_LEN].iter().fold(0i32, |ret, &i| {
  207. let b = i as i32 - off as i32;
  208. let b = ((b >> (shift - 1)) + 1) >> 1;
  209. ret + b.clamp(0, NELLY_BIT_CAP as i32)
  210. })
  211. }
  212. fn headroom(la: &mut i32) -> i16 {
  213. if *la == 0 {
  214. return 31;
  215. }
  216. let l = la.abs().leading_zeros() as i16 - 1;
  217. *la *= 1 << l;
  218. l
  219. }
  220. fn window(len: usize) -> Vec<f32> {
  221. (0..len)
  222. .map(|i| ((i as f32 + 0.5) / 128.0 * std::f32::consts::FRAC_PI_2).sin() / 8.0)
  223. .collect()
  224. }
  225. impl<R: AsRef<[u8]>> Decoder<Cursor<R>> {
  226. #[inline]
  227. pub fn reset(&mut self) {
  228. self.reader.set_position(0);
  229. self.state.iter_mut().for_each(|x| *x = 0.0);
  230. }
  231. }
  232. impl<R: Read> Iterator for Decoder<R> {
  233. type Item = f32;
  234. fn next(&mut self) -> Option<Self::Item> {
  235. if self.cur_sample >= NELLY_SAMPLES {
  236. self.next_frame()?;
  237. }
  238. let sample = self.cur_frame[self.cur_sample];
  239. self.cur_sample += 1;
  240. Some(sample)
  241. }
  242. }