Coverage Report

Created: 2026-12-01 06:43

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/proc/self/cwd/libfaad/shim.c
Line
Count
Source
1
/*
2
** FAAD2 compatibility layer over libfaad3.
3
**
4
** Exports the NeAACDec* API of FAAD2 on top of the faad3 decoder API.
5
** Everything legacy (frame counter, output format conversion, FAAD2 channel
6
** order and downmix, error numbers) lives here so libfaad3 stays clean.
7
**
8
** Copyright (C) 2026 Nils Schimmelmann
9
**
10
** This program is free software; you can redistribute it and/or modify
11
** it under the terms of the GNU General Public License as published by
12
** the Free Software Foundation; either version 2 of the License, or
13
** (at your option) any later version.
14
**
15
** This program 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
18
** GNU General Public License for more details.
19
**
20
** You should have received a copy of the GNU General Public License
21
** along with this program; if not, write to the Free Software
22
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23
**
24
** The error message table (libfaad/error.c) and the downmix coefficients
25
** (libfaad/output.c) come from FAAD2:
26
** Copyright (C) 2003-2005 M. Bakker, Nero AG, http://www.nero.com
27
** The "appropriate copyright message" mentioned in section 2c of the GPLv2
28
** must read: "Code from FAAD2 is copyright (c) Nero AG, www.nero.com"
29
*/
30
31
#include <math.h>
32
#include <stdint.h>
33
#include <stdlib.h>
34
#include <string.h>
35
36
#include <faad3.h>
37
#include <faar.h>
38
39
#include "neaacdec.h"
40
41
1.42k
#define SHIM_MAX_CHANNELS 64
42
246
#define SYNC_SEARCH 768
43
6.43k
#define DRC_TARGET_DB (-20.0f)
44
45
/* FAAD2 error numbers; the strings are indexed by number. */
46
enum {
47
    ERR_NONE = 0,
48
    ERR_BITSTREAM = 10,
49
    ERR_NO_SYNC = 5,
50
    ERR_BAD_CHANNELS = 12,
51
    ERR_INPUT_SMALL = 14,
52
    ERR_OUTPUT_SMALL = 27,
53
    ERR_NOT_ALLOWED = 32
54
};
55
56
static char *const err_msg[] = {
57
    "No error",
58
    "Gain control not yet implemented",
59
    "Pulse coding not allowed in short blocks",
60
    "Invalid huffman codebook",
61
    "Scalefactor out of range",
62
    "Unable to find ADTS syncword",
63
    "Channel coupling not yet implemented",
64
    "Channel configuration not allowed in error resilient frame",
65
    "Bit error in error resilient scalefactor decoding",
66
    "Error decoding huffman scalefactor (bitstream error)",
67
    "Error decoding huffman codeword (bitstream error)",
68
    "Non existent huffman codebook number found",
69
    "Invalid number of channels",
70
    "Maximum number of bitstream elements exceeded",
71
    "Input data buffer too small",
72
    "Array index out of range",
73
    "Maximum number of scalefactor bands exceeded",
74
    "Quantised value out of range",
75
    "LTP lag out of range",
76
    "Invalid SBR parameter decoded",
77
    "SBR called without being initialised",
78
    "Unexpected channel configuration change",
79
    "Error in program_config_element",
80
    "First SBR frame is not the same as first AAC frame",
81
    "Unexpected fill element with SBR data",
82
    "Not all elements were provided with SBR data",
83
    "LTP decoding not available",
84
    "Output data buffer too small",
85
    "CRC error in DRM data",
86
    "PNS not allowed in DRM data stream",
87
    "No standard extension payload allowed in DRM",
88
    "PCE shall be the first element in a frame",
89
    "Bitstream value not allowed by specification",
90
    "MAIN prediction not initialised",
91
    "Long term prediction not initialised"
92
};
93
94
/* Sample type delivered by faad3 into the scratch buffer. */
95
typedef enum { T_I16, T_I32, T_F32 } pcm_type;
96
97
typedef struct {
98
    NeAACDecConfiguration cfg;
99
    faad_decoder *dec;
100
    enum faad_stream_format stream;
101
    uint8_t *asc;
102
    uint32_t asc_len;
103
    pcm_type type;
104
    unsigned fmt;   /* output format and downmix in force for the open decoder */
105
    int downmix_on;
106
    int dirty;      /* configuration changed since the decoder was opened */
107
    int decoded;    /* a frame has been decoded since the decoder was opened */
108
    long frame;     /* FAAD2 frame counter; drives the silent first frame */
109
    uint8_t *pcm;   /* scratch for faad3 output, max_output_bytes */
110
    uint32_t pcm_cap;
111
    uint8_t *out;   /* converted output returned by NeAACDecDecode */
112
    size_t out_cap;
113
    int adts_sfi;   /* sampling frequency index of the ADTS stream, -1 until known */
114
    int upsample;   /* FAAD2 doubled the rate of this stream's frames without SBR data */
115
    int downsample; /* implicit SBR above 24 kHz: FAAD2 returned the core rate */
116
    faar_resampler *rs;
117
    uint32_t rs_ch, rs_rate, rs_out;
118
    float *fifo;    /* resampled frames not yet returned, interleaved */
119
    size_t fifo_n, fifo_cap;
120
    float *up;      /* frames returned by the last call */
121
    float *cv;      /* frames converted to float for decimating */
122
    size_t cv_cap;
123
    size_t up_cap;
124
} shim_t;
125
126
static const uint32_t sr_table[12] = {
127
    96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000
128
};
129
130
char *NeAACDecGetErrorMessage(unsigned char errcode)
131
0
{
132
0
    if (errcode >= sizeof(err_msg) / sizeof(err_msg[0]))
133
0
        return NULL;
134
0
    return err_msg[errcode];
135
0
}
136
137
unsigned long NeAACDecGetCapabilities(void)
138
0
{
139
0
    return LC_DEC_CAP;
140
0
}
141
142
int NeAACDecGetVersion(char **faad_id_string, char **faad_copyright_string)
143
0
{
144
0
    static char id[] = FAAD2_VERSION;
145
0
    static char copy[] = "Code from FAAD2 is copyright (c) Nero AG, www.nero.com";
146
0
    if (faad_id_string)
147
0
        *faad_id_string = id;
148
0
    if (faad_copyright_string)
149
0
        *faad_copyright_string = copy;
150
0
    return 0;
151
0
}
152
153
NeAACDecHandle NeAACDecOpen(void)
154
5.65k
{
155
5.65k
    shim_t *s = calloc(1, sizeof(*s));
156
5.65k
    if (!s)
157
0
        return NULL;
158
5.65k
    s->adts_sfi = -1;
159
5.65k
    s->cfg.outputFormat = FAAD_FMT_16BIT;
160
5.65k
    s->cfg.defObjectType = MAIN;
161
5.65k
    s->cfg.defSampleRate = 44100;
162
5.65k
    return s;
163
5.65k
}
164
165
NeAACDecConfigurationPtr NeAACDecGetCurrentConfiguration(NeAACDecHandle h)
166
5.57k
{
167
5.57k
    shim_t *s = h;
168
5.57k
    return s ? &s->cfg : NULL;
169
5.57k
}
170
171
unsigned char NeAACDecSetConfiguration(NeAACDecHandle h, NeAACDecConfigurationPtr c)
172
5.65k
{
173
5.65k
    shim_t *s = h;
174
5.65k
    if (!s || !c)
175
0
        return 0;
176
    /* defObjectType is not validated: callers read the defaults (MAIN), change
177
     * one field and write the structure back. */
178
5.65k
    if (c->defSampleRate == 0)
179
2
        return 0;
180
5.65k
    if (c->outputFormat < FAAD_FMT_16BIT || c->outputFormat > FAAD_FMT_DOUBLE)
181
66
        return 0;
182
5.58k
    if (c->downMatrix > 1)
183
11
        return 0;
184
    /* Callers edit the structure returned by GetCurrentConfiguration in place,
185
     * so compare with the settings the open decoder uses, not with s->cfg. */
186
5.57k
    s->dirty = c->outputFormat != s->fmt || c->downMatrix != s->downmix_on;
187
5.57k
    s->cfg = *c;
188
5.57k
    return 1;
189
5.58k
}
190
191
/* FAAD2 doubled the rate of streams without SBR at or below 24 kHz, assuming
192
 * implicit SBR, and returned a fixed 2 x frame_length samples per frame.
193
 * libfaar produces its output in blocks, so frames are queued and returned
194
 * from a FIFO that starts with UP_LEAD frames of silence, enough that a block
195
 * boundary never leaves a call short. The lead is the delay of the output, and
196
 * 962 samples is the delay of FAAD2's QMF upsampling, which callers align
197
 * against. With a two-stage cascade libfaar falls at most 126 frames behind;
198
 * the single stage it plans on its own falls behind by up to 1748. */
