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