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