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