You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1003 lines
26KB

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