summaryrefslogtreecommitdiff
path: root/apps/codecs/aiff.c
blob: 8b90f7fe9c80f6b32d1c949de15dae3e21ed5a25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
/***************************************************************************
 *             __________               __   ___.
 *   Open      \______   \ ____   ____ |  | _\_ |__   _______  ___
 *   Source     |       _//  _ \_/ ___\|  |/ /| __ \ /  _ \  \/  /
 *   Jukebox    |    |   (  <_> )  \___|    < | \_\ (  <_> > <  <
 *   Firmware   |____|_  /\____/ \___  >__|_ \|___  /\____/__/\_ \
 *                     \/            \/     \/    \/            \/
 * $Id$
 *
 * Copyright (c) 2005 Jvo Studer
 *
 * All files in this archive are subject to the GNU General Public License.
 * See the file COPYING in the source tree root for full license agreement.
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
 * KIND, either express or implied.
 *
 ****************************************************************************/

#include "codeclib.h"
#include <inttypes.h>

CODEC_HEADER

/* Macro that sign extends an unsigned byte */
#define SE(x) ((int32_t)((int8_t)(x)))

/* This codec supports AIFF files with the following formats:
 * - PCM, 8, 16 and 24 bits, mono or stereo
 */

enum
{
    AIFF_FORMAT_PCM = 0x0001,   /* AIFF PCM Format (big endian) */
    IEEE_FORMAT_FLOAT = 0x0003, /* IEEE Float */
    AIFF_FORMAT_ALAW = 0x0004,  /* AIFC ALaw compressed */
    AIFF_FORMAT_ULAW = 0x0005   /* AIFC uLaw compressed */
};

/* Maximum number of bytes to process in one iteration */
/* for 44.1kHz stereo 16bits, this represents 0.023s ~= 1/50s */
#define AIF_CHUNK_SIZE (1024*2)

static int32_t samples[AIF_CHUNK_SIZE] IBSS_ATTR;

enum codec_status codec_main(void)
{
    uint32_t numbytes, bytesdone;
    uint16_t num_channels = 0;
    uint32_t num_sample_frames = 0;
    uint16_t sample_size = 0;
    uint32_t sample_rate = 0;
    uint32_t i;
    size_t n;
    int bufcount;
    int endofstream;
    unsigned char *buf;
    uint8_t *aifbuf;
    long chunksize;
    uint32_t offset2snd = 0;
    uint16_t block_size = 0;
    uint32_t avgbytespersec = 0;
    off_t firstblockposn;     /* position of the first block in file */

    /* Generic codec initialisation */
    ci->configure(DSP_SET_SAMPLE_DEPTH, 28);
    ci->configure(CODEC_SET_FILEBUF_WATERMARK, 1024*512);
  
next_track:
    if (codec_init()) {
        i = CODEC_ERROR;
        goto exit;
    }

    while (!*ci->taginfo_ready && !ci->stop_codec)
        ci->sleep(1);

    codec_set_replaygain(ci->id3);
    
    /* assume the AIFF header is less than 1024 bytes */
    buf = ci->request_buffer(&n, 1024);
    if (n < 54) {
        i = CODEC_ERROR;
        goto done;
    }
    if ((memcmp(buf, "FORM", 4) != 0) || (memcmp(&buf[8], "AIFF", 4) != 0)) {
        i = CODEC_ERROR;
        goto done;
    }

    buf += 12;
    n -= 12;
    numbytes = 0;

