Coverage Report

Created: 2026-08-14 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/vlc/modules/packetizer/mpeg4audio.c
Line
Count
Source
1
/*****************************************************************************
2
 * mpeg4audio.c: parse and packetize an MPEG 4 audio stream
3
 *****************************************************************************
4
 * Copyright (C) 2001, 2002, 2006 VLC authors and VideoLAN
5
 *
6
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *          Gildas Bazin <gbazin@netcourrier.com>
8
 *
9
 * This program is free software; you can redistribute it and/or modify it
10
 * under the terms of the GNU Lesser General Public License as published by
11
 * the Free Software Foundation; either version 2.1 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Lesser General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU Lesser General Public License
20
 * along with this program; if not, write to the Free Software Foundation,
21
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22
 *****************************************************************************/
23
24
/*****************************************************************************
25
 * Preamble
26
 *****************************************************************************/
27
28
#ifdef HAVE_CONFIG_H
29
# include "config.h"
30
#endif
31
32
#include <vlc_common.h>
33
#include <vlc_plugin.h>
34
#include <vlc_codec.h>
35
#include <vlc_block.h>
36
#include <vlc_bits.h>
37
38
#include <vlc_block_helper.h>
39
#include "packetizer_helper.h"
40
#include "mpeg4audio.h"
41
42
#include <assert.h>
43
44
/* AAC Config in ES:
45
 *
46
 * AudioObjectType          5 bits
47
 * samplingFrequencyIndex   4 bits
48
 * if (samplingFrequencyIndex == 0xF)
49
 *  samplingFrequency   24 bits
50
 * channelConfiguration     4 bits
51
 * GA_SpecificConfig
52
 *  FrameLengthFlag         1 bit 1024 or 960
53
 *  DependsOnCoreCoder      1 bit (always 0)
54
 *  ExtensionFlag           1 bit (always 0)
55
 */
56
57
/*****************************************************************************
58
 * decoder_sys_t : decoder descriptor
59
 *****************************************************************************/
60
61
typedef struct
62
{
63
    /*
64
     * Input properties
65
     */
66
    enum vlc_packetizer_state i_state;
67
    int i_type;
68
69
    block_bytestream_t bytestream;
70
71
    /*
72
     * Common properties
73
     */
74
    date_t  end_date;
75
    vlc_tick_t i_pts;
76
    bool b_discontuinity;
77
78
    int i_frame_size;
79
    unsigned int i_channels;
80
    unsigned int i_rate, i_frame_length, i_header_size;
81
    int i_aac_profile;
82
83
    int i_input_rate;
84
85
    /* LOAS */
86
    bool b_latm_cfg;
87
    MPEG4_streammux_config_t latm;
88
89
    int i_warnings;
90
} decoder_sys_t;
91
92
enum
93
{
94
    WARN_CRC_UNSUPPORTED = 1
95
};
96
97
5.12k
#define WARN_ONCE(warn, msg) do{\
98
5.12k
        decoder_sys_t *p_sys = p_dec->p_sys;\
99
5.12k
        if( (p_sys->i_warnings & warn) == 0 )\
100
5.12k
        {\
101
310
            p_sys->i_warnings |= warn;\
102
310
            msg_Warn( p_dec, msg );\
103
310
        }\
104
5.12k
    } while(0)
105
106
enum {
107
    TYPE_UNKNOWN, /* AAC samples with[out] headers */
108
    TYPE_UNKNOWN_NONRAW, /* [un]packetized ADTS or LOAS */
109
    TYPE_RAW,    /* RAW AAC frames */
110
    TYPE_ADTS,
111
    TYPE_LOAS
112
};
113
114
static int ChannelConfigurationToVLC(uint8_t i_channel)
115
22.9k
{
116
22.9k
    if (i_channel == 7)
117
203
        return 8; // 7.1
118
22.7k
    if (i_channel >= 8)
119
3.48k
        return -1;
120
19.2k
    return i_channel;
121
22.7k
}
122
123
static int AOTtoAACProfile(uint8_t i_object_type)
124
7.40k
{
125
7.40k
    switch(i_object_type)
126
7.40k
    {
127
14
        case MPEG4_AOT_AAC_MAIN:
128
5.66k
        case MPEG4_AOT_AAC_LC:
129
5.67k
        case MPEG4_AOT_AAC_SSR:
130
5.80k
        case MPEG4_AOT_AAC_LTP:
131
5.80k
        case MPEG4_AOT_AAC_SBR:
132
5.82k
        case MPEG4_AOT_AAC_SC:
133
6.03k
        case MPEG4_AOT_ER_AAC_LD:
134
6.03k
        case MPEG4_AOT_AAC_PS:
135
6.05k
        case MPEG4_AOT_ER_AAC_ELD:
136
6.05k
            {
137
6.05k
            static_assert(MPEG4_AOT_AAC_MAIN == AAC_PROFILE_MAIN + 1,
138
6.05k
                          "invalid profile to object mapping");
139
6.05k
            return i_object_type - 1;
140
6.03k
            }
141
1.34k
        default:
142
1.34k
            return -1;
143
7.40k
    }
144
7.40k
}
145
146
18.2k
#define ADTS_HEADER_SIZE 9
147
29.2k
#define LOAS_HEADER_SIZE 3
148
149
/****************************************************************************
150
 * Local prototypes
151
 ****************************************************************************/
152
static int  OpenPacketizer(vlc_object_t *);
153
static void ClosePacketizer(vlc_object_t *);
154
155
static block_t *Packetize    (decoder_t *, block_t **);
156
static void     Flush( decoder_t * );
157
158
/*****************************************************************************
159
 * Module descriptor
160
 *****************************************************************************/
