celt_encoder.c 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411
  1. /* Copyright (c) 2007-2008 CSIRO
  2. Copyright (c) 2007-2010 Xiph.Org Foundation
  3. Copyright (c) 2008 Gregory Maxwell
  4. Written by Jean-Marc Valin and Gregory Maxwell */
  5. /*
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions
  8. are met:
  9. - Redistributions of source code must retain the above copyright
  10. notice, this list of conditions and the following disclaimer.
  11. - Redistributions in binary form must reproduce the above copyright
  12. notice, this list of conditions and the following disclaimer in the
  13. documentation and/or other materials provided with the distribution.
  14. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  15. ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  16. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  17. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
  18. OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  19. EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  20. PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  21. PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  22. LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  23. NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  24. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #ifdef HAVE_CONFIG_H
  27. #include "config.h"
  28. #endif
  29. #define CELT_ENCODER_C
  30. #include "cpu_support.h"
  31. #include "os_support.h"
  32. #include "mdct.h"
  33. #include <math.h>
  34. #include "celt.h"
  35. #include "pitch.h"
  36. #include "bands.h"
  37. #include "modes.h"
  38. #include "entcode.h"
  39. #include "quant_bands.h"
  40. #include "rate.h"
  41. #include "stack_alloc.h"
  42. #include "mathops.h"
  43. #include "float_cast.h"
  44. #include <stdarg.h>
  45. #include "celt_lpc.h"
  46. #include "vq.h"
  47. /** Encoder state
  48. @brief Encoder state
  49. */
  50. struct OpusCustomEncoder {
  51. const OpusCustomMode *mode; /**< Mode used by the encoder */
  52. int channels;
  53. int stream_channels;
  54. int force_intra;
  55. int clip;
  56. int disable_pf;
  57. int complexity;
  58. int upsample;
  59. int start, end;
  60. opus_int32 bitrate;
  61. int vbr;
  62. int signalling;
  63. int constrained_vbr; /* If zero, VBR can do whatever it likes with the rate */
  64. int loss_rate;
  65. int lsb_depth;
  66. int variable_duration;
  67. int lfe;
  68. int arch;
  69. /* Everything beyond this point gets cleared on a reset */
  70. #define ENCODER_RESET_START rng
  71. opus_uint32 rng;
  72. int spread_decision;
  73. opus_val32 delayedIntra;
  74. int tonal_average;
  75. int lastCodedBands;
  76. int hf_average;
  77. int tapset_decision;
  78. int prefilter_period;
  79. opus_val16 prefilter_gain;
  80. int prefilter_tapset;
  81. #ifdef RESYNTH
  82. int prefilter_period_old;
  83. opus_val16 prefilter_gain_old;
  84. int prefilter_tapset_old;
  85. #endif
  86. int consec_transient;
  87. AnalysisInfo analysis;
  88. opus_val32 preemph_memE[2];
  89. opus_val32 preemph_memD[2];
  90. /* VBR-related parameters */
  91. opus_int32 vbr_reservoir;
  92. opus_int32 vbr_drift;
  93. opus_int32 vbr_offset;
  94. opus_int32 vbr_count;
  95. opus_val32 overlap_max;
  96. opus_val16 stereo_saving;
  97. int intensity;
  98. opus_val16 *energy_mask;
  99. opus_val16 spec_avg;
  100. #ifdef RESYNTH
  101. /* +MAX_PERIOD/2 to make space for overlap */
  102. celt_sig syn_mem[2][2*MAX_PERIOD+MAX_PERIOD/2];
  103. #endif
  104. celt_sig in_mem[1]; /* Size = channels*mode->overlap */
  105. /* celt_sig prefilter_mem[], Size = channels*COMBFILTER_MAXPERIOD */
  106. /* opus_val16 oldBandE[], Size = channels*mode->nbEBands */
  107. /* opus_val16 oldLogE[], Size = channels*mode->nbEBands */
  108. /* opus_val16 oldLogE2[], Size = channels*mode->nbEBands */
  109. };
  110. int celt_encoder_get_size(int channels)
  111. {
  112. CELTMode *mode = opus_custom_mode_create(48000, 960, NULL);
  113. return opus_custom_encoder_get_size(mode, channels);
  114. }
  115. OPUS_CUSTOM_NOSTATIC int opus_custom_encoder_get_size(const CELTMode *mode, int channels)
  116. {
  117. int size = sizeof(struct CELTEncoder)
  118. + (channels*mode->overlap-1)*sizeof(celt_sig) /* celt_sig in_mem[channels*mode->overlap]; */
  119. + channels*COMBFILTER_MAXPERIOD*sizeof(celt_sig) /* celt_sig prefilter_mem[channels*COMBFILTER_MAXPERIOD]; */
  120. + 3*channels*mode->nbEBands*sizeof(opus_val16); /* opus_val16 oldBandE[channels*mode->nbEBands]; */
  121. /* opus_val16 oldLogE[channels*mode->nbEBands]; */
  122. /* opus_val16 oldLogE2[channels*mode->nbEBands]; */
  123. return size;
  124. }
  125. #ifdef CUSTOM_MODES
  126. CELTEncoder *opus_custom_encoder_create(const CELTMode *mode, int channels, int *error)
  127. {
  128. int ret;
  129. CELTEncoder *st = (CELTEncoder *)opus_alloc(opus_custom_encoder_get_size(mode, channels));
  130. /* init will handle the NULL case */
  131. ret = opus_custom_encoder_init(st, mode, channels);
  132. if (ret != OPUS_OK)
  133. {
  134. opus_custom_encoder_destroy(st);
  135. st = NULL;
  136. }
  137. if (error)
  138. *error = ret;
  139. return st;
  140. }
  141. #endif /* CUSTOM_MODES */
  142. static int opus_custom_encoder_init_arch(CELTEncoder *st, const CELTMode *mode,
  143. int channels, int arch)
  144. {
  145. if (channels < 0 || channels > 2)
  146. return OPUS_BAD_ARG;
  147. if (st==NULL || mode==NULL)
  148. return OPUS_ALLOC_FAIL;
  149. OPUS_CLEAR((char*)st, opus_custom_encoder_get_size(mode, channels));
  150. st->mode = mode;
  151. st->stream_channels = st->channels = channels;
  152. st->upsample = 1;
  153. st->start = 0;
  154. st->end = st->mode->effEBands;
  155. st->signalling = 1;
  156. st->arch = arch;
  157. st->constrained_vbr = 1;
  158. st->clip = 1;
  159. st->bitrate = OPUS_BITRATE_MAX;
  160. st->vbr = 0;
  161. st->force_intra = 0;
  162. st->complexity = 5;
  163. st->lsb_depth=24;
  164. opus_custom_encoder_ctl(st, OPUS_RESET_STATE);
  165. return OPUS_OK;
  166. }
  167. #ifdef CUSTOM_MODES
  168. int opus_custom_encoder_init(CELTEncoder *st, const CELTMode *mode, int channels)
  169. {
  170. return opus_custom_encoder_init_arch(st, mode, channels, opus_select_arch());
  171. }
  172. #endif
  173. int celt_encoder_init(CELTEncoder *st, opus_int32 sampling_rate, int channels,
  174. int arch)
  175. {
  176. int ret;
  177. ret = opus_custom_encoder_init_arch(st,
  178. opus_custom_mode_create(48000, 960, NULL), channels, arch);
  179. if (ret != OPUS_OK)
  180. return ret;
  181. st->upsample = resampling_factor(sampling_rate);
  182. return OPUS_OK;
  183. }
  184. #ifdef CUSTOM_MODES
  185. void opus_custom_encoder_destroy(CELTEncoder *st)
  186. {
  187. opus_free(st);
  188. }
  189. #endif /* CUSTOM_MODES */
  190. static int transient_analysis(const opus_val32 * OPUS_RESTRICT in, int len, int C,
  191. opus_val16 *tf_estimate, int *tf_chan)
  192. {
  193. int i;
  194. VARDECL(opus_val16, tmp);
  195. opus_val32 mem0,mem1;
  196. int is_transient = 0;
  197. opus_int32 mask_metric = 0;
  198. int c;
  199. opus_val16 tf_max;
  200. int len2;
  201. /* Table of 6*64/x, trained on real data to minimize the average error */
  202. static const unsigned char inv_table[128] = {
  203. 255,255,156,110, 86, 70, 59, 51, 45, 40, 37, 33, 31, 28, 26, 25,
  204. 23, 22, 21, 20, 19, 18, 17, 16, 16, 15, 15, 14, 13, 13, 12, 12,
  205. 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 9, 9, 8, 8,
  206. 8, 8, 8, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6,
  207. 6, 6, 6, 6, 6, 6, 6, 6, 6, 5, 5, 5, 5, 5, 5, 5,
  208. 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  209. 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3,
  210. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2,
  211. };
  212. SAVE_STACK;
  213. ALLOC(tmp, len, opus_val16);
  214. len2=len/2;
  215. for (c=0;c<C;c++)
  216. {
  217. opus_val32 mean;
  218. opus_int32 unmask=0;
  219. opus_val32 norm;
  220. opus_val16 maxE;
  221. mem0=0;
  222. mem1=0;
  223. /* High-pass filter: (1 - 2*z^-1 + z^-2) / (1 - z^-1 + .5*z^-2) */
  224. for (i=0;i<len;i++)
  225. {
  226. opus_val32 x,y;
  227. x = SHR32(in[i+c*len],SIG_SHIFT);
  228. y = ADD32(mem0, x);
  229. #ifdef FIXED_POINT
  230. mem0 = mem1 + y - SHL32(x,1);
  231. mem1 = x - SHR32(y,1);
  232. #else
  233. mem0 = mem1 + y - 2*x;
  234. mem1 = x - .5f*y;
  235. #endif
  236. tmp[i] = EXTRACT16(SHR32(y,2));
  237. /*printf("%f ", tmp[i]);*/
  238. }
  239. /*printf("\n");*/
  240. /* First few samples are bad because we don't propagate the memory */
  241. OPUS_CLEAR(tmp, 12);
  242. #ifdef FIXED_POINT
  243. /* Normalize tmp to max range */
  244. {
  245. int shift=0;
  246. shift = 14-celt_ilog2(1+celt_maxabs16(tmp, len));
  247. if (shift!=0)
  248. {
  249. for (i=0;i<len;i++)
  250. tmp[i] = SHL16(tmp[i], shift);
  251. }
  252. }
  253. #endif
  254. mean=0;
  255. mem0=0;
  256. /* Grouping by two to reduce complexity */
  257. /* Forward pass to compute the post-echo threshold*/
  258. for (i=0;i<len2;i++)
  259. {
  260. opus_val16 x2 = PSHR32(MULT16_16(tmp[2*i],tmp[2*i]) + MULT16_16(tmp[2*i+1],tmp[2*i+1]),16);
  261. mean += x2;
  262. #ifdef FIXED_POINT
  263. /* FIXME: Use PSHR16() instead */
  264. tmp[i] = mem0 + PSHR32(x2-mem0,4);
  265. #else
  266. tmp[i] = mem0 + MULT16_16_P15(QCONST16(.0625f,15),x2-mem0);
  267. #endif
  268. mem0 = tmp[i];
  269. }
  270. mem0=0;
  271. maxE=0;
  272. /* Backward pass to compute the pre-echo threshold */
  273. for (i=len2-1;i>=0;i--)
  274. {
  275. #ifdef FIXED_POINT
  276. /* FIXME: Use PSHR16() instead */
  277. tmp[i] = mem0 + PSHR32(tmp[i]-mem0,3);
  278. #else
  279. tmp[i] = mem0 + MULT16_16_P15(QCONST16(0.125f,15),tmp[i]-mem0);
  280. #endif
  281. mem0 = tmp[i];
  282. maxE = MAX16(maxE, mem0);
  283. }
  284. /*for (i=0;i<len2;i++)printf("%f ", tmp[i]/mean);printf("\n");*/
  285. /* Compute the ratio of the "frame energy" over the harmonic mean of the energy.
  286. This essentially corresponds to a bitrate-normalized temporal noise-to-mask
  287. ratio */
  288. /* As a compromise with the old transient detector, frame energy is the
  289. geometric mean of the energy and half the max */
  290. #ifdef FIXED_POINT
  291. /* Costs two sqrt() to avoid overflows */
  292. mean = MULT16_16(celt_sqrt(mean), celt_sqrt(MULT16_16(maxE,len2>>1)));
  293. #else
  294. mean = celt_sqrt(mean * maxE*.5*len2);
  295. #endif
  296. /* Inverse of the mean energy in Q15+6 */
  297. norm = SHL32(EXTEND32(len2),6+14)/ADD32(EPSILON,SHR32(mean,1));
  298. /* Compute harmonic mean discarding the unreliable boundaries
  299. The data is smooth, so we only take 1/4th of the samples */
  300. unmask=0;
  301. for (i=12;i<len2-5;i+=4)
  302. {
  303. int id;
  304. #ifdef FIXED_POINT
  305. id = MAX32(0,MIN32(127,MULT16_32_Q15(tmp[i]+EPSILON,norm))); /* Do not round to nearest */
  306. #else
  307. id = (int)MAX32(0,MIN32(127,floor(64*norm*(tmp[i]+EPSILON)))); /* Do not round to nearest */
  308. #endif
  309. unmask += inv_table[id];
  310. }
  311. /*printf("%d\n", unmask);*/
  312. /* Normalize, compensate for the 1/4th of the sample and the factor of 6 in the inverse table */
  313. unmask = 64*unmask*4/(6*(len2-17));
  314. if (unmask>mask_metric)
  315. {
  316. *tf_chan = c;
  317. mask_metric = unmask;
  318. }
  319. }
  320. is_transient = mask_metric>200;
  321. /* Arbitrary metric for VBR boost */
  322. tf_max = MAX16(0,celt_sqrt(27*mask_metric)-42);
  323. /* *tf_estimate = 1 + MIN16(1, sqrt(MAX16(0, tf_max-30))/20); */
  324. *tf_estimate = celt_sqrt(MAX32(0, SHL32(MULT16_16(QCONST16(0.0069,14),MIN16(163,tf_max)),14)-QCONST32(0.139,28)));
  325. /*printf("%d %f\n", tf_max, mask_metric);*/
  326. RESTORE_STACK;
  327. #ifdef FUZZING
  328. is_transient = rand()&0x1;
  329. #endif
  330. /*printf("%d %f %d\n", is_transient, (float)*tf_estimate, tf_max);*/
  331. return is_transient;
  332. }
  333. /* Looks for sudden increases of energy to decide whether we need to patch
  334. the transient decision */
  335. static int patch_transient_decision(opus_val16 *newE, opus_val16 *oldE, int nbEBands,
  336. int start, int end, int C)
  337. {
  338. int i, c;
  339. opus_val32 mean_diff=0;
  340. opus_val16 spread_old[26];
  341. /* Apply an aggressive (-6 dB/Bark) spreading function to the old frame to
  342. avoid false detection caused by irrelevant bands */
  343. if (C==1)
  344. {
  345. spread_old[start] = oldE[start];
  346. for (i=start+1;i<end;i++)
  347. spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT), oldE[i]);
  348. } else {
  349. spread_old[start] = MAX16(oldE[start],oldE[start+nbEBands]);
  350. for (i=start+1;i<end;i++)
  351. spread_old[i] = MAX16(spread_old[i-1]-QCONST16(1.0f, DB_SHIFT),
  352. MAX16(oldE[i],oldE[i+nbEBands]));
  353. }
  354. for (i=end-2;i>=start;i--)
  355. spread_old[i] = MAX16(spread_old[i], spread_old[i+1]-QCONST16(1.0f, DB_SHIFT));
  356. /* Compute mean increase */
  357. c=0; do {
  358. for (i=IMAX(2,start);i<end-1;i++)
  359. {
  360. opus_val16 x1, x2;
  361. x1 = MAX16(0, newE[i + c*nbEBands]);
  362. x2 = MAX16(0, spread_old[i]);
  363. mean_diff = ADD32(mean_diff, EXTEND32(MAX16(0, SUB16(x1, x2))));
  364. }
  365. } while (++c<C);
  366. mean_diff = DIV32(mean_diff, C*(end-1-IMAX(2,start)));
  367. /*printf("%f %f %d\n", mean_diff, max_diff, count);*/
  368. return mean_diff > QCONST16(1.f, DB_SHIFT);
  369. }
  370. /** Apply window and compute the MDCT for all sub-frames and
  371. all channels in a frame */
  372. static void compute_mdcts(const CELTMode *mode, int shortBlocks, celt_sig * OPUS_RESTRICT in,
  373. celt_sig * OPUS_RESTRICT out, int C, int CC, int LM, int upsample,
  374. int arch)
  375. {
  376. const int overlap = mode->overlap;
  377. int N;
  378. int B;
  379. int shift;
  380. int i, b, c;
  381. if (shortBlocks)
  382. {
  383. B = shortBlocks;
  384. N = mode->shortMdctSize;
  385. shift = mode->maxLM;
  386. } else {
  387. B = 1;
  388. N = mode->shortMdctSize<<LM;
  389. shift = mode->maxLM-LM;
  390. }
  391. c=0; do {
  392. for (b=0;b<B;b++)
  393. {
  394. /* Interleaving the sub-frames while doing the MDCTs */
  395. clt_mdct_forward(&mode->mdct, in+c*(B*N+overlap)+b*N,
  396. &out[b+c*N*B], mode->window, overlap, shift, B,
  397. arch);
  398. }
  399. } while (++c<CC);
  400. if (CC==2&&C==1)
  401. {
  402. for (i=0;i<B*N;i++)
  403. out[i] = ADD32(HALF32(out[i]), HALF32(out[B*N+i]));
  404. }
  405. if (upsample != 1)
  406. {
  407. c=0; do
  408. {
  409. int bound = B*N/upsample;
  410. for (i=0;i<bound;i++)
  411. out[c*B*N+i] *= upsample;
  412. OPUS_CLEAR(&out[c*B*N+bound], B*N-bound);
  413. } while (++c<C);
  414. }
  415. }
  416. void celt_preemphasis(const opus_val16 * OPUS_RESTRICT pcmp, celt_sig * OPUS_RESTRICT inp,
  417. int N, int CC, int upsample, const opus_val16 *coef, celt_sig *mem, int clip)
  418. {
  419. int i;
  420. opus_val16 coef0;
  421. celt_sig m;
  422. int Nu;
  423. coef0 = coef[0];
  424. m = *mem;
  425. /* Fast path for the normal 48kHz case and no clipping */
  426. if (coef[1] == 0 && upsample == 1 && !clip)
  427. {
  428. for (i=0;i<N;i++)
  429. {
  430. opus_val16 x;
  431. x = SCALEIN(pcmp[CC*i]);
  432. /* Apply pre-emphasis */
  433. inp[i] = SHL32(x, SIG_SHIFT) - m;
  434. m = SHR32(MULT16_16(coef0, x), 15-SIG_SHIFT);
  435. }
  436. *mem = m;
  437. return;
  438. }
  439. Nu = N/upsample;
  440. if (upsample!=1)
  441. {
  442. OPUS_CLEAR(inp, N);
  443. }
  444. for (i=0;i<Nu;i++)
  445. inp[i*upsample] = SCALEIN(pcmp[CC*i]);
  446. #ifndef FIXED_POINT
  447. if (clip)
  448. {
  449. /* Clip input to avoid encoding non-portable files */
  450. for (i=0;i<Nu;i++)
  451. inp[i*upsample] = MAX32(-65536.f, MIN32(65536.f,inp[i*upsample]));
  452. }
  453. #else
  454. (void)clip; /* Avoids a warning about clip being unused. */
  455. #endif
  456. #ifdef CUSTOM_MODES
  457. if (coef[1] != 0)
  458. {
  459. opus_val16 coef1 = coef[1];
  460. opus_val16 coef2 = coef[2];
  461. for (i=0;i<N;i++)
  462. {
  463. celt_sig x, tmp;
  464. x = inp[i];
  465. /* Apply pre-emphasis */
  466. tmp = MULT16_16(coef2, x);
  467. inp[i] = tmp + m;
  468. m = MULT16_32_Q15(coef1, inp[i]) - MULT16_32_Q15(coef0, tmp);
  469. }
  470. } else
  471. #endif
  472. {
  473. for (i=0;i<N;i++)
  474. {
  475. opus_val16 x;
  476. x = inp[i];
  477. /* Apply pre-emphasis */
  478. inp[i] = SHL32(x, SIG_SHIFT) - m;
  479. m = SHR32(MULT16_16(coef0, x), 15-SIG_SHIFT);
  480. }
  481. }
  482. *mem = m;
  483. }
  484. static opus_val32 l1_metric(const celt_norm *tmp, int N, int LM, opus_val16 bias)
  485. {
  486. int i;
  487. opus_val32 L1;
  488. L1 = 0;
  489. for (i=0;i<N;i++)
  490. L1 += EXTEND32(ABS16(tmp[i]));
  491. /* When in doubt, prefer good freq resolution */
  492. L1 = MAC16_32_Q15(L1, LM*bias, L1);
  493. return L1;
  494. }
  495. static int tf_analysis(const CELTMode *m, int len, int isTransient,
  496. int *tf_res, int lambda, celt_norm *X, int N0, int LM,
  497. int *tf_sum, opus_val16 tf_estimate, int tf_chan)
  498. {
  499. int i;
  500. VARDECL(int, metric);
  501. int cost0;
  502. int cost1;
  503. VARDECL(int, path0);
  504. VARDECL(int, path1);
  505. VARDECL(celt_norm, tmp);
  506. VARDECL(celt_norm, tmp_1);
  507. int sel;
  508. int selcost[2];
  509. int tf_select=0;
  510. opus_val16 bias;
  511. SAVE_STACK;
  512. bias = MULT16_16_Q14(QCONST16(.04f,15), MAX16(-QCONST16(.25f,14), QCONST16(.5f,14)-tf_estimate));
  513. /*printf("%f ", bias);*/
  514. ALLOC(metric, len, int);
  515. ALLOC(tmp, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
  516. ALLOC(tmp_1, (m->eBands[len]-m->eBands[len-1])<<LM, celt_norm);
  517. ALLOC(path0, len, int);
  518. ALLOC(path1, len, int);
  519. *tf_sum = 0;
  520. for (i=0;i<len;i++)
  521. {
  522. int k, N;
  523. int narrow;
  524. opus_val32 L1, best_L1;
  525. int best_level=0;
  526. N = (m->eBands[i+1]-m->eBands[i])<<LM;
  527. /* band is too narrow to be split down to LM=-1 */
  528. narrow = (m->eBands[i+1]-m->eBands[i])==1;
  529. OPUS_COPY(tmp, &X[tf_chan*N0 + (m->eBands[i]<<LM)], N);
  530. /* Just add the right channel if we're in stereo */
  531. /*if (C==2)
  532. for (j=0;j<N;j++)
  533. tmp[j] = ADD16(SHR16(tmp[j], 1),SHR16(X[N0+j+(m->eBands[i]<<LM)], 1));*/
  534. L1 = l1_metric(tmp, N, isTransient ? LM : 0, bias);
  535. best_L1 = L1;
  536. /* Check the -1 case for transients */
  537. if (isTransient && !narrow)
  538. {
  539. OPUS_COPY(tmp_1, tmp, N);
  540. haar1(tmp_1, N>>LM, 1<<LM);
  541. L1 = l1_metric(tmp_1, N, LM+1, bias);
  542. if (L1<best_L1)
  543. {
  544. best_L1 = L1;
  545. best_level = -1;
  546. }
  547. }
  548. /*printf ("%f ", L1);*/
  549. for (k=0;k<LM+!(isTransient||narrow);k++)
  550. {
  551. int B;
  552. if (isTransient)
  553. B = (LM-k-1);
  554. else
  555. B = k+1;
  556. haar1(tmp, N>>k, 1<<k);
  557. L1 = l1_metric(tmp, N, B, bias);
  558. if (L1 < best_L1)
  559. {
  560. best_L1 = L1;
  561. best_level = k+1;
  562. }
  563. }
  564. /*printf ("%d ", isTransient ? LM-best_level : best_level);*/
  565. /* metric is in Q1 to be able to select the mid-point (-0.5) for narrower bands */
  566. if (isTransient)
  567. metric[i] = 2*best_level;
  568. else
  569. metric[i] = -2*best_level;
  570. *tf_sum += (isTransient ? LM : 0) - metric[i]/2;
  571. /* For bands that can't be split to -1, set the metric to the half-way point to avoid
  572. biasing the decision */
  573. if (narrow && (metric[i]==0 || metric[i]==-2*LM))
  574. metric[i]-=1;
  575. /*printf("%d ", metric[i]);*/
  576. }
  577. /*printf("\n");*/
  578. /* Search for the optimal tf resolution, including tf_select */
  579. tf_select = 0;
  580. for (sel=0;sel<2;sel++)
  581. {
  582. cost0 = 0;
  583. cost1 = isTransient ? 0 : lambda;
  584. for (i=1;i<len;i++)
  585. {
  586. int curr0, curr1;
  587. curr0 = IMIN(cost0, cost1 + lambda);
  588. curr1 = IMIN(cost0 + lambda, cost1);
  589. cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+0]);
  590. cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*sel+1]);
  591. }
  592. cost0 = IMIN(cost0, cost1);
  593. selcost[sel]=cost0;
  594. }
  595. /* For now, we're conservative and only allow tf_select=1 for transients.
  596. * If tests confirm it's useful for non-transients, we could allow it. */
  597. if (selcost[1]<selcost[0] && isTransient)
  598. tf_select=1;
  599. cost0 = 0;
  600. cost1 = isTransient ? 0 : lambda;
  601. /* Viterbi forward pass */
  602. for (i=1;i<len;i++)
  603. {
  604. int curr0, curr1;
  605. int from0, from1;
  606. from0 = cost0;
  607. from1 = cost1 + lambda;
  608. if (from0 < from1)
  609. {
  610. curr0 = from0;
  611. path0[i]= 0;
  612. } else {
  613. curr0 = from1;
  614. path0[i]= 1;
  615. }
  616. from0 = cost0 + lambda;
  617. from1 = cost1;
  618. if (from0 < from1)
  619. {
  620. curr1 = from0;
  621. path1[i]= 0;
  622. } else {
  623. curr1 = from1;
  624. path1[i]= 1;
  625. }
  626. cost0 = curr0 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+0]);
  627. cost1 = curr1 + abs(metric[i]-2*tf_select_table[LM][4*isTransient+2*tf_select+1]);
  628. }
  629. tf_res[len-1] = cost0 < cost1 ? 0 : 1;
  630. /* Viterbi backward pass to check the decisions */
  631. for (i=len-2;i>=0;i--)
  632. {
  633. if (tf_res[i+1] == 1)
  634. tf_res[i] = path1[i+1];
  635. else
  636. tf_res[i] = path0[i+1];
  637. }
  638. /*printf("%d %f\n", *tf_sum, tf_estimate);*/
  639. RESTORE_STACK;
  640. #ifdef FUZZING
  641. tf_select = rand()&0x1;
  642. tf_res[0] = rand()&0x1;
  643. for (i=1;i<len;i++)
  644. tf_res[i] = tf_res[i-1] ^ ((rand()&0xF) == 0);
  645. #endif
  646. return tf_select;
  647. }
  648. static void tf_encode(int start, int end, int isTransient, int *tf_res, int LM, int tf_select, ec_enc *enc)
  649. {
  650. int curr, i;
  651. int tf_select_rsv;
  652. int tf_changed;
  653. int logp;
  654. opus_uint32 budget;
  655. opus_uint32 tell;
  656. budget = enc->storage*8;
  657. tell = ec_tell(enc);
  658. logp = isTransient ? 2 : 4;
  659. /* Reserve space to code the tf_select decision. */
  660. tf_select_rsv = LM>0 && tell+logp+1 <= budget;
  661. budget -= tf_select_rsv;
  662. curr = tf_changed = 0;
  663. for (i=start;i<end;i++)
  664. {
  665. if (tell+logp<=budget)
  666. {
  667. ec_enc_bit_logp(enc, tf_res[i] ^ curr, logp);
  668. tell = ec_tell(enc);
  669. curr = tf_res[i];
  670. tf_changed |= curr;
  671. }
  672. else
  673. tf_res[i] = curr;
  674. logp = isTransient ? 4 : 5;
  675. }
  676. /* Only code tf_select if it would actually make a difference. */
  677. if (tf_select_rsv &&
  678. tf_select_table[LM][4*isTransient+0+tf_changed]!=
  679. tf_select_table[LM][4*isTransient+2+tf_changed])
  680. ec_enc_bit_logp(enc, tf_select, 1);
  681. else
  682. tf_select = 0;
  683. for (i=start;i<end;i++)
  684. tf_res[i] = tf_select_table[LM][4*isTransient+2*tf_select+tf_res[i]];
  685. /*for(i=0;i<end;i++)printf("%d ", isTransient ? tf_res[i] : LM+tf_res[i]);printf("\n");*/
  686. }
  687. static int alloc_trim_analysis(const CELTMode *m, const celt_norm *X,
  688. const opus_val16 *bandLogE, int end, int LM, int C, int N0,
  689. AnalysisInfo *analysis, opus_val16 *stereo_saving, opus_val16 tf_estimate,
  690. int intensity, opus_val16 surround_trim, int arch)
  691. {
  692. int i;
  693. opus_val32 diff=0;
  694. int c;
  695. int trim_index;
  696. opus_val16 trim = QCONST16(5.f, 8);
  697. opus_val16 logXC, logXC2;
  698. if (C==2)
  699. {
  700. opus_val16 sum = 0; /* Q10 */
  701. opus_val16 minXC; /* Q10 */
  702. /* Compute inter-channel correlation for low frequencies */
  703. for (i=0;i<8;i++)
  704. {
  705. opus_val32 partial;
  706. partial = celt_inner_prod(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
  707. (m->eBands[i+1]-m->eBands[i])<<LM, arch);
  708. sum = ADD16(sum, EXTRACT16(SHR32(partial, 18)));
  709. }
  710. sum = MULT16_16_Q15(QCONST16(1.f/8, 15), sum);
  711. sum = MIN16(QCONST16(1.f, 10), ABS16(sum));
  712. minXC = sum;
  713. for (i=8;i<intensity;i++)
  714. {
  715. opus_val32 partial;
  716. partial = celt_inner_prod(&X[m->eBands[i]<<LM], &X[N0+(m->eBands[i]<<LM)],
  717. (m->eBands[i+1]-m->eBands[i])<<LM, arch);
  718. minXC = MIN16(minXC, ABS16(EXTRACT16(SHR32(partial, 18))));
  719. }
  720. minXC = MIN16(QCONST16(1.f, 10), ABS16(minXC));
  721. /*printf ("%f\n", sum);*/
  722. /* mid-side savings estimations based on the LF average*/
  723. logXC = celt_log2(QCONST32(1.001f, 20)-MULT16_16(sum, sum));
  724. /* mid-side savings estimations based on min correlation */
  725. logXC2 = MAX16(HALF16(logXC), celt_log2(QCONST32(1.001f, 20)-MULT16_16(minXC, minXC)));
  726. #ifdef FIXED_POINT
  727. /* Compensate for Q20 vs Q14 input and convert output to Q8 */
  728. logXC = PSHR32(logXC-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8);
  729. logXC2 = PSHR32(logXC2-QCONST16(6.f, DB_SHIFT),DB_SHIFT-8);
  730. #endif
  731. trim += MAX16(-QCONST16(4.f, 8), MULT16_16_Q15(QCONST16(.75f,15),logXC));
  732. *stereo_saving = MIN16(*stereo_saving + QCONST16(0.25f, 8), -HALF16(logXC2));
  733. }
  734. /* Estimate spectral tilt */
  735. c=0; do {
  736. for (i=0;i<end-1;i++)
  737. {
  738. diff += bandLogE[i+c*m->nbEBands]*(opus_int32)(2+2*i-end);
  739. }
  740. } while (++c<C);
  741. diff /= C*(end-1);
  742. /*printf("%f\n", diff);*/
  743. trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8), SHR16(diff+QCONST16(1.f, DB_SHIFT),DB_SHIFT-8)/6 ));
  744. trim -= SHR16(surround_trim, DB_SHIFT-8);
  745. trim -= 2*SHR16(tf_estimate, 14-8);
  746. #ifndef DISABLE_FLOAT_API
  747. if (analysis->valid)
  748. {
  749. trim -= MAX16(-QCONST16(2.f, 8), MIN16(QCONST16(2.f, 8),
  750. (opus_val16)(QCONST16(2.f, 8)*(analysis->tonality_slope+.05f))));
  751. }
  752. #else
  753. (void)analysis;
  754. #endif
  755. #ifdef FIXED_POINT
  756. trim_index = PSHR32(trim, 8);
  757. #else
  758. trim_index = (int)floor(.5f+trim);
  759. #endif
  760. trim_index = IMAX(0, IMIN(10, trim_index));
  761. /*printf("%d\n", trim_index);*/
  762. #ifdef FUZZING
  763. trim_index = rand()%11;
  764. #endif
  765. return trim_index;
  766. }
  767. static int stereo_analysis(const CELTMode *m, const celt_norm *X,
  768. int LM, int N0)
  769. {
  770. int i;
  771. int thetas;
  772. opus_val32 sumLR = EPSILON, sumMS = EPSILON;
  773. /* Use the L1 norm to model the entropy of the L/R signal vs the M/S signal */
  774. for (i=0;i<13;i++)
  775. {
  776. int j;
  777. for (j=m->eBands[i]<<LM;j<m->eBands[i+1]<<LM;j++)
  778. {
  779. opus_val32 L, R, M, S;
  780. /* We cast to 32-bit first because of the -32768 case */
  781. L = EXTEND32(X[j]);
  782. R = EXTEND32(X[N0+j]);
  783. M = ADD32(L, R);
  784. S = SUB32(L, R);
  785. sumLR = ADD32(sumLR, ADD32(ABS32(L), ABS32(R)));
  786. sumMS = ADD32(sumMS, ADD32(ABS32(M), ABS32(S)));
  787. }
  788. }
  789. sumMS = MULT16_32_Q15(QCONST16(0.707107f, 15), sumMS);
  790. thetas = 13;
  791. /* We don't need thetas for lower bands with LM<=1 */
  792. if (LM<=1)
  793. thetas -= 8;
  794. return MULT16_32_Q15((m->eBands[13]<<(LM+1))+thetas, sumMS)
  795. > MULT16_32_Q15(m->eBands[13]<<(LM+1), sumLR);
  796. }
  797. #define MSWAP(a,b) do {opus_val16 tmp = a;a=b;b=tmp;} while(0)
  798. static opus_val16 median_of_5(const opus_val16 *x)
  799. {
  800. opus_val16 t0, t1, t2, t3, t4;
  801. t2 = x[2];
  802. if (x[0] > x[1])
  803. {
  804. t0 = x[1];
  805. t1 = x[0];
  806. } else {
  807. t0 = x[0];
  808. t1 = x[1];
  809. }
  810. if (x[3] > x[4])
  811. {
  812. t3 = x[4];
  813. t4 = x[3];
  814. } else {
  815. t3 = x[3];
  816. t4 = x[4];
  817. }
  818. if (t0 > t3)
  819. {
  820. MSWAP(t0, t3);
  821. MSWAP(t1, t4);
  822. }
  823. if (t2 > t1)
  824. {
  825. if (t1 < t3)
  826. return MIN16(t2, t3);
  827. else
  828. return MIN16(t4, t1);
  829. } else {
  830. if (t2 < t3)
  831. return MIN16(t1, t3);
  832. else
  833. return MIN16(t2, t4);
  834. }
  835. }
  836. static opus_val16 median_of_3(const opus_val16 *x)
  837. {
  838. opus_val16 t0, t1, t2;
  839. if (x[0] > x[1])
  840. {
  841. t0 = x[1];
  842. t1 = x[0];
  843. } else {
  844. t0 = x[0];
  845. t1 = x[1];
  846. }
  847. t2 = x[2];
  848. if (t1 < t2)
  849. return t1;
  850. else if (t0 < t2)
  851. return t2;
  852. else
  853. return t0;
  854. }
  855. static opus_val16 dynalloc_analysis(const opus_val16 *bandLogE, const opus_val16 *bandLogE2,
  856. int nbEBands, int start, int end, int C, int *offsets, int lsb_depth, const opus_int16 *logN,
  857. int isTransient, int vbr, int constrained_vbr, const opus_int16 *eBands, int LM,
  858. int effectiveBytes, opus_int32 *tot_boost_, int lfe, opus_val16 *surround_dynalloc)
  859. {
  860. int i, c;
  861. opus_int32 tot_boost=0;
  862. opus_val16 maxDepth;
  863. VARDECL(opus_val16, follower);
  864. VARDECL(opus_val16, noise_floor);
  865. SAVE_STACK;
  866. ALLOC(follower, C*nbEBands, opus_val16);
  867. ALLOC(noise_floor, C*nbEBands, opus_val16);
  868. OPUS_CLEAR(offsets, nbEBands);
  869. /* Dynamic allocation code */
  870. maxDepth=-QCONST16(31.9f, DB_SHIFT);
  871. for (i=0;i<end;i++)
  872. {
  873. /* Noise floor must take into account eMeans, the depth, the width of the bands
  874. and the preemphasis filter (approx. square of bark band ID) */
  875. noise_floor[i] = MULT16_16(QCONST16(0.0625f, DB_SHIFT),logN[i])
  876. +QCONST16(.5f,DB_SHIFT)+SHL16(9-lsb_depth,DB_SHIFT)-SHL16(eMeans[i],6)
  877. +MULT16_16(QCONST16(.0062,DB_SHIFT),(i+5)*(i+5));
  878. }
  879. c=0;do
  880. {
  881. for (i=0;i<end;i++)
  882. maxDepth = MAX16(maxDepth, bandLogE[c*nbEBands+i]-noise_floor[i]);
  883. } while (++c<C);
  884. /* Make sure that dynamic allocation can't make us bust the budget */
  885. if (effectiveBytes > 50 && LM>=1 && !lfe)
  886. {
  887. int last=0;
  888. c=0;do
  889. {
  890. opus_val16 offset;
  891. opus_val16 tmp;
  892. opus_val16 *f;
  893. f = &follower[c*nbEBands];
  894. f[0] = bandLogE2[c*nbEBands];
  895. for (i=1;i<end;i++)
  896. {
  897. /* The last band to be at least 3 dB higher than the previous one
  898. is the last we'll consider. Otherwise, we run into problems on
  899. bandlimited signals. */
  900. if (bandLogE2[c*nbEBands+i] > bandLogE2[c*nbEBands+i-1]+QCONST16(.5f,DB_SHIFT))
  901. last=i;
  902. f[i] = MIN16(f[i-1]+QCONST16(1.5f,DB_SHIFT), bandLogE2[c*nbEBands+i]);
  903. }
  904. for (i=last-1;i>=0;i--)
  905. f[i] = MIN16(f[i], MIN16(f[i+1]+QCONST16(2.f,DB_SHIFT), bandLogE2[c*nbEBands+i]));
  906. /* Combine with a median filter to avoid dynalloc triggering unnecessarily.
  907. The "offset" value controls how conservative we are -- a higher offset
  908. reduces the impact of the median filter and makes dynalloc use more bits. */
  909. offset = QCONST16(1.f, DB_SHIFT);
  910. for (i=2;i<end-2;i++)
  911. f[i] = MAX16(f[i], median_of_5(&bandLogE2[c*nbEBands+i-2])-offset);
  912. tmp = median_of_3(&bandLogE2[c*nbEBands])-offset;
  913. f[0] = MAX16(f[0], tmp);
  914. f[1] = MAX16(f[1], tmp);
  915. tmp = median_of_3(&bandLogE2[c*nbEBands+end-3])-offset;
  916. f[end-2] = MAX16(f[end-2], tmp);
  917. f[end-1] = MAX16(f[end-1], tmp);
  918. for (i=0;i<end;i++)
  919. f[i] = MAX16(f[i], noise_floor[i]);
  920. } while (++c<C);
  921. if (C==2)
  922. {
  923. for (i=start;i<end;i++)
  924. {
  925. /* Consider 24 dB "cross-talk" */
  926. follower[nbEBands+i] = MAX16(follower[nbEBands+i], follower[ i]-QCONST16(4.f,DB_SHIFT));
  927. follower[ i] = MAX16(follower[ i], follower[nbEBands+i]-QCONST16(4.f,DB_SHIFT));
  928. follower[i] = HALF16(MAX16(0, bandLogE[i]-follower[i]) + MAX16(0, bandLogE[nbEBands+i]-follower[nbEBands+i]));
  929. }
  930. } else {
  931. for (i=start;i<end;i++)
  932. {
  933. follower[i] = MAX16(0, bandLogE[i]-follower[i]);
  934. }
  935. }
  936. for (i=start;i<end;i++)
  937. follower[i] = MAX16(follower[i], surround_dynalloc[i]);
  938. /* For non-transient CBR/CVBR frames, halve the dynalloc contribution */
  939. if ((!vbr || constrained_vbr)&&!isTransient)
  940. {
  941. for (i=start;i<end;i++)
  942. follower[i] = HALF16(follower[i]);
  943. }
  944. for (i=start;i<end;i++)
  945. {
  946. int width;
  947. int boost;
  948. int boost_bits;
  949. if (i<8)
  950. follower[i] *= 2;
  951. if (i>=12)
  952. follower[i] = HALF16(follower[i]);
  953. follower[i] = MIN16(follower[i], QCONST16(4, DB_SHIFT));
  954. width = C*(eBands[i+1]-eBands[i])<<LM;
  955. if (width<6)
  956. {
  957. boost = (int)SHR32(EXTEND32(follower[i]),DB_SHIFT);
  958. boost_bits = boost*width<<BITRES;
  959. } else if (width > 48) {
  960. boost = (int)SHR32(EXTEND32(follower[i])*8,DB_SHIFT);
  961. boost_bits = (boost*width<<BITRES)/8;
  962. } else {
  963. boost = (int)SHR32(EXTEND32(follower[i])*width/6,DB_SHIFT);
  964. boost_bits = boost*6<<BITRES;
  965. }
  966. /* For CBR and non-transient CVBR frames, limit dynalloc to 1/4 of the bits */
  967. if ((!vbr || (constrained_vbr&&!isTransient))
  968. && (tot_boost+boost_bits)>>BITRES>>3 > effectiveBytes/4)
  969. {
  970. opus_int32 cap = ((effectiveBytes/4)<<BITRES<<3);
  971. offsets[i] = cap-tot_boost;
  972. tot_boost = cap;
  973. break;
  974. } else {
  975. offsets[i] = boost;
  976. tot_boost += boost_bits;
  977. }
  978. }
  979. }
  980. *tot_boost_ = tot_boost;
  981. RESTORE_STACK;
  982. return maxDepth;
  983. }
  984. static int run_prefilter(CELTEncoder *st, celt_sig *in, celt_sig *prefilter_mem, int CC, int N,
  985. int prefilter_tapset, int *pitch, opus_val16 *gain, int *qgain, int enabled, int nbAvailableBytes)
  986. {
  987. int c;
  988. VARDECL(celt_sig, _pre);
  989. celt_sig *pre[2];
  990. const CELTMode *mode;
  991. int pitch_index;
  992. opus_val16 gain1;
  993. opus_val16 pf_threshold;
  994. int pf_on;
  995. int qg;
  996. int overlap;
  997. SAVE_STACK;
  998. mode = st->mode;
  999. overlap = mode->overlap;
  1000. ALLOC(_pre, CC*(N+COMBFILTER_MAXPERIOD), celt_sig);
  1001. pre[0] = _pre;
  1002. pre[1] = _pre + (N+COMBFILTER_MAXPERIOD);
  1003. c=0; do {
  1004. OPUS_COPY(pre[c], prefilter_mem+c*COMBFILTER_MAXPERIOD, COMBFILTER_MAXPERIOD);
  1005. OPUS_COPY(pre[c]+COMBFILTER_MAXPERIOD, in+c*(N+overlap)+overlap, N);
  1006. } while (++c<CC);
  1007. if (enabled)
  1008. {
  1009. VARDECL(opus_val16, pitch_buf);
  1010. ALLOC(pitch_buf, (COMBFILTER_MAXPERIOD+N)>>1, opus_val16);
  1011. pitch_downsample(pre, pitch_buf, COMBFILTER_MAXPERIOD+N, CC, st->arch);
  1012. /* Don't search for the fir last 1.5 octave of the range because
  1013. there's too many false-positives due to short-term correlation */
  1014. pitch_search(pitch_buf+(COMBFILTER_MAXPERIOD>>1), pitch_buf, N,
  1015. COMBFILTER_MAXPERIOD-3*COMBFILTER_MINPERIOD, &pitch_index,
  1016. st->arch);
  1017. pitch_index = COMBFILTER_MAXPERIOD-pitch_index;
  1018. gain1 = remove_doubling(pitch_buf, COMBFILTER_MAXPERIOD, COMBFILTER_MINPERIOD,
  1019. N, &pitch_index, st->prefilter_period, st->prefilter_gain, st->arch);
  1020. if (pitch_index > COMBFILTER_MAXPERIOD-2)
  1021. pitch_index = COMBFILTER_MAXPERIOD-2;
  1022. gain1 = MULT16_16_Q15(QCONST16(.7f,15),gain1);
  1023. /*printf("%d %d %f %f\n", pitch_change, pitch_index, gain1, st->analysis.tonality);*/
  1024. if (st->loss_rate>2)
  1025. gain1 = HALF32(gain1);
  1026. if (st->loss_rate>4)
  1027. gain1 = HALF32(gain1);
  1028. if (st->loss_rate>8)
  1029. gain1 = 0;
  1030. } else {
  1031. gain1 = 0;
  1032. pitch_index = COMBFILTER_MINPERIOD;
  1033. }
  1034. /* Gain threshold for enabling the prefilter/postfilter */
  1035. pf_threshold = QCONST16(.2f,15);
  1036. /* Adjusting the threshold based on rate and continuity */
  1037. if (abs(pitch_index-st->prefilter_period)*10>pitch_index)
  1038. pf_threshold += QCONST16(.2f,15);
  1039. if (nbAvailableBytes<25)
  1040. pf_threshold += QCONST16(.1f,15);
  1041. if (nbAvailableBytes<35)
  1042. pf_threshold += QCONST16(.1f,15);
  1043. if (st->prefilter_gain > QCONST16(.4f,15))
  1044. pf_threshold -= QCONST16(.1f,15);
  1045. if (st->prefilter_gain > QCONST16(.55f,15))
  1046. pf_threshold -= QCONST16(.1f,15);
  1047. /* Hard threshold at 0.2 */
  1048. pf_threshold = MAX16(pf_threshold, QCONST16(.2f,15));
  1049. if (gain1<pf_threshold)
  1050. {
  1051. gain1 = 0;
  1052. pf_on = 0;
  1053. qg = 0;
  1054. } else {
  1055. /*This block is not gated by a total bits check only because
  1056. of the nbAvailableBytes check above.*/
  1057. if (ABS16(gain1-st->prefilter_gain)<QCONST16(.1f,15))
  1058. gain1=st->prefilter_gain;
  1059. #ifdef FIXED_POINT
  1060. qg = ((gain1+1536)>>10)/3-1;
  1061. #else
  1062. qg = (int)floor(.5f+gain1*32/3)-1;
  1063. #endif
  1064. qg = IMAX(0, IMIN(7, qg));
  1065. gain1 = QCONST16(0.09375f,15)*(qg+1);
  1066. pf_on = 1;
  1067. }
  1068. /*printf("%d %f\n", pitch_index, gain1);*/
  1069. c=0; do {
  1070. int offset = mode->shortMdctSize-overlap;
  1071. st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
  1072. OPUS_COPY(in+c*(N+overlap), st->in_mem+c*(overlap), overlap);
  1073. if (offset)
  1074. comb_filter(in+c*(N+overlap)+overlap, pre[c]+COMBFILTER_MAXPERIOD,
  1075. st->prefilter_period, st->prefilter_period, offset, -st->prefilter_gain, -st->prefilter_gain,
  1076. st->prefilter_tapset, st->prefilter_tapset, NULL, 0, st->arch);
  1077. comb_filter(in+c*(N+overlap)+overlap+offset, pre[c]+COMBFILTER_MAXPERIOD+offset,
  1078. st->prefilter_period, pitch_index, N-offset, -st->prefilter_gain, -gain1,
  1079. st->prefilter_tapset, prefilter_tapset, mode->window, overlap, st->arch);
  1080. OPUS_COPY(st->in_mem+c*(overlap), in+c*(N+overlap)+N, overlap);
  1081. if (N>COMBFILTER_MAXPERIOD)
  1082. {
  1083. OPUS_COPY(prefilter_mem+c*COMBFILTER_MAXPERIOD, pre[c]+N, COMBFILTER_MAXPERIOD);
  1084. } else {
  1085. OPUS_MOVE(prefilter_mem+c*COMBFILTER_MAXPERIOD, prefilter_mem+c*COMBFILTER_MAXPERIOD+N, COMBFILTER_MAXPERIOD-N);
  1086. OPUS_COPY(prefilter_mem+c*COMBFILTER_MAXPERIOD+COMBFILTER_MAXPERIOD-N, pre[c]+COMBFILTER_MAXPERIOD, N);
  1087. }
  1088. } while (++c<CC);
  1089. RESTORE_STACK;
  1090. *gain = gain1;
  1091. *pitch = pitch_index;
  1092. *qgain = qg;
  1093. return pf_on;
  1094. }
  1095. static int compute_vbr(const CELTMode *mode, AnalysisInfo *analysis, opus_int32 base_target,
  1096. int LM, opus_int32 bitrate, int lastCodedBands, int C, int intensity,
  1097. int constrained_vbr, opus_val16 stereo_saving, int tot_boost,
  1098. opus_val16 tf_estimate, int pitch_change, opus_val16 maxDepth,
  1099. int variable_duration, int lfe, int has_surround_mask, opus_val16 surround_masking,
  1100. opus_val16 temporal_vbr)
  1101. {
  1102. /* The target rate in 8th bits per frame */
  1103. opus_int32 target;
  1104. int coded_bins;
  1105. int coded_bands;
  1106. opus_val16 tf_calibration;
  1107. int nbEBands;
  1108. const opus_int16 *eBands;
  1109. nbEBands = mode->nbEBands;
  1110. eBands = mode->eBands;
  1111. coded_bands = lastCodedBands ? lastCodedBands : nbEBands;
  1112. coded_bins = eBands[coded_bands]<<LM;
  1113. if (C==2)
  1114. coded_bins += eBands[IMIN(intensity, coded_bands)]<<LM;
  1115. target = base_target;
  1116. /*printf("%f %f %f %f %d %d ", st->analysis.activity, st->analysis.tonality, tf_estimate, st->stereo_saving, tot_boost, coded_bands);*/
  1117. #ifndef DISABLE_FLOAT_API
  1118. if (analysis->valid && analysis->activity<.4)
  1119. target -= (opus_int32)((coded_bins<<BITRES)*(.4f-analysis->activity));
  1120. #endif
  1121. /* Stereo savings */
  1122. if (C==2)
  1123. {
  1124. int coded_stereo_bands;
  1125. int coded_stereo_dof;
  1126. opus_val16 max_frac;
  1127. coded_stereo_bands = IMIN(intensity, coded_bands);
  1128. coded_stereo_dof = (eBands[coded_stereo_bands]<<LM)-coded_stereo_bands;
  1129. /* Maximum fraction of the bits we can save if the signal is mono. */
  1130. max_frac = DIV32_16(MULT16_16(QCONST16(0.8f, 15), coded_stereo_dof), coded_bins);
  1131. stereo_saving = MIN16(stereo_saving, QCONST16(1.f, 8));
  1132. /*printf("%d %d %d ", coded_stereo_dof, coded_bins, tot_boost);*/
  1133. target -= (opus_int32)MIN32(MULT16_32_Q15(max_frac,target),
  1134. SHR32(MULT16_16(stereo_saving-QCONST16(0.1f,8),(coded_stereo_dof<<BITRES)),8));
  1135. }
  1136. /* Boost the rate according to dynalloc (minus the dynalloc average for calibration). */
  1137. target += tot_boost-(16<<LM);
  1138. /* Apply transient boost, compensating for average boost. */
  1139. tf_calibration = variable_duration==OPUS_FRAMESIZE_VARIABLE ?
  1140. QCONST16(0.02f,14) : QCONST16(0.04f,14);
  1141. target += (opus_int32)SHL32(MULT16_32_Q15(tf_estimate-tf_calibration, target),1);
  1142. #ifndef DISABLE_FLOAT_API
  1143. /* Apply tonality boost */
  1144. if (analysis->valid && !lfe)
  1145. {
  1146. opus_int32 tonal_target;
  1147. float tonal;
  1148. /* Tonality boost (compensating for the average). */
  1149. tonal = MAX16(0.f,analysis->tonality-.15f)-0.09f;
  1150. tonal_target = target + (opus_int32)((coded_bins<<BITRES)*1.2f*tonal);
  1151. if (pitch_change)
  1152. tonal_target += (opus_int32)((coded_bins<<BITRES)*.8f);
  1153. /*printf("%f %f ", analysis->tonality, tonal);*/
  1154. target = tonal_target;
  1155. }
  1156. #else
  1157. (void)analysis;
  1158. (void)pitch_change;
  1159. #endif
  1160. if (has_surround_mask&&!lfe)
  1161. {
  1162. opus_int32 surround_target = target + (opus_int32)SHR32(MULT16_16(surround_masking,coded_bins<<BITRES), DB_SHIFT);
  1163. /*printf("%f %d %d %d %d %d %d ", surround_masking, coded_bins, st->end, st->intensity, surround_target, target, st->bitrate);*/
  1164. target = IMAX(target/4, surround_target);
  1165. }
  1166. {
  1167. opus_int32 floor_depth;
  1168. int bins;
  1169. bins = eBands[nbEBands-2]<<LM;
  1170. /*floor_depth = SHR32(MULT16_16((C*bins<<BITRES),celt_log2(SHL32(MAX16(1,sample_max),13))), DB_SHIFT);*/
  1171. floor_depth = (opus_int32)SHR32(MULT16_16((C*bins<<BITRES),maxDepth), DB_SHIFT);
  1172. floor_depth = IMAX(floor_depth, target>>2);
  1173. target = IMIN(target, floor_depth);
  1174. /*printf("%f %d\n", maxDepth, floor_depth);*/
  1175. }
  1176. if ((!has_surround_mask||lfe) && (constrained_vbr || bitrate<64000))
  1177. {
  1178. opus_val16 rate_factor = Q15ONE;
  1179. if (bitrate < 64000)
  1180. {
  1181. #ifdef FIXED_POINT
  1182. rate_factor = MAX16(0,(bitrate-32000));
  1183. #else
  1184. rate_factor = MAX16(0,(1.f/32768)*(bitrate-32000));
  1185. #endif
  1186. }
  1187. if (constrained_vbr)
  1188. rate_factor = MIN16(rate_factor, QCONST16(0.67f, 15));
  1189. target = base_target + (opus_int32)MULT16_32_Q15(rate_factor, target-base_target);
  1190. }
  1191. if (!has_surround_mask && tf_estimate < QCONST16(.2f, 14))
  1192. {
  1193. opus_val16 amount;
  1194. opus_val16 tvbr_factor;
  1195. amount = MULT16_16_Q15(QCONST16(.0000031f, 30), IMAX(0, IMIN(32000, 96000-bitrate)));
  1196. tvbr_factor = SHR32(MULT16_16(temporal_vbr, amount), DB_SHIFT);
  1197. target += (opus_int32)MULT16_32_Q15(tvbr_factor, target);
  1198. }
  1199. /* Don't allow more than doubling the rate */
  1200. target = IMIN(2*base_target, target);
  1201. return target;
  1202. }
  1203. int celt_encode_with_ec(CELTEncoder * OPUS_RESTRICT st, const opus_val16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes, ec_enc *enc)
  1204. {
  1205. int i, c, N;
  1206. opus_int32 bits;
  1207. ec_enc _enc;
  1208. VARDECL(celt_sig, in);
  1209. VARDECL(celt_sig, freq);
  1210. VARDECL(celt_norm, X);
  1211. VARDECL(celt_ener, bandE);
  1212. VARDECL(opus_val16, bandLogE);
  1213. VARDECL(opus_val16, bandLogE2);
  1214. VARDECL(int, fine_quant);
  1215. VARDECL(opus_val16, error);
  1216. VARDECL(int, pulses);
  1217. VARDECL(int, cap);
  1218. VARDECL(int, offsets);
  1219. VARDECL(int, fine_priority);
  1220. VARDECL(int, tf_res);
  1221. VARDECL(unsigned char, collapse_masks);
  1222. celt_sig *prefilter_mem;
  1223. opus_val16 *oldBandE, *oldLogE, *oldLogE2;
  1224. int shortBlocks=0;
  1225. int isTransient=0;
  1226. const int CC = st->channels;
  1227. const int C = st->stream_channels;
  1228. int LM, M;
  1229. int tf_select;
  1230. int nbFilledBytes, nbAvailableBytes;
  1231. int start;
  1232. int end;
  1233. int effEnd;
  1234. int codedBands;
  1235. int tf_sum;
  1236. int alloc_trim;
  1237. int pitch_index=COMBFILTER_MINPERIOD;
  1238. opus_val16 gain1 = 0;
  1239. int dual_stereo=0;
  1240. int effectiveBytes;
  1241. int dynalloc_logp;
  1242. opus_int32 vbr_rate;
  1243. opus_int32 total_bits;
  1244. opus_int32 total_boost;
  1245. opus_int32 balance;
  1246. opus_int32 tell;
  1247. int prefilter_tapset=0;
  1248. int pf_on;
  1249. int anti_collapse_rsv;
  1250. int anti_collapse_on=0;
  1251. int silence=0;
  1252. int tf_chan = 0;
  1253. opus_val16 tf_estimate;
  1254. int pitch_change=0;
  1255. opus_int32 tot_boost;
  1256. opus_val32 sample_max;
  1257. opus_val16 maxDepth;
  1258. const OpusCustomMode *mode;
  1259. int nbEBands;
  1260. int overlap;
  1261. const opus_int16 *eBands;
  1262. int secondMdct;
  1263. int signalBandwidth;
  1264. int transient_got_disabled=0;
  1265. opus_val16 surround_masking=0;
  1266. opus_val16 temporal_vbr=0;
  1267. opus_val16 surround_trim = 0;
  1268. opus_int32 equiv_rate = 510000;
  1269. VARDECL(opus_val16, surround_dynalloc);
  1270. ALLOC_STACK;
  1271. mode = st->mode;
  1272. nbEBands = mode->nbEBands;
  1273. overlap = mode->overlap;
  1274. eBands = mode->eBands;
  1275. start = st->start;
  1276. end = st->end;
  1277. tf_estimate = 0;
  1278. if (nbCompressedBytes<2 || pcm==NULL)
  1279. {
  1280. RESTORE_STACK;
  1281. return OPUS_BAD_ARG;
  1282. }
  1283. frame_size *= st->upsample;
  1284. for (LM=0;LM<=mode->maxLM;LM++)
  1285. if (mode->shortMdctSize<<LM==frame_size)
  1286. break;
  1287. if (LM>mode->maxLM)
  1288. {
  1289. RESTORE_STACK;
  1290. return OPUS_BAD_ARG;
  1291. }
  1292. M=1<<LM;
  1293. N = M*mode->shortMdctSize;
  1294. prefilter_mem = st->in_mem+CC*(overlap);
  1295. oldBandE = (opus_val16*)(st->in_mem+CC*(overlap+COMBFILTER_MAXPERIOD));
  1296. oldLogE = oldBandE + CC*nbEBands;
  1297. oldLogE2 = oldLogE + CC*nbEBands;
  1298. if (enc==NULL)
  1299. {
  1300. tell=1;
  1301. nbFilledBytes=0;
  1302. } else {
  1303. tell=ec_tell(enc);
  1304. nbFilledBytes=(tell+4)>>3;
  1305. }
  1306. #ifdef CUSTOM_MODES
  1307. if (st->signalling && enc==NULL)
  1308. {
  1309. int tmp = (mode->effEBands-end)>>1;
  1310. end = st->end = IMAX(1, mode->effEBands-tmp);
  1311. compressed[0] = tmp<<5;
  1312. compressed[0] |= LM<<3;
  1313. compressed[0] |= (C==2)<<2;
  1314. /* Convert "standard mode" to Opus header */
  1315. if (mode->Fs==48000 && mode->shortMdctSize==120)
  1316. {
  1317. int c0 = toOpus(compressed[0]);
  1318. if (c0<0)
  1319. {
  1320. RESTORE_STACK;
  1321. return OPUS_BAD_ARG;
  1322. }
  1323. compressed[0] = c0;
  1324. }
  1325. compressed++;
  1326. nbCompressedBytes--;
  1327. }
  1328. #else
  1329. celt_assert(st->signalling==0);
  1330. #endif
  1331. /* Can't produce more than 1275 output bytes */
  1332. nbCompressedBytes = IMIN(nbCompressedBytes,1275);
  1333. nbAvailableBytes = nbCompressedBytes - nbFilledBytes;
  1334. if (st->vbr && st->bitrate!=OPUS_BITRATE_MAX)
  1335. {
  1336. opus_int32 den=mode->Fs>>BITRES;
  1337. vbr_rate=(st->bitrate*frame_size+(den>>1))/den;
  1338. #ifdef CUSTOM_MODES
  1339. if (st->signalling)
  1340. vbr_rate -= 8<<BITRES;
  1341. #endif
  1342. effectiveBytes = vbr_rate>>(3+BITRES);
  1343. } else {
  1344. opus_int32 tmp;
  1345. vbr_rate = 0;
  1346. tmp = st->bitrate*frame_size;
  1347. if (tell>1)
  1348. tmp += tell;
  1349. if (st->bitrate!=OPUS_BITRATE_MAX)
  1350. nbCompressedBytes = IMAX(2, IMIN(nbCompressedBytes,
  1351. (tmp+4*mode->Fs)/(8*mode->Fs)-!!st->signalling));
  1352. effectiveBytes = nbCompressedBytes;
  1353. }
  1354. if (st->bitrate != OPUS_BITRATE_MAX)
  1355. equiv_rate = st->bitrate - (40*C+20)*((400>>LM) - 50);
  1356. if (enc==NULL)
  1357. {
  1358. ec_enc_init(&_enc, compressed, nbCompressedBytes);
  1359. enc = &_enc;
  1360. }
  1361. if (vbr_rate>0)
  1362. {
  1363. /* Computes the max bit-rate allowed in VBR mode to avoid violating the
  1364. target rate and buffering.
  1365. We must do this up front so that bust-prevention logic triggers
  1366. correctly if we don't have enough bits. */
  1367. if (st->constrained_vbr)
  1368. {
  1369. opus_int32 vbr_bound;
  1370. opus_int32 max_allowed;
  1371. /* We could use any multiple of vbr_rate as bound (depending on the
  1372. delay).
  1373. This is clamped to ensure we use at least two bytes if the encoder
  1374. was entirely empty, but to allow 0 in hybrid mode. */
  1375. vbr_bound = vbr_rate;
  1376. max_allowed = IMIN(IMAX(tell==1?2:0,
  1377. (vbr_rate+vbr_bound-st->vbr_reservoir)>>(BITRES+3)),
  1378. nbAvailableBytes);
  1379. if(max_allowed < nbAvailableBytes)
  1380. {
  1381. nbCompressedBytes = nbFilledBytes+max_allowed;
  1382. nbAvailableBytes = max_allowed;
  1383. ec_enc_shrink(enc, nbCompressedBytes);
  1384. }
  1385. }
  1386. }
  1387. total_bits = nbCompressedBytes*8;
  1388. effEnd = end;
  1389. if (effEnd > mode->effEBands)
  1390. effEnd = mode->effEBands;
  1391. ALLOC(in, CC*(N+overlap), celt_sig);
  1392. sample_max=MAX32(st->overlap_max, celt_maxabs16(pcm, C*(N-overlap)/st->upsample));
  1393. st->overlap_max=celt_maxabs16(pcm+C*(N-overlap)/st->upsample, C*overlap/st->upsample);
  1394. sample_max=MAX32(sample_max, st->overlap_max);
  1395. #ifdef FIXED_POINT
  1396. silence = (sample_max==0);
  1397. #else
  1398. silence = (sample_max <= (opus_val16)1/(1<<st->lsb_depth));
  1399. #endif
  1400. #ifdef FUZZING
  1401. if ((rand()&0x3F)==0)
  1402. silence = 1;
  1403. #endif
  1404. if (tell==1)
  1405. ec_enc_bit_logp(enc, silence, 15);
  1406. else
  1407. silence=0;
  1408. if (silence)
  1409. {
  1410. /*In VBR mode there is no need to send more than the minimum. */
  1411. if (vbr_rate>0)
  1412. {
  1413. effectiveBytes=nbCompressedBytes=IMIN(nbCompressedBytes, nbFilledBytes+2);
  1414. total_bits=nbCompressedBytes*8;
  1415. nbAvailableBytes=2;
  1416. ec_enc_shrink(enc, nbCompressedBytes);
  1417. }
  1418. /* Pretend we've filled all the remaining bits with zeros
  1419. (that's what the initialiser did anyway) */
  1420. tell = nbCompressedBytes*8;
  1421. enc->nbits_total+=tell-ec_tell(enc);
  1422. }
  1423. c=0; do {
  1424. int need_clip=0;
  1425. #ifndef FIXED_POINT
  1426. need_clip = st->clip && sample_max>65536.f;
  1427. #endif
  1428. celt_preemphasis(pcm+c, in+c*(N+overlap)+overlap, N, CC, st->upsample,
  1429. mode->preemph, st->preemph_memE+c, need_clip);
  1430. } while (++c<CC);
  1431. /* Find pitch period and gain */
  1432. {
  1433. int enabled;
  1434. int qg;
  1435. enabled = ((st->lfe&&nbAvailableBytes>3) || nbAvailableBytes>12*C) && start==0 && !silence && !st->disable_pf
  1436. && st->complexity >= 5 && !(st->consec_transient && LM!=3 && st->variable_duration==OPUS_FRAMESIZE_VARIABLE);
  1437. prefilter_tapset = st->tapset_decision;
  1438. pf_on = run_prefilter(st, in, prefilter_mem, CC, N, prefilter_tapset, &pitch_index, &gain1, &qg, enabled, nbAvailableBytes);
  1439. if ((gain1 > QCONST16(.4f,15) || st->prefilter_gain > QCONST16(.4f,15)) && (!st->analysis.valid || st->analysis.tonality > .3)
  1440. && (pitch_index > 1.26*st->prefilter_period || pitch_index < .79*st->prefilter_period))
  1441. pitch_change = 1;
  1442. if (pf_on==0)
  1443. {
  1444. if(start==0 && tell+16<=total_bits)
  1445. ec_enc_bit_logp(enc, 0, 1);
  1446. } else {
  1447. /*This block is not gated by a total bits check only because
  1448. of the nbAvailableBytes check above.*/
  1449. int octave;
  1450. ec_enc_bit_logp(enc, 1, 1);
  1451. pitch_index += 1;
  1452. octave = EC_ILOG(pitch_index)-5;
  1453. ec_enc_uint(enc, octave, 6);
  1454. ec_enc_bits(enc, pitch_index-(16<<octave), 4+octave);
  1455. pitch_index -= 1;
  1456. ec_enc_bits(enc, qg, 3);
  1457. ec_enc_icdf(enc, prefilter_tapset, tapset_icdf, 2);
  1458. }
  1459. }
  1460. isTransient = 0;
  1461. shortBlocks = 0;
  1462. if (st->complexity >= 1 && !st->lfe)
  1463. {
  1464. isTransient = transient_analysis(in, N+overlap, CC,
  1465. &tf_estimate, &tf_chan);
  1466. }
  1467. if (LM>0 && ec_tell(enc)+3<=total_bits)
  1468. {
  1469. if (isTransient)
  1470. shortBlocks = M;
  1471. } else {
  1472. isTransient = 0;
  1473. transient_got_disabled=1;
  1474. }
  1475. ALLOC(freq, CC*N, celt_sig); /**< Interleaved signal MDCTs */
  1476. ALLOC(bandE,nbEBands*CC, celt_ener);
  1477. ALLOC(bandLogE,nbEBands*CC, opus_val16);
  1478. secondMdct = shortBlocks && st->complexity>=8;
  1479. ALLOC(bandLogE2, C*nbEBands, opus_val16);
  1480. if (secondMdct)
  1481. {
  1482. compute_mdcts(mode, 0, in, freq, C, CC, LM, st->upsample, st->arch);
  1483. compute_band_energies(mode, freq, bandE, effEnd, C, LM);
  1484. amp2Log2(mode, effEnd, end, bandE, bandLogE2, C);
  1485. for (i=0;i<C*nbEBands;i++)
  1486. bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT));
  1487. }
  1488. compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
  1489. if (CC==2&&C==1)
  1490. tf_chan = 0;
  1491. compute_band_energies(mode, freq, bandE, effEnd, C, LM);
  1492. if (st->lfe)
  1493. {
  1494. for (i=2;i<end;i++)
  1495. {
  1496. bandE[i] = IMIN(bandE[i], MULT16_32_Q15(QCONST16(1e-4f,15),bandE[0]));
  1497. bandE[i] = MAX32(bandE[i], EPSILON);
  1498. }
  1499. }
  1500. amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
  1501. ALLOC(surround_dynalloc, C*nbEBands, opus_val16);
  1502. OPUS_CLEAR(surround_dynalloc, end);
  1503. /* This computes how much masking takes place between surround channels */
  1504. if (start==0&&st->energy_mask&&!st->lfe)
  1505. {
  1506. int mask_end;
  1507. int midband;
  1508. int count_dynalloc;
  1509. opus_val32 mask_avg=0;
  1510. opus_val32 diff=0;
  1511. int count=0;
  1512. mask_end = IMAX(2,st->lastCodedBands);
  1513. for (c=0;c<C;c++)
  1514. {
  1515. for(i=0;i<mask_end;i++)
  1516. {
  1517. opus_val16 mask;
  1518. mask = MAX16(MIN16(st->energy_mask[nbEBands*c+i],
  1519. QCONST16(.25f, DB_SHIFT)), -QCONST16(2.0f, DB_SHIFT));
  1520. if (mask > 0)
  1521. mask = HALF16(mask);
  1522. mask_avg += MULT16_16(mask, eBands[i+1]-eBands[i]);
  1523. count += eBands[i+1]-eBands[i];
  1524. diff += MULT16_16(mask, 1+2*i-mask_end);
  1525. }
  1526. }
  1527. celt_assert(count>0);
  1528. mask_avg = DIV32_16(mask_avg,count);
  1529. mask_avg += QCONST16(.2f, DB_SHIFT);
  1530. diff = diff*6/(C*(mask_end-1)*(mask_end+1)*mask_end);
  1531. /* Again, being conservative */
  1532. diff = HALF32(diff);
  1533. diff = MAX32(MIN32(diff, QCONST32(.031f, DB_SHIFT)), -QCONST32(.031f, DB_SHIFT));
  1534. /* Find the band that's in the middle of the coded spectrum */
  1535. for (midband=0;eBands[midband+1] < eBands[mask_end]/2;midband++);
  1536. count_dynalloc=0;
  1537. for(i=0;i<mask_end;i++)
  1538. {
  1539. opus_val32 lin;
  1540. opus_val16 unmask;
  1541. lin = mask_avg + diff*(i-midband);
  1542. if (C==2)
  1543. unmask = MAX16(st->energy_mask[i], st->energy_mask[nbEBands+i]);
  1544. else
  1545. unmask = st->energy_mask[i];
  1546. unmask = MIN16(unmask, QCONST16(.0f, DB_SHIFT));
  1547. unmask -= lin;
  1548. if (unmask > QCONST16(.25f, DB_SHIFT))
  1549. {
  1550. surround_dynalloc[i] = unmask - QCONST16(.25f, DB_SHIFT);
  1551. count_dynalloc++;
  1552. }
  1553. }
  1554. if (count_dynalloc>=3)
  1555. {
  1556. /* If we need dynalloc in many bands, it's probably because our
  1557. initial masking rate was too low. */
  1558. mask_avg += QCONST16(.25f, DB_SHIFT);
  1559. if (mask_avg>0)
  1560. {
  1561. /* Something went really wrong in the original calculations,
  1562. disabling masking. */
  1563. mask_avg = 0;
  1564. diff = 0;
  1565. OPUS_CLEAR(surround_dynalloc, mask_end);
  1566. } else {
  1567. for(i=0;i<mask_end;i++)
  1568. surround_dynalloc[i] = MAX16(0, surround_dynalloc[i]-QCONST16(.25f, DB_SHIFT));
  1569. }
  1570. }
  1571. mask_avg += QCONST16(.2f, DB_SHIFT);
  1572. /* Convert to 1/64th units used for the trim */
  1573. surround_trim = 64*diff;
  1574. /*printf("%d %d ", mask_avg, surround_trim);*/
  1575. surround_masking = mask_avg;
  1576. }
  1577. /* Temporal VBR (but not for LFE) */
  1578. if (!st->lfe)
  1579. {
  1580. opus_val16 follow=-QCONST16(10.0f,DB_SHIFT);
  1581. opus_val32 frame_avg=0;
  1582. opus_val16 offset = shortBlocks?HALF16(SHL16(LM, DB_SHIFT)):0;
  1583. for(i=start;i<end;i++)
  1584. {
  1585. follow = MAX16(follow-QCONST16(1.f, DB_SHIFT), bandLogE[i]-offset);
  1586. if (C==2)
  1587. follow = MAX16(follow, bandLogE[i+nbEBands]-offset);
  1588. frame_avg += follow;
  1589. }
  1590. frame_avg /= (end-start);
  1591. temporal_vbr = SUB16(frame_avg,st->spec_avg);
  1592. temporal_vbr = MIN16(QCONST16(3.f, DB_SHIFT), MAX16(-QCONST16(1.5f, DB_SHIFT), temporal_vbr));
  1593. st->spec_avg += MULT16_16_Q15(QCONST16(.02f, 15), temporal_vbr);
  1594. }
  1595. /*for (i=0;i<21;i++)
  1596. printf("%f ", bandLogE[i]);
  1597. printf("\n");*/
  1598. if (!secondMdct)
  1599. {
  1600. OPUS_COPY(bandLogE2, bandLogE, C*nbEBands);
  1601. }
  1602. /* Last chance to catch any transient we might have missed in the
  1603. time-domain analysis */
  1604. if (LM>0 && ec_tell(enc)+3<=total_bits && !isTransient && st->complexity>=5 && !st->lfe)
  1605. {
  1606. if (patch_transient_decision(bandLogE, oldBandE, nbEBands, start, end, C))
  1607. {
  1608. isTransient = 1;
  1609. shortBlocks = M;
  1610. compute_mdcts(mode, shortBlocks, in, freq, C, CC, LM, st->upsample, st->arch);
  1611. compute_band_energies(mode, freq, bandE, effEnd, C, LM);
  1612. amp2Log2(mode, effEnd, end, bandE, bandLogE, C);
  1613. /* Compensate for the scaling of short vs long mdcts */
  1614. for (i=0;i<C*nbEBands;i++)
  1615. bandLogE2[i] += HALF16(SHL16(LM, DB_SHIFT));
  1616. tf_estimate = QCONST16(.2f,14);
  1617. }
  1618. }
  1619. if (LM>0 && ec_tell(enc)+3<=total_bits)
  1620. ec_enc_bit_logp(enc, isTransient, 3);
  1621. ALLOC(X, C*N, celt_norm); /**< Interleaved normalised MDCTs */
  1622. /* Band normalisation */
  1623. normalise_bands(mode, freq, X, bandE, effEnd, C, M);
  1624. ALLOC(tf_res, nbEBands, int);
  1625. /* Disable variable tf resolution for hybrid and at very low bitrate */
  1626. if (effectiveBytes>=15*C && start==0 && st->complexity>=2 && !st->lfe)
  1627. {
  1628. int lambda;
  1629. if (effectiveBytes<40)
  1630. lambda = 12;
  1631. else if (effectiveBytes<60)
  1632. lambda = 6;
  1633. else if (effectiveBytes<100)
  1634. lambda = 4;
  1635. else
  1636. lambda = 3;
  1637. lambda*=2;
  1638. tf_select = tf_analysis(mode, effEnd, isTransient, tf_res, lambda, X, N, LM, &tf_sum, tf_estimate, tf_chan);
  1639. for (i=effEnd;i<end;i++)
  1640. tf_res[i] = tf_res[effEnd-1];
  1641. } else {
  1642. tf_sum = 0;
  1643. for (i=0;i<end;i++)
  1644. tf_res[i] = isTransient;
  1645. tf_select=0;
  1646. }
  1647. ALLOC(error, C*nbEBands, opus_val16);
  1648. quant_coarse_energy(mode, start, end, effEnd, bandLogE,
  1649. oldBandE, total_bits, error, enc,
  1650. C, LM, nbAvailableBytes, st->force_intra,
  1651. &st->delayedIntra, st->complexity >= 4, st->loss_rate, st->lfe);
  1652. tf_encode(start, end, isTransient, tf_res, LM, tf_select, enc);
  1653. if (ec_tell(enc)+4<=total_bits)
  1654. {
  1655. if (st->lfe)
  1656. {
  1657. st->tapset_decision = 0;
  1658. st->spread_decision = SPREAD_NORMAL;
  1659. } else if (shortBlocks || st->complexity < 3 || nbAvailableBytes < 10*C || start != 0)
  1660. {
  1661. if (st->complexity == 0)
  1662. st->spread_decision = SPREAD_NONE;
  1663. else
  1664. st->spread_decision = SPREAD_NORMAL;
  1665. } else {
  1666. /* Disable new spreading+tapset estimator until we can show it works
  1667. better than the old one. So far it seems like spreading_decision()
  1668. works best. */
  1669. #if 0
  1670. if (st->analysis.valid)
  1671. {
  1672. static const opus_val16 spread_thresholds[3] = {-QCONST16(.6f, 15), -QCONST16(.2f, 15), -QCONST16(.07f, 15)};
  1673. static const opus_val16 spread_histeresis[3] = {QCONST16(.15f, 15), QCONST16(.07f, 15), QCONST16(.02f, 15)};
  1674. static const opus_val16 tapset_thresholds[2] = {QCONST16(.0f, 15), QCONST16(.15f, 15)};
  1675. static const opus_val16 tapset_histeresis[2] = {QCONST16(.1f, 15), QCONST16(.05f, 15)};
  1676. st->spread_decision = hysteresis_decision(-st->analysis.tonality, spread_thresholds, spread_histeresis, 3, st->spread_decision);
  1677. st->tapset_decision = hysteresis_decision(st->analysis.tonality_slope, tapset_thresholds, tapset_histeresis, 2, st->tapset_decision);
  1678. } else
  1679. #endif
  1680. {
  1681. st->spread_decision = spreading_decision(mode, X,
  1682. &st->tonal_average, st->spread_decision, &st->hf_average,
  1683. &st->tapset_decision, pf_on&&!shortBlocks, effEnd, C, M);
  1684. }
  1685. /*printf("%d %d\n", st->tapset_decision, st->spread_decision);*/
  1686. /*printf("%f %d %f %d\n\n", st->analysis.tonality, st->spread_decision, st->analysis.tonality_slope, st->tapset_decision);*/
  1687. }
  1688. ec_enc_icdf(enc, st->spread_decision, spread_icdf, 5);
  1689. }
  1690. ALLOC(offsets, nbEBands, int);
  1691. maxDepth = dynalloc_analysis(bandLogE, bandLogE2, nbEBands, start, end, C, offsets,
  1692. st->lsb_depth, mode->logN, isTransient, st->vbr, st->constrained_vbr,
  1693. eBands, LM, effectiveBytes, &tot_boost, st->lfe, surround_dynalloc);
  1694. /* For LFE, everything interesting is in the first band */
  1695. if (st->lfe)
  1696. offsets[0] = IMIN(8, effectiveBytes/3);
  1697. ALLOC(cap, nbEBands, int);
  1698. init_caps(mode,cap,LM,C);
  1699. dynalloc_logp = 6;
  1700. total_bits<<=BITRES;
  1701. total_boost = 0;
  1702. tell = ec_tell_frac(enc);
  1703. for (i=start;i<end;i++)
  1704. {
  1705. int width, quanta;
  1706. int dynalloc_loop_logp;
  1707. int boost;
  1708. int j;
  1709. width = C*(eBands[i+1]-eBands[i])<<LM;
  1710. /* quanta is 6 bits, but no more than 1 bit/sample
  1711. and no less than 1/8 bit/sample */
  1712. quanta = IMIN(width<<BITRES, IMAX(6<<BITRES, width));
  1713. dynalloc_loop_logp = dynalloc_logp;
  1714. boost = 0;
  1715. for (j = 0; tell+(dynalloc_loop_logp<<BITRES) < total_bits-total_boost
  1716. && boost < cap[i]; j++)
  1717. {
  1718. int flag;
  1719. flag = j<offsets[i];
  1720. ec_enc_bit_logp(enc, flag, dynalloc_loop_logp);
  1721. tell = ec_tell_frac(enc);
  1722. if (!flag)
  1723. break;
  1724. boost += quanta;
  1725. total_boost += quanta;
  1726. dynalloc_loop_logp = 1;
  1727. }
  1728. /* Making dynalloc more likely */
  1729. if (j)
  1730. dynalloc_logp = IMAX(2, dynalloc_logp-1);
  1731. offsets[i] = boost;
  1732. }
  1733. if (C==2)
  1734. {
  1735. static const opus_val16 intensity_thresholds[21]=
  1736. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 off*/
  1737. { 1, 2, 3, 4, 5, 6, 7, 8,16,24,36,44,50,56,62,67,72,79,88,106,134};
  1738. static const opus_val16 intensity_histeresis[21]=
  1739. { 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 5, 6, 8, 8};
  1740. /* Always use MS for 2.5 ms frames until we can do a better analysis */
  1741. if (LM!=0)
  1742. dual_stereo = stereo_analysis(mode, X, LM, N);
  1743. st->intensity = hysteresis_decision((opus_val16)(equiv_rate/1000),
  1744. intensity_thresholds, intensity_histeresis, 21, st->intensity);
  1745. st->intensity = IMIN(end,IMAX(start, st->intensity));
  1746. }
  1747. alloc_trim = 5;
  1748. if (tell+(6<<BITRES) <= total_bits - total_boost)
  1749. {
  1750. if (st->lfe)
  1751. alloc_trim = 5;
  1752. else
  1753. alloc_trim = alloc_trim_analysis(mode, X, bandLogE,
  1754. end, LM, C, N, &st->analysis, &st->stereo_saving, tf_estimate,
  1755. st->intensity, surround_trim, st->arch);
  1756. ec_enc_icdf(enc, alloc_trim, trim_icdf, 7);
  1757. tell = ec_tell_frac(enc);
  1758. }
  1759. /* Variable bitrate */
  1760. if (vbr_rate>0)
  1761. {
  1762. opus_val16 alpha;
  1763. opus_int32 delta;
  1764. /* The target rate in 8th bits per frame */
  1765. opus_int32 target, base_target;
  1766. opus_int32 min_allowed;
  1767. int lm_diff = mode->maxLM - LM;
  1768. /* Don't attempt to use more than 510 kb/s, even for frames smaller than 20 ms.
  1769. The CELT allocator will just not be able to use more than that anyway. */
  1770. nbCompressedBytes = IMIN(nbCompressedBytes,1275>>(3-LM));
  1771. base_target = vbr_rate - ((40*C+20)<<BITRES);
  1772. if (st->constrained_vbr)
  1773. base_target += (st->vbr_offset>>lm_diff);
  1774. target = compute_vbr(mode, &st->analysis, base_target, LM, equiv_rate,
  1775. st->lastCodedBands, C, st->intensity, st->constrained_vbr,
  1776. st->stereo_saving, tot_boost, tf_estimate, pitch_change, maxDepth,
  1777. st->variable_duration, st->lfe, st->energy_mask!=NULL, surround_masking,
  1778. temporal_vbr);
  1779. /* The current offset is removed from the target and the space used
  1780. so far is added*/
  1781. target=target+tell;
  1782. /* In VBR mode the frame size must not be reduced so much that it would
  1783. result in the encoder running out of bits.
  1784. The margin of 2 bytes ensures that none of the bust-prevention logic
  1785. in the decoder will have triggered so far. */
  1786. min_allowed = ((tell+total_boost+(1<<(BITRES+3))-1)>>(BITRES+3)) + 2 - nbFilledBytes;
  1787. nbAvailableBytes = (target+(1<<(BITRES+2)))>>(BITRES+3);
  1788. nbAvailableBytes = IMAX(min_allowed,nbAvailableBytes);
  1789. nbAvailableBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes) - nbFilledBytes;
  1790. /* By how much did we "miss" the target on that frame */
  1791. delta = target - vbr_rate;
  1792. target=nbAvailableBytes<<(BITRES+3);
  1793. /*If the frame is silent we don't adjust our drift, otherwise
  1794. the encoder will shoot to very high rates after hitting a
  1795. span of silence, but we do allow the bitres to refill.
  1796. This means that we'll undershoot our target in CVBR/VBR modes
  1797. on files with lots of silence. */
  1798. if(silence)
  1799. {
  1800. nbAvailableBytes = 2;
  1801. target = 2*8<<BITRES;
  1802. delta = 0;
  1803. }
  1804. if (st->vbr_count < 970)
  1805. {
  1806. st->vbr_count++;
  1807. alpha = celt_rcp(SHL32(EXTEND32(st->vbr_count+20),16));
  1808. } else
  1809. alpha = QCONST16(.001f,15);
  1810. /* How many bits have we used in excess of what we're allowed */
  1811. if (st->constrained_vbr)
  1812. st->vbr_reservoir += target - vbr_rate;
  1813. /*printf ("%d\n", st->vbr_reservoir);*/
  1814. /* Compute the offset we need to apply in order to reach the target */
  1815. if (st->constrained_vbr)
  1816. {
  1817. st->vbr_drift += (opus_int32)MULT16_32_Q15(alpha,(delta*(1<<lm_diff))-st->vbr_offset-st->vbr_drift);
  1818. st->vbr_offset = -st->vbr_drift;
  1819. }
  1820. /*printf ("%d\n", st->vbr_drift);*/
  1821. if (st->constrained_vbr && st->vbr_reservoir < 0)
  1822. {
  1823. /* We're under the min value -- increase rate */
  1824. int adjust = (-st->vbr_reservoir)/(8<<BITRES);
  1825. /* Unless we're just coding silence */
  1826. nbAvailableBytes += silence?0:adjust;
  1827. st->vbr_reservoir = 0;
  1828. /*printf ("+%d\n", adjust);*/
  1829. }
  1830. nbCompressedBytes = IMIN(nbCompressedBytes,nbAvailableBytes+nbFilledBytes);
  1831. /*printf("%d\n", nbCompressedBytes*50*8);*/
  1832. /* This moves the raw bits to take into account the new compressed size */
  1833. ec_enc_shrink(enc, nbCompressedBytes);
  1834. }
  1835. /* Bit allocation */
  1836. ALLOC(fine_quant, nbEBands, int);
  1837. ALLOC(pulses, nbEBands, int);
  1838. ALLOC(fine_priority, nbEBands, int);
  1839. /* bits = packet size - where we are - safety*/
  1840. bits = (((opus_int32)nbCompressedBytes*8)<<BITRES) - ec_tell_frac(enc) - 1;
  1841. anti_collapse_rsv = isTransient&&LM>=2&&bits>=((LM+2)<<BITRES) ? (1<<BITRES) : 0;
  1842. bits -= anti_collapse_rsv;
  1843. signalBandwidth = end-1;
  1844. #ifndef DISABLE_FLOAT_API
  1845. if (st->analysis.valid)
  1846. {
  1847. int min_bandwidth;
  1848. if (equiv_rate < (opus_int32)32000*C)
  1849. min_bandwidth = 13;
  1850. else if (equiv_rate < (opus_int32)48000*C)
  1851. min_bandwidth = 16;
  1852. else if (equiv_rate < (opus_int32)60000*C)
  1853. min_bandwidth = 18;
  1854. else if (equiv_rate < (opus_int32)80000*C)
  1855. min_bandwidth = 19;
  1856. else
  1857. min_bandwidth = 20;
  1858. signalBandwidth = IMAX(st->analysis.bandwidth, min_bandwidth);
  1859. }
  1860. #endif
  1861. if (st->lfe)
  1862. signalBandwidth = 1;
  1863. codedBands = compute_allocation(mode, start, end, offsets, cap,
  1864. alloc_trim, &st->intensity, &dual_stereo, bits, &balance, pulses,
  1865. fine_quant, fine_priority, C, LM, enc, 1, st->lastCodedBands, signalBandwidth);
  1866. if (st->lastCodedBands)
  1867. st->lastCodedBands = IMIN(st->lastCodedBands+1,IMAX(st->lastCodedBands-1,codedBands));
  1868. else
  1869. st->lastCodedBands = codedBands;
  1870. quant_fine_energy(mode, start, end, oldBandE, error, fine_quant, enc, C);
  1871. /* Residual quantisation */
  1872. ALLOC(collapse_masks, C*nbEBands, unsigned char);
  1873. quant_all_bands(1, mode, start, end, X, C==2 ? X+N : NULL, collapse_masks,
  1874. bandE, pulses, shortBlocks, st->spread_decision,
  1875. dual_stereo, st->intensity, tf_res, nbCompressedBytes*(8<<BITRES)-anti_collapse_rsv,
  1876. balance, enc, LM, codedBands, &st->rng, st->arch);
  1877. if (anti_collapse_rsv > 0)
  1878. {
  1879. anti_collapse_on = st->consec_transient<2;
  1880. #ifdef FUZZING
  1881. anti_collapse_on = rand()&0x1;
  1882. #endif
  1883. ec_enc_bits(enc, anti_collapse_on, 1);
  1884. }
  1885. quant_energy_finalise(mode, start, end, oldBandE, error, fine_quant, fine_priority, nbCompressedBytes*8-ec_tell(enc), enc, C);
  1886. if (silence)
  1887. {
  1888. for (i=0;i<C*nbEBands;i++)
  1889. oldBandE[i] = -QCONST16(28.f,DB_SHIFT);
  1890. }
  1891. #ifdef RESYNTH
  1892. /* Re-synthesis of the coded audio if required */
  1893. {
  1894. celt_sig *out_mem[2];
  1895. if (anti_collapse_on)
  1896. {
  1897. anti_collapse(mode, X, collapse_masks, LM, C, N,
  1898. start, end, oldBandE, oldLogE, oldLogE2, pulses, st->rng);
  1899. }
  1900. c=0; do {
  1901. OPUS_MOVE(st->syn_mem[c], st->syn_mem[c]+N, 2*MAX_PERIOD-N+overlap/2);
  1902. } while (++c<CC);
  1903. c=0; do {
  1904. out_mem[c] = st->syn_mem[c]+2*MAX_PERIOD-N;
  1905. } while (++c<CC);
  1906. celt_synthesis(mode, X, out_mem, oldBandE, start, effEnd,
  1907. C, CC, isTransient, LM, st->upsample, silence, st->arch);
  1908. c=0; do {
  1909. st->prefilter_period=IMAX(st->prefilter_period, COMBFILTER_MINPERIOD);
  1910. st->prefilter_period_old=IMAX(st->prefilter_period_old, COMBFILTER_MINPERIOD);
  1911. comb_filter(out_mem[c], out_mem[c], st->prefilter_period_old, st->prefilter_period, mode->shortMdctSize,
  1912. st->prefilter_gain_old, st->prefilter_gain, st->prefilter_tapset_old, st->prefilter_tapset,
  1913. mode->window, overlap);
  1914. if (LM!=0)
  1915. comb_filter(out_mem[c]+mode->shortMdctSize, out_mem[c]+mode->shortMdctSize, st->prefilter_period, pitch_index, N-mode->shortMdctSize,
  1916. st->prefilter_gain, gain1, st->prefilter_tapset, prefilter_tapset,
  1917. mode->window, overlap);
  1918. } while (++c<CC);
  1919. /* We reuse freq[] as scratch space for the de-emphasis */
  1920. deemphasis(out_mem, (opus_val16*)pcm, N, CC, st->upsample, mode->preemph, st->preemph_memD);
  1921. st->prefilter_period_old = st->prefilter_period;
  1922. st->prefilter_gain_old = st->prefilter_gain;
  1923. st->prefilter_tapset_old = st->prefilter_tapset;
  1924. }
  1925. #endif
  1926. st->prefilter_period = pitch_index;
  1927. st->prefilter_gain = gain1;
  1928. st->prefilter_tapset = prefilter_tapset;
  1929. #ifdef RESYNTH
  1930. if (LM!=0)
  1931. {
  1932. st->prefilter_period_old = st->prefilter_period;
  1933. st->prefilter_gain_old = st->prefilter_gain;
  1934. st->prefilter_tapset_old = st->prefilter_tapset;
  1935. }
  1936. #endif
  1937. if (CC==2&&C==1) {
  1938. OPUS_COPY(&oldBandE[nbEBands], oldBandE, nbEBands);
  1939. }
  1940. if (!isTransient)
  1941. {
  1942. OPUS_COPY(oldLogE2, oldLogE, CC*nbEBands);
  1943. OPUS_COPY(oldLogE, oldBandE, CC*nbEBands);
  1944. } else {
  1945. for (i=0;i<CC*nbEBands;i++)
  1946. oldLogE[i] = MIN16(oldLogE[i], oldBandE[i]);
  1947. }
  1948. /* In case start or end were to change */
  1949. c=0; do
  1950. {
  1951. for (i=0;i<start;i++)
  1952. {
  1953. oldBandE[c*nbEBands+i]=0;
  1954. oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
  1955. }
  1956. for (i=end;i<nbEBands;i++)
  1957. {
  1958. oldBandE[c*nbEBands+i]=0;
  1959. oldLogE[c*nbEBands+i]=oldLogE2[c*nbEBands+i]=-QCONST16(28.f,DB_SHIFT);
  1960. }
  1961. } while (++c<CC);
  1962. if (isTransient || transient_got_disabled)
  1963. st->consec_transient++;
  1964. else
  1965. st->consec_transient=0;
  1966. st->rng = enc->rng;
  1967. /* If there's any room left (can only happen for very high rates),
  1968. it's already filled with zeros */
  1969. ec_enc_done(enc);
  1970. #ifdef CUSTOM_MODES
  1971. if (st->signalling)
  1972. nbCompressedBytes++;
  1973. #endif
  1974. RESTORE_STACK;
  1975. if (ec_get_error(enc))
  1976. return OPUS_INTERNAL_ERROR;
  1977. else
  1978. return nbCompressedBytes;
  1979. }
  1980. #ifdef CUSTOM_MODES
  1981. #ifdef FIXED_POINT
  1982. int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
  1983. {
  1984. return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
  1985. }
  1986. #ifndef DISABLE_FLOAT_API
  1987. int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
  1988. {
  1989. int j, ret, C, N;
  1990. VARDECL(opus_int16, in);
  1991. ALLOC_STACK;
  1992. if (pcm==NULL)
  1993. return OPUS_BAD_ARG;
  1994. C = st->channels;
  1995. N = frame_size;
  1996. ALLOC(in, C*N, opus_int16);
  1997. for (j=0;j<C*N;j++)
  1998. in[j] = FLOAT2INT16(pcm[j]);
  1999. ret=celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
  2000. #ifdef RESYNTH
  2001. for (j=0;j<C*N;j++)
  2002. ((float*)pcm)[j]=in[j]*(1.f/32768.f);
  2003. #endif
  2004. RESTORE_STACK;
  2005. return ret;
  2006. }
  2007. #endif /* DISABLE_FLOAT_API */
  2008. #else
  2009. int opus_custom_encode(CELTEncoder * OPUS_RESTRICT st, const opus_int16 * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
  2010. {
  2011. int j, ret, C, N;
  2012. VARDECL(celt_sig, in);
  2013. ALLOC_STACK;
  2014. if (pcm==NULL)
  2015. return OPUS_BAD_ARG;
  2016. C=st->channels;
  2017. N=frame_size;
  2018. ALLOC(in, C*N, celt_sig);
  2019. for (j=0;j<C*N;j++) {
  2020. in[j] = SCALEOUT(pcm[j]);
  2021. }
  2022. ret = celt_encode_with_ec(st,in,frame_size,compressed,nbCompressedBytes, NULL);
  2023. #ifdef RESYNTH
  2024. for (j=0;j<C*N;j++)
  2025. ((opus_int16*)pcm)[j] = FLOAT2INT16(in[j]);
  2026. #endif
  2027. RESTORE_STACK;
  2028. return ret;
  2029. }
  2030. int opus_custom_encode_float(CELTEncoder * OPUS_RESTRICT st, const float * pcm, int frame_size, unsigned char *compressed, int nbCompressedBytes)
  2031. {
  2032. return celt_encode_with_ec(st, pcm, frame_size, compressed, nbCompressedBytes, NULL);
  2033. }
  2034. #endif
  2035. #endif /* CUSTOM_MODES */
  2036. int opus_custom_encoder_ctl(CELTEncoder * OPUS_RESTRICT st, int request, ...)
  2037. {
  2038. va_list ap;
  2039. va_start(ap, request);
  2040. switch (request)
  2041. {
  2042. case OPUS_SET_COMPLEXITY_REQUEST:
  2043. {
  2044. int value = va_arg(ap, opus_int32);
  2045. if (value<0 || value>10)
  2046. goto bad_arg;
  2047. st->complexity = value;
  2048. }
  2049. break;
  2050. case CELT_SET_START_BAND_REQUEST:
  2051. {
  2052. opus_int32 value = va_arg(ap, opus_int32);
  2053. if (value<0 || value>=st->mode->nbEBands)
  2054. goto bad_arg;
  2055. st->start = value;
  2056. }
  2057. break;
  2058. case CELT_SET_END_BAND_REQUEST:
  2059. {
  2060. opus_int32 value = va_arg(ap, opus_int32);
  2061. if (value<1 || value>st->mode->nbEBands)
  2062. goto bad_arg;
  2063. st->end = value;
  2064. }
  2065. break;
  2066. case CELT_SET_PREDICTION_REQUEST:
  2067. {
  2068. int value = va_arg(ap, opus_int32);
  2069. if (value<0 || value>2)
  2070. goto bad_arg;
  2071. st->disable_pf = value<=1;
  2072. st->force_intra = value==0;
  2073. }
  2074. break;
  2075. case OPUS_SET_PACKET_LOSS_PERC_REQUEST:
  2076. {
  2077. int value = va_arg(ap, opus_int32);
  2078. if (value<0 || value>100)
  2079. goto bad_arg;
  2080. st->loss_rate = value;
  2081. }
  2082. break;
  2083. case OPUS_SET_VBR_CONSTRAINT_REQUEST:
  2084. {
  2085. opus_int32 value = va_arg(ap, opus_int32);
  2086. st->constrained_vbr = value;
  2087. }
  2088. break;
  2089. case OPUS_SET_VBR_REQUEST:
  2090. {
  2091. opus_int32 value = va_arg(ap, opus_int32);
  2092. st->vbr = value;
  2093. }
  2094. break;
  2095. case OPUS_SET_BITRATE_REQUEST:
  2096. {
  2097. opus_int32 value = va_arg(ap, opus_int32);
  2098. if (value<=500 && value!=OPUS_BITRATE_MAX)
  2099. goto bad_arg;
  2100. value = IMIN(value, 260000*st->channels);
  2101. st->bitrate = value;
  2102. }
  2103. break;
  2104. case CELT_SET_CHANNELS_REQUEST:
  2105. {
  2106. opus_int32 value = va_arg(ap, opus_int32);
  2107. if (value<1 || value>2)
  2108. goto bad_arg;
  2109. st->stream_channels = value;
  2110. }
  2111. break;
  2112. case OPUS_SET_LSB_DEPTH_REQUEST:
  2113. {
  2114. opus_int32 value = va_arg(ap, opus_int32);
  2115. if (value<8 || value>24)
  2116. goto bad_arg;
  2117. st->lsb_depth=value;
  2118. }
  2119. break;
  2120. case OPUS_GET_LSB_DEPTH_REQUEST:
  2121. {
  2122. opus_int32 *value = va_arg(ap, opus_int32*);
  2123. *value=st->lsb_depth;
  2124. }
  2125. break;
  2126. case OPUS_SET_EXPERT_FRAME_DURATION_REQUEST:
  2127. {
  2128. opus_int32 value = va_arg(ap, opus_int32);
  2129. st->variable_duration = value;
  2130. }
  2131. break;
  2132. case OPUS_RESET_STATE:
  2133. {
  2134. int i;
  2135. opus_val16 *oldBandE, *oldLogE, *oldLogE2;
  2136. oldBandE = (opus_val16*)(st->in_mem+st->channels*(st->mode->overlap+COMBFILTER_MAXPERIOD));
  2137. oldLogE = oldBandE + st->channels*st->mode->nbEBands;
  2138. oldLogE2 = oldLogE + st->channels*st->mode->nbEBands;
  2139. OPUS_CLEAR((char*)&st->ENCODER_RESET_START,
  2140. opus_custom_encoder_get_size(st->mode, st->channels)-
  2141. ((char*)&st->ENCODER_RESET_START - (char*)st));
  2142. for (i=0;i<st->channels*st->mode->nbEBands;i++)
  2143. oldLogE[i]=oldLogE2[i]=-QCONST16(28.f,DB_SHIFT);
  2144. st->vbr_offset = 0;
  2145. st->delayedIntra = 1;
  2146. st->spread_decision = SPREAD_NORMAL;
  2147. st->tonal_average = 256;
  2148. st->hf_average = 0;
  2149. st->tapset_decision = 0;
  2150. }
  2151. break;
  2152. #ifdef CUSTOM_MODES
  2153. case CELT_SET_INPUT_CLIPPING_REQUEST:
  2154. {
  2155. opus_int32 value = va_arg(ap, opus_int32);
  2156. st->clip = value;
  2157. }
  2158. break;
  2159. #endif
  2160. case CELT_SET_SIGNALLING_REQUEST:
  2161. {
  2162. opus_int32 value = va_arg(ap, opus_int32);
  2163. st->signalling = value;
  2164. }
  2165. break;
  2166. case CELT_SET_ANALYSIS_REQUEST:
  2167. {
  2168. AnalysisInfo *info = va_arg(ap, AnalysisInfo *);
  2169. if (info)
  2170. OPUS_COPY(&st->analysis, info, 1);
  2171. }
  2172. break;
  2173. case CELT_GET_MODE_REQUEST:
  2174. {
  2175. const CELTMode ** value = va_arg(ap, const CELTMode**);
  2176. if (value==0)
  2177. goto bad_arg;
  2178. *value=st->mode;
  2179. }
  2180. break;
  2181. case OPUS_GET_FINAL_RANGE_REQUEST:
  2182. {
  2183. opus_uint32 * value = va_arg(ap, opus_uint32 *);
  2184. if (value==0)
  2185. goto bad_arg;
  2186. *value=st->rng;
  2187. }
  2188. break;
  2189. case OPUS_SET_LFE_REQUEST:
  2190. {
  2191. opus_int32 value = va_arg(ap, opus_int32);
  2192. st->lfe = value;
  2193. }
  2194. break;
  2195. case OPUS_SET_ENERGY_MASK_REQUEST:
  2196. {
  2197. opus_val16 *value = va_arg(ap, opus_val16*);
  2198. st->energy_mask = value;
  2199. }
  2200. break;
  2201. default:
  2202. goto bad_request;
  2203. }
  2204. va_end(ap);
  2205. return OPUS_OK;
  2206. bad_arg:
  2207. va_end(ap);
  2208. return OPUS_BAD_ARG;
  2209. bad_request:
  2210. va_end(ap);
  2211. return OPUS_UNIMPLEMENTED;
  2212. }