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