]> git.sesse.net Git - ffmpeg/blob - libavcodec/atrac3plus.c
avcodec/atrac3plus: Simplify getting offset of VLC in VLC_TYPE buf
[ffmpeg] / libavcodec / atrac3plus.c
1 /*
2  * ATRAC3+ compatible decoder
3  *
4  * Copyright (c) 2010-2013 Maxim Poliakovski
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 /**
24  * @file
25  * Bitstream parser for ATRAC3+ decoder.
26  */
27
28 #include "libavutil/avassert.h"
29 #include "avcodec.h"
30 #include "get_bits.h"
31 #include "atrac3plus.h"
32 #include "atrac3plus_data.h"
33
34 static VLC_TYPE tables_data[154276][2];
35 static VLC wl_vlc_tabs[4];
36 static VLC sf_vlc_tabs[8];
37 static VLC ct_vlc_tabs[4];
38 static VLC spec_vlc_tabs[112];
39 static VLC gain_vlc_tabs[11];
40 static VLC tone_vlc_tabs[7];
41
42 /**
43  * Generate canonical VLC table from given descriptor.
44  *
45  * @param[in]     cb          ptr to codebook descriptor
46  * @param[in]     xlat        ptr to translation table or NULL
47  * @param[in,out] tab_offset  starting offset to the generated vlc table
48  * @param[out]    out_vlc     ptr to vlc table to be generated
49  */
50 static av_cold void build_canonical_huff(const uint8_t *cb, const uint8_t *xlat,
51                                          int *tab_offset, VLC *out_vlc)
52 {
53     int i, b;
54     uint8_t bits[256];
55     int index = 0;
56     int min_len = *cb++; // get shortest codeword length
57     int max_len = *cb++; // get longest  codeword length
58
59     for (b = min_len; b <= max_len; b++) {
60         for (i = *cb++; i > 0; i--) {
61             av_assert0(index < 256);
62             bits[index]  = b;
63             index++;
64         }
65     }
66
67     out_vlc->table = &tables_data[*tab_offset];
68     out_vlc->table_allocated = 1 << max_len;
69
70     ff_init_vlc_from_lengths(out_vlc, max_len, index, bits, 1,
71                              xlat, 1, 1, 0, INIT_VLC_USE_NEW_STATIC, NULL);
72
73     *tab_offset += 1 << max_len;
74 }
75
76 av_cold void ff_atrac3p_init_vlcs(void)
77 {
78     int i, tab_offset = 0;
79
80     static const uint8_t wl_nb_bits[4]  = { 2, 3, 5, 5 };
81     static const uint8_t wl_nb_codes[4] = { 3, 5, 8, 8 };
82     static const uint8_t (*const wl_huffs[4])[2] = {
83         atrac3p_wl_huff1, atrac3p_wl_huff2,
84         atrac3p_wl_huff3, atrac3p_wl_huff4
85     };
86
87     static const uint8_t ct_nb_bits[4]  = { 3, 4, 4, 4 };
88     static const uint8_t ct_nb_codes[4] = { 4, 8, 8, 8 };
89     static const uint8_t (*const ct_huffs[4])[2]  = {
90         atrac3p_ct_huff1, atrac3p_ct_huff2,
91         atrac3p_ct_huff3, atrac3p_ct_huff4
92     };
93
94     static const uint8_t sf_nb_bits[8]  = {  9,  9,  9,  9,  6,  6,  7,  7 };
95     static const uint8_t sf_nb_codes[8] = { 64, 64, 64, 64, 15, 15, 15, 15 };
96     static const uint8_t  (*const sf_huffs[8])[2]  = {
97         atrac3p_sf_huff1, atrac3p_sf_huff2, atrac3p_sf_huff3,
98         atrac3p_sf_huff4, atrac3p_sf_huff5, atrac3p_sf_huff6,
99         atrac3p_sf_huff7, atrac3p_sf_huff8
100     };
101
102     static const uint8_t * const gain_cbs[11] = {
103         atrac3p_huff_gain_npoints1_cb, atrac3p_huff_gain_npoints1_cb,
104         atrac3p_huff_gain_lev1_cb, atrac3p_huff_gain_lev2_cb,
105         atrac3p_huff_gain_lev3_cb, atrac3p_huff_gain_lev4_cb,
106         atrac3p_huff_gain_loc3_cb, atrac3p_huff_gain_loc1_cb,
107         atrac3p_huff_gain_loc4_cb, atrac3p_huff_gain_loc2_cb,
108         atrac3p_huff_gain_loc5_cb
109     };
110     static const uint8_t * const gain_xlats[11] = {
111         NULL, atrac3p_huff_gain_npoints2_xlat, atrac3p_huff_gain_lev1_xlat,
112         atrac3p_huff_gain_lev2_xlat, atrac3p_huff_gain_lev3_xlat,
113         atrac3p_huff_gain_lev4_xlat, atrac3p_huff_gain_loc3_xlat,
114         atrac3p_huff_gain_loc1_xlat, atrac3p_huff_gain_loc4_xlat,
115         atrac3p_huff_gain_loc2_xlat, atrac3p_huff_gain_loc5_xlat
116     };
117
118     static const uint8_t * const tone_cbs[7] = {
119         atrac3p_huff_tonebands_cb,  atrac3p_huff_numwavs1_cb,
120         atrac3p_huff_numwavs2_cb,   atrac3p_huff_wav_ampsf1_cb,
121         atrac3p_huff_wav_ampsf2_cb, atrac3p_huff_wav_ampsf3_cb,
122         atrac3p_huff_freq_cb
123     };
124     static const uint8_t * const tone_xlats[7] = {
125         NULL, NULL, atrac3p_huff_numwavs2_xlat, atrac3p_huff_wav_ampsf1_xlat,
126         atrac3p_huff_wav_ampsf2_xlat, atrac3p_huff_wav_ampsf3_xlat,
127         atrac3p_huff_freq_xlat
128     };
129
130     for (int i = 0; i < 4; i++) {
131         wl_vlc_tabs[i].table = &tables_data[tab_offset];
132         wl_vlc_tabs[i].table_allocated = 1 << wl_nb_bits[i];
133         tab_offset                    += 1 << wl_nb_bits[i];
134         ff_init_vlc_from_lengths(&wl_vlc_tabs[i], wl_nb_bits[i], wl_nb_codes[i],
135                                  &wl_huffs[i][0][1], 2,
136                                  &wl_huffs[i][0][0], 2, 1,
137                                  0, INIT_VLC_USE_NEW_STATIC, NULL);
138
139         ct_vlc_tabs[i].table = &tables_data[tab_offset];
140         ct_vlc_tabs[i].table_allocated = 1 << ct_nb_bits[i];
141         tab_offset                    += 1 << ct_nb_bits[i];
142         ff_init_vlc_from_lengths(&ct_vlc_tabs[i], ct_nb_bits[i], ct_nb_codes[i],
143                                  &ct_huffs[i][0][1], 2,
144                                  &ct_huffs[i][0][0], 2, 1,
145                                  0, INIT_VLC_USE_NEW_STATIC, NULL);
146     }
147
148     for (int i = 0; i < 8; i++) {
149         sf_vlc_tabs[i].table = &tables_data[tab_offset];
150         sf_vlc_tabs[i].table_allocated = 1 << sf_nb_bits[i];
151         tab_offset                    += 1 << sf_nb_bits[i];
152         ff_init_vlc_from_lengths(&sf_vlc_tabs[i], sf_nb_bits[i], sf_nb_codes[i],
153                                  &sf_huffs[i][0][1], 2,
154                                  &sf_huffs[i][0][0], 2, 1,
155                                  0, INIT_VLC_USE_NEW_STATIC, NULL);
156     }
157
158     /* build huffman tables for spectrum decoding */
159     for (i = 0; i < 112; i++) {
160         if (atrac3p_spectra_tabs[i].redirect < 0)
161             build_canonical_huff(atrac3p_spectra_tabs[i].cb,
162                                  atrac3p_spectra_tabs[i].xlat,
163                                  &tab_offset, &spec_vlc_tabs[i]);
164         else /* Reuse already initialized VLC table */
165             spec_vlc_tabs[i] = spec_vlc_tabs[atrac3p_spectra_tabs[i].redirect];
166     }
167
168     /* build huffman tables for gain data decoding */
169     for (i = 0; i < 11; i++)
170         build_canonical_huff(gain_cbs[i], gain_xlats[i], &tab_offset, &gain_vlc_tabs[i]);
171
172     /* build huffman tables for tone decoding */
173     for (i = 0; i < 7; i++)
174         build_canonical_huff(tone_cbs[i], tone_xlats[i], &tab_offset, &tone_vlc_tabs[i]);
175 }
176
177 /**
178  * Decode number of coded quantization units.
179  *
180  * @param[in]     gb            the GetBit context
181  * @param[in,out] chan          ptr to the channel parameters
182  * @param[in,out] ctx           ptr to the channel unit context
183  * @param[in]     avctx         ptr to the AVCodecContext
184  * @return result code: 0 = OK, otherwise - error code
185  */
186 static int num_coded_units(GetBitContext *gb, Atrac3pChanParams *chan,
187                            Atrac3pChanUnitCtx *ctx, AVCodecContext *avctx)
188 {
189     chan->fill_mode = get_bits(gb, 2);
190     if (!chan->fill_mode) {
191         chan->num_coded_vals = ctx->num_quant_units;
192     } else {
193         chan->num_coded_vals = get_bits(gb, 5);
194         if (chan->num_coded_vals > ctx->num_quant_units) {
195             av_log(avctx, AV_LOG_ERROR,
196                    "Invalid number of transmitted units!\n");
197             return AVERROR_INVALIDDATA;
198         }
199
200         if (chan->fill_mode == 3)
201             chan->split_point = get_bits(gb, 2) + (chan->ch_num << 1) + 1;
202     }
203
204     return 0;
205 }
206
207 /**
208  * Add weighting coefficients to the decoded word-length information.
209  *
210  * @param[in,out] ctx           ptr to the channel unit context
211  * @param[in,out] chan          ptr to the channel parameters
212  * @param[in]     wtab_idx      index of the table of weights
213  * @param[in]     avctx         ptr to the AVCodecContext
214  * @return result code: 0 = OK, otherwise - error code
215  */
216 static int add_wordlen_weights(Atrac3pChanUnitCtx *ctx,
217                                Atrac3pChanParams *chan, int wtab_idx,
218                                AVCodecContext *avctx)
219 {
220     int i;
221     const int8_t *weights_tab =
222         &atrac3p_wl_weights[chan->ch_num * 3 + wtab_idx - 1][0];
223
224     for (i = 0; i < ctx->num_quant_units; i++) {
225         chan->qu_wordlen[i] += weights_tab[i];
226         if (chan->qu_wordlen[i] < 0 || chan->qu_wordlen[i] > 7) {
227             av_log(avctx, AV_LOG_ERROR,
228                    "WL index out of range: pos=%d, val=%d!\n",
229                    i, chan->qu_wordlen[i]);
230             return AVERROR_INVALIDDATA;
231         }
232     }
233
234     return 0;
235 }
236
237 /**
238  * Subtract weighting coefficients from decoded scalefactors.
239  *
240  * @param[in,out] ctx           ptr to the channel unit context
241  * @param[in,out] chan          ptr to the channel parameters
242  * @param[in]     wtab_idx      index of table of weights
243  * @param[in]     avctx         ptr to the AVCodecContext
244  * @return result code: 0 = OK, otherwise - error code
245  */
246 static int subtract_sf_weights(Atrac3pChanUnitCtx *ctx,
247                                Atrac3pChanParams *chan, int wtab_idx,
248                                AVCodecContext *avctx)
249 {
250     int i;
251     const int8_t *weights_tab = &atrac3p_sf_weights[wtab_idx - 1][0];
252
253     for (i = 0; i < ctx->used_quant_units; i++) {
254         chan->qu_sf_idx[i] -= weights_tab[i];
255         if (chan->qu_sf_idx[i] < 0 || chan->qu_sf_idx[i] > 63) {
256             av_log(avctx, AV_LOG_ERROR,
257                    "SF index out of range: pos=%d, val=%d!\n",
258                    i, chan->qu_sf_idx[i]);
259             return AVERROR_INVALIDDATA;
260         }
261     }
262
263     return 0;
264 }
265
266 /**
267  * Unpack vector quantization tables.
268  *
269  * @param[in]    start_val    start value for the unpacked table
270  * @param[in]    shape_vec    ptr to table to unpack
271  * @param[out]   dst          ptr to output array
272  * @param[in]    num_values   number of values to unpack
273  */
274 static inline void unpack_vq_shape(int start_val, const int8_t *shape_vec,
275                                    int *dst, int num_values)
276 {
277     int i;
278
279     if (num_values) {
280         dst[0] = dst[1] = dst[2] = start_val;
281         for (i = 3; i < num_values; i++)
282             dst[i] = start_val - shape_vec[atrac3p_qu_num_to_seg[i] - 1];
283     }
284 }
285
286 #define UNPACK_SF_VQ_SHAPE(gb, dst, num_vals)                            \
287     start_val = get_bits((gb), 6);                                       \
288     unpack_vq_shape(start_val, &atrac3p_sf_shapes[get_bits((gb), 6)][0], \
289                     (dst), (num_vals))
290
291 /**
292  * Decode word length for each quantization unit of a channel.
293  *
294  * @param[in]     gb            the GetBit context
295  * @param[in,out] ctx           ptr to the channel unit context
296  * @param[in]     ch_num        channel to process
297  * @param[in]     avctx         ptr to the AVCodecContext
298  * @return result code: 0 = OK, otherwise - error code
299  */
300 static int decode_channel_wordlen(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
301                                   int ch_num, AVCodecContext *avctx)
302 {
303     int i, weight_idx = 0, delta, diff, pos, delta_bits, min_val, flag,
304         ret, start_val;
305     VLC *vlc_tab;
306     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
307     Atrac3pChanParams *ref_chan = &ctx->channels[0];
308
309     chan->fill_mode = 0;
310
311     switch (get_bits(gb, 2)) { /* switch according to coding mode */
312     case 0: /* coded using constant number of bits */
313         for (i = 0; i < ctx->num_quant_units; i++)
314             chan->qu_wordlen[i] = get_bits(gb, 3);
315         break;
316     case 1:
317         if (ch_num) {
318             if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
319                 return ret;
320
321             if (chan->num_coded_vals) {
322                 vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
323
324                 for (i = 0; i < chan->num_coded_vals; i++) {
325                     delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
326                     chan->qu_wordlen[i] = (ref_chan->qu_wordlen[i] + delta) & 7;
327                 }
328             }
329         } else {
330             weight_idx = get_bits(gb, 2);
331             if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
332                 return ret;
333
334             if (chan->num_coded_vals) {
335                 pos = get_bits(gb, 5);
336                 if (pos > chan->num_coded_vals) {
337                     av_log(avctx, AV_LOG_ERROR,
338                            "WL mode 1: invalid position!\n");
339                     return AVERROR_INVALIDDATA;
340                 }
341
342                 delta_bits = get_bits(gb, 2);
343                 min_val    = get_bits(gb, 3);
344
345                 for (i = 0; i < pos; i++)
346                     chan->qu_wordlen[i] = get_bits(gb, 3);
347
348                 for (i = pos; i < chan->num_coded_vals; i++)
349                     chan->qu_wordlen[i] = (min_val + get_bitsz(gb, delta_bits)) & 7;
350             }
351         }
352         break;
353     case 2:
354         if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
355             return ret;
356
357         if (ch_num && chan->num_coded_vals) {
358             vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
359             delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
360             chan->qu_wordlen[0] = (ref_chan->qu_wordlen[0] + delta) & 7;
361
362             for (i = 1; i < chan->num_coded_vals; i++) {
363                 diff = ref_chan->qu_wordlen[i] - ref_chan->qu_wordlen[i - 1];
364                 delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
365                 chan->qu_wordlen[i] = (chan->qu_wordlen[i - 1] + diff + delta) & 7;
366             }
367         } else if (chan->num_coded_vals) {
368             flag    = get_bits(gb, 1);
369             vlc_tab = &wl_vlc_tabs[get_bits(gb, 1)];
370
371             start_val = get_bits(gb, 3);
372             unpack_vq_shape(start_val,
373                             &atrac3p_wl_shapes[start_val][get_bits(gb, 4)][0],
374                             chan->qu_wordlen, chan->num_coded_vals);
375
376             if (!flag) {
377                 for (i = 0; i < chan->num_coded_vals; i++) {
378                     delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
379                     chan->qu_wordlen[i] = (chan->qu_wordlen[i] + delta) & 7;
380                 }
381             } else {
382                 for (i = 0; i < (chan->num_coded_vals & - 2); i += 2)
383                     if (!get_bits1(gb)) {
384                         chan->qu_wordlen[i]     = (chan->qu_wordlen[i] +
385                                                    get_vlc2(gb, vlc_tab->table,
386                                                             vlc_tab->bits, 1)) & 7;
387                         chan->qu_wordlen[i + 1] = (chan->qu_wordlen[i + 1] +
388                                                    get_vlc2(gb, vlc_tab->table,
389                                                             vlc_tab->bits, 1)) & 7;
390                     }
391
392                 if (chan->num_coded_vals & 1)
393                     chan->qu_wordlen[i] = (chan->qu_wordlen[i] +
394                                            get_vlc2(gb, vlc_tab->table,
395                                                     vlc_tab->bits, 1)) & 7;
396             }
397         }
398         break;
399     case 3:
400         weight_idx = get_bits(gb, 2);
401         if ((ret = num_coded_units(gb, chan, ctx, avctx)) < 0)
402             return ret;
403
404         if (chan->num_coded_vals) {
405             vlc_tab = &wl_vlc_tabs[get_bits(gb, 2)];
406
407             /* first coefficient is coded directly */
408             chan->qu_wordlen[0] = get_bits(gb, 3);
409
410             for (i = 1; i < chan->num_coded_vals; i++) {
411                 delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
412                 chan->qu_wordlen[i] = (chan->qu_wordlen[i - 1] + delta) & 7;
413             }
414         }
415         break;
416     }
417
418     if (chan->fill_mode == 2) {
419         for (i = chan->num_coded_vals; i < ctx->num_quant_units; i++)
420             chan->qu_wordlen[i] = ch_num ? get_bits1(gb) : 1;
421     } else if (chan->fill_mode == 3) {
422         pos = ch_num ? chan->num_coded_vals + chan->split_point
423                      : ctx->num_quant_units - chan->split_point;
424         if (pos > FF_ARRAY_ELEMS(chan->qu_wordlen)) {
425             av_log(avctx, AV_LOG_ERROR, "Split point beyond array\n");
426             pos = FF_ARRAY_ELEMS(chan->qu_wordlen);
427         }
428         for (i = chan->num_coded_vals; i < pos; i++)
429             chan->qu_wordlen[i] = 1;
430     }
431
432     if (weight_idx)
433         return add_wordlen_weights(ctx, chan, weight_idx, avctx);
434
435     return 0;
436 }
437
438 /**
439  * Decode scale factor indexes for each quant unit of a channel.
440  *
441  * @param[in]     gb            the GetBit context
442  * @param[in,out] ctx           ptr to the channel unit context
443  * @param[in]     ch_num        channel to process
444  * @param[in]     avctx         ptr to the AVCodecContext
445  * @return result code: 0 = OK, otherwise - error code
446  */
447 static int decode_channel_sf_idx(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
448                                  int ch_num, AVCodecContext *avctx)
449 {
450     int i, weight_idx = 0, delta, diff, num_long_vals,
451         delta_bits, min_val, vlc_sel, start_val;
452     VLC *vlc_tab;
453     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
454     Atrac3pChanParams *ref_chan = &ctx->channels[0];
455
456     switch (get_bits(gb, 2)) { /* switch according to coding mode */
457     case 0: /* coded using constant number of bits */
458         for (i = 0; i < ctx->used_quant_units; i++)
459             chan->qu_sf_idx[i] = get_bits(gb, 6);
460         break;
461     case 1:
462         if (ch_num) {
463             vlc_tab = &sf_vlc_tabs[get_bits(gb, 2)];
464
465             for (i = 0; i < ctx->used_quant_units; i++) {
466                 delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
467                 chan->qu_sf_idx[i] = (ref_chan->qu_sf_idx[i] + delta) & 0x3F;
468             }
469         } else {
470             weight_idx = get_bits(gb, 2);
471             if (weight_idx == 3) {
472                 UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
473
474                 num_long_vals = get_bits(gb, 5);
475                 delta_bits    = get_bits(gb, 2);
476                 min_val       = get_bits(gb, 4) - 7;
477
478                 for (i = 0; i < num_long_vals; i++)
479                     chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] +
480                                           get_bits(gb, 4) - 7) & 0x3F;
481
482                 /* all others are: min_val + delta */
483                 for (i = num_long_vals; i < ctx->used_quant_units; i++)
484                     chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] + min_val +
485                                           get_bitsz(gb, delta_bits)) & 0x3F;
486             } else {
487                 num_long_vals = get_bits(gb, 5);
488                 delta_bits    = get_bits(gb, 3);
489                 min_val       = get_bits(gb, 6);
490                 if (num_long_vals > ctx->used_quant_units || delta_bits == 7) {
491                     av_log(avctx, AV_LOG_ERROR,
492                            "SF mode 1: invalid parameters!\n");
493                     return AVERROR_INVALIDDATA;
494                 }
495
496                 /* read full-precision SF indexes */
497                 for (i = 0; i < num_long_vals; i++)
498                     chan->qu_sf_idx[i] = get_bits(gb, 6);
499
500                 /* all others are: min_val + delta */
501                 for (i = num_long_vals; i < ctx->used_quant_units; i++)
502                     chan->qu_sf_idx[i] = (min_val +
503                                           get_bitsz(gb, delta_bits)) & 0x3F;
504             }
505         }
506         break;
507     case 2:
508         if (ch_num) {
509             vlc_tab = &sf_vlc_tabs[get_bits(gb, 2)];
510
511             delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
512             chan->qu_sf_idx[0] = (ref_chan->qu_sf_idx[0] + delta) & 0x3F;
513
514             for (i = 1; i < ctx->used_quant_units; i++) {
515                 diff  = ref_chan->qu_sf_idx[i] - ref_chan->qu_sf_idx[i - 1];
516                 delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
517                 chan->qu_sf_idx[i] = (chan->qu_sf_idx[i - 1] + diff + delta) & 0x3F;
518             }
519         } else {
520             vlc_tab = &sf_vlc_tabs[get_bits(gb, 2) + 4];
521
522             UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
523
524             for (i = 0; i < ctx->used_quant_units; i++) {
525                 delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
526                 chan->qu_sf_idx[i] = (chan->qu_sf_idx[i] +
527                                       sign_extend(delta, 4)) & 0x3F;
528             }
529         }
530         break;
531     case 3:
532         if (ch_num) {
533             /* copy coefficients from reference channel */
534             for (i = 0; i < ctx->used_quant_units; i++)
535                 chan->qu_sf_idx[i] = ref_chan->qu_sf_idx[i];
536         } else {
537             weight_idx = get_bits(gb, 2);
538             vlc_sel    = get_bits(gb, 2);
539             vlc_tab    = &sf_vlc_tabs[vlc_sel];
540
541             if (weight_idx == 3) {
542                 vlc_tab = &sf_vlc_tabs[vlc_sel + 4];
543
544                 UNPACK_SF_VQ_SHAPE(gb, chan->qu_sf_idx, ctx->used_quant_units);
545
546                 diff               = (get_bits(gb, 4)    + 56)   & 0x3F;
547                 chan->qu_sf_idx[0] = (chan->qu_sf_idx[0] + diff) & 0x3F;
548
549                 for (i = 1; i < ctx->used_quant_units; i++) {
550                     delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
551                     diff               = (diff + sign_extend(delta, 4)) & 0x3F;
552                     chan->qu_sf_idx[i] = (diff + chan->qu_sf_idx[i])    & 0x3F;
553                 }
554             } else {
555                 /* 1st coefficient is coded directly */
556                 chan->qu_sf_idx[0] = get_bits(gb, 6);
557
558                 for (i = 1; i < ctx->used_quant_units; i++) {
559                     delta = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
560                     chan->qu_sf_idx[i] = (chan->qu_sf_idx[i - 1] + delta) & 0x3F;
561                 }
562             }
563         }
564         break;
565     }
566
567     if (weight_idx && weight_idx < 3)
568         return subtract_sf_weights(ctx, chan, weight_idx, avctx);
569
570     return 0;
571 }
572
573 /**
574  * Decode word length information for each channel.
575  *
576  * @param[in]     gb            the GetBit context
577  * @param[in,out] ctx           ptr to the channel unit context
578  * @param[in]     num_channels  number of channels to process
579  * @param[in]     avctx         ptr to the AVCodecContext
580  * @return result code: 0 = OK, otherwise - error code
581  */
582 static int decode_quant_wordlen(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
583                                 int num_channels, AVCodecContext *avctx)
584 {
585     int ch_num, i, ret;
586
587     for (ch_num = 0; ch_num < num_channels; ch_num++) {
588         memset(ctx->channels[ch_num].qu_wordlen, 0,
589                sizeof(ctx->channels[ch_num].qu_wordlen));
590
591         if ((ret = decode_channel_wordlen(gb, ctx, ch_num, avctx)) < 0)
592             return ret;
593     }
594
595     /* scan for last non-zero coeff in both channels and
596      * set number of quant units having coded spectrum */
597     for (i = ctx->num_quant_units - 1; i >= 0; i--)
598         if (ctx->channels[0].qu_wordlen[i] ||
599             (num_channels == 2 && ctx->channels[1].qu_wordlen[i]))
600             break;
601     ctx->used_quant_units = i + 1;
602
603     return 0;
604 }
605
606 /**
607  * Decode scale factor indexes for each channel.
608  *
609  * @param[in]     gb            the GetBit context
610  * @param[in,out] ctx           ptr to the channel unit context
611  * @param[in]     num_channels  number of channels to process
612  * @param[in]     avctx         ptr to the AVCodecContext
613  * @return result code: 0 = OK, otherwise - error code
614  */
615 static int decode_scale_factors(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
616                                 int num_channels, AVCodecContext *avctx)
617 {
618     int ch_num, ret;
619
620     if (!ctx->used_quant_units)
621         return 0;
622
623     for (ch_num = 0; ch_num < num_channels; ch_num++) {
624         memset(ctx->channels[ch_num].qu_sf_idx, 0,
625                sizeof(ctx->channels[ch_num].qu_sf_idx));
626
627         if ((ret = decode_channel_sf_idx(gb, ctx, ch_num, avctx)) < 0)
628             return ret;
629     }
630
631     return 0;
632 }
633
634 /**
635  * Decode number of code table values.
636  *
637  * @param[in]     gb            the GetBit context
638  * @param[in,out] ctx           ptr to the channel unit context
639  * @param[in]     avctx         ptr to the AVCodecContext
640  * @return result code: 0 = OK, otherwise - error code
641  */
642 static int get_num_ct_values(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
643                              AVCodecContext *avctx)
644 {
645     int num_coded_vals;
646
647     if (get_bits1(gb)) {
648         num_coded_vals = get_bits(gb, 5);
649         if (num_coded_vals > ctx->used_quant_units) {
650             av_log(avctx, AV_LOG_ERROR,
651                    "Invalid number of code table indexes: %d!\n", num_coded_vals);
652             return AVERROR_INVALIDDATA;
653         }
654         return num_coded_vals;
655     } else
656         return ctx->used_quant_units;
657 }
658
659 #define DEC_CT_IDX_COMMON(OP)                                           \
660     num_vals = get_num_ct_values(gb, ctx, avctx);                       \
661     if (num_vals < 0)                                                   \
662         return num_vals;                                                \
663                                                                         \
664     for (i = 0; i < num_vals; i++) {                                    \
665         if (chan->qu_wordlen[i]) {                                      \
666             chan->qu_tab_idx[i] = OP;                                   \
667         } else if (ch_num && ref_chan->qu_wordlen[i])                   \
668             /* get clone master flag */                                 \
669             chan->qu_tab_idx[i] = get_bits1(gb);                        \
670     }
671
672 #define CODING_DIRECT get_bits(gb, num_bits)
673
674 #define CODING_VLC get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1)
675
676 #define CODING_VLC_DELTA                                                \
677     (!i) ? CODING_VLC                                                   \
678          : (pred + get_vlc2(gb, delta_vlc->table,                       \
679                             delta_vlc->bits, 1)) & mask;                \
680     pred = chan->qu_tab_idx[i]
681
682 #define CODING_VLC_DIFF                                                 \
683     (ref_chan->qu_tab_idx[i] +                                          \
684      get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1)) & mask
685
686 /**
687  * Decode code table indexes for each quant unit of a channel.
688  *
689  * @param[in]     gb            the GetBit context
690  * @param[in,out] ctx           ptr to the channel unit context
691  * @param[in]     ch_num        channel to process
692  * @param[in]     avctx         ptr to the AVCodecContext
693  * @return result code: 0 = OK, otherwise - error code
694  */
695 static int decode_channel_code_tab(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
696                                    int ch_num, AVCodecContext *avctx)
697 {
698     int i, num_vals, num_bits, pred;
699     int mask = ctx->use_full_table ? 7 : 3; /* mask for modular arithmetic */
700     VLC *vlc_tab, *delta_vlc;
701     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
702     Atrac3pChanParams *ref_chan = &ctx->channels[0];
703
704     chan->table_type = get_bits1(gb);
705
706     switch (get_bits(gb, 2)) { /* switch according to coding mode */
707     case 0: /* directly coded */
708         num_bits = ctx->use_full_table + 2;
709         DEC_CT_IDX_COMMON(CODING_DIRECT);
710         break;
711     case 1: /* entropy-coded */
712         vlc_tab = ctx->use_full_table ? &ct_vlc_tabs[1]
713                                       : ct_vlc_tabs;
714         DEC_CT_IDX_COMMON(CODING_VLC);
715         break;
716     case 2: /* entropy-coded delta */
717         if (ctx->use_full_table) {
718             vlc_tab   = &ct_vlc_tabs[1];
719             delta_vlc = &ct_vlc_tabs[2];
720         } else {
721             vlc_tab   = ct_vlc_tabs;
722             delta_vlc = ct_vlc_tabs;
723         }
724         pred = 0;
725         DEC_CT_IDX_COMMON(CODING_VLC_DELTA);
726         break;
727     case 3: /* entropy-coded difference to master */
728         if (ch_num) {
729             vlc_tab = ctx->use_full_table ? &ct_vlc_tabs[3]
730                                           : ct_vlc_tabs;
731             DEC_CT_IDX_COMMON(CODING_VLC_DIFF);
732         }
733         break;
734     }
735
736     return 0;
737 }
738
739 /**
740  * Decode code table indexes for each channel.
741  *
742  * @param[in]     gb            the GetBit context
743  * @param[in,out] ctx           ptr to the channel unit context
744  * @param[in]     num_channels  number of channels to process
745  * @param[in]     avctx         ptr to the AVCodecContext
746  * @return result code: 0 = OK, otherwise - error code
747  */
748 static int decode_code_table_indexes(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
749                                      int num_channels, AVCodecContext *avctx)
750 {
751     int ch_num, ret;
752
753     if (!ctx->used_quant_units)
754         return 0;
755
756     ctx->use_full_table = get_bits1(gb);
757
758     for (ch_num = 0; ch_num < num_channels; ch_num++) {
759         memset(ctx->channels[ch_num].qu_tab_idx, 0,
760                sizeof(ctx->channels[ch_num].qu_tab_idx));
761
762         if ((ret = decode_channel_code_tab(gb, ctx, ch_num, avctx)) < 0)
763             return ret;
764     }
765
766     return 0;
767 }
768
769 /**
770  * Decode huffman-coded spectral lines for a given quant unit.
771  *
772  * This is a generalized version for all known coding modes.
773  * Its speed can be improved by creating separate functions for each mode.
774  *
775  * @param[in]   gb          the GetBit context
776  * @param[in]   tab         code table telling how to decode spectral lines
777  * @param[in]   vlc_tab     ptr to the huffman table associated with the code table
778  * @param[out]  out         pointer to buffer where decoded data should be stored
779  * @param[in]   num_specs   number of spectral lines to decode
780  */
781 static void decode_qu_spectra(GetBitContext *gb, const Atrac3pSpecCodeTab *tab,
782                               VLC *vlc_tab, int16_t *out, const int num_specs)
783 {
784     int i, j, pos, cf;
785     int group_size = tab->group_size;
786     int num_coeffs = tab->num_coeffs;
787     int bits       = tab->bits;
788     int is_signed  = tab->is_signed;
789     unsigned val;
790
791     for (pos = 0; pos < num_specs;) {
792         if (group_size == 1 || get_bits1(gb)) {
793             for (j = 0; j < group_size; j++) {
794                 val = get_vlc2(gb, vlc_tab->table, vlc_tab->bits, 1);
795
796                 for (i = 0; i < num_coeffs; i++) {
797                     cf = av_mod_uintp2(val, bits);
798                     if (is_signed)
799                         cf = sign_extend(cf, bits);
800                     else if (cf && get_bits1(gb))
801                         cf = -cf;
802
803                     out[pos++] = cf;
804                     val      >>= bits;
805                 }
806             }
807         } else /* group skipped */
808             pos += group_size * num_coeffs;
809     }
810 }
811
812 /**
813  * Decode huffman-coded IMDCT spectrum for all channels.
814  *
815  * @param[in]     gb            the GetBit context
816  * @param[in,out] ctx           ptr to the channel unit context
817  * @param[in]     num_channels  number of channels to process
818  * @param[in]     avctx         ptr to the AVCodecContext
819  */
820 static void decode_spectrum(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
821                             int num_channels, AVCodecContext *avctx)
822 {
823     int i, ch_num, qu, wordlen, codetab, tab_index, num_specs;
824     const Atrac3pSpecCodeTab *tab;
825     Atrac3pChanParams *chan;
826
827     for (ch_num = 0; ch_num < num_channels; ch_num++) {
828         chan = &ctx->channels[ch_num];
829
830         memset(chan->spectrum, 0, sizeof(chan->spectrum));
831
832         /* set power compensation level to disabled */
833         memset(chan->power_levs, ATRAC3P_POWER_COMP_OFF, sizeof(chan->power_levs));
834
835         for (qu = 0; qu < ctx->used_quant_units; qu++) {
836             num_specs = ff_atrac3p_qu_to_spec_pos[qu + 1] -
837                         ff_atrac3p_qu_to_spec_pos[qu];
838
839             wordlen = chan->qu_wordlen[qu];
840             codetab = chan->qu_tab_idx[qu];
841             if (wordlen) {
842                 if (!ctx->use_full_table)
843                     codetab = atrac3p_ct_restricted_to_full[chan->table_type][wordlen - 1][codetab];
844
845                 tab_index = (chan->table_type * 8 + codetab) * 7 + wordlen - 1;
846                 tab       = &atrac3p_spectra_tabs[tab_index];
847
848                 decode_qu_spectra(gb, tab, &spec_vlc_tabs[tab_index],
849                                   &chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
850                                   num_specs);
851             } else if (ch_num && ctx->channels[0].qu_wordlen[qu] && !codetab) {
852                 /* copy coefficients from master */
853                 memcpy(&chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
854                        &ctx->channels[0].spectrum[ff_atrac3p_qu_to_spec_pos[qu]],
855                        num_specs *
856                        sizeof(chan->spectrum[ff_atrac3p_qu_to_spec_pos[qu]]));
857                 chan->qu_wordlen[qu] = ctx->channels[0].qu_wordlen[qu];
858             }
859         }
860
861         /* Power compensation levels only present in the bitstream
862          * if there are more than 2 quant units. The lowest two units
863          * correspond to the frequencies 0...351 Hz, whose shouldn't
864          * be affected by the power compensation. */
865         if (ctx->used_quant_units > 2) {
866             num_specs = atrac3p_subband_to_num_powgrps[ctx->num_coded_subbands - 1];
867             for (i = 0; i < num_specs; i++)
868                 chan->power_levs[i] = get_bits(gb, 4);
869         }
870     }
871 }
872
873 /**
874  * Retrieve specified amount of flag bits from the input bitstream.
875  * The data can be shortened in the case of the following two common conditions:
876  * if all bits are zero then only one signal bit = 0 will be stored,
877  * if all bits are ones then two signal bits = 1,0 will be stored.
878  * Otherwise, all necessary bits will be directly stored
879  * prefixed by two signal bits = 1,1.
880  *
881  * @param[in]   gb              ptr to the GetBitContext
882  * @param[out]  out             where to place decoded flags
883  * @param[in]   num_flags       number of flags to process
884  * @return: 0 = all flag bits are zero, 1 = there is at least one non-zero flag bit
885  */
886 static int get_subband_flags(GetBitContext *gb, uint8_t *out, int num_flags)
887 {
888     int i, result;
889
890     memset(out, 0, num_flags);
891
892     result = get_bits1(gb);
893     if (result) {
894         if (get_bits1(gb))
895             for (i = 0; i < num_flags; i++)
896                 out[i] = get_bits1(gb);
897         else
898             memset(out, 1, num_flags);
899     }
900
901     return result;
902 }
903
904 /**
905  * Decode mdct window shape flags for all channels.
906  *
907  * @param[in]     gb            the GetBit context
908  * @param[in,out] ctx           ptr to the channel unit context
909  * @param[in]     num_channels  number of channels to process
910  */
911 static void decode_window_shape(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
912                                 int num_channels)
913 {
914     int ch_num;
915
916     for (ch_num = 0; ch_num < num_channels; ch_num++)
917         get_subband_flags(gb, ctx->channels[ch_num].wnd_shape,
918                           ctx->num_subbands);
919 }
920
921 /**
922  * Decode number of gain control points.
923  *
924  * @param[in]     gb              the GetBit context
925  * @param[in,out] ctx             ptr to the channel unit context
926  * @param[in]     ch_num          channel to process
927  * @param[in]     coded_subbands  number of subbands to process
928  * @return result code: 0 = OK, otherwise - error code
929  */
930 static int decode_gainc_npoints(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
931                                 int ch_num, int coded_subbands)
932 {
933     int i, delta, delta_bits, min_val;
934     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
935     Atrac3pChanParams *ref_chan = &ctx->channels[0];
936
937     switch (get_bits(gb, 2)) { /* switch according to coding mode */
938     case 0: /* fixed-length coding */
939         for (i = 0; i < coded_subbands; i++)
940             chan->gain_data[i].num_points = get_bits(gb, 3);
941         break;
942     case 1: /* variable-length coding */
943         for (i = 0; i < coded_subbands; i++)
944             chan->gain_data[i].num_points =
945                 get_vlc2(gb, gain_vlc_tabs[0].table,
946                          gain_vlc_tabs[0].bits, 1);
947         break;
948     case 2:
949         if (ch_num) { /* VLC modulo delta to master channel */
950             for (i = 0; i < coded_subbands; i++) {
951                 delta = get_vlc2(gb, gain_vlc_tabs[1].table,
952                                  gain_vlc_tabs[1].bits, 1);
953                 chan->gain_data[i].num_points =
954                     (ref_chan->gain_data[i].num_points + delta) & 7;
955             }
956         } else { /* VLC modulo delta to previous */
957             chan->gain_data[0].num_points =
958                 get_vlc2(gb, gain_vlc_tabs[0].table,
959                          gain_vlc_tabs[0].bits, 1);
960
961             for (i = 1; i < coded_subbands; i++) {
962                 delta = get_vlc2(gb, gain_vlc_tabs[1].table,
963                                  gain_vlc_tabs[1].bits, 1);
964                 chan->gain_data[i].num_points =
965                     (chan->gain_data[i - 1].num_points + delta) & 7;
966             }
967         }
968         break;
969     case 3:
970         if (ch_num) { /* copy data from master channel */
971             for (i = 0; i < coded_subbands; i++)
972                 chan->gain_data[i].num_points =
973                     ref_chan->gain_data[i].num_points;
974         } else { /* shorter delta to min */
975             delta_bits = get_bits(gb, 2);
976             min_val    = get_bits(gb, 3);
977
978             for (i = 0; i < coded_subbands; i++) {
979                 chan->gain_data[i].num_points = min_val + get_bitsz(gb, delta_bits);
980                 if (chan->gain_data[i].num_points > 7)
981                     return AVERROR_INVALIDDATA;
982             }
983         }
984     }
985
986     return 0;
987 }
988
989 /**
990  * Implements coding mode 3 (slave) for gain compensation levels.
991  *
992  * @param[out]   dst   ptr to the output array
993  * @param[in]    ref   ptr to the reference channel
994  */
995 static inline void gainc_level_mode3s(AtracGainInfo *dst, AtracGainInfo *ref)
996 {
997     int i;
998
999     for (i = 0; i < dst->num_points; i++)
1000         dst->lev_code[i] = (i >= ref->num_points) ? 7 : ref->lev_code[i];
1001 }
1002
1003 /**
1004  * Implements coding mode 1 (master) for gain compensation levels.
1005  *
1006  * @param[in]     gb     the GetBit context
1007  * @param[in]     ctx    ptr to the channel unit context
1008  * @param[out]    dst    ptr to the output array
1009  */
1010 static inline void gainc_level_mode1m(GetBitContext *gb,
1011                                       Atrac3pChanUnitCtx *ctx,
1012                                       AtracGainInfo *dst)
1013 {
1014     int i, delta;
1015
1016     if (dst->num_points > 0)
1017         dst->lev_code[0] = get_vlc2(gb, gain_vlc_tabs[2].table,
1018                                     gain_vlc_tabs[2].bits, 1);
1019
1020     for (i = 1; i < dst->num_points; i++) {
1021         delta = get_vlc2(gb, gain_vlc_tabs[3].table,
1022                          gain_vlc_tabs[3].bits, 1);
1023         dst->lev_code[i] = (dst->lev_code[i - 1] + delta) & 0xF;
1024     }
1025 }
1026
1027 /**
1028  * Decode level code for each gain control point.
1029  *
1030  * @param[in]     gb              the GetBit context
1031  * @param[in,out] ctx             ptr to the channel unit context
1032  * @param[in]     ch_num          channel to process
1033  * @param[in]     coded_subbands  number of subbands to process
1034  * @return result code: 0 = OK, otherwise - error code
1035  */
1036 static int decode_gainc_levels(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1037                                int ch_num, int coded_subbands)
1038 {
1039     int sb, i, delta, delta_bits, min_val, pred;
1040     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
1041     Atrac3pChanParams *ref_chan = &ctx->channels[0];
1042
1043     switch (get_bits(gb, 2)) { /* switch according to coding mode */
1044     case 0: /* fixed-length coding */
1045         for (sb = 0; sb < coded_subbands; sb++)
1046             for (i = 0; i < chan->gain_data[sb].num_points; i++)
1047                 chan->gain_data[sb].lev_code[i] = get_bits(gb, 4);
1048         break;
1049     case 1:
1050         if (ch_num) { /* VLC modulo delta to master channel */
1051             for (sb = 0; sb < coded_subbands; sb++)
1052                 for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1053                     delta = get_vlc2(gb, gain_vlc_tabs[5].table,
1054                                      gain_vlc_tabs[5].bits, 1);
1055                     pred = (i >= ref_chan->gain_data[sb].num_points)
1056                            ? 7 : ref_chan->gain_data[sb].lev_code[i];
1057                     chan->gain_data[sb].lev_code[i] = (pred + delta) & 0xF;
1058                 }
1059         } else { /* VLC modulo delta to previous */
1060             for (sb = 0; sb < coded_subbands; sb++)
1061                 gainc_level_mode1m(gb, ctx, &chan->gain_data[sb]);
1062         }
1063         break;
1064     case 2:
1065         if (ch_num) { /* VLC modulo delta to previous or clone master */
1066             for (sb = 0; sb < coded_subbands; sb++)
1067                 if (chan->gain_data[sb].num_points > 0) {
1068                     if (get_bits1(gb))
1069                         gainc_level_mode1m(gb, ctx, &chan->gain_data[sb]);
1070                     else
1071                         gainc_level_mode3s(&chan->gain_data[sb],
1072                                            &ref_chan->gain_data[sb]);
1073                 }
1074         } else { /* VLC modulo delta to lev_codes of previous subband */
1075             if (chan->gain_data[0].num_points > 0)
1076                 gainc_level_mode1m(gb, ctx, &chan->gain_data[0]);
1077
1078             for (sb = 1; sb < coded_subbands; sb++)
1079                 for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1080                     delta = get_vlc2(gb, gain_vlc_tabs[4].table,
1081                                      gain_vlc_tabs[4].bits, 1);
1082                     pred = (i >= chan->gain_data[sb - 1].num_points)
1083                            ? 7 : chan->gain_data[sb - 1].lev_code[i];
1084                     chan->gain_data[sb].lev_code[i] = (pred + delta) & 0xF;
1085                 }
1086         }
1087         break;
1088     case 3:
1089         if (ch_num) { /* clone master */
1090             for (sb = 0; sb < coded_subbands; sb++)
1091                 gainc_level_mode3s(&chan->gain_data[sb],
1092                                    &ref_chan->gain_data[sb]);
1093         } else { /* shorter delta to min */
1094             delta_bits = get_bits(gb, 2);
1095             min_val    = get_bits(gb, 4);
1096
1097             for (sb = 0; sb < coded_subbands; sb++)
1098                 for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1099                     chan->gain_data[sb].lev_code[i] = min_val + get_bitsz(gb, delta_bits);
1100                     if (chan->gain_data[sb].lev_code[i] > 15)
1101                         return AVERROR_INVALIDDATA;
1102                 }
1103         }
1104         break;
1105     }
1106
1107     return 0;
1108 }
1109
1110 /**
1111  * Implements coding mode 0 for gain compensation locations.
1112  *
1113  * @param[in]     gb     the GetBit context
1114  * @param[in]     ctx    ptr to the channel unit context
1115  * @param[out]    dst    ptr to the output array
1116  * @param[in]     pos    position of the value to be processed
1117  */
1118 static inline void gainc_loc_mode0(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1119                                    AtracGainInfo *dst, int pos)
1120 {
1121     int delta_bits;
1122
1123     if (!pos || dst->loc_code[pos - 1] < 15)
1124         dst->loc_code[pos] = get_bits(gb, 5);
1125     else if (dst->loc_code[pos - 1] >= 30)
1126         dst->loc_code[pos] = 31;
1127     else {
1128         delta_bits         = av_log2(30 - dst->loc_code[pos - 1]) + 1;
1129         dst->loc_code[pos] = dst->loc_code[pos - 1] +
1130                              get_bits(gb, delta_bits) + 1;
1131     }
1132 }
1133
1134 /**
1135  * Implements coding mode 1 for gain compensation locations.
1136  *
1137  * @param[in]     gb     the GetBit context
1138  * @param[in]     ctx    ptr to the channel unit context
1139  * @param[out]    dst    ptr to the output array
1140  */
1141 static inline void gainc_loc_mode1(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1142                                    AtracGainInfo *dst)
1143 {
1144     int i;
1145     VLC *tab;
1146
1147     if (dst->num_points > 0) {
1148         /* 1st coefficient is stored directly */
1149         dst->loc_code[0] = get_bits(gb, 5);
1150
1151         for (i = 1; i < dst->num_points; i++) {
1152             /* switch VLC according to the curve direction
1153              * (ascending/descending) */
1154             tab              = (dst->lev_code[i] <= dst->lev_code[i - 1])
1155                                ? &gain_vlc_tabs[7]
1156                                : &gain_vlc_tabs[9];
1157             dst->loc_code[i] = dst->loc_code[i - 1] +
1158                                get_vlc2(gb, tab->table, tab->bits, 1);
1159         }
1160     }
1161 }
1162
1163 /**
1164  * Decode location code for each gain control point.
1165  *
1166  * @param[in]     gb              the GetBit context
1167  * @param[in,out] ctx             ptr to the channel unit context
1168  * @param[in]     ch_num          channel to process
1169  * @param[in]     coded_subbands  number of subbands to process
1170  * @param[in]     avctx           ptr to the AVCodecContext
1171  * @return result code: 0 = OK, otherwise - error code
1172  */
1173 static int decode_gainc_loc_codes(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1174                                   int ch_num, int coded_subbands,
1175                                   AVCodecContext *avctx)
1176 {
1177     int sb, i, delta, delta_bits, min_val, pred, more_than_ref;
1178     AtracGainInfo *dst, *ref;
1179     VLC *tab;
1180     Atrac3pChanParams *chan     = &ctx->channels[ch_num];
1181     Atrac3pChanParams *ref_chan = &ctx->channels[0];
1182
1183     switch (get_bits(gb, 2)) { /* switch according to coding mode */
1184     case 0: /* sequence of numbers in ascending order */
1185         for (sb = 0; sb < coded_subbands; sb++)
1186             for (i = 0; i < chan->gain_data[sb].num_points; i++)
1187                 gainc_loc_mode0(gb, ctx, &chan->gain_data[sb], i);
1188         break;
1189     case 1:
1190         if (ch_num) {
1191             for (sb = 0; sb < coded_subbands; sb++) {
1192                 if (chan->gain_data[sb].num_points <= 0)
1193                     continue;
1194                 dst = &chan->gain_data[sb];
1195                 ref = &ref_chan->gain_data[sb];
1196
1197                 /* 1st value is vlc-coded modulo delta to master */
1198                 delta = get_vlc2(gb, gain_vlc_tabs[10].table,
1199                                  gain_vlc_tabs[10].bits, 1);
1200                 pred = ref->num_points > 0 ? ref->loc_code[0] : 0;
1201                 dst->loc_code[0] = (pred + delta) & 0x1F;
1202
1203                 for (i = 1; i < dst->num_points; i++) {
1204                     more_than_ref = i >= ref->num_points;
1205                     if (dst->lev_code[i] > dst->lev_code[i - 1]) {
1206                         /* ascending curve */
1207                         if (more_than_ref) {
1208                             delta =
1209                                 get_vlc2(gb, gain_vlc_tabs[9].table,
1210                                          gain_vlc_tabs[9].bits, 1);
1211                             dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1212                         } else {
1213                             if (get_bits1(gb))
1214                                 gainc_loc_mode0(gb, ctx, dst, i);  // direct coding
1215                             else
1216                                 dst->loc_code[i] = ref->loc_code[i];  // clone master
1217                         }
1218                     } else { /* descending curve */
1219                         tab   = more_than_ref ? &gain_vlc_tabs[7]
1220                                               : &gain_vlc_tabs[10];
1221                         delta = get_vlc2(gb, tab->table, tab->bits, 1);
1222                         if (more_than_ref)
1223                             dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1224                         else
1225                             dst->loc_code[i] = (ref->loc_code[i] + delta) & 0x1F;
1226                     }
1227                 }
1228             }
1229         } else /* VLC delta to previous */
1230             for (sb = 0; sb < coded_subbands; sb++)
1231                 gainc_loc_mode1(gb, ctx, &chan->gain_data[sb]);
1232         break;
1233     case 2:
1234         if (ch_num) {
1235             for (sb = 0; sb < coded_subbands; sb++) {
1236                 if (chan->gain_data[sb].num_points <= 0)
1237                     continue;
1238                 dst = &chan->gain_data[sb];
1239                 ref = &ref_chan->gain_data[sb];
1240                 if (dst->num_points > ref->num_points || get_bits1(gb))
1241                     gainc_loc_mode1(gb, ctx, dst);
1242                 else /* clone master for the whole subband */
1243                     for (i = 0; i < chan->gain_data[sb].num_points; i++)
1244                         dst->loc_code[i] = ref->loc_code[i];
1245             }
1246         } else {
1247             /* data for the first subband is coded directly */
1248             for (i = 0; i < chan->gain_data[0].num_points; i++)
1249                 gainc_loc_mode0(gb, ctx, &chan->gain_data[0], i);
1250
1251             for (sb = 1; sb < coded_subbands; sb++) {
1252                 if (chan->gain_data[sb].num_points <= 0)
1253                     continue;
1254                 dst = &chan->gain_data[sb];
1255
1256                 /* 1st value is vlc-coded modulo delta to the corresponding
1257                  * value of the previous subband if any or zero */
1258                 delta = get_vlc2(gb, gain_vlc_tabs[6].table,
1259                                  gain_vlc_tabs[6].bits, 1);
1260                 pred             = dst[-1].num_points > 0
1261                                    ? dst[-1].loc_code[0] : 0;
1262                 dst->loc_code[0] = (pred + delta) & 0x1F;
1263
1264                 for (i = 1; i < dst->num_points; i++) {
1265                     more_than_ref = i >= dst[-1].num_points;
1266                     /* Select VLC table according to curve direction and
1267                      * presence of prediction. */
1268                     tab = &gain_vlc_tabs[(dst->lev_code[i] > dst->lev_code[i - 1]) *
1269                                                    2 + more_than_ref + 6];
1270                     delta = get_vlc2(gb, tab->table, tab->bits, 1);
1271                     if (more_than_ref)
1272                         dst->loc_code[i] = dst->loc_code[i - 1] + delta;
1273                     else
1274                         dst->loc_code[i] = (dst[-1].loc_code[i] + delta) & 0x1F;
1275                 }
1276             }
1277         }
1278         break;
1279     case 3:
1280         if (ch_num) { /* clone master or direct or direct coding */
1281             for (sb = 0; sb < coded_subbands; sb++)
1282                 for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1283                     if (i >= ref_chan->gain_data[sb].num_points)
1284                         gainc_loc_mode0(gb, ctx, &chan->gain_data[sb], i);
1285                     else
1286                         chan->gain_data[sb].loc_code[i] =
1287                             ref_chan->gain_data[sb].loc_code[i];
1288                 }
1289         } else { /* shorter delta to min */
1290             delta_bits = get_bits(gb, 2) + 1;
1291             min_val    = get_bits(gb, 5);
1292
1293             for (sb = 0; sb < coded_subbands; sb++)
1294                 for (i = 0; i < chan->gain_data[sb].num_points; i++)
1295                     chan->gain_data[sb].loc_code[i] = min_val + i +
1296                                                       get_bits(gb, delta_bits);
1297         }
1298         break;
1299     }
1300
1301     /* Validate decoded information */
1302     for (sb = 0; sb < coded_subbands; sb++) {
1303         dst = &chan->gain_data[sb];
1304         for (i = 0; i < chan->gain_data[sb].num_points; i++) {
1305             if (dst->loc_code[i] < 0 || dst->loc_code[i] > 31 ||
1306                 (i && dst->loc_code[i] <= dst->loc_code[i - 1])) {
1307                 av_log(avctx, AV_LOG_ERROR,
1308                        "Invalid gain location: ch=%d, sb=%d, pos=%d, val=%d\n",
1309                        ch_num, sb, i, dst->loc_code[i]);
1310                 return AVERROR_INVALIDDATA;
1311             }
1312         }
1313     }
1314
1315     return 0;
1316 }
1317
1318 /**
1319  * Decode gain control data for all channels.
1320  *
1321  * @param[in]     gb            the GetBit context
1322  * @param[in,out] ctx           ptr to the channel unit context
1323  * @param[in]     num_channels  number of channels to process
1324  * @param[in]     avctx         ptr to the AVCodecContext
1325  * @return result code: 0 = OK, otherwise - error code
1326  */
1327 static int decode_gainc_data(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1328                              int num_channels, AVCodecContext *avctx)
1329 {
1330     int ch_num, coded_subbands, sb, ret;
1331
1332     for (ch_num = 0; ch_num < num_channels; ch_num++) {
1333         memset(ctx->channels[ch_num].gain_data, 0,
1334                sizeof(*ctx->channels[ch_num].gain_data) * ATRAC3P_SUBBANDS);
1335
1336         if (get_bits1(gb)) { /* gain control data present? */
1337             coded_subbands = get_bits(gb, 4) + 1;
1338             if (get_bits1(gb)) /* is high band gain data replication on? */
1339                 ctx->channels[ch_num].num_gain_subbands = get_bits(gb, 4) + 1;
1340             else
1341                 ctx->channels[ch_num].num_gain_subbands = coded_subbands;
1342
1343             if ((ret = decode_gainc_npoints(gb, ctx, ch_num, coded_subbands)) < 0 ||
1344                 (ret = decode_gainc_levels(gb, ctx, ch_num, coded_subbands))  < 0 ||
1345                 (ret = decode_gainc_loc_codes(gb, ctx, ch_num, coded_subbands, avctx)) < 0)
1346                 return ret;
1347
1348             if (coded_subbands > 0) { /* propagate gain data if requested */
1349                 for (sb = coded_subbands; sb < ctx->channels[ch_num].num_gain_subbands; sb++)
1350                     ctx->channels[ch_num].gain_data[sb] =
1351                         ctx->channels[ch_num].gain_data[sb - 1];
1352             }
1353         } else {
1354             ctx->channels[ch_num].num_gain_subbands = 0;
1355         }
1356     }
1357
1358     return 0;
1359 }
1360
1361 /**
1362  * Decode envelope for all tones of a channel.
1363  *
1364  * @param[in]     gb                the GetBit context
1365  * @param[in,out] ctx               ptr to the channel unit context
1366  * @param[in]     ch_num            channel to process
1367  * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1368  *                                  1 - tone data present
1369  */
1370 static void decode_tones_envelope(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1371                                   int ch_num, int band_has_tones[])
1372 {
1373     int sb;
1374     Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1375     Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1376
1377     if (!ch_num || !get_bits1(gb)) { /* mode 0: fixed-length coding */
1378         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1379             if (!band_has_tones[sb])
1380                 continue;
1381             dst[sb].pend_env.has_start_point = get_bits1(gb);
1382             dst[sb].pend_env.start_pos       = dst[sb].pend_env.has_start_point
1383                                                ? get_bits(gb, 5) : -1;
1384             dst[sb].pend_env.has_stop_point  = get_bits1(gb);
1385             dst[sb].pend_env.stop_pos        = dst[sb].pend_env.has_stop_point
1386                                                ? get_bits(gb, 5) : 32;
1387         }
1388     } else { /* mode 1(slave only): copy master */
1389         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1390             if (!band_has_tones[sb])
1391                 continue;
1392             dst[sb].pend_env.has_start_point = ref[sb].pend_env.has_start_point;
1393             dst[sb].pend_env.has_stop_point  = ref[sb].pend_env.has_stop_point;
1394             dst[sb].pend_env.start_pos       = ref[sb].pend_env.start_pos;
1395             dst[sb].pend_env.stop_pos        = ref[sb].pend_env.stop_pos;
1396         }
1397     }
1398 }
1399
1400 /**
1401  * Decode number of tones for each subband of a channel.
1402  *
1403  * @param[in]     gb                the GetBit context
1404  * @param[in,out] ctx               ptr to the channel unit context
1405  * @param[in]     ch_num            channel to process
1406  * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1407  *                                  1 - tone data present
1408  * @param[in]     avctx             ptr to the AVCodecContext
1409  * @return result code: 0 = OK, otherwise - error code
1410  */
1411 static int decode_band_numwavs(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1412                                int ch_num, int band_has_tones[],
1413                                AVCodecContext *avctx)
1414 {
1415     int mode, sb, delta;
1416     Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1417     Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1418
1419     mode = get_bits(gb, ch_num + 1);
1420     switch (mode) {
1421     case 0: /** fixed-length coding */
1422         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1423             if (band_has_tones[sb])
1424                 dst[sb].num_wavs = get_bits(gb, 4);
1425         break;
1426     case 1: /** variable-length coding */
1427         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1428             if (band_has_tones[sb])
1429                 dst[sb].num_wavs =
1430                     get_vlc2(gb, tone_vlc_tabs[1].table,
1431                              tone_vlc_tabs[1].bits, 1);
1432         break;
1433     case 2: /** VLC modulo delta to master (slave only) */
1434         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1435             if (band_has_tones[sb]) {
1436                 delta = get_vlc2(gb, tone_vlc_tabs[2].table,
1437                                  tone_vlc_tabs[2].bits, 1);
1438                 delta = sign_extend(delta, 3);
1439                 dst[sb].num_wavs = (ref[sb].num_wavs + delta) & 0xF;
1440             }
1441         break;
1442     case 3: /** copy master (slave only) */
1443         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1444             if (band_has_tones[sb])
1445                 dst[sb].num_wavs = ref[sb].num_wavs;
1446         break;
1447     }
1448
1449     /** initialize start tone index for each subband */
1450     for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++)
1451         if (band_has_tones[sb]) {
1452             if (ctx->waves_info->tones_index + dst[sb].num_wavs > 48) {
1453                 av_log(avctx, AV_LOG_ERROR,
1454                        "Too many tones: %d (max. 48), frame: %d!\n",
1455                        ctx->waves_info->tones_index + dst[sb].num_wavs,
1456                        avctx->frame_number);
1457                 return AVERROR_INVALIDDATA;
1458             }
1459             dst[sb].start_index           = ctx->waves_info->tones_index;
1460             ctx->waves_info->tones_index += dst[sb].num_wavs;
1461         }
1462
1463     return 0;
1464 }
1465
1466 /**
1467  * Decode frequency information for each subband of a channel.
1468  *
1469  * @param[in]     gb                the GetBit context
1470  * @param[in,out] ctx               ptr to the channel unit context
1471  * @param[in]     ch_num            channel to process
1472  * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1473  *                                  1 - tone data present
1474  */
1475 static void decode_tones_frequency(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1476                                    int ch_num, int band_has_tones[])
1477 {
1478     int sb, i, direction, nbits, pred, delta;
1479     Atrac3pWaveParam *iwav, *owav;
1480     Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1481     Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1482
1483     if (!ch_num || !get_bits1(gb)) { /* mode 0: fixed-length coding */
1484         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1485             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1486                 continue;
1487             iwav      = &ctx->waves_info->waves[dst[sb].start_index];
1488             direction = (dst[sb].num_wavs > 1) ? get_bits1(gb) : 0;
1489             if (direction) { /** packed numbers in descending order */
1490                 if (dst[sb].num_wavs)
1491                     iwav[dst[sb].num_wavs - 1].freq_index = get_bits(gb, 10);
1492                 for (i = dst[sb].num_wavs - 2; i >= 0 ; i--) {
1493                     nbits = av_log2(iwav[i+1].freq_index) + 1;
1494                     iwav[i].freq_index = get_bits(gb, nbits);
1495                 }
1496             } else { /** packed numbers in ascending order */
1497                 for (i = 0; i < dst[sb].num_wavs; i++) {
1498                     if (!i || iwav[i - 1].freq_index < 512)
1499                         iwav[i].freq_index = get_bits(gb, 10);
1500                     else {
1501                         nbits = av_log2(1023 - iwav[i - 1].freq_index) + 1;
1502                         iwav[i].freq_index = get_bits(gb, nbits) +
1503                                              1024 - (1 << nbits);
1504                     }
1505                 }
1506             }
1507         }
1508     } else { /* mode 1: VLC modulo delta to master (slave only) */
1509         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1510             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1511                 continue;
1512             iwav = &ctx->waves_info->waves[ref[sb].start_index];
1513             owav = &ctx->waves_info->waves[dst[sb].start_index];
1514             for (i = 0; i < dst[sb].num_wavs; i++) {
1515                 delta = get_vlc2(gb, tone_vlc_tabs[6].table,
1516                                  tone_vlc_tabs[6].bits, 1);
1517                 delta = sign_extend(delta, 8);
1518                 pred  = (i < ref[sb].num_wavs) ? iwav[i].freq_index :
1519                         (ref[sb].num_wavs ? iwav[ref[sb].num_wavs - 1].freq_index : 0);
1520                 owav[i].freq_index = (pred + delta) & 0x3FF;
1521             }
1522         }
1523     }
1524 }
1525
1526 /**
1527  * Decode amplitude information for each subband of a channel.
1528  *
1529  * @param[in]     gb                the GetBit context
1530  * @param[in,out] ctx               ptr to the channel unit context
1531  * @param[in]     ch_num            channel to process
1532  * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1533  *                                  1 - tone data present
1534  */
1535 static void decode_tones_amplitude(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1536                                    int ch_num, int band_has_tones[])
1537 {
1538     int mode, sb, j, i, diff, maxdiff, fi, delta, pred;
1539     Atrac3pWaveParam *wsrc, *wref;
1540     int refwaves[48] = { 0 };
1541     Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1542     Atrac3pWavesData *ref = ctx->channels[0].tones_info;
1543
1544     if (ch_num) {
1545         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1546             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1547                 continue;
1548             wsrc = &ctx->waves_info->waves[dst[sb].start_index];
1549             wref = &ctx->waves_info->waves[ref[sb].start_index];
1550             for (j = 0; j < dst[sb].num_wavs; j++) {
1551                 for (i = 0, fi = 0, maxdiff = 1024; i < ref[sb].num_wavs; i++) {
1552                     diff = FFABS(wsrc[j].freq_index - wref[i].freq_index);
1553                     if (diff < maxdiff) {
1554                         maxdiff = diff;
1555                         fi      = i;
1556                     }
1557                 }
1558
1559                 if (maxdiff < 8)
1560                     refwaves[dst[sb].start_index + j] = fi + ref[sb].start_index;
1561                 else if (j < ref[sb].num_wavs)
1562                     refwaves[dst[sb].start_index + j] = j + ref[sb].start_index;
1563                 else
1564                     refwaves[dst[sb].start_index + j] = -1;
1565             }
1566         }
1567     }
1568
1569     mode = get_bits(gb, ch_num + 1);
1570
1571     switch (mode) {
1572     case 0: /** fixed-length coding */
1573         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1574             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1575                 continue;
1576             if (ctx->waves_info->amplitude_mode)
1577                 for (i = 0; i < dst[sb].num_wavs; i++)
1578                     ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = get_bits(gb, 6);
1579             else
1580                 ctx->waves_info->waves[dst[sb].start_index].amp_sf = get_bits(gb, 6);
1581         }
1582         break;
1583     case 1: /** min + VLC delta */
1584         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1585             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1586                 continue;
1587             if (ctx->waves_info->amplitude_mode)
1588                 for (i = 0; i < dst[sb].num_wavs; i++)
1589                     ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =
1590                         get_vlc2(gb, tone_vlc_tabs[3].table,
1591                                  tone_vlc_tabs[3].bits, 1) + 20;
1592             else
1593                 ctx->waves_info->waves[dst[sb].start_index].amp_sf =
1594                     get_vlc2(gb, tone_vlc_tabs[4].table,
1595                              tone_vlc_tabs[4].bits, 1) + 24;
1596         }
1597         break;
1598     case 2: /** VLC modulo delta to master (slave only) */
1599         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1600             if (!band_has_tones[sb] || !dst[sb].num_wavs)
1601                 continue;
1602             for (i = 0; i < dst[sb].num_wavs; i++) {
1603                 delta = get_vlc2(gb, tone_vlc_tabs[5].table,
1604                                  tone_vlc_tabs[5].bits, 1);
1605                 delta = sign_extend(delta, 5);
1606                 pred  = refwaves[dst[sb].start_index + i] >= 0 ?
1607                         ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf : 34;
1608                 ctx->waves_info->waves[dst[sb].start_index + i].amp_sf = (pred + delta) & 0x3F;
1609             }
1610         }
1611         break;
1612     case 3: /** clone master (slave only) */
1613         for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1614             if (!band_has_tones[sb])
1615                 continue;
1616             for (i = 0; i < dst[sb].num_wavs; i++)
1617                 ctx->waves_info->waves[dst[sb].start_index + i].amp_sf =
1618                     refwaves[dst[sb].start_index + i] >= 0
1619                     ? ctx->waves_info->waves[refwaves[dst[sb].start_index + i]].amp_sf
1620                     : 32;
1621         }
1622         break;
1623     }
1624 }
1625
1626 /**
1627  * Decode phase information for each subband of a channel.
1628  *
1629  * @param[in]     gb                the GetBit context
1630  * @param[in,out] ctx               ptr to the channel unit context
1631  * @param[in]     ch_num            channel to process
1632  * @param[in]     band_has_tones    ptr to an array of per-band-flags:
1633  *                                  1 - tone data present
1634  */
1635 static void decode_tones_phase(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1636                                int ch_num, int band_has_tones[])
1637 {
1638     int sb, i;
1639     Atrac3pWaveParam *wparam;
1640     Atrac3pWavesData *dst = ctx->channels[ch_num].tones_info;
1641
1642     for (sb = 0; sb < ctx->waves_info->num_tone_bands; sb++) {
1643         if (!band_has_tones[sb])
1644             continue;
1645         wparam = &ctx->waves_info->waves[dst[sb].start_index];
1646         for (i = 0; i < dst[sb].num_wavs; i++)
1647             wparam[i].phase_index = get_bits(gb, 5);
1648     }
1649 }
1650
1651 /**
1652  * Decode tones info for all channels.
1653  *
1654  * @param[in]     gb            the GetBit context
1655  * @param[in,out] ctx           ptr to the channel unit context
1656  * @param[in]     num_channels  number of channels to process
1657  * @param[in]     avctx         ptr to the AVCodecContext
1658  * @return result code: 0 = OK, otherwise - error code
1659  */
1660 static int decode_tones_info(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1661                              int num_channels, AVCodecContext *avctx)
1662 {
1663     int ch_num, i, ret;
1664     int band_has_tones[16];
1665
1666     for (ch_num = 0; ch_num < num_channels; ch_num++)
1667         memset(ctx->channels[ch_num].tones_info, 0,
1668                sizeof(*ctx->channels[ch_num].tones_info) * ATRAC3P_SUBBANDS);
1669
1670     ctx->waves_info->tones_present = get_bits1(gb);
1671     if (!ctx->waves_info->tones_present)
1672         return 0;
1673
1674     memset(ctx->waves_info->waves, 0, sizeof(ctx->waves_info->waves));
1675
1676     ctx->waves_info->amplitude_mode = get_bits1(gb);
1677     if (!ctx->waves_info->amplitude_mode) {
1678         avpriv_report_missing_feature(avctx, "GHA amplitude mode 0");
1679         return AVERROR_PATCHWELCOME;
1680     }
1681
1682     ctx->waves_info->num_tone_bands =
1683         get_vlc2(gb, tone_vlc_tabs[0].table,
1684                  tone_vlc_tabs[0].bits, 1) + 1;
1685
1686     if (num_channels == 2) {
1687         get_subband_flags(gb, ctx->waves_info->tone_sharing, ctx->waves_info->num_tone_bands);
1688         get_subband_flags(gb, ctx->waves_info->tone_master,  ctx->waves_info->num_tone_bands);
1689         get_subband_flags(gb, ctx->waves_info->invert_phase, ctx->waves_info->num_tone_bands);
1690     }
1691
1692     ctx->waves_info->tones_index = 0;
1693
1694     for (ch_num = 0; ch_num < num_channels; ch_num++) {
1695         for (i = 0; i < ctx->waves_info->num_tone_bands; i++)
1696             band_has_tones[i] = !ch_num ? 1 : !ctx->waves_info->tone_sharing[i];
1697
1698         decode_tones_envelope(gb, ctx, ch_num, band_has_tones);
1699         if ((ret = decode_band_numwavs(gb, ctx, ch_num, band_has_tones,
1700                                        avctx)) < 0)
1701             return ret;
1702
1703         decode_tones_frequency(gb, ctx, ch_num, band_has_tones);
1704         decode_tones_amplitude(gb, ctx, ch_num, band_has_tones);
1705         decode_tones_phase(gb, ctx, ch_num, band_has_tones);
1706     }
1707
1708     if (num_channels == 2) {
1709         for (i = 0; i < ctx->waves_info->num_tone_bands; i++) {
1710             if (ctx->waves_info->tone_sharing[i])
1711                 ctx->channels[1].tones_info[i] = ctx->channels[0].tones_info[i];
1712
1713             if (ctx->waves_info->tone_master[i])
1714                 FFSWAP(Atrac3pWavesData, ctx->channels[0].tones_info[i],
1715                        ctx->channels[1].tones_info[i]);
1716         }
1717     }
1718
1719     return 0;
1720 }
1721
1722 int ff_atrac3p_decode_channel_unit(GetBitContext *gb, Atrac3pChanUnitCtx *ctx,
1723                                    int num_channels, AVCodecContext *avctx)
1724 {
1725     int ret;
1726
1727     /* parse sound header */
1728     ctx->num_quant_units = get_bits(gb, 5) + 1;
1729     if (ctx->num_quant_units > 28 && ctx->num_quant_units < 32) {
1730         av_log(avctx, AV_LOG_ERROR,
1731                "Invalid number of quantization units: %d!\n",
1732                ctx->num_quant_units);
1733         return AVERROR_INVALIDDATA;
1734     }
1735
1736     ctx->mute_flag = get_bits1(gb);
1737
1738     /* decode various sound parameters */
1739     if ((ret = decode_quant_wordlen(gb, ctx, num_channels, avctx)) < 0)
1740         return ret;
1741
1742     ctx->num_subbands       = atrac3p_qu_to_subband[ctx->num_quant_units - 1] + 1;
1743     ctx->num_coded_subbands = ctx->used_quant_units
1744                               ? atrac3p_qu_to_subband[ctx->used_quant_units - 1] + 1
1745                               : 0;
1746
1747     if ((ret = decode_scale_factors(gb, ctx, num_channels, avctx)) < 0)
1748         return ret;
1749
1750     if ((ret = decode_code_table_indexes(gb, ctx, num_channels, avctx)) < 0)
1751         return ret;
1752
1753     decode_spectrum(gb, ctx, num_channels, avctx);
1754
1755     if (num_channels == 2) {
1756         get_subband_flags(gb, ctx->swap_channels, ctx->num_coded_subbands);
1757         get_subband_flags(gb, ctx->negate_coeffs, ctx->num_coded_subbands);
1758     }
1759
1760     decode_window_shape(gb, ctx, num_channels);
1761
1762     if ((ret = decode_gainc_data(gb, ctx, num_channels, avctx)) < 0)
1763         return ret;
1764
1765     if ((ret = decode_tones_info(gb, ctx, num_channels, avctx)) < 0)
1766         return ret;
1767
1768     /* decode global noise info */
1769     ctx->noise_present = get_bits1(gb);
1770     if (ctx->noise_present) {
1771         ctx->noise_level_index = get_bits(gb, 4);
1772         ctx->noise_table_index = get_bits(gb, 4);
1773     }
1774
1775     return 0;
1776 }