]> git.sesse.net Git - ffmpeg/blob - libavcodec/sonic.c
Remove cs_test and swscale-example on clean.
[ffmpeg] / libavcodec / sonic.c
1 /*
2  * Simple free lossless/lossy audio codec
3  * Copyright (c) 2004 Alex Beregszaszi
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18  */
19 #include "avcodec.h"
20 #include "bitstream.h"
21 #include "golomb.h"
22
23 /**
24  * @file sonic.c
25  * Simple free lossless/lossy audio codec
26  * Based on Paul Francis Harrison's Bonk (http://www.logarithmic.net/pfh/bonk)
27  * Written and designed by Alex Beregszaszi
28  *
29  * TODO:
30  *  - CABAC put/get_symbol
31  *  - independent quantizer for channels
32  *  - >2 channels support
33  *  - more decorrelation types
34  *  - more tap_quant tests
35  *  - selectable intlist writers/readers (bonk-style, golomb, cabac)
36  */
37
38 #define MAX_CHANNELS 2
39
40 #define MID_SIDE 0
41 #define LEFT_SIDE 1
42 #define RIGHT_SIDE 2
43
44 typedef struct SonicContext {
45     int lossless, decorrelation;
46
47     int num_taps, downsampling;
48     double quantization;
49
50     int channels, samplerate, block_align, frame_size;
51
52     int *tap_quant;
53     int *int_samples;
54     int *coded_samples[MAX_CHANNELS];
55
56     // for encoding
57     int *tail;
58     int tail_size;
59     int *window;
60     int window_size;
61
62     // for decoding
63     int *predictor_k;
64     int *predictor_state[MAX_CHANNELS];
65 } SonicContext;
66
67 #define LATTICE_SHIFT   10
68 #define SAMPLE_SHIFT    4
69 #define LATTICE_FACTOR  (1 << LATTICE_SHIFT)
70 #define SAMPLE_FACTOR   (1 << SAMPLE_SHIFT)
71
72 #define BASE_QUANT      0.6
73 #define RATE_VARIATION  3.0
74
75 static inline int divide(int a, int b)
76 {
77     if (a < 0)
78         return -( (-a + b/2)/b );
79     else
80         return (a + b/2)/b;
81 }
82
83 static inline int shift(int a,int b)
84 {
85     return (a+(1<<(b-1))) >> b;
86 }
87
88 static inline int shift_down(int a,int b)
89 {
90     return (a>>b)+((a<0)?1:0);
91 }
92
93 #if 1
94 static inline int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
95 {
96     int i;
97
98     for (i = 0; i < entries; i++)
99         set_se_golomb(pb, buf[i]);
100
101     return 1;
102 }
103
104 static inline int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
105 {
106     int i;
107
108     for (i = 0; i < entries; i++)
109         buf[i] = get_se_golomb(gb);
110
111     return 1;
112 }
113
114 #else
115
116 #define ADAPT_LEVEL 8
117
118 static int bits_to_store(uint64_t x)
119 {
120     int res = 0;
121
122     while(x)
123     {
124         res++;
125         x >>= 1;
126     }
127     return res;
128 }
129
130 static void write_uint_max(PutBitContext *pb, unsigned int value, unsigned int max)
131 {
132     int i, bits;
133
134     if (!max)
135         return;
136
137     bits = bits_to_store(max);
138
139     for (i = 0; i < bits-1; i++)
140         put_bits(pb, 1, value & (1 << i));
141
142     if ( (value | (1 << (bits-1))) <= max)
143         put_bits(pb, 1, value & (1 << (bits-1)));
144 }
145
146 static unsigned int read_uint_max(GetBitContext *gb, int max)
147 {
148     int i, bits, value = 0;
149
150     if (!max)
151         return 0;
152
153     bits = bits_to_store(max);
154
155     for (i = 0; i < bits-1; i++)
156         if (get_bits1(gb))
157             value += 1 << i;
158
159     if ( (value | (1<<(bits-1))) <= max)
160         if (get_bits1(gb))
161             value += 1 << (bits-1);
162
163     return value;
164 }
165
166 static int intlist_write(PutBitContext *pb, int *buf, int entries, int base_2_part)
167 {
168     int i, j, x = 0, low_bits = 0, max = 0;
169     int step = 256, pos = 0, dominant = 0, any = 0;
170     int *copy, *bits;
171
172     copy = av_mallocz(4* entries);
173     if (!copy)
174         return -1;
175
176     if (base_2_part)
177     {
178         int energy = 0;
179
180         for (i = 0; i < entries; i++)
181             energy += abs(buf[i]);
182
183         low_bits = bits_to_store(energy / (entries * 2));
184         if (low_bits > 15)
185             low_bits = 15;
186
187         put_bits(pb, 4, low_bits);
188     }
189
190     for (i = 0; i < entries; i++)
191     {
192         put_bits(pb, low_bits, abs(buf[i]));
193         copy[i] = abs(buf[i]) >> low_bits;
194         if (copy[i] > max)
195             max = abs(copy[i]);
196     }
197
198     bits = av_mallocz(4* entries*max);
199     if (!bits)
200     {
201 //        av_free(copy);
202         return -1;
203     }
204
205     for (i = 0; i <= max; i++)
206     {
207         for (j = 0; j < entries; j++)
208             if (copy[j] >= i)
209                 bits[x++] = copy[j] > i;
210     }
211
212     // store bitstream
213     while (pos < x)
214     {
215         int steplet = step >> 8;
216
217         if (pos + steplet > x)
218             steplet = x - pos;
219
220         for (i = 0; i < steplet; i++)
221             if (bits[i+pos] != dominant)
222                 any = 1;
223
224         put_bits(pb, 1, any);
225
226         if (!any)
227         {
228             pos += steplet;
229             step += step / ADAPT_LEVEL;
230         }
231         else
232         {
233             int interloper = 0;
234
235             while (((pos + interloper) < x) && (bits[pos + interloper] == dominant))
236                 interloper++;
237
238             // note change
239             write_uint_max(pb, interloper, (step >> 8) - 1);
240
241             pos += interloper + 1;
242             step -= step / ADAPT_LEVEL;
243         }
244
245         if (step < 256)
246         {
247             step = 65536 / step;
248             dominant = !dominant;
249         }
250     }
251
252     // store signs
253     for (i = 0; i < entries; i++)
254         if (buf[i])
255             put_bits(pb, 1, buf[i] < 0);
256
257 //    av_free(bits);
258 //    av_free(copy);
259
260     return 0;
261 }
262
263 static int intlist_read(GetBitContext *gb, int *buf, int entries, int base_2_part)
264 {
265     int i, low_bits = 0, x = 0;
266     int n_zeros = 0, step = 256, dominant = 0;
267     int pos = 0, level = 0;
268     int *bits = av_mallocz(4* entries);
269
270     if (!bits)
271         return -1;
272
273     if (base_2_part)
274     {
275         low_bits = get_bits(gb, 4);
276
277         if (low_bits)
278             for (i = 0; i < entries; i++)
279                 buf[i] = get_bits(gb, low_bits);
280     }
281
282 //    av_log(NULL, AV_LOG_INFO, "entries: %d, low bits: %d\n", entries, low_bits);
283
284     while (n_zeros < entries)
285     {
286         int steplet = step >> 8;
287
288         if (!get_bits1(gb))
289         {
290             for (i = 0; i < steplet; i++)
291                 bits[x++] = dominant;
292
293             if (!dominant)
294                 n_zeros += steplet;
295
296             step += step / ADAPT_LEVEL;
297         }
298         else
299         {
300             int actual_run = read_uint_max(gb, steplet-1);
301
302 //            av_log(NULL, AV_LOG_INFO, "actual run: %d\n", actual_run);
303
304             for (i = 0; i < actual_run; i++)
305                 bits[x++] = dominant;
306
307             bits[x++] = !dominant;
308
309             if (!dominant)
310                 n_zeros += actual_run;
311             else
312                 n_zeros++;
313
314             step -= step / ADAPT_LEVEL;
315         }
316
317         if (step < 256)
318         {
319             step = 65536 / step;
320             dominant = !dominant;
321         }
322     }
323
324     // reconstruct unsigned values
325     n_zeros = 0;
326     for (i = 0; n_zeros < entries; i++)
327     {
328         while(1)
329         {
330             if (pos >= entries)
331             {
332                 pos = 0;
333                 level += 1 << low_bits;
334             }
335
336             if (buf[pos] >= level)
337                 break;
338
339             pos++;
340         }
341
342         if (bits[i])
343             buf[pos] += 1 << low_bits;
344         else
345             n_zeros++;
346
347         pos++;
348     }
349 //    av_free(bits);
350
351     // read signs
352     for (i = 0; i < entries; i++)
353         if (buf[i] && get_bits1(gb))
354             buf[i] = -buf[i];
355
356 //    av_log(NULL, AV_LOG_INFO, "zeros: %d pos: %d\n", n_zeros, pos);
357
358     return 0;
359 }
360 #endif
361
362 static void predictor_init_state(int *k, int *state, int order)
363 {
364     int i;
365
366     for (i = order-2; i >= 0; i--)
367     {
368         int j, p, x = state[i];
369
370         for (j = 0, p = i+1; p < order; j++,p++)
371             {
372             int tmp = x + shift_down(k[j] * state[p], LATTICE_SHIFT);
373             state[p] += shift_down(k[j]*x, LATTICE_SHIFT);
374             x = tmp;
375         }
376     }
377 }
378
379 static int predictor_calc_error(int *k, int *state, int order, int error)
380 {
381     int i, x = error - shift_down(k[order-1] * state[order-1], LATTICE_SHIFT);
382
383 #if 1
384     int *k_ptr = &(k[order-2]),
385         *state_ptr = &(state[order-2]);
386     for (i = order-2; i >= 0; i--, k_ptr--, state_ptr--)
387     {
388         int k_value = *k_ptr, state_value = *state_ptr;
389         x -= shift_down(k_value * state_value, LATTICE_SHIFT);
390         state_ptr[1] = state_value + shift_down(k_value * x, LATTICE_SHIFT);
391     }
392 #else
393     for (i = order-2; i >= 0; i--)
394     {
395         x -= shift_down(k[i] * state[i], LATTICE_SHIFT);
396         state[i+1] = state[i] + shift_down(k[i] * x, LATTICE_SHIFT);
397     }
398 #endif
399
400     // don't drift too far, to avoid overflows
401     if (x >  (SAMPLE_FACTOR<<16)) x =  (SAMPLE_FACTOR<<16);
402     if (x < -(SAMPLE_FACTOR<<16)) x = -(SAMPLE_FACTOR<<16);
403
404     state[0] = x;
405
406     return x;
407 }
408
409 #ifdef CONFIG_ENCODERS
410 // Heavily modified Levinson-Durbin algorithm which
411 // copes better with quantization, and calculates the
412 // actual whitened result as it goes.
413
414 static void modified_levinson_durbin(int *window, int window_entries,
415         int *out, int out_entries, int channels, int *tap_quant)
416 {
417     int i;
418     int *state = av_mallocz(4* window_entries);
419
420     memcpy(state, window, 4* window_entries);
421
422     for (i = 0; i < out_entries; i++)
423     {
424         int step = (i+1)*channels, k, j;
425         double xx = 0.0, xy = 0.0;
426 #if 1
427         int *x_ptr = &(window[step]), *state_ptr = &(state[0]);
428         j = window_entries - step;
429         for (;j>=0;j--,x_ptr++,state_ptr++)
430         {
431             double x_value = *x_ptr, state_value = *state_ptr;
432             xx += state_value*state_value;
433             xy += x_value*state_value;
434         }
435 #else
436         for (j = 0; j <= (window_entries - step); j++);
437         {
438             double stepval = window[step+j], stateval = window[j];
439 //            xx += (double)window[j]*(double)window[j];
440 //            xy += (double)window[step+j]*(double)window[j];
441             xx += stateval*stateval;
442             xy += stepval*stateval;
443         }
444 #endif
445         if (xx == 0.0)
446             k = 0;
447         else
448             k = (int)(floor(-xy/xx * (double)LATTICE_FACTOR / (double)(tap_quant[i]) + 0.5));
449
450         if (k > (LATTICE_FACTOR/tap_quant[i]))
451             k = LATTICE_FACTOR/tap_quant[i];
452         if (-k > (LATTICE_FACTOR/tap_quant[i]))
453             k = -(LATTICE_FACTOR/tap_quant[i]);
454
455         out[i] = k;
456         k *= tap_quant[i];
457
458 #if 1
459         x_ptr = &(window[step]);
460         state_ptr = &(state[0]);
461         j = window_entries - step;
462         for (;j>=0;j--,x_ptr++,state_ptr++)
463         {
464             int x_value = *x_ptr, state_value = *state_ptr;
465             *x_ptr = x_value + shift_down(k*state_value,LATTICE_SHIFT);
466             *state_ptr = state_value + shift_down(k*x_value, LATTICE_SHIFT);
467         }
468 #else
469         for (j=0; j <= (window_entries - step); j++)
470         {
471             int stepval = window[step+j], stateval=state[j];
472             window[step+j] += shift_down(k * stateval, LATTICE_SHIFT);
473             state[j] += shift_down(k * stepval, LATTICE_SHIFT);
474         }
475 #endif
476     }
477
478     av_free(state);
479 }
480 #endif /* CONFIG_ENCODERS */
481
482 static int samplerate_table[] =
483     { 44100, 22050, 11025, 96000, 48000, 32000, 24000, 16000, 8000 };
484
485 #ifdef CONFIG_ENCODERS
486
487 static inline int code_samplerate(int samplerate)
488 {
489     switch (samplerate)
490     {
491         case 44100: return 0;
492         case 22050: return 1;
493         case 11025: return 2;
494         case 96000: return 3;
495         case 48000: return 4;
496         case 32000: return 5;
497         case 24000: return 6;
498         case 16000: return 7;
499         case 8000: return 8;
500     }
501     return -1;
502 }
503
504 static int sonic_encode_init(AVCodecContext *avctx)
505 {
506     SonicContext *s = avctx->priv_data;
507     PutBitContext pb;
508     int i, version = 0;
509
510     if (avctx->channels > MAX_CHANNELS)
511     {
512         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
513         return -1; /* only stereo or mono for now */
514     }
515
516     if (avctx->channels == 2)
517         s->decorrelation = MID_SIDE;
518
519     if (avctx->codec->id == CODEC_ID_SONIC_LS)
520     {
521         s->lossless = 1;
522         s->num_taps = 32;
523         s->downsampling = 1;
524         s->quantization = 0.0;
525     }
526     else
527     {
528         s->num_taps = 128;
529         s->downsampling = 2;
530         s->quantization = 1.0;
531     }
532
533     // max tap 2048
534     if ((s->num_taps < 32) || (s->num_taps > 1024) ||
535         ((s->num_taps>>5)<<5 != s->num_taps))
536     {
537         av_log(avctx, AV_LOG_ERROR, "Invalid number of taps\n");
538         return -1;
539     }
540
541     // generate taps
542     s->tap_quant = av_mallocz(4* s->num_taps);
543     for (i = 0; i < s->num_taps; i++)
544         s->tap_quant[i] = (int)(sqrt(i+1));
545
546     s->channels = avctx->channels;
547     s->samplerate = avctx->sample_rate;
548
549     s->block_align = (int)(2048.0*s->samplerate/44100)/s->downsampling;
550     s->frame_size = s->channels*s->block_align*s->downsampling;
551
552     s->tail = av_mallocz(4* s->num_taps*s->channels);
553     if (!s->tail)
554         return -1;
555     s->tail_size = s->num_taps*s->channels;
556
557     s->predictor_k = av_mallocz(4 * s->num_taps);
558     if (!s->predictor_k)
559         return -1;
560
561     for (i = 0; i < s->channels; i++)
562     {
563         s->coded_samples[i] = av_mallocz(4* s->block_align);
564         if (!s->coded_samples[i])
565             return -1;
566     }
567
568     s->int_samples = av_mallocz(4* s->frame_size);
569
570     s->window_size = ((2*s->tail_size)+s->frame_size);
571     s->window = av_mallocz(4* s->window_size);
572     if (!s->window)
573         return -1;
574
575     avctx->extradata = av_mallocz(16);
576     if (!avctx->extradata)
577         return -1;
578     init_put_bits(&pb, avctx->extradata, 16*8);
579
580     put_bits(&pb, 2, version); // version
581     if (version == 1)
582     {
583         put_bits(&pb, 2, s->channels);
584         put_bits(&pb, 4, code_samplerate(s->samplerate));
585     }
586     put_bits(&pb, 1, s->lossless);
587     if (!s->lossless)
588         put_bits(&pb, 3, SAMPLE_SHIFT); // XXX FIXME: sample precision
589     put_bits(&pb, 2, s->decorrelation);
590     put_bits(&pb, 2, s->downsampling);
591     put_bits(&pb, 5, (s->num_taps >> 5)-1); // 32..1024
592     put_bits(&pb, 1, 0); // XXX FIXME: no custom tap quant table
593
594     flush_put_bits(&pb);
595     avctx->extradata_size = put_bits_count(&pb)/8;
596
597     av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
598         version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
599
600     avctx->coded_frame = avcodec_alloc_frame();
601     if (!avctx->coded_frame)
602         return -ENOMEM;
603     avctx->coded_frame->key_frame = 1;
604     avctx->frame_size = s->block_align*s->downsampling;
605
606     return 0;
607 }
608
609 static int sonic_encode_close(AVCodecContext *avctx)
610 {
611     SonicContext *s = avctx->priv_data;
612     int i;
613
614     av_freep(&avctx->coded_frame);
615
616     for (i = 0; i < s->channels; i++)
617         av_free(s->coded_samples[i]);
618
619     av_free(s->predictor_k);
620     av_free(s->tail);
621     av_free(s->tap_quant);
622     av_free(s->window);
623     av_free(s->int_samples);
624
625     return 0;
626 }
627
628 static int sonic_encode_frame(AVCodecContext *avctx,
629                             uint8_t *buf, int buf_size, void *data)
630 {
631     SonicContext *s = avctx->priv_data;
632     PutBitContext pb;
633     int i, j, ch, quant = 0, x = 0;
634     short *samples = data;
635
636     init_put_bits(&pb, buf, buf_size*8);
637
638     // short -> internal
639     for (i = 0; i < s->frame_size; i++)
640         s->int_samples[i] = samples[i];
641
642     if (!s->lossless)
643         for (i = 0; i < s->frame_size; i++)
644             s->int_samples[i] = s->int_samples[i] << SAMPLE_SHIFT;
645
646     switch(s->decorrelation)
647     {
648         case MID_SIDE:
649             for (i = 0; i < s->frame_size; i += s->channels)
650             {
651                 s->int_samples[i] += s->int_samples[i+1];
652                 s->int_samples[i+1] -= shift(s->int_samples[i], 1);
653             }
654             break;
655         case LEFT_SIDE:
656             for (i = 0; i < s->frame_size; i += s->channels)
657                 s->int_samples[i+1] -= s->int_samples[i];
658             break;
659         case RIGHT_SIDE:
660             for (i = 0; i < s->frame_size; i += s->channels)
661                 s->int_samples[i] -= s->int_samples[i+1];
662             break;
663     }
664
665     memset(s->window, 0, 4* s->window_size);
666
667     for (i = 0; i < s->tail_size; i++)
668         s->window[x++] = s->tail[i];
669
670     for (i = 0; i < s->frame_size; i++)
671         s->window[x++] = s->int_samples[i];
672
673     for (i = 0; i < s->tail_size; i++)
674         s->window[x++] = 0;
675
676     for (i = 0; i < s->tail_size; i++)
677         s->tail[i] = s->int_samples[s->frame_size - s->tail_size + i];
678
679     // generate taps
680     modified_levinson_durbin(s->window, s->window_size,
681                 s->predictor_k, s->num_taps, s->channels, s->tap_quant);
682     if (intlist_write(&pb, s->predictor_k, s->num_taps, 0) < 0)
683         return -1;
684
685     for (ch = 0; ch < s->channels; ch++)
686     {
687         x = s->tail_size+ch;
688         for (i = 0; i < s->block_align; i++)
689         {
690             int sum = 0;
691             for (j = 0; j < s->downsampling; j++, x += s->channels)
692                 sum += s->window[x];
693             s->coded_samples[ch][i] = sum;
694         }
695     }
696
697     // simple rate control code
698     if (!s->lossless)
699     {
700         double energy1 = 0.0, energy2 = 0.0;
701         for (ch = 0; ch < s->channels; ch++)
702         {
703             for (i = 0; i < s->block_align; i++)
704             {
705                 double sample = s->coded_samples[ch][i];
706                 energy2 += sample*sample;
707                 energy1 += fabs(sample);
708             }
709         }
710
711         energy2 = sqrt(energy2/(s->channels*s->block_align));
712         energy1 = sqrt(2.0)*energy1/(s->channels*s->block_align);
713
714         // increase bitrate when samples are like a gaussian distribution
715         // reduce bitrate when samples are like a two-tailed exponential distribution
716
717         if (energy2 > energy1)
718             energy2 += (energy2-energy1)*RATE_VARIATION;
719
720         quant = (int)(BASE_QUANT*s->quantization*energy2/SAMPLE_FACTOR);
721 //        av_log(avctx, AV_LOG_DEBUG, "quant: %d energy: %f / %f\n", quant, energy1, energy2);
722
723         if (quant < 1)
724             quant = 1;
725         if (quant > 65535)
726             quant = 65535;
727
728         set_ue_golomb(&pb, quant);
729
730         quant *= SAMPLE_FACTOR;
731     }
732
733     // write out coded samples
734     for (ch = 0; ch < s->channels; ch++)
735     {
736         if (!s->lossless)
737             for (i = 0; i < s->block_align; i++)
738                 s->coded_samples[ch][i] = divide(s->coded_samples[ch][i], quant);
739
740         if (intlist_write(&pb, s->coded_samples[ch], s->block_align, 1) < 0)
741             return -1;
742     }
743
744 //    av_log(avctx, AV_LOG_DEBUG, "used bytes: %d\n", (put_bits_count(&pb)+7)/8);
745
746     flush_put_bits(&pb);
747     return (put_bits_count(&pb)+7)/8;
748 }
749 #endif //CONFIG_ENCODERS
750
751 #ifdef CONFIG_DECODERS
752 static int sonic_decode_init(AVCodecContext *avctx)
753 {
754     SonicContext *s = avctx->priv_data;
755     GetBitContext gb;
756     int i, version;
757
758     s->channels = avctx->channels;
759     s->samplerate = avctx->sample_rate;
760
761     if (!avctx->extradata)
762     {
763         av_log(avctx, AV_LOG_ERROR, "No mandatory headers present\n");
764         return -1;
765     }
766
767     init_get_bits(&gb, avctx->extradata, avctx->extradata_size);
768
769     version = get_bits(&gb, 2);
770     if (version > 1)
771     {
772         av_log(avctx, AV_LOG_ERROR, "Unsupported Sonic version, please report\n");
773         return -1;
774     }
775
776     if (version == 1)
777     {
778         s->channels = get_bits(&gb, 2);
779         s->samplerate = samplerate_table[get_bits(&gb, 4)];
780         av_log(avctx, AV_LOG_INFO, "Sonicv2 chans: %d samprate: %d\n",
781             s->channels, s->samplerate);
782     }
783
784     if (s->channels > MAX_CHANNELS)
785     {
786         av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");
787         return -1;
788     }
789
790     s->lossless = get_bits1(&gb);
791     if (!s->lossless)
792         skip_bits(&gb, 3); // XXX FIXME
793     s->decorrelation = get_bits(&gb, 2);
794
795     s->downsampling = get_bits(&gb, 2);
796     s->num_taps = (get_bits(&gb, 5)+1)<<5;
797     if (get_bits1(&gb)) // XXX FIXME
798         av_log(avctx, AV_LOG_INFO, "Custom quant table\n");
799
800     s->block_align = (int)(2048.0*(s->samplerate/44100))/s->downsampling;
801     s->frame_size = s->channels*s->block_align*s->downsampling;
802 //    avctx->frame_size = s->block_align;
803
804     av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",
805         version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);
806
807     // generate taps
808     s->tap_quant = av_mallocz(4* s->num_taps);
809     for (i = 0; i < s->num_taps; i++)
810         s->tap_quant[i] = (int)(sqrt(i+1));
811
812     s->predictor_k = av_mallocz(4* s->num_taps);
813
814     for (i = 0; i < s->channels; i++)
815     {
816         s->predictor_state[i] = av_mallocz(4* s->num_taps);
817         if (!s->predictor_state[i])
818             return -1;
819     }
820
821     for (i = 0; i < s->channels; i++)
822     {
823         s->coded_samples[i] = av_mallocz(4* s->block_align);
824         if (!s->coded_samples[i])
825             return -1;
826     }
827     s->int_samples = av_mallocz(4* s->frame_size);
828
829     return 0;
830 }
831
832 static int sonic_decode_close(AVCodecContext *avctx)
833 {
834     SonicContext *s = avctx->priv_data;
835     int i;
836
837     av_free(s->int_samples);
838     av_free(s->tap_quant);
839     av_free(s->predictor_k);
840
841     for (i = 0; i < s->channels; i++)
842     {
843         av_free(s->predictor_state[i]);
844         av_free(s->coded_samples[i]);
845     }
846
847     return 0;
848 }
849
850 static int sonic_decode_frame(AVCodecContext *avctx,
851                             void *data, int *data_size,
852                             uint8_t *buf, int buf_size)
853 {
854     SonicContext *s = avctx->priv_data;
855     GetBitContext gb;
856     int i, quant, ch, j;
857     short *samples = data;
858
859     if (buf_size == 0) return 0;
860
861 //    av_log(NULL, AV_LOG_INFO, "buf_size: %d\n", buf_size);
862
863     init_get_bits(&gb, buf, buf_size*8);
864
865     intlist_read(&gb, s->predictor_k, s->num_taps, 0);
866
867     // dequantize
868     for (i = 0; i < s->num_taps; i++)
869         s->predictor_k[i] *= s->tap_quant[i];
870
871     if (s->lossless)
872         quant = 1;
873     else
874         quant = get_ue_golomb(&gb) * SAMPLE_FACTOR;
875
876 //    av_log(NULL, AV_LOG_INFO, "quant: %d\n", quant);
877
878     for (ch = 0; ch < s->channels; ch++)
879     {
880         int x = ch;
881
882         predictor_init_state(s->predictor_k, s->predictor_state[ch], s->num_taps);
883
884         intlist_read(&gb, s->coded_samples[ch], s->block_align, 1);
885
886         for (i = 0; i < s->block_align; i++)
887         {
888             for (j = 0; j < s->downsampling - 1; j++)
889             {
890                 s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, 0);
891                 x += s->channels;
892             }
893
894             s->int_samples[x] = predictor_calc_error(s->predictor_k, s->predictor_state[ch], s->num_taps, s->coded_samples[ch][i] * quant);
895             x += s->channels;
896         }
897
898         for (i = 0; i < s->num_taps; i++)
899             s->predictor_state[ch][i] = s->int_samples[s->frame_size - s->channels + ch - i*s->channels];
900     }
901
902     switch(s->decorrelation)
903     {
904         case MID_SIDE:
905             for (i = 0; i < s->frame_size; i += s->channels)
906             {
907                 s->int_samples[i+1] += shift(s->int_samples[i], 1);
908                 s->int_samples[i] -= s->int_samples[i+1];
909             }
910             break;
911         case LEFT_SIDE:
912             for (i = 0; i < s->frame_size; i += s->channels)
913                 s->int_samples[i+1] += s->int_samples[i];
914             break;
915         case RIGHT_SIDE:
916             for (i = 0; i < s->frame_size; i += s->channels)
917                 s->int_samples[i] += s->int_samples[i+1];
918             break;
919     }
920
921     if (!s->lossless)
922         for (i = 0; i < s->frame_size; i++)
923             s->int_samples[i] = shift(s->int_samples[i], SAMPLE_SHIFT);
924
925     // internal -> short
926     for (i = 0; i < s->frame_size; i++)
927     {
928         if (s->int_samples[i] > 32767)
929             samples[i] = 32767;
930         else if (s->int_samples[i] < -32768)
931             samples[i] = -32768;
932         else
933             samples[i] = s->int_samples[i];
934     }
935
936     align_get_bits(&gb);
937
938     *data_size = s->frame_size * 2;
939
940     return (get_bits_count(&gb)+7)/8;
941 }
942 #endif
943
944 #ifdef CONFIG_ENCODERS
945 AVCodec sonic_encoder = {
946     "sonic",
947     CODEC_TYPE_AUDIO,
948     CODEC_ID_SONIC,
949     sizeof(SonicContext),
950     sonic_encode_init,
951     sonic_encode_frame,
952     sonic_encode_close,
953     NULL,
954 };
955
956 AVCodec sonic_ls_encoder = {
957     "sonicls",
958     CODEC_TYPE_AUDIO,
959     CODEC_ID_SONIC_LS,
960     sizeof(SonicContext),
961     sonic_encode_init,
962     sonic_encode_frame,
963     sonic_encode_close,
964     NULL,
965 };
966 #endif
967
968 #ifdef CONFIG_DECODERS
969 AVCodec sonic_decoder = {
970     "sonic",
971     CODEC_TYPE_AUDIO,
972     CODEC_ID_SONIC,
973     sizeof(SonicContext),
974     sonic_decode_init,
975     NULL,
976     sonic_decode_close,
977     sonic_decode_frame,
978 };
979 #endif