    /* read until 'SSND' chunk, which typically is last */
    while (numbytes == 0 && n >= 8) {
        /* chunkSize */
        i = ((buf[4]<<24)|(buf[5]<<16)|(buf[6]<<8)|buf[7]);
        if (memcmp(buf, "COMM", 4) == 0) {
            if (i < 18) {
                DEBUGF("CODEC_ERROR: 'COMM' chunk size=%lu < 18\n",
                       (unsigned long)i);
                i = CODEC_ERROR;
                goto done;
            }
            /* num_channels */
            num_channels = ((buf[8]<<8)|buf[9]);
            /* num_sample_frames */
            num_sample_frames = ((buf[10]<<24)|(buf[11]<<16)|(buf[12]<<8)
                                |buf[13]);
            /* sample_size */
            sample_size  = ((buf[14]<<8)|buf[15]);
            /* sample_rate (don't use last 4 bytes, only integer fs) */
            if (buf[16] != 0x40) {
                DEBUGF("CODEC_ERROR: weird sampling rate (no @)\n");
                i = CODEC_ERROR;
                goto done;
            }
            sample_rate = ((buf[18]<<24)|(buf[19]<<16)|(buf[20]<<8)|buf[21])+1;
            sample_rate = sample_rate >> (16 + 14 - buf[17]);
            /* calc average bytes per second */
            avgbytespersec = sample_rate*num_channels*sample_size/8;
        } else if (memcmp(buf, "SSND", 4)==0) {
            if (sample_size == 0) {
                DEBUGF("CODEC_ERROR: unsupported chunk order\n");
                i = CODEC_ERROR;
                goto done;
            }
            /* offset2snd */
            offset2snd = (buf[8]<<24)|(buf[9]<<16)|(buf[10]<<8)|buf[11];
            /* block_size */
            block_size = (buf[12]<<24)|(buf[13]<<16)|(buf[14]<<8)|buf[15];
            if (block_size == 0)
                block_size = num_channels*sample_size;
            numbytes = i - 8 - offset2snd;
            i = 8 + offset2snd; /* advance to the beginning of data */
        } else {
            DEBUGF("unsupported AIFF chunk: '%c%c%c%c', size=%lu\n",
                   buf[0], buf[1], buf[2], buf[3], (unsigned long)i);
        }

        if (i & 0x01) /* odd chunk sizes must be padded */
            i++;
        buf += i + 8;
        if (n < (i + 8)) {
            DEBUGF("CODEC_ERROR: AIFF header size > 1024\n");
            i = CODEC_ERROR;
            goto done;
        }
        n -= i + 8;
    } /* while 'SSND' */

    if (num_channels == 0) {
        DEBUGF("CODEC_ERROR: 'COMM' chunk not found or 0-channels file\n");
        i = CODEC_ERROR;
        goto done;
    }
    if (numbytes == 0) {
        DEBUGF("CODEC_ERROR: 'SSND' chunk not found or has zero length\n");
        i = CODEC_ERROR;
        goto done;
    }
    if (sample_size > 24) {
        DEBUGF("CODEC_ERROR: PCM with more than 24 bits per sample "
               "is unsupported\n");
        i = CODEC_ERROR;
        goto done;
    }

    ci->configure(DSP_SWITCH_FREQUENCY, ci->id3->frequency);

    if (num_channels == 2) {
        ci->configure(DSP_SET_STEREO_MODE, STEREO_INTERLEAVED);
    } else if (num_channels == 1) {
        ci->configure(DSP_SET_STEREO_MODE, STEREO_MONO);
    } else {
        DEBUGF("CODEC_ERROR: more than 2 channels unsupported\n");
        i = CODEC_ERROR;
        goto done;
    }

    firstblockposn = 1024 - n;
    ci->advance_buffer(firstblockposn);

    /* The main decoder loop */
    bytesdone = 0;
    ci->set_elapsed(0);
    endofstream = 0;
    /* chunksize is computed so that one chunk is about 1/50s.
     * this make 4096 for 44.1kHz 16bits stereo.
     * It also has to be a multiple of blockalign */
    chunksize = (1 + avgbytespersec/(50*block_size))*block_size;
    /* check that the output buffer is big enough (convert to samplespersec,
      then round to the block_size multiple below) */
    if (((uint64_t)chunksize*ci->id3->frequency*num_channels*2)
        /(uint64_t)avgbytespersec >= AIF_CHUNK_SIZE) {
        chunksize = ((uint64_t)AIF_CHUNK_SIZE*avgbytespersec
                     /((uint64_t)ci->id3->frequency*num_channels*2 
                     *block_size))*block_size;
    }