161
172
vlc_module_begin ()
162
86
    set_subcategory(SUBCAT_SOUT_PACKETIZER)
163
86
    set_description(N_("MPEG4 audio packetizer"))
164
86
    set_capability("audio packetizer", 50)
165
172
    set_callbacks(OpenPacketizer, ClosePacketizer)
166
86
vlc_module_end ()
167
168
/*****************************************************************************
169
 * OpenPacketizer: probe the packetizer and return score
170
 *****************************************************************************/
171
static int OpenPacketizer(vlc_object_t *p_this)
172
192k
{
173
192k
    decoder_t *p_dec = (decoder_t*)p_this;
174
192k
    decoder_sys_t *p_sys;
175
176
192k
    if (p_dec->fmt_in->i_codec != VLC_CODEC_MP4A)
177
102k
        return VLC_EGENERIC;
178
179
    /* Allocate the memory needed to store the decoder's structure */
180
90.1k
    if ((p_dec->p_sys = p_sys = (decoder_sys_t *)malloc(sizeof(decoder_sys_t))) == NULL)
181
0
        return VLC_ENOMEM;
182
183
    /* Misc init */
184
90.1k
    p_sys->i_state = STATE_NOSYNC;
185
90.1k
    p_sys->b_discontuinity = false;
186
90.1k
    block_BytestreamInit(&p_sys->bytestream);
187
90.1k
    p_sys->i_aac_profile = -1;
188
90.1k
    p_sys->b_latm_cfg = false;
189
90.1k
    p_sys->i_warnings = 0;
190
90.1k
    p_sys->i_channels = 0;
191
90.1k
    p_sys->i_rate = 0;
192
90.1k
    p_sys->i_frame_length = 0;
193
194
    /* Set output properties */
195
90.1k
    p_dec->fmt_out.i_codec = VLC_CODEC_MP4A;
196
197
90.1k
    msg_Dbg(p_dec, "running MPEG4 audio packetizer");
198
199
    /*
200
     * We need to handle 3 cases.
201
     * Case 1 : RAW AAC samples without sync header
202
     *          The demuxer shouldn't need packetizer, see next case.
203
     * Case 2 : AAC samples with ADTS or LOAS/LATM header
204
     *          Some mux (avi) can't distinguish the both
205
     *          cases above, and then forwards to packetizer
206
     *          which should check for header and rewire to case below
207
     * Case 3 : Non packetized ADTS or LOAS/LATM
208
     *          The demuxer needs to set original_codec for hardwiring
209
     */
210
211
90.1k
    switch (p_dec->fmt_in->i_original_fourcc)
212
90.1k
    {
213
6.32k
        case VLC_FOURCC('L','A','T','M'):
214
6.32k
            p_sys->i_type = TYPE_LOAS;
215
6.32k
            msg_Dbg(p_dec, "LOAS/LATM Mode");
216
6.32k
            break;
217
218
386
        case VLC_FOURCC('A','D','T','S'):
219
386
            p_sys->i_type = TYPE_ADTS;
220
386
            msg_Dbg(p_dec, "ADTS Mode");
221
386
            break;
222
223
0
        case VLC_FOURCC('H','E','A','D'):
224
0
            p_sys->i_type = TYPE_UNKNOWN_NONRAW;
225
0
            break;
226
227
83.3k
        default:
228
83.3k
            p_sys->i_type = TYPE_UNKNOWN;
229
83.3k
            break;
230
90.1k
    }
231
232
    /* Some mux (avi) do send RAW AAC without extradata,
233
       and LATM can be sent with out-of-band audioconfig,
234
       (avformat sets m4a extradata in both cases)
235
       so we can't rely on extradata to guess multiplexing */
236
90.1k
    p_dec->fmt_out.audio.i_rate = p_dec->fmt_in->audio.i_rate;
237
238
90.1k
    if(p_dec->fmt_in->i_extra)
239
77.5k
    {
240
77.5k
        MPEG4_asc_t asc;
241
77.5k
        bs_t s;
242
77.5k
        bs_init(&s, p_dec->fmt_in->p_extra, p_dec->fmt_in->i_extra);
243
77.5k
        if(MPEG4_read_AudioSpecificConfig(&s, &asc, true) == VLC_SUCCESS)
244
8.10k
        {
245
8.10k
            p_dec->fmt_out.audio.i_rate = asc.i_samplerate;
246
8.10k
            p_dec->fmt_out.audio.i_frame_length = asc.i_frame_length;
247
8.10k
            p_dec->fmt_out.audio.i_channels =
248
8.10k
                    ChannelConfigurationToVLC(asc.i_channel_configuration);
249
8.10k
            if(p_dec->fmt_out.i_profile != -1)
250
0
                p_dec->fmt_out.i_profile = AOTtoAACProfile(asc.i_object_type);
251
252
8.10k
            msg_Dbg(p_dec, "%sAAC%s %dHz %d samples/frame",
253
8.10k
                    (asc.i_sbr) ? "HE-" : "",
254
8.10k
                    (asc.i_ps) ? "v2" : "",
255
8.10k
                    (asc.i_sbr) ? p_dec->fmt_out.audio.i_rate << 1
256
8.10k
                                : p_dec->fmt_out.audio.i_rate,
257
8.10k
                    p_dec->fmt_out.audio.i_frame_length);
258
8.10k
        }
259
260
77.5k
        p_dec->fmt_out.p_extra = malloc(p_dec->fmt_in->i_extra);
261
77.5k
        if (!p_dec->fmt_out.p_extra)
262
0
            return VLC_ENOMEM;
263
77.5k
        p_dec->fmt_out.i_extra = p_dec->fmt_in->i_extra;
264
77.5k
        memcpy(p_dec->fmt_out.p_extra, p_dec->fmt_in->p_extra,
265
77.5k
                p_dec->fmt_in->i_extra);
266
77.5k
    }
267
    /* else() We will try to create a AAC Config from adts/loas */
268
269
90.1k
    date_Init(&p_sys->end_date, p_dec->fmt_out.audio.i_rate ?
270
80.4k
                                p_dec->fmt_out.audio.i_rate : 48000, 1);
271
272
    /* Set callbacks */
273
90.1k
    p_dec->pf_packetize = Packetize;
274
90.1k
    p_dec->pf_flush = Flush;
275
90.1k
    p_dec->pf_get_cc = NULL;
276
277
90.1k
    return VLC_SUCCESS;
278
90.1k
}
279
280
/*****************************************************************************
281
 * ClosePacketizer: clean up the packetizer
282
 *****************************************************************************/
