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