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