283
static void ClosePacketizer(vlc_object_t *p_this)
284
90.1k
{
285
90.1k
    decoder_t *p_dec = (decoder_t *)p_this;
286
90.1k
    decoder_sys_t *p_sys = p_dec->p_sys;
287
288
90.1k
    block_BytestreamRelease(&p_sys->bytestream);
289
90.1k
    free(p_sys);
290
90.1k
}
291
292
/****************************************************************************
293
 * ForwardRawBlock:
294
 ****************************************************************************
295
 * This function must be fed with complete frames.
296
 ****************************************************************************/
297
static block_t *ForwardRawBlock(decoder_t *p_dec, block_t **pp_block)
298
342k
{
299
342k
    decoder_sys_t *p_sys = p_dec->p_sys;
300
342k
    block_t *p_block;
301
302
342k
    if (!pp_block || !*pp_block)
303
173k
        return NULL;
304
305
168k
    p_block = *pp_block;
306
168k
    *pp_block = NULL; /* Don't reuse this block */
307
308
168k
    vlc_tick_t i_diff = 0;
309
168k
    if (p_block->i_pts != VLC_TICK_INVALID &&
310
156k
        p_block->i_pts != date_Get(&p_sys->end_date))
311
134k
    {
312
134k
        if(date_Get(&p_sys->end_date) != VLC_TICK_INVALID)
313
127k
            i_diff = llabs( date_Get(&p_sys->end_date) - p_block->i_pts );
314
134k
        date_Set(&p_sys->end_date, p_block->i_pts);
315
134k
    }
316
317
168k
    p_block->i_pts = p_block->i_dts = date_Get(&p_sys->end_date);
318
319
    /* Might not be known due to missing extradata,
320
       will be set to block pts above */
321
168k
    if(p_dec->fmt_out.audio.i_frame_length && p_block->i_pts != VLC_TICK_INVALID)
322
53.0k
    {
323
53.0k
        p_block->i_length = date_Increment(&p_sys->end_date,
324
53.0k
            p_dec->fmt_out.audio.i_frame_length) - p_block->i_pts;
325
326
53.0k
        if( i_diff > p_block->i_length )
327
6.53k
            p_sys->b_discontuinity = true;
328
53.0k
    }
329
330
168k
    return p_block;
331
342k
}
332
333
/****************************************************************************
334
 * ADTS helpers
335
 ****************************************************************************/
336
static int ADTSSyncInfo(decoder_t * p_dec, const uint8_t * p_buf,
337
                         unsigned int * pi_channels,
338
                         unsigned int * pi_sample_rate,
339
                         unsigned int * pi_frame_length,
340
                         unsigned int * pi_header_size)