    while (!endofstream) {
        ci->yield();
        if (ci->stop_codec || ci->new_track)
            break;

        if (ci->seek_time) {
            uint32_t newpos;

            /* use avgbytespersec to round to the closest blockalign multiple,
               add firstblockposn. 64-bit casts to avoid overflows. */
            newpos = (((uint64_t)avgbytespersec*(ci->seek_time - 1))
                      /(1000LL*block_size))*block_size;
            if (newpos > numbytes)
                break;
            if (ci->seek_buffer(firstblockposn + newpos))
                bytesdone = newpos;
            ci->seek_complete();
        }
        aifbuf = (uint8_t *)ci->request_buffer(&n, chunksize);

        if (n == 0)
            break; /* End of stream */

        if (bytesdone + n > numbytes) {
            n = numbytes - bytesdone;
            endofstream = 1;
        }

        if (sample_size > 24) {
            for (i = 0; i < n; i += 4) {
                samples[i/4] = (SE(aifbuf[i])<<21)|(aifbuf[i + 1]<<13)
                               |(aifbuf[i + 2]<<5)|(aifbuf[i + 3]>>3);
            }
            bufcount = n >> 2;
        } else if (sample_size > 16) {
            for (i = 0; i < n; i += 3) {
                samples[i/3] = (SE(aifbuf[i])<<21)|(aifbuf[i + 1]<<13)
                               |(aifbuf[i + 2]<<5);
            }
            bufcount = n/3;
        } else if (sample_size > 8) {
            for (i = 0; i < n; i += 2)
                samples[i/2] = (SE(aifbuf[i])<<21)|(aifbuf[i + 1]<<13);
            bufcount = n >> 1;
        } else {
            for (i = 0; i < n; i++)
                samples[i] = SE(aifbuf[i]) << 21;
            bufcount = n;
        }

        if (num_channels == 2)
            bufcount >>= 1;

        ci->pcmbuf_insert(samples, NULL, bufcount);

        ci->advance_buffer(n);
        bytesdone += n;
        if (bytesdone >= numbytes)
            endofstream = 1;

        ci->set_elapsed(bytesdone*1000LL/avgbytespersec);
    }
    i = CODEC_OK;

done:
    if (ci->request_next_track())
        goto next_track;

exit:
    return i;
}

