FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
flacenc.c
Go to the documentation of this file.
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/avassert.h"
23 #include "libavutil/crc.h"
24 #include "libavutil/intmath.h"
25 #include "libavutil/md5.h"
26 #include "libavutil/opt.h"
27 #include "avcodec.h"
28 #include "bswapdsp.h"
29 #include "put_bits.h"
30 #include "golomb.h"
31 #include "internal.h"
32 #include "lpc.h"
33 #include "flac.h"
34 #include "flacdata.h"
35 #include "flacdsp.h"
36 
37 #define FLAC_SUBFRAME_CONSTANT 0
38 #define FLAC_SUBFRAME_VERBATIM 1
39 #define FLAC_SUBFRAME_FIXED 8
40 #define FLAC_SUBFRAME_LPC 32
41 
42 #define MAX_FIXED_ORDER 4
43 #define MAX_PARTITION_ORDER 8
44 #define MAX_PARTITIONS (1 << MAX_PARTITION_ORDER)
45 #define MAX_LPC_PRECISION 15
46 #define MAX_LPC_SHIFT 15
47 
48 enum CodingMode {
51 };
52 
53 typedef struct CompressionOptions {
64  int ch_mode;
68 
69 typedef struct RiceContext {
71  int porder;
73 } RiceContext;
74 
75 typedef struct FlacSubframe {
76  int type;
77  int type_code;
78  int obits;
79  int wasted;
80  int order;
82  int shift;
83 
86  uint64_t rc_sums[32][MAX_PARTITIONS];
87 
90 } FlacSubframe;
91 
92 typedef struct FlacFrame {
94  int blocksize;
95  int bs_code[2];
97  int ch_mode;
99 } FlacFrame;
100 
101 typedef struct FlacEncodeContext {
102  AVClass *class;
104  int channels;
106  int sr_code[2];
107  int bps_code;
112  uint32_t frame_count;
113  uint64_t sample_count;
119  struct AVMD5 *md5ctx;
121  unsigned int md5_buffer_size;
124 
125  int flushed;
126  int64_t next_pts;
128 
129 
130 /**
131  * Write streaminfo metadata block to byte array.
132  */
134 {
135  PutBitContext pb;
136 
137  memset(header, 0, FLAC_STREAMINFO_SIZE);
138  init_put_bits(&pb, header, FLAC_STREAMINFO_SIZE);
139 
140  /* streaminfo metadata block */
141  put_bits(&pb, 16, s->max_blocksize);
142  put_bits(&pb, 16, s->max_blocksize);
143  put_bits(&pb, 24, s->min_framesize);
144  put_bits(&pb, 24, s->max_framesize);
145  put_bits(&pb, 20, s->samplerate);
146  put_bits(&pb, 3, s->channels-1);
147  put_bits(&pb, 5, s->avctx->bits_per_raw_sample - 1);
148  /* write 36-bit sample count in 2 put_bits() calls */
149  put_bits(&pb, 24, (s->sample_count & 0xFFFFFF000LL) >> 12);
150  put_bits(&pb, 12, s->sample_count & 0x000000FFFLL);
151  flush_put_bits(&pb);
152  memcpy(&header[18], s->md5sum, 16);
153 }
154 
155 
156 /**
157  * Set blocksize based on samplerate.
158  * Choose the closest predefined blocksize >= BLOCK_TIME_MS milliseconds.
159  */
160 static int select_blocksize(int samplerate, int block_time_ms)
161 {
162  int i;
163  int target;
164  int blocksize;
165 
166  av_assert0(samplerate > 0);
167  blocksize = ff_flac_blocksize_table[1];
168  target = (samplerate * block_time_ms) / 1000;
169  for (i = 0; i < 16; i++) {
170  if (target >= ff_flac_blocksize_table[i] &&
171  ff_flac_blocksize_table[i] > blocksize) {
172  blocksize = ff_flac_blocksize_table[i];
173  }
174  }
175  return blocksize;
176 }
177 
178 
180 {
181  AVCodecContext *avctx = s->avctx;
182  CompressionOptions *opt = &s->options;
183 
184  av_log(avctx, AV_LOG_DEBUG, " compression: %d\n", opt->compression_level);
185 
186  switch (opt->lpc_type) {
187  case FF_LPC_TYPE_NONE:
188  av_log(avctx, AV_LOG_DEBUG, " lpc type: None\n");
189  break;
190  case FF_LPC_TYPE_FIXED:
191  av_log(avctx, AV_LOG_DEBUG, " lpc type: Fixed pre-defined coefficients\n");
192  break;
194  av_log(avctx, AV_LOG_DEBUG, " lpc type: Levinson-Durbin recursion with Welch window\n");
195  break;
197  av_log(avctx, AV_LOG_DEBUG, " lpc type: Cholesky factorization, %d pass%s\n",
198  opt->lpc_passes, opt->lpc_passes == 1 ? "" : "es");
199  break;
200  }
201 
202  av_log(avctx, AV_LOG_DEBUG, " prediction order: %d, %d\n",
204 
205  switch (opt->prediction_order_method) {
206  case ORDER_METHOD_EST:
207  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "estimate");
208  break;
209  case ORDER_METHOD_2LEVEL:
210  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "2-level");
211  break;
212  case ORDER_METHOD_4LEVEL:
213  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "4-level");
214  break;
215  case ORDER_METHOD_8LEVEL:
216  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "8-level");
217  break;
218  case ORDER_METHOD_SEARCH:
219  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "full search");
220  break;
221  case ORDER_METHOD_LOG:
222  av_log(avctx, AV_LOG_DEBUG, " order method: %s\n", "log search");
223  break;
224  }
225 
226 
227  av_log(avctx, AV_LOG_DEBUG, " partition order: %d, %d\n",
229 
230  av_log(avctx, AV_LOG_DEBUG, " block size: %d\n", avctx->frame_size);
231 
232  av_log(avctx, AV_LOG_DEBUG, " lpc precision: %d\n",
233  opt->lpc_coeff_precision);
234 }
235 
236 
238 {
239  int freq = avctx->sample_rate;
240  int channels = avctx->channels;
241  FlacEncodeContext *s = avctx->priv_data;
242  int i, level, ret;
243  uint8_t *streaminfo;
244 
245  s->avctx = avctx;
246 
247  switch (avctx->sample_fmt) {
248  case AV_SAMPLE_FMT_S16:
249  avctx->bits_per_raw_sample = 16;
250  s->bps_code = 4;
251  break;
252  case AV_SAMPLE_FMT_S32:
253  if (avctx->bits_per_raw_sample != 24)
254  av_log(avctx, AV_LOG_WARNING, "encoding as 24 bits-per-sample\n");
255  avctx->bits_per_raw_sample = 24;
256  s->bps_code = 6;
257  break;
258  }
259 
260  if (channels < 1 || channels > FLAC_MAX_CHANNELS) {
261  av_log(avctx, AV_LOG_ERROR, "%d channels not supported (max %d)\n",
262  channels, FLAC_MAX_CHANNELS);
263  return AVERROR(EINVAL);
264  }
265  s->channels = channels;
266 
267  /* find samplerate in table */
268  if (freq < 1)
269  return -1;
270  for (i = 4; i < 12; i++) {
271  if (freq == ff_flac_sample_rate_table[i]) {
273  s->sr_code[0] = i;
274  s->sr_code[1] = 0;
275  break;
276  }
277  }
278  /* if not in table, samplerate is non-standard */
279  if (i == 12) {
280  if (freq % 1000 == 0 && freq < 255000) {
281  s->sr_code[0] = 12;
282  s->sr_code[1] = freq / 1000;
283  } else if (freq % 10 == 0 && freq < 655350) {
284  s->sr_code[0] = 14;
285  s->sr_code[1] = freq / 10;
286  } else if (freq < 65535) {
287  s->sr_code[0] = 13;
288  s->sr_code[1] = freq;
289  } else {
290  av_log(avctx, AV_LOG_ERROR, "%d Hz not supported\n", freq);
291  return AVERROR(EINVAL);
292  }
293  s->samplerate = freq;
294  }
295 
296  /* set compression option defaults based on avctx->compression_level */
297  if (avctx->compression_level < 0)
298  s->options.compression_level = 5;
299  else
301 
302  level = s->options.compression_level;
303  if (level > 12) {
304  av_log(avctx, AV_LOG_ERROR, "invalid compression level: %d\n",
306  return AVERROR(EINVAL);
307  }
308 
309  s->options.block_time_ms = ((int[]){ 27, 27, 27,105,105,105,105,105,105,105,105,105,105})[level];
310 
316  FF_LPC_TYPE_LEVINSON})[level];
317 
318  s->options.min_prediction_order = ((int[]){ 2, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1})[level];
319  s->options.max_prediction_order = ((int[]){ 3, 4, 4, 6, 8, 8, 8, 8, 12, 12, 12, 32, 32})[level];
320 
321  if (s->options.prediction_order_method < 0)
326  ORDER_METHOD_SEARCH})[level];
327 
329  av_log(avctx, AV_LOG_ERROR, "invalid partition orders: min=%d max=%d\n",
331  return AVERROR(EINVAL);
332  }
333  if (s->options.min_partition_order < 0)
334  s->options.min_partition_order = ((int[]){ 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})[level];
335  if (s->options.max_partition_order < 0)
336  s->options.max_partition_order = ((int[]){ 2, 2, 3, 3, 3, 8, 8, 8, 8, 8, 8, 8, 8})[level];
337 
338  if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
340  } else if (avctx->min_prediction_order >= 0) {
341  if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
342  if (avctx->min_prediction_order > MAX_FIXED_ORDER) {
343  av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
344  avctx->min_prediction_order);
345  return AVERROR(EINVAL);
346  }
347  } else if (avctx->min_prediction_order < MIN_LPC_ORDER ||
349  av_log(avctx, AV_LOG_ERROR, "invalid min prediction order: %d\n",
350  avctx->min_prediction_order);
351  return AVERROR(EINVAL);
352  }
354  }
355  if (s->options.lpc_type == FF_LPC_TYPE_NONE) {
357  } else if (avctx->max_prediction_order >= 0) {
358  if (s->options.lpc_type == FF_LPC_TYPE_FIXED) {
359  if (avctx->max_prediction_order > MAX_FIXED_ORDER) {
360  av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
361  avctx->max_prediction_order);
362  return AVERROR(EINVAL);
363  }
364  } else if (avctx->max_prediction_order < MIN_LPC_ORDER ||
366  av_log(avctx, AV_LOG_ERROR, "invalid max prediction order: %d\n",
367  avctx->max_prediction_order);
368  return AVERROR(EINVAL);
369  }
371  }
373  av_log(avctx, AV_LOG_ERROR, "invalid prediction orders: min=%d max=%d\n",
375  return AVERROR(EINVAL);
376  }
377 
378  if (avctx->frame_size > 0) {
379  if (avctx->frame_size < FLAC_MIN_BLOCKSIZE ||
380  avctx->frame_size > FLAC_MAX_BLOCKSIZE) {
381  av_log(avctx, AV_LOG_ERROR, "invalid block size: %d\n",
382  avctx->frame_size);
383  return AVERROR(EINVAL);
384  }
385  } else {
387  }
388  s->max_blocksize = s->avctx->frame_size;
389 
390  /* set maximum encoded frame size in verbatim mode */
392  s->channels,
394 
395  /* initialize MD5 context */
396  s->md5ctx = av_md5_alloc();
397  if (!s->md5ctx)
398  return AVERROR(ENOMEM);
399  av_md5_init(s->md5ctx);
400 
401  streaminfo = av_malloc(FLAC_STREAMINFO_SIZE);
402  if (!streaminfo)
403  return AVERROR(ENOMEM);
404  write_streaminfo(s, streaminfo);
405  avctx->extradata = streaminfo;
407 
408  s->frame_count = 0;
410 
411  if (channels == 3 &&
413  channels == 4 &&
414  avctx->channel_layout != AV_CH_LAYOUT_2_2 &&
415  avctx->channel_layout != AV_CH_LAYOUT_QUAD ||
416  channels == 5 &&
419  channels == 6 &&
422  if (avctx->channel_layout) {
423  av_log(avctx, AV_LOG_ERROR, "Channel layout not supported by Flac, "
424  "output stream will have incorrect "
425  "channel layout.\n");
426  } else {
427  av_log(avctx, AV_LOG_WARNING, "No channel layout specified. The encoder "
428  "will use Flac channel layout for "
429  "%d channels.\n", channels);
430  }
431  }
432 
433  ret = ff_lpc_init(&s->lpc_ctx, avctx->frame_size,
435 
436  ff_bswapdsp_init(&s->bdsp);
437  ff_flacdsp_init(&s->flac_dsp, avctx->sample_fmt, channels,
438  avctx->bits_per_raw_sample);
439 
441 
442  return ret;
443 }
444 
445 
446 static void init_frame(FlacEncodeContext *s, int nb_samples)
447 {
448  int i, ch;
449  FlacFrame *frame;
450 
451  frame = &s->frame;
452 
453  for (i = 0; i < 16; i++) {
454  if (nb_samples == ff_flac_blocksize_table[i]) {
456  frame->bs_code[0] = i;
457  frame->bs_code[1] = 0;
458  break;
459  }
460  }
461  if (i == 16) {
462  frame->blocksize = nb_samples;
463  if (frame->blocksize <= 256) {
464  frame->bs_code[0] = 6;
465  frame->bs_code[1] = frame->blocksize-1;
466  } else {
467  frame->bs_code[0] = 7;
468  frame->bs_code[1] = frame->blocksize-1;
469  }
470  }
471 
472  for (ch = 0; ch < s->channels; ch++) {
473  FlacSubframe *sub = &frame->subframes[ch];
474 
475  sub->wasted = 0;
476  sub->obits = s->avctx->bits_per_raw_sample;
477 
478  if (sub->obits > 16)
480  else
482  }
483 
484  frame->verbatim_only = 0;
485 }
486 
487 
488 /**
489  * Copy channel-interleaved input samples into separate subframes.
490  */
491 static void copy_samples(FlacEncodeContext *s, const void *samples)
492 {
493  int i, j, ch;
494  FlacFrame *frame;
497 
498 #define COPY_SAMPLES(bits) do { \
499  const int ## bits ## _t *samples0 = samples; \
500  frame = &s->frame; \
501  for (i = 0, j = 0; i < frame->blocksize; i++) \
502  for (ch = 0; ch < s->channels; ch++, j++) \
503  frame->subframes[ch].samples[i] = samples0[j] >> shift; \
504 } while (0)
505 
507  COPY_SAMPLES(16);
508  else
509  COPY_SAMPLES(32);
510 }
511 
512 
513 static uint64_t rice_count_exact(const int32_t *res, int n, int k)
514 {
515  int i;
516  uint64_t count = 0;
517 
518  for (i = 0; i < n; i++) {
519  int32_t v = -2 * res[i] - 1;
520  v ^= v >> 31;
521  count += (v >> k) + 1 + k;
522  }
523  return count;
524 }
525 
526 
528  int pred_order)
529 {
530  int p, porder, psize;
531  int i, part_end;
532  uint64_t count = 0;
533 
534  /* subframe header */
535  count += 8;
536 
537  if (sub->wasted)
538  count += sub->wasted;
539 
540  /* subframe */
541  if (sub->type == FLAC_SUBFRAME_CONSTANT) {
542  count += sub->obits;
543  } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
544  count += s->frame.blocksize * sub->obits;
545  } else {
546  /* warm-up samples */
547  count += pred_order * sub->obits;
548 
549  /* LPC coefficients */
550  if (sub->type == FLAC_SUBFRAME_LPC)
551  count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
552 
553  /* rice-encoded block */
554  count += 2;
555 
556  /* partition order */
557  porder = sub->rc.porder;
558  psize = s->frame.blocksize >> porder;
559  count += 4;
560 
561  /* residual */
562  i = pred_order;
563  part_end = psize;
564  for (p = 0; p < 1 << porder; p++) {
565  int k = sub->rc.params[p];
566  count += sub->rc.coding_mode;
567  count += rice_count_exact(&sub->residual[i], part_end - i, k);
568  i = part_end;
569  part_end = FFMIN(s->frame.blocksize, part_end + psize);
570  }
571  }
572 
573  return count;
574 }
575 
576 
577 #define rice_encode_count(sum, n, k) (((n)*((k)+1))+((sum-(n>>1))>>(k)))
578 
579 /**
580  * Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
581  */
582 static int find_optimal_param(uint64_t sum, int n, int max_param)
583 {
584  int k;
585  uint64_t sum2;
586 
587  if (sum <= n >> 1)
588  return 0;
589  sum2 = sum - (n >> 1);
590  k = av_log2(av_clipl_int32(sum2 / n));
591  return FFMIN(k, max_param);
592 }
593 
594 static int find_optimal_param_exact(uint64_t sums[32][MAX_PARTITIONS], int i, int max_param)
595 {
596  int bestk = 0;
597  int64_t bestbits = INT64_MAX;
598  int k;
599 
600  for (k = 0; k <= max_param; k++) {
601  int64_t bits = sums[k][i];
602  if (bits < bestbits) {
603  bestbits = bits;
604  bestk = k;
605  }
606  }
607 
608  return bestk;
609 }
610 
611 static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder,
612  uint64_t sums[32][MAX_PARTITIONS],
613  int n, int pred_order, int max_param, int exact)
614 {
615  int i;
616  int k, cnt, part;
617  uint64_t all_bits;
618 
619  part = (1 << porder);
620  all_bits = 4 * part;
621 
622  cnt = (n >> porder) - pred_order;
623  for (i = 0; i < part; i++) {
624  if (exact) {
625  k = find_optimal_param_exact(sums, i, max_param);
626  all_bits += sums[k][i];
627  } else {
628  k = find_optimal_param(sums[0][i], cnt, max_param);
629  all_bits += rice_encode_count(sums[0][i], cnt, k);
630  }
631  rc->params[i] = k;
632  cnt = n >> porder;
633  }
634 
635  rc->porder = porder;
636 
637  return all_bits;
638 }
639 
640 
641 static void calc_sum_top(int pmax, int kmax, const uint32_t *data, int n, int pred_order,
642  uint64_t sums[32][MAX_PARTITIONS])
643 {
644  int i, k;
645  int parts;
646  const uint32_t *res, *res_end;
647 
648  /* sums for highest level */
649  parts = (1 << pmax);
650 
651  for (k = 0; k <= kmax; k++) {
652  res = &data[pred_order];
653  res_end = &data[n >> pmax];
654  for (i = 0; i < parts; i++) {
655  if (kmax) {
656  uint64_t sum = (1LL + k) * (res_end - res);
657  while (res < res_end)
658  sum += *(res++) >> k;
659  sums[k][i] = sum;
660  } else {
661  uint64_t sum = 0;
662  while (res < res_end)
663  sum += *(res++);
664  sums[k][i] = sum;
665  }
666  res_end += n >> pmax;
667  }
668  }
669 }
670 
671 static void calc_sum_next(int level, uint64_t sums[32][MAX_PARTITIONS], int kmax)
672 {
673  int i, k;
674  int parts = (1 << level);
675  for (i = 0; i < parts; i++) {
676  for (k=0; k<=kmax; k++)
677  sums[k][i] = sums[k][2*i] + sums[k][2*i+1];
678  }
679 }
680 
681 static uint64_t calc_rice_params(RiceContext *rc,
682  uint32_t udata[FLAC_MAX_BLOCKSIZE],
683  uint64_t sums[32][MAX_PARTITIONS],
684  int pmin, int pmax,
685  const int32_t *data, int n, int pred_order, int exact)
686 {
687  int i;
688  uint64_t bits[MAX_PARTITION_ORDER+1];
689  int opt_porder;
690  RiceContext tmp_rc;
691  int kmax = (1 << rc->coding_mode) - 2;
692 
693  av_assert1(pmin >= 0 && pmin <= MAX_PARTITION_ORDER);
694  av_assert1(pmax >= 0 && pmax <= MAX_PARTITION_ORDER);
695  av_assert1(pmin <= pmax);
696 
697  tmp_rc.coding_mode = rc->coding_mode;
698 
699  for (i = 0; i < n; i++)
700  udata[i] = (2 * data[i]) ^ (data[i] >> 31);
701 
702  calc_sum_top(pmax, exact ? kmax : 0, udata, n, pred_order, sums);
703 
704  opt_porder = pmin;
705  bits[pmin] = UINT32_MAX;
706  for (i = pmax; ; ) {
707  bits[i] = calc_optimal_rice_params(&tmp_rc, i, sums, n, pred_order, kmax, exact);
708  if (bits[i] < bits[opt_porder]) {
709  opt_porder = i;
710  *rc = tmp_rc;
711  }
712  if (i == pmin)
713  break;
714  calc_sum_next(--i, sums, exact ? kmax : 0);
715  }
716 
717  return bits[opt_porder];
718 }
719 
720 
721 static int get_max_p_order(int max_porder, int n, int order)
722 {
723  int porder = FFMIN(max_porder, av_log2(n^(n-1)));
724  if (order > 0)
725  porder = FFMIN(porder, av_log2(n/order));
726  return porder;
727 }
728 
729 
731  FlacSubframe *sub, int pred_order)
732 {
734  s->frame.blocksize, pred_order);
736  s->frame.blocksize, pred_order);
737 
738  uint64_t bits = 8 + pred_order * sub->obits + 2 + sub->rc.coding_mode;
739  if (sub->type == FLAC_SUBFRAME_LPC)
740  bits += 4 + 5 + pred_order * s->options.lpc_coeff_precision;
741  bits += calc_rice_params(&sub->rc, sub->rc_udata, sub->rc_sums, pmin, pmax, sub->residual,
742  s->frame.blocksize, pred_order, s->options.exact_rice_parameters);
743  return bits;
744 }
745 
746 
747 static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n,
748  int order)
749 {
750  int i;
751 
752  for (i = 0; i < order; i++)
753  res[i] = smp[i];
754 
755  if (order == 0) {
756  for (i = order; i < n; i++)
757  res[i] = smp[i];
758  } else if (order == 1) {
759  for (i = order; i < n; i++)
760  res[i] = smp[i] - smp[i-1];
761  } else if (order == 2) {
762  int a = smp[order-1] - smp[order-2];
763  for (i = order; i < n; i += 2) {
764  int b = smp[i ] - smp[i-1];
765  res[i] = b - a;
766  a = smp[i+1] - smp[i ];
767  res[i+1] = a - b;
768  }
769  } else if (order == 3) {
770  int a = smp[order-1] - smp[order-2];
771  int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
772  for (i = order; i < n; i += 2) {
773  int b = smp[i ] - smp[i-1];
774  int d = b - a;
775  res[i] = d - c;
776  a = smp[i+1] - smp[i ];
777  c = a - b;
778  res[i+1] = c - d;
779  }
780  } else {
781  int a = smp[order-1] - smp[order-2];
782  int c = smp[order-1] - 2*smp[order-2] + smp[order-3];
783  int e = smp[order-1] - 3*smp[order-2] + 3*smp[order-3] - smp[order-4];
784  for (i = order; i < n; i += 2) {
785  int b = smp[i ] - smp[i-1];
786  int d = b - a;
787  int f = d - c;
788  res[i ] = f - e;
789  a = smp[i+1] - smp[i ];
790  c = a - b;
791  e = c - d;
792  res[i+1] = e - f;
793  }
794  }
795 }
796 
797 
799 {
800  int i, n;
801  int min_order, max_order, opt_order, omethod;
802  FlacFrame *frame;
803  FlacSubframe *sub;
805  int shift[MAX_LPC_ORDER];
806  int32_t *res, *smp;
807 
808  frame = &s->frame;
809  sub = &frame->subframes[ch];
810  res = sub->residual;
811  smp = sub->samples;
812  n = frame->blocksize;
813 
814  /* CONSTANT */
815  for (i = 1; i < n; i++)
816  if(smp[i] != smp[0])
817  break;
818  if (i == n) {
819  sub->type = sub->type_code = FLAC_SUBFRAME_CONSTANT;
820  res[0] = smp[0];
821  return subframe_count_exact(s, sub, 0);
822  }
823 
824  /* VERBATIM */
825  if (frame->verbatim_only || n < 5) {
826  sub->type = sub->type_code = FLAC_SUBFRAME_VERBATIM;
827  memcpy(res, smp, n * sizeof(int32_t));
828  return subframe_count_exact(s, sub, 0);
829  }
830 
831  min_order = s->options.min_prediction_order;
832  max_order = s->options.max_prediction_order;
833  omethod = s->options.prediction_order_method;
834 
835  /* FIXED */
836  sub->type = FLAC_SUBFRAME_FIXED;
837  if (s->options.lpc_type == FF_LPC_TYPE_NONE ||
838  s->options.lpc_type == FF_LPC_TYPE_FIXED || n <= max_order) {
839  uint64_t bits[MAX_FIXED_ORDER+1];
840  if (max_order > MAX_FIXED_ORDER)
841  max_order = MAX_FIXED_ORDER;
842  opt_order = 0;
843  bits[0] = UINT32_MAX;
844  for (i = min_order; i <= max_order; i++) {
845  encode_residual_fixed(res, smp, n, i);
846  bits[i] = find_subframe_rice_params(s, sub, i);
847  if (bits[i] < bits[opt_order])
848  opt_order = i;
849  }
850  sub->order = opt_order;
851  sub->type_code = sub->type | sub->order;
852  if (sub->order != max_order) {
853  encode_residual_fixed(res, smp, n, sub->order);
854  find_subframe_rice_params(s, sub, sub->order);
855  }
856  return subframe_count_exact(s, sub, sub->order);
857  }
858 
859  /* LPC */
860  sub->type = FLAC_SUBFRAME_LPC;
861  opt_order = ff_lpc_calc_coefs(&s->lpc_ctx, smp, n, min_order, max_order,
862  s->options.lpc_coeff_precision, coefs, shift, s->options.lpc_type,
863  s->options.lpc_passes, omethod,
864  MAX_LPC_SHIFT, 0);
865 
866  if (omethod == ORDER_METHOD_2LEVEL ||
867  omethod == ORDER_METHOD_4LEVEL ||
868  omethod == ORDER_METHOD_8LEVEL) {
869  int levels = 1 << omethod;
870  uint64_t bits[1 << ORDER_METHOD_8LEVEL];
871  int order = -1;
872  int opt_index = levels-1;
873  opt_order = max_order-1;
874  bits[opt_index] = UINT32_MAX;
875  for (i = levels-1; i >= 0; i--) {
876  int last_order = order;
877  order = min_order + (((max_order-min_order+1) * (i+1)) / levels)-1;
878  order = av_clip(order, min_order - 1, max_order - 1);
879  if (order == last_order)
880  continue;
881  if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(order) <= 32) {
882  s->flac_dsp.lpc16_encode(res, smp, n, order+1, coefs[order],
883  shift[order]);
884  } else {
885  s->flac_dsp.lpc32_encode(res, smp, n, order+1, coefs[order],
886  shift[order]);
887  }
888  bits[i] = find_subframe_rice_params(s, sub, order+1);
889  if (bits[i] < bits[opt_index]) {
890  opt_index = i;
891  opt_order = order;
892  }
893  }
894  opt_order++;
895  } else if (omethod == ORDER_METHOD_SEARCH) {
896  // brute-force optimal order search
897  uint64_t bits[MAX_LPC_ORDER];
898  opt_order = 0;
899  bits[0] = UINT32_MAX;
900  for (i = min_order-1; i < max_order; i++) {
901  if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
902  s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
903  } else {
904  s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
905  }
906  bits[i] = find_subframe_rice_params(s, sub, i+1);
907  if (bits[i] < bits[opt_order])
908  opt_order = i;
909  }
910  opt_order++;
911  } else if (omethod == ORDER_METHOD_LOG) {
912  uint64_t bits[MAX_LPC_ORDER];
913  int step;
914 
915  opt_order = min_order - 1 + (max_order-min_order)/3;
916  memset(bits, -1, sizeof(bits));
917 
918  for (step = 16; step; step >>= 1) {
919  int last = opt_order;
920  for (i = last-step; i <= last+step; i += step) {
921  if (i < min_order-1 || i >= max_order || bits[i] < UINT32_MAX)
922  continue;
923  if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(i) <= 32) {
924  s->flac_dsp.lpc32_encode(res, smp, n, i+1, coefs[i], shift[i]);
925  } else {
926  s->flac_dsp.lpc16_encode(res, smp, n, i+1, coefs[i], shift[i]);
927  }
928  bits[i] = find_subframe_rice_params(s, sub, i+1);
929  if (bits[i] < bits[opt_order])
930  opt_order = i;
931  }
932  }
933  opt_order++;
934  }
935 
936  if (s->options.multi_dim_quant) {
937  int allsteps = 1;
938  int i, step, improved;
939  int64_t best_score = INT64_MAX;
940  int32_t qmax;
941 
942  qmax = (1 << (s->options.lpc_coeff_precision - 1)) - 1;
943 
944  for (i=0; i<opt_order; i++)
945  allsteps *= 3;
946 
947  do {
948  improved = 0;
949  for (step = 0; step < allsteps; step++) {
950  int tmp = step;
951  int32_t lpc_try[MAX_LPC_ORDER];
952  int64_t score = 0;
953  int diffsum = 0;
954 
955  for (i=0; i<opt_order; i++) {
956  int diff = ((tmp + 1) % 3) - 1;
957  lpc_try[i] = av_clip(coefs[opt_order - 1][i] + diff, -qmax, qmax);
958  tmp /= 3;
959  diffsum += !!diff;
960  }
961  if (diffsum >8)
962  continue;
963 
964  if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order - 1) <= 32) {
965  s->flac_dsp.lpc16_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
966  } else {
967  s->flac_dsp.lpc32_encode(res, smp, n, opt_order, lpc_try, shift[opt_order-1]);
968  }
969  score = find_subframe_rice_params(s, sub, opt_order);
970  if (score < best_score) {
971  best_score = score;
972  memcpy(coefs[opt_order-1], lpc_try, sizeof(*coefs));
973  improved=1;
974  }
975  }
976  } while(improved);
977  }
978 
979  sub->order = opt_order;
980  sub->type_code = sub->type | (sub->order-1);
981  sub->shift = shift[sub->order-1];
982  for (i = 0; i < sub->order; i++)
983  sub->coefs[i] = coefs[sub->order-1][i];
984 
985  if (s->bps_code * 4 + s->options.lpc_coeff_precision + av_log2(opt_order) <= 32) {
986  s->flac_dsp.lpc16_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
987  } else {
988  s->flac_dsp.lpc32_encode(res, smp, n, sub->order, sub->coefs, sub->shift);
989  }
990 
991  find_subframe_rice_params(s, sub, sub->order);
992 
993  return subframe_count_exact(s, sub, sub->order);
994 }
995 
996 
998 {
999  uint8_t av_unused tmp;
1000  int count;
1001 
1002  /*
1003  <14> Sync code
1004  <1> Reserved
1005  <1> Blocking strategy
1006  <4> Block size in inter-channel samples
1007  <4> Sample rate
1008  <4> Channel assignment
1009  <3> Sample size in bits
1010  <1> Reserved
1011  */
1012  count = 32;
1013 
1014  /* coded frame number */
1015  PUT_UTF8(s->frame_count, tmp, count += 8;)
1016 
1017  /* explicit block size */
1018  if (s->frame.bs_code[0] == 6)
1019  count += 8;
1020  else if (s->frame.bs_code[0] == 7)
1021  count += 16;
1022 
1023  /* explicit sample rate */
1024  count += ((s->sr_code[0] == 12) + (s->sr_code[0] > 12)) * 8;
1025 
1026  /* frame header CRC-8 */
1027  count += 8;
1028 
1029  return count;
1030 }
1031 
1032 
1034 {
1035  int ch;
1036  uint64_t count;
1037 
1038  count = count_frame_header(s);
1039 
1040  for (ch = 0; ch < s->channels; ch++)
1041  count += encode_residual_ch(s, ch);
1042 
1043  count += (8 - (count & 7)) & 7; // byte alignment
1044  count += 16; // CRC-16
1045 
1046  count >>= 3;
1047  if (count > INT_MAX)
1048  return AVERROR_BUG;
1049  return count;
1050 }
1051 
1052 
1054 {
1055  int ch, i;
1056 
1057  for (ch = 0; ch < s->channels; ch++) {
1058  FlacSubframe *sub = &s->frame.subframes[ch];
1059  int32_t v = 0;
1060 
1061  for (i = 0; i < s->frame.blocksize; i++) {
1062  v |= sub->samples[i];
1063  if (v & 1)
1064  break;
1065  }
1066 
1067  if (v && !(v & 1)) {
1068  v = av_ctz(v);
1069 
1070  for (i = 0; i < s->frame.blocksize; i++)
1071  sub->samples[i] >>= v;
1072 
1073  sub->wasted = v;
1074  sub->obits -= v;
1075 
1076  /* for 24-bit, check if removing wasted bits makes the range better
1077  suited for using RICE instead of RICE2 for entropy coding */
1078  if (sub->obits <= 17)
1080  }
1081  }
1082 }
1083 
1084 
1085 static int estimate_stereo_mode(const int32_t *left_ch, const int32_t *right_ch, int n,
1086  int max_rice_param)
1087 {
1088  int i, best;
1089  int32_t lt, rt;
1090  uint64_t sum[4];
1091  uint64_t score[4];
1092  int k;
1093 
1094  /* calculate sum of 2nd order residual for each channel */
1095  sum[0] = sum[1] = sum[2] = sum[3] = 0;
1096  for (i = 2; i < n; i++) {
1097  lt = left_ch[i] - 2*left_ch[i-1] + left_ch[i-2];
1098  rt = right_ch[i] - 2*right_ch[i-1] + right_ch[i-2];
1099  sum[2] += FFABS((lt + rt) >> 1);
1100  sum[3] += FFABS(lt - rt);
1101  sum[0] += FFABS(lt);
1102  sum[1] += FFABS(rt);
1103  }
1104  /* estimate bit counts */
1105  for (i = 0; i < 4; i++) {
1106  k = find_optimal_param(2 * sum[i], n, max_rice_param);
1107  sum[i] = rice_encode_count( 2 * sum[i], n, k);
1108  }
1109 
1110  /* calculate score for each mode */
1111  score[0] = sum[0] + sum[1];
1112  score[1] = sum[0] + sum[3];
1113  score[2] = sum[1] + sum[3];
1114  score[3] = sum[2] + sum[3];
1115 
1116  /* return mode with lowest score */
1117  best = 0;
1118  for (i = 1; i < 4; i++)
1119  if (score[i] < score[best])
1120  best = i;
1121 
1122  return best;
1123 }
1124 
1125 
1126 /**
1127  * Perform stereo channel decorrelation.
1128  */
1130 {
1131  FlacFrame *frame;
1132  int32_t *left, *right;
1133  int i, n;
1134 
1135  frame = &s->frame;
1136  n = frame->blocksize;
1137  left = frame->subframes[0].samples;
1138  right = frame->subframes[1].samples;
1139 
1140  if (s->channels != 2) {
1142  return;
1143  }
1144 
1145  if (s->options.ch_mode < 0) {
1146  int max_rice_param = (1 << frame->subframes[0].rc.coding_mode) - 2;
1147  frame->ch_mode = estimate_stereo_mode(left, right, n, max_rice_param);
1148  } else
1149  frame->ch_mode = s->options.ch_mode;
1150 
1151  /* perform decorrelation and adjust bits-per-sample */
1152  if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1153  return;
1154  if (frame->ch_mode == FLAC_CHMODE_MID_SIDE) {
1155  int32_t tmp;
1156  for (i = 0; i < n; i++) {
1157  tmp = left[i];
1158  left[i] = (tmp + right[i]) >> 1;
1159  right[i] = tmp - right[i];
1160  }
1161  frame->subframes[1].obits++;
1162  } else if (frame->ch_mode == FLAC_CHMODE_LEFT_SIDE) {
1163  for (i = 0; i < n; i++)
1164  right[i] = left[i] - right[i];
1165  frame->subframes[1].obits++;
1166  } else {
1167  for (i = 0; i < n; i++)
1168  left[i] -= right[i];
1169  frame->subframes[0].obits++;
1170  }
1171 }
1172 
1173 
1174 static void write_utf8(PutBitContext *pb, uint32_t val)
1175 {
1176  uint8_t tmp;
1177  PUT_UTF8(val, tmp, put_bits(pb, 8, tmp);)
1178 }
1179 
1180 
1182 {
1183  FlacFrame *frame;
1184  int crc;
1185 
1186  frame = &s->frame;
1187 
1188  put_bits(&s->pb, 16, 0xFFF8);
1189  put_bits(&s->pb, 4, frame->bs_code[0]);
1190  put_bits(&s->pb, 4, s->sr_code[0]);
1191 
1192  if (frame->ch_mode == FLAC_CHMODE_INDEPENDENT)
1193  put_bits(&s->pb, 4, s->channels-1);
1194  else
1195  put_bits(&s->pb, 4, frame->ch_mode + FLAC_MAX_CHANNELS - 1);
1196 
1197  put_bits(&s->pb, 3, s->bps_code);
1198  put_bits(&s->pb, 1, 0);
1199  write_utf8(&s->pb, s->frame_count);
1200 
1201  if (frame->bs_code[0] == 6)
1202  put_bits(&s->pb, 8, frame->bs_code[1]);
1203  else if (frame->bs_code[0] == 7)
1204  put_bits(&s->pb, 16, frame->bs_code[1]);
1205 
1206  if (s->sr_code[0] == 12)
1207  put_bits(&s->pb, 8, s->sr_code[1]);
1208  else if (s->sr_code[0] > 12)
1209  put_bits(&s->pb, 16, s->sr_code[1]);
1210 
1211  flush_put_bits(&s->pb);
1212  crc = av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, s->pb.buf,
1213  put_bits_count(&s->pb) >> 3);
1214  put_bits(&s->pb, 8, crc);
1215 }
1216 
1217 
1219 {
1220  int ch;
1221 
1222  for (ch = 0; ch < s->channels; ch++) {
1223  FlacSubframe *sub = &s->frame.subframes[ch];
1224  int i, p, porder, psize;
1225  int32_t *part_end;
1226  int32_t *res = sub->residual;
1227  int32_t *frame_end = &sub->residual[s->frame.blocksize];
1228 
1229  /* subframe header */
1230  put_bits(&s->pb, 1, 0);
1231  put_bits(&s->pb, 6, sub->type_code);
1232  put_bits(&s->pb, 1, !!sub->wasted);
1233  if (sub->wasted)
1234  put_bits(&s->pb, sub->wasted, 1);
1235 
1236  /* subframe */
1237  if (sub->type == FLAC_SUBFRAME_CONSTANT) {
1238  put_sbits(&s->pb, sub->obits, res[0]);
1239  } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {
1240  while (res < frame_end)
1241  put_sbits(&s->pb, sub->obits, *res++);
1242  } else {
1243  /* warm-up samples */
1244  for (i = 0; i < sub->order; i++)
1245  put_sbits(&s->pb, sub->obits, *res++);
1246 
1247  /* LPC coefficients */
1248  if (sub->type == FLAC_SUBFRAME_LPC) {
1249  int cbits = s->options.lpc_coeff_precision;
1250  put_bits( &s->pb, 4, cbits-1);
1251  put_sbits(&s->pb, 5, sub->shift);
1252  for (i = 0; i < sub->order; i++)
1253  put_sbits(&s->pb, cbits, sub->coefs[i]);
1254  }
1255 
1256  /* rice-encoded block */
1257  put_bits(&s->pb, 2, sub->rc.coding_mode - 4);
1258 
1259  /* partition order */
1260  porder = sub->rc.porder;
1261  psize = s->frame.blocksize >> porder;
1262  put_bits(&s->pb, 4, porder);
1263 
1264  /* residual */
1265  part_end = &sub->residual[psize];
1266  for (p = 0; p < 1 << porder; p++) {
1267  int k = sub->rc.params[p];
1268  put_bits(&s->pb, sub->rc.coding_mode, k);
1269  while (res < part_end)
1270  set_sr_golomb_flac(&s->pb, *res++, k, INT32_MAX, 0);
1271  part_end = FFMIN(frame_end, part_end + psize);
1272  }
1273  }
1274  }
1275 }
1276 
1277 
1279 {
1280  int crc;
1281  flush_put_bits(&s->pb);
1283  put_bits_count(&s->pb)>>3));
1284  put_bits(&s->pb, 16, crc);
1285  flush_put_bits(&s->pb);
1286 }
1287 
1288 
1290 {
1291  init_put_bits(&s->pb, avpkt->data, avpkt->size);
1292  write_frame_header(s);
1293  write_subframes(s);
1294  write_frame_footer(s);
1295  return put_bits_count(&s->pb) >> 3;
1296 }
1297 
1298 
1299 static int update_md5_sum(FlacEncodeContext *s, const void *samples)
1300 {
1301  const uint8_t *buf;
1302  int buf_size = s->frame.blocksize * s->channels *
1303  ((s->avctx->bits_per_raw_sample + 7) / 8);
1304 
1305  if (s->avctx->bits_per_raw_sample > 16 || HAVE_BIGENDIAN) {
1306  av_fast_malloc(&s->md5_buffer, &s->md5_buffer_size, buf_size);
1307  if (!s->md5_buffer)
1308  return AVERROR(ENOMEM);
1309  }
1310 
1311  if (s->avctx->bits_per_raw_sample <= 16) {
1312  buf = (const uint8_t *)samples;
1313 #if HAVE_BIGENDIAN
1314  s->bdsp.bswap16_buf((uint16_t *) s->md5_buffer,
1315  (const uint16_t *) samples, buf_size / 2);
1316  buf = s->md5_buffer;
1317 #endif
1318  } else {
1319  int i;
1320  const int32_t *samples0 = samples;
1321  uint8_t *tmp = s->md5_buffer;
1322 
1323  for (i = 0; i < s->frame.blocksize * s->channels; i++) {
1324  int32_t v = samples0[i] >> 8;
1325  AV_WL24(tmp + 3*i, v);
1326  }
1327  buf = s->md5_buffer;
1328  }
1329  av_md5_update(s->md5ctx, buf, buf_size);
1330 
1331  return 0;
1332 }
1333 
1334 
1335 static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
1336  const AVFrame *frame, int *got_packet_ptr)
1337 {
1339  int frame_bytes, out_bytes, ret;
1340 
1341  s = avctx->priv_data;
1342 
1343  /* when the last block is reached, update the header in extradata */
1344  if (!frame) {
1346  av_md5_final(s->md5ctx, s->md5sum);
1347  write_streaminfo(s, avctx->extradata);
1348 
1349  if (avctx->side_data_only_packets && !s->flushed) {
1351  avctx->extradata_size);
1352  if (!side_data)
1353  return AVERROR(ENOMEM);
1354  memcpy(side_data, avctx->extradata, avctx->extradata_size);
1355 
1356  avpkt->pts = s->next_pts;
1357 
1358  *got_packet_ptr = 1;
1359  s->flushed = 1;
1360  }
1361 
1362  return 0;
1363  }
1364 
1365  /* change max_framesize for small final frame */
1366  if (frame->nb_samples < s->frame.blocksize) {
1368  s->channels,
1369  avctx->bits_per_raw_sample);
1370  }
1371 
1372  init_frame(s, frame->nb_samples);
1373 
1374  copy_samples(s, frame->data[0]);
1375 
1377 
1378  remove_wasted_bits(s);
1379 
1380  frame_bytes = encode_frame(s);
1381 
1382  /* Fall back on verbatim mode if the compressed frame is larger than it
1383  would be if encoded uncompressed. */
1384  if (frame_bytes < 0 || frame_bytes > s->max_framesize) {
1385  s->frame.verbatim_only = 1;
1386  frame_bytes = encode_frame(s);
1387  if (frame_bytes < 0) {
1388  av_log(avctx, AV_LOG_ERROR, "Bad frame count\n");
1389  return frame_bytes;
1390  }
1391  }
1392 
1393  if ((ret = ff_alloc_packet2(avctx, avpkt, frame_bytes)) < 0)
1394  return ret;
1395 
1396  out_bytes = write_frame(s, avpkt);
1397 
1398  s->frame_count++;
1399  s->sample_count += frame->nb_samples;
1400  if ((ret = update_md5_sum(s, frame->data[0])) < 0) {
1401  av_log(avctx, AV_LOG_ERROR, "Error updating MD5 checksum\n");
1402  return ret;
1403  }
1404  if (out_bytes > s->max_encoded_framesize)
1405  s->max_encoded_framesize = out_bytes;
1406  if (out_bytes < s->min_framesize)
1407  s->min_framesize = out_bytes;
1408 
1409  avpkt->pts = frame->pts;
1410  avpkt->duration = ff_samples_to_time_base(avctx, frame->nb_samples);
1411  avpkt->size = out_bytes;
1412 
1413  s->next_pts = avpkt->pts + avpkt->duration;
1414 
1415  *got_packet_ptr = 1;
1416  return 0;
1417 }
1418 
1419 
1421 {
1422  if (avctx->priv_data) {
1423  FlacEncodeContext *s = avctx->priv_data;
1424  av_freep(&s->md5ctx);
1425  av_freep(&s->md5_buffer);
1426  ff_lpc_end(&s->lpc_ctx);
1427  }
1428  av_freep(&avctx->extradata);
1429  avctx->extradata_size = 0;
1430  return 0;
1431 }
1432 
1433 #define FLAGS AV_OPT_FLAG_ENCODING_PARAM | AV_OPT_FLAG_AUDIO_PARAM
1434 static const AVOption options[] = {
1435 { "lpc_coeff_precision", "LPC coefficient precision", offsetof(FlacEncodeContext, options.lpc_coeff_precision), AV_OPT_TYPE_INT, {.i64 = 15 }, 0, MAX_LPC_PRECISION, FLAGS },
1436 { "lpc_type", "LPC algorithm", offsetof(FlacEncodeContext, options.lpc_type), AV_OPT_TYPE_INT, {.i64 = FF_LPC_TYPE_DEFAULT }, FF_LPC_TYPE_DEFAULT, FF_LPC_TYPE_NB-1, FLAGS, "lpc_type" },
1437 { "none", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_NONE }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1438 { "fixed", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_FIXED }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1439 { "levinson", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_LEVINSON }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1440 { "cholesky", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = FF_LPC_TYPE_CHOLESKY }, INT_MIN, INT_MAX, FLAGS, "lpc_type" },
1441 { "lpc_passes", "Number of passes to use for Cholesky factorization during LPC analysis", offsetof(FlacEncodeContext, options.lpc_passes), AV_OPT_TYPE_INT, {.i64 = 2 }, 1, INT_MAX, FLAGS },
1442 { "min_partition_order", NULL, offsetof(FlacEncodeContext, options.min_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1443 { "max_partition_order", NULL, offsetof(FlacEncodeContext, options.max_partition_order), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, MAX_PARTITION_ORDER, FLAGS },
1444 { "prediction_order_method", "Search method for selecting prediction order", offsetof(FlacEncodeContext, options.prediction_order_method), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, ORDER_METHOD_LOG, FLAGS, "predm" },
1445 { "estimation", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_EST }, INT_MIN, INT_MAX, FLAGS, "predm" },
1446 { "2level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_2LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1447 { "4level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_4LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1448 { "8level", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_8LEVEL }, INT_MIN, INT_MAX, FLAGS, "predm" },
1449 { "search", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_SEARCH }, INT_MIN, INT_MAX, FLAGS, "predm" },
1450 { "log", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = ORDER_METHOD_LOG }, INT_MIN, INT_MAX, FLAGS, "predm" },
1451 { "ch_mode", "Stereo decorrelation mode", offsetof(FlacEncodeContext, options.ch_mode), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, FLAC_CHMODE_MID_SIDE, FLAGS, "ch_mode" },
1452 { "auto", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = -1 }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1453 { "indep", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_INDEPENDENT }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1454 { "left_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_LEFT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1455 { "right_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_RIGHT_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1456 { "mid_side", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FLAC_CHMODE_MID_SIDE }, INT_MIN, INT_MAX, FLAGS, "ch_mode" },
1457 { "exact_rice_parameters", "Calculate rice parameters exactly", offsetof(FlacEncodeContext, options.exact_rice_parameters), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1458 { "multi_dim_quant", "Multi-dimensional quantization", offsetof(FlacEncodeContext, options.multi_dim_quant), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
1459 { NULL },
1460 };
1461 
1462 static const AVClass flac_encoder_class = {
1463  "FLAC encoder",
1465  options,
1467 };
1468 
1470  .name = "flac",
1471  .long_name = NULL_IF_CONFIG_SMALL("FLAC (Free Lossless Audio Codec)"),
1472  .type = AVMEDIA_TYPE_AUDIO,
1473  .id = AV_CODEC_ID_FLAC,
1474  .priv_data_size = sizeof(FlacEncodeContext),
1476  .encode2 = flac_encode_frame,
1477  .close = flac_encode_close,
1479  .sample_fmts = (const enum AVSampleFormat[]){ AV_SAMPLE_FMT_S16,
1482  .priv_class = &flac_encoder_class,
1483 };
#define MAX_FIXED_ORDER
Definition: flacenc.c:42
uint32_t rc_udata[FLAC_MAX_BLOCKSIZE]
Definition: flacenc.c:85
#define NULL
Definition: coverity.c:32
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1736
#define rice_encode_count(sum, n, k)
Definition: flacenc.c:577
const char const char void * val
Definition: avisynth_c.h:634
float v
#define ORDER_METHOD_SEARCH
Definition: lpc.h:33
const char * s
Definition: avisynth_c.h:631
static int shift(int a, int b)
Definition: sonic.c:82
int type
Definition: flacenc.c:76
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
#define ORDER_METHOD_8LEVEL
Definition: lpc.h:32
AVCodec ff_flac_encoder
Definition: flacenc.c:1469
AVOption.
Definition: opt.h:255
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
int min_prediction_order
Definition: flacenc.c:59
Definition: lpc.h:51
static void put_sbits(PutBitContext *pb, int n, int32_t value)
Definition: put_bits.h:192
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:160
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
struct AVMD5 * md5ctx
Definition: flacenc.c:119
#define MAX_LPC_ORDER
Definition: lpc.h:37
int ff_lpc_calc_coefs(LPCContext *s, const int32_t *samples, int blocksize, int min_order, int max_order, int precision, int32_t coefs[][MAX_LPC_ORDER], int *shift, enum FFLPCType lpc_type, int lpc_passes, int omethod, int max_shift, int zero_shift)
Calculate LPC coefficients for multiple orders.
Definition: lpc.c:170
void(* bswap16_buf)(uint16_t *dst, const uint16_t *src, int len)
Definition: bswapdsp.h:26
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
int av_ctz(int v)
Trailing zero bit count.
Definition: intmath.c:36
int ff_flac_get_max_frame_size(int blocksize, int ch, int bps)
Calculate an estimate for the maximum frame size based on verbatim mode.
Definition: flac.c:148
#define CODEC_CAP_LOSSLESS
Codec is lossless.
Definition: avcodec.h:890
int size
Definition: avcodec.h:1163
const char * b
Definition: vf_curves.c:109
int min_partition_order
Definition: flacenc.c:62
#define MAX_PARTITION_ORDER
Definition: flacenc.c:43
#define av_bswap16
Definition: bswap.h:31
#define PUT_UTF8(val, tmp, PUT_BYTE)
Convert a 32-bit Unicode character to its UTF-8 encoded form (up to 4 bytes long).
Definition: common.h:387
int64_t next_pts
Definition: flacenc.c:126
#define FLAC_MAX_BLOCKSIZE
Definition: flac.h:37
#define MAX_LPC_SHIFT
Definition: flacenc.c:46
#define AV_CH_LAYOUT_STEREO
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:2727
static int flac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet_ptr)
Definition: flacenc.c:1335
int max_partition_order
Definition: flacenc.c:63
AVCodec.
Definition: avcodec.h:3181
#define AV_CH_LAYOUT_5POINT0
void(* lpc32_encode)(int32_t *res, const int32_t *smp, int len, int order, const int32_t coefs[32], int shift)
Definition: flacdsp.h:34
void av_md5_update(AVMD5 *ctx, const uint8_t *src, int len)
Update hash value.
Definition: md5.c:148
static int select_blocksize(int samplerate, int block_time_ms)
Set blocksize based on samplerate.
Definition: flacenc.c:160
FlacFrame frame
Definition: flacenc.c:115
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
#define AV_WL24(p, d)
Definition: intreadwrite.h:464
struct AVMD5 * av_md5_alloc(void)
Allocate an AVMD5 context.
Definition: md5.c:47
if()
Definition: avfilter.c:975
uint8_t bits
Definition: crc.c:295
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:1993
uint8_t
#define ORDER_METHOD_LOG
Definition: lpc.h:34
#define av_cold
Definition: attributes.h:74
#define av_malloc(s)
AVOptions.
int order
Definition: flacenc.c:80
do not use LPC prediction or use all zero coefficients
Definition: lpc.h:44
int32_t coefs[MAX_LPC_ORDER]
Definition: flacenc.c:81
int wasted
Definition: flacenc.c:79
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:257
FLACDSPContext flac_dsp
Definition: flacenc.c:123
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1355
uint8_t * md5_buffer
Definition: flacenc.c:120
static AVFrame * frame
uint8_t * data
Definition: avcodec.h:1162
static uint64_t find_subframe_rice_params(FlacEncodeContext *s, FlacSubframe *sub, int pred_order)
Definition: flacenc.c:730
int params[MAX_PARTITIONS]
Definition: flacenc.c:72
static const uint8_t header[24]
Definition: sdr2.c:67
int min_prediction_order
Definition: avcodec.h:2442
Definition: md5.c:39
uint64_t sample_count
Definition: flacenc.c:113
uint8_t crc8
Definition: flacenc.c:96
signed 32 bits
Definition: samplefmt.h:63
int duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: avcodec.h:1180
#define FLAC_MIN_BLOCKSIZE
Definition: flac.h:36
#define av_log(a,...)
static void write_subframes(FlacEncodeContext *s)
Definition: flacenc.c:1218
#define AV_CH_LAYOUT_5POINT1
int shift
Definition: flacenc.c:82
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
#define ORDER_METHOD_4LEVEL
Definition: lpc.h:31
unsigned int md5_buffer_size
Definition: flacenc.c:121
FLAC (Free Lossless Audio Codec) decoder/demuxer common functions.
#define CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: avcodec.h:824
int exact_rice_parameters
Definition: flacenc.c:65
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
uint64_t rc_sums[32][MAX_PARTITIONS]
Definition: flacenc.c:86
void(* lpc16_encode)(int32_t *res, const int32_t *smp, int len, int order, const int32_t coefs[32], int shift)
Definition: flacdsp.h:32
#define CODEC_CAP_SMALL_LAST_FRAME
Codec can be fed a final frame with a smaller size.
Definition: avcodec.h:829
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
int sr_code[2]
Definition: flacenc.c:106
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
#define FLAC_SUBFRAME_LPC
Definition: flacenc.c:40
GLenum GLint * params
Definition: opengl_enc.c:114
uint8_t * buf
Definition: put_bits.h:38
enum CodingMode coding_mode
Definition: flacenc.c:70
simple assert() macros that are a bit more flexible than ISO C assert().
#define AV_CH_LAYOUT_QUAD
const char * name
Name of the codec implementation.
Definition: avcodec.h:3188
#define COPY_SAMPLES(bits)
int porder
Definition: flacenc.c:71
#define FLAC_SUBFRAME_VERBATIM
Definition: flacenc.c:38
GLsizei count
Definition: opengl_enc.c:109
int32_t samples[FLAC_MAX_BLOCKSIZE]
Definition: flacenc.c:88
Libavcodec external API header.
static void remove_wasted_bits(FlacEncodeContext *s)
Definition: flacenc.c:1053
#define FLAC_SUBFRAME_CONSTANT
Definition: flacenc.c:37
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2046
static int put_bits_count(PutBitContext *s)
Definition: put_bits.h:85
#define ORDER_METHOD_2LEVEL
Definition: lpc.h:30
static uint64_t calc_optimal_rice_params(RiceContext *rc, int porder, uint64_t sums[32][MAX_PARTITIONS], int n, int pred_order, int max_param, int exact)
Definition: flacenc.c:611
static void frame_end(MpegEncContext *s)
av_cold void ff_bswapdsp_init(BswapDSPContext *c)
Definition: bswapdsp.c:49
#define AV_CH_LAYOUT_2_2
int type_code
Definition: flacenc.c:77
#define FLAC_SUBFRAME_FIXED
Definition: flacenc.c:39
static int encode_residual_ch(FlacEncodeContext *s, int ch)
Definition: flacenc.c:798
av_cold void ff_lpc_end(LPCContext *s)
Uninitialize LPCContext.
Definition: lpc.c:290
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition: avassert.h:53
static uint64_t rice_count_exact(const int32_t *res, int n, int k)
Definition: flacenc.c:513
#define FFMIN(a, b)
Definition: common.h:66
int obits
Definition: flacenc.c:78
static int encode_frame(FlacEncodeContext *s)
Definition: flacenc.c:1033
ret
Definition: avfilter.c:974
#define FLAGS
Definition: flacenc.c:1433
int32_t
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition: crc.c:356
int side_data_only_packets
Encoding only.
Definition: avcodec.h:2998
#define FLAC_STREAMINFO_SIZE
Definition: flac.h:34
#define FFABS(a)
Definition: common.h:61
int n
Definition: avisynth_c.h:547
#define AV_CH_FRONT_CENTER
int prediction_order_method
Definition: flacenc.c:61
#define AV_CH_LAYOUT_5POINT1_BACK
static int get_max_p_order(int max_porder, int n, int order)
Definition: flacenc.c:721
static int write_frame(FlacEncodeContext *s, AVPacket *avpkt)
Definition: flacenc.c:1289
static int find_optimal_param_exact(uint64_t sums[32][MAX_PARTITIONS], int i, int max_param)
Definition: flacenc.c:594
Not part of ABI.
Definition: lpc.h:48
PutBitContext pb
Definition: flacenc.c:103
int lpc_coeff_precision
Definition: flacenc.c:58
static void set_sr_golomb_flac(PutBitContext *pb, int i, int k, int limit, int esc_len)
write signed golomb rice code (flac).
Definition: golomb.h:574
static const AVOption options[]
Definition: flacenc.c:1434
static void channel_decorrelation(FlacEncodeContext *s)
Perform stereo channel decorrelation.
Definition: flacenc.c:1129
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:2005
int bs_code[2]
Definition: flacenc.c:95
const int ff_flac_sample_rate_table[16]
Definition: flacdata.c:24
static void calc_sum_next(int level, uint64_t sums[32][MAX_PARTITIONS], int kmax)
Definition: flacenc.c:671
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:59
int compression_level
Definition: avcodec.h:1327
int sample_rate
samples per second
Definition: avcodec.h:1985
static void write_frame_header(FlacEncodeContext *s)
Definition: flacenc.c:1181
#define MIN_LPC_ORDER
Definition: lpc.h:36
static void calc_sum_top(int pmax, int kmax, const uint32_t *data, int n, int pred_order, uint64_t sums[32][MAX_PARTITIONS])
Definition: flacenc.c:641
main external API structure.
Definition: avcodec.h:1241
int ch_mode
Definition: flacenc.c:97
static int count_frame_header(FlacEncodeContext *s)
Definition: flacenc.c:997
Levinson-Durbin recursion.
Definition: lpc.h:46
#define ORDER_METHOD_EST
Definition: lpc.h:29
void av_md5_init(AVMD5 *ctx)
Initialize MD5 hashing.
Definition: md5.c:138
void * buf
Definition: avisynth_c.h:553
int extradata_size
Definition: avcodec.h:1356
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
Describe the class of an AVClass context structure.
Definition: log.h:67
av_cold void ff_flacdsp_init(FLACDSPContext *c, enum AVSampleFormat fmt, int channels, int bps)
Definition: flacdsp.c:88
use the codec default LPC type
Definition: lpc.h:43
enum FFLPCType lpc_type
Definition: flacenc.c:56
int blocksize
Definition: flacenc.c:94
#define MAX_PARTITIONS
Definition: flacenc.c:44
#define AV_CH_LAYOUT_5POINT0_BACK
static uint64_t calc_rice_params(RiceContext *rc, uint32_t udata[FLAC_MAX_BLOCKSIZE], uint64_t sums[32][MAX_PARTITIONS], int pmin, int pmax, const int32_t *data, int n, int pred_order, int exact)
Definition: flacenc.c:681
uint8_t md5sum[16]
Definition: flacenc.c:114
static void encode_residual_fixed(int32_t *res, const int32_t *smp, int n, int order)
Definition: flacenc.c:747
void av_md5_final(AVMD5 *ctx, uint8_t *dst)
Finish hashing and output digest value.
Definition: md5.c:183
int max_encoded_framesize
Definition: flacenc.c:111
static void write_utf8(PutBitContext *pb, uint32_t val)
Definition: flacenc.c:1174
av_cold int ff_lpc_init(LPCContext *s, int blocksize, int max_order, enum FFLPCType lpc_type)
Initialize LPCContext.
Definition: lpc.c:268
#define MAX_LPC_PRECISION
Definition: flacenc.c:45
int max_prediction_order
Definition: flacenc.c:60
static void copy_samples(FlacEncodeContext *s, const void *samples)
Copy channel-interleaved input samples into separate subframes.
Definition: flacenc.c:491
int compression_level
Definition: flacenc.c:54
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
uint8_t level
Definition: svq3.c:150
RiceContext rc
Definition: flacenc.c:84
int av_get_bytes_per_sample(enum AVSampleFormat sample_fmt)
Return number of bytes per sample.
Definition: samplefmt.c:104
AVCodecContext * avctx
Definition: flacenc.c:117
static void write_frame_footer(FlacEncodeContext *s)
Definition: flacenc.c:1278
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition: crc.c:342
FlacSubframe subframes[FLAC_MAX_CHANNELS]
Definition: flacenc.c:93
CompressionOptions options
Definition: flacenc.c:116
FFLPCType
LPC analysis type.
Definition: lpc.h:42
void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)
Allocate a buffer, reusing the given one if large enough.
Definition: mem.c:513
Cholesky factorization.
Definition: lpc.h:47
static int estimate_stereo_mode(const int32_t *left_ch, const int32_t *right_ch, int n, int max_rice_param)
Definition: flacenc.c:1085
common internal api header.
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition: put_bits.h:101
int32_t residual[FLAC_MAX_BLOCKSIZE+11]
Definition: flacenc.c:89
const int32_t ff_flac_blocksize_table[16]
Definition: flacdata.c:30
signed 16 bits
Definition: samplefmt.h:62
static double c[64]
LPCContext lpc_ctx
Definition: flacenc.c:118
static void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Initialize the PutBitContext s.
Definition: put_bits.h:48
static av_cold int flac_encode_close(AVCodecContext *avctx)
Definition: flacenc.c:1420
static av_cold void dprint_compression_options(FlacEncodeContext *s)
Definition: flacenc.c:179
fixed LPC coefficients
Definition: lpc.h:45
void * priv_data
Definition: avcodec.h:1283
static int find_optimal_param(uint64_t sum, int n, int max_param)
Solve for d/dk(rice_encode_count) = n-((sum-(n>>1))>>(k+1)) = 0.
Definition: flacenc.c:582
static av_always_inline int diff(const uint32_t a, const uint32_t b)
int channels
number of audio channels
Definition: avcodec.h:1986
#define av_log2
Definition: intmath.h:105
static uint64_t subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub, int pred_order)
Definition: flacenc.c:527
static const AVClass flac_encoder_class
Definition: flacenc.c:1462
BswapDSPContext bdsp
Definition: flacenc.c:122
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:701
CodingMode
Definition: flacenc.c:48
int max_prediction_order
Definition: avcodec.h:2448
#define av_freep(p)
static void init_frame(FlacEncodeContext *s, int nb_samples)
Definition: flacenc.c:446
static av_always_inline int64_t ff_samples_to_time_base(AVCodecContext *avctx, int64_t samples)
Rescale from sample rate to AVCodecContext.time_base.
Definition: internal.h:225
static int update_md5_sum(FlacEncodeContext *s, const void *samples)
Definition: flacenc.c:1299
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:299
exp golomb vlc stuff
This structure stores compressed data.
Definition: avcodec.h:1139
int nb_samples
number of audio samples (per channel) described by this frame
Definition: frame.h:225
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1155
static av_cold int flac_encode_init(AVCodecContext *avctx)
Definition: flacenc.c:237
static void write_streaminfo(FlacEncodeContext *s, uint8_t *header)
Write streaminfo metadata block to byte array.
Definition: flacenc.c:133
#define FLAC_MAX_CHANNELS
Definition: flac.h:35
#define av_unused
Definition: attributes.h:118
int verbatim_only
Definition: flacenc.c:98
uint32_t frame_count
Definition: flacenc.c:112
bitstream writer API