341
15.6k
{
342
15.6k
    int i_profile, i_sample_rate_idx, i_frame_size;
343
15.6k
    bool b_crc;
344
345
    /* Fixed header between frames */
346
    //int i_id = ((p_buf[1] >> 3) & 0x01) ? 2 : 4; /* MPEG-2 or 4 */
347
15.6k
    b_crc = !(p_buf[1] & 0x01);
348
15.6k
    i_profile = p_buf[2] >> 6;
349
15.6k
    i_sample_rate_idx = (p_buf[2] >> 2) & 0x0f;
350
15.6k
    *pi_sample_rate = pi_sample_rates[i_sample_rate_idx];
351
    //private_bit = (p_buf[2] >> 1) & 0x01;
352
15.6k
    *pi_channels = ((p_buf[2] & 0x01) << 2) | ((p_buf[3] >> 6) & 0x03);
353
15.6k
    if (*pi_channels == 0) /* workaround broken streams */
354
5.21k
        *pi_channels = 2;
355
    //original_copy = (p_buf[3] >> 5) & 0x01;
356
    //home = (p_buf[3] >> 4) & 0x01;
357
358
    /* Variable header */
359
    //copyright_id_bit = (p_buf[3] >> 3) & 0x01;
360
    //copyright_id_start = (p_buf[3] >> 2) & 0x01;
361
15.6k
    i_frame_size = ((p_buf[3] & 0x03) << 11) | (p_buf[4] << 3) |
362
15.6k
                   ((p_buf[5] >> 5) /*& 0x7*/);
363
    //uint16_t buffer_fullness = ((p_buf[5] & 0x1f) << 6) | (p_buf[6] >> 2);
364
15.6k
    unsigned short i_raw_blocks_in_frame = p_buf[6] & 0x03;
365
366
15.6k
    if (!*pi_sample_rate || !i_frame_size) {
367
1.78k
        msg_Warn(p_dec, "Invalid ADTS header");
368
1.78k
        return 0;
369
1.78k
    }
370
371
13.8k
    *pi_frame_length = 1024;
372
373
13.8k
    if (i_raw_blocks_in_frame == 0) {
374
8.92k
        if (b_crc) {
375
5.12k
            WARN_ONCE(WARN_CRC_UNSUPPORTED, "ADTS CRC not supported");
376
            //uint16_t crc = (p_buf[7] << 8) | p_buf[8];
377
5.12k
        }
378
8.92k
    } else {
379
4.89k
        msg_Err(p_dec, "Multiple blocks per frame in ADTS not supported");
380
4.89k
        return 0;
381
#if 0
382
        int i;
383
        const uint8_t *p_pos = p_buf + 7;
384
        uint16_t crc_block;
385
        uint16_t i_block_pos[3];
386
        if (b_crc) {
387
            for (i = 0 ; i < i_raw_blocks_in_frame ; i++) {
388
                /* the 1st block's position is known ... */
389
                i_block_pos[i] = (*p_pos << 8) | *(p_pos+1);
390
                p_pos += 2;
391
            }
392
            crc_block = (*p_pos << 8) | *(p_pos+1);
393
            p_pos += 2;
394
        }
395
        for (i = 0 ; i <= i_raw_blocks_in_frame ; i++) {
396
            //read 1 block
397
            if (b_crc) {
398
                WARN_ONCE(WARN_CRC_UNSUPPORTED, "ADTS CRC not supported");
399
                //uint16_t crc = (*p_pos << 8) | *(p_pos+1);
400
                //p_pos += 2;
401
            }
402
        }
403
#endif
404
4.89k
    }
405
406
407
    /* Build the decoder specific info header */
408
8.92k
    if (!p_dec->fmt_out.i_extra) {
409
576
        p_dec->fmt_out.p_extra = malloc(2);
410
576
        if (!p_dec->fmt_out.p_extra)
411
0
            return 0;
412
576
        p_dec->fmt_out.i_extra = 2;
413
576
        ((uint8_t *)p_dec->fmt_out.p_extra)[0] =
414
576
            (i_profile + 1) << 3 | (i_sample_rate_idx >> 1);
415
576
        ((uint8_t *)p_dec->fmt_out.p_extra)[1] =
416
576
            ((i_sample_rate_idx & 0x01) << 7) | (*pi_channels <<3);
417
576
    }
418
419
    /* ADTS header length */
420
8.92k
    *pi_header_size = b_crc ? 9 : 7;
421
422
8.92k
    return i_frame_size - *pi_header_size;
423
8.92k
}
424
425
/****************************************************************************
426
 * LOAS helpers
427
 ****************************************************************************/
