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