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.

952 lines
34KB

  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, sce->ics.window_clipping[w]);
  417. start += sce->ics.swb_sizes[i];
  418. }
  419. }
  420. }
  421. /**
  422. * Downscale spectral coefficients for near-clipping windows to avoid artifacts
  423. */
  424. static void avoid_clipping(AACEncContext *s, SingleChannelElement *sce)
  425. {
  426. int start, i, j, w;
  427. if (sce->ics.clip_avoidance_factor < 1.0f) {
  428. for (w = 0; w < sce->ics.num_windows; w++) {
  429. start = 0;
  430. for (i = 0; i < sce->ics.max_sfb; i++) {
  431. float *swb_coeffs = sce->coeffs + start + w*128;
  432. for (j = 0; j < sce->ics.swb_sizes[i]; j++)
  433. swb_coeffs[j] *= sce->ics.clip_avoidance_factor;
  434. start += sce->ics.swb_sizes[i];
  435. }
  436. }
  437. }
  438. }
  439. /**
  440. * Encode one channel of audio data.
  441. */
  442. static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,
  443. SingleChannelElement *sce,
  444. int common_window)
  445. {
  446. put_bits(&s->pb, 8, sce->sf_idx[0]);
  447. if (!common_window)
  448. put_ics_info(s, &sce->ics);
  449. encode_band_info(s, sce);
  450. encode_scale_factors(avctx, s, sce);
  451. encode_pulses(s, &sce->pulse);
  452. put_bits(&s->pb, 1, 0); //tns
  453. put_bits(&s->pb, 1, 0); //ssr
  454. encode_spectral_coeffs(s, sce);
  455. return 0;
  456. }
  457. /**
  458. * Write some auxiliary information about the created AAC file.
  459. */
  460. static void put_bitstream_info(AACEncContext *s, const char *name)
  461. {
  462. int i, namelen, padbits;
  463. namelen = strlen(name) + 2;
  464. put_bits(&s->pb, 3, TYPE_FIL);
  465. put_bits(&s->pb, 4, FFMIN(namelen, 15));
  466. if (namelen >= 15)
  467. put_bits(&s->pb, 8, namelen - 14);
  468. put_bits(&s->pb, 4, 0); //extension type - filler
  469. padbits = -put_bits_count(&s->pb) & 7;
  470. avpriv_align_put_bits(&s->pb);
  471. for (i = 0; i < namelen - 2; i++)
  472. put_bits(&s->pb, 8, name[i]);
  473. put_bits(&s->pb, 12 - padbits, 0);
  474. }
  475. /*
  476. * Copy input samples.
  477. * Channels are reordered from libavcodec's default order to AAC order.
  478. */
  479. static void copy_input_samples(AACEncContext *s, const AVFrame *frame)
  480. {
  481. int ch;
  482. int end = 2048 + (frame ? frame->nb_samples : 0);
  483. const uint8_t *channel_map = aac_chan_maps[s->channels - 1];
  484. /* copy and remap input samples */
  485. for (ch = 0; ch < s->channels; ch++) {
  486. /* copy last 1024 samples of previous frame to the start of the current frame */
  487. memcpy(&s->planar_samples[ch][1024], &s->planar_samples[ch][2048], 1024 * sizeof(s->planar_samples[0][0]));
  488. /* copy new samples and zero any remaining samples */
  489. if (frame) {
  490. memcpy(&s->planar_samples[ch][2048],
  491. frame->extended_data[channel_map[ch]],
  492. frame->nb_samples * sizeof(s->planar_samples[0][0]));
  493. }
  494. memset(&s->planar_samples[ch][end], 0,
  495. (3072 - end) * sizeof(s->planar_samples[0][0]));
  496. }
  497. }
  498. static int aac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
  499. const AVFrame *frame, int *got_packet_ptr)
  500. {
  501. AACEncContext *s = avctx->priv_data;
  502. float **samples = s->planar_samples, *samples2, *la, *overlap;
  503. ChannelElement *cpe;
  504. int i, ch, w, g, chans, tag, start_ch, ret, ms_mode = 0, is_mode = 0;
  505. int chan_el_counter[4];
  506. FFPsyWindowInfo windows[AAC_MAX_CHANNELS];
  507. if (s->last_frame == 2)
  508. return 0;
  509. /* add current frame to queue */
  510. if (frame) {
  511. if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)
  512. return ret;
  513. }
  514. copy_input_samples(s, frame);
  515. if (s->psypp)
  516. ff_psy_preprocess(s->psypp, s->planar_samples, s->channels);
  517. if (!avctx->frame_number)
  518. return 0;
  519. start_ch = 0;
  520. for (i = 0; i < s->chan_map[0]; i++) {
  521. FFPsyWindowInfo* wi = windows + start_ch;
  522. tag = s->chan_map[i+1];
  523. chans = tag == TYPE_CPE ? 2 : 1;
  524. cpe = &s->cpe[i];
  525. for (ch = 0; ch < chans; ch++) {
  526. IndividualChannelStream *ics = &cpe->ch[ch].ics;
  527. int cur_channel = start_ch + ch;
  528. float clip_avoidance_factor;
  529. overlap = &samples[cur_channel][0];
  530. samples2 = overlap + 1024;
  531. la = samples2 + (448+64);
  532. if (!frame)
  533. la = NULL;
  534. if (tag == TYPE_LFE) {
  535. wi[ch].window_type[0] = ONLY_LONG_SEQUENCE;
  536. wi[ch].window_shape = 0;
  537. wi[ch].num_windows = 1;
  538. wi[ch].grouping[0] = 1;
  539. /* Only the lowest 12 coefficients are used in a LFE channel.
  540. * The expression below results in only the bottom 8 coefficients
  541. * being used for 11.025kHz to 16kHz sample rates.
  542. */
  543. ics->num_swb = s->samplerate_index >= 8 ? 1 : 3;
  544. } else {
  545. wi[ch] = s->psy.model->window(&s->psy, samples2, la, cur_channel,
  546. ics->window_sequence[0]);
  547. }
  548. ics->window_sequence[1] = ics->window_sequence[0];
  549. ics->window_sequence[0] = wi[ch].window_type[0];
  550. ics->use_kb_window[1] = ics->use_kb_window[0];
  551. ics->use_kb_window[0] = wi[ch].window_shape;
  552. ics->num_windows = wi[ch].num_windows;
  553. ics->swb_sizes = s->psy.bands [ics->num_windows == 8];
  554. ics->num_swb = tag == TYPE_LFE ? ics->num_swb : s->psy.num_bands[ics->num_windows == 8];
  555. clip_avoidance_factor = 0.0f;
  556. for (w = 0; w < ics->num_windows; w++)
  557. ics->group_len[w] = wi[ch].grouping[w];
  558. for (w = 0; w < ics->num_windows; w++) {
  559. if (wi[ch].clipping[w] > CLIP_AVOIDANCE_FACTOR) {
  560. ics->window_clipping[w] = 1;
  561. clip_avoidance_factor = FFMAX(clip_avoidance_factor, wi[ch].clipping[w]);
  562. } else {
  563. ics->window_clipping[w] = 0;
  564. }
  565. }
  566. if (clip_avoidance_factor > CLIP_AVOIDANCE_FACTOR) {
  567. ics->clip_avoidance_factor = CLIP_AVOIDANCE_FACTOR / clip_avoidance_factor;
  568. } else {
  569. ics->clip_avoidance_factor = 1.0f;
  570. }
  571. apply_window_and_mdct(s, &cpe->ch[ch], overlap);
  572. if (isnan(cpe->ch->coeffs[0])) {
  573. av_log(avctx, AV_LOG_ERROR, "Input contains NaN\n");
  574. return AVERROR(EINVAL);
  575. }
  576. avoid_clipping(s, &cpe->ch[ch]);
  577. }
  578. start_ch += chans;
  579. }
  580. if ((ret = ff_alloc_packet2(avctx, avpkt, 8192 * s->channels, 0)) < 0)
  581. return ret;
  582. do {
  583. int frame_bits;
  584. init_put_bits(&s->pb, avpkt->data, avpkt->size);
  585. if ((avctx->frame_number & 0xFF)==1 && !(avctx->flags & CODEC_FLAG_BITEXACT))
  586. put_bitstream_info(s, LIBAVCODEC_IDENT);
  587. start_ch = 0;
  588. memset(chan_el_counter, 0, sizeof(chan_el_counter));
  589. for (i = 0; i < s->chan_map[0]; i++) {
  590. FFPsyWindowInfo* wi = windows + start_ch;
  591. const float *coeffs[2];
  592. tag = s->chan_map[i+1];
  593. chans = tag == TYPE_CPE ? 2 : 1;
  594. cpe = &s->cpe[i];
  595. memset(cpe->is_mask, 0, sizeof(cpe->is_mask));
  596. memset(cpe->ms_mask, 0, sizeof(cpe->ms_mask));
  597. put_bits(&s->pb, 3, tag);
  598. put_bits(&s->pb, 4, chan_el_counter[tag]++);
  599. for (ch = 0; ch < chans; ch++)
  600. coeffs[ch] = cpe->ch[ch].coeffs;
  601. s->psy.model->analyze(&s->psy, start_ch, coeffs, wi);
  602. for (ch = 0; ch < chans; ch++) {
  603. s->cur_channel = start_ch + ch;
  604. s->coder->search_for_quantizers(avctx, s, &cpe->ch[ch], s->lambda);
  605. }
  606. cpe->common_window = 0;
  607. if (chans > 1
  608. && wi[0].window_type[0] == wi[1].window_type[0]
  609. && wi[0].window_shape == wi[1].window_shape) {
  610. cpe->common_window = 1;
  611. for (w = 0; w < wi[0].num_windows; w++) {
  612. if (wi[0].grouping[w] != wi[1].grouping[w]) {
  613. cpe->common_window = 0;
  614. break;
  615. }
  616. }
  617. }
  618. if (s->options.pns && s->coder->search_for_pns) {
  619. for (ch = 0; ch < chans; ch++) {
  620. s->cur_channel = start_ch + ch;
  621. s->coder->search_for_pns(s, avctx, &cpe->ch[ch], s->lambda);
  622. }
  623. }
  624. s->cur_channel = start_ch;
  625. if (s->options.stereo_mode && cpe->common_window) {
  626. if (s->options.stereo_mode > 0) {
  627. IndividualChannelStream *ics = &cpe->ch[0].ics;
  628. for (w = 0; w < ics->num_windows; w += ics->group_len[w])
  629. for (g = 0; g < ics->num_swb; g++)
  630. cpe->ms_mask[w*16+g] = 1;
  631. } else if (s->coder->search_for_ms) {
  632. s->coder->search_for_ms(s, cpe, s->lambda);
  633. }
  634. }
  635. if (chans > 1 && s->options.intensity_stereo && s->coder->search_for_is) {
  636. s->coder->search_for_is(s, avctx, cpe, s->lambda);
  637. if (cpe->is_mode) is_mode = 1;
  638. }
  639. if (s->coder->set_special_band_scalefactors)
  640. for (ch = 0; ch < chans; ch++)
  641. s->coder->set_special_band_scalefactors(s, &cpe->ch[ch]);
  642. adjust_frame_information(cpe, chans);
  643. if (chans == 2) {
  644. put_bits(&s->pb, 1, cpe->common_window);
  645. if (cpe->common_window) {
  646. put_ics_info(s, &cpe->ch[0].ics);
  647. encode_ms_info(&s->pb, cpe);
  648. if (cpe->ms_mode) ms_mode = 1;
  649. }
  650. }
  651. for (ch = 0; ch < chans; ch++) {
  652. s->cur_channel = start_ch + ch;
  653. encode_individual_channel(avctx, s, &cpe->ch[ch], cpe->common_window);
  654. }
  655. start_ch += chans;
  656. }
  657. frame_bits = put_bits_count(&s->pb);
  658. if (frame_bits <= 6144 * s->channels - 3) {
  659. s->psy.bitres.bits = frame_bits / s->channels;
  660. break;
  661. }
  662. if (is_mode || ms_mode) {
  663. for (i = 0; i < s->chan_map[0]; i++) {
  664. // Must restore coeffs
  665. chans = tag == TYPE_CPE ? 2 : 1;
  666. cpe = &s->cpe[i];
  667. for (ch = 0; ch < chans; ch++)
  668. memcpy(cpe->ch[ch].coeffs, cpe->ch[ch].pcoeffs, sizeof(cpe->ch[ch].coeffs));
  669. }
  670. }
  671. s->lambda *= avctx->bit_rate * 1024.0f / avctx->sample_rate / frame_bits;
  672. } while (1);
  673. put_bits(&s->pb, 3, TYPE_END);
  674. flush_put_bits(&s->pb);
  675. avctx->frame_bits = put_bits_count(&s->pb);
  676. // rate control stuff
  677. if (!(avctx->flags & CODEC_FLAG_QSCALE)) {
  678. float ratio = avctx->bit_rate * 1024.0f / avctx->sample_rate / avctx->frame_bits;
  679. s->lambda *= ratio;
  680. s->lambda = FFMIN(s->lambda, 65536.f);
  681. }
  682. if (!frame)
  683. s->last_frame++;
  684. ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,
  685. &avpkt->duration);
  686. avpkt->size = put_bits_count(&s->pb) >> 3;
  687. *got_packet_ptr = 1;
  688. return 0;
  689. }
  690. static av_cold int aac_encode_end(AVCodecContext *avctx)
  691. {
  692. AACEncContext *s = avctx->priv_data;
  693. ff_mdct_end(&s->mdct1024);
  694. ff_mdct_end(&s->mdct128);
  695. ff_psy_end(&s->psy);
  696. if (s->psypp)
  697. ff_psy_preprocess_end(s->psypp);
  698. av_freep(&s->buffer.samples);
  699. av_freep(&s->cpe);
  700. av_freep(&s->fdsp);
  701. ff_af_queue_close(&s->afq);
  702. return 0;
  703. }
  704. static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)
  705. {
  706. int ret = 0;
  707. s->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);
  708. if (!s->fdsp)
  709. return AVERROR(ENOMEM);
  710. // window init
  711. ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);
  712. ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);
  713. ff_init_ff_sine_windows(10);
  714. ff_init_ff_sine_windows(7);
  715. if ((ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0)) < 0)
  716. return ret;
  717. if ((ret = ff_mdct_init(&s->mdct128, 8, 0, 32768.0)) < 0)
  718. return ret;
  719. return 0;
  720. }
  721. static av_cold int alloc_buffers(AVCodecContext *avctx, AACEncContext *s)
  722. {
  723. int ch;
  724. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->buffer.samples, s->channels, 3 * 1024 * sizeof(s->buffer.samples[0]), alloc_fail);
  725. FF_ALLOCZ_ARRAY_OR_GOTO(avctx, s->cpe, s->chan_map[0], sizeof(ChannelElement), alloc_fail);
  726. FF_ALLOCZ_OR_GOTO(avctx, avctx->extradata, 5 + FF_INPUT_BUFFER_PADDING_SIZE, alloc_fail);
  727. for(ch = 0; ch < s->channels; ch++)
  728. s->planar_samples[ch] = s->buffer.samples + 3 * 1024 * ch;
  729. return 0;
  730. alloc_fail:
  731. return AVERROR(ENOMEM);
  732. }
  733. static av_cold int aac_encode_init(AVCodecContext *avctx)
  734. {
  735. AACEncContext *s = avctx->priv_data;
  736. int i, ret = 0;
  737. const uint8_t *sizes[2];
  738. uint8_t grouping[AAC_MAX_CHANNELS];
  739. int lengths[2];
  740. avctx->frame_size = 1024;
  741. for (i = 0; i < 16; i++)
  742. if (avctx->sample_rate == avpriv_mpeg4audio_sample_rates[i])
  743. break;
  744. s->channels = avctx->channels;
  745. ERROR_IF(i == 16
  746. || i >= (sizeof(swb_size_1024) / sizeof(*swb_size_1024))
  747. || i >= (sizeof(swb_size_128) / sizeof(*swb_size_128)),
  748. "Unsupported sample rate %d\n", avctx->sample_rate);
  749. ERROR_IF(s->channels > AAC_MAX_CHANNELS,
  750. "Unsupported number of channels: %d\n", s->channels);
  751. ERROR_IF(avctx->profile != FF_PROFILE_UNKNOWN && avctx->profile != FF_PROFILE_AAC_LOW,
  752. "Unsupported profile %d\n", avctx->profile);
  753. WARN_IF(1024.0 * avctx->bit_rate / avctx->sample_rate > 6144 * s->channels,
  754. "Too many bits per frame requested, clamping to max\n");
  755. avctx->bit_rate = (int)FFMIN(
  756. 6144 * s->channels / 1024.0 * avctx->sample_rate,
  757. avctx->bit_rate);
  758. s->samplerate_index = i;
  759. s->chan_map = aac_chan_configs[s->channels-1];
  760. if ((ret = dsp_init(avctx, s)) < 0)
  761. goto fail;
  762. if ((ret = alloc_buffers(avctx, s)) < 0)
  763. goto fail;
  764. avctx->extradata_size = 5;
  765. put_audio_specific_config(avctx);
  766. sizes[0] = swb_size_1024[i];
  767. sizes[1] = swb_size_128[i];
  768. lengths[0] = ff_aac_num_swb_1024[i];
  769. lengths[1] = ff_aac_num_swb_128[i];
  770. for (i = 0; i < s->chan_map[0]; i++)
  771. grouping[i] = s->chan_map[i + 1] == TYPE_CPE;
  772. if ((ret = ff_psy_init(&s->psy, avctx, 2, sizes, lengths,
  773. s->chan_map[0], grouping)) < 0)
  774. goto fail;
  775. s->psypp = ff_psy_preprocess_init(avctx);
  776. s->coder = &ff_aac_coders[s->options.aac_coder];
  777. if (HAVE_MIPSDSPR1)
  778. ff_aac_coder_init_mips(s);
  779. s->lambda = avctx->global_quality > 0 ? avctx->global_quality : 120;
  780. ff_aac_tableinit();
  781. avctx->initial_padding = 1024;
  782. ff_af_queue_init(avctx, &s->afq);
  783. return 0;
  784. fail:
  785. aac_encode_end(avctx);
  786. return ret;
  787. }
  788. #define AACENC_FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
  789. static const AVOption aacenc_options[] = {
  790. {"stereo_mode", "Stereo coding method", offsetof(AACEncContext, options.stereo_mode), AV_OPT_TYPE_INT, {.i64 = 0}, -1, 1, AACENC_FLAGS, "stereo_mode"},
  791. {"auto", "Selected by the Encoder", 0, AV_OPT_TYPE_CONST, {.i64 = -1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  792. {"ms_off", "Disable Mid/Side coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "stereo_mode"},
  793. {"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"},
  794. {"aac_coder", "", offsetof(AACEncContext, options.aac_coder), AV_OPT_TYPE_INT, {.i64 = AAC_CODER_TWOLOOP}, 0, AAC_CODER_NB-1, AACENC_FLAGS, "aac_coder"},
  795. {"faac", "FAAC-inspired method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAAC}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  796. {"anmr", "ANMR method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_ANMR}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  797. {"twoloop", "Two loop searching method", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_TWOLOOP}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  798. {"fast", "Constant quantizer", 0, AV_OPT_TYPE_CONST, {.i64 = AAC_CODER_FAST}, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_coder"},
  799. {"aac_pns", "Perceptual Noise Substitution", offsetof(AACEncContext, options.pns), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AACENC_FLAGS, "aac_pns"},
  800. {"disable", "Disable perceptual noise substitution", 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_pns"},
  801. {"enable", "Enable perceptual noise substitution", 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, INT_MIN, INT_MAX, AACENC_FLAGS, "aac_pns"},
  802. {"aac_is", "Intensity stereo coding", offsetof(AACEncContext, options.intensity_stereo), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AACENC_FLAGS, "intensity_stereo"},
  803. {"disable", "Disable intensity stereo coding", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, INT_MIN, INT_MAX, AACENC_FLAGS, "intensity_stereo"},
  804. {"enable", "Enable intensity stereo coding", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, INT_MIN, INT_MAX, AACENC_FLAGS, "intensity_stereo"},
  805. {NULL}
  806. };
  807. static const AVClass aacenc_class = {
  808. "AAC encoder",
  809. av_default_item_name,
  810. aacenc_options,
  811. LIBAVUTIL_VERSION_INT,
  812. };
  813. /* duplicated from avpriv_mpeg4audio_sample_rates to avoid shared build
  814. * failures */
  815. static const int mpeg4audio_sample_rates[16] = {
  816. 96000, 88200, 64000, 48000, 44100, 32000,
  817. 24000, 22050, 16000, 12000, 11025, 8000, 7350
  818. };
  819. AVCodec ff_aac_encoder = {
  820. .name = "aac",
  821. .long_name = NULL_IF_CONFIG_SMALL("AAC (Advanced Audio Coding)"),
  822. .type = AVMEDIA_TYPE_AUDIO,
  823. .id = AV_CODEC_ID_AAC,
  824. .priv_data_size = sizeof(AACEncContext),
  825. .init = aac_encode_init,
  826. .encode2 = aac_encode_frame,
  827. .close = aac_encode_end,
  828. .supported_samplerates = mpeg4audio_sample_rates,
  829. .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY |
  830. CODEC_CAP_EXPERIMENTAL,
  831. .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_FLTP,
  832. AV_SAMPLE_FMT_NONE },
  833. .priv_class = &aacenc_class,
  834. };