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