]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/flacenc.c
stereo decorrelation support by (Justin Ruggles jruggle earthlink net>)
[frescor/ffmpeg.git] / libavcodec / flacenc.c
1 /**
2  * FLAC audio encoder
3  * Copyright (c) 2006  Justin Ruggles <jruggle@earthlink.net>
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
20 #include "avcodec.h"
21 #include "bitstream.h"
22 #include "crc.h"
23 #include "golomb.h"
24
25 #define FLAC_MAX_CH  8
26 #define FLAC_MIN_BLOCKSIZE  16
27 #define FLAC_MAX_BLOCKSIZE  65535
28
29 #define FLAC_SUBFRAME_CONSTANT  0
30 #define FLAC_SUBFRAME_VERBATIM  1
31 #define FLAC_SUBFRAME_FIXED     8
32 #define FLAC_SUBFRAME_LPC      32
33
34 #define FLAC_CHMODE_NOT_STEREO      0
35 #define FLAC_CHMODE_LEFT_RIGHT      1
36 #define FLAC_CHMODE_LEFT_SIDE       8
37 #define FLAC_CHMODE_RIGHT_SIDE      9
38 #define FLAC_CHMODE_MID_SIDE       10
39
40 #define FLAC_STREAMINFO_SIZE  34
41
42 typedef struct FlacSubframe {
43     int type;
44     int type_code;
45     int obits;
46     int order;
47     int32_t samples[FLAC_MAX_BLOCKSIZE];
48     int32_t residual[FLAC_MAX_BLOCKSIZE];
49 } FlacSubframe;
50
51 typedef struct FlacFrame {
52     FlacSubframe subframes[FLAC_MAX_CH];
53     int blocksize;
54     int bs_code[2];
55     uint8_t crc8;
56     int ch_mode;
57 } FlacFrame;
58
59 typedef struct FlacEncodeContext {
60     PutBitContext pb;
61     int channels;
62     int ch_code;
63     int samplerate;
64     int sr_code[2];
65     int blocksize;
66     int max_framesize;
67     uint32_t frame_count;
68     FlacFrame frame;
69 } FlacEncodeContext;
70
71 static const int flac_samplerates[16] = {
72     0, 0, 0, 0,
73     8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
74     0, 0, 0, 0
75 };
76
77 static const int flac_blocksizes[16] = {
78     0,
79     192,
80     576, 1152, 2304, 4608,
81     0, 0,
82     256, 512, 1024, 2048, 4096, 8192, 16384, 32768
83 };
84
85 /**
86  * Writes streaminfo metadata block to byte array
87  */
88 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
89 {
90     PutBitContext pb;
91
92     memset(header, 0, FLAC_STREAMINFO_SIZE);
93     init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
94
95     /* streaminfo metadata block */
96     put_bits(&pb, 16, s->blocksize);
97     put_bits(&pb, 16, s->blocksize);
98     put_bits(&pb, 24, 0);
99     put_bits(&pb, 24, s->max_framesize);
100     put_bits(&pb, 20, s->samplerate);
101     put_bits(&pb, 3, s->channels-1);
102     put_bits(&pb, 5, 15);       /* bits per sample - 1 */
103     flush_put_bits(&pb);
104     /* total samples = 0 */
105     /* MD5 signature = 0 */
106 }
107
108 #define BLOCK_TIME_MS 105
109
110 /**
111  * Sets blocksize based on samplerate
112  * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
113  */
114 static int select_blocksize(int samplerate)
115 {
116     int i;
117     int target;
118     int blocksize;
119
120     assert(samplerate > 0);
121     blocksize = flac_blocksizes[1];
122     target = (samplerate * BLOCK_TIME_MS) / 1000;
123     for(i=0; i<16; i++) {
124         if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
125             blocksize = flac_blocksizes[i];
126         }
127     }
128     return blocksize;
129 }
130
131 static int flac_encode_init(AVCodecContext *avctx)
132 {
133     int freq = avctx->sample_rate;
134     int channels = avctx->channels;
135     FlacEncodeContext *s = avctx->priv_data;
136     int i;
137     uint8_t *streaminfo;
138
139     if(avctx->sample_fmt != SAMPLE_FMT_S16) {
140         return -1;
141     }
142
143     if(channels < 1 || channels > FLAC_MAX_CH) {
144         return -1;
145     }
146     s->channels = channels;
147     s->ch_code = s->channels-1;
148
149     /* find samplerate in table */
150     if(freq < 1)
151         return -1;
152     for(i=4; i<12; i++) {
153         if(freq == flac_samplerates[i]) {
154             s->samplerate = flac_samplerates[i];
155             s->sr_code[0] = i;
156             s->sr_code[1] = 0;
157             break;
158         }
159     }
160     /* if not in table, samplerate is non-standard */
161     if(i == 12) {
162         if(freq % 1000 == 0 && freq < 255000) {
163             s->sr_code[0] = 12;
164             s->sr_code[1] = freq / 1000;
165         } else if(freq % 10 == 0 && freq < 655350) {
166             s->sr_code[0] = 14;
167             s->sr_code[1] = freq / 10;
168         } else if(freq < 65535) {
169             s->sr_code[0] = 13;
170             s->sr_code[1] = freq;
171         } else {
172             return -1;
173         }
174         s->samplerate = freq;
175     }
176
177     s->blocksize = select_blocksize(s->samplerate);
178     avctx->frame_size = s->blocksize;
179
180     /* set maximum encoded frame size in verbatim mode */
181     if(s->channels == 2) {
182         s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
183     } else {
184         s->max_framesize = 14 + (s->blocksize * s->channels * 2);
185     }
186
187     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
188     write_streaminfo(s, streaminfo);
189     avctx->extradata = streaminfo;
190     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
191
192     s->frame_count = 0;
193
194     avctx->coded_frame = avcodec_alloc_frame();
195     avctx->coded_frame->key_frame = 1;
196
197     return 0;
198 }
199
200 static void init_frame(FlacEncodeContext *s)
201 {
202     int i, ch;
203     FlacFrame *frame;
204
205     frame = &s->frame;
206
207     for(i=0; i<16; i++) {
208         if(s->blocksize == flac_blocksizes[i]) {
209             frame->blocksize = flac_blocksizes[i];
210             frame->bs_code[0] = i;
211             frame->bs_code[1] = 0;
212             break;
213         }
214     }
215     if(i == 16) {
216         frame->blocksize = s->blocksize;
217         if(frame->blocksize <= 256) {
218             frame->bs_code[0] = 6;
219             frame->bs_code[1] = frame->blocksize-1;
220         } else {
221             frame->bs_code[0] = 7;
222             frame->bs_code[1] = frame->blocksize-1;
223         }
224     }
225
226     for(ch=0; ch<s->channels; ch++) {
227         frame->subframes[ch].obits = 16;
228     }
229 }
230
231 /**
232  * Copy channel-interleaved input samples into separate subframes
233  */
234 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
235 {
236     int i, j, ch;
237     FlacFrame *frame;
238
239     frame = &s->frame;
240     for(i=0,j=0; i<frame->blocksize; i++) {
241         for(ch=0; ch<s->channels; ch++,j++) {
242             frame->subframes[ch].samples[i] = samples[j];
243         }
244     }
245 }
246
247 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
248 {
249     int i, best;
250     int32_t lt, rt;
251     uint64_t left, right, mid, side;
252     uint64_t score[4];
253
254     /* calculate sum of squares for each channel */
255     left = right = mid = side = 0;
256     for(i=2; i<n; i++) {
257         lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
258         rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
259         mid   += ABS((lt + rt) >> 1);
260         side  += ABS(lt - rt);
261         left  += ABS(lt);
262         right += ABS(rt);
263     }
264
265     /* calculate score for each mode */
266     score[0] = left  + right;
267     score[1] = left  +  side;
268     score[2] = right +  side;
269     score[3] = mid   +  side;
270
271     /* return mode with lowest score */
272     best = 0;
273     for(i=1; i<4; i++) {
274         if(score[i] < score[best]) {
275             best = i;
276         }
277     }
278     if(best == 0) {
279         return FLAC_CHMODE_LEFT_RIGHT;
280     } else if(best == 1) {
281         return FLAC_CHMODE_LEFT_SIDE;
282     } else if(best == 2) {
283         return FLAC_CHMODE_RIGHT_SIDE;
284     } else {
285         return FLAC_CHMODE_MID_SIDE;
286     }
287 }
288
289 /**
290  * Perform stereo channel decorrelation
291  */
292 static void channel_decorrelation(FlacEncodeContext *ctx)
293 {
294     FlacFrame *frame;
295     int32_t *left, *right;
296     int i, n;
297
298     frame = &ctx->frame;
299     n = frame->blocksize;
300     left  = frame->subframes[0].samples;
301     right = frame->subframes[1].samples;
302
303     if(ctx->channels != 2) {
304         frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
305         return;
306     }
307
308     frame->ch_mode = estimate_stereo_mode(left, right, n);
309
310     /* perform decorrelation and adjust bits-per-sample */
311     if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
312         return;
313     }
314     if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
315         int32_t tmp;
316         for(i=0; i<n; i++) {
317             tmp = left[i];
318             left[i] = (tmp + right[i]) >> 1;
319             right[i] = tmp - right[i];
320         }
321         frame->subframes[1].obits++;
322     } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
323         for(i=0; i<n; i++) {
324             right[i] = left[i] - right[i];
325         }
326         frame->subframes[1].obits++;
327     } else {
328         for(i=0; i<n; i++) {
329             left[i] -= right[i];
330         }
331         frame->subframes[0].obits++;
332     }
333 }
334
335 static void encode_residual_verbatim(FlacEncodeContext *s, int ch)
336 {
337     FlacFrame *frame;
338     FlacSubframe *sub;
339     int32_t *res;
340     int32_t *smp;
341     int n;
342
343     frame = &s->frame;
344     sub = &frame->subframes[ch];
345     res = sub->residual;
346     smp = sub->samples;
347     n = frame->blocksize;
348
349     sub->order = 0;
350     sub->type = FLAC_SUBFRAME_VERBATIM;
351     sub->type_code = sub->type;
352
353     memcpy(res, smp, n * sizeof(int32_t));
354 }
355
356 static void encode_residual_fixed(int32_t *res, int32_t *smp, int n, int order)
357 {
358     int i;
359
360     for(i=0; i<order; i++) {
361         res[i] = smp[i];
362     }
363
364     if(order==0){
365         for(i=order; i<n; i++)
366             res[i]= smp[i];
367     }else if(order==1){
368         for(i=order; i<n; i++)
369             res[i]= smp[i] - smp[i-1];
370     }else if(order==2){
371         for(i=order; i<n; i++)
372             res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
373     }else if(order==3){
374         for(i=order; i<n; i++)
375             res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
376     }else{
377         for(i=order; i<n; i++)
378             res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
379     }
380 }
381
382 static void encode_residual(FlacEncodeContext *s, int ch)
383 {
384     FlacFrame *frame;
385     FlacSubframe *sub;
386     int32_t *res;
387     int32_t *smp;
388     int n;
389
390     frame = &s->frame;
391     sub = &frame->subframes[ch];
392     res = sub->residual;
393     smp = sub->samples;
394     n = frame->blocksize;
395
396     sub->order = 2;
397     sub->type = FLAC_SUBFRAME_FIXED;
398     sub->type_code = sub->type | sub->order;
399     encode_residual_fixed(res, smp, n, sub->order);
400 }
401
402 static void
403 put_sbits(PutBitContext *pb, int bits, int32_t val)
404 {
405     assert(bits >= 0 && bits <= 31);
406
407     put_bits(pb, bits, val & ((1<<bits)-1));
408 }
409
410 static void
411 write_utf8(PutBitContext *pb, uint32_t val)
412 {
413     int bytes, shift;
414
415     if(val < 0x80){
416         put_bits(pb, 8, val);
417         return;
418     }
419
420     bytes= (av_log2(val)+4) / 5;
421     shift = (bytes - 1) * 6;
422     put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
423     while(shift >= 6){
424         shift -= 6;
425         put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
426     }
427 }
428
429 static void
430 output_frame_header(FlacEncodeContext *s)
431 {
432     FlacFrame *frame;
433     int crc;
434
435     frame = &s->frame;
436
437     put_bits(&s->pb, 16, 0xFFF8);
438     put_bits(&s->pb, 4, frame->bs_code[0]);
439     put_bits(&s->pb, 4, s->sr_code[0]);
440     if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
441         put_bits(&s->pb, 4, s->ch_code);
442     } else {
443         put_bits(&s->pb, 4, frame->ch_mode);
444     }
445     put_bits(&s->pb, 3, 4); /* bits-per-sample code */
446     put_bits(&s->pb, 1, 0);
447     write_utf8(&s->pb, s->frame_count);
448     if(frame->bs_code[0] == 6) {
449         put_bits(&s->pb, 8, frame->bs_code[1]);
450     } else if(frame->bs_code[0] == 7) {
451         put_bits(&s->pb, 16, frame->bs_code[1]);
452     }
453     if(s->sr_code[0] == 12) {
454         put_bits(&s->pb, 8, s->sr_code[1]);
455     } else if(s->sr_code[0] > 12) {
456         put_bits(&s->pb, 16, s->sr_code[1]);
457     }
458     flush_put_bits(&s->pb);
459     crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
460     put_bits(&s->pb, 8, crc);
461 }
462
463 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
464 {
465     int i;
466     FlacFrame *frame;
467     FlacSubframe *sub;
468     int32_t res;
469
470     frame = &s->frame;
471     sub = &frame->subframes[ch];
472
473     for(i=0; i<frame->blocksize; i++) {
474         res = sub->residual[i];
475         put_sbits(&s->pb, sub->obits, res);
476     }
477 }
478
479 static void
480 output_residual(FlacEncodeContext *ctx, int ch)
481 {
482     int i, j, p;
483     int k, porder, psize, res_cnt;
484     FlacFrame *frame;
485     FlacSubframe *sub;
486
487     frame = &ctx->frame;
488     sub = &frame->subframes[ch];
489
490     /* rice-encoded block */
491     put_bits(&ctx->pb, 2, 0);
492
493     /* partition order */
494     porder = 0;
495     psize = frame->blocksize;
496     //porder = sub->rc.porder;
497     //psize = frame->blocksize >> porder;
498     put_bits(&ctx->pb, 4, porder);
499     res_cnt = psize - sub->order;
500
501     /* residual */
502     j = sub->order;
503     for(p=0; p<(1 << porder); p++) {
504         //k = sub->rc.params[p];
505         k = 9;
506         put_bits(&ctx->pb, 4, k);
507         if(p == 1) res_cnt = psize;
508         for(i=0; i<res_cnt && j<frame->blocksize; i++, j++) {
509             set_sr_golomb_flac(&ctx->pb, sub->residual[j], k, INT32_MAX, 0);
510         }
511     }
512 }
513
514 static void
515 output_subframe_fixed(FlacEncodeContext *ctx, int ch)
516 {
517     int i;
518     FlacFrame *frame;
519     FlacSubframe *sub;
520
521     frame = &ctx->frame;
522     sub = &frame->subframes[ch];
523
524     /* warm-up samples */
525     for(i=0; i<sub->order; i++) {
526         put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
527     }
528
529     /* residual */
530     output_residual(ctx, ch);
531 }
532
533 static void output_subframes(FlacEncodeContext *s)
534 {
535     FlacFrame *frame;
536     FlacSubframe *sub;
537     int ch;
538
539     frame = &s->frame;
540
541     for(ch=0; ch<s->channels; ch++) {
542         sub = &frame->subframes[ch];
543
544         /* subframe header */
545         put_bits(&s->pb, 1, 0);
546         put_bits(&s->pb, 6, sub->type_code);
547         put_bits(&s->pb, 1, 0); /* no wasted bits */
548
549         /* subframe */
550         if(sub->type == FLAC_SUBFRAME_VERBATIM) {
551             output_subframe_verbatim(s, ch);
552         } else {
553             output_subframe_fixed(s, ch);
554         }
555     }
556 }
557
558 static void output_frame_footer(FlacEncodeContext *s)
559 {
560     int crc;
561     flush_put_bits(&s->pb);
562     crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
563     put_bits(&s->pb, 16, crc);
564     flush_put_bits(&s->pb);
565 }
566
567 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
568                              int buf_size, void *data)
569 {
570     int ch;
571     FlacEncodeContext *s;
572     int16_t *samples = data;
573     int out_bytes;
574
575     s = avctx->priv_data;
576
577     s->blocksize = avctx->frame_size;
578     init_frame(s);
579
580     copy_samples(s, samples);
581
582     channel_decorrelation(s);
583
584     for(ch=0; ch<s->channels; ch++) {
585         encode_residual(s, ch);
586     }
587     init_put_bits(&s->pb, frame, buf_size);
588     output_frame_header(s);
589     output_subframes(s);
590     output_frame_footer(s);
591     out_bytes = put_bits_count(&s->pb) >> 3;
592
593     if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
594         /* frame too large. use verbatim mode */
595         for(ch=0; ch<s->channels; ch++) {
596             encode_residual_verbatim(s, ch);
597         }
598         init_put_bits(&s->pb, frame, buf_size);
599         output_frame_header(s);
600         output_subframes(s);
601         output_frame_footer(s);
602         out_bytes = put_bits_count(&s->pb) >> 3;
603
604         if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
605             /* still too large. must be an error. */
606             av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
607             return -1;
608         }
609     }
610
611     s->frame_count++;
612     return out_bytes;
613 }
614
615 static int flac_encode_close(AVCodecContext *avctx)
616 {
617     av_freep(&avctx->extradata);
618     avctx->extradata_size = 0;
619     av_freep(&avctx->coded_frame);
620     return 0;
621 }
622
623 AVCodec flac_encoder = {
624     "flac",
625     CODEC_TYPE_AUDIO,
626     CODEC_ID_FLAC,
627     sizeof(FlacEncodeContext),
628     flac_encode_init,
629     flac_encode_frame,
630     flac_encode_close,
631     NULL,
632     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
633 };