sonic.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. /*
  2. * Simple free lossless/lossy audio codec
  3. * Copyright (c) 2004 Alex Beregszaszi
  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. #include "avcodec.h"
  22. #include "bitstream.h"
  23. #include "golomb.h"
  24. /**
  25. * @file libavcodec/sonic.c
  26. * Simple free lossless/lossy audio codec
  27. * Based on Paul Francis Harrison's Bonk (http://www.logarithmic.net/pfh/bonk)
  28. * Written and designed by Alex Beregszaszi
  29. *
  30. * TODO:
  31. * - CABAC put/get_symbol
  32. * - independent quantizer for channels
  33. * - >2 channels support
  34. * - more decorrelation types
  35. * - more tap_quant tests
  36. * - selectable intlist writers/readers (bonk-style, golomb, cabac)
  37. */
  38. #define MAX_CHANNELS 2
  39. #define MID_SIDE 0
  40. #define LEFT_SIDE 1
  41. #define RIGHT_SIDE 2
  42. typedef struct SonicContext {
  43. int lossless, decorrelation;
  44. int num_taps, downsampling;
  45. double quantization;
  46. int channels, samplerate, block_align, frame_size;
  47. int *tap_quant;
  48. int *int_samples;
  49. int *coded_samples[MAX_CHANNELS];
  50. // for encoding
  51. int *tail;
  52. int tail_size;
  53. int *window;
  54. int window_size;
  55. // for decoding
  56. int *predictor_k;
  57. int *predictor_state[MAX_CHANNELS];
  58. } SonicContext;
  59. #define LATTICE_SHIFT 10
  60. #define SAMPLE_SHIFT 4
  61. #define LATTICE_FACTOR (1 << LATTICE_SHIFT)
  62. #define SAMPLE_FACTOR (1 << SAMPLE_SHIFT)
  63. #define BASE_QUANT 0.6
  64. #define RATE_VARIATION 3.0
  65. static inline int divide(int a, int b)
  66. {
  67. if (a < 0)
  68. return -( (-a + b/2)/b );
  69. else
  70. return (a + b/2)/b;
  71. }
  72. static inline int shift(int a,int b)
  73. {
  74. return (a+(1<<(b-1))) >> b;
  75. }
  76. static inline int shift_down(int a,int b)
  77. {
  78. return (a>>b)+((a<0)?1:0);
  79. }
  80. #if 1
  81. static inline int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
  82. {
  83. int i;
  84. for (i = 0; i < entries; i++)
  85. set_se_golomb(pb, buf[i]);
  86. return 1;
  87. }
  88. static inline int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
  89. {
  90. int i;
  91. for (i = 0; i < entries; i++)
  92. buf[i] = get_se_golomb(gb);
  93. return 1;
  94. }
  95. #else
  96. #define ADAPT_LEVEL 8
  97. static int bits_to_store(uint64_t x)
  98. {
  99. int res = 0;
  100. while(x)
  101. {
  102. res++;
  103. x >>= 1;
  104. }
  105. return res;
  106. }
  107. static void write_uint_max(PutBitContext *pb, unsigned int value, unsigned int max)
  108. {
  109. int i, bits;
  110. if (!max)
  111. return;
  112. bits = bits_to_store(max);
  113. for (i = 0; i < bits-1; i++)
  114. put_bits(pb, 1, value & (1 << i));
  115. if ( (value | (1 << (bits-1))) <= max)
  116. put_bits(pb, 1, value & (1 << (bits-1)));
  117. }
  118. static unsigned int read_uint_max(GetBitContext *gb, int max)
  119. {
  120. int i, bits, value = 0;
  121. if (!max)
  122. return 0;
  123. bits = bits_to_store(max);
  124. for (i = 0; i < bits-1; i++)
  125. if (get_bits1(gb))
  126. value += 1 << i;
  127. if ( (value | (1<<(bits-1))) <= max)
  128. if (get_bits1(gb))
  129. value += 1 << (bits-1);
  130. return value;
  131. }
  132. static int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
  133. {
  134. int i, j, x = 0, low_bits = 0, max = 0;
  135. int step = 256, pos = 0, dominant = 0, any = 0;
  136. int *copy, *bits;
  137. copy = av_mallocz(4* entries);
  138. if (!copy)
  139. return -1;
  140. if (base_2_part)
  141. {
  142. int energy = 0;
  143. for (i = 0; i < entries; i++)
  144. energy += abs(buf[i]);
  145. low_bits = bits_to_store(energy / (entries * 2));
  146. if (low_bits > 15)
  147. low_bits = 15;
  148. put_bits(pb, 4, low_bits);
  149. }
  150. for (i = 0; i < entries; i++)
  151. {
  152. put_bits(pb, low_bits, abs(buf[i]));
  153. copy[i] = abs(buf[i]) >> low_bits;
  154. if (copy[i] > max)
  155. max = abs(copy[i]);
  156. }
  157. bits = av_mallocz(4* entries*max);
  158. if (!bits)
  159. {
  160. // av_free(copy);
  161. return -1;
  162. }
  163. for (i = 0; i <= max; i++)
  164. {
  165. for (j = 0; j < entries; j++)
  166. if (copy[j] >= i)
  167. bits[x++] = copy[j] > i;
  168. }
  169. // store bitstream
  170. while (pos < x)
  171. {
  172. int steplet = step >> 8;
  173. if (pos + steplet > x)
  174. steplet = x - pos;
  175. for (i = 0; i < steplet; i++)
  176. if (bits[i+pos] != dominant)
  177. any = 1;
  178. put_bits(pb, 1, any);
  179. if (!any)
  180. {
  181. pos += steplet;
  182. step += step / ADAPT_LEVEL;
  183. }
  184. else
  185. {
  186. int interloper = 0;
  187. while (((pos + interloper) < x) && (bits[pos + interloper] == dominant))
  188. interloper++;
  189. // note change
  190. write_uint_max(pb, interloper, (step >> 8) - 1);
  191. pos += interloper + 1;
  192. step -= step / ADAPT_LEVEL;
  193. }
  194. if (step < 256)
  195. {
  196. step = 65536 / step;
  197. dominant = !dominant;
  198. }
  199. }
  200. // store signs
  201. for (i = 0; i < entries; i++)
  202. if (buf[i])
  203. put_bits(pb, 1, buf[i] < 0);
  204. // av_free(bits);
  205. // av_free(copy);
  206. return 0;
  207. }
  208. static int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
  209. {
  210. int i, low_bits = 0, x = 0;
  211. int n_zeros = 0, step = 256, dominant = 0;
  212. int pos = 0, level = 0;
  213. int *bits = av_mallocz(4* entries);
  214. if (!bits)
  215. return -1;
  216. if (base_2_part)
  217. {
  218. low_bits = get_bits(gb, 4);
  219. if (low_bits)
  220. for (i = 0; i < entries; i++)
  221. buf[i] = get_bits(gb, low_bits);
  222. }
  223. // av_log(NULL, AV_LOG_INFO, "entries: %d, low bits: %d\n", entries, low_bits);
  224. while (n_zeros < entries)
  225. {
  226. int steplet = step >> 8;
  227. if (!get_bits1(gb))
  228. {
  229. for (i = 0; i < steplet; i++)
  230. bits[x++] = dominant;
  231. if (!dominant)
  232. n_zeros += steplet;
  233. step += step / ADAPT_LEVEL;
  234. }
  235. else
  236. {
  237. int actual_run = read_uint_max(gb, steplet-1);
  238. // av_log(NULL, AV_LOG_INFO, "actual run: %d\n", actual_run);
  239. for (i = 0; i < actual_run; i++)
  240. bits[x++] = dominant;
  241. bits[x++] = !dominant;
  242. if (!dominant)
  243. n_zeros += actual_run;
  244. else
  245. n_zeros++;
  246. step -= step / ADAPT_LEVEL;
  247. }
  248. if (step < 256)
  249. {
  250. step = 65536 / step;
  251. dominant = !dominant;
  252. }
  253. }
  254. // reconstruct unsigned values
  255. n_zeros = 0;
  256. for (i = 0; n_zeros < entries; i++)
  257. {
  258. while(1)
  259. {
  260. if (pos >= entries)
  261. {
  262. pos = 0;
  263. level += 1 << low_bits;
  264. }
  265. if (buf[pos] >= level)
  266. break;
  267. pos++;
  268. }
  269. if (bits[i])
  270. buf[pos] += 1 << low_bits;
  271. else
  272. n_zeros++;
  273. pos++;
  274. }
  275. // av_free(bits);
  276. // read signs
  277. for (i = 0; i < entries; i++)
  278. if (buf[i] && get_bits1(gb))
  279. buf[i] = -buf[i];
  280. // av_log(NULL, AV_LOG_INFO, "zeros: %d pos: %d\n", n_zeros, pos);
  281. return 0;
  282. }
  283. #endif
  284. static void predictor_init_state(int *k, int *state, int order)
  285. {
  286. int i;
  287. for (i = order-2; i >= 0; i--)
  288. {
  289. int j, p, x = state[i];
  290. for (j = 0, p = i+1; p < order; j++,p++)
  291. {
  292. int tmp = x + shift_down(k[j] * state[p], LATTICE_SHIFT);
  293. state[p] += shift_down(k[j]*x, LATTICE_SHIFT);
  294. x = tmp;
  295. }
  296. }
  297. }
  298. static int predictor_calc_error(int *k, int *state, int order, int error)
  299. {
  300. int i, x = error - shift_down(k[order-1] * state[order-1], LATTICE_SHIFT);
  301. #if 1
  302. int *k_ptr = &(k[order-2]),
  303. *state_ptr = &(state[order-2]);
  304. for (i = order-2; i >= 0; i--, k_ptr--, state_ptr--)
  305. {
  306. int k_value = *k_ptr, state_value = *state_ptr;
  307. x -= shift_down(k_value * state_value, LATTICE_SHIFT);
  308. state_ptr[1] = state_value + shift_down(k_value * x, LATTICE_SHIFT);
  309. }
  310. #else
  311. for (i = order-2; i >= 0; i--)
  312. {
  313. x -= shift_down(k[i] * state[i], LATTICE_SHIFT);
  314. state[i+1] = state[i] + shift_down(k[i] * x, LATTICE_SHIFT);
  315. }
  316. #endif
  317. // don't drift too far, to avoid overflows
  318. if (x > (SAMPLE_FACTOR<<16)) x = (SAMPLE_FACTOR<<16);
  319. if (x < -(SAMPLE_FACTOR<<16)) x = -(SAMPLE_FACTOR<<16);
  320. state[0] = x;
  321. return x;
  322. }
  323. #if CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER
  324. // Heavily modified Levinson-Durbin algorithm which
  325. // copes better with quantization, and calculates the
  326. // actual whitened result as it goes.
  327. static void modified_levinson_durbin(int *window, int window_entries,
  328. int *out, int out_entries, int channels, int *tap_quant)
  329. {
  330. int i;
  331. int *state = av_mallocz(4* window_entries);
  332. memcpy(state, window, 4* window_entries);
  333. for (i = 0; i < out_entries; i++)
  334. {
  335. int step = (i+1)*channels, k, j;
  336. double xx = 0.0, xy = 0.0;
  337. #if 1
  338. int *x_ptr = &(window[step]), *state_ptr = &(state[0]);
  339. j = window_entries - step;
  340. for (;j>=0;j--,x_ptr++,state_ptr++)
  341. {
  342. double x_value = *x_ptr, state_value = *state_ptr;
  343. xx += state_value*state_value;
  344. xy += x_value*state_value;
  345. }
  346. #else
  347. for (j = 0; j <= (window_entries - step); j++);
  348. {
  349. double stepval = window[step+j], stateval = window[j];
  350. // xx += (double)window[j]*(double)window[j];
  351. // xy += (double)window[step+j]*(double)window[j];
  352. xx += stateval*stateval;
  353. xy += stepval*stateval;
  354. }
  355. #endif
  356. if (xx == 0.0)
  357. k = 0;
  358. else
  359. k = (int)(floor(-xy/xx * (double)LATTICE_FACTOR / (double)(tap_quant[i]) + 0.5));
  360. if (k > (LATTICE_FACTOR/tap_quant[i]))
  361. k = LATTICE_FACTOR/tap_quant[i];
  362. if (-k > (LATTICE_FACTOR/tap_quant[i]))
  363. k = -(LATTICE_FACTOR/tap_quant[i]);
  364. out[i] = k;
  365. k *= tap_quant[i];
  366. #if 1
  367. x_ptr = &(window[step]);
  368. state_ptr = &(state[0]);
  369. j = window_entries - step;
  370. for (;j>=0;j--,x_ptr++,state_ptr++)
  371. {
  372. int x_value = *x_ptr, state_value = *state_ptr;
  373. *x_ptr = x_value + shift_down(k*state_value,LATTICE_SHIFT);
  374. *state_ptr = state_value + shift_down(k*x_value, LATTICE_SHIFT);
  375. }
  376. #else
  377. for (j=0; j <= (window_entries - step); j++)
  378. {
  379. int stepval = window[step+j], stateval=state[j];
  380. window[step+j] += shift_down(k * stateval, LATTICE_SHIFT);
  381. state[j] += shift_down(k * stepval, LATTICE_SHIFT);
  382. }
  383. #endif
  384. }
  385. av_free(state);
  386. }
  387. #endif /* CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER */
  388. static const int samplerate_table[] =
  389. { 44100, 22050, 11025, 96000, 48000, 32000, 24000, 16000, 8000 };
  390. #if CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER
  391. static inline int code_samplerate(int samplerate)
  392. {
  393. switch (samplerate)
  394. {
  395. case 44100: return 0;
  396. case 22050: return 1;
  397. case 11025: return 2;
  398. case 96000: return 3;
  399. case 48000: return 4;
  400. case 32000: return 5;
  401. case 24000: return 6;
  402. case 16000: return 7;
  403. case 8000: return 8;
  404. }
  405. return -1;
  406. }
  407. static av_cold int sonic_encode_init(AVCodecContext *avctx)
  408. {
  409. SonicContext *s = avctx->priv_data;
  410. PutBitContext pb;
  411. int i, version = 0;
  412. if (avctx->channels > MAX_CHANNELS)
  413. {
  414. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
  415. return -1; /* only stereo or mono for now */
  416. }
  417. if (avctx->channels == 2)
  418. s->decorrelation = MID_SIDE;
  419. if (avctx->codec->id == CODEC_ID_SONIC_LS)
  420. {
  421. s->lossless = 1;
  422. s->num_taps = 32;
  423. s->downsampling = 1;
  424. s->quantization = 0.0;
  425. }
  426. else
  427. {
  428. s->num_taps = 128;
  429. s->downsampling = 2;
  430. s->quantization = 1.0;
  431. }
  432. // max tap 2048
  433. if ((s->num_taps < 32) || (s->num_taps > 1024) ||
  434. ((s->num_taps>>5)<<5 != s->num_taps))
  435. {
  436. av_log(avctx, AV_LOG_ERROR, "Invalid number of taps\n");
  437. return -1;
  438. }
  439. // generate taps
  440. s->tap_quant = av_mallocz(4* s->num_taps);
  441. for (i = 0; i < s->num_taps; i++)
  442. s->tap_quant[i] = (int)(sqrt(i+1));
  443. s->channels = avctx->channels;
  444. s->samplerate = avctx->sample_rate;
  445. s->block_align = (int)(2048.0*s->samplerate/44100)/s->downsampling;
  446. s->frame_size = s->channels*s->block_align*s->downsampling;
  447. s->tail = av_mallocz(4* s->num_taps*s->channels);
  448. if (!s->tail)
  449. return -1;
  450. s->tail_size = s->num_taps*s->channels;
  451. s->predictor_k = av_mallocz(4 * s->num_taps);
  452. if (!s->predictor_k)
  453. return -1;
  454. for (i = 0; i < s->channels; i++)
  455. {
  456. s->coded_samples[i] = av_mallocz(4* s->block_align);
  457. if (!s->coded_samples[i])
  458. return -1;
  459. }
  460. s->int_samples = av_mallocz(4* s->frame_size);
  461. s->window_size = ((2*s->tail_size)+s->frame_size);
  462. s->window = av_mallocz(4* s->window_size);
  463. if (!s->window)
  464. return -1;
  465. avctx->extradata = av_mallocz(16);
  466. if (!avctx->extradata)
  467. return -1;
  468. init_put_bits(&pb, avctx->extradata, 16*8);
  469. put_bits(&pb, 2, version); // version
  470. if (version == 1)
  471. {
  472. put_bits(&pb, 2, s->channels);
  473. put_bits(&pb, 4, code_samplerate(s->samplerate));
  474. }
  475. put_bits(&pb, 1, s->lossless);
  476. if (!s->lossless)
  477. put_bits(&pb, 3, SAMPLE_SHIFT); // XXX FIXME: sample precision
  478. put_bits(&pb, 2, s->decorrelation);
  479. put_bits(&pb, 2, s->downsampling);
  480. put_bits(&pb, 5, (s->num_taps >> 5)-1); // 32..1024
  481. put_bits(&pb, 1, 0); // XXX FIXME: no custom tap quant table
  482. flush_put_bits(&pb);
  483. avctx->extradata_size = put_bits_count(&pb)/8;
  484. av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
  485. version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
  486. avctx->coded_frame = avcodec_alloc_frame();
  487. if (!avctx->coded_frame)
  488. return AVERROR(ENOMEM);
  489. avctx->coded_frame->key_frame = 1;
  490. avctx->frame_size = s->block_align*s->downsampling;
  491. return 0;
  492. }
  493. static av_cold int sonic_encode_close(AVCodecContext *avctx)
  494. {
  495. SonicContext *s = avctx->priv_data;
  496. int i;
  497. av_freep(&avctx->coded_frame);
  498. for (i = 0; i < s->channels; i++)
  499. av_free(s->coded_samples[i]);
  500. av_free(s->predictor_k);
  501. av_free(s->tail);
  502. av_free(s->tap_quant);
  503. av_free(s->window);
  504. av_free(s->int_samples);
  505. return 0;
  506. }
  507. static int sonic_encode_frame(AVCodecContext *avctx,
  508. uint8_t *buf, int buf_size, void *data)
  509. {
  510. SonicContext *s = avctx->priv_data;
  511. PutBitContext pb;
  512. int i, j, ch, quant = 0, x = 0;
  513. short *samples = data;
  514. init_put_bits(&pb, buf, buf_size*8);
  515. // short -> internal
  516. for (i = 0; i < s->frame_size; i++)
  517. s->int_samples[i] = samples[i];
  518. if (!s->lossless)
  519. for (i = 0; i < s->frame_size; i++)
  520. s->int_samples[i] = s->int_samples[i] << SAMPLE_SHIFT;
  521. switch(s->decorrelation)
  522. {
  523. case MID_SIDE:
  524. for (i = 0; i < s->frame_size; i += s->channels)
  525. {
  526. s->int_samples[i] += s->int_samples[i+1];
  527. s->int_samples[i+1] -= shift(s->int_samples[i], 1);
  528. }
  529. break;
  530. case LEFT_SIDE:
  531. for (i = 0; i < s->frame_size; i += s->channels)
  532. s->int_samples[i+1] -= s->int_samples[i];
  533. break;
  534. case RIGHT_SIDE:
  535. for (i = 0; i < s->frame_size; i += s->channels)
  536. s->int_samples[i] -= s->int_samples[i+1];
  537. break;
  538. }
  539. memset(s->window, 0, 4* s->window_size);
  540. for (i = 0; i < s->tail_size; i++)
  541. s->window[x++] = s->tail[i];
  542. for (i = 0; i < s->frame_size; i++)
  543. s->window[x++] = s->int_samples[i];
  544. for (i = 0; i < s->tail_size; i++)
  545. s->window[x++] = 0;
  546. for (i = 0; i < s->tail_size; i++)
  547. s->tail[i] = s->int_samples[s->frame_size - s->tail_size + i];
  548. // generate taps
  549. modified_levinson_durbin(s->window, s->window_size,
  550. s->predictor_k, s->num_taps, s->channels, s->tap_quant);
  551. if (intlist_write(&pb, s->predictor_k, s->num_taps, 0) < 0)
  552. return -1;
  553. for (ch = 0; ch < s->channels; ch++)
  554. {
  555. x = s->tail_size+ch;
  556. for (i = 0; i < s->block_align; i++)
  557. {
  558. int sum = 0;
  559. for (j = 0; j < s->downsampling; j++, x += s->channels)
  560. sum += s->window[x];
  561. s->coded_samples[ch][i] = sum;
  562. }
  563. }
  564. // simple rate control code
  565. if (!s->lossless)
  566. {
  567. double energy1 = 0.0, energy2 = 0.0;
  568. for (ch = 0; ch < s->channels; ch++)
  569. {
  570. for (i = 0; i < s->block_align; i++)
  571. {
  572. double sample = s->coded_samples[ch][i];
  573. energy2 += sample*sample;
  574. energy1 += fabs(sample);
  575. }
  576. }
  577. energy2 = sqrt(energy2/(s->channels*s->block_align));
  578. energy1 = sqrt(2.0)*energy1/(s->channels*s->block_align);
  579. // increase bitrate when samples are like a gaussian distribution
  580. // reduce bitrate when samples are like a two-tailed exponential distribution
  581. if (energy2 > energy1)
  582. energy2 += (energy2-energy1)*RATE_VARIATION;
  583. quant = (int)(BASE_QUANT*s->quantization*energy2/SAMPLE_FACTOR);
  584. // av_log(avctx, AV_LOG_DEBUG, "quant: %d energy: %f / %f\n", quant, energy1, energy2);
  585. if (quant < 1)
  586. quant = 1;
  587. if (quant > 65535)
  588. quant = 65535;
  589. set_ue_golomb(&pb, quant);
  590. quant *= SAMPLE_FACTOR;
  591. }
  592. // write out coded samples
  593. for (ch = 0; ch < s->channels; ch++)
  594. {
  595. if (!s->lossless)
  596. for (i = 0; i < s->block_align; i++)
  597. s->coded_samples[ch][i] = divide(s->coded_samples[ch][i], quant);
  598. if (intlist_write(&pb, s->coded_samples[ch], s->block_align, 1) < 0)
  599. return -1;
  600. }
  601. // av_log(avctx, AV_LOG_DEBUG, "used bytes: %d\n", (put_bits_count(&pb)+7)/8);
  602. flush_put_bits(&pb);
  603. return (put_bits_count(&pb)+7)/8;
  604. }
  605. #endif /* CONFIG_SONIC_ENCODER || CONFIG_SONIC_LS_ENCODER */
  606. #if CONFIG_SONIC_DECODER
  607. static av_cold int sonic_decode_init(AVCodecContext *avctx)
  608. {
  609. SonicContext *s = avctx->priv_data;
  610. GetBitContext gb;
  611. int i, version;
  612. s->channels = avctx->channels;
  613. s->samplerate = avctx->sample_rate;
  614. if (!avctx->extradata)
  615. {
  616. av_log(avctx, AV_LOG_ERROR, "No mandatory headers present\n");
  617. return -1;
  618. }
  619. init_get_bits(&gb, avctx->extradata, avctx->extradata_size);
  620. version = get_bits(&gb, 2);
  621. if (version > 1)
  622. {
  623. av_log(avctx, AV_LOG_ERROR, "Unsupported Sonic version, please report\n");
  624. return -1;
  625. }
  626. if (version == 1)
  627. {
  628. s->channels = get_bits(&gb, 2);
  629. s->samplerate = samplerate_table[get_bits(&gb, 4)];
  630. av_log(avctx, AV_LOG_INFO, "Sonicv2 chans: %d samprate: %d\n",
  631. s->channels, s->samplerate);
  632. }
  633. if (s->channels > MAX_CHANNELS)
  634. {
  635. av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
  636. return -1;
  637. }
  638. s->lossless = get_bits1(&gb);
  639. if (!s->lossless)
  640. skip_bits(&gb, 3); // XXX FIXME
  641. s->decorrelation = get_bits(&gb, 2);
  642. s->downsampling = get_bits(&gb, 2);
  643. s->num_taps = (get_bits(&gb, 5)+1)<<5;
  644. if (get_bits1(&gb)) // XXX FIXME
  645. av_log(avctx, AV_LOG_INFO, "Custom quant table\n");
  646. s->block_align = (int)(2048.0*(s->samplerate/44100))/s->downsampling;
  647. s->frame_size = s->channels*s->block_align*s->downsampling;
  648. // avctx->frame_size = s->block_align;
  649. av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
  650. version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
  651. // generate taps
  652. s->tap_quant = av_mallocz(4* s->num_taps);
  653. for (i = 0; i < s->num_taps; i++)
  654. s->tap_quant[i] = (int)(sqrt(i+1));
  655. s->predictor_k = av_mallocz(4* s->num_taps);
  656. for (i = 0; i < s->channels; i++)
  657. {
  658. s->predictor_state[i] = av_mallocz(4* s->num_taps);
  659. if (!s->predictor_state[i])
  660. return -1;
  661. }
  662. for (i = 0; i < s->channels; i++)
  663. {
  664. s->coded_samples[i] = av_mallocz(4* s->block_align);
  665. if (!s->coded_samples[i])
  666. return -1;
  667. }
  668. s->int_samples = av_mallocz(4* s->frame_size);
  669. avctx->sample_fmt = SAMPLE_FMT_S16;
  670. return 0;
  671. }
  672. static av_cold int sonic_decode_close(AVCodecContext *avctx)
  673. {
  674. SonicContext *s = avctx->priv_data;
  675. int i;
  676. av_free(s->int_samples);
  677. av_free(s->tap_quant);
  678. av_free(s->predictor_k);
  679. for (i = 0; i < s->channels; i++)
  680. {
  681. av_free(s->predictor_state[i]);
  682. av_free(s->coded_samples[i]);
  683. }
  684. return 0;
  685. }
  686. static int sonic_decode_frame(AVCodecContext *avctx,
  687. void *data, int *data_size,
  688. const uint8_t *buf, int buf_size)
  689. {
  690. SonicContext *s = avctx->priv_data;
  691. GetBitContext gb;
  692. int i, quant, ch, j;
  693. short *samples = data;
  694. if (buf_size == 0) return 0;
  695. // av_log(NULL, AV_LOG_INFO, "buf_size: %d\n", buf_size);
  696. init_get_bits(&gb, buf, buf_size*8);
  697. intlist_read(&gb, s->predictor_k, s->num_taps, 0);
  698. // dequantize
  699. for (i = 0; i < s->num_taps; i++)
  700. s->predictor_k[i] *= s->tap_quant[i];
  701. if (s->lossless)
  702. quant = 1;
  703. else
  704. quant = get_ue_golomb(&gb) * SAMPLE_FACTOR;
  705. // av_log(NULL, AV_LOG_INFO, "quant: %d\n", quant);
  706. for (ch = 0; ch < s->channels; ch++)
  707. {
  708. int x = ch;
  709. predictor_init_state(s->predictor_k, s->predictor_state[ch], s->num_taps);
  710. intlist_read(&gb, s->coded_samples[ch], s->block_align, 1);
  711. for (i = 0; i < s->block_align; i++)
  712. {
  713. for (j = 0; j < s->downsampling - 1; j++)
  714. {
  715. s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, 0);
  716. x += s->channels;
  717. }
  718. s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, s->coded_samples[ch][i] * quant);
  719. x += s->channels;
  720. }
  721. for (i = 0; i < s->num_taps; i++)
  722. s->predictor_state[ch][i] = s->int_samples[s->frame_size - s->channels + ch - i*s->channels];
  723. }
  724. switch(s->decorrelation)
  725. {
  726. case MID_SIDE:
  727. for (i = 0; i < s->frame_size; i += s->channels)
  728. {
  729. s->int_samples[i+1] += shift(s->int_samples[i], 1);
  730. s->int_samples[i] -= s->int_samples[i+1];
  731. }
  732. break;
  733. case LEFT_SIDE:
  734. for (i = 0; i < s->frame_size; i += s->channels)
  735. s->int_samples[i+1] += s->int_samples[i];
  736. break;
  737. case RIGHT_SIDE:
  738. for (i = 0; i < s->frame_size; i += s->channels)
  739. s->int_samples[i] += s->int_samples[i+1];
  740. break;
  741. }
  742. if (!s->lossless)
  743. for (i = 0; i < s->frame_size; i++)
  744. s->int_samples[i] = shift(s->int_samples[i], SAMPLE_SHIFT);
  745. // internal -> short
  746. for (i = 0; i < s->frame_size; i++)
  747. samples[i] = av_clip_int16(s->int_samples[i]);
  748. align_get_bits(&gb);
  749. *data_size = s->frame_size * 2;
  750. return (get_bits_count(&gb)+7)/8;
  751. }
  752. #endif /* CONFIG_SONIC_DECODER */
  753. #if CONFIG_SONIC_ENCODER
  754. AVCodec sonic_encoder = {
  755. "sonic",
  756. CODEC_TYPE_AUDIO,
  757. CODEC_ID_SONIC,
  758. sizeof(SonicContext),
  759. sonic_encode_init,
  760. sonic_encode_frame,
  761. sonic_encode_close,
  762. NULL,
  763. .long_name = NULL_IF_CONFIG_SMALL("Sonic"),
  764. };
  765. #endif
  766. #if CONFIG_SONIC_LS_ENCODER
  767. AVCodec sonic_ls_encoder = {
  768. "sonicls",
  769. CODEC_TYPE_AUDIO,
  770. CODEC_ID_SONIC_LS,
  771. sizeof(SonicContext),
  772. sonic_encode_init,
  773. sonic_encode_frame,
  774. sonic_encode_close,
  775. NULL,
  776. .long_name = NULL_IF_CONFIG_SMALL("Sonic lossless"),
  777. };
  778. #endif
  779. #if CONFIG_SONIC_DECODER
  780. AVCodec sonic_decoder = {
  781. "sonic",
  782. CODEC_TYPE_AUDIO,
  783. CODEC_ID_SONIC,
  784. sizeof(SonicContext),
  785. sonic_decode_init,
  786. NULL,
  787. sonic_decode_close,
  788. sonic_decode_frame,
  789. .long_name = NULL_IF_CONFIG_SMALL("Sonic"),
  790. };
  791. #endif