ac3enc.c 78 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250
  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 <stdint.h>
  30. #include "libavutil/audioconvert.h"
  31. #include "libavutil/avassert.h"
  32. #include "libavutil/crc.h"
  33. #include "libavutil/opt.h"
  34. #include "avcodec.h"
  35. #include "put_bits.h"
  36. #include "dsputil.h"
  37. #include "ac3dsp.h"
  38. #include "ac3.h"
  39. #include "audioconvert.h"
  40. #include "fft.h"
  41. #ifndef CONFIG_AC3ENC_FLOAT
  42. #define CONFIG_AC3ENC_FLOAT 0
  43. #endif
  44. /** Maximum number of exponent groups. +1 for separate DC exponent. */
  45. #define AC3_MAX_EXP_GROUPS 85
  46. /* stereo rematrixing algorithms */
  47. #define AC3_REMATRIXING_IS_STATIC 0x1
  48. #define AC3_REMATRIXING_SUMS 0
  49. #define AC3_REMATRIXING_NONE 1
  50. #define AC3_REMATRIXING_ALWAYS 3
  51. #if CONFIG_AC3ENC_FLOAT
  52. #define MAC_COEF(d,a,b) ((d)+=(a)*(b))
  53. typedef float SampleType;
  54. typedef float CoefType;
  55. typedef float CoefSumType;
  56. #else
  57. #define MAC_COEF(d,a,b) MAC64(d,a,b)
  58. typedef int16_t SampleType;
  59. typedef int32_t CoefType;
  60. typedef int64_t CoefSumType;
  61. #endif
  62. typedef struct AC3MDCTContext {
  63. const SampleType *window; ///< MDCT window function
  64. FFTContext fft; ///< FFT context for MDCT calculation
  65. } AC3MDCTContext;
  66. /**
  67. * Data for a single audio block.
  68. */
  69. typedef struct AC3Block {
  70. uint8_t **bap; ///< bit allocation pointers (bap)
  71. CoefType **mdct_coef; ///< MDCT coefficients
  72. int32_t **fixed_coef; ///< fixed-point MDCT coefficients
  73. uint8_t **exp; ///< original exponents
  74. uint8_t **grouped_exp; ///< grouped exponents
  75. int16_t **psd; ///< psd per frequency bin
  76. int16_t **band_psd; ///< psd per critical band
  77. int16_t **mask; ///< masking curve
  78. uint16_t **qmant; ///< quantized mantissas
  79. uint8_t coeff_shift[AC3_MAX_CHANNELS]; ///< fixed-point coefficient shift values
  80. uint8_t new_rematrixing_strategy; ///< send new rematrixing flags in this block
  81. uint8_t rematrixing_flags[4]; ///< rematrixing flags
  82. struct AC3Block *exp_ref_block[AC3_MAX_CHANNELS]; ///< reference blocks for EXP_REUSE
  83. } AC3Block;
  84. /**
  85. * AC-3 encoder private context.
  86. */
  87. typedef struct AC3EncodeContext {
  88. AVClass *av_class; ///< AVClass used for AVOption
  89. AC3EncOptions options; ///< encoding options
  90. PutBitContext pb; ///< bitstream writer context
  91. DSPContext dsp;
  92. AC3DSPContext ac3dsp; ///< AC-3 optimized functions
  93. AC3MDCTContext mdct; ///< MDCT context
  94. AC3Block blocks[AC3_MAX_BLOCKS]; ///< per-block info
  95. int bitstream_id; ///< bitstream id (bsid)
  96. int bitstream_mode; ///< bitstream mode (bsmod)
  97. int bit_rate; ///< target bit rate, in bits-per-second
  98. int sample_rate; ///< sampling frequency, in Hz
  99. int frame_size_min; ///< minimum frame size in case rounding is necessary
  100. int frame_size; ///< current frame size in bytes
  101. int frame_size_code; ///< frame size code (frmsizecod)
  102. uint16_t crc_inv[2];
  103. int bits_written; ///< bit count (used to avg. bitrate)
  104. int samples_written; ///< sample count (used to avg. bitrate)
  105. int fbw_channels; ///< number of full-bandwidth channels (nfchans)
  106. int channels; ///< total number of channels (nchans)
  107. int lfe_on; ///< indicates if there is an LFE channel (lfeon)
  108. int lfe_channel; ///< channel index of the LFE channel
  109. int has_center; ///< indicates if there is a center channel
  110. int has_surround; ///< indicates if there are one or more surround channels
  111. int channel_mode; ///< channel mode (acmod)
  112. const uint8_t *channel_map; ///< channel map used to reorder channels
  113. int center_mix_level; ///< center mix level code
  114. int surround_mix_level; ///< surround mix level code
  115. int ltrt_center_mix_level; ///< Lt/Rt center mix level code
  116. int ltrt_surround_mix_level; ///< Lt/Rt surround mix level code
  117. int loro_center_mix_level; ///< Lo/Ro center mix level code
  118. int loro_surround_mix_level; ///< Lo/Ro surround mix level code
  119. int cutoff; ///< user-specified cutoff frequency, in Hz
  120. int bandwidth_code[AC3_MAX_CHANNELS]; ///< bandwidth code (0 to 60) (chbwcod)
  121. int nb_coefs[AC3_MAX_CHANNELS];
  122. int rematrixing; ///< determines how rematrixing strategy is calculated
  123. int num_rematrixing_bands; ///< number of rematrixing bands
  124. /* bitrate allocation control */
  125. int slow_gain_code; ///< slow gain code (sgaincod)
  126. int slow_decay_code; ///< slow decay code (sdcycod)
  127. int fast_decay_code; ///< fast decay code (fdcycod)
  128. int db_per_bit_code; ///< dB/bit code (dbpbcod)
  129. int floor_code; ///< floor code (floorcod)
  130. AC3BitAllocParameters bit_alloc; ///< bit allocation parameters
  131. int coarse_snr_offset; ///< coarse SNR offsets (csnroffst)
  132. int fast_gain_code[AC3_MAX_CHANNELS]; ///< fast gain codes (signal-to-mask ratio) (fgaincod)
  133. int fine_snr_offset[AC3_MAX_CHANNELS]; ///< fine SNR offsets (fsnroffst)
  134. int frame_bits_fixed; ///< number of non-coefficient bits for fixed parameters
  135. int frame_bits; ///< all frame bits except exponents and mantissas
  136. int exponent_bits; ///< number of bits used for exponents
  137. SampleType **planar_samples;
  138. uint8_t *bap_buffer;
  139. uint8_t *bap1_buffer;
  140. CoefType *mdct_coef_buffer;
  141. int32_t *fixed_coef_buffer;
  142. uint8_t *exp_buffer;
  143. uint8_t *grouped_exp_buffer;
  144. int16_t *psd_buffer;
  145. int16_t *band_psd_buffer;
  146. int16_t *mask_buffer;
  147. uint16_t *qmant_buffer;
  148. uint8_t exp_strategy[AC3_MAX_CHANNELS][AC3_MAX_BLOCKS]; ///< exponent strategies
  149. DECLARE_ALIGNED(32, SampleType, windowed_samples)[AC3_WINDOW_SIZE];
  150. } AC3EncodeContext;
  151. typedef struct AC3Mant {
  152. uint16_t *qmant1_ptr, *qmant2_ptr, *qmant4_ptr; ///< mantissa pointers for bap=1,2,4
  153. int mant1_cnt, mant2_cnt, mant4_cnt; ///< mantissa counts for bap=1,2,4
  154. } AC3Mant;
  155. #define CMIXLEV_NUM_OPTIONS 3
  156. static const float cmixlev_options[CMIXLEV_NUM_OPTIONS] = {
  157. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB
  158. };
  159. #define SURMIXLEV_NUM_OPTIONS 3
  160. static const float surmixlev_options[SURMIXLEV_NUM_OPTIONS] = {
  161. LEVEL_MINUS_3DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  162. };
  163. #define EXTMIXLEV_NUM_OPTIONS 8
  164. static const float extmixlev_options[EXTMIXLEV_NUM_OPTIONS] = {
  165. LEVEL_PLUS_3DB, LEVEL_PLUS_1POINT5DB, LEVEL_ONE, LEVEL_MINUS_4POINT5DB,
  166. LEVEL_MINUS_3DB, LEVEL_MINUS_4POINT5DB, LEVEL_MINUS_6DB, LEVEL_ZERO
  167. };
  168. #define OFFSET(param) offsetof(AC3EncodeContext, options.param)
  169. #define AC3ENC_PARAM (AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_ENCODING_PARAM)
  170. #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
  171. const AVOption ff_ac3_options[] = {
  172. /* Metadata Options */
  173. {"per_frame_metadata", "Allow Changing Metadata Per-Frame", OFFSET(allow_per_frame_metadata), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  174. /* downmix levels */
  175. {"center_mixlev", "Center Mix Level", OFFSET(center_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_4POINT5DB, 0.0, 1.0, AC3ENC_PARAM},
  176. {"surround_mixlev", "Surround Mix Level", OFFSET(surround_mix_level), FF_OPT_TYPE_FLOAT, LEVEL_MINUS_6DB, 0.0, 1.0, AC3ENC_PARAM},
  177. /* audio production information */
  178. {"mixing_level", "Mixing Level", OFFSET(mixing_level), FF_OPT_TYPE_INT, -1, -1, 111, AC3ENC_PARAM},
  179. {"room_type", "Room Type", OFFSET(room_type), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "room_type"},
  180. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  181. {"large", "Large Room", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  182. {"small", "Small Room", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "room_type"},
  183. /* other metadata options */
  184. {"copyright", "Copyright Bit", OFFSET(copyright), FF_OPT_TYPE_INT, 0, 0, 1, AC3ENC_PARAM},
  185. {"dialnorm", "Dialogue Level (dB)", OFFSET(dialogue_level), FF_OPT_TYPE_INT, -31, -31, -1, AC3ENC_PARAM},
  186. {"dsur_mode", "Dolby Surround Mode", OFFSET(dolby_surround_mode), FF_OPT_TYPE_INT, 0, 0, 2, AC3ENC_PARAM, "dsur_mode"},
  187. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  188. {"on", "Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  189. {"off", "Not Dolby Surround Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsur_mode"},
  190. {"original", "Original Bit Stream", OFFSET(original), FF_OPT_TYPE_INT, 1, 0, 1, AC3ENC_PARAM},
  191. /* extended bitstream information */
  192. {"dmix_mode", "Preferred Stereo Downmix Mode", OFFSET(preferred_stereo_downmix), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dmix_mode"},
  193. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  194. {"ltrt", "Lt/Rt Downmix Preferred", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  195. {"loro", "Lo/Ro Downmix Preferred", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dmix_mode"},
  196. {"ltrt_cmixlev", "Lt/Rt Center Mix Level", OFFSET(ltrt_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  197. {"ltrt_surmixlev", "Lt/Rt Surround Mix Level", OFFSET(ltrt_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  198. {"loro_cmixlev", "Lo/Ro Center Mix Level", OFFSET(loro_center_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  199. {"loro_surmixlev", "Lo/Ro Surround Mix Level", OFFSET(loro_surround_mix_level), FF_OPT_TYPE_FLOAT, -1.0, -1.0, 2.0, AC3ENC_PARAM},
  200. {"dsurex_mode", "Dolby Surround EX Mode", OFFSET(dolby_surround_ex_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dsurex_mode"},
  201. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  202. {"on", "Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  203. {"off", "Not Dolby Surround EX Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dsurex_mode"},
  204. {"dheadphone_mode", "Dolby Headphone Mode", OFFSET(dolby_headphone_mode), FF_OPT_TYPE_INT, -1, -1, 2, AC3ENC_PARAM, "dheadphone_mode"},
  205. {"notindicated", "Not Indicated (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  206. {"on", "Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  207. {"off", "Not Dolby Headphone Encoded", 0, FF_OPT_TYPE_CONST, 2, INT_MIN, INT_MAX, AC3ENC_PARAM, "dheadphone_mode"},
  208. {"ad_conv_type", "A/D Converter Type", OFFSET(ad_converter_type), FF_OPT_TYPE_INT, -1, -1, 1, AC3ENC_PARAM, "ad_conv_type"},
  209. {"standard", "Standard (default)", 0, FF_OPT_TYPE_CONST, 0, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  210. {"hdcd", "HDCD", 0, FF_OPT_TYPE_CONST, 1, INT_MIN, INT_MAX, AC3ENC_PARAM, "ad_conv_type"},
  211. {NULL}
  212. };
  213. #endif
  214. #if CONFIG_AC3ENC_FLOAT
  215. static AVClass ac3enc_class = { "AC-3 Encoder", av_default_item_name,
  216. ff_ac3_options, LIBAVUTIL_VERSION_INT };
  217. #else
  218. static AVClass ac3enc_class = { "Fixed-Point AC-3 Encoder", av_default_item_name,
  219. ff_ac3_options, LIBAVUTIL_VERSION_INT };
  220. #endif
  221. /* prototypes for functions in ac3enc_fixed.c and ac3enc_float.c */
  222. static av_cold void mdct_end(AC3MDCTContext *mdct);
  223. static av_cold int mdct_init(AVCodecContext *avctx, AC3MDCTContext *mdct,
  224. int nbits);
  225. static void apply_window(DSPContext *dsp, SampleType *output, const SampleType *input,
  226. const SampleType *window, unsigned int len);
  227. static int normalize_samples(AC3EncodeContext *s);
  228. static void scale_coefficients(AC3EncodeContext *s);
  229. /**
  230. * LUT for number of exponent groups.
  231. * exponent_group_tab[exponent strategy-1][number of coefficients]
  232. */
  233. static uint8_t exponent_group_tab[3][256];
  234. /**
  235. * List of supported channel layouts.
  236. */
  237. #if CONFIG_AC3ENC_FLOAT || !CONFIG_AC3_FLOAT_ENCODER //we need this exactly once compiled in
  238. const int64_t ff_ac3_channel_layouts[] = {
  239. AV_CH_LAYOUT_MONO,
  240. AV_CH_LAYOUT_STEREO,
  241. AV_CH_LAYOUT_2_1,
  242. AV_CH_LAYOUT_SURROUND,
  243. AV_CH_LAYOUT_2_2,
  244. AV_CH_LAYOUT_QUAD,
  245. AV_CH_LAYOUT_4POINT0,
  246. AV_CH_LAYOUT_5POINT0,
  247. AV_CH_LAYOUT_5POINT0_BACK,
  248. (AV_CH_LAYOUT_MONO | AV_CH_LOW_FREQUENCY),
  249. (AV_CH_LAYOUT_STEREO | AV_CH_LOW_FREQUENCY),
  250. (AV_CH_LAYOUT_2_1 | AV_CH_LOW_FREQUENCY),
  251. (AV_CH_LAYOUT_SURROUND | AV_CH_LOW_FREQUENCY),
  252. (AV_CH_LAYOUT_2_2 | AV_CH_LOW_FREQUENCY),
  253. (AV_CH_LAYOUT_QUAD | AV_CH_LOW_FREQUENCY),
  254. (AV_CH_LAYOUT_4POINT0 | AV_CH_LOW_FREQUENCY),
  255. AV_CH_LAYOUT_5POINT1,
  256. AV_CH_LAYOUT_5POINT1_BACK,
  257. 0
  258. };
  259. #endif
  260. /**
  261. * LUT to select the bandwidth code based on the bit rate, sample rate, and
  262. * number of full-bandwidth channels.
  263. * bandwidth_tab[fbw_channels-1][sample rate code][bit rate code]
  264. */
  265. static const uint8_t ac3_bandwidth_tab[5][3][19] = {
  266. // 32 40 48 56 64 80 96 112 128 160 192 224 256 320 384 448 512 576 640
  267. { { 0, 0, 0, 12, 16, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  268. { 0, 0, 0, 16, 20, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  269. { 0, 0, 0, 32, 40, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  270. { { 0, 0, 0, 0, 0, 0, 0, 20, 24, 32, 48, 48, 48, 48, 48, 48, 48, 48, 48 },
  271. { 0, 0, 0, 0, 0, 0, 4, 24, 28, 36, 56, 56, 56, 56, 56, 56, 56, 56, 56 },
  272. { 0, 0, 0, 0, 0, 0, 20, 44, 52, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60 } },
  273. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 24, 32, 40, 48, 48, 48, 48, 48, 48 },
  274. { 0, 0, 0, 0, 0, 0, 0, 0, 4, 20, 28, 36, 44, 56, 56, 56, 56, 56, 56 },
  275. { 0, 0, 0, 0, 0, 0, 0, 0, 20, 40, 48, 60, 60, 60, 60, 60, 60, 60, 60 } },
  276. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 32, 48, 48, 48, 48, 48, 48 },
  277. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 28, 36, 56, 56, 56, 56, 56, 56 },
  278. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 32, 48, 60, 60, 60, 60, 60, 60, 60 } },
  279. { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 20, 32, 40, 48, 48, 48, 48 },
  280. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 24, 36, 44, 56, 56, 56, 56 },
  281. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 28, 44, 60, 60, 60, 60, 60, 60 } }
  282. };
  283. /**
  284. * Adjust the frame size to make the average bit rate match the target bit rate.
  285. * This is only needed for 11025, 22050, and 44100 sample rates.
  286. */
  287. static void adjust_frame_size(AC3EncodeContext *s)
  288. {
  289. while (s->bits_written >= s->bit_rate && s->samples_written >= s->sample_rate) {
  290. s->bits_written -= s->bit_rate;
  291. s->samples_written -= s->sample_rate;
  292. }
  293. s->frame_size = s->frame_size_min +
  294. 2 * (s->bits_written * s->sample_rate < s->samples_written * s->bit_rate);
  295. s->bits_written += s->frame_size * 8;
  296. s->samples_written += AC3_FRAME_SIZE;
  297. }
  298. /**
  299. * Deinterleave input samples.
  300. * Channels are reordered from FFmpeg's default order to AC-3 order.
  301. */
  302. static void deinterleave_input_samples(AC3EncodeContext *s,
  303. const SampleType *samples)
  304. {
  305. int ch, i;
  306. /* deinterleave and remap input samples */
  307. for (ch = 0; ch < s->channels; ch++) {
  308. const SampleType *sptr;
  309. int sinc;
  310. /* copy last 256 samples of previous frame to the start of the current frame */
  311. memcpy(&s->planar_samples[ch][0], &s->planar_samples[ch][AC3_FRAME_SIZE],
  312. AC3_BLOCK_SIZE * sizeof(s->planar_samples[0][0]));
  313. /* deinterleave */
  314. sinc = s->channels;
  315. sptr = samples + s->channel_map[ch];
  316. for (i = AC3_BLOCK_SIZE; i < AC3_FRAME_SIZE+AC3_BLOCK_SIZE; i++) {
  317. s->planar_samples[ch][i] = *sptr;
  318. sptr += sinc;
  319. }
  320. }
  321. }
  322. /**
  323. * Apply the MDCT to input samples to generate frequency coefficients.
  324. * This applies the KBD window and normalizes the input to reduce precision
  325. * loss due to fixed-point calculations.
  326. */
  327. static void apply_mdct(AC3EncodeContext *s)
  328. {
  329. int blk, ch;
  330. for (ch = 0; ch < s->channels; ch++) {
  331. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  332. AC3Block *block = &s->blocks[blk];
  333. const SampleType *input_samples = &s->planar_samples[ch][blk * AC3_BLOCK_SIZE];
  334. apply_window(&s->dsp, s->windowed_samples, input_samples, s->mdct.window, AC3_WINDOW_SIZE);
  335. block->coeff_shift[ch] = normalize_samples(s);
  336. s->mdct.fft.mdct_calcw(&s->mdct.fft, block->mdct_coef[ch],
  337. s->windowed_samples);
  338. }
  339. }
  340. }
  341. /**
  342. * Initialize stereo rematrixing.
  343. * If the strategy does not change for each frame, set the rematrixing flags.
  344. */
  345. static void rematrixing_init(AC3EncodeContext *s)
  346. {
  347. if (s->channel_mode == AC3_CHMODE_STEREO)
  348. s->rematrixing = AC3_REMATRIXING_SUMS;
  349. else
  350. s->rematrixing = AC3_REMATRIXING_NONE;
  351. /* NOTE: AC3_REMATRIXING_ALWAYS might be used in
  352. the future in conjunction with channel coupling. */
  353. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC) {
  354. int flag = (s->rematrixing == AC3_REMATRIXING_ALWAYS);
  355. s->blocks[0].new_rematrixing_strategy = 1;
  356. memset(s->blocks[0].rematrixing_flags, flag,
  357. sizeof(s->blocks[0].rematrixing_flags));
  358. }
  359. }
  360. /**
  361. * Determine rematrixing flags for each block and band.
  362. */
  363. static void compute_rematrixing_strategy(AC3EncodeContext *s)
  364. {
  365. int nb_coefs;
  366. int blk, bnd, i;
  367. AC3Block *block, *block0;
  368. s->num_rematrixing_bands = 4;
  369. if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)
  370. return;
  371. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  372. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  373. block = &s->blocks[blk];
  374. block->new_rematrixing_strategy = !blk;
  375. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  376. /* calculate calculate sum of squared coeffs for one band in one block */
  377. int start = ff_ac3_rematrix_band_tab[bnd];
  378. int end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  379. CoefSumType sum[4] = {0,};
  380. for (i = start; i < end; i++) {
  381. CoefType lt = block->mdct_coef[0][i];
  382. CoefType rt = block->mdct_coef[1][i];
  383. CoefType md = lt + rt;
  384. CoefType sd = lt - rt;
  385. MAC_COEF(sum[0], lt, lt);
  386. MAC_COEF(sum[1], rt, rt);
  387. MAC_COEF(sum[2], md, md);
  388. MAC_COEF(sum[3], sd, sd);
  389. }
  390. /* compare sums to determine if rematrixing will be used for this band */
  391. if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))
  392. block->rematrixing_flags[bnd] = 1;
  393. else
  394. block->rematrixing_flags[bnd] = 0;
  395. /* determine if new rematrixing flags will be sent */
  396. if (blk &&
  397. block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {
  398. block->new_rematrixing_strategy = 1;
  399. }
  400. }
  401. block0 = block;
  402. }
  403. }
  404. /**
  405. * Apply stereo rematrixing to coefficients based on rematrixing flags.
  406. */
  407. static void apply_rematrixing(AC3EncodeContext *s)
  408. {
  409. int nb_coefs;
  410. int blk, bnd, i;
  411. int start, end;
  412. uint8_t *flags;
  413. if (s->rematrixing == AC3_REMATRIXING_NONE)
  414. return;
  415. nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);
  416. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  417. AC3Block *block = &s->blocks[blk];
  418. if (block->new_rematrixing_strategy)
  419. flags = block->rematrixing_flags;
  420. for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {
  421. if (flags[bnd]) {
  422. start = ff_ac3_rematrix_band_tab[bnd];
  423. end = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);
  424. for (i = start; i < end; i++) {
  425. int32_t lt = block->fixed_coef[0][i];
  426. int32_t rt = block->fixed_coef[1][i];
  427. block->fixed_coef[0][i] = (lt + rt) >> 1;
  428. block->fixed_coef[1][i] = (lt - rt) >> 1;
  429. }
  430. }
  431. }
  432. }
  433. }
  434. /**
  435. * Initialize exponent tables.
  436. */
  437. static av_cold void exponent_init(AC3EncodeContext *s)
  438. {
  439. int i;
  440. for (i = 73; i < 256; i++) {
  441. exponent_group_tab[0][i] = (i - 1) / 3;
  442. exponent_group_tab[1][i] = (i + 2) / 6;
  443. exponent_group_tab[2][i] = (i + 8) / 12;
  444. }
  445. /* LFE */
  446. exponent_group_tab[0][7] = 2;
  447. }
  448. /**
  449. * Extract exponents from the MDCT coefficients.
  450. * This takes into account the normalization that was done to the input samples
  451. * by adjusting the exponents by the exponent shift values.
  452. */
  453. static void extract_exponents(AC3EncodeContext *s)
  454. {
  455. int blk, ch;
  456. for (ch = 0; ch < s->channels; ch++) {
  457. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  458. AC3Block *block = &s->blocks[blk];
  459. s->ac3dsp.extract_exponents(block->exp[ch], block->fixed_coef[ch],
  460. AC3_MAX_COEFS);
  461. }
  462. }
  463. }
  464. /**
  465. * Exponent Difference Threshold.
  466. * New exponents are sent if their SAD exceed this number.
  467. */
  468. #define EXP_DIFF_THRESHOLD 500
  469. /**
  470. * Calculate exponent strategies for all blocks in a single channel.
  471. */
  472. static void compute_exp_strategy_ch(AC3EncodeContext *s, uint8_t *exp_strategy,
  473. uint8_t *exp)
  474. {
  475. int blk, blk1;
  476. int exp_diff;
  477. /* estimate if the exponent variation & decide if they should be
  478. reused in the next frame */
  479. exp_strategy[0] = EXP_NEW;
  480. exp += AC3_MAX_COEFS;
  481. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {
  482. exp_diff = s->dsp.sad[0](NULL, exp, exp - AC3_MAX_COEFS, 16, 16);
  483. if (exp_diff > EXP_DIFF_THRESHOLD)
  484. exp_strategy[blk] = EXP_NEW;
  485. else
  486. exp_strategy[blk] = EXP_REUSE;
  487. exp += AC3_MAX_COEFS;
  488. }
  489. /* now select the encoding strategy type : if exponents are often
  490. recoded, we use a coarse encoding */
  491. blk = 0;
  492. while (blk < AC3_MAX_BLOCKS) {
  493. blk1 = blk + 1;
  494. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE)
  495. blk1++;
  496. switch (blk1 - blk) {
  497. case 1: exp_strategy[blk] = EXP_D45; break;
  498. case 2:
  499. case 3: exp_strategy[blk] = EXP_D25; break;
  500. default: exp_strategy[blk] = EXP_D15; break;
  501. }
  502. blk = blk1;
  503. }
  504. }
  505. /**
  506. * Calculate exponent strategies for all channels.
  507. * Array arrangement is reversed to simplify the per-channel calculation.
  508. */
  509. static void compute_exp_strategy(AC3EncodeContext *s)
  510. {
  511. int ch, blk;
  512. for (ch = 0; ch < s->fbw_channels; ch++) {
  513. compute_exp_strategy_ch(s, s->exp_strategy[ch], s->blocks[0].exp[ch]);
  514. }
  515. if (s->lfe_on) {
  516. ch = s->lfe_channel;
  517. s->exp_strategy[ch][0] = EXP_D15;
  518. for (blk = 1; blk < AC3_MAX_BLOCKS; blk++)
  519. s->exp_strategy[ch][blk] = EXP_REUSE;
  520. }
  521. }
  522. /**
  523. * Update the exponents so that they are the ones the decoder will decode.
  524. */
  525. static void encode_exponents_blk_ch(uint8_t *exp, int nb_exps, int exp_strategy)
  526. {
  527. int nb_groups, i, k;
  528. nb_groups = exponent_group_tab[exp_strategy-1][nb_exps] * 3;
  529. /* for each group, compute the minimum exponent */
  530. switch(exp_strategy) {
  531. case EXP_D25:
  532. for (i = 1, k = 1; i <= nb_groups; i++) {
  533. uint8_t exp_min = exp[k];
  534. if (exp[k+1] < exp_min)
  535. exp_min = exp[k+1];
  536. exp[i] = exp_min;
  537. k += 2;
  538. }
  539. break;
  540. case EXP_D45:
  541. for (i = 1, k = 1; i <= nb_groups; i++) {
  542. uint8_t exp_min = exp[k];
  543. if (exp[k+1] < exp_min)
  544. exp_min = exp[k+1];
  545. if (exp[k+2] < exp_min)
  546. exp_min = exp[k+2];
  547. if (exp[k+3] < exp_min)
  548. exp_min = exp[k+3];
  549. exp[i] = exp_min;
  550. k += 4;
  551. }
  552. break;
  553. }
  554. /* constraint for DC exponent */
  555. if (exp[0] > 15)
  556. exp[0] = 15;
  557. /* decrease the delta between each groups to within 2 so that they can be
  558. differentially encoded */
  559. for (i = 1; i <= nb_groups; i++)
  560. exp[i] = FFMIN(exp[i], exp[i-1] + 2);
  561. i--;
  562. while (--i >= 0)
  563. exp[i] = FFMIN(exp[i], exp[i+1] + 2);
  564. /* now we have the exponent values the decoder will see */
  565. switch (exp_strategy) {
  566. case EXP_D25:
  567. for (i = nb_groups, k = nb_groups * 2; i > 0; i--) {
  568. uint8_t exp1 = exp[i];
  569. exp[k--] = exp1;
  570. exp[k--] = exp1;
  571. }
  572. break;
  573. case EXP_D45:
  574. for (i = nb_groups, k = nb_groups * 4; i > 0; i--) {
  575. exp[k] = exp[k-1] = exp[k-2] = exp[k-3] = exp[i];
  576. k -= 4;
  577. }
  578. break;
  579. }
  580. }
  581. /**
  582. * Encode exponents from original extracted form to what the decoder will see.
  583. * This copies and groups exponents based on exponent strategy and reduces
  584. * deltas between adjacent exponent groups so that they can be differentially
  585. * encoded.
  586. */
  587. static void encode_exponents(AC3EncodeContext *s)
  588. {
  589. int blk, blk1, ch;
  590. uint8_t *exp, *exp_strategy;
  591. int nb_coefs, num_reuse_blocks;
  592. for (ch = 0; ch < s->channels; ch++) {
  593. exp = s->blocks[0].exp[ch];
  594. exp_strategy = s->exp_strategy[ch];
  595. nb_coefs = s->nb_coefs[ch];
  596. blk = 0;
  597. while (blk < AC3_MAX_BLOCKS) {
  598. blk1 = blk + 1;
  599. /* count the number of EXP_REUSE blocks after the current block
  600. and set exponent reference block pointers */
  601. s->blocks[blk].exp_ref_block[ch] = &s->blocks[blk];
  602. while (blk1 < AC3_MAX_BLOCKS && exp_strategy[blk1] == EXP_REUSE) {
  603. s->blocks[blk1].exp_ref_block[ch] = &s->blocks[blk];
  604. blk1++;
  605. }
  606. num_reuse_blocks = blk1 - blk - 1;
  607. /* for the EXP_REUSE case we select the min of the exponents */
  608. s->ac3dsp.ac3_exponent_min(exp, num_reuse_blocks, nb_coefs);
  609. encode_exponents_blk_ch(exp, nb_coefs, exp_strategy[blk]);
  610. exp += AC3_MAX_COEFS * (num_reuse_blocks + 1);
  611. blk = blk1;
  612. }
  613. }
  614. }
  615. /**
  616. * Group exponents.
  617. * 3 delta-encoded exponents are in each 7-bit group. The number of groups
  618. * varies depending on exponent strategy and bandwidth.
  619. */
  620. static void group_exponents(AC3EncodeContext *s)
  621. {
  622. int blk, ch, i;
  623. int group_size, nb_groups, bit_count;
  624. uint8_t *p;
  625. int delta0, delta1, delta2;
  626. int exp0, exp1;
  627. bit_count = 0;
  628. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  629. AC3Block *block = &s->blocks[blk];
  630. for (ch = 0; ch < s->channels; ch++) {
  631. int exp_strategy = s->exp_strategy[ch][blk];
  632. if (exp_strategy == EXP_REUSE)
  633. continue;
  634. group_size = exp_strategy + (exp_strategy == EXP_D45);
  635. nb_groups = exponent_group_tab[exp_strategy-1][s->nb_coefs[ch]];
  636. bit_count += 4 + (nb_groups * 7);
  637. p = block->exp[ch];
  638. /* DC exponent */
  639. exp1 = *p++;
  640. block->grouped_exp[ch][0] = exp1;
  641. /* remaining exponents are delta encoded */
  642. for (i = 1; i <= nb_groups; i++) {
  643. /* merge three delta in one code */
  644. exp0 = exp1;
  645. exp1 = p[0];
  646. p += group_size;
  647. delta0 = exp1 - exp0 + 2;
  648. av_assert2(delta0 >= 0 && delta0 <= 4);
  649. exp0 = exp1;
  650. exp1 = p[0];
  651. p += group_size;
  652. delta1 = exp1 - exp0 + 2;
  653. av_assert2(delta1 >= 0 && delta1 <= 4);
  654. exp0 = exp1;
  655. exp1 = p[0];
  656. p += group_size;
  657. delta2 = exp1 - exp0 + 2;
  658. av_assert2(delta2 >= 0 && delta2 <= 4);
  659. block->grouped_exp[ch][i] = ((delta0 * 5 + delta1) * 5) + delta2;
  660. }
  661. }
  662. }
  663. s->exponent_bits = bit_count;
  664. }
  665. /**
  666. * Calculate final exponents from the supplied MDCT coefficients and exponent shift.
  667. * Extract exponents from MDCT coefficients, calculate exponent strategies,
  668. * and encode final exponents.
  669. */
  670. static void process_exponents(AC3EncodeContext *s)
  671. {
  672. extract_exponents(s);
  673. compute_exp_strategy(s);
  674. encode_exponents(s);
  675. group_exponents(s);
  676. emms_c();
  677. }
  678. /**
  679. * Count frame bits that are based solely on fixed parameters.
  680. * This only has to be run once when the encoder is initialized.
  681. */
  682. static void count_frame_bits_fixed(AC3EncodeContext *s)
  683. {
  684. static const int frame_bits_inc[8] = { 0, 0, 2, 2, 2, 4, 2, 4 };
  685. int blk;
  686. int frame_bits;
  687. /* assumptions:
  688. * no dynamic range codes
  689. * no channel coupling
  690. * bit allocation parameters do not change between blocks
  691. * SNR offsets do not change between blocks
  692. * no delta bit allocation
  693. * no skipped data
  694. * no auxilliary data
  695. */
  696. /* header size */
  697. frame_bits = 65;
  698. frame_bits += frame_bits_inc[s->channel_mode];
  699. /* audio blocks */
  700. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  701. frame_bits += s->fbw_channels * 2 + 2; /* blksw * c, dithflag * c, dynrnge, cplstre */
  702. if (s->channel_mode == AC3_CHMODE_STEREO) {
  703. frame_bits++; /* rematstr */
  704. }
  705. frame_bits += 2 * s->fbw_channels; /* chexpstr[2] * c */
  706. if (s->lfe_on)
  707. frame_bits++; /* lfeexpstr */
  708. frame_bits++; /* baie */
  709. frame_bits++; /* snr */
  710. frame_bits += 2; /* delta / skip */
  711. }
  712. frame_bits++; /* cplinu for block 0 */
  713. /* bit alloc info */
  714. /* sdcycod[2], fdcycod[2], sgaincod[2], dbpbcod[2], floorcod[3] */
  715. /* csnroffset[6] */
  716. /* (fsnoffset[4] + fgaincod[4]) * c */
  717. frame_bits += 2*4 + 3 + 6 + s->channels * (4 + 3);
  718. /* auxdatae, crcrsv */
  719. frame_bits += 2;
  720. /* CRC */
  721. frame_bits += 16;
  722. s->frame_bits_fixed = frame_bits;
  723. }
  724. /**
  725. * Initialize bit allocation.
  726. * Set default parameter codes and calculate parameter values.
  727. */
  728. static void bit_alloc_init(AC3EncodeContext *s)
  729. {
  730. int ch;
  731. /* init default parameters */
  732. s->slow_decay_code = 2;
  733. s->fast_decay_code = 1;
  734. s->slow_gain_code = 1;
  735. s->db_per_bit_code = 3;
  736. s->floor_code = 7;
  737. for (ch = 0; ch < s->channels; ch++)
  738. s->fast_gain_code[ch] = 4;
  739. /* initial snr offset */
  740. s->coarse_snr_offset = 40;
  741. /* compute real values */
  742. /* currently none of these values change during encoding, so we can just
  743. set them once at initialization */
  744. s->bit_alloc.slow_decay = ff_ac3_slow_decay_tab[s->slow_decay_code] >> s->bit_alloc.sr_shift;
  745. s->bit_alloc.fast_decay = ff_ac3_fast_decay_tab[s->fast_decay_code] >> s->bit_alloc.sr_shift;
  746. s->bit_alloc.slow_gain = ff_ac3_slow_gain_tab[s->slow_gain_code];
  747. s->bit_alloc.db_per_bit = ff_ac3_db_per_bit_tab[s->db_per_bit_code];
  748. s->bit_alloc.floor = ff_ac3_floor_tab[s->floor_code];
  749. count_frame_bits_fixed(s);
  750. }
  751. /**
  752. * Count the bits used to encode the frame, minus exponents and mantissas.
  753. * Bits based on fixed parameters have already been counted, so now we just
  754. * have to add the bits based on parameters that change during encoding.
  755. */
  756. static void count_frame_bits(AC3EncodeContext *s)
  757. {
  758. AC3EncOptions *opt = &s->options;
  759. int blk, ch;
  760. int frame_bits = 0;
  761. if (opt->audio_production_info)
  762. frame_bits += 7;
  763. if (s->bitstream_id == 6) {
  764. if (opt->extended_bsi_1)
  765. frame_bits += 14;
  766. if (opt->extended_bsi_2)
  767. frame_bits += 14;
  768. }
  769. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  770. /* stereo rematrixing */
  771. if (s->channel_mode == AC3_CHMODE_STEREO &&
  772. s->blocks[blk].new_rematrixing_strategy) {
  773. frame_bits += s->num_rematrixing_bands;
  774. }
  775. for (ch = 0; ch < s->fbw_channels; ch++) {
  776. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  777. frame_bits += 6 + 2; /* chbwcod[6], gainrng[2] */
  778. }
  779. }
  780. s->frame_bits = s->frame_bits_fixed + frame_bits;
  781. }
  782. /**
  783. * Finalize the mantissa bit count by adding in the grouped mantissas.
  784. */
  785. static int compute_mantissa_size_final(int mant_cnt[5])
  786. {
  787. // bap=1 : 3 mantissas in 5 bits
  788. int bits = (mant_cnt[1] / 3) * 5;
  789. // bap=2 : 3 mantissas in 7 bits
  790. // bap=4 : 2 mantissas in 7 bits
  791. bits += ((mant_cnt[2] / 3) + (mant_cnt[4] >> 1)) * 7;
  792. // bap=3 : each mantissa is 3 bits
  793. bits += mant_cnt[3] * 3;
  794. return bits;
  795. }
  796. /**
  797. * Calculate masking curve based on the final exponents.
  798. * Also calculate the power spectral densities to use in future calculations.
  799. */
  800. static void bit_alloc_masking(AC3EncodeContext *s)
  801. {
  802. int blk, ch;
  803. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  804. AC3Block *block = &s->blocks[blk];
  805. for (ch = 0; ch < s->channels; ch++) {
  806. /* We only need psd and mask for calculating bap.
  807. Since we currently do not calculate bap when exponent
  808. strategy is EXP_REUSE we do not need to calculate psd or mask. */
  809. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  810. ff_ac3_bit_alloc_calc_psd(block->exp[ch], 0,
  811. s->nb_coefs[ch],
  812. block->psd[ch], block->band_psd[ch]);
  813. ff_ac3_bit_alloc_calc_mask(&s->bit_alloc, block->band_psd[ch],
  814. 0, s->nb_coefs[ch],
  815. ff_ac3_fast_gain_tab[s->fast_gain_code[ch]],
  816. ch == s->lfe_channel,
  817. DBA_NONE, 0, NULL, NULL, NULL,
  818. block->mask[ch]);
  819. }
  820. }
  821. }
  822. }
  823. /**
  824. * Ensure that bap for each block and channel point to the current bap_buffer.
  825. * They may have been switched during the bit allocation search.
  826. */
  827. static void reset_block_bap(AC3EncodeContext *s)
  828. {
  829. int blk, ch;
  830. if (s->blocks[0].bap[0] == s->bap_buffer)
  831. return;
  832. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  833. for (ch = 0; ch < s->channels; ch++) {
  834. s->blocks[blk].bap[ch] = &s->bap_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  835. }
  836. }
  837. }
  838. /**
  839. * Run the bit allocation with a given SNR offset.
  840. * This calculates the bit allocation pointers that will be used to determine
  841. * the quantization of each mantissa.
  842. * @return the number of bits needed for mantissas if the given SNR offset is
  843. * is used.
  844. */
  845. static int bit_alloc(AC3EncodeContext *s, int snr_offset)
  846. {
  847. int blk, ch;
  848. int mantissa_bits;
  849. int mant_cnt[5];
  850. snr_offset = (snr_offset - 240) << 2;
  851. reset_block_bap(s);
  852. mantissa_bits = 0;
  853. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  854. AC3Block *block;
  855. // initialize grouped mantissa counts. these are set so that they are
  856. // padded to the next whole group size when bits are counted in
  857. // compute_mantissa_size_final
  858. mant_cnt[0] = mant_cnt[3] = 0;
  859. mant_cnt[1] = mant_cnt[2] = 2;
  860. mant_cnt[4] = 1;
  861. for (ch = 0; ch < s->channels; ch++) {
  862. /* Currently the only bit allocation parameters which vary across
  863. blocks within a frame are the exponent values. We can take
  864. advantage of that by reusing the bit allocation pointers
  865. whenever we reuse exponents. */
  866. block = s->blocks[blk].exp_ref_block[ch];
  867. if (s->exp_strategy[ch][blk] != EXP_REUSE) {
  868. s->ac3dsp.bit_alloc_calc_bap(block->mask[ch], block->psd[ch], 0,
  869. s->nb_coefs[ch], snr_offset,
  870. s->bit_alloc.floor, ff_ac3_bap_tab,
  871. block->bap[ch]);
  872. }
  873. mantissa_bits += s->ac3dsp.compute_mantissa_size(mant_cnt, block->bap[ch], s->nb_coefs[ch]);
  874. }
  875. mantissa_bits += compute_mantissa_size_final(mant_cnt);
  876. }
  877. return mantissa_bits;
  878. }
  879. /**
  880. * Constant bitrate bit allocation search.
  881. * Find the largest SNR offset that will allow data to fit in the frame.
  882. */
  883. static int cbr_bit_allocation(AC3EncodeContext *s)
  884. {
  885. int ch;
  886. int bits_left;
  887. int snr_offset, snr_incr;
  888. bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);
  889. av_assert2(bits_left >= 0);
  890. snr_offset = s->coarse_snr_offset << 4;
  891. /* if previous frame SNR offset was 1023, check if current frame can also
  892. use SNR offset of 1023. if so, skip the search. */
  893. if ((snr_offset | s->fine_snr_offset[0]) == 1023) {
  894. if (bit_alloc(s, 1023) <= bits_left)
  895. return 0;
  896. }
  897. while (snr_offset >= 0 &&
  898. bit_alloc(s, snr_offset) > bits_left) {
  899. snr_offset -= 64;
  900. }
  901. if (snr_offset < 0)
  902. return AVERROR(EINVAL);
  903. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  904. for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {
  905. while (snr_offset + snr_incr <= 1023 &&
  906. bit_alloc(s, snr_offset + snr_incr) <= bits_left) {
  907. snr_offset += snr_incr;
  908. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  909. }
  910. }
  911. FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);
  912. reset_block_bap(s);
  913. s->coarse_snr_offset = snr_offset >> 4;
  914. for (ch = 0; ch < s->channels; ch++)
  915. s->fine_snr_offset[ch] = snr_offset & 0xF;
  916. return 0;
  917. }
  918. /**
  919. * Downgrade exponent strategies to reduce the bits used by the exponents.
  920. * This is a fallback for when bit allocation fails with the normal exponent
  921. * strategies. Each time this function is run it only downgrades the
  922. * strategy in 1 channel of 1 block.
  923. * @return non-zero if downgrade was unsuccessful
  924. */
  925. static int downgrade_exponents(AC3EncodeContext *s)
  926. {
  927. int ch, blk;
  928. for (ch = 0; ch < s->fbw_channels; ch++) {
  929. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  930. if (s->exp_strategy[ch][blk] == EXP_D15) {
  931. s->exp_strategy[ch][blk] = EXP_D25;
  932. return 0;
  933. }
  934. }
  935. }
  936. for (ch = 0; ch < s->fbw_channels; ch++) {
  937. for (blk = AC3_MAX_BLOCKS-1; blk >= 0; blk--) {
  938. if (s->exp_strategy[ch][blk] == EXP_D25) {
  939. s->exp_strategy[ch][blk] = EXP_D45;
  940. return 0;
  941. }
  942. }
  943. }
  944. for (ch = 0; ch < s->fbw_channels; ch++) {
  945. /* block 0 cannot reuse exponents, so only downgrade D45 to REUSE if
  946. the block number > 0 */
  947. for (blk = AC3_MAX_BLOCKS-1; blk > 0; blk--) {
  948. if (s->exp_strategy[ch][blk] > EXP_REUSE) {
  949. s->exp_strategy[ch][blk] = EXP_REUSE;
  950. return 0;
  951. }
  952. }
  953. }
  954. return -1;
  955. }
  956. /**
  957. * Reduce the bandwidth to reduce the number of bits used for a given SNR offset.
  958. * This is a second fallback for when bit allocation still fails after exponents
  959. * have been downgraded.
  960. * @return non-zero if bandwidth reduction was unsuccessful
  961. */
  962. static int reduce_bandwidth(AC3EncodeContext *s, int min_bw_code)
  963. {
  964. int ch;
  965. if (s->bandwidth_code[0] > min_bw_code) {
  966. for (ch = 0; ch < s->fbw_channels; ch++) {
  967. s->bandwidth_code[ch]--;
  968. s->nb_coefs[ch] = s->bandwidth_code[ch] * 3 + 73;
  969. }
  970. return 0;
  971. }
  972. return -1;
  973. }
  974. /**
  975. * Perform bit allocation search.
  976. * Finds the SNR offset value that maximizes quality and fits in the specified
  977. * frame size. Output is the SNR offset and a set of bit allocation pointers
  978. * used to quantize the mantissas.
  979. */
  980. static int compute_bit_allocation(AC3EncodeContext *s)
  981. {
  982. int ret;
  983. count_frame_bits(s);
  984. bit_alloc_masking(s);
  985. ret = cbr_bit_allocation(s);
  986. while (ret) {
  987. /* fallback 1: downgrade exponents */
  988. if (!downgrade_exponents(s)) {
  989. extract_exponents(s);
  990. encode_exponents(s);
  991. group_exponents(s);
  992. ret = compute_bit_allocation(s);
  993. continue;
  994. }
  995. /* fallback 2: reduce bandwidth */
  996. /* only do this if the user has not specified a specific cutoff
  997. frequency */
  998. if (!s->cutoff && !reduce_bandwidth(s, 0)) {
  999. process_exponents(s);
  1000. ret = compute_bit_allocation(s);
  1001. continue;
  1002. }
  1003. /* fallbacks were not enough... */
  1004. break;
  1005. }
  1006. return ret;
  1007. }
  1008. /**
  1009. * Symmetric quantization on 'levels' levels.
  1010. */
  1011. static inline int sym_quant(int c, int e, int levels)
  1012. {
  1013. int v = (((levels * c) >> (24 - e)) + levels) >> 1;
  1014. av_assert2(v >= 0 && v < levels);
  1015. return v;
  1016. }
  1017. /**
  1018. * Asymmetric quantization on 2^qbits levels.
  1019. */
  1020. static inline int asym_quant(int c, int e, int qbits)
  1021. {
  1022. int lshift, m, v;
  1023. lshift = e + qbits - 24;
  1024. if (lshift >= 0)
  1025. v = c << lshift;
  1026. else
  1027. v = c >> (-lshift);
  1028. /* rounding */
  1029. v = (v + 1) >> 1;
  1030. m = (1 << (qbits-1));
  1031. if (v >= m)
  1032. v = m - 1;
  1033. av_assert2(v >= -m);
  1034. return v & ((1 << qbits)-1);
  1035. }
  1036. /**
  1037. * Quantize a set of mantissas for a single channel in a single block.
  1038. */
  1039. static void quantize_mantissas_blk_ch(AC3Mant *s, int32_t *fixed_coef,
  1040. uint8_t *exp,
  1041. uint8_t *bap, uint16_t *qmant, int n)
  1042. {
  1043. int i;
  1044. for (i = 0; i < n; i++) {
  1045. int v;
  1046. int c = fixed_coef[i];
  1047. int e = exp[i];
  1048. int b = bap[i];
  1049. switch (b) {
  1050. case 0:
  1051. v = 0;
  1052. break;
  1053. case 1:
  1054. v = sym_quant(c, e, 3);
  1055. switch (s->mant1_cnt) {
  1056. case 0:
  1057. s->qmant1_ptr = &qmant[i];
  1058. v = 9 * v;
  1059. s->mant1_cnt = 1;
  1060. break;
  1061. case 1:
  1062. *s->qmant1_ptr += 3 * v;
  1063. s->mant1_cnt = 2;
  1064. v = 128;
  1065. break;
  1066. default:
  1067. *s->qmant1_ptr += v;
  1068. s->mant1_cnt = 0;
  1069. v = 128;
  1070. break;
  1071. }
  1072. break;
  1073. case 2:
  1074. v = sym_quant(c, e, 5);
  1075. switch (s->mant2_cnt) {
  1076. case 0:
  1077. s->qmant2_ptr = &qmant[i];
  1078. v = 25 * v;
  1079. s->mant2_cnt = 1;
  1080. break;
  1081. case 1:
  1082. *s->qmant2_ptr += 5 * v;
  1083. s->mant2_cnt = 2;
  1084. v = 128;
  1085. break;
  1086. default:
  1087. *s->qmant2_ptr += v;
  1088. s->mant2_cnt = 0;
  1089. v = 128;
  1090. break;
  1091. }
  1092. break;
  1093. case 3:
  1094. v = sym_quant(c, e, 7);
  1095. break;
  1096. case 4:
  1097. v = sym_quant(c, e, 11);
  1098. switch (s->mant4_cnt) {
  1099. case 0:
  1100. s->qmant4_ptr = &qmant[i];
  1101. v = 11 * v;
  1102. s->mant4_cnt = 1;
  1103. break;
  1104. default:
  1105. *s->qmant4_ptr += v;
  1106. s->mant4_cnt = 0;
  1107. v = 128;
  1108. break;
  1109. }
  1110. break;
  1111. case 5:
  1112. v = sym_quant(c, e, 15);
  1113. break;
  1114. case 14:
  1115. v = asym_quant(c, e, 14);
  1116. break;
  1117. case 15:
  1118. v = asym_quant(c, e, 16);
  1119. break;
  1120. default:
  1121. v = asym_quant(c, e, b - 1);
  1122. break;
  1123. }
  1124. qmant[i] = v;
  1125. }
  1126. }
  1127. /**
  1128. * Quantize mantissas using coefficients, exponents, and bit allocation pointers.
  1129. */
  1130. static void quantize_mantissas(AC3EncodeContext *s)
  1131. {
  1132. int blk, ch;
  1133. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1134. AC3Block *block = &s->blocks[blk];
  1135. AC3Block *ref_block;
  1136. AC3Mant m = { 0 };
  1137. for (ch = 0; ch < s->channels; ch++) {
  1138. ref_block = block->exp_ref_block[ch];
  1139. quantize_mantissas_blk_ch(&m, block->fixed_coef[ch],
  1140. ref_block->exp[ch], ref_block->bap[ch],
  1141. block->qmant[ch], s->nb_coefs[ch]);
  1142. }
  1143. }
  1144. }
  1145. /**
  1146. * Write the AC-3 frame header to the output bitstream.
  1147. */
  1148. static void output_frame_header(AC3EncodeContext *s)
  1149. {
  1150. AC3EncOptions *opt = &s->options;
  1151. put_bits(&s->pb, 16, 0x0b77); /* frame header */
  1152. put_bits(&s->pb, 16, 0); /* crc1: will be filled later */
  1153. put_bits(&s->pb, 2, s->bit_alloc.sr_code);
  1154. put_bits(&s->pb, 6, s->frame_size_code + (s->frame_size - s->frame_size_min) / 2);
  1155. put_bits(&s->pb, 5, s->bitstream_id);
  1156. put_bits(&s->pb, 3, s->bitstream_mode);
  1157. put_bits(&s->pb, 3, s->channel_mode);
  1158. if ((s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO)
  1159. put_bits(&s->pb, 2, s->center_mix_level);
  1160. if (s->channel_mode & 0x04)
  1161. put_bits(&s->pb, 2, s->surround_mix_level);
  1162. if (s->channel_mode == AC3_CHMODE_STEREO)
  1163. put_bits(&s->pb, 2, opt->dolby_surround_mode);
  1164. put_bits(&s->pb, 1, s->lfe_on); /* LFE */
  1165. put_bits(&s->pb, 5, -opt->dialogue_level);
  1166. put_bits(&s->pb, 1, 0); /* no compression control word */
  1167. put_bits(&s->pb, 1, 0); /* no lang code */
  1168. put_bits(&s->pb, 1, opt->audio_production_info);
  1169. if (opt->audio_production_info) {
  1170. put_bits(&s->pb, 5, opt->mixing_level - 80);
  1171. put_bits(&s->pb, 2, opt->room_type);
  1172. }
  1173. put_bits(&s->pb, 1, opt->copyright);
  1174. put_bits(&s->pb, 1, opt->original);
  1175. if (s->bitstream_id == 6) {
  1176. /* alternate bit stream syntax */
  1177. put_bits(&s->pb, 1, opt->extended_bsi_1);
  1178. if (opt->extended_bsi_1) {
  1179. put_bits(&s->pb, 2, opt->preferred_stereo_downmix);
  1180. put_bits(&s->pb, 3, s->ltrt_center_mix_level);
  1181. put_bits(&s->pb, 3, s->ltrt_surround_mix_level);
  1182. put_bits(&s->pb, 3, s->loro_center_mix_level);
  1183. put_bits(&s->pb, 3, s->loro_surround_mix_level);
  1184. }
  1185. put_bits(&s->pb, 1, opt->extended_bsi_2);
  1186. if (opt->extended_bsi_2) {
  1187. put_bits(&s->pb, 2, opt->dolby_surround_ex_mode);
  1188. put_bits(&s->pb, 2, opt->dolby_headphone_mode);
  1189. put_bits(&s->pb, 1, opt->ad_converter_type);
  1190. put_bits(&s->pb, 9, 0); /* xbsi2 and encinfo : reserved */
  1191. }
  1192. } else {
  1193. put_bits(&s->pb, 1, 0); /* no time code 1 */
  1194. put_bits(&s->pb, 1, 0); /* no time code 2 */
  1195. }
  1196. put_bits(&s->pb, 1, 0); /* no additional bit stream info */
  1197. }
  1198. /**
  1199. * Write one audio block to the output bitstream.
  1200. */
  1201. static void output_audio_block(AC3EncodeContext *s, int blk)
  1202. {
  1203. int ch, i, baie, rbnd;
  1204. AC3Block *block = &s->blocks[blk];
  1205. /* block switching */
  1206. for (ch = 0; ch < s->fbw_channels; ch++)
  1207. put_bits(&s->pb, 1, 0);
  1208. /* dither flags */
  1209. for (ch = 0; ch < s->fbw_channels; ch++)
  1210. put_bits(&s->pb, 1, 1);
  1211. /* dynamic range codes */
  1212. put_bits(&s->pb, 1, 0);
  1213. /* channel coupling */
  1214. if (!blk) {
  1215. put_bits(&s->pb, 1, 1); /* coupling strategy present */
  1216. put_bits(&s->pb, 1, 0); /* no coupling strategy */
  1217. } else {
  1218. put_bits(&s->pb, 1, 0); /* no new coupling strategy */
  1219. }
  1220. /* stereo rematrixing */
  1221. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1222. put_bits(&s->pb, 1, block->new_rematrixing_strategy);
  1223. if (block->new_rematrixing_strategy) {
  1224. /* rematrixing flags */
  1225. for (rbnd = 0; rbnd < s->num_rematrixing_bands; rbnd++)
  1226. put_bits(&s->pb, 1, block->rematrixing_flags[rbnd]);
  1227. }
  1228. }
  1229. /* exponent strategy */
  1230. for (ch = 0; ch < s->fbw_channels; ch++)
  1231. put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);
  1232. if (s->lfe_on)
  1233. put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);
  1234. /* bandwidth */
  1235. for (ch = 0; ch < s->fbw_channels; ch++) {
  1236. if (s->exp_strategy[ch][blk] != EXP_REUSE)
  1237. put_bits(&s->pb, 6, s->bandwidth_code[ch]);
  1238. }
  1239. /* exponents */
  1240. for (ch = 0; ch < s->channels; ch++) {
  1241. int nb_groups;
  1242. if (s->exp_strategy[ch][blk] == EXP_REUSE)
  1243. continue;
  1244. /* DC exponent */
  1245. put_bits(&s->pb, 4, block->grouped_exp[ch][0]);
  1246. /* exponent groups */
  1247. nb_groups = exponent_group_tab[s->exp_strategy[ch][blk]-1][s->nb_coefs[ch]];
  1248. for (i = 1; i <= nb_groups; i++)
  1249. put_bits(&s->pb, 7, block->grouped_exp[ch][i]);
  1250. /* gain range info */
  1251. if (ch != s->lfe_channel)
  1252. put_bits(&s->pb, 2, 0);
  1253. }
  1254. /* bit allocation info */
  1255. baie = (blk == 0);
  1256. put_bits(&s->pb, 1, baie);
  1257. if (baie) {
  1258. put_bits(&s->pb, 2, s->slow_decay_code);
  1259. put_bits(&s->pb, 2, s->fast_decay_code);
  1260. put_bits(&s->pb, 2, s->slow_gain_code);
  1261. put_bits(&s->pb, 2, s->db_per_bit_code);
  1262. put_bits(&s->pb, 3, s->floor_code);
  1263. }
  1264. /* snr offset */
  1265. put_bits(&s->pb, 1, baie);
  1266. if (baie) {
  1267. put_bits(&s->pb, 6, s->coarse_snr_offset);
  1268. for (ch = 0; ch < s->channels; ch++) {
  1269. put_bits(&s->pb, 4, s->fine_snr_offset[ch]);
  1270. put_bits(&s->pb, 3, s->fast_gain_code[ch]);
  1271. }
  1272. }
  1273. put_bits(&s->pb, 1, 0); /* no delta bit allocation */
  1274. put_bits(&s->pb, 1, 0); /* no data to skip */
  1275. /* mantissas */
  1276. for (ch = 0; ch < s->channels; ch++) {
  1277. int b, q;
  1278. AC3Block *ref_block = block->exp_ref_block[ch];
  1279. for (i = 0; i < s->nb_coefs[ch]; i++) {
  1280. q = block->qmant[ch][i];
  1281. b = ref_block->bap[ch][i];
  1282. switch (b) {
  1283. case 0: break;
  1284. case 1: if (q != 128) put_bits(&s->pb, 5, q); break;
  1285. case 2: if (q != 128) put_bits(&s->pb, 7, q); break;
  1286. case 3: put_bits(&s->pb, 3, q); break;
  1287. case 4: if (q != 128) put_bits(&s->pb, 7, q); break;
  1288. case 14: put_bits(&s->pb, 14, q); break;
  1289. case 15: put_bits(&s->pb, 16, q); break;
  1290. default: put_bits(&s->pb, b-1, q); break;
  1291. }
  1292. }
  1293. }
  1294. }
  1295. /** CRC-16 Polynomial */
  1296. #define CRC16_POLY ((1 << 0) | (1 << 2) | (1 << 15) | (1 << 16))
  1297. static unsigned int mul_poly(unsigned int a, unsigned int b, unsigned int poly)
  1298. {
  1299. unsigned int c;
  1300. c = 0;
  1301. while (a) {
  1302. if (a & 1)
  1303. c ^= b;
  1304. a = a >> 1;
  1305. b = b << 1;
  1306. if (b & (1 << 16))
  1307. b ^= poly;
  1308. }
  1309. return c;
  1310. }
  1311. static unsigned int pow_poly(unsigned int a, unsigned int n, unsigned int poly)
  1312. {
  1313. unsigned int r;
  1314. r = 1;
  1315. while (n) {
  1316. if (n & 1)
  1317. r = mul_poly(r, a, poly);
  1318. a = mul_poly(a, a, poly);
  1319. n >>= 1;
  1320. }
  1321. return r;
  1322. }
  1323. /**
  1324. * Fill the end of the frame with 0's and compute the two CRCs.
  1325. */
  1326. static void output_frame_end(AC3EncodeContext *s)
  1327. {
  1328. const AVCRC *crc_ctx = av_crc_get_table(AV_CRC_16_ANSI);
  1329. int frame_size_58, pad_bytes, crc1, crc2_partial, crc2, crc_inv;
  1330. uint8_t *frame;
  1331. frame_size_58 = ((s->frame_size >> 2) + (s->frame_size >> 4)) << 1;
  1332. /* pad the remainder of the frame with zeros */
  1333. av_assert2(s->frame_size * 8 - put_bits_count(&s->pb) >= 18);
  1334. flush_put_bits(&s->pb);
  1335. frame = s->pb.buf;
  1336. pad_bytes = s->frame_size - (put_bits_ptr(&s->pb) - frame) - 2;
  1337. av_assert2(pad_bytes >= 0);
  1338. if (pad_bytes > 0)
  1339. memset(put_bits_ptr(&s->pb), 0, pad_bytes);
  1340. /* compute crc1 */
  1341. /* this is not so easy because it is at the beginning of the data... */
  1342. crc1 = av_bswap16(av_crc(crc_ctx, 0, frame + 4, frame_size_58 - 4));
  1343. crc_inv = s->crc_inv[s->frame_size > s->frame_size_min];
  1344. crc1 = mul_poly(crc_inv, crc1, CRC16_POLY);
  1345. AV_WB16(frame + 2, crc1);
  1346. /* compute crc2 */
  1347. crc2_partial = av_crc(crc_ctx, 0, frame + frame_size_58,
  1348. s->frame_size - frame_size_58 - 3);
  1349. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1350. /* ensure crc2 does not match sync word by flipping crcrsv bit if needed */
  1351. if (crc2 == 0x770B) {
  1352. frame[s->frame_size - 3] ^= 0x1;
  1353. crc2 = av_crc(crc_ctx, crc2_partial, frame + s->frame_size - 3, 1);
  1354. }
  1355. crc2 = av_bswap16(crc2);
  1356. AV_WB16(frame + s->frame_size - 2, crc2);
  1357. }
  1358. /**
  1359. * Write the frame to the output bitstream.
  1360. */
  1361. static void output_frame(AC3EncodeContext *s, unsigned char *frame)
  1362. {
  1363. int blk;
  1364. init_put_bits(&s->pb, frame, AC3_MAX_CODED_FRAME_SIZE);
  1365. output_frame_header(s);
  1366. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)
  1367. output_audio_block(s, blk);
  1368. output_frame_end(s);
  1369. }
  1370. static void dprint_options(AVCodecContext *avctx)
  1371. {
  1372. #ifdef DEBUG
  1373. AC3EncodeContext *s = avctx->priv_data;
  1374. AC3EncOptions *opt = &s->options;
  1375. char strbuf[32];
  1376. switch (s->bitstream_id) {
  1377. case 6: strncpy(strbuf, "AC-3 (alt syntax)", 32); break;
  1378. case 8: strncpy(strbuf, "AC-3 (standard)", 32); break;
  1379. case 9: strncpy(strbuf, "AC-3 (dnet half-rate)", 32); break;
  1380. case 10: strncpy(strbuf, "AC-3 (dnet quater-rate", 32); break;
  1381. default: snprintf(strbuf, 32, "ERROR");
  1382. }
  1383. av_dlog(avctx, "bitstream_id: %s (%d)\n", strbuf, s->bitstream_id);
  1384. av_dlog(avctx, "sample_fmt: %s\n", av_get_sample_fmt_name(avctx->sample_fmt));
  1385. av_get_channel_layout_string(strbuf, 32, s->channels, avctx->channel_layout);
  1386. av_dlog(avctx, "channel_layout: %s\n", strbuf);
  1387. av_dlog(avctx, "sample_rate: %d\n", s->sample_rate);
  1388. av_dlog(avctx, "bit_rate: %d\n", s->bit_rate);
  1389. if (s->cutoff)
  1390. av_dlog(avctx, "cutoff: %d\n", s->cutoff);
  1391. av_dlog(avctx, "per_frame_metadata: %s\n",
  1392. opt->allow_per_frame_metadata?"on":"off");
  1393. if (s->has_center)
  1394. av_dlog(avctx, "center_mixlev: %0.3f (%d)\n", opt->center_mix_level,
  1395. s->center_mix_level);
  1396. else
  1397. av_dlog(avctx, "center_mixlev: {not written}\n");
  1398. if (s->has_surround)
  1399. av_dlog(avctx, "surround_mixlev: %0.3f (%d)\n", opt->surround_mix_level,
  1400. s->surround_mix_level);
  1401. else
  1402. av_dlog(avctx, "surround_mixlev: {not written}\n");
  1403. if (opt->audio_production_info) {
  1404. av_dlog(avctx, "mixing_level: %ddB\n", opt->mixing_level);
  1405. switch (opt->room_type) {
  1406. case 0: strncpy(strbuf, "notindicated", 32); break;
  1407. case 1: strncpy(strbuf, "large", 32); break;
  1408. case 2: strncpy(strbuf, "small", 32); break;
  1409. default: snprintf(strbuf, 32, "ERROR (%d)", opt->room_type);
  1410. }
  1411. av_dlog(avctx, "room_type: %s\n", strbuf);
  1412. } else {
  1413. av_dlog(avctx, "mixing_level: {not written}\n");
  1414. av_dlog(avctx, "room_type: {not written}\n");
  1415. }
  1416. av_dlog(avctx, "copyright: %s\n", opt->copyright?"on":"off");
  1417. av_dlog(avctx, "dialnorm: %ddB\n", opt->dialogue_level);
  1418. if (s->channel_mode == AC3_CHMODE_STEREO) {
  1419. switch (opt->dolby_surround_mode) {
  1420. case 0: strncpy(strbuf, "notindicated", 32); break;
  1421. case 1: strncpy(strbuf, "on", 32); break;
  1422. case 2: strncpy(strbuf, "off", 32); break;
  1423. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_mode);
  1424. }
  1425. av_dlog(avctx, "dsur_mode: %s\n", strbuf);
  1426. } else {
  1427. av_dlog(avctx, "dsur_mode: {not written}\n");
  1428. }
  1429. av_dlog(avctx, "original: %s\n", opt->original?"on":"off");
  1430. if (s->bitstream_id == 6) {
  1431. if (opt->extended_bsi_1) {
  1432. switch (opt->preferred_stereo_downmix) {
  1433. case 0: strncpy(strbuf, "notindicated", 32); break;
  1434. case 1: strncpy(strbuf, "ltrt", 32); break;
  1435. case 2: strncpy(strbuf, "loro", 32); break;
  1436. default: snprintf(strbuf, 32, "ERROR (%d)", opt->preferred_stereo_downmix);
  1437. }
  1438. av_dlog(avctx, "dmix_mode: %s\n", strbuf);
  1439. av_dlog(avctx, "ltrt_cmixlev: %0.3f (%d)\n",
  1440. opt->ltrt_center_mix_level, s->ltrt_center_mix_level);
  1441. av_dlog(avctx, "ltrt_surmixlev: %0.3f (%d)\n",
  1442. opt->ltrt_surround_mix_level, s->ltrt_surround_mix_level);
  1443. av_dlog(avctx, "loro_cmixlev: %0.3f (%d)\n",
  1444. opt->loro_center_mix_level, s->loro_center_mix_level);
  1445. av_dlog(avctx, "loro_surmixlev: %0.3f (%d)\n",
  1446. opt->loro_surround_mix_level, s->loro_surround_mix_level);
  1447. } else {
  1448. av_dlog(avctx, "extended bitstream info 1: {not written}\n");
  1449. }
  1450. if (opt->extended_bsi_2) {
  1451. switch (opt->dolby_surround_ex_mode) {
  1452. case 0: strncpy(strbuf, "notindicated", 32); break;
  1453. case 1: strncpy(strbuf, "on", 32); break;
  1454. case 2: strncpy(strbuf, "off", 32); break;
  1455. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_surround_ex_mode);
  1456. }
  1457. av_dlog(avctx, "dsurex_mode: %s\n", strbuf);
  1458. switch (opt->dolby_headphone_mode) {
  1459. case 0: strncpy(strbuf, "notindicated", 32); break;
  1460. case 1: strncpy(strbuf, "on", 32); break;
  1461. case 2: strncpy(strbuf, "off", 32); break;
  1462. default: snprintf(strbuf, 32, "ERROR (%d)", opt->dolby_headphone_mode);
  1463. }
  1464. av_dlog(avctx, "dheadphone_mode: %s\n", strbuf);
  1465. switch (opt->ad_converter_type) {
  1466. case 0: strncpy(strbuf, "standard", 32); break;
  1467. case 1: strncpy(strbuf, "hdcd", 32); break;
  1468. default: snprintf(strbuf, 32, "ERROR (%d)", opt->ad_converter_type);
  1469. }
  1470. av_dlog(avctx, "ad_conv_type: %s\n", strbuf);
  1471. } else {
  1472. av_dlog(avctx, "extended bitstream info 2: {not written}\n");
  1473. }
  1474. }
  1475. #endif
  1476. }
  1477. #define FLT_OPTION_THRESHOLD 0.01
  1478. static int validate_float_option(float v, const float *v_list, int v_list_size)
  1479. {
  1480. int i;
  1481. for (i = 0; i < v_list_size; i++) {
  1482. if (v < (v_list[i] + FLT_OPTION_THRESHOLD) &&
  1483. v > (v_list[i] - FLT_OPTION_THRESHOLD))
  1484. break;
  1485. }
  1486. if (i == v_list_size)
  1487. return -1;
  1488. return i;
  1489. }
  1490. static void validate_mix_level(void *log_ctx, const char *opt_name,
  1491. float *opt_param, const float *list,
  1492. int list_size, int default_value, int min_value,
  1493. int *ctx_param)
  1494. {
  1495. int mixlev = validate_float_option(*opt_param, list, list_size);
  1496. if (mixlev < min_value) {
  1497. mixlev = default_value;
  1498. if (*opt_param >= 0.0) {
  1499. av_log(log_ctx, AV_LOG_WARNING, "requested %s is not valid. using "
  1500. "default value: %0.3f\n", opt_name, list[mixlev]);
  1501. }
  1502. }
  1503. *opt_param = list[mixlev];
  1504. *ctx_param = mixlev;
  1505. }
  1506. /**
  1507. * Validate metadata options as set by AVOption system.
  1508. * These values can optionally be changed per-frame.
  1509. */
  1510. static int validate_metadata(AVCodecContext *avctx)
  1511. {
  1512. AC3EncodeContext *s = avctx->priv_data;
  1513. AC3EncOptions *opt = &s->options;
  1514. /* validate mixing levels */
  1515. if (s->has_center) {
  1516. validate_mix_level(avctx, "center_mix_level", &opt->center_mix_level,
  1517. cmixlev_options, CMIXLEV_NUM_OPTIONS, 1, 0,
  1518. &s->center_mix_level);
  1519. }
  1520. if (s->has_surround) {
  1521. validate_mix_level(avctx, "surround_mix_level", &opt->surround_mix_level,
  1522. surmixlev_options, SURMIXLEV_NUM_OPTIONS, 1, 0,
  1523. &s->surround_mix_level);
  1524. }
  1525. /* set audio production info flag */
  1526. if (opt->mixing_level >= 0 || opt->room_type >= 0) {
  1527. if (opt->mixing_level < 0) {
  1528. av_log(avctx, AV_LOG_ERROR, "mixing_level must be set if "
  1529. "room_type is set\n");
  1530. return AVERROR(EINVAL);
  1531. }
  1532. if (opt->mixing_level < 80) {
  1533. av_log(avctx, AV_LOG_ERROR, "invalid mixing level. must be between "
  1534. "80dB and 111dB\n");
  1535. return AVERROR(EINVAL);
  1536. }
  1537. /* default room type */
  1538. if (opt->room_type < 0)
  1539. opt->room_type = 0;
  1540. opt->audio_production_info = 1;
  1541. } else {
  1542. opt->audio_production_info = 0;
  1543. }
  1544. /* set extended bsi 1 flag */
  1545. if ((s->has_center || s->has_surround) &&
  1546. (opt->preferred_stereo_downmix >= 0 ||
  1547. opt->ltrt_center_mix_level >= 0 ||
  1548. opt->ltrt_surround_mix_level >= 0 ||
  1549. opt->loro_center_mix_level >= 0 ||
  1550. opt->loro_surround_mix_level >= 0)) {
  1551. /* default preferred stereo downmix */
  1552. if (opt->preferred_stereo_downmix < 0)
  1553. opt->preferred_stereo_downmix = 0;
  1554. /* validate Lt/Rt center mix level */
  1555. validate_mix_level(avctx, "ltrt_center_mix_level",
  1556. &opt->ltrt_center_mix_level, extmixlev_options,
  1557. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1558. &s->ltrt_center_mix_level);
  1559. /* validate Lt/Rt surround mix level */
  1560. validate_mix_level(avctx, "ltrt_surround_mix_level",
  1561. &opt->ltrt_surround_mix_level, extmixlev_options,
  1562. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1563. &s->ltrt_surround_mix_level);
  1564. /* validate Lo/Ro center mix level */
  1565. validate_mix_level(avctx, "loro_center_mix_level",
  1566. &opt->loro_center_mix_level, extmixlev_options,
  1567. EXTMIXLEV_NUM_OPTIONS, 5, 0,
  1568. &s->loro_center_mix_level);
  1569. /* validate Lo/Ro surround mix level */
  1570. validate_mix_level(avctx, "loro_surround_mix_level",
  1571. &opt->loro_surround_mix_level, extmixlev_options,
  1572. EXTMIXLEV_NUM_OPTIONS, 6, 3,
  1573. &s->loro_surround_mix_level);
  1574. opt->extended_bsi_1 = 1;
  1575. } else {
  1576. opt->extended_bsi_1 = 0;
  1577. }
  1578. /* set extended bsi 2 flag */
  1579. if (opt->dolby_surround_ex_mode >= 0 ||
  1580. opt->dolby_headphone_mode >= 0 ||
  1581. opt->ad_converter_type >= 0) {
  1582. /* default dolby surround ex mode */
  1583. if (opt->dolby_surround_ex_mode < 0)
  1584. opt->dolby_surround_ex_mode = 0;
  1585. /* default dolby headphone mode */
  1586. if (opt->dolby_headphone_mode < 0)
  1587. opt->dolby_headphone_mode = 0;
  1588. /* default A/D converter type */
  1589. if (opt->ad_converter_type < 0)
  1590. opt->ad_converter_type = 0;
  1591. opt->extended_bsi_2 = 1;
  1592. } else {
  1593. opt->extended_bsi_2 = 0;
  1594. }
  1595. /* set bitstream id for alternate bitstream syntax */
  1596. if (opt->extended_bsi_1 || opt->extended_bsi_2) {
  1597. if (s->bitstream_id > 8 && s->bitstream_id < 11) {
  1598. static int warn_once = 1;
  1599. if (warn_once) {
  1600. av_log(avctx, AV_LOG_WARNING, "alternate bitstream syntax is "
  1601. "not compatible with reduced samplerates. writing of "
  1602. "extended bitstream information will be disabled.\n");
  1603. warn_once = 0;
  1604. }
  1605. } else {
  1606. s->bitstream_id = 6;
  1607. }
  1608. }
  1609. return 0;
  1610. }
  1611. /**
  1612. * Encode a single AC-3 frame.
  1613. */
  1614. static int ac3_encode_frame(AVCodecContext *avctx, unsigned char *frame,
  1615. int buf_size, void *data)
  1616. {
  1617. AC3EncodeContext *s = avctx->priv_data;
  1618. const SampleType *samples = data;
  1619. int ret;
  1620. if (s->options.allow_per_frame_metadata) {
  1621. ret = validate_metadata(avctx);
  1622. if (ret)
  1623. return ret;
  1624. }
  1625. if (s->bit_alloc.sr_code == 1)
  1626. adjust_frame_size(s);
  1627. deinterleave_input_samples(s, samples);
  1628. apply_mdct(s);
  1629. scale_coefficients(s);
  1630. compute_rematrixing_strategy(s);
  1631. apply_rematrixing(s);
  1632. process_exponents(s);
  1633. ret = compute_bit_allocation(s);
  1634. if (ret) {
  1635. av_log(avctx, AV_LOG_ERROR, "Bit allocation failed. Try increasing the bitrate.\n");
  1636. return ret;
  1637. }
  1638. quantize_mantissas(s);
  1639. output_frame(s, frame);
  1640. return s->frame_size;
  1641. }
  1642. /**
  1643. * Finalize encoding and free any memory allocated by the encoder.
  1644. */
  1645. static av_cold int ac3_encode_close(AVCodecContext *avctx)
  1646. {
  1647. int blk, ch;
  1648. AC3EncodeContext *s = avctx->priv_data;
  1649. for (ch = 0; ch < s->channels; ch++)
  1650. av_freep(&s->planar_samples[ch]);
  1651. av_freep(&s->planar_samples);
  1652. av_freep(&s->bap_buffer);
  1653. av_freep(&s->bap1_buffer);
  1654. av_freep(&s->mdct_coef_buffer);
  1655. av_freep(&s->fixed_coef_buffer);
  1656. av_freep(&s->exp_buffer);
  1657. av_freep(&s->grouped_exp_buffer);
  1658. av_freep(&s->psd_buffer);
  1659. av_freep(&s->band_psd_buffer);
  1660. av_freep(&s->mask_buffer);
  1661. av_freep(&s->qmant_buffer);
  1662. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1663. AC3Block *block = &s->blocks[blk];
  1664. av_freep(&block->bap);
  1665. av_freep(&block->mdct_coef);
  1666. av_freep(&block->fixed_coef);
  1667. av_freep(&block->exp);
  1668. av_freep(&block->grouped_exp);
  1669. av_freep(&block->psd);
  1670. av_freep(&block->band_psd);
  1671. av_freep(&block->mask);
  1672. av_freep(&block->qmant);
  1673. }
  1674. mdct_end(&s->mdct);
  1675. av_freep(&avctx->coded_frame);
  1676. return 0;
  1677. }
  1678. /**
  1679. * Set channel information during initialization.
  1680. */
  1681. static av_cold int set_channel_info(AC3EncodeContext *s, int channels,
  1682. int64_t *channel_layout)
  1683. {
  1684. int ch_layout;
  1685. if (channels < 1 || channels > AC3_MAX_CHANNELS)
  1686. return AVERROR(EINVAL);
  1687. if ((uint64_t)*channel_layout > 0x7FF)
  1688. return AVERROR(EINVAL);
  1689. ch_layout = *channel_layout;
  1690. if (!ch_layout)
  1691. ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);
  1692. if (av_get_channel_layout_nb_channels(ch_layout) != channels)
  1693. return AVERROR(EINVAL);
  1694. s->lfe_on = !!(ch_layout & AV_CH_LOW_FREQUENCY);
  1695. s->channels = channels;
  1696. s->fbw_channels = channels - s->lfe_on;
  1697. s->lfe_channel = s->lfe_on ? s->fbw_channels : -1;
  1698. if (s->lfe_on)
  1699. ch_layout -= AV_CH_LOW_FREQUENCY;
  1700. switch (ch_layout) {
  1701. case AV_CH_LAYOUT_MONO: s->channel_mode = AC3_CHMODE_MONO; break;
  1702. case AV_CH_LAYOUT_STEREO: s->channel_mode = AC3_CHMODE_STEREO; break;
  1703. case AV_CH_LAYOUT_SURROUND: s->channel_mode = AC3_CHMODE_3F; break;
  1704. case AV_CH_LAYOUT_2_1: s->channel_mode = AC3_CHMODE_2F1R; break;
  1705. case AV_CH_LAYOUT_4POINT0: s->channel_mode = AC3_CHMODE_3F1R; break;
  1706. case AV_CH_LAYOUT_QUAD:
  1707. case AV_CH_LAYOUT_2_2: s->channel_mode = AC3_CHMODE_2F2R; break;
  1708. case AV_CH_LAYOUT_5POINT0:
  1709. case AV_CH_LAYOUT_5POINT0_BACK: s->channel_mode = AC3_CHMODE_3F2R; break;
  1710. default:
  1711. return AVERROR(EINVAL);
  1712. }
  1713. s->has_center = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;
  1714. s->has_surround = s->channel_mode & 0x04;
  1715. s->channel_map = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];
  1716. *channel_layout = ch_layout;
  1717. if (s->lfe_on)
  1718. *channel_layout |= AV_CH_LOW_FREQUENCY;
  1719. return 0;
  1720. }
  1721. static av_cold int validate_options(AVCodecContext *avctx, AC3EncodeContext *s)
  1722. {
  1723. int i, ret;
  1724. /* validate channel layout */
  1725. if (!avctx->channel_layout) {
  1726. av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The "
  1727. "encoder will guess the layout, but it "
  1728. "might be incorrect.\n");
  1729. }
  1730. ret = set_channel_info(s, avctx->channels, &avctx->channel_layout);
  1731. if (ret) {
  1732. av_log(avctx, AV_LOG_ERROR, "invalid channel layout\n");
  1733. return ret;
  1734. }
  1735. /* validate sample rate */
  1736. for (i = 0; i < 9; i++) {
  1737. if ((ff_ac3_sample_rate_tab[i / 3] >> (i % 3)) == avctx->sample_rate)
  1738. break;
  1739. }
  1740. if (i == 9) {
  1741. av_log(avctx, AV_LOG_ERROR, "invalid sample rate\n");
  1742. return AVERROR(EINVAL);
  1743. }
  1744. s->sample_rate = avctx->sample_rate;
  1745. s->bit_alloc.sr_shift = i % 3;
  1746. s->bit_alloc.sr_code = i / 3;
  1747. s->bitstream_id = 8 + s->bit_alloc.sr_shift;
  1748. /* validate bit rate */
  1749. for (i = 0; i < 19; i++) {
  1750. if ((ff_ac3_bitrate_tab[i] >> s->bit_alloc.sr_shift)*1000 == avctx->bit_rate)
  1751. break;
  1752. }
  1753. if (i == 19) {
  1754. av_log(avctx, AV_LOG_ERROR, "invalid bit rate\n");
  1755. return AVERROR(EINVAL);
  1756. }
  1757. s->bit_rate = avctx->bit_rate;
  1758. s->frame_size_code = i << 1;
  1759. /* validate cutoff */
  1760. if (avctx->cutoff < 0) {
  1761. av_log(avctx, AV_LOG_ERROR, "invalid cutoff frequency\n");
  1762. return AVERROR(EINVAL);
  1763. }
  1764. s->cutoff = avctx->cutoff;
  1765. if (s->cutoff > (s->sample_rate >> 1))
  1766. s->cutoff = s->sample_rate >> 1;
  1767. /* validate audio service type / channels combination */
  1768. if ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_KARAOKE &&
  1769. avctx->channels == 1) ||
  1770. ((avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_COMMENTARY ||
  1771. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_EMERGENCY ||
  1772. avctx->audio_service_type == AV_AUDIO_SERVICE_TYPE_VOICE_OVER)
  1773. && avctx->channels > 1)) {
  1774. av_log(avctx, AV_LOG_ERROR, "invalid audio service type for the "
  1775. "specified number of channels\n");
  1776. return AVERROR(EINVAL);
  1777. }
  1778. ret = validate_metadata(avctx);
  1779. if (ret)
  1780. return ret;
  1781. return 0;
  1782. }
  1783. /**
  1784. * Set bandwidth for all channels.
  1785. * The user can optionally supply a cutoff frequency. Otherwise an appropriate
  1786. * default value will be used.
  1787. */
  1788. static av_cold void set_bandwidth(AC3EncodeContext *s)
  1789. {
  1790. int ch, bw_code;
  1791. if (s->cutoff) {
  1792. /* calculate bandwidth based on user-specified cutoff frequency */
  1793. int fbw_coeffs;
  1794. fbw_coeffs = s->cutoff * 2 * AC3_MAX_COEFS / s->sample_rate;
  1795. bw_code = av_clip((fbw_coeffs - 73) / 3, 0, 60);
  1796. } else {
  1797. /* use default bandwidth setting */
  1798. bw_code = ac3_bandwidth_tab[s->fbw_channels-1][s->bit_alloc.sr_code][s->frame_size_code/2];
  1799. }
  1800. /* set number of coefficients for each channel */
  1801. for (ch = 0; ch < s->fbw_channels; ch++) {
  1802. s->bandwidth_code[ch] = bw_code;
  1803. s->nb_coefs[ch] = bw_code * 3 + 73;
  1804. }
  1805. if (s->lfe_on)
  1806. s->nb_coefs[s->lfe_channel] = 7; /* LFE channel always has 7 coefs */
  1807. }
  1808. static av_cold int allocate_buffers(AVCodecContext *avctx)
  1809. {
  1810. int blk, ch;
  1811. AC3EncodeContext *s = avctx->priv_data;
  1812. FF_ALLOC_OR_GOTO(avctx, s->planar_samples, s->channels * sizeof(*s->planar_samples),
  1813. alloc_fail);
  1814. for (ch = 0; ch < s->channels; ch++) {
  1815. FF_ALLOCZ_OR_GOTO(avctx, s->planar_samples[ch],
  1816. (AC3_FRAME_SIZE+AC3_BLOCK_SIZE) * sizeof(**s->planar_samples),
  1817. alloc_fail);
  1818. }
  1819. FF_ALLOC_OR_GOTO(avctx, s->bap_buffer, AC3_MAX_BLOCKS * s->channels *
  1820. AC3_MAX_COEFS * sizeof(*s->bap_buffer), alloc_fail);
  1821. FF_ALLOC_OR_GOTO(avctx, s->bap1_buffer, AC3_MAX_BLOCKS * s->channels *
  1822. AC3_MAX_COEFS * sizeof(*s->bap1_buffer), alloc_fail);
  1823. FF_ALLOC_OR_GOTO(avctx, s->mdct_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1824. AC3_MAX_COEFS * sizeof(*s->mdct_coef_buffer), alloc_fail);
  1825. FF_ALLOC_OR_GOTO(avctx, s->exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1826. AC3_MAX_COEFS * sizeof(*s->exp_buffer), alloc_fail);
  1827. FF_ALLOC_OR_GOTO(avctx, s->grouped_exp_buffer, AC3_MAX_BLOCKS * s->channels *
  1828. 128 * sizeof(*s->grouped_exp_buffer), alloc_fail);
  1829. FF_ALLOC_OR_GOTO(avctx, s->psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1830. AC3_MAX_COEFS * sizeof(*s->psd_buffer), alloc_fail);
  1831. FF_ALLOC_OR_GOTO(avctx, s->band_psd_buffer, AC3_MAX_BLOCKS * s->channels *
  1832. 64 * sizeof(*s->band_psd_buffer), alloc_fail);
  1833. FF_ALLOC_OR_GOTO(avctx, s->mask_buffer, AC3_MAX_BLOCKS * s->channels *
  1834. 64 * sizeof(*s->mask_buffer), alloc_fail);
  1835. FF_ALLOC_OR_GOTO(avctx, s->qmant_buffer, AC3_MAX_BLOCKS * s->channels *
  1836. AC3_MAX_COEFS * sizeof(*s->qmant_buffer), alloc_fail);
  1837. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1838. AC3Block *block = &s->blocks[blk];
  1839. FF_ALLOC_OR_GOTO(avctx, block->bap, s->channels * sizeof(*block->bap),
  1840. alloc_fail);
  1841. FF_ALLOCZ_OR_GOTO(avctx, block->mdct_coef, s->channels * sizeof(*block->mdct_coef),
  1842. alloc_fail);
  1843. FF_ALLOCZ_OR_GOTO(avctx, block->exp, s->channels * sizeof(*block->exp),
  1844. alloc_fail);
  1845. FF_ALLOCZ_OR_GOTO(avctx, block->grouped_exp, s->channels * sizeof(*block->grouped_exp),
  1846. alloc_fail);
  1847. FF_ALLOCZ_OR_GOTO(avctx, block->psd, s->channels * sizeof(*block->psd),
  1848. alloc_fail);
  1849. FF_ALLOCZ_OR_GOTO(avctx, block->band_psd, s->channels * sizeof(*block->band_psd),
  1850. alloc_fail);
  1851. FF_ALLOCZ_OR_GOTO(avctx, block->mask, s->channels * sizeof(*block->mask),
  1852. alloc_fail);
  1853. FF_ALLOCZ_OR_GOTO(avctx, block->qmant, s->channels * sizeof(*block->qmant),
  1854. alloc_fail);
  1855. for (ch = 0; ch < s->channels; ch++) {
  1856. /* arrangement: block, channel, coeff */
  1857. block->bap[ch] = &s->bap_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1858. block->mdct_coef[ch] = &s->mdct_coef_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1859. block->grouped_exp[ch] = &s->grouped_exp_buffer[128 * (blk * s->channels + ch)];
  1860. block->psd[ch] = &s->psd_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1861. block->band_psd[ch] = &s->band_psd_buffer [64 * (blk * s->channels + ch)];
  1862. block->mask[ch] = &s->mask_buffer [64 * (blk * s->channels + ch)];
  1863. block->qmant[ch] = &s->qmant_buffer [AC3_MAX_COEFS * (blk * s->channels + ch)];
  1864. /* arrangement: channel, block, coeff */
  1865. block->exp[ch] = &s->exp_buffer [AC3_MAX_COEFS * (AC3_MAX_BLOCKS * ch + blk)];
  1866. }
  1867. }
  1868. if (CONFIG_AC3ENC_FLOAT) {
  1869. FF_ALLOC_OR_GOTO(avctx, s->fixed_coef_buffer, AC3_MAX_BLOCKS * s->channels *
  1870. AC3_MAX_COEFS * sizeof(*s->fixed_coef_buffer), alloc_fail);
  1871. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1872. AC3Block *block = &s->blocks[blk];
  1873. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1874. sizeof(*block->fixed_coef), alloc_fail);
  1875. for (ch = 0; ch < s->channels; ch++)
  1876. block->fixed_coef[ch] = &s->fixed_coef_buffer[AC3_MAX_COEFS * (blk * s->channels + ch)];
  1877. }
  1878. } else {
  1879. for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {
  1880. AC3Block *block = &s->blocks[blk];
  1881. FF_ALLOCZ_OR_GOTO(avctx, block->fixed_coef, s->channels *
  1882. sizeof(*block->fixed_coef), alloc_fail);
  1883. for (ch = 0; ch < s->channels; ch++)
  1884. block->fixed_coef[ch] = (int32_t *)block->mdct_coef[ch];
  1885. }
  1886. }
  1887. return 0;
  1888. alloc_fail:
  1889. return AVERROR(ENOMEM);
  1890. }
  1891. /**
  1892. * Initialize the encoder.
  1893. */
  1894. static av_cold int ac3_encode_init(AVCodecContext *avctx)
  1895. {
  1896. AC3EncodeContext *s = avctx->priv_data;
  1897. int ret, frame_size_58;
  1898. avctx->frame_size = AC3_FRAME_SIZE;
  1899. ff_ac3_common_init();
  1900. ret = validate_options(avctx, s);
  1901. if (ret)
  1902. return ret;
  1903. s->bitstream_mode = avctx->audio_service_type;
  1904. if (s->bitstream_mode == AV_AUDIO_SERVICE_TYPE_KARAOKE)
  1905. s->bitstream_mode = 0x7;
  1906. s->frame_size_min = 2 * ff_ac3_frame_size_tab[s->frame_size_code][s->bit_alloc.sr_code];
  1907. s->bits_written = 0;
  1908. s->samples_written = 0;
  1909. s->frame_size = s->frame_size_min;
  1910. /* calculate crc_inv for both possible frame sizes */
  1911. frame_size_58 = (( s->frame_size >> 2) + ( s->frame_size >> 4)) << 1;
  1912. s->crc_inv[0] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1913. if (s->bit_alloc.sr_code == 1) {
  1914. frame_size_58 = (((s->frame_size+2) >> 2) + ((s->frame_size+2) >> 4)) << 1;
  1915. s->crc_inv[1] = pow_poly((CRC16_POLY >> 1), (8 * frame_size_58) - 16, CRC16_POLY);
  1916. }
  1917. set_bandwidth(s);
  1918. rematrixing_init(s);
  1919. exponent_init(s);
  1920. bit_alloc_init(s);
  1921. ret = mdct_init(avctx, &s->mdct, 9);
  1922. if (ret)
  1923. goto init_fail;
  1924. ret = allocate_buffers(avctx);
  1925. if (ret)
  1926. goto init_fail;
  1927. avctx->coded_frame= avcodec_alloc_frame();
  1928. dsputil_init(&s->dsp, avctx);
  1929. ff_ac3dsp_init(&s->ac3dsp, avctx->flags & CODEC_FLAG_BITEXACT);
  1930. dprint_options(avctx);
  1931. return 0;
  1932. init_fail:
  1933. ac3_encode_close(avctx);
  1934. return ret;
  1935. }