]> git.sesse.net Git - ffmpeg/blob - libavcodec/dca_xll.c
avcodec/dvaudiodec: now that we got samples, fix 12bit case
[ffmpeg] / libavcodec / dca_xll.c
1 /*
2  * Copyright (C) 2016 foo86
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 #include "dcadec.h"
22 #include "dcadata.h"
23 #include "dcamath.h"
24 #include "dca_syncwords.h"
25 #include "unary.h"
26
27 static int get_linear(GetBitContext *gb, int n)
28 {
29     unsigned int v = get_bits_long(gb, n);
30     return (v >> 1) ^ -(v & 1);
31 }
32
33 static int get_rice_un(GetBitContext *gb, int k)
34 {
35     unsigned int v = get_unary(gb, 1, 128);
36     return (v << k) | get_bits_long(gb, k);
37 }
38
39 static int get_rice(GetBitContext *gb, int k)
40 {
41     unsigned int v = get_rice_un(gb, k);
42     return (v >> 1) ^ -(v & 1);
43 }
44
45 static void get_array(GetBitContext *gb, int32_t *array, int size, int n)
46 {
47     int i;
48
49     for (i = 0; i < size; i++)
50         array[i] = get_bits(gb, n);
51 }
52
53 static void get_linear_array(GetBitContext *gb, int32_t *array, int size, int n)
54 {
55     int i;
56
57     if (n == 0)
58         memset(array, 0, sizeof(*array) * size);
59     else for (i = 0; i < size; i++)
60         array[i] = get_linear(gb, n);
61 }
62
63 static void get_rice_array(GetBitContext *gb, int32_t *array, int size, int k)
64 {
65     int i;
66
67     for (i = 0; i < size; i++)
68         array[i] = get_rice(gb, k);
69 }
70
71 static int parse_dmix_coeffs(DCAXllDecoder *s, DCAXllChSet *c)
72 {
73     // Size of downmix coefficient matrix
74     int m = c->primary_chset ? ff_dca_dmix_primary_nch[c->dmix_type] : c->hier_ofs;
75     int i, j, *coeff_ptr = c->dmix_coeff;
76
77     for (i = 0; i < m; i++) {
78         int code, sign, coeff, scale, scale_inv = 0;
79         unsigned int index;
80
81         // Downmix scale (only for non-primary channel sets)
82         if (!c->primary_chset) {
83             code = get_bits(&s->gb, 9);
84             sign = (code >> 8) - 1;
85             index = (code & 0xff) - FF_DCA_DMIXTABLE_OFFSET;
86             if (index >= FF_DCA_INV_DMIXTABLE_SIZE) {
87                 av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL downmix scale index\n");
88                 return AVERROR_INVALIDDATA;
89             }
90             scale = ff_dca_dmixtable[index + FF_DCA_DMIXTABLE_OFFSET];
91             scale_inv = ff_dca_inv_dmixtable[index];
92             c->dmix_scale[i] = (scale ^ sign) - sign;
93             c->dmix_scale_inv[i] = (scale_inv ^ sign) - sign;
94         }
95
96         // Downmix coefficients
97         for (j = 0; j < c->nchannels; j++) {
98             code = get_bits(&s->gb, 9);
99             sign = (code >> 8) - 1;
100             index = code & 0xff;
101             if (index >= FF_DCA_DMIXTABLE_SIZE) {
102                 av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL downmix coefficient index\n");
103                 return AVERROR_INVALIDDATA;
104             }
105             coeff = ff_dca_dmixtable[index];
106             if (!c->primary_chset)
107                 // Multiply by |InvDmixScale| to get |UndoDmixScale|
108                 coeff = mul16(scale_inv, coeff);
109             *coeff_ptr++ = (coeff ^ sign) - sign;
110         }
111     }
112
113     return 0;
114 }
115
116 static int chs_parse_header(DCAXllDecoder *s, DCAXllChSet *c, DCAExssAsset *asset)
117 {
118     int i, j, k, ret, band, header_size, header_pos = get_bits_count(&s->gb);
119     DCAXllChSet *p = &s->chset[0];
120     DCAXllBand *b;
121
122     // Size of channel set sub-header
123     header_size = get_bits(&s->gb, 10) + 1;
124
125     // Check CRC
126     if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
127         && ff_dca_check_crc(&s->gb, header_pos, header_pos + header_size * 8)) {
128         av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL sub-header checksum\n");
129         return AVERROR_INVALIDDATA;
130     }
131
132     // Number of channels in the channel set
133     c->nchannels = get_bits(&s->gb, 4) + 1;
134     if (c->nchannels > DCA_XLL_CHANNELS_MAX) {
135         avpriv_request_sample(s->avctx, "%d XLL channels", c->nchannels);
136         return AVERROR_PATCHWELCOME;
137     }
138
139     // Residual type
140     c->residual_encode = get_bits(&s->gb, c->nchannels);
141
142     // PCM bit resolution
143     c->pcm_bit_res = get_bits(&s->gb, 5) + 1;
144
145     // Storage unit width
146     c->storage_bit_res = get_bits(&s->gb, 5) + 1;
147     if (c->storage_bit_res != 16 && c->storage_bit_res != 24) {
148         avpriv_request_sample(s->avctx, "%d-bit XLL storage resolution", c->storage_bit_res);
149         return AVERROR_PATCHWELCOME;
150     }
151
152     if (c->pcm_bit_res > c->storage_bit_res) {
153         av_log(s->avctx, AV_LOG_ERROR, "Invalid PCM bit resolution for XLL channel set (%d > %d)\n", c->pcm_bit_res, c->storage_bit_res);
154         return AVERROR_INVALIDDATA;
155     }
156
157     // Original sampling frequency
158     c->freq = ff_dca_sampling_freqs[get_bits(&s->gb, 4)];
159     if (c->freq > 192000) {
160         avpriv_request_sample(s->avctx, "%d Hz XLL sampling frequency", c->freq);
161         return AVERROR_PATCHWELCOME;
162     }
163
164     // Sampling frequency modifier
165     if (get_bits(&s->gb, 2)) {
166         avpriv_request_sample(s->avctx, "XLL sampling frequency modifier");
167         return AVERROR_PATCHWELCOME;
168     }
169
170     // Which replacement set this channel set is member of
171     if (get_bits(&s->gb, 2)) {
172         avpriv_request_sample(s->avctx, "XLL replacement set");
173         return AVERROR_PATCHWELCOME;
174     }
175
176     if (asset->one_to_one_map_ch_to_spkr) {
177         // Primary channel set flag
178         c->primary_chset = get_bits1(&s->gb);
179         if (c->primary_chset != (c == p)) {
180             av_log(s->avctx, AV_LOG_ERROR, "The first (and only) XLL channel set must be primary\n");
181             return AVERROR_INVALIDDATA;
182         }
183
184         // Downmix coefficients present in stream
185         c->dmix_coeffs_present = get_bits1(&s->gb);
186
187         // Downmix already performed by encoder
188         c->dmix_embedded = c->dmix_coeffs_present && get_bits1(&s->gb);
189
190         // Downmix type
191         if (c->dmix_coeffs_present && c->primary_chset) {
192             c->dmix_type = get_bits(&s->gb, 3);
193             if (c->dmix_type >= DCA_DMIX_TYPE_COUNT) {
194                 av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL primary channel set downmix type\n");
195                 return AVERROR_INVALIDDATA;
196             }
197         }
198
199         // Whether the channel set is part of a hierarchy
200         c->hier_chset = get_bits1(&s->gb);
201         if (!c->hier_chset && s->nchsets != 1) {
202             avpriv_request_sample(s->avctx, "XLL channel set outside of hierarchy");
203             return AVERROR_PATCHWELCOME;
204         }
205
206         // Downmix coefficients
207         if (c->dmix_coeffs_present && (ret = parse_dmix_coeffs(s, c)) < 0)
208             return ret;
209
210         // Channel mask enabled
211         if (!get_bits1(&s->gb)) {
212             avpriv_request_sample(s->avctx, "Disabled XLL channel mask");
213             return AVERROR_PATCHWELCOME;
214         }
215
216         // Channel mask for set
217         c->ch_mask = get_bits_long(&s->gb, s->ch_mask_nbits);
218         if (av_popcount(c->ch_mask) != c->nchannels) {
219             av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL channel mask\n");
220             return AVERROR_INVALIDDATA;
221         }
222
223         // Build the channel to speaker map
224         for (i = 0, j = 0; i < s->ch_mask_nbits; i++)
225             if (c->ch_mask & (1U << i))
226                 c->ch_remap[j++] = i;
227     } else {
228         // Mapping coeffs present flag
229         if (c->nchannels != 2 || s->nchsets != 1 || get_bits1(&s->gb)) {
230             avpriv_request_sample(s->avctx, "Custom XLL channel to speaker mapping");
231             return AVERROR_PATCHWELCOME;
232         }
233
234         // Setup for LtRt decoding
235         c->primary_chset = 1;
236         c->dmix_coeffs_present = 0;
237         c->dmix_embedded = 0;
238         c->hier_chset = 0;
239         c->ch_mask = DCA_SPEAKER_LAYOUT_STEREO;
240         c->ch_remap[0] = DCA_SPEAKER_L;
241         c->ch_remap[1] = DCA_SPEAKER_R;
242     }
243
244     if (c->freq > 96000) {
245         // Extra frequency bands flag
246         if (get_bits1(&s->gb)) {
247             avpriv_request_sample(s->avctx, "Extra XLL frequency bands");
248             return AVERROR_PATCHWELCOME;
249         }
250         c->nfreqbands = 2;
251     } else {
252         c->nfreqbands = 1;
253     }
254
255     // Set the sampling frequency to that of the first frequency band.
256     // Frequency will be doubled again after bands assembly.
257     c->freq >>= c->nfreqbands - 1;
258
259     // Verify that all channel sets have the same audio characteristics
260     if (c != p && (c->nfreqbands != p->nfreqbands || c->freq != p->freq
261                    || c->pcm_bit_res != p->pcm_bit_res
262                    || c->storage_bit_res != p->storage_bit_res)) {
263         avpriv_request_sample(s->avctx, "Different XLL audio characteristics");
264         return AVERROR_PATCHWELCOME;
265     }
266
267     // Determine number of bits to read bit allocation coding parameter
268     if (c->storage_bit_res > 16)
269         c->nabits = 5;
270     else if (c->storage_bit_res > 8)
271         c->nabits = 4;
272     else
273         c->nabits = 3;
274
275     // Account for embedded downmix and decimator saturation
276     if ((s->nchsets > 1 || c->nfreqbands > 1) && c->nabits < 5)
277         c->nabits++;
278
279     for (band = 0, b = c->bands; band < c->nfreqbands; band++, b++) {
280         // Pairwise channel decorrelation
281         if ((b->decor_enabled = get_bits1(&s->gb)) && c->nchannels > 1) {
282             int ch_nbits = av_ceil_log2(c->nchannels);
283
284             // Original channel order
285             for (i = 0; i < c->nchannels; i++) {
286                 b->orig_order[i] = get_bits(&s->gb, ch_nbits);
287                 if (b->orig_order[i] >= c->nchannels) {
288                     av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL original channel order\n");
289                     return AVERROR_INVALIDDATA;
290                 }
291             }
292
293             // Pairwise channel coefficients
294             for (i = 0; i < c->nchannels / 2; i++)
295                 b->decor_coeff[i] = get_bits1(&s->gb) ? get_linear(&s->gb, 7) : 0;
296         } else {
297             for (i = 0; i < c->nchannels; i++)
298                 b->orig_order[i] = i;
299             for (i = 0; i < c->nchannels / 2; i++)
300                 b->decor_coeff[i] = 0;
301         }
302
303         // Adaptive predictor order
304         b->highest_pred_order = 0;
305         for (i = 0; i < c->nchannels; i++) {
306             b->adapt_pred_order[i] = get_bits(&s->gb, 4);
307             if (b->adapt_pred_order[i] > b->highest_pred_order)
308                 b->highest_pred_order = b->adapt_pred_order[i];
309         }
310         if (b->highest_pred_order > s->nsegsamples) {
311             av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL adaptive predicition order\n");
312             return AVERROR_INVALIDDATA;
313         }
314
315         // Fixed predictor order
316         for (i = 0; i < c->nchannels; i++)
317             b->fixed_pred_order[i] = b->adapt_pred_order[i] ? 0 : get_bits(&s->gb, 2);
318
319         // Adaptive predictor quantized reflection coefficients
320         for (i = 0; i < c->nchannels; i++) {
321             for (j = 0; j < b->adapt_pred_order[i]; j++) {
322                 k = get_linear(&s->gb, 8);
323                 if (k == -128) {
324                     av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL reflection coefficient index\n");
325                     return AVERROR_INVALIDDATA;
326                 }
327                 if (k < 0)
328                     b->adapt_refl_coeff[i][j] = -(int)ff_dca_xll_refl_coeff[-k];
329                 else
330                     b->adapt_refl_coeff[i][j] =  (int)ff_dca_xll_refl_coeff[ k];
331             }
332         }
333
334         // Downmix performed by encoder in extension frequency band
335         b->dmix_embedded = c->dmix_embedded && (band == 0 || get_bits1(&s->gb));
336
337         // MSB/LSB split flag in extension frequency band
338         if ((band == 0 && s->scalable_lsbs) || (band != 0 && get_bits1(&s->gb))) {
339             // Size of LSB section in any segment
340             b->lsb_section_size = get_bits_long(&s->gb, s->seg_size_nbits);
341             if (b->lsb_section_size < 0 || b->lsb_section_size > s->frame_size) {
342                 av_log(s->avctx, AV_LOG_ERROR, "Invalid LSB section size\n");
343                 return AVERROR_INVALIDDATA;
344             }
345
346             // Account for optional CRC bytes after LSB section
347             if (b->lsb_section_size && (s->band_crc_present > 2 ||
348                                         (band == 0 && s->band_crc_present > 1)))
349                 b->lsb_section_size += 2;
350
351             // Number of bits to represent the samples in LSB part
352             for (i = 0; i < c->nchannels; i++) {
353                 b->nscalablelsbs[i] = get_bits(&s->gb, 4);
354                 if (b->nscalablelsbs[i] && !b->lsb_section_size) {
355                     av_log(s->avctx, AV_LOG_ERROR, "LSB section missing with non-zero LSB width\n");
356                     return AVERROR_INVALIDDATA;
357                 }
358             }
359         } else {
360             b->lsb_section_size = 0;
361             for (i = 0; i < c->nchannels; i++)
362                 b->nscalablelsbs[i] = 0;
363         }
364
365         // Scalable resolution flag in extension frequency band
366         if ((band == 0 && s->scalable_lsbs) || (band != 0 && get_bits1(&s->gb))) {
367             // Number of bits discarded by authoring
368             for (i = 0; i < c->nchannels; i++)
369                 b->bit_width_adjust[i] = get_bits(&s->gb, 4);
370         } else {
371             for (i = 0; i < c->nchannels; i++)
372                 b->bit_width_adjust[i] = 0;
373         }
374     }
375
376     // Reserved
377     // Byte align
378     // CRC16 of channel set sub-header
379     if (ff_dca_seek_bits(&s->gb, header_pos + header_size * 8)) {
380         av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL sub-header\n");
381         return AVERROR_INVALIDDATA;
382     }
383
384     return 0;
385 }
386
387 static int chs_alloc_msb_band_data(DCAXllDecoder *s, DCAXllChSet *c)
388 {
389     int ndecisamples = c->nfreqbands > 1 ? DCA_XLL_DECI_HISTORY_MAX : 0;
390     int nchsamples = s->nframesamples + ndecisamples;
391     int i, j, nsamples = nchsamples * c->nchannels * c->nfreqbands;
392     int32_t *ptr;
393
394     // Reallocate MSB sample buffer
395     av_fast_malloc(&c->sample_buffer[0], &c->sample_size[0], nsamples * sizeof(int32_t));
396     if (!c->sample_buffer[0])
397         return AVERROR(ENOMEM);
398
399     ptr = c->sample_buffer[0] + ndecisamples;
400     for (i = 0; i < c->nfreqbands; i++) {
401         for (j = 0; j < c->nchannels; j++) {
402             c->bands[i].msb_sample_buffer[j] = ptr;
403             ptr += nchsamples;
404         }
405     }
406
407     return 0;
408 }
409
410 static int chs_alloc_lsb_band_data(DCAXllDecoder *s, DCAXllChSet *c)
411 {
412     int i, j, nsamples = 0;
413     int32_t *ptr;
414
415     // Determine number of frequency bands that have MSB/LSB split
416     for (i = 0; i < c->nfreqbands; i++)
417         if (c->bands[i].lsb_section_size)
418             nsamples += s->nframesamples * c->nchannels;
419     if (!nsamples)
420         return 0;
421
422     // Reallocate LSB sample buffer
423     av_fast_malloc(&c->sample_buffer[1], &c->sample_size[1], nsamples * sizeof(int32_t));
424     if (!c->sample_buffer[1])
425         return AVERROR(ENOMEM);
426
427     ptr = c->sample_buffer[1];
428     for (i = 0; i < c->nfreqbands; i++) {
429         if (c->bands[i].lsb_section_size) {
430             for (j = 0; j < c->nchannels; j++) {
431                 c->bands[i].lsb_sample_buffer[j] = ptr;
432                 ptr += s->nframesamples;
433             }
434         } else {
435             for (j = 0; j < c->nchannels; j++)
436                 c->bands[i].lsb_sample_buffer[j] = NULL;
437         }
438     }
439
440     return 0;
441 }
442
443 static int chs_parse_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band, int seg, int band_data_end)
444 {
445     DCAXllBand *b = &c->bands[band];
446     int i, j, k;
447
448     // Start unpacking MSB portion of the segment
449     if (!(seg && get_bits1(&s->gb))) {
450         // Unpack segment type
451         // 0 - distinct coding parameters for each channel
452         // 1 - common coding parameters for all channels
453         c->seg_common = get_bits1(&s->gb);
454
455         // Determine number of coding parameters encoded in segment
456         k = c->seg_common ? 1 : c->nchannels;
457
458         // Unpack Rice coding parameters
459         for (i = 0; i < k; i++) {
460             // Unpack Rice coding flag
461             // 0 - linear code, 1 - Rice code
462             c->rice_code_flag[i] = get_bits1(&s->gb);
463             // Unpack Hybrid Rice coding flag
464             // 0 - Rice code, 1 - Hybrid Rice code
465             if (!c->seg_common && c->rice_code_flag[i] && get_bits1(&s->gb))
466                 // Unpack binary code length for isolated samples
467                 c->bitalloc_hybrid_linear[i] = get_bits(&s->gb, c->nabits) + 1;
468             else
469                 // 0 indicates no Hybrid Rice coding
470                 c->bitalloc_hybrid_linear[i] = 0;
471         }
472
473         // Unpack coding parameters
474         for (i = 0; i < k; i++) {
475             if (seg == 0) {
476                 // Unpack coding parameter for part A of segment 0
477                 c->bitalloc_part_a[i] = get_bits(&s->gb, c->nabits);
478
479                 // Adjust for the linear code
480                 if (!c->rice_code_flag[i] && c->bitalloc_part_a[i])
481                     c->bitalloc_part_a[i]++;
482
483                 if (!c->seg_common)
484                     c->nsamples_part_a[i] = b->adapt_pred_order[i];
485                 else
486                     c->nsamples_part_a[i] = b->highest_pred_order;
487             } else {
488                 c->bitalloc_part_a[i] = 0;
489                 c->nsamples_part_a[i] = 0;
490             }
491
492             // Unpack coding parameter for part B of segment
493             c->bitalloc_part_b[i] = get_bits(&s->gb, c->nabits);
494
495             // Adjust for the linear code
496             if (!c->rice_code_flag[i] && c->bitalloc_part_b[i])
497                 c->bitalloc_part_b[i]++;
498         }
499     }
500
501     // Unpack entropy codes
502     for (i = 0; i < c->nchannels; i++) {
503         int32_t *part_a, *part_b;
504         int nsamples_part_b;
505
506         // Select index of coding parameters
507         k = c->seg_common ? 0 : i;
508
509         // Slice the segment into parts A and B
510         part_a = b->msb_sample_buffer[i] + seg * s->nsegsamples;
511         part_b = part_a + c->nsamples_part_a[k];
512         nsamples_part_b = s->nsegsamples - c->nsamples_part_a[k];
513
514         if (get_bits_left(&s->gb) < 0)
515             return AVERROR_INVALIDDATA;
516
517         if (!c->rice_code_flag[k]) {
518             // Linear codes
519             // Unpack all residuals of part A of segment 0
520             get_linear_array(&s->gb, part_a, c->nsamples_part_a[k],
521                              c->bitalloc_part_a[k]);
522
523             // Unpack all residuals of part B of segment 0 and others
524             get_linear_array(&s->gb, part_b, nsamples_part_b,
525                              c->bitalloc_part_b[k]);
526         } else {
527             // Rice codes
528             // Unpack all residuals of part A of segment 0
529             get_rice_array(&s->gb, part_a, c->nsamples_part_a[k],
530                            c->bitalloc_part_a[k]);
531
532             if (c->bitalloc_hybrid_linear[k]) {
533                 // Hybrid Rice codes
534                 // Unpack the number of isolated samples
535                 int nisosamples = get_bits(&s->gb, s->nsegsamples_log2);
536
537                 // Set all locations to 0
538                 memset(part_b, 0, sizeof(*part_b) * nsamples_part_b);
539
540                 // Extract the locations of isolated samples and flag by -1
541                 for (j = 0; j < nisosamples; j++) {
542                     int loc = get_bits(&s->gb, s->nsegsamples_log2);
543                     if (loc >= nsamples_part_b) {
544                         av_log(s->avctx, AV_LOG_ERROR, "Invalid isolated sample location\n");
545                         return AVERROR_INVALIDDATA;
546                     }
547                     part_b[loc] = -1;
548                 }
549
550                 // Unpack all residuals of part B of segment 0 and others
551                 for (j = 0; j < nsamples_part_b; j++) {
552                     if (part_b[j])
553                         part_b[j] = get_linear(&s->gb, c->bitalloc_hybrid_linear[k]);
554                     else
555                         part_b[j] = get_rice(&s->gb, c->bitalloc_part_b[k]);
556                 }
557             } else {
558                 // Rice codes
559                 // Unpack all residuals of part B of segment 0 and others
560                 get_rice_array(&s->gb, part_b, nsamples_part_b, c->bitalloc_part_b[k]);
561             }
562         }
563     }
564
565     // Unpack decimator history for frequency band 1
566     if (seg == 0 && band == 1) {
567         int nbits = get_bits(&s->gb, 5) + 1;
568         for (i = 0; i < c->nchannels; i++)
569             for (j = 1; j < DCA_XLL_DECI_HISTORY_MAX; j++)
570                 c->deci_history[i][j] = get_sbits_long(&s->gb, nbits);
571     }
572
573     // Start unpacking LSB portion of the segment
574     if (b->lsb_section_size) {
575         // Skip to the start of LSB portion
576         if (ff_dca_seek_bits(&s->gb, band_data_end - b->lsb_section_size * 8)) {
577             av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL band data\n");
578             return AVERROR_INVALIDDATA;
579         }
580
581         // Unpack all LSB parts of residuals of this segment
582         for (i = 0; i < c->nchannels; i++) {
583             if (b->nscalablelsbs[i]) {
584                 get_array(&s->gb,
585                           b->lsb_sample_buffer[i] + seg * s->nsegsamples,
586                           s->nsegsamples, b->nscalablelsbs[i]);
587             }
588         }
589     }
590
591     // Skip to the end of band data
592     if (ff_dca_seek_bits(&s->gb, band_data_end)) {
593         av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL band data\n");
594         return AVERROR_INVALIDDATA;
595     }
596
597     return 0;
598 }
599
600 static av_cold void chs_clear_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band, int seg)
601 {
602     DCAXllBand *b = &c->bands[band];
603     int i, offset, nsamples;
604
605     if (seg < 0) {
606         offset = 0;
607         nsamples = s->nframesamples;
608     } else {
609         offset = seg * s->nsegsamples;
610         nsamples = s->nsegsamples;
611     }
612
613     for (i = 0; i < c->nchannels; i++) {
614         memset(b->msb_sample_buffer[i] + offset, 0, nsamples * sizeof(int32_t));
615         if (b->lsb_section_size)
616             memset(b->lsb_sample_buffer[i] + offset, 0, nsamples * sizeof(int32_t));
617     }
618
619     if (seg <= 0 && band)
620         memset(c->deci_history, 0, sizeof(c->deci_history));
621
622     if (seg < 0) {
623         memset(b->nscalablelsbs, 0, sizeof(b->nscalablelsbs));
624         memset(b->bit_width_adjust, 0, sizeof(b->bit_width_adjust));
625     }
626 }
627
628 static void chs_filter_band_data(DCAXllDecoder *s, DCAXllChSet *c, int band)
629 {
630     DCAXllBand *b = &c->bands[band];
631     int nsamples = s->nframesamples;
632     int i, j, k;
633
634     // Inverse adaptive or fixed prediction
635     for (i = 0; i < c->nchannels; i++) {
636         int32_t *buf = b->msb_sample_buffer[i];
637         int order = b->adapt_pred_order[i];
638         if (order > 0) {
639             int coeff[DCA_XLL_ADAPT_PRED_ORDER_MAX];
640             // Conversion from reflection coefficients to direct form coefficients
641             for (j = 0; j < order; j++) {
642                 int rc = b->adapt_refl_coeff[i][j];
643                 for (k = 0; k < (j + 1) / 2; k++) {
644                     int tmp1 = coeff[    k    ];
645                     int tmp2 = coeff[j - k - 1];
646                     coeff[    k    ] = tmp1 + mul16(rc, tmp2);
647                     coeff[j - k - 1] = tmp2 + mul16(rc, tmp1);
648                 }
649                 coeff[j] = rc;
650             }
651             // Inverse adaptive prediction
652             for (j = 0; j < nsamples - order; j++) {
653                 int64_t err = 0;
654                 for (k = 0; k < order; k++)
655                     err += (int64_t)buf[j + k] * coeff[order - k - 1];
656                 buf[j + k] -= clip23(norm16(err));
657             }
658         } else {
659             // Inverse fixed coefficient prediction
660             for (j = 0; j < b->fixed_pred_order[i]; j++)
661                 for (k = 1; k < nsamples; k++)
662                     buf[k] += buf[k - 1];
663         }
664     }
665
666     // Inverse pairwise channel decorrellation
667     if (b->decor_enabled) {
668         int32_t *tmp[DCA_XLL_CHANNELS_MAX];
669
670         for (i = 0; i < c->nchannels / 2; i++) {
671             int coeff = b->decor_coeff[i];
672             if (coeff) {
673                 s->dcadsp->decor(b->msb_sample_buffer[i * 2 + 1],
674                                  b->msb_sample_buffer[i * 2    ],
675                                  coeff, nsamples);
676             }
677         }
678
679         // Reorder channel pointers to the original order
680         for (i = 0; i < c->nchannels; i++)
681             tmp[i] = b->msb_sample_buffer[i];
682
683         for (i = 0; i < c->nchannels; i++)
684             b->msb_sample_buffer[b->orig_order[i]] = tmp[i];
685     }
686
687     // Map output channel pointers for frequency band 0
688     if (c->nfreqbands == 1)
689         for (i = 0; i < c->nchannels; i++)
690             s->output_samples[c->ch_remap[i]] = b->msb_sample_buffer[i];
691 }
692
693 static int chs_get_lsb_width(DCAXllDecoder *s, DCAXllChSet *c, int band, int ch)
694 {
695     int adj = c->bands[band].bit_width_adjust[ch];
696     int shift = c->bands[band].nscalablelsbs[ch];
697
698     if (s->fixed_lsb_width)
699         shift = s->fixed_lsb_width;
700     else if (shift && adj)
701         shift += adj - 1;
702     else
703         shift += adj;
704
705     return shift;
706 }
707
708 static void chs_assemble_msbs_lsbs(DCAXllDecoder *s, DCAXllChSet *c, int band)
709 {
710     DCAXllBand *b = &c->bands[band];
711     int n, ch, nsamples = s->nframesamples;
712
713     for (ch = 0; ch < c->nchannels; ch++) {
714         int shift = chs_get_lsb_width(s, c, band, ch);
715         if (shift) {
716             int32_t *msb = b->msb_sample_buffer[ch];
717             if (b->nscalablelsbs[ch]) {
718                 int32_t *lsb = b->lsb_sample_buffer[ch];
719                 int adj = b->bit_width_adjust[ch];
720                 for (n = 0; n < nsamples; n++)
721                     msb[n] = msb[n] * (1 << shift) + (lsb[n] << adj);
722             } else {
723                 for (n = 0; n < nsamples; n++)
724                     msb[n] = msb[n] * (1 << shift);
725             }
726         }
727     }
728 }
729
730 static int chs_assemble_freq_bands(DCAXllDecoder *s, DCAXllChSet *c)
731 {
732     int ch, nsamples = s->nframesamples;
733     int32_t *ptr;
734
735     av_assert1(c->nfreqbands > 1);
736
737     // Reallocate frequency band assembly buffer
738     av_fast_malloc(&c->sample_buffer[2], &c->sample_size[2],
739                    2 * nsamples * c->nchannels * sizeof(int32_t));
740     if (!c->sample_buffer[2])
741         return AVERROR(ENOMEM);
742
743     // Assemble frequency bands 0 and 1
744     ptr = c->sample_buffer[2];
745     for (ch = 0; ch < c->nchannels; ch++) {
746         int32_t *band0 = c->bands[0].msb_sample_buffer[ch];
747         int32_t *band1 = c->bands[1].msb_sample_buffer[ch];
748
749         // Copy decimator history
750         memcpy(band0 - DCA_XLL_DECI_HISTORY_MAX,
751                c->deci_history[ch], sizeof(c->deci_history[0]));
752
753         // Filter
754         s->dcadsp->assemble_freq_bands(ptr, band0, band1,
755                                        ff_dca_xll_band_coeff,
756                                        nsamples);
757
758         // Remap output channel pointer to assembly buffer
759         s->output_samples[c->ch_remap[ch]] = ptr;
760         ptr += nsamples * 2;
761     }
762
763     return 0;
764 }
765
766 static int parse_common_header(DCAXllDecoder *s)
767 {
768     int stream_ver, header_size, frame_size_nbits, nframesegs_log2;
769
770     // XLL extension sync word
771     if (get_bits_long(&s->gb, 32) != DCA_SYNCWORD_XLL) {
772         av_log(s->avctx, AV_LOG_VERBOSE, "Invalid XLL sync word\n");
773         return AVERROR(EAGAIN);
774     }
775
776     // Version number
777     stream_ver = get_bits(&s->gb, 4) + 1;
778     if (stream_ver > 1) {
779         avpriv_request_sample(s->avctx, "XLL stream version %d", stream_ver);
780         return AVERROR_PATCHWELCOME;
781     }
782
783     // Lossless frame header length
784     header_size = get_bits(&s->gb, 8) + 1;
785
786     // Check CRC
787     if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
788         && ff_dca_check_crc(&s->gb, 32, header_size * 8)) {
789         av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL common header checksum\n");
790         return AVERROR_INVALIDDATA;
791     }
792
793     // Number of bits used to read frame size
794     frame_size_nbits = get_bits(&s->gb, 5) + 1;
795
796     // Number of bytes in a lossless frame
797     s->frame_size = get_bits_long(&s->gb, frame_size_nbits);
798     if (s->frame_size < 0 || s->frame_size >= DCA_XLL_PBR_BUFFER_MAX) {
799         av_log(s->avctx, AV_LOG_ERROR, "Invalid XLL frame size (%d bytes)\n", s->frame_size);
800         return AVERROR_INVALIDDATA;
801     }
802     s->frame_size++;
803
804     // Number of channels sets per frame
805     s->nchsets = get_bits(&s->gb, 4) + 1;
806     if (s->nchsets > DCA_XLL_CHSETS_MAX) {
807         avpriv_request_sample(s->avctx, "%d XLL channel sets", s->nchsets);
808         return AVERROR_PATCHWELCOME;
809     }
810
811     // Number of segments per frame
812     nframesegs_log2 = get_bits(&s->gb, 4);
813     s->nframesegs = 1 << nframesegs_log2;
814     if (s->nframesegs > 1024) {
815         av_log(s->avctx, AV_LOG_ERROR, "Too many segments per XLL frame\n");
816         return AVERROR_INVALIDDATA;
817     }
818
819     // Samples in segment per one frequency band for the first channel set
820     // Maximum value is 256 for sampling frequencies <= 48 kHz
821     // Maximum value is 512 for sampling frequencies > 48 kHz
822     s->nsegsamples_log2 = get_bits(&s->gb, 4);
823     if (!s->nsegsamples_log2) {
824         av_log(s->avctx, AV_LOG_ERROR, "Too few samples per XLL segment\n");
825         return AVERROR_INVALIDDATA;
826     }
827     s->nsegsamples = 1 << s->nsegsamples_log2;
828     if (s->nsegsamples > 512) {
829         av_log(s->avctx, AV_LOG_ERROR, "Too many samples per XLL segment\n");
830         return AVERROR_INVALIDDATA;
831     }
832
833     // Samples in frame per one frequency band for the first channel set
834     s->nframesamples_log2 = s->nsegsamples_log2 + nframesegs_log2;
835     s->nframesamples = 1 << s->nframesamples_log2;
836     if (s->nframesamples > 65536) {
837         av_log(s->avctx, AV_LOG_ERROR, "Too many samples per XLL frame\n");
838         return AVERROR_INVALIDDATA;
839     }
840
841     // Number of bits used to read segment size
842     s->seg_size_nbits = get_bits(&s->gb, 5) + 1;
843
844     // Presence of CRC16 within each frequency band
845     // 0 - No CRC16 within band
846     // 1 - CRC16 placed at the end of MSB0
847     // 2 - CRC16 placed at the end of MSB0 and LSB0
848     // 3 - CRC16 placed at the end of MSB0 and LSB0 and other frequency bands
849     s->band_crc_present = get_bits(&s->gb, 2);
850
851     // MSB/LSB split flag
852     s->scalable_lsbs = get_bits1(&s->gb);
853
854     // Channel position mask
855     s->ch_mask_nbits = get_bits(&s->gb, 5) + 1;
856
857     // Fixed LSB width
858     if (s->scalable_lsbs)
859         s->fixed_lsb_width = get_bits(&s->gb, 4);
860     else
861         s->fixed_lsb_width = 0;
862
863     // Reserved
864     // Byte align
865     // Header CRC16 protection
866     if (ff_dca_seek_bits(&s->gb, header_size * 8)) {
867         av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL common header\n");
868         return AVERROR_INVALIDDATA;
869     }
870
871     return 0;
872 }
873
874 static int is_hier_dmix_chset(DCAXllChSet *c)
875 {
876     return !c->primary_chset && c->dmix_embedded && c->hier_chset;
877 }
878
879 static DCAXllChSet *find_next_hier_dmix_chset(DCAXllDecoder *s, DCAXllChSet *c)
880 {
881     if (c->hier_chset)
882         while (++c < &s->chset[s->nchsets])
883             if (is_hier_dmix_chset(c))
884                 return c;
885
886     return NULL;
887 }
888
889 static void prescale_down_mix(DCAXllChSet *c, DCAXllChSet *o)
890 {
891     int i, j, *coeff_ptr = c->dmix_coeff;
892
893     for (i = 0; i < c->hier_ofs; i++) {
894         int scale = o->dmix_scale[i];
895         int scale_inv = o->dmix_scale_inv[i];
896         c->dmix_scale[i] = mul15(c->dmix_scale[i], scale);
897         c->dmix_scale_inv[i] = mul16(c->dmix_scale_inv[i], scale_inv);
898         for (j = 0; j < c->nchannels; j++) {
899             int coeff = mul16(*coeff_ptr, scale_inv);
900             *coeff_ptr++ = mul15(coeff, o->dmix_scale[c->hier_ofs + j]);
901         }
902     }
903 }
904
905 static int parse_sub_headers(DCAXllDecoder *s, DCAExssAsset *asset)
906 {
907     DCAContext *dca = s->avctx->priv_data;
908     DCAXllChSet *c;
909     int i, ret;
910
911     // Parse channel set headers
912     s->nfreqbands = 0;
913     s->nchannels = 0;
914     s->nreschsets = 0;
915     for (i = 0, c = s->chset; i < s->nchsets; i++, c++) {
916         c->hier_ofs = s->nchannels;
917         if ((ret = chs_parse_header(s, c, asset)) < 0)
918             return ret;
919         if (c->nfreqbands > s->nfreqbands)
920             s->nfreqbands = c->nfreqbands;
921         if (c->hier_chset)
922             s->nchannels += c->nchannels;
923         if (c->residual_encode != (1 << c->nchannels) - 1)
924             s->nreschsets++;
925     }
926
927     // Pre-scale downmixing coefficients for all non-primary channel sets
928     for (i = s->nchsets - 1, c = &s->chset[i]; i > 0; i--, c--) {
929         if (is_hier_dmix_chset(c)) {
930             DCAXllChSet *o = find_next_hier_dmix_chset(s, c);
931             if (o)
932                 prescale_down_mix(c, o);
933         }
934     }
935
936     // Determine number of active channel sets to decode
937     switch (dca->request_channel_layout) {
938     case DCA_SPEAKER_LAYOUT_STEREO:
939         s->nactivechsets = 1;
940         break;
941     case DCA_SPEAKER_LAYOUT_5POINT0:
942     case DCA_SPEAKER_LAYOUT_5POINT1:
943         s->nactivechsets = (s->chset[0].nchannels < 5 && s->nchsets > 1) ? 2 : 1;
944         break;
945     default:
946         s->nactivechsets = s->nchsets;
947         break;
948     }
949
950     return 0;
951 }
952
953 static int parse_navi_table(DCAXllDecoder *s)
954 {
955     int chs, seg, band, navi_nb, navi_pos, *navi_ptr;
956     DCAXllChSet *c;
957
958     // Determine size of NAVI table
959     navi_nb = s->nfreqbands * s->nframesegs * s->nchsets;
960     if (navi_nb > 1024) {
961         av_log(s->avctx, AV_LOG_ERROR, "Too many NAVI entries (%d)\n", navi_nb);
962         return AVERROR_INVALIDDATA;
963     }
964
965     // Reallocate NAVI table
966     av_fast_malloc(&s->navi, &s->navi_size, navi_nb * sizeof(*s->navi));
967     if (!s->navi)
968         return AVERROR(ENOMEM);
969
970     // Parse NAVI
971     navi_pos = get_bits_count(&s->gb);
972     navi_ptr = s->navi;
973     for (band = 0; band < s->nfreqbands; band++) {
974         for (seg = 0; seg < s->nframesegs; seg++) {
975             for (chs = 0, c = s->chset; chs < s->nchsets; chs++, c++) {
976                 int size = 0;
977                 if (c->nfreqbands > band) {
978                     size = get_bits_long(&s->gb, s->seg_size_nbits);
979                     if (size < 0 || size >= s->frame_size) {
980                         av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI segment size (%d bytes)\n", size);
981                         return AVERROR_INVALIDDATA;
982                     }
983                     size++;
984                 }
985                 *navi_ptr++ = size;
986             }
987         }
988     }
989
990     // Byte align
991     // CRC16
992     skip_bits(&s->gb, -get_bits_count(&s->gb) & 7);
993     skip_bits(&s->gb, 16);
994
995     // Check CRC
996     if ((s->avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_CAREFUL))
997         && ff_dca_check_crc(&s->gb, navi_pos, get_bits_count(&s->gb))) {
998         av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI checksum\n");
999         return AVERROR_INVALIDDATA;
1000     }
1001
1002     return 0;
1003 }
1004
1005 static int parse_band_data(DCAXllDecoder *s)
1006 {
1007     int ret, chs, seg, band, navi_pos, *navi_ptr;
1008     DCAXllChSet *c;
1009
1010     for (chs = 0, c = s->chset; chs < s->nactivechsets; chs++, c++) {
1011         if ((ret = chs_alloc_msb_band_data(s, c)) < 0)
1012             return ret;
1013         if ((ret = chs_alloc_lsb_band_data(s, c)) < 0)
1014             return ret;
1015     }
1016
1017     navi_pos = get_bits_count(&s->gb);
1018     navi_ptr = s->navi;
1019     for (band = 0; band < s->nfreqbands; band++) {
1020         for (seg = 0; seg < s->nframesegs; seg++) {
1021             for (chs = 0, c = s->chset; chs < s->nchsets; chs++, c++) {
1022                 if (c->nfreqbands > band) {
1023                     navi_pos += *navi_ptr * 8;
1024                     if (navi_pos > s->gb.size_in_bits) {
1025                         av_log(s->avctx, AV_LOG_ERROR, "Invalid NAVI position\n");
1026                         return AVERROR_INVALIDDATA;
1027                     }
1028                     if (chs < s->nactivechsets &&
1029                         (ret = chs_parse_band_data(s, c, band, seg, navi_pos)) < 0) {
1030                         if (s->avctx->err_recognition & AV_EF_EXPLODE)
1031                             return ret;
1032                         chs_clear_band_data(s, c, band, seg);
1033                     }
1034                     s->gb.index = navi_pos;
1035                 }
1036                 navi_ptr++;
1037             }
1038         }
1039     }
1040
1041     return 0;
1042 }
1043
1044 static int parse_frame(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1045 {
1046     int ret;
1047
1048     if ((ret = init_get_bits8(&s->gb, data, size)) < 0)
1049         return ret;
1050     if ((ret = parse_common_header(s)) < 0)
1051         return ret;
1052     if ((ret = parse_sub_headers(s, asset)) < 0)
1053         return ret;
1054     if ((ret = parse_navi_table(s)) < 0)
1055         return ret;
1056     if ((ret = parse_band_data(s)) < 0)
1057         return ret;
1058     if (ff_dca_seek_bits(&s->gb, s->frame_size * 8)) {
1059         av_log(s->avctx, AV_LOG_ERROR, "Read past end of XLL frame\n");
1060         return AVERROR_INVALIDDATA;
1061     }
1062     return ret;
1063 }
1064
1065 static void clear_pbr(DCAXllDecoder *s)
1066 {
1067     s->pbr_length = 0;
1068     s->pbr_delay = 0;
1069 }
1070
1071 static int copy_to_pbr(DCAXllDecoder *s, uint8_t *data, int size, int delay)
1072 {
1073     if (size > DCA_XLL_PBR_BUFFER_MAX)
1074         return AVERROR(ENOSPC);
1075
1076     if (!s->pbr_buffer && !(s->pbr_buffer = av_malloc(DCA_XLL_PBR_BUFFER_MAX + DCA_BUFFER_PADDING_SIZE)))
1077         return AVERROR(ENOMEM);
1078
1079     memcpy(s->pbr_buffer, data, size);
1080     s->pbr_length = size;
1081     s->pbr_delay = delay;
1082     return 0;
1083 }
1084
1085 static int parse_frame_no_pbr(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1086 {
1087     int ret = parse_frame(s, data, size, asset);
1088
1089     // If XLL packet data didn't start with a sync word, we must have jumped
1090     // right into the middle of PBR smoothing period
1091     if (ret == AVERROR(EAGAIN) && asset->xll_sync_present && asset->xll_sync_offset < size) {
1092         // Skip to the next sync word in this packet
1093         data += asset->xll_sync_offset;
1094         size -= asset->xll_sync_offset;
1095
1096         // If decoding delay is set, put the frame into PBR buffer and return
1097         // failure code. Higher level decoder is expected to switch to lossy
1098         // core decoding or mute its output until decoding delay expires.
1099         if (asset->xll_delay_nframes > 0) {
1100             if ((ret = copy_to_pbr(s, data, size, asset->xll_delay_nframes)) < 0)
1101                 return ret;
1102             return AVERROR(EAGAIN);
1103         }
1104
1105         // No decoding delay, just parse the frame in place
1106         ret = parse_frame(s, data, size, asset);
1107     }
1108
1109     if (ret < 0)
1110         return ret;
1111
1112     if (s->frame_size > size)
1113         return AVERROR(EINVAL);
1114
1115     // If the XLL decoder didn't consume full packet, start PBR smoothing period
1116     if (s->frame_size < size)
1117         if ((ret = copy_to_pbr(s, data + s->frame_size, size - s->frame_size, 0)) < 0)
1118             return ret;
1119
1120     return 0;
1121 }
1122
1123 static int parse_frame_pbr(DCAXllDecoder *s, uint8_t *data, int size, DCAExssAsset *asset)
1124 {
1125     int ret;
1126
1127     if (size > DCA_XLL_PBR_BUFFER_MAX - s->pbr_length) {
1128         ret = AVERROR(ENOSPC);
1129         goto fail;
1130     }
1131
1132     memcpy(s->pbr_buffer + s->pbr_length, data, size);
1133     s->pbr_length += size;
1134
1135     // Respect decoding delay after synchronization error
1136     if (s->pbr_delay > 0 && --s->pbr_delay)
1137         return AVERROR(EAGAIN);
1138
1139     if ((ret = parse_frame(s, s->pbr_buffer, s->pbr_length, asset)) < 0)
1140         goto fail;
1141
1142     if (s->frame_size > s->pbr_length) {
1143         ret = AVERROR(EINVAL);
1144         goto fail;
1145     }
1146
1147     if (s->frame_size == s->pbr_length) {
1148         // End of PBR smoothing period
1149         clear_pbr(s);
1150     } else {
1151         s->pbr_length -= s->frame_size;
1152         memmove(s->pbr_buffer, s->pbr_buffer + s->frame_size, s->pbr_length);
1153     }
1154
1155     return 0;
1156
1157 fail:
1158     // For now, throw out all PBR state on failure.
1159     // Perhaps we can be smarter and try to resync somehow.
1160     clear_pbr(s);
1161     return ret;
1162 }
1163
1164 int ff_dca_xll_parse(DCAXllDecoder *s, uint8_t *data, DCAExssAsset *asset)
1165 {
1166     int ret;
1167
1168     if (s->hd_stream_id != asset->hd_stream_id) {
1169         clear_pbr(s);
1170         s->hd_stream_id = asset->hd_stream_id;
1171     }
1172
1173     if (s->pbr_length)
1174         ret = parse_frame_pbr(s, data + asset->xll_offset, asset->xll_size, asset);
1175     else
1176         ret = parse_frame_no_pbr(s, data + asset->xll_offset, asset->xll_size, asset);
1177
1178     return ret;
1179 }
1180
1181 static void undo_down_mix(DCAXllDecoder *s, DCAXllChSet *o, int band)
1182 {
1183     int i, j, k, nchannels = 0, *coeff_ptr = o->dmix_coeff;
1184     DCAXllChSet *c;
1185
1186     for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1187         if (!c->hier_chset)
1188             continue;
1189
1190         av_assert1(band < c->nfreqbands);
1191         for (j = 0; j < c->nchannels; j++) {
1192             for (k = 0; k < o->nchannels; k++) {
1193                 int coeff = *coeff_ptr++;
1194                 if (coeff) {
1195                     s->dcadsp->dmix_sub(c->bands[band].msb_sample_buffer[j],
1196                                         o->bands[band].msb_sample_buffer[k],
1197                                         coeff, s->nframesamples);
1198                     if (band)
1199                         s->dcadsp->dmix_sub(c->deci_history[j],
1200                                             o->deci_history[k],
1201                                             coeff, DCA_XLL_DECI_HISTORY_MAX);
1202                 }
1203             }
1204         }
1205
1206         nchannels += c->nchannels;
1207         if (nchannels >= o->hier_ofs)
1208             break;
1209     }
1210 }
1211
1212 static void scale_down_mix(DCAXllDecoder *s, DCAXllChSet *o, int band)
1213 {
1214     int i, j, nchannels = 0;
1215     DCAXllChSet *c;
1216
1217     for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1218         if (!c->hier_chset)
1219             continue;
1220
1221         av_assert1(band < c->nfreqbands);
1222         for (j = 0; j < c->nchannels; j++) {
1223             int scale = o->dmix_scale[nchannels++];
1224             if (scale != (1 << 15)) {
1225                 s->dcadsp->dmix_scale(c->bands[band].msb_sample_buffer[j],
1226                                       scale, s->nframesamples);
1227                 if (band)
1228                     s->dcadsp->dmix_scale(c->deci_history[j],
1229                                           scale, DCA_XLL_DECI_HISTORY_MAX);
1230             }
1231         }
1232
1233         if (nchannels >= o->hier_ofs)
1234             break;
1235     }
1236 }
1237
1238 // Clear all band data and replace non-residual encoded channels with lossy
1239 // counterparts
1240 static av_cold void force_lossy_output(DCAXllDecoder *s, DCAXllChSet *c)
1241 {
1242     DCAContext *dca = s->avctx->priv_data;
1243     int band, ch;
1244
1245     for (band = 0; band < c->nfreqbands; band++)
1246         chs_clear_band_data(s, c, band, -1);
1247
1248     for (ch = 0; ch < c->nchannels; ch++) {
1249         if (!(c->residual_encode & (1 << ch)))
1250             continue;
1251         if (ff_dca_core_map_spkr(&dca->core, c->ch_remap[ch]) < 0)
1252             continue;
1253         c->residual_encode &= ~(1 << ch);
1254     }
1255 }
1256
1257 static int combine_residual_frame(DCAXllDecoder *s, DCAXllChSet *c)
1258 {
1259     DCAContext *dca = s->avctx->priv_data;
1260     int ch, nsamples = s->nframesamples;
1261     DCAXllChSet *o;
1262
1263     // Verify that core is compatible
1264     if (!(dca->packet & DCA_PACKET_CORE)) {
1265         av_log(s->avctx, AV_LOG_ERROR, "Residual encoded channels are present without core\n");
1266         return AVERROR(EINVAL);
1267     }
1268
1269     if (c->freq != dca->core.output_rate) {
1270         av_log(s->avctx, AV_LOG_WARNING, "Sample rate mismatch between core (%d Hz) and XLL (%d Hz)\n", dca->core.output_rate, c->freq);
1271         return AVERROR_INVALIDDATA;
1272     }
1273
1274     if (nsamples != dca->core.npcmsamples) {
1275         av_log(s->avctx, AV_LOG_WARNING, "Number of samples per frame mismatch between core (%d) and XLL (%d)\n", dca->core.npcmsamples, nsamples);
1276         return AVERROR_INVALIDDATA;
1277     }
1278
1279     // See if this channel set is downmixed and find the next channel set in
1280     // hierarchy. If downmixed, undo core pre-scaling before combining with
1281     // residual (residual is not scaled).
1282     o = find_next_hier_dmix_chset(s, c);
1283
1284     // Reduce core bit width and combine with residual
1285     for (ch = 0; ch < c->nchannels; ch++) {
1286         int n, spkr, shift, round;
1287         int32_t *src, *dst;
1288
1289         if (c->residual_encode & (1 << ch))
1290             continue;
1291
1292         // Map this channel to core speaker
1293         spkr = ff_dca_core_map_spkr(&dca->core, c->ch_remap[ch]);
1294         if (spkr < 0) {
1295             av_log(s->avctx, AV_LOG_WARNING, "Residual encoded channel (%d) references unavailable core channel\n", c->ch_remap[ch]);
1296             return AVERROR_INVALIDDATA;
1297         }
1298
1299         // Account for LSB width
1300         shift = 24 - c->pcm_bit_res + chs_get_lsb_width(s, c, 0, ch);
1301         if (shift > 24) {
1302             av_log(s->avctx, AV_LOG_WARNING, "Invalid core shift (%d bits)\n", shift);
1303             return AVERROR_INVALIDDATA;
1304         }
1305
1306         round = shift > 0 ? 1 << (shift - 1) : 0;
1307
1308         src = dca->core.output_samples[spkr];
1309         dst = c->bands[0].msb_sample_buffer[ch];
1310         if (o) {
1311             // Undo embedded core downmix pre-scaling
1312             int scale_inv = o->dmix_scale_inv[c->hier_ofs + ch];
1313             for (n = 0; n < nsamples; n++)
1314                 dst[n] += clip23((mul16(src[n], scale_inv) + round) >> shift);
1315         } else {
1316             // No downmix scaling
1317             for (n = 0; n < nsamples; n++)
1318                 dst[n] += (src[n] + round) >> shift;
1319         }
1320     }
1321
1322     return 0;
1323 }
1324
1325 int ff_dca_xll_filter_frame(DCAXllDecoder *s, AVFrame *frame)
1326 {
1327     AVCodecContext *avctx = s->avctx;
1328     DCAContext *dca = avctx->priv_data;
1329     DCAExssAsset *asset = &dca->exss.assets[0];
1330     DCAXllChSet *p = &s->chset[0], *c;
1331     enum AVMatrixEncoding matrix_encoding = AV_MATRIX_ENCODING_NONE;
1332     int i, j, k, ret, shift, nsamples, request_mask;
1333     int ch_remap[DCA_SPEAKER_COUNT];
1334
1335     // Force lossy downmixed output during recovery
1336     if (dca->packet & DCA_PACKET_RECOVERY) {
1337         for (i = 0, c = s->chset; i < s->nchsets; i++, c++) {
1338             if (i < s->nactivechsets)
1339                 force_lossy_output(s, c);
1340
1341             if (!c->primary_chset)
1342                 c->dmix_embedded = 0;
1343         }
1344
1345         s->scalable_lsbs = 0;
1346         s->fixed_lsb_width = 0;
1347     }
1348
1349     // Filter frequency bands for active channel sets
1350     s->output_mask = 0;
1351     for (i = 0, c = s->chset; i < s->nactivechsets; i++, c++) {
1352         chs_filter_band_data(s, c, 0);
1353
1354         if (c->residual_encode != (1 << c->nchannels) - 1
1355             && (ret = combine_residual_frame(s, c)) < 0)
1356             return ret;
1357
1358         if (s->scalable_lsbs)
1359             chs_assemble_msbs_lsbs(s, c, 0);
1360
1361         if (c->nfreqbands > 1) {
1362             chs_filter_band_data(s, c, 1);
1363             chs_assemble_msbs_lsbs(s, c, 1);
1364         }
1365
1366         s->output_mask |= c->ch_mask;
1367     }
1368
1369     // Undo hierarchial downmix and/or apply scaling
1370     for (i = 1, c = &s->chset[1]; i < s->nchsets; i++, c++) {
1371         if (!is_hier_dmix_chset(c))
1372             continue;
1373
1374         if (i >= s->nactivechsets) {
1375             for (j = 0; j < c->nfreqbands; j++)
1376                 if (c->bands[j].dmix_embedded)
1377                     scale_down_mix(s, c, j);
1378             break;
1379         }
1380
1381         for (j = 0; j < c->nfreqbands; j++)
1382             if (c->bands[j].dmix_embedded)
1383                 undo_down_mix(s, c, j);
1384     }
1385
1386     // Assemble frequency bands for active channel sets
1387     if (s->nfreqbands > 1) {
1388         for (i = 0; i < s->nactivechsets; i++)
1389             if ((ret = chs_assemble_freq_bands(s, &s->chset[i])) < 0)
1390                 return ret;
1391     }
1392
1393     // Normalize to regular 5.1 layout if downmixing
1394     if (dca->request_channel_layout) {
1395         if (s->output_mask & DCA_SPEAKER_MASK_Lss) {
1396             s->output_samples[DCA_SPEAKER_Ls] = s->output_samples[DCA_SPEAKER_Lss];
1397             s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Lss) | DCA_SPEAKER_MASK_Ls;
1398         }
1399         if (s->output_mask & DCA_SPEAKER_MASK_Rss) {
1400             s->output_samples[DCA_SPEAKER_Rs] = s->output_samples[DCA_SPEAKER_Rss];
1401             s->output_mask = (s->output_mask & ~DCA_SPEAKER_MASK_Rss) | DCA_SPEAKER_MASK_Rs;
1402         }
1403     }
1404
1405     // Handle downmixing to stereo request
1406     if (dca->request_channel_layout == DCA_SPEAKER_LAYOUT_STEREO
1407         && DCA_HAS_STEREO(s->output_mask) && p->dmix_embedded
1408         && (p->dmix_type == DCA_DMIX_TYPE_LoRo ||
1409             p->dmix_type == DCA_DMIX_TYPE_LtRt))
1410         request_mask = DCA_SPEAKER_LAYOUT_STEREO;
1411     else
1412         request_mask = s->output_mask;
1413     if (!ff_dca_set_channel_layout(avctx, ch_remap, request_mask))
1414         return AVERROR(EINVAL);
1415
1416     avctx->sample_rate = p->freq << (s->nfreqbands - 1);
1417
1418     switch (p->storage_bit_res) {
1419     case 16:
1420         avctx->sample_fmt = AV_SAMPLE_FMT_S16P;
1421         break;
1422     case 24:
1423         avctx->sample_fmt = AV_SAMPLE_FMT_S32P;
1424         break;
1425     default:
1426         return AVERROR(EINVAL);
1427     }
1428
1429     avctx->bits_per_raw_sample = p->storage_bit_res;
1430     avctx->profile = FF_PROFILE_DTS_HD_MA;
1431     avctx->bit_rate = 0;
1432
1433     frame->nb_samples = nsamples = s->nframesamples << (s->nfreqbands - 1);
1434     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
1435         return ret;
1436
1437     // Downmix primary channel set to stereo
1438     if (request_mask != s->output_mask) {
1439         ff_dca_downmix_to_stereo_fixed(s->dcadsp, s->output_samples,
1440                                        p->dmix_coeff, nsamples,
1441                                        s->output_mask);
1442     }
1443
1444     shift = p->storage_bit_res - p->pcm_bit_res;
1445     for (i = 0; i < avctx->channels; i++) {
1446         int32_t *samples = s->output_samples[ch_remap[i]];
1447         if (frame->format == AV_SAMPLE_FMT_S16P) {
1448             int16_t *plane = (int16_t *)frame->extended_data[i];
1449             for (k = 0; k < nsamples; k++)
1450                 plane[k] = av_clip_int16(samples[k] * (1 << shift));
1451         } else {
1452             int32_t *plane = (int32_t *)frame->extended_data[i];
1453             for (k = 0; k < nsamples; k++)
1454                 plane[k] = clip23(samples[k] * (1 << shift)) * (1 << 8);
1455         }
1456     }
1457
1458     if (!asset->one_to_one_map_ch_to_spkr) {
1459         if (asset->representation_type == DCA_REPR_TYPE_LtRt)
1460             matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
1461         else if (asset->representation_type == DCA_REPR_TYPE_LhRh)
1462             matrix_encoding = AV_MATRIX_ENCODING_DOLBYHEADPHONE;
1463     } else if (request_mask != s->output_mask && p->dmix_type == DCA_DMIX_TYPE_LtRt) {
1464         matrix_encoding = AV_MATRIX_ENCODING_DOLBY;
1465     }
1466     if ((ret = ff_side_data_update_matrix_encoding(frame, matrix_encoding)) < 0)
1467         return ret;
1468
1469     return 0;
1470 }
1471
1472 av_cold void ff_dca_xll_flush(DCAXllDecoder *s)
1473 {
1474     clear_pbr(s);
1475 }
1476
1477 av_cold void ff_dca_xll_close(DCAXllDecoder *s)
1478 {
1479     DCAXllChSet *c;
1480     int i, j;
1481
1482     for (i = 0, c = s->chset; i < DCA_XLL_CHSETS_MAX; i++, c++) {
1483         for (j = 0; j < DCA_XLL_SAMPLE_BUFFERS_MAX; j++) {
1484             av_freep(&c->sample_buffer[j]);
1485             c->sample_size[j] = 0;
1486         }
1487     }
1488
1489     av_freep(&s->navi);
1490     s->navi_size = 0;
1491
1492     av_freep(&s->pbr_buffer);
1493     clear_pbr(s);
1494 }