2
0

opus_silk.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882
  1. /*
  2. * Copyright (c) 2012 Andrew D'Addesio
  3. * Copyright (c) 2013-2014 Mozilla Corporation
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Opus SILK decoder
  24. */
  25. #include <stdint.h>
  26. #include "opus.h"
  27. #include "opustab.h"
  28. typedef struct SilkFrame {
  29. int coded;
  30. int log_gain;
  31. int16_t nlsf[16];
  32. float lpc[16];
  33. float output [2 * SILK_HISTORY];
  34. float lpc_history[2 * SILK_HISTORY];
  35. int primarylag;
  36. int prev_voiced;
  37. } SilkFrame;
  38. struct SilkContext {
  39. AVCodecContext *avctx;
  40. int output_channels;
  41. int midonly;
  42. int subframes;
  43. int sflength;
  44. int flength;
  45. int nlsf_interp_factor;
  46. enum OpusBandwidth bandwidth;
  47. int wb;
  48. SilkFrame frame[2];
  49. float prev_stereo_weights[2];
  50. float stereo_weights[2];
  51. int prev_coded_channels;
  52. };
  53. static inline void silk_stabilize_lsf(int16_t nlsf[16], int order, const uint16_t min_delta[17])
  54. {
  55. int pass, i;
  56. for (pass = 0; pass < 20; pass++) {
  57. int k, min_diff = 0;
  58. for (i = 0; i < order+1; i++) {
  59. int low = i != 0 ? nlsf[i-1] : 0;
  60. int high = i != order ? nlsf[i] : 32768;
  61. int diff = (high - low) - (min_delta[i]);
  62. if (diff < min_diff) {
  63. min_diff = diff;
  64. k = i;
  65. if (pass == 20)
  66. break;
  67. }
  68. }
  69. if (min_diff == 0) /* no issues; stabilized */
  70. return;
  71. /* wiggle one or two LSFs */
  72. if (k == 0) {
  73. /* repel away from lower bound */
  74. nlsf[0] = min_delta[0];
  75. } else if (k == order) {
  76. /* repel away from higher bound */
  77. nlsf[order-1] = 32768 - min_delta[order];
  78. } else {
  79. /* repel away from current position */
  80. int min_center = 0, max_center = 32768, center_val;
  81. /* lower extent */
  82. for (i = 0; i < k; i++)
  83. min_center += min_delta[i];
  84. min_center += min_delta[k] >> 1;
  85. /* upper extent */
  86. for (i = order; i > k; i--)
  87. max_center -= min_delta[i];
  88. max_center -= min_delta[k] >> 1;
  89. /* move apart */
  90. center_val = nlsf[k - 1] + nlsf[k];
  91. center_val = (center_val >> 1) + (center_val & 1); // rounded divide by 2
  92. center_val = FFMIN(max_center, FFMAX(min_center, center_val));
  93. nlsf[k - 1] = center_val - (min_delta[k] >> 1);
  94. nlsf[k] = nlsf[k - 1] + min_delta[k];
  95. }
  96. }
  97. /* resort to the fall-back method, the standard method for LSF stabilization */
  98. /* sort; as the LSFs should be nearly sorted, use insertion sort */
  99. for (i = 1; i < order; i++) {
  100. int j, value = nlsf[i];
  101. for (j = i - 1; j >= 0 && nlsf[j] > value; j--)
  102. nlsf[j + 1] = nlsf[j];
  103. nlsf[j + 1] = value;
  104. }
  105. /* push forwards to increase distance */
  106. if (nlsf[0] < min_delta[0])
  107. nlsf[0] = min_delta[0];
  108. for (i = 1; i < order; i++)
  109. nlsf[i] = FFMAX(nlsf[i], FFMIN(nlsf[i - 1] + min_delta[i], 32767));
  110. /* push backwards to increase distance */
  111. if (nlsf[order-1] > 32768 - min_delta[order])
  112. nlsf[order-1] = 32768 - min_delta[order];
  113. for (i = order-2; i >= 0; i--)
  114. if (nlsf[i] > nlsf[i + 1] - min_delta[i+1])
  115. nlsf[i] = nlsf[i + 1] - min_delta[i+1];
  116. return;
  117. }
  118. static inline int silk_is_lpc_stable(const int16_t lpc[16], int order)
  119. {
  120. int k, j, DC_resp = 0;
  121. int32_t lpc32[2][16]; // Q24
  122. int totalinvgain = 1 << 30; // 1.0 in Q30
  123. int32_t *row = lpc32[0], *prevrow;
  124. /* initialize the first row for the Levinson recursion */
  125. for (k = 0; k < order; k++) {
  126. DC_resp += lpc[k];
  127. row[k] = lpc[k] * 4096;
  128. }
  129. if (DC_resp >= 4096)
  130. return 0;
  131. /* check if prediction gain pushes any coefficients too far */
  132. for (k = order - 1; 1; k--) {
  133. int rc; // Q31; reflection coefficient
  134. int gaindiv; // Q30; inverse of the gain (the divisor)
  135. int gain; // gain for this reflection coefficient
  136. int fbits; // fractional bits used for the gain
  137. int error; // Q29; estimate of the error of our partial estimate of 1/gaindiv
  138. if (FFABS(row[k]) > 16773022)
  139. return 0;
  140. rc = -(row[k] * 128);
  141. gaindiv = (1 << 30) - MULH(rc, rc);
  142. totalinvgain = MULH(totalinvgain, gaindiv) << 2;
  143. if (k == 0)
  144. return (totalinvgain >= 107374);
  145. /* approximate 1.0/gaindiv */
  146. fbits = opus_ilog(gaindiv);
  147. gain = ((1 << 29) - 1) / (gaindiv >> (fbits + 1 - 16)); // Q<fbits-16>
  148. error = (1 << 29) - MULL(gaindiv << (15 + 16 - fbits), gain, 16);
  149. gain = ((gain << 16) + (error * gain >> 13));
  150. /* switch to the next row of the LPC coefficients */
  151. prevrow = row;
  152. row = lpc32[k & 1];
  153. for (j = 0; j < k; j++) {
  154. int x = av_sat_sub32(prevrow[j], ROUND_MULL(prevrow[k - j - 1], rc, 31));
  155. int64_t tmp = ROUND_MULL(x, gain, fbits);
  156. /* per RFC 8251 section 6, if this calculation overflows, the filter
  157. is considered unstable. */
  158. if (tmp < INT32_MIN || tmp > INT32_MAX)
  159. return 0;
  160. row[j] = (int32_t)tmp;
  161. }
  162. }
  163. }
  164. static void silk_lsp2poly(const int32_t lsp[16], int32_t pol[16], int half_order)
  165. {
  166. int i, j;
  167. pol[0] = 65536; // 1.0 in Q16
  168. pol[1] = -lsp[0];
  169. for (i = 1; i < half_order; i++) {
  170. pol[i + 1] = pol[i - 1] * 2 - ROUND_MULL(lsp[2 * i], pol[i], 16);
  171. for (j = i; j > 1; j--)
  172. pol[j] += pol[j - 2] - ROUND_MULL(lsp[2 * i], pol[j - 1], 16);
  173. pol[1] -= lsp[2 * i];
  174. }
  175. }
  176. static void silk_lsf2lpc(const int16_t nlsf[16], float lpcf[16], int order)
  177. {
  178. int i, k;
  179. int32_t lsp[16]; // Q17; 2*cos(LSF)
  180. int32_t p[9], q[9]; // Q16
  181. int32_t lpc32[16]; // Q17
  182. int16_t lpc[16]; // Q12
  183. /* convert the LSFs to LSPs, i.e. 2*cos(LSF) */
  184. for (k = 0; k < order; k++) {
  185. int index = nlsf[k] >> 8;
  186. int offset = nlsf[k] & 255;
  187. int k2 = (order == 10) ? ff_silk_lsf_ordering_nbmb[k] : ff_silk_lsf_ordering_wb[k];
  188. /* interpolate and round */
  189. lsp[k2] = ff_silk_cosine[index] * 256;
  190. lsp[k2] += (ff_silk_cosine[index + 1] - ff_silk_cosine[index]) * offset;
  191. lsp[k2] = (lsp[k2] + 4) >> 3;
  192. }
  193. silk_lsp2poly(lsp , p, order >> 1);
  194. silk_lsp2poly(lsp + 1, q, order >> 1);
  195. /* reconstruct A(z) */
  196. for (k = 0; k < order>>1; k++) {
  197. int32_t p_tmp = p[k + 1] + p[k];
  198. int32_t q_tmp = q[k + 1] - q[k];
  199. lpc32[k] = -q_tmp - p_tmp;
  200. lpc32[order-k-1] = q_tmp - p_tmp;
  201. }
  202. /* limit the range of the LPC coefficients to each fit within an int16_t */
  203. for (i = 0; i < 10; i++) {
  204. int j;
  205. unsigned int maxabs = 0;
  206. for (j = 0, k = 0; j < order; j++) {
  207. unsigned int x = FFABS(lpc32[k]);
  208. if (x > maxabs) {
  209. maxabs = x; // Q17
  210. k = j;
  211. }
  212. }
  213. maxabs = (maxabs + 16) >> 5; // convert to Q12
  214. if (maxabs > 32767) {
  215. /* perform bandwidth expansion */
  216. unsigned int chirp, chirp_base; // Q16
  217. maxabs = FFMIN(maxabs, 163838); // anything above this overflows chirp's numerator
  218. chirp_base = chirp = 65470 - ((maxabs - 32767) << 14) / ((maxabs * (k+1)) >> 2);
  219. for (k = 0; k < order; k++) {
  220. lpc32[k] = ROUND_MULL(lpc32[k], chirp, 16);
  221. chirp = (chirp_base * chirp + 32768) >> 16;
  222. }
  223. } else break;
  224. }
  225. if (i == 10) {
  226. /* time's up: just clamp */
  227. for (k = 0; k < order; k++) {
  228. int x = (lpc32[k] + 16) >> 5;
  229. lpc[k] = av_clip_int16(x);
  230. lpc32[k] = lpc[k] << 5; // shortcut mandated by the spec; drops lower 5 bits
  231. }
  232. } else {
  233. for (k = 0; k < order; k++)
  234. lpc[k] = (lpc32[k] + 16) >> 5;
  235. }
  236. /* if the prediction gain causes the LPC filter to become unstable,
  237. apply further bandwidth expansion on the Q17 coefficients */
  238. for (i = 1; i <= 16 && !silk_is_lpc_stable(lpc, order); i++) {
  239. unsigned int chirp, chirp_base;
  240. chirp_base = chirp = 65536 - (1 << i);
  241. for (k = 0; k < order; k++) {
  242. lpc32[k] = ROUND_MULL(lpc32[k], chirp, 16);
  243. lpc[k] = (lpc32[k] + 16) >> 5;
  244. chirp = (chirp_base * chirp + 32768) >> 16;
  245. }
  246. }
  247. for (i = 0; i < order; i++)
  248. lpcf[i] = lpc[i] / 4096.0f;
  249. }
  250. static inline void silk_decode_lpc(SilkContext *s, SilkFrame *frame,
  251. OpusRangeCoder *rc,
  252. float lpc_leadin[16], float lpc[16],
  253. int *lpc_order, int *has_lpc_leadin, int voiced)
  254. {
  255. int i;
  256. int order; // order of the LP polynomial; 10 for NB/MB and 16 for WB
  257. int8_t lsf_i1, lsf_i2[16]; // stage-1 and stage-2 codebook indices
  258. int16_t lsf_res[16]; // residual as a Q10 value
  259. int16_t nlsf[16]; // Q15
  260. *lpc_order = order = s->wb ? 16 : 10;
  261. /* obtain LSF stage-1 and stage-2 indices */
  262. lsf_i1 = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s1[s->wb][voiced]);
  263. for (i = 0; i < order; i++) {
  264. int index = s->wb ? ff_silk_lsf_s2_model_sel_wb [lsf_i1][i] :
  265. ff_silk_lsf_s2_model_sel_nbmb[lsf_i1][i];
  266. lsf_i2[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2[index]) - 4;
  267. if (lsf_i2[i] == -4)
  268. lsf_i2[i] -= ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2_ext);
  269. else if (lsf_i2[i] == 4)
  270. lsf_i2[i] += ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_s2_ext);
  271. }
  272. /* reverse the backwards-prediction step */
  273. for (i = order - 1; i >= 0; i--) {
  274. int qstep = s->wb ? 9830 : 11796;
  275. lsf_res[i] = lsf_i2[i] * 1024;
  276. if (lsf_i2[i] < 0) lsf_res[i] += 102;
  277. else if (lsf_i2[i] > 0) lsf_res[i] -= 102;
  278. lsf_res[i] = (lsf_res[i] * qstep) >> 16;
  279. if (i + 1 < order) {
  280. int weight = s->wb ? ff_silk_lsf_pred_weights_wb [ff_silk_lsf_weight_sel_wb [lsf_i1][i]][i] :
  281. ff_silk_lsf_pred_weights_nbmb[ff_silk_lsf_weight_sel_nbmb[lsf_i1][i]][i];
  282. lsf_res[i] += (lsf_res[i+1] * weight) >> 8;
  283. }
  284. }
  285. /* reconstruct the NLSF coefficients from the supplied indices */
  286. for (i = 0; i < order; i++) {
  287. const uint8_t * codebook = s->wb ? ff_silk_lsf_codebook_wb [lsf_i1] :
  288. ff_silk_lsf_codebook_nbmb[lsf_i1];
  289. int cur, prev, next, weight_sq, weight, ipart, fpart, y, value;
  290. /* find the weight of the residual */
  291. /* TODO: precompute */
  292. cur = codebook[i];
  293. prev = i ? codebook[i - 1] : 0;
  294. next = i + 1 < order ? codebook[i + 1] : 256;
  295. weight_sq = (1024 / (cur - prev) + 1024 / (next - cur)) << 16;
  296. /* approximate square-root with mandated fixed-point arithmetic */
  297. ipart = opus_ilog(weight_sq);
  298. fpart = (weight_sq >> (ipart-8)) & 127;
  299. y = ((ipart & 1) ? 32768 : 46214) >> ((32 - ipart)>>1);
  300. weight = y + ((213 * fpart * y) >> 16);
  301. value = cur * 128 + (lsf_res[i] * 16384) / weight;
  302. nlsf[i] = av_clip_uintp2(value, 15);
  303. }
  304. /* stabilize the NLSF coefficients */
  305. silk_stabilize_lsf(nlsf, order, s->wb ? ff_silk_lsf_min_spacing_wb :
  306. ff_silk_lsf_min_spacing_nbmb);
  307. /* produce an interpolation for the first 2 subframes, */
  308. /* and then convert both sets of NLSFs to LPC coefficients */
  309. *has_lpc_leadin = 0;
  310. if (s->subframes == 4) {
  311. int offset = ff_opus_rc_dec_cdf(rc, ff_silk_model_lsf_interpolation_offset);
  312. if (offset != 4 && frame->coded) {
  313. *has_lpc_leadin = 1;
  314. if (offset != 0) {
  315. int16_t nlsf_leadin[16];
  316. for (i = 0; i < order; i++)
  317. nlsf_leadin[i] = frame->nlsf[i] +
  318. ((nlsf[i] - frame->nlsf[i]) * offset >> 2);
  319. silk_lsf2lpc(nlsf_leadin, lpc_leadin, order);
  320. } else /* avoid re-computation for a (roughly) 1-in-4 occurrence */
  321. memcpy(lpc_leadin, frame->lpc, 16 * sizeof(float));
  322. } else
  323. offset = 4;
  324. s->nlsf_interp_factor = offset;
  325. silk_lsf2lpc(nlsf, lpc, order);
  326. } else {
  327. s->nlsf_interp_factor = 4;
  328. silk_lsf2lpc(nlsf, lpc, order);
  329. }
  330. memcpy(frame->nlsf, nlsf, order * sizeof(nlsf[0]));
  331. memcpy(frame->lpc, lpc, order * sizeof(lpc[0]));
  332. }
  333. static inline void silk_count_children(OpusRangeCoder *rc, int model, int32_t total,
  334. int32_t child[2])
  335. {
  336. if (total != 0) {
  337. child[0] = ff_opus_rc_dec_cdf(rc,
  338. ff_silk_model_pulse_location[model] + (((total - 1 + 5) * (total - 1)) >> 1));
  339. child[1] = total - child[0];
  340. } else {
  341. child[0] = 0;
  342. child[1] = 0;
  343. }
  344. }
  345. static inline void silk_decode_excitation(SilkContext *s, OpusRangeCoder *rc,
  346. float* excitationf,
  347. int qoffset_high, int active, int voiced)
  348. {
  349. int i;
  350. uint32_t seed;
  351. int shellblocks;
  352. int ratelevel;
  353. uint8_t pulsecount[20]; // total pulses in each shell block
  354. uint8_t lsbcount[20] = {0}; // raw lsbits defined for each pulse in each shell block
  355. int32_t excitation[320]; // Q23
  356. /* excitation parameters */
  357. seed = ff_opus_rc_dec_cdf(rc, ff_silk_model_lcg_seed);
  358. shellblocks = ff_silk_shell_blocks[s->bandwidth][s->subframes >> 2];
  359. ratelevel = ff_opus_rc_dec_cdf(rc, ff_silk_model_exc_rate[voiced]);
  360. for (i = 0; i < shellblocks; i++) {
  361. pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[ratelevel]);
  362. if (pulsecount[i] == 17) {
  363. while (pulsecount[i] == 17 && ++lsbcount[i] != 10)
  364. pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[9]);
  365. if (lsbcount[i] == 10)
  366. pulsecount[i] = ff_opus_rc_dec_cdf(rc, ff_silk_model_pulse_count[10]);
  367. }
  368. }
  369. /* decode pulse locations using PVQ */
  370. for (i = 0; i < shellblocks; i++) {
  371. if (pulsecount[i] != 0) {
  372. int a, b, c, d;
  373. int32_t * location = excitation + 16*i;
  374. int32_t branch[4][2];
  375. branch[0][0] = pulsecount[i];
  376. /* unrolled tail recursion */
  377. for (a = 0; a < 1; a++) {
  378. silk_count_children(rc, 0, branch[0][a], branch[1]);
  379. for (b = 0; b < 2; b++) {
  380. silk_count_children(rc, 1, branch[1][b], branch[2]);
  381. for (c = 0; c < 2; c++) {
  382. silk_count_children(rc, 2, branch[2][c], branch[3]);
  383. for (d = 0; d < 2; d++) {
  384. silk_count_children(rc, 3, branch[3][d], location);
  385. location += 2;
  386. }
  387. }
  388. }
  389. }
  390. } else
  391. memset(excitation + 16*i, 0, 16*sizeof(int32_t));
  392. }
  393. /* decode least significant bits */
  394. for (i = 0; i < shellblocks << 4; i++) {
  395. int bit;
  396. for (bit = 0; bit < lsbcount[i >> 4]; bit++)
  397. excitation[i] = (excitation[i] << 1) |
  398. ff_opus_rc_dec_cdf(rc, ff_silk_model_excitation_lsb);
  399. }
  400. /* decode signs */
  401. for (i = 0; i < shellblocks << 4; i++) {
  402. if (excitation[i] != 0) {
  403. int sign = ff_opus_rc_dec_cdf(rc, ff_silk_model_excitation_sign[active +
  404. voiced][qoffset_high][FFMIN(pulsecount[i >> 4], 6)]);
  405. if (sign == 0)
  406. excitation[i] *= -1;
  407. }
  408. }
  409. /* assemble the excitation */
  410. for (i = 0; i < shellblocks << 4; i++) {
  411. int value = excitation[i];
  412. excitation[i] = value * 256 | ff_silk_quant_offset[voiced][qoffset_high];
  413. if (value < 0) excitation[i] += 20;
  414. else if (value > 0) excitation[i] -= 20;
  415. /* invert samples pseudorandomly */
  416. seed = 196314165 * seed + 907633515;
  417. if (seed & 0x80000000)
  418. excitation[i] *= -1;
  419. seed += value;
  420. excitationf[i] = excitation[i] / 8388608.0f;
  421. }
  422. }
  423. /** Maximum residual history according to 4.2.7.6.1 */
  424. #define SILK_MAX_LAG (288 + LTP_ORDER / 2)
  425. /** Order of the LTP filter */
  426. #define LTP_ORDER 5
  427. static void silk_decode_frame(SilkContext *s, OpusRangeCoder *rc,
  428. int frame_num, int channel, int coded_channels, int active, int active1)
  429. {
  430. /* per frame */
  431. int voiced; // combines with active to indicate inactive, active, or active+voiced
  432. int qoffset_high;
  433. int order; // order of the LPC coefficients
  434. float lpc_leadin[16], lpc_body[16], residual[SILK_MAX_LAG + SILK_HISTORY];
  435. int has_lpc_leadin;
  436. float ltpscale;
  437. /* per subframe */
  438. struct {
  439. float gain;
  440. int pitchlag;
  441. float ltptaps[5];
  442. } sf[4];
  443. SilkFrame * const frame = s->frame + channel;
  444. int i;
  445. /* obtain stereo weights */
  446. if (coded_channels == 2 && channel == 0) {
  447. int n, wi[2], ws[2], w[2];
  448. n = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s1);
  449. wi[0] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s2) + 3 * (n / 5);
  450. ws[0] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s3);
  451. wi[1] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s2) + 3 * (n % 5);
  452. ws[1] = ff_opus_rc_dec_cdf(rc, ff_silk_model_stereo_s3);
  453. for (i = 0; i < 2; i++)
  454. w[i] = ff_silk_stereo_weights[wi[i]] +
  455. (((ff_silk_stereo_weights[wi[i] + 1] - ff_silk_stereo_weights[wi[i]]) * 6554) >> 16)
  456. * (ws[i]*2 + 1);
  457. s->stereo_weights[0] = (w[0] - w[1]) / 8192.0;
  458. s->stereo_weights[1] = w[1] / 8192.0;
  459. /* and read the mid-only flag */
  460. s->midonly = active1 ? 0 : ff_opus_rc_dec_cdf(rc, ff_silk_model_mid_only);
  461. }
  462. /* obtain frame type */
  463. if (!active) {
  464. qoffset_high = ff_opus_rc_dec_cdf(rc, ff_silk_model_frame_type_inactive);
  465. voiced = 0;
  466. } else {
  467. int type = ff_opus_rc_dec_cdf(rc, ff_silk_model_frame_type_active);
  468. qoffset_high = type & 1;
  469. voiced = type >> 1;
  470. }
  471. /* obtain subframe quantization gains */
  472. for (i = 0; i < s->subframes; i++) {
  473. int log_gain; //Q7
  474. int ipart, fpart, lingain;
  475. if (i == 0 && (frame_num == 0 || !frame->coded)) {
  476. /* gain is coded absolute */
  477. int x = ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_highbits[active + voiced]);
  478. log_gain = (x<<3) | ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_lowbits);
  479. if (frame->coded)
  480. log_gain = FFMAX(log_gain, frame->log_gain - 16);
  481. } else {
  482. /* gain is coded relative */
  483. int delta_gain = ff_opus_rc_dec_cdf(rc, ff_silk_model_gain_delta);
  484. log_gain = av_clip_uintp2(FFMAX((delta_gain<<1) - 16,
  485. frame->log_gain + delta_gain - 4), 6);
  486. }
  487. frame->log_gain = log_gain;
  488. /* approximate 2**(x/128) with a Q7 (i.e. non-integer) input */
  489. log_gain = (log_gain * 0x1D1C71 >> 16) + 2090;
  490. ipart = log_gain >> 7;
  491. fpart = log_gain & 127;
  492. lingain = (1 << ipart) + ((-174 * fpart * (128-fpart) >>16) + fpart) * ((1<<ipart) >> 7);
  493. sf[i].gain = lingain / 65536.0f;
  494. }
  495. /* obtain LPC filter coefficients */
  496. silk_decode_lpc(s, frame, rc, lpc_leadin, lpc_body, &order, &has_lpc_leadin, voiced);
  497. /* obtain pitch lags, if this is a voiced frame */
  498. if (voiced) {
  499. int lag_absolute = (!frame_num || !frame->prev_voiced);
  500. int primarylag; // primary pitch lag for the entire SILK frame
  501. int ltpfilter;
  502. const int8_t * offsets;
  503. if (!lag_absolute) {
  504. int delta = ff_opus_rc_dec_cdf(rc, ff_silk_model_pitch_delta);
  505. if (delta)
  506. primarylag = frame->primarylag + delta - 9;
  507. else
  508. lag_absolute = 1;
  509. }
  510. if (lag_absolute) {
  511. /* primary lag is coded absolute */
  512. int highbits, lowbits;
  513. static const uint16_t * const model[] = {
  514. ff_silk_model_pitch_lowbits_nb, ff_silk_model_pitch_lowbits_mb,
  515. ff_silk_model_pitch_lowbits_wb
  516. };
  517. highbits = ff_opus_rc_dec_cdf(rc, ff_silk_model_pitch_highbits);
  518. lowbits = ff_opus_rc_dec_cdf(rc, model[s->bandwidth]);
  519. primarylag = ff_silk_pitch_min_lag[s->bandwidth] +
  520. highbits*ff_silk_pitch_scale[s->bandwidth] + lowbits;
  521. }
  522. frame->primarylag = primarylag;
  523. if (s->subframes == 2)
  524. offsets = (s->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
  525. ? ff_silk_pitch_offset_nb10ms[ff_opus_rc_dec_cdf(rc,
  526. ff_silk_model_pitch_contour_nb10ms)]
  527. : ff_silk_pitch_offset_mbwb10ms[ff_opus_rc_dec_cdf(rc,
  528. ff_silk_model_pitch_contour_mbwb10ms)];
  529. else
  530. offsets = (s->bandwidth == OPUS_BANDWIDTH_NARROWBAND)
  531. ? ff_silk_pitch_offset_nb20ms[ff_opus_rc_dec_cdf(rc,
  532. ff_silk_model_pitch_contour_nb20ms)]
  533. : ff_silk_pitch_offset_mbwb20ms[ff_opus_rc_dec_cdf(rc,
  534. ff_silk_model_pitch_contour_mbwb20ms)];
  535. for (i = 0; i < s->subframes; i++)
  536. sf[i].pitchlag = av_clip(primarylag + offsets[i],
  537. ff_silk_pitch_min_lag[s->bandwidth],
  538. ff_silk_pitch_max_lag[s->bandwidth]);
  539. /* obtain LTP filter coefficients */
  540. ltpfilter = ff_opus_rc_dec_cdf(rc, ff_silk_model_ltp_filter);
  541. for (i = 0; i < s->subframes; i++) {
  542. int index, j;
  543. static const uint16_t * const filter_sel[] = {
  544. ff_silk_model_ltp_filter0_sel, ff_silk_model_ltp_filter1_sel,
  545. ff_silk_model_ltp_filter2_sel
  546. };
  547. static const int8_t (* const filter_taps[])[5] = {
  548. ff_silk_ltp_filter0_taps, ff_silk_ltp_filter1_taps, ff_silk_ltp_filter2_taps
  549. };
  550. index = ff_opus_rc_dec_cdf(rc, filter_sel[ltpfilter]);
  551. for (j = 0; j < 5; j++)
  552. sf[i].ltptaps[j] = filter_taps[ltpfilter][index][j] / 128.0f;
  553. }
  554. }
  555. /* obtain LTP scale factor */
  556. if (voiced && frame_num == 0)
  557. ltpscale = ff_silk_ltp_scale_factor[ff_opus_rc_dec_cdf(rc,
  558. ff_silk_model_ltp_scale_index)] / 16384.0f;
  559. else ltpscale = 15565.0f/16384.0f;
  560. /* generate the excitation signal for the entire frame */
  561. silk_decode_excitation(s, rc, residual + SILK_MAX_LAG, qoffset_high,
  562. active, voiced);
  563. /* skip synthesising the side channel if we want mono-only */
  564. if (s->output_channels == channel)
  565. return;
  566. /* generate the output signal */
  567. for (i = 0; i < s->subframes; i++) {
  568. const float * lpc_coeff = (i < 2 && has_lpc_leadin) ? lpc_leadin : lpc_body;
  569. float *dst = frame->output + SILK_HISTORY + i * s->sflength;
  570. float *resptr = residual + SILK_MAX_LAG + i * s->sflength;
  571. float *lpc = frame->lpc_history + SILK_HISTORY + i * s->sflength;
  572. float sum;
  573. int j, k;
  574. if (voiced) {
  575. int out_end;
  576. float scale;
  577. if (i < 2 || s->nlsf_interp_factor == 4) {
  578. out_end = -i * s->sflength;
  579. scale = ltpscale;
  580. } else {
  581. out_end = -(i - 2) * s->sflength;
  582. scale = 1.0f;
  583. }
  584. /* when the LPC coefficients change, a re-whitening filter is used */
  585. /* to produce a residual that accounts for the change */
  586. for (j = - sf[i].pitchlag - LTP_ORDER/2; j < out_end; j++) {
  587. sum = dst[j];
  588. for (k = 0; k < order; k++)
  589. sum -= lpc_coeff[k] * dst[j - k - 1];
  590. resptr[j] = av_clipf(sum, -1.0f, 1.0f) * scale / sf[i].gain;
  591. }
  592. if (out_end) {
  593. float rescale = sf[i-1].gain / sf[i].gain;
  594. for (j = out_end; j < 0; j++)
  595. resptr[j] *= rescale;
  596. }
  597. /* LTP synthesis */
  598. for (j = 0; j < s->sflength; j++) {
  599. sum = resptr[j];
  600. for (k = 0; k < LTP_ORDER; k++)
  601. sum += sf[i].ltptaps[k] * resptr[j - sf[i].pitchlag + LTP_ORDER/2 - k];
  602. resptr[j] = sum;
  603. }
  604. }
  605. /* LPC synthesis */
  606. for (j = 0; j < s->sflength; j++) {
  607. sum = resptr[j] * sf[i].gain;
  608. for (k = 1; k <= order; k++)
  609. sum += lpc_coeff[k - 1] * lpc[j - k];
  610. lpc[j] = sum;
  611. dst[j] = av_clipf(sum, -1.0f, 1.0f);
  612. }
  613. }
  614. frame->prev_voiced = voiced;
  615. memmove(frame->lpc_history, frame->lpc_history + s->flength, SILK_HISTORY * sizeof(float));
  616. memmove(frame->output, frame->output + s->flength, SILK_HISTORY * sizeof(float));
  617. frame->coded = 1;
  618. }
  619. static void silk_unmix_ms(SilkContext *s, float *l, float *r)
  620. {
  621. float *mid = s->frame[0].output + SILK_HISTORY - s->flength;
  622. float *side = s->frame[1].output + SILK_HISTORY - s->flength;
  623. float w0_prev = s->prev_stereo_weights[0];
  624. float w1_prev = s->prev_stereo_weights[1];
  625. float w0 = s->stereo_weights[0];
  626. float w1 = s->stereo_weights[1];
  627. int n1 = ff_silk_stereo_interp_len[s->bandwidth];
  628. int i;
  629. for (i = 0; i < n1; i++) {
  630. float interp0 = w0_prev + i * (w0 - w0_prev) / n1;
  631. float interp1 = w1_prev + i * (w1 - w1_prev) / n1;
  632. float p0 = 0.25 * (mid[i - 2] + 2 * mid[i - 1] + mid[i]);
  633. l[i] = av_clipf((1 + interp1) * mid[i - 1] + side[i - 1] + interp0 * p0, -1.0, 1.0);
  634. r[i] = av_clipf((1 - interp1) * mid[i - 1] - side[i - 1] - interp0 * p0, -1.0, 1.0);
  635. }
  636. for (; i < s->flength; i++) {
  637. float p0 = 0.25 * (mid[i - 2] + 2 * mid[i - 1] + mid[i]);
  638. l[i] = av_clipf((1 + w1) * mid[i - 1] + side[i - 1] + w0 * p0, -1.0, 1.0);
  639. r[i] = av_clipf((1 - w1) * mid[i - 1] - side[i - 1] - w0 * p0, -1.0, 1.0);
  640. }
  641. memcpy(s->prev_stereo_weights, s->stereo_weights, sizeof(s->stereo_weights));
  642. }
  643. static void silk_flush_frame(SilkFrame *frame)
  644. {
  645. if (!frame->coded)
  646. return;
  647. memset(frame->output, 0, sizeof(frame->output));
  648. memset(frame->lpc_history, 0, sizeof(frame->lpc_history));
  649. memset(frame->lpc, 0, sizeof(frame->lpc));
  650. memset(frame->nlsf, 0, sizeof(frame->nlsf));
  651. frame->log_gain = 0;
  652. frame->primarylag = 0;
  653. frame->prev_voiced = 0;
  654. frame->coded = 0;
  655. }
  656. int ff_silk_decode_superframe(SilkContext *s, OpusRangeCoder *rc,
  657. float *output[2],
  658. enum OpusBandwidth bandwidth,
  659. int coded_channels,
  660. int duration_ms)
  661. {
  662. int active[2][6], redundancy[2];
  663. int nb_frames, i, j;
  664. if (bandwidth > OPUS_BANDWIDTH_WIDEBAND ||
  665. coded_channels > 2 || duration_ms > 60) {
  666. av_log(s->avctx, AV_LOG_ERROR, "Invalid parameters passed "
  667. "to the SILK decoder.\n");
  668. return AVERROR(EINVAL);
  669. }
  670. nb_frames = 1 + (duration_ms > 20) + (duration_ms > 40);
  671. s->subframes = duration_ms / nb_frames / 5; // 5ms subframes
  672. s->sflength = 20 * (bandwidth + 2);
  673. s->flength = s->sflength * s->subframes;
  674. s->bandwidth = bandwidth;
  675. s->wb = bandwidth == OPUS_BANDWIDTH_WIDEBAND;
  676. /* make sure to flush the side channel when switching from mono to stereo */
  677. if (coded_channels > s->prev_coded_channels)
  678. silk_flush_frame(&s->frame[1]);
  679. s->prev_coded_channels = coded_channels;
  680. /* read the LP-layer header bits */
  681. for (i = 0; i < coded_channels; i++) {
  682. for (j = 0; j < nb_frames; j++)
  683. active[i][j] = ff_opus_rc_dec_log(rc, 1);
  684. redundancy[i] = ff_opus_rc_dec_log(rc, 1);
  685. if (redundancy[i]) {
  686. avpriv_report_missing_feature(s->avctx, "LBRR frames");
  687. return AVERROR_PATCHWELCOME;
  688. }
  689. }
  690. for (i = 0; i < nb_frames; i++) {
  691. for (j = 0; j < coded_channels && !s->midonly; j++)
  692. silk_decode_frame(s, rc, i, j, coded_channels, active[j][i], active[1][i]);
  693. /* reset the side channel if it is not coded */
  694. if (s->midonly && s->frame[1].coded)
  695. silk_flush_frame(&s->frame[1]);
  696. if (coded_channels == 1 || s->output_channels == 1) {
  697. for (j = 0; j < s->output_channels; j++) {
  698. memcpy(output[j] + i * s->flength,
  699. s->frame[0].output + SILK_HISTORY - s->flength - 2,
  700. s->flength * sizeof(float));
  701. }
  702. } else {
  703. silk_unmix_ms(s, output[0] + i * s->flength, output[1] + i * s->flength);
  704. }
  705. s->midonly = 0;
  706. }
  707. return nb_frames * s->flength;
  708. }
  709. void ff_silk_free(SilkContext **ps)
  710. {
  711. av_freep(ps);
  712. }
  713. void ff_silk_flush(SilkContext *s)
  714. {
  715. silk_flush_frame(&s->frame[0]);
  716. silk_flush_frame(&s->frame[1]);
  717. memset(s->prev_stereo_weights, 0, sizeof(s->prev_stereo_weights));
  718. }
  719. int ff_silk_init(AVCodecContext *avctx, SilkContext **ps, int output_channels)
  720. {
  721. SilkContext *s;
  722. if (output_channels != 1 && output_channels != 2) {
  723. av_log(avctx, AV_LOG_ERROR, "Invalid number of output channels: %d\n",
  724. output_channels);
  725. return AVERROR(EINVAL);
  726. }
  727. s = av_mallocz(sizeof(*s));
  728. if (!s)
  729. return AVERROR(ENOMEM);
  730. s->avctx = avctx;
  731. s->output_channels = output_channels;
  732. ff_silk_flush(s);
  733. *ps = s;
  734. return 0;
  735. }