199
109
#define UP_LEAD 962
200
201
/* FAAD2 returned implicit SBR above 24 kHz at the core rate, and its 32-band
202
 * synthesis delayed that output by the same amount as libfaad3's full-rate SBR
203
 * output, so the decimated stream needs no lead to line up with FAAD2's. libfaar
204
 * cannot do that: a zero-phase 2:1 filter needs 147 input frames of lookahead,
205
 * so it always has 73 output frames less than the input timeline. The FIFO must
206
 * start with at least that much silence or it underruns; the output is then 73
207
 * samples late against FAAD2. This is the smallest lag libfaar offers (FAST
208
 * quality with an explicit single stage); automatic planning and other stages
209
 * fall further behind. */
210
676
#define DOWN_LEAD 73
211
212
static void upsample_reset(shim_t *s)
213
15.1k
{
214
15.1k
    if (s->rs)
215
764
        faar_resampler_close(&s->rs);
216
15.1k
    s->fifo_n = 0;
217
15.1k
}
218
219
static void upsample_free(shim_t *s)
220
5.65k
{
221
5.65k
    upsample_reset(s);
222
5.65k
    free(s->fifo);
223
5.65k
    free(s->up);
224
5.65k
    free(s->cv);
225
5.65k
    s->fifo = s->up = s->cv = NULL;
226
5.65k
    s->fifo_cap = s->up_cap = s->cv_cap = 0;
227
5.65k
}
228
229
static int grow(float **buf, size_t *cap, size_t need)
230
3.44k
{
231
3.44k
    float *p;
232
233
3.44k
    if (*cap >= need)
234
280
        return 0;
235
3.16k
    p = realloc(*buf, need * sizeof(float));
236
3.16k
    if (!p)
237
0
        return -1;
238
3.16k
    *buf = p;
239
3.16k
    *cap = need;
240
3.16k
    return 0;
241
3.16k
}
242
243
/* Resample interleaved frames by a factor of two, priming the FIFO with lead
244
 * frames of silence. Returns the frames * out_rate / in_rate result, valid until
245
 * the next call, or NULL on failure. */
246
static const float *resample_frames(shim_t *s, const float *in, uint32_t frames, uint32_t n,
247
                                    uint32_t in_rate, uint32_t out_rate, size_t lead)
248
785
{
249
785
    const size_t out_frames = (size_t)frames * out_rate / in_rate;
250
785
    size_t got;
251
252
785
    if (s->rs && (s->rs_ch != n || s->rs_rate != in_rate || s->rs_out != out_rate))
253
35
        upsample_reset(s);
254
785
    if (!s->rs) {
255
764
        faar_config cfg;
256
764
        if (faar_config_init(&cfg, sizeof(cfg)) != FAAR_OK)
257
0
            return NULL;
258
764
        cfg.in_rate = in_rate;
259
764
        cfg.out_rate = out_rate;
260
764
        cfg.channels = n;
261
764
        cfg.quality = FAAR_QUALITY_FAST;
262
764
        cfg.decimate_factor = 2;
263
764
        if (faar_resampler_open(&cfg, &s->rs) != FAAR_OK)
264
0
            return NULL;
265
764
        s->rs_ch = n;
266
764
        s->rs_rate = in_rate;
267
764
        s->rs_out = out_rate;
268
764
        if (grow(&s->fifo, &s->fifo_cap, (size_t)(lead + out_frames) * n))
269
0
            return NULL;
270
764
        memset(s->fifo, 0, lead * n * sizeof(float));
271
764
        s->fifo_n = lead;
272
764
    }
273
    /* A block holds up to a few thousand frames beyond the input's share. */
274
785
    if (grow(&s->fifo, &s->fifo_cap, (s->fifo_n + out_frames + 8192) * n) ||
275
785
        grow(&s->up, &s->up_cap, out_frames * n))
276
0
        return NULL;
277
1.57k
    for (;;) {
278
1.57k
        faar_status st = faar_resampler_process(s->rs, in, frames, s->fifo + s->fifo_n * n,
279
1.57k
                                                s->fifo_cap / n - s->fifo_n, &got);
280
1.57k
        if (st != FAAR_OK)
281
0
            return NULL;
282
1.57k
        s->fifo_n += got;
283
1.57k
        if (!got)
284
785
            break;
285
785
        in = NULL;
286
785
        frames = 0;
287
785
        if (grow(&s->fifo, &s->fifo_cap, (s->fifo_n + out_frames + 8192) * n))
288
0
            return NULL;
289
785
    }
290
785
    if (s->fifo_n < out_frames) {
291
        /* Not expected with the lead; keep the frame size at the cost of a gap. */
292
0
        size_t gap = out_frames - s->fifo_n;
293
0
        memmove(s->fifo + gap * n, s->fifo, s->fifo_n * n * sizeof(float));
294
0
        memset(s->fifo, 0, gap * n * sizeof(float));
295
0
        s->fifo_n = out_frames;
296
0
    }
297
785
    memcpy(s->up, s->fifo, out_frames * n * sizeof(float));
298
785
    s->fifo_n -= out_frames;
299
785
    memmove(s->fifo, s->fifo + out_frames * n, s->fifo_n * n * sizeof(float));
300
785
    return s->up;
301
785
}
302
303
/* The stream is assumed to carry SBR implicitly. */
304
static int implicit_sbr(const faad_stream_info *info)
305
6.80k
{
306
6.80k
    return info->object_type == FAAD_OBJ_LC && info->sample_rate > 0 && info->sample_rate <= 24000;
307
6.80k
}
308
309
static int wants_upsample(const shim_t *s, const faad_stream_info *info)
310
5.09k
{
311
5.09k
    return !s->cfg.dontUpSampleImplicitSBR && implicit_sbr(info);
312
5.09k
}
313
314
static void shim_release(shim_t *s)
315
5.65k
{
316
5.65k
    upsample_free(s);
317
5.65k
    if (s->dec)
318
5.09k
        faad_decoder_close(&s->dec);
319
5.65k
    free(s->pcm);
320
5.65k
    s->pcm = NULL;
321
5.65k
    s->pcm_cap = 0;
322
5.65k
}
323
324
/* Output format requested from faad3 for the configured FAAD2 format. The
325
 * 32-bit and double formats and the FAAD2 downmix go through float. */
