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.

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