428
static int LOASSyncInfo(uint8_t p_header[LOAS_HEADER_SIZE], unsigned int *pi_header_size)
429
29.1k
{
430
29.1k
    *pi_header_size = 3;
431
29.1k
    return ((p_header[1] & 0x1f) << 8) + p_header[2];
432
29.1k
}
433
434
static int LOASParse(decoder_t *p_dec, uint8_t *p_buffer, int i_buffer)
435
14.1k
{
436
14.1k
    decoder_sys_t *p_sys = p_dec->p_sys;
437
14.1k
    bs_t s;
438
14.1k
    int i_accumulated = 0;
439
440
14.1k
    bs_init(&s, p_buffer, i_buffer);
441
442
    /* Read the stream mux configuration if present */
443
14.1k
    if (!bs_read1(&s) && !MPEG4_parse_StreamMuxConfig(&s, &p_sys->latm) &&
444
9.66k
            p_sys->latm.i_streams > 0) {
445
9.66k
        const MPEG4_audio_stream_t *st = &p_sys->latm.stream[0];
446
447
9.66k
        if(st->cfg.i_samplerate == 0 || st->cfg.i_frame_length == 0 ||
448
7.46k
           ChannelConfigurationToVLC(st->cfg.i_channel_configuration) == 0)
449
2.25k
            return 0;
450
451
7.40k
        p_sys->i_channels = ChannelConfigurationToVLC(st->cfg.i_channel_configuration);
452
7.40k
        p_sys->i_rate = st->cfg.i_samplerate;
453
7.40k
        p_sys->i_frame_length = st->cfg.i_frame_length;
454
7.40k
        p_sys->i_aac_profile = AOTtoAACProfile(st->cfg.i_object_type);
455
456
7.40k
        if (p_sys->i_channels && p_sys->i_rate && p_sys->i_frame_length > 0)
457
7.40k
        {
458
7.40k
            if(p_dec->fmt_out.i_extra != st->i_extra ||
459
6.12k
               (p_dec->fmt_out.i_extra > 0 &&
460
6.11k
                memcmp(p_dec->fmt_out.p_extra, st->extra, st->i_extra)) )
461
1.51k
            {
462
1.51k
                if(p_dec->fmt_out.i_extra)
463
341
                    free(p_dec->fmt_out.p_extra);
464
1.51k
                p_dec->fmt_out.p_extra = st->i_extra ? malloc(st->i_extra) : NULL;
465
1.51k
                if(p_dec->fmt_out.p_extra)
466
1.51k
                {
467
1.51k
                    p_dec->fmt_out.i_extra = st->i_extra;
468
1.51k
                    memcpy(p_dec->fmt_out.p_extra, st->extra, st->i_extra);
469
1.51k
                    p_sys->b_latm_cfg = true;
470
1.51k
                }
471
1
                else
472
1
                {
473
1
                    p_dec->fmt_out.i_extra = 0;
474
1
                    p_sys->b_latm_cfg = false;
475
1
                }
476
1.51k
            }
477
7.40k
        }
478
7.40k
    }
479
480
    /* Wait for the configuration */
481
11.8k
    if (!p_sys->b_latm_cfg)
482
3.75k
    {
483
        /* WAVE_FORMAT_MPEG_LOAS, configuration provided as AAC header :/ */
484
3.75k
        if( p_dec->fmt_in->i_extra > 0 &&
485
1
            p_sys->i_channels && p_sys->i_rate && p_sys->i_frame_length )
486
0
        {
487
0
            p_sys->b_latm_cfg = true;
488
0
        }
489
3.75k
        else return 0;
490
3.75k
    }
491
492
8.10k
    if(bs_eof(&s) && i_buffer)
493
652
        goto truncated;
494
495
    /* FIXME do we need to split the subframe into independent packet ? */
496
7.45k
    if (p_sys->latm.numSubFrames != 0)
497
7.45k
        msg_Err(p_dec, "latm sub frames not yet supported, please send a sample");
498
499
116k
    for (uint8_t i_sub = 0; i_sub <= p_sys->latm.numSubFrames; i_sub++) {
500
110k
        unsigned pi_payload[MPEG4_STREAMMUX_MAX_PROGRAM][MPEG4_STREAMMUX_MAX_LAYER];
501
110k
        if (p_sys->latm.allStreamsSameTimeFraming) {
502
            /* Payload length */
503
726k
            for (uint8_t i_program = 0; i_program <= p_sys->latm.numProgram; i_program++) {
504
3.19M
                for (uint8_t i_layer = 0; i_layer <= p_sys->latm.p_numLayer[i_program]; i_layer++) {
505
2.56M
                    const MPEG4_audio_stream_t *st = &p_sys->latm.stream[p_sys->latm.pi_stream[i_program][i_layer]];
506
2.56M
                    if (st->i_frame_length_type == 0) {
507
774k
                        unsigned i_payload = 0;
508
898k
                        for (;;) {
509
898k
                            uint8_t i_tmp = bs_read(&s, 8);
510
898k
                            i_payload += i_tmp;
511
898k
                            if (i_tmp != 255)
512
774k
                                break;
513
898k
                        }
514
774k
                        pi_payload[i_program][i_layer] = i_payload;
515
1.79M
                    } else if (st->i_frame_length_type == 1) {
516
334k
                        pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
517
1.45M
                    } else if ((st->i_frame_length_type == 3) ||
518
1.20M
                             (st->i_frame_length_type == 5) ||
519
1.06M
                             (st->i_frame_length_type == 7)) {
520
685k
                        bs_skip(&s, 2); // muxSlotLengthCoded
521
685k
                        pi_payload[i_program][i_layer] = 0; /* TODO */
522
772k
                    } else {
523
772k
                        pi_payload[i_program][i_layer] = 0; /* TODO */
524
772k
                    }
525
2.56M
                }
526
627k
            }
527
528
            /* Payload Data */
529
712k
            for (uint8_t i_program = 0; i_program <= p_sys->latm.numProgram; i_program++) {
530
712k
                for (uint8_t i_layer = 0; i_layer <= p_sys->latm.p_numLayer[i_program]; i_layer++) {
531
                    /* XXX we only extract 1 stream */
532
708k
                    if (i_program != 0 || i_layer != 0)
533
609k
                        break;
534
535
99.0k
                    if (pi_payload[i_program][i_layer] <= 0)
536
15.3k
                        continue;
537
538
                    /* FIXME that's slow (and a bit ugly to write in place) */
539
2.12M
                    for (unsigned i = 0; i < pi_payload[i_program][i_layer]; i++) {
540
2.04M
                        if (i_accumulated >= i_buffer)
541
0
                            return 0;
542
2.04M
                        p_buffer[i_accumulated++] = bs_read(&s, 8);
543
2.04M
                        if(bs_error(&s))
544
1.31k
                            goto truncated;
545
2.04M
                    }
546
83.6k
                }
547
614k
            }
548
99.0k
        } else {
549
11.1k
            const int i_chunks = bs_read(&s, 4);
550
#if 0
551
            int pi_program[16];
552
            int pi_layer[16];
553
#endif
554
555
11.1k
            msg_Err(p_dec, "latm without same time frameing not yet supported, please send a sample");
556
557
51.7k
            for (int i_chunk = 0; i_chunk < i_chunks; i_chunk++) {
558
40.5k
                const int streamIndex = bs_read(&s, 4);
559
40.5k
                const MPEG4_audio_stream_t *st = &p_sys->latm.stream[streamIndex];
560
40.5k
                const int i_program = st->i_program;
561
40.5k
                const int i_layer = st->i_layer;
562
563
#if 0
564
                pi_program[i_chunk] = i_program;
565
                pi_layer[i_chunk] = i_layer;
566
#endif
567
568
40.5k
                if (st->i_frame_length_type == 0) {
569
20.3k
                    int i_payload = 0;
570
32.4k
                    for (;;) {
571
32.4k
                        int i_tmp = bs_read(&s, 8);
572
32.4k
                        i_payload += i_tmp;
573
32.4k
                        if (i_tmp != 255)
574
20.3k
                            break;
575
32.4k
                    }
576
20.3k
                    pi_payload[i_program][i_layer] = i_payload;
577
20.3k
                    bs_skip(&s, 1); // auEndFlag
578
20.3k
                } else if (st->i_frame_length_type == 1) {
579
1.48k
                    pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
580
18.7k
                } else if ((st->i_frame_length_type == 3) ||
581
14.9k
                         (st->i_frame_length_type == 5) ||
582
13.7k
                         (st->i_frame_length_type == 7)) {
583
9.44k
                    bs_read(&s, 2); // muxSlotLengthCoded
584
9.44k
                }
585
40.5k
            }
586
#if 0
587
            for (int i_chunk = 0; i_chunk < i_chunks; i_chunk++) {
588
                //const int i_program = pi_program[i_chunk];
589
                //const int i_layer = pi_layer[i_chunk];
590
591
                /* TODO ? Payload */
592
            }
593
#endif
594
11.1k
        }
595
110k
    }
596
597
598
6.13k
    bs_skip(&s, p_sys->latm.otherDataLenBits);
599
6.13k
    bs_align(&s);
600
601
6.13k
    return i_accumulated;
602
603
1.96k
truncated:
604
1.96k
    msg_Warn(p_dec,"Truncated LOAS packet. Wrong format ?");
605
1.96k
    return 0;
606
7.45k
}
607
608
/*****************************************************************************
609
 *
610
 *****************************************************************************/