326
static pcm_type wanted_type(const shim_t *s)
327
5.96k
{
328
5.96k
    const NeAACDecConfiguration *c = &s->cfg;
329
330
5.96k
    if (c->downMatrix || s->upsample)
331
1.09k
        return T_F32;
332
4.86k
    switch (c->outputFormat) {
333
2.45k
    case FAAD_FMT_16BIT: return T_I16;
334
789
    case FAAD_FMT_24BIT: return T_I32;
335
1.62k
    default: return T_F32;
336
4.86k
    }
337
4.86k
}
338
339
static enum faad_output_format faad3_format(pcm_type t)
340
6.35k
{
341
6.35k
    return t == T_I16 ? FAAD_OUTPUT_16BIT : t == T_I32 ? FAAD_OUTPUT_24IN32 : FAAD_OUTPUT_FLOAT;
342
6.35k
}
343
344
static faad_status shim_open_dec(const shim_t *s, enum faad_stream_format stream, pcm_type type,
345
                                 const uint8_t *asc, uint32_t asc_len, faad_decoder **dec)
346
6.35k
{
347
6.35k
    faad_config cfg;
348
6.35k
    faad_status st = faad_config_init(&cfg, sizeof(cfg));
349
6.35k
    if (st != FAAD_OK)
350
0
        return st;
351
6.35k
    (void)s;
352
6.35k
    cfg.stream_format = stream;
353
6.35k
    cfg.output_format = faad3_format(type);
354
    /* FAAD2 applies the full compression and normalises to -20 dBFS. */
355
6.35k
    cfg.drc_cut = 127;
356
6.35k
    cfg.drc_boost = 127;
357
6.35k
    cfg.drc_target_level = DRC_TARGET_DB;
358
6.35k
    return faad_decoder_open(&cfg, asc, asc_len, dec);
359
6.35k
}
360
361
/* (Re)open the faad3 decoder for the stored stream parameters. */
362
static int shim_reopen(shim_t *s)
363
5.96k
{
364
5.96k
    faad_stream_info info = { .struct_size = sizeof(info) };
365
5.96k
    if (s->dec)
366
457
        faad_decoder_close(&s->dec);
367
5.96k
    free(s->pcm);
368
5.96k
    s->pcm = NULL;
369
5.96k
    s->type = wanted_type(s);
370
5.96k
    upsample_reset(s);
371
5.96k
    s->fmt = s->cfg.outputFormat;
372
5.96k
    s->downmix_on = s->cfg.downMatrix;
373
5.96k
    if (shim_open_dec(s, s->stream, s->type, s->asc, s->asc_len, &s->dec) != FAAD_OK)
374
408
        return -1;
375
5.55k
    if (faad_decoder_get_info(s->dec, &info) != FAAD_OK)
376
0
        return -1;
377
5.55k
    s->pcm = malloc(info.max_output_bytes);
378
5.55k
    if (!s->pcm)
379
0
        return -1;
380
5.55k
    s->pcm_cap = info.max_output_bytes;
381
5.55k
    s->dirty = 0;
382
5.55k
    s->decoded = 0;
383
5.55k
    return 0;
384
5.55k
}
385
386
static int adts_sniff(const unsigned char *b, unsigned long n)
387
166k
{
388
166k
    return n >= 7 && b[0] == 0xFF && (b[1] & 0xF6) == 0xF0;
389
166k
}
390
391
long NeAACDecInit(NeAACDecHandle h, unsigned char *buffer, unsigned long buffer_size,
392
                  unsigned long *samplerate, unsigned char *channels)
