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