611
static void SetupOutput(decoder_t *p_dec, block_t *p_block)
612
6.00k
{
613
6.00k
    decoder_sys_t *p_sys = p_dec->p_sys;
614
615
6.00k
    if (p_dec->fmt_out.audio.i_rate != p_sys->i_rate && p_sys->i_rate > 0)
616
1.06k
    {
617
1.06k
        msg_Info(p_dec, "AAC channels: %d samplerate: %d",
618
1.06k
                  p_sys->i_channels, p_sys->i_rate);
619
1.06k
        date_Change(&p_sys->end_date, p_sys->i_rate, 1);
620
1.06k
    }
621
622
6.00k
    p_dec->fmt_out.audio.i_rate     = p_sys->i_rate;
623
6.00k
    p_dec->fmt_out.audio.i_channels = p_sys->i_channels;
624
6.00k
    p_dec->fmt_out.audio.i_bytes_per_frame = p_sys->i_frame_size;
625
6.00k
    p_dec->fmt_out.audio.i_frame_length = p_sys->i_frame_length;
626
    /* Will reload extradata on change */
627
6.00k
    p_dec->fmt_out.i_profile = p_sys->i_aac_profile;
628
629
#if 0
630
    p_dec->fmt_out.audio.i_physical_channels = p_sys->i_channels_conf;
631
#endif
632
633
6.00k
    p_block->i_pts = p_block->i_dts = date_Get(&p_sys->end_date);
634
635
6.00k
    p_block->i_length =
636
6.00k
        date_Increment(&p_sys->end_date, p_sys->i_frame_length) - p_block->i_pts;
637
6.00k
}
638
639
/*****************************************************************************
640
 * FlushStreamBlock:
641
 *****************************************************************************/
642
static void Flush(decoder_t *p_dec)
643
9.48k
{
644
9.48k
    decoder_sys_t *p_sys = p_dec->p_sys;
645
646
9.48k
    p_sys->i_state = STATE_NOSYNC;
647
9.48k
    block_BytestreamEmpty(&p_sys->bytestream);
648
9.48k
    date_Set(&p_sys->end_date, VLC_TICK_INVALID);
649
9.48k
    p_sys->b_discontuinity = true;
650
9.48k
}
651
652
static inline bool HasADTSHeader( const uint8_t *p_header )
653
4.84M
{
654
4.84M
    return p_header[0] == 0xff && (p_header[1] & 0xf6) == 0xf0;
655
4.84M
}
656
657
static inline bool HasLoasHeader( const uint8_t *p_header )
658
21.0M
{
659
21.0M
    return p_header[0] == 0x56 && (p_header[1] & 0xe0) == 0xe0;
660
21.0M
}
661
662
/****************************************************************************
663
 * PacketizeStreamBlock: ADTS/LOAS packetizer
664
 ****************************************************************************/
