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.

1023 lines
37KB

  1. /*
  2. * AAC encoder
  3. * Copyright (C) 2008 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 encoder
  24. */
  25. /***********************************
  26. * TODOs:
  27. * add sane pulse detection
  28. ***********************************/
  29. #include "libavutil/float_dsp.h"
  30. #include "libavutil/opt.h"
  31. #include "avcodec.h"
  32. #include "put_bits.h"
  33. #include "internal.h"
  34. #include "mpeg4audio.h"
  35. #include "kbdwin.h"
  36. #include "sinewin.h"
  37. #include "aac.h"
  38. #include "aactab.h"
  39. #include "aacenc.h"
  40. #include "aacenctab.h"
  41. #include "aacenc_utils.h"
  42. #include "psymodel.h"
  43. struct AACProfileOptions {
  44. int profile;
  45. struct AACEncOptions opts;
  46. };
  47. /**
  48. * List of currently supported profiles, anything not listed isn't supported.
  49. */
  50. static const struct AACProfileOptions aacenc_profiles[] = {
  51. {FF_PROFILE_AAC_MAIN,
  52. { /* Main profile, all advanced encoding abilities enabled */
  53. .mid_side = 0,
  54. .pns = 1,
  55. .tns = 0,
  56. .pred = OPT_REQUIRED,
  57. .intensity_stereo = 1,
  58. },
  59. },
  60. {FF_PROFILE_AAC_LOW,
  61. { /* Default profile, these are the settings that get set by default */
  62. .mid_side = 0,
  63. .pns = 1,
  64. .tns = 0,
  65. .pred = OPT_NEEDS_MAIN,
  66. .intensity_stereo = 1,
  67. },
  68. },
  69. {FF_PROFILE_MPEG2_AAC_LOW,
  70. { /* Strict MPEG 2 Part 7 compliance profile */
  71. .mid_side = 0,
  72. .pns = OPT_BANNED,
  73. .tns = 0,
  74. .pred = OPT_BANNED,
  75. .intensity_stereo = 1,
  76. },
  77. },
  78. };
  79. /**
  80. * Make AAC audio config object.
  81. * @see 1.6.2.1 "Syntax - AudioSpecificConfig"
  82. */
  83. static void put_audio_specific_config(AVCodecContext *avctx)
  84. {
  85. PutBitContext pb;
  86. AACEncContext *s = avctx->priv_data;
  87. int channels = s->channels - (s->channels == 8 ? 1 : 0);
  88. init_put_bits(&pb, avctx->extradata, avctx->extradata_size);
  89. put_bits(&pb, 5, s->profile+1); //profile
  90. put_bits(&pb, 4, s->samplerate_index); //sample rate index
  91. put_bits(&pb, 4, channels);
  92. //GASpecificConfig
  93. put_bits(&pb, 1, 0); //frame length - 1024 samples
  94. put_bits(&pb, 1, 0); //does not depend on core coder
  95. put_bits(&pb, 1, 0); //is not extension
  96. //Explicitly Mark SBR absent
  97. put_bits(&pb, 11, 0x2b7); //sync extension
  98. put_bits(&pb, 5, AOT_SBR);
  99. put_bits(&pb, 1, 0);
  100. flush_put_bits(&pb);
  101. }
  102. void ff_quantize_band_cost_cache_init(struct AACEncContext *s)
  103. {
  104. int sf, g;
  105. for (sf = 0; sf < 256; sf++) {
  106. for (g = 0; g < 128; g++) {
  107. s->quantize_band_cost_cache[sf][g].bits = -1;
  108. }
  109. }
  110. }
  111. #define WINDOW_FUNC(type) \
  112. static void apply_ ##type ##_window(AVFloatDSPContext *fdsp, \
  113. SingleChannelElement *sce, \
  114. const float *audio)
  115. WINDOW_FUNC(only_long)
  116. {
  117. const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  118. const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  119. float *out = sce->ret_buf;
  120. fdsp->vector_fmul (out, audio, lwindow, 1024);
  121. fdsp->vector_fmul_reverse(out + 1024, audio + 1024, pwindow, 1024);
  122. }
  123. WINDOW_FUNC(long_start)
  124. {
  125. const float *lwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  126. const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  127. float *out = sce->ret_buf;
  128. fdsp->vector_fmul(out, audio, lwindow, 1024);
  129. memcpy(out + 1024, audio + 1024, sizeof(out[0]) * 448);
  130. fdsp->vector_fmul_reverse(out + 1024 + 448, audio + 1024 + 448, swindow, 128);
  131. memset(out + 1024 + 576, 0, sizeof(out[0]) * 448);
  132. }
  133. WINDOW_FUNC(long_stop)
  134. {
  135. const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  136. const float *swindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  137. float *out = sce->ret_buf;
  138. memset(out, 0, sizeof(out[0]) * 448);
  139. fdsp->vector_fmul(out + 448, audio + 448, swindow, 128);
  140. memcpy(out + 576, audio + 576, sizeof(out[0]) * 448);
  141. fdsp->vector_fmul_reverse(out + 1024, audio + 1024, lwindow, 1024);
  142. }
  143. WINDOW_FUNC(eight_short)
  144. {
  145. const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  146. const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  147. const float *in = audio + 448;
  148. float *out = sce->ret_buf;
  149. int w;
  150. for (w = 0; w < 8; w++) {
  151. fdsp->vector_fmul (out, in, w ? pwindow : swindow, 128);
  152. out += 128;
  153. in += 128;
  154. fdsp->vector_fmul_reverse(out, in, swindow, 128);
  155. out += 128;
  156. }
  157. }
  158. static void (*const apply_window[4])(AVFloatDSPContext *fdsp,
  159. SingleChannelElement *sce,
  160. const float *audio) = {
  161. [ONLY_LONG_SEQUENCE] = apply_only_long_window,
  162. [LONG_START_SEQUENCE] = apply_long_start_window,
  163. [EIGHT_SHORT_SEQUENCE] = apply_eight_short_window,
  164. [LONG_STOP_SEQUENCE] = apply_long_stop_window
  165. };
  166. static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,
  167. float *audio)
  168. {
  169. int i;
  170. float *output = sce->ret_buf;
  171. apply_window[sce->ics.window_sequence[0]](s->fdsp, sce, audio);
  172. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE)
  173. s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);
  174. else
  175. for (i = 0; i < 1024; i += 128)
  176. s->mdct128.mdct_calc(&s->mdct128, &sce->coeffs[i], output + i*2);
  177. memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);
  178. memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs));
  179. }
  180. /**
  181. * Encode ics_info element.
  182. * @see Table 4.6 (syntax of ics_info)
  183. */
  184. static void put_ics_info(AACEncContext *s, IndividualChannelStream *info)
  185. {
  186. int w;
  187. put_bits(&s->pb, 1, 0); // ics_reserved bit
  188. put_bits(&s->pb, 2, info->window_sequence[0]);
  189. put_bits(&s->pb, 1, info->use_kb_window[0]);
  190. if (info->window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  191. put_bits(&s->pb, 6, info->max_sfb);
  192. put_bits(&s->pb, 1, !!info->predictor_present);
  193. } else {
  194. put_bits(&s->pb, 4, info->max_sfb);
  195. for (w = 1; w < 8; w++)
  196. put_bits(&s->pb, 1, !info->group_len[w]);
  197. }
  198. }
  199. /**
  200. * Encode MS data.
  201. * @see 4.6.8.1 "Joint Coding - M/S Stereo"
  202. */
  203. static void encode_ms_info(PutBitContext *pb, ChannelElement *cpe)
  204. {
  205. int i, w;
  206. put_bits(pb, 2, cpe->ms_mode);
  207. if (cpe->ms_mode == 1)
  208. for (w = 0; w < cpe->ch[0].ics.num_windows; w += cpe->ch[0].ics.group_len[w])
  209. for (i = 0; i < cpe->ch[0].ics.max_sfb; i++)
  210. put_bits(pb, 1, cpe->ms_mask[w*16 + i]);
  211. }
  212. /**
  213. * Produce integer coefficients from scalefactors provided by the model.
  214. */
  215. static void adjust_frame_information(ChannelElement *cpe, int chans)
  216. {
  217. int i, w, w2, g, ch;
  218. int maxsfb, cmaxsfb;
  219. for (ch = 0; ch < chans; ch++) {
  220. IndividualChannelStream *ics = &cpe->ch[ch].ics;
  221. maxsfb = 0;
  222. cpe->ch[ch].pulse.num_pulse = 0;
  223. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  224. for (w2 = 0; w2 < ics->group_len[w]; w2++) {
  225. for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--)
  226. ;
  227. maxsfb = FFMAX(maxsfb, cmaxsfb);
  228. }
  229. }
  230. ics->max_sfb = maxsfb;
  231. //adjust zero bands for window groups
  232. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  233. for (g = 0; g < ics->max_sfb; g++) {
  234. i = 1;
  235. for (w2 = w; w2 < w + ics->group_len[w]; w2++) {
  236. if (!cpe->ch[ch].zeroes[w2*16 + g]) {
  237. i = 0;
  238. break;
  239. }
  240. }
  241. cpe->ch[ch].zeroes[w*16 + g] = i;
  242. }
  243. }
  244. }
  245. if (chans > 1 && cpe->common_window) {
  246. IndividualChannelStream *ics0 = &cpe->ch[0].ics;
  247. IndividualChannelStream *ics1 = &cpe->ch[1].ics;
  248. int msc = 0;
  249. ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);
  250. ics1->max_sfb = ics0->max_sfb;
  251. for (w = 0; w < ics0->num_windows*16; w += 16)
  252. for (i = 0; i < ics0->max_sfb; i++)
  253. if (cpe->ms_mask[w+i])
  254. msc++;
  255. if (msc == 0 || ics0->max_sfb == 0)
  256. cpe->ms_mode = 0;
  257. else
  258. cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;
  259. }
  260. }
  261. static void apply_intensity_stereo(ChannelElement *cpe)
  262. {
  263. int w, w2, g, i;
  264. IndividualChannelStream *ics = &cpe->ch[0].ics;
  265. if (!cpe->common_window)
  266. return;
  267. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  268. for (w2 = 0; w2 < ics->group_len[w]; w2++) {
  269. int start = (w+w2) * 128;
  270. for (g = 0; g < ics->num_swb; g++) {
  271. int p = -1 + 2 * (cpe->ch[1].band_type[w*16+g] - 14);
  272. float scale = cpe->ch[0].is_ener[w*16+g];
  273. if (!cpe->is_mask[w*16 + g]) {
  274. start += ics->swb_sizes[g];
  275. continue;
  276. }
  277. if (cpe->ms_mask[w*16 + g])
  278. p *= -1;
  279. for (i = 0; i < ics->swb_sizes[g]; i++) {
  280. float sum = (cpe->ch[0].coeffs[start+i] + p*cpe->ch[1].coeffs[start+i])*scale;
  281. cpe->ch[0].coeffs[start+i] = sum;
  282. cpe->ch[1].coeffs[start+i] = 0.0f;
  283. }
  284. start += ics->swb_sizes[g];
  285. }
  286. }
  287. }
  288. }
  289. static void apply_mid_side_stereo(ChannelElement *cpe)
  290. {
  291. int w, w2, g, i;
  292. IndividualChannelStream *ics = &cpe->ch[0].ics;
  293. if (!cpe->common_window)
  294. return;
  295. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  296. for (w2 = 0; w2 < ics->group_len[w]; w2++) {
  297. int start = (w+w2) * 128;
  298. for (g = 0; g < ics->num_swb; g++) {
  299. if (!cpe->ms_mask[w*16 + g] && !cpe->is_mask[w*16 + g]) {
  300. start += ics->swb_sizes[g];
  301. continue;
  302. }
  303. for (i = 0; i < ics->swb_sizes[g]; i++) {
  304. float L = (cpe->ch[0].coeffs[start+i] + cpe->ch[1].coeffs[start+i]) * 0.5f;
  305. float R = L - cpe->ch[1].coeffs[start+i];
  306. cpe->ch[0].coeffs[start+i] = L;
  307. cpe->ch[1].coeffs[start+i] = R;
  308. }
  309. start += ics->swb_sizes[g];
  310. }
  311. }
  312. }
  313. }
  314. /**
  315. * Encode scalefactor band coding type.
  316. */
  317. static void encode_band_info(AACEncContext *s, SingleChannelElement *sce)
  318. {
  319. int w;
  320. if (s->coder->set_special_band_scalefactors)
  321. s->coder->set_special_band_scalefactors(s, sce);
  322. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  323. s->coder->encode_window_bands_info(s, sce, w, sce->ics.group_len[w], s->lambda);
  324. }
  325. /**
  326. * Encode scalefactors.
  327. */
  328. static void encode_scale_factors(AVCodecContext *avctx, AACEncContext *s,
  329. SingleChannelElement *sce)
  330. {
  331. int diff, off_sf = sce->sf_idx[0], off_pns = sce->sf_idx[0] - NOISE_OFFSET;
  332. int off_is = 0, noise_flag = 1;
  333. int i, w;
  334. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  335. for (i = 0; i < sce->ics.max_sfb; i++) {
  336. if (!sce->zeroes[w*16 + i]) {
  337. if (sce->band_type[w*16 + i] == NOISE_BT) {
  338. diff = sce->sf_idx[w*16 + i] - off_pns;
  339. off_pns = sce->sf_idx[w*16 + i];
  340. if (noise_flag-- > 0) {
  341. put_bits(&s->pb, NOISE_PRE_BITS, diff + NOISE_PRE);
  342. continue;
  343. }
  344. } else if (sce->band_type[w*16 + i] == INTENSITY_BT ||
  345. sce->band_type[w*16 + i] == INTENSITY_BT2) {
  346. diff = sce->sf_idx[w*16 + i] - off_is;
  347. off_is = sce->sf_idx[w*16 + i];
  348. } else {
  349. diff = sce->sf_idx[w*16 + i] - off_sf;
  350. off_sf = sce->sf_idx[w*16 + i];
  351. }
  352. diff += SCALE_DIFF_ZERO;
  353. av_assert0(diff >= 0 && diff <= 120);
  354. put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);
  355. }
  356. }
  357. }
  358. }
  359. /**
  360. * Encode pulse data.
  361. */
  362. static void encode_pulses(AACEncContext *s, Pulse *pulse)
  363. {
  364. int i;
  365. put_bits(&s->pb, 1, !!pulse->num_pulse);
  366. if (!pulse->num_pulse)
  367. return;
  368. put_bits(&s->pb, 2, pulse->num_pulse - 1);
  369. put_bits(&s->pb, 6, pulse->start);
  370. for (i = 0; i < pulse->num_pulse; i++) {
  371. put_bits(&s->pb, 5, pulse->pos[i]);
  372. put_bits(&s->pb, 4, pulse->amp[i]);
  373. }
  374. }
  375. /**
  376. * Encode spectral coefficients processed by psychoacoustic model.
  377. */
  378. static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce)
  379. {
  380. int start, i, w, w2;
  381. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  382. start = 0;
  383. for (i = 0; i < sce->ics.max_sfb; i++) {
  384. if (sce->zeroes[w*16 + i]) {
  385. start += sce->ics.swb_sizes[i];
  386. continue;
  387. }
  388. for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++) {
  389. s->coder->quantize_and_encode_band(s, &s->pb,
  390. &sce->coeffs[start + w2*128],
  391. NULL, sce->ics.swb_sizes[i],
  392. sce->sf_idx[w*16 + i],
  393. sce->band_type[w*16 + i],
  394. s->lambda,
  395. sce->ics.window_clipping[w]);
  396. }
  397. start += sce->ics.swb_sizes[i];
  398. }
  399. }
  400. }
  401. /**
  402. * Downscale spectral coefficients for near-clipping windows to avoid artifacts
  403. */
  404. static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce)
  405. {
  406. int start, i, j, w;
  407. if (sce->ics.clip_avoidance_factor < 1.0f) {
  408. for (w = 0; w < sce->ics.num_windows; w++) {
  409. start = 0;
  410. for (i = 0; i < sce->ics.max_sfb; i++) {
  411. float *swb_coeffs = &sce->coeffs[start + w*128];
  412. for (j = 0; j < sce->ics.swb_sizes[i]; j++)
  413. swb_coeffs[j] *= sce->ics.clip_avoidance_factor;
  414. start += sce->ics.swb_sizes[i];
  415. }
  416. }
  417. }
  418. }
  419. /**
  420. * Encode one channel of audio data.
  421. */
  422. static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,
  423. SingleChannelElement *sce,
  424. int common_window)
  425. {
  426. put_bits(&s->pb, 8, sce->sf_idx[0]);
  427. if (!common_window) {
  428. put_ics_info(s, &sce->ics);
  429. if (s->coder->encode_main_pred)
  430. s->coder->encode_main_pred(s, sce);
  431. }
  432. encode_band_info(s, sce);
  433. encode_scale_factors(avctx, s, sce);
  434. encode_pulses(s, &sce->pulse);
  435. put_bits(&s->pb, 1, !!sce->tns.present);
  436. if (s->coder->encode_tns_info)
  437. s->coder->encode_tns_info(s, sce);
  438. put_bits(&s->pb, 1, 0); //ssr
  439. encode_spectral_coeffs(s, sce);
  440. return 0;
  441. }
  442. /**
  443. * Write some auxiliary information about the created AAC file.
  444. */
  445. static void put_bitstream_info(AACEncContext *s, const char *name)
  446. {
  447. int i, namelen, padbits;
  448. namelen = strlen(name) + 2;
  449. put_bits(&s->pb, 3, TYPE_FIL);
  450. put_bits(&s->pb, 4, FFMIN(namelen, 15));
  451. if (namelen >= 15)
  452. put_bits(&s->pb, 8, namelen - 14);
  453. put_bits(&s->pb, 4, 0); //extension type - filler
  454. padbits = -put_bits_count(&s->pb) & 7;
  455. avpriv_align_put_bits(&s->pb);
  456. for (i = 0; i < namelen - 2; i++)
  457. put_bits(&s->pb, 8, name[i]);
  458. put_bits(&s->pb, 12 - padbits, 0);
  459. }
  460. /*
  461. * Copy input samples.
  462. * Channels are reordered from libavcodec's default order to AAC order.
  463. */
  464. static void copy_input_samples(AACEncContext *s, const AVFrame *frame)
  465. {
  466. int ch;
  467. int end = 2048 + (frame ? frame->nb_samples : 0);
  468. const uint8_t *channel_map = aac_chan_maps[s->channels - 1];
  469. /* copy and remap input samples */
  470. for (ch = 0; ch < s->channels; ch++) {
  471. /* copy last 1024 samples of previous frame to the start of the current frame */
  472. memcpy(&s->planar_samples[ch][1024], &s->planar_samples[ch][2048], 1024 * sizeof(s->planar_samples[0][0]));
  473. /* copy new samples and zero any remaining samples */
  474. if (frame) {
  475. memcpy(&s->planar_samples[ch][2048],
  476. frame->extended_data[channel_map[ch]],
  477. frame->nb_samples * sizeof(s->planar_samples[0][0]));
  478. }
  479. memset(&s->planar_samples[ch][end], 0,
  480. (3072 - end) * sizeof(s->planar_samples[0][0]));
  481. }
  482. }
  483. static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  484. const AVFrame *frame, int *got_packet_ptr)
  485. {
  486. AACEncContext *s = avctx->priv_data;
  487. float **samples = s->planar_samples, *samples2, *la, *overlap;
  488. ChannelElement *cpe;
  489. SingleChannelElement *sce;
  490. IndividualChannelStream *ics;
  491. int i, its, ch, w, chans, tag, start_ch, ret, frame_bits;
  492. int target_bits, rate_bits, too_many_bits, too_few_bits;
  493. int ms_mode = 0, is_mode = 0, tns_mode = 0, pred_mode = 0;
  494. int chan_el_counter[4];
  495. FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
  496. if (s->last_frame == 2)
  497. return 0;
  498. /* add current frame to queue */
  499. if (frame) {
  500. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  501. return ret;
  502. }
  503. copy_input_samples(s, frame);
  504. if (s->psypp)
  505. ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
  506. if (!avctx->frame_number)
  507. return 0;
  508. start_ch = 0;
  509. for (i = 0; i < s->chan_map[0]; i++) {
  510. FFPsyWindowInfo* wi = windows + start_ch;
  511. tag = s->chan_map[i+1];
  512. chans = tag == TYPE_CPE ? 2 : 1;
  513. cpe = &s->cpe[i];
  514. for (ch = 0; ch < chans; ch++) {
  515. sce = &cpe->ch[ch];
  516. ics = &sce->ics;
  517. s->cur_channel = start_ch + ch;
  518. float clip_avoidance_factor;
  519. overlap = &samples[s->cur_channel][0];
  520. samples2 = overlap + 1024;
  521. la = samples2 + (448+64);
  522. if (!frame)
  523. la = NULL;
  524. if (tag == TYPE_LFE) {
  525. wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
  526. wi[ch].window_shape = 0;
  527. wi[ch].num_windows = 1;
  528. wi[ch].grouping[0] = 1;
  529. /* Only the lowest 12 coefficients are used in a LFE channel.
  530. * The expression below results in only the bottom 8 coefficients
  531. * being used for 11.025kHz to 16kHz sample rates.
  532. */
  533. ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
  534. } else {
  535. wi[ch] = s->psy.model->window(&s->psy, samples2, la, s->cur_channel,
  536. ics->window_sequence[0]);
  537. }
  538. ics->window_sequence[1] = ics->window_sequence[0];
  539. ics->window_sequence[0] = wi[ch].window_type[0];
  540. ics->use_kb_window[1] = ics->use_kb_window[0];
  541. ics->use_kb_window[0] = wi[ch].window_shape;
  542. ics->num_windows = wi[ch].num_windows;
  543. ics->swb_sizes = s->psy.bands [ics->num_windows == 8];
  544. ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
  545. ics->swb_offset = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?
  546. ff_swb_offset_128 [s->samplerate_index]:
  547. ff_swb_offset_1024[s->samplerate_index];
  548. ics->tns_max_bands = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?
  549. ff_tns_max_bands_128 [s->samplerate_index]:
  550. ff_tns_max_bands_1024[s->samplerate_index];
  551. clip_avoidance_factor = 0.0f;
  552. for (w = 0; w < ics->num_windows; w++)
  553. ics->group_len[w] = wi[ch].grouping[w];
  554. for (w = 0; w < ics->num_windows; w++) {
  555. if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {
  556. ics->window_clipping[w] = 1;
  557. clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);
  558. } else {
  559. ics->window_clipping[w] = 0;
  560. }
  561. }
  562. if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {
  563. ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;
  564. } else {
  565. ics->clip_avoidance_factor = 1.0f;
  566. }
  567. apply_window_and_mdct(s, sce, overlap);
  568. if (isnan(cpe->ch->coeffs[0])) {
  569. av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");
  570. return AVERROR(EINVAL);
  571. }
  572. avoid_clipping(s, sce);
  573. }
  574. start_ch += chans;
  575. }
  576. if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)
  577. return ret;
  578. frame_bits = its = 0;
  579. do {
  580. init_put_bits(&s->pb, avpkt->data, avpkt->size);
  581. if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & AV_CODEC_FLAG_BITEXACT))
  582. put_bitstream_info(s, LIBAVCODEC_IDENT);
  583. start_ch = 0;
  584. target_bits = 0;
  585. memset(chan_el_counter, 0, sizeof(chan_el_counter));
  586. for (i = 0; i < s->chan_map[0]; i++) {
  587. FFPsyWindowInfo* wi = windows + start_ch;
  588. const float *coeffs[2];
  589. tag = s->chan_map[i+1];
  590. chans = tag == TYPE_CPE ? 2 : 1;
  591. cpe = &s->cpe[i];
  592. cpe->common_window = 0;
  593. memset(cpe->is_mask, 0, sizeof(cpe->is_mask));
  594. memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));
  595. put_bits(&s->pb, 3, tag);
  596. put_bits(&s->pb, 4, chan_el_counter[tag]++);
  597. for (ch = 0; ch < chans; ch++) {
  598. sce = &cpe->ch[ch];
  599. coeffs[ch] = sce->coeffs;
  600. sce->ics.predictor_present = 0;
  601. memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));
  602. memset(&sce->tns, 0, sizeof(TemporalNoiseShaping));
  603. for (w = 0; w < 128; w++)
  604. if (sce->band_type[w] > RESERVED_BT)
  605. sce->band_type[w] = 0;
  606. }
  607. s->psy.bitres.alloc = -1;
  608. s->psy.bitres.bits = avctx->frame_bits / s->channels;
  609. s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
  610. if (s->psy.bitres.alloc > 0) {
  611. /* Lambda unused here on purpose, we need to take psy's unscaled allocation */
  612. target_bits += s->psy.bitres.alloc
  613. * (s->lambda / (avctx->global_quality ? avctx->global_quality : 120));
  614. s->psy.bitres.alloc /= chans;
  615. }
  616. s->cur_type = tag;
  617. for (ch = 0; ch < chans; ch++) {
  618. s->cur_channel = start_ch + ch;
  619. if (s->options.pns && s->coder->mark_pns)
  620. s->coder->mark_pns(s, avctx, &cpe->ch[ch]);
  621. s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
  622. }
  623. if (chans > 1
  624. && wi[0].window_type[0] == wi[1].window_type[0]
  625. && wi[0].window_shape == wi[1].window_shape) {
  626. cpe->common_window = 1;
  627. for (w = 0; w < wi[0].num_windows; w++) {
  628. if (wi[0].grouping[w] != wi[1].grouping[w]) {
  629. cpe->common_window = 0;
  630. break;
  631. }
  632. }
  633. }
  634. for (ch = 0; ch < chans; ch++) { /* TNS and PNS */
  635. sce = &cpe->ch[ch];
  636. s->cur_channel = start_ch + ch;
  637. if (s->options.pns && s->coder->search_for_pns)
  638. s->coder->search_for_pns(s, avctx, sce);
  639. if (s->options.tns && s->coder->search_for_tns)
  640. s->coder->search_for_tns(s, sce);
  641. if (s->options.tns && s->coder->apply_tns_filt)
  642. s->coder->apply_tns_filt(s, sce);
  643. if (sce->tns.present)
  644. tns_mode = 1;
  645. }
  646. s->cur_channel = start_ch;
  647. if (s->options.intensity_stereo) { /* Intensity Stereo */
  648. if (s->coder->search_for_is)
  649. s->coder->search_for_is(s, avctx, cpe);
  650. if (cpe->is_mode) is_mode = 1;
  651. apply_intensity_stereo(cpe);
  652. }
  653. if (s->options.pred) { /* Prediction */
  654. for (ch = 0; ch < chans; ch++) {
  655. sce = &cpe->ch[ch];
  656. s->cur_channel = start_ch + ch;
  657. if (s->options.pred && s->coder->search_for_pred)
  658. s->coder->search_for_pred(s, sce);
  659. if (cpe->ch[ch].ics.predictor_present) pred_mode = 1;
  660. }
  661. if (s->coder->adjust_common_pred)
  662. s->coder->adjust_common_pred(s, cpe);
  663. for (ch = 0; ch < chans; ch++) {
  664. sce = &cpe->ch[ch];
  665. s->cur_channel = start_ch + ch;
  666. if (s->options.pred && s->coder->apply_main_pred)
  667. s->coder->apply_main_pred(s, sce);
  668. }
  669. s->cur_channel = start_ch;
  670. }
  671. if (s->options.mid_side) { /* Mid/Side stereo */
  672. if (s->options.mid_side == -1 && s->coder->search_for_ms)
  673. s->coder->search_for_ms(s, cpe);
  674. else if (cpe->common_window)
  675. memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask));
  676. apply_mid_side_stereo(cpe);
  677. }
  678. adjust_frame_information(cpe, chans);
  679. if (chans == 2) {
  680. put_bits(&s->pb, 1, cpe->common_window);
  681. if (cpe->common_window) {
  682. put_ics_info(s, &cpe->ch[0].ics);
  683. if (s->coder->encode_main_pred)
  684. s->coder->encode_main_pred(s, &cpe->ch[0]);
  685. encode_ms_info(&s->pb, cpe);
  686. if (cpe->ms_mode) ms_mode = 1;
  687. }
  688. }
  689. for (ch = 0; ch < chans; ch++) {
  690. s->cur_channel = start_ch + ch;
  691. encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
  692. }
  693. start_ch += chans;
  694. }
  695. if (avctx->flags & CODEC_FLAG_QSCALE) {
  696. /* When using a constant Q-scale, don't mess with lambda */
  697. break;
  698. }
  699. /* rate control stuff
  700. * allow between the nominal bitrate, and what psy's bit reservoir says to target
  701. * but drift towards the nominal bitrate always
  702. */
  703. frame_bits = put_bits_count(&s->pb);
  704. rate_bits = avctx->bit_rate * 1024 / avctx->sample_rate;
  705. rate_bits = FFMIN(rate_bits, 6144 * s->channels - 3);
  706. too_many_bits = FFMAX(target_bits, rate_bits);
  707. too_many_bits = FFMIN(too_many_bits, 6144 * s->channels - 3);
  708. too_few_bits = FFMIN(FFMAX(rate_bits - rate_bits/4, target_bits), too_many_bits);
  709. /* When using ABR, be strict (but only for increasing) */
  710. too_few_bits = too_few_bits - too_few_bits/8;
  711. too_many_bits = too_many_bits + too_many_bits/2;
  712. if ( its == 0 /* for steady-state Q-scale tracking */
  713. || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
  714. || frame_bits >= 6144 * s->channels - 3 )
  715. {
  716. float ratio = ((float)rate_bits) / frame_bits;
  717. if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
  718. /*
  719. * This path is for steady-state Q-scale tracking
  720. * When frame bits fall within the stable range, we still need to adjust
  721. * lambda to maintain it like so in a stable fashion (large jumps in lambda
  722. * create artifacts and should be avoided), but slowly
  723. */
  724. ratio = sqrtf(sqrtf(ratio));
  725. ratio = av_clipf(ratio, 0.9f, 1.1f);
  726. } else {
  727. /* Not so fast though */
  728. ratio = sqrtf(ratio);
  729. }
  730. s->lambda = FFMIN(s->lambda * ratio, 65536.f);
  731. /* Keep iterating if we must reduce and lambda is in the sky */
  732. if ((s->lambda < 300.f || ratio > 0.9f) && (s->lambda > 10.f || ratio < 1.1f)) {
  733. break;
  734. } else {
  735. if (is_mode || ms_mode || tns_mode || pred_mode) {
  736. for (i = 0; i < s->chan_map[0]; i++) {
  737. // Must restore coeffs
  738. chans = tag == TYPE_CPE ? 2 : 1;
  739. cpe = &s->cpe[i];
  740. for (ch = 0; ch < chans; ch++)
  741. memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
  742. }
  743. }
  744. its++;
  745. }
  746. } else {
  747. break;
  748. }
  749. } while (1);
  750. put_bits(&s->pb, 3, TYPE_END);
  751. flush_put_bits(&s->pb);
  752. avctx->frame_bits = put_bits_count(&s->pb);
  753. s->lambda_sum += s->lambda;
  754. s->lambda_count++;
  755. if (!frame)
  756. s->last_frame++;
  757. ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
  758. &avpkt->duration);
  759. avpkt->size = put_bits_count(&s->pb) >> 3;
  760. *got_packet_ptr = 1;
  761. return 0;
  762. }
  763. static av_cold int aac_encode_end(AVCodecContext *avctx)
  764. {
  765. AACEncContext *s = avctx->priv_data;
  766. av_log(avctx, AV_LOG_INFO, "Qavg: %.3f\n", s->lambda_sum / s->lambda_count);
  767. ff_mdct_end(&s->mdct1024);
  768. ff_mdct_end(&s->mdct128);
  769. ff_psy_end(&s->psy);
  770. ff_lpc_end(&s->lpc);
  771. if (s->psypp)
  772. ff_psy_preprocess_end(s->psypp);
  773. av_freep(&s->buffer.samples);
  774. av_freep(&s->cpe);
  775. av_freep(&s->fdsp);
  776. ff_af_queue_close(&s->afq);
  777. return 0;
  778. }
  779. static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
  780. {
  781. int ret = 0;
  782. s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
  783. if (!s->fdsp)
  784. return AVERROR(ENOMEM);
  785. // window init
  786. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  787. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  788. ff_init_ff_sine_windows(10);
  789. ff_init_ff_sine_windows(7);
  790. if ((ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0)) < 0)
  791. return ret;
  792. if ((ret = ff_mdct_init(&s->mdct128, 8, 0, 32768.0)) < 0)
  793. return ret;
  794. return 0;
  795. }
  796. static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
  797. {
  798. int ch;
  799. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->buffer.samples, s->channels, 3 * 1024 * sizeof(s->buffer.samples[0]), alloc_fail);
  800. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->cpe, s->chan_map[0], sizeof(ChannelElement), alloc_fail);
  801. FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + AV_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
  802. for(ch = 0; ch < s->channels; ch++)
  803. s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;
  804. return 0;
  805. alloc_fail:
  806. return AVERROR(ENOMEM);
  807. }
  808. static av_cold int aac_encode_init(AVCodecContext *avctx)
  809. {
  810. AACEncContext *s = avctx->priv_data;
  811. const AACEncOptions *p_opt = NULL;
  812. int i, ret = 0;
  813. const uint8_t *sizes[2];
  814. uint8_t grouping[AAC_MAX_CHANNELS];
  815. int lengths[2];
  816. s->channels = avctx->channels;
  817. s->chan_map = aac_chan_configs[s->channels-1];
  818. s->random_state = 0x1f2e3d4c;
  819. s->lambda = avctx->global_quality > 0 ? avctx->global_quality : 120;
  820. avctx->extradata_size = 5;
  821. avctx->frame_size = 1024;
  822. avctx->initial_padding = 1024;
  823. avctx->bit_rate = (int)FFMIN(
  824. 6144 * s->channels / 1024.0 * avctx->sample_rate,
  825. avctx->bit_rate);
  826. avctx->profile = avctx->profile == FF_PROFILE_UNKNOWN ? FF_PROFILE_AAC_LOW :
  827. avctx->profile;
  828. for (i = 0; i < 16; i++)
  829. if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
  830. break;
  831. s->samplerate_index = i;
  832. ERROR_IF(s->samplerate_index == 16 ||
  833. s->samplerate_index >= ff_aac_swb_size_1024_len ||
  834. s->samplerate_index >= ff_aac_swb_size_128_len,
  835. "Unsupported sample rate %d\n", avctx->sample_rate);
  836. ERROR_IF(s->channels > AAC_MAX_CHANNELS || s->channels == 7,
  837. "Unsupported number of channels: %d\n", s->channels);
  838. WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
  839. "Too many bits per frame requested, clamping to max\n");
  840. for (i = 0; i < FF_ARRAY_ELEMS(aacenc_profiles); i++) {
  841. if (avctx->profile == aacenc_profiles[i].profile) {
  842. p_opt = &aacenc_profiles[i].opts;
  843. break;
  844. }
  845. }
  846. ERROR_IF(!p_opt, "Unsupported encoding profile: %d\n", avctx->profile);
  847. AAC_OPT_SET(&s->options, p_opt, 1, coder);
  848. AAC_OPT_SET(&s->options, p_opt, 0, pns);
  849. AAC_OPT_SET(&s->options, p_opt, 1, tns);
  850. AAC_OPT_SET(&s->options, p_opt, 0, pred);
  851. AAC_OPT_SET(&s->options, p_opt, 1, mid_side);
  852. AAC_OPT_SET(&s->options, p_opt, 0, intensity_stereo);
  853. if (avctx->profile == FF_PROFILE_MPEG2_AAC_LOW)
  854. s->profile = FF_PROFILE_AAC_LOW;
  855. else
  856. s->profile = avctx->profile;
  857. s->coder = &ff_aac_coders[s->options.coder];
  858. if (s->options.coder != AAC_CODER_TWOLOOP) {
  859. s->options.intensity_stereo = 0;
  860. s->options.pns = 0;
  861. }
  862. if ((ret = dsp_init(avctx, s)) < 0)
  863. goto fail;
  864. if ((ret = alloc_buffers(avctx, s)) < 0)
  865. goto fail;
  866. put_audio_specific_config(avctx);
  867. sizes[0] = ff_aac_swb_size_1024[s->samplerate_index];
  868. sizes[1] = ff_aac_swb_size_128[s->samplerate_index];
  869. lengths[0] = ff_aac_num_swb_1024[s->samplerate_index];
  870. lengths[1] = ff_aac_num_swb_128[s->samplerate_index];
  871. for (i = 0; i < s->chan_map[0]; i++)
  872. grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
  873. if ((ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths,
  874. s->chan_map[0], grouping)) < 0)
  875. goto fail;
  876. s->psypp = ff_psy_preprocess_init(avctx);
  877. ff_lpc_init(&s->lpc, 2*avctx->frame_size, TNS_MAX_ORDER, FF_LPC_TYPE_LEVINSON);
  878. if (HAVE_MIPSDSPR1)
  879. ff_aac_coder_init_mips(s);
  880. ff_aac_tableinit();
  881. ff_af_queue_init(avctx, &s->afq);
  882. return 0;
  883. fail:
  884. aac_encode_end(avctx);
  885. return ret;
  886. }
  887. #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  888. static const AVOption aacenc_options[] = {
  889. {"aac_coder", "Coding algorithm", offsetof(AACEncContext, options.coder), AV_OPT_TYPE_INT, {.i64 = AAC_CODER_TWOLOOP}, -1, AAC_CODER_NB-1, AACENC_FLAGS, "coder"},
  890. {"faac", "FAAC-inspired method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAAC}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  891. {"anmr", "ANMR method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_ANMR}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  892. {"twoloop", "Two loop searching method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_TWOLOOP}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  893. {"fast", "Constant quantizer", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAST}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  894. {"aac_ms", "Force M/S stereo coding", offsetof(AACEncContext, options.mid_side), AV_OPT_TYPE_BOOL, {.i64 = 0}, -1, 1, AACENC_FLAGS},
  895. {"aac_is", "Intensity stereo coding", offsetof(AACEncContext, options.intensity_stereo), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  896. {"aac_pns", "Perceptual noise substitution", offsetof(AACEncContext, options.pns), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  897. {"aac_tns", "Temporal noise shaping", offsetof(AACEncContext, options.tns), AV_OPT_TYPE_BOOL, {.i64 = 0}, -1, 1, AACENC_FLAGS},
  898. {"aac_pred", "AAC-Main prediction", offsetof(AACEncContext, options.pred), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  899. {NULL}
  900. };
  901. static const AVClass aacenc_class = {
  902. "AAC encoder",
  903. av_default_item_name,
  904. aacenc_options,
  905. LIBAVUTIL_VERSION_INT,
  906. };
  907. AVCodec ff_aac_encoder = {
  908. .name = "aac",
  909. .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
  910. .type = AVMEDIA_TYPE_AUDIO,
  911. .id = AV_CODEC_ID_AAC,
  912. .priv_data_size = sizeof(AACEncContext),
  913. .init = aac_encode_init,
  914. .encode2 = aac_encode_frame,
  915. .close = aac_encode_end,
  916. .supported_samplerates = mpeg4audio_sample_rates,
  917. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY |
  918. AV_CODEC_CAP_EXPERIMENTAL,
  919. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
  920. AV_SAMPLE_FMT_NONE },
  921. .priv_class = &aacenc_class,
  922. };