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.

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