665
static block_t *PacketizeStreamBlock(decoder_t *p_dec, block_t **pp_block)
666
108k
{
667
108k
    decoder_sys_t *p_sys = p_dec->p_sys;
668
108k
    uint8_t p_header[ADTS_HEADER_SIZE + LOAS_HEADER_SIZE];
669
108k
    block_t *p_out_buffer;
670
108k
    uint8_t *p_buf;
671
672
108k
    block_t *p_block = pp_block ? *pp_block : NULL;
673
674
108k
    if(p_block)
675
89.7k
    {
676
89.7k
        block_BytestreamPush(&p_sys->bytestream, p_block);
677
89.7k
        *pp_block = NULL;
678
89.7k
    }
679
680
206k
    for (;;) switch(p_sys->i_state) {
681
81.7k
    case STATE_NOSYNC:
682
25.9M
        while (block_PeekBytes(&p_sys->bytestream, p_header, 2) == VLC_SUCCESS) {
683
            /* Look for sync word - should be 0xfff(adts) or 0x2b7(loas) */
684
25.8M
            if ((p_sys->i_type == TYPE_ADTS || p_sys->i_type == TYPE_UNKNOWN_NONRAW) &&
685
4.83M
                HasADTSHeader( p_header ) )
686
15.6k
            {
687
15.6k
                if (p_sys->i_type != TYPE_ADTS)
688
15.6k
                    msg_Dbg(p_dec, "detected ADTS format");
689
690
15.6k
                p_sys->i_state = STATE_SYNC;
691
15.6k
                p_sys->i_type = TYPE_ADTS;
692
15.6k
                break;
693
15.6k
            }
694
25.8M
            else if ((p_sys->i_type == TYPE_LOAS || p_sys->i_type == TYPE_UNKNOWN_NONRAW) &&
695
21.0M
                      HasLoasHeader( p_header ) )
696
29.1k
            {
697
29.1k
                if (p_sys->i_type != TYPE_LOAS)
698
29.1k
                    msg_Dbg(p_dec, "detected LOAS format");
699
700
29.1k
                p_sys->i_state = STATE_SYNC;
701
29.1k
                p_sys->i_type = TYPE_LOAS;
702
29.1k
                break;
703
29.1k
            }
704
25.8M
            (void) block_SkipByte(&p_sys->bytestream);
705
25.8M
        }
706
81.7k
        if (p_sys->i_state != STATE_SYNC) {
707
36.8k
            block_BytestreamFlush(&p_sys->bytestream);
708
709
            /* Need more data */
710
36.8k
            return NULL;
711
36.8k
        }
712
        /* fallthrough */
713
714
44.8k
    case STATE_SYNC:
715
        /* New frame, set the Presentation Time Stamp */
716
44.8k
        p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
717
44.8k
        if (p_sys->i_pts != VLC_TICK_INVALID &&
718
32.1k
            p_sys->i_pts != date_Get(&p_sys->end_date))
719
6.71k
            date_Set(&p_sys->end_date, p_sys->i_pts);
720
44.8k
        p_sys->i_state = STATE_HEADER;
721
44.8k
        break;
722
723
47.4k
    case STATE_HEADER:
724
47.4k
        if (p_sys->i_type == TYPE_ADTS) {
725
            /* Get ADTS frame header (ADTS_HEADER_SIZE bytes) */
726
18.2k
            if (block_PeekBytes(&p_sys->bytestream, p_header,
727
18.2k
                        ADTS_HEADER_SIZE) != VLC_SUCCESS)
728
2.65k
                return NULL; /* Need more data */
729
730
            /* Check if frame is valid and get frame info */
731
15.6k
            p_sys->i_frame_size = ADTSSyncInfo(p_dec, p_header,
732
15.6k
                    &p_sys->i_channels,
733
15.6k
                    &p_sys->i_rate,
734
15.6k
                    &p_sys->i_frame_length,
735
15.6k
                    &p_sys->i_header_size);
736
29.2k
        } else {
737
29.2k
            assert(p_sys->i_type == TYPE_LOAS);
738
            /* Get LOAS frame header (LOAS_HEADER_SIZE bytes) */
739
29.2k
            if (block_PeekBytes(&p_sys->bytestream, p_header,
740
29.2k
                        LOAS_HEADER_SIZE) != VLC_SUCCESS)
741
52
                return NULL; /* Need more data */
742
743
            /* Check if frame is valid and get frame info */
744
29.1k
            p_sys->i_frame_size = LOASSyncInfo(p_header, &p_sys->i_header_size);
745
29.1k
        }
746
747
44.7k
        if (p_sys->i_frame_size <= 0) {
748
6.69k
            msg_Dbg(p_dec, "emulated sync word");
749
6.69k
            block_SkipByte(&p_sys->bytestream);
750
6.69k
            p_sys->i_state = STATE_NOSYNC;
751
6.69k
            break;
752
6.69k
        }
753
754
38.1k
        p_sys->i_state = STATE_NEXT_SYNC;
755
        /* fallthrough */
756
757
98.1k
    case STATE_NEXT_SYNC:
758
98.1k
        if (p_sys->bytestream.p_block == NULL) {
759
0
            p_sys->i_state = STATE_NOSYNC;
760
0
            block_BytestreamFlush(&p_sys->bytestream);
761
0
            return NULL;
762
0
        }
763
764
        /* Check if next expected frame contains the sync word */
765
98.1k
        if (block_PeekOffsetBytes(&p_sys->bytestream, p_sys->i_frame_size
766
98.1k
                    + p_sys->i_header_size, p_header, 2) != VLC_SUCCESS)
767
62.5k
        {
768
62.5k
            if(p_block == NULL) /* drain */
769
2.50k
            {
770
2.50k
                p_sys->i_state = STATE_SEND_DATA;
771
2.50k
                break;
772
2.50k
            }
773
60.0k
            return NULL; /* Need more data */
774
62.5k
        }
775
776
98.1k
        assert((p_sys->i_type == TYPE_ADTS) || (p_sys->i_type == TYPE_LOAS));
777
35.6k
        if ( (p_sys->i_type == TYPE_ADTS && !HasADTSHeader( p_header )) ||
778
27.7k
             (p_sys->i_type == TYPE_LOAS && !HasLoasHeader( p_header )) )
779
35.0k
        {
780
            /* Check spacial padding case. Failing if need more bytes is ok since
781
               that should have been sent as a whole block */
782
35.0k
            if( block_PeekOffsetBytes(&p_sys->bytestream,
783
35.0k
                                      p_sys->i_frame_size + p_sys->i_header_size,
784
35.0k
                                      p_header, 3) == VLC_SUCCESS &&
785
34.4k
                p_header[0] == 0x00 &&
786
16.2k
               ((p_sys->i_type == TYPE_ADTS && HasADTSHeader( &p_header[1] )) ||
787
15.8k
                (p_sys->i_type == TYPE_LOAS && !HasLoasHeader( &p_header[1] ))))
788
14.3k
            {
789
14.3k
                p_sys->i_state = STATE_SEND_DATA;
790
14.3k
            }
791
20.6k
            else
792
20.6k
            {
793
20.6k
                msg_Dbg(p_dec, "emulated sync word (no sync on following frame)"
794
20.6k
                               " 0x%"PRIx8" 0x%"PRIx8, p_header[0], p_header[1] );
795
20.6k
                p_sys->i_state = STATE_NOSYNC;
796
20.6k
                block_SkipByte(&p_sys->bytestream);
797
20.6k
            }
798
35.0k
            break;
799
35.0k
        }
800
801
574
        p_sys->i_state = STATE_SEND_DATA;
802
574
        break;
803
804
0
    case STATE_GET_DATA:
805
        /* Make sure we have enough data.
806
         * (Not useful if we went through NEXT_SYNC) */
807
0
        if (block_WaitBytes(&p_sys->bytestream, p_sys->i_frame_size +
808
0
                    p_sys->i_header_size) != VLC_SUCCESS)
809
0
            return NULL; /* Need more data */
810
0
        p_sys->i_state = STATE_SEND_DATA;
811
        /* fallthrough */
812
813
17.4k
    case STATE_SEND_DATA:
814
        /* When we reach this point we already know we have enough
815
         * data available. */
816
817
17.4k
        if (unlikely( block_BytestreamRemaining(&p_sys->bytestream) <
818
17.4k
                      p_sys->i_header_size + p_sys->i_frame_size ))
819
2.38k
            return NULL; // need more data
820
821
15.0k
        p_out_buffer = block_Alloc(p_sys->i_frame_size);
822
15.0k
        if (!p_out_buffer) {
823
0
            return NULL;
824
0
        }
825
15.0k
        p_buf = p_out_buffer->p_buffer;
826
827
        /* Skip the ADTS/LOAS header */
828
15.0k
        (void) block_SkipBytes(&p_sys->bytestream, p_sys->i_header_size);
829
830
        /* Copy the whole frame into the buffer */
831
15.0k
        (void) block_GetBytes(&p_sys->bytestream, p_buf, p_sys->i_frame_size);
832
15.0k
        if (p_sys->i_type != TYPE_ADTS) { /* parse/extract the whole frame */
833
14.1k
            assert(p_sys->i_type == TYPE_LOAS);
834
14.1k
            p_out_buffer->i_buffer = LOASParse(p_dec, p_buf, p_sys->i_frame_size);
835
14.1k
            if (p_out_buffer->i_buffer <= 0)
836
9.03k
            {
837
9.03k
                if (!p_sys->b_latm_cfg)
838
9.03k
                    msg_Warn(p_dec, "waiting for header");
839
840
9.03k
                block_Release(p_out_buffer);
841
9.03k
                p_out_buffer = NULL;
842
9.03k
                p_sys->i_state = STATE_NOSYNC;
843
9.03k
                break;
844
9.03k
            }
845
14.1k
        }
846
6.00k
        SetupOutput(p_dec, p_out_buffer);
847
        /* Make sure we don't reuse the same pts twice */
848
6.00k
        if (p_sys->i_pts == p_sys->bytestream.p_block->i_pts)
849
5.81k
            p_sys->i_pts = p_sys->bytestream.p_block->i_pts = VLC_TICK_INVALID;
850
851
        /* So p_block doesn't get re-added several times */
852
6.00k
        if( pp_block )
853
5.90k
            *pp_block = block_BytestreamPop(&p_sys->bytestream);
854
855
6.00k
        p_sys->i_state = STATE_NOSYNC;
856
857
6.00k
        return p_out_buffer;
858
859
0
    case STATE_CUSTOM_FIRST:
860
0
        break; // do nothing
861
206k
    }
862
863
0
    return NULL;
864
108k
}
865
866
/****************************************************************************
867
 * Packetize: just forwards raw blocks, or packetizes LOAS/ADTS
868
 *            and strips headers
869
 ****************************************************************************/
