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