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.

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