2
0

ac3enc.c 85 KB

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