bands.c 46 KB

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