You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

864 lines
31KB

  1. /*
  2. * Audio Processing Technology codec for Bluetooth (aptX)
  3. *
  4. * Copyright (C) 2017 Aurelien Jacobs <aurel@gnuage.org>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "libavutil/intreadwrite.h"
  23. #include "avcodec.h"
  24. #include "internal.h"
  25. #include "mathops.h"
  26. #include "audio_frame_queue.h"
  27. enum channels {
  28. LEFT,
  29. RIGHT,
  30. NB_CHANNELS
  31. };
  32. enum subbands {
  33. LF, // Low Frequency (0-5.5 kHz)
  34. MLF, // Medium-Low Frequency (5.5-11kHz)
  35. MHF, // Medium-High Frequency (11-16.5kHz)
  36. HF, // High Frequency (16.5-22kHz)
  37. NB_SUBBANDS
  38. };
  39. #define NB_FILTERS 2
  40. #define FILTER_TAPS 16
  41. typedef struct {
  42. int pos;
  43. int32_t buffer[2*FILTER_TAPS];
  44. } FilterSignal;
  45. typedef struct {
  46. FilterSignal outer_filter_signal[NB_FILTERS];
  47. FilterSignal inner_filter_signal[NB_FILTERS][NB_FILTERS];
  48. } QMFAnalysis;
  49. typedef struct {
  50. int32_t quantized_sample;
  51. int32_t quantized_sample_parity_change;
  52. int32_t error;
  53. } Quantize;
  54. typedef struct {
  55. int32_t quantization_factor;
  56. int32_t factor_select;
  57. int32_t reconstructed_difference;
  58. } InvertQuantize;
  59. typedef struct {
  60. int32_t prev_sign[2];
  61. int32_t s_weight[2];
  62. int32_t d_weight[24];
  63. int32_t pos;
  64. int32_t reconstructed_differences[48];
  65. int32_t previous_reconstructed_sample;
  66. int32_t predicted_difference;
  67. int32_t predicted_sample;
  68. } Prediction;
  69. typedef struct {
  70. int32_t codeword_history;
  71. int32_t dither_parity;
  72. int32_t dither[NB_SUBBANDS];
  73. QMFAnalysis qmf;
  74. Quantize quantize[NB_SUBBANDS];
  75. InvertQuantize invert_quantize[NB_SUBBANDS];
  76. Prediction prediction[NB_SUBBANDS];
  77. } Channel;
  78. typedef struct {
  79. int32_t sync_idx;
  80. Channel channels[NB_CHANNELS];
  81. AudioFrameQueue afq;
  82. } AptXContext;
  83. static const int32_t quantize_intervals_LF[65] = {
  84. -9948, 9948, 29860, 49808, 69822, 89926, 110144, 130502,
  85. 151026, 171738, 192666, 213832, 235264, 256982, 279014, 301384,
  86. 324118, 347244, 370790, 394782, 419250, 444226, 469742, 495832,
  87. 522536, 549890, 577936, 606720, 636290, 666700, 698006, 730270,
  88. 763562, 797958, 833538, 870398, 908640, 948376, 989740, 1032874,
  89. 1077948, 1125150, 1174700, 1226850, 1281900, 1340196, 1402156, 1468282,
  90. 1539182, 1615610, 1698514, 1789098, 1888944, 2000168, 2125700, 2269750,
  91. 2438670, 2642660, 2899462, 3243240, 3746078, 4535138, 5664098, 7102424,
  92. 8897462,
  93. };
  94. static const int32_t invert_quantize_dither_factors_LF[65] = {
  95. 9948, 9948, 9962, 9988, 10026, 10078, 10142, 10218,
  96. 10306, 10408, 10520, 10646, 10784, 10934, 11098, 11274,
  97. 11462, 11664, 11880, 12112, 12358, 12618, 12898, 13194,
  98. 13510, 13844, 14202, 14582, 14988, 15422, 15884, 16380,
  99. 16912, 17484, 18098, 18762, 19480, 20258, 21106, 22030,
  100. 23044, 24158, 25390, 26760, 28290, 30008, 31954, 34172,
  101. 36728, 39700, 43202, 47382, 52462, 58762, 66770, 77280,
  102. 91642, 112348, 144452, 199326, 303512, 485546, 643414, 794914,
  103. 1000124,
  104. };
  105. static const int32_t quantize_dither_factors_LF[65] = {
  106. 0, 4, 7, 10, 13, 16, 19, 22,
  107. 26, 28, 32, 35, 38, 41, 44, 47,
  108. 51, 54, 58, 62, 65, 70, 74, 79,
  109. 84, 90, 95, 102, 109, 116, 124, 133,
  110. 143, 154, 166, 180, 195, 212, 231, 254,
  111. 279, 308, 343, 383, 430, 487, 555, 639,
  112. 743, 876, 1045, 1270, 1575, 2002, 2628, 3591,
  113. 5177, 8026, 13719, 26047, 45509, 39467, 37875, 51303,
  114. 0,
  115. };
  116. static const int16_t quantize_factor_select_offset_LF[65] = {
  117. 0, -21, -19, -17, -15, -12, -10, -8,
  118. -6, -4, -1, 1, 3, 6, 8, 10,
  119. 13, 15, 18, 20, 23, 26, 29, 31,
  120. 34, 37, 40, 43, 47, 50, 53, 57,
  121. 60, 64, 68, 72, 76, 80, 85, 89,
  122. 94, 99, 105, 110, 116, 123, 129, 136,
  123. 144, 152, 161, 171, 182, 194, 207, 223,
  124. 241, 263, 291, 328, 382, 467, 522, 522,
  125. 522,
  126. };
  127. static const int32_t quantize_intervals_MLF[9] = {
  128. -89806, 89806, 278502, 494338, 759442, 1113112, 1652322, 2720256, 5190186,
  129. };
  130. static const int32_t invert_quantize_dither_factors_MLF[9] = {
  131. 89806, 89806, 98890, 116946, 148158, 205512, 333698, 734236, 1735696,
  132. };
  133. static const int32_t quantize_dither_factors_MLF[9] = {
  134. 0, 2271, 4514, 7803, 14339, 32047, 100135, 250365, 0,
  135. };
  136. static const int16_t quantize_factor_select_offset_MLF[9] = {
  137. 0, -14, 6, 29, 58, 96, 154, 270, 521,
  138. };
  139. static const int32_t quantize_intervals_MHF[3] = {
  140. -194080, 194080, 890562,
  141. };
  142. static const int32_t invert_quantize_dither_factors_MHF[3] = {
  143. 194080, 194080, 502402,
  144. };
  145. static const int32_t quantize_dither_factors_MHF[3] = {
  146. 0, 77081, 0,
  147. };
  148. static const int16_t quantize_factor_select_offset_MHF[3] = {
  149. 0, -33, 136,
  150. };
  151. static const int32_t quantize_intervals_HF[5] = {
  152. -163006, 163006, 542708, 1120554, 2669238,
  153. };
  154. static const int32_t invert_quantize_dither_factors_HF[5] = {
  155. 163006, 163006, 216698, 361148, 1187538,
  156. };
  157. static const int32_t quantize_dither_factors_HF[5] = {
  158. 0, 13423, 36113, 206598, 0,
  159. };
  160. static const int16_t quantize_factor_select_offset_HF[5] = {
  161. 0, -8, 33, 95, 262,
  162. };
  163. typedef const struct {
  164. const int32_t *quantize_intervals;
  165. const int32_t *invert_quantize_dither_factors;
  166. const int32_t *quantize_dither_factors;
  167. const int16_t *quantize_factor_select_offset;
  168. int tables_size;
  169. int32_t factor_max;
  170. int32_t prediction_order;
  171. } ConstTables;
  172. static ConstTables tables[NB_SUBBANDS] = {
  173. [LF] = { quantize_intervals_LF,
  174. invert_quantize_dither_factors_LF,
  175. quantize_dither_factors_LF,
  176. quantize_factor_select_offset_LF,
  177. FF_ARRAY_ELEMS(quantize_intervals_LF),
  178. 0x11FF, 24 },
  179. [MLF] = { quantize_intervals_MLF,
  180. invert_quantize_dither_factors_MLF,
  181. quantize_dither_factors_MLF,
  182. quantize_factor_select_offset_MLF,
  183. FF_ARRAY_ELEMS(quantize_intervals_MLF),
  184. 0x14FF, 12 },
  185. [MHF] = { quantize_intervals_MHF,
  186. invert_quantize_dither_factors_MHF,
  187. quantize_dither_factors_MHF,
  188. quantize_factor_select_offset_MHF,
  189. FF_ARRAY_ELEMS(quantize_intervals_MHF),
  190. 0x16FF, 6 },
  191. [HF] = { quantize_intervals_HF,
  192. invert_quantize_dither_factors_HF,
  193. quantize_dither_factors_HF,
  194. quantize_factor_select_offset_HF,
  195. FF_ARRAY_ELEMS(quantize_intervals_HF),
  196. 0x15FF, 12 },
  197. };
  198. static const int16_t quantization_factors[32] = {
  199. 2048, 2093, 2139, 2186, 2233, 2282, 2332, 2383,
  200. 2435, 2489, 2543, 2599, 2656, 2714, 2774, 2834,
  201. 2896, 2960, 3025, 3091, 3158, 3228, 3298, 3371,
  202. 3444, 3520, 3597, 3676, 3756, 3838, 3922, 4008,
  203. };
  204. /* Rounded right shift with optionnal clipping */
  205. #define RSHIFT_SIZE(size) \
  206. av_always_inline \
  207. static int##size##_t rshift##size(int##size##_t value, int shift) \
  208. { \
  209. int##size##_t rounding = (int##size##_t)1 << (shift - 1); \
  210. int##size##_t mask = ((int##size##_t)1 << (shift + 1)) - 1; \
  211. return ((value + rounding) >> shift) - ((value & mask) == rounding); \
  212. } \
  213. av_always_inline \
  214. static int##size##_t rshift##size##_clip24(int##size##_t value, int shift) \
  215. { \
  216. return av_clip_intp2(rshift##size(value, shift), 23); \
  217. }
  218. RSHIFT_SIZE(32)
  219. RSHIFT_SIZE(64)
  220. av_always_inline
  221. static void aptx_update_codeword_history(Channel *channel)
  222. {
  223. int32_t cw = ((channel->quantize[0].quantized_sample & 3) << 0) +
  224. ((channel->quantize[1].quantized_sample & 2) << 1) +
  225. ((channel->quantize[2].quantized_sample & 1) << 3);
  226. channel->codeword_history = (cw << 8) + (channel->codeword_history << 4);
  227. }
  228. static void aptx_generate_dither(Channel *channel)
  229. {
  230. int subband;
  231. int64_t m;
  232. int32_t d;
  233. aptx_update_codeword_history(channel);
  234. m = (int64_t)5184443 * (channel->codeword_history >> 7);
  235. d = (m << 2) + (m >> 22);
  236. for (subband = 0; subband < NB_SUBBANDS; subband++)
  237. channel->dither[subband] = d << (23 - 5*subband);
  238. channel->dither_parity = (d >> 25) & 1;
  239. }
  240. /*
  241. * Convolution filter coefficients for the outer QMF of the QMF tree.
  242. * The 2 sets are a mirror of each other.
  243. */
  244. static const int32_t aptx_qmf_outer_coeffs[NB_FILTERS][FILTER_TAPS] = {
  245. {
  246. 730, -413, -9611, 43626, -121026, 269973, -585547, 2801966,
  247. 697128, -160481, 27611, 8478, -10043, 3511, 688, -897,
  248. },
  249. {
  250. -897, 688, 3511, -10043, 8478, 27611, -160481, 697128,
  251. 2801966, -585547, 269973, -121026, 43626, -9611, -413, 730,
  252. },
  253. };
  254. /*
  255. * Convolution filter coefficients for the inner QMF of the QMF tree.
  256. * The 2 sets are a mirror of each other.
  257. */
  258. static const int32_t aptx_qmf_inner_coeffs[NB_FILTERS][FILTER_TAPS] = {
  259. {
  260. 1033, -584, -13592, 61697, -171156, 381799, -828088, 3962579,
  261. 985888, -226954, 39048, 11990, -14203, 4966, 973, -1268,
  262. },
  263. {
  264. -1268, 973, 4966, -14203, 11990, 39048, -226954, 985888,
  265. 3962579, -828088, 381799, -171156, 61697, -13592, -584, 1033,
  266. },
  267. };
  268. /*
  269. * Push one sample into a circular signal buffer.
  270. */
  271. av_always_inline
  272. static void aptx_qmf_filter_signal_push(FilterSignal *signal, int32_t sample)
  273. {
  274. signal->buffer[signal->pos ] = sample;
  275. signal->buffer[signal->pos+FILTER_TAPS] = sample;
  276. signal->pos = (signal->pos + 1) & (FILTER_TAPS - 1);
  277. }
  278. /*
  279. * Compute the convolution of the signal with the coefficients, and reduce
  280. * to 24 bits by applying the specified right shifting.
  281. */
  282. av_always_inline
  283. static int32_t aptx_qmf_convolution(FilterSignal *signal,
  284. const int32_t coeffs[FILTER_TAPS],
  285. int shift)
  286. {
  287. int32_t *sig = &signal->buffer[signal->pos];
  288. int64_t e = 0;
  289. int i;
  290. for (i = 0; i < FILTER_TAPS; i++)
  291. e += MUL64(sig[i], coeffs[i]);
  292. return rshift64_clip24(e, shift);
  293. }
  294. /*
  295. * Half-band QMF analysis filter realized with a polyphase FIR filter.
  296. * Split into 2 subbands and downsample by 2.
  297. * So for each pair of samples that goes in, one sample goes out,
  298. * split into 2 separate subbands.
  299. */
  300. av_always_inline
  301. static void aptx_qmf_polyphase_analysis(FilterSignal signal[NB_FILTERS],
  302. const int32_t coeffs[NB_FILTERS][FILTER_TAPS],
  303. int shift,
  304. int32_t samples[NB_FILTERS],
  305. int32_t *low_subband_output,
  306. int32_t *high_subband_output)
  307. {
  308. int32_t subbands[NB_FILTERS];
  309. int i;
  310. for (i = 0; i < NB_FILTERS; i++) {
  311. aptx_qmf_filter_signal_push(&signal[i], samples[NB_FILTERS-1-i]);
  312. subbands[i] = aptx_qmf_convolution(&signal[i], coeffs[i], shift);
  313. }
  314. *low_subband_output = av_clip_intp2(subbands[0] + subbands[1], 23);
  315. *high_subband_output = av_clip_intp2(subbands[0] - subbands[1], 23);
  316. }
  317. /*
  318. * Two stage QMF analysis tree.
  319. * Split 4 input samples into 4 subbands and downsample by 4.
  320. * So for each group of 4 samples that goes in, one sample goes out,
  321. * split into 4 separate subbands.
  322. */
  323. static void aptx_qmf_tree_analysis(QMFAnalysis *qmf,
  324. int32_t samples[4],
  325. int32_t subband_samples[4])
  326. {
  327. int32_t intermediate_samples[4];
  328. int i;
  329. /* Split 4 input samples into 2 intermediate subbands downsampled to 2 samples */
  330. for (i = 0; i < 2; i++)
  331. aptx_qmf_polyphase_analysis(qmf->outer_filter_signal,
  332. aptx_qmf_outer_coeffs, 23,
  333. &samples[2*i],
  334. &intermediate_samples[0+i],
  335. &intermediate_samples[2+i]);
  336. /* Split 2 intermediate subband samples into 4 final subbands downsampled to 1 sample */
  337. for (i = 0; i < 2; i++)
  338. aptx_qmf_polyphase_analysis(qmf->inner_filter_signal[i],
  339. aptx_qmf_inner_coeffs, 23,
  340. &intermediate_samples[2*i],
  341. &subband_samples[2*i+0],
  342. &subband_samples[2*i+1]);
  343. }
  344. /*
  345. * Half-band QMF synthesis filter realized with a polyphase FIR filter.
  346. * Join 2 subbands and upsample by 2.
  347. * So for each 2 subbands sample that goes in, a pair of samples goes out.
  348. */
  349. av_always_inline
  350. static void aptx_qmf_polyphase_synthesis(FilterSignal signal[NB_FILTERS],
  351. const int32_t coeffs[NB_FILTERS][FILTER_TAPS],
  352. int shift,
  353. int32_t low_subband_input,
  354. int32_t high_subband_input,
  355. int32_t samples[NB_FILTERS])
  356. {
  357. int32_t subbands[NB_FILTERS];
  358. int i;
  359. subbands[0] = low_subband_input + high_subband_input;
  360. subbands[1] = low_subband_input - high_subband_input;
  361. for (i = 0; i < NB_FILTERS; i++) {
  362. aptx_qmf_filter_signal_push(&signal[i], subbands[1-i]);
  363. samples[i] = aptx_qmf_convolution(&signal[i], coeffs[i], shift);
  364. }
  365. }
  366. /*
  367. * Two stage QMF synthesis tree.
  368. * Join 4 subbands and upsample by 4.
  369. * So for each 4 subbands sample that goes in, a group of 4 samples goes out.
  370. */
  371. static void aptx_qmf_tree_synthesis(QMFAnalysis *qmf,
  372. int32_t subband_samples[4],
  373. int32_t samples[4])
  374. {
  375. int32_t intermediate_samples[4];
  376. int i;
  377. /* Join 4 subbands into 2 intermediate subbands upsampled to 2 samples. */
  378. for (i = 0; i < 2; i++)
  379. aptx_qmf_polyphase_synthesis(qmf->inner_filter_signal[i],
  380. aptx_qmf_inner_coeffs, 22,
  381. subband_samples[2*i+0],
  382. subband_samples[2*i+1],
  383. &intermediate_samples[2*i]);
  384. /* Join 2 samples from intermediate subbands upsampled to 4 samples. */
  385. for (i = 0; i < 2; i++)
  386. aptx_qmf_polyphase_synthesis(qmf->outer_filter_signal,
  387. aptx_qmf_outer_coeffs, 21,
  388. intermediate_samples[0+i],
  389. intermediate_samples[2+i],
  390. &samples[2*i]);
  391. }
  392. av_always_inline
  393. static int32_t aptx_bin_search(int32_t value, int32_t factor,
  394. const int32_t *intervals, int32_t nb_intervals)
  395. {
  396. int32_t idx = 0;
  397. int i;
  398. for (i = nb_intervals >> 1; i > 0; i >>= 1)
  399. if (MUL64(factor, intervals[idx + i]) <= ((int64_t)value << 24))
  400. idx += i;
  401. return idx;
  402. }
  403. static void aptx_quantize_difference(Quantize *quantize,
  404. int32_t sample_difference,
  405. int32_t dither,
  406. int32_t quantization_factor,
  407. ConstTables *tables)
  408. {
  409. const int32_t *intervals = tables->quantize_intervals;
  410. int32_t quantized_sample, dithered_sample, parity_change;
  411. int32_t d, mean, interval, inv, sample_difference_abs;
  412. int64_t error;
  413. sample_difference_abs = FFABS(sample_difference);
  414. quantized_sample = aptx_bin_search(sample_difference_abs >> 4,
  415. quantization_factor,
  416. intervals, tables->tables_size);
  417. d = rshift32_clip24(MULH(dither, dither), 7) - (1 << 23);
  418. d = rshift64(MUL64(d, tables->quantize_dither_factors[quantized_sample]), 23);
  419. intervals += quantized_sample;
  420. mean = (intervals[1] + intervals[0]) / 2;
  421. interval = (intervals[1] - intervals[0]) * (-(sample_difference < 0) | 1);
  422. dithered_sample = rshift64_clip24(MUL64(dither, interval) + ((int64_t)(mean + d) << 32), 32);
  423. error = ((int64_t)sample_difference_abs << 20) - MUL64(dithered_sample, quantization_factor);
  424. quantize->error = FFABS(rshift64(error, 23));
  425. parity_change = quantized_sample;
  426. if (error < 0)
  427. quantized_sample--;
  428. else
  429. parity_change--;
  430. inv = -(sample_difference < 0);
  431. quantize->quantized_sample = quantized_sample ^ inv;
  432. quantize->quantized_sample_parity_change = parity_change ^ inv;
  433. }
  434. static void aptx_encode_channel(Channel *channel, int32_t samples[4])
  435. {
  436. int32_t subband_samples[4];
  437. int subband;
  438. aptx_qmf_tree_analysis(&channel->qmf, samples, subband_samples);
  439. aptx_generate_dither(channel);
  440. for (subband = 0; subband < NB_SUBBANDS; subband++) {
  441. int32_t diff = av_clip_intp2(subband_samples[subband] - channel->prediction[subband].predicted_sample, 23);
  442. aptx_quantize_difference(&channel->quantize[subband], diff,
  443. channel->dither[subband],
  444. channel->invert_quantize[subband].quantization_factor,
  445. &tables[subband]);
  446. }
  447. }
  448. static void aptx_decode_channel(Channel *channel, int32_t samples[4])
  449. {
  450. int32_t subband_samples[4];
  451. int subband;
  452. for (subband = 0; subband < NB_SUBBANDS; subband++)
  453. subband_samples[subband] = channel->prediction[subband].previous_reconstructed_sample;
  454. aptx_qmf_tree_synthesis(&channel->qmf, subband_samples, samples);
  455. }
  456. static void aptx_invert_quantization(InvertQuantize *invert_quantize,
  457. int32_t quantized_sample, int32_t dither,
  458. ConstTables *tables)
  459. {
  460. int32_t qr, idx, shift, factor_select;
  461. idx = (quantized_sample ^ -(quantized_sample < 0)) + 1;
  462. qr = tables->quantize_intervals[idx] / 2;
  463. if (quantized_sample < 0)
  464. qr = -qr;
  465. qr = rshift64_clip24(((int64_t)qr<<32) + MUL64(dither, tables->invert_quantize_dither_factors[idx]), 32);
  466. invert_quantize->reconstructed_difference = MUL64(invert_quantize->quantization_factor, qr) >> 19;
  467. /* update factor_select */
  468. factor_select = 32620 * invert_quantize->factor_select;
  469. factor_select = rshift32(factor_select + (tables->quantize_factor_select_offset[idx] << 15), 15);
  470. invert_quantize->factor_select = av_clip(factor_select, 0, tables->factor_max);
  471. /* update quantization factor */
  472. idx = (invert_quantize->factor_select & 0xFF) >> 3;
  473. shift = (tables->factor_max - invert_quantize->factor_select) >> 8;
  474. invert_quantize->quantization_factor = (quantization_factors[idx] << 11) >> shift;
  475. }
  476. static int32_t *aptx_reconstructed_differences_update(Prediction *prediction,
  477. int32_t reconstructed_difference,
  478. int order)
  479. {
  480. int32_t *rd1 = prediction->reconstructed_differences, *rd2 = rd1 + order;
  481. int p = prediction->pos;
  482. rd1[p] = rd2[p];
  483. prediction->pos = p = (p + 1) % order;
  484. rd2[p] = reconstructed_difference;
  485. return &rd2[p];
  486. }
  487. static void aptx_prediction_filtering(Prediction *prediction,
  488. int32_t reconstructed_difference,
  489. int order)
  490. {
  491. int32_t reconstructed_sample, predictor, srd0;
  492. int32_t *reconstructed_differences;
  493. int64_t predicted_difference = 0;
  494. int i;
  495. reconstructed_sample = av_clip_intp2(reconstructed_difference + prediction->predicted_sample, 23);
  496. predictor = av_clip_intp2((MUL64(prediction->s_weight[0], prediction->previous_reconstructed_sample)
  497. + MUL64(prediction->s_weight[1], reconstructed_sample)) >> 22, 23);
  498. prediction->previous_reconstructed_sample = reconstructed_sample;
  499. reconstructed_differences = aptx_reconstructed_differences_update(prediction, reconstructed_difference, order);
  500. srd0 = FFDIFFSIGN(reconstructed_difference, 0) << 23;
  501. for (i = 0; i < order; i++) {
  502. int32_t srd = FF_SIGNBIT(reconstructed_differences[-i-1]) | 1;
  503. prediction->d_weight[i] -= rshift32(prediction->d_weight[i] - srd*srd0, 8);
  504. predicted_difference += MUL64(reconstructed_differences[-i], prediction->d_weight[i]);
  505. }
  506. prediction->predicted_difference = av_clip_intp2(predicted_difference >> 22, 23);
  507. prediction->predicted_sample = av_clip_intp2(predictor + prediction->predicted_difference, 23);
  508. }
  509. static void aptx_process_subband(InvertQuantize *invert_quantize,
  510. Prediction *prediction,
  511. int32_t quantized_sample, int32_t dither,
  512. ConstTables *tables)
  513. {
  514. int32_t sign, same_sign[2], weight[2], sw1, range;
  515. aptx_invert_quantization(invert_quantize, quantized_sample, dither, tables);
  516. sign = FFDIFFSIGN(invert_quantize->reconstructed_difference,
  517. -prediction->predicted_difference);
  518. same_sign[0] = sign * prediction->prev_sign[0];
  519. same_sign[1] = sign * prediction->prev_sign[1];
  520. prediction->prev_sign[0] = prediction->prev_sign[1];
  521. prediction->prev_sign[1] = sign | 1;
  522. range = 0x100000;
  523. sw1 = rshift32(-same_sign[1] * prediction->s_weight[1], 1);
  524. sw1 = (av_clip(sw1, -range, range) & ~0xF) << 4;
  525. range = 0x300000;
  526. weight[0] = 254 * prediction->s_weight[0] + 0x800000*same_sign[0] + sw1;
  527. prediction->s_weight[0] = av_clip(rshift32(weight[0], 8), -range, range);
  528. range = 0x3C0000 - prediction->s_weight[0];
  529. weight[1] = 255 * prediction->s_weight[1] + 0xC00000*same_sign[1];
  530. prediction->s_weight[1] = av_clip(rshift32(weight[1], 8), -range, range);
  531. aptx_prediction_filtering(prediction,
  532. invert_quantize->reconstructed_difference,
  533. tables->prediction_order);
  534. }
  535. static void aptx_invert_quantize_and_prediction(Channel *channel)
  536. {
  537. int subband;
  538. for (subband = 0; subband < NB_SUBBANDS; subband++)
  539. aptx_process_subband(&channel->invert_quantize[subband],
  540. &channel->prediction[subband],
  541. channel->quantize[subband].quantized_sample,
  542. channel->dither[subband],
  543. &tables[subband]);
  544. }
  545. static int32_t aptx_quantized_parity(Channel *channel)
  546. {
  547. int32_t parity = channel->dither_parity;
  548. int subband;
  549. for (subband = 0; subband < NB_SUBBANDS; subband++)
  550. parity ^= channel->quantize[subband].quantized_sample;
  551. return parity & 1;
  552. }
  553. /* For each sample, ensure that the parity of all subbands of all channels
  554. * is 0 except once every 8 samples where the parity is forced to 1. */
  555. static int aptx_check_parity(Channel channels[NB_CHANNELS], int32_t *idx)
  556. {
  557. int32_t parity = aptx_quantized_parity(&channels[LEFT])
  558. ^ aptx_quantized_parity(&channels[RIGHT]);
  559. int eighth = *idx == 7;
  560. *idx = (*idx + 1) & 7;
  561. return parity ^ eighth;
  562. }
  563. static void aptx_insert_sync(Channel channels[NB_CHANNELS], int32_t *idx)
  564. {
  565. if (aptx_check_parity(channels, idx)) {
  566. int i;
  567. Channel *c;
  568. static const int map[] = { 1, 2, 0, 3 };
  569. Quantize *min = &channels[NB_CHANNELS-1].quantize[map[0]];
  570. for (c = &channels[NB_CHANNELS-1]; c >= channels; c--)
  571. for (i = 0; i < NB_SUBBANDS; i++)
  572. if (c->quantize[map[i]].error < min->error)
  573. min = &c->quantize[map[i]];
  574. /* Forcing the desired parity is done by offsetting by 1 the quantized
  575. * sample from the subband featuring the smallest quantization error. */
  576. min->quantized_sample = min->quantized_sample_parity_change;
  577. }
  578. }
  579. static uint16_t aptx_pack_codeword(Channel *channel)
  580. {
  581. int32_t parity = aptx_quantized_parity(channel);
  582. return (((channel->quantize[3].quantized_sample & 0x06) | parity) << 13)
  583. | (((channel->quantize[2].quantized_sample & 0x03) ) << 11)
  584. | (((channel->quantize[1].quantized_sample & 0x0F) ) << 7)
  585. | (((channel->quantize[0].quantized_sample & 0x7F) ) << 0);
  586. }
  587. static void aptx_unpack_codeword(Channel *channel, uint16_t codeword)
  588. {
  589. channel->quantize[0].quantized_sample = sign_extend(codeword >> 0, 7);
  590. channel->quantize[1].quantized_sample = sign_extend(codeword >> 7, 4);
  591. channel->quantize[2].quantized_sample = sign_extend(codeword >> 11, 2);
  592. channel->quantize[3].quantized_sample = sign_extend(codeword >> 13, 3);
  593. channel->quantize[3].quantized_sample = (channel->quantize[3].quantized_sample & ~1)
  594. | aptx_quantized_parity(channel);
  595. }
  596. static void aptx_encode_samples(AptXContext *ctx,
  597. int32_t samples[NB_CHANNELS][4],
  598. uint8_t output[2*NB_CHANNELS])
  599. {
  600. int channel;
  601. for (channel = 0; channel < NB_CHANNELS; channel++)
  602. aptx_encode_channel(&ctx->channels[channel], samples[channel]);
  603. aptx_insert_sync(ctx->channels, &ctx->sync_idx);
  604. for (channel = 0; channel < NB_CHANNELS; channel++) {
  605. aptx_invert_quantize_and_prediction(&ctx->channels[channel]);
  606. AV_WB16(output + 2*channel, aptx_pack_codeword(&ctx->channels[channel]));
  607. }
  608. }
  609. static int aptx_decode_samples(AptXContext *ctx,
  610. const uint8_t input[2*NB_CHANNELS],
  611. int32_t samples[NB_CHANNELS][4])
  612. {
  613. int channel, ret;
  614. for (channel = 0; channel < NB_CHANNELS; channel++) {
  615. uint16_t codeword;
  616. aptx_generate_dither(&ctx->channels[channel]);
  617. codeword = AV_RB16(input + 2*channel);
  618. aptx_unpack_codeword(&ctx->channels[channel], codeword);
  619. aptx_invert_quantize_and_prediction(&ctx->channels[channel]);
  620. }
  621. ret = aptx_check_parity(ctx->channels, &ctx->sync_idx);
  622. for (channel = 0; channel < NB_CHANNELS; channel++)
  623. aptx_decode_channel(&ctx->channels[channel], samples[channel]);
  624. return ret;
  625. }
  626. static av_cold int aptx_init(AVCodecContext *avctx)
  627. {
  628. AptXContext *s = avctx->priv_data;
  629. int chan, subband;
  630. if (avctx->frame_size == 0)
  631. avctx->frame_size = 1024;
  632. if (avctx->frame_size & 3) {
  633. av_log(avctx, AV_LOG_ERROR, "Frame size must be a multiple of 4 samples\n");
  634. return AVERROR(EINVAL);
  635. }
  636. for (chan = 0; chan < NB_CHANNELS; chan++) {
  637. Channel *channel = &s->channels[chan];
  638. for (subband = 0; subband < NB_SUBBANDS; subband++) {
  639. Prediction *prediction = &channel->prediction[subband];
  640. prediction->prev_sign[0] = 1;
  641. prediction->prev_sign[1] = 1;
  642. }
  643. }
  644. ff_af_queue_init(avctx, &s->afq);
  645. return 0;
  646. }
  647. static int aptx_decode_frame(AVCodecContext *avctx, void *data,
  648. int *got_frame_ptr, AVPacket *avpkt)
  649. {
  650. AptXContext *s = avctx->priv_data;
  651. AVFrame *frame = data;
  652. int pos, channel, sample, ret;
  653. if (avpkt->size < 4) {
  654. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  655. return AVERROR_INVALIDDATA;
  656. }
  657. /* get output buffer */
  658. frame->channels = NB_CHANNELS;
  659. frame->format = AV_SAMPLE_FMT_S32P;
  660. frame->nb_samples = avpkt->size & ~3;
  661. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  662. return ret;
  663. for (pos = 0; pos < frame->nb_samples; pos += 4) {
  664. int32_t samples[NB_CHANNELS][4];
  665. if (aptx_decode_samples(s, &avpkt->data[pos], samples)) {
  666. av_log(avctx, AV_LOG_ERROR, "Synchronization error\n");
  667. return AVERROR_INVALIDDATA;
  668. }
  669. for (channel = 0; channel < NB_CHANNELS; channel++)
  670. for (sample = 0; sample < 4; sample++)
  671. AV_WN32A(&frame->data[channel][4*(sample+pos)],
  672. samples[channel][sample] << 8);
  673. }
  674. *got_frame_ptr = 1;
  675. return frame->nb_samples;
  676. }
  677. static int aptx_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  678. const AVFrame *frame, int *got_packet_ptr)
  679. {
  680. AptXContext *s = avctx->priv_data;
  681. int pos, channel, sample, ret;
  682. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  683. return ret;
  684. if ((ret = ff_alloc_packet2(avctx, avpkt, frame->nb_samples, 0)) < 0)
  685. return ret;
  686. for (pos = 0; pos < frame->nb_samples; pos += 4) {
  687. int32_t samples[NB_CHANNELS][4];
  688. for (channel = 0; channel < NB_CHANNELS; channel++)
  689. for (sample = 0; sample < 4; sample++)
  690. samples[channel][sample] = (int32_t)AV_RN32A(&frame->data[channel][4*(sample+pos)]) >> 8;
  691. aptx_encode_samples(s, samples, avpkt->data + pos);
  692. }
  693. ff_af_queue_remove(&s->afq, frame->nb_samples, &avpkt->pts, &avpkt->duration);
  694. *got_packet_ptr = 1;
  695. return 0;
  696. }
  697. static av_cold int aptx_close(AVCodecContext *avctx)
  698. {
  699. AptXContext *s = avctx->priv_data;
  700. ff_af_queue_close(&s->afq);
  701. return 0;
  702. }
  703. #if CONFIG_APTX_DECODER
  704. AVCodec ff_aptx_decoder = {
  705. .name = "aptx",
  706. .long_name = NULL_IF_CONFIG_SMALL("aptX (Audio Processing Technology for Bluetooth)"),
  707. .type = AVMEDIA_TYPE_AUDIO,
  708. .id = AV_CODEC_ID_APTX,
  709. .priv_data_size = sizeof(AptXContext),
  710. .init = aptx_init,
  711. .decode = aptx_decode_frame,
  712. .close = aptx_close,
  713. .capabilities = AV_CODEC_CAP_DR1,
  714. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  715. .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_STEREO, 0},
  716. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
  717. AV_SAMPLE_FMT_NONE },
  718. };
  719. #endif
  720. #if CONFIG_APTX_ENCODER
  721. AVCodec ff_aptx_encoder = {
  722. .name = "aptx",
  723. .long_name = NULL_IF_CONFIG_SMALL("aptX (Audio Processing Technology for Bluetooth)"),
  724. .type = AVMEDIA_TYPE_AUDIO,
  725. .id = AV_CODEC_ID_APTX,
  726. .priv_data_size = sizeof(AptXContext),
  727. .init = aptx_init,
  728. .encode2 = aptx_encode_frame,
  729. .close = aptx_close,
  730. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME,
  731. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  732. .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_STEREO, 0},
  733. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
  734. AV_SAMPLE_FMT_NONE },
  735. .supported_samplerates = (const int[]) {8000, 16000, 24000, 32000, 44100, 48000, 0},
  736. };
  737. #endif