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.

1045 lines
40KB

  1. /*
  2. * AAC coefficients encoder
  3. * Copyright (C) 2008-2009 Konstantin Shishkov
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file libavcodec/aaccoder.c
  23. * AAC coefficients encoder
  24. */
  25. /***********************************
  26. * TODOs:
  27. * speedup quantizer selection
  28. * add sane pulse detection
  29. ***********************************/
  30. #include "avcodec.h"
  31. #include "put_bits.h"
  32. #include "aac.h"
  33. #include "aacenc.h"
  34. #include "aactab.h"
  35. /** bits needed to code codebook run value for long windows */
  36. static const uint8_t run_value_bits_long[64] = {
  37. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  38. 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 10,
  39. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,
  40. 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 15
  41. };
  42. /** bits needed to code codebook run value for short windows */
  43. static const uint8_t run_value_bits_short[16] = {
  44. 3, 3, 3, 3, 3, 3, 3, 6, 6, 6, 6, 6, 6, 6, 6, 9
  45. };
  46. static const uint8_t *run_value_bits[2] = {
  47. run_value_bits_long, run_value_bits_short
  48. };
  49. /**
  50. * Quantize one coefficient.
  51. * @return absolute value of the quantized coefficient
  52. * @see 3GPP TS26.403 5.6.2 "Scalefactor determination"
  53. */
  54. static av_always_inline int quant(float coef, const float Q)
  55. {
  56. return pow(coef * Q, 0.75) + 0.4054;
  57. }
  58. static void quantize_bands(int (*out)[2], const float *in, const float *scaled,
  59. int size, float Q34, int is_signed, int maxval)
  60. {
  61. int i;
  62. double qc;
  63. for (i = 0; i < size; i++) {
  64. qc = scaled[i] * Q34;
  65. out[i][0] = (int)FFMIN((int)qc, maxval);
  66. out[i][1] = (int)FFMIN((int)(qc + 0.4054), maxval);
  67. if (is_signed && in[i] < 0.0f) {
  68. out[i][0] = -out[i][0];
  69. out[i][1] = -out[i][1];
  70. }
  71. }
  72. }
  73. static void abs_pow34_v(float *out, const float *in, const int size)
  74. {
  75. #ifndef USE_REALLY_FULL_SEARCH
  76. int i;
  77. for (i = 0; i < size; i++)
  78. out[i] = pow(fabsf(in[i]), 0.75);
  79. #endif /* USE_REALLY_FULL_SEARCH */
  80. }
  81. static av_always_inline int quant2(float coef, const float Q)
  82. {
  83. return pow(coef * Q, 0.75);
  84. }
  85. static const uint8_t aac_cb_range [12] = {0, 3, 3, 3, 3, 9, 9, 8, 8, 13, 13, 17};
  86. static const uint8_t aac_cb_maxval[12] = {0, 1, 1, 2, 2, 4, 4, 7, 7, 12, 12, 16};
  87. /**
  88. * Calculate rate distortion cost for quantizing with given codebook
  89. *
  90. * @return quantization distortion
  91. */
  92. static float quantize_band_cost(struct AACEncContext *s, const float *in,
  93. const float *scaled, int size, int scale_idx,
  94. int cb, const float lambda, const float uplim,
  95. int *bits)
  96. {
  97. const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
  98. const float Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];
  99. const float CLIPPED_ESCAPE = 165140.0f*IQ;
  100. int i, j, k;
  101. float cost = 0;
  102. const int dim = cb < FIRST_PAIR_BT ? 4 : 2;
  103. int resbits = 0;
  104. #ifndef USE_REALLY_FULL_SEARCH
  105. const float Q34 = pow(Q, 0.75);
  106. const int range = aac_cb_range[cb];
  107. const int maxval = aac_cb_maxval[cb];
  108. int offs[4];
  109. #endif /* USE_REALLY_FULL_SEARCH */
  110. if (!cb) {
  111. for (i = 0; i < size; i++)
  112. cost += in[i]*in[i]*lambda;
  113. return cost;
  114. }
  115. #ifndef USE_REALLY_FULL_SEARCH
  116. offs[0] = 1;
  117. for (i = 1; i < dim; i++)
  118. offs[i] = offs[i-1]*range;
  119. quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);
  120. #endif /* USE_REALLY_FULL_SEARCH */
  121. for (i = 0; i < size; i += dim) {
  122. float mincost;
  123. int minidx = 0;
  124. int minbits = 0;
  125. const float *vec;
  126. #ifndef USE_REALLY_FULL_SEARCH
  127. int (*quants)[2] = &s->qcoefs[i];
  128. mincost = 0.0f;
  129. for (j = 0; j < dim; j++)
  130. mincost += in[i+j]*in[i+j]*lambda;
  131. minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
  132. minbits = ff_aac_spectral_bits[cb-1][minidx];
  133. mincost += minbits;
  134. for (j = 0; j < (1<<dim); j++) {
  135. float rd = 0.0f;
  136. int curbits;
  137. int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
  138. int same = 0;
  139. for (k = 0; k < dim; k++) {
  140. if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {
  141. same = 1;
  142. break;
  143. }
  144. }
  145. if (same)
  146. continue;
  147. for (k = 0; k < dim; k++)
  148. curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];
  149. curbits = ff_aac_spectral_bits[cb-1][curidx];
  150. vec = &ff_aac_codebook_vectors[cb-1][curidx*dim];
  151. #else
  152. mincost = INFINITY;
  153. vec = ff_aac_codebook_vectors[cb-1];
  154. for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {
  155. float rd = 0.0f;
  156. int curbits = ff_aac_spectral_bits[cb-1][j];
  157. #endif /* USE_REALLY_FULL_SEARCH */
  158. if (IS_CODEBOOK_UNSIGNED(cb)) {
  159. for (k = 0; k < dim; k++) {
  160. float t = fabsf(in[i+k]);
  161. float di;
  162. //do not code with escape sequence small values
  163. if (vec[k] == 64.0f && t < 39.0f*IQ) {
  164. rd = INFINITY;
  165. break;
  166. }
  167. if (vec[k] == 64.0f) { //FIXME: slow
  168. if (t >= CLIPPED_ESCAPE) {
  169. di = t - CLIPPED_ESCAPE;
  170. curbits += 21;
  171. } else {
  172. int c = av_clip(quant(t, Q), 0, 8191);
  173. di = t - c*cbrt(c)*IQ;
  174. curbits += av_log2(c)*2 - 4 + 1;
  175. }
  176. } else {
  177. di = t - vec[k]*IQ;
  178. }
  179. if (vec[k] != 0.0f)
  180. curbits++;
  181. rd += di*di*lambda;
  182. }
  183. } else {
  184. for (k = 0; k < dim; k++) {
  185. float di = in[i+k] - vec[k]*IQ;
  186. rd += di*di*lambda;
  187. }
  188. }
  189. rd += curbits;
  190. if (rd < mincost) {
  191. mincost = rd;
  192. minidx = j;
  193. minbits = curbits;
  194. }
  195. }
  196. cost += mincost;
  197. resbits += minbits;
  198. if (cost >= uplim)
  199. return uplim;
  200. }
  201. if (bits)
  202. *bits = resbits;
  203. return cost;
  204. }
  205. static void quantize_and_encode_band(struct AACEncContext *s, PutBitContext *pb,
  206. const float *in, int size, int scale_idx,
  207. int cb, const float lambda)
  208. {
  209. const float IQ = ff_aac_pow2sf_tab[200 + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];
  210. const float Q = ff_aac_pow2sf_tab[200 - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];
  211. const float CLIPPED_ESCAPE = 165140.0f*IQ;
  212. const int dim = (cb < FIRST_PAIR_BT) ? 4 : 2;
  213. int i, j, k;
  214. #ifndef USE_REALLY_FULL_SEARCH
  215. const float Q34 = pow(Q, 0.75);
  216. const int range = aac_cb_range[cb];
  217. const int maxval = aac_cb_maxval[cb];
  218. int offs[4];
  219. float *scaled = s->scoefs;
  220. #endif /* USE_REALLY_FULL_SEARCH */
  221. //START_TIMER
  222. if (!cb)
  223. return;
  224. #ifndef USE_REALLY_FULL_SEARCH
  225. offs[0] = 1;
  226. for (i = 1; i < dim; i++)
  227. offs[i] = offs[i-1]*range;
  228. abs_pow34_v(scaled, in, size);
  229. quantize_bands(s->qcoefs, in, scaled, size, Q34, !IS_CODEBOOK_UNSIGNED(cb), maxval);
  230. #endif /* USE_REALLY_FULL_SEARCH */
  231. for (i = 0; i < size; i += dim) {
  232. float mincost;
  233. int minidx = 0;
  234. int minbits = 0;
  235. const float *vec;
  236. #ifndef USE_REALLY_FULL_SEARCH
  237. int (*quants)[2] = &s->qcoefs[i];
  238. mincost = 0.0f;
  239. for (j = 0; j < dim; j++)
  240. mincost += in[i+j]*in[i+j]*lambda;
  241. minidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
  242. minbits = ff_aac_spectral_bits[cb-1][minidx];
  243. mincost += minbits;
  244. for (j = 0; j < (1<<dim); j++) {
  245. float rd = 0.0f;
  246. int curbits;
  247. int curidx = IS_CODEBOOK_UNSIGNED(cb) ? 0 : 40;
  248. int same = 0;
  249. for (k = 0; k < dim; k++) {
  250. if ((j & (1 << k)) && quants[k][0] == quants[k][1]) {
  251. same = 1;
  252. break;
  253. }
  254. }
  255. if (same)
  256. continue;
  257. for (k = 0; k < dim; k++)
  258. curidx += quants[k][!!(j & (1 << k))] * offs[dim - 1 - k];
  259. curbits = ff_aac_spectral_bits[cb-1][curidx];
  260. vec = &ff_aac_codebook_vectors[cb-1][curidx*dim];
  261. #else
  262. vec = ff_aac_codebook_vectors[cb-1];
  263. mincost = INFINITY;
  264. for (j = 0; j < ff_aac_spectral_sizes[cb-1]; j++, vec += dim) {
  265. float rd = 0.0f;
  266. int curbits = ff_aac_spectral_bits[cb-1][j];
  267. int curidx = j;
  268. #endif /* USE_REALLY_FULL_SEARCH */
  269. if (IS_CODEBOOK_UNSIGNED(cb)) {
  270. for (k = 0; k < dim; k++) {
  271. float t = fabsf(in[i+k]);
  272. float di;
  273. //do not code with escape sequence small values
  274. if (vec[k] == 64.0f && t < 39.0f*IQ) {
  275. rd = INFINITY;
  276. break;
  277. }
  278. if (vec[k] == 64.0f) { //FIXME: slow
  279. if (t >= CLIPPED_ESCAPE) {
  280. di = t - CLIPPED_ESCAPE;
  281. curbits += 21;
  282. } else {
  283. int c = av_clip(quant(t, Q), 0, 8191);
  284. di = t - c*cbrt(c)*IQ;
  285. curbits += av_log2(c)*2 - 4 + 1;
  286. }
  287. } else {
  288. di = t - vec[k]*IQ;
  289. }
  290. if (vec[k] != 0.0f)
  291. curbits++;
  292. rd += di*di*lambda;
  293. }
  294. } else {
  295. for (k = 0; k < dim; k++) {
  296. float di = in[i+k] - vec[k]*IQ;
  297. rd += di*di*lambda;
  298. }
  299. }
  300. rd += curbits;
  301. if (rd < mincost) {
  302. mincost = rd;
  303. minidx = curidx;
  304. minbits = curbits;
  305. }
  306. }
  307. put_bits(pb, ff_aac_spectral_bits[cb-1][minidx], ff_aac_spectral_codes[cb-1][minidx]);
  308. if (IS_CODEBOOK_UNSIGNED(cb))
  309. for (j = 0; j < dim; j++)
  310. if (ff_aac_codebook_vectors[cb-1][minidx*dim+j] != 0.0f)
  311. put_bits(pb, 1, in[i+j] < 0.0f);
  312. if (cb == ESC_BT) {
  313. for (j = 0; j < 2; j++) {
  314. if (ff_aac_codebook_vectors[cb-1][minidx*2+j] == 64.0f) {
  315. int coef = av_clip(quant(fabsf(in[i+j]), Q), 0, 8191);
  316. int len = av_log2(coef);
  317. put_bits(pb, len - 4 + 1, (1 << (len - 4 + 1)) - 2);
  318. put_bits(pb, len, coef & ((1 << len) - 1));
  319. }
  320. }
  321. }
  322. }
  323. //STOP_TIMER("quantize_and_encode")
  324. }
  325. /**
  326. * structure used in optimal codebook search
  327. */
  328. typedef struct BandCodingPath {
  329. int prev_idx; ///< pointer to the previous path point
  330. int codebook; ///< codebook for coding band run
  331. float cost; ///< path cost
  332. int run;
  333. } BandCodingPath;
  334. /**
  335. * Encode band info for single window group bands.
  336. */
  337. static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce,
  338. int win, int group_len, const float lambda)
  339. {
  340. BandCodingPath path[120][12];
  341. int w, swb, cb, start, start2, size;
  342. int i, j;
  343. const int max_sfb = sce->ics.max_sfb;
  344. const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
  345. const int run_esc = (1 << run_bits) - 1;
  346. int idx, ppos, count;
  347. int stackrun[120], stackcb[120], stack_len;
  348. float next_minrd = INFINITY;
  349. int next_mincb = 0;
  350. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  351. start = win*128;
  352. for (cb = 0; cb < 12; cb++) {
  353. path[0][cb].cost = 0.0f;
  354. path[0][cb].prev_idx = -1;
  355. path[0][cb].run = 0;
  356. }
  357. for (swb = 0; swb < max_sfb; swb++) {
  358. start2 = start;
  359. size = sce->ics.swb_sizes[swb];
  360. if (sce->zeroes[win*16 + swb]) {
  361. for (cb = 0; cb < 12; cb++) {
  362. path[swb+1][cb].prev_idx = cb;
  363. path[swb+1][cb].cost = path[swb][cb].cost;
  364. path[swb+1][cb].run = path[swb][cb].run + 1;
  365. }
  366. } else {
  367. float minrd = next_minrd;
  368. int mincb = next_mincb;
  369. next_minrd = INFINITY;
  370. next_mincb = 0;
  371. for (cb = 0; cb < 12; cb++) {
  372. float cost_stay_here, cost_get_here;
  373. float rd = 0.0f;
  374. for (w = 0; w < group_len; w++) {
  375. FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(win+w)*16+swb];
  376. rd += quantize_band_cost(s, sce->coeffs + start + w*128,
  377. s->scoefs + start + w*128, size,
  378. sce->sf_idx[(win+w)*16+swb], cb,
  379. lambda / band->threshold, INFINITY, NULL);
  380. }
  381. cost_stay_here = path[swb][cb].cost + rd;
  382. cost_get_here = minrd + rd + run_bits + 4;
  383. if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
  384. != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
  385. cost_stay_here += run_bits;
  386. if (cost_get_here < cost_stay_here) {
  387. path[swb+1][cb].prev_idx = mincb;
  388. path[swb+1][cb].cost = cost_get_here;
  389. path[swb+1][cb].run = 1;
  390. } else {
  391. path[swb+1][cb].prev_idx = cb;
  392. path[swb+1][cb].cost = cost_stay_here;
  393. path[swb+1][cb].run = path[swb][cb].run + 1;
  394. }
  395. if (path[swb+1][cb].cost < next_minrd) {
  396. next_minrd = path[swb+1][cb].cost;
  397. next_mincb = cb;
  398. }
  399. }
  400. }
  401. start += sce->ics.swb_sizes[swb];
  402. }
  403. //convert resulting path from backward-linked list
  404. stack_len = 0;
  405. idx = 0;
  406. for (cb = 1; cb < 12; cb++)
  407. if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
  408. idx = cb;
  409. ppos = max_sfb;
  410. while (ppos > 0) {
  411. cb = idx;
  412. stackrun[stack_len] = path[ppos][cb].run;
  413. stackcb [stack_len] = cb;
  414. idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
  415. ppos -= path[ppos][cb].run;
  416. stack_len++;
  417. }
  418. //perform actual band info encoding
  419. start = 0;
  420. for (i = stack_len - 1; i >= 0; i--) {
  421. put_bits(&s->pb, 4, stackcb[i]);
  422. count = stackrun[i];
  423. memset(sce->zeroes + win*16 + start, !stackcb[i], count);
  424. //XXX: memset when band_type is also uint8_t
  425. for (j = 0; j < count; j++) {
  426. sce->band_type[win*16 + start] = stackcb[i];
  427. start++;
  428. }
  429. while (count >= run_esc) {
  430. put_bits(&s->pb, run_bits, run_esc);
  431. count -= run_esc;
  432. }
  433. put_bits(&s->pb, run_bits, count);
  434. }
  435. }
  436. static void encode_window_bands_info_fixed(AACEncContext *s,
  437. SingleChannelElement *sce,
  438. int win, int group_len,
  439. const float lambda)
  440. {
  441. encode_window_bands_info(s, sce, win, group_len, 1.0f);
  442. }
  443. typedef struct TrellisPath {
  444. float cost;
  445. int prev;
  446. int min_val;
  447. int max_val;
  448. } TrellisPath;
  449. static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
  450. SingleChannelElement *sce,
  451. const float lambda)
  452. {
  453. int q, w, w2, g, start = 0;
  454. int i;
  455. int idx;
  456. TrellisPath paths[256*121];
  457. int bandaddr[121];
  458. int minq;
  459. float mincost;
  460. for (i = 0; i < 256; i++) {
  461. paths[i].cost = 0.0f;
  462. paths[i].prev = -1;
  463. paths[i].min_val = i;
  464. paths[i].max_val = i;
  465. }
  466. for (i = 256; i < 256*121; i++) {
  467. paths[i].cost = INFINITY;
  468. paths[i].prev = -2;
  469. paths[i].min_val = INT_MAX;
  470. paths[i].max_val = 0;
  471. }
  472. idx = 256;
  473. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  474. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  475. start = w*128;
  476. for (g = 0; g < sce->ics.num_swb; g++) {
  477. const float *coefs = sce->coeffs + start;
  478. float qmin, qmax;
  479. int nz = 0;
  480. bandaddr[idx >> 8] = w * 16 + g;
  481. qmin = INT_MAX;
  482. qmax = 0.0f;
  483. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  484. FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
  485. if (band->energy <= band->threshold || band->threshold == 0.0f) {
  486. sce->zeroes[(w+w2)*16+g] = 1;
  487. continue;
  488. }
  489. sce->zeroes[(w+w2)*16+g] = 0;
  490. nz = 1;
  491. for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
  492. float t = fabsf(coefs[w2*128+i]);
  493. if (t > 0.0f)
  494. qmin = fminf(qmin, t);
  495. qmax = fmaxf(qmax, t);
  496. }
  497. }
  498. if (nz) {
  499. int minscale, maxscale;
  500. float minrd = INFINITY;
  501. //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
  502. minscale = av_clip_uint8(log2(qmin)*4 - 69 + SCALE_ONE_POS - SCALE_DIV_512);
  503. //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
  504. maxscale = av_clip_uint8(log2(qmax)*4 + 6 + SCALE_ONE_POS - SCALE_DIV_512);
  505. for (q = minscale; q < maxscale; q++) {
  506. float dists[12], dist;
  507. memset(dists, 0, sizeof(dists));
  508. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  509. FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
  510. int cb;
  511. for (cb = 0; cb <= ESC_BT; cb++)
  512. dists[cb] += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
  513. q, cb, lambda / band->threshold, INFINITY, NULL);
  514. }
  515. dist = dists[0];
  516. for (i = 1; i <= ESC_BT; i++)
  517. dist = fminf(dist, dists[i]);
  518. minrd = fminf(minrd, dist);
  519. for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, 256); i++) {
  520. float cost;
  521. int minv, maxv;
  522. if (isinf(paths[idx - 256 + i].cost))
  523. continue;
  524. cost = paths[idx - 256 + i].cost + dist
  525. + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
  526. minv = FFMIN(paths[idx - 256 + i].min_val, q);
  527. maxv = FFMAX(paths[idx - 256 + i].max_val, q);
  528. if (cost < paths[idx + q].cost && maxv-minv < SCALE_MAX_DIFF) {
  529. paths[idx + q].cost = cost;
  530. paths[idx + q].prev = idx - 256 + i;
  531. paths[idx + q].min_val = minv;
  532. paths[idx + q].max_val = maxv;
  533. }
  534. }
  535. }
  536. } else {
  537. for (q = 0; q < 256; q++) {
  538. if (!isinf(paths[idx - 256 + q].cost)) {
  539. paths[idx + q].cost = paths[idx - 256 + q].cost + 1;
  540. paths[idx + q].prev = idx - 256 + q;
  541. paths[idx + q].min_val = FFMIN(paths[idx - 256 + q].min_val, q);
  542. paths[idx + q].max_val = FFMAX(paths[idx - 256 + q].max_val, q);
  543. continue;
  544. }
  545. for (i = FFMAX(q - SCALE_MAX_DIFF, 0); i < FFMIN(q + SCALE_MAX_DIFF, 256); i++) {
  546. float cost;
  547. int minv, maxv;
  548. if (isinf(paths[idx - 256 + i].cost))
  549. continue;
  550. cost = paths[idx - 256 + i].cost + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
  551. minv = FFMIN(paths[idx - 256 + i].min_val, q);
  552. maxv = FFMAX(paths[idx - 256 + i].max_val, q);
  553. if (cost < paths[idx + q].cost && maxv-minv < SCALE_MAX_DIFF) {
  554. paths[idx + q].cost = cost;
  555. paths[idx + q].prev = idx - 256 + i;
  556. paths[idx + q].min_val = minv;
  557. paths[idx + q].max_val = maxv;
  558. }
  559. }
  560. }
  561. }
  562. sce->zeroes[w*16+g] = !nz;
  563. start += sce->ics.swb_sizes[g];
  564. idx += 256;
  565. }
  566. }
  567. idx -= 256;
  568. mincost = paths[idx].cost;
  569. minq = idx;
  570. for (i = 1; i < 256; i++) {
  571. if (paths[idx + i].cost < mincost) {
  572. mincost = paths[idx + i].cost;
  573. minq = idx + i;
  574. }
  575. }
  576. while (minq >= 256) {
  577. sce->sf_idx[bandaddr[minq>>8]] = minq & 0xFF;
  578. minq = paths[minq].prev;
  579. }
  580. //set the same quantizers inside window groups
  581. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  582. for (g = 0; g < sce->ics.num_swb; g++)
  583. for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
  584. sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
  585. }
  586. /**
  587. * two-loop quantizers search taken from ISO 13818-7 Appendix C
  588. */
  589. static void search_for_quantizers_twoloop(AVCodecContext *avctx,
  590. AACEncContext *s,
  591. SingleChannelElement *sce,
  592. const float lambda)
  593. {
  594. int start = 0, i, w, w2, g;
  595. int destbits = avctx->bit_rate * 1024.0 / avctx->sample_rate / avctx->channels;
  596. float dists[128], uplims[128];
  597. int fflag, minscaler;
  598. int its = 0;
  599. int allz = 0;
  600. float minthr = INFINITY;
  601. //XXX: some heuristic to determine initial quantizers will reduce search time
  602. memset(dists, 0, sizeof(dists));
  603. //determine zero bands and upper limits
  604. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  605. for (g = 0; g < sce->ics.num_swb; g++) {
  606. int nz = 0;
  607. float uplim = 0.0f;
  608. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  609. FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
  610. uplim += band->threshold;
  611. if (band->energy <= band->threshold || band->threshold == 0.0f) {
  612. sce->zeroes[(w+w2)*16+g] = 1;
  613. continue;
  614. }
  615. nz = 1;
  616. }
  617. uplims[w*16+g] = uplim *512;
  618. sce->zeroes[w*16+g] = !nz;
  619. if (nz)
  620. minthr = fminf(minthr, uplim);
  621. allz = FFMAX(allz, nz);
  622. }
  623. }
  624. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  625. for (g = 0; g < sce->ics.num_swb; g++) {
  626. if (sce->zeroes[w*16+g]) {
  627. sce->sf_idx[w*16+g] = SCALE_ONE_POS;
  628. continue;
  629. }
  630. sce->sf_idx[w*16+g] = SCALE_ONE_POS + fminf(log2(uplims[w*16+g]/minthr)*4,59);
  631. }
  632. }
  633. if (!allz)
  634. return;
  635. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  636. //perform two-loop search
  637. //outer loop - improve quality
  638. do {
  639. int tbits, qstep;
  640. minscaler = sce->sf_idx[0];
  641. //inner loop - quantize spectrum to fit into given number of bits
  642. qstep = its ? 1 : 32;
  643. do {
  644. int prev = -1;
  645. tbits = 0;
  646. fflag = 0;
  647. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  648. start = w*128;
  649. for (g = 0; g < sce->ics.num_swb; g++) {
  650. const float *coefs = sce->coeffs + start;
  651. const float *scaled = s->scoefs + start;
  652. int bits = 0;
  653. int cb;
  654. float mindist = INFINITY;
  655. int minbits = 0;
  656. if (sce->zeroes[w*16+g] || sce->sf_idx[w*16+g] >= 218)
  657. continue;
  658. minscaler = FFMIN(minscaler, sce->sf_idx[w*16+g]);
  659. for (cb = 0; cb <= ESC_BT; cb++) {
  660. float dist = 0.0f;
  661. int bb = 0;
  662. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  663. int b;
  664. dist += quantize_band_cost(s, coefs + w2*128,
  665. scaled + w2*128,
  666. sce->ics.swb_sizes[g],
  667. sce->sf_idx[w*16+g],
  668. ESC_BT,
  669. 1.0,
  670. INFINITY,
  671. &b);
  672. bb += b;
  673. }
  674. if (dist < mindist) {
  675. mindist = dist;
  676. minbits = bb;
  677. }
  678. }
  679. dists[w*16+g] = mindist - minbits;
  680. bits = minbits;
  681. if (prev != -1) {
  682. bits += ff_aac_scalefactor_bits[sce->sf_idx[w*16+g] - prev + SCALE_DIFF_ZERO];
  683. }
  684. tbits += bits;
  685. start += sce->ics.swb_sizes[g];
  686. prev = sce->sf_idx[w*16+g];
  687. }
  688. }
  689. if (tbits > destbits) {
  690. for (i = 0; i < 128; i++)
  691. if (sce->sf_idx[i] < 218 - qstep)
  692. sce->sf_idx[i] += qstep;
  693. } else {
  694. for (i = 0; i < 128; i++)
  695. if (sce->sf_idx[i] > 60 - qstep)
  696. sce->sf_idx[i] -= qstep;
  697. }
  698. qstep >>= 1;
  699. if (!qstep && tbits > destbits*1.02)
  700. qstep = 1;
  701. if (sce->sf_idx[0] >= 217)
  702. break;
  703. } while (qstep);
  704. fflag = 0;
  705. minscaler = av_clip(minscaler, 60, 255 - SCALE_MAX_DIFF);
  706. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  707. start = w*128;
  708. for (g = 0; g < sce->ics.num_swb; g++) {
  709. int prevsc = sce->sf_idx[w*16+g];
  710. if (dists[w*16+g] > uplims[w*16+g] && sce->sf_idx[w*16+g] > 60)
  711. sce->sf_idx[w*16+g]--;
  712. sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler, minscaler + SCALE_MAX_DIFF);
  713. sce->sf_idx[w*16+g] = FFMIN(sce->sf_idx[w*16+g], 219);
  714. if (sce->sf_idx[w*16+g] != prevsc)
  715. fflag = 1;
  716. }
  717. }
  718. its++;
  719. } while (fflag && its < 10);
  720. }
  721. static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
  722. SingleChannelElement *sce,
  723. const float lambda)
  724. {
  725. int start = 0, i, w, w2, g;
  726. float uplim[128], maxq[128];
  727. int minq, maxsf;
  728. float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
  729. int last = 0, lastband = 0, curband = 0;
  730. float avg_energy = 0.0;
  731. if (sce->ics.num_windows == 1) {
  732. start = 0;
  733. for (i = 0; i < 1024; i++) {
  734. if (i - start >= sce->ics.swb_sizes[curband]) {
  735. start += sce->ics.swb_sizes[curband];
  736. curband++;
  737. }
  738. if (sce->coeffs[i]) {
  739. avg_energy += sce->coeffs[i] * sce->coeffs[i];
  740. last = i;
  741. lastband = curband;
  742. }
  743. }
  744. } else {
  745. for (w = 0; w < 8; w++) {
  746. const float *coeffs = sce->coeffs + w*128;
  747. start = 0;
  748. for (i = 0; i < 128; i++) {
  749. if (i - start >= sce->ics.swb_sizes[curband]) {
  750. start += sce->ics.swb_sizes[curband];
  751. curband++;
  752. }
  753. if (coeffs[i]) {
  754. avg_energy += coeffs[i] * coeffs[i];
  755. last = FFMAX(last, i);
  756. lastband = FFMAX(lastband, curband);
  757. }
  758. }
  759. }
  760. }
  761. last++;
  762. avg_energy /= last;
  763. if (avg_energy == 0.0f) {
  764. for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
  765. sce->sf_idx[i] = SCALE_ONE_POS;
  766. return;
  767. }
  768. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  769. start = w*128;
  770. for (g = 0; g < sce->ics.num_swb; g++) {
  771. float *coefs = sce->coeffs + start;
  772. const int size = sce->ics.swb_sizes[g];
  773. int start2 = start, end2 = start + size, peakpos = start;
  774. float maxval = -1, thr = 0.0f, t;
  775. maxq[w*16+g] = 0.0f;
  776. if (g > lastband) {
  777. maxq[w*16+g] = 0.0f;
  778. start += size;
  779. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
  780. memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
  781. continue;
  782. }
  783. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  784. for (i = 0; i < size; i++) {
  785. float t = coefs[w2*128+i]*coefs[w2*128+i];
  786. maxq[w*16+g] = fmaxf(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
  787. thr += t;
  788. if (sce->ics.num_windows == 1 && maxval < t) {
  789. maxval = t;
  790. peakpos = start+i;
  791. }
  792. }
  793. }
  794. if (sce->ics.num_windows == 1) {
  795. start2 = FFMAX(peakpos - 2, start2);
  796. end2 = FFMIN(peakpos + 3, end2);
  797. } else {
  798. start2 -= start;
  799. end2 -= start;
  800. }
  801. start += size;
  802. thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
  803. t = 1.0 - (1.0 * start2 / last);
  804. uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
  805. }
  806. }
  807. memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
  808. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  809. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  810. start = w*128;
  811. for (g = 0; g < sce->ics.num_swb; g++) {
  812. const float *coefs = sce->coeffs + start;
  813. const float *scaled = s->scoefs + start;
  814. const int size = sce->ics.swb_sizes[g];
  815. int scf, prev_scf, step;
  816. int min_scf = 0, max_scf = 255;
  817. float curdiff;
  818. if (maxq[w*16+g] < 21.544) {
  819. sce->zeroes[w*16+g] = 1;
  820. start += size;
  821. continue;
  822. }
  823. sce->zeroes[w*16+g] = 0;
  824. scf = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2(1/maxq[w*16+g])*16/3, 60, 218);
  825. step = 16;
  826. for (;;) {
  827. float dist = 0.0f;
  828. int quant_max;
  829. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  830. int b;
  831. dist += quantize_band_cost(s, coefs + w2*128,
  832. scaled + w2*128,
  833. sce->ics.swb_sizes[g],
  834. scf,
  835. ESC_BT,
  836. 1.0,
  837. INFINITY,
  838. &b);
  839. dist -= b;
  840. }
  841. dist *= 1.0f/512.0f;
  842. quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[200 - scf + SCALE_ONE_POS - SCALE_DIV_512]);
  843. if (quant_max >= 8191) { // too much, return to the previous quantizer
  844. sce->sf_idx[w*16+g] = prev_scf;
  845. break;
  846. }
  847. prev_scf = scf;
  848. curdiff = fabsf(dist - uplim[w*16+g]);
  849. if (curdiff == 0.0f)
  850. step = 0;
  851. else
  852. step = fabsf(log2(curdiff));
  853. if (dist > uplim[w*16+g])
  854. step = -step;
  855. if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
  856. sce->sf_idx[w*16+g] = scf;
  857. break;
  858. }
  859. scf += step;
  860. if (step > 0)
  861. min_scf = scf;
  862. else
  863. max_scf = scf;
  864. }
  865. start += size;
  866. }
  867. }
  868. minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
  869. for (i = 1; i < 128; i++) {
  870. if (!sce->sf_idx[i])
  871. sce->sf_idx[i] = sce->sf_idx[i-1];
  872. else
  873. minq = FFMIN(minq, sce->sf_idx[i]);
  874. }
  875. if (minq == INT_MAX)
  876. minq = 0;
  877. minq = FFMIN(minq, SCALE_MAX_POS);
  878. maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
  879. for (i = 126; i >= 0; i--) {
  880. if (!sce->sf_idx[i])
  881. sce->sf_idx[i] = sce->sf_idx[i+1];
  882. sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
  883. }
  884. }
  885. static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
  886. SingleChannelElement *sce,
  887. const float lambda)
  888. {
  889. int start = 0, i, w, w2, g;
  890. int minq = 255;
  891. memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
  892. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  893. start = w*128;
  894. for (g = 0; g < sce->ics.num_swb; g++) {
  895. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  896. FFPsyBand *band = &s->psy.psy_bands[s->cur_channel*PSY_MAX_BANDS+(w+w2)*16+g];
  897. if (band->energy <= band->threshold) {
  898. sce->sf_idx[(w+w2)*16+g] = 218;
  899. sce->zeroes[(w+w2)*16+g] = 1;
  900. } else {
  901. sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2(band->threshold), 80, 218);
  902. sce->zeroes[(w+w2)*16+g] = 0;
  903. }
  904. minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
  905. }
  906. }
  907. }
  908. for (i = 0; i < 128; i++) {
  909. sce->sf_idx[i] = 140;
  910. //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
  911. }
  912. //set the same quantizers inside window groups
  913. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  914. for (g = 0; g < sce->ics.num_swb; g++)
  915. for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
  916. sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
  917. }
  918. static void search_for_ms(AACEncContext *s, ChannelElement *cpe,
  919. const float lambda)
  920. {
  921. int start = 0, i, w, w2, g;
  922. float M[128], S[128];
  923. float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
  924. SingleChannelElement *sce0 = &cpe->ch[0];
  925. SingleChannelElement *sce1 = &cpe->ch[1];
  926. if (!cpe->common_window)
  927. return;
  928. for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
  929. for (g = 0; g < sce0->ics.num_swb; g++) {
  930. if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
  931. float dist1 = 0.0f, dist2 = 0.0f;
  932. for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
  933. FFPsyBand *band0 = &s->psy.psy_bands[(s->cur_channel+0)*PSY_MAX_BANDS+(w+w2)*16+g];
  934. FFPsyBand *band1 = &s->psy.psy_bands[(s->cur_channel+1)*PSY_MAX_BANDS+(w+w2)*16+g];
  935. float minthr = fminf(band0->threshold, band1->threshold);
  936. float maxthr = fmaxf(band0->threshold, band1->threshold);
  937. for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
  938. M[i] = (sce0->coeffs[start+w2*128+i]
  939. + sce1->coeffs[start+w2*128+i]) * 0.5;
  940. S[i] = sce0->coeffs[start+w2*128+i]
  941. - sce1->coeffs[start+w2*128+i];
  942. }
  943. abs_pow34_v(L34, sce0->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
  944. abs_pow34_v(R34, sce1->coeffs+start+w2*128, sce0->ics.swb_sizes[g]);
  945. abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
  946. abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
  947. dist1 += quantize_band_cost(s, sce0->coeffs + start + w2*128,
  948. L34,
  949. sce0->ics.swb_sizes[g],
  950. sce0->sf_idx[(w+w2)*16+g],
  951. sce0->band_type[(w+w2)*16+g],
  952. lambda / band0->threshold, INFINITY, NULL);
  953. dist1 += quantize_band_cost(s, sce1->coeffs + start + w2*128,
  954. R34,
  955. sce1->ics.swb_sizes[g],
  956. sce1->sf_idx[(w+w2)*16+g],
  957. sce1->band_type[(w+w2)*16+g],
  958. lambda / band1->threshold, INFINITY, NULL);
  959. dist2 += quantize_band_cost(s, M,
  960. M34,
  961. sce0->ics.swb_sizes[g],
  962. sce0->sf_idx[(w+w2)*16+g],
  963. sce0->band_type[(w+w2)*16+g],
  964. lambda / maxthr, INFINITY, NULL);
  965. dist2 += quantize_band_cost(s, S,
  966. S34,
  967. sce1->ics.swb_sizes[g],
  968. sce1->sf_idx[(w+w2)*16+g],
  969. sce1->band_type[(w+w2)*16+g],
  970. lambda / minthr, INFINITY, NULL);
  971. }
  972. cpe->ms_mask[w*16+g] = dist2 < dist1;
  973. }
  974. start += sce0->ics.swb_sizes[g];
  975. }
  976. }
  977. }
  978. AACCoefficientsEncoder ff_aac_coders[] = {
  979. {
  980. search_for_quantizers_faac,
  981. encode_window_bands_info_fixed,
  982. quantize_and_encode_band,
  983. // search_for_ms,
  984. },
  985. {
  986. search_for_quantizers_anmr,
  987. encode_window_bands_info,
  988. quantize_and_encode_band,
  989. // search_for_ms,
  990. },
  991. {
  992. search_for_quantizers_twoloop,
  993. encode_window_bands_info,
  994. quantize_and_encode_band,
  995. // search_for_ms,
  996. },
  997. {
  998. search_for_quantizers_fast,
  999. encode_window_bands_info,
  1000. quantize_and_encode_band,
  1001. // search_for_ms,
  1002. },
  1003. };