393
454
{
394
454
    shim_t *s = h;
395
454
    faad_decoder *probe = NULL;
396
454
    faad_stream_info info = { .struct_size = sizeof(info) };
397
454
    uint32_t used = 0, wr = 0, fl = 0;
398
454
    uint8_t *pcm;
399
454
    unsigned cc;
400
454
    enum faad_object_type probed = FAAD_OBJ_LC;
401
402
454
    if (!s || !samplerate || !channels || buffer_size == 0 || !buffer)
403
13
        return -1;
404
441
    {
405
441
        unsigned long k;
406
166k
        for (k = 0; k < buffer_size && !adts_sniff(buffer + k, buffer_size - k); k++)
407
165k
            ;
408
441
        if (k >= buffer_size)
409
43
            return -1;
410
398
        buffer += k;
411
398
        buffer_size -= k;
412
        /* Only AAC-LC decodes. Say so here, where players can still fall back
413
         * to another decoder, rather than failing on the first frame. */
414
398
        if ((buffer[2] >> 6) != 1)
415
4
            return -1;
416
398
    }
417
418
394
    free(s->asc);
419
394
    s->asc = NULL;
420
394
    s->asc_len = 0;
421
394
    s->stream = FAAD_STREAM_ADTS;
422
394
    s->frame = 0;
423
394
    s->upsample = 0;
424
394
    s->downsample = 0;
425
394
    s->adts_sfi = (buffer[2] >> 2) & 15;
426
427
    /* Report the format the decoder will really emit: decode the first frame
428
     * on a scratch decoder. A buffer too short for a frame falls back to the
429
     * ADTS header. */
430
394
    {
431
394
        unsigned sfi = (buffer[2] >> 2) & 15;
432
394
        cc = ((buffer[2] & 1) << 2) | (buffer[3] >> 6);
433
394
        *samplerate = sr_table[sfi < 12 ? sfi : 0];
434
394
        *channels = (unsigned char)(cc == 7 ? 8 : cc);
435
394
    }
436
394
    if (shim_open_dec(s, FAAD_STREAM_ADTS, T_I16, NULL, 0, &probe) == FAAD_OK) {
437
394
        if (faad_decoder_get_info(probe, &info) == FAAD_OK &&
438
394
            (pcm = malloc(info.max_output_bytes)) != NULL) {
439
394
            if (faad_decode_frame(probe, buffer, (uint32_t)buffer_size, &used, pcm,
440
394
                                  info.max_output_bytes, &wr, &fl) == FAAD_OK &&
441
175
                faad_decoder_get_info(probe, &info) == FAAD_OK && (info.flags & FAAD_STREAM_FORMAT_KNOWN)) {
442
175
                *samplerate = info.sample_rate;
443
175
                *channels = (unsigned char)info.channels;
444
175
                probed = info.object_type;
445
175
            }
446
394
            free(pcm);
447
394
        }
448
394
        faad_decoder_close(&probe);
449
394
    }
450
    /* FAAD2 2.11.3 upmixed every mono stream to stereo (implicit PS signalling):
451
     * the Init functions reported two channels and every frame that decoded to
452
     * one channel came back as dual-mono, so PS showing up mid-stream (ADTS
453
     * cannot signal it up front) never changes the channel count. The frames
454
     * are upmixed per frame in shim_decode, as FAAD2 did. */
455
394
    if (*channels == 1)
456
84
        *channels = 2;
457
    /* A stream without SBR data at or below 24 kHz is assumed to carry SBR
458
     * implicitly, and FAAD2 reported and returned its doubled rate. */
459
394
    info.object_type = probed;
460
394
    info.sample_rate = (uint32_t)*samplerate;
461
394
    if (wants_upsample(s, &info)) {
462
48
        s->upsample = 1;
463
48
        *samplerate *= 2;
464
346
    } else if (sr_table[((buffer[2] >> 2) & 15) < 12 ? (buffer[2] >> 2) & 15 : 0] > 24000) {
465
        /* Above 24 kHz FAAD2 configured the decoder from the header, assumed
466
         * implicit SBR and reported the core rate. Frames that carry SBR then
467
         * came back downsampled to it; dontUpSampleImplicitSBR kept them at the
468
         * SBR rate. */
469
196
        *samplerate = sr_table[((buffer[2] >> 2) & 15) < 12 ? (buffer[2] >> 2) & 15 : 0];
470
196
        if (!s->cfg.dontUpSampleImplicitSBR)
471
112
            s->downsample = 1;
472
196
    } else if (s->cfg.dontUpSampleImplicitSBR) {
473
        /* FAAD2 then reported the rate in the ADTS header, SBR or not. */
474
138
        *samplerate = sr_table[((buffer[2] >> 2) & 15) < 12 ? (buffer[2] >> 2) & 15 : 0];
475
138
    }
476
394
    if (shim_reopen(s) != 0)
477
0
        return -1;
478
    /* FAAD2 reported two channels for any ADTS channel configuration above 6,
479
     * whatever the stream carried; the frames report the real count. */
480
394
    if (cc == 7)
481
68
        *channels = 2;
482
394
    return 0;
483
394
}
484
485
char NeAACDecInit2(NeAACDecHandle h, unsigned char *pBuffer, unsigned long size,
486
                   unsigned long *samplerate, unsigned char *channels)
487
5.12k
{
488
5.12k
    shim_t *s = h;
489
5.12k
    faad_stream_info info = { .struct_size = sizeof(info) };
490
491
5.12k
    if (!s || !pBuffer || size < 2 || !samplerate || !channels)
492
11
        return -1;
493
494
5.11k
    free(s->asc);
495
5.11k
    s->asc = malloc(size);
496
5.11k
    if (!s->asc)
497
0
        return -1;
498
5.11k
    memcpy(s->asc, pBuffer, size);
499
5.11k
    s->asc_len = (uint32_t)size;
500
5.11k
    s->stream = FAAD_STREAM_RAW;
501
5.11k
    s->frame = 0;
502
5.11k
    s->upsample = 0;
503
5.11k
    s->downsample = 0;
504
5.11k
    if (shim_reopen(s) != 0)
505
408
        return -1;
506
4.70k
    if (faad_decoder_get_info(s->dec, &info) != FAAD_OK || !(info.flags & FAAD_STREAM_FORMAT_KNOWN))
507
0
        return -1;
508
4.70k
    *samplerate = info.sample_rate;
509
    /* An ASC without SBR signalling at or below 24 kHz is treated as implicit
510
     * SBR: FAAD2 reported and returned the doubled rate. */
511
4.70k
    s->upsample = wants_upsample(s, &info);
512
    /* Without SBR signalling above 24 kHz, FAAD2 parsed downSampledSBR from the
513
     * ASC and returned the core rate whether or not dontUpSampleImplicitSBR was
514
     * set. Frames that turn out to carry SBR data are converted to float for the
515
     * decimation, so that streams without it keep their native output. */
516
4.70k
    s->downsample = info.object_type == FAAD_OBJ_LC && info.sample_rate > 24000;
517
4.70k
    if (s->upsample && shim_reopen(s) != 0)
518
0
        return -1;
519
    /* FAAD2 doubled the rate it reported even when dontUpSampleImplicitSBR kept
520
     * the frames at the core rate. */
521
4.70k
    if (implicit_sbr(&info))
522
961
        *samplerate *= 2;
523
    /* FAAD2 reported the channels of the core, which is mono for PS streams;
524
     * the frames then carry two. */
525
4.70k
    *channels = (unsigned char)(info.object_type == FAAD_OBJ_HE_AAC_V2 ? 1 : info.channels);
526
    /* FAAD2 2.11.3 upmixed every mono stream to stereo (implicit PS signalling). */
527
4.70k
    if (*channels == 1)
528
362
        *channels = 2;
529
    /* FAAD2 returned the channel configuration index, which is 7 for 7.1. */
530
4.70k
    if (*channels == 8)
531
866
        *channels = 7;
532
4.70k
    return 0;
533
4.70k
}
534
535
char NeAACDecInitDRM(NeAACDecHandle *h, unsigned long samplerate, unsigned char channels)
536
1.32k
{
537
1.32k
    (void)h;
538
1.32k
    (void)samplerate;
539
1.32k
    (void)channels;
540
1.32k
    return 1;
541
1.32k
}
542
543
void NeAACDecPostSeekReset(NeAACDecHandle h, long frame)
544
3.50k
{
545
3.50k
    shim_t *s = h;
546
3.50k
    if (!s)
547
0
        return;
548
    /* A seek discards decoder history anyway, so this is where a changed
549
     * output format or downmix can take effect mid-stream. */
550
3.50k
    if (s->dec) {
551
3.50k
        if (s->dirty && (s->cfg.outputFormat != s->fmt || s->cfg.downMatrix != s->downmix_on))
552
0
            shim_reopen(s);
553
3.50k
        else {
554
3.50k
            faad_decoder_flush(s->dec);
555
3.50k
            upsample_reset(s);
556
3.50k
        }
557
3.50k
    }
558
3.50k
    if (frame != -1)
559
3.50k
        s->frame = frame;
560
3.50k
}
561
562
void NeAACDecClose(NeAACDecHandle h)
563
5.65k
{
564
5.65k
    shim_t *s = h;
565
5.65k
    if (!s)
566
0
        return;
567
5.65k
    shim_release(s);
568
5.65k
    free(s->asc);
569
5.65k
    free(s->out);
570
5.65k
    free(s);
571
5.65k
}
572
573
char NeAACDecAudioSpecificConfig(unsigned char *pBuffer, unsigned long size,
574
                                 mp4AudioSpecificConfig *asc)
