ac3enc.c 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842
  1. /*
  2. * The simplest AC-3 encoder
  3. * Copyright (c) 2000 Fabrice Bellard
  4. * Copyright (c) 2006-2010 Justin Ruggles <justin.ruggles@gmail.com>
  5. * Copyright (c) 2006-2010 Prakash Punnoor <prakash@punnoor.de>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * The simplest AC-3 encoder.
  26. */
  27. //#define DEBUG
  28. //#define ASSERT_LEVEL 2
  29. #include "libavutil/audioconvert.h"
  30. #include "libavutil/avassert.h"
  31. #include "libavutil/crc.h"
  32. #include "avcodec.h"
  33. #include "put_bits.h"
  34. #include "dsputil.h"
  35. #include "ac3dsp.h"
  36. #include "ac3.h"
  37. #include "audioconvert.h"
  38. #ifndef CONFIG_AC3ENC_FLOAT
  39. #define CONFIG_AC3ENC_FLOAT 0
  40. #endif
  41. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  42. #define AC3_MAX_EXP_GROUPS 85
  43. /* stereo rematrixing algorithms */
  44. #define AC3_REMATRIXING_IS_STATIC 0x1
  45. #define AC3_REMATRIXING_SUMS 0
  46. #define AC3_REMATRIXING_NONE 1
  47. #define AC3_REMATRIXING_ALWAYS 3
  48. /** Scale a float value by 2^bits and convert to an integer. */
  49. #define SCALE_FLOAT(a, bits) lrintf((a) * (float)(1 << (bits)))
  50. #if CONFIG_AC3ENC_FLOAT
  51. #include "ac3enc_float.h"
  52. #else
  53. #include "ac3enc_fixed.h"
  54. #endif
  55. /**
  56. * Data for a single audio block.
  57. */
  58. typedef struct AC3Block {
  59. uint8_t **bap; ///< bit allocation pointers (bap)
  60. CoefType **mdct_coef; ///< MDCT coefficients
  61. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  62. uint8_t **exp; ///< original exponents
  63. uint8_t **grouped_exp; ///< grouped exponents
  64. int16_t **psd; ///< psd per frequency bin
  65. int16_t **band_psd; ///< psd per critical band
  66. int16_t **mask; ///< masking curve
  67. uint16_t **qmant; ///< quantized mantissas
  68. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  69. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  70. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  71. } AC3Block;
  72. /**
  73. * AC-3 encoder private context.
  74. */
  75. typedef struct AC3EncodeContext {
  76. PutBitContext pb; ///< bitstream writer context
  77. DSPContext dsp;
  78. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  79. AC3MDCTContext mdct; ///< MDCT context
  80. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  81. int bitstream_id; ///< bitstream id (bsid)
  82. int bitstream_mode; ///< bitstream mode (bsmod)
  83. int bit_rate; ///< target bit rate, in bits-per-second
  84. int sample_rate; ///< sampling frequency, in Hz
  85. int frame_size_min; ///< minimum frame size in case rounding is necessary
  86. int frame_size; ///< current frame size in bytes
  87. int frame_size_code; ///< frame size code (frmsizecod)
  88. uint16_t crc_inv[2];
  89. int bits_written; ///< bit count (used to avg. bitrate)
  90. int samples_written; ///< sample count (used to avg. bitrate)
  91. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  92. int channels; ///< total number of channels (nchans)
  93. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  94. int lfe_channel; ///< channel index of the LFE channel
  95. int channel_mode; ///< channel mode (acmod)
  96. const uint8_t *channel_map; ///< channel map used to reorder channels
  97. int cutoff; ///< user-specified cutoff frequency, in Hz
  98. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  99. int nb_coefs[AC3_MAX_CHANNELS];
  100. int rematrixing; ///< determines how rematrixing strategy is calculated
  101. int num_rematrixing_bands; ///< number of rematrixing bands
  102. /* bitrate allocation control */
  103. int slow_gain_code; ///< slow gain code (sgaincod)
  104. int slow_decay_code; ///< slow decay code (sdcycod)
  105. int fast_decay_code; ///< fast decay code (fdcycod)
  106. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  107. int floor_code; ///< floor code (floorcod)
  108. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  109. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  110. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  111. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  112. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  113. int frame_bits; ///< all frame bits except exponents and mantissas
  114. int exponent_bits; ///< number of bits used for exponents
  115. /* mantissa encoding */
  116. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  117. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  118. SampleType **planar_samples;
  119. uint8_t *bap_buffer;
  120. uint8_t *bap1_buffer;
  121. CoefType *mdct_coef_buffer;
  122. int32_t *fixed_coef_buffer;
  123. uint8_t *exp_buffer;
  124. uint8_t *grouped_exp_buffer;
  125. int16_t *psd_buffer;
  126. int16_t *band_psd_buffer;
  127. int16_t *mask_buffer;
  128. uint16_t *qmant_buffer;
  129. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  130. DECLARE_ALIGNED(16, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  131. } AC3EncodeContext;
  132. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  133. static av_cold void mdct_end(AC3MDCTContext *mdct);
  134. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  135. int nbits);
  136. static void mdct512(AC3MDCTContext *mdct, CoefType *out, SampleType *in);
  137. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  138. const SampleType *window, int n);
  139. static int normalize_samples(AC3EncodeContext *s);
  140. static void scale_coefficients(AC3EncodeContext *s);
  141. /**
  142. * LUT for number of exponent groups.
  143. * exponent_group_tab[exponent strategy-1][number of coefficients]
  144. */
  145. static uint8_t exponent_group_tab[3][256];
  146. /**
  147. * List of supported channel layouts.
  148. */
  149. static const int64_t ac3_channel_layouts[] = {
  150. AV_CH_LAYOUT_MONO,
  151. AV_CH_LAYOUT_STEREO,
  152. AV_CH_LAYOUT_2_1,
  153. AV_CH_LAYOUT_SURROUND,
  154. AV_CH_LAYOUT_2_2,
  155. AV_CH_LAYOUT_QUAD,
  156. AV_CH_LAYOUT_4POINT0,
  157. AV_CH_LAYOUT_5POINT0,
  158. AV_CH_LAYOUT_5POINT0_BACK,
  159. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  160. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  161. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  162. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  163. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  164. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  165. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  166. AV_CH_LAYOUT_5POINT1,
  167. AV_CH_LAYOUT_5POINT1_BACK,
  168. 0
  169. };
  170. /**
  171. * Adjust the frame size to make the average bit rate match the target bit rate.
  172. * This is only needed for 11025, 22050, and 44100 sample rates.
  173. */
  174. static void adjust_frame_size(AC3EncodeContext *s)
  175. {
  176. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  177. s->bits_written -= s->bit_rate;
  178. s->samples_written -= s->sample_rate;
  179. }
  180. s->frame_size = s->frame_size_min +
  181. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  182. s->bits_written += s->frame_size * 8;
  183. s->samples_written += AC3_FRAME_SIZE;
  184. }
  185. /**
  186. * Deinterleave input samples.
  187. * Channels are reordered from FFmpeg's default order to AC-3 order.
  188. */
  189. static void deinterleave_input_samples(AC3EncodeContext *s,
  190. const SampleType *samples)
  191. {
  192. int ch, i;
  193. /* deinterleave and remap input samples */
  194. for (ch = 0; ch < s->channels; ch++) {
  195. const SampleType *sptr;
  196. int sinc;
  197. /* copy last 256 samples of previous frame to the start of the current frame */
  198. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  199. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  200. /* deinterleave */
  201. sinc = s->channels;
  202. sptr = samples + s->channel_map[ch];
  203. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  204. s->planar_samples[ch][i] = *sptr;
  205. sptr += sinc;
  206. }
  207. }
  208. }
  209. /**
  210. * Apply the MDCT to input samples to generate frequency coefficients.
  211. * This applies the KBD window and normalizes the input to reduce precision
  212. * loss due to fixed-point calculations.
  213. */
  214. static void apply_mdct(AC3EncodeContext *s)
  215. {
  216. int blk, ch;
  217. for (ch = 0; ch < s->channels; ch++) {
  218. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  219. AC3Block *block = &s->blocks[blk];
  220. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  221. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  222. block->coeff_shift[ch] = normalize_samples(s);
  223. mdct512(&s->mdct, block->mdct_coef[ch], s->windowed_samples);
  224. }
  225. }
  226. }
  227. /**
  228. * Initialize stereo rematrixing.
  229. * If the strategy does not change for each frame, set the rematrixing flags.
  230. */
  231. static void rematrixing_init(AC3EncodeContext *s)
  232. {
  233. if (s->channel_mode == AC3_CHMODE_STEREO)
  234. s->rematrixing = AC3_REMATRIXING_SUMS;
  235. else
  236. s->rematrixing = AC3_REMATRIXING_NONE;
  237. /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
  238. the future in conjunction with channel coupling. */
  239. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
  240. int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
  241. s->blocks[0].new_rematrixing_strategy = 1;
  242. memset(s->blocks[0].rematrixing_flags, flag,
  243. sizeof(s->blocks[0].rematrixing_flags));
  244. }
  245. }
  246. /**
  247. * Determine rematrixing flags for each block and band.
  248. */
  249. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  250. {
  251. int nb_coefs;
  252. int blk, bnd, i;
  253. AC3Block *block, *block0;
  254. s->num_rematrixing_bands = 4;
  255. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
  256. return;
  257. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  258. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  259. block = &s->blocks[blk];
  260. block->new_rematrixing_strategy = !blk;
  261. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  262. /* calculate calculate sum of squared coeffs for one band in one block */
  263. int start = ff_ac3_rematrix_band_tab[bnd];
  264. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  265. CoefSumType sum[4] = {0,};
  266. for (i = start; i < end; i++) {
  267. CoefType lt = block->mdct_coef[0][i];
  268. CoefType rt = block->mdct_coef[1][i];
  269. CoefType md = lt + rt;
  270. CoefType sd = lt - rt;
  271. MAC_COEF(sum[0], lt, lt);
  272. MAC_COEF(sum[1], rt, rt);
  273. MAC_COEF(sum[2], md, md);
  274. MAC_COEF(sum[3], sd, sd);
  275. }
  276. /* compare sums to determine if rematrixing will be used for this band */
  277. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  278. block->rematrixing_flags[bnd] = 1;
  279. else
  280. block->rematrixing_flags[bnd] = 0;
  281. /* determine if new rematrixing flags will be sent */
  282. if (blk &&
  283. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  284. block->new_rematrixing_strategy = 1;
  285. }
  286. }
  287. block0 = block;
  288. }
  289. }
  290. /**
  291. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  292. */
  293. static void apply_rematrixing(AC3EncodeContext *s)
  294. {
  295. int nb_coefs;
  296. int blk, bnd, i;
  297. int start, end;
  298. uint8_t *flags;
  299. if (s->rematrixing == AC3_REMATRIXING_NONE)
  300. return;
  301. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  302. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  303. AC3Block *block = &s->blocks[blk];
  304. if (block->new_rematrixing_strategy)
  305. flags = block->rematrixing_flags;
  306. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  307. if (flags[bnd]) {
  308. start = ff_ac3_rematrix_band_tab[bnd];
  309. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  310. for (i = start; i < end; i++) {
  311. int32_t lt = block->fixed_coef[0][i];
  312. int32_t rt = block->fixed_coef[1][i];
  313. block->fixed_coef[0][i] = (lt + rt) >> 1;
  314. block->fixed_coef[1][i] = (lt - rt) >> 1;
  315. }
  316. }
  317. }
  318. }
  319. }
  320. /**
  321. * Initialize exponent tables.
  322. */
  323. static av_cold void exponent_init(AC3EncodeContext *s)
  324. {
  325. int i;
  326. for (i = 73; i < 256; i++) {
  327. exponent_group_tab[0][i] = (i - 1) / 3;
  328. exponent_group_tab[1][i] = (i + 2) / 6;
  329. exponent_group_tab[2][i] = (i + 8) / 12;
  330. }
  331. /* LFE */
  332. exponent_group_tab[0][7] = 2;
  333. }
  334. /**
  335. * Extract exponents from the MDCT coefficients.
  336. * This takes into account the normalization that was done to the input samples
  337. * by adjusting the exponents by the exponent shift values.
  338. */
  339. static void extract_exponents(AC3EncodeContext *s)
  340. {
  341. int blk, ch, i;
  342. for (ch = 0; ch < s->channels; ch++) {
  343. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  344. AC3Block *block = &s->blocks[blk];
  345. uint8_t *exp = block->exp[ch];
  346. int32_t *coef = block->fixed_coef[ch];
  347. for (i = 0; i < AC3_MAX_COEFS; i++) {
  348. int e;
  349. int v = abs(coef[i]);
  350. if (v == 0)
  351. e = 24;
  352. else {
  353. e = 23 - av_log2(v);
  354. if (e >= 24) {
  355. e = 24;
  356. coef[i] = 0;
  357. }
  358. av_assert2(e >= 0);
  359. }
  360. exp[i] = e;
  361. }
  362. }
  363. }
  364. }
  365. /**
  366. * Exponent Difference Threshold.
  367. * New exponents are sent if their SAD exceed this number.
  368. */
  369. #define EXP_DIFF_THRESHOLD 500
  370. /**
  371. * Calculate exponent strategies for all blocks in a single channel.
  372. */
  373. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  374. uint8_t *exp)
  375. {
  376. int blk, blk1;
  377. int exp_diff;
  378. /* estimate if the exponent variation & decide if they should be
  379. reused in the next frame */
  380. exp_strategy[0] = EXP_NEW;
  381. exp += AC3_MAX_COEFS;
  382. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  383. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  384. if (exp_diff > EXP_DIFF_THRESHOLD)
  385. exp_strategy[blk] = EXP_NEW;
  386. else
  387. exp_strategy[blk] = EXP_REUSE;
  388. exp += AC3_MAX_COEFS;
  389. }
  390. /* now select the encoding strategy type : if exponents are often
  391. recoded, we use a coarse encoding */
  392. blk = 0;
  393. while (blk < AC3_MAX_BLOCKS) {
  394. blk1 = blk + 1;
  395. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  396. blk1++;
  397. switch (blk1 - blk) {
  398. case 1: exp_strategy[blk] = EXP_D45; break;
  399. case 2:
  400. case 3: exp_strategy[blk] = EXP_D25; break;
  401. default: exp_strategy[blk] = EXP_D15; break;
  402. }
  403. blk = blk1;
  404. }
  405. }
  406. /**
  407. * Calculate exponent strategies for all channels.
  408. * Array arrangement is reversed to simplify the per-channel calculation.
  409. */
  410. static void compute_exp_strategy(AC3EncodeContext *s)
  411. {
  412. int ch, blk;
  413. for (ch = 0; ch < s->fbw_channels; ch++) {
  414. compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
  415. }
  416. if (s->lfe_on) {
  417. ch = s->lfe_channel;
  418. s->exp_strategy[ch][0] = EXP_D15;
  419. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  420. s->exp_strategy[ch][blk] = EXP_REUSE;
  421. }
  422. }
  423. /**
  424. * Update the exponents so that they are the ones the decoder will decode.
  425. */
  426. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  427. {
  428. int nb_groups, i, k;
  429. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  430. /* for each group, compute the minimum exponent */
  431. switch(exp_strategy) {
  432. case EXP_D25:
  433. for (i = 1, k = 1; i <= nb_groups; i++) {
  434. uint8_t exp_min = exp[k];
  435. if (exp[k+1] < exp_min)
  436. exp_min = exp[k+1];
  437. exp[i] = exp_min;
  438. k += 2;
  439. }
  440. break;
  441. case EXP_D45:
  442. for (i = 1, k = 1; i <= nb_groups; i++) {
  443. uint8_t exp_min = exp[k];
  444. if (exp[k+1] < exp_min)
  445. exp_min = exp[k+1];
  446. if (exp[k+2] < exp_min)
  447. exp_min = exp[k+2];
  448. if (exp[k+3] < exp_min)
  449. exp_min = exp[k+3];
  450. exp[i] = exp_min;
  451. k += 4;
  452. }
  453. break;
  454. }
  455. /* constraint for DC exponent */
  456. if (exp[0] > 15)
  457. exp[0] = 15;
  458. /* decrease the delta between each groups to within 2 so that they can be
  459. differentially encoded */
  460. for (i = 1; i <= nb_groups; i++)
  461. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  462. i--;
  463. while (--i >= 0)
  464. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  465. /* now we have the exponent values the decoder will see */
  466. switch (exp_strategy) {
  467. case EXP_D25:
  468. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  469. uint8_t exp1 = exp[i];
  470. exp[k--] = exp1;
  471. exp[k--] = exp1;
  472. }
  473. break;
  474. case EXP_D45:
  475. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  476. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  477. k -= 4;
  478. }
  479. break;
  480. }
  481. }
  482. /**
  483. * Encode exponents from original extracted form to what the decoder will see.
  484. * This copies and groups exponents based on exponent strategy and reduces
  485. * deltas between adjacent exponent groups so that they can be differentially
  486. * encoded.
  487. */
  488. static void encode_exponents(AC3EncodeContext *s)
  489. {
  490. int blk, blk1, ch;
  491. uint8_t *exp, *exp1, *exp_strategy;
  492. int nb_coefs, num_reuse_blocks;
  493. for (ch = 0; ch < s->channels; ch++) {
  494. exp = s->blocks[0].exp[ch];
  495. exp_strategy = s->exp_strategy[ch];
  496. nb_coefs = s->nb_coefs[ch];
  497. blk = 0;
  498. while (blk < AC3_MAX_BLOCKS) {
  499. blk1 = blk + 1;
  500. /* count the number of EXP_REUSE blocks after the current block */
  501. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  502. blk1++;
  503. num_reuse_blocks = blk1 - blk - 1;
  504. /* for the EXP_REUSE case we select the min of the exponents */
  505. s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
  506. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
  507. /* copy encoded exponents for reuse case */
  508. exp1 = exp + AC3_MAX_COEFS;
  509. while (blk < blk1-1) {
  510. memcpy(exp1, exp, nb_coefs * sizeof(*exp));
  511. exp1 += AC3_MAX_COEFS;
  512. blk++;
  513. }
  514. blk = blk1;
  515. exp = exp1;
  516. }
  517. }
  518. }
  519. /**
  520. * Group exponents.
  521. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  522. * varies depending on exponent strategy and bandwidth.
  523. */
  524. static void group_exponents(AC3EncodeContext *s)
  525. {
  526. int blk, ch, i;
  527. int group_size, nb_groups, bit_count;
  528. uint8_t *p;
  529. int delta0, delta1, delta2;
  530. int exp0, exp1;
  531. bit_count = 0;
  532. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  533. AC3Block *block = &s->blocks[blk];
  534. for (ch = 0; ch < s->channels; ch++) {
  535. int exp_strategy = s->exp_strategy[ch][blk];
  536. if (exp_strategy == EXP_REUSE)
  537. continue;
  538. group_size = exp_strategy + (exp_strategy == EXP_D45);
  539. nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
  540. bit_count += 4 + (nb_groups * 7);
  541. p = block->exp[ch];
  542. /* DC exponent */
  543. exp1 = *p++;
  544. block->grouped_exp[ch][0] = exp1;
  545. /* remaining exponents are delta encoded */
  546. for (i = 1; i <= nb_groups; i++) {
  547. /* merge three delta in one code */
  548. exp0 = exp1;
  549. exp1 = p[0];
  550. p += group_size;
  551. delta0 = exp1 - exp0 + 2;
  552. av_assert2(delta0 >= 0 && delta0 <= 4);
  553. exp0 = exp1;
  554. exp1 = p[0];
  555. p += group_size;
  556. delta1 = exp1 - exp0 + 2;
  557. av_assert2(delta1 >= 0 && delta1 <= 4);
  558. exp0 = exp1;
  559. exp1 = p[0];
  560. p += group_size;
  561. delta2 = exp1 - exp0 + 2;
  562. av_assert2(delta2 >= 0 && delta2 <= 4);
  563. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  564. }
  565. }
  566. }
  567. s->exponent_bits = bit_count;
  568. }
  569. /**
  570. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  571. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  572. * and encode final exponents.
  573. */
  574. static void process_exponents(AC3EncodeContext *s)
  575. {
  576. extract_exponents(s);
  577. compute_exp_strategy(s);
  578. encode_exponents(s);
  579. group_exponents(s);
  580. emms_c();
  581. }
  582. /**
  583. * Count frame bits that are based solely on fixed parameters.
  584. * This only has to be run once when the encoder is initialized.
  585. */
  586. static void count_frame_bits_fixed(AC3EncodeContext *s)
  587. {
  588. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  589. int blk;
  590. int frame_bits;
  591. /* assumptions:
  592. * no dynamic range codes
  593. * no channel coupling
  594. * bit allocation parameters do not change between blocks
  595. * SNR offsets do not change between blocks
  596. * no delta bit allocation
  597. * no skipped data
  598. * no auxilliary data
  599. */
  600. /* header size */
  601. frame_bits = 65;
  602. frame_bits += frame_bits_inc[s->channel_mode];
  603. /* audio blocks */
  604. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  605. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  606. if (s->channel_mode == AC3_CHMODE_STEREO) {
  607. frame_bits++; /* rematstr */
  608. }
  609. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  610. if (s->lfe_on)
  611. frame_bits++; /* lfeexpstr */
  612. frame_bits++; /* baie */
  613. frame_bits++; /* snr */
  614. frame_bits += 2; /* delta / skip */
  615. }
  616. frame_bits++; /* cplinu for block 0 */
  617. /* bit alloc info */
  618. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  619. /* csnroffset[6] */
  620. /* (fsnoffset[4] + fgaincod[4]) * c */
  621. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  622. /* auxdatae, crcrsv */
  623. frame_bits += 2;
  624. /* CRC */
  625. frame_bits += 16;
  626. s->frame_bits_fixed = frame_bits;
  627. }
  628. /**
  629. * Initialize bit allocation.
  630. * Set default parameter codes and calculate parameter values.
  631. */
  632. static void bit_alloc_init(AC3EncodeContext *s)
  633. {
  634. int ch;
  635. /* init default parameters */
  636. s->slow_decay_code = 2;
  637. s->fast_decay_code = 1;
  638. s->slow_gain_code = 1;
  639. s->db_per_bit_code = 3;
  640. s->floor_code = 7;
  641. for (ch = 0; ch < s->channels; ch++)
  642. s->fast_gain_code[ch] = 4;
  643. /* initial snr offset */
  644. s->coarse_snr_offset = 40;
  645. /* compute real values */
  646. /* currently none of these values change during encoding, so we can just
  647. set them once at initialization */
  648. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  649. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  650. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  651. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  652. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  653. count_frame_bits_fixed(s);
  654. }
  655. /**
  656. * Count the bits used to encode the frame, minus exponents and mantissas.
  657. * Bits based on fixed parameters have already been counted, so now we just
  658. * have to add the bits based on parameters that change during encoding.
  659. */
  660. static void count_frame_bits(AC3EncodeContext *s)
  661. {
  662. int blk, ch;
  663. int frame_bits = 0;
  664. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  665. /* stereo rematrixing */
  666. if (s->channel_mode == AC3_CHMODE_STEREO &&
  667. s->blocks[blk].new_rematrixing_strategy) {
  668. frame_bits += s->num_rematrixing_bands;
  669. }
  670. for (ch = 0; ch < s->fbw_channels; ch++) {
  671. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  672. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  673. }
  674. }
  675. s->frame_bits = s->frame_bits_fixed + frame_bits;
  676. }
  677. /**
  678. * Calculate the number of bits needed to encode a set of mantissas.
  679. */
  680. static int compute_mantissa_size(int mant_cnt[5], uint8_t *bap, int nb_coefs)
  681. {
  682. int bits, b, i;
  683. bits = 0;
  684. for (i = 0; i < nb_coefs; i++) {
  685. b = bap[i];
  686. if (b <= 4) {
  687. // bap=1 to bap=4 will be counted in compute_mantissa_size_final
  688. mant_cnt[b]++;
  689. } else if (b <= 13) {
  690. // bap=5 to bap=13 use (bap-1) bits
  691. bits += b - 1;
  692. } else {
  693. // bap=14 uses 14 bits and bap=15 uses 16 bits
  694. bits += (b == 14) ? 14 : 16;
  695. }
  696. }
  697. return bits;
  698. }
  699. /**
  700. * Finalize the mantissa bit count by adding in the grouped mantissas.
  701. */
  702. static int compute_mantissa_size_final(int mant_cnt[5])
  703. {
  704. // bap=1 : 3 mantissas in 5 bits
  705. int bits = (mant_cnt[1] / 3) * 5;
  706. // bap=2 : 3 mantissas in 7 bits
  707. // bap=4 : 2 mantissas in 7 bits
  708. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  709. // bap=3 : each mantissa is 3 bits
  710. bits += mant_cnt[3] * 3;
  711. return bits;
  712. }
  713. /**
  714. * Calculate masking curve based on the final exponents.
  715. * Also calculate the power spectral densities to use in future calculations.
  716. */
  717. static void bit_alloc_masking(AC3EncodeContext *s)
  718. {
  719. int blk, ch;
  720. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  721. AC3Block *block = &s->blocks[blk];
  722. for (ch = 0; ch < s->channels; ch++) {
  723. /* We only need psd and mask for calculating bap.
  724. Since we currently do not calculate bap when exponent
  725. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  726. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  727. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  728. s->nb_coefs[ch],
  729. block->psd[ch], block->band_psd[ch]);
  730. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  731. 0, s->nb_coefs[ch],
  732. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  733. ch == s->lfe_channel,
  734. DBA_NONE, 0, NULL, NULL, NULL,
  735. block->mask[ch]);
  736. }
  737. }
  738. }
  739. }
  740. /**
  741. * Ensure that bap for each block and channel point to the current bap_buffer.
  742. * They may have been switched during the bit allocation search.
  743. */
  744. static void reset_block_bap(AC3EncodeContext *s)
  745. {
  746. int blk, ch;
  747. if (s->blocks[0].bap[0] == s->bap_buffer)
  748. return;
  749. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  750. for (ch = 0; ch < s->channels; ch++) {
  751. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  752. }
  753. }
  754. }
  755. /**
  756. * Run the bit allocation with a given SNR offset.
  757. * This calculates the bit allocation pointers that will be used to determine
  758. * the quantization of each mantissa.
  759. * @return the number of bits needed for mantissas if the given SNR offset is
  760. * is used.
  761. */
  762. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  763. {
  764. int blk, ch;
  765. int mantissa_bits;
  766. int mant_cnt[5];
  767. snr_offset = (snr_offset - 240) << 2;
  768. reset_block_bap(s);
  769. mantissa_bits = 0;
  770. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  771. AC3Block *block = &s->blocks[blk];
  772. // initialize grouped mantissa counts. these are set so that they are
  773. // padded to the next whole group size when bits are counted in
  774. // compute_mantissa_size_final
  775. mant_cnt[0] = mant_cnt[3] = 0;
  776. mant_cnt[1] = mant_cnt[2] = 2;
  777. mant_cnt[4] = 1;
  778. for (ch = 0; ch < s->channels; ch++) {
  779. /* Currently the only bit allocation parameters which vary across
  780. blocks within a frame are the exponent values. We can take
  781. advantage of that by reusing the bit allocation pointers
  782. whenever we reuse exponents. */
  783. if (s->exp_strategy[ch][blk] == EXP_REUSE) {
  784. memcpy(block->bap[ch], s->blocks[blk-1].bap[ch], AC3_MAX_COEFS);
  785. } else {
  786. ff_ac3_bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  787. s->nb_coefs[ch], snr_offset,
  788. s->bit_alloc.floor, ff_ac3_bap_tab,
  789. block->bap[ch]);
  790. }
  791. mantissa_bits += compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  792. }
  793. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  794. }
  795. return mantissa_bits;
  796. }
  797. /**
  798. * Constant bitrate bit allocation search.
  799. * Find the largest SNR offset that will allow data to fit in the frame.
  800. */
  801. static int cbr_bit_allocation(AC3EncodeContext *s)
  802. {
  803. int ch;
  804. int bits_left;
  805. int snr_offset, snr_incr;
  806. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  807. av_assert2(bits_left >= 0);
  808. snr_offset = s->coarse_snr_offset << 4;
  809. /* if previous frame SNR offset was 1023, check if current frame can also
  810. use SNR offset of 1023. if so, skip the search. */
  811. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  812. if (bit_alloc(s, 1023) <= bits_left)
  813. return 0;
  814. }
  815. while (snr_offset >= 0 &&
  816. bit_alloc(s, snr_offset) > bits_left) {
  817. snr_offset -= 64;
  818. }
  819. if (snr_offset < 0)
  820. return AVERROR(EINVAL);
  821. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  822. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  823. while (snr_offset + snr_incr <= 1023 &&
  824. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  825. snr_offset += snr_incr;
  826. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  827. }
  828. }
  829. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  830. reset_block_bap(s);
  831. s->coarse_snr_offset = snr_offset >> 4;
  832. for (ch = 0; ch < s->channels; ch++)
  833. s->fine_snr_offset[ch] = snr_offset & 0xF;
  834. return 0;
  835. }
  836. /**
  837. * Downgrade exponent strategies to reduce the bits used by the exponents.
  838. * This is a fallback for when bit allocation fails with the normal exponent
  839. * strategies. Each time this function is run it only downgrades the
  840. * strategy in 1 channel of 1 block.
  841. * @return non-zero if downgrade was unsuccessful
  842. */
  843. static int downgrade_exponents(AC3EncodeContext *s)
  844. {
  845. int ch, blk;
  846. for (ch = 0; ch < s->fbw_channels; ch++) {
  847. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  848. if (s->exp_strategy[ch][blk] == EXP_D15) {
  849. s->exp_strategy[ch][blk] = EXP_D25;
  850. return 0;
  851. }
  852. }
  853. }
  854. for (ch = 0; ch < s->fbw_channels; ch++) {
  855. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  856. if (s->exp_strategy[ch][blk] == EXP_D25) {
  857. s->exp_strategy[ch][blk] = EXP_D45;
  858. return 0;
  859. }
  860. }
  861. }
  862. for (ch = 0; ch < s->fbw_channels; ch++) {
  863. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  864. the block number > 0 */
  865. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  866. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  867. s->exp_strategy[ch][blk] = EXP_REUSE;
  868. return 0;
  869. }
  870. }
  871. }
  872. return -1;
  873. }
  874. /**
  875. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  876. * This is a second fallback for when bit allocation still fails after exponents
  877. * have been downgraded.
  878. * @return non-zero if bandwidth reduction was unsuccessful
  879. */
  880. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  881. {
  882. int ch;
  883. if (s->bandwidth_code[0] > min_bw_code) {
  884. for (ch = 0; ch < s->fbw_channels; ch++) {
  885. s->bandwidth_code[ch]--;
  886. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  887. }
  888. return 0;
  889. }
  890. return -1;
  891. }
  892. /**
  893. * Perform bit allocation search.
  894. * Finds the SNR offset value that maximizes quality and fits in the specified
  895. * frame size. Output is the SNR offset and a set of bit allocation pointers
  896. * used to quantize the mantissas.
  897. */
  898. static int compute_bit_allocation(AC3EncodeContext *s)
  899. {
  900. int ret;
  901. count_frame_bits(s);
  902. bit_alloc_masking(s);
  903. ret = cbr_bit_allocation(s);
  904. while (ret) {
  905. /* fallback 1: downgrade exponents */
  906. if (!downgrade_exponents(s)) {
  907. extract_exponents(s);
  908. encode_exponents(s);
  909. group_exponents(s);
  910. ret = compute_bit_allocation(s);
  911. continue;
  912. }
  913. /* fallback 2: reduce bandwidth */
  914. /* only do this if the user has not specified a specific cutoff
  915. frequency */
  916. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  917. process_exponents(s);
  918. ret = compute_bit_allocation(s);
  919. continue;
  920. }
  921. /* fallbacks were not enough... */
  922. break;
  923. }
  924. return ret;
  925. }
  926. /**
  927. * Symmetric quantization on 'levels' levels.
  928. */
  929. static inline int sym_quant(int c, int e, int levels)
  930. {
  931. int v = ((((levels * c) >> (24 - e)) + 1) >> 1) + (levels >> 1);
  932. av_assert2(v >= 0 && v < levels);
  933. return v;
  934. }
  935. /**
  936. * Asymmetric quantization on 2^qbits levels.
  937. */
  938. static inline int asym_quant(int c, int e, int qbits)
  939. {
  940. int lshift, m, v;
  941. lshift = e + qbits - 24;
  942. if (lshift >= 0)
  943. v = c << lshift;
  944. else
  945. v = c >> (-lshift);
  946. /* rounding */
  947. v = (v + 1) >> 1;
  948. m = (1 << (qbits-1));
  949. if (v >= m)
  950. v = m - 1;
  951. av_assert2(v >= -m);
  952. return v & ((1 << qbits)-1);
  953. }
  954. /**
  955. * Quantize a set of mantissas for a single channel in a single block.
  956. */
  957. static void quantize_mantissas_blk_ch(AC3EncodeContext *s, int32_t *fixed_coef,
  958. uint8_t *exp,
  959. uint8_t *bap, uint16_t *qmant, int n)
  960. {
  961. int i;
  962. for (i = 0; i < n; i++) {
  963. int v;
  964. int c = fixed_coef[i];
  965. int e = exp[i];
  966. int b = bap[i];
  967. switch (b) {
  968. case 0:
  969. v = 0;
  970. break;
  971. case 1:
  972. v = sym_quant(c, e, 3);
  973. switch (s->mant1_cnt) {
  974. case 0:
  975. s->qmant1_ptr = &qmant[i];
  976. v = 9 * v;
  977. s->mant1_cnt = 1;
  978. break;
  979. case 1:
  980. *s->qmant1_ptr += 3 * v;
  981. s->mant1_cnt = 2;
  982. v = 128;
  983. break;
  984. default:
  985. *s->qmant1_ptr += v;
  986. s->mant1_cnt = 0;
  987. v = 128;
  988. break;
  989. }
  990. break;
  991. case 2:
  992. v = sym_quant(c, e, 5);
  993. switch (s->mant2_cnt) {
  994. case 0:
  995. s->qmant2_ptr = &qmant[i];
  996. v = 25 * v;
  997. s->mant2_cnt = 1;
  998. break;
  999. case 1:
  1000. *s->qmant2_ptr += 5 * v;
  1001. s->mant2_cnt = 2;
  1002. v = 128;
  1003. break;
  1004. default:
  1005. *s->qmant2_ptr += v;
  1006. s->mant2_cnt = 0;
  1007. v = 128;
  1008. break;
  1009. }
  1010. break;
  1011. case 3:
  1012. v = sym_quant(c, e, 7);
  1013. break;
  1014. case 4:
  1015. v = sym_quant(c, e, 11);
  1016. switch (s->mant4_cnt) {
  1017. case 0:
  1018. s->qmant4_ptr = &qmant[i];
  1019. v = 11 * v;
  1020. s->mant4_cnt = 1;
  1021. break;
  1022. default:
  1023. *s->qmant4_ptr += v;
  1024. s->mant4_cnt = 0;
  1025. v = 128;
  1026. break;
  1027. }
  1028. break;
  1029. case 5:
  1030. v = sym_quant(c, e, 15);
  1031. break;
  1032. case 14:
  1033. v = asym_quant(c, e, 14);
  1034. break;
  1035. case 15:
  1036. v = asym_quant(c, e, 16);
  1037. break;
  1038. default:
  1039. v = asym_quant(c, e, b - 1);
  1040. break;
  1041. }
  1042. qmant[i] = v;
  1043. }
  1044. }
  1045. /**
  1046. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1047. */
  1048. static void quantize_mantissas(AC3EncodeContext *s)
  1049. {
  1050. int blk, ch;
  1051. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1052. AC3Block *block = &s->blocks[blk];
  1053. s->mant1_cnt = s->mant2_cnt = s->mant4_cnt = 0;
  1054. s->qmant1_ptr = s->qmant2_ptr = s->qmant4_ptr = NULL;
  1055. for (ch = 0; ch < s->channels; ch++) {
  1056. quantize_mantissas_blk_ch(s, block->fixed_coef[ch],
  1057. block->exp[ch], block->bap[ch],
  1058. block->qmant[ch], s->nb_coefs[ch]);
  1059. }
  1060. }
  1061. }
  1062. /**
  1063. * Write the AC-3 frame header to the output bitstream.
  1064. */
  1065. static void output_frame_header(AC3EncodeContext *s)
  1066. {
  1067. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1068. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1069. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1070. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1071. put_bits(&s->pb, 5, s->bitstream_id);
  1072. put_bits(&s->pb, 3, s->bitstream_mode);
  1073. put_bits(&s->pb, 3, s->channel_mode);
  1074. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1075. put_bits(&s->pb, 2, 1); /* XXX -4.5 dB */
  1076. if (s->channel_mode & 0x04)
  1077. put_bits(&s->pb, 2, 1); /* XXX -6 dB */
  1078. if (s->channel_mode == AC3_CHMODE_STEREO)
  1079. put_bits(&s->pb, 2, 0); /* surround not indicated */
  1080. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1081. put_bits(&s->pb, 5, 31); /* dialog norm: -31 db */
  1082. put_bits(&s->pb, 1, 0); /* no compression control word */
  1083. put_bits(&s->pb, 1, 0); /* no lang code */
  1084. put_bits(&s->pb, 1, 0); /* no audio production info */
  1085. put_bits(&s->pb, 1, 0); /* no copyright */
  1086. put_bits(&s->pb, 1, 1); /* original bitstream */
  1087. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1088. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1089. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1090. }
  1091. /**
  1092. * Write one audio block to the output bitstream.
  1093. */
  1094. static void output_audio_block(AC3EncodeContext *s, int blk)
  1095. {
  1096. int ch, i, baie, rbnd;
  1097. AC3Block *block = &s->blocks[blk];
  1098. /* block switching */
  1099. for (ch = 0; ch < s->fbw_channels; ch++)
  1100. put_bits(&s->pb, 1, 0);
  1101. /* dither flags */
  1102. for (ch = 0; ch < s->fbw_channels; ch++)
  1103. put_bits(&s->pb, 1, 1);
  1104. /* dynamic range codes */
  1105. put_bits(&s->pb, 1, 0);
  1106. /* channel coupling */
  1107. if (!blk) {
  1108. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1109. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1110. } else {
  1111. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1112. }
  1113. /* stereo rematrixing */
  1114. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1115. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1116. if (block->new_rematrixing_strategy) {
  1117. /* rematrixing flags */
  1118. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1119. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1120. }
  1121. }
  1122. /* exponent strategy */
  1123. for (ch = 0; ch < s->fbw_channels; ch++)
  1124. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1125. if (s->lfe_on)
  1126. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1127. /* bandwidth */
  1128. for (ch = 0; ch < s->fbw_channels; ch++) {
  1129. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1130. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1131. }
  1132. /* exponents */
  1133. for (ch = 0; ch < s->channels; ch++) {
  1134. int nb_groups;
  1135. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1136. continue;
  1137. /* DC exponent */
  1138. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1139. /* exponent groups */
  1140. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1141. for (i = 1; i <= nb_groups; i++)
  1142. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1143. /* gain range info */
  1144. if (ch != s->lfe_channel)
  1145. put_bits(&s->pb, 2, 0);
  1146. }
  1147. /* bit allocation info */
  1148. baie = (blk == 0);
  1149. put_bits(&s->pb, 1, baie);
  1150. if (baie) {
  1151. put_bits(&s->pb, 2, s->slow_decay_code);
  1152. put_bits(&s->pb, 2, s->fast_decay_code);
  1153. put_bits(&s->pb, 2, s->slow_gain_code);
  1154. put_bits(&s->pb, 2, s->db_per_bit_code);
  1155. put_bits(&s->pb, 3, s->floor_code);
  1156. }
  1157. /* snr offset */
  1158. put_bits(&s->pb, 1, baie);
  1159. if (baie) {
  1160. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1161. for (ch = 0; ch < s->channels; ch++) {
  1162. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1163. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1164. }
  1165. }
  1166. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1167. put_bits(&s->pb, 1, 0); /* no data to skip */
  1168. /* mantissas */
  1169. for (ch = 0; ch < s->channels; ch++) {
  1170. int b, q;
  1171. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1172. q = block->qmant[ch][i];
  1173. b = block->bap[ch][i];
  1174. switch (b) {
  1175. case 0: break;
  1176. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1177. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1178. case 3: put_bits(&s->pb, 3, q); break;
  1179. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1180. case 14: put_bits(&s->pb, 14, q); break;
  1181. case 15: put_bits(&s->pb, 16, q); break;
  1182. default: put_bits(&s->pb, b-1, q); break;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. /** CRC-16 Polynomial */
  1188. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1189. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1190. {
  1191. unsigned int c;
  1192. c = 0;
  1193. while (a) {
  1194. if (a & 1)
  1195. c ^= b;
  1196. a = a >> 1;
  1197. b = b << 1;
  1198. if (b & (1 << 16))
  1199. b ^= poly;
  1200. }
  1201. return c;
  1202. }
  1203. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1204. {
  1205. unsigned int r;
  1206. r = 1;
  1207. while (n) {
  1208. if (n & 1)
  1209. r = mul_poly(r, a, poly);
  1210. a = mul_poly(a, a, poly);
  1211. n >>= 1;
  1212. }
  1213. return r;
  1214. }
  1215. /**
  1216. * Fill the end of the frame with 0's and compute the two CRCs.
  1217. */
  1218. static void output_frame_end(AC3EncodeContext *s)
  1219. {
  1220. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1221. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1222. uint8_t *frame;
  1223. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1224. /* pad the remainder of the frame with zeros */
  1225. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1226. flush_put_bits(&s->pb);
  1227. frame = s->pb.buf;
  1228. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1229. av_assert2(pad_bytes >= 0);
  1230. if (pad_bytes > 0)
  1231. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1232. /* compute crc1 */
  1233. /* this is not so easy because it is at the beginning of the data... */
  1234. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1235. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1236. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1237. AV_WB16(frame + 2, crc1);
  1238. /* compute crc2 */
  1239. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1240. s->frame_size - frame_size_58 - 3);
  1241. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1242. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1243. if (crc2 == 0x770B) {
  1244. frame[s->frame_size - 3] ^= 0x1;
  1245. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1246. }
  1247. crc2 = av_bswap16(crc2);
  1248. AV_WB16(frame + s->frame_size - 2, crc2);
  1249. }
  1250. /**
  1251. * Write the frame to the output bitstream.
  1252. */
  1253. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1254. {
  1255. int blk;
  1256. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1257. output_frame_header(s);
  1258. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1259. output_audio_block(s, blk);
  1260. output_frame_end(s);
  1261. }
  1262. /**
  1263. * Encode a single AC-3 frame.
  1264. */
  1265. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1266. int buf_size, void *data)
  1267. {
  1268. AC3EncodeContext *s = avctx->priv_data;
  1269. const SampleType *samples = data;
  1270. int ret;
  1271. if (s->bit_alloc.sr_code == 1)
  1272. adjust_frame_size(s);
  1273. deinterleave_input_samples(s, samples);
  1274. apply_mdct(s);
  1275. scale_coefficients(s);
  1276. compute_rematrixing_strategy(s);
  1277. apply_rematrixing(s);
  1278. process_exponents(s);
  1279. ret = compute_bit_allocation(s);
  1280. if (ret) {
  1281. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1282. return ret;
  1283. }
  1284. quantize_mantissas(s);
  1285. output_frame(s, frame);
  1286. return s->frame_size;
  1287. }
  1288. /**
  1289. * Finalize encoding and free any memory allocated by the encoder.
  1290. */
  1291. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1292. {
  1293. int blk, ch;
  1294. AC3EncodeContext *s = avctx->priv_data;
  1295. for (ch = 0; ch < s->channels; ch++)
  1296. av_freep(&s->planar_samples[ch]);
  1297. av_freep(&s->planar_samples);
  1298. av_freep(&s->bap_buffer);
  1299. av_freep(&s->bap1_buffer);
  1300. av_freep(&s->mdct_coef_buffer);
  1301. av_freep(&s->fixed_coef_buffer);
  1302. av_freep(&s->exp_buffer);
  1303. av_freep(&s->grouped_exp_buffer);
  1304. av_freep(&s->psd_buffer);
  1305. av_freep(&s->band_psd_buffer);
  1306. av_freep(&s->mask_buffer);
  1307. av_freep(&s->qmant_buffer);
  1308. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1309. AC3Block *block = &s->blocks[blk];
  1310. av_freep(&block->bap);
  1311. av_freep(&block->mdct_coef);
  1312. av_freep(&block->fixed_coef);
  1313. av_freep(&block->exp);
  1314. av_freep(&block->grouped_exp);
  1315. av_freep(&block->psd);
  1316. av_freep(&block->band_psd);
  1317. av_freep(&block->mask);
  1318. av_freep(&block->qmant);
  1319. }
  1320. mdct_end(&s->mdct);
  1321. av_freep(&avctx->coded_frame);
  1322. return 0;
  1323. }
  1324. /**
  1325. * Set channel information during initialization.
  1326. */
  1327. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1328. int64_t *channel_layout)
  1329. {
  1330. int ch_layout;
  1331. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1332. return AVERROR(EINVAL);
  1333. if ((uint64_t)*channel_layout > 0x7FF)
  1334. return AVERROR(EINVAL);
  1335. ch_layout = *channel_layout;
  1336. if (!ch_layout)
  1337. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1338. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1339. return AVERROR(EINVAL);
  1340. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1341. s->channels = channels;
  1342. s->fbw_channels = channels - s->lfe_on;
  1343. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1344. if (s->lfe_on)
  1345. ch_layout -= AV_CH_LOW_FREQUENCY;
  1346. switch (ch_layout) {
  1347. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1348. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1349. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1350. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1351. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1352. case AV_CH_LAYOUT_QUAD:
  1353. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1354. case AV_CH_LAYOUT_5POINT0:
  1355. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1356. default:
  1357. return AVERROR(EINVAL);
  1358. }
  1359. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1360. *channel_layout = ch_layout;
  1361. if (s->lfe_on)
  1362. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1363. return 0;
  1364. }
  1365. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1366. {
  1367. int i, ret;
  1368. /* validate channel layout */
  1369. if (!avctx->channel_layout) {
  1370. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1371. "encoder will guess the layout, but it "
  1372. "might be incorrect.\n");
  1373. }
  1374. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1375. if (ret) {
  1376. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1377. return ret;
  1378. }
  1379. /* validate sample rate */
  1380. for (i = 0; i < 9; i++) {
  1381. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1382. break;
  1383. }
  1384. if (i == 9) {
  1385. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1386. return AVERROR(EINVAL);
  1387. }
  1388. s->sample_rate = avctx->sample_rate;
  1389. s->bit_alloc.sr_shift = i % 3;
  1390. s->bit_alloc.sr_code = i / 3;
  1391. /* validate bit rate */
  1392. for (i = 0; i < 19; i++) {
  1393. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1394. break;
  1395. }
  1396. if (i == 19) {
  1397. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1398. return AVERROR(EINVAL);
  1399. }
  1400. s->bit_rate = avctx->bit_rate;
  1401. s->frame_size_code = i << 1;
  1402. /* validate cutoff */
  1403. if (avctx->cutoff < 0) {
  1404. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1405. return AVERROR(EINVAL);
  1406. }
  1407. s->cutoff = avctx->cutoff;
  1408. if (s->cutoff > (s->sample_rate >> 1))
  1409. s->cutoff = s->sample_rate >> 1;
  1410. return 0;
  1411. }
  1412. /**
  1413. * Set bandwidth for all channels.
  1414. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1415. * default value will be used.
  1416. */
  1417. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1418. {
  1419. int ch, bw_code;
  1420. if (s->cutoff) {
  1421. /* calculate bandwidth based on user-specified cutoff frequency */
  1422. int fbw_coeffs;
  1423. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1424. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1425. } else {
  1426. /* use default bandwidth setting */
  1427. /* XXX: should compute the bandwidth according to the frame
  1428. size, so that we avoid annoying high frequency artifacts */
  1429. bw_code = 50;
  1430. }
  1431. /* set number of coefficients for each channel */
  1432. for (ch = 0; ch < s->fbw_channels; ch++) {
  1433. s->bandwidth_code[ch] = bw_code;
  1434. s->nb_coefs[ch] = bw_code * 3 + 73;
  1435. }
  1436. if (s->lfe_on)
  1437. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1438. }
  1439. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1440. {
  1441. int blk, ch;
  1442. AC3EncodeContext *s = avctx->priv_data;
  1443. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1444. alloc_fail);
  1445. for (ch = 0; ch < s->channels; ch++) {
  1446. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1447. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1448. alloc_fail);
  1449. }
  1450. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1451. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1452. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1453. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1454. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1455. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1456. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1457. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1458. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1459. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1460. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1461. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1462. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1463. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1464. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1465. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1466. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1467. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1468. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1469. AC3Block *block = &s->blocks[blk];
  1470. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1471. alloc_fail);
  1472. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1473. alloc_fail);
  1474. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1475. alloc_fail);
  1476. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1477. alloc_fail);
  1478. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1479. alloc_fail);
  1480. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1481. alloc_fail);
  1482. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1483. alloc_fail);
  1484. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1485. alloc_fail);
  1486. for (ch = 0; ch < s->channels; ch++) {
  1487. /* arrangement: block, channel, coeff */
  1488. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1489. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1490. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1491. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1492. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1493. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1494. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1495. /* arrangement: channel, block, coeff */
  1496. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1497. }
  1498. }
  1499. if (CONFIG_AC3ENC_FLOAT) {
  1500. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1501. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1502. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1503. AC3Block *block = &s->blocks[blk];
  1504. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1505. sizeof(*block->fixed_coef), alloc_fail);
  1506. for (ch = 0; ch < s->channels; ch++)
  1507. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1508. }
  1509. } else {
  1510. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1511. AC3Block *block = &s->blocks[blk];
  1512. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1513. sizeof(*block->fixed_coef), alloc_fail);
  1514. for (ch = 0; ch < s->channels; ch++)
  1515. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1516. }
  1517. }
  1518. return 0;
  1519. alloc_fail:
  1520. return AVERROR(ENOMEM);
  1521. }
  1522. /**
  1523. * Initialize the encoder.
  1524. */
  1525. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1526. {
  1527. AC3EncodeContext *s = avctx->priv_data;
  1528. int ret, frame_size_58;
  1529. avctx->frame_size = AC3_FRAME_SIZE;
  1530. ff_ac3_common_init();
  1531. ret = validate_options(avctx, s);
  1532. if (ret)
  1533. return ret;
  1534. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1535. s->bitstream_mode = 0; /* complete main audio service */
  1536. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1537. s->bits_written = 0;
  1538. s->samples_written = 0;
  1539. s->frame_size = s->frame_size_min;
  1540. /* calculate crc_inv for both possible frame sizes */
  1541. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1542. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1543. if (s->bit_alloc.sr_code == 1) {
  1544. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1545. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1546. }
  1547. set_bandwidth(s);
  1548. rematrixing_init(s);
  1549. exponent_init(s);
  1550. bit_alloc_init(s);
  1551. ret = mdct_init(avctx, &s->mdct, 9);
  1552. if (ret)
  1553. goto init_fail;
  1554. ret = allocate_buffers(avctx);
  1555. if (ret)
  1556. goto init_fail;
  1557. avctx->coded_frame= avcodec_alloc_frame();
  1558. dsputil_init(&s->dsp, avctx);
  1559. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1560. return 0;
  1561. init_fail:
  1562. ac3_encode_close(avctx);
  1563. return ret;
  1564. }