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.

916 lines
33KB

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