575
0
{
576
0
    faad_decoder *d = NULL;
577
0
    faad_stream_info info = { .struct_size = sizeof(info) };
578
0
    unsigned i;
579
580
0
    if (!pBuffer || size < 2 || !asc)
581
0
        return -1;
582
0
    memset(asc, 0, sizeof(*asc));
583
0
    if (shim_open_dec(NULL, FAAD_STREAM_RAW, T_I16, pBuffer, (uint32_t)size, &d) != FAAD_OK)
584
0
        return -1;
585
0
    if (faad_decoder_get_info(d, &info) != FAAD_OK || !(info.flags & FAAD_STREAM_FORMAT_KNOWN)) {
586
0
        faad_decoder_close(&d);
587
0
        return -1;
588
0
    }
589
0
    faad_decoder_close(&d);
590
591
    /* FAAD2 reported the object type the ASC starts with when SBR is signalled
592
     * explicitly (AOT 5 or 29 is wrapped around an AAC-LC core, so 2), and 5
593
     * when the SBR or PS extension follows an AOT 2 core. */
594
0
    {
595
0
        unsigned first = pBuffer[0] >> 3;
596
0
        int hev2 = info.object_type == FAAD_OBJ_HE_AAC_V2;
597
0
        asc->objectTypeIndex = (unsigned char)((first == 5 || first == 29) ? LC :
598
0
                               hev2 ? HE_AAC : info.object_type);
599
0
        asc->sbr_present_flag = info.object_type != FAAD_OBJ_LC ? 1 : -1;
600
0
        asc->ps_present_flag = hev2 ? 1 : -1;
601
0
    }
602
0
    asc->samplingFrequency = info.sample_rate;
603
    /* The channel configuration index, which is 7 for 7.1. */
604
0
    asc->channelsConfiguration = (unsigned char)(info.object_type == FAAD_OBJ_HE_AAC_V2 ? 1 :
605
0
                                                 info.channels == 8 ? 7 : info.channels);
606
    /* FAAD2 2.11.3 upmixed mono to stereo in the ASC too (implicit PS). */
607
0
    if (asc->channelsConfiguration == 1)
608
0
        asc->channelsConfiguration = 2;
609
0
    asc->frameLengthFlag = (info.frame_samples % 960) == 0 && (info.frame_samples % 1024) != 0;
610
0
    {
611
0
        unsigned long core = asc->sbr_present_flag > 0 ? info.sample_rate / 2 : info.sample_rate;
612
0
        for (i = 0; i < 12; i++)
613
0
            if (sr_table[i] == core)
614
0
                break;
615
0
        asc->samplingFrequencyIndex = (unsigned char)(i < 12 ? i : 15);
616
0
    }
617
    /* Without SBR signalling FAAD2 assumed implicit SBR: upsampled output at or
618
     * below 24 kHz, and SBR at the core rate above it. */
619
0
    if (asc->sbr_present_flag < 0) {
620
0
        if (implicit_sbr(&info)) {
621
0
            asc->samplingFrequency *= 2;
622
0
            asc->forceUpSampling = 1;
623
0
        } else if (info.sample_rate > 24000) {
624
0
            asc->downSampledSBR = 1;
625
0
        }
626
0
    }
627
0
    return 0;
628
0
}
629
630
/* FAAD2 position code for each bit of a WAVE channel mask. */
631
/* wide: the mask has an inner front pair (FLC FRC), which is how libfaad3 reads
632
 * channelConfiguration 7. FAAD2 labels that stream's three pairs front, side and back
633
 * in stream order, so the inner pair is the front one, FL/FR the side one, and BL/BR the
634
 * back one. */
635
static unsigned mask_bit_code(unsigned bit, int wide)
636
2.42k
{
637
2.42k
    switch (bit) {
638
640
    case 0: return wide ? SIDE_CHANNEL_LEFT : FRONT_CHANNEL_LEFT;
639
640
    case 1: return wide ? SIDE_CHANNEL_RIGHT : FRONT_CHANNEL_RIGHT;
640
47
    case 6: return wide ? FRONT_CHANNEL_LEFT : UNKNOWN_CHANNEL;
641
47
    case 7: return wide ? FRONT_CHANNEL_RIGHT : UNKNOWN_CHANNEL;
642
586
    case 2: return FRONT_CHANNEL_CENTER;
643
103
    case 3: return LFE_CHANNEL;
644
130
    case 4: return BACK_CHANNEL_LEFT;
645
130
    case 5: return BACK_CHANNEL_RIGHT;
646
34
    case 8: return BACK_CHANNEL_CENTER;
647
33
    case 9: return SIDE_CHANNEL_LEFT;
648
33
    case 10: return SIDE_CHANNEL_RIGHT;
649
0
    default: return UNKNOWN_CHANNEL;
650
2.42k
    }
651
2.42k
}
652
653
/* FAAD2 emits channels in bitstream order, which is ascending position code
654
 * (C L R, side, back, back centre, LFE). faad3 emits ascending WAVE mask bit.
655
 * perm[j] is the faad3 channel that becomes output channel j. Returns 1 when
656
 * the order is not the identity. */
