]> git.sesse.net Git - ffmpeg/blob - libavcodec/qdmc.c
Merge commit '39f3b6f3fc2b46b405b680cce3599f1b370e342d'
[ffmpeg] / libavcodec / qdmc.c
1 /*
2  * QDMC compatible decoder
3  * Copyright (c) 2017 Paul B Mahol
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include <math.h>
23 #include <stddef.h>
24 #include <stdio.h>
25
26 #define BITSTREAM_READER_LE
27
28 #include "libavutil/channel_layout.h"
29 #include "libavutil/thread.h"
30
31 #include "avcodec.h"
32 #include "bytestream.h"
33 #include "get_bits.h"
34 #include "internal.h"
35 #include "fft.h"
36
37 typedef struct QDMCTone {
38     uint8_t mode;
39     uint8_t phase;
40     uint8_t offset;
41     int16_t freq;
42     int16_t amplitude;
43 } QDMCTone;
44
45 typedef struct QDMCContext {
46     AVCodecContext *avctx;
47
48     uint8_t frame_bits;
49     int band_index;
50     int frame_size;
51     int subframe_size;
52     int fft_offset;
53     int buffer_offset;
54     int nb_channels;
55     int checksum_size;
56
57     uint8_t noise[2][19][17];
58     QDMCTone tones[5][8192];
59     int nb_tones[5];
60     int cur_tone[5];
61     float alt_sin[5][31];
62     float fft_buffer[4][8192 * 2];
63     float noise2_buffer[4096 * 2];
64     float noise_buffer[4096 * 2];
65     float buffer[2 * 32768];
66     float *buffer_ptr;
67     int rndval;
68
69     DECLARE_ALIGNED(32, FFTComplex, cmplx)[2][512];
70     FFTContext fft_ctx;
71 } QDMCContext;
72
73 static float sin_table[512];
74 static VLC vtable[6];
75
76 static const unsigned code_prefix[] = {
77     0x0, 0x1, 0x2, 0x3, 0x4, 0x6, 0x8, 0xA,
78     0xC, 0x10, 0x14, 0x18, 0x1C, 0x24, 0x2C, 0x34,
79     0x3C, 0x4C, 0x5C, 0x6C, 0x7C, 0x9C, 0xBC, 0xDC,
80     0xFC, 0x13C, 0x17C, 0x1BC, 0x1FC, 0x27C, 0x2FC, 0x37C,
81     0x3FC, 0x4FC, 0x5FC, 0x6FC, 0x7FC, 0x9FC, 0xBFC, 0xDFC,
82     0xFFC, 0x13FC, 0x17FC, 0x1BFC, 0x1FFC, 0x27FC, 0x2FFC, 0x37FC,
83     0x3FFC, 0x4FFC, 0x5FFC, 0x6FFC, 0x7FFC, 0x9FFC, 0xBFFC, 0xDFFC,
84     0xFFFC, 0x13FFC, 0x17FFC, 0x1BFFC, 0x1FFFC, 0x27FFC, 0x2FFFC, 0x37FFC,
85     0x3FFFC
86 };
87
88 static const float amplitude_tab[64] = {
89     1.18750000f, 1.68359380f, 2.37500000f, 3.36718750f, 4.75000000f,
90     6.73437500f, 9.50000000f, 13.4687500f, 19.0000000f, 26.9375000f,
91     38.0000000f, 53.8750000f, 76.0000000f, 107.750000f, 152.000000f,
92     215.500000f, 304.000000f, 431.000000f, 608.000000f, 862.000000f,
93     1216.00000f, 1724.00000f, 2432.00000f, 3448.00000f, 4864.00000f,
94     6896.00000f, 9728.00000f, 13792.0000f, 19456.0000f, 27584.0000f,
95     38912.0000f, 55168.0000f, 77824.0000f, 110336.000f, 155648.000f,
96     220672.000f, 311296.000f, 441344.000f, 622592.000f, 882688.000f,
97     1245184.00f, 1765376.00f, 2490368.00f, 3530752.00f, 4980736.00f,
98     7061504.00f, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
99 };
100
101 static const uint16_t qdmc_nodes[112] = {
102     0, 1, 2, 4, 6, 8, 12, 16, 24, 32, 48, 56, 64,
103     80, 96, 120, 144, 176, 208, 240, 256,
104     0, 2, 4, 8, 16, 24, 32, 48, 56, 64, 80, 104,
105     128, 160, 208, 256, 0, 0, 0, 0, 0,
106     0, 2, 4, 8, 16, 32, 48, 64, 80, 112, 160, 208,
107     256, 0, 0, 0, 0, 0, 0, 0, 0,
108     0, 4, 8, 16, 32, 48, 64, 96, 144, 208, 256,
109     0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
110     0, 4, 16, 32, 64, 256, 0, 0, 0, 0, 0, 0, 0, 0,
111     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
112 };
113
114 static const uint8_t noise_bands_size[] = {
115     19, 14, 11, 9, 4, 2, 0
116 };
117
118 static const uint8_t noise_bands_selector[] = {
119     4, 3, 2, 1, 0, 0, 0,
120 };
121
122 static const uint8_t noise_value_bits[] = {
123     12, 7, 9, 7, 10, 9, 11, 9, 9, 2, 9, 9, 9, 9,
124     9, 3, 9, 10, 10, 12, 2, 3, 3, 5, 5, 6, 7,
125 };
126
127 static const uint8_t noise_value_symbols[] = {
128     0, 10, 11, 12, 13, 14, 15, 16, 18, 1, 20, 22, 24,
129     26, 28, 2, 30, 32, 34, 36, 3, 4, 5, 6, 7, 8, 9,
130 };
131
132 static const uint16_t noise_value_codes[] = {
133     0xC7A, 0x002, 0x0FA, 0x03A, 0x35A, 0x1C2, 0x07A, 0x1FA,
134     0x17A, 0x000, 0x0DA, 0x142, 0x0C2, 0x042, 0x1DA, 0x001,
135     0x05A, 0x15A, 0x27A, 0x47A, 0x003, 0x005, 0x006, 0x012,
136     0x00A, 0x022, 0x01A,
137 };
138
139 static const uint8_t noise_segment_length_bits[] = {
140     10, 8, 5, 1, 2, 4, 4, 4, 6, 7, 9, 10,
141 };
142
143 static const uint8_t noise_segment_length_symbols[] = {
144     0, 13, 17, 1, 2, 3, 4, 5, 6, 7, 8, 9,
145 };
146
147 static const uint16_t noise_segment_length_codes[] = {
148     0x30B, 0x8B, 0x1B, 0x0, 0x1, 0x3, 0x7, 0xF, 0x2b, 0x4B, 0xB, 0x10B,
149 };
150
151 static const uint8_t freq_diff_bits[] = {
152     18, 2, 4, 4, 5, 4, 4, 5, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 7, 7, 6,
153     7, 6, 6, 6, 7, 7, 7, 7, 7, 8, 9, 9, 8, 9, 11, 11, 12, 12, 13, 12,
154     14, 15, 18, 16, 17,
155 };
156
157 static const uint32_t freq_diff_codes[] = {
158     0x2AD46, 0x1, 0x0, 0x3, 0xC, 0xA, 0x7, 0x18, 0x12, 0xE, 0x4, 0x16,
159     0xF, 0x1C, 0x8, 0x22, 0x26, 0x2, 0x3B, 0x34, 0x74, 0x1F, 0x14, 0x2B,
160     0x1B, 0x3F, 0x28, 0x54, 0x6, 0x4B, 0xB, 0x68, 0xE8, 0x46, 0xC6, 0x1E8,
161     0x146, 0x346, 0x546, 0x746, 0x1D46, 0xF46, 0xD46, 0x6D46, 0xAD46, 0x2D46,
162     0x1AD46,
163 };
164
165 static const uint8_t amplitude_bits[] = {
166     13, 7, 8, 9, 10, 10, 10, 10, 10, 9, 8, 7, 6,
167     5, 4, 3, 3, 2, 3, 3, 4, 5, 7, 8, 9, 11, 12, 13,
168 };
169
170 static const uint16_t amplitude_codes[] = {
171     0x1EC6, 0x6, 0xC2, 0x142, 0x242, 0x246, 0xC6, 0x46, 0x42, 0x146, 0xA2,
172     0x62, 0x26, 0x16, 0xE, 0x5, 0x4, 0x3, 0x0, 0x1, 0xA, 0x12, 0x2, 0x22,
173     0x1C6, 0x2C6, 0x6C6, 0xEC6,
174 };
175
176 static const uint8_t amplitude_diff_bits[] = {
177     8, 2, 1, 3, 4, 5, 6, 7, 8,
178 };
179
180 static const uint8_t amplitude_diff_codes[] = {
181     0xFE, 0x0, 0x1, 0x2, 0x6, 0xE, 0x1E, 0x3E, 0x7E,
182 };
183
184 static const uint8_t phase_diff_bits[] = {
185     6, 2, 2, 4, 4, 6, 5, 4, 2,
186 };
187
188 static const uint8_t phase_diff_codes[] = {
189     0x35, 0x2, 0x0, 0x1, 0xD, 0x15, 0x5, 0x9, 0x3,
190 };
191
192 #define INIT_VLC_STATIC_LE(vlc, nb_bits, nb_codes,                 \
193                            bits, bits_wrap, bits_size,             \
194                            codes, codes_wrap, codes_size,          \
195                            symbols, symbols_wrap, symbols_size,    \
196                            static_size)                            \
197     do {                                                           \
198         static VLC_TYPE table[static_size][2];                     \
199         (vlc)->table           = table;                            \
200         (vlc)->table_allocated = static_size;                      \
201         ff_init_vlc_sparse(vlc, nb_bits, nb_codes,                 \
202                            bits, bits_wrap, bits_size,             \
203                            codes, codes_wrap, codes_size,          \
204                            symbols, symbols_wrap, symbols_size,    \
205                            INIT_VLC_LE | INIT_VLC_USE_NEW_STATIC); \
206     } while (0)
207
208 static av_cold void qdmc_init_static_data(void)
209 {
210     int i;
211
212     INIT_VLC_STATIC_LE(&vtable[0], 12, FF_ARRAY_ELEMS(noise_value_bits),
213                        noise_value_bits, 1, 1, noise_value_codes, 2, 2, noise_value_symbols, 1, 1, 4096);
214     INIT_VLC_STATIC_LE(&vtable[1], 10, FF_ARRAY_ELEMS(noise_segment_length_bits),
215                        noise_segment_length_bits, 1, 1, noise_segment_length_codes, 2, 2,
216                        noise_segment_length_symbols, 1, 1, 1024);
217     INIT_VLC_STATIC_LE(&vtable[2], 13, FF_ARRAY_ELEMS(amplitude_bits),
218                        amplitude_bits, 1, 1, amplitude_codes, 2, 2, NULL, 0, 0, 8192);
219     INIT_VLC_STATIC_LE(&vtable[3], 18, FF_ARRAY_ELEMS(freq_diff_bits),
220                        freq_diff_bits, 1, 1, freq_diff_codes, 4, 4, NULL, 0, 0, 262144);
221     INIT_VLC_STATIC_LE(&vtable[4], 8, FF_ARRAY_ELEMS(amplitude_diff_bits),
222                        amplitude_diff_bits, 1, 1, amplitude_diff_codes, 1, 1, NULL, 0, 0, 256);
223     INIT_VLC_STATIC_LE(&vtable[5], 6, FF_ARRAY_ELEMS(phase_diff_bits),
224                        phase_diff_bits, 1, 1, phase_diff_codes, 1, 1, NULL, 0, 0, 64);
225
226     for (i = 0; i < 512; i++)
227         sin_table[i] = sin(2.0f * i * M_PI * 0.001953125f);
228 }
229
230 static void make_noises(QDMCContext *s)
231 {
232     int i, j, n0, n1, n2, diff;
233     float *nptr;
234
235     for (j = 0; j < noise_bands_size[s->band_index]; j++) {
236         n0 = qdmc_nodes[j + 21 * s->band_index    ];
237         n1 = qdmc_nodes[j + 21 * s->band_index + 1];
238         n2 = qdmc_nodes[j + 21 * s->band_index + 2];
239         nptr = s->noise_buffer + 256 * j;
240
241         for (i = 0; i + n0 < n1; i++, nptr++)
242             nptr[0] = i / (float)(n1 - n0);
243
244         diff = n2 - n1;
245         nptr = s->noise_buffer + (j << 8) + n1 - n0;
246
247         for (i = n1; i < n2; i++, nptr++, diff--)
248             nptr[0] = diff / (float)(n2 - n1);
249     }
250 }
251
252 static av_cold int qdmc_decode_init(AVCodecContext *avctx)
253 {
254     static AVOnce init_static_once = AV_ONCE_INIT;
255     QDMCContext *s = avctx->priv_data;
256     int fft_size, fft_order, size, g, j, x;
257     GetByteContext b;
258
259     ff_thread_once(&init_static_once, qdmc_init_static_data);
260
261     if (!avctx->extradata || (avctx->extradata_size < 48)) {
262         av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
263         return AVERROR_INVALIDDATA;
264     }
265
266     bytestream2_init(&b, avctx->extradata, avctx->extradata_size);
267
268     while (bytestream2_get_bytes_left(&b) > 8) {
269         if (bytestream2_peek_be64(&b) == (((uint64_t)MKBETAG('f','r','m','a') << 32) |
270                                            (uint64_t)MKBETAG('Q','D','M','C')))
271             break;
272         bytestream2_skipu(&b, 1);
273     }
274     bytestream2_skipu(&b, 8);
275
276     if (bytestream2_get_bytes_left(&b) < 36) {
277         av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
278                bytestream2_get_bytes_left(&b));
279         return AVERROR_INVALIDDATA;
280     }
281
282     size = bytestream2_get_be32u(&b);
283     if (size > bytestream2_get_bytes_left(&b)) {
284         av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
285                bytestream2_get_bytes_left(&b), size);
286         return AVERROR_INVALIDDATA;
287     }
288
289     if (bytestream2_get_be32u(&b) != MKBETAG('Q','D','C','A')) {
290         av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
291         return AVERROR_INVALIDDATA;
292     }
293     bytestream2_skipu(&b, 4);
294
295     avctx->channels = s->nb_channels = bytestream2_get_be32u(&b);
296     if (s->nb_channels <= 0 || s->nb_channels > 2) {
297         av_log(avctx, AV_LOG_ERROR, "invalid number of channels\n");
298         return AVERROR_INVALIDDATA;
299     }
300     avctx->channel_layout = avctx->channels == 2 ? AV_CH_LAYOUT_STEREO :
301                                                    AV_CH_LAYOUT_MONO;
302
303     avctx->sample_rate = bytestream2_get_be32u(&b);
304     avctx->bit_rate = bytestream2_get_be32u(&b);
305     bytestream2_skipu(&b, 4);
306     fft_size = bytestream2_get_be32u(&b);
307     fft_order = av_log2(fft_size) + 1;
308     s->checksum_size = bytestream2_get_be32u(&b);
309     if (s->checksum_size >= 1U << 28) {
310         av_log(avctx, AV_LOG_ERROR, "data block size too large (%u)\n", s->checksum_size);
311         return AVERROR_INVALIDDATA;
312     }
313
314     if (avctx->sample_rate >= 32000) {
315         x = 28000;
316         s->frame_bits = 13;
317     } else if (avctx->sample_rate >= 16000) {
318         x = 20000;
319         s->frame_bits = 12;
320     } else {
321         x = 16000;
322         s->frame_bits = 11;
323     }
324     s->frame_size = 1 << s->frame_bits;
325     s->subframe_size = s->frame_size >> 5;
326
327     if (avctx->channels == 2)
328         x = 3 * x / 2;
329     s->band_index = noise_bands_selector[FFMIN(6, llrint(floor(avctx->bit_rate * 3.0 / (double)x + 0.5)))];
330
331     if ((fft_order < 7) || (fft_order > 9)) {
332         avpriv_request_sample(avctx, "Unknown FFT order %d", fft_order);
333         return AVERROR_PATCHWELCOME;
334     }
335
336     if (fft_size != (1 << (fft_order - 1))) {
337         av_log(avctx, AV_LOG_ERROR, "FFT size %d not power of 2.\n", fft_size);
338         return AVERROR_INVALIDDATA;
339     }
340
341     ff_fft_init(&s->fft_ctx, fft_order, 1);
342
343     avctx->sample_fmt = AV_SAMPLE_FMT_S16;
344
345     for (g = 5; g > 0; g--) {
346         for (j = 0; j < (1 << g) - 1; j++)
347             s->alt_sin[5-g][j] = sin_table[(((j+1) << (8 - g)) & 0x1FF)];
348     }
349
350     make_noises(s);
351
352     return 0;
353 }
354
355 static av_cold int qdmc_decode_close(AVCodecContext *avctx)
356 {
357     QDMCContext *s = avctx->priv_data;
358
359     ff_fft_end(&s->fft_ctx);
360
361     return 0;
362 }
363
364 static int qdmc_get_vlc(GetBitContext *gb, VLC *table, int flag)
365 {
366     int v;
367
368     v = get_vlc2(gb, table->table, table->bits, 1);
369     if (v < 0)
370         return AVERROR_INVALIDDATA;
371     if (v)
372         v = v - 1;
373     else
374         v = get_bits(gb, get_bits(gb, 3) + 1);
375
376     if (flag) {
377         if (v >= FF_ARRAY_ELEMS(code_prefix))
378             return AVERROR_INVALIDDATA;
379
380         v = code_prefix[v] + get_bitsz(gb, v >> 2);
381     }
382
383     return v;
384 }
385
386 static int skip_label(QDMCContext *s, GetBitContext *gb)
387 {
388     uint32_t label = get_bits_long(gb, 32);
389     uint16_t sum = 226, checksum = get_bits(gb, 16);
390     const uint8_t *ptr = gb->buffer + 6;
391     int i;
392
393     if (label != MKTAG('Q', 'M', 'C', 1))
394         return AVERROR_INVALIDDATA;
395
396     for (i = 0; i < s->checksum_size - 6; i++)
397         sum += ptr[i];
398
399     return sum != checksum;
400 }
401
402 static int read_noise_data(QDMCContext *s, GetBitContext *gb)
403 {
404     int ch, j, k, v, idx, band, lastval, newval, len;
405
406     for (ch = 0; ch < s->nb_channels; ch++) {
407         for (band = 0; band < noise_bands_size[s->band_index]; band++) {
408             v = qdmc_get_vlc(gb, &vtable[0], 0);
409             if (v < 0)
410                 return AVERROR_INVALIDDATA;
411
412             if (v & 1)
413                 v = v + 1;
414             else
415                 v = -v;
416
417             lastval = v / 2;
418             s->noise[ch][band][0] = lastval - 1;
419             for (j = 0; j < 15;) {
420                 len = qdmc_get_vlc(gb, &vtable[1], 1);
421                 if (len < 0)
422                     return AVERROR_INVALIDDATA;
423                 len += 1;
424
425                 v = qdmc_get_vlc(gb, &vtable[0], 0);
426                 if (v < 0)
427                     return AVERROR_INVALIDDATA;
428
429                 if (v & 1)
430                     newval = lastval + (v + 1) / 2;
431                 else
432                     newval = lastval - v / 2;
433
434                 idx = j + 1;
435                 if (len + idx > 16)
436                     return AVERROR_INVALIDDATA;
437
438                 for (k = 1; idx <= j + len; k++, idx++)
439                     s->noise[ch][band][idx] = lastval + k * (newval - lastval) / len - 1;
440
441                 lastval = newval;
442                 j += len;
443             }
444         }
445     }
446
447     return 0;
448 }
449
450 static void add_tone(QDMCContext *s, int group, int offset, int freq, int stereo_mode, int amplitude, int phase)
451 {
452     const int index = s->nb_tones[group];
453
454     if (index >= FF_ARRAY_ELEMS(s->tones[group])) {
455         av_log(s->avctx, AV_LOG_WARNING, "Too many tones already in buffer, ignoring tone!\n");
456         return;
457     }
458
459     s->tones[group][index].offset    = offset;
460     s->tones[group][index].freq      = freq;
461     s->tones[group][index].mode      = stereo_mode;
462     s->tones[group][index].amplitude = amplitude;
463     s->tones[group][index].phase     = phase;
464     s->nb_tones[group]++;
465 }
466
467 static int read_wave_data(QDMCContext *s, GetBitContext *gb)
468 {
469     int amp, phase, stereo_mode = 0, i, group, freq, group_size, group_bits;
470     int amp2, phase2, pos2, off;
471
472     for (group = 0; group < 5; group++) {
473         group_size = 1 << (s->frame_bits - group - 1);
474         group_bits = 4 - group;
475         pos2 = 0;
476         off  = 0;
477
478         for (i = 1; ; i = freq + 1) {
479             int v;
480
481             v = qdmc_get_vlc(gb, &vtable[3], 1);
482             if (v < 0)
483                 return AVERROR_INVALIDDATA;
484
485             freq = i + v;
486             while (freq >= group_size - 1) {
487                 freq += 2 - group_size;
488                 pos2 += group_size;
489                 off  += 1 << group_bits;
490             }
491
492             if (pos2 >= s->frame_size)
493                 break;
494
495             if (s->nb_channels > 1)
496                 stereo_mode = get_bits(gb, 2);
497
498             amp   = qdmc_get_vlc(gb, &vtable[2], 0);
499             if (amp < 0)
500                 return AVERROR_INVALIDDATA;
501             phase = get_bits(gb, 3);
502
503             if (stereo_mode > 1) {
504                 amp2   = qdmc_get_vlc(gb, &vtable[4], 0);
505                 if (amp2 < 0)
506                     return AVERROR_INVALIDDATA;
507                 amp2   = amp - amp2;
508
509                 phase2 = qdmc_get_vlc(gb, &vtable[5], 0);
510                 if (phase2 < 0)
511                     return AVERROR_INVALIDDATA;
512                 phase2 = phase - phase2;
513
514                 if (phase2 < 0)
515                     phase2 += 8;
516             }
517
518             if ((freq >> group_bits) + 1 < s->subframe_size) {
519                 add_tone(s, group, off, freq, stereo_mode & 1, amp, phase);
520                 if (stereo_mode > 1)
521                     add_tone(s, group, off, freq, ~stereo_mode & 1, amp2, phase2);
522             }
523         }
524     }
525
526     return 0;
527 }
528
529 static void lin_calc(QDMCContext *s, float amplitude, int node1, int node2, int index)
530 {
531     int subframe_size, i, j, k, length;
532     float scale, *noise_ptr;
533
534     scale = 0.5 * amplitude;
535     subframe_size = s->subframe_size;
536     if (subframe_size >= node2)
537         subframe_size = node2;
538     length = (subframe_size - node1) & 0xFFFC;
539     j = node1;
540     noise_ptr = &s->noise_buffer[256 * index];
541
542     for (i = 0; i < length; i += 4, j+= 4, noise_ptr += 4) {
543         s->noise2_buffer[j    ] += scale * noise_ptr[0];
544         s->noise2_buffer[j + 1] += scale * noise_ptr[1];
545         s->noise2_buffer[j + 2] += scale * noise_ptr[2];
546         s->noise2_buffer[j + 3] += scale * noise_ptr[3];
547     }
548
549     k = length + node1;
550     noise_ptr = s->noise_buffer + length + (index << 8);
551     for (i = length; i < subframe_size - node1; i++, k++, noise_ptr++)
552         s->noise2_buffer[k] += scale * noise_ptr[0];
553 }
554
555 static void add_noise(QDMCContext *s, int ch, int current_subframe)
556 {
557     int i, j, aindex;
558     float amplitude;
559     float *im = &s->fft_buffer[0 + ch][s->fft_offset + s->subframe_size * current_subframe];
560     float *re = &s->fft_buffer[2 + ch][s->fft_offset + s->subframe_size * current_subframe];
561
562     memset(s->noise2_buffer, 0, 4 * s->subframe_size);
563
564     for (i = 0; i < noise_bands_size[s->band_index]; i++) {
565         if (qdmc_nodes[i + 21 * s->band_index] > s->subframe_size - 1)
566             break;
567
568         aindex = s->noise[ch][i][current_subframe / 2];
569         amplitude = aindex > 0 ? amplitude_tab[aindex & 0x3F] : 0.0f;
570
571         lin_calc(s, amplitude, qdmc_nodes[21 * s->band_index + i],
572                  qdmc_nodes[21 * s->band_index + i + 2], i);
573     }
574
575     for (j = 2; j < s->subframe_size - 1; j++) {
576         float rnd_re, rnd_im;
577
578         s->rndval = 214013 * s->rndval + 2531011;
579         rnd_im = ((s->rndval & 0x7FFF) - 16384.0f) * 0.000030517578f * s->noise2_buffer[j];
580         s->rndval = 214013 * s->rndval + 2531011;
581         rnd_re = ((s->rndval & 0x7FFF) - 16384.0f) * 0.000030517578f * s->noise2_buffer[j];
582         im[j  ] += rnd_im;
583         re[j  ] += rnd_re;
584         im[j+1] -= rnd_im;
585         re[j+1] -= rnd_re;
586     }
587 }
588
589 static void add_wave(QDMCContext *s, int offset, int freqs, int group, int stereo_mode, int amp, int phase)
590 {
591     int j, group_bits, pos, pindex;
592     float im, re, amplitude, level, *imptr, *reptr;
593
594     if (s->nb_channels == 1)
595         stereo_mode = 0;
596
597     group_bits = 4 - group;
598     pos = freqs >> (4 - group);
599     amplitude = amplitude_tab[amp & 0x3F];
600     imptr = &s->fft_buffer[    stereo_mode][s->fft_offset + s->subframe_size * offset + pos];
601     reptr = &s->fft_buffer[2 + stereo_mode][s->fft_offset + s->subframe_size * offset + pos];
602     pindex = (phase << 6) - ((2 * (freqs >> (4 - group)) + 1) << 7);
603     for (j = 0; j < (1 << (group_bits + 1)) - 1; j++) {
604         pindex += (2 * freqs + 1) << (7 - group_bits);
605         level = amplitude * s->alt_sin[group][j];
606         im = level * sin_table[ pindex        & 0x1FF];
607         re = level * sin_table[(pindex + 128) & 0x1FF];
608         imptr[0] += im;
609         imptr[1] -= im;
610         reptr[0] += re;
611         reptr[1] -= re;
612         imptr += s->subframe_size;
613         reptr += s->subframe_size;
614         if (imptr >= &s->fft_buffer[stereo_mode][2 * s->frame_size]) {
615             imptr = &s->fft_buffer[0 + stereo_mode][pos];
616             reptr = &s->fft_buffer[2 + stereo_mode][pos];
617         }
618     }
619 }
620
621 static void add_wave0(QDMCContext *s, int offset, int freqs, int stereo_mode, int amp, int phase)
622 {
623     float level, im, re;
624     int pos;
625
626     if (s->nb_channels == 1)
627         stereo_mode = 0;
628
629     level = amplitude_tab[amp & 0x3F];
630     im = level * sin_table[ (phase << 6)        & 0x1FF];
631     re = level * sin_table[((phase << 6) + 128) & 0x1FF];
632     pos = s->fft_offset + freqs + s->subframe_size * offset;
633     s->fft_buffer[    stereo_mode][pos    ] += im;
634     s->fft_buffer[2 + stereo_mode][pos    ] += re;
635     s->fft_buffer[    stereo_mode][pos + 1] -= im;
636     s->fft_buffer[2 + stereo_mode][pos + 1] -= re;
637 }
638
639 static void add_waves(QDMCContext *s, int current_subframe)
640 {
641     int w, g;
642
643     for (g = 0; g < 4; g++) {
644         for (w = s->cur_tone[g]; w < s->nb_tones[g]; w++) {
645             QDMCTone *t = &s->tones[g][w];
646
647             if (current_subframe < t->offset)
648                 break;
649             add_wave(s, t->offset, t->freq, g, t->mode, t->amplitude, t->phase);
650         }
651         s->cur_tone[g] = w;
652     }
653     for (w = s->cur_tone[4]; w < s->nb_tones[4]; w++) {
654         QDMCTone *t = &s->tones[4][w];
655
656         if (current_subframe < t->offset)
657             break;
658         add_wave0(s, t->offset, t->freq, t->mode, t->amplitude, t->phase);
659     }
660     s->cur_tone[4] = w;
661 }
662
663 static int decode_frame(QDMCContext *s, GetBitContext *gb, int16_t *out)
664 {
665     int ret, ch, i, n;
666
667     if (skip_label(s, gb))
668         return AVERROR_INVALIDDATA;
669
670     s->fft_offset = s->frame_size - s->fft_offset;
671     s->buffer_ptr = &s->buffer[s->nb_channels * s->buffer_offset];
672
673     ret = read_noise_data(s, gb);
674     if (ret < 0)
675         return ret;
676
677     ret = read_wave_data(s, gb);
678     if (ret < 0)
679         return ret;
680
681     for (n = 0; n < 32; n++) {
682         float *r;
683
684         for (ch = 0; ch < s->nb_channels; ch++)
685             add_noise(s, ch, n);
686
687         add_waves(s, n);
688
689         for (ch = 0; ch < s->nb_channels; ch++) {
690             for (i = 0; i < s->subframe_size; i++) {
691                 s->cmplx[ch][i].re = s->fft_buffer[ch + 2][s->fft_offset + n * s->subframe_size + i];
692                 s->cmplx[ch][i].im = s->fft_buffer[ch + 0][s->fft_offset + n * s->subframe_size + i];
693                 s->cmplx[ch][s->subframe_size + i].re = 0;
694                 s->cmplx[ch][s->subframe_size + i].im = 0;
695             }
696         }
697
698         for (ch = 0; ch < s->nb_channels; ch++) {
699             s->fft_ctx.fft_permute(&s->fft_ctx, s->cmplx[ch]);
700             s->fft_ctx.fft_calc(&s->fft_ctx, s->cmplx[ch]);
701         }
702
703         r = &s->buffer_ptr[s->nb_channels * n * s->subframe_size];
704         for (i = 0; i < 2 * s->subframe_size; i++) {
705             for (ch = 0; ch < s->nb_channels; ch++) {
706                 *r++ += s->cmplx[ch][i].re;
707             }
708         }
709
710         r = &s->buffer_ptr[n * s->subframe_size * s->nb_channels];
711         for (i = 0; i < s->nb_channels * s->subframe_size; i++) {
712             out[i] = av_clipf(r[i], INT16_MIN, INT16_MAX);
713         }
714         out += s->subframe_size * s->nb_channels;
715
716         for (ch = 0; ch < s->nb_channels; ch++) {
717             memset(s->fft_buffer[ch+0] + s->fft_offset + n * s->subframe_size, 0, 4 * s->subframe_size);
718             memset(s->fft_buffer[ch+2] + s->fft_offset + n * s->subframe_size, 0, 4 * s->subframe_size);
719         }
720         memset(s->buffer + s->nb_channels * (n * s->subframe_size + s->frame_size + s->buffer_offset), 0, 4 * s->subframe_size * s->nb_channels);
721     }
722
723     s->buffer_offset += s->frame_size;
724     if (s->buffer_offset >= 32768 - s->frame_size) {
725         memcpy(s->buffer, &s->buffer[s->nb_channels * s->buffer_offset], 4 * s->frame_size * s->nb_channels);
726         s->buffer_offset = 0;
727     }
728
729     return 0;
730 }
731
732 static av_cold void qdmc_flush(AVCodecContext *avctx)
733 {
734     QDMCContext *s = avctx->priv_data;
735
736     memset(s->buffer, 0, sizeof(s->buffer));
737     memset(s->fft_buffer, 0, sizeof(s->fft_buffer));
738     s->fft_offset = 0;
739     s->buffer_offset = 0;
740 }
741
742 static int qdmc_decode_frame(AVCodecContext *avctx, void *data,
743                              int *got_frame_ptr, AVPacket *avpkt)
744 {
745     QDMCContext *s = avctx->priv_data;
746     AVFrame *frame = data;
747     GetBitContext gb;
748     int ret;
749
750     if (!avpkt->data)
751         return 0;
752     if (avpkt->size < s->checksum_size)
753         return AVERROR_INVALIDDATA;
754
755     s->avctx = avctx;
756     frame->nb_samples = s->frame_size;
757     if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
758         return ret;
759
760     if ((ret = init_get_bits8(&gb, avpkt->data, s->checksum_size)) < 0)
761         return ret;
762
763     memset(s->nb_tones, 0, sizeof(s->nb_tones));
764     memset(s->cur_tone, 0, sizeof(s->cur_tone));
765
766     ret = decode_frame(s, &gb, (int16_t *)frame->data[0]);
767     if (ret >= 0) {
768         *got_frame_ptr = 1;
769         return s->checksum_size;
770     }
771     qdmc_flush(avctx);
772     return ret;
773 }
774
775 AVCodec ff_qdmc_decoder = {
776     .name             = "qdmc",
777     .long_name        = NULL_IF_CONFIG_SMALL("QDesign Music Codec 1"),
778     .type             = AVMEDIA_TYPE_AUDIO,
779     .id               = AV_CODEC_ID_QDMC,
780     .priv_data_size   = sizeof(QDMCContext),
781     .init             = qdmc_decode_init,
782     .close            = qdmc_decode_close,
783     .decode           = qdmc_decode_frame,
784     .flush            = qdmc_flush,
785     .capabilities     = AV_CODEC_CAP_DR1,
786 };