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
8 * This file is part of Libav.
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.
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.
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
28 * @author Ewald Snel, Benjamin Larsson, Alex Beregszaszi, Roberto Togni
30 * The decoder is not perfect yet, there are still some distortions
31 * especially on files encoded with 16 or 8 subbands.
38 #define BITSTREAM_READER_LE
43 #include "mpegaudiodsp.h"
44 #include "mpegaudio.h"
47 #include "qdm2_tablegen.h"
53 #define QDM2_LIST_ADD(list, size, packet) \
56 list[size - 1].next = &list[size]; \
58 list[size].packet = packet; \
59 list[size].next = NULL; \
63 // Result is 8, 16 or 30
64 #define QDM2_SB_USED(sub_sampling) (((sub_sampling) >= 2) ? 30 : 8 << (sub_sampling))
66 #define FIX_NOISE_IDX(noise_idx) \
67 if ((noise_idx) >= 3840) \
68 (noise_idx) -= 3840; \
70 #define SB_DITHERING_NOISE(sb,noise_idx) (noise_table[(noise_idx)++] * sb_noise_attenuation[(sb)])
72 #define SAMPLES_NEEDED \
73 av_log (NULL,AV_LOG_INFO,"This file triggers some untested code. Please contact the developers.\n");
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);
78 #define QDM2_MAX_FRAME_SIZE 512
80 typedef int8_t sb_int8_array[2][30][64];
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)
92 * A node in the subpacket list
94 typedef struct QDM2SubPNode {
95 QDM2SubPacket *packet; ///< packet
96 struct QDM2SubPNode *next; ///< pointer to next packet in the list, NULL if leaf node
106 QDM2Complex *complex;
124 DECLARE_ALIGNED(32, QDM2Complex, complex)[MPA_MAX_CHANNELS][256];
128 * QDM2 decoder context
133 /// Parameters from codec header, do not change during playback
134 int nb_channels; ///< number of channels
135 int channels; ///< number of channels
136 int group_size; ///< size of frame group (16 frames per group)
137 int fft_size; ///< size of FFT, in complex numbers
138 int checksum_size; ///< size of data block, used also for checksum
140 /// Parameters built from header parameters, do not change during playback
141 int group_order; ///< order of frame group
142 int fft_order; ///< order of FFT (actually fftorder+1)
143 int frame_size; ///< size of data frame
145 int sub_sampling; ///< subsampling: 0=25%, 1=50%, 2=100% */
146 int coeff_per_sb_select; ///< selector for "num. of coeffs. per subband" tables. Can be 0, 1, 2
147 int cm_table_select; ///< selector for "coding method" tables. Can be 0, 1 (from init: 0-4)
149 /// Packets and packet lists
150 QDM2SubPacket sub_packets[16]; ///< the packets themselves
151 QDM2SubPNode sub_packet_list_A[16]; ///< list of all packets
152 QDM2SubPNode sub_packet_list_B[16]; ///< FFT packets B are on list
153 int sub_packets_B; ///< number of packets on 'B' list
154 QDM2SubPNode sub_packet_list_C[16]; ///< packets with errors?
155 QDM2SubPNode sub_packet_list_D[16]; ///< DCT packets
158 FFTTone fft_tones[1000];
161 FFTCoefficient fft_coefs[1000];
163 int fft_coefs_min_index[5];
164 int fft_coefs_max_index[5];
165 int fft_level_exp[6];
166 RDFTContext rdft_ctx;
170 const uint8_t *compressed_data;
172 float output_buffer[QDM2_MAX_FRAME_SIZE * 2];
175 MPADSPContext mpadsp;
176 DECLARE_ALIGNED(32, float, synth_buf)[MPA_MAX_CHANNELS][512*2];
177 int synth_buf_offset[MPA_MAX_CHANNELS];
178 DECLARE_ALIGNED(32, float, sb_samples)[MPA_MAX_CHANNELS][128][SBLIMIT];
179 DECLARE_ALIGNED(32, float, samples)[MPA_MAX_CHANNELS * MPA_FRAME_SIZE];
181 /// Mixed temporary data used in decoding
182 float tone_level[MPA_MAX_CHANNELS][30][64];
183 int8_t coding_method[MPA_MAX_CHANNELS][30][64];
184 int8_t quantized_coeffs[MPA_MAX_CHANNELS][10][8];
185 int8_t tone_level_idx_base[MPA_MAX_CHANNELS][30][8];
186 int8_t tone_level_idx_hi1[MPA_MAX_CHANNELS][3][8][8];
187 int8_t tone_level_idx_mid[MPA_MAX_CHANNELS][26][8];
188 int8_t tone_level_idx_hi2[MPA_MAX_CHANNELS][26];
189 int8_t tone_level_idx[MPA_MAX_CHANNELS][30][64];
190 int8_t tone_level_idx_temp[MPA_MAX_CHANNELS][30][64];
193 int has_errors; ///< packet has errors
194 int superblocktype_2_3; ///< select fft tables and some algorithm based on superblock type
195 int do_synth_filter; ///< used to perform or skip synthesis filter
198 int noise_idx; ///< index for dithering noise table
202 static VLC vlc_tab_level;
203 static VLC vlc_tab_diff;
204 static VLC vlc_tab_run;
205 static VLC fft_level_exp_alt_vlc;
206 static VLC fft_level_exp_vlc;
207 static VLC fft_stereo_exp_vlc;
208 static VLC fft_stereo_phase_vlc;
209 static VLC vlc_tab_tone_level_idx_hi1;
210 static VLC vlc_tab_tone_level_idx_mid;
211 static VLC vlc_tab_tone_level_idx_hi2;
212 static VLC vlc_tab_type30;
213 static VLC vlc_tab_type34;
214 static VLC vlc_tab_fft_tone_offset[5];
216 static const uint16_t qdm2_vlc_offs[] = {
217 0,260,566,598,894,1166,1230,1294,1678,1950,2214,2278,2310,2570,2834,3124,3448,3838,
220 static av_cold void qdm2_init_vlc(void)
222 static int vlcs_initialized = 0;
223 static VLC_TYPE qdm2_table[3838][2];
225 if (!vlcs_initialized) {
227 vlc_tab_level.table = &qdm2_table[qdm2_vlc_offs[0]];
228 vlc_tab_level.table_allocated = qdm2_vlc_offs[1] - qdm2_vlc_offs[0];
229 init_vlc (&vlc_tab_level, 8, 24,
230 vlc_tab_level_huffbits, 1, 1,
231 vlc_tab_level_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
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, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
239 vlc_tab_run.table = &qdm2_table[qdm2_vlc_offs[2]];
240 vlc_tab_run.table_allocated = qdm2_vlc_offs[3] - qdm2_vlc_offs[2];
241 init_vlc (&vlc_tab_run, 5, 6,
242 vlc_tab_run_huffbits, 1, 1,
243 vlc_tab_run_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
245 fft_level_exp_alt_vlc.table = &qdm2_table[qdm2_vlc_offs[3]];
246 fft_level_exp_alt_vlc.table_allocated = qdm2_vlc_offs[4] - qdm2_vlc_offs[3];
247 init_vlc (&fft_level_exp_alt_vlc, 8, 28,
248 fft_level_exp_alt_huffbits, 1, 1,
249 fft_level_exp_alt_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
252 fft_level_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[4]];
253 fft_level_exp_vlc.table_allocated = qdm2_vlc_offs[5] - qdm2_vlc_offs[4];
254 init_vlc (&fft_level_exp_vlc, 8, 20,
255 fft_level_exp_huffbits, 1, 1,
256 fft_level_exp_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
258 fft_stereo_exp_vlc.table = &qdm2_table[qdm2_vlc_offs[5]];
259 fft_stereo_exp_vlc.table_allocated = qdm2_vlc_offs[6] - qdm2_vlc_offs[5];
260 init_vlc (&fft_stereo_exp_vlc, 6, 7,
261 fft_stereo_exp_huffbits, 1, 1,
262 fft_stereo_exp_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
264 fft_stereo_phase_vlc.table = &qdm2_table[qdm2_vlc_offs[6]];
265 fft_stereo_phase_vlc.table_allocated = qdm2_vlc_offs[7] - qdm2_vlc_offs[6];
266 init_vlc (&fft_stereo_phase_vlc, 6, 9,
267 fft_stereo_phase_huffbits, 1, 1,
268 fft_stereo_phase_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
270 vlc_tab_tone_level_idx_hi1.table = &qdm2_table[qdm2_vlc_offs[7]];
271 vlc_tab_tone_level_idx_hi1.table_allocated = qdm2_vlc_offs[8] - qdm2_vlc_offs[7];
272 init_vlc (&vlc_tab_tone_level_idx_hi1, 8, 20,
273 vlc_tab_tone_level_idx_hi1_huffbits, 1, 1,
274 vlc_tab_tone_level_idx_hi1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
276 vlc_tab_tone_level_idx_mid.table = &qdm2_table[qdm2_vlc_offs[8]];
277 vlc_tab_tone_level_idx_mid.table_allocated = qdm2_vlc_offs[9] - qdm2_vlc_offs[8];
278 init_vlc (&vlc_tab_tone_level_idx_mid, 8, 24,
279 vlc_tab_tone_level_idx_mid_huffbits, 1, 1,
280 vlc_tab_tone_level_idx_mid_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
282 vlc_tab_tone_level_idx_hi2.table = &qdm2_table[qdm2_vlc_offs[9]];
283 vlc_tab_tone_level_idx_hi2.table_allocated = qdm2_vlc_offs[10] - qdm2_vlc_offs[9];
284 init_vlc (&vlc_tab_tone_level_idx_hi2, 8, 24,
285 vlc_tab_tone_level_idx_hi2_huffbits, 1, 1,
286 vlc_tab_tone_level_idx_hi2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
288 vlc_tab_type30.table = &qdm2_table[qdm2_vlc_offs[10]];
289 vlc_tab_type30.table_allocated = qdm2_vlc_offs[11] - qdm2_vlc_offs[10];
290 init_vlc (&vlc_tab_type30, 6, 9,
291 vlc_tab_type30_huffbits, 1, 1,
292 vlc_tab_type30_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
294 vlc_tab_type34.table = &qdm2_table[qdm2_vlc_offs[11]];
295 vlc_tab_type34.table_allocated = qdm2_vlc_offs[12] - qdm2_vlc_offs[11];
296 init_vlc (&vlc_tab_type34, 5, 10,
297 vlc_tab_type34_huffbits, 1, 1,
298 vlc_tab_type34_huffcodes, 1, 1, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
300 vlc_tab_fft_tone_offset[0].table = &qdm2_table[qdm2_vlc_offs[12]];
301 vlc_tab_fft_tone_offset[0].table_allocated = qdm2_vlc_offs[13] - qdm2_vlc_offs[12];
302 init_vlc (&vlc_tab_fft_tone_offset[0], 8, 23,
303 vlc_tab_fft_tone_offset_0_huffbits, 1, 1,
304 vlc_tab_fft_tone_offset_0_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
306 vlc_tab_fft_tone_offset[1].table = &qdm2_table[qdm2_vlc_offs[13]];
307 vlc_tab_fft_tone_offset[1].table_allocated = qdm2_vlc_offs[14] - qdm2_vlc_offs[13];
308 init_vlc (&vlc_tab_fft_tone_offset[1], 8, 28,
309 vlc_tab_fft_tone_offset_1_huffbits, 1, 1,
310 vlc_tab_fft_tone_offset_1_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
312 vlc_tab_fft_tone_offset[2].table = &qdm2_table[qdm2_vlc_offs[14]];
313 vlc_tab_fft_tone_offset[2].table_allocated = qdm2_vlc_offs[15] - qdm2_vlc_offs[14];
314 init_vlc (&vlc_tab_fft_tone_offset[2], 8, 32,
315 vlc_tab_fft_tone_offset_2_huffbits, 1, 1,
316 vlc_tab_fft_tone_offset_2_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
318 vlc_tab_fft_tone_offset[3].table = &qdm2_table[qdm2_vlc_offs[15]];
319 vlc_tab_fft_tone_offset[3].table_allocated = qdm2_vlc_offs[16] - qdm2_vlc_offs[15];
320 init_vlc (&vlc_tab_fft_tone_offset[3], 8, 35,
321 vlc_tab_fft_tone_offset_3_huffbits, 1, 1,
322 vlc_tab_fft_tone_offset_3_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
324 vlc_tab_fft_tone_offset[4].table = &qdm2_table[qdm2_vlc_offs[16]];
325 vlc_tab_fft_tone_offset[4].table_allocated = qdm2_vlc_offs[17] - qdm2_vlc_offs[16];
326 init_vlc (&vlc_tab_fft_tone_offset[4], 8, 38,
327 vlc_tab_fft_tone_offset_4_huffbits, 1, 1,
328 vlc_tab_fft_tone_offset_4_huffcodes, 2, 2, INIT_VLC_USE_NEW_STATIC | INIT_VLC_LE);
334 static int qdm2_get_vlc (GetBitContext *gb, VLC *vlc, int flag, int depth)
338 value = get_vlc2(gb, vlc->table, vlc->bits, depth);
340 /* stage-2, 3 bits exponent escape sequence */
342 value = get_bits (gb, get_bits (gb, 3) + 1);
344 /* stage-3, optional */
346 int tmp = vlc_stage3_values[value];
348 if ((value & ~3) > 0)
349 tmp += get_bits (gb, (value >> 2));
357 static int qdm2_get_se_vlc (VLC *vlc, GetBitContext *gb, int depth)
359 int value = qdm2_get_vlc (gb, vlc, 0, depth);
361 return (value & 1) ? ((value + 1) >> 1) : -(value >> 1);
368 * @param data pointer to data to be checksum'ed
369 * @param length data length
370 * @param value checksum value
372 * @return 0 if checksum is OK
374 static uint16_t qdm2_packet_checksum (const uint8_t *data, int length, int value) {
377 for (i=0; i < length; i++)
380 return (uint16_t)(value & 0xffff);
385 * Fill a QDM2SubPacket structure with packet type, size, and data pointer.
387 * @param gb bitreader context
388 * @param sub_packet packet under analysis
390 static void qdm2_decode_sub_packet_header (GetBitContext *gb, QDM2SubPacket *sub_packet)
392 sub_packet->type = get_bits (gb, 8);
394 if (sub_packet->type == 0) {
395 sub_packet->size = 0;
396 sub_packet->data = NULL;
398 sub_packet->size = get_bits (gb, 8);
400 if (sub_packet->type & 0x80) {
401 sub_packet->size <<= 8;
402 sub_packet->size |= get_bits (gb, 8);
403 sub_packet->type &= 0x7f;
406 if (sub_packet->type == 0x7f)
407 sub_packet->type |= (get_bits (gb, 8) << 8);
409 sub_packet->data = &gb->buffer[get_bits_count(gb) / 8]; // FIXME: this depends on bitreader internal data
412 av_log(NULL,AV_LOG_DEBUG,"Subpacket: type=%d size=%d start_offs=%x\n",
413 sub_packet->type, sub_packet->size, get_bits_count(gb) / 8);
418 * Return node pointer to first packet of requested type in list.
420 * @param list list of subpackets to be scanned
421 * @param type type of searched subpacket
422 * @return node pointer for subpacket if found, else NULL
424 static QDM2SubPNode* qdm2_search_subpacket_type_in_list (QDM2SubPNode *list, int type)
426 while (list != NULL && list->packet != NULL) {
427 if (list->packet->type == type)
436 * Replace 8 elements with their average value.
437 * Called by qdm2_decode_superblock before starting subblock decoding.
441 static void average_quantized_coeffs (QDM2Context *q)
443 int i, j, n, ch, sum;
445 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1;
447 for (ch = 0; ch < q->nb_channels; ch++)
448 for (i = 0; i < n; i++) {
451 for (j = 0; j < 8; j++)
452 sum += q->quantized_coeffs[ch][i][j];
458 for (j=0; j < 8; j++)
459 q->quantized_coeffs[ch][i][j] = sum;
465 * Build subband samples with noise weighted by q->tone_level.
466 * Called by synthfilt_build_sb_samples.
469 * @param sb subband index
471 static void build_sb_samples_from_noise (QDM2Context *q, int sb)
475 FIX_NOISE_IDX(q->noise_idx);
480 for (ch = 0; ch < q->nb_channels; ch++)
481 for (j = 0; j < 64; j++) {
482 q->sb_samples[ch][j * 2][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
483 q->sb_samples[ch][j * 2 + 1][sb] = SB_DITHERING_NOISE(sb,q->noise_idx) * q->tone_level[ch][sb][j];
489 * Called while processing data from subpackets 11 and 12.
490 * Used after making changes to coding_method array.
492 * @param sb subband index
493 * @param channels number of channels
494 * @param coding_method q->coding_method[0][0][0]
496 static void fix_coding_method_array (int sb, int channels, sb_int8_array coding_method)
501 static const int switchtable[23] = {0,5,1,5,5,5,5,5,2,5,5,5,5,5,5,5,3,5,5,5,5,5,4};
503 for (ch = 0; ch < channels; ch++) {
504 for (j = 0; j < 64; ) {
505 if((coding_method[ch][sb][j] - 8) > 22) {
509 switch (switchtable[coding_method[ch][sb][j]-8]) {
510 case 0: run = 10; case_val = 10; break;
511 case 1: run = 1; case_val = 16; break;
512 case 2: run = 5; case_val = 24; break;
513 case 3: run = 3; case_val = 30; break;
514 case 4: run = 1; case_val = 30; break;
515 case 5: run = 1; case_val = 8; break;
516 default: run = 1; case_val = 8; break;
519 for (k = 0; k < run; k++)
521 if (coding_method[ch][sb + (j + k) / 64][(j + k) % 64] > coding_method[ch][sb][j])
524 //not debugged, almost never used
525 memset(&coding_method[ch][sb][j + k], case_val, k * sizeof(int8_t));
526 memset(&coding_method[ch][sb][j + k], case_val, 3 * sizeof(int8_t));
535 * Related to synthesis filter
536 * Called by process_subpacket_10
539 * @param flag 1 if called after getting data from subpacket 10, 0 if no subpacket 10
541 static void fill_tone_level_array (QDM2Context *q, int flag)
543 int i, sb, ch, sb_used;
546 // This should never happen
547 if (q->nb_channels <= 0)
550 for (ch = 0; ch < q->nb_channels; ch++)
551 for (sb = 0; sb < 30; sb++)
552 for (i = 0; i < 8; i++) {
553 if ((tab=coeff_per_sb_for_dequant[q->coeff_per_sb_select][sb]) < (last_coeff[q->coeff_per_sb_select] - 1))
554 tmp = q->quantized_coeffs[ch][tab + 1][i] * dequant_table[q->coeff_per_sb_select][tab + 1][sb]+
555 q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
557 tmp = q->quantized_coeffs[ch][tab][i] * dequant_table[q->coeff_per_sb_select][tab][sb];
560 q->tone_level_idx_base[ch][sb][i] = (tmp / 256) & 0xff;
563 sb_used = QDM2_SB_USED(q->sub_sampling);
565 if ((q->superblocktype_2_3 != 0) && !flag) {
566 for (sb = 0; sb < sb_used; sb++)
567 for (ch = 0; ch < q->nb_channels; ch++)
568 for (i = 0; i < 64; i++) {
569 q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
570 if (q->tone_level_idx[ch][sb][i] < 0)
571 q->tone_level[ch][sb][i] = 0;
573 q->tone_level[ch][sb][i] = fft_tone_level_table[0][q->tone_level_idx[ch][sb][i] & 0x3f];
576 tab = q->superblocktype_2_3 ? 0 : 1;
577 for (sb = 0; sb < sb_used; sb++) {
578 if ((sb >= 4) && (sb <= 23)) {
579 for (ch = 0; ch < q->nb_channels; ch++)
580 for (i = 0; i < 64; i++) {
581 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
582 q->tone_level_idx_hi1[ch][sb / 8][i / 8][i % 8] -
583 q->tone_level_idx_mid[ch][sb - 4][i / 8] -
584 q->tone_level_idx_hi2[ch][sb - 4];
585 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
586 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
587 q->tone_level[ch][sb][i] = 0;
589 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
593 for (ch = 0; ch < q->nb_channels; ch++)
594 for (i = 0; i < 64; i++) {
595 tmp = q->tone_level_idx_base[ch][sb][i / 8] -
596 q->tone_level_idx_hi1[ch][2][i / 8][i % 8] -
597 q->tone_level_idx_hi2[ch][sb - 4];
598 q->tone_level_idx[ch][sb][i] = tmp & 0xff;
599 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
600 q->tone_level[ch][sb][i] = 0;
602 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
605 for (ch = 0; ch < q->nb_channels; ch++)
606 for (i = 0; i < 64; i++) {
607 tmp = q->tone_level_idx[ch][sb][i] = q->tone_level_idx_base[ch][sb][i / 8];
608 if ((tmp < 0) || (!q->superblocktype_2_3 && !tmp))
609 q->tone_level[ch][sb][i] = 0;
611 q->tone_level[ch][sb][i] = fft_tone_level_table[tab][tmp & 0x3f];
623 * Related to synthesis filter
624 * Called by process_subpacket_11
625 * c is built with data from subpacket 11
626 * Most of this function is used only if superblock_type_2_3 == 0, never seen it in samples
628 * @param tone_level_idx
629 * @param tone_level_idx_temp
630 * @param coding_method q->coding_method[0][0][0]
631 * @param nb_channels number of channels
632 * @param c coming from subpacket 11, passed as 8*c
633 * @param superblocktype_2_3 flag based on superblock packet type
634 * @param cm_table_select q->cm_table_select
636 static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,
637 sb_int8_array coding_method, int nb_channels,
638 int c, int superblocktype_2_3, int cm_table_select)
641 int tmp, acc, esp_40, comp;
642 int add1, add2, add3, add4;
645 // This should never happen
646 if (nb_channels <= 0)
649 if (!superblocktype_2_3) {
650 /* This case is untested, no samples available */
652 for (ch = 0; ch < nb_channels; ch++)
653 for (sb = 0; sb < 30; sb++) {
654 for (j = 1; j < 63; j++) { // The loop only iterates to 63 so the code doesn't overflow the buffer
655 add1 = tone_level_idx[ch][sb][j] - 10;
658 add2 = add3 = add4 = 0;
660 add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;
665 add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;
670 add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;
674 tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;
677 tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;
679 tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];
682 for (ch = 0; ch < nb_channels; ch++)
683 for (sb = 0; sb < 30; sb++)
684 for (j = 0; j < 64; j++)
685 acc += tone_level_idx_temp[ch][sb][j];
687 multres = 0x66666667 * (acc * 10);
688 esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);
689 for (ch = 0; ch < nb_channels; ch++)
690 for (sb = 0; sb < 30; sb++)
691 for (j = 0; j < 64; j++) {
692 comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;
695 comp /= 256; // signed shift
723 coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;
725 for (sb = 0; sb < 30; sb++)
726 fix_coding_method_array(sb, nb_channels, coding_method);
727 for (ch = 0; ch < nb_channels; ch++)
728 for (sb = 0; sb < 30; sb++)
729 for (j = 0; j < 64; j++)
731 if (coding_method[ch][sb][j] < 10)
732 coding_method[ch][sb][j] = 10;
735 if (coding_method[ch][sb][j] < 16)
736 coding_method[ch][sb][j] = 16;
738 if (coding_method[ch][sb][j] < 30)
739 coding_method[ch][sb][j] = 30;
742 } else { // superblocktype_2_3 != 0
743 for (ch = 0; ch < nb_channels; ch++)
744 for (sb = 0; sb < 30; sb++)
745 for (j = 0; j < 64; j++)
746 coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];
755 * Called by process_subpacket_11 to process more data from subpacket 11 with sb 0-8
756 * Called by process_subpacket_12 to process data from subpacket 12 with sb 8-sb_used
759 * @param gb bitreader context
760 * @param length packet length in bits
761 * @param sb_min lower subband processed (sb_min included)
762 * @param sb_max higher subband processed (sb_max excluded)
764 static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)
766 int sb, j, k, n, ch, run, channels;
767 int joined_stereo, zero_encoding, chs;
769 float type34_div = 0;
770 float type34_predictor;
771 float samples[10], sign_bits[16];
774 // If no data use noise
775 for (sb=sb_min; sb < sb_max; sb++)
776 build_sb_samples_from_noise (q, sb);
781 for (sb = sb_min; sb < sb_max; sb++) {
782 FIX_NOISE_IDX(q->noise_idx);
784 channels = q->nb_channels;
786 if (q->nb_channels <= 1 || sb < 12)
791 joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1 (gb) : 0;
794 if (get_bits_left(gb) >= 16)
795 for (j = 0; j < 16; j++)
796 sign_bits[j] = get_bits1 (gb);
798 for (j = 0; j < 64; j++)
799 if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])
800 q->coding_method[0][sb][j] = q->coding_method[1][sb][j];
802 fix_coding_method_array(sb, q->nb_channels, q->coding_method);
806 for (ch = 0; ch < channels; ch++) {
807 zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;
808 type34_predictor = 0.0;
811 for (j = 0; j < 128; ) {
812 switch (q->coding_method[ch][sb][j / 2]) {
814 if (get_bits_left(gb) >= 10) {
816 for (k = 0; k < 5; k++) {
817 if ((j + 2 * k) >= 128)
819 samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;
823 for (k = 0; k < 5; k++)
824 samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
826 for (k = 0; k < 5; k++)
827 samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);
829 for (k = 0; k < 10; k++)
830 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
836 if (get_bits_left(gb) >= 1) {
841 f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;
844 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
850 if (get_bits_left(gb) >= 10) {
852 for (k = 0; k < 5; k++) {
855 samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];
858 n = get_bits (gb, 8);
859 for (k = 0; k < 5; k++)
860 samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];
863 for (k = 0; k < 5; k++)
864 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
870 if (get_bits_left(gb) >= 7) {
872 for (k = 0; k < 3; k++)
873 samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;
875 for (k = 0; k < 3; k++)
876 samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);
882 if (get_bits_left(gb) >= 4) {
883 unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);
884 if (index < FF_ARRAY_ELEMS(type30_dequant)) {
885 samples[0] = type30_dequant[index];
887 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
889 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
895 if (get_bits_left(gb) >= 7) {
897 type34_div = (float)(1 << get_bits(gb, 2));
898 samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;
899 type34_predictor = samples[0];
902 unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);
903 if (index < FF_ARRAY_ELEMS(type34_delta)) {
904 samples[0] = type34_delta[index] / type34_div + type34_predictor;
905 type34_predictor = samples[0];
907 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
910 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
916 samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);
922 float tmp[10][MPA_MAX_CHANNELS];
924 for (k = 0; k < run; k++) {
925 tmp[k][0] = samples[k];
926 tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];
928 for (chs = 0; chs < q->nb_channels; chs++)
929 for (k = 0; k < run; k++)
931 q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];
933 for (k = 0; k < run; k++)
935 q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];
946 * Init the first element of a channel in quantized_coeffs with data from packet 10 (quantized_coeffs[ch][0]).
947 * This is similar to process_subpacket_9, but for a single channel and for element [0]
948 * same VLC tables as process_subpacket_9 are used.
950 * @param quantized_coeffs pointer to quantized_coeffs[ch][0]
951 * @param gb bitreader context
953 static void init_quantized_coeffs_elem0 (int8_t *quantized_coeffs, GetBitContext *gb)
955 int i, k, run, level, diff;
957 if (get_bits_left(gb) < 16)
959 level = qdm2_get_vlc(gb, &vlc_tab_level, 0, 2);
961 quantized_coeffs[0] = level;
963 for (i = 0; i < 7; ) {
964 if (get_bits_left(gb) < 16)
966 run = qdm2_get_vlc(gb, &vlc_tab_run, 0, 1) + 1;
968 if (get_bits_left(gb) < 16)
970 diff = qdm2_get_se_vlc(&vlc_tab_diff, gb, 2);
972 for (k = 1; k <= run; k++)
973 quantized_coeffs[i + k] = (level + ((k * diff) / run));
982 * Related to synthesis filter, process data from packet 10
983 * Init part of quantized_coeffs via function init_quantized_coeffs_elem0
984 * Init tone_level_idx_hi1, tone_level_idx_hi2, tone_level_idx_mid with data from packet 10
987 * @param gb bitreader context
989 static void init_tone_level_dequantization (QDM2Context *q, GetBitContext *gb)
993 for (ch = 0; ch < q->nb_channels; ch++) {
994 init_quantized_coeffs_elem0(q->quantized_coeffs[ch][0], gb);
996 if (get_bits_left(gb) < 16) {
997 memset(q->quantized_coeffs[ch][0], 0, 8);
1002 n = q->sub_sampling + 1;
1004 for (sb = 0; sb < n; sb++)
1005 for (ch = 0; ch < q->nb_channels; ch++)
1006 for (j = 0; j < 8; j++) {
1007 if (get_bits_left(gb) < 1)
1009 if (get_bits1(gb)) {
1010 for (k=0; k < 8; k++) {
1011 if (get_bits_left(gb) < 16)
1013 q->tone_level_idx_hi1[ch][sb][j][k] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi1, 0, 2);
1016 for (k=0; k < 8; k++)
1017 q->tone_level_idx_hi1[ch][sb][j][k] = 0;
1021 n = QDM2_SB_USED(q->sub_sampling) - 4;
1023 for (sb = 0; sb < n; sb++)
1024 for (ch = 0; ch < q->nb_channels; ch++) {
1025 if (get_bits_left(gb) < 16)
1027 q->tone_level_idx_hi2[ch][sb] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_hi2, 0, 2);
1029 q->tone_level_idx_hi2[ch][sb] -= 16;
1031 for (j = 0; j < 8; j++)
1032 q->tone_level_idx_mid[ch][sb][j] = -16;
1035 n = QDM2_SB_USED(q->sub_sampling) - 5;
1037 for (sb = 0; sb < n; sb++)
1038 for (ch = 0; ch < q->nb_channels; ch++)
1039 for (j = 0; j < 8; j++) {
1040 if (get_bits_left(gb) < 16)
1042 q->tone_level_idx_mid[ch][sb][j] = qdm2_get_vlc(gb, &vlc_tab_tone_level_idx_mid, 0, 2) - 32;
1047 * Process subpacket 9, init quantized_coeffs with data from it
1050 * @param node pointer to node with packet
1052 static void process_subpacket_9 (QDM2Context *q, QDM2SubPNode *node)
1055 int i, j, k, n, ch, run, level, diff;
1057 init_get_bits(&gb, node->packet->data, node->packet->size*8);
1059 n = coeff_per_sb_for_avg[q->coeff_per_sb_select][QDM2_SB_USED(q->sub_sampling) - 1] + 1; // same as averagesomething function
1061 for (i = 1; i < n; i++)
1062 for (ch=0; ch < q->nb_channels; ch++) {
1063 level = qdm2_get_vlc(&gb, &vlc_tab_level, 0, 2);
1064 q->quantized_coeffs[ch][i][0] = level;
1066 for (j = 0; j < (8 - 1); ) {
1067 run = qdm2_get_vlc(&gb, &vlc_tab_run, 0, 1) + 1;
1068 diff = qdm2_get_se_vlc(&vlc_tab_diff, &gb, 2);
1070 for (k = 1; k <= run; k++)
1071 q->quantized_coeffs[ch][i][j + k] = (level + ((k*diff) / run));
1078 for (ch = 0; ch < q->nb_channels; ch++)
1079 for (i = 0; i < 8; i++)
1080 q->quantized_coeffs[ch][0][i] = 0;
1085 * Process subpacket 10 if not null, else
1088 * @param node pointer to node with packet
1089 * @param length packet length in bits
1091 static void process_subpacket_10 (QDM2Context *q, QDM2SubPNode *node)
1096 init_get_bits(&gb, node->packet->data, node->packet->size * 8);
1097 init_tone_level_dequantization(q, &gb);
1098 fill_tone_level_array(q, 1);
1100 fill_tone_level_array(q, 0);
1106 * Process subpacket 11
1109 * @param node pointer to node with packet
1111 static void process_subpacket_11 (QDM2Context *q, QDM2SubPNode *node)
1117 length = node->packet->size * 8;
1118 init_get_bits(&gb, node->packet->data, length);
1122 int c = get_bits (&gb, 13);
1125 fill_coding_method_array (q->tone_level_idx, q->tone_level_idx_temp, q->coding_method,
1126 q->nb_channels, 8*c, q->superblocktype_2_3, q->cm_table_select);
1129 synthfilt_build_sb_samples(q, &gb, length, 0, 8);
1134 * Process subpacket 12
1137 * @param node pointer to node with packet
1138 * @param length packet length in bits
1140 static void process_subpacket_12 (QDM2Context *q, QDM2SubPNode *node)
1146 length = node->packet->size * 8;
1147 init_get_bits(&gb, node->packet->data, length);
1150 synthfilt_build_sb_samples(q, &gb, length, 8, QDM2_SB_USED(q->sub_sampling));
1154 * Process new subpackets for synthesis filter
1157 * @param list list with synthesis filter packets (list D)
1159 static void process_synthesis_subpackets (QDM2Context *q, QDM2SubPNode *list)
1161 QDM2SubPNode *nodes[4];
1163 nodes[0] = qdm2_search_subpacket_type_in_list(list, 9);
1164 if (nodes[0] != NULL)
1165 process_subpacket_9(q, nodes[0]);
1167 nodes[1] = qdm2_search_subpacket_type_in_list(list, 10);
1168 if (nodes[1] != NULL)
1169 process_subpacket_10(q, nodes[1]);
1171 process_subpacket_10(q, NULL);
1173 nodes[2] = qdm2_search_subpacket_type_in_list(list, 11);
1174 if (nodes[0] != NULL && nodes[1] != NULL && nodes[2] != NULL)
1175 process_subpacket_11(q, nodes[2]);
1177 process_subpacket_11(q, NULL);
1179 nodes[3] = qdm2_search_subpacket_type_in_list(list, 12);
1180 if (nodes[0] != NULL && nodes[1] != NULL && nodes[3] != NULL)
1181 process_subpacket_12(q, nodes[3]);
1183 process_subpacket_12(q, NULL);
1188 * Decode superblock, fill packet lists.
1192 static void qdm2_decode_super_block (QDM2Context *q)
1195 QDM2SubPacket header, *packet;
1196 int i, packet_bytes, sub_packet_size, sub_packets_D;
1197 unsigned int next_index = 0;
1199 memset(q->tone_level_idx_hi1, 0, sizeof(q->tone_level_idx_hi1));
1200 memset(q->tone_level_idx_mid, 0, sizeof(q->tone_level_idx_mid));
1201 memset(q->tone_level_idx_hi2, 0, sizeof(q->tone_level_idx_hi2));
1203 q->sub_packets_B = 0;
1206 average_quantized_coeffs(q); // average elements in quantized_coeffs[max_ch][10][8]
1208 init_get_bits(&gb, q->compressed_data, q->compressed_size*8);
1209 qdm2_decode_sub_packet_header(&gb, &header);
1211 if (header.type < 2 || header.type >= 8) {
1213 av_log(NULL,AV_LOG_ERROR,"bad superblock type\n");
1217 q->superblocktype_2_3 = (header.type == 2 || header.type == 3);
1218 packet_bytes = (q->compressed_size - get_bits_count(&gb) / 8);
1220 init_get_bits(&gb, header.data, header.size*8);
1222 if (header.type == 2 || header.type == 4 || header.type == 5) {
1223 int csum = 257 * get_bits(&gb, 8);
1224 csum += 2 * get_bits(&gb, 8);
1226 csum = qdm2_packet_checksum(q->compressed_data, q->checksum_size, csum);
1230 av_log(NULL,AV_LOG_ERROR,"bad packet checksum\n");
1235 q->sub_packet_list_B[0].packet = NULL;
1236 q->sub_packet_list_D[0].packet = NULL;
1238 for (i = 0; i < 6; i++)
1239 if (--q->fft_level_exp[i] < 0)
1240 q->fft_level_exp[i] = 0;
1242 for (i = 0; packet_bytes > 0; i++) {
1245 q->sub_packet_list_A[i].next = NULL;
1248 q->sub_packet_list_A[i - 1].next = &q->sub_packet_list_A[i];
1250 /* seek to next block */
1251 init_get_bits(&gb, header.data, header.size*8);
1252 skip_bits(&gb, next_index*8);
1254 if (next_index >= header.size)
1258 /* decode subpacket */
1259 packet = &q->sub_packets[i];
1260 qdm2_decode_sub_packet_header(&gb, packet);
1261 next_index = packet->size + get_bits_count(&gb) / 8;
1262 sub_packet_size = ((packet->size > 0xff) ? 1 : 0) + packet->size + 2;
1264 if (packet->type == 0)
1267 if (sub_packet_size > packet_bytes) {
1268 if (packet->type != 10 && packet->type != 11 && packet->type != 12)
1270 packet->size += packet_bytes - sub_packet_size;
1273 packet_bytes -= sub_packet_size;
1275 /* add subpacket to 'all subpackets' list */
1276 q->sub_packet_list_A[i].packet = packet;
1278 /* add subpacket to related list */
1279 if (packet->type == 8) {
1280 SAMPLES_NEEDED_2("packet type 8");
1282 } else if (packet->type >= 9 && packet->type <= 12) {
1283 /* packets for MPEG Audio like Synthesis Filter */
1284 QDM2_LIST_ADD(q->sub_packet_list_D, sub_packets_D, packet);
1285 } else if (packet->type == 13) {
1286 for (j = 0; j < 6; j++)
1287 q->fft_level_exp[j] = get_bits(&gb, 6);
1288 } else if (packet->type == 14) {
1289 for (j = 0; j < 6; j++)
1290 q->fft_level_exp[j] = qdm2_get_vlc(&gb, &fft_level_exp_vlc, 0, 2);
1291 } else if (packet->type == 15) {
1292 SAMPLES_NEEDED_2("packet type 15")
1294 } else if (packet->type >= 16 && packet->type < 48 && !fft_subpackets[packet->type - 16]) {
1295 /* packets for FFT */
1296 QDM2_LIST_ADD(q->sub_packet_list_B, q->sub_packets_B, packet);
1298 } // Packet bytes loop
1300 /* **************************************************************** */
1301 if (q->sub_packet_list_D[0].packet != NULL) {
1302 process_synthesis_subpackets(q, q->sub_packet_list_D);
1303 q->do_synth_filter = 1;
1304 } else if (q->do_synth_filter) {
1305 process_subpacket_10(q, NULL);
1306 process_subpacket_11(q, NULL);
1307 process_subpacket_12(q, NULL);
1309 /* **************************************************************** */
1313 static void qdm2_fft_init_coefficient (QDM2Context *q, int sub_packet,
1314 int offset, int duration, int channel,
1317 if (q->fft_coefs_min_index[duration] < 0)
1318 q->fft_coefs_min_index[duration] = q->fft_coefs_index;
1320 q->fft_coefs[q->fft_coefs_index].sub_packet = ((sub_packet >= 16) ? (sub_packet - 16) : sub_packet);
1321 q->fft_coefs[q->fft_coefs_index].channel = channel;
1322 q->fft_coefs[q->fft_coefs_index].offset = offset;
1323 q->fft_coefs[q->fft_coefs_index].exp = exp;
1324 q->fft_coefs[q->fft_coefs_index].phase = phase;
1325 q->fft_coefs_index++;
1329 static void qdm2_fft_decode_tones (QDM2Context *q, int duration, GetBitContext *gb, int b)
1331 int channel, stereo, phase, exp;
1332 int local_int_4, local_int_8, stereo_phase, local_int_10;
1333 int local_int_14, stereo_exp, local_int_20, local_int_28;
1339 local_int_8 = (4 - duration);
1340 local_int_10 = 1 << (q->group_order - duration - 1);
1344 if (q->superblocktype_2_3) {
1345 while ((n = qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2)) < 2) {
1348 local_int_4 += local_int_10;
1349 local_int_28 += (1 << local_int_8);
1351 local_int_4 += 8*local_int_10;
1352 local_int_28 += (8 << local_int_8);
1357 offset += qdm2_get_vlc(gb, &vlc_tab_fft_tone_offset[local_int_8], 1, 2);
1358 while (offset >= (local_int_10 - 1)) {
1359 offset += (1 - (local_int_10 - 1));
1360 local_int_4 += local_int_10;
1361 local_int_28 += (1 << local_int_8);
1365 if (local_int_4 >= q->group_size)
1368 local_int_14 = (offset >> local_int_8);
1369 if (local_int_14 >= FF_ARRAY_ELEMS(fft_level_index_table))
1372 if (q->nb_channels > 1) {
1373 channel = get_bits1(gb);
1374 stereo = get_bits1(gb);
1380 exp = qdm2_get_vlc(gb, (b ? &fft_level_exp_vlc : &fft_level_exp_alt_vlc), 0, 2);
1381 exp += q->fft_level_exp[fft_level_index_table[local_int_14]];
1382 exp = (exp < 0) ? 0 : exp;
1384 phase = get_bits(gb, 3);
1389 stereo_exp = (exp - qdm2_get_vlc(gb, &fft_stereo_exp_vlc, 0, 1));
1390 stereo_phase = (phase - qdm2_get_vlc(gb, &fft_stereo_phase_vlc, 0, 1));
1391 if (stereo_phase < 0)
1395 if (q->frequency_range > (local_int_14 + 1)) {
1396 int sub_packet = (local_int_20 + local_int_28);
1398 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, channel, exp, phase);
1400 qdm2_fft_init_coefficient(q, sub_packet, offset, duration, (1 - channel), stereo_exp, stereo_phase);
1408 static void qdm2_decode_fft_packets (QDM2Context *q)
1410 int i, j, min, max, value, type, unknown_flag;
1413 if (q->sub_packet_list_B[0].packet == NULL)
1416 /* reset minimum indexes for FFT coefficients */
1417 q->fft_coefs_index = 0;
1418 for (i=0; i < 5; i++)
1419 q->fft_coefs_min_index[i] = -1;
1421 /* process subpackets ordered by type, largest type first */
1422 for (i = 0, max = 256; i < q->sub_packets_B; i++) {
1423 QDM2SubPacket *packet= NULL;
1425 /* find subpacket with largest type less than max */
1426 for (j = 0, min = 0; j < q->sub_packets_B; j++) {
1427 value = q->sub_packet_list_B[j].packet->type;
1428 if (value > min && value < max) {
1430 packet = q->sub_packet_list_B[j].packet;
1436 /* check for errors (?) */
1440 if (i == 0 && (packet->type < 16 || packet->type >= 48 || fft_subpackets[packet->type - 16]))
1443 /* decode FFT tones */
1444 init_get_bits (&gb, packet->data, packet->size*8);
1446 if (packet->type >= 32 && packet->type < 48 && !fft_subpackets[packet->type - 16])
1451 type = packet->type;
1453 if ((type >= 17 && type < 24) || (type >= 33 && type < 40)) {
1454 int duration = q->sub_sampling + 5 - (type & 15);
1456 if (duration >= 0 && duration < 4)
1457 qdm2_fft_decode_tones(q, duration, &gb, unknown_flag);
1458 } else if (type == 31) {
1459 for (j=0; j < 4; j++)
1460 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1461 } else if (type == 46) {
1462 for (j=0; j < 6; j++)
1463 q->fft_level_exp[j] = get_bits(&gb, 6);
1464 for (j=0; j < 4; j++)
1465 qdm2_fft_decode_tones(q, j, &gb, unknown_flag);
1467 } // Loop on B packets
1469 /* calculate maximum indexes for FFT coefficients */
1470 for (i = 0, j = -1; i < 5; i++)
1471 if (q->fft_coefs_min_index[i] >= 0) {
1473 q->fft_coefs_max_index[j] = q->fft_coefs_min_index[i];
1477 q->fft_coefs_max_index[j] = q->fft_coefs_index;
1481 static void qdm2_fft_generate_tone (QDM2Context *q, FFTTone *tone)
1486 const double iscale = 2.0*M_PI / 512.0;
1488 tone->phase += tone->phase_shift;
1490 /* calculate current level (maximum amplitude) of tone */
1491 level = fft_tone_envelope_table[tone->duration][tone->time_index] * tone->level;
1492 c.im = level * sin(tone->phase*iscale);
1493 c.re = level * cos(tone->phase*iscale);
1495 /* generate FFT coefficients for tone */
1496 if (tone->duration >= 3 || tone->cutoff >= 3) {
1497 tone->complex[0].im += c.im;
1498 tone->complex[0].re += c.re;
1499 tone->complex[1].im -= c.im;
1500 tone->complex[1].re -= c.re;
1502 f[1] = -tone->table[4];
1503 f[0] = tone->table[3] - tone->table[0];
1504 f[2] = 1.0 - tone->table[2] - tone->table[3];
1505 f[3] = tone->table[1] + tone->table[4] - 1.0;
1506 f[4] = tone->table[0] - tone->table[1];
1507 f[5] = tone->table[2];
1508 for (i = 0; i < 2; i++) {
1509 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].re += c.re * f[i];
1510 tone->complex[fft_cutoff_index_table[tone->cutoff][i]].im += c.im *((tone->cutoff <= i) ? -f[i] : f[i]);
1512 for (i = 0; i < 4; i++) {
1513 tone->complex[i].re += c.re * f[i+2];
1514 tone->complex[i].im += c.im * f[i+2];
1518 /* copy the tone if it has not yet died out */
1519 if (++tone->time_index < ((1 << (5 - tone->duration)) - 1)) {
1520 memcpy(&q->fft_tones[q->fft_tone_end], tone, sizeof(FFTTone));
1521 q->fft_tone_end = (q->fft_tone_end + 1) % 1000;
1526 static void qdm2_fft_tone_synthesizer (QDM2Context *q, int sub_packet)
1529 const double iscale = 0.25 * M_PI;
1531 for (ch = 0; ch < q->channels; ch++) {
1532 memset(q->fft.complex[ch], 0, q->fft_size * sizeof(QDM2Complex));
1536 /* apply FFT tones with duration 4 (1 FFT period) */
1537 if (q->fft_coefs_min_index[4] >= 0)
1538 for (i = q->fft_coefs_min_index[4]; i < q->fft_coefs_max_index[4]; i++) {
1542 if (q->fft_coefs[i].sub_packet != sub_packet)
1545 ch = (q->channels == 1) ? 0 : q->fft_coefs[i].channel;
1546 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];
1548 c.re = level * cos(q->fft_coefs[i].phase * iscale);
1549 c.im = level * sin(q->fft_coefs[i].phase * iscale);
1550 q->fft.complex[ch][q->fft_coefs[i].offset + 0].re += c.re;
1551 q->fft.complex[ch][q->fft_coefs[i].offset + 0].im += c.im;
1552 q->fft.complex[ch][q->fft_coefs[i].offset + 1].re -= c.re;
1553 q->fft.complex[ch][q->fft_coefs[i].offset + 1].im -= c.im;
1556 /* generate existing FFT tones */
1557 for (i = q->fft_tone_end; i != q->fft_tone_start; ) {
1558 qdm2_fft_generate_tone(q, &q->fft_tones[q->fft_tone_start]);
1559 q->fft_tone_start = (q->fft_tone_start + 1) % 1000;
1562 /* create and generate new FFT tones with duration 0 (long) to 3 (short) */
1563 for (i = 0; i < 4; i++)
1564 if (q->fft_coefs_min_index[i] >= 0) {
1565 for (j = q->fft_coefs_min_index[i]; j < q->fft_coefs_max_index[i]; j++) {
1569 if (q->fft_coefs[j].sub_packet != sub_packet)
1573 offset = q->fft_coefs[j].offset >> four_i;
1574 ch = (q->channels == 1) ? 0 : q->fft_coefs[j].channel;
1576 if (offset < q->frequency_range) {
1578 tone.cutoff = offset;
1580 tone.cutoff = (offset >= 60) ? 3 : 2;
1582 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];
1583 tone.complex = &q->fft.complex[ch][offset];
1584 tone.table = fft_tone_sample_table[i][q->fft_coefs[j].offset - (offset << four_i)];
1585 tone.phase = 64 * q->fft_coefs[j].phase - (offset << 8) - 128;
1586 tone.phase_shift = (2 * q->fft_coefs[j].offset + 1) << (7 - four_i);
1588 tone.time_index = 0;
1590 qdm2_fft_generate_tone(q, &tone);
1593 q->fft_coefs_min_index[i] = j;
1598 static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)
1600 const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;
1601 float *out = q->output_buffer + channel;
1603 q->fft.complex[channel][0].re *= 2.0f;
1604 q->fft.complex[channel][0].im = 0.0f;
1605 q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);
1606 /* add samples to output buffer */
1607 for (i = 0; i < FFALIGN(q->fft_size, 8); i++) {
1608 out[0] += q->fft.complex[channel][i].re * gain;
1609 out[q->channels] += q->fft.complex[channel][i].im * gain;
1610 out += 2 * q->channels;
1617 * @param index subpacket number
1619 static void qdm2_synthesis_filter (QDM2Context *q, int index)
1621 int i, k, ch, sb_used, sub_sampling, dither_state = 0;
1623 /* copy sb_samples */
1624 sb_used = QDM2_SB_USED(q->sub_sampling);
1626 for (ch = 0; ch < q->channels; ch++)
1627 for (i = 0; i < 8; i++)
1628 for (k=sb_used; k < SBLIMIT; k++)
1629 q->sb_samples[ch][(8 * index) + i][k] = 0;
1631 for (ch = 0; ch < q->nb_channels; ch++) {
1632 float *samples_ptr = q->samples + ch;
1634 for (i = 0; i < 8; i++) {
1635 ff_mpa_synth_filter_float(&q->mpadsp,
1636 q->synth_buf[ch], &(q->synth_buf_offset[ch]),
1637 ff_mpa_synth_window_float, &dither_state,
1638 samples_ptr, q->nb_channels,
1639 q->sb_samples[ch][(8 * index) + i]);
1640 samples_ptr += 32 * q->nb_channels;
1644 /* add samples to output buffer */
1645 sub_sampling = (4 >> q->sub_sampling);
1647 for (ch = 0; ch < q->channels; ch++)
1648 for (i = 0; i < q->frame_size; i++)
1649 q->output_buffer[q->channels * i + ch] += (1 << 23) * q->samples[q->nb_channels * sub_sampling * i + ch];
1654 * Init static data (does not depend on specific file)
1658 static av_cold void qdm2_init(QDM2Context *q) {
1659 static int initialized = 0;
1661 if (initialized != 0)
1666 ff_mpa_synth_init_float(ff_mpa_synth_window_float);
1667 softclip_table_init();
1669 init_noise_samples();
1671 av_log(NULL, AV_LOG_DEBUG, "init done\n");
1676 static void dump_context(QDM2Context *q)
1679 #define PRINT(a,b) av_log(NULL,AV_LOG_DEBUG," %s = %d\n", a, b);
1680 PRINT("compressed_data",q->compressed_data);
1681 PRINT("compressed_size",q->compressed_size);
1682 PRINT("frame_size",q->frame_size);
1683 PRINT("checksum_size",q->checksum_size);
1684 PRINT("channels",q->channels);
1685 PRINT("nb_channels",q->nb_channels);
1686 PRINT("fft_size",q->fft_size);
1687 PRINT("sub_sampling",q->sub_sampling);
1688 PRINT("fft_order",q->fft_order);
1689 PRINT("group_order",q->group_order);
1690 PRINT("group_size",q->group_size);
1691 PRINT("sub_packet",q->sub_packet);
1692 PRINT("frequency_range",q->frequency_range);
1693 PRINT("has_errors",q->has_errors);
1694 PRINT("fft_tone_end",q->fft_tone_end);
1695 PRINT("fft_tone_start",q->fft_tone_start);
1696 PRINT("fft_coefs_index",q->fft_coefs_index);
1697 PRINT("coeff_per_sb_select",q->coeff_per_sb_select);
1698 PRINT("cm_table_select",q->cm_table_select);
1699 PRINT("noise_idx",q->noise_idx);
1701 for (i = q->fft_tone_start; i < q->fft_tone_end; i++)
1703 FFTTone *t = &q->fft_tones[i];
1705 av_log(NULL,AV_LOG_DEBUG,"Tone (%d) dump:\n", i);
1706 av_log(NULL,AV_LOG_DEBUG," level = %f\n", t->level);
1707 // PRINT(" level", t->level);
1708 PRINT(" phase", t->phase);
1709 PRINT(" phase_shift", t->phase_shift);
1710 PRINT(" duration", t->duration);
1711 PRINT(" samples_im", t->samples_im);
1712 PRINT(" samples_re", t->samples_re);
1713 PRINT(" table", t->table);
1721 * Init parameters from codec extradata
1723 static av_cold int qdm2_decode_init(AVCodecContext *avctx)
1725 QDM2Context *s = avctx->priv_data;
1728 int tmp_val, tmp, size;
1730 /* extradata parsing
1739 32 size (including this field)
1741 32 type (=QDM2 or QDMC)
1743 32 size (including this field, in bytes)
1744 32 tag (=QDCA) // maybe mandatory parameters
1747 32 samplerate (=44100)
1749 32 block size (=4096)
1750 32 frame size (=256) (for one channel)
1751 32 packet size (=1300)
1753 32 size (including this field, in bytes)
1754 32 tag (=QDCP) // maybe some tuneable parameters
1764 if (!avctx->extradata || (avctx->extradata_size < 48)) {
1765 av_log(avctx, AV_LOG_ERROR, "extradata missing or truncated\n");
1769 extradata = avctx->extradata;
1770 extradata_size = avctx->extradata_size;
1772 while (extradata_size > 7) {
1773 if (!memcmp(extradata, "frmaQDM", 7))
1779 if (extradata_size < 12) {
1780 av_log(avctx, AV_LOG_ERROR, "not enough extradata (%i)\n",
1785 if (memcmp(extradata, "frmaQDM", 7)) {
1786 av_log(avctx, AV_LOG_ERROR, "invalid headers, QDM? not found\n");
1790 if (extradata[7] == 'C') {
1792 av_log(avctx, AV_LOG_ERROR, "stream is QDMC version 1, which is not supported\n");
1797 extradata_size -= 8;
1799 size = AV_RB32(extradata);
1801 if(size > extradata_size){
1802 av_log(avctx, AV_LOG_ERROR, "extradata size too small, %i < %i\n",
1803 extradata_size, size);
1808 av_log(avctx, AV_LOG_DEBUG, "size: %d\n", size);
1809 if (AV_RB32(extradata) != MKBETAG('Q','D','C','A')) {
1810 av_log(avctx, AV_LOG_ERROR, "invalid extradata, expecting QDCA\n");
1816 avctx->channels = s->nb_channels = s->channels = AV_RB32(extradata);
1818 if (s->channels > MPA_MAX_CHANNELS)
1819 return AVERROR_INVALIDDATA;
1821 avctx->sample_rate = AV_RB32(extradata);
1824 avctx->bit_rate = AV_RB32(extradata);
1827 s->group_size = AV_RB32(extradata);
1830 s->fft_size = AV_RB32(extradata);
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;
1839 s->fft_order = av_log2(s->fft_size) + 1;
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;
1847 s->sub_sampling = s->fft_order - 7;
1848 s->frequency_range = 255 / (1 << (2 - s->sub_sampling));
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;
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;
1866 if (s->sub_sampling == 0)
1869 tmp = ((-(s->sub_sampling -1)) & 8000) + 20000;
1876 s->coeff_per_sb_select = 0;
1877 else if (tmp <= 16000)
1878 s->coeff_per_sb_select = 1;
1880 s->coeff_per_sb_select = 2;
1882 // Fail on unknown fft order
1883 if ((s->fft_order < 7) || (s->fft_order > 9)) {
1884 av_log(avctx, AV_LOG_ERROR, "Unknown FFT order (%d), contact the developers!\n", s->fft_order);
1888 ff_rdft_init(&s->rdft_ctx, s->fft_order, IDFT_C2R);
1889 ff_mpadsp_init(&s->mpadsp);
1893 avctx->sample_fmt = AV_SAMPLE_FMT_S16;
1895 avcodec_get_frame_defaults(&s->frame);
1896 avctx->coded_frame = &s->frame;
1903 static av_cold int qdm2_decode_close(AVCodecContext *avctx)
1905 QDM2Context *s = avctx->priv_data;
1907 ff_rdft_end(&s->rdft_ctx);
1913 static int qdm2_decode (QDM2Context *q, const uint8_t *in, int16_t *out)
1916 const int frame_size = (q->frame_size * q->channels);
1918 /* select input buffer */
1919 q->compressed_data = in;
1920 q->compressed_size = q->checksum_size;
1924 /* copy old block, clear new block of output samples */
1925 memmove(q->output_buffer, &q->output_buffer[frame_size], frame_size * sizeof(float));
1926 memset(&q->output_buffer[frame_size], 0, frame_size * sizeof(float));
1928 /* decode block of QDM2 compressed data */
1929 if (q->sub_packet == 0) {
1930 q->has_errors = 0; // zero it for a new super block
1931 av_log(NULL,AV_LOG_DEBUG,"Superblock follows\n");
1932 qdm2_decode_super_block(q);
1935 /* parse subpackets */
1936 if (!q->has_errors) {
1937 if (q->sub_packet == 2)
1938 qdm2_decode_fft_packets(q);
1940 qdm2_fft_tone_synthesizer(q, q->sub_packet);
1943 /* sound synthesis stage 1 (FFT) */
1944 for (ch = 0; ch < q->channels; ch++) {
1945 qdm2_calculate_fft(q, ch, q->sub_packet);
1947 if (!q->has_errors && q->sub_packet_list_C[0].packet != NULL) {
1948 SAMPLES_NEEDED_2("has errors, and C list is not empty")
1953 /* sound synthesis stage 2 (MPEG audio like synthesis filter) */
1954 if (!q->has_errors && q->do_synth_filter)
1955 qdm2_synthesis_filter(q, q->sub_packet);
1957 q->sub_packet = (q->sub_packet + 1) % 16;
1959 /* clip and convert output float[] to 16bit signed samples */
1960 for (i = 0; i < frame_size; i++) {
1961 int value = (int)q->output_buffer[i];
1963 if (value > SOFTCLIP_THRESHOLD)
1964 value = (value > HARDCLIP_THRESHOLD) ? 32767 : softclip_table[ value - SOFTCLIP_THRESHOLD];
1965 else if (value < -SOFTCLIP_THRESHOLD)
1966 value = (value < -HARDCLIP_THRESHOLD) ? -32767 : -softclip_table[-value - SOFTCLIP_THRESHOLD];
1975 static int qdm2_decode_frame(AVCodecContext *avctx, void *data,
1976 int *got_frame_ptr, AVPacket *avpkt)
1978 const uint8_t *buf = avpkt->data;
1979 int buf_size = avpkt->size;
1980 QDM2Context *s = avctx->priv_data;
1986 if(buf_size < s->checksum_size)
1989 /* get output buffer */
1990 s->frame.nb_samples = 16 * s->frame_size;
1991 if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
1992 av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
1995 out = (int16_t *)s->frame.data[0];
1997 for (i = 0; i < 16; i++) {
1998 if (qdm2_decode(s, buf, out) < 0)
2000 out += s->channels * s->frame_size;
2004 *(AVFrame *)data = s->frame;
2006 return s->checksum_size;
2009 AVCodec ff_qdm2_decoder =
2012 .type = AVMEDIA_TYPE_AUDIO,
2013 .id = CODEC_ID_QDM2,
2014 .priv_data_size = sizeof(QDM2Context),
2015 .init = qdm2_decode_init,
2016 .close = qdm2_decode_close,
2017 .decode = qdm2_decode_frame,
2018 .capabilities = CODEC_CAP_DR1,
2019 .long_name = NULL_IF_CONFIG_SMALL("QDesign Music Codec 2"),