657
static int build_perm(uint32_t mask, uint32_t n, uint8_t *perm, uint8_t *pos)
658
1.42k
{
659
1.42k
    uint8_t code[SHIM_MAX_CHANNELS];
660
1.42k
    uint32_t k = 0, i, j;
661
1.42k
    int moved = 0, wide = (mask & 0xC0u) == 0xC0u;
662
663
5.41k
    for (i = 0; i < n; i++)
664
3.99k
        perm[i] = (uint8_t)i, pos[i] = UNKNOWN_CHANNEL;
665
1.42k
    if (!mask)
666
357
        return 0;
667
4.60k
    for (i = 0; i < 32 && k < n; i++)
668
3.53k
        if (mask & (1u << i))
669
2.42k
            code[k++] = (uint8_t)mask_bit_code(i, wide);
670
1.06k
    if (k != n)
671
0
        return 0;
672
3.49k
    for (i = 0; i < n; i++)
673
2.42k
        if (code[i] == UNKNOWN_CHANNEL)
674
0
            return 0;
675
2.42k
    for (i = 1; i < n; i++) {   /* stable insertion sort by code */
676
1.35k
        uint8_t c = code[i], p = perm[i];
677
2.55k
        for (j = i; j > 0 && code[j - 1] > c; j--) {
678
1.19k
            code[j] = code[j - 1];
679
1.19k
            perm[j] = perm[j - 1];
680
1.19k
        }
681
1.35k
        code[j] = c;
682
1.35k
        perm[j] = p;
683
1.35k
    }
684
3.49k
    for (i = 0; i < n; i++) {
685
2.42k
        pos[i] = code[i];
686
2.42k
        moved |= perm[i] != i;
687
2.42k
    }
688
1.06k
    return moved;
689
1.06k
}
690
691
static size_t out_sample_bytes(unsigned fmt)
692
1.42k
{
693
1.42k
    switch (fmt) {
694
517
    case FAAD_FMT_16BIT: return 2;
695
100
    case FAAD_FMT_DOUBLE: return 8;
696
807
    default: return 4;
697
1.42k
    }
698
1.42k
}
699
700
static void put_sample(unsigned fmt, uint8_t *dst, size_t idx, double v)
701
3.06M
{
702
3.06M
    switch (fmt) {
703
1.11M
    case FAAD_FMT_16BIT: {
704
1.11M
        double x = v * 32768.0;
705
1.11M
        x = x >= 32767.0 ? 32767.0 : x <= -32768.0 ? -32768.0 : x;
706
1.11M
        ((int16_t *)dst)[idx] = (int16_t)lrint(x);
707
1.11M
        break;
708
0
    }
709
451k
    case FAAD_FMT_24BIT: {
710
451k
        double x = v * 8388608.0;
711
451k
        x = x >= 8388607.0 ? 8388607.0 : x <= -8388608.0 ? -8388608.0 : x;
712
451k
        ((int32_t *)dst)[idx] = (int32_t)lrint(x);
713
451k
        break;
714
0
    }
715
555k
    case FAAD_FMT_32BIT: {
716
555k
        double x = v * 2147483648.0;
717
555k
        x = x >= 2147483647.0 ? 2147483647.0 : x <= -2147483648.0 ? -2147483648.0 : x;
718
555k
        ((int32_t *)dst)[idx] = (int32_t)lrint(x);
719
555k
        break;
720
0
    }
721
676k
    case FAAD_FMT_FLOAT:
722
676k
        ((float *)dst)[idx] = (float)v;
723
676k
        break;
724
265k
    default:
725
265k
        ((double *)dst)[idx] = v;
726
265k
        break;
727
3.06M
    }
728
3.06M
}
729
730
static int ensure_out(shim_t *s, size_t need)
731
928
{
732
928
    if (s->out_cap < need) {
733
858
        uint8_t *p = realloc(s->out, need);
734
858
        if (!p)
735
0
            return -1;
736
858
        s->out = p;
737
858
        s->out_cap = need;
738
858
    }
739
928
    return 0;
740
928
}
741
742
102k
#define DM_MUL 0.3203772410170407
743
204k
#define RSQRT2 0.7071067811865475244
744
745
/* Map a faad3 error to the nearest FAAD2 error number. */
746
static unsigned char map_status(faad_status st)
747
803
{
748
803
    switch (st) {
749
0
    case FAAD_OK: return ERR_NONE;
750
129
    case FAAD_ERR_SYNC_LOST: return ERR_NO_SYNC;
751
59
    case FAAD_ERR_NEED_MORE_DATA: return ERR_INPUT_SMALL;
752
0
    case FAAD_ERR_OUTPUT_TOO_SMALL: return ERR_OUTPUT_SMALL;
753
23
    case FAAD_ERR_UNSUPPORTED: return ERR_NOT_ALLOWED;
754
592
    case FAAD_ERR_DECODE_FAILED: return ERR_BITSTREAM;
755
0
    default: return ERR_NOT_ALLOWED;
756
803
    }
757
803
}
758
759
/* FAAD2 normalised a stream that carries DRC data but no programme reference
760
 * level as if the reference were 0 dBFS, so those streams came out 20 dB quieter.
761
 * Callers may have worked around that, so it is reproduced. */
762
static void attenuate_missing_reference(void *pcm, pcm_type t, size_t count)
763
77
{
764
77
    const float g = exp2f(DRC_TARGET_DB / 6.0f);
765
77
    size_t i;
766
767
340k
    for (i = 0; i < count; i++) {
768
340k
        if (t == T_I16) ((int16_t *)pcm)[i] = (int16_t)lrintf(((int16_t *)pcm)[i] * g);
769
229k
        else if (t == T_I32) ((int32_t *)pcm)[i] = (int32_t)lrintf(((int32_t *)pcm)[i] * g);
770
188k
        else ((float *)pcm)[i] *= g;
771
340k
    }
772
77
}
773
774
static void *shim_decode(shim_t *s, NeAACDecFrameInfo *fi, const uint8_t *buf, unsigned long size,
775
                         void *dest, unsigned long dest_size)
