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.

1021 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. int i, its, ch, w, chans, tag, start_ch, ret, frame_bits;
  491. int target_bits, rate_bits, too_many_bits, too_few_bits;
  492. int ms_mode = 0, is_mode = 0, tns_mode = 0, pred_mode = 0;
  493. int chan_el_counter[4];
  494. FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
  495. if (s->last_frame == 2)
  496. return 0;
  497. /* add current frame to queue */
  498. if (frame) {
  499. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  500. return ret;
  501. }
  502. copy_input_samples(s, frame);
  503. if (s->psypp)
  504. ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
  505. if (!avctx->frame_number)
  506. return 0;
  507. start_ch = 0;
  508. for (i = 0; i < s->chan_map[0]; i++) {
  509. FFPsyWindowInfo* wi = windows + start_ch;
  510. tag = s->chan_map[i+1];
  511. chans = tag == TYPE_CPE ? 2 : 1;
  512. cpe = &s->cpe[i];
  513. for (ch = 0; ch < chans; ch++) {
  514. IndividualChannelStream *ics = &cpe->ch[ch].ics;
  515. int cur_channel = start_ch + ch;
  516. float clip_avoidance_factor;
  517. overlap = &samples[cur_channel][0];
  518. samples2 = overlap + 1024;
  519. la = samples2 + (448+64);
  520. if (!frame)
  521. la = NULL;
  522. if (tag == TYPE_LFE) {
  523. wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
  524. wi[ch].window_shape = 0;
  525. wi[ch].num_windows = 1;
  526. wi[ch].grouping[0] = 1;
  527. /* Only the lowest 12 coefficients are used in a LFE channel.
  528. * The expression below results in only the bottom 8 coefficients
  529. * being used for 11.025kHz to 16kHz sample rates.
  530. */
  531. ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
  532. } else {
  533. wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,
  534. ics->window_sequence[0]);
  535. }
  536. ics->window_sequence[1] = ics->window_sequence[0];
  537. ics->window_sequence[0] = wi[ch].window_type[0];
  538. ics->use_kb_window[1] = ics->use_kb_window[0];
  539. ics->use_kb_window[0] = wi[ch].window_shape;
  540. ics->num_windows = wi[ch].num_windows;
  541. ics->swb_sizes = s->psy.bands [ics->num_windows == 8];
  542. ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
  543. ics->swb_offset = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?
  544. ff_swb_offset_128 [s->samplerate_index]:
  545. ff_swb_offset_1024[s->samplerate_index];
  546. ics->tns_max_bands = wi[ch].window_type[0] == EIGHT_SHORT_SEQUENCE ?
  547. ff_tns_max_bands_128 [s->samplerate_index]:
  548. ff_tns_max_bands_1024[s->samplerate_index];
  549. clip_avoidance_factor = 0.0f;
  550. for (w = 0; w < ics->num_windows; w++)
  551. ics->group_len[w] = wi[ch].grouping[w];
  552. for (w = 0; w < ics->num_windows; w++) {
  553. if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {
  554. ics->window_clipping[w] = 1;
  555. clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);
  556. } else {
  557. ics->window_clipping[w] = 0;
  558. }
  559. }
  560. if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {
  561. ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;
  562. } else {
  563. ics->clip_avoidance_factor = 1.0f;
  564. }
  565. apply_window_and_mdct(s, &cpe->ch[ch], overlap);
  566. if (isnan(cpe->ch->coeffs[0])) {
  567. av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");
  568. return AVERROR(EINVAL);
  569. }
  570. avoid_clipping(s, &cpe->ch[ch]);
  571. }
  572. start_ch += chans;
  573. }
  574. if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)
  575. return ret;
  576. frame_bits = its = 0;
  577. do {
  578. init_put_bits(&s->pb, avpkt->data, avpkt->size);
  579. if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & AV_CODEC_FLAG_BITEXACT))
  580. put_bitstream_info(s, LIBAVCODEC_IDENT);
  581. start_ch = 0;
  582. target_bits = 0;
  583. memset(chan_el_counter, 0, sizeof(chan_el_counter));
  584. for (i = 0; i < s->chan_map[0]; i++) {
  585. FFPsyWindowInfo* wi = windows + start_ch;
  586. const float *coeffs[2];
  587. tag = s->chan_map[i+1];
  588. chans = tag == TYPE_CPE ? 2 : 1;
  589. cpe = &s->cpe[i];
  590. cpe->common_window = 0;
  591. memset(cpe->is_mask, 0, sizeof(cpe->is_mask));
  592. memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));
  593. put_bits(&s->pb, 3, tag);
  594. put_bits(&s->pb, 4, chan_el_counter[tag]++);
  595. for (ch = 0; ch < chans; ch++) {
  596. sce = &cpe->ch[ch];
  597. coeffs[ch] = sce->coeffs;
  598. sce->ics.predictor_present = 0;
  599. memset(&sce->ics.prediction_used, 0, sizeof(sce->ics.prediction_used));
  600. memset(&sce->tns, 0, sizeof(TemporalNoiseShaping));
  601. for (w = 0; w < 128; w++)
  602. if (sce->band_type[w] > RESERVED_BT)
  603. sce->band_type[w] = 0;
  604. }
  605. s->psy.bitres.alloc = -1;
  606. s->psy.bitres.bits = avctx->frame_bits / s->channels;
  607. s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
  608. if (s->psy.bitres.alloc > 0) {
  609. /* Lambda unused here on purpose, we need to take psy's unscaled allocation */
  610. target_bits += s->psy.bitres.alloc
  611. * (s->lambda / (avctx->global_quality ? avctx->global_quality : 120));
  612. s->psy.bitres.alloc /= chans;
  613. }
  614. s->cur_type = tag;
  615. for (ch = 0; ch < chans; ch++) {
  616. s->cur_channel = start_ch + ch;
  617. if (s->options.pns && s->coder->mark_pns)
  618. s->coder->mark_pns(s, avctx, &cpe->ch[ch]);
  619. s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
  620. }
  621. if (chans > 1
  622. && wi[0].window_type[0] == wi[1].window_type[0]
  623. && wi[0].window_shape == wi[1].window_shape) {
  624. cpe->common_window = 1;
  625. for (w = 0; w < wi[0].num_windows; w++) {
  626. if (wi[0].grouping[w] != wi[1].grouping[w]) {
  627. cpe->common_window = 0;
  628. break;
  629. }
  630. }
  631. }
  632. for (ch = 0; ch < chans; ch++) { /* TNS and PNS */
  633. sce = &cpe->ch[ch];
  634. s->cur_channel = start_ch + ch;
  635. if (s->options.pns && s->coder->search_for_pns)
  636. s->coder->search_for_pns(s, avctx, sce);
  637. if (s->options.tns && s->coder->search_for_tns)
  638. s->coder->search_for_tns(s, sce);
  639. if (s->options.tns && s->coder->apply_tns_filt)
  640. s->coder->apply_tns_filt(s, sce);
  641. if (sce->tns.present)
  642. tns_mode = 1;
  643. }
  644. s->cur_channel = start_ch;
  645. if (s->options.intensity_stereo) { /* Intensity Stereo */
  646. if (s->coder->search_for_is)
  647. s->coder->search_for_is(s, avctx, cpe);
  648. if (cpe->is_mode) is_mode = 1;
  649. apply_intensity_stereo(cpe);
  650. }
  651. if (s->options.pred) { /* Prediction */
  652. for (ch = 0; ch < chans; ch++) {
  653. sce = &cpe->ch[ch];
  654. s->cur_channel = start_ch + ch;
  655. if (s->options.pred && s->coder->search_for_pred)
  656. s->coder->search_for_pred(s, sce);
  657. if (cpe->ch[ch].ics.predictor_present) pred_mode = 1;
  658. }
  659. if (s->coder->adjust_common_prediction)
  660. s->coder->adjust_common_prediction(s, cpe);
  661. for (ch = 0; ch < chans; ch++) {
  662. sce = &cpe->ch[ch];
  663. s->cur_channel = start_ch + ch;
  664. if (s->options.pred && s->coder->apply_main_pred)
  665. s->coder->apply_main_pred(s, sce);
  666. }
  667. s->cur_channel = start_ch;
  668. }
  669. if (s->options.mid_side) { /* Mid/Side stereo */
  670. if (s->options.mid_side == -1 && s->coder->search_for_ms)
  671. s->coder->search_for_ms(s, cpe);
  672. else if (cpe->common_window)
  673. memset(cpe->ms_mask, 1, sizeof(cpe->ms_mask));
  674. apply_mid_side_stereo(cpe);
  675. }
  676. adjust_frame_information(cpe, chans);
  677. if (chans == 2) {
  678. put_bits(&s->pb, 1, cpe->common_window);
  679. if (cpe->common_window) {
  680. put_ics_info(s, &cpe->ch[0].ics);
  681. if (s->coder->encode_main_pred)
  682. s->coder->encode_main_pred(s, &cpe->ch[0]);
  683. encode_ms_info(&s->pb, cpe);
  684. if (cpe->ms_mode) ms_mode = 1;
  685. }
  686. }
  687. for (ch = 0; ch < chans; ch++) {
  688. s->cur_channel = start_ch + ch;
  689. encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
  690. }
  691. start_ch += chans;
  692. }
  693. if (avctx->flags & CODEC_FLAG_QSCALE) {
  694. /* When using a constant Q-scale, don't mess with lambda */
  695. break;
  696. }
  697. /* rate control stuff
  698. * allow between the nominal bitrate, and what psy's bit reservoir says to target
  699. * but drift towards the nominal bitrate always
  700. */
  701. frame_bits = put_bits_count(&s->pb);
  702. rate_bits = avctx->bit_rate * 1024 / avctx->sample_rate;
  703. rate_bits = FFMIN(rate_bits, 6144 * s->channels - 3);
  704. too_many_bits = FFMAX(target_bits, rate_bits);
  705. too_many_bits = FFMIN(too_many_bits, 6144 * s->channels - 3);
  706. too_few_bits = FFMIN(FFMAX(rate_bits - rate_bits/4, target_bits), too_many_bits);
  707. /* When using ABR, be strict (but only for increasing) */
  708. too_few_bits = too_few_bits - too_few_bits/8;
  709. too_many_bits = too_many_bits + too_many_bits/2;
  710. if ( its == 0 /* for steady-state Q-scale tracking */
  711. || (its < 5 && (frame_bits < too_few_bits || frame_bits > too_many_bits))
  712. || frame_bits >= 6144 * s->channels - 3 )
  713. {
  714. float ratio = ((float)rate_bits) / frame_bits;
  715. if (frame_bits >= too_few_bits && frame_bits <= too_many_bits) {
  716. /*
  717. * This path is for steady-state Q-scale tracking
  718. * When frame bits fall within the stable range, we still need to adjust
  719. * lambda to maintain it like so in a stable fashion (large jumps in lambda
  720. * create artifacts and should be avoided), but slowly
  721. */
  722. ratio = sqrtf(sqrtf(ratio));
  723. ratio = av_clipf(ratio, 0.9f, 1.1f);
  724. } else {
  725. /* Not so fast though */
  726. ratio = sqrtf(ratio);
  727. }
  728. s->lambda = FFMIN(s->lambda * ratio, 65536.f);
  729. /* Keep iterating if we must reduce and lambda is in the sky */
  730. if ((s->lambda < 300.f || ratio > 0.9f) && (s->lambda > 10.f || ratio < 1.1f)) {
  731. break;
  732. } else {
  733. if (is_mode || ms_mode || tns_mode || pred_mode) {
  734. for (i = 0; i < s->chan_map[0]; i++) {
  735. // Must restore coeffs
  736. chans = tag == TYPE_CPE ? 2 : 1;
  737. cpe = &s->cpe[i];
  738. for (ch = 0; ch < chans; ch++)
  739. memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
  740. }
  741. }
  742. its++;
  743. }
  744. } else {
  745. break;
  746. }
  747. } while (1);
  748. put_bits(&s->pb, 3, TYPE_END);
  749. flush_put_bits(&s->pb);
  750. avctx->frame_bits = put_bits_count(&s->pb);
  751. s->lambda_sum += s->lambda;
  752. s->lambda_count++;
  753. if (!frame)
  754. s->last_frame++;
  755. ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
  756. &avpkt->duration);
  757. avpkt->size = put_bits_count(&s->pb) >> 3;
  758. *got_packet_ptr = 1;
  759. return 0;
  760. }
  761. static av_cold int aac_encode_end(AVCodecContext *avctx)
  762. {
  763. AACEncContext *s = avctx->priv_data;
  764. av_log(avctx, AV_LOG_INFO, "Qavg: %.3f\n", s->lambda_sum / s->lambda_count);
  765. ff_mdct_end(&s->mdct1024);
  766. ff_mdct_end(&s->mdct128);
  767. ff_psy_end(&s->psy);
  768. ff_lpc_end(&s->lpc);
  769. if (s->psypp)
  770. ff_psy_preprocess_end(s->psypp);
  771. av_freep(&s->buffer.samples);
  772. av_freep(&s->cpe);
  773. av_freep(&s->fdsp);
  774. ff_af_queue_close(&s->afq);
  775. return 0;
  776. }
  777. static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
  778. {
  779. int ret = 0;
  780. s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
  781. if (!s->fdsp)
  782. return AVERROR(ENOMEM);
  783. // window init
  784. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  785. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  786. ff_init_ff_sine_windows(10);
  787. ff_init_ff_sine_windows(7);
  788. if ((ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0)) < 0)
  789. return ret;
  790. if ((ret = ff_mdct_init(&s->mdct128, 8, 0, 32768.0)) < 0)
  791. return ret;
  792. return 0;
  793. }
  794. static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
  795. {
  796. int ch;
  797. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->buffer.samples, s->channels, 3 * 1024 * sizeof(s->buffer.samples[0]), alloc_fail);
  798. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->cpe, s->chan_map[0], sizeof(ChannelElement), alloc_fail);
  799. FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + AV_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
  800. for(ch = 0; ch < s->channels; ch++)
  801. s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;
  802. return 0;
  803. alloc_fail:
  804. return AVERROR(ENOMEM);
  805. }
  806. static av_cold int aac_encode_init(AVCodecContext *avctx)
  807. {
  808. AACEncContext *s = avctx->priv_data;
  809. const AACEncOptions *p_opt = NULL;
  810. int i, ret = 0;
  811. const uint8_t *sizes[2];
  812. uint8_t grouping[AAC_MAX_CHANNELS];
  813. int lengths[2];
  814. s->channels = avctx->channels;
  815. s->chan_map = aac_chan_configs[s->channels-1];
  816. s->random_state = 0x1f2e3d4c;
  817. s->lambda = avctx->global_quality > 0 ? avctx->global_quality : 120;
  818. avctx->extradata_size = 5;
  819. avctx->frame_size = 1024;
  820. avctx->initial_padding = 1024;
  821. avctx->bit_rate = (int)FFMIN(
  822. 6144 * s->channels / 1024.0 * avctx->sample_rate,
  823. avctx->bit_rate);
  824. avctx->profile = avctx->profile == FF_PROFILE_UNKNOWN ? FF_PROFILE_AAC_LOW :
  825. avctx->profile;
  826. for (i = 0; i < 16; i++)
  827. if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
  828. break;
  829. s->samplerate_index = i;
  830. ERROR_IF(s->samplerate_index == 16 ||
  831. s->samplerate_index >= ff_aac_swb_size_1024_len ||
  832. s->samplerate_index >= ff_aac_swb_size_128_len,
  833. "Unsupported sample rate %d\n", avctx->sample_rate);
  834. ERROR_IF(s->channels > AAC_MAX_CHANNELS || s->channels == 7,
  835. "Unsupported number of channels: %d\n", s->channels);
  836. WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
  837. "Too many bits per frame requested, clamping to max\n");
  838. for (i = 0; i < FF_ARRAY_ELEMS(aacenc_profiles); i++) {
  839. if (avctx->profile == aacenc_profiles[i].profile) {
  840. p_opt = &aacenc_profiles[i].opts;
  841. break;
  842. }
  843. }
  844. ERROR_IF(!p_opt, "Unsupported encoding profile: %d\n", avctx->profile);
  845. AAC_OPT_SET(&s->options, p_opt, 1, coder);
  846. AAC_OPT_SET(&s->options, p_opt, 0, pns);
  847. AAC_OPT_SET(&s->options, p_opt, 0, tns);
  848. AAC_OPT_SET(&s->options, p_opt, 0, pred);
  849. AAC_OPT_SET(&s->options, p_opt, 1, mid_side);
  850. AAC_OPT_SET(&s->options, p_opt, 0, intensity_stereo);
  851. if (avctx->profile == FF_PROFILE_MPEG2_AAC_LOW)
  852. s->profile = FF_PROFILE_AAC_LOW;
  853. else
  854. s->profile = avctx->profile;
  855. s->coder = &ff_aac_coders[s->options.coder];
  856. if (s->options.coder != AAC_CODER_TWOLOOP) {
  857. s->options.intensity_stereo = 0;
  858. s->options.pns = 0;
  859. }
  860. if ((ret = dsp_init(avctx, s)) < 0)
  861. goto fail;
  862. if ((ret = alloc_buffers(avctx, s)) < 0)
  863. goto fail;
  864. put_audio_specific_config(avctx);
  865. sizes[0] = ff_aac_swb_size_1024[s->samplerate_index];
  866. sizes[1] = ff_aac_swb_size_128[s->samplerate_index];
  867. lengths[0] = ff_aac_num_swb_1024[s->samplerate_index];
  868. lengths[1] = ff_aac_num_swb_128[s->samplerate_index];
  869. for (i = 0; i < s->chan_map[0]; i++)
  870. grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
  871. if ((ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths,
  872. s->chan_map[0], grouping)) < 0)
  873. goto fail;
  874. s->psypp = ff_psy_preprocess_init(avctx);
  875. ff_lpc_init(&s->lpc, 2*avctx->frame_size, TNS_MAX_ORDER, FF_LPC_TYPE_LEVINSON);
  876. if (HAVE_MIPSDSPR1)
  877. ff_aac_coder_init_mips(s);
  878. ff_aac_tableinit();
  879. ff_af_queue_init(avctx, &s->afq);
  880. return 0;
  881. fail:
  882. aac_encode_end(avctx);
  883. return ret;
  884. }
  885. #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  886. static const AVOption aacenc_options[] = {
  887. {"aac_coder", "Coding algorithm", offsetof(AACEncContext, options.coder), AV_OPT_TYPE_INT, {.i64 = AAC_CODER_TWOLOOP}, -1, AAC_CODER_NB-1, AACENC_FLAGS, "coder"},
  888. {"faac", "FAAC-inspired method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAAC}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  889. {"anmr", "ANMR method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_ANMR}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  890. {"twoloop", "Two loop searching method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_TWOLOOP}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  891. {"fast", "Constant quantizer", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAST}, INT_MIN, INT_MAX, AACENC_FLAGS, "coder"},
  892. {"aac_ms", "Force M/S stereo coding", offsetof(AACEncContext, options.mid_side), AV_OPT_TYPE_BOOL, {.i64 = 0}, -1, 1, AACENC_FLAGS},
  893. {"aac_is", "Intensity stereo coding", offsetof(AACEncContext, options.intensity_stereo), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  894. {"aac_pns", "Perceptual noise substitution", offsetof(AACEncContext, options.pns), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  895. {"aac_tns", "Temporal noise shaping", offsetof(AACEncContext, options.tns), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  896. {"aac_pred", "AAC-Main prediction", offsetof(AACEncContext, options.pred), AV_OPT_TYPE_BOOL, {.i64 = OPT_AUTO}, -1, 1, AACENC_FLAGS},
  897. {NULL}
  898. };
  899. static const AVClass aacenc_class = {
  900. "AAC encoder",
  901. av_default_item_name,
  902. aacenc_options,
  903. LIBAVUTIL_VERSION_INT,
  904. };
  905. AVCodec ff_aac_encoder = {
  906. .name = "aac",
  907. .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
  908. .type = AVMEDIA_TYPE_AUDIO,
  909. .id = AV_CODEC_ID_AAC,
  910. .priv_data_size = sizeof(AACEncContext),
  911. .init = aac_encode_init,
  912. .encode2 = aac_encode_frame,
  913. .close = aac_encode_end,
  914. .supported_samplerates = mpeg4audio_sample_rates,
  915. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY |
  916. AV_CODEC_CAP_EXPERIMENTAL,
  917. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
  918. AV_SAMPLE_FMT_NONE },
  919. .priv_class = &aacenc_class,
  920. };