ac3enc.c 101 KB

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