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