- add third_party src.
[platform/framework/web/crosswalk.git] / src / third_party / ffmpeg / libavcodec / qdm2.c
1 /*
2  * QDM2 compatible decoder
3  * Copyright (c) 2003 Ewald Snel
4  * Copyright (c) 2005 Benjamin Larsson
5  * Copyright (c) 2005 Alex Beregszaszi
6  * Copyright (c) 2005 Roberto Togni
7  *
8  * This file is part of FFmpeg.
9  *
10  * FFmpeg is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * FFmpeg is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with FFmpeg; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
23  */
24
25 /**
26  * @file
27  * QDM2 decoder
28  * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
29  *
30  * The decoder is not perfect yet, there are still some distortions
31  * especially on files encoded with 16 or 8 subbands.
32  */
33
34 #include <math.h>
35 #include <stddef.h>
36 #include <stdio.h>
37
38 #define BITSTREAM_READER_LE
39 #include "libavutil/channel_layout.h"
40 #include "avcodec.h"
41 #include "get_bits.h"
42 #include "internal.h"
43 #include "rdft.h"
44 #include "mpegaudiodsp.h"
45 #include "mpegaudio.h"
46
47 #include "qdm2data.h"
48 #include "qdm2_tablegen.h"
49
50 #undef NDEBUG
51 #include <assert.h>
52
53
54 #define QDM2_LIST_ADD(list, size, packet) \
55 do { \
56       if (size > 0) { \
57     list[size - 1].next = &list[size]; \
58       } \
59       list[size].packet = packet; \
60       list[size].next = NULL; \
61       size++; \
62 } while(0)
63
64 // Result is 8, 16 or 30
65 #define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
66
67 #define FIX_NOISE_IDX(noise_idx) \
68   if ((noise_idx) >= 3840) \
69     (noise_idx) -= 3840; \
70
71 #define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
72
73 #define SAMPLES_NEEDED \
74      av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
75
76 #define SAMPLES_NEEDED_2(why) \
77      av_log (NULL,AV_LOG_INFO,"This file triggers some missing code. Please contact the developers.\nPosition: %s\n",why);
78
79 #define QDM2_MAX_FRAME_SIZE 512
80
81 typedef int8_t sb_int8_array[2][30][64];
82
83 /**
84  * Subpacket
85  */
86 typedef struct {
87     int type;            ///< subpacket type
88     unsigned int size;   ///< subpacket size
89     const uint8_t *data; ///< pointer to subpacket data (points to input data buffer, it's not a private copy)
90 } QDM2SubPacket;
91
92 /**
93  * A node in the subpacket list
94  */
95 typedef struct QDM2SubPNode {
96     QDM2SubPacket *packet;      ///< packet
97     struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
98 } QDM2SubPNode;
99
100 typedef struct {
101     float re;
102     float im;
103 } QDM2Complex;
104
105 typedef struct {
106     float level;
107     QDM2Complex *complex;
108     const float *table;
109     int   phase;
110     int   phase_shift;
111     int   duration;
112     short time_index;
113     short cutoff;
114 } FFTTone;
115
116 typedef struct {
117     int16_t sub_packet;
118     uint8_t channel;
119     int16_t offset;
120     int16_t exp;
121     uint8_t phase;
122 } FFTCoefficient;
123
124 typedef struct {
125     DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
126 } QDM2FFT;
127
128 /**
129  * QDM2 decoder context
130  */
131 typedef struct {
132     /// Parameters from codec header, do not change during playback
133     int nb_channels;         ///< number of channels
134     int channels;            ///< number of channels
135     int group_size;          ///< size of frame group (16 frames per group)
136     int fft_size;            ///< size of FFT, in complex numbers
137     int checksum_size;       ///< size of data block, used also for checksum
138
139     /// Parameters built from header parameters, do not change during playback
140     int group_order;         ///< order of frame group
141     int fft_order;           ///< order of FFT (actually fftorder+1)
142     int frame_size;          ///< size of data frame
143     int frequency_range;
144     int sub_sampling;        ///< subsampling: 0=25%, 1=50%, 2=100% */
145     int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
146     int cm_table_select;     ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
147
148     /// Packets and packet lists
149     QDM2SubPacket sub_packets[16];      ///< the packets themselves
150     QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
151     QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
152     int sub_packets_B;                  ///< number of packets on 'B' list
153     QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
154     QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
155
156     /// FFT and tones
157     FFTTone fft_tones[1000];
158     int fft_tone_start;
159     int fft_tone_end;
160     FFTCoefficient fft_coefs[1000];
161     int fft_coefs_index;
162     int fft_coefs_min_index[5];
163     int fft_coefs_max_index[5];
164     int fft_level_exp[6];
165     RDFTContext rdft_ctx;
166     QDM2FFT fft;
167
168     /// I/O data
169     const uint8_t *compressed_data;
170     int compressed_size;
171     float output_buffer[QDM2_MAX_FRAME_SIZE * MPA_MAX_CHANNELS * 2];
172
173     /// Synthesis filter
174     MPADSPContext mpadsp;
175     DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
176     int synth_buf_offset[MPA_MAX_CHANNELS];
177     DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
178     DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
179
180     /// Mixed temporary data used in decoding
181     float tone_level[MPA_MAX_CHANNELS][30][64];
182     int8_t coding_method[MPA_MAX_CHANNELS][30][64];
183     int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
184     int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
185     int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
186     int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
187     int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
188     int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
189     int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
190
191     // Flags
192     int has_errors;         ///< packet has errors
193     int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
194     int do_synth_filter;    ///< used to perform or skip synthesis filter
195
196     int sub_packet;
197     int noise_idx; ///< index for dithering noise table
198 } QDM2Context;
199
200
201 static VLC vlc_tab_level;
202 static VLC vlc_tab_diff;
203 static VLC vlc_tab_run;
204 static VLC fft_level_exp_alt_vlc;
205 static VLC fft_level_exp_vlc;
206 static VLC fft_stereo_exp_vlc;
207 static VLC fft_stereo_phase_vlc;
208 static VLC vlc_tab_tone_level_idx_hi1;
209 static VLC vlc_tab_tone_level_idx_mid;
210 static VLC vlc_tab_tone_level_idx_hi2;
211 static VLC vlc_tab_type30;
212 static VLC vlc_tab_type34;
213 static VLC vlc_tab_fft_tone_offset[5];
214
215 static const uint16_t qdm2_vlc_offs[] = {
216     0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
217 };
218
219 static const int switchtable[23] = {
220     0, 5, 1, 5, 5, 5, 5, 5, 2, 5, 5, 5, 5, 5, 5, 5, 3, 5, 5, 5, 5, 5, 4
221 };
222
223 static av_cold void qdm2_init_vlc(void)
224 {
225     static VLC_TYPE qdm2_table[3838][2];
226
227     vlc_tab_level.table           = &qdm2_table[qdm2_vlc_offs[0]];
228     vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
229     init_vlc(&vlc_tab_level, 8, 24,
230              vlc_tab_level_huffbits, 1, 1,
231              vlc_tab_level_huffcodes, 2, 2,
232              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
233
234     vlc_tab_diff.table           = &qdm2_table[qdm2_vlc_offs[1]];
235     vlc_tab_diff.table_allocated = qdm2_vlc_offs[2] - qdm2_vlc_offs[1];
236     init_vlc(&vlc_tab_diff, 8, 37,
237              vlc_tab_diff_huffbits, 1, 1,
238              vlc_tab_diff_huffcodes, 2, 2,
239              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
240
241     vlc_tab_run.table           = &qdm2_table[qdm2_vlc_offs[2]];
242     vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
243     init_vlc(&vlc_tab_run, 5, 6,
244              vlc_tab_run_huffbits, 1, 1,
245              vlc_tab_run_huffcodes, 1, 1,
246              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
247
248     fft_level_exp_alt_vlc.table           = &qdm2_table[qdm2_vlc_offs[3]];
249     fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] -
250                                             qdm2_vlc_offs[3];
251     init_vlc(&fft_level_exp_alt_vlc, 8, 28,
252              fft_level_exp_alt_huffbits, 1, 1,
253              fft_level_exp_alt_huffcodes, 2, 2,
254              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
255
256     fft_level_exp_vlc.table           = &qdm2_table[qdm2_vlc_offs[4]];
257     fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
258     init_vlc(&fft_level_exp_vlc, 8, 20,
259              fft_level_exp_huffbits, 1, 1,
260              fft_level_exp_huffcodes, 2, 2,
261              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
262
263     fft_stereo_exp_vlc.table           = &qdm2_table[qdm2_vlc_offs[5]];
264     fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] -
265                                          qdm2_vlc_offs[5];
266     init_vlc(&fft_stereo_exp_vlc, 6, 7,
267              fft_stereo_exp_huffbits, 1, 1,
268              fft_stereo_exp_huffcodes, 1, 1,
269              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
270
271     fft_stereo_phase_vlc.table           = &qdm2_table[qdm2_vlc_offs[6]];
272     fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] -
273                                            qdm2_vlc_offs[6];
274     init_vlc(&fft_stereo_phase_vlc, 6, 9,
275              fft_stereo_phase_huffbits, 1, 1,
276              fft_stereo_phase_huffcodes, 1, 1,
277              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
278
279     vlc_tab_tone_level_idx_hi1.table =
280         &qdm2_table[qdm2_vlc_offs[7]];
281     vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] -
282                                                  qdm2_vlc_offs[7];
283     init_vlc(&vlc_tab_tone_level_idx_hi1, 8, 20,
284              vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
285              vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2,
286              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
287
288     vlc_tab_tone_level_idx_mid.table =
289         &qdm2_table[qdm2_vlc_offs[8]];
290     vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] -
291                                                  qdm2_vlc_offs[8];
292     init_vlc(&vlc_tab_tone_level_idx_mid, 8, 24,
293              vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
294              vlc_tab_tone_level_idx_mid_huffcodes, 2, 2,
295              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
296
297     vlc_tab_tone_level_idx_hi2.table =
298         &qdm2_table[qdm2_vlc_offs[9]];
299     vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] -
300                                                  qdm2_vlc_offs[9];
301     init_vlc(&vlc_tab_tone_level_idx_hi2, 8, 24,
302              vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
303              vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2,
304              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
305
306     vlc_tab_type30.table           = &qdm2_table[qdm2_vlc_offs[10]];
307     vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
308     init_vlc(&vlc_tab_type30, 6, 9,
309              vlc_tab_type30_huffbits, 1, 1,
310              vlc_tab_type30_huffcodes, 1, 1,
311              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
312
313     vlc_tab_type34.table           = &qdm2_table[qdm2_vlc_offs[11]];
314     vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
315     init_vlc(&vlc_tab_type34, 5, 10,
316              vlc_tab_type34_huffbits, 1, 1,
317              vlc_tab_type34_huffcodes, 1, 1,
318              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
319
320     vlc_tab_fft_tone_offset[0].table =
321         &qdm2_table[qdm2_vlc_offs[12]];
322     vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] -
323                                                  qdm2_vlc_offs[12];
324     init_vlc(&vlc_tab_fft_tone_offset[0], 8, 23,
325              vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
326              vlc_tab_fft_tone_offset_0_huffcodes, 2, 2,
327              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
328
329     vlc_tab_fft_tone_offset[1].table =
330         &qdm2_table[qdm2_vlc_offs[13]];
331     vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] -
332                                                  qdm2_vlc_offs[13];
333     init_vlc(&vlc_tab_fft_tone_offset[1], 8, 28,
334              vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
335              vlc_tab_fft_tone_offset_1_huffcodes, 2, 2,
336              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
337
338     vlc_tab_fft_tone_offset[2].table =
339         &qdm2_table[qdm2_vlc_offs[14]];
340     vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] -
341                                                  qdm2_vlc_offs[14];
342     init_vlc(&vlc_tab_fft_tone_offset[2], 8, 32,
343              vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
344              vlc_tab_fft_tone_offset_2_huffcodes, 2, 2,
345              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
346
347     vlc_tab_fft_tone_offset[3].table =
348         &qdm2_table[qdm2_vlc_offs[15]];
349     vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] -
350                                                  qdm2_vlc_offs[15];
351     init_vlc(&vlc_tab_fft_tone_offset[3], 8, 35,
352              vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
353              vlc_tab_fft_tone_offset_3_huffcodes, 2, 2,
354              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
355
356     vlc_tab_fft_tone_offset[4].table =
357         &qdm2_table[qdm2_vlc_offs[16]];
358     vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] -
359                                                  qdm2_vlc_offs[16];
360     init_vlc(&vlc_tab_fft_tone_offset[4], 8, 38,
361              vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
362              vlc_tab_fft_tone_offset_4_huffcodes, 2, 2,
363              INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
364 }
365
366 static int qdm2_get_vlc(GetBitContext *gb, VLC *vlc, int flag, int depth)
367 {
368     int value;
369
370     value = get_vlc2(gb, vlc->table, vlc->bits, depth);
371
372     /* stage-2, 3 bits exponent escape sequence */
373     if (value-- == 0)
374         value = get_bits(gb, get_bits(gb, 3) + 1);
375
376     /* stage-3, optional */
377     if (flag) {
378         int tmp;
379
380         if (value >= 60) {
381             av_log(NULL, AV_LOG_ERROR, "value %d in qdm2_get_vlc too large\n", value);
382             return 0;
383         }
384
385         tmp= vlc_stage3_values[value];
386
387         if ((value & ~3) > 0)
388             tmp += get_bits(gb, (value >> 2));
389         value = tmp;
390     }
391
392     return value;
393 }
394
395 static int qdm2_get_se_vlc(VLC *vlc, GetBitContext *gb, int depth)
396 {
397     int value = qdm2_get_vlc(gb, vlc, 0, depth);
398
399     return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
400 }
401
402 /**
403  * QDM2 checksum
404  *
405  * @param data      pointer to data to be checksum'ed
406  * @param length    data length
407  * @param value     checksum value
408  *
409  * @return          0 if checksum is OK
410  */
411 static uint16_t qdm2_packet_checksum(const uint8_t *data, int length, int value)
412 {
413     int i;
414
415     for (i = 0; i < length; i++)
416         value -= data[i];
417
418     return (uint16_t)(value & 0xffff);
419 }
420
421 /**
422  * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
423  *
424  * @param gb            bitreader context
425  * @param sub_packet    packet under analysis
426  */
427 static void qdm2_decode_sub_packet_header(GetBitContext *gb,
428                                           QDM2SubPacket *sub_packet)
429 {
430     sub_packet->type = get_bits(gb, 8);
431
432     if (sub_packet->type == 0) {
433         sub_packet->size = 0;
434         sub_packet->data = NULL;
435     } else {
436         sub_packet->size = get_bits(gb, 8);
437
438         if (sub_packet->type & 0x80) {
439             sub_packet->size <<= 8;
440             sub_packet->size  |= get_bits(gb, 8);
441             sub_packet->type  &= 0x7f;
442         }
443
444         if (sub_packet->type == 0x7f)
445             sub_packet->type |= (get_bits(gb, 8) << 8);
446
447         // FIXME: this depends on bitreader-internal data
448         sub_packet->data = &gb->buffer[get_bits_count(gb) / 8];
449     }
450
451     av_log(NULL, AV_LOG_DEBUG, "Subpacket: type=%d size=%d start_offs=%x\n",
452            sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
453 }
454
455 /**
456  * Return node pointer to first packet of requested type in list.
457  *
458  * @param list    list of subpackets to be scanned
459  * @param type    type of searched subpacket
460  * @return        node pointer for subpacket if found, else NULL
461  */
462 static QDM2SubPNode *qdm2_search_subpacket_type_in_list(QDM2SubPNode *list,
463                                                         int type)
464 {
465     while (list != NULL && list->packet != NULL) {
466         if (list->packet->type == type)
467             return list;
468         list = list->next;
469     }
470     return NULL;
471 }
472
473 /**
474  * Replace 8 elements with their average value.
475  * Called by qdm2_decode_superblock before starting subblock decoding.
476  *
477  * @param q       context
478  */
479 static void average_quantized_coeffs(QDM2Context *q)
480 {
481     int i, j, n, ch, sum;
482
483     n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
484
485     for (ch = 0; ch < q->nb_channels; ch++)
486         for (i = 0; i < n; i++) {
487             sum = 0;
488
489             for (j = 0; j < 8; j++)
490                 sum += q->quantized_coeffs[ch][i][j];
491
492             sum /= 8;
493             if (sum > 0)
494                 sum--;
495
496             for (j = 0; j < 8; j++)
497                 q->quantized_coeffs[ch][i][j] = sum;
498         }
499 }
500
501 /**
502  * Build subband samples with noise weighted by q->tone_level.
503  * Called by synthfilt_build_sb_samples.
504  *
505  * @param q     context
506  * @param sb    subband index
507  */
508 static void build_sb_samples_from_noise(QDM2Context *q, int sb)
509 {
510     int ch, j;
511
512     FIX_NOISE_IDX(q->noise_idx);
513
514     if (!q->nb_channels)
515         return;
516
517     for (ch = 0; ch < q->nb_channels; ch++) {
518         for (j = 0; j < 64; j++) {
519             q->sb_samples[ch][j * 2][sb] =
520                 SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
521             q->sb_samples[ch][j * 2 + 1][sb] =
522                 SB_DITHERING_NOISE(sb, q->noise_idx) * q->tone_level[ch][sb][j];
523         }
524     }
525 }
526
527 /**
528  * Called while processing data from subpackets 11 and 12.
529  * Used after making changes to coding_method array.
530  *
531  * @param sb               subband index
532  * @param channels         number of channels
533  * @param coding_method    q->coding_method[0][0][0]
534  */
535 static int fix_coding_method_array(int sb, int channels,
536                                    sb_int8_array coding_method)
537 {
538     int j, k;
539     int ch;
540     int run, case_val;
541
542     for (ch = 0; ch < channels; ch++) {
543         for (j = 0; j < 64; ) {
544             if (coding_method[ch][sb][j] < 8)
545                 return -1;
546             if ((coding_method[ch][sb][j] - 8) > 22) {
547                 run      = 1;
548                 case_val = 8;
549             } else {
550                 switch (switchtable[coding_method[ch][sb][j] - 8]) {
551                 case 0: run  = 10;
552                     case_val = 10;
553                     break;
554                 case 1: run  = 1;
555                     case_val = 16;
556                     break;
557                 case 2: run  = 5;
558                     case_val = 24;
559                     break;
560                 case 3: run  = 3;
561                     case_val = 30;
562                     break;
563                 case 4: run  = 1;
564                     case_val = 30;
565                     break;
566                 case 5: run  = 1;
567                     case_val = 8;
568                     break;
569                 default: run = 1;
570                     case_val = 8;
571                     break;
572                 }
573             }
574             for (k = 0; k < run; k++) {
575                 if (j + k < 128) {
576                     if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j]) {
577                         if (k > 0) {
578                             SAMPLES_NEEDED
579                             //not debugged, almost never used
580                             memset(&coding_method[ch][sb][j + k], case_val,
581                                    k *sizeof(int8_t));
582                             memset(&coding_method[ch][sb][j + k], case_val,
583                                    3 * sizeof(int8_t));
584                         }
585                     }
586                 }
587             }
588             j += run;
589         }
590     }
591     return 0;
592 }
593
594 /**
595  * Related to synthesis filter
596  * Called by process_subpacket_10
597  *
598  * @param q       context
599  * @param flag    1 if called after getting data from subpacket 10, 0 if no subpacket 10
600  */
601 static void fill_tone_level_array(QDM2Context *q, int flag)
602 {
603     int i, sb, ch, sb_used;
604     int tmp, tab;
605
606     for (ch = 0; ch < q->nb_channels; ch++)
607         for (sb = 0; sb < 30; sb++)
608             for (i = 0; i < 8; i++) {
609                 if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
610                     tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
611                           q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
612                 else
613                     tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
614                 if(tmp < 0)
615                     tmp += 0xff;
616                 q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
617             }
618
619     sb_used = QDM2_SB_USED(q->sub_sampling);
620
621     if ((q->superblocktype_2_3 != 0) && !flag) {
622         for (sb = 0; sb < sb_used; sb++)
623             for (ch = 0; ch < q->nb_channels; ch++)
624                 for (i = 0; i < 64; i++) {
625                     q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
626                     if (q->tone_level_idx[ch][sb][i] < 0)
627                         q->tone_level[ch][sb][i] = 0;
628                     else
629                         q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
630                 }
631     } else {
632         tab = q->superblocktype_2_3 ? 0 : 1;
633         for (sb = 0; sb < sb_used; sb++) {
634             if ((sb >= 4) && (sb <= 23)) {
635                 for (ch = 0; ch < q->nb_channels; ch++)
636                     for (i = 0; i < 64; i++) {
637                         tmp = q->tone_level_idx_base[ch][sb][i / 8] -
638                               q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
639                               q->tone_level_idx_mid[ch][sb - 4][i / 8] -
640                               q->tone_level_idx_hi2[ch][sb - 4];
641                         q->tone_level_idx[ch][sb][i] = tmp & 0xff;
642                         if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
643                             q->tone_level[ch][sb][i] = 0;
644                         else
645                             q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
646                 }
647             } else {
648                 if (sb > 4) {
649                     for (ch = 0; ch < q->nb_channels; ch++)
650                         for (i = 0; i < 64; i++) {
651                             tmp = q->tone_level_idx_base[ch][sb][i / 8] -
652                                   q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
653                                   q->tone_level_idx_hi2[ch][sb - 4];
654                             q->tone_level_idx[ch][sb][i] = tmp & 0xff;
655                             if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
656                                 q->tone_level[ch][sb][i] = 0;
657                             else
658                                 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
659                     }
660                 } else {
661                     for (ch = 0; ch < q->nb_channels; ch++)
662                         for (i = 0; i < 64; i++) {
663                             tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
664                             if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
665                                 q->tone_level[ch][sb][i] = 0;
666                             else
667                                 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
668                         }
669                 }
670             }
671         }
672     }
673 }
674
675 /**
676  * Related to synthesis filter
677  * Called by process_subpacket_11
678  * c is built with data from subpacket 11
679  * Most of this function is used only if superblock_type_2_3 == 0,
680  * never seen it in samples.
681  *
682  * @param tone_level_idx
683  * @param tone_level_idx_temp
684  * @param coding_method        q->coding_method[0][0][0]
685  * @param nb_channels          number of channels
686  * @param c                    coming from subpacket 11, passed as 8*c
687  * @param superblocktype_2_3   flag based on superblock packet type
688  * @param cm_table_select      q->cm_table_select
689  */
690 static void fill_coding_method_array(sb_int8_array tone_level_idx,
691                                      sb_int8_array tone_level_idx_temp,
692                                      sb_int8_array coding_method,
693                                      int nb_channels,
694                                      int c, int superblocktype_2_3,
695                                      int cm_table_select)
696 {
697     int ch, sb, j;
698     int tmp, acc, esp_40, comp;
699     int add1, add2, add3, add4;
700     int64_t multres;
701
702     if (!superblocktype_2_3) {
703         /* This case is untested, no samples available */
704         avpriv_request_sample(NULL, "!superblocktype_2_3");
705         return;
706         for (ch = 0; ch < nb_channels; ch++)
707             for (sb = 0; sb < 30; sb++) {
708                 for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer
709                     add1 = tone_level_idx[ch][sb][j] - 10;
710                     if (add1 < 0)
711                         add1 = 0;
712                     add2 = add3 = add4 = 0;
713                     if (sb > 1) {
714                         add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
715                         if (add2 < 0)
716                             add2 = 0;
717                     }
718                     if (sb > 0) {
719                         add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
720                         if (add3 < 0)
721                             add3 = 0;
722                     }
723                     if (sb < 29) {
724                         add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
725                         if (add4 < 0)
726                             add4 = 0;
727                     }
728                     tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
729                     if (tmp < 0)
730                         tmp = 0;
731                     tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
732                 }
733                 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
734             }
735             acc = 0;
736             for (ch = 0; ch < nb_channels; ch++)
737                 for (sb = 0; sb < 30; sb++)
738                     for (j = 0; j < 64; j++)
739                         acc += tone_level_idx_temp[ch][sb][j];
740
741             multres = 0x66666667LL * (acc * 10);
742             esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
743             for (ch = 0;  ch < nb_channels; ch++)
744                 for (sb = 0; sb < 30; sb++)
745                     for (j = 0; j < 64; j++) {
746                         comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
747                         if (comp < 0)
748                             comp += 0xff;
749                         comp /= 256; // signed shift
750                         switch(sb) {
751                             case 0:
752                                 if (comp < 30)
753                                     comp = 30;
754                                 comp += 15;
755                                 break;
756                             case 1:
757                                 if (comp < 24)
758                                     comp = 24;
759                                 comp += 10;
760                                 break;
761                             case 2:
762                             case 3:
763                             case 4:
764                                 if (comp < 16)
765                                     comp = 16;
766                         }
767                         if (comp <= 5)
768                             tmp = 0;
769                         else if (comp <= 10)
770                             tmp = 10;
771                         else if (comp <= 16)
772                             tmp = 16;
773                         else if (comp <= 24)
774                             tmp = -1;
775                         else
776                             tmp = 0;
777                         coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
778                     }
779             for (sb = 0; sb < 30; sb++)
780                 fix_coding_method_array(sb, nb_channels, coding_method);
781             for (ch = 0; ch < nb_channels; ch++)
782                 for (sb = 0; sb < 30; sb++)
783                     for (j = 0; j < 64; j++)
784                         if (sb >= 10) {
785                             if (coding_method[ch][sb][j] < 10)
786                                 coding_method[ch][sb][j] = 10;
787                         } else {
788                             if (sb >= 2) {
789                                 if (coding_method[ch][sb][j] < 16)
790                                     coding_method[ch][sb][j] = 16;
791                             } else {
792                                 if (coding_method[ch][sb][j] < 30)
793                                     coding_method[ch][sb][j] = 30;
794                             }
795                         }
796     } else { // superblocktype_2_3 != 0
797         for (ch = 0; ch < nb_channels; ch++)
798             for (sb = 0; sb < 30; sb++)
799                 for (j = 0; j < 64; j++)
800                     coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
801     }
802 }
803
804 /**
805  *
806  * Called by process_subpacket_11 to process more data from subpacket 11
807  * with sb 0-8.
808  * Called by process_subpacket_12 to process data from subpacket 12 with
809  * sb 8-sb_used.
810  *
811  * @param q         context
812  * @param gb        bitreader context
813  * @param length    packet length in bits
814  * @param sb_min    lower subband processed (sb_min included)
815  * @param sb_max    higher subband processed (sb_max excluded)
816  */
817 static int synthfilt_build_sb_samples(QDM2Context *q, GetBitContext *gb,
818                                        int length, int sb_min, int sb_max)
819 {
820     int sb, j, k, n, ch, run, channels;
821     int joined_stereo, zero_encoding;
822     int type34_first;
823     float type34_div = 0;
824     float type34_predictor;
825     float samples[10];
826     int sign_bits[16] = {0};
827
828     if (length == 0) {
829         // If no data use noise
830         for (sb=sb_min; sb < sb_max; sb++)
831             build_sb_samples_from_noise(q, sb);
832
833         return 0;
834     }
835
836     for (sb = sb_min; sb < sb_max; sb++) {
837         channels = q->nb_channels;
838
839         if (q->nb_channels <= 1 || sb < 12)
840             joined_stereo = 0;
841         else if (sb >= 24)
842             joined_stereo = 1;
843         else
844             joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
845
846         if (joined_stereo) {
847             if (get_bits_left(gb) >= 16)
848                 for (j = 0; j < 16; j++)
849                     sign_bits[j] = get_bits1(gb);
850
851             for (j = 0; j < 64; j++)
852                 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
853                     q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
854
855             if (fix_coding_method_array(sb, q->nb_channels,
856                                             q->coding_method)) {
857                 av_log(NULL, AV_LOG_ERROR, "coding method invalid\n");
858                 build_sb_samples_from_noise(q, sb);
859                 continue;
860             }
861             channels = 1;
862         }
863
864         for (ch = 0; ch < channels; ch++) {
865             FIX_NOISE_IDX(q->noise_idx);
866             zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
867             type34_predictor = 0.0;
868             type34_first = 1;
869
870             for (j = 0; j < 128; ) {
871                 switch (q->coding_method[ch][sb][j / 2]) {
872                     case 8:
873                         if (get_bits_left(gb) >= 10) {
874                             if (zero_encoding) {
875                                 for (k = 0; k < 5; k++) {
876                                     if ((j + 2 * k) >= 128)
877                                         break;
878                                     samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
879                                 }
880                             } else {
881                                 n = get_bits(gb, 8);
882                                 if (n >= 243) {
883                                     av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");
884                                     return AVERROR_INVALIDDATA;
885                                 }
886
887                                 for (k = 0; k < 5; k++)
888                                     samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
889                             }
890                             for (k = 0; k < 5; k++)
891                                 samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
892                         } else {
893                             for (k = 0; k < 10; k++)
894                                 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
895                         }
896                         run = 10;
897                         break;
898
899                     case 10:
900                         if (get_bits_left(gb) >= 1) {
901                             float f = 0.81;
902
903                             if (get_bits1(gb))
904                                 f = -f;
905                             f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
906                             samples[0] = f;
907                         } else {
908                             samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
909                         }
910                         run = 1;
911                         break;
912
913                     case 16:
914                         if (get_bits_left(gb) >= 10) {
915                             if (zero_encoding) {
916                                 for (k = 0; k < 5; k++) {
917                                     if ((j + k) >= 128)
918                                         break;
919                                     samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
920                                 }
921                             } else {
922                                 n = get_bits (gb, 8);
923                                 if (n >= 243) {
924                                     av_log(NULL, AV_LOG_ERROR, "Invalid 8bit codeword\n");
925                                     return AVERROR_INVALIDDATA;
926                                 }
927
928                                 for (k = 0; k < 5; k++)
929                                     samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
930                             }
931                         } else {
932                             for (k = 0; k < 5; k++)
933                                 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
934                         }
935                         run = 5;
936                         break;
937
938                     case 24:
939                         if (get_bits_left(gb) >= 7) {
940                             n = get_bits(gb, 7);
941                             if (n >= 125) {
942                                 av_log(NULL, AV_LOG_ERROR, "Invalid 7bit codeword\n");
943                                 return AVERROR_INVALIDDATA;
944                             }
945
946                             for (k = 0; k < 3; k++)
947                                 samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
948                         } else {
949                             for (k = 0; k < 3; k++)
950                                 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
951                         }
952                         run = 3;
953                         break;
954
955                     case 30:
956                         if (get_bits_left(gb) >= 4) {
957                             unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);
958                             if (index >= FF_ARRAY_ELEMS(type30_dequant)) {
959                                 av_log(NULL, AV_LOG_ERROR, "index %d out of type30_dequant array\n", index);
960                                 return AVERROR_INVALIDDATA;
961                             }
962                             samples[0] = type30_dequant[index];
963                         } else
964                             samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
965
966                         run = 1;
967                         break;
968
969                     case 34:
970                         if (get_bits_left(gb) >= 7) {
971                             if (type34_first) {
972                                 type34_div = (float)(1 << get_bits(gb, 2));
973                                 samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
974                                 type34_predictor = samples[0];
975                                 type34_first = 0;
976                             } else {
977                                 unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);
978                                 if (index >= FF_ARRAY_ELEMS(type34_delta)) {
979                                     av_log(NULL, AV_LOG_ERROR, "index %d out of type34_delta array\n", index);
980                                     return AVERROR_INVALIDDATA;
981                                 }
982                                 samples[0] = type34_delta[index] / type34_div + type34_predictor;
983                                 type34_predictor = samples[0];
984                             }
985                         } else {
986                             samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
987                         }
988                         run = 1;
989                         break;
990
991                     default:
992                         samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
993                         run = 1;
994                         break;
995                 }
996
997                 if (joined_stereo) {
998                     for (k = 0; k < run && j + k < 128; k++) {
999                         q->sb_samples[0][j + k][sb] =
1000                             q->tone_level[0][sb][(j + k) / 2] * samples[k];
1001                         if (q->nb_channels == 2) {
1002                             if (sign_bits[(j + k) / 8])
1003                                 q->sb_samples[1][j + k][sb] =
1004                                     q->tone_level[1][sb][(j + k) / 2] * -samples[k];
1005                             else
1006                                 q->sb_samples[1][j + k][sb] =
1007                                     q->tone_level[1][sb][(j + k) / 2] * samples[k];
1008                         }
1009                     }
1010                 } else {
1011                     for (k = 0; k < run; k++)
1012                         if ((j + k) < 128)
1013                             q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
1014                 }
1015
1016                 j += run;
1017             } // j loop
1018         } // channel loop
1019     } // subband loop
1020     return 0;
1021 }
1022
1023 /**
1024  * Init the first element of a channel in quantized_coeffs with data
1025  * from packet 10 (quantized_coeffs[ch][0]).
1026  * This is similar to process_subpacket_9, but for a single channel
1027  * and for element [0]
1028  * same VLC tables as process_subpacket_9 are used.
1029  *
1030  * @param quantized_coeffs    pointer to quantized_coeffs[ch][0]
1031  * @param gb        bitreader context
1032  */
1033 static int init_quantized_coeffs_elem0(int8_t *quantized_coeffs,
1034                                         GetBitContext *gb)
1035 {
1036     int i, k, run, level, diff;
1037
1038     if (get_bits_left(gb) < 16)
1039         return -1;
1040     level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
1041
1042     quantized_coeffs[0] = level;
1043
1044     for (i = 0; i < 7; ) {
1045         if (get_bits_left(gb) < 16)
1046             return -1;
1047         run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
1048
1049         if (i + run >= 8)
1050             return -1;
1051
1052         if (get_bits_left(gb) < 16)
1053             return -1;
1054         diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
1055
1056         for (k = 1; k <= run; k++)
1057             quantized_coeffs[i + k] = (level + ((k * diff) / run));
1058
1059         level += diff;
1060         i += run;
1061     }
1062     return 0;
1063 }
1064
1065 /**
1066  * Related to synthesis filter, process data from packet 10
1067  * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
1068  * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with
1069  * data from packet 10
1070  *
1071  * @param q         context
1072  * @param gb        bitreader context
1073  */
1074 static void init_tone_level_dequantization(QDM2Context *q, GetBitContext *gb)
1075 {
1076     int sb, j, k, n, ch;
1077
1078     for (ch = 0; ch < q->nb_channels; ch++) {
1079         init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb);
1080
1081         if (get_bits_left(gb) < 16) {
1082             memset(q->quantized_coeffs[ch][0], 0, 8);
1083             break;
1084         }
1085     }
1086
1087     n = q->sub_sampling + 1;
1088
1089     for (sb = 0; sb < n; sb++)
1090         for (ch = 0; ch < q->nb_channels; ch++)
1091             for (j = 0; j < 8; j++) {
1092                 if (get_bits_left(gb) < 1)
1093                     break;
1094                 if (get_bits1(gb)) {
1095                     for (k=0; k < 8; k++) {
1096                         if (get_bits_left(gb) < 16)
1097                             break;
1098                         q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1099                     }
1100                 } else {
1101                     for (k=0; k < 8; k++)
1102                         q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1103                 }
1104             }
1105
1106     n = QDM2_SB_USED(q->sub_sampling) - 4;
1107
1108     for (sb = 0; sb < n; sb++)
1109         for (ch = 0; ch < q->nb_channels; ch++) {
1110             if (get_bits_left(gb) < 16)
1111                 break;
1112             q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1113             if (sb > 19)
1114                 q->tone_level_idx_hi2[ch][sb] -= 16;
1115             else
1116                 for (j = 0; j < 8; j++)
1117                     q->tone_level_idx_mid[ch][sb][j] = -16;
1118         }
1119
1120     n = QDM2_SB_USED(q->sub_sampling) - 5;
1121
1122     for (sb = 0; sb < n; sb++)
1123         for (ch = 0; ch < q->nb_channels; ch++)
1124             for (j = 0; j < 8; j++) {
1125                 if (get_bits_left(gb) < 16)
1126                     break;
1127                 q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1128             }
1129 }
1130
1131 /**
1132  * Process subpacket 9, init quantized_coeffs with data from it
1133  *
1134  * @param q       context
1135  * @param node    pointer to node with packet
1136  */
1137 static int process_subpacket_9(QDM2Context *q, QDM2SubPNode *node)
1138 {
1139     GetBitContext gb;
1140     int i, j, k, n, ch, run, level, diff;
1141
1142     init_get_bits(&gb, node->packet->data, node->packet->size * 8);
1143
1144     n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
1145
1146     for (i = 1; i < n; i++)
1147         for (ch = 0; ch < q->nb_channels; ch++) {
1148             level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1149             q->quantized_coeffs[ch][i][0] = level;
1150
1151             for (j = 0; j < (8 - 1); ) {
1152                 run  = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1153                 diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1154
1155                 if (j + run >= 8)
1156                     return -1;
1157
1158                 for (k = 1; k <= run; k++)
1159                     q->quantized_coeffs[ch][i][j + k] = (level + ((k * diff) / run));
1160
1161                 level += diff;
1162                 j     += run;
1163             }
1164         }
1165
1166     for (ch = 0; ch < q->nb_channels; ch++)
1167         for (i = 0; i < 8; i++)
1168             q->quantized_coeffs[ch][0][i] = 0;
1169
1170     return 0;
1171 }
1172
1173 /**
1174  * Process subpacket 10 if not null, else
1175  *
1176  * @param q         context
1177  * @param node      pointer to node with packet
1178  */
1179 static void process_subpacket_10(QDM2Context *q, QDM2SubPNode *node)
1180 {
1181     GetBitContext gb;
1182
1183     if (node) {
1184         init_get_bits(&gb, node->packet->data, node->packet->size * 8);
1185         init_tone_level_dequantization(q, &gb);
1186         fill_tone_level_array(q, 1);
1187     } else {
1188         fill_tone_level_array(q, 0);
1189     }
1190 }
1191
1192 /**
1193  * Process subpacket 11
1194  *
1195  * @param q         context
1196  * @param node      pointer to node with packet
1197  */
1198 static void process_subpacket_11(QDM2Context *q, QDM2SubPNode *node)
1199 {
1200     GetBitContext gb;
1201     int length = 0;
1202
1203     if (node) {
1204         length = node->packet->size * 8;
1205         init_get_bits(&gb, node->packet->data, length);
1206     }
1207
1208     if (length >= 32) {
1209         int c = get_bits(&gb, 13);
1210
1211         if (c > 3)
1212             fill_coding_method_array(q->tone_level_idx,
1213                                      q->tone_level_idx_temp, q->coding_method,
1214                                      q->nb_channels, 8 * c,
1215                                      q->superblocktype_2_3, q->cm_table_select);
1216     }
1217
1218     synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1219 }
1220
1221 /**
1222  * Process subpacket 12
1223  *
1224  * @param q         context
1225  * @param node      pointer to node with packet
1226  */
1227 static void process_subpacket_12(QDM2Context *q, QDM2SubPNode *node)
1228 {
1229     GetBitContext gb;
1230     int length = 0;
1231
1232     if (node) {
1233         length = node->packet->size * 8;
1234         init_get_bits(&gb, node->packet->data, length);
1235     }
1236
1237     synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1238 }
1239
1240 /**
1241  * Process new subpackets for synthesis filter
1242  *
1243  * @param q       context
1244  * @param list    list with synthesis filter packets (list D)
1245  */
1246 static void process_synthesis_subpackets(QDM2Context *q, QDM2SubPNode *list)
1247 {
1248     QDM2SubPNode *nodes[4];
1249
1250     nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1251     if (nodes[0] != NULL)
1252         process_subpacket_9(q, nodes[0]);
1253
1254     nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1255     if (nodes[1] != NULL)
1256         process_subpacket_10(q, nodes[1]);
1257     else
1258         process_subpacket_10(q, NULL);
1259
1260     nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1261     if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1262         process_subpacket_11(q, nodes[2]);
1263     else
1264         process_subpacket_11(q, NULL);
1265
1266     nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1267     if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1268         process_subpacket_12(q, nodes[3]);
1269     else
1270         process_subpacket_12(q, NULL);
1271 }
1272
1273 /**
1274  * Decode superblock, fill packet lists.
1275  *
1276  * @param q    context
1277  */
1278 static void qdm2_decode_super_block(QDM2Context *q)
1279 {
1280     GetBitContext gb;
1281     QDM2SubPacket header, *packet;
1282     int i, packet_bytes, sub_packet_size, sub_packets_D;
1283     unsigned int next_index = 0;
1284
1285     memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1286     memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1287     memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1288
1289     q->sub_packets_B = 0;
1290     sub_packets_D    = 0;
1291
1292     average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1293
1294     init_get_bits(&gb, q->compressed_data, q->compressed_size * 8);
1295     qdm2_decode_sub_packet_header(&gb, &header);
1296
1297     if (header.type < 2 || header.type >= 8) {
1298         q->has_errors = 1;
1299         av_log(NULL, AV_LOG_ERROR, "bad superblock type\n");
1300         return;
1301     }
1302
1303     q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1304     packet_bytes          = (q->compressed_size - get_bits_count(&gb) / 8);
1305
1306     init_get_bits(&gb, header.data, header.size * 8);
1307
1308     if (header.type == 2 || header.type == 4 || header.type == 5) {
1309         int csum = 257 * get_bits(&gb, 8);
1310         csum += 2 * get_bits(&gb, 8);
1311
1312         csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1313
1314         if (csum != 0) {
1315             q->has_errors = 1;
1316             av_log(NULL, AV_LOG_ERROR, "bad packet checksum\n");
1317             return;
1318         }
1319     }
1320
1321     q->sub_packet_list_B[0].packet = NULL;
1322     q->sub_packet_list_D[0].packet = NULL;
1323
1324     for (i = 0; i < 6; i++)
1325         if (--q->fft_level_exp[i] < 0)
1326             q->fft_level_exp[i] = 0;
1327
1328     for (i = 0; packet_bytes > 0; i++) {
1329         int j;
1330
1331         if (i >= FF_ARRAY_ELEMS(q->sub_packet_list_A)) {
1332             SAMPLES_NEEDED_2("too many packet bytes");
1333             return;
1334         }
1335
1336         q->sub_packet_list_A[i].next = NULL;
1337
1338         if (i > 0) {
1339             q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1340
1341             /* seek to next block */
1342             init_get_bits(&gb, header.data, header.size * 8);
1343             skip_bits(&gb, next_index * 8);
1344
1345             if (next_index >= header.size)
1346                 break;
1347         }
1348
1349         /* decode subpacket */
1350         packet = &q->sub_packets[i];
1351         qdm2_decode_sub_packet_header(&gb, packet);
1352         next_index      = packet->size + get_bits_count(&gb) / 8;
1353         sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1354
1355         if (packet->type == 0)
1356             break;
1357
1358         if (sub_packet_size > packet_bytes) {
1359             if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1360                 break;
1361             packet->size += packet_bytes - sub_packet_size;
1362         }
1363
1364         packet_bytes -= sub_packet_size;
1365
1366         /* add subpacket to 'all subpackets' list */
1367         q->sub_packet_list_A[i].packet = packet;
1368
1369         /* add subpacket to related list */
1370         if (packet->type == 8) {
1371             SAMPLES_NEEDED_2("packet type 8");
1372             return;
1373         } else if (packet->type >= 9 && packet->type <= 12) {
1374             /* packets for MPEG Audio like Synthesis Filter */
1375             QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1376         } else if (packet->type == 13) {
1377             for (j = 0; j < 6; j++)
1378                 q->fft_level_exp[j] = get_bits(&gb, 6);
1379         } else if (packet->type == 14) {
1380             for (j = 0; j < 6; j++)
1381                 q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1382         } else if (packet->type == 15) {
1383             SAMPLES_NEEDED_2("packet type 15")
1384             return;
1385         } else if (packet->type >= 16 && packet->type < 48 &&
1386                    !fft_subpackets[packet->type - 16]) {
1387             /* packets for FFT */
1388             QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1389         }
1390     } // Packet bytes loop
1391
1392     if (q->sub_packet_list_D[0].packet != NULL) {
1393         process_synthesis_subpackets(q, q->sub_packet_list_D);
1394         q->do_synth_filter = 1;
1395     } else if (q->do_synth_filter) {
1396         process_subpacket_10(q, NULL);
1397         process_subpacket_11(q, NULL);
1398         process_subpacket_12(q, NULL);
1399     }
1400 }
1401
1402 static void qdm2_fft_init_coefficient(QDM2Context *q, int sub_packet,
1403                                       int offset, int duration, int channel,
1404                                       int exp, int phase)
1405 {
1406     if (q->fft_coefs_min_index[duration] < 0)
1407         q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1408
1409     q->fft_coefs[q->fft_coefs_index].sub_packet =
1410         ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1411     q->fft_coefs[q->fft_coefs_index].channel = channel;
1412     q->fft_coefs[q->fft_coefs_index].offset  = offset;
1413     q->fft_coefs[q->fft_coefs_index].exp     = exp;
1414     q->fft_coefs[q->fft_coefs_index].phase   = phase;
1415     q->fft_coefs_index++;
1416 }
1417
1418 static void qdm2_fft_decode_tones(QDM2Context *q, int duration,
1419                                   GetBitContext *gb, int b)
1420 {
1421     int channel, stereo, phase, exp;
1422     int local_int_4, local_int_8, stereo_phase, local_int_10;
1423     int local_int_14, stereo_exp, local_int_20, local_int_28;
1424     int n, offset;
1425
1426     local_int_4  = 0;
1427     local_int_28 = 0;
1428     local_int_20 = 2;
1429     local_int_8  = (4 - duration);
1430     local_int_10 = 1 << (q->group_order - duration - 1);
1431     offset       = 1;
1432
1433     while (get_bits_left(gb)>0) {
1434         if (q->superblocktype_2_3) {
1435             while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1436                 if (get_bits_left(gb)<0) {
1437                     if(local_int_4 < q->group_size)
1438                         av_log(NULL, AV_LOG_ERROR, "overread in qdm2_fft_decode_tones()\n");
1439                     return;
1440                 }
1441                 offset = 1;
1442                 if (n == 0) {
1443                     local_int_4  += local_int_10;
1444                     local_int_28 += (1 << local_int_8);
1445                 } else {
1446                     local_int_4  += 8 * local_int_10;
1447                     local_int_28 += (8 << local_int_8);
1448                 }
1449             }
1450             offset += (n - 2);
1451         } else {
1452             offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1453             while (offset >= (local_int_10 - 1)) {
1454                 offset       += (1 - (local_int_10 - 1));
1455                 local_int_4  += local_int_10;
1456                 local_int_28 += (1 << local_int_8);
1457             }
1458         }
1459
1460         if (local_int_4 >= q->group_size)
1461             return;
1462
1463         local_int_14 = (offset >> local_int_8);
1464         if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1465             return;
1466
1467         if (q->nb_channels > 1) {
1468             channel = get_bits1(gb);
1469             stereo  = get_bits1(gb);
1470         } else {
1471             channel = 0;
1472             stereo  = 0;
1473         }
1474
1475         exp  = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1476         exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1477         exp  = (exp < 0) ? 0 : exp;
1478
1479         phase        = get_bits(gb, 3);
1480         stereo_exp   = 0;
1481         stereo_phase = 0;
1482
1483         if (stereo) {
1484             stereo_exp   = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1485             stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1486             if (stereo_phase < 0)
1487                 stereo_phase += 8;
1488         }
1489
1490         if (q->frequency_range > (local_int_14 + 1)) {
1491             int sub_packet = (local_int_20 + local_int_28);
1492
1493             qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1494                                       channel, exp, phase);
1495             if (stereo)
1496                 qdm2_fft_init_coefficient(q, sub_packet, offset, duration,
1497                                           1 - channel,
1498                                           stereo_exp, stereo_phase);
1499         }
1500         offset++;
1501     }
1502 }
1503
1504 static void qdm2_decode_fft_packets(QDM2Context *q)
1505 {
1506     int i, j, min, max, value, type, unknown_flag;
1507     GetBitContext gb;
1508
1509     if (q->sub_packet_list_B[0].packet == NULL)
1510         return;
1511
1512     /* reset minimum indexes for FFT coefficients */
1513     q->fft_coefs_index = 0;
1514     for (i = 0; i < 5; i++)
1515         q->fft_coefs_min_index[i] = -1;
1516
1517     /* process subpackets ordered by type, largest type first */
1518     for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1519         QDM2SubPacket *packet = NULL;
1520
1521         /* find subpacket with largest type less than max */
1522         for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1523             value = q->sub_packet_list_B[j].packet->type;
1524             if (value > min && value < max) {
1525                 min    = value;
1526                 packet = q->sub_packet_list_B[j].packet;
1527             }
1528         }
1529
1530         max = min;
1531
1532         /* check for errors (?) */
1533         if (!packet)
1534             return;
1535
1536         if (i == 0 &&
1537             (packet->type < 16 || packet->type >= 48 ||
1538              fft_subpackets[packet->type - 16]))
1539             return;
1540
1541         /* decode FFT tones */
1542         init_get_bits(&gb, packet->data, packet->size * 8);
1543
1544         if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1545             unknown_flag = 1;
1546         else
1547             unknown_flag = 0;
1548
1549         type = packet->type;
1550
1551         if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1552             int duration = q->sub_sampling + 5 - (type & 15);
1553
1554             if (duration >= 0 && duration < 4)
1555                 qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1556         } else if (type == 31) {
1557             for (j = 0; j < 4; j++)
1558                 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1559         } else if (type == 46) {
1560             for (j = 0; j < 6; j++)
1561                 q->fft_level_exp[j] = get_bits(&gb, 6);
1562             for (j = 0; j < 4; j++)
1563                 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1564         }
1565     } // Loop on B packets
1566
1567     /* calculate maximum indexes for FFT coefficients */
1568     for (i = 0, j = -1; i < 5; i++)
1569         if (q->fft_coefs_min_index[i] >= 0) {
1570             if (j >= 0)
1571                 q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1572             j = i;
1573         }
1574     if (j >= 0)
1575         q->fft_coefs_max_index[j] = q->fft_coefs_index;
1576 }
1577
1578 static void qdm2_fft_generate_tone(QDM2Context *q, FFTTone *tone)
1579 {
1580     float level, f[6];
1581     int i;
1582     QDM2Complex c;
1583     const double iscale = 2.0 * M_PI / 512.0;
1584
1585     tone->phase += tone->phase_shift;
1586
1587     /* calculate current level (maximum amplitude) of tone */
1588     level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1589     c.im  = level * sin(tone->phase * iscale);
1590     c.re  = level * cos(tone->phase * iscale);
1591
1592     /* generate FFT coefficients for tone */
1593     if (tone->duration >= 3 || tone->cutoff >= 3) {
1594         tone->complex[0].im += c.im;
1595         tone->complex[0].re += c.re;
1596         tone->complex[1].im -= c.im;
1597         tone->complex[1].re -= c.re;
1598     } else {
1599         f[1] = -tone->table[4];
1600         f[0] = tone->table[3] - tone->table[0];
1601         f[2] = 1.0 - tone->table[2] - tone->table[3];
1602         f[3] = tone->table[1] + tone->table[4] - 1.0;
1603         f[4] = tone->table[0] - tone->table[1];
1604         f[5] = tone->table[2];
1605         for (i = 0; i < 2; i++) {
1606             tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re +=
1607                 c.re * f[i];
1608             tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im +=
1609                 c.im * ((tone->cutoff <= i) ? -f[i] : f[i]);
1610         }
1611         for (i = 0; i < 4; i++) {
1612             tone->complex[i].re += c.re * f[i + 2];
1613             tone->complex[i].im += c.im * f[i + 2];
1614         }
1615     }
1616
1617     /* copy the tone if it has not yet died out */
1618     if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1619         memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1620         q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1621     }
1622 }
1623
1624 static void qdm2_fft_tone_synthesizer(QDM2Context *q, int sub_packet)
1625 {
1626     int i, j, ch;
1627     const double iscale = 0.25 * M_PI;
1628
1629     for (ch = 0; ch < q->channels; ch++) {
1630         memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1631     }
1632
1633
1634     /* apply FFT tones with duration 4 (1 FFT period) */
1635     if (q->fft_coefs_min_index[4] >= 0)
1636         for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1637             float level;
1638             QDM2Complex c;
1639
1640             if (q->fft_coefs[i].sub_packet != sub_packet)
1641                 break;
1642
1643             ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1644             level = (q->fft_coefs[i].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[i].exp & 63];
1645
1646             c.re = level * cos(q->fft_coefs[i].phase * iscale);
1647             c.im = level * sin(q->fft_coefs[i].phase * iscale);
1648             q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1649             q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1650             q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1651             q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1652         }
1653
1654     /* generate existing FFT tones */
1655     for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1656         qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1657         q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1658     }
1659
1660     /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1661     for (i = 0; i < 4; i++)
1662         if (q->fft_coefs_min_index[i] >= 0) {
1663             for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1664                 int offset, four_i;
1665                 FFTTone tone;
1666
1667                 if (q->fft_coefs[j].sub_packet != sub_packet)
1668                     break;
1669
1670                 four_i = (4 - i);
1671                 offset = q->fft_coefs[j].offset >> four_i;
1672                 ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1673
1674                 if (offset < q->frequency_range) {
1675                     if (offset < 2)
1676                         tone.cutoff = offset;
1677                     else
1678                         tone.cutoff = (offset >= 60) ? 3 : 2;
1679
1680                     tone.level = (q->fft_coefs[j].exp < 0) ? 0.0 : fft_tone_level_table[q->superblocktype_2_3 ? 0 : 1][q->fft_coefs[j].exp & 63];
1681                     tone.complex = &q->fft.complex[ch][offset];
1682                     tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1683                     tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1684                     tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1685                     tone.duration = i;
1686                     tone.time_index = 0;
1687
1688                     qdm2_fft_generate_tone(q, &tone);
1689                 }
1690             }
1691             q->fft_coefs_min_index[i] = j;
1692         }
1693 }
1694
1695 static void qdm2_calculate_fft(QDM2Context *q, int channel, int sub_packet)
1696 {
1697     const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1698     float *out       = q->output_buffer + channel;
1699     int i;
1700     q->fft.complex[channel][0].re *= 2.0f;
1701     q->fft.complex[channel][0].im  = 0.0f;
1702     q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1703     /* add samples to output buffer */
1704     for (i = 0; i < FFALIGN(q->fft_size, 8); i++) {
1705         out[0]           += q->fft.complex[channel][i].re * gain;
1706         out[q->channels] += q->fft.complex[channel][i].im * gain;
1707         out              += 2 * q->channels;
1708     }
1709 }
1710
1711 /**
1712  * @param q        context
1713  * @param index    subpacket number
1714  */
1715 static void qdm2_synthesis_filter(QDM2Context *q, int index)
1716 {
1717     int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1718
1719     /* copy sb_samples */
1720     sb_used = QDM2_SB_USED(q->sub_sampling);
1721
1722     for (ch = 0; ch < q->channels; ch++)
1723         for (i = 0; i < 8; i++)
1724             for (k = sb_used; k < SBLIMIT; k++)
1725                 q->sb_samples[ch][(8 * index) + i][k] = 0;
1726
1727     for (ch = 0; ch < q->nb_channels; ch++) {
1728         float *samples_ptr = q->samples + ch;
1729
1730         for (i = 0; i < 8; i++) {
1731             ff_mpa_synth_filter_float(&q->mpadsp,
1732                                       q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1733                                       ff_mpa_synth_window_float, &dither_state,
1734                                       samples_ptr, q->nb_channels,
1735                                       q->sb_samples[ch][(8 * index) + i]);
1736             samples_ptr += 32 * q->nb_channels;
1737         }
1738     }
1739
1740     /* add samples to output buffer */
1741     sub_sampling = (4 >> q->sub_sampling);
1742
1743     for (ch = 0; ch < q->channels; ch++)
1744         for (i = 0; i < q->frame_size; i++)
1745             q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
1746 }
1747
1748 /**
1749  * Init static data (does not depend on specific file)
1750  *
1751  * @param q    context
1752  */
1753 static av_cold void qdm2_init_static_data(AVCodec *codec) {
1754     qdm2_init_vlc();
1755     ff_mpa_synth_init_float(ff_mpa_synth_window_float);
1756     softclip_table_init();
1757     rnd_table_init();
1758     init_noise_samples();
1759 }
1760
1761 /**
1762  * Init parameters from codec extradata
1763  */
1764 static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1765 {
1766     QDM2Context *s = avctx->priv_data;
1767     uint8_t *extradata;
1768     int extradata_size;
1769     int tmp_val, tmp, size;
1770
1771     /* extradata parsing
1772
1773     Structure:
1774     wave {
1775         frma (QDM2)
1776         QDCA
1777         QDCP
1778     }
1779
1780     32  size (including this field)
1781     32  tag (=frma)
1782     32  type (=QDM2 or QDMC)
1783
1784     32  size (including this field, in bytes)
1785     32  tag (=QDCA) // maybe mandatory parameters
1786     32  unknown (=1)
1787     32  channels (=2)
1788     32  samplerate (=44100)
1789     32  bitrate (=96000)
1790     32  block size (=4096)
1791     32  frame size (=256) (for one channel)
1792     32  packet size (=1300)
1793
1794     32  size (including this field, in bytes)
1795     32  tag (=QDCP) // maybe some tuneable parameters
1796     32  float1 (=1.0)
1797     32  zero ?
1798     32  float2 (=1.0)
1799     32  float3 (=1.0)
1800     32  unknown (27)
1801     32  unknown (8)
1802     32  zero ?
1803     */
1804
1805     if (!avctx->extradata || (avctx->extradata_size < 48)) {
1806         av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1807         return -1;
1808     }
1809
1810     extradata      = avctx->extradata;
1811     extradata_size = avctx->extradata_size;
1812
1813     while (extradata_size > 7) {
1814         if (!memcmp(extradata, "frmaQDM", 7))
1815             break;
1816         extradata++;
1817         extradata_size--;
1818     }
1819
1820     if (extradata_size < 12) {
1821         av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1822                extradata_size);
1823         return -1;
1824     }
1825
1826     if (memcmp(extradata, "frmaQDM", 7)) {
1827         av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1828         return -1;
1829     }
1830
1831     if (extradata[7] == 'C') {
1832 //        s->is_qdmc = 1;
1833         av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1834         return -1;
1835     }
1836
1837     extradata += 8;
1838     extradata_size -= 8;
1839
1840     size = AV_RB32(extradata);
1841
1842     if(size > extradata_size){
1843         av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1844                extradata_size, size);
1845         return -1;
1846     }
1847
1848     extradata += 4;
1849     av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1850     if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1851         av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1852         return -1;
1853     }
1854
1855     extradata += 8;
1856
1857     avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1858     extradata += 4;
1859     if (s->channels <= 0 || s->channels > MPA_MAX_CHANNELS) {
1860         av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");
1861         return AVERROR_INVALIDDATA;
1862     }
1863     avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
1864                                                    AV_CH_LAYOUT_MONO;
1865
1866     avctx->sample_rate = AV_RB32(extradata);
1867     extradata += 4;
1868
1869     avctx->bit_rate = AV_RB32(extradata);
1870     extradata += 4;
1871
1872     s->group_size = AV_RB32(extradata);
1873     extradata += 4;
1874
1875     s->fft_size = AV_RB32(extradata);
1876     extradata += 4;
1877
1878     s->checksum_size = AV_RB32(extradata);
1879     if (s->checksum_size >= 1U << 28) {
1880         av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
1881         return AVERROR_INVALIDDATA;
1882     }
1883
1884     s->fft_order = av_log2(s->fft_size) + 1;
1885
1886     // something like max decodable tones
1887     s->group_order = av_log2(s->group_size) + 1;
1888     s->frame_size = s->group_size / 16; // 16 iterations per super block
1889
1890     if (s->frame_size > QDM2_MAX_FRAME_SIZE)
1891         return AVERROR_INVALIDDATA;
1892
1893     s->sub_sampling = s->fft_order - 7;
1894     s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
1895
1896     switch ((s->sub_sampling * 2 + s->channels - 1)) {
1897         case 0: tmp = 40; break;
1898         case 1: tmp = 48; break;
1899         case 2: tmp = 56; break;
1900         case 3: tmp = 72; break;
1901         case 4: tmp = 80; break;
1902         case 5: tmp = 100;break;
1903         default: tmp=s->sub_sampling; break;
1904     }
1905     tmp_val = 0;
1906     if ((tmp * 1000) < avctx->bit_rate)  tmp_val = 1;
1907     if ((tmp * 1440) < avctx->bit_rate)  tmp_val = 2;
1908     if ((tmp * 1760) < avctx->bit_rate)  tmp_val = 3;
1909     if ((tmp * 2240) < avctx->bit_rate)  tmp_val = 4;
1910     s->cm_table_select = tmp_val;
1911
1912     if (avctx->bit_rate <= 8000)
1913         s->coeff_per_sb_select = 0;
1914     else if (avctx->bit_rate < 16000)
1915         s->coeff_per_sb_select = 1;
1916     else
1917         s->coeff_per_sb_select = 2;
1918
1919     // Fail on unknown fft order
1920     if ((s->fft_order < 7) || (s->fft_order > 9)) {
1921         av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1922         return -1;
1923     }
1924     if (s->fft_size != (1 << (s->fft_order - 1))) {
1925         av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", s->fft_size);
1926         return AVERROR_INVALIDDATA;
1927     }
1928
1929     ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
1930     ff_mpadsp_init(&s->mpadsp);
1931
1932     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1933
1934     return 0;
1935 }
1936
1937 static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1938 {
1939     QDM2Context *s = avctx->priv_data;
1940
1941     ff_rdft_end(&s->rdft_ctx);
1942
1943     return 0;
1944 }
1945
1946 static int qdm2_decode(QDM2Context *q, const uint8_t *in, int16_t *out)
1947 {
1948     int ch, i;
1949     const int frame_size = (q->frame_size * q->channels);
1950
1951     if((unsigned)frame_size > FF_ARRAY_ELEMS(q->output_buffer)/2)
1952         return -1;
1953
1954     /* select input buffer */
1955     q->compressed_data = in;
1956     q->compressed_size = q->checksum_size;
1957
1958     /* copy old block, clear new block of output samples */
1959     memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1960     memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1961
1962     /* decode block of QDM2 compressed data */
1963     if (q->sub_packet == 0) {
1964         q->has_errors = 0; // zero it for a new super block
1965         av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1966         qdm2_decode_super_block(q);
1967     }
1968
1969     /* parse subpackets */
1970     if (!q->has_errors) {
1971         if (q->sub_packet == 2)
1972             qdm2_decode_fft_packets(q);
1973
1974         qdm2_fft_tone_synthesizer(q, q->sub_packet);
1975     }
1976
1977     /* sound synthesis stage 1 (FFT) */
1978     for (ch = 0; ch < q->channels; ch++) {
1979         qdm2_calculate_fft(q, ch, q->sub_packet);
1980
1981         if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1982             SAMPLES_NEEDED_2("has errors, and C list is not empty")
1983             return -1;
1984         }
1985     }
1986
1987     /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1988     if (!q->has_errors && q->do_synth_filter)
1989         qdm2_synthesis_filter(q, q->sub_packet);
1990
1991     q->sub_packet = (q->sub_packet + 1) % 16;
1992
1993     /* clip and convert output float[] to 16bit signed samples */
1994     for (i = 0; i < frame_size; i++) {
1995         int value = (int)q->output_buffer[i];
1996
1997         if (value > SOFTCLIP_THRESHOLD)
1998             value = (value >  HARDCLIP_THRESHOLD) ?  32767 :  softclip_table[ value - SOFTCLIP_THRESHOLD];
1999         else if (value < -SOFTCLIP_THRESHOLD)
2000             value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
2001
2002         out[i] = value;
2003     }
2004
2005     return 0;
2006 }
2007
2008 static int qdm2_decode_frame(AVCodecContext *avctx, void *data,
2009                              int *got_frame_ptr, AVPacket *avpkt)
2010 {
2011     AVFrame *frame     = data;
2012     const uint8_t *buf = avpkt->data;
2013     int buf_size = avpkt->size;
2014     QDM2Context *s = avctx->priv_data;
2015     int16_t *out;
2016     int i, ret;
2017
2018     if(!buf)
2019         return 0;
2020     if(buf_size < s->checksum_size)
2021         return -1;
2022
2023     /* get output buffer */
2024     frame->nb_samples = 16 * s->frame_size;
2025     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
2026         return ret;
2027     out = (int16_t *)frame->data[0];
2028
2029     for (i = 0; i < 16; i++) {
2030         if (qdm2_decode(s, buf, out) < 0)
2031             return -1;
2032         out += s->channels * s->frame_size;
2033     }
2034
2035     *got_frame_ptr = 1;
2036
2037     return s->checksum_size;
2038 }
2039
2040 AVCodec ff_qdm2_decoder = {
2041     .name             = "qdm2",
2042     .long_name        = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),
2043     .type             = AVMEDIA_TYPE_AUDIO,
2044     .id               = AV_CODEC_ID_QDM2,
2045     .priv_data_size   = sizeof(QDM2Context),
2046     .init             = qdm2_decode_init,
2047     .init_static_data = qdm2_init_static_data,
2048     .close            = qdm2_decode_close,
2049     .decode           = qdm2_decode_frame,
2050     .capabilities     = CODEC_CAP_DR1,
2051 };