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.

1020 lines
42KB

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