776
10.1k
{
777
10.1k
    faad_stream_info info = { .struct_size = sizeof(info) };
778
10.1k
    uint32_t used = 0, wr = 0, flags = 0, n, frames, i, c, out_ch, skipped = 0, rate;
779
10.1k
    int upsampled = 0, downsampled = 0;
780
10.1k
    pcm_type st_type;
781
10.1k
    uint8_t perm[SHIM_MAX_CHANNELS], pos[SHIM_MAX_CHANNELS];
782
10.1k
    unsigned fmt = s->fmt;
783
10.1k
    size_t esz, osz, need;
784
10.1k
    int moved, downmix;
785
10.1k
    faad_status st;
786
10.1k
    uint8_t *src, *out, *src_pcm = NULL;
787
788
10.1k
    if (!fi)
789
0
        return NULL;
790
10.1k
    memset(fi, 0, sizeof(*fi));
791
10.1k
    if (!s->dec || !buf || size == 0) {
792
3.10k
        fi->error = ERR_INPUT_SMALL;
793
3.10k
        return NULL;
794
3.10k
    }
795
7.04k
    if (s->dirty && !s->decoded && shim_reopen(s) != 0) {
796
0
        fi->error = ERR_NOT_ALLOWED;
797
0
        return NULL;
798
0
    }
799
800
    /* FAAD2 searches up to 768 bytes for an ADTS syncword inside one call and
801
     * then decodes the frame behind the junk; callers rely on that. */
802
7.27k
    for (;;) {
803
7.27k
        st = faad_decode_frame(s->dec, buf + skipped, (uint32_t)(size - skipped), &used,
804
7.27k
                               s->pcm, s->pcm_cap, &wr, &flags);
805
7.27k
        if (st != FAAD_ERR_SYNC_LOST || used == 0 || skipped + used >= size ||
806
246
            skipped + used >= SYNC_SEARCH)
807
7.04k
            break;
808
228
        skipped += used;
809
228
    }
810
7.04k
    used += skipped;
811
7.04k
    fi->bytesconsumed = used;
812
7.04k
    if (st != FAAD_OK) {
813
803
        fi->error = map_status(st);
814
        /* FAAD2 consumed nothing on an error and callers step through the
815
         * stream themselves; claiming a frame length could jump over real
816
         * frames when the header was a false sync. */
817
803
        fi->bytesconsumed = 0;
818
803
        return NULL;
819
803
    }
820
6.23k
    if (flags & FAAD_FRAME_CONCEALED) {
821
        /* FAAD2 reported corrupt core data as an error and returned no samples;
822
         * its callers and their resync logic expect that. The claimed length
823
         * of a corrupt ADTS frame cannot be trusted either. */
824
4.79k
        fi->error = ERR_BITSTREAM;
825
4.79k
        fi->bytesconsumed = 0;
826
4.79k
        return NULL;
827
4.79k
    }
828
    /* FAAD2 configured the decoder once, from the first header. Frames written for
829
     * another sampling rate then failed to decode, with errors that depend on the
830
     * bits; 32 was the usual one. */
831
1.44k
    if (s->stream == FAAD_STREAM_ADTS && s->adts_sfi >= 0 && ((buf[skipped + 2] >> 2) & 15) != s->adts_sfi) {
832
23
        fi->error = ERR_NOT_ALLOWED;
833
23
        fi->bytesconsumed = 0;
834
23
        return NULL;
835
23
    }
836
1.42k
    s->decoded = 1;
837
1.42k
    s->frame++;
838
1.42k
    fi->header_type = s->stream == FAAD_STREAM_ADTS ? ADTS : RAW;
839
1.42k
    if (wr == 0)
840
0
        return NULL;
841
1.42k
    if (faad_decoder_get_info(s->dec, &info) != FAAD_OK || info.channels == 0 ||
842
1.42k
        info.channels > SHIM_MAX_CHANNELS) {
843
0
        fi->error = ERR_BAD_CHANNELS;
844
0
        return NULL;
845
0
    }
846
847
1.42k
    n = info.channels;
848
1.42k
    st_type = s->type;
849
1.42k
    esz = s->type == T_I16 ? 2 : 4;
850
1.42k
    frames = wr / (uint32_t)(esz * n);
851
1.42k
    if ((flags & FAAD_FRAME_DRC_INFO) && !(info.flags & FAAD_STREAM_DRC_REF_LEVEL))
852
77
        attenuate_missing_reference(s->pcm, s->type, (size_t)frames * n);
853
1.42k
    rate = info.sample_rate;
854
1.42k
    if (s->upsample && !(flags & FAAD_FRAME_SBR) && s->type == T_F32 && rate <= 24000) {
855
109
        const float *up = resample_frames(s, (const float *)s->pcm, frames, n, rate, rate * 2,
856
109
                                          UP_LEAD);
857
109
        if (!up) {
858
0
            fi->error = ERR_NOT_ALLOWED;
859
0
            return NULL;
860
0
        }
861
109
        src_pcm = (uint8_t *)up;
862
109
        frames *= 2;
863
109
        rate *= 2;
864
109
        upsampled = 1;
865
1.31k
    } else if (s->downsample && (flags & FAAD_FRAME_SBR) && rate > 24000) {
866
676
        const float *in_f = (const float *)s->pcm, *down;
867
676
        size_t total = (size_t)frames * n, k_;
868
676
        if (s->type != T_F32) {
869
322
            const float scale = s->type == T_I16 ? 1.0f / 32768.0f : 1.0f / 8388608.0f;
870
322
            if (grow(&s->cv, &s->cv_cap, total)) {
871
0
                fi->error = ERR_NOT_ALLOWED;
872
0
                return NULL;
873
0
            }
874
1.52M
            for (k_ = 0; k_ < total; k_++)
875
1.52M
                s->cv[k_] = s->type == T_I16 ? (float)((int16_t *)s->pcm)[k_] * scale
876
1.52M
                                             : (float)((int32_t *)s->pcm)[k_] * scale;
877
322
            in_f = s->cv;
878
322
        }
879
676
        down = resample_frames(s, in_f, frames, n, rate, rate / 2, DOWN_LEAD);
880
676
        if (!down) {
881
0
            fi->error = ERR_NOT_ALLOWED;
882
0
            return NULL;
883
0
        }
884
676
        src_pcm = (uint8_t *)down;
885
676
        frames /= 2;
886
676
        rate /= 2;
887
676
        downsampled = 1;
888
676
        st_type = T_F32;
889
676
    }
890
1.42k
    downmix = s->downmix_on && (n == 5 || n == 6);
891
1.42k
    out_ch = n == 1 ? 2 : (downmix ? 2 : n);
892
1.42k
    moved = build_perm(info.channel_mask, n, perm, pos);
893
1.42k
    osz = out_sample_bytes(fmt);
894
1.42k
    need = (size_t)frames * out_ch * osz;
895
896
1.42k
    src = (upsampled || downsampled) ? src_pcm : s->pcm;
897
1.42k
    if (!downmix && !moved && n != 1 &&
898
813
        ((st_type == T_I16 && fmt == FAAD_FMT_16BIT) ||
899
689
         (st_type == T_I32 && fmt == FAAD_FMT_24BIT) ||
900
650
         (st_type == T_F32 && fmt == FAAD_FMT_FLOAT))) {
901
379
        out = src;
902
1.04k
    } else {
903
1.04k
        if (dest) {
904
117
            if (dest_size < need) {
905
30
                fi->error = ERR_OUTPUT_SMALL;
906
30
                return NULL;
907
30
            }
908
87
            out = dest;
909
928
        } else {
910
928
            if (ensure_out(s, need) != 0) {
911
0
                fi->error = ERR_NOT_ALLOWED;
912
0
                return NULL;
913
0
            }
914
928
            out = s->out;
915
928
        }
916
1.01k
        if (downmix) {
917
37
            const float *f = (const float *)src;
918
51.0k
            for (i = 0; i < frames; i++) {
919
51.0k
                const float *x = f + (size_t)i * n;
920
51.0k
                double cen = x[perm[0]], l = x[perm[1]], r = x[perm[2]];
921
51.0k
                double bl = x[perm[3]], br = x[perm[4]];
922
51.0k
                put_sample(fmt, out, (size_t)i * 2, DM_MUL * (l + cen * RSQRT2 + bl * RSQRT2));
923
51.0k
                put_sample(fmt, out, (size_t)i * 2 + 1, DM_MUL * (r + cen * RSQRT2 + br * RSQRT2));
924
51.0k
            }
925
978
        } else if (n == 1) {
926
416
            if (st_type == T_F32) {
927
287
                const float *f = (const float *)src;
928
332k
                for (i = 0; i < frames; i++) {
929
332k
                    put_sample(fmt, out, (size_t)i * 2, f[i]);
930
332k
                    put_sample(fmt, out, (size_t)i * 2 + 1, f[i]);
931
332k
                }
932
287
            } else if (st_type == T_I16) {
933
65
                const int16_t *p = (const int16_t *)src;
934
71.2k
                for (i = 0; i < frames; i++) {
935
71.2k
                    ((int16_t *)out)[(size_t)i * 2] = p[i];
936
71.2k
                    ((int16_t *)out)[(size_t)i * 2 + 1] = p[i];
937
71.2k
                }
938
65
            } else {
939
64
                const int32_t *p = (const int32_t *)src;
940
97.7k
                for (i = 0; i < frames; i++) {
941
97.7k
                    ((int32_t *)out)[(size_t)i * 2] = p[i];
942
97.7k
                    ((int32_t *)out)[(size_t)i * 2 + 1] = p[i];
943
97.7k
                }
944
64
            }
945
562
        } else if (st_type == T_F32) {
946
515
            const float *f = (const float *)src;
947
637k
            for (i = 0; i < frames; i++)
948
2.93M
                for (c = 0; c < n; c++)
949
2.29M
                    put_sample(fmt, out, (size_t)i * n + c, f[(size_t)i * n + perm[c]]);
950
515
        } else if (st_type == T_I16) {
951
32
            const int16_t *p = (const int16_t *)src;
952
38.3k
            for (i = 0; i < frames; i++)
953
218k
                for (c = 0; c < n; c++)
954
180k
                    ((int16_t *)out)[(size_t)i * n + c] = p[(size_t)i * n + perm[c]];
955
32
        } else {
956
15
            const int32_t *p = (const int32_t *)src;
957
19.5k
            for (i = 0; i < frames; i++)
958
106k
                for (c = 0; c < n; c++)
959
86.6k
                    ((int32_t *)out)[(size_t)i * n + c] = p[(size_t)i * n + perm[c]];
960
15
        }
961
1.01k
    }
962
1.39k
    if (out == src && dest) {
963
32
        if (dest_size < need) {
964
11
            fi->error = ERR_OUTPUT_SMALL;
965
11
            return NULL;
966
11
        }
967
21
        memcpy(dest, src, need);
968
21
        out = dest;
969
21
    }
970
971
1.38k
    fi->channels = (unsigned char)out_ch;
972
1.38k
    fi->samples = (unsigned long)frames * out_ch;
973
1.38k
    fi->samplerate = rate;
974
1.38k
    fi->object_type = info.object_type == FAAD_OBJ_LC ? LC : HE_AAC;
975
1.38k
    fi->sbr = downsampled ? SBR_DOWNSAMPLED :
976
1.38k
              upsampled ? NO_SBR_UPSAMPLED : (flags & FAAD_FRAME_SBR) ? SBR_UPSAMPLED : NO_SBR;
977
1.38k
    fi->ps = (flags & FAAD_FRAME_PS) ? 1 : 0;
978
1.38k
    if (downmix || n == 1) {
979
453
        fi->num_front_channels = 2;
980
453
        fi->channel_position[0] = FRONT_CHANNEL_LEFT;
981
453
        fi->channel_position[1] = FRONT_CHANNEL_RIGHT;
982
930
    } else {
983
4.15k
        for (c = 0; c < n; c++) {
984
3.22k
            fi->channel_position[c] = pos[c];
985
3.22k
            switch (pos[c]) {
986
145
            case FRONT_CHANNEL_CENTER:
987
755
            case FRONT_CHANNEL_LEFT:
988
1.36k
            case FRONT_CHANNEL_RIGHT: fi->num_front_channels++; break;
989
76
            case SIDE_CHANNEL_LEFT:
990
152
            case SIDE_CHANNEL_RIGHT: fi->num_side_channels++; break;
991
110
            case BACK_CHANNEL_LEFT:
992
220
            case BACK_CHANNEL_RIGHT:
993
252
            case BACK_CHANNEL_CENTER: fi->num_back_channels++; break;
994
95
            case LFE_CHANNEL: fi->num_lfe_channels++; break;
995
1.35k
            default: break;
996
3.22k
            }
997
3.22k
        }
998
930
    }
999
    /* FAAD2 decodes the first frame but hands back no samples for it. */
1000
1.38k
    if (s->frame <= 1)
1001
1.05k
        fi->samples = 0;
1002
1.38k
    return out;
1003
1.38k
}
1004
1005
void *NeAACDecDecode(NeAACDecHandle h, NeAACDecFrameInfo *hInfo, unsigned char *buffer,
1006
                     unsigned long buffer_size)
1007
9.08k
{
1008
9.08k
    return shim_decode(h, hInfo, buffer, buffer_size, NULL, 0);
1009
9.08k
}
1010
1011
void *NeAACDecDecode2(NeAACDecHandle h, NeAACDecFrameInfo *hInfo, unsigned char *buffer,
1012
                      unsigned long buffer_size, void **sample_buffer,
1013
                      unsigned long sample_buffer_size)
1014
1.11k
{
1015
1.11k
    if (!sample_buffer || !*sample_buffer || sample_buffer_size == 0) {
1016
47
        if (hInfo) {
1017
47
            memset(hInfo, 0, sizeof(*hInfo));
1018
47
            hInfo->error = ERR_OUTPUT_SMALL;
1019
47
        }
1020
47
        return NULL;
1021
47
    }
1022
1.06k
    return shim_decode(h, hInfo, buffer, buffer_size, *sample_buffer, sample_buffer_size);
1023
1.11k
}