3 * Copyright (c) 2006 Justin Ruggles <jruggle@earthlink.net>
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.
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.
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
21 #include "bitstream.h"
26 #define FLAC_MIN_BLOCKSIZE 16
27 #define FLAC_MAX_BLOCKSIZE 65535
29 #define FLAC_SUBFRAME_CONSTANT 0
30 #define FLAC_SUBFRAME_VERBATIM 1
31 #define FLAC_SUBFRAME_FIXED 8
32 #define FLAC_SUBFRAME_LPC 32
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
40 #define FLAC_STREAMINFO_SIZE 34
42 typedef struct FlacSubframe {
47 int32_t samples[FLAC_MAX_BLOCKSIZE];
48 int32_t residual[FLAC_MAX_BLOCKSIZE];
51 typedef struct FlacFrame {
52 FlacSubframe subframes[FLAC_MAX_CH];
59 typedef struct FlacEncodeContext {
71 static const int flac_samplerates[16] = {
73 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
77 static const int flac_blocksizes[16] = {
80 576, 1152, 2304, 4608,
82 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
86 * Writes streaminfo metadata block to byte array
88 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
92 memset(header, 0, FLAC_STREAMINFO_SIZE);
93 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
95 /* streaminfo metadata block */
96 put_bits(&pb, 16, s->blocksize);
97 put_bits(&pb, 16, s->blocksize);
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 */
104 /* total samples = 0 */
105 /* MD5 signature = 0 */
108 #define BLOCK_TIME_MS 105
111 * Sets blocksize based on samplerate
112 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
114 static int select_blocksize(int samplerate)
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];
131 static int flac_encode_init(AVCodecContext *avctx)
133 int freq = avctx->sample_rate;
134 int channels = avctx->channels;
135 FlacEncodeContext *s = avctx->priv_data;
139 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
143 if(channels < 1 || channels > FLAC_MAX_CH) {
146 s->channels = channels;
147 s->ch_code = s->channels-1;
149 /* find samplerate in table */
152 for(i=4; i<12; i++) {
153 if(freq == flac_samplerates[i]) {
154 s->samplerate = flac_samplerates[i];
160 /* if not in table, samplerate is non-standard */
162 if(freq % 1000 == 0 && freq < 255000) {
164 s->sr_code[1] = freq / 1000;
165 } else if(freq % 10 == 0 && freq < 655350) {
167 s->sr_code[1] = freq / 10;
168 } else if(freq < 65535) {
170 s->sr_code[1] = freq;
174 s->samplerate = freq;
177 s->blocksize = select_blocksize(s->samplerate);
178 avctx->frame_size = s->blocksize;
180 /* set maximum encoded frame size in verbatim mode */
181 if(s->channels == 2) {
182 s->max_framesize = 14 + ((s->blocksize * 33 + 7) >> 3);
184 s->max_framesize = 14 + (s->blocksize * s->channels * 2);
187 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
188 write_streaminfo(s, streaminfo);
189 avctx->extradata = streaminfo;
190 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
194 avctx->coded_frame = avcodec_alloc_frame();
195 avctx->coded_frame->key_frame = 1;
200 static void init_frame(FlacEncodeContext *s)
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;
216 frame->blocksize = s->blocksize;
217 if(frame->blocksize <= 256) {
218 frame->bs_code[0] = 6;
219 frame->bs_code[1] = frame->blocksize-1;
221 frame->bs_code[0] = 7;
222 frame->bs_code[1] = frame->blocksize-1;
226 for(ch=0; ch<s->channels; ch++) {
227 frame->subframes[ch].obits = 16;
232 * Copy channel-interleaved input samples into separate subframes
234 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
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];
247 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
251 uint64_t left, right, mid, side;
254 /* calculate sum of squares for each channel */
255 left = right = mid = side = 0;
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);
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;
271 /* return mode with lowest score */
274 if(score[i] < score[best]) {
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;
285 return FLAC_CHMODE_MID_SIDE;
290 * Perform stereo channel decorrelation
292 static void channel_decorrelation(FlacEncodeContext *ctx)
295 int32_t *left, *right;
299 n = frame->blocksize;
300 left = frame->subframes[0].samples;
301 right = frame->subframes[1].samples;
303 if(ctx->channels != 2) {
304 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
308 frame->ch_mode = estimate_stereo_mode(left, right, n);
310 /* perform decorrelation and adjust bits-per-sample */
311 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
314 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
318 left[i] = (tmp + right[i]) >> 1;
319 right[i] = tmp - right[i];
321 frame->subframes[1].obits++;
322 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
324 right[i] = left[i] - right[i];
326 frame->subframes[1].obits++;
331 frame->subframes[0].obits++;
335 static void encode_residual_verbatim(FlacEncodeContext *s, int ch)
344 sub = &frame->subframes[ch];
347 n = frame->blocksize;
350 sub->type = FLAC_SUBFRAME_VERBATIM;
351 sub->type_code = sub->type;
353 memcpy(res, smp, n * sizeof(int32_t));
356 static void encode_residual_fixed(int32_t *res, int32_t *smp, int n, int order)
360 for(i=0; i<order; i++) {
365 for(i=order; i<n; i++)
368 for(i=order; i<n; i++)
369 res[i]= smp[i] - smp[i-1];
371 for(i=order; i<n; i++)
372 res[i]= smp[i] - 2*smp[i-1] + smp[i-2];
374 for(i=order; i<n; i++)
375 res[i]= smp[i] - 3*smp[i-1] + 3*smp[i-2] - smp[i-3];
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];
382 static void encode_residual(FlacEncodeContext *s, int ch)
391 sub = &frame->subframes[ch];
394 n = frame->blocksize;
397 sub->type = FLAC_SUBFRAME_FIXED;
398 sub->type_code = sub->type | sub->order;
399 encode_residual_fixed(res, smp, n, sub->order);
403 put_sbits(PutBitContext *pb, int bits, int32_t val)
405 assert(bits >= 0 && bits <= 31);
407 put_bits(pb, bits, val & ((1<<bits)-1));
411 write_utf8(PutBitContext *pb, uint32_t val)
416 put_bits(pb, 8, val);
420 bytes= (av_log2(val)+4) / 5;
421 shift = (bytes - 1) * 6;
422 put_bits(pb, 8, (256 - (256>>bytes)) | (val >> shift));
425 put_bits(pb, 8, 0x80 | ((val >> shift) & 0x3F));
430 output_frame_header(FlacEncodeContext *s)
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);
443 put_bits(&s->pb, 4, frame->ch_mode);
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]);
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]);
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);
463 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
471 sub = &frame->subframes[ch];
473 for(i=0; i<frame->blocksize; i++) {
474 res = sub->residual[i];
475 put_sbits(&s->pb, sub->obits, res);
480 output_residual(FlacEncodeContext *ctx, int ch)
483 int k, porder, psize, res_cnt;
488 sub = &frame->subframes[ch];
490 /* rice-encoded block */
491 put_bits(&ctx->pb, 2, 0);
493 /* partition order */
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;
503 for(p=0; p<(1 << porder); p++) {
504 //k = sub->rc.params[p];
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);
515 output_subframe_fixed(FlacEncodeContext *ctx, int ch)
522 sub = &frame->subframes[ch];
524 /* warm-up samples */
525 for(i=0; i<sub->order; i++) {
526 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
530 output_residual(ctx, ch);
533 static void output_subframes(FlacEncodeContext *s)
541 for(ch=0; ch<s->channels; ch++) {
542 sub = &frame->subframes[ch];
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 */
550 if(sub->type == FLAC_SUBFRAME_VERBATIM) {
551 output_subframe_verbatim(s, ch);
553 output_subframe_fixed(s, ch);
558 static void output_frame_footer(FlacEncodeContext *s)
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);
567 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
568 int buf_size, void *data)
571 FlacEncodeContext *s;
572 int16_t *samples = data;
575 s = avctx->priv_data;
577 s->blocksize = avctx->frame_size;
580 copy_samples(s, samples);
582 channel_decorrelation(s);
584 for(ch=0; ch<s->channels; ch++) {
585 encode_residual(s, ch);
587 init_put_bits(&s->pb, frame, buf_size);
588 output_frame_header(s);
590 output_frame_footer(s);
591 out_bytes = put_bits_count(&s->pb) >> 3;
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);
598 init_put_bits(&s->pb, frame, buf_size);
599 output_frame_header(s);
601 output_frame_footer(s);
602 out_bytes = put_bits_count(&s->pb) >> 3;
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");
615 static int flac_encode_close(AVCodecContext *avctx)
617 av_freep(&avctx->extradata);
618 avctx->extradata_size = 0;
619 av_freep(&avctx->coded_frame);
623 AVCodec flac_encoder = {
627 sizeof(FlacEncodeContext),
632 .capabilities = CODEC_CAP_SMALL_LAST_FRAME,