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.

862 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;
  412. int64_t error;
  413. quantized_sample = aptx_bin_search(FFABS(sample_difference) >> 4,
  414. quantization_factor,
  415. intervals, tables->tables_size);
  416. d = rshift32_clip24(MULH(dither, dither), 7) - (1 << 23);
  417. d = rshift64(MUL64(d, tables->quantize_dither_factors[quantized_sample]), 23);
  418. intervals += quantized_sample;
  419. mean = (intervals[1] + intervals[0]) / 2;
  420. interval = (intervals[1] - intervals[0]) * (-(sample_difference < 0) | 1);
  421. dithered_sample = rshift64_clip24(MUL64(dither, interval) + ((int64_t)(mean + d) << 32), 32);
  422. error = ((int64_t)FFABS(sample_difference) << 20) - MUL64(dithered_sample, quantization_factor);
  423. quantize->error = FFABS(rshift64(error, 23));
  424. parity_change = quantized_sample;
  425. if (error < 0)
  426. quantized_sample--;
  427. else
  428. parity_change--;
  429. inv = -(sample_difference < 0);
  430. quantize->quantized_sample = quantized_sample ^ inv;
  431. quantize->quantized_sample_parity_change = parity_change ^ inv;
  432. }
  433. static void aptx_encode_channel(Channel *channel, int32_t samples[4])
  434. {
  435. int32_t subband_samples[4];
  436. int subband;
  437. aptx_qmf_tree_analysis(&channel->qmf, samples, subband_samples);
  438. aptx_generate_dither(channel);
  439. for (subband = 0; subband < NB_SUBBANDS; subband++) {
  440. int32_t diff = av_clip_intp2(subband_samples[subband] - channel->prediction[subband].predicted_sample, 23);
  441. aptx_quantize_difference(&channel->quantize[subband], diff,
  442. channel->dither[subband],
  443. channel->invert_quantize[subband].quantization_factor,
  444. &tables[subband]);
  445. }
  446. }
  447. static void aptx_decode_channel(Channel *channel, int32_t samples[4])
  448. {
  449. int32_t subband_samples[4];
  450. int subband;
  451. for (subband = 0; subband < NB_SUBBANDS; subband++)
  452. subband_samples[subband] = channel->prediction[subband].previous_reconstructed_sample;
  453. aptx_qmf_tree_synthesis(&channel->qmf, subband_samples, samples);
  454. }
  455. static void aptx_invert_quantization(InvertQuantize *invert_quantize,
  456. int32_t quantized_sample, int32_t dither,
  457. ConstTables *tables)
  458. {
  459. int32_t qr, idx, shift, factor_select;
  460. idx = (quantized_sample ^ -(quantized_sample < 0)) + 1;
  461. qr = tables->quantize_intervals[idx] / 2;
  462. if (quantized_sample < 0)
  463. qr = -qr;
  464. qr = rshift64_clip24(((int64_t)qr<<32) + MUL64(dither, tables->invert_quantize_dither_factors[idx]), 32);
  465. invert_quantize->reconstructed_difference = MUL64(invert_quantize->quantization_factor, qr) >> 19;
  466. /* update factor_select */
  467. factor_select = 32620 * invert_quantize->factor_select;
  468. factor_select = rshift32(factor_select + (tables->quantize_factor_select_offset[idx] << 15), 15);
  469. invert_quantize->factor_select = av_clip(factor_select, 0, tables->factor_max);
  470. /* update quantization factor */
  471. idx = (invert_quantize->factor_select & 0xFF) >> 3;
  472. shift = (tables->factor_max - invert_quantize->factor_select) >> 8;
  473. invert_quantize->quantization_factor = (quantization_factors[idx] << 11) >> shift;
  474. }
  475. static int32_t *aptx_reconstructed_differences_update(Prediction *prediction,
  476. int32_t reconstructed_difference,
  477. int order)
  478. {
  479. int32_t *rd1 = prediction->reconstructed_differences, *rd2 = rd1 + order;
  480. int p = prediction->pos;
  481. rd1[p] = rd2[p];
  482. prediction->pos = p = (p + 1) % order;
  483. rd2[p] = reconstructed_difference;
  484. return &rd2[p];
  485. }
  486. static void aptx_prediction_filtering(Prediction *prediction,
  487. int32_t reconstructed_difference,
  488. int order)
  489. {
  490. int32_t reconstructed_sample, predictor, srd0;
  491. int32_t *reconstructed_differences;
  492. int64_t predicted_difference = 0;
  493. int i;
  494. reconstructed_sample = av_clip_intp2(reconstructed_difference + prediction->predicted_sample, 23);
  495. predictor = av_clip_intp2((MUL64(prediction->s_weight[0], prediction->previous_reconstructed_sample)
  496. + MUL64(prediction->s_weight[1], reconstructed_sample)) >> 22, 23);
  497. prediction->previous_reconstructed_sample = reconstructed_sample;
  498. reconstructed_differences = aptx_reconstructed_differences_update(prediction, reconstructed_difference, order);
  499. srd0 = FFDIFFSIGN(reconstructed_difference, 0) << 23;
  500. for (i = 0; i < order; i++) {
  501. int32_t srd = FF_SIGNBIT(reconstructed_differences[-i-1]) | 1;
  502. prediction->d_weight[i] -= rshift32(prediction->d_weight[i] - srd*srd0, 8);
  503. predicted_difference += MUL64(reconstructed_differences[-i], prediction->d_weight[i]);
  504. }
  505. prediction->predicted_difference = av_clip_intp2(predicted_difference >> 22, 23);
  506. prediction->predicted_sample = av_clip_intp2(predictor + prediction->predicted_difference, 23);
  507. }
  508. static void aptx_process_subband(InvertQuantize *invert_quantize,
  509. Prediction *prediction,
  510. int32_t quantized_sample, int32_t dither,
  511. ConstTables *tables)
  512. {
  513. int32_t sign, same_sign[2], weight[2], sw1, range;
  514. aptx_invert_quantization(invert_quantize, quantized_sample, dither, tables);
  515. sign = FFDIFFSIGN(invert_quantize->reconstructed_difference,
  516. -prediction->predicted_difference);
  517. same_sign[0] = sign * prediction->prev_sign[0];
  518. same_sign[1] = sign * prediction->prev_sign[1];
  519. prediction->prev_sign[0] = prediction->prev_sign[1];
  520. prediction->prev_sign[1] = sign | 1;
  521. range = 0x100000;
  522. sw1 = rshift32(-same_sign[1] * prediction->s_weight[1], 1);
  523. sw1 = (av_clip(sw1, -range, range) & ~0xF) << 4;
  524. range = 0x300000;
  525. weight[0] = 254 * prediction->s_weight[0] + 0x800000*same_sign[0] + sw1;
  526. prediction->s_weight[0] = av_clip(rshift32(weight[0], 8), -range, range);
  527. range = 0x3C0000 - prediction->s_weight[0];
  528. weight[1] = 255 * prediction->s_weight[1] + 0xC00000*same_sign[1];
  529. prediction->s_weight[1] = av_clip(rshift32(weight[1], 8), -range, range);
  530. aptx_prediction_filtering(prediction,
  531. invert_quantize->reconstructed_difference,
  532. tables->prediction_order);
  533. }
  534. static void aptx_invert_quantize_and_prediction(Channel *channel)
  535. {
  536. int subband;
  537. for (subband = 0; subband < NB_SUBBANDS; subband++)
  538. aptx_process_subband(&channel->invert_quantize[subband],
  539. &channel->prediction[subband],
  540. channel->quantize[subband].quantized_sample,
  541. channel->dither[subband],
  542. &tables[subband]);
  543. }
  544. static int32_t aptx_quantized_parity(Channel *channel)
  545. {
  546. int32_t parity = channel->dither_parity;
  547. int subband;
  548. for (subband = 0; subband < NB_SUBBANDS; subband++)
  549. parity ^= channel->quantize[subband].quantized_sample;
  550. return parity & 1;
  551. }
  552. /* For each sample, ensure that the parity of all subbands of all channels
  553. * is 0 except once every 8 samples where the parity is forced to 1. */
  554. static int aptx_check_parity(Channel channels[NB_CHANNELS], int32_t *idx)
  555. {
  556. int32_t parity = aptx_quantized_parity(&channels[LEFT])
  557. ^ aptx_quantized_parity(&channels[RIGHT]);
  558. int eighth = *idx == 7;
  559. *idx = (*idx + 1) & 7;
  560. return parity ^ eighth;
  561. }
  562. static void aptx_insert_sync(Channel channels[NB_CHANNELS], int32_t *idx)
  563. {
  564. if (aptx_check_parity(channels, idx)) {
  565. int i;
  566. Channel *c;
  567. static const int map[] = { 1, 2, 0, 3 };
  568. Quantize *min = &channels[NB_CHANNELS-1].quantize[map[0]];
  569. for (c = &channels[NB_CHANNELS-1]; c >= channels; c--)
  570. for (i = 0; i < NB_SUBBANDS; i++)
  571. if (c->quantize[map[i]].error < min->error)
  572. min = &c->quantize[map[i]];
  573. /* Forcing the desired parity is done by offsetting by 1 the quantized
  574. * sample from the subband featuring the smallest quantization error. */
  575. min->quantized_sample = min->quantized_sample_parity_change;
  576. }
  577. }
  578. static uint16_t aptx_pack_codeword(Channel *channel)
  579. {
  580. int32_t parity = aptx_quantized_parity(channel);
  581. return (((channel->quantize[3].quantized_sample & 0x06) | parity) << 13)
  582. | (((channel->quantize[2].quantized_sample & 0x03) ) << 11)
  583. | (((channel->quantize[1].quantized_sample & 0x0F) ) << 7)
  584. | (((channel->quantize[0].quantized_sample & 0x7F) ) << 0);
  585. }
  586. static void aptx_unpack_codeword(Channel *channel, uint16_t codeword)
  587. {
  588. channel->quantize[0].quantized_sample = sign_extend(codeword >> 0, 7);
  589. channel->quantize[1].quantized_sample = sign_extend(codeword >> 7, 4);
  590. channel->quantize[2].quantized_sample = sign_extend(codeword >> 11, 2);
  591. channel->quantize[3].quantized_sample = sign_extend(codeword >> 13, 3);
  592. channel->quantize[3].quantized_sample = (channel->quantize[3].quantized_sample & ~1)
  593. | aptx_quantized_parity(channel);
  594. }
  595. static void aptx_encode_samples(AptXContext *ctx,
  596. int32_t samples[NB_CHANNELS][4],
  597. uint8_t output[2*NB_CHANNELS])
  598. {
  599. int channel;
  600. for (channel = 0; channel < NB_CHANNELS; channel++)
  601. aptx_encode_channel(&ctx->channels[channel], samples[channel]);
  602. aptx_insert_sync(ctx->channels, &ctx->sync_idx);
  603. for (channel = 0; channel < NB_CHANNELS; channel++) {
  604. aptx_invert_quantize_and_prediction(&ctx->channels[channel]);
  605. AV_WB16(output + 2*channel, aptx_pack_codeword(&ctx->channels[channel]));
  606. }
  607. }
  608. static int aptx_decode_samples(AptXContext *ctx,
  609. const uint8_t input[2*NB_CHANNELS],
  610. int32_t samples[NB_CHANNELS][4])
  611. {
  612. int channel, ret;
  613. for (channel = 0; channel < NB_CHANNELS; channel++) {
  614. uint16_t codeword;
  615. aptx_generate_dither(&ctx->channels[channel]);
  616. codeword = AV_RB16(input + 2*channel);
  617. aptx_unpack_codeword(&ctx->channels[channel], codeword);
  618. aptx_invert_quantize_and_prediction(&ctx->channels[channel]);
  619. }
  620. ret = aptx_check_parity(ctx->channels, &ctx->sync_idx);
  621. for (channel = 0; channel < NB_CHANNELS; channel++)
  622. aptx_decode_channel(&ctx->channels[channel], samples[channel]);
  623. return ret;
  624. }
  625. static av_cold int aptx_init(AVCodecContext *avctx)
  626. {
  627. AptXContext *s = avctx->priv_data;
  628. int chan, subband;
  629. if (avctx->frame_size == 0)
  630. avctx->frame_size = 1024;
  631. if (avctx->frame_size & 3) {
  632. av_log(avctx, AV_LOG_ERROR, "Frame size must be a multiple of 4 samples\n");
  633. return AVERROR(EINVAL);
  634. }
  635. for (chan = 0; chan < NB_CHANNELS; chan++) {
  636. Channel *channel = &s->channels[chan];
  637. for (subband = 0; subband < NB_SUBBANDS; subband++) {
  638. Prediction *prediction = &channel->prediction[subband];
  639. prediction->prev_sign[0] = 1;
  640. prediction->prev_sign[1] = 1;
  641. }
  642. }
  643. ff_af_queue_init(avctx, &s->afq);
  644. return 0;
  645. }
  646. static int aptx_decode_frame(AVCodecContext *avctx, void *data,
  647. int *got_frame_ptr, AVPacket *avpkt)
  648. {
  649. AptXContext *s = avctx->priv_data;
  650. AVFrame *frame = data;
  651. int pos, channel, sample, ret;
  652. if (avpkt->size < 4) {
  653. av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
  654. return AVERROR_INVALIDDATA;
  655. }
  656. /* get output buffer */
  657. frame->channels = NB_CHANNELS;
  658. frame->format = AV_SAMPLE_FMT_S32P;
  659. frame->nb_samples = avpkt->size & ~3;
  660. if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
  661. return ret;
  662. for (pos = 0; pos < frame->nb_samples; pos += 4) {
  663. int32_t samples[NB_CHANNELS][4];
  664. if (aptx_decode_samples(s, &avpkt->data[pos], samples)) {
  665. av_log(avctx, AV_LOG_ERROR, "Synchronization error\n");
  666. return AVERROR_INVALIDDATA;
  667. }
  668. for (channel = 0; channel < NB_CHANNELS; channel++)
  669. for (sample = 0; sample < 4; sample++)
  670. AV_WN32A(&frame->data[channel][4*(sample+pos)],
  671. samples[channel][sample] << 8);
  672. }
  673. *got_frame_ptr = 1;
  674. return frame->nb_samples;
  675. }
  676. static int aptx_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  677. const AVFrame *frame, int *got_packet_ptr)
  678. {
  679. AptXContext *s = avctx->priv_data;
  680. int pos, channel, sample, ret;
  681. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  682. return ret;
  683. if ((ret = ff_alloc_packet2(avctx, avpkt, frame->nb_samples, 0)) < 0)
  684. return ret;
  685. for (pos = 0; pos < frame->nb_samples; pos += 4) {
  686. int32_t samples[NB_CHANNELS][4];
  687. for (channel = 0; channel < NB_CHANNELS; channel++)
  688. for (sample = 0; sample < 4; sample++)
  689. samples[channel][sample] = (int32_t)AV_RN32A(&frame->data[channel][4*(sample+pos)]) >> 8;
  690. aptx_encode_samples(s, samples, avpkt->data + pos);
  691. }
  692. ff_af_queue_remove(&s->afq, frame->nb_samples, &avpkt->pts, &avpkt->duration);
  693. *got_packet_ptr = 1;
  694. return 0;
  695. }
  696. static av_cold int aptx_close(AVCodecContext *avctx)
  697. {
  698. AptXContext *s = avctx->priv_data;
  699. ff_af_queue_close(&s->afq);
  700. return 0;
  701. }
  702. #if CONFIG_APTX_DECODER
  703. AVCodec ff_aptx_decoder = {
  704. .name = "aptx",
  705. .long_name = NULL_IF_CONFIG_SMALL("aptX (Audio Processing Technology for Bluetooth)"),
  706. .type = AVMEDIA_TYPE_AUDIO,
  707. .id = AV_CODEC_ID_APTX,
  708. .priv_data_size = sizeof(AptXContext),
  709. .init = aptx_init,
  710. .decode = aptx_decode_frame,
  711. .close = aptx_close,
  712. .capabilities = AV_CODEC_CAP_DR1,
  713. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  714. .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_STEREO, 0},
  715. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
  716. AV_SAMPLE_FMT_NONE },
  717. };
  718. #endif
  719. #if CONFIG_APTX_ENCODER
  720. AVCodec ff_aptx_encoder = {
  721. .name = "aptx",
  722. .long_name = NULL_IF_CONFIG_SMALL("aptX (Audio Processing Technology for Bluetooth)"),
  723. .type = AVMEDIA_TYPE_AUDIO,
  724. .id = AV_CODEC_ID_APTX,
  725. .priv_data_size = sizeof(AptXContext),
  726. .init = aptx_init,
  727. .encode2 = aptx_encode_frame,
  728. .close = aptx_close,
  729. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME,
  730. .caps_internal = FF_CODEC_CAP_INIT_THREADSAFE,
  731. .channel_layouts = (const uint64_t[]) { AV_CH_LAYOUT_STEREO, 0},
  732. .sample_fmts = (const enum AVSampleFormat[]) { AV_SAMPLE_FMT_S32P,
  733. AV_SAMPLE_FMT_NONE },
  734. .supported_samplerates = (const int[]) {8000, 16000, 24000, 32000, 44100, 48000, 0},
  735. };
  736. #endif