d1002f381422cbac1cedfd17bc9d4877303b0f53
[libav.git] / libavcodec / flacenc.c
1 /**
2 * FLAC audio encoder
3 * Copyright (c) 2006 Justin Ruggles <justin.ruggles@gmail.com>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "libavutil/crc.h"
23 #include "libavutil/lls.h"
24 #include "avcodec.h"
25 #include "bitstream.h"
26 #include "dsputil.h"
27 #include "golomb.h"
28 #include "lpc.h"
29
30 #define FLAC_MAX_CH 8
31 #define FLAC_MIN_BLOCKSIZE 16
32 #define FLAC_MAX_BLOCKSIZE 65535
33
34 #define FLAC_SUBFRAME_CONSTANT 0
35 #define FLAC_SUBFRAME_VERBATIM 1
36 #define FLAC_SUBFRAME_FIXED 8
37 #define FLAC_SUBFRAME_LPC 32
38
39 #define FLAC_CHMODE_NOT_STEREO 0
40 #define FLAC_CHMODE_LEFT_RIGHT 1
41 #define FLAC_CHMODE_LEFT_SIDE 8
42 #define FLAC_CHMODE_RIGHT_SIDE 9
43 #define FLAC_CHMODE_MID_SIDE 10
44
45 #define FLAC_STREAMINFO_SIZE 34
46
47 #define MAX_FIXED_ORDER 4
48 #define MAX_PARTITION_ORDER 8
49 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
50 #define MAX_LPC_PRECISION 15
51 #define MAX_LPC_SHIFT 15
52 #define MAX_RICE_PARAM 14
53
54 typedef struct CompressionOptions {
55 int compression_level;
56 int block_time_ms;
57 int use_lpc;
58 int lpc_coeff_precision;
59 int min_prediction_order;
60 int max_prediction_order;
61 int prediction_order_method;
62 int min_partition_order;
63 int max_partition_order;
64 } CompressionOptions;
65
66 typedef struct RiceContext {
67 int porder;
68 int params[MAX_PARTITIONS];
69 } RiceContext;
70
71 typedef struct FlacSubframe {
72 int type;
73 int type_code;
74 int obits;
75 int order;
76 int32_t coefs[MAX_LPC_ORDER];
77 int shift;
78 RiceContext rc;
79 int32_t samples[FLAC_MAX_BLOCKSIZE];
80 int32_t residual[FLAC_MAX_BLOCKSIZE+1];
81 } FlacSubframe;
82
83 typedef struct FlacFrame {
84 FlacSubframe subframes[FLAC_MAX_CH];
85 int blocksize;
86 int bs_code[2];
87 uint8_t crc8;
88 int ch_mode;
89 } FlacFrame;
90
91 typedef struct FlacEncodeContext {
92 PutBitContext pb;
93 int channels;
94 int ch_code;
95 int samplerate;
96 int sr_code[2];
97 int max_framesize;
98 uint32_t frame_count;
99 uint64_t sample_count;
100 FlacFrame frame;
101 CompressionOptions options;
102 AVCodecContext *avctx;
103 DSPContext dsp;
104 } FlacEncodeContext;
105
106 static const int flac_samplerates[16] = {
107 0, 0, 0, 0,
108 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000,
109 0, 0, 0, 0
110 };
111
112 static const int flac_blocksizes[16] = {
113 0,
114 192,
115 576, 1152, 2304, 4608,
116 0, 0,
117 256, 512, 1024, 2048, 4096, 8192, 16384, 32768
118 };
119
120 /**
121 * Writes streaminfo metadata block to byte array
122 */
123 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
124 {
125 PutBitContext pb;
126
127 memset(header, 0, FLAC_STREAMINFO_SIZE);
128 init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
129
130 /* streaminfo metadata block */
131 put_bits(&pb, 16, s->avctx->frame_size);
132 put_bits(&pb, 16, s->avctx->frame_size);
133 put_bits(&pb, 24, 0);
134 put_bits(&pb, 24, s->max_framesize);
135 put_bits(&pb, 20, s->samplerate);
136 put_bits(&pb, 3, s->channels-1);
137 put_bits(&pb, 5, 15); /* bits per sample - 1 */
138 /* write 36-bit sample count in 2 put_bits() calls */
139 put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
140 put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
141 flush_put_bits(&pb);
142 /* MD5 signature = 0 */
143 }
144
145 /**
146 * Sets blocksize based on samplerate
147 * Chooses the closest predefined blocksize >= BLOCK_TIME_MS milliseconds
148 */
149 static int select_blocksize(int samplerate, int block_time_ms)
150 {
151 int i;
152 int target;
153 int blocksize;
154
155 assert(samplerate > 0);
156 blocksize = flac_blocksizes[1];
157 target = (samplerate * block_time_ms) / 1000;
158 for(i=0; i<16; i++) {
159 if(target >= flac_blocksizes[i] && flac_blocksizes[i] > blocksize) {
160 blocksize = flac_blocksizes[i];
161 }
162 }
163 return blocksize;
164 }
165
166 static av_cold int flac_encode_init(AVCodecContext *avctx)
167 {
168 int freq = avctx->sample_rate;
169 int channels = avctx->channels;
170 FlacEncodeContext *s = avctx->priv_data;
171 int i, level;
172 uint8_t *streaminfo;
173
174 s->avctx = avctx;
175
176 dsputil_init(&s->dsp, avctx);
177
178 if(avctx->sample_fmt != SAMPLE_FMT_S16) {
179 return -1;
180 }
181
182 if(channels < 1 || channels > FLAC_MAX_CH) {
183 return -1;
184 }
185 s->channels = channels;
186 s->ch_code = s->channels-1;
187
188 /* find samplerate in table */
189 if(freq < 1)
190 return -1;
191 for(i=4; i<12; i++) {
192 if(freq == flac_samplerates[i]) {
193 s->samplerate = flac_samplerates[i];
194 s->sr_code[0] = i;
195 s->sr_code[1] = 0;
196 break;
197 }
198 }
199 /* if not in table, samplerate is non-standard */
200 if(i == 12) {
201 if(freq % 1000 == 0 && freq < 255000) {
202 s->sr_code[0] = 12;
203 s->sr_code[1] = freq / 1000;
204 } else if(freq % 10 == 0 && freq < 655350) {
205 s->sr_code[0] = 14;
206 s->sr_code[1] = freq / 10;
207 } else if(freq < 65535) {
208 s->sr_code[0] = 13;
209 s->sr_code[1] = freq;
210 } else {
211 return -1;
212 }
213 s->samplerate = freq;
214 }
215
216 /* set compression option defaults based on avctx->compression_level */
217 if(avctx->compression_level < 0) {
218 s->options.compression_level = 5;
219 } else {
220 s->options.compression_level = avctx->compression_level;
221 }
222 av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", s->options.compression_level);
223
224 level= s->options.compression_level;
225 if(level > 12) {
226 av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
227 s->options.compression_level);
228 return -1;
229 }
230
231 s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
232 s->options.use_lpc = ((int[]){ 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
233 s->options.min_prediction_order= ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
234 s->options.max_prediction_order= ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
235 s->options.prediction_order_method = ((int[]){ ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
236 ORDER_METHOD_EST, ORDER_METHOD_EST, ORDER_METHOD_EST,
237 ORDER_METHOD_4LEVEL, ORDER_METHOD_LOG, ORDER_METHOD_4LEVEL,
238 ORDER_METHOD_LOG, ORDER_METHOD_SEARCH, ORDER_METHOD_LOG,
239 ORDER_METHOD_SEARCH})[level];
240 s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
241 s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
242
243 /* set compression option overrides from AVCodecContext */
244 if(avctx->use_lpc >= 0) {
245 s->options.use_lpc = av_clip(avctx->use_lpc, 0, 11);
246 }
247 if(s->options.use_lpc == 1)
248 av_log(avctx, AV_LOG_DEBUG, " use lpc: Levinson-Durbin recursion with Welch window\n");
249 else if(s->options.use_lpc > 1)
250 av_log(avctx, AV_LOG_DEBUG, " use lpc: Cholesky factorization\n");
251
252 if(avctx->min_prediction_order >= 0) {
253 if(s->options.use_lpc) {
254 if(avctx->min_prediction_order < MIN_LPC_ORDER ||
255 avctx->min_prediction_order > MAX_LPC_ORDER) {
256 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
257 avctx->min_prediction_order);
258 return -1;
259 }
260 } else {
261 if(avctx->min_prediction_order > MAX_FIXED_ORDER) {
262 av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
263 avctx->min_prediction_order);
264 return -1;
265 }
266 }
267 s->options.min_prediction_order = avctx->min_prediction_order;
268 }
269 if(avctx->max_prediction_order >= 0) {
270 if(s->options.use_lpc) {
271 if(avctx->max_prediction_order < MIN_LPC_ORDER ||
272 avctx->max_prediction_order > MAX_LPC_ORDER) {
273 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
274 avctx->max_prediction_order);
275 return -1;
276 }
277 } else {
278 if(avctx->max_prediction_order > MAX_FIXED_ORDER) {
279 av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
280 avctx->max_prediction_order);
281 return -1;
282 }
283 }
284 s->options.max_prediction_order = avctx->max_prediction_order;
285 }
286 if(s->options.max_prediction_order < s->options.min_prediction_order) {
287 av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
288 s->options.min_prediction_order, s->options.max_prediction_order);
289 return -1;
290 }
291 av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
292 s->options.min_prediction_order, s->options.max_prediction_order);
293
294 if(avctx->prediction_order_method >= 0) {
295 if(avctx->prediction_order_method > ORDER_METHOD_LOG) {
296 av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
297 avctx->prediction_order_method);
298 return -1;
299 }
300 s->options.prediction_order_method = avctx->prediction_order_method;
301 }
302 switch(s->options.prediction_order_method) {
303 case ORDER_METHOD_EST: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
304 "estimate"); break;
305 case ORDER_METHOD_2LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
306 "2-level"); break;
307 case ORDER_METHOD_4LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
308 "4-level"); break;
309 case ORDER_METHOD_8LEVEL: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
310 "8-level"); break;
311 case ORDER_METHOD_SEARCH: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
312 "full search"); break;
313 case ORDER_METHOD_LOG: av_log(avctx, AV_LOG_DEBUG, " order method: %s\n",
314 "log search"); break;
315 }
316
317 if(avctx->min_partition_order >= 0) {
318 if(avctx->min_partition_order > MAX_PARTITION_ORDER) {
319 av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
320 avctx->min_partition_order);
321 return -1;
322 }
323 s->options.min_partition_order = avctx->min_partition_order;
324 }
325 if(avctx->max_partition_order >= 0) {
326 if(avctx->max_partition_order > MAX_PARTITION_ORDER) {
327 av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
328 avctx->max_partition_order);
329 return -1;
330 }
331 s->options.max_partition_order = avctx->max_partition_order;
332 }
333 if(s->options.max_partition_order < s->options.min_partition_order) {
334 av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
335 s->options.min_partition_order, s->options.max_partition_order);
336 return -1;
337 }
338 av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
339 s->options.min_partition_order, s->options.max_partition_order);
340
341 if(avctx->frame_size > 0) {
342 if(avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
343 avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
344 av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
345 avctx->frame_size);
346 return -1;
347 }
348 } else {
349 s->avctx->frame_size = select_blocksize(s->samplerate, s->options.block_time_ms);
350 }
351 av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", s->avctx->frame_size);
352
353 /* set LPC precision */
354 if(avctx->lpc_coeff_precision > 0) {
355 if(avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
356 av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
357 avctx->lpc_coeff_precision);
358 return -1;
359 }
360 s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
361 } else {
362 /* default LPC precision */
363 s->options.lpc_coeff_precision = 15;
364 }
365 av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
366 s->options.lpc_coeff_precision);
367
368 /* set maximum encoded frame size in verbatim mode */
369 if(s->channels == 2) {
370 s->max_framesize = 14 + ((s->avctx->frame_size * 33 + 7) >> 3);
371 } else {
372 s->max_framesize = 14 + (s->avctx->frame_size * s->channels * 2);
373 }
374
375 streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
376 write_streaminfo(s, streaminfo);
377 avctx->extradata = streaminfo;
378 avctx->extradata_size = FLAC_STREAMINFO_SIZE;
379
380 s->frame_count = 0;
381
382 avctx->coded_frame = avcodec_alloc_frame();
383 avctx->coded_frame->key_frame = 1;
384
385 return 0;
386 }
387
388 static void init_frame(FlacEncodeContext *s)
389 {
390 int i, ch;
391 FlacFrame *frame;
392
393 frame = &s->frame;
394
395 for(i=0; i<16; i++) {
396 if(s->avctx->frame_size == flac_blocksizes[i]) {
397 frame->blocksize = flac_blocksizes[i];
398 frame->bs_code[0] = i;
399 frame->bs_code[1] = 0;
400 break;
401 }
402 }
403 if(i == 16) {
404 frame->blocksize = s->avctx->frame_size;
405 if(frame->blocksize <= 256) {
406 frame->bs_code[0] = 6;
407 frame->bs_code[1] = frame->blocksize-1;
408 } else {
409 frame->bs_code[0] = 7;
410 frame->bs_code[1] = frame->blocksize-1;
411 }
412 }
413
414 for(ch=0; ch<s->channels; ch++) {
415 frame->subframes[ch].obits = 16;
416 }
417 }
418
419 /**
420 * Copy channel-interleaved input samples into separate subframes
421 */
422 static void copy_samples(FlacEncodeContext *s, int16_t *samples)
423 {
424 int i, j, ch;
425 FlacFrame *frame;
426
427 frame = &s->frame;
428 for(i=0,j=0; i<frame->blocksize; i++) {
429 for(ch=0; ch<s->channels; ch++,j++) {
430 frame->subframes[ch].samples[i] = samples[j];
431 }
432 }
433 }
434
435
436 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
437
438 /**
439 * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0
440 */
441 static int find_optimal_param(uint32_t sum, int n)
442 {
443 int k;
444 uint32_t sum2;
445
446 if(sum <= n>>1)
447 return 0;
448 sum2 = sum-(n>>1);
449 k = av_log2(n<256 ? FASTDIV(sum2,n) : sum2/n);
450 return FFMIN(k, MAX_RICE_PARAM);
451 }
452
453 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
454 uint32_t *sums, int n, int pred_order)
455 {
456 int i;
457 int k, cnt, part;
458 uint32_t all_bits;
459
460 part = (1 << porder);
461 all_bits = 4 * part;
462
463 cnt = (n >> porder) - pred_order;
464 for(i=0; i<part; i++) {
465 k = find_optimal_param(sums[i], cnt);
466 rc->params[i] = k;
467 all_bits += rice_encode_count(sums[i], cnt, k);
468 cnt = n >> porder;
469 }
470
471 rc->porder = porder;
472
473 return all_bits;
474 }
475
476 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
477 uint32_t sums[][MAX_PARTITIONS])
478 {
479 int i, j;
480 int parts;
481 uint32_t *res, *res_end;
482
483 /* sums for highest level */
484 parts = (1 << pmax);
485 res = &data[pred_order];
486 res_end = &data[n >> pmax];
487 for(i=0; i<parts; i++) {
488 uint32_t sum = 0;
489 while(res < res_end){
490 sum += *(res++);
491 }
492 sums[pmax][i] = sum;
493 res_end+= n >> pmax;
494 }
495 /* sums for lower levels */
496 for(i=pmax-1; i>=pmin; i--) {
497 parts = (1 << i);
498 for(j=0; j<parts; j++) {
499 sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
500 }
501 }
502 }
503
504 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
505 int32_t *data, int n, int pred_order)
506 {
507 int i;
508 uint32_t bits[MAX_PARTITION_ORDER+1];
509 int opt_porder;
510 RiceContext tmp_rc;
511 uint32_t *udata;
512 uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
513
514 assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
515 assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
516 assert(pmin <= pmax);
517
518 udata = av_malloc(n * sizeof(uint32_t));
519 for(i=0; i<n; i++) {
520 udata[i] = (2*data[i]) ^ (data[i]>>31);
521 }
522
523 calc_sums(pmin, pmax, udata, n, pred_order, sums);
524
525 opt_porder = pmin;
526 bits[pmin] = UINT32_MAX;
527 for(i=pmin; i<=pmax; i++) {
528 bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
529 if(bits[i] <= bits[opt_porder]) {
530 opt_porder = i;
531 *rc= tmp_rc;
532 }
533 }
534
535 av_freep(&udata);
536 return bits[opt_porder];
537 }
538
539 static int get_max_p_order(int max_porder, int n, int order)
540 {
541 int porder = FFMIN(max_porder, av_log2(n^(n-1)));
542 if(order > 0)
543 porder = FFMIN(porder, av_log2(n/order));
544 return porder;
545 }
546
547 static uint32_t calc_rice_params_fixed(RiceContext *rc, int pmin, int pmax,
548 int32_t *data, int n, int pred_order,
549 int bps)
550 {
551 uint32_t bits;
552 pmin = get_max_p_order(pmin, n, pred_order);
553 pmax = get_max_p_order(pmax, n, pred_order);
554 bits = pred_order*bps + 6;
555 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
556 return bits;
557 }
558
559 static uint32_t calc_rice_params_lpc(RiceContext *rc, int pmin, int pmax,
560 int32_t *data, int n, int pred_order,
561 int bps, int precision)
562 {
563 uint32_t bits;
564 pmin = get_max_p_order(pmin, n, pred_order);
565 pmax = get_max_p_order(pmax, n, pred_order);
566 bits = pred_order*bps + 4 + 5 + pred_order*precision + 6;
567 bits += calc_rice_params(rc, pmin, pmax, data, n, pred_order);
568 return bits;
569 }
570
571 /**
572 * Apply Welch window function to audio block
573 */
574 static void apply_welch_window(const int32_t *data, int len, double *w_data)
575 {
576 int i, n2;
577 double w;
578 double c;
579
580 assert(!(len&1)); //the optimization in r11881 does not support odd len
581 //if someone wants odd len extend the change in r11881
582
583 n2 = (len >> 1);
584 c = 2.0 / (len - 1.0);
585
586 w_data+=n2;
587 data+=n2;
588 for(i=0; i<n2; i++) {
589 w = c - n2 + i;
590 w = 1.0 - (w * w);
591 w_data[-i-1] = data[-i-1] * w;
592 w_data[+i ] = data[+i ] * w;
593 }
594 }
595
596 /**
597 * Calculates autocorrelation data from audio samples
598 * A Welch window function is applied before calculation.
599 */
600 void ff_flac_compute_autocorr(const int32_t *data, int len, int lag,
601 double *autoc)
602 {
603 int i, j;
604 double tmp[len + lag + 1];
605 double *data1= tmp + lag;
606
607 apply_welch_window(data, len, data1);
608
609 for(j=0; j<lag; j++)
610 data1[j-lag]= 0.0;
611 data1[len] = 0.0;
612
613 for(j=0; j<lag; j+=2){
614 double sum0 = 1.0, sum1 = 1.0;
615 for(i=0; i<len; i++){
616 sum0 += data1[i] * data1[i-j];
617 sum1 += data1[i] * data1[i-j-1];
618 }
619 autoc[j ] = sum0;
620 autoc[j+1] = sum1;
621 }
622
623 if(j==lag){
624 double sum = 1.0;
625 for(i=0; i<len; i+=2){
626 sum += data1[i ] * data1[i-j ]
627 + data1[i+1] * data1[i-j+1];
628 }
629 autoc[j] = sum;
630 }
631 }
632
633
634 static void encode_residual_verbatim(int32_t *res, int32_t *smp, int n)
635 {
636 assert(n > 0);
637 memcpy(res, smp, n * sizeof(int32_t));
638 }
639
640 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
641 int order)
642 {
643 int i;
644
645 for(i=0; i<order; i++) {
646 res[i] = smp[i];
647 }
648
649 if(order==0){
650 for(i=order; i<n; i++)
651 res[i]= smp[i];
652 }else if(order==1){
653 for(i=order; i<n; i++)
654 res[i]= smp[i] - smp[i-1];
655 }else if(order==2){
656 int a = smp[order-1] - smp[order-2];
657 for(i=order; i<n; i+=2) {
658 int b = smp[i] - smp[i-1];
659 res[i]= b - a;
660 a = smp[i+1] - smp[i];
661 res[i+1]= a - b;
662 }
663 }else if(order==3){
664 int a = smp[order-1] - smp[order-2];
665 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
666 for(i=order; i<n; i+=2) {
667 int b = smp[i] - smp[i-1];
668 int d = b - a;
669 res[i]= d - c;
670 a = smp[i+1] - smp[i];
671 c = a - b;
672 res[i+1]= c - d;
673 }
674 }else{
675 int a = smp[order-1] - smp[order-2];
676 int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
677 int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
678 for(i=order; i<n; i+=2) {
679 int b = smp[i] - smp[i-1];
680 int d = b - a;
681 int f = d - c;
682 res[i]= f - e;
683 a = smp[i+1] - smp[i];
684 c = a - b;
685 e = c - d;
686 res[i+1]= e - f;
687 }
688 }
689 }
690
691 #define LPC1(x) {\
692 int c = coefs[(x)-1];\
693 p0 += c*s;\
694 s = smp[i-(x)+1];\
695 p1 += c*s;\
696 }
697
698 static av_always_inline void encode_residual_lpc_unrolled(
699 int32_t *res, const int32_t *smp, int n,
700 int order, const int32_t *coefs, int shift, int big)
701 {
702 int i;
703 for(i=order; i<n; i+=2) {
704 int s = smp[i-order];
705 int p0 = 0, p1 = 0;
706 if(big) {
707 switch(order) {
708 case 32: LPC1(32)
709 case 31: LPC1(31)
710 case 30: LPC1(30)
711 case 29: LPC1(29)
712 case 28: LPC1(28)
713 case 27: LPC1(27)
714 case 26: LPC1(26)
715 case 25: LPC1(25)
716 case 24: LPC1(24)
717 case 23: LPC1(23)
718 case 22: LPC1(22)
719 case 21: LPC1(21)
720 case 20: LPC1(20)
721 case 19: LPC1(19)
722 case 18: LPC1(18)
723 case 17: LPC1(17)
724 case 16: LPC1(16)
725 case 15: LPC1(15)
726 case 14: LPC1(14)
727 case 13: LPC1(13)
728 case 12: LPC1(12)
729 case 11: LPC1(11)
730 case 10: LPC1(10)
731 case 9: LPC1( 9)
732 LPC1( 8)
733 LPC1( 7)
734 LPC1( 6)
735 LPC1( 5)
736 LPC1( 4)
737 LPC1( 3)
738 LPC1( 2)
739 LPC1( 1)
740 }
741 } else {
742 switch(order) {
743 case 8: LPC1( 8)
744 case 7: LPC1( 7)
745 case 6: LPC1( 6)
746 case 5: LPC1( 5)
747 case 4: LPC1( 4)
748 case 3: LPC1( 3)
749 case 2: LPC1( 2)
750 case 1: LPC1( 1)
751 }
752 }
753 res[i ] = smp[i ] - (p0 >> shift);
754 res[i+1] = smp[i+1] - (p1 >> shift);
755 }
756 }
757
758 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
759 int order, const int32_t *coefs, int shift)
760 {
761 int i;
762 for(i=0; i<order; i++) {
763 res[i] = smp[i];
764 }
765 #ifdef CONFIG_SMALL
766 for(i=order; i<n; i+=2) {
767 int j;
768 int s = smp[i];
769 int p0 = 0, p1 = 0;
770 for(j=0; j<order; j++) {
771 int c = coefs[j];
772 p1 += c*s;
773 s = smp[i-j-1];
774 p0 += c*s;
775 }
776 res[i ] = smp[i ] - (p0 >> shift);
777 res[i+1] = smp[i+1] - (p1 >> shift);
778 }
779 #else
780 switch(order) {
781 case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
782 case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
783 case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
784 case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
785 case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
786 case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
787 case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
788 case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
789 default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
790 }
791 #endif
792 }
793
794 static int encode_residual(FlacEncodeContext *ctx, int ch)
795 {
796 int i, n;
797 int min_order, max_order, opt_order, precision, omethod;
798 int min_porder, max_porder;
799 FlacFrame *frame;
800 FlacSubframe *sub;
801 int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
802 int shift[MAX_LPC_ORDER];
803 int32_t *res, *smp;
804
805 frame = &ctx->frame;
806 sub = &frame->subframes[ch];
807 res = sub->residual;
808 smp = sub->samples;
809 n = frame->blocksize;
810
811 /* CONSTANT */
812 for(i=1; i<n; i++) {
813 if(smp[i] != smp[0]) break;
814 }
815 if(i == n) {
816 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
817 res[0] = smp[0];
818 return sub->obits;
819 }
820
821 /* VERBATIM */
822 if(n < 5) {
823 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
824 encode_residual_verbatim(res, smp, n);
825 return sub->obits * n;
826 }
827
828 min_order = ctx->options.min_prediction_order;
829 max_order = ctx->options.max_prediction_order;
830 min_porder = ctx->options.min_partition_order;
831 max_porder = ctx->options.max_partition_order;
832 precision = ctx->options.lpc_coeff_precision;
833 omethod = ctx->options.prediction_order_method;
834
835 /* FIXED */
836 if(!ctx->options.use_lpc || max_order == 0 || (n <= max_order)) {
837 uint32_t bits[MAX_FIXED_ORDER+1];
838 if(max_order > MAX_FIXED_ORDER) max_order = MAX_FIXED_ORDER;
839 opt_order = 0;
840 bits[0] = UINT32_MAX;
841 for(i=min_order; i<=max_order; i++) {
842 encode_residual_fixed(res, smp, n, i);
843 bits[i] = calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res,
844 n, i, sub->obits);
845 if(bits[i] < bits[opt_order]) {
846 opt_order = i;
847 }
848 }
849 sub->order = opt_order;
850 sub->type = FLAC_SUBFRAME_FIXED;
851 sub->type_code = sub->type | sub->order;
852 if(sub->order != max_order) {
853 encode_residual_fixed(res, smp, n, sub->order);
854 return calc_rice_params_fixed(&sub->rc, min_porder, max_porder, res, n,
855 sub->order, sub->obits);
856 }
857 return bits[sub->order];
858 }
859
860 /* LPC */
861 opt_order = ff_lpc_calc_coefs(&ctx->dsp, smp, n, min_order, max_order,
862 precision, coefs, shift, ctx->options.use_lpc,
863 omethod, MAX_LPC_SHIFT, 0);
864
865 if(omethod == ORDER_METHOD_2LEVEL ||
866 omethod == ORDER_METHOD_4LEVEL ||
867 omethod == ORDER_METHOD_8LEVEL) {
868 int levels = 1 << omethod;
869 uint32_t bits[levels];
870 int order;
871 int opt_index = levels-1;
872 opt_order = max_order-1;
873 bits[opt_index] = UINT32_MAX;
874 for(i=levels-1; i>=0; i--) {
875 order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
876 if(order < 0) order = 0;
877 encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
878 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
879 res, n, order+1, sub->obits, precision);
880 if(bits[i] < bits[opt_index]) {
881 opt_index = i;
882 opt_order = order;
883 }
884 }
885 opt_order++;
886 } else if(omethod == ORDER_METHOD_SEARCH) {
887 // brute-force optimal order search
888 uint32_t bits[MAX_LPC_ORDER];
889 opt_order = 0;
890 bits[0] = UINT32_MAX;
891 for(i=min_order-1; i<max_order; i++) {
892 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
893 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
894 res, n, i+1, sub->obits, precision);
895 if(bits[i] < bits[opt_order]) {
896 opt_order = i;
897 }
898 }
899 opt_order++;
900 } else if(omethod == ORDER_METHOD_LOG) {
901 uint32_t bits[MAX_LPC_ORDER];
902 int step;
903
904 opt_order= min_order - 1 + (max_order-min_order)/3;
905 memset(bits, -1, sizeof(bits));
906
907 for(step=16 ;step; step>>=1){
908 int last= opt_order;
909 for(i=last-step; i<=last+step; i+= step){
910 if(i<min_order-1 || i>=max_order || bits[i] < UINT32_MAX)
911 continue;
912 encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
913 bits[i] = calc_rice_params_lpc(&sub->rc, min_porder, max_porder,
914 res, n, i+1, sub->obits, precision);
915 if(bits[i] < bits[opt_order])
916 opt_order= i;
917 }
918 }
919 opt_order++;
920 }
921
922 sub->order = opt_order;
923 sub->type = FLAC_SUBFRAME_LPC;
924 sub->type_code = sub->type | (sub->order-1);
925 sub->shift = shift[sub->order-1];
926 for(i=0; i<sub->order; i++) {
927 sub->coefs[i] = coefs[sub->order-1][i];
928 }
929 encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
930 return calc_rice_params_lpc(&sub->rc, min_porder, max_porder, res, n, sub->order,
931 sub->obits, precision);
932 }
933
934 static int encode_residual_v(FlacEncodeContext *ctx, int ch)
935 {
936 int i, n;
937 FlacFrame *frame;
938 FlacSubframe *sub;
939 int32_t *res, *smp;
940
941 frame = &ctx->frame;
942 sub = &frame->subframes[ch];
943 res = sub->residual;
944 smp = sub->samples;
945 n = frame->blocksize;
946
947 /* CONSTANT */
948 for(i=1; i<n; i++) {
949 if(smp[i] != smp[0]) break;
950 }
951 if(i == n) {
952 sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
953 res[0] = smp[0];
954 return sub->obits;
955 }
956
957 /* VERBATIM */
958 sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
959 encode_residual_verbatim(res, smp, n);
960 return sub->obits * n;
961 }
962
963 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
964 {
965 int i, best;
966 int32_t lt, rt;
967 uint64_t sum[4];
968 uint64_t score[4];
969 int k;
970
971 /* calculate sum of 2nd order residual for each channel */
972 sum[0] = sum[1] = sum[2] = sum[3] = 0;
973 for(i=2; i<n; i++) {
974 lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
975 rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
976 sum[2] += FFABS((lt + rt) >> 1);
977 sum[3] += FFABS(lt - rt);
978 sum[0] += FFABS(lt);
979 sum[1] += FFABS(rt);
980 }
981 /* estimate bit counts */
982 for(i=0; i<4; i++) {
983 k = find_optimal_param(2*sum[i], n);
984 sum[i] = rice_encode_count(2*sum[i], n, k);
985 }
986
987 /* calculate score for each mode */
988 score[0] = sum[0] + sum[1];
989 score[1] = sum[0] + sum[3];
990 score[2] = sum[1] + sum[3];
991 score[3] = sum[2] + sum[3];
992
993 /* return mode with lowest score */
994 best = 0;
995 for(i=1; i<4; i++) {
996 if(score[i] < score[best]) {
997 best = i;
998 }
999 }
1000 if(best == 0) {
1001 return FLAC_CHMODE_LEFT_RIGHT;
1002 } else if(best == 1) {
1003 return FLAC_CHMODE_LEFT_SIDE;
1004 } else if(best == 2) {
1005 return FLAC_CHMODE_RIGHT_SIDE;
1006 } else {
1007 return FLAC_CHMODE_MID_SIDE;
1008 }
1009 }
1010
1011 /**
1012 * Perform stereo channel decorrelation
1013 */
1014 static void channel_decorrelation(FlacEncodeContext *ctx)
1015 {
1016 FlacFrame *frame;
1017 int32_t *left, *right;
1018 int i, n;
1019
1020 frame = &ctx->frame;
1021 n = frame->blocksize;
1022 left = frame->subframes[0].samples;
1023 right = frame->subframes[1].samples;
1024
1025 if(ctx->channels != 2) {
1026 frame->ch_mode = FLAC_CHMODE_NOT_STEREO;
1027 return;
1028 }
1029
1030 frame->ch_mode = estimate_stereo_mode(left, right, n);
1031
1032 /* perform decorrelation and adjust bits-per-sample */
1033 if(frame->ch_mode == FLAC_CHMODE_LEFT_RIGHT) {
1034 return;
1035 }
1036 if(frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1037 int32_t tmp;
1038 for(i=0; i<n; i++) {
1039 tmp = left[i];
1040 left[i] = (tmp + right[i]) >> 1;
1041 right[i] = tmp - right[i];
1042 }
1043 frame->subframes[1].obits++;
1044 } else if(frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1045 for(i=0; i<n; i++) {
1046 right[i] = left[i] - right[i];
1047 }
1048 frame->subframes[1].obits++;
1049 } else {
1050 for(i=0; i<n; i++) {
1051 left[i] -= right[i];
1052 }
1053 frame->subframes[0].obits++;
1054 }
1055 }
1056
1057 static void write_utf8(PutBitContext *pb, uint32_t val)
1058 {
1059 uint8_t tmp;
1060 PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1061 }
1062
1063 static void output_frame_header(FlacEncodeContext *s)
1064 {
1065 FlacFrame *frame;
1066 int crc;
1067
1068 frame = &s->frame;
1069
1070 put_bits(&s->pb, 16, 0xFFF8);
1071 put_bits(&s->pb, 4, frame->bs_code[0]);
1072 put_bits(&s->pb, 4, s->sr_code[0]);
1073 if(frame->ch_mode == FLAC_CHMODE_NOT_STEREO) {
1074 put_bits(&s->pb, 4, s->ch_code);
1075 } else {
1076 put_bits(&s->pb, 4, frame->ch_mode);
1077 }
1078 put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1079 put_bits(&s->pb, 1, 0);
1080 write_utf8(&s->pb, s->frame_count);
1081 if(frame->bs_code[0] == 6) {
1082 put_bits(&s->pb, 8, frame->bs_code[1]);
1083 } else if(frame->bs_code[0] == 7) {
1084 put_bits(&s->pb, 16, frame->bs_code[1]);
1085 }
1086 if(s->sr_code[0] == 12) {
1087 put_bits(&s->pb, 8, s->sr_code[1]);
1088 } else if(s->sr_code[0] > 12) {
1089 put_bits(&s->pb, 16, s->sr_code[1]);
1090 }
1091 flush_put_bits(&s->pb);
1092 crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0,
1093 s->pb.buf, put_bits_count(&s->pb)>>3);
1094 put_bits(&s->pb, 8, crc);
1095 }
1096
1097 static void output_subframe_constant(FlacEncodeContext *s, int ch)
1098 {
1099 FlacSubframe *sub;
1100 int32_t res;
1101
1102 sub = &s->frame.subframes[ch];
1103 res = sub->residual[0];
1104 put_sbits(&s->pb, sub->obits, res);
1105 }
1106
1107 static void output_subframe_verbatim(FlacEncodeContext *s, int ch)
1108 {
1109 int i;
1110 FlacFrame *frame;
1111 FlacSubframe *sub;
1112 int32_t res;
1113
1114 frame = &s->frame;
1115 sub = &frame->subframes[ch];
1116
1117 for(i=0; i<frame->blocksize; i++) {
1118 res = sub->residual[i];
1119 put_sbits(&s->pb, sub->obits, res);
1120 }
1121 }
1122
1123 static void output_residual(FlacEncodeContext *ctx, int ch)
1124 {
1125 int i, j, p, n, parts;
1126 int k, porder, psize, res_cnt;
1127 FlacFrame *frame;
1128 FlacSubframe *sub;
1129 int32_t *res;
1130
1131 frame = &ctx->frame;
1132 sub = &frame->subframes[ch];
1133 res = sub->residual;
1134 n = frame->blocksize;
1135
1136 /* rice-encoded block */
1137 put_bits(&ctx->pb, 2, 0);
1138
1139 /* partition order */
1140 porder = sub->rc.porder;
1141 psize = n >> porder;
1142 parts = (1 << porder);
1143 put_bits(&ctx->pb, 4, porder);
1144 res_cnt = psize - sub->order;
1145
1146 /* residual */
1147 j = sub->order;
1148 for(p=0; p<parts; p++) {
1149 k = sub->rc.params[p];
1150 put_bits(&ctx->pb, 4, k);
1151 if(p == 1) res_cnt = psize;
1152 for(i=0; i<res_cnt && j<n; i++, j++) {
1153 set_sr_golomb_flac(&ctx->pb, res[j], k, INT32_MAX, 0);
1154 }
1155 }
1156 }
1157
1158 static void output_subframe_fixed(FlacEncodeContext *ctx, int ch)
1159 {
1160 int i;
1161 FlacFrame *frame;
1162 FlacSubframe *sub;
1163
1164 frame = &ctx->frame;
1165 sub = &frame->subframes[ch];
1166
1167 /* warm-up samples */
1168 for(i=0; i<sub->order; i++) {
1169 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1170 }
1171
1172 /* residual */
1173 output_residual(ctx, ch);
1174 }
1175
1176 static void output_subframe_lpc(FlacEncodeContext *ctx, int ch)
1177 {
1178 int i, cbits;
1179 FlacFrame *frame;
1180 FlacSubframe *sub;
1181
1182 frame = &ctx->frame;
1183 sub = &frame->subframes[ch];
1184
1185 /* warm-up samples */
1186 for(i=0; i<sub->order; i++) {
1187 put_sbits(&ctx->pb, sub->obits, sub->residual[i]);
1188 }
1189
1190 /* LPC coefficients */
1191 cbits = ctx->options.lpc_coeff_precision;
1192 put_bits(&ctx->pb, 4, cbits-1);
1193 put_sbits(&ctx->pb, 5, sub->shift);
1194 for(i=0; i<sub->order; i++) {
1195 put_sbits(&ctx->pb, cbits, sub->coefs[i]);
1196 }
1197
1198 /* residual */
1199 output_residual(ctx, ch);
1200 }
1201
1202 static void output_subframes(FlacEncodeContext *s)
1203 {
1204 FlacFrame *frame;
1205 FlacSubframe *sub;
1206 int ch;
1207
1208 frame = &s->frame;
1209
1210 for(ch=0; ch<s->channels; ch++) {
1211 sub = &frame->subframes[ch];
1212
1213 /* subframe header */
1214 put_bits(&s->pb, 1, 0);
1215 put_bits(&s->pb, 6, sub->type_code);
1216 put_bits(&s->pb, 1, 0); /* no wasted bits */
1217
1218 /* subframe */
1219 if(sub->type == FLAC_SUBFRAME_CONSTANT) {
1220 output_subframe_constant(s, ch);
1221 } else if(sub->type == FLAC_SUBFRAME_VERBATIM) {
1222 output_subframe_verbatim(s, ch);
1223 } else if(sub->type == FLAC_SUBFRAME_FIXED) {
1224 output_subframe_fixed(s, ch);
1225 } else if(sub->type == FLAC_SUBFRAME_LPC) {
1226 output_subframe_lpc(s, ch);
1227 }
1228 }
1229 }
1230
1231 static void output_frame_footer(FlacEncodeContext *s)
1232 {
1233 int crc;
1234 flush_put_bits(&s->pb);
1235 crc = bswap_16(av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0,
1236 s->pb.buf, put_bits_count(&s->pb)>>3));
1237 put_bits(&s->pb, 16, crc);
1238 flush_put_bits(&s->pb);
1239 }
1240
1241 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1242 int buf_size, void *data)
1243 {
1244 int ch;
1245 FlacEncodeContext *s;
1246 int16_t *samples = data;
1247 int out_bytes;
1248 int reencoded=0;
1249
1250 s = avctx->priv_data;
1251
1252 if(buf_size < s->max_framesize*2) {
1253 av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1254 return 0;
1255 }
1256
1257 /* when the last block is reached, update the header in extradata */
1258 if (!data) {
1259 write_streaminfo(s, avctx->extradata);
1260 return 0;
1261 }
1262
1263 init_frame(s);
1264
1265 copy_samples(s, samples);
1266
1267 channel_decorrelation(s);
1268
1269 for(ch=0; ch<s->channels; ch++) {
1270 encode_residual(s, ch);
1271 }
1272
1273 write_frame:
1274 init_put_bits(&s->pb, frame, buf_size);
1275 output_frame_header(s);
1276 output_subframes(s);
1277 output_frame_footer(s);
1278 out_bytes = put_bits_count(&s->pb) >> 3;
1279
1280 if(out_bytes > s->max_framesize) {
1281 if(reencoded) {
1282 /* still too large. must be an error. */
1283 av_log(avctx, AV_LOG_ERROR, "error encoding frame\n");
1284 return -1;
1285 }
1286
1287 /* frame too large. use verbatim mode */
1288 for(ch=0; ch<s->channels; ch++) {
1289 encode_residual_v(s, ch);
1290 }
1291 reencoded = 1;
1292 goto write_frame;
1293 }
1294
1295 s->frame_count++;
1296 s->sample_count += avctx->frame_size;
1297
1298 return out_bytes;
1299 }
1300
1301 static av_cold int flac_encode_close(AVCodecContext *avctx)
1302 {
1303 av_freep(&avctx->extradata);
1304 avctx->extradata_size = 0;
1305 av_freep(&avctx->coded_frame);
1306 return 0;
1307 }
1308
1309 AVCodec flac_encoder = {
1310 "flac",
1311 CODEC_TYPE_AUDIO,
1312 CODEC_ID_FLAC,
1313 sizeof(FlacEncodeContext),
1314 flac_encode_init,
1315 flac_encode_frame,
1316 flac_encode_close,
1317 NULL,
1318 .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1319 .sample_fmts = (enum SampleFormat[]){SAMPLE_FMT_S16,SAMPLE_FMT_NONE},
1320 .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1321 };