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.

999 lines
41KB

  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 "libavutil/libm.h" // brought forward to work around cygwin header breakage
  31. #include <float.h>
  32. #include "libavutil/mathematics.h"
  33. #include "mathops.h"
  34. #include "avcodec.h"
  35. #include "put_bits.h"
  36. #include "aac.h"
  37. #include "aacenc.h"
  38. #include "aactab.h"
  39. #include "aacenctab.h"
  40. #include "aacenc_utils.h"
  41. #include "aacenc_quantization.h"
  42. #include "aac_tablegen_decl.h"
  43. #include "aacenc_is.h"
  44. #include "aacenc_tns.h"
  45. #include "aacenc_ltp.h"
  46. #include "aacenc_pred.h"
  47. #include "libavcodec/aaccoder_twoloop.h"
  48. /* Parameter of f(x) = a*(lambda/100), defines the maximum fourier spread
  49. * beyond which no PNS is used (since the SFBs contain tone rather than noise) */
  50. #define NOISE_SPREAD_THRESHOLD 0.5073f
  51. /* Parameter of f(x) = a*(100/lambda), defines how much PNS is allowed to
  52. * replace low energy non zero bands */
  53. #define NOISE_LAMBDA_REPLACE 1.948f
  54. #include "libavcodec/aaccoder_trellis.h"
  55. /**
  56. * structure used in optimal codebook search
  57. */
  58. typedef struct BandCodingPath {
  59. int prev_idx; ///< pointer to the previous path point
  60. float cost; ///< path cost
  61. int run;
  62. } BandCodingPath;
  63. /**
  64. * Encode band info for single window group bands.
  65. */
  66. static void encode_window_bands_info(AACEncContext *s, SingleChannelElement *sce,
  67. int win, int group_len, const float lambda)
  68. {
  69. BandCodingPath path[120][CB_TOT_ALL];
  70. int w, swb, cb, start, size;
  71. int i, j;
  72. const int max_sfb = sce->ics.max_sfb;
  73. const int run_bits = sce->ics.num_windows == 1 ? 5 : 3;
  74. const int run_esc = (1 << run_bits) - 1;
  75. int idx, ppos, count;
  76. int stackrun[120], stackcb[120], stack_len;
  77. float next_minrd = INFINITY;
  78. int next_mincb = 0;
  79. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  80. start = win*128;
  81. for (cb = 0; cb < CB_TOT_ALL; cb++) {
  82. path[0][cb].cost = 0.0f;
  83. path[0][cb].prev_idx = -1;
  84. path[0][cb].run = 0;
  85. }
  86. for (swb = 0; swb < max_sfb; swb++) {
  87. size = sce->ics.swb_sizes[swb];
  88. if (sce->zeroes[win*16 + swb]) {
  89. for (cb = 0; cb < CB_TOT_ALL; cb++) {
  90. path[swb+1][cb].prev_idx = cb;
  91. path[swb+1][cb].cost = path[swb][cb].cost;
  92. path[swb+1][cb].run = path[swb][cb].run + 1;
  93. }
  94. } else {
  95. float minrd = next_minrd;
  96. int mincb = next_mincb;
  97. next_minrd = INFINITY;
  98. next_mincb = 0;
  99. for (cb = 0; cb < CB_TOT_ALL; cb++) {
  100. float cost_stay_here, cost_get_here;
  101. float rd = 0.0f;
  102. if (cb >= 12 && sce->band_type[win*16+swb] < aac_cb_out_map[cb] ||
  103. cb < aac_cb_in_map[sce->band_type[win*16+swb]] && sce->band_type[win*16+swb] > aac_cb_out_map[cb]) {
  104. path[swb+1][cb].prev_idx = -1;
  105. path[swb+1][cb].cost = INFINITY;
  106. path[swb+1][cb].run = path[swb][cb].run + 1;
  107. continue;
  108. }
  109. for (w = 0; w < group_len; w++) {
  110. FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(win+w)*16+swb];
  111. rd += quantize_band_cost(s, &sce->coeffs[start + w*128],
  112. &s->scoefs[start + w*128], size,
  113. sce->sf_idx[(win+w)*16+swb], aac_cb_out_map[cb],
  114. lambda / band->threshold, INFINITY, NULL, NULL, 0);
  115. }
  116. cost_stay_here = path[swb][cb].cost + rd;
  117. cost_get_here = minrd + rd + run_bits + 4;
  118. if ( run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run]
  119. != run_value_bits[sce->ics.num_windows == 8][path[swb][cb].run+1])
  120. cost_stay_here += run_bits;
  121. if (cost_get_here < cost_stay_here) {
  122. path[swb+1][cb].prev_idx = mincb;
  123. path[swb+1][cb].cost = cost_get_here;
  124. path[swb+1][cb].run = 1;
  125. } else {
  126. path[swb+1][cb].prev_idx = cb;
  127. path[swb+1][cb].cost = cost_stay_here;
  128. path[swb+1][cb].run = path[swb][cb].run + 1;
  129. }
  130. if (path[swb+1][cb].cost < next_minrd) {
  131. next_minrd = path[swb+1][cb].cost;
  132. next_mincb = cb;
  133. }
  134. }
  135. }
  136. start += sce->ics.swb_sizes[swb];
  137. }
  138. //convert resulting path from backward-linked list
  139. stack_len = 0;
  140. idx = 0;
  141. for (cb = 1; cb < CB_TOT_ALL; cb++)
  142. if (path[max_sfb][cb].cost < path[max_sfb][idx].cost)
  143. idx = cb;
  144. ppos = max_sfb;
  145. while (ppos > 0) {
  146. av_assert1(idx >= 0);
  147. cb = idx;
  148. stackrun[stack_len] = path[ppos][cb].run;
  149. stackcb [stack_len] = cb;
  150. idx = path[ppos-path[ppos][cb].run+1][cb].prev_idx;
  151. ppos -= path[ppos][cb].run;
  152. stack_len++;
  153. }
  154. //perform actual band info encoding
  155. start = 0;
  156. for (i = stack_len - 1; i >= 0; i--) {
  157. cb = aac_cb_out_map[stackcb[i]];
  158. put_bits(&s->pb, 4, cb);
  159. count = stackrun[i];
  160. memset(sce->zeroes + win*16 + start, !cb, count);
  161. //XXX: memset when band_type is also uint8_t
  162. for (j = 0; j < count; j++) {
  163. sce->band_type[win*16 + start] = cb;
  164. start++;
  165. }
  166. while (count >= run_esc) {
  167. put_bits(&s->pb, run_bits, run_esc);
  168. count -= run_esc;
  169. }
  170. put_bits(&s->pb, run_bits, count);
  171. }
  172. }
  173. typedef struct TrellisPath {
  174. float cost;
  175. int prev;
  176. } TrellisPath;
  177. #define TRELLIS_STAGES 121
  178. #define TRELLIS_STATES (SCALE_MAX_DIFF+1)
  179. static void set_special_band_scalefactors(AACEncContext *s, SingleChannelElement *sce)
  180. {
  181. int w, g, start = 0;
  182. int minscaler_n = sce->sf_idx[0], minscaler_i = sce->sf_idx[0];
  183. int bands = 0;
  184. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  185. start = 0;
  186. for (g = 0; g < sce->ics.num_swb; g++) {
  187. if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
  188. sce->sf_idx[w*16+g] = av_clip(roundf(log2f(sce->is_ener[w*16+g])*2), -155, 100);
  189. minscaler_i = FFMIN(minscaler_i, sce->sf_idx[w*16+g]);
  190. bands++;
  191. } else if (sce->band_type[w*16+g] == NOISE_BT) {
  192. sce->sf_idx[w*16+g] = av_clip(3+ceilf(log2f(sce->pns_ener[w*16+g])*2), -100, 155);
  193. minscaler_n = FFMIN(minscaler_n, sce->sf_idx[w*16+g]);
  194. bands++;
  195. }
  196. start += sce->ics.swb_sizes[g];
  197. }
  198. }
  199. if (!bands)
  200. return;
  201. /* Clip the scalefactor indices */
  202. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  203. for (g = 0; g < sce->ics.num_swb; g++) {
  204. if (sce->band_type[w*16+g] == INTENSITY_BT || sce->band_type[w*16+g] == INTENSITY_BT2) {
  205. sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_i, minscaler_i + SCALE_MAX_DIFF);
  206. } else if (sce->band_type[w*16+g] == NOISE_BT) {
  207. sce->sf_idx[w*16+g] = av_clip(sce->sf_idx[w*16+g], minscaler_n, minscaler_n + SCALE_MAX_DIFF);
  208. }
  209. }
  210. }
  211. }
  212. static void search_for_quantizers_anmr(AVCodecContext *avctx, AACEncContext *s,
  213. SingleChannelElement *sce,
  214. const float lambda)
  215. {
  216. int q, w, w2, g, start = 0;
  217. int i, j;
  218. int idx;
  219. TrellisPath paths[TRELLIS_STAGES][TRELLIS_STATES];
  220. int bandaddr[TRELLIS_STAGES];
  221. int minq;
  222. float mincost;
  223. float q0f = FLT_MAX, q1f = 0.0f, qnrgf = 0.0f;
  224. int q0, q1, qcnt = 0;
  225. for (i = 0; i < 1024; i++) {
  226. float t = fabsf(sce->coeffs[i]);
  227. if (t > 0.0f) {
  228. q0f = FFMIN(q0f, t);
  229. q1f = FFMAX(q1f, t);
  230. qnrgf += t*t;
  231. qcnt++;
  232. }
  233. }
  234. if (!qcnt) {
  235. memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
  236. memset(sce->zeroes, 1, sizeof(sce->zeroes));
  237. return;
  238. }
  239. //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
  240. q0 = coef2minsf(q0f);
  241. //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
  242. q1 = coef2maxsf(q1f);
  243. if (q1 - q0 > 60) {
  244. int q0low = q0;
  245. int q1high = q1;
  246. //minimum scalefactor index is when maximum nonzero coefficient after quantizing is not clipped
  247. int qnrg = av_clip_uint8(log2f(sqrtf(qnrgf/qcnt))*4 - 31 + SCALE_ONE_POS - SCALE_DIV_512);
  248. q1 = qnrg + 30;
  249. q0 = qnrg - 30;
  250. if (q0 < q0low) {
  251. q1 += q0low - q0;
  252. q0 = q0low;
  253. } else if (q1 > q1high) {
  254. q0 -= q1 - q1high;
  255. q1 = q1high;
  256. }
  257. }
  258. for (i = 0; i < TRELLIS_STATES; i++) {
  259. paths[0][i].cost = 0.0f;
  260. paths[0][i].prev = -1;
  261. }
  262. for (j = 1; j < TRELLIS_STAGES; j++) {
  263. for (i = 0; i < TRELLIS_STATES; i++) {
  264. paths[j][i].cost = INFINITY;
  265. paths[j][i].prev = -2;
  266. }
  267. }
  268. idx = 1;
  269. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  270. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  271. start = w*128;
  272. for (g = 0; g < sce->ics.num_swb; g++) {
  273. const float *coefs = &sce->coeffs[start];
  274. float qmin, qmax;
  275. int nz = 0;
  276. bandaddr[idx] = w * 16 + g;
  277. qmin = INT_MAX;
  278. qmax = 0.0f;
  279. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  280. FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  281. if (band->energy <= band->threshold || band->threshold == 0.0f) {
  282. sce->zeroes[(w+w2)*16+g] = 1;
  283. continue;
  284. }
  285. sce->zeroes[(w+w2)*16+g] = 0;
  286. nz = 1;
  287. for (i = 0; i < sce->ics.swb_sizes[g]; i++) {
  288. float t = fabsf(coefs[w2*128+i]);
  289. if (t > 0.0f)
  290. qmin = FFMIN(qmin, t);
  291. qmax = FFMAX(qmax, t);
  292. }
  293. }
  294. if (nz) {
  295. int minscale, maxscale;
  296. float minrd = INFINITY;
  297. float maxval;
  298. //minimum scalefactor index is when minimum nonzero coefficient after quantizing is not clipped
  299. minscale = coef2minsf(qmin);
  300. //maximum scalefactor index is when maximum coefficient after quantizing is still not zero
  301. maxscale = coef2maxsf(qmax);
  302. minscale = av_clip(minscale - q0, 0, TRELLIS_STATES - 1);
  303. maxscale = av_clip(maxscale - q0, 0, TRELLIS_STATES);
  304. maxval = find_max_val(sce->ics.group_len[w], sce->ics.swb_sizes[g], s->scoefs+start);
  305. for (q = minscale; q < maxscale; q++) {
  306. float dist = 0;
  307. int cb = find_min_book(maxval, sce->sf_idx[w*16+g]);
  308. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  309. FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  310. dist += quantize_band_cost(s, coefs + w2*128, s->scoefs + start + w2*128, sce->ics.swb_sizes[g],
  311. q + q0, cb, lambda / band->threshold, INFINITY, NULL, NULL, 0);
  312. }
  313. minrd = FFMIN(minrd, dist);
  314. for (i = 0; i < q1 - q0; i++) {
  315. float cost;
  316. cost = paths[idx - 1][i].cost + dist
  317. + ff_aac_scalefactor_bits[q - i + SCALE_DIFF_ZERO];
  318. if (cost < paths[idx][q].cost) {
  319. paths[idx][q].cost = cost;
  320. paths[idx][q].prev = i;
  321. }
  322. }
  323. }
  324. } else {
  325. for (q = 0; q < q1 - q0; q++) {
  326. paths[idx][q].cost = paths[idx - 1][q].cost + 1;
  327. paths[idx][q].prev = q;
  328. }
  329. }
  330. sce->zeroes[w*16+g] = !nz;
  331. start += sce->ics.swb_sizes[g];
  332. idx++;
  333. }
  334. }
  335. idx--;
  336. mincost = paths[idx][0].cost;
  337. minq = 0;
  338. for (i = 1; i < TRELLIS_STATES; i++) {
  339. if (paths[idx][i].cost < mincost) {
  340. mincost = paths[idx][i].cost;
  341. minq = i;
  342. }
  343. }
  344. while (idx) {
  345. sce->sf_idx[bandaddr[idx]] = minq + q0;
  346. minq = paths[idx][minq].prev;
  347. idx--;
  348. }
  349. //set the same quantizers inside window groups
  350. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  351. for (g = 0; g < sce->ics.num_swb; g++)
  352. for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
  353. sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
  354. }
  355. static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,
  356. SingleChannelElement *sce,
  357. const float lambda)
  358. {
  359. int start = 0, i, w, w2, g;
  360. float uplim[128], maxq[128];
  361. int minq, maxsf;
  362. float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;
  363. int last = 0, lastband = 0, curband = 0;
  364. float avg_energy = 0.0;
  365. if (sce->ics.num_windows == 1) {
  366. start = 0;
  367. for (i = 0; i < 1024; i++) {
  368. if (i - start >= sce->ics.swb_sizes[curband]) {
  369. start += sce->ics.swb_sizes[curband];
  370. curband++;
  371. }
  372. if (sce->coeffs[i]) {
  373. avg_energy += sce->coeffs[i] * sce->coeffs[i];
  374. last = i;
  375. lastband = curband;
  376. }
  377. }
  378. } else {
  379. for (w = 0; w < 8; w++) {
  380. const float *coeffs = &sce->coeffs[w*128];
  381. curband = start = 0;
  382. for (i = 0; i < 128; i++) {
  383. if (i - start >= sce->ics.swb_sizes[curband]) {
  384. start += sce->ics.swb_sizes[curband];
  385. curband++;
  386. }
  387. if (coeffs[i]) {
  388. avg_energy += coeffs[i] * coeffs[i];
  389. last = FFMAX(last, i);
  390. lastband = FFMAX(lastband, curband);
  391. }
  392. }
  393. }
  394. }
  395. last++;
  396. avg_energy /= last;
  397. if (avg_energy == 0.0f) {
  398. for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)
  399. sce->sf_idx[i] = SCALE_ONE_POS;
  400. return;
  401. }
  402. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  403. start = w*128;
  404. for (g = 0; g < sce->ics.num_swb; g++) {
  405. float *coefs = &sce->coeffs[start];
  406. const int size = sce->ics.swb_sizes[g];
  407. int start2 = start, end2 = start + size, peakpos = start;
  408. float maxval = -1, thr = 0.0f, t;
  409. maxq[w*16+g] = 0.0f;
  410. if (g > lastband) {
  411. maxq[w*16+g] = 0.0f;
  412. start += size;
  413. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)
  414. memset(coefs + w2*128, 0, sizeof(coefs[0])*size);
  415. continue;
  416. }
  417. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  418. for (i = 0; i < size; i++) {
  419. float t = coefs[w2*128+i]*coefs[w2*128+i];
  420. maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));
  421. thr += t;
  422. if (sce->ics.num_windows == 1 && maxval < t) {
  423. maxval = t;
  424. peakpos = start+i;
  425. }
  426. }
  427. }
  428. if (sce->ics.num_windows == 1) {
  429. start2 = FFMAX(peakpos - 2, start2);
  430. end2 = FFMIN(peakpos + 3, end2);
  431. } else {
  432. start2 -= start;
  433. end2 -= start;
  434. }
  435. start += size;
  436. thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);
  437. t = 1.0 - (1.0 * start2 / last);
  438. uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);
  439. }
  440. }
  441. memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
  442. abs_pow34_v(s->scoefs, sce->coeffs, 1024);
  443. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  444. start = w*128;
  445. for (g = 0; g < sce->ics.num_swb; g++) {
  446. const float *coefs = &sce->coeffs[start];
  447. const float *scaled = &s->scoefs[start];
  448. const int size = sce->ics.swb_sizes[g];
  449. int scf, prev_scf, step;
  450. int min_scf = -1, max_scf = 256;
  451. float curdiff;
  452. if (maxq[w*16+g] < 21.544) {
  453. sce->zeroes[w*16+g] = 1;
  454. start += size;
  455. continue;
  456. }
  457. sce->zeroes[w*16+g] = 0;
  458. scf = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);
  459. for (;;) {
  460. float dist = 0.0f;
  461. int quant_max;
  462. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  463. int b;
  464. dist += quantize_band_cost(s, coefs + w2*128,
  465. scaled + w2*128,
  466. sce->ics.swb_sizes[g],
  467. scf,
  468. ESC_BT,
  469. lambda,
  470. INFINITY,
  471. &b, NULL,
  472. 0);
  473. dist -= b;
  474. }
  475. dist *= 1.0f / 512.0f / lambda;
  476. quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);
  477. if (quant_max >= 8191) { // too much, return to the previous quantizer
  478. sce->sf_idx[w*16+g] = prev_scf;
  479. break;
  480. }
  481. prev_scf = scf;
  482. curdiff = fabsf(dist - uplim[w*16+g]);
  483. if (curdiff <= 1.0f)
  484. step = 0;
  485. else
  486. step = log2f(curdiff);
  487. if (dist > uplim[w*16+g])
  488. step = -step;
  489. scf += step;
  490. scf = av_clip_uint8(scf);
  491. step = scf - prev_scf;
  492. if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {
  493. sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);
  494. break;
  495. }
  496. if (step > 0)
  497. min_scf = prev_scf;
  498. else
  499. max_scf = prev_scf;
  500. }
  501. start += size;
  502. }
  503. }
  504. minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;
  505. for (i = 1; i < 128; i++) {
  506. if (!sce->sf_idx[i])
  507. sce->sf_idx[i] = sce->sf_idx[i-1];
  508. else
  509. minq = FFMIN(minq, sce->sf_idx[i]);
  510. }
  511. if (minq == INT_MAX)
  512. minq = 0;
  513. minq = FFMIN(minq, SCALE_MAX_POS);
  514. maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);
  515. for (i = 126; i >= 0; i--) {
  516. if (!sce->sf_idx[i])
  517. sce->sf_idx[i] = sce->sf_idx[i+1];
  518. sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);
  519. }
  520. }
  521. static void search_for_quantizers_fast(AVCodecContext *avctx, AACEncContext *s,
  522. SingleChannelElement *sce,
  523. const float lambda)
  524. {
  525. int i, w, w2, g;
  526. int minq = 255;
  527. memset(sce->sf_idx, 0, sizeof(sce->sf_idx));
  528. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  529. for (g = 0; g < sce->ics.num_swb; g++) {
  530. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  531. FFPsyBand *band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  532. if (band->energy <= band->threshold) {
  533. sce->sf_idx[(w+w2)*16+g] = 218;
  534. sce->zeroes[(w+w2)*16+g] = 1;
  535. } else {
  536. sce->sf_idx[(w+w2)*16+g] = av_clip(SCALE_ONE_POS - SCALE_DIV_512 + log2f(band->threshold), 80, 218);
  537. sce->zeroes[(w+w2)*16+g] = 0;
  538. }
  539. minq = FFMIN(minq, sce->sf_idx[(w+w2)*16+g]);
  540. }
  541. }
  542. }
  543. for (i = 0; i < 128; i++) {
  544. sce->sf_idx[i] = 140;
  545. //av_clip(sce->sf_idx[i], minq, minq + SCALE_MAX_DIFF - 1);
  546. }
  547. //set the same quantizers inside window groups
  548. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  549. for (g = 0; g < sce->ics.num_swb; g++)
  550. for (w2 = 1; w2 < sce->ics.group_len[w]; w2++)
  551. sce->sf_idx[(w+w2)*16+g] = sce->sf_idx[w*16+g];
  552. }
  553. static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)
  554. {
  555. FFPsyBand *band;
  556. int w, g, w2, i;
  557. int wlen = 1024 / sce->ics.num_windows;
  558. int bandwidth, cutoff;
  559. float *PNS = &s->scoefs[0*128], *PNS34 = &s->scoefs[1*128];
  560. float *NOR34 = &s->scoefs[3*128];
  561. const float lambda = s->lambda;
  562. const float freq_mult = avctx->sample_rate*0.5f/wlen;
  563. const float thr_mult = NOISE_LAMBDA_REPLACE*(100.0f/lambda);
  564. const float spread_threshold = FFMIN(0.75f, NOISE_SPREAD_THRESHOLD*FFMAX(0.5f, lambda/100.f));
  565. const float dist_bias = av_clipf(4.f * 120 / lambda, 0.25f, 4.0f);
  566. const float pns_transient_energy_r = FFMIN(0.7f, lambda / 140.f);
  567. int refbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
  568. / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
  569. * (lambda / 120.f);
  570. /** Keep this in sync with twoloop's cutoff selection */
  571. float rate_bandwidth_multiplier = 1.5f;
  572. int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
  573. ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
  574. : (avctx->bit_rate / avctx->channels);
  575. frame_bit_rate *= 1.15f;
  576. if (avctx->cutoff > 0) {
  577. bandwidth = avctx->cutoff;
  578. } else {
  579. bandwidth = FFMAX(3000, AAC_CUTOFF_FROM_BITRATE(frame_bit_rate, 1, avctx->sample_rate));
  580. }
  581. cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
  582. memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));
  583. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  584. int wstart = w*128;
  585. for (g = 0; g < sce->ics.num_swb; g++) {
  586. int noise_sfi;
  587. float dist1 = 0.0f, dist2 = 0.0f, noise_amp;
  588. float pns_energy = 0.0f, pns_tgt_energy, energy_ratio, dist_thresh;
  589. float sfb_energy = 0.0f, threshold = 0.0f, spread = 2.0f;
  590. float min_energy = -1.0f, max_energy = 0.0f;
  591. const int start = wstart+sce->ics.swb_offset[g];
  592. const float freq = (start-wstart)*freq_mult;
  593. const float freq_boost = FFMAX(0.88f*freq/NOISE_LOW_LIMIT, 1.0f);
  594. if (freq < NOISE_LOW_LIMIT || (start-wstart) >= cutoff)
  595. continue;
  596. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  597. band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  598. sfb_energy += band->energy;
  599. spread = FFMIN(spread, band->spread);
  600. threshold += band->threshold;
  601. if (!w2) {
  602. min_energy = max_energy = band->energy;
  603. } else {
  604. min_energy = FFMIN(min_energy, band->energy);
  605. max_energy = FFMAX(max_energy, band->energy);
  606. }
  607. }
  608. /* Ramps down at ~8000Hz and loosens the dist threshold */
  609. dist_thresh = av_clipf(2.5f*NOISE_LOW_LIMIT/freq, 0.5f, 2.5f) * dist_bias;
  610. /* PNS is acceptable when all of these are true:
  611. * 1. high spread energy (noise-like band)
  612. * 2. near-threshold energy (high PE means the random nature of PNS content will be noticed)
  613. * 3. on short window groups, all windows have similar energy (variations in energy would be destroyed by PNS)
  614. *
  615. * At this stage, point 2 is relaxed for zeroed bands near the noise threshold (hole avoidance is more important)
  616. */
  617. if (((sce->zeroes[w*16+g] || !sce->band_alt[w*16+g]) && sfb_energy < threshold*sqrtf(1.5f/freq_boost)) || spread < spread_threshold ||
  618. (!sce->zeroes[w*16+g] && sce->band_alt[w*16+g] && sfb_energy > threshold*thr_mult*freq_boost) ||
  619. min_energy < pns_transient_energy_r * max_energy ) {
  620. sce->pns_ener[w*16+g] = sfb_energy;
  621. continue;
  622. }
  623. pns_tgt_energy = sfb_energy*FFMIN(1.0f, spread*spread);
  624. noise_sfi = av_clip(roundf(log2f(pns_tgt_energy)*2), -100, 155); /* Quantize */
  625. noise_amp = -ff_aac_pow2sf_tab[noise_sfi + POW_SF2_ZERO]; /* Dequantize */
  626. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  627. float band_energy, scale, pns_senergy;
  628. const int start_c = (w+w2)*128+sce->ics.swb_offset[g];
  629. band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  630. for (i = 0; i < sce->ics.swb_sizes[g]; i++)
  631. PNS[i] = s->random_state = lcg_random(s->random_state);
  632. band_energy = s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);
  633. scale = noise_amp/sqrtf(band_energy);
  634. s->fdsp->vector_fmul_scalar(PNS, PNS, scale, sce->ics.swb_sizes[g]);
  635. pns_senergy = s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);
  636. pns_energy += pns_senergy;
  637. abs_pow34_v(NOR34, &sce->coeffs[start_c], sce->ics.swb_sizes[g]);
  638. abs_pow34_v(PNS34, PNS, sce->ics.swb_sizes[g]);
  639. dist1 += quantize_band_cost(s, &sce->coeffs[start_c],
  640. NOR34,
  641. sce->ics.swb_sizes[g],
  642. sce->sf_idx[(w+w2)*16+g],
  643. sce->band_alt[(w+w2)*16+g],
  644. lambda/band->threshold, INFINITY, NULL, NULL, 0);
  645. /* Estimate rd on average as 5 bits for SF, 4 for the CB, plus spread energy * lambda/thr */
  646. dist2 += band->energy/(band->spread*band->spread)*lambda*dist_thresh/band->threshold;
  647. }
  648. if (g && sce->sf_idx[(w+w2)*16+g-1] == NOISE_BT) {
  649. dist2 += 5;
  650. } else {
  651. dist2 += 9;
  652. }
  653. energy_ratio = pns_tgt_energy/pns_energy; /* Compensates for quantization error */
  654. sce->pns_ener[w*16+g] = energy_ratio*pns_tgt_energy;
  655. if (sce->zeroes[w*16+g] || !sce->band_alt[w*16+g] || (energy_ratio > 0.85f && energy_ratio < 1.25f && dist2 < dist1)) {
  656. sce->band_type[w*16+g] = NOISE_BT;
  657. sce->zeroes[w*16+g] = 0;
  658. }
  659. }
  660. }
  661. }
  662. static void mark_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)
  663. {
  664. FFPsyBand *band;
  665. int w, g, w2;
  666. int wlen = 1024 / sce->ics.num_windows;
  667. int bandwidth, cutoff;
  668. const float lambda = s->lambda;
  669. const float freq_mult = avctx->sample_rate*0.5f/wlen;
  670. const float spread_threshold = FFMIN(0.75f, NOISE_SPREAD_THRESHOLD*FFMAX(0.5f, lambda/100.f));
  671. const float pns_transient_energy_r = FFMIN(0.7f, lambda / 140.f);
  672. int refbits = avctx->bit_rate * 1024.0 / avctx->sample_rate
  673. / ((avctx->flags & CODEC_FLAG_QSCALE) ? 2.0f : avctx->channels)
  674. * (lambda / 120.f);
  675. /** Keep this in sync with twoloop's cutoff selection */
  676. float rate_bandwidth_multiplier = 1.5f;
  677. int frame_bit_rate = (avctx->flags & CODEC_FLAG_QSCALE)
  678. ? (refbits * rate_bandwidth_multiplier * avctx->sample_rate / 1024)
  679. : (avctx->bit_rate / avctx->channels);
  680. frame_bit_rate *= 1.15f;
  681. if (avctx->cutoff > 0) {
  682. bandwidth = avctx->cutoff;
  683. } else {
  684. bandwidth = FFMAX(3000, AAC_CUTOFF_FROM_BITRATE(frame_bit_rate, 1, avctx->sample_rate));
  685. }
  686. cutoff = bandwidth * 2 * wlen / avctx->sample_rate;
  687. memcpy(sce->band_alt, sce->band_type, sizeof(sce->band_type));
  688. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  689. for (g = 0; g < sce->ics.num_swb; g++) {
  690. float sfb_energy = 0.0f, threshold = 0.0f, spread = 2.0f;
  691. float min_energy = -1.0f, max_energy = 0.0f;
  692. const int start = sce->ics.swb_offset[g];
  693. const float freq = start*freq_mult;
  694. const float freq_boost = FFMAX(0.88f*freq/NOISE_LOW_LIMIT, 1.0f);
  695. if (freq < NOISE_LOW_LIMIT || start >= cutoff) {
  696. sce->can_pns[w*16+g] = 0;
  697. continue;
  698. }
  699. for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {
  700. band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];
  701. sfb_energy += band->energy;
  702. spread = FFMIN(spread, band->spread);
  703. threshold += band->threshold;
  704. if (!w2) {
  705. min_energy = max_energy = band->energy;
  706. } else {
  707. min_energy = FFMIN(min_energy, band->energy);
  708. max_energy = FFMAX(max_energy, band->energy);
  709. }
  710. }
  711. /* PNS is acceptable when all of these are true:
  712. * 1. high spread energy (noise-like band)
  713. * 2. near-threshold energy (high PE means the random nature of PNS content will be noticed)
  714. * 3. on short window groups, all windows have similar energy (variations in energy would be destroyed by PNS)
  715. */
  716. sce->pns_ener[w*16+g] = sfb_energy;
  717. if (sfb_energy < threshold*sqrtf(1.5f/freq_boost) || spread < spread_threshold || min_energy < pns_transient_energy_r * max_energy) {
  718. sce->can_pns[w*16+g] = 0;
  719. } else {
  720. sce->can_pns[w*16+g] = 1;
  721. }
  722. }
  723. }
  724. }
  725. static void search_for_ms(AACEncContext *s, ChannelElement *cpe)
  726. {
  727. int start = 0, i, w, w2, g, sid_sf_boost;
  728. float M[128], S[128];
  729. float *L34 = s->scoefs, *R34 = s->scoefs + 128, *M34 = s->scoefs + 128*2, *S34 = s->scoefs + 128*3;
  730. const float lambda = s->lambda;
  731. const float mslambda = FFMIN(1.0f, lambda / 120.f);
  732. SingleChannelElement *sce0 = &cpe->ch[0];
  733. SingleChannelElement *sce1 = &cpe->ch[1];
  734. if (!cpe->common_window)
  735. return;
  736. for (w = 0; w < sce0->ics.num_windows; w += sce0->ics.group_len[w]) {
  737. int min_sf_idx_mid = SCALE_MAX_POS;
  738. int min_sf_idx_side = SCALE_MAX_POS;
  739. for (g = 0; g < sce0->ics.num_swb; g++) {
  740. if (!sce0->zeroes[w*16+g] && sce0->band_type[w*16+g] < RESERVED_BT)
  741. min_sf_idx_mid = FFMIN(min_sf_idx_mid, sce0->sf_idx[w*16+g]);
  742. if (!sce1->zeroes[w*16+g] && sce1->band_type[w*16+g] < RESERVED_BT)
  743. min_sf_idx_side = FFMIN(min_sf_idx_side, sce1->sf_idx[w*16+g]);
  744. }
  745. start = 0;
  746. for (g = 0; g < sce0->ics.num_swb; g++) {
  747. float bmax = bval2bmax(g * 17.0f / sce0->ics.num_swb) / 0.0045f;
  748. cpe->ms_mask[w*16+g] = 0;
  749. if (!cpe->ch[0].zeroes[w*16+g] && !cpe->ch[1].zeroes[w*16+g]) {
  750. float Mmax = 0.0f, Smax = 0.0f;
  751. /* Must compute mid/side SF and book for the whole window group */
  752. for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
  753. for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
  754. M[i] = (sce0->coeffs[start+(w+w2)*128+i]
  755. + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;
  756. S[i] = M[i]
  757. - sce1->coeffs[start+(w+w2)*128+i];
  758. }
  759. abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
  760. abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
  761. for (i = 0; i < sce0->ics.swb_sizes[g]; i++ ) {
  762. Mmax = FFMAX(Mmax, M34[i]);
  763. Smax = FFMAX(Smax, S34[i]);
  764. }
  765. }
  766. for (sid_sf_boost = 0; sid_sf_boost < 4; sid_sf_boost++) {
  767. float dist1 = 0.0f, dist2 = 0.0f;
  768. int B0 = 0, B1 = 0;
  769. int minidx;
  770. int mididx, sididx;
  771. int midcb, sidcb;
  772. minidx = FFMIN(sce0->sf_idx[w*16+g], sce1->sf_idx[w*16+g]);
  773. mididx = av_clip(minidx, min_sf_idx_mid, min_sf_idx_mid + SCALE_MAX_DIFF);
  774. sididx = av_clip(minidx - sid_sf_boost * 3, min_sf_idx_side, min_sf_idx_side + SCALE_MAX_DIFF);
  775. midcb = find_min_book(Mmax, mididx);
  776. sidcb = find_min_book(Smax, sididx);
  777. if ((mididx > minidx) || (sididx > minidx)) {
  778. /* scalefactor range violation, bad stuff, will decrease quality unacceptably */
  779. continue;
  780. }
  781. /* No CB can be zero */
  782. midcb = FFMAX(1,midcb);
  783. sidcb = FFMAX(1,sidcb);
  784. for (w2 = 0; w2 < sce0->ics.group_len[w]; w2++) {
  785. FFPsyBand *band0 = &s->psy.ch[s->cur_channel+0].psy_bands[(w+w2)*16+g];
  786. FFPsyBand *band1 = &s->psy.ch[s->cur_channel+1].psy_bands[(w+w2)*16+g];
  787. float minthr = FFMIN(band0->threshold, band1->threshold);
  788. int b1,b2,b3,b4;
  789. for (i = 0; i < sce0->ics.swb_sizes[g]; i++) {
  790. M[i] = (sce0->coeffs[start+(w+w2)*128+i]
  791. + sce1->coeffs[start+(w+w2)*128+i]) * 0.5;
  792. S[i] = M[i]
  793. - sce1->coeffs[start+(w+w2)*128+i];
  794. }
  795. abs_pow34_v(L34, sce0->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
  796. abs_pow34_v(R34, sce1->coeffs+start+(w+w2)*128, sce0->ics.swb_sizes[g]);
  797. abs_pow34_v(M34, M, sce0->ics.swb_sizes[g]);
  798. abs_pow34_v(S34, S, sce0->ics.swb_sizes[g]);
  799. dist1 += quantize_band_cost(s, &sce0->coeffs[start + (w+w2)*128],
  800. L34,
  801. sce0->ics.swb_sizes[g],
  802. sce0->sf_idx[(w+w2)*16+g],
  803. sce0->band_type[(w+w2)*16+g],
  804. lambda / band0->threshold, INFINITY, &b1, NULL, 0);
  805. dist1 += quantize_band_cost(s, &sce1->coeffs[start + (w+w2)*128],
  806. R34,
  807. sce1->ics.swb_sizes[g],
  808. sce1->sf_idx[(w+w2)*16+g],
  809. sce1->band_type[(w+w2)*16+g],
  810. lambda / band1->threshold, INFINITY, &b2, NULL, 0);
  811. dist2 += quantize_band_cost(s, M,
  812. M34,
  813. sce0->ics.swb_sizes[g],
  814. sce0->sf_idx[(w+w2)*16+g],
  815. sce0->band_type[(w+w2)*16+g],
  816. lambda / minthr, INFINITY, &b3, NULL, 0);
  817. dist2 += quantize_band_cost(s, S,
  818. S34,
  819. sce1->ics.swb_sizes[g],
  820. sce1->sf_idx[(w+w2)*16+g],
  821. sce1->band_type[(w+w2)*16+g],
  822. mslambda / (minthr * bmax), INFINITY, &b4, NULL, 0);
  823. B0 += b1+b2;
  824. B1 += b3+b4;
  825. dist1 -= B0;
  826. dist2 -= B1;
  827. }
  828. cpe->ms_mask[w*16+g] = dist2 <= dist1 && B1 < B0;
  829. if (cpe->ms_mask[w*16+g]) {
  830. /* Setting the M/S mask is useful with I/S or PNS, but only the flag */
  831. if (!cpe->is_mask[w*16+g] && sce0->band_type[w*16+g] != NOISE_BT && sce1->band_type[w*16+g] != NOISE_BT) {
  832. sce0->sf_idx[w*16+g] = mididx;
  833. sce1->sf_idx[w*16+g] = sididx;
  834. sce0->band_type[w*16+g] = midcb;
  835. sce1->band_type[w*16+g] = sidcb;
  836. }
  837. break;
  838. } else if (B1 > B0) {
  839. /* More boost won't fix this */
  840. break;
  841. }
  842. }
  843. }
  844. start += sce0->ics.swb_sizes[g];
  845. }
  846. }
  847. }
  848. AACCoefficientsEncoder ff_aac_coders[AAC_CODER_NB] = {
  849. [AAC_CODER_FAAC] = {
  850. search_for_quantizers_faac,
  851. encode_window_bands_info,
  852. quantize_and_encode_band,
  853. ff_aac_encode_tns_info,
  854. ff_aac_encode_ltp_info,
  855. ff_aac_encode_main_pred,
  856. ff_aac_adjust_common_pred,
  857. ff_aac_adjust_common_ltp,
  858. ff_aac_apply_main_pred,
  859. ff_aac_apply_tns,
  860. ff_aac_update_ltp,
  861. ff_aac_ltp_insert_new_frame,
  862. set_special_band_scalefactors,
  863. search_for_pns,
  864. mark_pns,
  865. ff_aac_search_for_tns,
  866. ff_aac_search_for_ltp,
  867. search_for_ms,
  868. ff_aac_search_for_is,
  869. ff_aac_search_for_pred,
  870. },
  871. [AAC_CODER_ANMR] = {
  872. search_for_quantizers_anmr,
  873. encode_window_bands_info,
  874. quantize_and_encode_band,
  875. ff_aac_encode_tns_info,
  876. ff_aac_encode_ltp_info,
  877. ff_aac_encode_main_pred,
  878. ff_aac_adjust_common_pred,
  879. ff_aac_adjust_common_ltp,
  880. ff_aac_apply_main_pred,
  881. ff_aac_apply_tns,
  882. ff_aac_update_ltp,
  883. ff_aac_ltp_insert_new_frame,
  884. set_special_band_scalefactors,
  885. search_for_pns,
  886. mark_pns,
  887. ff_aac_search_for_tns,
  888. ff_aac_search_for_ltp,
  889. search_for_ms,
  890. ff_aac_search_for_is,
  891. ff_aac_search_for_pred,
  892. },
  893. [AAC_CODER_TWOLOOP] = {
  894. search_for_quantizers_twoloop,
  895. codebook_trellis_rate,
  896. quantize_and_encode_band,
  897. ff_aac_encode_tns_info,
  898. ff_aac_encode_ltp_info,
  899. ff_aac_encode_main_pred,
  900. ff_aac_adjust_common_pred,
  901. ff_aac_adjust_common_ltp,
  902. ff_aac_apply_main_pred,
  903. ff_aac_apply_tns,
  904. ff_aac_update_ltp,
  905. ff_aac_ltp_insert_new_frame,
  906. set_special_band_scalefactors,
  907. search_for_pns,
  908. mark_pns,
  909. ff_aac_search_for_tns,
  910. ff_aac_search_for_ltp,
  911. search_for_ms,
  912. ff_aac_search_for_is,
  913. ff_aac_search_for_pred,
  914. },
  915. [AAC_CODER_FAST] = {
  916. search_for_quantizers_fast,
  917. encode_window_bands_info,
  918. quantize_and_encode_band,
  919. ff_aac_encode_tns_info,
  920. ff_aac_encode_ltp_info,
  921. ff_aac_encode_main_pred,
  922. ff_aac_adjust_common_pred,
  923. ff_aac_adjust_common_ltp,
  924. ff_aac_apply_main_pred,
  925. ff_aac_apply_tns,
  926. ff_aac_update_ltp,
  927. ff_aac_ltp_insert_new_frame,
  928. set_special_band_scalefactors,
  929. search_for_pns,
  930. mark_pns,
  931. ff_aac_search_for_tns,
  932. ff_aac_search_for_ltp,
  933. search_for_ms,
  934. ff_aac_search_for_is,
  935. ff_aac_search_for_pred,
  936. },
  937. };