bands.c 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  1. /* Copyright (c) 2007-2008 CSIRO
  2. Copyright (c) 2007-2009 Xiph.Org Foundation
  3. Copyright (c) 2008-2009 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. #include <math.h>
  30. #include "bands.h"
  31. #include "modes.h"
  32. #include "vq.h"
  33. #include "cwrs.h"
  34. #include "stack_alloc.h"
  35. #include "os_support.h"
  36. #include "mathops.h"
  37. #include "rate.h"
  38. #include "quant_bands.h"
  39. #include "pitch.h"
  40. int hysteresis_decision(opus_val16 val, const opus_val16 *thresholds, const opus_val16 *hysteresis, int N, int prev)
  41. {
  42. int i;
  43. for (i=0;i<N;i++)
  44. {
  45. if (val < thresholds[i])
  46. break;
  47. }
  48. if (i>prev && val < thresholds[prev]+hysteresis[prev])
  49. i=prev;
  50. if (i<prev && val > thresholds[prev-1]-hysteresis[prev-1])
  51. i=prev;
  52. return i;
  53. }
  54. opus_uint32 celt_lcg_rand(opus_uint32 seed)
  55. {
  56. return 1664525 * seed + 1013904223;
  57. }
  58. /* This is a cos() approximation designed to be bit-exact on any platform. Bit exactness
  59. with this approximation is important because it has an impact on the bit allocation */
  60. opus_int16 bitexact_cos(opus_int16 x)
  61. {
  62. opus_int32 tmp;
  63. opus_int16 x2;
  64. tmp = (4096+((opus_int32)(x)*(x)))>>13;
  65. celt_sig_assert(tmp<=32767);
  66. x2 = tmp;
  67. x2 = (32767-x2) + FRAC_MUL16(x2, (-7651 + FRAC_MUL16(x2, (8277 + FRAC_MUL16(-626, x2)))));
  68. celt_sig_assert(x2<=32766);
  69. return 1+x2;
  70. }
  71. int bitexact_log2tan(int isin,int icos)
  72. {
  73. int lc;
  74. int ls;
  75. lc=EC_ILOG(icos);
  76. ls=EC_ILOG(isin);
  77. icos<<=15-lc;
  78. isin<<=15-ls;
  79. return (ls-lc)*(1<<11)
  80. +FRAC_MUL16(isin, FRAC_MUL16(isin, -2597) + 7932)
  81. -FRAC_MUL16(icos, FRAC_MUL16(icos, -2597) + 7932);
  82. }
  83. #ifdef FIXED_POINT
  84. /* Compute the amplitude (sqrt energy) in each of the bands */
  85. void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int LM, int arch)
  86. {
  87. int i, c, N;
  88. const opus_int16 *eBands = m->eBands;
  89. (void)arch;
  90. N = m->shortMdctSize<<LM;
  91. c=0; do {
  92. for (i=0;i<end;i++)
  93. {
  94. int j;
  95. opus_val32 maxval=0;
  96. opus_val32 sum = 0;
  97. maxval = celt_maxabs32(&X[c*N+(eBands[i]<<LM)], (eBands[i+1]-eBands[i])<<LM);
  98. if (maxval > 0)
  99. {
  100. int shift = celt_ilog2(maxval) - 14 + (((m->logN[i]>>BITRES)+LM+1)>>1);
  101. j=eBands[i]<<LM;
  102. if (shift>0)
  103. {
  104. do {
  105. sum = MAC16_16(sum, EXTRACT16(SHR32(X[j+c*N],shift)),
  106. EXTRACT16(SHR32(X[j+c*N],shift)));
  107. } while (++j<eBands[i+1]<<LM);
  108. } else {
  109. do {
  110. sum = MAC16_16(sum, EXTRACT16(SHL32(X[j+c*N],-shift)),
  111. EXTRACT16(SHL32(X[j+c*N],-shift)));
  112. } while (++j<eBands[i+1]<<LM);
  113. }
  114. /* We're adding one here to ensure the normalized band isn't larger than unity norm */
  115. bandE[i+c*m->nbEBands] = EPSILON+VSHR32(EXTEND32(celt_sqrt(sum)),-shift);
  116. } else {
  117. bandE[i+c*m->nbEBands] = EPSILON;
  118. }
  119. /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
  120. }
  121. } while (++c<C);
  122. /*printf ("\n");*/
  123. }
  124. /* Normalise each band such that the energy is one. */
  125. void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
  126. {
  127. int i, c, N;
  128. const opus_int16 *eBands = m->eBands;
  129. N = M*m->shortMdctSize;
  130. c=0; do {
  131. i=0; do {
  132. opus_val16 g;
  133. int j,shift;
  134. opus_val16 E;
  135. shift = celt_zlog2(bandE[i+c*m->nbEBands])-13;
  136. E = VSHR32(bandE[i+c*m->nbEBands], shift);
  137. g = EXTRACT16(celt_rcp(SHL32(E,3)));
  138. j=M*eBands[i]; do {
  139. X[j+c*N] = MULT16_16_Q15(VSHR32(freq[j+c*N],shift-1),g);
  140. } while (++j<M*eBands[i+1]);
  141. } while (++i<end);
  142. } while (++c<C);
  143. }
  144. #else /* FIXED_POINT */
  145. /* Compute the amplitude (sqrt energy) in each of the bands */
  146. void compute_band_energies(const CELTMode *m, const celt_sig *X, celt_ener *bandE, int end, int C, int LM, int arch)
  147. {
  148. int i, c, N;
  149. const opus_int16 *eBands = m->eBands;
  150. N = m->shortMdctSize<<LM;
  151. c=0; do {
  152. for (i=0;i<end;i++)
  153. {
  154. opus_val32 sum;
  155. sum = 1e-27f + celt_inner_prod(&X[c*N+(eBands[i]<<LM)], &X[c*N+(eBands[i]<<LM)], (eBands[i+1]-eBands[i])<<LM, arch);
  156. bandE[i+c*m->nbEBands] = celt_sqrt(sum);
  157. /*printf ("%f ", bandE[i+c*m->nbEBands]);*/
  158. }
  159. } while (++c<C);
  160. /*printf ("\n");*/
  161. }
  162. /* Normalise each band such that the energy is one. */
  163. void normalise_bands(const CELTMode *m, const celt_sig * OPUS_RESTRICT freq, celt_norm * OPUS_RESTRICT X, const celt_ener *bandE, int end, int C, int M)
  164. {
  165. int i, c, N;
  166. const opus_int16 *eBands = m->eBands;
  167. N = M*m->shortMdctSize;
  168. c=0; do {
  169. for (i=0;i<end;i++)
  170. {
  171. int j;
  172. opus_val16 g = 1.f/(1e-27f+bandE[i+c*m->nbEBands]);
  173. for (j=M*eBands[i];j<M*eBands[i+1];j++)
  174. X[j+c*N] = freq[j+c*N]*g;
  175. }
  176. } while (++c<C);
  177. }
  178. #endif /* FIXED_POINT */
  179. /* De-normalise the energy to produce the synthesis from the unit-energy bands */
  180. void denormalise_bands(const CELTMode *m, const celt_norm * OPUS_RESTRICT X,
  181. celt_sig * OPUS_RESTRICT freq, const opus_val16 *bandLogE, int start,
  182. int end, int M, int downsample, int silence)
  183. {
  184. int i, N;
  185. int bound;
  186. celt_sig * OPUS_RESTRICT f;
  187. const celt_norm * OPUS_RESTRICT x;
  188. const opus_int16 *eBands = m->eBands;
  189. N = M*m->shortMdctSize;
  190. bound = M*eBands[end];
  191. if (downsample!=1)
  192. bound = IMIN(bound, N/downsample);
  193. if (silence)
  194. {
  195. bound = 0;
  196. start = end = 0;
  197. }
  198. f = freq;
  199. x = X+M*eBands[start];
  200. for (i=0;i<M*eBands[start];i++)
  201. *f++ = 0;
  202. for (i=start;i<end;i++)
  203. {
  204. int j, band_end;
  205. opus_val16 g;
  206. opus_val16 lg;
  207. #ifdef FIXED_POINT
  208. int shift;
  209. #endif
  210. j=M*eBands[i];
  211. band_end = M*eBands[i+1];
  212. lg = SATURATE16(ADD32(bandLogE[i], SHL32((opus_val32)eMeans[i],6)));
  213. #ifndef FIXED_POINT
  214. g = celt_exp2(MIN32(32.f, lg));
  215. #else
  216. /* Handle the integer part of the log energy */
  217. shift = 16-(lg>>DB_SHIFT);
  218. if (shift>31)
  219. {
  220. shift=0;
  221. g=0;
  222. } else {
  223. /* Handle the fractional part. */
  224. g = celt_exp2_frac(lg&((1<<DB_SHIFT)-1));
  225. }
  226. /* Handle extreme gains with negative shift. */
  227. if (shift<0)
  228. {
  229. /* For shift <= -2 and g > 16384 we'd be likely to overflow, so we're
  230. capping the gain here, which is equivalent to a cap of 18 on lg.
  231. This shouldn't trigger unless the bitstream is already corrupted. */
  232. if (shift <= -2)
  233. {
  234. g = 16384;
  235. shift = -2;
  236. }
  237. do {
  238. *f++ = SHL32(MULT16_16(*x++, g), -shift);
  239. } while (++j<band_end);
  240. } else
  241. #endif
  242. /* Be careful of the fixed-point "else" just above when changing this code */
  243. do {
  244. *f++ = SHR32(MULT16_16(*x++, g), shift);
  245. } while (++j<band_end);
  246. }
  247. celt_assert(start <= end);
  248. OPUS_CLEAR(&freq[bound], N-bound);
  249. }
  250. /* This prevents energy collapse for transients with multiple short MDCTs */
  251. void anti_collapse(const CELTMode *m, celt_norm *X_, unsigned char *collapse_masks, int LM, int C, int size,
  252. int start, int end, const opus_val16 *logE, const opus_val16 *prev1logE,
  253. const opus_val16 *prev2logE, const int *pulses, opus_uint32 seed, int arch)
  254. {
  255. int c, i, j, k;
  256. for (i=start;i<end;i++)
  257. {
  258. int N0;
  259. opus_val16 thresh, sqrt_1;
  260. int depth;
  261. #ifdef FIXED_POINT
  262. int shift;
  263. opus_val32 thresh32;
  264. #endif
  265. N0 = m->eBands[i+1]-m->eBands[i];
  266. /* depth in 1/8 bits */
  267. celt_sig_assert(pulses[i]>=0);
  268. depth = celt_udiv(1+pulses[i], (m->eBands[i+1]-m->eBands[i]))>>LM;
  269. #ifdef FIXED_POINT
  270. thresh32 = SHR32(celt_exp2(-SHL16(depth, 10-BITRES)),1);
  271. thresh = MULT16_32_Q15(QCONST16(0.5f, 15), MIN32(32767,thresh32));
  272. {
  273. opus_val32 t;
  274. t = N0<<LM;
  275. shift = celt_ilog2(t)>>1;
  276. t = SHL32(t, (7-shift)<<1);
  277. sqrt_1 = celt_rsqrt_norm(t);
  278. }
  279. #else
  280. thresh = .5f*celt_exp2(-.125f*depth);
  281. sqrt_1 = celt_rsqrt(N0<<LM);
  282. #endif
  283. c=0; do
  284. {
  285. celt_norm *X;
  286. opus_val16 prev1;
  287. opus_val16 prev2;
  288. opus_val32 Ediff;
  289. opus_val16 r;
  290. int renormalize=0;
  291. prev1 = prev1logE[c*m->nbEBands+i];
  292. prev2 = prev2logE[c*m->nbEBands+i];
  293. if (C==1)
  294. {
  295. prev1 = MAX16(prev1,prev1logE[m->nbEBands+i]);
  296. prev2 = MAX16(prev2,prev2logE[m->nbEBands+i]);
  297. }
  298. Ediff = EXTEND32(logE[c*m->nbEBands+i])-EXTEND32(MIN16(prev1,prev2));
  299. Ediff = MAX32(0, Ediff);
  300. #ifdef FIXED_POINT
  301. if (Ediff < 16384)
  302. {
  303. opus_val32 r32 = SHR32(celt_exp2(-EXTRACT16(Ediff)),1);
  304. r = 2*MIN16(16383,r32);
  305. } else {
  306. r = 0;
  307. }
  308. if (LM==3)
  309. r = MULT16_16_Q14(23170, MIN32(23169, r));
  310. r = SHR16(MIN16(thresh, r),1);
  311. r = SHR32(MULT16_16_Q15(sqrt_1, r),shift);
  312. #else
  313. /* r needs to be multiplied by 2 or 2*sqrt(2) depending on LM because
  314. short blocks don't have the same energy as long */
  315. r = 2.f*celt_exp2(-Ediff);
  316. if (LM==3)
  317. r *= 1.41421356f;
  318. r = MIN16(thresh, r);
  319. r = r*sqrt_1;
  320. #endif
  321. X = X_+c*size+(m->eBands[i]<<LM);
  322. for (k=0;k<1<<LM;k++)
  323. {
  324. /* Detect collapse */
  325. if (!(collapse_masks[i*C+c]&1<<k))
  326. {
  327. /* Fill with noise */
  328. for (j=0;j<N0;j++)
  329. {
  330. seed = celt_lcg_rand(seed);
  331. X[(j<<LM)+k] = (seed&0x8000 ? r : -r);
  332. }
  333. renormalize = 1;
  334. }
  335. }
  336. /* We just added some energy, so we need to renormalise */
  337. if (renormalize)
  338. renormalise_vector(X, N0<<LM, Q15ONE, arch);
  339. } while (++c<C);
  340. }
  341. }
  342. /* Compute the weights to use for optimizing normalized distortion across
  343. channels. We use the amplitude to weight square distortion, which means
  344. that we use the square root of the value we would have been using if we
  345. wanted to minimize the MSE in the non-normalized domain. This roughly
  346. corresponds to some quick-and-dirty perceptual experiments I ran to
  347. measure inter-aural masking (there doesn't seem to be any published data
  348. on the topic). */
  349. static void compute_channel_weights(celt_ener Ex, celt_ener Ey, opus_val16 w[2])
  350. {
  351. celt_ener minE;
  352. #ifdef FIXED_POINT
  353. int shift;
  354. #endif
  355. minE = MIN32(Ex, Ey);
  356. /* Adjustment to make the weights a bit more conservative. */
  357. Ex = ADD32(Ex, minE/3);
  358. Ey = ADD32(Ey, minE/3);
  359. #ifdef FIXED_POINT
  360. shift = celt_ilog2(EPSILON+MAX32(Ex, Ey))-14;
  361. #endif
  362. w[0] = VSHR32(Ex, shift);
  363. w[1] = VSHR32(Ey, shift);
  364. }
  365. static void intensity_stereo(const CELTMode *m, celt_norm * OPUS_RESTRICT X, const celt_norm * OPUS_RESTRICT Y, const celt_ener *bandE, int bandID, int N)
  366. {
  367. int i = bandID;
  368. int j;
  369. opus_val16 a1, a2;
  370. opus_val16 left, right;
  371. opus_val16 norm;
  372. #ifdef FIXED_POINT
  373. int shift = celt_zlog2(MAX32(bandE[i], bandE[i+m->nbEBands]))-13;
  374. #endif
  375. left = VSHR32(bandE[i],shift);
  376. right = VSHR32(bandE[i+m->nbEBands],shift);
  377. norm = EPSILON + celt_sqrt(EPSILON+MULT16_16(left,left)+MULT16_16(right,right));
  378. a1 = DIV32_16(SHL32(EXTEND32(left),14),norm);
  379. a2 = DIV32_16(SHL32(EXTEND32(right),14),norm);
  380. for (j=0;j<N;j++)
  381. {
  382. celt_norm r, l;
  383. l = X[j];
  384. r = Y[j];
  385. X[j] = EXTRACT16(SHR32(MAC16_16(MULT16_16(a1, l), a2, r), 14));
  386. /* Side is not encoded, no need to calculate */
  387. }
  388. }
  389. static void stereo_split(celt_norm * OPUS_RESTRICT X, celt_norm * OPUS_RESTRICT Y, int N)
  390. {
  391. int j;
  392. for (j=0;j<N;j++)
  393. {
  394. opus_val32 r, l;
  395. l = MULT16_16(QCONST16(.70710678f, 15), X[j]);
  396. r = MULT16_16(QCONST16(.70710678f, 15), Y[j]);
  397. X[j] = EXTRACT16(SHR32(ADD32(l, r), 15));
  398. Y[j] = EXTRACT16(SHR32(SUB32(r, l), 15));
  399. }
  400. }
  401. static void stereo_merge(celt_norm * OPUS_RESTRICT X, celt_norm * OPUS_RESTRICT Y, opus_val16 mid, int N, int arch)
  402. {
  403. int j;
  404. opus_val32 xp=0, side=0;
  405. opus_val32 El, Er;
  406. opus_val16 mid2;
  407. #ifdef FIXED_POINT
  408. int kl, kr;
  409. #endif
  410. opus_val32 t, lgain, rgain;
  411. /* Compute the norm of X+Y and X-Y as |X|^2 + |Y|^2 +/- sum(xy) */
  412. dual_inner_prod(Y, X, Y, N, &xp, &side, arch);
  413. /* Compensating for the mid normalization */
  414. xp = MULT16_32_Q15(mid, xp);
  415. /* mid and side are in Q15, not Q14 like X and Y */
  416. mid2 = SHR16(mid, 1);
  417. El = MULT16_16(mid2, mid2) + side - 2*xp;
  418. Er = MULT16_16(mid2, mid2) + side + 2*xp;
  419. if (Er < QCONST32(6e-4f, 28) || El < QCONST32(6e-4f, 28))
  420. {
  421. OPUS_COPY(Y, X, N);
  422. return;
  423. }
  424. #ifdef FIXED_POINT
  425. kl = celt_ilog2(El)>>1;
  426. kr = celt_ilog2(Er)>>1;
  427. #endif
  428. t = VSHR32(El, (kl-7)<<1);
  429. lgain = celt_rsqrt_norm(t);
  430. t = VSHR32(Er, (kr-7)<<1);
  431. rgain = celt_rsqrt_norm(t);
  432. #ifdef FIXED_POINT
  433. if (kl < 7)
  434. kl = 7;
  435. if (kr < 7)
  436. kr = 7;
  437. #endif
  438. for (j=0;j<N;j++)
  439. {
  440. celt_norm r, l;
  441. /* Apply mid scaling (side is already scaled) */
  442. l = MULT16_16_P15(mid, X[j]);
  443. r = Y[j];
  444. X[j] = EXTRACT16(PSHR32(MULT16_16(lgain, SUB16(l,r)), kl+1));
  445. Y[j] = EXTRACT16(PSHR32(MULT16_16(rgain, ADD16(l,r)), kr+1));
  446. }
  447. }
  448. /* Decide whether we should spread the pulses in the current frame */
  449. int spreading_decision(const CELTMode *m, const celt_norm *X, int *average,
  450. int last_decision, int *hf_average, int *tapset_decision, int update_hf,
  451. int end, int C, int M, const int *spread_weight)
  452. {
  453. int i, c, N0;
  454. int sum = 0, nbBands=0;
  455. const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
  456. int decision;
  457. int hf_sum=0;
  458. celt_assert(end>0);
  459. N0 = M*m->shortMdctSize;
  460. if (M*(eBands[end]-eBands[end-1]) <= 8)
  461. return SPREAD_NONE;
  462. c=0; do {
  463. for (i=0;i<end;i++)
  464. {
  465. int j, N, tmp=0;
  466. int tcount[3] = {0,0,0};
  467. const celt_norm * OPUS_RESTRICT x = X+M*eBands[i]+c*N0;
  468. N = M*(eBands[i+1]-eBands[i]);
  469. if (N<=8)
  470. continue;
  471. /* Compute rough CDF of |x[j]| */
  472. for (j=0;j<N;j++)
  473. {
  474. opus_val32 x2N; /* Q13 */
  475. x2N = MULT16_16(MULT16_16_Q15(x[j], x[j]), N);
  476. if (x2N < QCONST16(0.25f,13))
  477. tcount[0]++;
  478. if (x2N < QCONST16(0.0625f,13))
  479. tcount[1]++;
  480. if (x2N < QCONST16(0.015625f,13))
  481. tcount[2]++;
  482. }
  483. /* Only include four last bands (8 kHz and up) */
  484. if (i>m->nbEBands-4)
  485. hf_sum += celt_udiv(32*(tcount[1]+tcount[0]), N);
  486. tmp = (2*tcount[2] >= N) + (2*tcount[1] >= N) + (2*tcount[0] >= N);
  487. sum += tmp*spread_weight[i];
  488. nbBands+=spread_weight[i];
  489. }
  490. } while (++c<C);
  491. if (update_hf)
  492. {
  493. if (hf_sum)
  494. hf_sum = celt_udiv(hf_sum, C*(4-m->nbEBands+end));
  495. *hf_average = (*hf_average+hf_sum)>>1;
  496. hf_sum = *hf_average;
  497. if (*tapset_decision==2)
  498. hf_sum += 4;
  499. else if (*tapset_decision==0)
  500. hf_sum -= 4;
  501. if (hf_sum > 22)
  502. *tapset_decision=2;
  503. else if (hf_sum > 18)
  504. *tapset_decision=1;
  505. else
  506. *tapset_decision=0;
  507. }
  508. /*printf("%d %d %d\n", hf_sum, *hf_average, *tapset_decision);*/
  509. celt_assert(nbBands>0); /* end has to be non-zero */
  510. celt_assert(sum>=0);
  511. sum = celt_udiv((opus_int32)sum<<8, nbBands);
  512. /* Recursive averaging */
  513. sum = (sum+*average)>>1;
  514. *average = sum;
  515. /* Hysteresis */
  516. sum = (3*sum + (((3-last_decision)<<7) + 64) + 2)>>2;
  517. if (sum < 80)
  518. {
  519. decision = SPREAD_AGGRESSIVE;
  520. } else if (sum < 256)
  521. {
  522. decision = SPREAD_NORMAL;
  523. } else if (sum < 384)
  524. {
  525. decision = SPREAD_LIGHT;
  526. } else {
  527. decision = SPREAD_NONE;
  528. }
  529. #ifdef FUZZING
  530. decision = rand()&0x3;
  531. *tapset_decision=rand()%3;
  532. #endif
  533. return decision;
  534. }
  535. /* Indexing table for converting from natural Hadamard to ordery Hadamard
  536. This is essentially a bit-reversed Gray, on top of which we've added
  537. an inversion of the order because we want the DC at the end rather than
  538. the beginning. The lines are for N=2, 4, 8, 16 */
  539. static const int ordery_table[] = {
  540. 1, 0,
  541. 3, 0, 2, 1,
  542. 7, 0, 4, 3, 6, 1, 5, 2,
  543. 15, 0, 8, 7, 12, 3, 11, 4, 14, 1, 9, 6, 13, 2, 10, 5,
  544. };
  545. static void deinterleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
  546. {
  547. int i,j;
  548. VARDECL(celt_norm, tmp);
  549. int N;
  550. SAVE_STACK;
  551. N = N0*stride;
  552. ALLOC(tmp, N, celt_norm);
  553. celt_assert(stride>0);
  554. if (hadamard)
  555. {
  556. const int *ordery = ordery_table+stride-2;
  557. for (i=0;i<stride;i++)
  558. {
  559. for (j=0;j<N0;j++)
  560. tmp[ordery[i]*N0+j] = X[j*stride+i];
  561. }
  562. } else {
  563. for (i=0;i<stride;i++)
  564. for (j=0;j<N0;j++)
  565. tmp[i*N0+j] = X[j*stride+i];
  566. }
  567. OPUS_COPY(X, tmp, N);
  568. RESTORE_STACK;
  569. }
  570. static void interleave_hadamard(celt_norm *X, int N0, int stride, int hadamard)
  571. {
  572. int i,j;
  573. VARDECL(celt_norm, tmp);
  574. int N;
  575. SAVE_STACK;
  576. N = N0*stride;
  577. ALLOC(tmp, N, celt_norm);
  578. if (hadamard)
  579. {
  580. const int *ordery = ordery_table+stride-2;
  581. for (i=0;i<stride;i++)
  582. for (j=0;j<N0;j++)
  583. tmp[j*stride+i] = X[ordery[i]*N0+j];
  584. } else {
  585. for (i=0;i<stride;i++)
  586. for (j=0;j<N0;j++)
  587. tmp[j*stride+i] = X[i*N0+j];
  588. }
  589. OPUS_COPY(X, tmp, N);
  590. RESTORE_STACK;
  591. }
  592. void haar1(celt_norm *X, int N0, int stride)
  593. {
  594. int i, j;
  595. N0 >>= 1;
  596. for (i=0;i<stride;i++)
  597. for (j=0;j<N0;j++)
  598. {
  599. opus_val32 tmp1, tmp2;
  600. tmp1 = MULT16_16(QCONST16(.70710678f,15), X[stride*2*j+i]);
  601. tmp2 = MULT16_16(QCONST16(.70710678f,15), X[stride*(2*j+1)+i]);
  602. X[stride*2*j+i] = EXTRACT16(PSHR32(ADD32(tmp1, tmp2), 15));
  603. X[stride*(2*j+1)+i] = EXTRACT16(PSHR32(SUB32(tmp1, tmp2), 15));
  604. }
  605. }
  606. static int compute_qn(int N, int b, int offset, int pulse_cap, int stereo)
  607. {
  608. static const opus_int16 exp2_table8[8] =
  609. {16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048};
  610. int qn, qb;
  611. int N2 = 2*N-1;
  612. if (stereo && N==2)
  613. N2--;
  614. /* The upper limit ensures that in a stereo split with itheta==16384, we'll
  615. always have enough bits left over to code at least one pulse in the
  616. side; otherwise it would collapse, since it doesn't get folded. */
  617. qb = celt_sudiv(b+N2*offset, N2);
  618. qb = IMIN(b-pulse_cap-(4<<BITRES), qb);
  619. qb = IMIN(8<<BITRES, qb);
  620. if (qb<(1<<BITRES>>1)) {
  621. qn = 1;
  622. } else {
  623. qn = exp2_table8[qb&0x7]>>(14-(qb>>BITRES));
  624. qn = (qn+1)>>1<<1;
  625. }
  626. celt_assert(qn <= 256);
  627. return qn;
  628. }
  629. struct band_ctx {
  630. int encode;
  631. int resynth;
  632. const CELTMode *m;
  633. int i;
  634. int intensity;
  635. int spread;
  636. int tf_change;
  637. ec_ctx *ec;
  638. opus_int32 remaining_bits;
  639. const celt_ener *bandE;
  640. opus_uint32 seed;
  641. int arch;
  642. int theta_round;
  643. int disable_inv;
  644. int avoid_split_noise;
  645. };
  646. struct split_ctx {
  647. int inv;
  648. int imid;
  649. int iside;
  650. int delta;
  651. int itheta;
  652. int qalloc;
  653. };
  654. static void compute_theta(struct band_ctx *ctx, struct split_ctx *sctx,
  655. celt_norm *X, celt_norm *Y, int N, int *b, int B, int B0,
  656. int LM,
  657. int stereo, int *fill)
  658. {
  659. int qn;
  660. int itheta=0;
  661. int delta;
  662. int imid, iside;
  663. int qalloc;
  664. int pulse_cap;
  665. int offset;
  666. opus_int32 tell;
  667. int inv=0;
  668. int encode;
  669. const CELTMode *m;
  670. int i;
  671. int intensity;
  672. ec_ctx *ec;
  673. const celt_ener *bandE;
  674. encode = ctx->encode;
  675. m = ctx->m;
  676. i = ctx->i;
  677. intensity = ctx->intensity;
  678. ec = ctx->ec;
  679. bandE = ctx->bandE;
  680. /* Decide on the resolution to give to the split parameter theta */
  681. pulse_cap = m->logN[i]+LM*(1<<BITRES);
  682. offset = (pulse_cap>>1) - (stereo&&N==2 ? QTHETA_OFFSET_TWOPHASE : QTHETA_OFFSET);
  683. qn = compute_qn(N, *b, offset, pulse_cap, stereo);
  684. if (stereo && i>=intensity)
  685. qn = 1;
  686. if (encode)
  687. {
  688. /* theta is the atan() of the ratio between the (normalized)
  689. side and mid. With just that parameter, we can re-scale both
  690. mid and side because we know that 1) they have unit norm and
  691. 2) they are orthogonal. */
  692. itheta = stereo_itheta(X, Y, stereo, N, ctx->arch);
  693. }
  694. tell = ec_tell_frac(ec);
  695. if (qn!=1)
  696. {
  697. if (encode)
  698. {
  699. if (!stereo || ctx->theta_round == 0)
  700. {
  701. itheta = (itheta*(opus_int32)qn+8192)>>14;
  702. if (!stereo && ctx->avoid_split_noise && itheta > 0 && itheta < qn)
  703. {
  704. /* Check if the selected value of theta will cause the bit allocation
  705. to inject noise on one side. If so, make sure the energy of that side
  706. is zero. */
  707. int unquantized = celt_udiv((opus_int32)itheta*16384, qn);
  708. imid = bitexact_cos((opus_int16)unquantized);
  709. iside = bitexact_cos((opus_int16)(16384-unquantized));
  710. delta = FRAC_MUL16((N-1)<<7,bitexact_log2tan(iside,imid));
  711. if (delta > *b)
  712. itheta = qn;
  713. else if (delta < -*b)
  714. itheta = 0;
  715. }
  716. } else {
  717. int down;
  718. /* Bias quantization towards itheta=0 and itheta=16384. */
  719. int bias = itheta > 8192 ? 32767/qn : -32767/qn;
  720. down = IMIN(qn-1, IMAX(0, (itheta*(opus_int32)qn + bias)>>14));
  721. if (ctx->theta_round < 0)
  722. itheta = down;
  723. else
  724. itheta = down+1;
  725. }
  726. }
  727. /* Entropy coding of the angle. We use a uniform pdf for the
  728. time split, a step for stereo, and a triangular one for the rest. */
  729. if (stereo && N>2)
  730. {
  731. int p0 = 3;
  732. int x = itheta;
  733. int x0 = qn/2;
  734. int ft = p0*(x0+1) + x0;
  735. /* Use a probability of p0 up to itheta=8192 and then use 1 after */
  736. if (encode)
  737. {
  738. ec_encode(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
  739. } else {
  740. int fs;
  741. fs=ec_decode(ec,ft);
  742. if (fs<(x0+1)*p0)
  743. x=fs/p0;
  744. else
  745. x=x0+1+(fs-(x0+1)*p0);
  746. ec_dec_update(ec,x<=x0?p0*x:(x-1-x0)+(x0+1)*p0,x<=x0?p0*(x+1):(x-x0)+(x0+1)*p0,ft);
  747. itheta = x;
  748. }
  749. } else if (B0>1 || stereo) {
  750. /* Uniform pdf */
  751. if (encode)
  752. ec_enc_uint(ec, itheta, qn+1);
  753. else
  754. itheta = ec_dec_uint(ec, qn+1);
  755. } else {
  756. int fs=1, ft;
  757. ft = ((qn>>1)+1)*((qn>>1)+1);
  758. if (encode)
  759. {
  760. int fl;
  761. fs = itheta <= (qn>>1) ? itheta + 1 : qn + 1 - itheta;
  762. fl = itheta <= (qn>>1) ? itheta*(itheta + 1)>>1 :
  763. ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
  764. ec_encode(ec, fl, fl+fs, ft);
  765. } else {
  766. /* Triangular pdf */
  767. int fl=0;
  768. int fm;
  769. fm = ec_decode(ec, ft);
  770. if (fm < ((qn>>1)*((qn>>1) + 1)>>1))
  771. {
  772. itheta = (isqrt32(8*(opus_uint32)fm + 1) - 1)>>1;
  773. fs = itheta + 1;
  774. fl = itheta*(itheta + 1)>>1;
  775. }
  776. else
  777. {
  778. itheta = (2*(qn + 1)
  779. - isqrt32(8*(opus_uint32)(ft - fm - 1) + 1))>>1;
  780. fs = qn + 1 - itheta;
  781. fl = ft - ((qn + 1 - itheta)*(qn + 2 - itheta)>>1);
  782. }
  783. ec_dec_update(ec, fl, fl+fs, ft);
  784. }
  785. }
  786. celt_assert(itheta>=0);
  787. itheta = celt_udiv((opus_int32)itheta*16384, qn);
  788. if (encode && stereo)
  789. {
  790. if (itheta==0)
  791. intensity_stereo(m, X, Y, bandE, i, N);
  792. else
  793. stereo_split(X, Y, N);
  794. }
  795. /* NOTE: Renormalising X and Y *may* help fixed-point a bit at very high rate.
  796. Let's do that at higher complexity */
  797. } else if (stereo) {
  798. if (encode)
  799. {
  800. inv = itheta > 8192 && !ctx->disable_inv;
  801. if (inv)
  802. {
  803. int j;
  804. for (j=0;j<N;j++)
  805. Y[j] = -Y[j];
  806. }
  807. intensity_stereo(m, X, Y, bandE, i, N);
  808. }
  809. if (*b>2<<BITRES && ctx->remaining_bits > 2<<BITRES)
  810. {
  811. if (encode)
  812. ec_enc_bit_logp(ec, inv, 2);
  813. else
  814. inv = ec_dec_bit_logp(ec, 2);
  815. } else
  816. inv = 0;
  817. /* inv flag override to avoid problems with downmixing. */
  818. if (ctx->disable_inv)
  819. inv = 0;
  820. itheta = 0;
  821. }
  822. qalloc = ec_tell_frac(ec) - tell;
  823. *b -= qalloc;
  824. if (itheta == 0)
  825. {
  826. imid = 32767;
  827. iside = 0;
  828. *fill &= (1<<B)-1;
  829. delta = -16384;
  830. } else if (itheta == 16384)
  831. {
  832. imid = 0;
  833. iside = 32767;
  834. *fill &= ((1<<B)-1)<<B;
  835. delta = 16384;
  836. } else {
  837. imid = bitexact_cos((opus_int16)itheta);
  838. iside = bitexact_cos((opus_int16)(16384-itheta));
  839. /* This is the mid vs side allocation that minimizes squared error
  840. in that band. */
  841. delta = FRAC_MUL16((N-1)<<7,bitexact_log2tan(iside,imid));
  842. }
  843. sctx->inv = inv;
  844. sctx->imid = imid;
  845. sctx->iside = iside;
  846. sctx->delta = delta;
  847. sctx->itheta = itheta;
  848. sctx->qalloc = qalloc;
  849. }
  850. static unsigned quant_band_n1(struct band_ctx *ctx, celt_norm *X, celt_norm *Y, int b,
  851. celt_norm *lowband_out)
  852. {
  853. int c;
  854. int stereo;
  855. celt_norm *x = X;
  856. int encode;
  857. ec_ctx *ec;
  858. encode = ctx->encode;
  859. ec = ctx->ec;
  860. stereo = Y != NULL;
  861. c=0; do {
  862. int sign=0;
  863. if (ctx->remaining_bits>=1<<BITRES)
  864. {
  865. if (encode)
  866. {
  867. sign = x[0]<0;
  868. ec_enc_bits(ec, sign, 1);
  869. } else {
  870. sign = ec_dec_bits(ec, 1);
  871. }
  872. ctx->remaining_bits -= 1<<BITRES;
  873. b-=1<<BITRES;
  874. }
  875. if (ctx->resynth)
  876. x[0] = sign ? -NORM_SCALING : NORM_SCALING;
  877. x = Y;
  878. } while (++c<1+stereo);
  879. if (lowband_out)
  880. lowband_out[0] = SHR16(X[0],4);
  881. return 1;
  882. }
  883. /* This function is responsible for encoding and decoding a mono partition.
  884. It can split the band in two and transmit the energy difference with
  885. the two half-bands. It can be called recursively so bands can end up being
  886. split in 8 parts. */
  887. static unsigned quant_partition(struct band_ctx *ctx, celt_norm *X,
  888. int N, int b, int B, celt_norm *lowband,
  889. int LM,
  890. opus_val16 gain, int fill)
  891. {
  892. const unsigned char *cache;
  893. int q;
  894. int curr_bits;
  895. int imid=0, iside=0;
  896. int B0=B;
  897. opus_val16 mid=0, side=0;
  898. unsigned cm=0;
  899. celt_norm *Y=NULL;
  900. int encode;
  901. const CELTMode *m;
  902. int i;
  903. int spread;
  904. ec_ctx *ec;
  905. encode = ctx->encode;
  906. m = ctx->m;
  907. i = ctx->i;
  908. spread = ctx->spread;
  909. ec = ctx->ec;
  910. /* If we need 1.5 more bit than we can produce, split the band in two. */
  911. cache = m->cache.bits + m->cache.index[(LM+1)*m->nbEBands+i];
  912. if (LM != -1 && b > cache[cache[0]]+12 && N>2)
  913. {
  914. int mbits, sbits, delta;
  915. int itheta;
  916. int qalloc;
  917. struct split_ctx sctx;
  918. celt_norm *next_lowband2=NULL;
  919. opus_int32 rebalance;
  920. N >>= 1;
  921. Y = X+N;
  922. LM -= 1;
  923. if (B==1)
  924. fill = (fill&1)|(fill<<1);
  925. B = (B+1)>>1;
  926. compute_theta(ctx, &sctx, X, Y, N, &b, B, B0, LM, 0, &fill);
  927. imid = sctx.imid;
  928. iside = sctx.iside;
  929. delta = sctx.delta;
  930. itheta = sctx.itheta;
  931. qalloc = sctx.qalloc;
  932. #ifdef FIXED_POINT
  933. mid = imid;
  934. side = iside;
  935. #else
  936. mid = (1.f/32768)*imid;
  937. side = (1.f/32768)*iside;
  938. #endif
  939. /* Give more bits to low-energy MDCTs than they would otherwise deserve */
  940. if (B0>1 && (itheta&0x3fff))
  941. {
  942. if (itheta > 8192)
  943. /* Rough approximation for pre-echo masking */
  944. delta -= delta>>(4-LM);
  945. else
  946. /* Corresponds to a forward-masking slope of 1.5 dB per 10 ms */
  947. delta = IMIN(0, delta + (N<<BITRES>>(5-LM)));
  948. }
  949. mbits = IMAX(0, IMIN(b, (b-delta)/2));
  950. sbits = b-mbits;
  951. ctx->remaining_bits -= qalloc;
  952. if (lowband)
  953. next_lowband2 = lowband+N; /* >32-bit split case */
  954. rebalance = ctx->remaining_bits;
  955. if (mbits >= sbits)
  956. {
  957. cm = quant_partition(ctx, X, N, mbits, B, lowband, LM,
  958. MULT16_16_P15(gain,mid), fill);
  959. rebalance = mbits - (rebalance-ctx->remaining_bits);
  960. if (rebalance > 3<<BITRES && itheta!=0)
  961. sbits += rebalance - (3<<BITRES);
  962. cm |= quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
  963. MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
  964. } else {
  965. cm = quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
  966. MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
  967. rebalance = sbits - (rebalance-ctx->remaining_bits);
  968. if (rebalance > 3<<BITRES && itheta!=16384)
  969. mbits += rebalance - (3<<BITRES);
  970. cm |= quant_partition(ctx, X, N, mbits, B, lowband, LM,
  971. MULT16_16_P15(gain,mid), fill);
  972. }
  973. } else {
  974. /* This is the basic no-split case */
  975. q = bits2pulses(m, i, LM, b);
  976. curr_bits = pulses2bits(m, i, LM, q);
  977. ctx->remaining_bits -= curr_bits;
  978. /* Ensures we can never bust the budget */
  979. while (ctx->remaining_bits < 0 && q > 0)
  980. {
  981. ctx->remaining_bits += curr_bits;
  982. q--;
  983. curr_bits = pulses2bits(m, i, LM, q);
  984. ctx->remaining_bits -= curr_bits;
  985. }
  986. if (q!=0)
  987. {
  988. int K = get_pulses(q);
  989. /* Finally do the actual quantization */
  990. if (encode)
  991. {
  992. cm = alg_quant(X, N, K, spread, B, ec, gain, ctx->resynth, ctx->arch);
  993. } else {
  994. cm = alg_unquant(X, N, K, spread, B, ec, gain);
  995. }
  996. } else {
  997. /* If there's no pulse, fill the band anyway */
  998. int j;
  999. if (ctx->resynth)
  1000. {
  1001. unsigned cm_mask;
  1002. /* B can be as large as 16, so this shift might overflow an int on a
  1003. 16-bit platform; use a long to get defined behavior.*/
  1004. cm_mask = (unsigned)(1UL<<B)-1;
  1005. fill &= cm_mask;
  1006. if (!fill)
  1007. {
  1008. OPUS_CLEAR(X, N);
  1009. } else {
  1010. if (lowband == NULL)
  1011. {
  1012. /* Noise */
  1013. for (j=0;j<N;j++)
  1014. {
  1015. ctx->seed = celt_lcg_rand(ctx->seed);
  1016. X[j] = (celt_norm)((opus_int32)ctx->seed>>20);
  1017. }
  1018. cm = cm_mask;
  1019. } else {
  1020. /* Folded spectrum */
  1021. for (j=0;j<N;j++)
  1022. {
  1023. opus_val16 tmp;
  1024. ctx->seed = celt_lcg_rand(ctx->seed);
  1025. /* About 48 dB below the "normal" folding level */
  1026. tmp = QCONST16(1.0f/256, 10);
  1027. tmp = (ctx->seed)&0x8000 ? tmp : -tmp;
  1028. X[j] = lowband[j]+tmp;
  1029. }
  1030. cm = fill;
  1031. }
  1032. renormalise_vector(X, N, gain, ctx->arch);
  1033. }
  1034. }
  1035. }
  1036. }
  1037. return cm;
  1038. }
  1039. /* This function is responsible for encoding and decoding a band for the mono case. */
  1040. static unsigned quant_band(struct band_ctx *ctx, celt_norm *X,
  1041. int N, int b, int B, celt_norm *lowband,
  1042. int LM, celt_norm *lowband_out,
  1043. opus_val16 gain, celt_norm *lowband_scratch, int fill)
  1044. {
  1045. int N0=N;
  1046. int N_B=N;
  1047. int N_B0;
  1048. int B0=B;
  1049. int time_divide=0;
  1050. int recombine=0;
  1051. int longBlocks;
  1052. unsigned cm=0;
  1053. int k;
  1054. int encode;
  1055. int tf_change;
  1056. encode = ctx->encode;
  1057. tf_change = ctx->tf_change;
  1058. longBlocks = B0==1;
  1059. N_B = celt_udiv(N_B, B);
  1060. /* Special case for one sample */
  1061. if (N==1)
  1062. {
  1063. return quant_band_n1(ctx, X, NULL, b, lowband_out);
  1064. }
  1065. if (tf_change>0)
  1066. recombine = tf_change;
  1067. /* Band recombining to increase frequency resolution */
  1068. if (lowband_scratch && lowband && (recombine || ((N_B&1) == 0 && tf_change<0) || B0>1))
  1069. {
  1070. OPUS_COPY(lowband_scratch, lowband, N);
  1071. lowband = lowband_scratch;
  1072. }
  1073. for (k=0;k<recombine;k++)
  1074. {
  1075. static const unsigned char bit_interleave_table[16]={
  1076. 0,1,1,1,2,3,3,3,2,3,3,3,2,3,3,3
  1077. };
  1078. if (encode)
  1079. haar1(X, N>>k, 1<<k);
  1080. if (lowband)
  1081. haar1(lowband, N>>k, 1<<k);
  1082. fill = bit_interleave_table[fill&0xF]|bit_interleave_table[fill>>4]<<2;
  1083. }
  1084. B>>=recombine;
  1085. N_B<<=recombine;
  1086. /* Increasing the time resolution */
  1087. while ((N_B&1) == 0 && tf_change<0)
  1088. {
  1089. if (encode)
  1090. haar1(X, N_B, B);
  1091. if (lowband)
  1092. haar1(lowband, N_B, B);
  1093. fill |= fill<<B;
  1094. B <<= 1;
  1095. N_B >>= 1;
  1096. time_divide++;
  1097. tf_change++;
  1098. }
  1099. B0=B;
  1100. N_B0 = N_B;
  1101. /* Reorganize the samples in time order instead of frequency order */
  1102. if (B0>1)
  1103. {
  1104. if (encode)
  1105. deinterleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
  1106. if (lowband)
  1107. deinterleave_hadamard(lowband, N_B>>recombine, B0<<recombine, longBlocks);
  1108. }
  1109. cm = quant_partition(ctx, X, N, b, B, lowband, LM, gain, fill);
  1110. /* This code is used by the decoder and by the resynthesis-enabled encoder */
  1111. if (ctx->resynth)
  1112. {
  1113. /* Undo the sample reorganization going from time order to frequency order */
  1114. if (B0>1)
  1115. interleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
  1116. /* Undo time-freq changes that we did earlier */
  1117. N_B = N_B0;
  1118. B = B0;
  1119. for (k=0;k<time_divide;k++)
  1120. {
  1121. B >>= 1;
  1122. N_B <<= 1;
  1123. cm |= cm>>B;
  1124. haar1(X, N_B, B);
  1125. }
  1126. for (k=0;k<recombine;k++)
  1127. {
  1128. static const unsigned char bit_deinterleave_table[16]={
  1129. 0x00,0x03,0x0C,0x0F,0x30,0x33,0x3C,0x3F,
  1130. 0xC0,0xC3,0xCC,0xCF,0xF0,0xF3,0xFC,0xFF
  1131. };
  1132. cm = bit_deinterleave_table[cm];
  1133. haar1(X, N0>>k, 1<<k);
  1134. }
  1135. B<<=recombine;
  1136. /* Scale output for later folding */
  1137. if (lowband_out)
  1138. {
  1139. int j;
  1140. opus_val16 n;
  1141. n = celt_sqrt(SHL32(EXTEND32(N0),22));
  1142. for (j=0;j<N0;j++)
  1143. lowband_out[j] = MULT16_16_Q15(n,X[j]);
  1144. }
  1145. cm &= (1<<B)-1;
  1146. }
  1147. return cm;
  1148. }
  1149. /* This function is responsible for encoding and decoding a band for the stereo case. */
  1150. static unsigned quant_band_stereo(struct band_ctx *ctx, celt_norm *X, celt_norm *Y,
  1151. int N, int b, int B, celt_norm *lowband,
  1152. int LM, celt_norm *lowband_out,
  1153. celt_norm *lowband_scratch, int fill)
  1154. {
  1155. int imid=0, iside=0;
  1156. int inv = 0;
  1157. opus_val16 mid=0, side=0;
  1158. unsigned cm=0;
  1159. int mbits, sbits, delta;
  1160. int itheta;
  1161. int qalloc;
  1162. struct split_ctx sctx;
  1163. int orig_fill;
  1164. int encode;
  1165. ec_ctx *ec;
  1166. encode = ctx->encode;
  1167. ec = ctx->ec;
  1168. /* Special case for one sample */
  1169. if (N==1)
  1170. {
  1171. return quant_band_n1(ctx, X, Y, b, lowband_out);
  1172. }
  1173. orig_fill = fill;
  1174. compute_theta(ctx, &sctx, X, Y, N, &b, B, B, LM, 1, &fill);
  1175. inv = sctx.inv;
  1176. imid = sctx.imid;
  1177. iside = sctx.iside;
  1178. delta = sctx.delta;
  1179. itheta = sctx.itheta;
  1180. qalloc = sctx.qalloc;
  1181. #ifdef FIXED_POINT
  1182. mid = imid;
  1183. side = iside;
  1184. #else
  1185. mid = (1.f/32768)*imid;
  1186. side = (1.f/32768)*iside;
  1187. #endif
  1188. /* This is a special case for N=2 that only works for stereo and takes
  1189. advantage of the fact that mid and side are orthogonal to encode
  1190. the side with just one bit. */
  1191. if (N==2)
  1192. {
  1193. int c;
  1194. int sign=0;
  1195. celt_norm *x2, *y2;
  1196. mbits = b;
  1197. sbits = 0;
  1198. /* Only need one bit for the side. */
  1199. if (itheta != 0 && itheta != 16384)
  1200. sbits = 1<<BITRES;
  1201. mbits -= sbits;
  1202. c = itheta > 8192;
  1203. ctx->remaining_bits -= qalloc+sbits;
  1204. x2 = c ? Y : X;
  1205. y2 = c ? X : Y;
  1206. if (sbits)
  1207. {
  1208. if (encode)
  1209. {
  1210. /* Here we only need to encode a sign for the side. */
  1211. sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
  1212. ec_enc_bits(ec, sign, 1);
  1213. } else {
  1214. sign = ec_dec_bits(ec, 1);
  1215. }
  1216. }
  1217. sign = 1-2*sign;
  1218. /* We use orig_fill here because we want to fold the side, but if
  1219. itheta==16384, we'll have cleared the low bits of fill. */
  1220. cm = quant_band(ctx, x2, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1221. lowband_scratch, orig_fill);
  1222. /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
  1223. and there's no need to worry about mixing with the other channel. */
  1224. y2[0] = -sign*x2[1];
  1225. y2[1] = sign*x2[0];
  1226. if (ctx->resynth)
  1227. {
  1228. celt_norm tmp;
  1229. X[0] = MULT16_16_Q15(mid, X[0]);
  1230. X[1] = MULT16_16_Q15(mid, X[1]);
  1231. Y[0] = MULT16_16_Q15(side, Y[0]);
  1232. Y[1] = MULT16_16_Q15(side, Y[1]);
  1233. tmp = X[0];
  1234. X[0] = SUB16(tmp,Y[0]);
  1235. Y[0] = ADD16(tmp,Y[0]);
  1236. tmp = X[1];
  1237. X[1] = SUB16(tmp,Y[1]);
  1238. Y[1] = ADD16(tmp,Y[1]);
  1239. }
  1240. } else {
  1241. /* "Normal" split code */
  1242. opus_int32 rebalance;
  1243. mbits = IMAX(0, IMIN(b, (b-delta)/2));
  1244. sbits = b-mbits;
  1245. ctx->remaining_bits -= qalloc;
  1246. rebalance = ctx->remaining_bits;
  1247. if (mbits >= sbits)
  1248. {
  1249. /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
  1250. mid for folding later. */
  1251. cm = quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1252. lowband_scratch, fill);
  1253. rebalance = mbits - (rebalance-ctx->remaining_bits);
  1254. if (rebalance > 3<<BITRES && itheta!=0)
  1255. sbits += rebalance - (3<<BITRES);
  1256. /* For a stereo split, the high bits of fill are always zero, so no
  1257. folding will be done to the side. */
  1258. cm |= quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
  1259. } else {
  1260. /* For a stereo split, the high bits of fill are always zero, so no
  1261. folding will be done to the side. */
  1262. cm = quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
  1263. rebalance = sbits - (rebalance-ctx->remaining_bits);
  1264. if (rebalance > 3<<BITRES && itheta!=16384)
  1265. mbits += rebalance - (3<<BITRES);
  1266. /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
  1267. mid for folding later. */
  1268. cm |= quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1269. lowband_scratch, fill);
  1270. }
  1271. }
  1272. /* This code is used by the decoder and by the resynthesis-enabled encoder */
  1273. if (ctx->resynth)
  1274. {
  1275. if (N!=2)
  1276. stereo_merge(X, Y, mid, N, ctx->arch);
  1277. if (inv)
  1278. {
  1279. int j;
  1280. for (j=0;j<N;j++)
  1281. Y[j] = -Y[j];
  1282. }
  1283. }
  1284. return cm;
  1285. }
  1286. static void special_hybrid_folding(const CELTMode *m, celt_norm *norm, celt_norm *norm2, int start, int M, int dual_stereo)
  1287. {
  1288. int n1, n2;
  1289. const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
  1290. n1 = M*(eBands[start+1]-eBands[start]);
  1291. n2 = M*(eBands[start+2]-eBands[start+1]);
  1292. /* Duplicate enough of the first band folding data to be able to fold the second band.
  1293. Copies no data for CELT-only mode. */
  1294. OPUS_COPY(&norm[n1], &norm[2*n1 - n2], n2-n1);
  1295. if (dual_stereo)
  1296. OPUS_COPY(&norm2[n1], &norm2[2*n1 - n2], n2-n1);
  1297. }
  1298. void quant_all_bands(int encode, const CELTMode *m, int start, int end,
  1299. celt_norm *X_, celt_norm *Y_, unsigned char *collapse_masks,
  1300. const celt_ener *bandE, int *pulses, int shortBlocks, int spread,
  1301. int dual_stereo, int intensity, int *tf_res, opus_int32 total_bits,
  1302. opus_int32 balance, ec_ctx *ec, int LM, int codedBands,
  1303. opus_uint32 *seed, int complexity, int arch, int disable_inv)
  1304. {
  1305. int i;
  1306. opus_int32 remaining_bits;
  1307. const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
  1308. celt_norm * OPUS_RESTRICT norm, * OPUS_RESTRICT norm2;
  1309. VARDECL(celt_norm, _norm);
  1310. VARDECL(celt_norm, _lowband_scratch);
  1311. VARDECL(celt_norm, X_save);
  1312. VARDECL(celt_norm, Y_save);
  1313. VARDECL(celt_norm, X_save2);
  1314. VARDECL(celt_norm, Y_save2);
  1315. VARDECL(celt_norm, norm_save2);
  1316. int resynth_alloc;
  1317. celt_norm *lowband_scratch;
  1318. int B;
  1319. int M;
  1320. int lowband_offset;
  1321. int update_lowband = 1;
  1322. int C = Y_ != NULL ? 2 : 1;
  1323. int norm_offset;
  1324. int theta_rdo = encode && Y_!=NULL && !dual_stereo && complexity>=8;
  1325. #ifdef RESYNTH
  1326. int resynth = 1;
  1327. #else
  1328. int resynth = !encode || theta_rdo;
  1329. #endif
  1330. struct band_ctx ctx;
  1331. SAVE_STACK;
  1332. M = 1<<LM;
  1333. B = shortBlocks ? M : 1;
  1334. norm_offset = M*eBands[start];
  1335. /* No need to allocate norm for the last band because we don't need an
  1336. output in that band. */
  1337. ALLOC(_norm, C*(M*eBands[m->nbEBands-1]-norm_offset), celt_norm);
  1338. norm = _norm;
  1339. norm2 = norm + M*eBands[m->nbEBands-1]-norm_offset;
  1340. /* For decoding, we can use the last band as scratch space because we don't need that
  1341. scratch space for the last band and we don't care about the data there until we're
  1342. decoding the last band. */
  1343. if (encode && resynth)
  1344. resynth_alloc = M*(eBands[m->nbEBands]-eBands[m->nbEBands-1]);
  1345. else
  1346. resynth_alloc = ALLOC_NONE;
  1347. ALLOC(_lowband_scratch, resynth_alloc, celt_norm);
  1348. if (encode && resynth)
  1349. lowband_scratch = _lowband_scratch;
  1350. else
  1351. lowband_scratch = X_+M*eBands[m->nbEBands-1];
  1352. ALLOC(X_save, resynth_alloc, celt_norm);
  1353. ALLOC(Y_save, resynth_alloc, celt_norm);
  1354. ALLOC(X_save2, resynth_alloc, celt_norm);
  1355. ALLOC(Y_save2, resynth_alloc, celt_norm);
  1356. ALLOC(norm_save2, resynth_alloc, celt_norm);
  1357. lowband_offset = 0;
  1358. ctx.bandE = bandE;
  1359. ctx.ec = ec;
  1360. ctx.encode = encode;
  1361. ctx.intensity = intensity;
  1362. ctx.m = m;
  1363. ctx.seed = *seed;
  1364. ctx.spread = spread;
  1365. ctx.arch = arch;
  1366. ctx.disable_inv = disable_inv;
  1367. ctx.resynth = resynth;
  1368. ctx.theta_round = 0;
  1369. /* Avoid injecting noise in the first band on transients. */
  1370. ctx.avoid_split_noise = B > 1;
  1371. for (i=start;i<end;i++)
  1372. {
  1373. opus_int32 tell;
  1374. int b;
  1375. int N;
  1376. opus_int32 curr_balance;
  1377. int effective_lowband=-1;
  1378. celt_norm * OPUS_RESTRICT X, * OPUS_RESTRICT Y;
  1379. int tf_change=0;
  1380. unsigned x_cm;
  1381. unsigned y_cm;
  1382. int last;
  1383. ctx.i = i;
  1384. last = (i==end-1);
  1385. X = X_+M*eBands[i];
  1386. if (Y_!=NULL)
  1387. Y = Y_+M*eBands[i];
  1388. else
  1389. Y = NULL;
  1390. N = M*eBands[i+1]-M*eBands[i];
  1391. celt_assert(N > 0);
  1392. tell = ec_tell_frac(ec);
  1393. /* Compute how many bits we want to allocate to this band */
  1394. if (i != start)
  1395. balance -= tell;
  1396. remaining_bits = total_bits-tell-1;
  1397. ctx.remaining_bits = remaining_bits;
  1398. if (i <= codedBands-1)
  1399. {
  1400. curr_balance = celt_sudiv(balance, IMIN(3, codedBands-i));
  1401. b = IMAX(0, IMIN(16383, IMIN(remaining_bits+1,pulses[i]+curr_balance)));
  1402. } else {
  1403. b = 0;
  1404. }
  1405. #ifndef DISABLE_UPDATE_DRAFT
  1406. if (resynth && (M*eBands[i]-N >= M*eBands[start] || i==start+1) && (update_lowband || lowband_offset==0))
  1407. lowband_offset = i;
  1408. if (i == start+1)
  1409. special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
  1410. #else
  1411. if (resynth && M*eBands[i]-N >= M*eBands[start] && (update_lowband || lowband_offset==0))
  1412. lowband_offset = i;
  1413. #endif
  1414. tf_change = tf_res[i];
  1415. ctx.tf_change = tf_change;
  1416. if (i>=m->effEBands)
  1417. {
  1418. X=norm;
  1419. if (Y_!=NULL)
  1420. Y = norm;
  1421. lowband_scratch = NULL;
  1422. }
  1423. if (last && !theta_rdo)
  1424. lowband_scratch = NULL;
  1425. /* Get a conservative estimate of the collapse_mask's for the bands we're
  1426. going to be folding from. */
  1427. if (lowband_offset != 0 && (spread!=SPREAD_AGGRESSIVE || B>1 || tf_change<0))
  1428. {
  1429. int fold_start;
  1430. int fold_end;
  1431. int fold_i;
  1432. /* This ensures we never repeat spectral content within one band */
  1433. effective_lowband = IMAX(0, M*eBands[lowband_offset]-norm_offset-N);
  1434. fold_start = lowband_offset;
  1435. while(M*eBands[--fold_start] > effective_lowband+norm_offset);
  1436. fold_end = lowband_offset-1;
  1437. #ifndef DISABLE_UPDATE_DRAFT
  1438. while(++fold_end < i && M*eBands[fold_end] < effective_lowband+norm_offset+N);
  1439. #else
  1440. while(M*eBands[++fold_end] < effective_lowband+norm_offset+N);
  1441. #endif
  1442. x_cm = y_cm = 0;
  1443. fold_i = fold_start; do {
  1444. x_cm |= collapse_masks[fold_i*C+0];
  1445. y_cm |= collapse_masks[fold_i*C+C-1];
  1446. } while (++fold_i<fold_end);
  1447. }
  1448. /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
  1449. always) be non-zero. */
  1450. else
  1451. x_cm = y_cm = (1<<B)-1;
  1452. if (dual_stereo && i==intensity)
  1453. {
  1454. int j;
  1455. /* Switch off dual stereo to do intensity. */
  1456. dual_stereo = 0;
  1457. if (resynth)
  1458. for (j=0;j<M*eBands[i]-norm_offset;j++)
  1459. norm[j] = HALF32(norm[j]+norm2[j]);
  1460. }
  1461. if (dual_stereo)
  1462. {
  1463. x_cm = quant_band(&ctx, X, N, b/2, B,
  1464. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1465. last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm);
  1466. y_cm = quant_band(&ctx, Y, N, b/2, B,
  1467. effective_lowband != -1 ? norm2+effective_lowband : NULL, LM,
  1468. last?NULL:norm2+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, y_cm);
  1469. } else {
  1470. if (Y!=NULL)
  1471. {
  1472. if (theta_rdo && i < intensity)
  1473. {
  1474. ec_ctx ec_save, ec_save2;
  1475. struct band_ctx ctx_save, ctx_save2;
  1476. opus_val32 dist0, dist1;
  1477. unsigned cm, cm2;
  1478. int nstart_bytes, nend_bytes, save_bytes;
  1479. unsigned char *bytes_buf;
  1480. unsigned char bytes_save[1275];
  1481. opus_val16 w[2];
  1482. compute_channel_weights(bandE[i], bandE[i+m->nbEBands], w);
  1483. /* Make a copy. */
  1484. cm = x_cm|y_cm;
  1485. ec_save = *ec;
  1486. ctx_save = ctx;
  1487. OPUS_COPY(X_save, X, N);
  1488. OPUS_COPY(Y_save, Y, N);
  1489. /* Encode and round down. */
  1490. ctx.theta_round = -1;
  1491. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1492. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1493. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
  1494. dist0 = MULT16_32_Q15(w[0], celt_inner_prod(X_save, X, N, arch)) + MULT16_32_Q15(w[1], celt_inner_prod(Y_save, Y, N, arch));
  1495. /* Save first result. */
  1496. cm2 = x_cm;
  1497. ec_save2 = *ec;
  1498. ctx_save2 = ctx;
  1499. OPUS_COPY(X_save2, X, N);
  1500. OPUS_COPY(Y_save2, Y, N);
  1501. if (!last)
  1502. OPUS_COPY(norm_save2, norm+M*eBands[i]-norm_offset, N);
  1503. nstart_bytes = ec_save.offs;
  1504. nend_bytes = ec_save.storage;
  1505. bytes_buf = ec_save.buf+nstart_bytes;
  1506. save_bytes = nend_bytes-nstart_bytes;
  1507. OPUS_COPY(bytes_save, bytes_buf, save_bytes);
  1508. /* Restore */
  1509. *ec = ec_save;
  1510. ctx = ctx_save;
  1511. OPUS_COPY(X, X_save, N);
  1512. OPUS_COPY(Y, Y_save, N);
  1513. #ifndef DISABLE_UPDATE_DRAFT
  1514. if (i == start+1)
  1515. special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
  1516. #endif
  1517. /* Encode and round up. */
  1518. ctx.theta_round = 1;
  1519. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1520. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1521. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
  1522. dist1 = MULT16_32_Q15(w[0], celt_inner_prod(X_save, X, N, arch)) + MULT16_32_Q15(w[1], celt_inner_prod(Y_save, Y, N, arch));
  1523. if (dist0 >= dist1) {
  1524. x_cm = cm2;
  1525. *ec = ec_save2;
  1526. ctx = ctx_save2;
  1527. OPUS_COPY(X, X_save2, N);
  1528. OPUS_COPY(Y, Y_save2, N);
  1529. if (!last)
  1530. OPUS_COPY(norm+M*eBands[i]-norm_offset, norm_save2, N);
  1531. OPUS_COPY(bytes_buf, bytes_save, save_bytes);
  1532. }
  1533. } else {
  1534. ctx.theta_round = 0;
  1535. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1536. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1537. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, x_cm|y_cm);
  1538. }
  1539. } else {
  1540. x_cm = quant_band(&ctx, X, N, b, B,
  1541. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1542. last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm|y_cm);
  1543. }
  1544. y_cm = x_cm;
  1545. }
  1546. collapse_masks[i*C+0] = (unsigned char)x_cm;
  1547. collapse_masks[i*C+C-1] = (unsigned char)y_cm;
  1548. balance += pulses[i] + tell;
  1549. /* Update the folding position only as long as we have 1 bit/sample depth. */
  1550. update_lowband = b>(N<<BITRES);
  1551. /* We only need to avoid noise on a split for the first band. After that, we
  1552. have folding. */
  1553. ctx.avoid_split_noise = 0;
  1554. }
  1555. *seed = ctx.seed;
  1556. RESTORE_STACK;
  1557. }