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