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