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