]> rtime.felk.cvut.cz Git - frescor/ffmpeg.git/blob - libavcodec/flacenc.c
simplify & optimize things a little
[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     s->max_framesize = 14 + (s->blocksize * s->channels * 2);
181
182     streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
183     write_streaminfo(s, streaminfo);
184     avctx->extradata = streaminfo;
185     avctx->extradata_size = FLAC_STREAMINFO_SIZE;
186
187     s->frame_count = 0;
188
189     avctx->coded_frame = avcodec_alloc_frame();
190     avctx->coded_frame->key_frame = 1;
191
192     return 0;
193 }
194
195 static int init_frame(FlacEncodeContext *s)
196 {
197     int i, ch;
198     FlacFrame *frame;
199
200     frame = &s->frame;
201
202     for(i=0; i<16; i++) {
203         if(s->blocksize == flac_blocksizes[i]) {
204             frame->blocksize = flac_blocksizes[i];
205             frame->bs_code[0] = i;
206             frame->bs_code[1] = 0;
207             break;
208         }
209     }
210     if(i == 16) {
211         frame->blocksize = s->blocksize;
212         if(frame->blocksize <= 256) {
213             frame->bs_code[0] = 6;
214             frame->bs_code[1] = frame->blocksize-1;
215         } else {
216             frame->bs_code[0] = 7;
217             frame->bs_code[1] = frame->blocksize-1;
218         }
219     }
220
221     for(ch=0; ch<s->channels; ch++) {
222         frame->subframes[ch].obits = 16;
223     }
224     if(s->channels == 2) {
225         frame->ch_mode = FLAC_CHMODE_LEFT_RIGHT;
226     } else {
227         frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
228     }
229
230     return 0;
231 }
232
233 /**
234  * Copy channel-interleaved input samples into separate subframes
235  */
236 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
237 {
238     int i, j, ch;
239     FlacFrame *frame;
240
241     frame = &s->frame;
242     for(i=0,j=0; i<frame->blocksize; i++) {
243         for(ch=0; ch<s->channels; ch++,j++) {
244             frame->subframes[ch].samples[i] = samples[j];
245         }
246     }
247 }
248
249 static void encode_residual_verbatim(FlacEncodeContext *s, int ch)
250 {
251     FlacFrame *frame;
252     FlacSubframe *sub;
253     int32_t *res;
254     int32_t *smp;
255     int n;
256
257     frame = &s->frame;
258     sub = &frame->subframes[ch];
259     res = sub->residual;
260     smp = sub->samples;
261     n = frame->blocksize;
262
263     sub->order = 0;
264     sub->type = FLAC_SUBFRAME_VERBATIM;
265     sub->type_code = sub->type;
266
267     memcpy(res, smp, n * sizeof(int32_t));
268 }
269
270 static void encode_residual_fixed(int32_t *res, int32_t *smp, int n, int order)
271 {
272     int i;
273
274     for(i=0; i<order; i++) {
275         res[i] = smp[i];
276     }
277
278     if(order==0){
279         for(i=order; i<n; i++)
280             res[i]= smp[i];
281     }else if(order==1){
282         for(i=order; i<n; i++)
283             res[i]= smp[i] - smp[i-1];
284     }else if(order==2){
285         for(i=order; i<n; i++)
286             res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
287     }else if(order==3){
288         for(i=order; i<n; i++)
289             res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
290     }else{
291         for(i=order; i<n; i++)
292             res[i]= smp[i] - 4*smp[i-1] + 6*smp[i-2] - 4*smp[i-3] + smp[i-4];
293     }
294 }
295
296 static void encode_residual(FlacEncodeContext *s, int ch)
297 {
298     FlacFrame *frame;
299     FlacSubframe *sub;
300     int32_t *res;
301     int32_t *smp;
302     int n;
303
304     frame = &s->frame;
305     sub = &frame->subframes[ch];
306     res = sub->residual;
307     smp = sub->samples;
308     n = frame->blocksize;
309
310     sub->order = 2;
311     sub->type = FLAC_SUBFRAME_FIXED;
312     sub->type_code = sub->type | sub->order;
313     encode_residual_fixed(res, smp, n, sub->order);
314 }
315
316 static void
317 put_sbits(PutBitContext *pb, int bits, int32_t val)
318 {
319     assert(bits >= 0 && bits <= 31);
320
321     put_bits(pb, bits, val & ((1<<bits)-1));
322 }
323
324 static void
325 write_utf8(PutBitContext *pb, uint32_t val)
326 {
327     int bytes, shift;
328
329     if(val < 0x80){
330         put_bits(pb, 8, val);
331         return;
332     }
333
334     bytes= (av_log2(val)-1) / 5;
335     shift = (bytes - 1) * 6;
336     put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
337     while(shift >= 6){
338         shift -= 6;
339         put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
340     }
341 }
342
343 static void
344 output_frame_header(FlacEncodeContext *s)
345 {
346     FlacFrame *frame;
347     int crc;
348
349     frame = &s->frame;
350
351     put_bits(&s->pb, 16, 0xFFF8);
352     put_bits(&s->pb, 4, frame->bs_code[0]);
353     put_bits(&s->pb, 4, s->sr_code[0]);
354     if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
355         put_bits(&s->pb, 4, s->ch_code);
356     } else {
357         put_bits(&s->pb, 4, frame->ch_mode);
358     }
359     put_bits(&s->pb, 3, 4); /* bits-per-sample code */
360     put_bits(&s->pb, 1, 0);
361     write_utf8(&s->pb, s->frame_count);
362     if(frame->bs_code[1] > 0) {
363         if(frame->bs_code[1] < 256) {
364             put_bits(&s->pb, 8, frame->bs_code[1]);
365         } else {
366             put_bits(&s->pb, 16, frame->bs_code[1]);
367         }
368     }
369     if(s->sr_code[1] > 0) {
370         if(s->sr_code[1] < 256) {
371             put_bits(&s->pb, 8, s->sr_code[1]);
372         } else {
373             put_bits(&s->pb, 16, s->sr_code[1]);
374         }
375     }
376     flush_put_bits(&s->pb);
377     crc = av_crc(av_crc07, 0, s->pb.buf, put_bits_count(&s->pb)>>3);
378     put_bits(&s->pb, 8, crc);
379 }
380
381 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
382 {
383     int i;
384     FlacFrame *frame;
385     FlacSubframe *sub;
386     int32_t res;
387
388     frame = &s->frame;
389     sub = &frame->subframes[ch];
390
391     for(i=0; i<frame->blocksize; i++) {
392         res = sub->residual[i];
393         put_sbits(&s->pb, sub->obits, res);
394     }
395 }
396
397 static void
398 output_residual(FlacEncodeContext *ctx, int ch)
399 {
400     int i, j, p;
401     int k, porder, psize, res_cnt;
402     FlacFrame *frame;
403     FlacSubframe *sub;
404
405     frame = &ctx->frame;
406     sub = &frame->subframes[ch];
407
408     /* rice-encoded block */
409     put_bits(&ctx->pb, 2, 0);
410
411     /* partition order */
412     porder = 0;
413     psize = frame->blocksize;
414     //porder = sub->rc.porder;
415     //psize = frame->blocksize >> porder;
416     put_bits(&ctx->pb, 4, porder);
417     res_cnt = psize - sub->order;
418
419     /* residual */
420     j = sub->order;
421     for(p=0; p<(1 << porder); p++) {
422         //k = sub->rc.params[p];
423         k = 9;
424         put_bits(&ctx->pb, 4, k);
425         if(p == 1) res_cnt = psize;
426         for(i=0; i<res_cnt && j<frame->blocksize; i++, j++) {
427             set_sr_golomb_flac(&ctx->pb, sub->residual[j], k, INT32_MAX, 0);
428         }
429     }
430 }
431
432 static void
433 output_subframe_fixed(FlacEncodeContext *ctx, int ch)
434 {
435     int i;
436     FlacFrame *frame;
437     FlacSubframe *sub;
438
439     frame = &ctx->frame;
440     sub = &frame->subframes[ch];
441
442     /* warm-up samples */
443     for(i=0; i<sub->order; i++) {
444         put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
445     }
446
447     /* residual */
448     output_residual(ctx, ch);
449 }
450
451 static void output_subframes(FlacEncodeContext *s)
452 {
453     FlacFrame *frame;
454     FlacSubframe *sub;
455     int ch;
456
457     frame = &s->frame;
458
459     for(ch=0; ch<s->channels; ch++) {
460         sub = &frame->subframes[ch];
461
462         /* subframe header */
463         put_bits(&s->pb, 1, 0);
464         put_bits(&s->pb, 6, sub->type_code);
465         put_bits(&s->pb, 1, 0); /* no wasted bits */
466
467         /* subframe */
468         if(sub->type == FLAC_SUBFRAME_VERBATIM) {
469             output_subframe_verbatim(s, ch);
470         } else {
471             output_subframe_fixed(s, ch);
472         }
473     }
474 }
475
476 static void output_frame_footer(FlacEncodeContext *s)
477 {
478     int crc;
479     flush_put_bits(&s->pb);
480     crc = bswap_16(av_crc(av_crc8005, 0, s->pb.buf, put_bits_count(&s->pb)>>3));
481     put_bits(&s->pb, 16, crc);
482     flush_put_bits(&s->pb);
483 }
484
485 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
486                              int buf_size, void *data)
487 {
488     int ch;
489     FlacEncodeContext *s;
490     int16_t *samples = data;
491     int out_bytes;
492
493     s = avctx->priv_data;
494
495     s->blocksize = avctx->frame_size;
496     if(init_frame(s)) {
497         return 0;
498     }
499
500     copy_samples(s, samples);
501
502     for(ch=0; ch<s->channels; ch++) {
503         encode_residual(s, ch);
504     }
505     init_put_bits(&s->pb, frame, buf_size);
506     output_frame_header(s);
507     output_subframes(s);
508     output_frame_footer(s);
509     out_bytes = put_bits_count(&s->pb) >> 3;
510
511     if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
512         /* frame too large. use verbatim mode */
513         for(ch=0; ch<s->channels; ch++) {
514             encode_residual_verbatim(s, ch);
515         }
516         init_put_bits(&s->pb, frame, buf_size);
517         output_frame_header(s);
518         output_subframes(s);
519         output_frame_footer(s);
520         out_bytes = put_bits_count(&s->pb) >> 3;
521
522         if(out_bytes > s->max_framesize || out_bytes >= buf_size) {
523             /* still too large. must be an error. */
524             av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
525             return -1;
526         }
527     }
528
529     s->frame_count++;
530     return out_bytes;
531 }
532
533 static int flac_encode_close(AVCodecContext *avctx)
534 {
535     av_freep(&avctx->coded_frame);
536     return 0;
537 }
538
539 AVCodec flac_encoder = {
540     "flac",
541     CODEC_TYPE_AUDIO,
542     CODEC_ID_FLAC,
543     sizeof(FlacEncodeContext),
544     flac_encode_init,
545     flac_encode_frame,
546     flac_encode_close,
547     NULL,
548     .capabilities = CODEC_CAP_SMALL_LAST_FRAME,
549 };