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.

828 lines
30KB

  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. * add temporal noise shaping
  29. ***********************************/
  30. #include "libavutil/float_dsp.h"
  31. #include "libavutil/opt.h"
  32. #include "avcodec.h"
  33. #include "put_bits.h"
  34. #include "internal.h"
  35. #include "mpeg4audio.h"
  36. #include "kbdwin.h"
  37. #include "sinewin.h"
  38. #include "aac.h"
  39. #include "aactab.h"
  40. #include "aacenc.h"
  41. #include "aacenctab.h"
  42. #include "aacenc_utils.h"
  43. #include "psymodel.h"
  44. /**
  45. * Make AAC audio config object.
  46. * @see 1.6.2.1 "Syntax - AudioSpecificConfig"
  47. */
  48. static void put_audio_specific_config(AVCodecContext *avctx)
  49. {
  50. PutBitContext pb;
  51. AACEncContext *s = avctx->priv_data;
  52. init_put_bits(&pb, avctx->extradata, avctx->extradata_size);
  53. put_bits(&pb, 5, 2); //object type - AAC-LC
  54. put_bits(&pb, 4, s->samplerate_index); //sample rate index
  55. put_bits(&pb, 4, s->channels);
  56. //GASpecificConfig
  57. put_bits(&pb, 1, 0); //frame length - 1024 samples
  58. put_bits(&pb, 1, 0); //does not depend on core coder
  59. put_bits(&pb, 1, 0); //is not extension
  60. //Explicitly Mark SBR absent
  61. put_bits(&pb, 11, 0x2b7); //sync extension
  62. put_bits(&pb, 5, AOT_SBR);
  63. put_bits(&pb, 1, 0);
  64. flush_put_bits(&pb);
  65. }
  66. #define WINDOW_FUNC(type) \
  67. static void apply_ ##type ##_window(AVFloatDSPContext *fdsp, \
  68. SingleChannelElement *sce, \
  69. const float *audio)
  70. WINDOW_FUNC(only_long)
  71. {
  72. const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  73. const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  74. float *out = sce->ret_buf;
  75. fdsp->vector_fmul (out, audio, lwindow, 1024);
  76. fdsp->vector_fmul_reverse(out + 1024, audio + 1024, pwindow, 1024);
  77. }
  78. WINDOW_FUNC(long_start)
  79. {
  80. const float *lwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  81. const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  82. float *out = sce->ret_buf;
  83. fdsp->vector_fmul(out, audio, lwindow, 1024);
  84. memcpy(out + 1024, audio + 1024, sizeof(out[0]) * 448);
  85. fdsp->vector_fmul_reverse(out + 1024 + 448, audio + 1024 + 448, swindow, 128);
  86. memset(out + 1024 + 576, 0, sizeof(out[0]) * 448);
  87. }
  88. WINDOW_FUNC(long_stop)
  89. {
  90. const float *lwindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_long_1024 : ff_sine_1024;
  91. const float *swindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  92. float *out = sce->ret_buf;
  93. memset(out, 0, sizeof(out[0]) * 448);
  94. fdsp->vector_fmul(out + 448, audio + 448, swindow, 128);
  95. memcpy(out + 576, audio + 576, sizeof(out[0]) * 448);
  96. fdsp->vector_fmul_reverse(out + 1024, audio + 1024, lwindow, 1024);
  97. }
  98. WINDOW_FUNC(eight_short)
  99. {
  100. const float *swindow = sce->ics.use_kb_window[0] ? ff_aac_kbd_short_128 : ff_sine_128;
  101. const float *pwindow = sce->ics.use_kb_window[1] ? ff_aac_kbd_short_128 : ff_sine_128;
  102. const float *in = audio + 448;
  103. float *out = sce->ret_buf;
  104. int w;
  105. for (w = 0; w < 8; w++) {
  106. fdsp->vector_fmul (out, in, w ? pwindow : swindow, 128);
  107. out += 128;
  108. in += 128;
  109. fdsp->vector_fmul_reverse(out, in, swindow, 128);
  110. out += 128;
  111. }
  112. }
  113. static void (*const apply_window[4])(AVFloatDSPContext *fdsp,
  114. SingleChannelElement *sce,
  115. const float *audio) = {
  116. [ONLY_LONG_SEQUENCE] = apply_only_long_window,
  117. [LONG_START_SEQUENCE] = apply_long_start_window,
  118. [EIGHT_SHORT_SEQUENCE] = apply_eight_short_window,
  119. [LONG_STOP_SEQUENCE] = apply_long_stop_window
  120. };
  121. static void apply_window_and_mdct(AACEncContext *s, SingleChannelElement *sce,
  122. float *audio)
  123. {
  124. int i;
  125. float *output = sce->ret_buf;
  126. apply_window[sce->ics.window_sequence[0]](s->fdsp, sce, audio);
  127. if (sce->ics.window_sequence[0] != EIGHT_SHORT_SEQUENCE)
  128. s->mdct1024.mdct_calc(&s->mdct1024, sce->coeffs, output);
  129. else
  130. for (i = 0; i < 1024; i += 128)
  131. s->mdct128.mdct_calc(&s->mdct128, sce->coeffs + i, output + i*2);
  132. memcpy(audio, audio + 1024, sizeof(audio[0]) * 1024);
  133. memcpy(sce->pcoeffs, sce->coeffs, sizeof(sce->pcoeffs));
  134. }
  135. /**
  136. * Encode ics_info element.
  137. * @see Table 4.6 (syntax of ics_info)
  138. */
  139. static void put_ics_info(AACEncContext *s, IndividualChannelStream *info)
  140. {
  141. int w;
  142. put_bits(&s->pb, 1, 0); // ics_reserved bit
  143. put_bits(&s->pb, 2, info->window_sequence[0]);
  144. put_bits(&s->pb, 1, info->use_kb_window[0]);
  145. if (info->window_sequence[0] != EIGHT_SHORT_SEQUENCE) {
  146. put_bits(&s->pb, 6, info->max_sfb);
  147. put_bits(&s->pb, 1, 0); // no prediction
  148. } else {
  149. put_bits(&s->pb, 4, info->max_sfb);
  150. for (w = 1; w < 8; w++)
  151. put_bits(&s->pb, 1, !info->group_len[w]);
  152. }
  153. }
  154. /**
  155. * Encode MS data.
  156. * @see 4.6.8.1 "Joint Coding - M/S Stereo"
  157. */
  158. static void encode_ms_info(PutBitContext *pb, ChannelElement *cpe)
  159. {
  160. int i, w;
  161. put_bits(pb, 2, cpe->ms_mode);
  162. if (cpe->ms_mode == 1)
  163. for (w = 0; w < cpe->ch[0].ics.num_windows; w += cpe->ch[0].ics.group_len[w])
  164. for (i = 0; i < cpe->ch[0].ics.max_sfb; i++)
  165. put_bits(pb, 1, cpe->ms_mask[w*16 + i]);
  166. }
  167. /**
  168. * Produce integer coefficients from scalefactors provided by the model.
  169. */
  170. static void adjust_frame_information(ChannelElement *cpe, int chans)
  171. {
  172. int i, w, w2, g, ch;
  173. int maxsfb, cmaxsfb;
  174. IndividualChannelStream *ics;
  175. if (cpe->common_window) {
  176. ics = &cpe->ch[0].ics;
  177. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  178. for (w2 = 0; w2 < ics->group_len[w]; w2++) {
  179. int start = (w+w2) * 128;
  180. for (g = 0; g < ics->num_swb; g++) {
  181. //apply Intensity stereo coeffs transformation
  182. if (cpe->is_mask[w*16 + g]) {
  183. int p = -1 + 2 * (cpe->ch[1].band_type[w*16+g] - 14);
  184. float scale = cpe->ch[0].is_ener[w*16+g];
  185. for (i = 0; i < ics->swb_sizes[g]; i++) {
  186. cpe->ch[0].coeffs[start+i] = (cpe->ch[0].pcoeffs[start+i] + p*cpe->ch[1].pcoeffs[start+i]) * scale;
  187. cpe->ch[1].coeffs[start+i] = 0.0f;
  188. }
  189. } else if (cpe->ms_mask[w*16 + g] &&
  190. cpe->ch[0].band_type[w*16 + g] < NOISE_BT &&
  191. cpe->ch[1].band_type[w*16 + g] < NOISE_BT) {
  192. for (i = 0; i < ics->swb_sizes[g]; i++) {
  193. cpe->ch[0].coeffs[start+i] = (cpe->ch[0].pcoeffs[start+i] + cpe->ch[1].pcoeffs[start+i]) * 0.5f;
  194. cpe->ch[1].coeffs[start+i] = cpe->ch[0].coeffs[start+i] - cpe->ch[1].pcoeffs[start+i];
  195. }
  196. }
  197. start += ics->swb_sizes[g];
  198. }
  199. }
  200. }
  201. }
  202. for (ch = 0; ch < chans; ch++) {
  203. IndividualChannelStream *ics = &cpe->ch[ch].ics;
  204. maxsfb = 0;
  205. cpe->ch[ch].pulse.num_pulse = 0;
  206. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  207. for (w2 = 0; w2 < ics->group_len[w]; w2++) {
  208. for (cmaxsfb = ics->num_swb; cmaxsfb > 0 && cpe->ch[ch].zeroes[w*16+cmaxsfb-1]; cmaxsfb--)
  209. ;
  210. maxsfb = FFMAX(maxsfb, cmaxsfb);
  211. }
  212. }
  213. ics->max_sfb = maxsfb;
  214. //adjust zero bands for window groups
  215. for (w = 0; w < ics->num_windows; w += ics->group_len[w]) {
  216. for (g = 0; g < ics->max_sfb; g++) {
  217. i = 1;
  218. for (w2 = w; w2 < w + ics->group_len[w]; w2++) {
  219. if (!cpe->ch[ch].zeroes[w2*16 + g]) {
  220. i = 0;
  221. break;
  222. }
  223. }
  224. cpe->ch[ch].zeroes[w*16 + g] = i;
  225. }
  226. }
  227. }
  228. if (chans > 1 && cpe->common_window) {
  229. IndividualChannelStream *ics0 = &cpe->ch[0].ics;
  230. IndividualChannelStream *ics1 = &cpe->ch[1].ics;
  231. int msc = 0;
  232. ics0->max_sfb = FFMAX(ics0->max_sfb, ics1->max_sfb);
  233. ics1->max_sfb = ics0->max_sfb;
  234. for (w = 0; w < ics0->num_windows*16; w += 16)
  235. for (i = 0; i < ics0->max_sfb; i++)
  236. if (cpe->ms_mask[w+i])
  237. msc++;
  238. if (msc == 0 || ics0->max_sfb == 0)
  239. cpe->ms_mode = 0;
  240. else
  241. cpe->ms_mode = msc < ics0->max_sfb * ics0->num_windows ? 1 : 2;
  242. }
  243. }
  244. /**
  245. * Encode scalefactor band coding type.
  246. */
  247. static void encode_band_info(AACEncContext *s, SingleChannelElement *sce)
  248. {
  249. int w;
  250. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w])
  251. s->coder->encode_window_bands_info(s, sce, w, sce->ics.group_len[w], s->lambda);
  252. }
  253. /**
  254. * Encode scalefactors.
  255. */
  256. static void encode_scale_factors(AVCodecContext *avctx, AACEncContext *s,
  257. SingleChannelElement *sce)
  258. {
  259. int diff, off_sf = sce->sf_idx[0], off_pns = sce->sf_idx[0] - NOISE_OFFSET;
  260. int off_is = 0, noise_flag = 1;
  261. int i, w;
  262. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  263. for (i = 0; i < sce->ics.max_sfb; i++) {
  264. if (!sce->zeroes[w*16 + i]) {
  265. if (sce->band_type[w*16 + i] == NOISE_BT) {
  266. diff = sce->sf_idx[w*16 + i] - off_pns;
  267. off_pns = sce->sf_idx[w*16 + i];
  268. if (noise_flag-- > 0) {
  269. put_bits(&s->pb, NOISE_PRE_BITS, diff + NOISE_PRE);
  270. continue;
  271. }
  272. } else if (sce->band_type[w*16 + i] == INTENSITY_BT ||
  273. sce->band_type[w*16 + i] == INTENSITY_BT2) {
  274. diff = sce->sf_idx[w*16 + i] - off_is;
  275. off_is = sce->sf_idx[w*16 + i];
  276. } else {
  277. diff = sce->sf_idx[w*16 + i] - off_sf;
  278. off_sf = sce->sf_idx[w*16 + i];
  279. }
  280. diff += SCALE_DIFF_ZERO;
  281. av_assert0(diff >= 0 && diff <= 120);
  282. put_bits(&s->pb, ff_aac_scalefactor_bits[diff], ff_aac_scalefactor_code[diff]);
  283. }
  284. }
  285. }
  286. }
  287. /**
  288. * Encode pulse data.
  289. */
  290. static void encode_pulses(AACEncContext *s, Pulse *pulse)
  291. {
  292. int i;
  293. put_bits(&s->pb, 1, !!pulse->num_pulse);
  294. if (!pulse->num_pulse)
  295. return;
  296. put_bits(&s->pb, 2, pulse->num_pulse - 1);
  297. put_bits(&s->pb, 6, pulse->start);
  298. for (i = 0; i < pulse->num_pulse; i++) {
  299. put_bits(&s->pb, 5, pulse->pos[i]);
  300. put_bits(&s->pb, 4, pulse->amp[i]);
  301. }
  302. }
  303. /**
  304. * Encode spectral coefficients processed by psychoacoustic model.
  305. */
  306. static void encode_spectral_coeffs(AACEncContext *s, SingleChannelElement *sce)
  307. {
  308. int start, i, w, w2;
  309. for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {
  310. start = 0;
  311. for (i = 0; i < sce->ics.max_sfb; i++) {
  312. if (sce->zeroes[w*16 + i]) {
  313. start += sce->ics.swb_sizes[i];
  314. continue;
  315. }
  316. for (w2 = w; w2 < w + sce->ics.group_len[w]; w2++)
  317. s->coder->quantize_and_encode_band(s, &s->pb, sce->coeffs + start + w2*128,
  318. sce->ics.swb_sizes[i],
  319. sce->sf_idx[w*16 + i],
  320. sce->band_type[w*16 + i],
  321. s->lambda, sce->ics.window_clipping[w]);
  322. start += sce->ics.swb_sizes[i];
  323. }
  324. }
  325. }
  326. /**
  327. * Downscale spectral coefficients for near-clipping windows to avoid artifacts
  328. */
  329. static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce)
  330. {
  331. int start, i, j, w;
  332. if (sce->ics.clip_avoidance_factor < 1.0f) {
  333. for (w = 0; w < sce->ics.num_windows; w++) {
  334. start = 0;
  335. for (i = 0; i < sce->ics.max_sfb; i++) {
  336. float *swb_coeffs = sce->coeffs + start + w*128;
  337. for (j = 0; j < sce->ics.swb_sizes[i]; j++)
  338. swb_coeffs[j] *= sce->ics.clip_avoidance_factor;
  339. start += sce->ics.swb_sizes[i];
  340. }
  341. }
  342. }
  343. }
  344. /**
  345. * Encode one channel of audio data.
  346. */
  347. static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,
  348. SingleChannelElement *sce,
  349. int common_window)
  350. {
  351. put_bits(&s->pb, 8, sce->sf_idx[0]);
  352. if (!common_window)
  353. put_ics_info(s, &sce->ics);
  354. encode_band_info(s, sce);
  355. encode_scale_factors(avctx, s, sce);
  356. encode_pulses(s, &sce->pulse);
  357. put_bits(&s->pb, 1, 0); //tns
  358. put_bits(&s->pb, 1, 0); //ssr
  359. encode_spectral_coeffs(s, sce);
  360. return 0;
  361. }
  362. /**
  363. * Write some auxiliary information about the created AAC file.
  364. */
  365. static void put_bitstream_info(AACEncContext *s, const char *name)
  366. {
  367. int i, namelen, padbits;
  368. namelen = strlen(name) + 2;
  369. put_bits(&s->pb, 3, TYPE_FIL);
  370. put_bits(&s->pb, 4, FFMIN(namelen, 15));
  371. if (namelen >= 15)
  372. put_bits(&s->pb, 8, namelen - 14);
  373. put_bits(&s->pb, 4, 0); //extension type - filler
  374. padbits = -put_bits_count(&s->pb) & 7;
  375. avpriv_align_put_bits(&s->pb);
  376. for (i = 0; i < namelen - 2; i++)
  377. put_bits(&s->pb, 8, name[i]);
  378. put_bits(&s->pb, 12 - padbits, 0);
  379. }
  380. /*
  381. * Copy input samples.
  382. * Channels are reordered from libavcodec's default order to AAC order.
  383. */
  384. static void copy_input_samples(AACEncContext *s, const AVFrame *frame)
  385. {
  386. int ch;
  387. int end = 2048 + (frame ? frame->nb_samples : 0);
  388. const uint8_t *channel_map = aac_chan_maps[s->channels - 1];
  389. /* copy and remap input samples */
  390. for (ch = 0; ch < s->channels; ch++) {
  391. /* copy last 1024 samples of previous frame to the start of the current frame */
  392. memcpy(&s->planar_samples[ch][1024], &s->planar_samples[ch][2048], 1024 * sizeof(s->planar_samples[0][0]));
  393. /* copy new samples and zero any remaining samples */
  394. if (frame) {
  395. memcpy(&s->planar_samples[ch][2048],
  396. frame->extended_data[channel_map[ch]],
  397. frame->nb_samples * sizeof(s->planar_samples[0][0]));
  398. }
  399. memset(&s->planar_samples[ch][end], 0,
  400. (3072 - end) * sizeof(s->planar_samples[0][0]));
  401. }
  402. }
  403. static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  404. const AVFrame *frame, int *got_packet_ptr)
  405. {
  406. AACEncContext *s = avctx->priv_data;
  407. float **samples = s->planar_samples, *samples2, *la, *overlap;
  408. ChannelElement *cpe;
  409. int i, ch, w, g, chans, tag, start_ch, ret, ms_mode = 0, is_mode = 0;
  410. int chan_el_counter[4];
  411. FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
  412. if (s->last_frame == 2)
  413. return 0;
  414. /* add current frame to queue */
  415. if (frame) {
  416. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  417. return ret;
  418. }
  419. copy_input_samples(s, frame);
  420. if (s->psypp)
  421. ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
  422. if (!avctx->frame_number)
  423. return 0;
  424. start_ch = 0;
  425. for (i = 0; i < s->chan_map[0]; i++) {
  426. FFPsyWindowInfo* wi = windows + start_ch;
  427. tag = s->chan_map[i+1];
  428. chans = tag == TYPE_CPE ? 2 : 1;
  429. cpe = &s->cpe[i];
  430. for (ch = 0; ch < chans; ch++) {
  431. IndividualChannelStream *ics = &cpe->ch[ch].ics;
  432. int cur_channel = start_ch + ch;
  433. float clip_avoidance_factor;
  434. overlap = &samples[cur_channel][0];
  435. samples2 = overlap + 1024;
  436. la = samples2 + (448+64);
  437. if (!frame)
  438. la = NULL;
  439. if (tag == TYPE_LFE) {
  440. wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
  441. wi[ch].window_shape = 0;
  442. wi[ch].num_windows = 1;
  443. wi[ch].grouping[0] = 1;
  444. /* Only the lowest 12 coefficients are used in a LFE channel.
  445. * The expression below results in only the bottom 8 coefficients
  446. * being used for 11.025kHz to 16kHz sample rates.
  447. */
  448. ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
  449. } else {
  450. wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,
  451. ics->window_sequence[0]);
  452. }
  453. ics->window_sequence[1] = ics->window_sequence[0];
  454. ics->window_sequence[0] = wi[ch].window_type[0];
  455. ics->use_kb_window[1] = ics->use_kb_window[0];
  456. ics->use_kb_window[0] = wi[ch].window_shape;
  457. ics->num_windows = wi[ch].num_windows;
  458. ics->swb_sizes = s->psy.bands [ics->num_windows == 8];
  459. ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
  460. clip_avoidance_factor = 0.0f;
  461. for (w = 0; w < ics->num_windows; w++)
  462. ics->group_len[w] = wi[ch].grouping[w];
  463. for (w = 0; w < ics->num_windows; w++) {
  464. if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {
  465. ics->window_clipping[w] = 1;
  466. clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);
  467. } else {
  468. ics->window_clipping[w] = 0;
  469. }
  470. }
  471. if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {
  472. ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;
  473. } else {
  474. ics->clip_avoidance_factor = 1.0f;
  475. }
  476. apply_window_and_mdct(s, &cpe->ch[ch], overlap);
  477. if (isnan(cpe->ch->coeffs[0])) {
  478. av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");
  479. return AVERROR(EINVAL);
  480. }
  481. avoid_clipping(s, &cpe->ch[ch]);
  482. }
  483. start_ch += chans;
  484. }
  485. if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)
  486. return ret;
  487. do {
  488. int frame_bits;
  489. init_put_bits(&s->pb, avpkt->data, avpkt->size);
  490. if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & AV_CODEC_FLAG_BITEXACT))
  491. put_bitstream_info(s, LIBAVCODEC_IDENT);
  492. start_ch = 0;
  493. memset(chan_el_counter, 0, sizeof(chan_el_counter));
  494. for (i = 0; i < s->chan_map[0]; i++) {
  495. FFPsyWindowInfo* wi = windows + start_ch;
  496. const float *coeffs[2];
  497. tag = s->chan_map[i+1];
  498. chans = tag == TYPE_CPE ? 2 : 1;
  499. cpe = &s->cpe[i];
  500. memset(cpe->is_mask, 0, sizeof(cpe->is_mask));
  501. memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));
  502. put_bits(&s->pb, 3, tag);
  503. put_bits(&s->pb, 4, chan_el_counter[tag]++);
  504. for (ch = 0; ch < chans; ch++)
  505. coeffs[ch] = cpe->ch[ch].coeffs;
  506. s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
  507. for (ch = 0; ch < chans; ch++) {
  508. s->cur_channel = start_ch + ch;
  509. s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
  510. }
  511. cpe->common_window = 0;
  512. if (chans > 1
  513. && wi[0].window_type[0] == wi[1].window_type[0]
  514. && wi[0].window_shape == wi[1].window_shape) {
  515. cpe->common_window = 1;
  516. for (w = 0; w < wi[0].num_windows; w++) {
  517. if (wi[0].grouping[w] != wi[1].grouping[w]) {
  518. cpe->common_window = 0;
  519. break;
  520. }
  521. }
  522. }
  523. if (s->options.pns && s->coder->search_for_pns) {
  524. for (ch = 0; ch < chans; ch++) {
  525. s->cur_channel = start_ch + ch;
  526. s->coder->search_for_pns(s, avctx, &cpe->ch[ch]);
  527. }
  528. }
  529. s->cur_channel = start_ch;
  530. if (s->options.stereo_mode && cpe->common_window) {
  531. if (s->options.stereo_mode > 0) {
  532. IndividualChannelStream *ics = &cpe->ch[0].ics;
  533. for (w = 0; w < ics->num_windows; w += ics->group_len[w])
  534. for (g = 0; g < ics->num_swb; g++)
  535. cpe->ms_mask[w*16+g] = 1;
  536. } else if (s->coder->search_for_ms) {
  537. s->coder->search_for_ms(s, cpe);
  538. }
  539. }
  540. if (chans > 1 && s->options.intensity_stereo && s->coder->search_for_is) {
  541. s->coder->search_for_is(s, avctx, cpe);
  542. if (cpe->is_mode) is_mode = 1;
  543. }
  544. if (s->coder->set_special_band_scalefactors)
  545. for (ch = 0; ch < chans; ch++)
  546. s->coder->set_special_band_scalefactors(s, &cpe->ch[ch]);
  547. adjust_frame_information(cpe, chans);
  548. if (chans == 2) {
  549. put_bits(&s->pb, 1, cpe->common_window);
  550. if (cpe->common_window) {
  551. put_ics_info(s, &cpe->ch[0].ics);
  552. encode_ms_info(&s->pb, cpe);
  553. if (cpe->ms_mode) ms_mode = 1;
  554. }
  555. }
  556. for (ch = 0; ch < chans; ch++) {
  557. s->cur_channel = start_ch + ch;
  558. encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
  559. }
  560. start_ch += chans;
  561. }
  562. frame_bits = put_bits_count(&s->pb);
  563. if (frame_bits <= 6144 * s->channels - 3) {
  564. s->psy.bitres.bits = frame_bits / s->channels;
  565. break;
  566. }
  567. if (is_mode || ms_mode) {
  568. for (i = 0; i < s->chan_map[0]; i++) {
  569. // Must restore coeffs
  570. chans = tag == TYPE_CPE ? 2 : 1;
  571. cpe = &s->cpe[i];
  572. for (ch = 0; ch < chans; ch++)
  573. memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
  574. }
  575. }
  576. s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
  577. } while (1);
  578. put_bits(&s->pb, 3, TYPE_END);
  579. flush_put_bits(&s->pb);
  580. avctx->frame_bits = put_bits_count(&s->pb);
  581. // rate control stuff
  582. if (!(avctx->flags & AV_CODEC_FLAG_QSCALE)) {
  583. float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
  584. s->lambda *= ratio;
  585. s->lambda = FFMIN(s->lambda, 65536.f);
  586. }
  587. if (!frame)
  588. s->last_frame++;
  589. ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
  590. &avpkt->duration);
  591. avpkt->size = put_bits_count(&s->pb) >> 3;
  592. *got_packet_ptr = 1;
  593. return 0;
  594. }
  595. static av_cold int aac_encode_end(AVCodecContext *avctx)
  596. {
  597. AACEncContext *s = avctx->priv_data;
  598. ff_mdct_end(&s->mdct1024);
  599. ff_mdct_end(&s->mdct128);
  600. ff_psy_end(&s->psy);
  601. if (s->psypp)
  602. ff_psy_preprocess_end(s->psypp);
  603. av_freep(&s->buffer.samples);
  604. av_freep(&s->cpe);
  605. av_freep(&s->fdsp);
  606. ff_af_queue_close(&s->afq);
  607. return 0;
  608. }
  609. static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
  610. {
  611. int ret = 0;
  612. s->fdsp = avpriv_float_dsp_alloc(avctx->flags & AV_CODEC_FLAG_BITEXACT);
  613. if (!s->fdsp)
  614. return AVERROR(ENOMEM);
  615. // window init
  616. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  617. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  618. ff_init_ff_sine_windows(10);
  619. ff_init_ff_sine_windows(7);
  620. if ((ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0)) < 0)
  621. return ret;
  622. if ((ret = ff_mdct_init(&s->mdct128, 8, 0, 32768.0)) < 0)
  623. return ret;
  624. return 0;
  625. }
  626. static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
  627. {
  628. int ch;
  629. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->buffer.samples, s->channels, 3 * 1024 * sizeof(s->buffer.samples[0]), alloc_fail);
  630. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->cpe, s->chan_map[0], sizeof(ChannelElement), alloc_fail);
  631. FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + AV_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
  632. for(ch = 0; ch < s->channels; ch++)
  633. s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;
  634. return 0;
  635. alloc_fail:
  636. return AVERROR(ENOMEM);
  637. }
  638. static av_cold int aac_encode_init(AVCodecContext *avctx)
  639. {
  640. AACEncContext *s = avctx->priv_data;
  641. int i, ret = 0;
  642. const uint8_t *sizes[2];
  643. uint8_t grouping[AAC_MAX_CHANNELS];
  644. int lengths[2];
  645. avctx->frame_size = 1024;
  646. for (i = 0; i < 16; i++)
  647. if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
  648. break;
  649. s->channels = avctx->channels;
  650. ERROR_IF(i == 16 || i >= swb_size_1024_len || i >= swb_size_128_len,
  651. "Unsupported sample rate %d\n", avctx->sample_rate);
  652. ERROR_IF(s->channels > AAC_MAX_CHANNELS,
  653. "Unsupported number of channels: %d\n", s->channels);
  654. ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
  655. "Unsupported profile %d\n", avctx->profile);
  656. WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
  657. "Too many bits per frame requested, clamping to max\n");
  658. avctx->bit_rate = (int)FFMIN(
  659. 6144 * s->channels / 1024.0 * avctx->sample_rate,
  660. avctx->bit_rate);
  661. s->samplerate_index = i;
  662. s->chan_map = aac_chan_configs[s->channels-1];
  663. if ((ret = dsp_init(avctx, s)) < 0)
  664. goto fail;
  665. if ((ret = alloc_buffers(avctx, s)) < 0)
  666. goto fail;
  667. avctx->extradata_size = 5;
  668. put_audio_specific_config(avctx);
  669. sizes[0] = swb_size_1024[i];
  670. sizes[1] = swb_size_128[i];
  671. lengths[0] = ff_aac_num_swb_1024[i];
  672. lengths[1] = ff_aac_num_swb_128[i];
  673. for (i = 0; i < s->chan_map[0]; i++)
  674. grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
  675. if ((ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths,
  676. s->chan_map[0], grouping)) < 0)
  677. goto fail;
  678. s->psypp = ff_psy_preprocess_init(avctx);
  679. s->coder = &ff_aac_coders[s->options.aac_coder];
  680. if (HAVE_MIPSDSPR1)
  681. ff_aac_coder_init_mips(s);
  682. s->lambda = avctx->global_quality > 0 ? avctx->global_quality : 120;
  683. ff_aac_tableinit();
  684. avctx->initial_padding = 1024;
  685. ff_af_queue_init(avctx, &s->afq);
  686. return 0;
  687. fail:
  688. aac_encode_end(avctx);
  689. return ret;
  690. }
  691. #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  692. static const AVOption aacenc_options[] = {
  693. {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
  694. {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  695. {"ms_off", "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  696. {"ms_force", "Force Mid/Side for the whole frame if possible", 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  697. {"aac_coder", "Coding algorithm", offsetof(AACEncContext, options.aac_coder), AV_OPT_TYPE_INT, {.i64 = AAC_CODER_TWOLOOP}, 0, AAC_CODER_NB-1, AACENC_FLAGS, "aac_coder"},
  698. {"faac", "FAAC-inspired method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAAC}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  699. {"anmr", "ANMR method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_ANMR}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  700. {"twoloop", "Two loop searching method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_TWOLOOP}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  701. {"fast", "Constant quantizer", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAST}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  702. {"aac_pns", "Perceptual Noise Substitution", offsetof(AACEncContext, options.pns), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AACENC_FLAGS, "aac_pns"},
  703. {"disable", "Disable perceptual noise substitution", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_pns"},
  704. {"enable", "Enable perceptual noise substitution", 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_pns"},
  705. {"aac_is", "Intensity stereo coding", offsetof(AACEncContext, options.intensity_stereo), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AACENC_FLAGS, "intensity_stereo"},
  706. {"disable", "Disable intensity stereo coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, AACENC_FLAGS, "intensity_stereo"},
  707. {"enable", "Enable intensity stereo coding", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, INT_MIN, INT_MAX, AACENC_FLAGS, "intensity_stereo"},
  708. {NULL}
  709. };
  710. static const AVClass aacenc_class = {
  711. "AAC encoder",
  712. av_default_item_name,
  713. aacenc_options,
  714. LIBAVUTIL_VERSION_INT,
  715. };
  716. AVCodec ff_aac_encoder = {
  717. .name = "aac",
  718. .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
  719. .type = AVMEDIA_TYPE_AUDIO,
  720. .id = AV_CODEC_ID_AAC,
  721. .priv_data_size = sizeof(AACEncContext),
  722. .init = aac_encode_init,
  723. .encode2 = aac_encode_frame,
  724. .close = aac_encode_end,
  725. .supported_samplerates = mpeg4audio_sample_rates,
  726. .capabilities = AV_CODEC_CAP_SMALL_LAST_FRAME | AV_CODEC_CAP_DELAY |
  727. AV_CODEC_CAP_EXPERIMENTAL,
  728. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
  729. AV_SAMPLE_FMT_NONE },
  730. .priv_class = &aacenc_class,
  731. };