bands.c 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  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,
  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. }
  874. if (ctx->resynth)
  875. x[0] = sign ? -NORM_SCALING : NORM_SCALING;
  876. x = Y;
  877. } while (++c<1+stereo);
  878. if (lowband_out)
  879. lowband_out[0] = SHR16(X[0],4);
  880. return 1;
  881. }
  882. /* This function is responsible for encoding and decoding a mono partition.
  883. It can split the band in two and transmit the energy difference with
  884. the two half-bands. It can be called recursively so bands can end up being
  885. split in 8 parts. */
  886. static unsigned quant_partition(struct band_ctx *ctx, celt_norm *X,
  887. int N, int b, int B, celt_norm *lowband,
  888. int LM,
  889. opus_val16 gain, int fill)
  890. {
  891. const unsigned char *cache;
  892. int q;
  893. int curr_bits;
  894. int imid=0, iside=0;
  895. int B0=B;
  896. opus_val16 mid=0, side=0;
  897. unsigned cm=0;
  898. celt_norm *Y=NULL;
  899. int encode;
  900. const CELTMode *m;
  901. int i;
  902. int spread;
  903. ec_ctx *ec;
  904. encode = ctx->encode;
  905. m = ctx->m;
  906. i = ctx->i;
  907. spread = ctx->spread;
  908. ec = ctx->ec;
  909. /* If we need 1.5 more bit than we can produce, split the band in two. */
  910. cache = m->cache.bits + m->cache.index[(LM+1)*m->nbEBands+i];
  911. if (LM != -1 && b > cache[cache[0]]+12 && N>2)
  912. {
  913. int mbits, sbits, delta;
  914. int itheta;
  915. int qalloc;
  916. struct split_ctx sctx;
  917. celt_norm *next_lowband2=NULL;
  918. opus_int32 rebalance;
  919. N >>= 1;
  920. Y = X+N;
  921. LM -= 1;
  922. if (B==1)
  923. fill = (fill&1)|(fill<<1);
  924. B = (B+1)>>1;
  925. compute_theta(ctx, &sctx, X, Y, N, &b, B, B0, LM, 0, &fill);
  926. imid = sctx.imid;
  927. iside = sctx.iside;
  928. delta = sctx.delta;
  929. itheta = sctx.itheta;
  930. qalloc = sctx.qalloc;
  931. #ifdef FIXED_POINT
  932. mid = imid;
  933. side = iside;
  934. #else
  935. mid = (1.f/32768)*imid;
  936. side = (1.f/32768)*iside;
  937. #endif
  938. /* Give more bits to low-energy MDCTs than they would otherwise deserve */
  939. if (B0>1 && (itheta&0x3fff))
  940. {
  941. if (itheta > 8192)
  942. /* Rough approximation for pre-echo masking */
  943. delta -= delta>>(4-LM);
  944. else
  945. /* Corresponds to a forward-masking slope of 1.5 dB per 10 ms */
  946. delta = IMIN(0, delta + (N<<BITRES>>(5-LM)));
  947. }
  948. mbits = IMAX(0, IMIN(b, (b-delta)/2));
  949. sbits = b-mbits;
  950. ctx->remaining_bits -= qalloc;
  951. if (lowband)
  952. next_lowband2 = lowband+N; /* >32-bit split case */
  953. rebalance = ctx->remaining_bits;
  954. if (mbits >= sbits)
  955. {
  956. cm = quant_partition(ctx, X, N, mbits, B, lowband, LM,
  957. MULT16_16_P15(gain,mid), fill);
  958. rebalance = mbits - (rebalance-ctx->remaining_bits);
  959. if (rebalance > 3<<BITRES && itheta!=0)
  960. sbits += rebalance - (3<<BITRES);
  961. cm |= quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
  962. MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
  963. } else {
  964. cm = quant_partition(ctx, Y, N, sbits, B, next_lowband2, LM,
  965. MULT16_16_P15(gain,side), fill>>B)<<(B0>>1);
  966. rebalance = sbits - (rebalance-ctx->remaining_bits);
  967. if (rebalance > 3<<BITRES && itheta!=16384)
  968. mbits += rebalance - (3<<BITRES);
  969. cm |= quant_partition(ctx, X, N, mbits, B, lowband, LM,
  970. MULT16_16_P15(gain,mid), fill);
  971. }
  972. } else {
  973. /* This is the basic no-split case */
  974. q = bits2pulses(m, i, LM, b);
  975. curr_bits = pulses2bits(m, i, LM, q);
  976. ctx->remaining_bits -= curr_bits;
  977. /* Ensures we can never bust the budget */
  978. while (ctx->remaining_bits < 0 && q > 0)
  979. {
  980. ctx->remaining_bits += curr_bits;
  981. q--;
  982. curr_bits = pulses2bits(m, i, LM, q);
  983. ctx->remaining_bits -= curr_bits;
  984. }
  985. if (q!=0)
  986. {
  987. int K = get_pulses(q);
  988. /* Finally do the actual quantization */
  989. if (encode)
  990. {
  991. cm = alg_quant(X, N, K, spread, B, ec, gain, ctx->resynth, ctx->arch);
  992. } else {
  993. cm = alg_unquant(X, N, K, spread, B, ec, gain);
  994. }
  995. } else {
  996. /* If there's no pulse, fill the band anyway */
  997. int j;
  998. if (ctx->resynth)
  999. {
  1000. unsigned cm_mask;
  1001. /* B can be as large as 16, so this shift might overflow an int on a
  1002. 16-bit platform; use a long to get defined behavior.*/
  1003. cm_mask = (unsigned)(1UL<<B)-1;
  1004. fill &= cm_mask;
  1005. if (!fill)
  1006. {
  1007. OPUS_CLEAR(X, N);
  1008. } else {
  1009. if (lowband == NULL)
  1010. {
  1011. /* Noise */
  1012. for (j=0;j<N;j++)
  1013. {
  1014. ctx->seed = celt_lcg_rand(ctx->seed);
  1015. X[j] = (celt_norm)((opus_int32)ctx->seed>>20);
  1016. }
  1017. cm = cm_mask;
  1018. } else {
  1019. /* Folded spectrum */
  1020. for (j=0;j<N;j++)
  1021. {
  1022. opus_val16 tmp;
  1023. ctx->seed = celt_lcg_rand(ctx->seed);
  1024. /* About 48 dB below the "normal" folding level */
  1025. tmp = QCONST16(1.0f/256, 10);
  1026. tmp = (ctx->seed)&0x8000 ? tmp : -tmp;
  1027. X[j] = lowband[j]+tmp;
  1028. }
  1029. cm = fill;
  1030. }
  1031. renormalise_vector(X, N, gain, ctx->arch);
  1032. }
  1033. }
  1034. }
  1035. }
  1036. return cm;
  1037. }
  1038. /* This function is responsible for encoding and decoding a band for the mono case. */
  1039. static unsigned quant_band(struct band_ctx *ctx, celt_norm *X,
  1040. int N, int b, int B, celt_norm *lowband,
  1041. int LM, celt_norm *lowband_out,
  1042. opus_val16 gain, celt_norm *lowband_scratch, int fill)
  1043. {
  1044. int N0=N;
  1045. int N_B=N;
  1046. int N_B0;
  1047. int B0=B;
  1048. int time_divide=0;
  1049. int recombine=0;
  1050. int longBlocks;
  1051. unsigned cm=0;
  1052. int k;
  1053. int encode;
  1054. int tf_change;
  1055. encode = ctx->encode;
  1056. tf_change = ctx->tf_change;
  1057. longBlocks = B0==1;
  1058. N_B = celt_udiv(N_B, B);
  1059. /* Special case for one sample */
  1060. if (N==1)
  1061. {
  1062. return quant_band_n1(ctx, X, NULL, lowband_out);
  1063. }
  1064. if (tf_change>0)
  1065. recombine = tf_change;
  1066. /* Band recombining to increase frequency resolution */
  1067. if (lowband_scratch && lowband && (recombine || ((N_B&1) == 0 && tf_change<0) || B0>1))
  1068. {
  1069. OPUS_COPY(lowband_scratch, lowband, N);
  1070. lowband = lowband_scratch;
  1071. }
  1072. for (k=0;k<recombine;k++)
  1073. {
  1074. static const unsigned char bit_interleave_table[16]={
  1075. 0,1,1,1,2,3,3,3,2,3,3,3,2,3,3,3
  1076. };
  1077. if (encode)
  1078. haar1(X, N>>k, 1<<k);
  1079. if (lowband)
  1080. haar1(lowband, N>>k, 1<<k);
  1081. fill = bit_interleave_table[fill&0xF]|bit_interleave_table[fill>>4]<<2;
  1082. }
  1083. B>>=recombine;
  1084. N_B<<=recombine;
  1085. /* Increasing the time resolution */
  1086. while ((N_B&1) == 0 && tf_change<0)
  1087. {
  1088. if (encode)
  1089. haar1(X, N_B, B);
  1090. if (lowband)
  1091. haar1(lowband, N_B, B);
  1092. fill |= fill<<B;
  1093. B <<= 1;
  1094. N_B >>= 1;
  1095. time_divide++;
  1096. tf_change++;
  1097. }
  1098. B0=B;
  1099. N_B0 = N_B;
  1100. /* Reorganize the samples in time order instead of frequency order */
  1101. if (B0>1)
  1102. {
  1103. if (encode)
  1104. deinterleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
  1105. if (lowband)
  1106. deinterleave_hadamard(lowband, N_B>>recombine, B0<<recombine, longBlocks);
  1107. }
  1108. cm = quant_partition(ctx, X, N, b, B, lowband, LM, gain, fill);
  1109. /* This code is used by the decoder and by the resynthesis-enabled encoder */
  1110. if (ctx->resynth)
  1111. {
  1112. /* Undo the sample reorganization going from time order to frequency order */
  1113. if (B0>1)
  1114. interleave_hadamard(X, N_B>>recombine, B0<<recombine, longBlocks);
  1115. /* Undo time-freq changes that we did earlier */
  1116. N_B = N_B0;
  1117. B = B0;
  1118. for (k=0;k<time_divide;k++)
  1119. {
  1120. B >>= 1;
  1121. N_B <<= 1;
  1122. cm |= cm>>B;
  1123. haar1(X, N_B, B);
  1124. }
  1125. for (k=0;k<recombine;k++)
  1126. {
  1127. static const unsigned char bit_deinterleave_table[16]={
  1128. 0x00,0x03,0x0C,0x0F,0x30,0x33,0x3C,0x3F,
  1129. 0xC0,0xC3,0xCC,0xCF,0xF0,0xF3,0xFC,0xFF
  1130. };
  1131. cm = bit_deinterleave_table[cm];
  1132. haar1(X, N0>>k, 1<<k);
  1133. }
  1134. B<<=recombine;
  1135. /* Scale output for later folding */
  1136. if (lowband_out)
  1137. {
  1138. int j;
  1139. opus_val16 n;
  1140. n = celt_sqrt(SHL32(EXTEND32(N0),22));
  1141. for (j=0;j<N0;j++)
  1142. lowband_out[j] = MULT16_16_Q15(n,X[j]);
  1143. }
  1144. cm &= (1<<B)-1;
  1145. }
  1146. return cm;
  1147. }
  1148. /* This function is responsible for encoding and decoding a band for the stereo case. */
  1149. static unsigned quant_band_stereo(struct band_ctx *ctx, celt_norm *X, celt_norm *Y,
  1150. int N, int b, int B, celt_norm *lowband,
  1151. int LM, celt_norm *lowband_out,
  1152. celt_norm *lowband_scratch, int fill)
  1153. {
  1154. int imid=0, iside=0;
  1155. int inv = 0;
  1156. opus_val16 mid=0, side=0;
  1157. unsigned cm=0;
  1158. int mbits, sbits, delta;
  1159. int itheta;
  1160. int qalloc;
  1161. struct split_ctx sctx;
  1162. int orig_fill;
  1163. int encode;
  1164. ec_ctx *ec;
  1165. encode = ctx->encode;
  1166. ec = ctx->ec;
  1167. /* Special case for one sample */
  1168. if (N==1)
  1169. {
  1170. return quant_band_n1(ctx, X, Y, lowband_out);
  1171. }
  1172. orig_fill = fill;
  1173. compute_theta(ctx, &sctx, X, Y, N, &b, B, B, LM, 1, &fill);
  1174. inv = sctx.inv;
  1175. imid = sctx.imid;
  1176. iside = sctx.iside;
  1177. delta = sctx.delta;
  1178. itheta = sctx.itheta;
  1179. qalloc = sctx.qalloc;
  1180. #ifdef FIXED_POINT
  1181. mid = imid;
  1182. side = iside;
  1183. #else
  1184. mid = (1.f/32768)*imid;
  1185. side = (1.f/32768)*iside;
  1186. #endif
  1187. /* This is a special case for N=2 that only works for stereo and takes
  1188. advantage of the fact that mid and side are orthogonal to encode
  1189. the side with just one bit. */
  1190. if (N==2)
  1191. {
  1192. int c;
  1193. int sign=0;
  1194. celt_norm *x2, *y2;
  1195. mbits = b;
  1196. sbits = 0;
  1197. /* Only need one bit for the side. */
  1198. if (itheta != 0 && itheta != 16384)
  1199. sbits = 1<<BITRES;
  1200. mbits -= sbits;
  1201. c = itheta > 8192;
  1202. ctx->remaining_bits -= qalloc+sbits;
  1203. x2 = c ? Y : X;
  1204. y2 = c ? X : Y;
  1205. if (sbits)
  1206. {
  1207. if (encode)
  1208. {
  1209. /* Here we only need to encode a sign for the side. */
  1210. sign = x2[0]*y2[1] - x2[1]*y2[0] < 0;
  1211. ec_enc_bits(ec, sign, 1);
  1212. } else {
  1213. sign = ec_dec_bits(ec, 1);
  1214. }
  1215. }
  1216. sign = 1-2*sign;
  1217. /* We use orig_fill here because we want to fold the side, but if
  1218. itheta==16384, we'll have cleared the low bits of fill. */
  1219. cm = quant_band(ctx, x2, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1220. lowband_scratch, orig_fill);
  1221. /* We don't split N=2 bands, so cm is either 1 or 0 (for a fold-collapse),
  1222. and there's no need to worry about mixing with the other channel. */
  1223. y2[0] = -sign*x2[1];
  1224. y2[1] = sign*x2[0];
  1225. if (ctx->resynth)
  1226. {
  1227. celt_norm tmp;
  1228. X[0] = MULT16_16_Q15(mid, X[0]);
  1229. X[1] = MULT16_16_Q15(mid, X[1]);
  1230. Y[0] = MULT16_16_Q15(side, Y[0]);
  1231. Y[1] = MULT16_16_Q15(side, Y[1]);
  1232. tmp = X[0];
  1233. X[0] = SUB16(tmp,Y[0]);
  1234. Y[0] = ADD16(tmp,Y[0]);
  1235. tmp = X[1];
  1236. X[1] = SUB16(tmp,Y[1]);
  1237. Y[1] = ADD16(tmp,Y[1]);
  1238. }
  1239. } else {
  1240. /* "Normal" split code */
  1241. opus_int32 rebalance;
  1242. mbits = IMAX(0, IMIN(b, (b-delta)/2));
  1243. sbits = b-mbits;
  1244. ctx->remaining_bits -= qalloc;
  1245. rebalance = ctx->remaining_bits;
  1246. if (mbits >= sbits)
  1247. {
  1248. /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
  1249. mid for folding later. */
  1250. cm = quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1251. lowband_scratch, fill);
  1252. rebalance = mbits - (rebalance-ctx->remaining_bits);
  1253. if (rebalance > 3<<BITRES && itheta!=0)
  1254. sbits += rebalance - (3<<BITRES);
  1255. /* For a stereo split, the high bits of fill are always zero, so no
  1256. folding will be done to the side. */
  1257. cm |= quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
  1258. } else {
  1259. /* For a stereo split, the high bits of fill are always zero, so no
  1260. folding will be done to the side. */
  1261. cm = quant_band(ctx, Y, N, sbits, B, NULL, LM, NULL, side, NULL, fill>>B);
  1262. rebalance = sbits - (rebalance-ctx->remaining_bits);
  1263. if (rebalance > 3<<BITRES && itheta!=16384)
  1264. mbits += rebalance - (3<<BITRES);
  1265. /* In stereo mode, we do not apply a scaling to the mid because we need the normalized
  1266. mid for folding later. */
  1267. cm |= quant_band(ctx, X, N, mbits, B, lowband, LM, lowband_out, Q15ONE,
  1268. lowband_scratch, fill);
  1269. }
  1270. }
  1271. /* This code is used by the decoder and by the resynthesis-enabled encoder */
  1272. if (ctx->resynth)
  1273. {
  1274. if (N!=2)
  1275. stereo_merge(X, Y, mid, N, ctx->arch);
  1276. if (inv)
  1277. {
  1278. int j;
  1279. for (j=0;j<N;j++)
  1280. Y[j] = -Y[j];
  1281. }
  1282. }
  1283. return cm;
  1284. }
  1285. static void special_hybrid_folding(const CELTMode *m, celt_norm *norm, celt_norm *norm2, int start, int M, int dual_stereo)
  1286. {
  1287. int n1, n2;
  1288. const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
  1289. n1 = M*(eBands[start+1]-eBands[start]);
  1290. n2 = M*(eBands[start+2]-eBands[start+1]);
  1291. /* Duplicate enough of the first band folding data to be able to fold the second band.
  1292. Copies no data for CELT-only mode. */
  1293. OPUS_COPY(&norm[n1], &norm[2*n1 - n2], n2-n1);
  1294. if (dual_stereo)
  1295. OPUS_COPY(&norm2[n1], &norm2[2*n1 - n2], n2-n1);
  1296. }
  1297. void quant_all_bands(int encode, const CELTMode *m, int start, int end,
  1298. celt_norm *X_, celt_norm *Y_, unsigned char *collapse_masks,
  1299. const celt_ener *bandE, int *pulses, int shortBlocks, int spread,
  1300. int dual_stereo, int intensity, int *tf_res, opus_int32 total_bits,
  1301. opus_int32 balance, ec_ctx *ec, int LM, int codedBands,
  1302. opus_uint32 *seed, int complexity, int arch, int disable_inv)
  1303. {
  1304. int i;
  1305. opus_int32 remaining_bits;
  1306. const opus_int16 * OPUS_RESTRICT eBands = m->eBands;
  1307. celt_norm * OPUS_RESTRICT norm, * OPUS_RESTRICT norm2;
  1308. VARDECL(celt_norm, _norm);
  1309. VARDECL(celt_norm, _lowband_scratch);
  1310. VARDECL(celt_norm, X_save);
  1311. VARDECL(celt_norm, Y_save);
  1312. VARDECL(celt_norm, X_save2);
  1313. VARDECL(celt_norm, Y_save2);
  1314. VARDECL(celt_norm, norm_save2);
  1315. int resynth_alloc;
  1316. celt_norm *lowband_scratch;
  1317. int B;
  1318. int M;
  1319. int lowband_offset;
  1320. int update_lowband = 1;
  1321. int C = Y_ != NULL ? 2 : 1;
  1322. int norm_offset;
  1323. int theta_rdo = encode && Y_!=NULL && !dual_stereo && complexity>=8;
  1324. #ifdef RESYNTH
  1325. int resynth = 1;
  1326. #else
  1327. int resynth = !encode || theta_rdo;
  1328. #endif
  1329. struct band_ctx ctx;
  1330. SAVE_STACK;
  1331. M = 1<<LM;
  1332. B = shortBlocks ? M : 1;
  1333. norm_offset = M*eBands[start];
  1334. /* No need to allocate norm for the last band because we don't need an
  1335. output in that band. */
  1336. ALLOC(_norm, C*(M*eBands[m->nbEBands-1]-norm_offset), celt_norm);
  1337. norm = _norm;
  1338. norm2 = norm + M*eBands[m->nbEBands-1]-norm_offset;
  1339. /* For decoding, we can use the last band as scratch space because we don't need that
  1340. scratch space for the last band and we don't care about the data there until we're
  1341. decoding the last band. */
  1342. if (encode && resynth)
  1343. resynth_alloc = M*(eBands[m->nbEBands]-eBands[m->nbEBands-1]);
  1344. else
  1345. resynth_alloc = ALLOC_NONE;
  1346. ALLOC(_lowband_scratch, resynth_alloc, celt_norm);
  1347. if (encode && resynth)
  1348. lowband_scratch = _lowband_scratch;
  1349. else
  1350. lowband_scratch = X_+M*eBands[m->nbEBands-1];
  1351. ALLOC(X_save, resynth_alloc, celt_norm);
  1352. ALLOC(Y_save, resynth_alloc, celt_norm);
  1353. ALLOC(X_save2, resynth_alloc, celt_norm);
  1354. ALLOC(Y_save2, resynth_alloc, celt_norm);
  1355. ALLOC(norm_save2, resynth_alloc, celt_norm);
  1356. lowband_offset = 0;
  1357. ctx.bandE = bandE;
  1358. ctx.ec = ec;
  1359. ctx.encode = encode;
  1360. ctx.intensity = intensity;
  1361. ctx.m = m;
  1362. ctx.seed = *seed;
  1363. ctx.spread = spread;
  1364. ctx.arch = arch;
  1365. ctx.disable_inv = disable_inv;
  1366. ctx.resynth = resynth;
  1367. ctx.theta_round = 0;
  1368. /* Avoid injecting noise in the first band on transients. */
  1369. ctx.avoid_split_noise = B > 1;
  1370. for (i=start;i<end;i++)
  1371. {
  1372. opus_int32 tell;
  1373. int b;
  1374. int N;
  1375. opus_int32 curr_balance;
  1376. int effective_lowband=-1;
  1377. celt_norm * OPUS_RESTRICT X, * OPUS_RESTRICT Y;
  1378. int tf_change=0;
  1379. unsigned x_cm;
  1380. unsigned y_cm;
  1381. int last;
  1382. ctx.i = i;
  1383. last = (i==end-1);
  1384. X = X_+M*eBands[i];
  1385. if (Y_!=NULL)
  1386. Y = Y_+M*eBands[i];
  1387. else
  1388. Y = NULL;
  1389. N = M*eBands[i+1]-M*eBands[i];
  1390. celt_assert(N > 0);
  1391. tell = ec_tell_frac(ec);
  1392. /* Compute how many bits we want to allocate to this band */
  1393. if (i != start)
  1394. balance -= tell;
  1395. remaining_bits = total_bits-tell-1;
  1396. ctx.remaining_bits = remaining_bits;
  1397. if (i <= codedBands-1)
  1398. {
  1399. curr_balance = celt_sudiv(balance, IMIN(3, codedBands-i));
  1400. b = IMAX(0, IMIN(16383, IMIN(remaining_bits+1,pulses[i]+curr_balance)));
  1401. } else {
  1402. b = 0;
  1403. }
  1404. #ifndef DISABLE_UPDATE_DRAFT
  1405. if (resynth && (M*eBands[i]-N >= M*eBands[start] || i==start+1) && (update_lowband || lowband_offset==0))
  1406. lowband_offset = i;
  1407. if (i == start+1)
  1408. special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
  1409. #else
  1410. if (resynth && M*eBands[i]-N >= M*eBands[start] && (update_lowband || lowband_offset==0))
  1411. lowband_offset = i;
  1412. #endif
  1413. tf_change = tf_res[i];
  1414. ctx.tf_change = tf_change;
  1415. if (i>=m->effEBands)
  1416. {
  1417. X=norm;
  1418. if (Y_!=NULL)
  1419. Y = norm;
  1420. lowband_scratch = NULL;
  1421. }
  1422. if (last && !theta_rdo)
  1423. lowband_scratch = NULL;
  1424. /* Get a conservative estimate of the collapse_mask's for the bands we're
  1425. going to be folding from. */
  1426. if (lowband_offset != 0 && (spread!=SPREAD_AGGRESSIVE || B>1 || tf_change<0))
  1427. {
  1428. int fold_start;
  1429. int fold_end;
  1430. int fold_i;
  1431. /* This ensures we never repeat spectral content within one band */
  1432. effective_lowband = IMAX(0, M*eBands[lowband_offset]-norm_offset-N);
  1433. fold_start = lowband_offset;
  1434. while(M*eBands[--fold_start] > effective_lowband+norm_offset);
  1435. fold_end = lowband_offset-1;
  1436. #ifndef DISABLE_UPDATE_DRAFT
  1437. while(++fold_end < i && M*eBands[fold_end] < effective_lowband+norm_offset+N);
  1438. #else
  1439. while(M*eBands[++fold_end] < effective_lowband+norm_offset+N);
  1440. #endif
  1441. x_cm = y_cm = 0;
  1442. fold_i = fold_start; do {
  1443. x_cm |= collapse_masks[fold_i*C+0];
  1444. y_cm |= collapse_masks[fold_i*C+C-1];
  1445. } while (++fold_i<fold_end);
  1446. }
  1447. /* Otherwise, we'll be using the LCG to fold, so all blocks will (almost
  1448. always) be non-zero. */
  1449. else
  1450. x_cm = y_cm = (1<<B)-1;
  1451. if (dual_stereo && i==intensity)
  1452. {
  1453. int j;
  1454. /* Switch off dual stereo to do intensity. */
  1455. dual_stereo = 0;
  1456. if (resynth)
  1457. for (j=0;j<M*eBands[i]-norm_offset;j++)
  1458. norm[j] = HALF32(norm[j]+norm2[j]);
  1459. }
  1460. if (dual_stereo)
  1461. {
  1462. x_cm = quant_band(&ctx, X, N, b/2, B,
  1463. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1464. last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm);
  1465. y_cm = quant_band(&ctx, Y, N, b/2, B,
  1466. effective_lowband != -1 ? norm2+effective_lowband : NULL, LM,
  1467. last?NULL:norm2+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, y_cm);
  1468. } else {
  1469. if (Y!=NULL)
  1470. {
  1471. if (theta_rdo && i < intensity)
  1472. {
  1473. ec_ctx ec_save, ec_save2;
  1474. struct band_ctx ctx_save, ctx_save2;
  1475. opus_val32 dist0, dist1;
  1476. unsigned cm, cm2;
  1477. int nstart_bytes, nend_bytes, save_bytes;
  1478. unsigned char *bytes_buf;
  1479. unsigned char bytes_save[1275];
  1480. opus_val16 w[2];
  1481. compute_channel_weights(bandE[i], bandE[i+m->nbEBands], w);
  1482. /* Make a copy. */
  1483. cm = x_cm|y_cm;
  1484. ec_save = *ec;
  1485. ctx_save = ctx;
  1486. OPUS_COPY(X_save, X, N);
  1487. OPUS_COPY(Y_save, Y, N);
  1488. /* Encode and round down. */
  1489. ctx.theta_round = -1;
  1490. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1491. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1492. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
  1493. 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));
  1494. /* Save first result. */
  1495. cm2 = x_cm;
  1496. ec_save2 = *ec;
  1497. ctx_save2 = ctx;
  1498. OPUS_COPY(X_save2, X, N);
  1499. OPUS_COPY(Y_save2, Y, N);
  1500. if (!last)
  1501. OPUS_COPY(norm_save2, norm+M*eBands[i]-norm_offset, N);
  1502. nstart_bytes = ec_save.offs;
  1503. nend_bytes = ec_save.storage;
  1504. bytes_buf = ec_save.buf+nstart_bytes;
  1505. save_bytes = nend_bytes-nstart_bytes;
  1506. OPUS_COPY(bytes_save, bytes_buf, save_bytes);
  1507. /* Restore */
  1508. *ec = ec_save;
  1509. ctx = ctx_save;
  1510. OPUS_COPY(X, X_save, N);
  1511. OPUS_COPY(Y, Y_save, N);
  1512. #ifndef DISABLE_UPDATE_DRAFT
  1513. if (i == start+1)
  1514. special_hybrid_folding(m, norm, norm2, start, M, dual_stereo);
  1515. #endif
  1516. /* Encode and round up. */
  1517. ctx.theta_round = 1;
  1518. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1519. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1520. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, cm);
  1521. 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));
  1522. if (dist0 >= dist1) {
  1523. x_cm = cm2;
  1524. *ec = ec_save2;
  1525. ctx = ctx_save2;
  1526. OPUS_COPY(X, X_save2, N);
  1527. OPUS_COPY(Y, Y_save2, N);
  1528. if (!last)
  1529. OPUS_COPY(norm+M*eBands[i]-norm_offset, norm_save2, N);
  1530. OPUS_COPY(bytes_buf, bytes_save, save_bytes);
  1531. }
  1532. } else {
  1533. ctx.theta_round = 0;
  1534. x_cm = quant_band_stereo(&ctx, X, Y, N, b, B,
  1535. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1536. last?NULL:norm+M*eBands[i]-norm_offset, lowband_scratch, x_cm|y_cm);
  1537. }
  1538. } else {
  1539. x_cm = quant_band(&ctx, X, N, b, B,
  1540. effective_lowband != -1 ? norm+effective_lowband : NULL, LM,
  1541. last?NULL:norm+M*eBands[i]-norm_offset, Q15ONE, lowband_scratch, x_cm|y_cm);
  1542. }
  1543. y_cm = x_cm;
  1544. }
  1545. collapse_masks[i*C+0] = (unsigned char)x_cm;
  1546. collapse_masks[i*C+C-1] = (unsigned char)y_cm;
  1547. balance += pulses[i] + tell;
  1548. /* Update the folding position only as long as we have 1 bit/sample depth. */
  1549. update_lowband = b>(N<<BITRES);
  1550. /* We only need to avoid noise on a split for the first band. After that, we
  1551. have folding. */
  1552. ctx.avoid_split_noise = 0;
  1553. }
  1554. *seed = ctx.seed;
  1555. RESTORE_STACK;
  1556. }