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