flacenc.c
Go to the documentation of this file.
1 
22 #include "libavutil/crc.h"
23 #include "libavutil/md5.h"
24 #include "libavutil/opt.h"
25 #include "avcodec.h"
26 #include "get_bits.h"
27 #include "golomb.h"
28 #include "lpc.h"
29 #include "flac.h"
30 #include "flacdata.h"
31 
32 #define FLAC_SUBFRAME_CONSTANT 0
33 #define FLAC_SUBFRAME_VERBATIM 1
34 #define FLAC_SUBFRAME_FIXED 8
35 #define FLAC_SUBFRAME_LPC 32
36 
37 #define MAX_FIXED_ORDER 4
38 #define MAX_PARTITION_ORDER 8
39 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
40 #define MAX_LPC_PRECISION 15
41 #define MAX_LPC_SHIFT 15
42 #define MAX_RICE_PARAM 14
43 
44 typedef struct CompressionOptions {
56 
57 typedef struct RiceContext {
58  int porder;
60 } RiceContext;
61 
62 typedef struct FlacSubframe {
63  int type;
64  int type_code;
65  int obits;
66  int order;
67  int32_t coefs[MAX_LPC_ORDER];
68  int shift;
72 } FlacSubframe;
73 
74 typedef struct FlacFrame {
76  int blocksize;
77  int bs_code[2];
78  uint8_t crc8;
79  int ch_mode;
81 } FlacFrame;
82 
83 typedef struct FlacEncodeContext {
84  AVClass *class;
86  int channels;
88  int sr_code[2];
93  uint32_t frame_count;
94  uint64_t sample_count;
95  uint8_t md5sum[16];
100  struct AVMD5 *md5ctx;
102 
103 
107 static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
108 {
109  PutBitContext pb;
110 
111  memset(header, 0, FLAC_STREAMINFO_SIZE);
112  init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
113 
114  /* streaminfo metadata block */
115  put_bits(&pb, 16, s->max_blocksize);
116  put_bits(&pb, 16, s->max_blocksize);
117  put_bits(&pb, 24, s->min_framesize);
118  put_bits(&pb, 24, s->max_framesize);
119  put_bits(&pb, 20, s->samplerate);
120  put_bits(&pb, 3, s->channels-1);
121  put_bits(&pb, 5, 15); /* bits per sample - 1 */
122  /* write 36-bit sample count in 2 put_bits() calls */
123  put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
124  put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
125  flush_put_bits(&pb);
126  memcpy(&header[18], s->md5sum, 16);
127 }
128 
129 
134 static int select_blocksize(int samplerate, int block_time_ms)
135 {
136  int i;
137  int target;
138  int blocksize;
139 
140  assert(samplerate > 0);
141  blocksize = ff_flac_blocksize_table[1];
142  target = (samplerate * block_time_ms) / 1000;
143  for (i = 0; i < 16; i++) {
144  if (target >= ff_flac_blocksize_table[i] &&
145  ff_flac_blocksize_table[i] > blocksize) {
146  blocksize = ff_flac_blocksize_table[i];
147  }
148  }
149  return blocksize;
150 }
151 
152 
154 {
155  AVCodecContext *avctx = s->avctx;
156  CompressionOptions *opt = &s->options;
157 
158  av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
159 
160  switch (opt->lpc_type) {
161  case FF_LPC_TYPE_NONE:
162  av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
163  break;
164  case FF_LPC_TYPE_FIXED:
165  av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
166  break;
168  av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
169  break;
171  av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
172  opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
173  break;
174  }
175 
176  av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
178 
179  switch (opt->prediction_order_method) {
180  case ORDER_METHOD_EST:
181  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
182  break;
183  case ORDER_METHOD_2LEVEL:
184  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
185  break;
186  case ORDER_METHOD_4LEVEL:
187  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
188  break;
189  case ORDER_METHOD_8LEVEL:
190  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
191  break;
192  case ORDER_METHOD_SEARCH:
193  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
194  break;
195  case ORDER_METHOD_LOG:
196  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
197  break;
198  }
199 
200 
201  av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
203 
204  av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
205 
206  av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
207  opt->lpc_coeff_precision);
208 }
209 
210 
212 {
213  int freq = avctx->sample_rate;
214  int channels = avctx->channels;
215  FlacEncodeContext *s = avctx->priv_data;
216  int i, level, ret;
217  uint8_t *streaminfo;
218 
219  s->avctx = avctx;
220 
221  if (avctx->sample_fmt != AV_SAMPLE_FMT_S16)
222  return -1;
223 
224  if (channels < 1 || channels > FLAC_MAX_CHANNELS)
225  return -1;
226  s->channels = channels;
227 
228  /* find samplerate in table */
229  if (freq < 1)
230  return -1;
231  for (i = 4; i < 12; i++) {
232  if (freq == ff_flac_sample_rate_table[i]) {
234  s->sr_code[0] = i;
235  s->sr_code[1] = 0;
236  break;
237  }
238  }
239  /* if not in table, samplerate is non-standard */
240  if (i == 12) {
241  if (freq % 1000 == 0 && freq < 255000) {
242  s->sr_code[0] = 12;
243  s->sr_code[1] = freq / 1000;
244  } else if (freq % 10 == 0 && freq < 655350) {
245  s->sr_code[0] = 14;
246  s->sr_code[1] = freq / 10;
247  } else if (freq < 65535) {
248  s->sr_code[0] = 13;
249  s->sr_code[1] = freq;
250  } else {
251  return -1;
252  }
253  s->samplerate = freq;
254  }
255 
256  /* set compression option defaults based on avctx->compression_level */
257  if (avctx->compression_level < 0)
258  s->options.compression_level = 5;
259  else
261 
262  level = s->options.compression_level;
263  if (level > 12) {
264  av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
266  return -1;
267  }
268 
269  s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
270 
276  FF_LPC_TYPE_LEVINSON})[level];
277 
278  s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
279  s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
280 
281  if (s->options.prediction_order_method < 0)
286  ORDER_METHOD_SEARCH})[level];
287 
289  av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
291  return AVERROR(EINVAL);
292  }
293  if (s->options.min_partition_order < 0)
294  s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
295  if (s->options.max_partition_order < 0)
296  s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
297 
298  /* set compression option overrides from AVCodecContext */
299 #if FF_API_FLAC_GLOBAL_OPTS
300  if (avctx->lpc_type > FF_LPC_TYPE_DEFAULT) {
301  if (avctx->lpc_type > FF_LPC_TYPE_CHOLESKY) {
302  av_log(avctx, AV_LOG_ERROR, "unknown lpc type: %d\n", avctx->lpc_type);
303  return -1;
304  }
305  s->options.lpc_type = avctx->lpc_type;
307  if (avctx->lpc_passes < 0) {
308  // default number of passes for Cholesky
309  s->options.lpc_passes = 2;
310  } else if (avctx->lpc_passes == 0) {
311  av_log(avctx, AV_LOG_ERROR, "invalid number of lpc passes: %d\n",
312  avctx->lpc_passes);
313  return -1;
314  } else {
315  s->options.lpc_passes = avctx->lpc_passes;
316  }
317  }
318  }
319 #endif
320 
321  if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
323  } else if (avctx->min_prediction_order >= 0) {
324  if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
325  if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
326  av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
327  avctx->min_prediction_order);
328  return -1;
329  }
330  } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
332  av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
333  avctx->min_prediction_order);
334  return -1;
335  }
337  }
338  if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
340  } else if (avctx->max_prediction_order >= 0) {
341  if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
342  if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
343  av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
344  avctx->max_prediction_order);
345  return -1;
346  }
347  } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
349  av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
350  avctx->max_prediction_order);
351  return -1;
352  }
354  }
356  av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
358  return -1;
359  }
360 
361 #if FF_API_FLAC_GLOBAL_OPTS
362  if (avctx->prediction_order_method >= 0) {
363  if (avctx->prediction_order_method > ORDER_METHOD_LOG) {
364  av_log(avctx, AV_LOG_ERROR, "invalid prediction order method: %d\n",
365  avctx->prediction_order_method);
366  return -1;
367  }
368  s->options.prediction_order_method = avctx->prediction_order_method;
369  }
370 
371  if (avctx->min_partition_order >= 0) {
372  if (avctx->min_partition_order > MAX_PARTITION_ORDER) {
373  av_log(avctx, AV_LOG_ERROR, "invalid min partition order: %d\n",
374  avctx->min_partition_order);
375  return -1;
376  }
377  s->options.min_partition_order = avctx->min_partition_order;
378  }
379  if (avctx->max_partition_order >= 0) {
380  if (avctx->max_partition_order > MAX_PARTITION_ORDER) {
381  av_log(avctx, AV_LOG_ERROR, "invalid max partition order: %d\n",
382  avctx->max_partition_order);
383  return -1;
384  }
385  s->options.max_partition_order = avctx->max_partition_order;
386  }
388  av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
390  return -1;
391  }
392 #endif
393 
394  if (avctx->frame_size > 0) {
395  if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
396  avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
397  av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
398  avctx->frame_size);
399  return -1;
400  }
401  } else {
403  }
404  s->max_blocksize = s->avctx->frame_size;
405 
406 #if FF_API_FLAC_GLOBAL_OPTS
407  /* set LPC precision */
408  if (avctx->lpc_coeff_precision > 0) {
409  if (avctx->lpc_coeff_precision > MAX_LPC_PRECISION) {
410  av_log(avctx, AV_LOG_ERROR, "invalid lpc coeff precision: %d\n",
411  avctx->lpc_coeff_precision);
412  return -1;
413  }
414  s->options.lpc_coeff_precision = avctx->lpc_coeff_precision;
415  }
416 #endif
417 
418  /* set maximum encoded frame size in verbatim mode */
420  s->channels, 16);
421 
422  /* initialize MD5 context */
424  if (!s->md5ctx)
425  return AVERROR(ENOMEM);
426  av_md5_init(s->md5ctx);
427 
428  streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
429  if (!streaminfo)
430  return AVERROR(ENOMEM);
431  write_streaminfo(s, streaminfo);
432  avctx->extradata = streaminfo;
434 
435  s->frame_count = 0;
437 
438  avctx->coded_frame = avcodec_alloc_frame();
439  if (!avctx->coded_frame)
440  return AVERROR(ENOMEM);
441 
442  ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
444 
446 
447  return ret;
448 }
449 
450 
452 {
453  int i, ch;
454  FlacFrame *frame;
455 
456  frame = &s->frame;
457 
458  for (i = 0; i < 16; i++) {
459  if (s->avctx->frame_size == ff_flac_blocksize_table[i]) {
461  frame->bs_code[0] = i;
462  frame->bs_code[1] = 0;
463  break;
464  }
465  }
466  if (i == 16) {
467  frame->blocksize = s->avctx->frame_size;
468  if (frame->blocksize <= 256) {
469  frame->bs_code[0] = 6;
470  frame->bs_code[1] = frame->blocksize-1;
471  } else {
472  frame->bs_code[0] = 7;
473  frame->bs_code[1] = frame->blocksize-1;
474  }
475  }
476 
477  for (ch = 0; ch < s->channels; ch++)
478  frame->subframes[ch].obits = 16;
479 
480  frame->verbatim_only = 0;
481 }
482 
483 
487 static void copy_samples(FlacEncodeContext *s, const int16_t *samples)
488 {
489  int i, j, ch;
490  FlacFrame *frame;
491 
492  frame = &s->frame;
493  for (i = 0, j = 0; i < frame->blocksize; i++)
494  for (ch = 0; ch < s->channels; ch++, j++)
495  frame->subframes[ch].samples[i] = samples[j];
496 }
497 
498 
499 static int rice_count_exact(int32_t *res, int n, int k)
500 {
501  int i;
502  int count = 0;
503 
504  for (i = 0; i < n; i++) {
505  int32_t v = -2 * res[i] - 1;
506  v ^= v >> 31;
507  count += (v >> k) + 1 + k;
508  }
509  return count;
510 }
511 
512 
514  int pred_order)
515 {
516  int p, porder, psize;
517  int i, part_end;
518  int count = 0;
519 
520  /* subframe header */
521  count += 8;
522 
523  /* subframe */
524  if (sub->type == FLAC_SUBFRAME_CONSTANT) {
525  count += sub->obits;
526  } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
527  count += s->frame.blocksize * sub->obits;
528  } else {
529  /* warm-up samples */
530  count += pred_order * sub->obits;
531 
532  /* LPC coefficients */
533  if (sub->type == FLAC_SUBFRAME_LPC)
534  count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
535 
536  /* rice-encoded block */
537  count += 2;
538 
539  /* partition order */
540  porder = sub->rc.porder;
541  psize = s->frame.blocksize >> porder;
542  count += 4;
543 
544  /* residual */
545  i = pred_order;
546  part_end = psize;
547  for (p = 0; p < 1 << porder; p++) {
548  int k = sub->rc.params[p];
549  count += 4;
550  count += rice_count_exact(&sub->residual[i], part_end - i, k);
551  i = part_end;
552  part_end = FFMIN(s->frame.blocksize, part_end + psize);
553  }
554  }
555 
556  return count;
557 }
558 
559 
560 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
561 
565 static int find_optimal_param(uint32_t sum, int n)
566 {
567  int k;
568  uint32_t sum2;
569 
570  if (sum <= n >> 1)
571  return 0;
572  sum2 = sum - (n >> 1);
573  k = av_log2(n < 256 ? FASTDIV(sum2, n) : sum2 / n);
574  return FFMIN(k, MAX_RICE_PARAM);
575 }
576 
577 
578 static uint32_t calc_optimal_rice_params(RiceContext *rc, int porder,
579  uint32_t *sums, int n, int pred_order)
580 {
581  int i;
582  int k, cnt, part;
583  uint32_t all_bits;
584 
585  part = (1 << porder);
586  all_bits = 4 * part;
587 
588  cnt = (n >> porder) - pred_order;
589  for (i = 0; i < part; i++) {
590  k = find_optimal_param(sums[i], cnt);
591  rc->params[i] = k;
592  all_bits += rice_encode_count(sums[i], cnt, k);
593  cnt = n >> porder;
594  }
595 
596  rc->porder = porder;
597 
598  return all_bits;
599 }
600 
601 
602 static void calc_sums(int pmin, int pmax, uint32_t *data, int n, int pred_order,
603  uint32_t sums[][MAX_PARTITIONS])
604 {
605  int i, j;
606  int parts;
607  uint32_t *res, *res_end;
608 
609  /* sums for highest level */
610  parts = (1 << pmax);
611  res = &data[pred_order];
612  res_end = &data[n >> pmax];
613  for (i = 0; i < parts; i++) {
614  uint32_t sum = 0;
615  while (res < res_end)
616  sum += *(res++);
617  sums[pmax][i] = sum;
618  res_end += n >> pmax;
619  }
620  /* sums for lower levels */
621  for (i = pmax - 1; i >= pmin; i--) {
622  parts = (1 << i);
623  for (j = 0; j < parts; j++)
624  sums[i][j] = sums[i+1][2*j] + sums[i+1][2*j+1];
625  }
626 }
627 
628 
629 static uint32_t calc_rice_params(RiceContext *rc, int pmin, int pmax,
630  int32_t *data, int n, int pred_order)
631 {
632  int i;
633  uint32_t bits[MAX_PARTITION_ORDER+1];
634  int opt_porder;
635  RiceContext tmp_rc;
636  uint32_t *udata;
637  uint32_t sums[MAX_PARTITION_ORDER+1][MAX_PARTITIONS];
638 
639  assert(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
640  assert(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
641  assert(pmin <= pmax);
642 
643  udata = av_malloc(n * sizeof(uint32_t));
644  for (i = 0; i < n; i++)
645  udata[i] = (2*data[i]) ^ (data[i]>>31);
646 
647  calc_sums(pmin, pmax, udata, n, pred_order, sums);
648 
649  opt_porder = pmin;
650  bits[pmin] = UINT32_MAX;
651  for (i = pmin; i <= pmax; i++) {
652  bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums[i], n, pred_order);
653  if (bits[i] <= bits[opt_porder]) {
654  opt_porder = i;
655  *rc = tmp_rc;
656  }
657  }
658 
659  av_freep(&udata);
660  return bits[opt_porder];
661 }
662 
663 
664 static int get_max_p_order(int max_porder, int n, int order)
665 {
666  int porder = FFMIN(max_porder, av_log2(n^(n-1)));
667  if (order > 0)
668  porder = FFMIN(porder, av_log2(n/order));
669  return porder;
670 }
671 
672 
674  FlacSubframe *sub, int pred_order)
675 {
677  s->frame.blocksize, pred_order);
679  s->frame.blocksize, pred_order);
680 
681  uint32_t bits = 8 + pred_order * sub->obits + 2 + 4;
682  if (sub->type == FLAC_SUBFRAME_LPC)
683  bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
684  bits += calc_rice_params(&sub->rc, pmin, pmax, sub->residual,
685  s->frame.blocksize, pred_order);
686  return bits;
687 }
688 
689 
690 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
691  int order)
692 {
693  int i;
694 
695  for (i = 0; i < order; i++)
696  res[i] = smp[i];
697 
698  if (order == 0) {
699  for (i = order; i < n; i++)
700  res[i] = smp[i];
701  } else if (order == 1) {
702  for (i = order; i < n; i++)
703  res[i] = smp[i] - smp[i-1];
704  } else if (order == 2) {
705  int a = smp[order-1] - smp[order-2];
706  for (i = order; i < n; i += 2) {
707  int b = smp[i ] - smp[i-1];
708  res[i] = b - a;
709  a = smp[i+1] - smp[i ];
710  res[i+1] = a - b;
711  }
712  } else if (order == 3) {
713  int a = smp[order-1] - smp[order-2];
714  int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
715  for (i = order; i < n; i += 2) {
716  int b = smp[i ] - smp[i-1];
717  int d = b - a;
718  res[i] = d - c;
719  a = smp[i+1] - smp[i ];
720  c = a - b;
721  res[i+1] = c - d;
722  }
723  } else {
724  int a = smp[order-1] - smp[order-2];
725  int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
726  int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
727  for (i = order; i < n; i += 2) {
728  int b = smp[i ] - smp[i-1];
729  int d = b - a;
730  int f = d - c;
731  res[i ] = f - e;
732  a = smp[i+1] - smp[i ];
733  c = a - b;
734  e = c - d;
735  res[i+1] = e - f;
736  }
737  }
738 }
739 
740 
741 #define LPC1(x) {\
742  int c = coefs[(x)-1];\
743  p0 += c * s;\
744  s = smp[i-(x)+1];\
745  p1 += c * s;\
746 }
747 
749  const int32_t *smp, int n, int order,
750  const int32_t *coefs, int shift, int big)
751 {
752  int i;
753  for (i = order; i < n; i += 2) {
754  int s = smp[i-order];
755  int p0 = 0, p1 = 0;
756  if (big) {
757  switch (order) {
758  case 32: LPC1(32)
759  case 31: LPC1(31)
760  case 30: LPC1(30)
761  case 29: LPC1(29)
762  case 28: LPC1(28)
763  case 27: LPC1(27)
764  case 26: LPC1(26)
765  case 25: LPC1(25)
766  case 24: LPC1(24)
767  case 23: LPC1(23)
768  case 22: LPC1(22)
769  case 21: LPC1(21)
770  case 20: LPC1(20)
771  case 19: LPC1(19)
772  case 18: LPC1(18)
773  case 17: LPC1(17)
774  case 16: LPC1(16)
775  case 15: LPC1(15)
776  case 14: LPC1(14)
777  case 13: LPC1(13)
778  case 12: LPC1(12)
779  case 11: LPC1(11)
780  case 10: LPC1(10)
781  case 9: LPC1( 9)
782  LPC1( 8)
783  LPC1( 7)
784  LPC1( 6)
785  LPC1( 5)
786  LPC1( 4)
787  LPC1( 3)
788  LPC1( 2)
789  LPC1( 1)
790  }
791  } else {
792  switch (order) {
793  case 8: LPC1( 8)
794  case 7: LPC1( 7)
795  case 6: LPC1( 6)
796  case 5: LPC1( 5)
797  case 4: LPC1( 4)
798  case 3: LPC1( 3)
799  case 2: LPC1( 2)
800  case 1: LPC1( 1)
801  }
802  }
803  res[i ] = smp[i ] - (p0 >> shift);
804  res[i+1] = smp[i+1] - (p1 >> shift);
805  }
806 }
807 
808 
809 static void encode_residual_lpc(int32_t *res, const int32_t *smp, int n,
810  int order, const int32_t *coefs, int shift)
811 {
812  int i;
813  for (i = 0; i < order; i++)
814  res[i] = smp[i];
815 #if CONFIG_SMALL
816  for (i = order; i < n; i += 2) {
817  int j;
818  int s = smp[i];
819  int p0 = 0, p1 = 0;
820  for (j = 0; j < order; j++) {
821  int c = coefs[j];
822  p1 += c * s;
823  s = smp[i-j-1];
824  p0 += c * s;
825  }
826  res[i ] = smp[i ] - (p0 >> shift);
827  res[i+1] = smp[i+1] - (p1 >> shift);
828  }
829 #else
830  switch (order) {
831  case 1: encode_residual_lpc_unrolled(res, smp, n, 1, coefs, shift, 0); break;
832  case 2: encode_residual_lpc_unrolled(res, smp, n, 2, coefs, shift, 0); break;
833  case 3: encode_residual_lpc_unrolled(res, smp, n, 3, coefs, shift, 0); break;
834  case 4: encode_residual_lpc_unrolled(res, smp, n, 4, coefs, shift, 0); break;
835  case 5: encode_residual_lpc_unrolled(res, smp, n, 5, coefs, shift, 0); break;
836  case 6: encode_residual_lpc_unrolled(res, smp, n, 6, coefs, shift, 0); break;
837  case 7: encode_residual_lpc_unrolled(res, smp, n, 7, coefs, shift, 0); break;
838  case 8: encode_residual_lpc_unrolled(res, smp, n, 8, coefs, shift, 0); break;
839  default: encode_residual_lpc_unrolled(res, smp, n, order, coefs, shift, 1); break;
840  }
841 #endif
842 }
843 
844 
845 static int encode_residual_ch(FlacEncodeContext *s, int ch)
846 {
847  int i, n;
848  int min_order, max_order, opt_order, omethod;
849  FlacFrame *frame;
850  FlacSubframe *sub;
851  int32_t coefs[MAX_LPC_ORDER][MAX_LPC_ORDER];
852  int shift[MAX_LPC_ORDER];
853  int32_t *res, *smp;
854 
855  frame = &s->frame;
856  sub = &frame->subframes[ch];
857  res = sub->residual;
858  smp = sub->samples;
859  n = frame->blocksize;
860 
861  /* CONSTANT */
862  for (i = 1; i < n; i++)
863  if(smp[i] != smp[0])
864  break;
865  if (i == n) {
866  sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
867  res[0] = smp[0];
868  return subframe_count_exact(s, sub, 0);
869  }
870 
871  /* VERBATIM */
872  if (frame->verbatim_only || n < 5) {
873  sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
874  memcpy(res, smp, n * sizeof(int32_t));
875  return subframe_count_exact(s, sub, 0);
876  }
877 
878  min_order = s->options.min_prediction_order;
879  max_order = s->options.max_prediction_order;
880  omethod = s->options.prediction_order_method;
881 
882  /* FIXED */
883  sub->type = FLAC_SUBFRAME_FIXED;
884  if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
885  s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
886  uint32_t bits[MAX_FIXED_ORDER+1];
887  if (max_order > MAX_FIXED_ORDER)
888  max_order = MAX_FIXED_ORDER;
889  opt_order = 0;
890  bits[0] = UINT32_MAX;
891  for (i = min_order; i <= max_order; i++) {
892  encode_residual_fixed(res, smp, n, i);
893  bits[i] = find_subframe_rice_params(s, sub, i);
894  if (bits[i] < bits[opt_order])
895  opt_order = i;
896  }
897  sub->order = opt_order;
898  sub->type_code = sub->type | sub->order;
899  if (sub->order != max_order) {
900  encode_residual_fixed(res, smp, n, sub->order);
901  find_subframe_rice_params(s, sub, sub->order);
902  }
903  return subframe_count_exact(s, sub, sub->order);
904  }
905 
906  /* LPC */
907  sub->type = FLAC_SUBFRAME_LPC;
908  opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
909  s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
910  s->options.lpc_passes, omethod,
911  MAX_LPC_SHIFT, 0);
912 
913  if (omethod == ORDER_METHOD_2LEVEL ||
914  omethod == ORDER_METHOD_4LEVEL ||
915  omethod == ORDER_METHOD_8LEVEL) {
916  int levels = 1 << omethod;
917  uint32_t bits[1 << ORDER_METHOD_8LEVEL];
918  int order = -1;
919  int opt_index = levels-1;
920  opt_order = max_order-1;
921  bits[opt_index] = UINT32_MAX;
922  for (i = levels-1; i >= 0; i--) {
923  int last_order = order;
924  order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
925  order = av_clip(order, min_order - 1, max_order - 1);
926  if (order == last_order)
927  continue;
928  encode_residual_lpc(res, smp, n, order+1, coefs[order], shift[order]);
929  bits[i] = find_subframe_rice_params(s, sub, order+1);
930  if (bits[i] < bits[opt_index]) {
931  opt_index = i;
932  opt_order = order;
933  }
934  }
935  opt_order++;
936  } else if (omethod == ORDER_METHOD_SEARCH) {
937  // brute-force optimal order search
938  uint32_t bits[MAX_LPC_ORDER];
939  opt_order = 0;
940  bits[0] = UINT32_MAX;
941  for (i = min_order-1; i < max_order; i++) {
942  encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
943  bits[i] = find_subframe_rice_params(s, sub, i+1);
944  if (bits[i] < bits[opt_order])
945  opt_order = i;
946  }
947  opt_order++;
948  } else if (omethod == ORDER_METHOD_LOG) {
949  uint32_t bits[MAX_LPC_ORDER];
950  int step;
951 
952  opt_order = min_order - 1 + (max_order-min_order)/3;
953  memset(bits, -1, sizeof(bits));
954 
955  for (step = 16; step; step >>= 1) {
956  int last = opt_order;
957  for (i = last-step; i <= last+step; i += step) {
958  if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
959  continue;
960  encode_residual_lpc(res, smp, n, i+1, coefs[i], shift[i]);
961  bits[i] = find_subframe_rice_params(s, sub, i+1);
962  if (bits[i] < bits[opt_order])
963  opt_order = i;
964  }
965  }
966  opt_order++;
967  }
968 
969  sub->order = opt_order;
970  sub->type_code = sub->type | (sub->order-1);
971  sub->shift = shift[sub->order-1];
972  for (i = 0; i < sub->order; i++)
973  sub->coefs[i] = coefs[sub->order-1][i];
974 
975  encode_residual_lpc(res, smp, n, sub->order, sub->coefs, sub->shift);
976 
977  find_subframe_rice_params(s, sub, sub->order);
978 
979  return subframe_count_exact(s, sub, sub->order);
980 }
981 
982 
984 {
985  uint8_t av_unused tmp;
986  int count;
987 
988  /*
989  <14> Sync code
990  <1> Reserved
991  <1> Blocking strategy
992  <4> Block size in inter-channel samples
993  <4> Sample rate
994  <4> Channel assignment
995  <3> Sample size in bits
996  <1> Reserved
997  */
998  count = 32;
999 
1000  /* coded frame number */
1001  PUT_UTF8(s->frame_count, tmp, count += 8;)
1002 
1003  /* explicit block size */
1004  if (s->frame.bs_code[0] == 6)
1005  count += 8;
1006  else if (s->frame.bs_code[0] == 7)
1007  count += 16;
1008 
1009  /* explicit sample rate */
1010  count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
1011 
1012  /* frame header CRC-8 */
1013  count += 8;
1014 
1015  return count;
1016 }
1017 
1018 
1020 {
1021  int ch, count;
1022 
1023  count = count_frame_header(s);
1024 
1025  for (ch = 0; ch < s->channels; ch++)
1026  count += encode_residual_ch(s, ch);
1027 
1028  count += (8 - (count & 7)) & 7; // byte alignment
1029  count += 16; // CRC-16
1030 
1031  return count >> 3;
1032 }
1033 
1034 
1035 static int estimate_stereo_mode(int32_t *left_ch, int32_t *right_ch, int n)
1036 {
1037  int i, best;
1038  int32_t lt, rt;
1039  uint64_t sum[4];
1040  uint64_t score[4];
1041  int k;
1042 
1043  /* calculate sum of 2nd order residual for each channel */
1044  sum[0] = sum[1] = sum[2] = sum[3] = 0;
1045  for (i = 2; i < n; i++) {
1046  lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1047  rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1048  sum[2] += FFABS((lt + rt) >> 1);
1049  sum[3] += FFABS(lt - rt);
1050  sum[0] += FFABS(lt);
1051  sum[1] += FFABS(rt);
1052  }
1053  /* estimate bit counts */
1054  for (i = 0; i < 4; i++) {
1055  k = find_optimal_param(2 * sum[i], n);
1056  sum[i] = rice_encode_count( 2 * sum[i], n, k);
1057  }
1058 
1059  /* calculate score for each mode */
1060  score[0] = sum[0] + sum[1];
1061  score[1] = sum[0] + sum[3];
1062  score[2] = sum[1] + sum[3];
1063  score[3] = sum[2] + sum[3];
1064 
1065  /* return mode with lowest score */
1066  best = 0;
1067  for (i = 1; i < 4; i++)
1068  if (score[i] < score[best])
1069  best = i;
1070  if (best == 0) {
1071  return FLAC_CHMODE_INDEPENDENT;
1072  } else if (best == 1) {
1073  return FLAC_CHMODE_LEFT_SIDE;
1074  } else if (best == 2) {
1075  return FLAC_CHMODE_RIGHT_SIDE;
1076  } else {
1077  return FLAC_CHMODE_MID_SIDE;
1078  }
1079 }
1080 
1081 
1086 {
1087  FlacFrame *frame;
1088  int32_t *left, *right;
1089  int i, n;
1090 
1091  frame = &s->frame;
1092  n = frame->blocksize;
1093  left = frame->subframes[0].samples;
1094  right = frame->subframes[1].samples;
1095 
1096  if (s->channels != 2) {
1098  return;
1099  }
1100 
1101  frame->ch_mode = estimate_stereo_mode(left, right, n);
1102 
1103  /* perform decorrelation and adjust bits-per-sample */
1104  if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1105  return;
1106  if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1107  int32_t tmp;
1108  for (i = 0; i < n; i++) {
1109  tmp = left[i];
1110  left[i] = (tmp + right[i]) >> 1;
1111  right[i] = tmp - right[i];
1112  }
1113  frame->subframes[1].obits++;
1114  } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1115  for (i = 0; i < n; i++)
1116  right[i] = left[i] - right[i];
1117  frame->subframes[1].obits++;
1118  } else {
1119  for (i = 0; i < n; i++)
1120  left[i] -= right[i];
1121  frame->subframes[0].obits++;
1122  }
1123 }
1124 
1125 
1126 static void write_utf8(PutBitContext *pb, uint32_t val)
1127 {
1128  uint8_t tmp;
1129  PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1130 }
1131 
1132 
1134 {
1135  FlacFrame *frame;
1136  int crc;
1137 
1138  frame = &s->frame;
1139 
1140  put_bits(&s->pb, 16, 0xFFF8);
1141  put_bits(&s->pb, 4, frame->bs_code[0]);
1142  put_bits(&s->pb, 4, s->sr_code[0]);
1143 
1144  if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1145  put_bits(&s->pb, 4, s->channels-1);
1146  else
1147  put_bits(&s->pb, 4, frame->ch_mode);
1148 
1149  put_bits(&s->pb, 3, 4); /* bits-per-sample code */
1150  put_bits(&s->pb, 1, 0);
1151  write_utf8(&s->pb, s->frame_count);
1152 
1153  if (frame->bs_code[0] == 6)
1154  put_bits(&s->pb, 8, frame->bs_code[1]);
1155  else if (frame->bs_code[0] == 7)
1156  put_bits(&s->pb, 16, frame->bs_code[1]);
1157 
1158  if (s->sr_code[0] == 12)
1159  put_bits(&s->pb, 8, s->sr_code[1]);
1160  else if (s->sr_code[0] > 12)
1161  put_bits(&s->pb, 16, s->sr_code[1]);
1162 
1163  flush_put_bits(&s->pb);
1164  crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1165  put_bits_count(&s->pb) >> 3);
1166  put_bits(&s->pb, 8, crc);
1167 }
1168 
1169 
1171 {
1172  int ch;
1173 
1174  for (ch = 0; ch < s->channels; ch++) {
1175  FlacSubframe *sub = &s->frame.subframes[ch];
1176  int i, p, porder, psize;
1177  int32_t *part_end;
1178  int32_t *res = sub->residual;
1179  int32_t *frame_end = &sub->residual[s->frame.blocksize];
1180 
1181  /* subframe header */
1182  put_bits(&s->pb, 1, 0);
1183  put_bits(&s->pb, 6, sub->type_code);
1184  put_bits(&s->pb, 1, 0); /* no wasted bits */
1185 
1186  /* subframe */
1187  if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1188  put_sbits(&s->pb, sub->obits, res[0]);
1189  } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1190  while (res < frame_end)
1191  put_sbits(&s->pb, sub->obits, *res++);
1192  } else {
1193  /* warm-up samples */
1194  for (i = 0; i < sub->order; i++)
1195  put_sbits(&s->pb, sub->obits, *res++);
1196 
1197  /* LPC coefficients */
1198  if (sub->type == FLAC_SUBFRAME_LPC) {
1199  int cbits = s->options.lpc_coeff_precision;
1200  put_bits( &s->pb, 4, cbits-1);
1201  put_sbits(&s->pb, 5, sub->shift);
1202  for (i = 0; i < sub->order; i++)
1203  put_sbits(&s->pb, cbits, sub->coefs[i]);
1204  }
1205 
1206  /* rice-encoded block */
1207  put_bits(&s->pb, 2, 0);
1208 
1209  /* partition order */
1210  porder = sub->rc.porder;
1211  psize = s->frame.blocksize >> porder;
1212  put_bits(&s->pb, 4, porder);
1213 
1214  /* residual */
1215  part_end = &sub->residual[psize];
1216  for (p = 0; p < 1 << porder; p++) {
1217  int k = sub->rc.params[p];
1218  put_bits(&s->pb, 4, k);
1219  while (res < part_end)
1220  set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1221  part_end = FFMIN(frame_end, part_end + psize);
1222  }
1223  }
1224  }
1225 }
1226 
1227 
1229 {
1230  int crc;
1231  flush_put_bits(&s->pb);
1233  put_bits_count(&s->pb)>>3));
1234  put_bits(&s->pb, 16, crc);
1235  flush_put_bits(&s->pb);
1236 }
1237 
1238 
1239 static int write_frame(FlacEncodeContext *s, uint8_t *frame, int buf_size)
1240 {
1241  init_put_bits(&s->pb, frame, buf_size);
1242  write_frame_header(s);
1243  write_subframes(s);
1244  write_frame_footer(s);
1245  return put_bits_count(&s->pb) >> 3;
1246 }
1247 
1248 
1249 static void update_md5_sum(FlacEncodeContext *s, const int16_t *samples)
1250 {
1251 #if HAVE_BIGENDIAN
1252  int i;
1253  for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1254  int16_t smp = av_le2ne16(samples[i]);
1255  av_md5_update(s->md5ctx, (uint8_t *)&smp, 2);
1256  }
1257 #else
1258  av_md5_update(s->md5ctx, (const uint8_t *)samples, s->frame.blocksize*s->channels*2);
1259 #endif
1260 }
1261 
1262 
1263 static int flac_encode_frame(AVCodecContext *avctx, uint8_t *frame,
1264  int buf_size, void *data)
1265 {
1266  FlacEncodeContext *s;
1267  const int16_t *samples = data;
1268  int frame_bytes, out_bytes;
1269 
1270  s = avctx->priv_data;
1271 
1272  /* when the last block is reached, update the header in extradata */
1273  if (!data) {
1275  av_md5_final(s->md5ctx, s->md5sum);
1276  write_streaminfo(s, avctx->extradata);
1277  return 0;
1278  }
1279 
1280  /* change max_framesize for small final frame */
1281  if (avctx->frame_size < s->frame.blocksize) {
1283  s->channels, 16);
1284  }
1285 
1286  init_frame(s);
1287 
1288  copy_samples(s, samples);
1289 
1291 
1292  frame_bytes = encode_frame(s);
1293 
1294  /* fallback to verbatim mode if the compressed frame is larger than it
1295  would be if encoded uncompressed. */
1296  if (frame_bytes > s->max_framesize) {
1297  s->frame.verbatim_only = 1;
1298  frame_bytes = encode_frame(s);
1299  }
1300 
1301  if (buf_size < frame_bytes) {
1302  av_log(avctx, AV_LOG_ERROR, "output buffer too small\n");
1303  return 0;
1304  }
1305  out_bytes = write_frame(s, frame, buf_size);
1306 
1307  s->frame_count++;
1308  avctx->coded_frame->pts = s->sample_count;
1309  s->sample_count += avctx->frame_size;
1310  update_md5_sum(s, samples);
1311  if (out_bytes > s->max_encoded_framesize)
1312  s->max_encoded_framesize = out_bytes;
1313  if (out_bytes < s->min_framesize)
1314  s->min_framesize = out_bytes;
1315 
1316  return out_bytes;
1317 }
1318 
1319 
1321 {
1322  if (avctx->priv_data) {
1323  FlacEncodeContext *s = avctx->priv_data;
1324  av_freep(&s->md5ctx);
1325  ff_lpc_end(&s->lpc_ctx);
1326  }
1327  av_freep(&avctx->extradata);
1328  avctx->extradata_size = 0;
1329  av_freep(&avctx->coded_frame);
1330  return 0;
1331 }
1332 
1333 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1334 static const AVOption options[] = {
1335 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.dbl = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1336 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.dbl = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
1337 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1338 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1339 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1340 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1341 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.dbl = -1 }, INT_MIN, INT_MAX, FLAGS },
1342 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1343 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1344 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.dbl = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
1345 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1346 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1347 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1348 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1349 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1350 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.dbl = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1351 { NULL },
1352 };
1353 
1354 static const AVClass flac_encoder_class = {
1355  "FLAC encoder",
1357  options,
1359 };
1360 
1362  .name = "flac",
1363  .type = AVMEDIA_TYPE_AUDIO,
1364  .id = CODEC_ID_FLAC,
1365  .priv_data_size = sizeof(FlacEncodeContext),
1367  .encode = flac_encode_frame,
1369  .capabilities = CODEC_CAP_SMALL_LAST_FRAME | CODEC_CAP_DELAY,
1370  .sample_fmts = (const enum AVSampleFormat[]){AV_SAMPLE_FMT_S16,AV_SAMPLE_FMT_NONE},
1371  .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1372  .priv_class = &flac_encoder_class,
1373 };