870
static block_t *Packetize(decoder_t *p_dec, block_t **pp_block)
871
457k
{
872
457k
    decoder_sys_t *p_sys = p_dec->p_sys;
873
457k
    block_t *p_block = pp_block ? *pp_block : NULL;
874
875
457k
    if(p_block)
876
272k
    {
877
272k
        if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED))
878
9.55k
        {
879
9.55k
            if(p_sys->i_type == TYPE_ADTS || p_sys->i_type == TYPE_LOAS)
880
6.60k
            {
881
                /* First always drain complete blocks before discontinuity */
882
6.60k
                block_t *p_drain = PacketizeStreamBlock(p_dec, NULL);
883
6.60k
                if(p_drain)
884
65
                    return p_drain;
885
6.60k
            }
886
887
9.48k
            Flush(p_dec);
888
889
9.48k
            if (p_block->i_flags & BLOCK_FLAG_CORRUPTED)
890
8.55k
            {
891
8.55k
                block_Release(p_block);
892
8.55k
                return NULL;
893
8.55k
            }
894
9.48k
        }
895
896
263k
        if ( p_block->i_pts == VLC_TICK_INVALID &&
897
60.3k
             date_Get(&p_sys->end_date) == VLC_TICK_INVALID )
898
5.07k
        {
899
            /* We've just started the stream, wait for the first PTS. */
900
5.07k
            block_Release(p_block);
901
5.07k
            return NULL;
902
5.07k
        }
903
263k
    }
904
905
444k
    if(p_block && p_sys->i_type == TYPE_UNKNOWN)
906
5.84k
    {
907
5.84k
        p_sys->i_type = TYPE_RAW;
908
5.84k
        if(p_block->i_buffer > 1)
909
5.77k
        {
910
5.77k
            if(p_block->p_buffer[0] == 0xff && (p_block->p_buffer[1] & 0xf6) == 0xf0)
911
565
            {
912
565
                p_sys->i_type = TYPE_ADTS;
913
565
            }
914
5.20k
            else if(p_block->p_buffer[0] == 0x56 && (p_block->p_buffer[1] & 0xe0) == 0xe0)
915
475
            {
916
475
                p_sys->i_type = TYPE_LOAS;
917
475
            }
918
5.77k
        }
919
5.84k
    }
920
921
444k
    if(p_sys->i_type == TYPE_RAW)
922
342k
        p_block = ForwardRawBlock(p_dec, pp_block);
923
101k
    else
924
101k
        p_block = PacketizeStreamBlock(p_dec, pp_block);
925
926
444k
    if(p_block && p_sys->b_discontuinity)
927
8.92k
    {
928
8.92k
        p_block->i_flags |= BLOCK_FLAG_DISCONTINUITY;
929
8.92k
        p_sys->b_discontuinity = false;
930
8.92k
    }
931
932
444k
    return p_block;
933
457k
}