* Copyright (c) 2006-2008 Maxim Poliakovski * Copyright (c) 2006-2008 Benjamin Larsson * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file libavcodec/atrac3.c * Atrac 3 compatible decoder. * This decoder handles Sony's ATRAC3 data. * * Container formats used to store atrac 3 data: * RealMedia (.rm), RIFF WAV (.wav, .at3), Sony OpenMG (.oma, .aa3). * * To use this decoder, a calling application must supply the extradata * bytes provided in the containers above. */ #include <math.h> #include <stddef.h> #include <stdio.h> #include "atrac3.h" #include "atrac3data.h" #include "atrac3data_fixed.h" #include "fixp_math.h" #define JOINT_STEREO 0x12 #define STEREO 0x2 #ifdef ROCKBOX #undef DEBUGF #define DEBUGF(...) #endif /* ROCKBOX */ /* FFMAX/MIN/SWAP and av_clip were taken from libavutil/common.h */ #define FFMAX(a,b) ((a) > (b) ? (a) : (b)) #define FFMIN(a,b) ((a) > (b) ? (b) : (a)) #define FFSWAP(type,a,b) do{type SWAP_tmp= b; b= a; a= SWAP_tmp;}while(0) #if defined(CPU_ARM) && (ARM_ARCH >= 5) #define QMFWIN_TYPE int16_t /* ARMv5e+ uses 32x16 multiplication */ #else #define QMFWIN_TYPE int32_t #endif static VLC spectral_coeff_tab[7]; static QMFWIN_TYPE qmf_window[48] IBSS_ATTR MEM_ALIGN_ATTR; static int32_t atrac3_spectrum [2][1024] IBSS_ATTR MEM_ALIGN_ATTR; static int32_t atrac3_IMDCT_buf[2][ 512] IBSS_ATTR MEM_ALIGN_ATTR; static int32_t atrac3_prevFrame[2][1024] IBSS_ATTR MEM_ALIGN_ATTR; static channel_unit channel_units[2] IBSS_ATTR_LARGE_IRAM; /** * Matrixing within quadrature mirror synthesis filter. * * @param p3 output buffer * @param inlo lower part of spectrum * @param inhi higher part of spectrum * @param nIn size of spectrum buffer */ #if defined(CPU_ARM) extern void atrac3_iqmf_matrixing(int32_t *p3, int32_t *inlo, int32_t *inhi, unsigned int nIn); #else static inline void atrac3_iqmf_matrixing(int32_t *p3, int32_t *inlo, int32_t *inhi, unsigned int nIn) { uint32_t i; for(i=0; i<nIn; i+=2){ p3[2*i+0] = inlo[i ] + inhi[i ]; p3[2*i+1] = inlo[i ] - inhi[i ]; p3[2*i+2] = inlo[i+1] + inhi[i+1]; p3[2*i+3] = inlo[i+1] - inhi[i+1]; } } #endif /** * Matrixing within quadrature mirror synthesis filter. * * @param out output buffer * @param in input buffer * @param win windowing coefficients * @param nIn size of spectrum buffer * Reference implementation: * * for (j = nIn; j != 0; j--) { * s1 = fixmul32(in[0], win[0]); * s2 = fixmul32(in[1], win[1]); * for (i = 2; i < 48; i += 2) { * s1 += fixmul31(in[i ], win[i ]); * s2 += fixmul31(in[i+1], win[i+1]); * } * out[0] = s2; * out[1] = s1; * in += 2; * out += 2; * } */ #if defined(CPU_ARM) && (ARM_ARCH >= 5) extern void atrac3_iqmf_dewindowing_armv5e(int32_t *out, int32_t *in, int16_t *win, unsigned int nIn); static inline void atrac3_iqmf_dewindowing(int32_t *out, int32_t *in, int16_t *win, unsigned int nIn) { atrac3_iqmf_dewindowing_armv5e(out, in, win, nIn); } #elif defined(CPU_ARM) extern void atrac3_iqmf_dewindowing(int32_t *out, int32_t *in, int32_t *win, unsigned int nIn); #elif defined (CPU_COLDFIRE) #define MULTIPLY_ADD_BLOCK \ "movem.l (%[win]), %%d0-%%d7 \n\t" \ "lea.l (8*4, %[win]), %[win] \n\t" \ "mac.l %%d0, %%a5, (%[in])+, %%a5, %%acc0\n\t" \ "mac.l %%d1, %%a5, (%[in])+, %%a5, %%acc1\n\t" \ "mac.l %%d2, %%a5, (%[in])+, %%a5, %%acc0\n\t" \ "mac.l %%d3, %%a5, (%[in])+, %%a5, %%acc1\n\t" \ "mac.l %%d4, %%a5, (%[in])+, %%a5, %%acc0\n\t" \ "mac.l %%d5, %%a5, (%[in])+, %%a5, %%acc1\n\t" \ "mac.l %%d6, %%a5, (%[in])+, %%a5, %%acc0\n\t" \ "mac.l %%d7, %%a5, (%[in])+, %%a5, %%acc1\n\t" \ static inline void atrac3_iqmf_dewindowing(int32_t *out, int32_t *in, int32_t *win, unsigned int nIn) { int32_t j; int32_t *_in, *_win; for (j = nIn; j != 0; j--, in+=2, out+=2) { _in = in; _win = win; asm volatile ( "move.l (%[in])+, %%a5 \n\t" /* preload frist in value */ MULTIPLY_ADD_BLOCK /* 0.. 7 */ MULTIPLY_ADD_BLOCK /* 8..15 */ MULTIPLY_ADD_BLOCK /* 16..23 */ MULTIPLY_ADD_BLOCK /* 24..31 */ MULTIPLY_ADD_BLOCK /* 32..39 */ /* 40..47 */ "movem.l (%[win]), %%d0-%%d7 \n\t" "mac.l %%d0, %%a5, (%[in])+, %%a5, %%acc0 \n\t" "mac.l %%d1, %%a5, (%[in])+, %%a5, %%acc1 \n\t" "mac.l %%d2, %%a5, (%[in])+, %%a5, %%acc0 \n\t" "mac.l %%d3, %%a5, (%[in])+, %%a5, %%acc1 \n\t" "mac.l %%d4, %%a5, (%[in])+, %%a5, %%acc0 \n\t" "mac.l %%d5, %%a5, (%[in])+, %%a5, %%acc1 \n\t" "mac.l %%d6, %%a5, (%[in])+, %%a5, %%acc0 \n\t" "mac.l %%d7, %%a5, %%acc1 \n\t" "movclr.l %%acc0, %%d1 \n\t" /* s1 */ "movclr.l %%acc1, %%d0 \n\t" /* s2 */ "movem.l %%d0-%%d1, (%[out]) \n\t" : [in] "+a" (_in), [win] "+a" (_win) : [out] "a" (out) : "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "a5", "memory"); } } #else #define MULTIPLY_ADD_BLOCK(y1, y2, x, c, k) \ y1 += fixmul31(c[k], x[k]); k++; \ y2 += fixmul31(c[k], x[k]); k++; \ y1 += fixmul31(c[k], x[k]); k++; \ y2 += fixmul31(c[k], x[k]); k++; \ y1 += fixmul31(c[k], x[k]); k++; \ y2 += fixmul31(c[k], x[k]); k++; \ y1 += fixmul31(c[k], x[k]); k++; \ y2 += fixmul31(c[k], x[k]); k++; static inline void atrac3_iqmf_dewindowing(int32_t *out, int32_t *in, int32_t *win, unsigned int nIn) { int32_t i, j, s1, s2; for (j = nIn; j != 0; j--, in+=2, out+=2) { s1 = s2 = i = 0; MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 0.. 7 */ MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 8..15 */ MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 16..23 */ MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 24..31 */ MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 32..39 */ MULTIPLY_ADD_BLOCK(s1, s2, in, win, i); /* 40..47 */ out[0] = s2; out[1] = s1; } } #endif /** * IMDCT windowing. * * @param buffer sample buffer * @param win window coefficients */ static inline void atrac3_imdct_windowing(int32_t *buffer, const int32_t *win) { int32_t i; /* win[0..127] = win[511..384], win[128..383] = 1 */ for(i = 0; i<128; i++) { buffer[ i] = fixmul31(win[i], buffer[ i]); buffer[511-i] = fixmul31(win[i], buffer[511-i]); } } /** * Quadrature mirror synthesis filter. * * @param inlo lower part of spectrum * @param inhi higher part of spectrum * @param nIn size of spectrum buffer * @param pOut out buffer * @param delayBuf delayBuf buffer * @param temp temp buffer */ static void iqmf (int32_t *inlo, int32_t *inhi, unsigned int nIn, int32_t *pOut, int32_t *delayBuf, int32_t *temp) { /* Restore the delay buffer */ memcpy(temp, delayBuf, 46*sizeof(int32_t)); /* loop1: matrixing */ atrac3_iqmf_matrixing(temp + 46, inlo, inhi, nIn); /* loop2: dewindowing */ atrac3_iqmf_dewindowing(pOut, temp, qmf_window, nIn); /* Save the delay buffer */ memcpy(delayBuf, temp + (nIn << 1), 46*sizeof(int32_t)); } /** * Regular 512 points IMDCT without overlapping, with the exception of the swapping of odd bands * caused by the reverse spectra of the QMF. * * @param pInput input * @param pOutput output * @param odd_band 1 if the band is an odd band */ static void IMLT(int32_t *pInput, int32_t *pOutput) { /* Apply the imdct. */ ff_imdct_calc(9, pOutput, pInput); /* Windowing. */ atrac3_imdct_windowing(pOutput, window_lookup); } /** * Atrac 3 indata descrambling, only used for data coming from the rm container * * @param in pointer to 8 bit array of indata * @param bits amount of bits * @param out pointer to 8 bit array of outdata */ static int decode_bytes(const uint8_t* inbuffer, uint8_t* out, int bytes){ int i, off; uint32_t c; const uint32_t* buf; uint32_t* obuf = (uint32_t*) out; #if ((defined(TEST) || defined(SIMULATOR)) && !defined(CPU_ARM)) off = 0; /* no check for memory alignment of inbuffer */ #else off = (intptr_t)inbuffer & 3; #endif /* TEST */ buf = (const uint32_t*) (inbuffer - off); c = be2me_32((0x537F6103 >> (off*8)) | (0x537F6103 << (32-(off*8)))); bytes += 3 + off; for (i = 0; i < bytes/4; i++) obuf[i] = c ^ buf[i]; return off; } static void init_atrac3_transforms(void) { int32_t s; int i; /* Generate the mdct window, for details see * http://wiki.multimedia.cx/index.php?title=RealAudio_atrc#Windows */ /* mdct window had been generated and saved as a lookup table in atrac3data_fixed.h */ /* Generate the QMF window. */ for (i=0 ; i<24; i++) { s = qmf_48tap_half_fix[i] << 1; #if defined(CPU_ARM) && (ARM_ARCH >= 5) qmf_window[i] = qmf_window[47-i] = (int16_t)((s+(1<<15))>>16); #else qmf_window[i] = qmf_window[47-i] = s; #endif } } /** * Mantissa decoding * * @param gb the GetBit context * @param selector what table is the output values coded with * @param codingFlag constant length coding or variable length coding * @param mantissas mantissa output table * @param numCodes amount of values to get */ static void readQuantSpectralCoeffs (GetBitContext *gb, int selector, int codingFlag, int* mantissas, int numCodes) { int numBits, cnt, code, huffSymb; if (selector == 1) numCodes /= 2; if (codingFlag != 0) { /* constant length coding (CLC) */ numBits = CLCLengthTab[selector]; if (selector > 1) { for (cnt = 0; cnt < numCodes; cnt++) { if (numBits) code = get_sbits(gb, numBits); else code = 0; mantissas[cnt] = code; } } else { for (cnt = 0; cnt < numCodes; cnt++) { if (numBits) code = get_bits(gb, numBits); /* numBits is always 4 in this case */ else code = 0; mantissas[cnt*2] = seTab_0[code >> 2]; mantissas[cnt*2+1] = seTab_0[code & 3]; } } } else { /* variable length coding (VLC) */ if (selector != 1) { for (cnt = 0; cnt < numCodes; cnt++) { huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3); huffSymb += 1; code = huffSymb >> 1; if (huffSymb & 1) code = -code; mantissas[cnt] = code; } } else { for (cnt = 0; cnt < numCodes; cnt++) { huffSymb = get_vlc2(gb, spectral_coeff_tab[selector-1].table, spectral_coeff_tab[selector-1].bits, 3); mantissas[cnt*2] = decTable1[huffSymb*2]; mantissas[cnt*2+1] = decTable1[huffSymb*2+1]; } } } } /** * Requantize the spectrum. * * @param *mantissas pointer to mantissas for each spectral line * @param pOut requantized band spectrum * @param first first spectral line in subband * @param last last spectral line in subband * @param SF scalefactor for all spectral lines of this band */ static void inverseQuantizeSpectrum(int *mantissas, int32_t *pOut, int32_t first, int32_t last, int32_t SF) { int *pIn = mantissas; /* Inverse quantize the coefficients. */ if((first/256) &1) { /* Odd band - Reverse coefficients */ do { pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); pOut[last--] = fixmul16(*pIn++, SF); } while (last>first); } else { /* Even band - Do not reverse coefficients */ do { pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); pOut[first++] = fixmul16(*pIn++, SF); } while (first<last); } } /** * Restore the quantized band spectrum coefficients * * @param gb the GetBit context * @param pOut decoded band spectrum * @return outSubbands subband counter, fix for broken specification/files */ int decodeSpectrum (GetBitContext *gb, int32_t *pOut) ICODE_ATTR_LARGE_IRAM; int decodeSpectrum (GetBitContext *gb, int32_t *pOut) { int numSubbands, codingMode, cnt, first, last, subbWidth; int subband_vlc_index[32], SF_idxs[32]; int mantissas[128]; int32_t SF; numSubbands = get_bits(gb, 5); /* number of coded subbands */ codingMode = get_bits1(gb); /* coding Mode: 0 - VLC/ 1-CLC */ /* Get the VLC selector table for the subbands, 0 means not coded. */ for (cnt = 0; cnt <= numSubbands; cnt++) subband_vlc_index[cnt] = get_bits(gb, 3); /* Read the scale factor indexes from the stream. */ for (cnt = 0; cnt <= numSubbands; cnt++) { if (subband_vlc_index[cnt] != 0) SF_idxs[cnt] = get_bits(gb, 6); } for (cnt = 0; cnt <= numSubbands; cnt++) { first = subbandTab[cnt]; last = subbandTab[cnt+1]; subbWidth = last - first; if (subband_vlc_index[cnt] != 0) { /* Decode spectral coefficients for this subband. */ /* TODO: This can be done faster is several blocks share the * same VLC selector (subband_vlc_index) */ readQuantSpectralCoeffs (gb, subband_vlc_index[cnt], codingMode, mantissas, subbWidth); /* Decode the scale factor for this subband. */ SF = fixmul31(SFTable_fixed[SF_idxs[cnt]], iMaxQuant_fix[subband_vlc_index[cnt]]); /* Remark: Hardcoded hack to add 2 bits (empty) fract part to internal sample * representation. Needed for higher accuracy in internal calculations as * well as for DSP configuration. See also: ../atrac3_rm.c, DSP_SET_SAMPLE_DEPTH */ SF <<= 2; /* Inverse quantize the coefficients. */ inverseQuantizeSpectrum(mantissas, pOut, first, last, SF); } else { /* This subband was not coded, so zero the entire subband. */ memset(pOut+first, 0, subbWidth*sizeof(int32_t)); } } /* Clear the subbands that were not coded. */ first = subbandTab[cnt]; memset(pOut+first, 0, (1024 - first) * sizeof(int32_t)); return numSubbands; } /** * Restore the quantized tonal components * * @param gb the GetBit context * @param pComponent tone component * @param numBands amount of coded bands */ static int decodeTonalComponents (GetBitContext *gb, tonal_component *pComponent, int numBands) { int i,j,k,cnt; int components, coding_mode_selector, coding_mode, coded_values_per_component; int sfIndx, coded_values, max_coded_values, quant_step_index, coded_components; int band_flags[4], mantissa[8]; int32_t *pCoef; int32_t scalefactor; int component_count = 0; components = get_bits(gb,5); /* no tonal components */ if (components == 0) return 0; coding_mode_selector = get_bits(gb,2); if (coding_mode_selector == 2) return -1; coding_mode = coding_mode_selector & 1; for (i = 0; i < components; i++) { for (cnt = 0; cnt <= numBands; cnt++) band_flags[cnt] = get_bits1(gb); coded_values_per_component = get_bits(gb,3); quant_step_index = get_bits(gb,3); if (quant_step_index <= 1) return -1; if (coding_mode_selector == 3) coding_mode = get_bits1(gb); for (j = 0; j < (numBands + 1) * 4; j++) { if (band_flags[j >> 2] == 0) continue; coded_components = get_bits(gb,3); for (k=0; k<coded_components; k++) { sfIndx = get_bits(gb,6); pComponent[component_count].pos = j * 64 + (get_bits(gb,6)); max_coded_values = 1024 - pComponent[component_count].pos; coded_values = coded_values_per_component + 1; coded_values = FFMIN(max_coded_values,coded_values); scalefactor = fixmul31(SFTable_fixed[sfIndx], iMaxQuant_fix[quant_step_index]); /* Remark: Hardcoded hack to add 2 bits (empty) fract part to internal sample * representation. Needed for higher accuracy in internal calculations as * well as for DSP configuration. See also: ../atrac3_rm.c, DSP_SET_SAMPLE_DEPTH */ scalefactor <<= 2; readQuantSpectralCoeffs(gb, quant_step_index, coding_mode, mantissa, coded_values); pComponent[component_count].numCoefs = coded_values; /* inverse quant */ pCoef = pComponent[component_count].coef; for (cnt = 0; cnt < coded_values; cnt++) pCoef[cnt] = fixmul16(mantissa[cnt], scalefactor); component_count++; } } } return component_count; } /** * Decode gain parameters for the coded bands * * @param gb the GetBit context * @param pGb the gainblock for the current band * @param numBands amount of coded bands */ static int decodeGainControl (GetBitContext *gb, gain_block *pGb, int numBands) { int i, cf, numData; int *pLevel, *pLoc; gain_info *pGain = pGb->gBlock; for (i=0 ; i<=numBands; i++) { numData = get_bits(gb,3); pGain[i].num_gain_data = numData; pLevel = pGain[i].levcode; pLoc = pGain[i].loccode; for (cf = 0; cf < numData; cf++){ pLevel[cf]= get_bits(gb,4); pLoc [cf]= get_bits(gb,5); if(cf && pLoc[cf] <= pLoc[cf-1]) return -1; } } /* Clear the unused blocks. */ for (; i<4 ; i++) pGain[i].num_gain_data = 0; return 0; } /** * Apply fix (constant) gain and overlap for sample[start...255]. * * @param pIn input buffer * @param pPrev previous buffer to perform overlap against * @param pOut output buffer * @param start index to start with (always a multiple of 8) * @param gain gain to apply */ static void applyFixGain (int32_t *pIn, int32_t *pPrev, int32_t *pOut, int32_t start, int32_t gain) { int32_t i = start; /* start is always a multiple of 8 and therefore allows us to unroll the * loop to 8 calculation per loop */ if (ONE_16 == gain) { /* gain1 = 1.0 -> no multiplication needed, just adding */ /* Remark: This path is called >90%. */ while (i<256) { pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; pOut[i] = pIn[i] + pPrev[i]; i++; }; } else { /* gain1 != 1.0 -> we need to do a multiplication */ /* Remark: This path is called seldom. */ while (i<256) { pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; pOut[i] = fixmul16(pIn[i], gain) + pPrev[i]; i++; }; } } /** * Apply variable gain and overlap. Returns sample index after applying gain, * resulting sample index is always a multiple of 8. * * @param pIn input buffer * @param pPrev previous buffer to perform overlap against * @param pOut output buffer * @param start index to start with (always a multiple of 8) * @param end end index for first loop (always a multiple of 8) * @param gain1 current bands gain to apply * @param gain2 next bands gain to apply * @param gain_inc stepwise adaption from gain1 to gain2 */ static int applyVariableGain (int32_t *pIn, int32_t *pPrev, int32_t *pOut, int32_t start, int32_t end, int32_t gain1, int32_t gain2, int32_t gain_inc) { int32_t i = start; /* Apply fix gains until end index is reached */ do { pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; } while (i < end); /* Interpolation is done over next eight samples */ pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); pOut[i] = fixmul16((fixmul16(pIn[i], gain1) + pPrev[i]), gain2); i++; gain2 = fixmul16(gain2, gain_inc); return i; } /** * Apply gain parameters and perform the MDCT overlapping part * * @param pIn input buffer * @param pPrev previous buffer to perform overlap against * @param pOut output buffer * @param pGain1 current band gain info * @param pGain2 next band gain info */ static void gainCompensateAndOverlap (int32_t *pIn, int32_t *pPrev, int32_t *pOut, gain_info *pGain1, gain_info *pGain2) { /* gain compensation function */ int32_t gain1, gain2, gain_inc; int cnt, numdata, nsample, startLoc; if (pGain2->num_gain_data == 0) gain1 = ONE_16; else gain1 = (ONE_16<<4)>>(pGain2->levcode[0]); if (pGain1->num_gain_data == 0) { /* Remark: This path is called >90%. */ /* Apply gain for all samples from 0...255 */ applyFixGain(pIn, pPrev, pOut, 0, gain1); } else { /* Remark: This path is called seldom. */ numdata = pGain1->num_gain_data; pGain1->loccode[numdata] = 32; pGain1->levcode[numdata] = 4; nsample = 0; /* starting loop with =0 */ for (cnt = 0; cnt < numdata; cnt++) { startLoc = pGain1->loccode[cnt] * 8; gain2 = (ONE_16<<4)>>(pGain1->levcode[cnt]); gain_inc = gain_tab2[(pGain1->levcode[cnt+1] - pGain1->levcode[cnt])+15]; /* Apply variable gain (gain1 -> gain2) to samples */ nsample = applyVariableGain(pIn, pPrev, pOut, nsample, startLoc, gain1, gain2, gain_inc); } /* Apply gain for the residual samples from nsample...255 */ applyFixGain(pIn, pPrev, pOut, nsample, gain1);