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.

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