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