ac3enc.c 93 KB

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