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.

962 lines
37KB

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