FFmpeg
mlpenc.c
Go to the documentation of this file.
1 /**
2  * MLP encoder
3  * Copyright (c) 2008 Ramiro Polla
4  * Copyright (c) 2016-2019 Jai Luthra
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 #include "avcodec.h"
24 #include "encode.h"
25 #include "internal.h"
26 #include "put_bits.h"
27 #include "audio_frame_queue.h"
29 #include "libavutil/crc.h"
30 #include "libavutil/avstring.h"
31 #include "libavutil/samplefmt.h"
32 #include "libavutil/thread.h"
33 #include "mlp.h"
34 #include "lpc.h"
35 
36 #define MAJOR_HEADER_INTERVAL 16
37 
38 #define MLP_MIN_LPC_ORDER 1
39 #define MLP_MAX_LPC_ORDER 8
40 #define MLP_MIN_LPC_SHIFT 8
41 #define MLP_MAX_LPC_SHIFT 15
42 
43 typedef struct {
44  uint8_t min_channel; ///< The index of the first channel coded in this substream.
45  uint8_t max_channel; ///< The index of the last channel coded in this substream.
46  uint8_t max_matrix_channel; ///< The number of channels input into the rematrix stage.
47 
48  uint8_t noise_shift; ///< The left shift applied to random noise in 0x31ea substreams.
49  uint32_t noisegen_seed; ///< The current seed value for the pseudorandom noise generator(s).
50 
51  int data_check_present; ///< Set if the substream contains extra info to check the size of VLC blocks.
52 
53  int32_t lossless_check_data; ///< XOR of all output samples
54 
55  uint8_t max_huff_lsbs; ///< largest huff_lsbs
56  uint8_t max_output_bits; ///< largest output bit-depth
58 
59 typedef struct {
60  uint8_t count; ///< number of matrices to apply
61 
62  uint8_t outch[MAX_MATRICES]; ///< output channel for each matrix
63  int32_t forco[MAX_MATRICES][MAX_CHANNELS+2]; ///< forward coefficients
64  int32_t coeff[MAX_MATRICES][MAX_CHANNELS+2]; ///< decoding coefficients
65  uint8_t fbits[MAX_CHANNELS]; ///< fraction bits
66 
67  int8_t shift[MAX_CHANNELS]; ///< Left shift to apply to decoded PCM values to get final 24-bit output.
68 } MatrixParams;
69 
70 enum ParamFlags {
73  PARAM_BLOCKSIZE = 1 << 7,
74  PARAM_MATRIX = 1 << 6,
75  PARAM_OUTSHIFT = 1 << 5,
76  PARAM_QUANTSTEP = 1 << 4,
77  PARAM_FIR = 1 << 3,
78  PARAM_IIR = 1 << 2,
79  PARAM_HUFFOFFSET = 1 << 1,
80  PARAM_PRESENT = 1 << 0,
81 };
82 
83 typedef struct {
84  uint16_t blocksize; ///< number of PCM samples in current audio block
85  uint8_t quant_step_size[MAX_CHANNELS]; ///< left shift to apply to Huffman-decoded residuals
86 
88 
89  uint8_t param_presence_flags; ///< Bitmask of which parameter sets are conveyed in a decoding parameter block.
91 
92 typedef struct BestOffset {
94  int bitcount;
95  int lsb_bits;
98 } BestOffset;
99 
100 #define HUFF_OFFSET_MIN (-16384)
101 #define HUFF_OFFSET_MAX ( 16383)
102 
103 /** Number of possible codebooks (counting "no codebooks") */
104 #define NUM_CODEBOOKS 4
105 
106 typedef struct {
108 
109  int num_substreams; ///< Number of substreams contained within this stream.
110 
111  int num_channels; /**< Number of channels in major_scratch_buffer.
112  * Normal channels + noise channels. */
113 
114  int coded_sample_fmt [2]; ///< sample format encoded for MLP
115  int coded_sample_rate[2]; ///< sample rate encoded for MLP
116  int coded_peak_bitrate; ///< peak bitrate for this major sync header
117 
118  int flags; ///< major sync info flags
119 
120  /* channel_meaning */
122  int fs;
126 
127  int32_t *inout_buffer; ///< Pointer to data currently being read from lavc or written to bitstream.
128  int32_t *major_inout_buffer; ///< Buffer with all in/out data for one entire major frame interval.
129  int32_t *write_buffer; ///< Pointer to data currently being written to bitstream.
130  int32_t *sample_buffer; ///< Pointer to current access unit samples.
131  int32_t *major_scratch_buffer; ///< Scratch buffer big enough to fit all data for one entire major frame interval.
132  int32_t *last_frame; ///< Pointer to last frame with data to encode.
133 
135 
138 
139  unsigned int major_frame_size; ///< Number of samples in current major frame being encoded.
140  unsigned int next_major_frame_size; ///< Counter of number of samples for next major frame.
141 
142  int32_t *lossless_check_data; ///< Array with lossless_check_data for each access unit.
143 
144  unsigned int *max_output_bits; ///< largest output bit-depth
145  unsigned int *frame_size; ///< Array with number of samples/channel in each access unit.
146  unsigned int frame_index; ///< Index of current frame being encoded.
147 
148  unsigned int one_sample_buffer_size; ///< Number of samples*channel for one access unit.
149 
150  unsigned int max_restart_interval; ///< Max interval of access units in between two major frames.
151  unsigned int min_restart_interval; ///< Min interval of access units in between two major frames.
152  unsigned int restart_intervals; ///< Number of possible major frame sizes.
153 
154  uint16_t timestamp; ///< Timestamp of current access unit.
155  uint16_t dts; ///< Decoding timestamp of current access unit.
156 
157  uint8_t channel_arrangement; ///< channel arrangement for MLP streams
158 
159  uint8_t ch_modifier_thd0; ///< channel modifier for TrueHD stream 0
160  uint8_t ch_modifier_thd1; ///< channel modifier for TrueHD stream 1
161  uint8_t ch_modifier_thd2; ///< channel modifier for TrueHD stream 2
162 
163  unsigned int seq_size [MAJOR_HEADER_INTERVAL];
164  unsigned int seq_offset[MAJOR_HEADER_INTERVAL];
165  unsigned int sequence_size;
166 
168 
170 
172  RestartHeader restart_header [MAX_SUBSTREAMS];
173 
174  ChannelParams major_channel_params[MAJOR_HEADER_INTERVAL+1][MAX_CHANNELS]; ///< ChannelParams to be written to bitstream.
175  DecodingParams major_decoding_params[MAJOR_HEADER_INTERVAL+1][MAX_SUBSTREAMS]; ///< DecodingParams to be written to bitstream.
176  int major_params_changed[MAJOR_HEADER_INTERVAL+1][MAX_SUBSTREAMS]; ///< params_changed to be written to bitstream.
177 
181 
182  BestOffset (*cur_best_offset)[NUM_CODEBOOKS];
186 
188 
189  /* Analysis stage. */
190  unsigned int starting_frame_index;
191  unsigned int number_of_frames;
192  unsigned int number_of_samples;
193  unsigned int number_of_subblocks;
194  unsigned int seq_index; ///< Sequence index for high compression levels.
195 
198 
201 
202  unsigned int max_codebook_search;
203 
206 
210 
211 #define SYNC_MAJOR 0xf8726f
212 #define MAJOR_SYNC_INFO_SIGNATURE 0xB752
213 
214 #define SYNC_MLP 0xbb
215 #define SYNC_TRUEHD 0xba
216 
217 /* must be set for DVD-A */
218 #define FLAGS_DVDA 0x4000
219 /* FIFO delay must be constant */
220 #define FLAGS_CONST 0x8000
221 
222 #define SUBSTREAM_INFO_MAX_2_CHAN 0x01
223 #define SUBSTREAM_INFO_HIGH_RATE 0x02
224 #define SUBSTREAM_INFO_ALWAYS_SET 0x04
225 #define SUBSTREAM_INFO_2_SUBSTREAMS 0x08
226 
227 /****************************************************************************
228  ************ Functions that copy, clear, or compare parameters *************
229  ****************************************************************************/
230 
231 /** Compares two FilterParams structures and returns 1 if anything has
232  * changed. Returns 0 if they are both equal.
233  */
234 static int compare_filter_params(const ChannelParams *prev_cp, const ChannelParams *cp, int filter)
235 {
236  const FilterParams *prev = &prev_cp->filter_params[filter];
237  const FilterParams *fp = &cp->filter_params[filter];
238  int i;
239 
240  if (prev->order != fp->order)
241  return 1;
242 
243  if (!prev->order)
244  return 0;
245 
246  if (prev->shift != fp->shift)
247  return 1;
248 
249  for (i = 0; i < fp->order; i++)
250  if (prev_cp->coeff[filter][i] != cp->coeff[filter][i])
251  return 1;
252 
253  return 0;
254 }
255 
256 /** Compare two primitive matrices and returns 1 if anything has changed.
257  * Returns 0 if they are both equal.
258  */
260 {
261  RestartHeader *rh = ctx->cur_restart_header;
262  unsigned int channel, mat;
263 
264  if (prev->count != mp->count)
265  return 1;
266 
267  if (!prev->count)
268  return 0;
269 
270  for (channel = rh->min_channel; channel <= rh->max_channel; channel++)
271  if (prev->fbits[channel] != mp->fbits[channel])
272  return 1;
273 
274  for (mat = 0; mat < mp->count; mat++) {
275  if (prev->outch[mat] != mp->outch[mat])
276  return 1;
277 
278  for (channel = 0; channel < ctx->num_channels; channel++)
279  if (prev->coeff[mat][channel] != mp->coeff[mat][channel])
280  return 1;
281  }
282 
283  return 0;
284 }
285 
286 /** Compares two DecodingParams and ChannelParams structures to decide if a
287  * new decoding params header has to be written.
288  */
290 {
291  const DecodingParams *prev = ctx->prev_decoding_params;
292  DecodingParams *dp = ctx->cur_decoding_params;
293  const MatrixParams *prev_mp = &prev->matrix_params;
294  MatrixParams *mp = &dp->matrix_params;
295  RestartHeader *rh = ctx->cur_restart_header;
296  unsigned int ch;
297  int retval = 0;
298 
300  retval |= PARAM_PRESENCE_FLAGS;
301 
302  if (prev->blocksize != dp->blocksize)
303  retval |= PARAM_BLOCKSIZE;
304 
305  if (compare_matrix_params(ctx, prev_mp, mp))
306  retval |= PARAM_MATRIX;
307 
308  for (ch = 0; ch <= rh->max_matrix_channel; ch++)
309  if (prev_mp->shift[ch] != mp->shift[ch]) {
310  retval |= PARAM_OUTSHIFT;
311  break;
312  }
313 
314  for (ch = 0; ch <= rh->max_channel; ch++)
315  if (prev->quant_step_size[ch] != dp->quant_step_size[ch]) {
316  retval |= PARAM_QUANTSTEP;
317  break;
318  }
319 
320  for (ch = rh->min_channel; ch <= rh->max_channel; ch++) {
321  const ChannelParams *prev_cp = &ctx->prev_channel_params[ch];
322  ChannelParams *cp = &ctx->cur_channel_params[ch];
323 
324  if (!(retval & PARAM_FIR) &&
325  compare_filter_params(prev_cp, cp, FIR))
326  retval |= PARAM_FIR;
327 
328  if (!(retval & PARAM_IIR) &&
329  compare_filter_params(prev_cp, cp, IIR))
330  retval |= PARAM_IIR;
331 
332  if (prev_cp->huff_offset != cp->huff_offset)
333  retval |= PARAM_HUFFOFFSET;
334 
335  if (prev_cp->codebook != cp->codebook ||
336  prev_cp->huff_lsbs != cp->huff_lsbs )
337  retval |= 0x1;
338  }
339 
340  return retval;
341 }
342 
343 static void copy_filter_params(ChannelParams *dst_cp, ChannelParams *src_cp, int filter)
344 {
345  FilterParams *dst = &dst_cp->filter_params[filter];
346  FilterParams *src = &src_cp->filter_params[filter];
347  unsigned int order;
348 
349  dst->order = src->order;
350 
351  if (dst->order) {
352  dst->shift = src->shift;
353 
354  dst->coeff_shift = src->coeff_shift;
355  dst->coeff_bits = src->coeff_bits;
356  }
357 
358  for (order = 0; order < dst->order; order++)
359  dst_cp->coeff[filter][order] = src_cp->coeff[filter][order];
360 }
361 
363 {
364  dst->count = src->count;
365 
366  if (dst->count) {
367  unsigned int channel, count;
368 
369  for (channel = 0; channel < MAX_CHANNELS; channel++) {
370 
371  dst->fbits[channel] = src->fbits[channel];
372  dst->shift[channel] = src->shift[channel];
373 
374  for (count = 0; count < MAX_MATRICES; count++)
375  dst->coeff[count][channel] = src->coeff[count][channel];
376  }
377 
378  for (count = 0; count < MAX_MATRICES; count++)
379  dst->outch[count] = src->outch[count];
380  }
381 }
382 
384  unsigned int substr)
385 {
386  unsigned int index;
387 
388  for (index = 0; index < ctx->number_of_subblocks; index++) {
389  DecodingParams *dp = ctx->seq_decoding_params + index*(ctx->num_substreams) + substr;
390  unsigned int channel;
391 
392  copy_matrix_params(&dp->matrix_params, &ctx->cur_decoding_params->matrix_params);
393 
394  for (channel = 0; channel < ctx->avctx->channels; channel++) {
395  ChannelParams *cp = ctx->seq_channel_params + index*(ctx->avctx->channels) + channel;
396  unsigned int filter;
397 
398  dp->quant_step_size[channel] = ctx->cur_decoding_params->quant_step_size[channel];
399  dp->matrix_params.shift[channel] = ctx->cur_decoding_params->matrix_params.shift[channel];
400 
401  if (index)
402  for (filter = 0; filter < NUM_FILTERS; filter++)
403  copy_filter_params(cp, &ctx->cur_channel_params[channel], filter);
404  }
405  }
406 }
407 
408 /** Clears a DecodingParams struct the way it should be after a restart header. */
409 static void clear_decoding_params(DecodingParams decoding_params[MAX_SUBSTREAMS], int num_substreams)
410 {
411  for (unsigned substr = 0; substr < num_substreams; substr++) {
412  DecodingParams *dp = &decoding_params[substr];
413 
414  dp->param_presence_flags = 0xff;
415  dp->blocksize = 8;
416 
417  memset(&dp->matrix_params , 0, sizeof(MatrixParams ));
418  memset(dp->quant_step_size, 0, sizeof(dp->quant_step_size));
419  }
420 }
421 
422 /** Clears a ChannelParams struct the way it should be after a restart header. */
424 {
425  for (unsigned channel = 0; channel < nb_channels; channel++) {
426  ChannelParams *cp = &channel_params[channel];
427 
428  memset(&cp->filter_params, 0, sizeof(cp->filter_params));
429 
430  /* Default audio coding is 24-bit raw PCM. */
431  cp->huff_offset = 0;
432  cp->codebook = 0;
433  cp->huff_lsbs = 24;
434  }
435 }
436 
437 /** Sets default vales in our encoder for a DecodingParams struct. */
439  DecodingParams decoding_params[MAX_SUBSTREAMS])
440 {
441  unsigned int substr;
442 
443  clear_decoding_params(decoding_params, ctx->num_substreams);
444 
445  for (substr = 0; substr < ctx->num_substreams; substr++) {
446  DecodingParams *dp = &decoding_params[substr];
447  uint8_t param_presence_flags = 0;
448 
449  param_presence_flags |= PARAM_BLOCKSIZE;
450  param_presence_flags |= PARAM_MATRIX;
451  param_presence_flags |= PARAM_OUTSHIFT;
452  param_presence_flags |= PARAM_QUANTSTEP;
453  param_presence_flags |= PARAM_FIR;
454 /* param_presence_flags |= PARAM_IIR; */
455  param_presence_flags |= PARAM_HUFFOFFSET;
456  param_presence_flags |= PARAM_PRESENT;
457 
458  dp->param_presence_flags = param_presence_flags;
459  }
460 }
461 
462 /****************************************************************************/
463 
464 /** Calculates the smallest number of bits it takes to encode a given signed
465  * value in two's complement.
466  */
467 static int inline number_sbits(int number)
468 {
469  if (number < -1)
470  number++;
471 
472  return av_log2(FFABS(number)) + 1 + !!number;
473 }
474 
479 };
480 
481 static int mlp_peak_bitrate(int peak_bitrate, int sample_rate)
482 {
483  return ((peak_bitrate << 4) - 8) / sample_rate;
484 }
485 
487 {
490  ff_mlp_init_crc();
491 }
492 
494 {
495  static AVOnce init_static_once = AV_ONCE_INIT;
496  MLPEncodeContext *ctx = avctx->priv_data;
497  unsigned int substr, index;
498  unsigned int sum = 0;
499  unsigned int size;
500  int ret;
501 
502  ctx->avctx = avctx;
503 
504  switch (avctx->sample_rate) {
505  case 44100 << 0:
506  avctx->frame_size = 40 << 0;
507  ctx->coded_sample_rate[0] = 0x08 + 0;
508  ctx->fs = 0x08 + 1;
509  break;
510  case 44100 << 1:
511  avctx->frame_size = 40 << 1;
512  ctx->coded_sample_rate[0] = 0x08 + 1;
513  ctx->fs = 0x0C + 1;
514  break;
515  case 44100 << 2:
516  ctx->substream_info |= SUBSTREAM_INFO_HIGH_RATE;
517  avctx->frame_size = 40 << 2;
518  ctx->coded_sample_rate[0] = 0x08 + 2;
519  ctx->fs = 0x10 + 1;
520  break;
521  case 48000 << 0:
522  avctx->frame_size = 40 << 0;
523  ctx->coded_sample_rate[0] = 0x00 + 0;
524  ctx->fs = 0x08 + 2;
525  break;
526  case 48000 << 1:
527  avctx->frame_size = 40 << 1;
528  ctx->coded_sample_rate[0] = 0x00 + 1;
529  ctx->fs = 0x0C + 2;
530  break;
531  case 48000 << 2:
532  ctx->substream_info |= SUBSTREAM_INFO_HIGH_RATE;
533  avctx->frame_size = 40 << 2;
534  ctx->coded_sample_rate[0] = 0x00 + 2;
535  ctx->fs = 0x10 + 2;
536  break;
537  default:
538  av_log(avctx, AV_LOG_ERROR, "Unsupported sample rate %d. Supported "
539  "sample rates are 44100, 88200, 176400, 48000, "
540  "96000, and 192000.\n", avctx->sample_rate);
541  return AVERROR(EINVAL);
542  }
543  ctx->coded_sample_rate[1] = -1 & 0xf;
544 
545  /* TODO Keep count of bitrate and calculate real value. */
546  ctx->coded_peak_bitrate = mlp_peak_bitrate(9600000, avctx->sample_rate);
547 
548  /* TODO support more channels. */
549  if (avctx->channels > 2) {
550  av_log(avctx, AV_LOG_WARNING,
551  "Only mono and stereo are supported at the moment.\n");
552  }
553 
554  ctx->substream_info |= SUBSTREAM_INFO_ALWAYS_SET;
555  if (avctx->channels <= 2) {
556  ctx->substream_info |= SUBSTREAM_INFO_MAX_2_CHAN;
557  }
558 
559  switch (avctx->sample_fmt) {
560  case AV_SAMPLE_FMT_S16:
561  ctx->coded_sample_fmt[0] = BITS_16;
562  ctx->wordlength = 16;
563  avctx->bits_per_raw_sample = 16;
564  break;
565  /* TODO 20 bits: */
566  case AV_SAMPLE_FMT_S32:
567  ctx->coded_sample_fmt[0] = BITS_24;
568  ctx->wordlength = 24;
569  avctx->bits_per_raw_sample = 24;
570  break;
571  default:
572  av_log(avctx, AV_LOG_ERROR, "Sample format not supported. "
573  "Only 16- and 24-bit samples are supported.\n");
574  return AVERROR(EINVAL);
575  }
576  ctx->coded_sample_fmt[1] = -1 & 0xf;
577 
578  ctx->dts = -avctx->frame_size;
579 
580  ctx->num_channels = avctx->channels + 2; /* +2 noise channels */
581  ctx->one_sample_buffer_size = avctx->frame_size
582  * ctx->num_channels;
583  /* TODO Let user pass major header interval as parameter. */
584  ctx->max_restart_interval = MAJOR_HEADER_INTERVAL;
585 
586  ctx->max_codebook_search = 3;
587  ctx->min_restart_interval = MAJOR_HEADER_INTERVAL;
588  ctx->restart_intervals = ctx->max_restart_interval / ctx->min_restart_interval;
589 
590  /* TODO Let user pass parameters for LPC filter. */
591 
592  size = avctx->frame_size * ctx->max_restart_interval;
593 
594  ctx->lpc_sample_buffer = av_malloc_array(size, sizeof(int32_t));
595  if (!ctx->lpc_sample_buffer) {
596  av_log(avctx, AV_LOG_ERROR,
597  "Not enough memory for buffering samples.\n");
598  return AVERROR(ENOMEM);
599  }
600 
601  size = ctx->one_sample_buffer_size * ctx->max_restart_interval;
602 
603  ctx->major_scratch_buffer = av_malloc_array(size, sizeof(int32_t));
604  if (!ctx->major_scratch_buffer) {
605  av_log(avctx, AV_LOG_ERROR,
606  "Not enough memory for buffering samples.\n");
607  return AVERROR(ENOMEM);
608  }
609 
610  ctx->major_inout_buffer = av_malloc_array(size, sizeof(int32_t));
611  if (!ctx->major_inout_buffer) {
612  av_log(avctx, AV_LOG_ERROR,
613  "Not enough memory for buffering samples.\n");
614  return AVERROR(ENOMEM);
615  }
616 
617  ctx->num_substreams = 1; // TODO: change this after adding multi-channel support for TrueHD
618 
619  if (ctx->avctx->codec_id == AV_CODEC_ID_MLP) {
620  /* MLP */
621  switch(avctx->channel_layout) {
622  case AV_CH_LAYOUT_MONO:
623  ctx->channel_arrangement = 0; break;
624  case AV_CH_LAYOUT_STEREO:
625  ctx->channel_arrangement = 1; break;
626  case AV_CH_LAYOUT_2_1:
627  ctx->channel_arrangement = 2; break;
628  case AV_CH_LAYOUT_QUAD:
629  ctx->channel_arrangement = 3; break;
631  ctx->channel_arrangement = 4; break;
633  ctx->channel_arrangement = 7; break;
635  ctx->channel_arrangement = 8; break;
637  ctx->channel_arrangement = 9; break;
639  ctx->channel_arrangement = 10; break;
641  ctx->channel_arrangement = 11; break;
643  ctx->channel_arrangement = 12; break;
644  default:
645  av_log(avctx, AV_LOG_ERROR, "Unsupported channel arrangement\n");
646  return AVERROR(EINVAL);
647  }
648  ctx->flags = FLAGS_DVDA;
649  ctx->channel_occupancy = ff_mlp_ch_info[ctx->channel_arrangement].channel_occupancy;
650  ctx->summary_info = ff_mlp_ch_info[ctx->channel_arrangement].summary_info ;
651  } else {
652  /* TrueHD */
653  switch(avctx->channel_layout) {
654  case AV_CH_LAYOUT_STEREO:
655  ctx->ch_modifier_thd0 = 0;
656  ctx->ch_modifier_thd1 = 0;
657  ctx->ch_modifier_thd2 = 0;
658  ctx->channel_arrangement = 1;
659  break;
661  ctx->ch_modifier_thd0 = 1;
662  ctx->ch_modifier_thd1 = 1;
663  ctx->ch_modifier_thd2 = 1;
664  ctx->channel_arrangement = 11;
665  break;
667  ctx->ch_modifier_thd0 = 2;
668  ctx->ch_modifier_thd1 = 1;
669  ctx->ch_modifier_thd2 = 2;
670  ctx->channel_arrangement = 15;
671  break;
672  default:
673  av_log(avctx, AV_LOG_ERROR, "Unsupported channel arrangement\n");
674  return AVERROR(EINVAL);
675  }
676  ctx->flags = 0;
677  ctx->channel_occupancy = 0;
678  ctx->summary_info = 0;
679  }
680 
681  size = sizeof(unsigned int) * ctx->max_restart_interval;
682 
683  ctx->frame_size = av_malloc(size);
684  if (!ctx->frame_size)
685  return AVERROR(ENOMEM);
686 
687  ctx->max_output_bits = av_malloc(size);
688  if (!ctx->max_output_bits)
689  return AVERROR(ENOMEM);
690 
691  size = sizeof(int32_t)
692  * ctx->num_substreams * ctx->max_restart_interval;
693 
694  ctx->lossless_check_data = av_malloc(size);
695  if (!ctx->lossless_check_data)
696  return AVERROR(ENOMEM);
697 
698  for (index = 0; index < ctx->restart_intervals; index++) {
699  ctx->seq_offset[index] = sum;
700  ctx->seq_size [index] = ((index + 1) * ctx->min_restart_interval) + 1;
701  sum += ctx->seq_size[index];
702  }
703  ctx->sequence_size = sum;
704  size = sizeof(ChannelParams)
705  * ctx->restart_intervals * ctx->sequence_size * ctx->avctx->channels;
706  ctx->channel_params = av_malloc(size);
707  if (!ctx->channel_params) {
708  av_log(avctx, AV_LOG_ERROR,
709  "Not enough memory for analysis context.\n");
710  return AVERROR(ENOMEM);
711  }
712 
713  size = sizeof(DecodingParams)
714  * ctx->restart_intervals * ctx->sequence_size * ctx->num_substreams;
715  ctx->decoding_params = av_malloc(size);
716  if (!ctx->decoding_params) {
717  av_log(avctx, AV_LOG_ERROR,
718  "Not enough memory for analysis context.\n");
719  return AVERROR(ENOMEM);
720  }
721 
722  for (substr = 0; substr < ctx->num_substreams; substr++) {
723  RestartHeader *rh = &ctx->restart_header [substr];
724 
725  /* TODO see if noisegen_seed is really worth it. */
726  rh->noisegen_seed = 0;
727 
728  rh->min_channel = 0;
729  rh->max_channel = avctx->channels - 1;
730  /* FIXME: this works for 1 and 2 channels, but check for more */
732  }
733 
734  if ((ret = ff_lpc_init(&ctx->lpc_ctx, ctx->number_of_samples,
736  av_log(avctx, AV_LOG_ERROR,
737  "Not enough memory for LPC context.\n");
738  return ret;
739  }
740 
741  ff_af_queue_init(avctx, &ctx->afq);
742 
743  ff_thread_once(&init_static_once, mlp_encode_init_static);
744 
745  return 0;
746 }
747 
748 /****************************************************************************
749  ****************** Functions that write to the bitstream *******************
750  ****************************************************************************/
751 
752 /** Writes a major sync header to the bitstream. */
753 static void write_major_sync(MLPEncodeContext *ctx, uint8_t *buf, int buf_size)
754 {
755  PutBitContext pb;
756 
757  init_put_bits(&pb, buf, buf_size);
758 
759  put_bits(&pb, 24, SYNC_MAJOR );
760 
761  if (ctx->avctx->codec_id == AV_CODEC_ID_MLP) {
762  put_bits(&pb, 8, SYNC_MLP );
763  put_bits(&pb, 4, ctx->coded_sample_fmt [0]);
764  put_bits(&pb, 4, ctx->coded_sample_fmt [1]);
765  put_bits(&pb, 4, ctx->coded_sample_rate[0]);
766  put_bits(&pb, 4, ctx->coded_sample_rate[1]);
767  put_bits(&pb, 4, 0 ); /* ignored */
768  put_bits(&pb, 4, 0 ); /* multi_channel_type */
769  put_bits(&pb, 3, 0 ); /* ignored */
770  put_bits(&pb, 5, ctx->channel_arrangement );
771  } else if (ctx->avctx->codec_id == AV_CODEC_ID_TRUEHD) {
772  put_bits(&pb, 8, SYNC_TRUEHD );
773  put_bits(&pb, 4, ctx->coded_sample_rate[0]);
774  put_bits(&pb, 4, 0 ); /* ignored */
775  put_bits(&pb, 2, ctx->ch_modifier_thd0 );
776  put_bits(&pb, 2, ctx->ch_modifier_thd1 );
777  put_bits(&pb, 5, ctx->channel_arrangement );
778  put_bits(&pb, 2, ctx->ch_modifier_thd2 );
779  put_bits(&pb, 13, ctx->channel_arrangement );
780  }
781 
783  put_bits(&pb, 16, ctx->flags );
784  put_bits(&pb, 16, 0 ); /* ignored */
785  put_bits(&pb, 1, 1 ); /* is_vbr */
786  put_bits(&pb, 15, ctx->coded_peak_bitrate );
787  put_bits(&pb, 4, 1 ); /* num_substreams */
788  put_bits(&pb, 4, 0x1 ); /* ignored */
789 
790  /* channel_meaning */
791  put_bits(&pb, 8, ctx->substream_info );
792  put_bits(&pb, 5, ctx->fs );
793  put_bits(&pb, 5, ctx->wordlength );
794  put_bits(&pb, 6, ctx->channel_occupancy );
795  put_bits(&pb, 3, 0 ); /* ignored */
796  put_bits(&pb, 10, 0 ); /* speaker_layout */
797  put_bits(&pb, 3, 0 ); /* copy_protection */
798  put_bits(&pb, 16, 0x8080 ); /* ignored */
799  put_bits(&pb, 7, 0 ); /* ignored */
800  put_bits(&pb, 4, 0 ); /* source_format */
801  put_bits(&pb, 5, ctx->summary_info );
802 
803  flush_put_bits(&pb);
804 
805  AV_WL16(buf+26, ff_mlp_checksum16(buf, 26));
806 }
807 
808 /** Writes a restart header to the bitstream. Damaged streams can start being
809  * decoded losslessly again after such a header and the subsequent decoding
810  * params header.
811  */
813 {
814  RestartHeader *rh = ctx->cur_restart_header;
815  uint8_t lossless_check = xor_32_to_8(rh->lossless_check_data);
816  unsigned int start_count = put_bits_count(pb);
817  PutBitContext tmpb;
818  uint8_t checksum;
819  unsigned int ch;
820 
821  put_bits(pb, 14, 0x31ea ); /* TODO 0x31eb */
822  put_bits(pb, 16, ctx->timestamp );
823  put_bits(pb, 4, rh->min_channel );
824  put_bits(pb, 4, rh->max_channel );
825  put_bits(pb, 4, rh->max_matrix_channel);
826  put_bits(pb, 4, rh->noise_shift );
827  put_bits(pb, 23, rh->noisegen_seed );
828  put_bits(pb, 4, 0 ); /* TODO max_shift */
829  put_bits(pb, 5, rh->max_huff_lsbs );
830  put_bits(pb, 5, rh->max_output_bits );
831  put_bits(pb, 5, rh->max_output_bits );
832  put_bits(pb, 1, rh->data_check_present);
833  put_bits(pb, 8, lossless_check );
834  put_bits(pb, 16, 0 ); /* ignored */
835 
836  for (ch = 0; ch <= rh->max_matrix_channel; ch++)
837  put_bits(pb, 6, ch);
838 
839  /* Data must be flushed for the checksum to be correct. */
840  tmpb = *pb;
841  flush_put_bits(&tmpb);
842 
843  checksum = ff_mlp_restart_checksum(pb->buf, put_bits_count(pb) - start_count);
844 
845  put_bits(pb, 8, checksum);
846 }
847 
848 /** Writes matrix params for all primitive matrices to the bitstream. */
850 {
851  DecodingParams *dp = ctx->cur_decoding_params;
852  MatrixParams *mp = &dp->matrix_params;
853  unsigned int mat;
854 
855  put_bits(pb, 4, mp->count);
856 
857  for (mat = 0; mat < mp->count; mat++) {
858  unsigned int channel;
859 
860  put_bits(pb, 4, mp->outch[mat]); /* matrix_out_ch */
861  put_bits(pb, 4, mp->fbits[mat]);
862  put_bits(pb, 1, 0 ); /* lsb_bypass */
863 
864  for (channel = 0; channel < ctx->num_channels; channel++) {
865  int32_t coeff = mp->coeff[mat][channel];
866 
867  if (coeff) {
868  put_bits(pb, 1, 1);
869 
870  coeff >>= 14 - mp->fbits[mat];
871 
872  put_sbits(pb, mp->fbits[mat] + 2, coeff);
873  } else {
874  put_bits(pb, 1, 0);
875  }
876  }
877  }
878 }
879 
880 /** Writes filter parameters for one filter to the bitstream. */
882  unsigned int channel, unsigned int filter)
883 {
884  FilterParams *fp = &ctx->cur_channel_params[channel].filter_params[filter];
885 
886  put_bits(pb, 4, fp->order);
887 
888  if (fp->order > 0) {
889  int i;
890  int32_t *fcoeff = ctx->cur_channel_params[channel].coeff[filter];
891 
892  put_bits(pb, 4, fp->shift );
893  put_bits(pb, 5, fp->coeff_bits );
894  put_bits(pb, 3, fp->coeff_shift);
895 
896  for (i = 0; i < fp->order; i++) {
897  put_sbits(pb, fp->coeff_bits, fcoeff[i] >> fp->coeff_shift);
898  }
899 
900  /* TODO state data for IIR filter. */
901  put_bits(pb, 1, 0);
902  }
903 }
904 
905 /** Writes decoding parameters to the bitstream. These change very often,
906  * usually at almost every frame.
907  */
909  int params_changed)
910 {
911  DecodingParams *dp = ctx->cur_decoding_params;
912  RestartHeader *rh = ctx->cur_restart_header;
913  MatrixParams *mp = &dp->matrix_params;
914  unsigned int ch;
915 
917  params_changed & PARAM_PRESENCE_FLAGS) {
918  put_bits(pb, 1, 1);
919  put_bits(pb, 8, dp->param_presence_flags);
920  } else {
921  put_bits(pb, 1, 0);
922  }
923 
925  if (params_changed & PARAM_BLOCKSIZE) {
926  put_bits(pb, 1, 1);
927  put_bits(pb, 9, dp->blocksize);
928  } else {
929  put_bits(pb, 1, 0);
930  }
931  }
932 
934  if (params_changed & PARAM_MATRIX) {
935  put_bits(pb, 1, 1);
937  } else {
938  put_bits(pb, 1, 0);
939  }
940  }
941 
943  if (params_changed & PARAM_OUTSHIFT) {
944  put_bits(pb, 1, 1);
945  for (ch = 0; ch <= rh->max_matrix_channel; ch++)
946  put_sbits(pb, 4, mp->shift[ch]);
947  } else {
948  put_bits(pb, 1, 0);
949  }
950  }
951 
953  if (params_changed & PARAM_QUANTSTEP) {
954  put_bits(pb, 1, 1);
955  for (ch = 0; ch <= rh->max_channel; ch++)
956  put_bits(pb, 4, dp->quant_step_size[ch]);
957  } else {
958  put_bits(pb, 1, 0);
959  }
960  }
961 
962  for (ch = rh->min_channel; ch <= rh->max_channel; ch++) {
963  ChannelParams *cp = &ctx->cur_channel_params[ch];
964 
965  if (dp->param_presence_flags & 0xF) {
966  put_bits(pb, 1, 1);
967 
968  if (dp->param_presence_flags & PARAM_FIR) {
969  if (params_changed & PARAM_FIR) {
970  put_bits(pb, 1, 1);
971  write_filter_params(ctx, pb, ch, FIR);
972  } else {
973  put_bits(pb, 1, 0);
974  }
975  }
976 
977  if (dp->param_presence_flags & PARAM_IIR) {
978  if (params_changed & PARAM_IIR) {
979  put_bits(pb, 1, 1);
980  write_filter_params(ctx, pb, ch, IIR);
981  } else {
982  put_bits(pb, 1, 0);
983  }
984  }
985 
987  if (params_changed & PARAM_HUFFOFFSET) {
988  put_bits (pb, 1, 1);
989  put_sbits(pb, 15, cp->huff_offset);
990  } else {
991  put_bits(pb, 1, 0);
992  }
993  }
994  if (cp->codebook > 0 && cp->huff_lsbs > 24) {
995  av_log(ctx->avctx, AV_LOG_ERROR, "Invalid Huff LSBs\n");
996  }
997 
998  put_bits(pb, 2, cp->codebook );
999  put_bits(pb, 5, cp->huff_lsbs);
1000  } else {
1001  put_bits(pb, 1, 0);
1002  }
1003  }
1004 }
1005 
1006 /** Writes the residuals to the bitstream. That is, the VLC codes from the
1007  * codebooks (if any is used), and then the residual.
1008  */
1010 {
1011  DecodingParams *dp = ctx->cur_decoding_params;
1012  RestartHeader *rh = ctx->cur_restart_header;
1013  int32_t *sample_buffer = ctx->write_buffer;
1014  int32_t sign_huff_offset[MAX_CHANNELS];
1015  int codebook_index [MAX_CHANNELS];
1016  int lsb_bits [MAX_CHANNELS];
1017  unsigned int i, ch;
1018 
1019  for (ch = rh->min_channel; ch <= rh->max_channel; ch++) {
1020  ChannelParams *cp = &ctx->cur_channel_params[ch];
1021  int sign_shift;
1022 
1023  lsb_bits [ch] = cp->huff_lsbs - dp->quant_step_size[ch];
1024  codebook_index [ch] = cp->codebook - 1;
1025  sign_huff_offset[ch] = cp->huff_offset;
1026 
1027  sign_shift = lsb_bits[ch] + (cp->codebook ? 2 - cp->codebook : -1);
1028 
1029  if (cp->codebook > 0)
1030  sign_huff_offset[ch] -= 7 << lsb_bits[ch];
1031 
1032  /* Unsign if needed. */
1033  if (sign_shift >= 0)
1034  sign_huff_offset[ch] -= 1 << sign_shift;
1035  }
1036 
1037  for (i = 0; i < dp->blocksize; i++) {
1038  for (ch = rh->min_channel; ch <= rh->max_channel; ch++) {
1039  int32_t sample = *sample_buffer++ >> dp->quant_step_size[ch];
1040  sample -= sign_huff_offset[ch];
1041 
1042  if (codebook_index[ch] >= 0) {
1043  int vlc = sample >> lsb_bits[ch];
1044  put_bits(pb, ff_mlp_huffman_tables[codebook_index[ch]][vlc][1],
1045  ff_mlp_huffman_tables[codebook_index[ch]][vlc][0]);
1046  }
1047 
1048  put_sbits(pb, lsb_bits[ch], sample);
1049  }
1050  sample_buffer += 2; /* noise channels */
1051  }
1052 
1053  ctx->write_buffer = sample_buffer;
1054 }
1055 
1056 /** Writes the substreams data to the bitstream. */
1057 static uint8_t *write_substrs(MLPEncodeContext *ctx, uint8_t *buf, int buf_size,
1058  int restart_frame,
1059  uint16_t substream_data_len[MAX_SUBSTREAMS])
1060 {
1061  int32_t *lossless_check_data = ctx->lossless_check_data;
1062  unsigned int substr;
1063  int end = 0;
1064 
1065  lossless_check_data += ctx->frame_index * ctx->num_substreams;
1066 
1067  for (substr = 0; substr < ctx->num_substreams; substr++) {
1068  unsigned int cur_subblock_index = ctx->major_cur_subblock_index;
1069  unsigned int num_subblocks = ctx->major_filter_state_subblock;
1070  unsigned int subblock;
1071  RestartHeader *rh = &ctx->restart_header [substr];
1072  int substr_restart_frame = restart_frame;
1073  uint8_t parity, checksum;
1074  PutBitContext pb;
1075  int params_changed;
1076 
1077  ctx->cur_restart_header = rh;
1078 
1079  init_put_bits(&pb, buf, buf_size);
1080 
1081  for (subblock = 0; subblock <= num_subblocks; subblock++) {
1082  unsigned int subblock_index;
1083 
1084  subblock_index = cur_subblock_index++;
1085 
1086  ctx->cur_decoding_params = &ctx->major_decoding_params[subblock_index][substr];
1087  ctx->cur_channel_params = ctx->major_channel_params[subblock_index];
1088 
1089  params_changed = ctx->major_params_changed[subblock_index][substr];
1090 
1091  if (substr_restart_frame || params_changed) {
1092  put_bits(&pb, 1, 1);
1093 
1094  if (substr_restart_frame) {
1095  put_bits(&pb, 1, 1);
1096 
1097  write_restart_header(ctx, &pb);
1098  rh->lossless_check_data = 0;
1099  } else {
1100  put_bits(&pb, 1, 0);
1101  }
1102 
1103  write_decoding_params(ctx, &pb, params_changed);
1104  } else {
1105  put_bits(&pb, 1, 0);
1106  }
1107 
1108  write_block_data(ctx, &pb);
1109 
1110  put_bits(&pb, 1, !substr_restart_frame);
1111 
1112  substr_restart_frame = 0;
1113  }
1114 
1115  put_bits(&pb, (-put_bits_count(&pb)) & 15, 0);
1116 
1117  rh->lossless_check_data ^= *lossless_check_data++;
1118 
1119  if (ctx->last_frame == ctx->inout_buffer) {
1120  /* TODO find a sample and implement shorten_by. */
1121  put_bits(&pb, 32, END_OF_STREAM);
1122  }
1123 
1124  /* Data must be flushed for the checksum and parity to be correct;
1125  * notice that we already are word-aligned here. */
1126  flush_put_bits(&pb);
1127 
1128  parity = ff_mlp_calculate_parity(buf, put_bytes_output(&pb)) ^ 0xa9;
1130 
1131  put_bits(&pb, 8, parity );
1132  put_bits(&pb, 8, checksum);
1133 
1134  flush_put_bits(&pb);
1135 
1136  end += put_bytes_output(&pb);
1137  substream_data_len[substr] = end;
1138 
1139  buf += put_bytes_output(&pb);
1140  }
1141 
1142  ctx->major_cur_subblock_index += ctx->major_filter_state_subblock + 1;
1143  ctx->major_filter_state_subblock = 0;
1144 
1145  return buf;
1146 }
1147 
1148 /** Writes the access unit and substream headers to the bitstream. */
1150  uint8_t *substream_headers, unsigned int length,
1151  int restart_frame,
1152  uint16_t substream_data_len[MAX_SUBSTREAMS])
1153 {
1154  uint16_t access_unit_header = 0;
1155  uint16_t parity_nibble = 0;
1156  unsigned int substr;
1157 
1158  parity_nibble = ctx->dts;
1159  parity_nibble ^= length;
1160 
1161  for (substr = 0; substr < ctx->num_substreams; substr++) {
1162  uint16_t substr_hdr = 0;
1163 
1164  substr_hdr |= (0 << 15); /* extraword */
1165  substr_hdr |= (!restart_frame << 14); /* !restart_frame */
1166  substr_hdr |= (1 << 13); /* checkdata */
1167  substr_hdr |= (0 << 12); /* ??? */
1168  substr_hdr |= (substream_data_len[substr] / 2) & 0x0FFF;
1169 
1170  AV_WB16(substream_headers, substr_hdr);
1171 
1172  parity_nibble ^= *substream_headers++;
1173  parity_nibble ^= *substream_headers++;
1174  }
1175 
1176  parity_nibble ^= parity_nibble >> 8;
1177  parity_nibble ^= parity_nibble >> 4;
1178  parity_nibble &= 0xF;
1179 
1180  access_unit_header |= (parity_nibble ^ 0xF) << 12;
1181  access_unit_header |= length & 0xFFF;
1182 
1183  AV_WB16(frame_header , access_unit_header);
1184  AV_WB16(frame_header+2, ctx->dts );
1185 }
1186 
1187 /** Writes an entire access unit to the bitstream. */
1188 static unsigned int write_access_unit(MLPEncodeContext *ctx, uint8_t *buf,
1189  int buf_size, int restart_frame)
1190 {
1191  uint16_t substream_data_len[MAX_SUBSTREAMS];
1192  uint8_t *buf1, *buf0 = buf;
1193  unsigned int substr;
1194  int total_length;
1195 
1196  if (buf_size < 4)
1197  return AVERROR(EINVAL);
1198 
1199  /* Frame header will be written at the end. */
1200  buf += 4;
1201  buf_size -= 4;
1202 
1203  if (restart_frame) {
1204  if (buf_size < 28)
1205  return AVERROR(EINVAL);
1206  write_major_sync(ctx, buf, buf_size);
1207  buf += 28;
1208  buf_size -= 28;
1209  }
1210 
1211  buf1 = buf;
1212 
1213  /* Substream headers will be written at the end. */
1214  for (substr = 0; substr < ctx->num_substreams; substr++) {
1215  buf += 2;
1216  buf_size -= 2;
1217  }
1218 
1219  buf = write_substrs(ctx, buf, buf_size, restart_frame, substream_data_len);
1220 
1221  total_length = buf - buf0;
1222 
1223  write_frame_headers(ctx, buf0, buf1, total_length / 2, restart_frame, substream_data_len);
1224 
1225  return total_length;
1226 }
1227 
1228 /****************************************************************************
1229  ****************** Functions that input data to context ********************
1230  ****************************************************************************/
1231 
1232 /** Inputs data from the samples passed by lavc into the context, shifts them
1233  * appropriately depending on the bit-depth, and calculates the
1234  * lossless_check_data that will be written to the restart header.
1235  */
1236 static void input_data_internal(MLPEncodeContext *ctx, const uint8_t *samples,
1237  int is24)
1238 {
1239  int32_t *lossless_check_data = ctx->lossless_check_data;
1240  const int32_t *samples_32 = (const int32_t *) samples;
1241  const int16_t *samples_16 = (const int16_t *) samples;
1242  unsigned int substr;
1243 
1244  lossless_check_data += ctx->frame_index * ctx->num_substreams;
1245 
1246  for (substr = 0; substr < ctx->num_substreams; substr++) {
1247  RestartHeader *rh = &ctx->restart_header [substr];
1248  int32_t *sample_buffer = ctx->inout_buffer;
1249  int32_t temp_lossless_check_data = 0;
1250  uint32_t greatest = 0;
1251  unsigned int channel;
1252  int i;
1253 
1254  for (i = 0; i < ctx->frame_size[ctx->frame_index]; i++) {
1255  for (channel = 0; channel <= rh->max_channel; channel++) {
1256  uint32_t abs_sample;
1257  int32_t sample;
1258 
1259  sample = is24 ? *samples_32++ >> 8 : *samples_16++ * 256;
1260 
1261  /* TODO Find out if number_sbits can be used for negative values. */
1262  abs_sample = FFABS(sample);
1263  if (greatest < abs_sample)
1264  greatest = abs_sample;
1265 
1266  temp_lossless_check_data ^= (sample & 0x00ffffff) << channel;
1267  *sample_buffer++ = sample;
1268  }
1269 
1270  sample_buffer += 2; /* noise channels */
1271  }
1272 
1273  ctx->max_output_bits[ctx->frame_index] = number_sbits(greatest);
1274 
1275  *lossless_check_data++ = temp_lossless_check_data;
1276  }
1277 }
1278 
1279 /** Wrapper function for inputting data in two different bit-depths. */
1281 {
1282  if (ctx->avctx->sample_fmt == AV_SAMPLE_FMT_S32)
1284  else
1286 }
1287 
1289 {
1290  int32_t *sample_buffer = ctx->sample_buffer;
1291  unsigned int index;
1292 
1293  for (index = 0; index < ctx->number_of_frames; index++) {
1294  unsigned int cur_index = (ctx->starting_frame_index + index) % ctx->max_restart_interval;
1295  int32_t *input_buffer = ctx->inout_buffer + cur_index * ctx->one_sample_buffer_size;
1296  unsigned int i, channel;
1297 
1298  for (i = 0; i < ctx->frame_size[cur_index]; i++) {
1299  for (channel = 0; channel < ctx->avctx->channels; channel++)
1300  *sample_buffer++ = *input_buffer++;
1301  sample_buffer += 2; /* noise_channels */
1302  input_buffer += 2; /* noise_channels */
1303  }
1304  }
1305 }
1306 
1307 /****************************************************************************
1308  ********* Functions that analyze the data and set the parameters ***********
1309  ****************************************************************************/
1310 
1311 /** Counts the number of trailing zeroes in a value */
1313 {
1314  int bits;
1315 
1316  for (bits = 0; bits < 24 && !(sample & (1<<bits)); bits++);
1317 
1318  /* All samples are 0. TODO Return previous quant_step_size to avoid
1319  * writing a new header. */
1320  if (bits == 24)
1321  return 0;
1322 
1323  return bits;
1324 }
1325 
1326 /** Determines how many bits are zero at the end of all samples so they can be
1327  * shifted out.
1328  */
1330 {
1331  DecodingParams *dp = ctx->cur_decoding_params;
1332  RestartHeader *rh = ctx->cur_restart_header;
1333  MatrixParams *mp = &dp->matrix_params;
1334  int32_t *sample_buffer = ctx->sample_buffer;
1335  int32_t sample_mask[MAX_CHANNELS];
1336  unsigned int channel;
1337  int i;
1338 
1339  memset(sample_mask, 0x00, sizeof(sample_mask));
1340 
1341  for (i = 0; i < ctx->number_of_samples; i++) {
1342  for (channel = 0; channel <= rh->max_channel; channel++)
1343  sample_mask[channel] |= *sample_buffer++;
1344 
1345  sample_buffer += 2; /* noise channels */
1346  }
1347 
1348  for (channel = 0; channel <= rh->max_channel; channel++)
1349  dp->quant_step_size[channel] = number_trailing_zeroes(sample_mask[channel]) - mp->shift[channel];
1350 }
1351 
1352 /** Determines the smallest number of bits needed to encode the filter
1353  * coefficients, and if it's possible to right-shift their values without
1354  * losing any precision.
1355  */
1357 {
1358  int min = INT_MAX, max = INT_MIN;
1359  int bits, shift;
1360  int coeff_mask = 0;
1361  int order;
1362 
1363  for (order = 0; order < fp->order; order++) {
1364  int coeff = fcoeff[order];
1365 
1366  if (coeff < min)
1367  min = coeff;
1368  if (coeff > max)
1369  max = coeff;
1370 
1371  coeff_mask |= coeff;
1372  }
1373 
1375 
1376  for (shift = 0; shift < 7 && bits + shift < 16 && !(coeff_mask & (1<<shift)); shift++);
1377 
1378  fp->coeff_bits = bits;
1379  fp->coeff_shift = shift;
1380 }
1381 
1382 /** Determines the best filter parameters for the given data and writes the
1383  * necessary information to the context.
1384  * TODO Add IIR filter predictor!
1385  */
1387  unsigned int channel, unsigned int filter,
1388  int clear_filter)
1389 {
1390  ChannelParams *cp = &ctx->cur_channel_params[channel];
1392 
1393  if ((filter == IIR && ctx->substream_info & SUBSTREAM_INFO_HIGH_RATE) ||
1394  clear_filter) {
1395  fp->order = 0;
1396  } else if (filter == IIR) {
1397  fp->order = 0;
1398  } else if (filter == FIR) {
1399  const int max_order = (ctx->substream_info & SUBSTREAM_INFO_HIGH_RATE)
1400  ? 4 : MLP_MAX_LPC_ORDER;
1401  int32_t *sample_buffer = ctx->sample_buffer + channel;
1403  int32_t *lpc_samples = ctx->lpc_sample_buffer;
1404  int32_t *fcoeff = ctx->cur_channel_params[channel].coeff[filter];
1405  int shift[MLP_MAX_LPC_ORDER];
1406  unsigned int i;
1407  int order;
1408 
1409  for (i = 0; i < ctx->number_of_samples; i++) {
1410  *lpc_samples++ = *sample_buffer;
1411  sample_buffer += ctx->num_channels;
1412  }
1413 
1414  order = ff_lpc_calc_coefs(&ctx->lpc_ctx, ctx->lpc_sample_buffer,
1415  ctx->number_of_samples, MLP_MIN_LPC_ORDER,
1416  max_order, 11, coefs, shift, FF_LPC_TYPE_LEVINSON, 0,
1419 
1420  fp->order = order;
1421  fp->shift = shift[order-1];
1422 
1423  for (i = 0; i < order; i++)
1424  fcoeff[i] = coefs[order-1][i];
1425 
1426  code_filter_coeffs(ctx, fp, fcoeff);
1427  }
1428 }
1429 
1430 /** Tries to determine a good prediction filter, and applies it to the samples
1431  * buffer if the filter is good enough. Sets the filter data to be cleared if
1432  * no good filter was found.
1433  */
1435 {
1436  RestartHeader *rh = ctx->cur_restart_header;
1437  int channel, filter;
1438 
1439  for (channel = rh->min_channel; channel <= rh->max_channel; channel++) {
1440  for (filter = 0; filter < NUM_FILTERS; filter++)
1442  }
1443 }
1444 
1450 };
1451 
1453 {
1454  uint64_t score[4], sum[4] = { 0, 0, 0, 0, };
1455  int32_t *right_ch = ctx->sample_buffer + 1;
1456  int32_t *left_ch = ctx->sample_buffer;
1457  int i;
1458  enum MLPChMode best = 0;
1459 
1460  for(i = 2; i < ctx->number_of_samples; i++) {
1461  int32_t left = left_ch [i * ctx->num_channels] - 2 * left_ch [(i - 1) * ctx->num_channels] + left_ch [(i - 2) * ctx->num_channels];
1462  int32_t right = right_ch[i * ctx->num_channels] - 2 * right_ch[(i - 1) * ctx->num_channels] + right_ch[(i - 2) * ctx->num_channels];
1463 
1464  sum[0] += FFABS( left );
1465  sum[1] += FFABS( right);
1466  sum[2] += FFABS((left + right) >> 1);
1467  sum[3] += FFABS( left - right);
1468  }
1469 
1470  score[MLP_CHMODE_LEFT_RIGHT] = sum[0] + sum[1];
1471  score[MLP_CHMODE_LEFT_SIDE] = sum[0] + sum[3];
1472  score[MLP_CHMODE_RIGHT_SIDE] = sum[1] + sum[3];
1473  score[MLP_CHMODE_MID_SIDE] = sum[2] + sum[3];
1474 
1475  for(i = 1; i < 3; i++)
1476  if(score[i] < score[best])
1477  best = i;
1478 
1479  return best;
1480 }
1481 
1482 /** Determines how many fractional bits are needed to encode matrix
1483  * coefficients. Also shifts the coefficients to fit within 2.14 bits.
1484  */
1485 static void code_matrix_coeffs(MLPEncodeContext *ctx, unsigned int mat)
1486 {
1487  DecodingParams *dp = ctx->cur_decoding_params;
1488  MatrixParams *mp = &dp->matrix_params;
1489  int32_t coeff_mask = 0;
1490  unsigned int channel;
1491  unsigned int bits;
1492 
1493  for (channel = 0; channel < ctx->num_channels; channel++) {
1494  int32_t coeff = mp->coeff[mat][channel];
1495  coeff_mask |= coeff;
1496  }
1497 
1498  for (bits = 0; bits < 14 && !(coeff_mask & (1<<bits)); bits++);
1499 
1500  mp->fbits [mat] = 14 - bits;
1501 }
1502 
1503 /** Determines best coefficients to use for the lossless matrix. */
1505 {
1506  DecodingParams *dp = ctx->cur_decoding_params;
1507  MatrixParams *mp = &dp->matrix_params;
1508  unsigned int shift = 0;
1509  unsigned int channel;
1510  int mat;
1511  enum MLPChMode mode;
1512 
1513  /* No decorrelation for non-stereo. */
1514  if (ctx->num_channels - 2 != 2) {
1515  mp->count = 0;
1516  return;
1517  }
1518 
1520 
1521  switch(mode) {
1522  /* TODO: add matrix for MID_SIDE */
1523  case MLP_CHMODE_MID_SIDE:
1524  case MLP_CHMODE_LEFT_RIGHT:
1525  mp->count = 0;
1526  break;
1527  case MLP_CHMODE_LEFT_SIDE:
1528  mp->count = 1;
1529  mp->outch[0] = 1;
1530  mp->coeff[0][0] = 1 << 14; mp->coeff[0][1] = -(1 << 14);
1531  mp->coeff[0][2] = 0 << 14; mp->coeff[0][2] = 0 << 14;
1532  mp->forco[0][0] = 1 << 14; mp->forco[0][1] = -(1 << 14);
1533  mp->forco[0][2] = 0 << 14; mp->forco[0][2] = 0 << 14;
1534  break;
1535  case MLP_CHMODE_RIGHT_SIDE:
1536  mp->count = 1;
1537  mp->outch[0] = 0;
1538  mp->coeff[0][0] = 1 << 14; mp->coeff[0][1] = 1 << 14;
1539  mp->coeff[0][2] = 0 << 14; mp->coeff[0][2] = 0 << 14;
1540  mp->forco[0][0] = 1 << 14; mp->forco[0][1] = -(1 << 14);
1541  mp->forco[0][2] = 0 << 14; mp->forco[0][2] = 0 << 14;
1542  break;
1543  }
1544 
1545  for (mat = 0; mat < mp->count; mat++)
1546  code_matrix_coeffs(ctx, mat);
1547 
1548  for (channel = 0; channel < ctx->num_channels; channel++)
1549  mp->shift[channel] = shift;
1550 }
1551 
1552 /** Min and max values that can be encoded with each codebook. The values for
1553  * the third codebook take into account the fact that the sign shift for this
1554  * codebook is outside the coded value, so it has one more bit of precision.
1555  * It should actually be -7 -> 7, shifted down by 0.5.
1556  */
1557 static const int codebook_extremes[3][2] = {
1558  {-9, 8}, {-8, 7}, {-15, 14},
1559 };
1560 
1561 /** Determines the amount of bits needed to encode the samples using no
1562  * codebooks and a specified offset.
1563  */
1565  unsigned int channel, int16_t offset,
1567  BestOffset *bo)
1568 {
1569  DecodingParams *dp = ctx->cur_decoding_params;
1570  int32_t unsign = 0;
1571  int lsb_bits;
1572 
1573  min -= offset;
1574  max -= offset;
1575 
1576  lsb_bits = FFMAX(number_sbits(min), number_sbits(max)) - 1;
1577 
1578  lsb_bits += !!lsb_bits;
1579 
1580  if (lsb_bits > 0)
1581  unsign = 1 << (lsb_bits - 1);
1582 
1583  bo->offset = offset;
1584  bo->lsb_bits = lsb_bits;
1585  bo->bitcount = lsb_bits * dp->blocksize;
1586  bo->min = offset - unsign + 1;
1587  bo->max = offset + unsign;
1588 }
1589 
1590 /** Determines the least amount of bits needed to encode the samples using no
1591  * codebooks.
1592  */
1594  unsigned int channel,
1596  BestOffset *bo)
1597 {
1598  DecodingParams *dp = ctx->cur_decoding_params;
1599  int16_t offset;
1600  int32_t unsign = 0;
1601  uint32_t diff;
1602  int lsb_bits;
1603 
1604  /* Set offset inside huffoffset's boundaries by adjusting extremes
1605  * so that more bits are used, thus shifting the offset. */
1606  if (min < HUFF_OFFSET_MIN)
1607  max = FFMAX(max, 2 * HUFF_OFFSET_MIN - min + 1);
1608  if (max > HUFF_OFFSET_MAX)
1609  min = FFMIN(min, 2 * HUFF_OFFSET_MAX - max - 1);
1610 
1611  /* Determine offset and minimum number of bits. */
1612  diff = max - min;
1613 
1614  lsb_bits = number_sbits(diff) - 1;
1615 
1616  if (lsb_bits > 0)
1617  unsign = 1 << (lsb_bits - 1);
1618 
1619  /* If all samples are the same (lsb_bits == 0), offset must be
1620  * adjusted because of sign_shift. */
1621  offset = min + diff / 2 + !!lsb_bits;
1622 
1623  bo->offset = offset;
1624  bo->lsb_bits = lsb_bits;
1625  bo->bitcount = lsb_bits * dp->blocksize;
1626  bo->min = max - unsign + 1;
1627  bo->max = min + unsign;
1628 }
1629 
1630 /** Determines the least amount of bits needed to encode the samples using a
1631  * given codebook and a given offset.
1632  */
1634  unsigned int channel, int codebook,
1635  int32_t sample_min, int32_t sample_max,
1636  int16_t offset, BestOffset *bo)
1637 {
1638  int32_t codebook_min = codebook_extremes[codebook][0];
1639  int32_t codebook_max = codebook_extremes[codebook][1];
1640  int32_t *sample_buffer = ctx->sample_buffer + channel;
1641  DecodingParams *dp = ctx->cur_decoding_params;
1642  int codebook_offset = 7 + (2 - codebook);
1643  int32_t unsign_offset = offset;
1644  int lsb_bits = 0, bitcount = 0;
1645  int offset_min = INT_MAX, offset_max = INT_MAX;
1646  int unsign, mask;
1647  int i;
1648 
1649  sample_min -= offset;
1650  sample_max -= offset;
1651 
1652  while (sample_min < codebook_min || sample_max > codebook_max) {
1653  lsb_bits++;
1654  sample_min >>= 1;
1655  sample_max >>= 1;
1656  }
1657 
1658  unsign = 1 << lsb_bits;
1659  mask = unsign - 1;
1660 
1661  if (codebook == 2) {
1662  unsign_offset -= unsign;
1663  lsb_bits++;
1664  }
1665 
1666  for (i = 0; i < dp->blocksize; i++) {
1667  int32_t sample = *sample_buffer >> dp->quant_step_size[channel];
1668  int temp_min, temp_max;
1669 
1670  sample -= unsign_offset;
1671 
1672  temp_min = sample & mask;
1673  if (temp_min < offset_min)
1674  offset_min = temp_min;
1675 
1676  temp_max = unsign - temp_min - 1;
1677  if (temp_max < offset_max)
1678  offset_max = temp_max;
1679 
1680  sample >>= lsb_bits;
1681 
1682  bitcount += ff_mlp_huffman_tables[codebook][sample + codebook_offset][1];
1683 
1684  sample_buffer += ctx->num_channels;
1685  }
1686 
1687  bo->offset = offset;
1688  bo->lsb_bits = lsb_bits;
1689  bo->bitcount = lsb_bits * dp->blocksize + bitcount;
1690  bo->min = FFMAX(offset - offset_min, HUFF_OFFSET_MIN);
1691  bo->max = FFMIN(offset + offset_max, HUFF_OFFSET_MAX);
1692 }
1693 
1694 /** Determines the least amount of bits needed to encode the samples using a
1695  * given codebook. Searches for the best offset to minimize the bits.
1696  */
1697 static inline void codebook_bits(MLPEncodeContext *ctx,
1698  unsigned int channel, int codebook,
1699  int offset, int32_t min, int32_t max,
1700  BestOffset *bo, int direction)
1701 {
1702  int previous_count = INT_MAX;
1703  int offset_min, offset_max;
1704  int is_greater = 0;
1705 
1706  offset_min = FFMAX(min, HUFF_OFFSET_MIN);
1707  offset_max = FFMIN(max, HUFF_OFFSET_MAX);
1708 
1709  while (offset <= offset_max && offset >= offset_min) {
1710  BestOffset temp_bo;
1711 
1713  min, max, offset,
1714  &temp_bo);
1715 
1716  if (temp_bo.bitcount < previous_count) {
1717  if (temp_bo.bitcount < bo->bitcount)
1718  *bo = temp_bo;
1719 
1720  is_greater = 0;
1721  } else if (++is_greater >= ctx->max_codebook_search)
1722  break;
1723 
1724  previous_count = temp_bo.bitcount;
1725 
1726  if (direction) {
1727  offset = temp_bo.max + 1;
1728  } else {
1729  offset = temp_bo.min - 1;
1730  }
1731  }
1732 }
1733 
1734 /** Determines the least amount of bits needed to encode the samples using
1735  * any or no codebook.
1736  */
1738 {
1739  DecodingParams *dp = ctx->cur_decoding_params;
1740  RestartHeader *rh = ctx->cur_restart_header;
1741  unsigned int channel;
1742 
1743  for (channel = 0; channel <= rh->max_channel; channel++) {
1744  ChannelParams *cp = &ctx->cur_channel_params[channel];
1745  int32_t *sample_buffer = ctx->sample_buffer + channel;
1746  int32_t min = INT32_MAX, max = INT32_MIN;
1747  int no_filters_used = !cp->filter_params[FIR].order;
1748  int average = 0;
1749  int offset = 0;
1750  int i;
1751 
1752  /* Determine extremes and average. */
1753  for (i = 0; i < dp->blocksize; i++) {
1754  int32_t sample = *sample_buffer >> dp->quant_step_size[channel];
1755  if (sample < min)
1756  min = sample;
1757  if (sample > max)
1758  max = sample;
1759  average += sample;
1760  sample_buffer += ctx->num_channels;
1761  }
1762  average /= dp->blocksize;
1763 
1764  /* If filtering is used, we always set the offset to zero, otherwise
1765  * we search for the offset that minimizes the bitcount. */
1766  if (no_filters_used) {
1767  no_codebook_bits(ctx, channel, min, max, &ctx->cur_best_offset[channel][0]);
1769  } else {
1770  no_codebook_bits_offset(ctx, channel, offset, min, max, &ctx->cur_best_offset[channel][0]);
1771  }
1772 
1773  for (i = 1; i < NUM_CODEBOOKS; i++) {
1774  BestOffset temp_bo = { 0, INT_MAX, 0, 0, 0, };
1775  int16_t offset_max;
1776 
1778  min, max, offset,
1779  &temp_bo);
1780 
1781  if (no_filters_used) {
1782  offset_max = temp_bo.max;
1783 
1784  codebook_bits(ctx, channel, i - 1, temp_bo.min - 1,
1785  min, max, &temp_bo, 0);
1786  codebook_bits(ctx, channel, i - 1, offset_max + 1,
1787  min, max, &temp_bo, 1);
1788  }
1789 
1790  ctx->cur_best_offset[channel][i] = temp_bo;
1791  }
1792  }
1793 }
1794 
1795 /****************************************************************************
1796  *************** Functions that process the data in some way ****************
1797  ****************************************************************************/
1798 
1799 #define SAMPLE_MAX(bitdepth) ((1 << (bitdepth - 1)) - 1)
1800 #define SAMPLE_MIN(bitdepth) (~SAMPLE_MAX(bitdepth))
1801 
1802 #define MSB_MASK(bits) (-(int)(1u << (bits)))
1803 
1804 /** Applies the filter to the current samples, and saves the residual back
1805  * into the samples buffer. If the filter is too bad and overflows the
1806  * maximum amount of bits allowed (24), the samples buffer is left as is and
1807  * the function returns -1.
1808  */
1809 static int apply_filter(MLPEncodeContext *ctx, unsigned int channel)
1810 {
1811  FilterParams *fp[NUM_FILTERS] = { &ctx->cur_channel_params[channel].filter_params[FIR],
1812  &ctx->cur_channel_params[channel].filter_params[IIR], };
1813  int32_t *filter_state_buffer[NUM_FILTERS] = { NULL };
1814  int32_t mask = MSB_MASK(ctx->cur_decoding_params->quant_step_size[channel]);
1815  int32_t *sample_buffer = ctx->sample_buffer + channel;
1816  unsigned int number_of_samples = ctx->number_of_samples;
1817  unsigned int filter_shift = fp[FIR]->shift;
1818  int filter;
1819  int i, ret = 0;
1820 
1821  for (i = 0; i < NUM_FILTERS; i++) {
1822  unsigned int size = ctx->number_of_samples;
1823  filter_state_buffer[i] = av_malloc(size*sizeof(int32_t));
1824  if (!filter_state_buffer[i]) {
1825  av_log(ctx->avctx, AV_LOG_ERROR,
1826  "Not enough memory for applying filters.\n");
1827  ret = AVERROR(ENOMEM);
1828  goto free_and_return;
1829  }
1830  }
1831 
1832  for (i = 0; i < 8; i++) {
1833  filter_state_buffer[FIR][i] = *sample_buffer;
1834  filter_state_buffer[IIR][i] = *sample_buffer;
1835 
1836  sample_buffer += ctx->num_channels;
1837  }
1838 
1839  for (i = 8; i < number_of_samples; i++) {
1840  int32_t sample = *sample_buffer;
1841  unsigned int order;
1842  int64_t accum = 0;
1843  int64_t residual;
1844 
1845  for (filter = 0; filter < NUM_FILTERS; filter++) {
1846  int32_t *fcoeff = ctx->cur_channel_params[channel].coeff[filter];
1847  for (order = 0; order < fp[filter]->order; order++)
1848  accum += (int64_t)filter_state_buffer[filter][i - 1 - order] *
1849  fcoeff[order];
1850  }
1851 
1852  accum >>= filter_shift;
1853  residual = sample - (accum & mask);
1854 
1855  if (residual < SAMPLE_MIN(24) || residual > SAMPLE_MAX(24)) {
1857  goto free_and_return;
1858  }
1859 
1860  filter_state_buffer[FIR][i] = sample;
1861  filter_state_buffer[IIR][i] = (int32_t) residual;
1862 
1863  sample_buffer += ctx->num_channels;
1864  }
1865 
1866  sample_buffer = ctx->sample_buffer + channel;
1867  for (i = 0; i < number_of_samples; i++) {
1868  *sample_buffer = filter_state_buffer[IIR][i];
1869 
1870  sample_buffer += ctx->num_channels;
1871  }
1872 
1873 free_and_return:
1874  for (i = 0; i < NUM_FILTERS; i++) {
1875  av_freep(&filter_state_buffer[i]);
1876  }
1877 
1878  return ret;
1879 }
1880 
1882 {
1883  RestartHeader *rh = ctx->cur_restart_header;
1884  int channel;
1885 
1886  for (channel = rh->min_channel; channel <= rh->max_channel; channel++) {
1887  if (apply_filter(ctx, channel) < 0) {
1888  /* Filter is horribly wrong.
1889  * Clear filter params and update state. */
1893  }
1894  }
1895 }
1896 
1897 /** Generates two noise channels worth of data. */
1899 {
1900  int32_t *sample_buffer = ctx->sample_buffer + ctx->num_channels - 2;
1901  RestartHeader *rh = ctx->cur_restart_header;
1902  unsigned int i;
1903  uint32_t seed = rh->noisegen_seed;
1904 
1905  for (i = 0; i < ctx->number_of_samples; i++) {
1906  uint16_t seed_shr7 = seed >> 7;
1907  *sample_buffer++ = ((int8_t)(seed >> 15)) * (1 << rh->noise_shift);
1908  *sample_buffer++ = ((int8_t) seed_shr7) * (1 << rh->noise_shift);
1909 
1910  seed = (seed << 16) ^ seed_shr7 ^ (seed_shr7 << 5);
1911 
1912  sample_buffer += ctx->num_channels - 2;
1913  }
1914 
1915  rh->noisegen_seed = seed & ((1 << 24)-1);
1916 }
1917 
1918 /** Rematrixes all channels using chosen coefficients. */
1920 {
1921  DecodingParams *dp = ctx->cur_decoding_params;
1922  MatrixParams *mp = &dp->matrix_params;
1923  int32_t *sample_buffer = ctx->sample_buffer;
1924  unsigned int mat, i, maxchan;
1925 
1926  maxchan = ctx->num_channels;
1927 
1928  for (mat = 0; mat < mp->count; mat++) {
1929  unsigned int msb_mask_bits = (ctx->avctx->sample_fmt == AV_SAMPLE_FMT_S16 ? 8 : 0) - mp->shift[mat];
1930  int32_t mask = MSB_MASK(msb_mask_bits);
1931  unsigned int outch = mp->outch[mat];
1932 
1933  sample_buffer = ctx->sample_buffer;
1934  for (i = 0; i < ctx->number_of_samples; i++) {
1935  unsigned int src_ch;
1936  int64_t accum = 0;
1937 
1938  for (src_ch = 0; src_ch < maxchan; src_ch++) {
1939  int32_t sample = *(sample_buffer + src_ch);
1940  accum += (int64_t) sample * mp->forco[mat][src_ch];
1941  }
1942  sample_buffer[outch] = (accum >> 14) & mask;
1943 
1944  sample_buffer += ctx->num_channels;
1945  }
1946  }
1947 }
1948 
1949 /****************************************************************************
1950  **** Functions that deal with determining the best parameters and output ***
1951  ****************************************************************************/
1952 
1953 typedef struct {
1954  char path[MAJOR_HEADER_INTERVAL + 2];
1955  int cur_idx;
1956  int bitcount;
1959 #define CODEBOOK_CHANGE_BITS 21
1960 
1961 static void clear_path_counter(PathCounter *path_counter)
1962 {
1963  memset(path_counter, 0, (NUM_CODEBOOKS + 1) * sizeof(*path_counter));
1964 }
1965 
1966 static int compare_best_offset(const BestOffset *prev, const BestOffset *cur)
1967 {
1968  if (prev->lsb_bits != cur->lsb_bits)
1969  return 1;
1970 
1971  return 0;
1972 }
1973 
1975  PathCounter *src, int cur_codebook)
1976 {
1977  int idx = src->cur_idx;
1978  const BestOffset *cur_bo = ctx->best_offset[idx][channel],
1979  *prev_bo = idx ? ctx->best_offset[idx - 1][channel] :
1981  int bitcount = src->bitcount;
1982  int prev_codebook = src->path[idx];
1983 
1984  bitcount += cur_bo[cur_codebook].bitcount;
1985 
1986  if (prev_codebook != cur_codebook ||
1987  compare_best_offset(&prev_bo[prev_codebook], &cur_bo[cur_codebook]))
1988  bitcount += CODEBOOK_CHANGE_BITS;
1989 
1990  return bitcount;
1991 }
1992 
1994 {
1995  DecodingParams *dp = ctx->cur_decoding_params;
1996  RestartHeader *rh = ctx->cur_restart_header;
1997  unsigned int channel;
1998 
1999  for (channel = rh->min_channel; channel <= rh->max_channel; channel++) {
2000  const BestOffset *prev_bo = restart_best_offset;
2001  BestOffset *cur_bo;
2002  PathCounter path_counter[NUM_CODEBOOKS + 1];
2003  unsigned int best_codebook;
2004  unsigned int index;
2005  char *best_path;
2006 
2007  clear_path_counter(path_counter);
2008 
2009  for (index = 0; index < ctx->number_of_subblocks; index++) {
2010  unsigned int best_bitcount = INT_MAX;
2011  unsigned int codebook;
2012 
2013  cur_bo = ctx->best_offset[index][channel];
2014 
2015  for (codebook = 0; codebook < NUM_CODEBOOKS; codebook++) {
2016  int prev_best_bitcount = INT_MAX;
2017  int last_best;
2018 
2019  for (last_best = 0; last_best < 2; last_best++) {
2020  PathCounter *dst_path = &path_counter[codebook];
2021  PathCounter *src_path;
2022  int temp_bitcount;
2023 
2024  /* First test last path with same headers,
2025  * then with last best. */
2026  if (last_best) {
2027  src_path = &path_counter[NUM_CODEBOOKS];
2028  } else {
2029  if (compare_best_offset(&prev_bo[codebook], &cur_bo[codebook]))
2030  continue;
2031  else
2032  src_path = &path_counter[codebook];
2033  }
2034 
2035  temp_bitcount = best_codebook_path_cost(ctx, channel, src_path, codebook);
2036 
2037  if (temp_bitcount < best_bitcount) {
2038  best_bitcount = temp_bitcount;
2039  best_codebook = codebook;
2040  }
2041 
2042  if (temp_bitcount < prev_best_bitcount) {
2043  prev_best_bitcount = temp_bitcount;
2044  if (src_path != dst_path)
2045  memcpy(dst_path, src_path, sizeof(PathCounter));
2046  if (dst_path->cur_idx < FF_ARRAY_ELEMS(dst_path->path) - 1)
2047  dst_path->path[++dst_path->cur_idx] = codebook;
2048  dst_path->bitcount = temp_bitcount;
2049  }
2050  }
2051  }
2052 
2053  prev_bo = cur_bo;
2054 
2055  memcpy(&path_counter[NUM_CODEBOOKS], &path_counter[best_codebook], sizeof(PathCounter));
2056  }
2057 
2058  best_path = path_counter[NUM_CODEBOOKS].path + 1;
2059 
2060  /* Update context. */
2061  for (index = 0; index < ctx->number_of_subblocks; index++) {
2062  ChannelParams *cp = ctx->seq_channel_params + index*(ctx->avctx->channels) + channel;
2063 
2064  best_codebook = *best_path++;
2065  cur_bo = &ctx->best_offset[index][channel][best_codebook];
2066 
2067  cp->huff_offset = cur_bo->offset;
2068  cp->huff_lsbs = cur_bo->lsb_bits + dp->quant_step_size[channel];
2069  cp->codebook = best_codebook;
2070  }
2071  }
2072 }
2073 
2074 /** Analyzes all collected bitcounts and selects the best parameters for each
2075  * individual access unit.
2076  * TODO This is just a stub!
2077  */
2079 {
2080  RestartHeader *rh = ctx->cur_restart_header;
2081  unsigned int index;
2082  unsigned int substr;
2083  uint8_t max_huff_lsbs = 0;
2084  uint8_t max_output_bits = 0;
2085 
2086  for (substr = 0; substr < ctx->num_substreams; substr++) {
2087  DecodingParams *seq_dp = (DecodingParams *) ctx->decoding_params+
2088  (ctx->restart_intervals - 1)*(ctx->sequence_size)*(ctx->avctx->channels) +
2089  (ctx->seq_offset[ctx->restart_intervals - 1])*(ctx->avctx->channels);
2090 
2091  ChannelParams *seq_cp = (ChannelParams *) ctx->channel_params +
2092  (ctx->restart_intervals - 1)*(ctx->sequence_size)*(ctx->avctx->channels) +
2093  (ctx->seq_offset[ctx->restart_intervals - 1])*(ctx->avctx->channels);
2094  unsigned int channel;
2095  for (index = 0; index < ctx->seq_size[ctx->restart_intervals-1]; index++) {
2096  memcpy(&ctx->major_decoding_params[index][substr], seq_dp + index*(ctx->num_substreams) + substr, sizeof(DecodingParams));
2097  for (channel = 0; channel < ctx->avctx->channels; channel++) {
2098  uint8_t huff_lsbs = (seq_cp + index*(ctx->avctx->channels) + channel)->huff_lsbs;
2099  if (max_huff_lsbs < huff_lsbs)
2100  max_huff_lsbs = huff_lsbs;
2101  memcpy(&ctx->major_channel_params[index][channel],
2102  (seq_cp + index*(ctx->avctx->channels) + channel),
2103  sizeof(ChannelParams));
2104  }
2105  }
2106  }
2107 
2108  rh->max_huff_lsbs = max_huff_lsbs;
2109 
2110  for (index = 0; index < ctx->number_of_frames; index++)
2111  if (max_output_bits < ctx->max_output_bits[index])
2112  max_output_bits = ctx->max_output_bits[index];
2113  rh->max_output_bits = max_output_bits;
2114 
2115  for (substr = 0; substr < ctx->num_substreams; substr++) {
2116 
2117  ctx->cur_restart_header = &ctx->restart_header[substr];
2118 
2119  ctx->prev_decoding_params = &restart_decoding_params[substr];
2120  ctx->prev_channel_params = restart_channel_params;
2121 
2122  for (index = 0; index < MAJOR_HEADER_INTERVAL + 1; index++) {
2123  ctx->cur_decoding_params = &ctx->major_decoding_params[index][substr];
2124  ctx->cur_channel_params = ctx->major_channel_params[index];
2125 
2126  ctx->major_params_changed[index][substr] = compare_decoding_params(ctx);
2127 
2128  ctx->prev_decoding_params = ctx->cur_decoding_params;
2129  ctx->prev_channel_params = ctx->cur_channel_params;
2130  }
2131  }
2132 
2133  ctx->major_number_of_subblocks = ctx->number_of_subblocks;
2134  ctx->major_filter_state_subblock = 1;
2135  ctx->major_cur_subblock_index = 0;
2136 }
2137 
2139 {
2140  ChannelParams *seq_cp = ctx->seq_channel_params;
2141  DecodingParams *seq_dp = ctx->seq_decoding_params;
2142  unsigned int index;
2143  unsigned int substr;
2144 
2145  for (substr = 0; substr < ctx->num_substreams; substr++) {
2146 
2147  ctx->cur_restart_header = &ctx->restart_header[substr];
2148  ctx->cur_decoding_params = seq_dp + 1*(ctx->num_substreams) + substr;
2149  ctx->cur_channel_params = seq_cp + 1*(ctx->avctx->channels);
2150 
2156  apply_filters (ctx);
2157 
2158  copy_restart_frame_params(ctx, substr);
2159 
2160  /* Copy frame_size from frames 0...max to decoding_params 1...max + 1
2161  * decoding_params[0] is for the filter state subblock.
2162  */
2163  for (index = 0; index < ctx->number_of_frames; index++) {
2164  DecodingParams *dp = seq_dp + (index + 1)*(ctx->num_substreams) + substr;
2165  dp->blocksize = ctx->frame_size[index];
2166  }
2167  /* The official encoder seems to always encode a filter state subblock
2168  * even if there are no filters. TODO check if it is possible to skip
2169  * the filter state subblock for no filters.
2170  */
2171  (seq_dp + substr)->blocksize = 8;
2172  (seq_dp + 1*(ctx->num_substreams) + substr)->blocksize -= 8;
2173 
2174  for (index = 0; index < ctx->number_of_subblocks; index++) {
2175  ctx->cur_decoding_params = seq_dp + index*(ctx->num_substreams) + substr;
2176  ctx->cur_channel_params = seq_cp + index*(ctx->avctx->channels);
2177  ctx->cur_best_offset = ctx->best_offset[index];
2179  ctx->sample_buffer += ctx->cur_decoding_params->blocksize * ctx->num_channels;
2180  }
2181 
2183  }
2184 }
2185 
2187 {
2188  unsigned int substr;
2189 
2190  ctx->sample_buffer = ctx->major_inout_buffer;
2191 
2192  ctx->starting_frame_index = 0;
2193  ctx->number_of_frames = ctx->major_number_of_frames;
2194  ctx->number_of_samples = ctx->major_frame_size;
2195 
2196  for (substr = 0; substr < ctx->num_substreams; substr++) {
2197  ctx->cur_restart_header = &ctx->restart_header[substr];
2198 
2199  ctx->cur_decoding_params = &ctx->major_decoding_params[1][substr];
2200  ctx->cur_channel_params = ctx->major_channel_params[1];
2201 
2204 
2205  apply_filters(ctx);
2206  }
2207 }
2208 
2209 /****************************************************************************/
2210 
2211 static int mlp_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,
2212  const AVFrame *frame, int *got_packet)
2213 {
2214  MLPEncodeContext *ctx = avctx->priv_data;
2215  unsigned int bytes_written = 0;
2216  int restart_frame, ret;
2217  uint8_t *data;
2218 
2219  if ((ret = ff_alloc_packet(avctx, avpkt, 87500 * avctx->channels)) < 0)
2220  return ret;
2221 
2222  /* add current frame to queue */
2223  if ((ret = ff_af_queue_add(&ctx->afq, frame)) < 0)
2224  return ret;
2225 
2226  data = frame->data[0];
2227 
2228  ctx->frame_index = avctx->frame_number % ctx->max_restart_interval;
2229 
2230  ctx->inout_buffer = ctx->major_inout_buffer
2231  + ctx->frame_index * ctx->one_sample_buffer_size;
2232 
2233  if (ctx->last_frame == ctx->inout_buffer) {
2234  return 0;
2235  }
2236 
2237  ctx->sample_buffer = ctx->major_scratch_buffer
2238  + ctx->frame_index * ctx->one_sample_buffer_size;
2239 
2240  ctx->write_buffer = ctx->inout_buffer;
2241 
2242  if (avctx->frame_number < ctx->max_restart_interval) {
2243  if (data) {
2244  goto input_and_return;
2245  } else {
2246  /* There are less frames than the requested major header interval.
2247  * Update the context to reflect this.
2248  */
2249  ctx->max_restart_interval = avctx->frame_number;
2250  ctx->frame_index = 0;
2251 
2252  ctx->sample_buffer = ctx->major_scratch_buffer;
2253  ctx->inout_buffer = ctx->major_inout_buffer;
2254  }
2255  }
2256 
2257  if (ctx->frame_size[ctx->frame_index] > MAX_BLOCKSIZE) {
2258  av_log(avctx, AV_LOG_ERROR, "Invalid frame size (%d > %d)\n",
2259  ctx->frame_size[ctx->frame_index], MAX_BLOCKSIZE);
2260  return AVERROR_INVALIDDATA;
2261  }
2262 
2263  restart_frame = !ctx->frame_index;
2264 
2265  if (restart_frame) {
2267  if (ctx->min_restart_interval != ctx->max_restart_interval)
2269  }
2270 
2271  if (ctx->min_restart_interval == ctx->max_restart_interval)
2272  ctx->write_buffer = ctx->sample_buffer;
2273 
2274  bytes_written = write_access_unit(ctx, avpkt->data, avpkt->size, restart_frame);
2275 
2276  ctx->timestamp += ctx->frame_size[ctx->frame_index];
2277  ctx->dts += ctx->frame_size[ctx->frame_index];
2278 
2279 input_and_return:
2280 
2281  if (data) {
2282  ctx->frame_size[ctx->frame_index] = avctx->frame_size;
2283  ctx->next_major_frame_size += avctx->frame_size;
2284  ctx->next_major_number_of_frames++;
2285  input_data(ctx, data);
2286  } else if (!ctx->last_frame) {
2287  ctx->last_frame = ctx->inout_buffer;
2288  }
2289 
2290  restart_frame = (ctx->frame_index + 1) % ctx->min_restart_interval;
2291 
2292  if (!restart_frame) {
2293  int seq_index;
2294 
2295  for (seq_index = 0;
2296  seq_index < ctx->restart_intervals && (seq_index * ctx->min_restart_interval) <= ctx->avctx->frame_number;
2297  seq_index++) {
2298  unsigned int number_of_samples = 0;
2299  unsigned int index;
2300 
2301  ctx->sample_buffer = ctx->major_scratch_buffer;
2302  ctx->inout_buffer = ctx->major_inout_buffer;
2303  ctx->seq_index = seq_index;
2304 
2305  ctx->starting_frame_index = (ctx->avctx->frame_number - (ctx->avctx->frame_number % ctx->min_restart_interval)
2306  - (seq_index * ctx->min_restart_interval)) % ctx->max_restart_interval;
2307  ctx->number_of_frames = ctx->next_major_number_of_frames;
2308  ctx->number_of_subblocks = ctx->next_major_number_of_frames + 1;
2309 
2310  ctx->seq_channel_params = (ChannelParams *) ctx->channel_params +
2311  (ctx->frame_index / ctx->min_restart_interval)*(ctx->sequence_size)*(ctx->avctx->channels) +
2312  (ctx->seq_offset[seq_index])*(ctx->avctx->channels);
2313 
2314  ctx->seq_decoding_params = (DecodingParams *) ctx->decoding_params +
2315  (ctx->frame_index / ctx->min_restart_interval)*(ctx->sequence_size)*(ctx->num_substreams) +
2316  (ctx->seq_offset[seq_index])*(ctx->num_substreams);
2317 
2318  for (index = 0; index < ctx->number_of_frames; index++) {
2319  number_of_samples += ctx->frame_size[(ctx->starting_frame_index + index) % ctx->max_restart_interval];
2320  }
2321  ctx->number_of_samples = number_of_samples;
2322 
2323  for (index = 0; index < ctx->seq_size[seq_index]; index++) {
2324  clear_channel_params(ctx->seq_channel_params + index * ctx->avctx->channels, ctx->avctx->channels);
2325  default_decoding_params(ctx, ctx->seq_decoding_params + index*(ctx->num_substreams));
2326  }
2327 
2329 
2331  }
2332 
2333  if (ctx->frame_index == (ctx->max_restart_interval - 1)) {
2334  ctx->major_frame_size = ctx->next_major_frame_size;
2335  ctx->next_major_frame_size = 0;
2336  ctx->major_number_of_frames = ctx->next_major_number_of_frames;
2337  ctx->next_major_number_of_frames = 0;
2338 
2339  if (!ctx->major_frame_size)
2340  goto no_data_left;
2341  }
2342  }
2343 
2344 no_data_left:
2345 
2346  ff_af_queue_remove(&ctx->afq, avctx->frame_size, &avpkt->pts,
2347  &avpkt->duration);
2348  avpkt->size = bytes_written;
2349  *got_packet = 1;
2350  return 0;
2351 }
2352 
2354 {
2355  MLPEncodeContext *ctx = avctx->priv_data;
2356 
2357  ff_lpc_end(&ctx->lpc_ctx);
2358 
2359  av_freep(&ctx->lossless_check_data);
2360  av_freep(&ctx->major_scratch_buffer);
2361  av_freep(&ctx->major_inout_buffer);
2362  av_freep(&ctx->lpc_sample_buffer);
2363  av_freep(&ctx->decoding_params);
2364  av_freep(&ctx->channel_params);
2365  av_freep(&ctx->frame_size);
2366  av_freep(&ctx->max_output_bits);
2367  ff_af_queue_close(&ctx->afq);
2368 
2369  return 0;
2370 }
2371 
2372 #if CONFIG_MLP_ENCODER
2373 const AVCodec ff_mlp_encoder = {
2374  .name ="mlp",
2375  .long_name = NULL_IF_CONFIG_SMALL("MLP (Meridian Lossless Packing)"),
2376  .type = AVMEDIA_TYPE_AUDIO,
2377  .id = AV_CODEC_ID_MLP,
2378  .priv_data_size = sizeof(MLPEncodeContext),
2379  .init = mlp_encode_init,
2380  .encode2 = mlp_encode_frame,
2381  .close = mlp_encode_close,
2384  .supported_samplerates = (const int[]) {44100, 48000, 88200, 96000, 176400, 192000, 0},
2385  .channel_layouts = ff_mlp_channel_layouts,
2387 };
2388 #endif
2389 #if CONFIG_TRUEHD_ENCODER
2390 const AVCodec ff_truehd_encoder = {
2391  .name ="truehd",
2392  .long_name = NULL_IF_CONFIG_SMALL("TrueHD"),
2393  .type = AVMEDIA_TYPE_AUDIO,
2394  .id = AV_CODEC_ID_TRUEHD,
2395  .priv_data_size = sizeof(MLPEncodeContext),
2396  .init = mlp_encode_init,
2397  .encode2 = mlp_encode_frame,
2398  .close = mlp_encode_close,
2401  .supported_samplerates = (const int[]) {44100, 48000, 88200, 96000, 176400, 192000, 0},
2402  .channel_layouts = (const uint64_t[]) {AV_CH_LAYOUT_STEREO, AV_CH_LAYOUT_5POINT0_BACK, AV_CH_LAYOUT_5POINT1_BACK, 0},
2404 };
2405 #endif
ChannelInformation::summary_info
uint8_t summary_info
Definition: mlp.h:104
MatrixParams::fbits
uint8_t fbits[MAX_CHANNELS]
fraction bits
Definition: mlpenc.c:65
AVCodecContext::frame_size
int frame_size
Number of samples per channel in an audio frame.
Definition: avcodec.h:1008
set_best_codebook
static void set_best_codebook(MLPEncodeContext *ctx)
Definition: mlpenc.c:1993
AVCodec
AVCodec.
Definition: codec.h:197
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
FF_CODEC_CAP_INIT_THREADSAFE
#define FF_CODEC_CAP_INIT_THREADSAFE
The codec does not modify any global variables in the init function, allowing to call the init functi...
Definition: internal.h:42
no_codebook_bits
static void no_codebook_bits(MLPEncodeContext *ctx, unsigned int channel, int32_t min, int32_t max, BestOffset *bo)
Determines the least amount of bits needed to encode the samples using no codebooks.
Definition: mlpenc.c:1593
AV_CH_LAYOUT_5POINT0_BACK
#define AV_CH_LAYOUT_5POINT0_BACK
Definition: channel_layout.h:102
av_clip
#define av_clip
Definition: common.h:96
init
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:31
MLP_MIN_LPC_ORDER
#define MLP_MIN_LPC_ORDER
Definition: mlpenc.c:38
MLPEncodeContext::major_cur_subblock_index
unsigned int major_cur_subblock_index
Definition: mlpenc.c:178
ChannelParams::codebook
uint8_t codebook
Which VLC codebook to use to read residuals.
Definition: mlp.h:89
MLPEncodeContext::avctx
AVCodecContext * avctx
Definition: mlpenc.c:107
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
MLPEncodeContext::ch_modifier_thd1
uint8_t ch_modifier_thd1
channel modifier for TrueHD stream 1
Definition: mlpenc.c:160
mlp_encode_init_static
static av_cold void mlp_encode_init_static(void)
Definition: mlpenc.c:486
xor_32_to_8
static uint8_t xor_32_to_8(uint32_t value)
XOR four bytes into one.
Definition: mlp.h:158
AVCodecContext::channel_layout
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:1039
restart_channel_params
static ChannelParams restart_channel_params[MAX_CHANNELS]
Definition: mlpenc.c:207
write_decoding_params
static void write_decoding_params(MLPEncodeContext *ctx, PutBitContext *pb, int params_changed)
Writes decoding parameters to the bitstream.
Definition: mlpenc.c:908
ff_af_queue_remove
void ff_af_queue_remove(AudioFrameQueue *afq, int nb_samples, int64_t *pts, int64_t *duration)
Remove frame(s) from the queue.
Definition: audio_frame_queue.c:75
PARAMS_DEFAULT
@ PARAMS_DEFAULT
Definition: mlpenc.c:71
put_bytes_output
static int put_bytes_output(const PutBitContext *s)
Definition: put_bits.h:88
AVCodecContext::sample_rate
int sample_rate
samples per second
Definition: avcodec.h:988
MLPEncodeContext::afq
AudioFrameQueue afq
Definition: mlpenc.c:187
write_substrs
static uint8_t * write_substrs(MLPEncodeContext *ctx, uint8_t *buf, int buf_size, int restart_frame, uint16_t substream_data_len[MAX_SUBSTREAMS])
Writes the substreams data to the bitstream.
Definition: mlpenc.c:1057
estimate_stereo_mode
static enum MLPChMode estimate_stereo_mode(MLPEncodeContext *ctx)
Definition: mlpenc.c:1452
ff_af_queue_close
void ff_af_queue_close(AudioFrameQueue *afq)
Close AudioFrameQueue.
Definition: audio_frame_queue.c:36
MLPEncodeContext::major_scratch_buffer
int32_t * major_scratch_buffer
Scratch buffer big enough to fit all data for one entire major frame interval.
Definition: mlpenc.c:131
sample_fmts
static enum AVSampleFormat sample_fmts[]
Definition: adpcmenc.c:948
write_major_sync
static void write_major_sync(MLPEncodeContext *ctx, uint8_t *buf, int buf_size)
Writes a major sync header to the bitstream.
Definition: mlpenc.c:753
mlp_encode_close
static av_cold int mlp_encode_close(AVCodecContext *avctx)
Definition: mlpenc.c:2353
thread.h
DecodingParams::blocksize
uint16_t blocksize
number of PCM samples in current audio block
Definition: mlpenc.c:84
PARAM_PRESENCE_FLAGS
@ PARAM_PRESENCE_FLAGS
Definition: mlpenc.c:72
SAMPLE_MAX
#define SAMPLE_MAX(bitdepth)
Definition: mlpenc.c:1799
MLPEncodeContext::coded_peak_bitrate
int coded_peak_bitrate
peak bitrate for this major sync header
Definition: mlpenc.c:116
AV_CH_LAYOUT_MONO
#define AV_CH_LAYOUT_MONO
Definition: channel_layout.h:90
MLPEncodeContext::lpc_sample_buffer
int32_t * lpc_sample_buffer
Definition: mlpenc.c:134
put_sbits
static void put_sbits(PutBitContext *pb, int n, int32_t value)
Definition: put_bits.h:280
MatrixParams::forco
int32_t forco[MAX_MATRICES][MAX_CHANNELS+2]
forward coefficients
Definition: mlpenc.c:63
init_put_bits
static void init_put_bits(PutBitContext *s, uint8_t *buffer, int buffer_size)
Initialize the PutBitContext s.
Definition: put_bits.h:61
ff_af_queue_init
av_cold void ff_af_queue_init(AVCodecContext *avctx, AudioFrameQueue *afq)
Initialize AudioFrameQueue.
Definition: audio_frame_queue.c:28
SUBSTREAM_INFO_HIGH_RATE
#define SUBSTREAM_INFO_HIGH_RATE
Definition: mlpenc.c:223
MatrixParams::shift
int8_t shift[MAX_CHANNELS]
Left shift to apply to decoded PCM values to get final 24-bit output.
Definition: mlpenc.c:67
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:303
put_bits
static void put_bits(Jpeg2000EncoderContext *s, int val, int n)
put n times val bit
Definition: j2kenc.c:220
index
fg index
Definition: ffmpeg_filter.c:168
internal.h
AVPacket::data
uint8_t * data
Definition: packet.h:373
restart_best_offset
static const BestOffset restart_best_offset[NUM_CODEBOOKS]
Definition: mlpenc.c:209
write_frame_headers
static void write_frame_headers(MLPEncodeContext *ctx, uint8_t *frame_header, uint8_t *substream_headers, unsigned int length, int restart_frame, uint16_t substream_data_len[MAX_SUBSTREAMS])
Writes the access unit and substream headers to the bitstream.
Definition: mlpenc.c:1149
clear_path_counter
static void clear_path_counter(PathCounter *path_counter)
Definition: mlpenc.c:1961
MLPEncodeContext::number_of_subblocks
unsigned int number_of_subblocks
Definition: mlpenc.c:193
ff_mlp_calculate_parity
uint8_t ff_mlp_calculate_parity(const uint8_t *buf, unsigned int buf_size)
XOR together all the bytes of a buffer.
Definition: mlp.c:124
encode.h
MLPEncodeContext::number_of_frames
unsigned int number_of_frames
Definition: mlpenc.c:191
data
const char data[16]
Definition: mxf.c:143
MLPChMode
MLPChMode
Definition: mlpenc.c:1445
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:391
max
#define max(a, b)
Definition: cuda_runtime.h:33
ff_mlp_ch_info
const ChannelInformation ff_mlp_ch_info[21]
Tables defining channel information.
Definition: mlp.c:46
filter
filter_frame For filters that do not use the this method is called when a frame is pushed to the filter s input It can be called at any time except in a reentrant way If the input frame is enough to produce then the filter should push the output frames on the output link immediately As an exception to the previous rule if the input frame is enough to produce several output frames then the filter needs output only at least one per link The additional frames can be left buffered in the filter
Definition: filter_design.txt:228
FFMAX
#define FFMAX(a, b)
Definition: macros.h:47
lpc.h
AV_CODEC_ID_TRUEHD
@ AV_CODEC_ID_TRUEHD
Definition: codec_id.h:466
BestOffset
Definition: mlpenc.c:92
MLPEncodeContext::fs
int fs
Definition: mlpenc.c:122
PARAM_MATRIX
@ PARAM_MATRIX
Definition: mlpenc.c:74
set_major_params
static void set_major_params(MLPEncodeContext *ctx)
Analyzes all collected bitcounts and selects the best parameters for each individual access unit.
Definition: mlpenc.c:2078
sample_rate
sample_rate
Definition: ffmpeg_filter.c:156
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:31
MLPEncodeContext::min_restart_interval
unsigned int min_restart_interval
Min interval of access units in between two major frames.
Definition: mlpenc.c:151
MLPEncodeContext::sequence_size
unsigned int sequence_size
Definition: mlpenc.c:165
crc.h
BITS_20
@ BITS_20
Definition: mlpenc.c:477
write_block_data
static void write_block_data(MLPEncodeContext *ctx, PutBitContext *pb)
Writes the residuals to the bitstream.
Definition: mlpenc.c:1009
LPCContext
Definition: lpc.h:52
BITS_24
@ BITS_24
Definition: mlpenc.c:478
PARAM_OUTSHIFT
@ PARAM_OUTSHIFT
Definition: mlpenc.c:75
ff_mlp_checksum16
uint16_t ff_mlp_checksum16(const uint8_t *buf, unsigned int buf_size)
Definition: mlp.c:89
ChannelParams::filter_params
FilterParams filter_params[NUM_FILTERS]
Definition: mlp.h:84
ff_mlp_checksum8
uint8_t ff_mlp_checksum8(const uint8_t *buf, unsigned int buf_size)
MLP uses checksums that seem to be based on the standard CRC algorithm, but are not (in implementatio...
Definition: mlp.c:98
MAX_MATRICES
#define MAX_MATRICES
Definition: mlp.h:41
ChannelParams::huff_lsbs
uint8_t huff_lsbs
Size of residual suffix not encoded using VLC.
Definition: mlp.h:90
mlp_encode_frame
static int mlp_encode_frame(AVCodecContext *avctx, AVPacket *avpkt, const AVFrame *frame, int *got_packet)
Definition: mlpenc.c:2211
MLPEncodeContext::lpc_ctx
LPCContext lpc_ctx
Definition: mlpenc.c:204
SYNC_MAJOR
#define SYNC_MAJOR
Definition: mlpenc.c:211
MLPEncodeContext::major_number_of_frames
unsigned int major_number_of_frames
Definition: mlpenc.c:136
MLP_MAX_LPC_ORDER
#define MLP_MAX_LPC_ORDER
Definition: mlpenc.c:39
audio_frame_queue.h
samplefmt.h
compare_matrix_params
static int compare_matrix_params(MLPEncodeContext *ctx, const MatrixParams *prev, const MatrixParams *mp)
Compare two primitive matrices and returns 1 if anything has changed.
Definition: mlpenc.c:259
MLPEncodeContext::next_major_frame_size
unsigned int next_major_frame_size
Counter of number of samples for next major frame.
Definition: mlpenc.c:140
ff_af_queue_add
int ff_af_queue_add(AudioFrameQueue *afq, const AVFrame *f)
Add a frame to the queue.
Definition: audio_frame_queue.c:44
MLPEncodeContext::substream_info
int substream_info
Definition: mlpenc.c:121
AV_CH_LAYOUT_STEREO
#define AV_CH_LAYOUT_STEREO
Definition: channel_layout.h:91
AV_CH_LAYOUT_QUAD
#define AV_CH_LAYOUT_QUAD
Definition: channel_layout.h:99
RestartHeader::max_output_bits
uint8_t max_output_bits
largest output bit-depth
Definition: mlpenc.c:56
MLPEncodeContext::sample_buffer
int32_t * sample_buffer
Pointer to current access unit samples.
Definition: mlpenc.c:130
END_OF_STREAM
#define END_OF_STREAM
Definition: libxavs.c:37
set_filter_params
static void set_filter_params(MLPEncodeContext *ctx, unsigned int channel, unsigned int filter, int clear_filter)
Determines the best filter parameters for the given data and writes the necessary information to the ...
Definition: mlpenc.c:1386
ff_thread_once
static int ff_thread_once(char *control, void(*routine)(void))
Definition: thread.h:175
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
SUBSTREAM_INFO_MAX_2_CHAN
#define SUBSTREAM_INFO_MAX_2_CHAN
Definition: mlpenc.c:222
FIR
#define FIR
Definition: mlp.h:68
AV_CODEC_CAP_EXPERIMENTAL
#define AV_CODEC_CAP_EXPERIMENTAL
Codec is experimental and is thus avoided in favor of non experimental encoders.
Definition: codec.h:100
FF_ARRAY_ELEMS
#define FF_ARRAY_ELEMS(a)
Definition: sinewin_tablegen.c:29
av_cold
#define av_cold
Definition: attributes.h:90
MLPEncodeContext::prev_channel_params
const ChannelParams * prev_channel_params
Definition: mlpenc.c:196
MLPEncodeContext::major_filter_state_subblock
unsigned int major_filter_state_subblock
Definition: mlpenc.c:179
MLPEncodeContext::summary_info
int summary_info
Definition: mlpenc.c:125
mask
static const uint16_t mask[17]
Definition: lzw.c:38
MLPEncodeContext::seq_channel_params
ChannelParams * seq_channel_params
Definition: mlpenc.c:199
RestartHeader::min_channel
uint8_t min_channel
The index of the first channel coded in this substream.
Definition: mlpenc.c:44
MLPEncodeContext::ch_modifier_thd2
uint8_t ch_modifier_thd2
channel modifier for TrueHD stream 2
Definition: mlpenc.c:161
copy_matrix_params
static void copy_matrix_params(MatrixParams *dst, MatrixParams *src)
Definition: mlpenc.c:362
AVFormatContext::flags
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1225
MLPEncodeContext::dts
uint16_t dts
Decoding timestamp of current access unit.
Definition: mlpenc.c:155
MLPEncodeContext
Definition: mlpenc.c:106
AVMEDIA_TYPE_AUDIO
@ AVMEDIA_TYPE_AUDIO
Definition: avutil.h:202
BestOffset::lsb_bits
int lsb_bits
Definition: mlpenc.c:95
MLP_CHMODE_LEFT_RIGHT
@ MLP_CHMODE_LEFT_RIGHT
Definition: mlpenc.c:1446
MLPEncodeContext::num_channels
int num_channels
Number of channels in major_scratch_buffer.
Definition: mlpenc.c:111
bits
uint8_t bits
Definition: vp3data.h:141
AudioFrameQueue
Definition: audio_frame_queue.h:32
AVCodecContext::bits_per_raw_sample
int bits_per_raw_sample
Bits per sample/pixel of internal libavcodec pixel/sample format.
Definition: avcodec.h:1421
MLP_CHMODE_MID_SIDE
@ MLP_CHMODE_MID_SIDE
Definition: mlpenc.c:1449
ctx
AVFormatContext * ctx
Definition: movenc.c:48
mlp_peak_bitrate
static int mlp_peak_bitrate(int peak_bitrate, int sample_rate)
Definition: mlpenc.c:481
default_decoding_params
static void default_decoding_params(MLPEncodeContext *ctx, DecodingParams decoding_params[MAX_SUBSTREAMS])
Sets default vales in our encoder for a DecodingParams struct.
Definition: mlpenc.c:438
BestOffset::bitcount
int bitcount
Definition: mlpenc.c:94
code_matrix_coeffs
static void code_matrix_coeffs(MLPEncodeContext *ctx, unsigned int mat)
Determines how many fractional bits are needed to encode matrix coefficients.
Definition: mlpenc.c:1485
PathCounter::path
char path[MAJOR_HEADER_INTERVAL+2]
Definition: mlpenc.c:1956
PutBitContext
Definition: put_bits.h:49
ff_mlp_channel_layouts
const uint64_t ff_mlp_channel_layouts[12]
Definition: mlp.c:60
AV_CH_LAYOUT_2_1
#define AV_CH_LAYOUT_2_1
Definition: channel_layout.h:93
FFABS
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:65
if
if(ret)
Definition: filter_design.txt:179
determine_bits
static void determine_bits(MLPEncodeContext *ctx)
Determines the least amount of bits needed to encode the samples using any or no codebook.
Definition: mlpenc.c:1737
MLPEncodeContext::flags
int flags
major sync info flags
Definition: mlpenc.c:118
lossless_matrix_coeffs
static void lossless_matrix_coeffs(MLPEncodeContext *ctx)
Determines best coefficients to use for the lossless matrix.
Definition: mlpenc.c:1504
AV_ONCE_INIT
#define AV_ONCE_INIT
Definition: thread.h:173
codebook_bits
static void codebook_bits(MLPEncodeContext *ctx, unsigned int channel, int codebook, int offset, int32_t min, int32_t max, BestOffset *bo, int direction)
Determines the least amount of bits needed to encode the samples using a given codebook.
Definition: mlpenc.c:1697
ff_mlp_encoder
const AVCodec ff_mlp_encoder
MLPEncodeContext::timestamp
uint16_t timestamp
Timestamp of current access unit.
Definition: mlpenc.c:154
PutBitContext::buf
uint8_t * buf
Definition: put_bits.h:52
NULL
#define NULL
Definition: coverity.c:32
MLPEncodeContext::cur_restart_header
RestartHeader * cur_restart_header
Definition: mlpenc.c:185
codebook_extremes
static const int codebook_extremes[3][2]
Min and max values that can be encoded with each codebook.
Definition: mlpenc.c:1557
apply_filters
static void apply_filters(MLPEncodeContext *ctx)
Definition: mlpenc.c:1881
BestOffset::max
int32_t max
Definition: mlpenc.c:97
AV_WB16
#define AV_WB16(p, v)
Definition: intreadwrite.h:405
MLPEncodeContext::major_frame_size
unsigned int major_frame_size
Number of samples in current major frame being encoded.
Definition: mlpenc.c:139
MLPEncodeContext::num_substreams
int num_substreams
Number of substreams contained within this stream.
Definition: mlpenc.c:109
MLPEncodeContext::lossless_check_data
int32_t * lossless_check_data
Array with lossless_check_data for each access unit.
Definition: mlpenc.c:142
MatrixParams
Definition: mlpenc.c:59
apply_filter
static int apply_filter(MLPEncodeContext *ctx, unsigned int channel)
Applies the filter to the current samples, and saves the residual back into the samples buffer.
Definition: mlpenc.c:1809
MLPEncodeContext::starting_frame_index
unsigned int starting_frame_index
Definition: mlpenc.c:190
RestartHeader::lossless_check_data
int32_t lossless_check_data
XOR of all output samples.
Definition: mlpenc.c:53
src
#define src
Definition: vp8dsp.c:255
quant_step_size
static const float quant_step_size[]
Definition: hca_data.h:125
SYNC_TRUEHD
#define SYNC_TRUEHD
Definition: mlpenc.c:215
copy_filter_params
static void copy_filter_params(ChannelParams *dst_cp, ChannelParams *src_cp, int filter)
Definition: mlpenc.c:343
SYNC_MLP
#define SYNC_MLP
Definition: mlpenc.c:214
ParamFlags
ParamFlags
Definition: mlpenc.c:70
input_to_sample_buffer
static void input_to_sample_buffer(MLPEncodeContext *ctx)
Definition: mlpenc.c:1288
MLPEncodeContext::frame_size
unsigned int * frame_size
Array with number of samples/channel in each access unit.
Definition: mlpenc.c:145
rematrix_channels
static void rematrix_channels(MLPEncodeContext *ctx)
Rematrixes all channels using chosen coefficients.
Definition: mlpenc.c:1919
ChannelParams::coeff
int32_t coeff[NUM_FILTERS][MAX_FIR_ORDER]
Definition: mlp.h:85
ff_lpc_calc_coefs
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 min_shift, int max_shift, int zero_shift)
Calculate LPC coefficients for multiple orders.
Definition: lpc.c:201
fp
#define fp
Definition: regdef.h:44
seed
static unsigned int seed
Definition: videogen.c:78
MLPEncodeContext::max_output_bits
unsigned int * max_output_bits
largest output bit-depth
Definition: mlpenc.c:144
number_sbits
static int number_sbits(int number)
Calculates the smallest number of bits it takes to encode a given signed value in two's complement.
Definition: mlpenc.c:467
AVOnce
#define AVOnce
Definition: thread.h:172
MLPEncodeContext::number_of_samples
unsigned int number_of_samples
Definition: mlpenc.c:192
for
for(j=16;j >0;--j)
Definition: h264pred_template.c:469
FilterParams::coeff_shift
int coeff_shift
Definition: mlp.h:79
FilterParams
filter data
Definition: mlp.h:72
MLPEncodeContext::major_number_of_subblocks
unsigned int major_number_of_subblocks
Definition: mlpenc.c:180
MLPEncodeContext::channel_arrangement
uint8_t channel_arrangement
channel arrangement for MLP streams
Definition: mlpenc.c:157
ff_mlp_restart_checksum
uint8_t ff_mlp_restart_checksum(const uint8_t *buf, unsigned int bit_size)
Calculate an 8-bit checksum over a restart header – a non-multiple-of-8 number of bits,...
Definition: mlp.c:105
code_filter_coeffs
static void code_filter_coeffs(MLPEncodeContext *ctx, FilterParams *fp, int32_t *fcoeff)
Determines the smallest number of bits needed to encode the filter coefficients, and if it's possible...
Definition: mlpenc.c:1356
AVPacket::size
int size
Definition: packet.h:374
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:116
PathCounter::bitcount
int bitcount
Definition: mlpenc.c:1958
InputBitDepth
InputBitDepth
Definition: mlpenc.c:475
FilterParams::coeff_bits
int coeff_bits
Definition: mlp.h:78
ff_truehd_encoder
const AVCodec ff_truehd_encoder
PARAM_IIR
@ PARAM_IIR
Definition: mlpenc.c:78
MLPEncodeContext::last_frame
int32_t * last_frame
Pointer to last frame with data to encode.
Definition: mlpenc.c:132
MAX_LPC_ORDER
#define MAX_LPC_ORDER
Definition: lpc.h:38
PARAM_QUANTSTEP
@ PARAM_QUANTSTEP
Definition: mlpenc.c:76
MLPEncodeContext::max_restart_interval
unsigned int max_restart_interval
Max interval of access units in between two major frames.
Definition: mlpenc.c:150
AVCodecContext::sample_fmt
enum AVSampleFormat sample_fmt
audio sample format
Definition: avcodec.h:996
AV_SAMPLE_FMT_NONE
@ AV_SAMPLE_FMT_NONE
Definition: samplefmt.h:59
sample
#define sample
Definition: flacdsp_template.c:44
MAX_SUBSTREAMS
#define MAX_SUBSTREAMS
Maximum number of substreams that can be decoded.
Definition: mlp.h:46
size
int size
Definition: twinvq_data.h:10344
MLPEncodeContext::write_buffer
int32_t * write_buffer
Pointer to data currently being written to bitstream.
Definition: mlpenc.c:129
parity
mcdeint parity
Definition: vf_mcdeint.c:277
MLPEncodeContext::ch_modifier_thd0
uint8_t ch_modifier_thd0
channel modifier for TrueHD stream 0
Definition: mlpenc.c:159
NUM_FILTERS
#define NUM_FILTERS
number of allowed filters
Definition: mlp.h:59
MLPEncodeContext::cur_decoding_params
DecodingParams * cur_decoding_params
Definition: mlpenc.c:184
FilterParams::order
uint8_t order
number of taps in filter
Definition: mlp.h:73
generate_2_noise_channels
static void generate_2_noise_channels(MLPEncodeContext *ctx)
Generates two noise channels worth of data.
Definition: mlpenc.c:1898
BITS_16
@ BITS_16
Definition: mlpenc.c:476
AV_WL16
#define AV_WL16(p, v)
Definition: intreadwrite.h:412
DecodingParams::quant_step_size
uint8_t quant_step_size[MAX_CHANNELS]
left shift to apply to Huffman-decoded residuals
Definition: mlpenc.c:85
write_access_unit
static unsigned int write_access_unit(MLPEncodeContext *ctx, uint8_t *buf, int buf_size, int restart_frame)
Writes an entire access unit to the bitstream.
Definition: mlpenc.c:1188
AV_CH_LAYOUT_5POINT1_BACK
#define AV_CH_LAYOUT_5POINT1_BACK
Definition: channel_layout.h:103
offset
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf offset
Definition: writing_filters.txt:86
BestOffset::offset
int32_t offset
Definition: mlpenc.c:93
ChannelParams::huff_offset
int16_t huff_offset
Offset to apply to residual values.
Definition: mlp.h:87
BestOffset::min
int32_t min
Definition: mlpenc.c:96
ORDER_METHOD_EST
#define ORDER_METHOD_EST
Definition: lpc.h:30
MAX_CHANNELS
#define MAX_CHANNELS
Definition: aac.h:48
number_trailing_zeroes
static int number_trailing_zeroes(int32_t sample)
Counts the number of trailing zeroes in a value.
Definition: mlpenc.c:1312
input_data
static void input_data(MLPEncodeContext *ctx, void *samples)
Wrapper function for inputting data in two different bit-depths.
Definition: mlpenc.c:1280
AV_CH_LAYOUT_3POINT1
#define AV_CH_LAYOUT_3POINT1
Definition: channel_layout.h:95
ff_lpc_end
av_cold void ff_lpc_end(LPCContext *s)
Uninitialize LPCContext.
Definition: lpc.c:323
AVCodecContext::channels
int channels
number of audio channels
Definition: avcodec.h:989
compare_filter_params
static int compare_filter_params(const ChannelParams *prev_cp, const ChannelParams *cp, int filter)
Compares two FilterParams structures and returns 1 if anything has changed.
Definition: mlpenc.c:234
FLAGS_DVDA
#define FLAGS_DVDA
Definition: mlpenc.c:218
MLPEncodeContext::decoding_params
DecodingParams * decoding_params
Definition: mlpenc.c:171
MLPEncodeContext::restart_intervals
unsigned int restart_intervals
Number of possible major frame sizes.
Definition: mlpenc.c:152
MatrixParams::outch
uint8_t outch[MAX_MATRICES]
output channel for each matrix
Definition: mlpenc.c:62
i
int i
Definition: input.c:406
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:366
put_bits_count
static int put_bits_count(PutBitContext *s)
Definition: put_bits.h:79
MLPEncodeContext::inout_buffer
int32_t * inout_buffer
Pointer to data currently being read from lavc or written to bitstream.
Definition: mlpenc.c:127
AV_CH_LAYOUT_2POINT1
#define AV_CH_LAYOUT_2POINT1
Definition: channel_layout.h:92
PARAM_PRESENT
@ PARAM_PRESENT
Definition: mlpenc.c:80
FF_CODEC_CAP_INIT_CLEANUP
#define FF_CODEC_CAP_INIT_CLEANUP
The codec allows calling the close function for deallocation even if the init function returned a fai...
Definition: internal.h:50
SUBSTREAM_INFO_ALWAYS_SET
#define SUBSTREAM_INFO_ALWAYS_SET
Definition: mlpenc.c:224
restart_decoding_params
static DecodingParams restart_decoding_params[MAX_SUBSTREAMS]
Definition: mlpenc.c:208
av_malloc_array
#define av_malloc_array(a, b)
Definition: tableprint_vlc.h:32
AVSampleFormat
AVSampleFormat
Audio sample formats.
Definition: samplefmt.h:58
AV_CH_LAYOUT_4POINT1
#define AV_CH_LAYOUT_4POINT1
Definition: channel_layout.h:97
MLPEncodeContext::max_codebook_search
unsigned int max_codebook_search
Definition: mlpenc.c:202
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AV_SAMPLE_FMT_S16
@ AV_SAMPLE_FMT_S16
signed 16 bits
Definition: samplefmt.h:61
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:204
ChannelParams
sample data coding information
Definition: mlp.h:83
MAX_BLOCKSIZE
#define MAX_BLOCKSIZE
Definition: diracdec.c:55
PARAM_HUFFOFFSET
@ PARAM_HUFFOFFSET
Definition: mlpenc.c:79
ff_mlp_init_crc
av_cold void ff_mlp_init_crc(void)
Definition: mlp.c:83
MLPEncodeContext::wordlength
int wordlength
Definition: mlpenc.c:123
MAJOR_SYNC_INFO_SIGNATURE
#define MAJOR_SYNC_INFO_SIGNATURE
Definition: mlpenc.c:212
MLPEncodeContext::cur_channel_params
ChannelParams * cur_channel_params
Definition: mlpenc.c:183
avcodec.h
NUM_CODEBOOKS
#define NUM_CODEBOOKS
Number of possible codebooks (counting "no codebooks")
Definition: mlpenc.c:104
RestartHeader::max_huff_lsbs
uint8_t max_huff_lsbs
largest huff_lsbs
Definition: mlpenc.c:55
ret
ret
Definition: filter_design.txt:187
frame
these buffered frames must be flushed immediately if a new input produces new the filter must not call request_frame to get more It must just process the frame or queue it The task of requesting more frames is left to the filter s request_frame method or the application If a filter has several the filter must be ready for frames arriving randomly on any input any filter with several inputs will most likely require some kind of queuing mechanism It is perfectly acceptable to have a limited queue and to drop frames when the inputs are too unbalanced request_frame For filters that do not use the this method is called when a frame is wanted on an output For a it should directly call filter_frame on the corresponding output For a if there are queued frames already one of these frames should be pushed If the filter should request a frame on one of its repeatedly until at least one frame has been pushed Return or at least make progress towards producing a frame
Definition: filter_design.txt:264
RestartHeader::max_matrix_channel
uint8_t max_matrix_channel
The number of channels input into the rematrix stage.
Definition: mlpenc.c:46
AV_CH_LAYOUT_SURROUND
#define AV_CH_LAYOUT_SURROUND
Definition: channel_layout.h:94
ChannelInformation::channel_occupancy
uint8_t channel_occupancy
Definition: mlp.h:101
RestartHeader::noise_shift
uint8_t noise_shift
The left shift applied to random noise in 0x31ea substreams.
Definition: mlpenc.c:48
MatrixParams::coeff
int32_t coeff[MAX_MATRICES][MAX_CHANNELS+2]
decoding coefficients
Definition: mlpenc.c:64
checksum
static volatile int checksum
Definition: adler32.c:30
clear_decoding_params
static void clear_decoding_params(DecodingParams decoding_params[MAX_SUBSTREAMS], int num_substreams)
Clears a DecodingParams struct the way it should be after a restart header.
Definition: mlpenc.c:409
left
Tag MUST be and< 10hcoeff half pel interpolation filter coefficients, hcoeff[0] are the 2 middle coefficients[1] are the next outer ones and so on, resulting in a filter like:...eff[2], hcoeff[1], hcoeff[0], hcoeff[0], hcoeff[1], hcoeff[2] ... the sign of the coefficients is not explicitly stored but alternates after each coeff and coeff[0] is positive, so ...,+,-,+,-,+,+,-,+,-,+,... hcoeff[0] is not explicitly stored but found by subtracting the sum of all stored coefficients with signs from 32 hcoeff[0]=32 - hcoeff[1] - hcoeff[2] - ... a good choice for hcoeff and htaps is htaps=6 hcoeff={40,-10, 2} an alternative which requires more computations at both encoder and decoder side and may or may not be better is htaps=8 hcoeff={42,-14, 6,-2}ref_frames minimum of the number of available reference frames and max_ref_frames for example the first frame after a key frame always has ref_frames=1spatial_decomposition_type wavelet type 0 is a 9/7 symmetric compact integer wavelet 1 is a 5/3 symmetric compact integer wavelet others are reserved stored as delta from last, last is reset to 0 if always_reset||keyframeqlog quality(logarithmic quantizer scale) stored as delta from last, last is reset to 0 if always_reset||keyframemv_scale stored as delta from last, last is reset to 0 if always_reset||keyframe FIXME check that everything works fine if this changes between framesqbias dequantization bias stored as delta from last, last is reset to 0 if always_reset||keyframeblock_max_depth maximum depth of the block tree stored as delta from last, last is reset to 0 if always_reset||keyframequant_table quantization tableHighlevel bitstream structure:==============================--------------------------------------------|Header|--------------------------------------------|------------------------------------|||Block0||||split?||||yes no||||......... intra?||||:Block01 :yes no||||:Block02 :....... ..........||||:Block03 ::y DC ::ref index:||||:Block04 ::cb DC ::motion x :||||......... :cr DC ::motion y :||||....... ..........|||------------------------------------||------------------------------------|||Block1|||...|--------------------------------------------|------------ ------------ ------------|||Y subbands||Cb subbands||Cr subbands||||--- ---||--- ---||--- ---|||||LL0||HL0||||LL0||HL0||||LL0||HL0|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||LH0||HH0||||LH0||HH0||||LH0||HH0|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||HL1||LH1||||HL1||LH1||||HL1||LH1|||||--- ---||--- ---||--- ---||||--- ---||--- ---||--- ---|||||HH1||HL2||||HH1||HL2||||HH1||HL2|||||...||...||...|||------------ ------------ ------------|--------------------------------------------Decoding process:=================------------|||Subbands|------------||||------------|Intra DC||||LL0 subband prediction ------------|\ Dequantization ------------------- \||Reference frames|\ IDWT|------- -------|Motion \|||Frame 0||Frame 1||Compensation . OBMC v -------|------- -------|--------------. \------> Frame n output Frame Frame<----------------------------------/|...|------------------- Range Coder:============Binary Range Coder:------------------- The implemented range coder is an adapted version based upon "Range encoding: an algorithm for removing redundancy from a digitised message." by G. N. N. Martin. The symbols encoded by the Snow range coder are bits(0|1). The associated probabilities are not fix but change depending on the symbol mix seen so far. bit seen|new state ---------+----------------------------------------------- 0|256 - state_transition_table[256 - old_state];1|state_transition_table[old_state];state_transition_table={ 0, 0, 0, 0, 0, 0, 0, 0, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 190, 191, 192, 194, 194, 195, 196, 197, 198, 199, 200, 201, 202, 202, 204, 205, 206, 207, 208, 209, 209, 210, 211, 212, 213, 215, 215, 216, 217, 218, 219, 220, 220, 222, 223, 224, 225, 226, 227, 227, 229, 229, 230, 231, 232, 234, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 248, 0, 0, 0, 0, 0, 0, 0};FIXME Range Coding of integers:------------------------- FIXME Neighboring Blocks:===================left and top are set to the respective blocks unless they are outside of the image in which case they are set to the Null block top-left is set to the top left block unless it is outside of the image in which case it is set to the left block if this block has no larger parent block or it is at the left side of its parent block and the top right block is not outside of the image then the top right block is used for top-right else the top-left block is used Null block y, cb, cr are 128 level, ref, mx and my are 0 Motion Vector Prediction:=========================1. the motion vectors of all the neighboring blocks are scaled to compensate for the difference of reference frames scaled_mv=(mv *(256 *(current_reference+1)/(mv.reference+1))+128)> the median of the scaled left
Definition: snow.txt:386
best_codebook_path_cost
static int best_codebook_path_cost(MLPEncodeContext *ctx, unsigned int channel, PathCounter *src, int cur_codebook)
Definition: mlpenc.c:1974
no_codebook_bits_offset
static void no_codebook_bits_offset(MLPEncodeContext *ctx, unsigned int channel, int16_t offset, int32_t min, int32_t max, BestOffset *bo)
Determines the amount of bits needed to encode the samples using no codebooks and a specified offset.
Definition: mlpenc.c:1564
compare_decoding_params
static int compare_decoding_params(MLPEncodeContext *ctx)
Compares two DecodingParams and ChannelParams structures to decide if a new decoding params header ha...
Definition: mlpenc.c:289
determine_quant_step_size
static void determine_quant_step_size(MLPEncodeContext *ctx)
Determines how many bits are zero at the end of all samples so they can be shifted out.
Definition: mlpenc.c:1329
compare_best_offset
static int compare_best_offset(const BestOffset *prev, const BestOffset *cur)
Definition: mlpenc.c:1966
AVCodecContext
main external API structure.
Definition: avcodec.h:379
PARAM_FIR
@ PARAM_FIR
Definition: mlpenc.c:77
HUFF_OFFSET_MAX
#define HUFF_OFFSET_MAX
Definition: mlpenc.c:101
frame_header
Definition: truemotion1.c:87
channel_layout.h
write_filter_params
static void write_filter_params(MLPEncodeContext *ctx, PutBitContext *pb, unsigned int channel, unsigned int filter)
Writes filter parameters for one filter to the bitstream.
Definition: mlpenc.c:881
mode
mode
Definition: ebur128.h:83
clear_channel_params
static void clear_channel_params(ChannelParams channel_params[MAX_CHANNELS], int nb_channels)
Clears a ChannelParams struct the way it should be after a restart header.
Definition: mlpenc.c:423
MLPEncodeContext::major_inout_buffer
int32_t * major_inout_buffer
Buffer with all in/out data for one entire major frame interval.
Definition: mlpenc.c:128
input_data_internal
static void input_data_internal(MLPEncodeContext *ctx, const uint8_t *samples, int is24)
Inputs data from the samples passed by lavc into the context, shifts them appropriately depending on ...
Definition: mlpenc.c:1236
MLPEncodeContext::channel_params
ChannelParams * channel_params
Definition: mlpenc.c:167
MLPEncodeContext::next_major_number_of_frames
unsigned int next_major_number_of_frames
Definition: mlpenc.c:137
DecodingParams::matrix_params
MatrixParams matrix_params
Definition: mlpenc.c:87
analyze_sample_buffer
static void analyze_sample_buffer(MLPEncodeContext *ctx)
Definition: mlpenc.c:2138
HUFF_OFFSET_MIN
#define HUFF_OFFSET_MIN
Definition: mlpenc.c:100
samples
Filter the word “frame” indicates either a video frame or a group of audio samples
Definition: filter_design.txt:8
SAMPLE_MIN
#define SAMPLE_MIN(bitdepth)
Definition: mlpenc.c:1800
IIR
#define IIR
Definition: mlp.h:69
RestartHeader::noisegen_seed
uint32_t noisegen_seed
The current seed value for the pseudorandom noise generator(s).
Definition: mlpenc.c:49
PARAM_BLOCKSIZE
@ PARAM_BLOCKSIZE
Definition: mlpenc.c:73
MLPEncodeContext::one_sample_buffer_size
unsigned int one_sample_buffer_size
Number of samples*channel for one access unit.
Definition: mlpenc.c:148
codebook_bits_offset
static void codebook_bits_offset(MLPEncodeContext *ctx, unsigned int channel, int codebook, int32_t sample_min, int32_t sample_max, int16_t offset, BestOffset *bo)
Determines the least amount of bits needed to encode the samples using a given codebook and a given o...
Definition: mlpenc.c:1633
shift
static int shift(int a, int b)
Definition: sonic.c:83
RestartHeader::data_check_present
int data_check_present
Set if the substream contains extra info to check the size of VLC blocks.
Definition: mlpenc.c:51
MLPEncodeContext::seq_index
unsigned int seq_index
Sequence index for high compression levels.
Definition: mlpenc.c:194
MLPEncodeContext::frame_index
unsigned int frame_index
Index of current frame being encoded.
Definition: mlpenc.c:146
process_major_frame
static void process_major_frame(MLPEncodeContext *ctx)
Definition: mlpenc.c:2186
DecodingParams
Definition: mlpenc.c:83
AVCodecContext::frame_number
int frame_number
Frame counter, set by libavcodec.
Definition: avcodec.h:1019
MLPEncodeContext::prev_decoding_params
const DecodingParams * prev_decoding_params
Definition: mlpenc.c:197
RestartHeader::max_channel
uint8_t max_channel
The index of the last channel coded in this substream.
Definition: mlpenc.c:45
flush_put_bits
static void flush_put_bits(PutBitContext *s)
Pad the end of the output stream with zeros.
Definition: put_bits.h:142
MSB_MASK
#define MSB_MASK(bits)
Definition: mlpenc.c:1802
mlp.h
diff
static av_always_inline int diff(const uint32_t a, const uint32_t b)
Definition: vf_palettegen.c:136
ff_mlp_huffman_tables
const uint8_t ff_mlp_huffman_tables[3][18][2]
Tables defining the Huffman codes.
Definition: mlp.c:30
mlp_encode_init
static av_cold int mlp_encode_init(AVCodecContext *avctx)
Definition: mlpenc.c:493
MLP_CHMODE_LEFT_SIDE
@ MLP_CHMODE_LEFT_SIDE
Definition: mlpenc.c:1447
AVPacket
This structure stores compressed data.
Definition: packet.h:350
AVCodecContext::priv_data
void * priv_data
Definition: avcodec.h:406
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:35
PathCounter
Definition: mlpenc.c:1953
MLPEncodeContext::seq_decoding_params
DecodingParams * seq_decoding_params
Definition: mlpenc.c:200
AV_CH_LAYOUT_4POINT0
#define AV_CH_LAYOUT_4POINT0
Definition: channel_layout.h:96
int32_t
int32_t
Definition: audioconvert.c:56
CODEBOOK_CHANGE_BITS
#define CODEBOOK_CHANGE_BITS
Definition: mlpenc.c:1959
coeff
static const double coeff[2][5]
Definition: vf_owdenoise.c:73
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:28
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
write_matrix_params
static void write_matrix_params(MLPEncodeContext *ctx, PutBitContext *pb)
Writes matrix params for all primitive matrices to the bitstream.
Definition: mlpenc.c:849
PathCounter::cur_idx
int cur_idx
Definition: mlpenc.c:1957
MLP_MIN_LPC_SHIFT
#define MLP_MIN_LPC_SHIFT
Definition: mlpenc.c:40
avstring.h
MatrixParams::count
uint8_t count
number of matrices to apply
Definition: mlpenc.c:60
AV_CODEC_CAP_SMALL_LAST_FRAME
#define AV_CODEC_CAP_SMALL_LAST_FRAME
Codec can be fed a final frame with a smaller size.
Definition: codec.h:82
int
int
Definition: ffmpeg_filter.c:156
put_bits.h
determine_filters
static void determine_filters(MLPEncodeContext *ctx)
Tries to determine a good prediction filter, and applies it to the samples buffer if the filter is go...
Definition: mlpenc.c:1434
FilterParams::shift
uint8_t shift
Right shift to apply to output of filter.
Definition: mlp.h:74
AV_SAMPLE_FMT_S32
@ AV_SAMPLE_FMT_S32
signed 32 bits
Definition: samplefmt.h:62
MLP_MAX_LPC_SHIFT
#define MLP_MAX_LPC_SHIFT
Definition: mlpenc.c:41
av_log2
int av_log2(unsigned v)
Definition: intmath.c:26
ff_alloc_packet
int ff_alloc_packet(AVCodecContext *avctx, AVPacket *avpkt, int64_t size)
Check AVPacket size and allocate data.
Definition: encode.c:34
FF_LPC_TYPE_LEVINSON
@ FF_LPC_TYPE_LEVINSON
Levinson-Durbin recursion.
Definition: lpc.h:47
DecodingParams::param_presence_flags
uint8_t param_presence_flags
Bitmask of which parameter sets are conveyed in a decoding parameter block.
Definition: mlpenc.c:89
MLP_CHMODE_RIGHT_SIDE
@ MLP_CHMODE_RIGHT_SIDE
Definition: mlpenc.c:1448
channel
channel
Definition: ebur128.h:39
RestartHeader
Definition: mlpenc.c:43
MAJOR_HEADER_INTERVAL
#define MAJOR_HEADER_INTERVAL
MLP encoder Copyright (c) 2008 Ramiro Polla Copyright (c) 2016-2019 Jai Luthra.
Definition: mlpenc.c:36
codebook
static const unsigned codebook[256][2]
Definition: cfhdenc.c:42
AV_CODEC_ID_MLP
@ AV_CODEC_ID_MLP
Definition: codec_id.h:451
ff_lpc_init
av_cold int ff_lpc_init(LPCContext *s, int blocksize, int max_order, enum FFLPCType lpc_type)
Initialize LPCContext.
Definition: lpc.c:301
write_restart_header
static void write_restart_header(MLPEncodeContext *ctx, PutBitContext *pb)
Writes a restart header to the bitstream.
Definition: mlpenc.c:812
min
float min
Definition: vorbis_enc_data.h:429
nb_channels
int nb_channels
Definition: channel_layout.c:81
copy_restart_frame_params
static void copy_restart_frame_params(MLPEncodeContext *ctx, unsigned int substr)
Definition: mlpenc.c:383
MLPEncodeContext::channel_occupancy
int channel_occupancy
Definition: mlpenc.c:124