Coverage Report

Created: 2026-10-17 07:46

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
16.1k
#define WARN_ONCE(warn, msg) do{\
98
16.1k
        decoder_sys_t *p_sys = p_dec->p_sys;\
99
16.1k
        if( (p_sys->i_warnings & warn) == 0 )\
100
16.1k
        {\
101
889
            p_sys->i_warnings |= warn;\
102
889
            msg_Warn( p_dec, msg );\
103
889
        }\
104
16.1k
    } 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
321k
{
116
321k
    if (i_channel == 7)
117
70.2k
        return 8; // 7.1
118
251k
    if (i_channel >= 8)
119
33.9k
        return -1;
120
217k
    return i_channel;
121
251k
}
122
123
static int AOTtoAACProfile(uint8_t i_object_type)
124
148k
{
125
148k
    switch(i_object_type)
126
148k
    {
127
3.69k
        case MPEG4_AOT_AAC_MAIN:
128
17.2k
        case MPEG4_AOT_AAC_LC:
129
21.0k
        case MPEG4_AOT_AAC_SSR:
130
68.5k
        case MPEG4_AOT_AAC_LTP:
131
68.5k
        case MPEG4_AOT_AAC_SBR:
132
72.8k
        case MPEG4_AOT_AAC_SC:
133
91.3k
        case MPEG4_AOT_ER_AAC_LD:
134
91.3k
        case MPEG4_AOT_AAC_PS:
135
97.7k
        case MPEG4_AOT_ER_AAC_ELD:
136
97.7k
            {
137
97.7k
            static_assert(MPEG4_AOT_AAC_MAIN == AAC_PROFILE_MAIN + 1,
138
97.7k
                          "invalid profile to object mapping");
139
97.7k
            return i_object_type - 1;
140
91.3k
            }
141
51.2k
        default:
142
51.2k
            return -1;
143
148k
    }
144
148k
}
145
146
1.88M
#define ADTS_HEADER_SIZE 9
147
502k
#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
174
vlc_module_begin ()
162
87
    set_subcategory(SUBCAT_SOUT_PACKETIZER)
163
87
    set_description(N_("MPEG4 audio packetizer"))
164
87
    set_capability("audio packetizer", 50)
165
174
    set_callbacks(OpenPacketizer, ClosePacketizer)
166
87
vlc_module_end ()
167
168
/*****************************************************************************
169
 * OpenPacketizer: probe the packetizer and return score
170
 *****************************************************************************/
171
static int OpenPacketizer(vlc_object_t *p_this)
172
3.47M
{
173
3.47M
    decoder_t *p_dec = (decoder_t*)p_this;
174
3.47M
    decoder_sys_t *p_sys;
175
176
3.47M
    if (p_dec->fmt_in->i_codec != VLC_CODEC_MP4A)
177
3.35M
        return VLC_EGENERIC;
178
179
    /* Allocate the memory needed to store the decoder's structure */
180
117k
    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
117k
    p_sys->i_state = STATE_NOSYNC;
185
117k
    p_sys->b_discontuinity = false;
186
117k
    block_BytestreamInit(&p_sys->bytestream);
187
117k
    p_sys->i_aac_profile = -1;
188
117k
    p_sys->b_latm_cfg = false;
189
117k
    p_sys->i_warnings = 0;
190
117k
    p_sys->i_channels = 0;
191
117k
    p_sys->i_rate = 0;
192
117k
    p_sys->i_frame_length = 0;
193
194
    /* Set output properties */
195
117k
    p_dec->fmt_out.i_codec = VLC_CODEC_MP4A;
196
197
117k
    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
117k
    switch (p_dec->fmt_in->i_original_fourcc)
212
117k
    {
213
6.59k
        case VLC_FOURCC('L','A','T','M'):
214
6.59k
            p_sys->i_type = TYPE_LOAS;
215
6.59k
            msg_Dbg(p_dec, "LOAS/LATM Mode");
216
6.59k
            break;
217
218
502
        case VLC_FOURCC('A','D','T','S'):
219
502
            p_sys->i_type = TYPE_ADTS;
220
502
            msg_Dbg(p_dec, "ADTS Mode");
221
502
            break;
222
223
8.79k
        case VLC_FOURCC('H','E','A','D'):
224
8.79k
            p_sys->i_type = TYPE_UNKNOWN_NONRAW;
225
8.79k
            break;
226
227
101k
        default:
228
101k
            p_sys->i_type = TYPE_UNKNOWN;
229
101k
            break;
230
117k
    }
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
117k
    p_dec->fmt_out.audio.i_rate = p_dec->fmt_in->audio.i_rate;
237
238
117k
    if(p_dec->fmt_in->i_extra)
239
92.7k
    {
240
92.7k
        MPEG4_asc_t asc;
241
92.7k
        bs_t s;
242
92.7k
        bs_init(&s, p_dec->fmt_in->p_extra, p_dec->fmt_in->i_extra);
243
92.7k
        if(MPEG4_read_AudioSpecificConfig(&s, &asc, true) == VLC_SUCCESS)
244
15.1k
        {
245
15.1k
            p_dec->fmt_out.audio.i_rate = asc.i_samplerate;
246
15.1k
            p_dec->fmt_out.audio.i_frame_length = asc.i_frame_length;
247
15.1k
            p_dec->fmt_out.audio.i_channels =
248
15.1k
                    ChannelConfigurationToVLC(asc.i_channel_configuration);
249
15.1k
            if(p_dec->fmt_out.i_profile != -1)
250
0
                p_dec->fmt_out.i_profile = AOTtoAACProfile(asc.i_object_type);
251
252
15.1k
            msg_Dbg(p_dec, "%sAAC%s %dHz %d samples/frame",
253
15.1k
                    (asc.i_sbr) ? "HE-" : "",
254
15.1k
                    (asc.i_ps) ? "v2" : "",
255
15.1k
                    (asc.i_sbr) ? p_dec->fmt_out.audio.i_rate << 1
256
15.1k
                                : p_dec->fmt_out.audio.i_rate,
257
15.1k
                    p_dec->fmt_out.audio.i_frame_length);
258
15.1k
        }
259
260
92.7k
        p_dec->fmt_out.p_extra = malloc(p_dec->fmt_in->i_extra);
261
92.7k
        if (!p_dec->fmt_out.p_extra)
262
0
            return VLC_ENOMEM;
263
92.7k
        p_dec->fmt_out.i_extra = p_dec->fmt_in->i_extra;
264
92.7k
        memcpy(p_dec->fmt_out.p_extra, p_dec->fmt_in->p_extra,
265
92.7k
                p_dec->fmt_in->i_extra);
266
92.7k
    }
267
    /* else() We will try to create a AAC Config from adts/loas */
268
269
117k
    date_Init(&p_sys->end_date, p_dec->fmt_out.audio.i_rate ?
270
100k
                                p_dec->fmt_out.audio.i_rate : 48000, 1);
271
272
    /* Set callbacks */
273
117k
    p_dec->pf_packetize = Packetize;
274
117k
    p_dec->pf_flush = Flush;
275
117k
    p_dec->pf_get_cc = NULL;
276
277
117k
    return VLC_SUCCESS;
278
117k
}
279
280
/*****************************************************************************
281
 * ClosePacketizer: clean up the packetizer
282
 *****************************************************************************/
283
static void ClosePacketizer(vlc_object_t *p_this)
284
117k
{
285
117k
    decoder_t *p_dec = (decoder_t *)p_this;
286
117k
    decoder_sys_t *p_sys = p_dec->p_sys;
287
288
117k
    block_BytestreamRelease(&p_sys->bytestream);
289
117k
    free(p_sys);
290
117k
}
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
1.30M
{
299
1.30M
    decoder_sys_t *p_sys = p_dec->p_sys;
300
1.30M
    block_t *p_block;
301
302
1.30M
    if (!pp_block || !*pp_block)
303
661k
        return NULL;
304
305
643k
    p_block = *pp_block;
306
643k
    *pp_block = NULL; /* Don't reuse this block */
307
308
643k
    vlc_tick_t i_diff = 0;
309
643k
    if (p_block->i_pts != VLC_TICK_INVALID &&
310
612k
        p_block->i_pts != date_Get(&p_sys->end_date))
311
488k
    {
312
488k
        if(date_Get(&p_sys->end_date) != VLC_TICK_INVALID)
313
459k
            i_diff = llabs( date_Get(&p_sys->end_date) - p_block->i_pts );
314
488k
        date_Set(&p_sys->end_date, p_block->i_pts);
315
488k
    }
316
317
643k
    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
643k
    if(p_dec->fmt_out.audio.i_frame_length && p_block->i_pts != VLC_TICK_INVALID)
322
332k
    {
323
332k
        p_block->i_length = date_Increment(&p_sys->end_date,
324
332k
            p_dec->fmt_out.audio.i_frame_length) - p_block->i_pts;
325
326
332k
        if( i_diff > p_block->i_length )
327
43.6k
            p_sys->b_discontuinity = true;
328
332k
    }
329
330
643k
    return p_block;
331
1.30M
}
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
1.83M
{
342
1.83M
    int i_profile, i_sample_rate_idx, i_frame_size;
343
1.83M
    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
1.83M
    b_crc = !(p_buf[1] & 0x01);
348
1.83M
    i_profile = p_buf[2] >> 6;
349
1.83M
    i_sample_rate_idx = (p_buf[2] >> 2) & 0x0f;
350
1.83M
    *pi_sample_rate = pi_sample_rates[i_sample_rate_idx];
351
    //private_bit = (p_buf[2] >> 1) & 0x01;
352
1.83M
    *pi_channels = ((p_buf[2] & 0x01) << 2) | ((p_buf[3] >> 6) & 0x03);
353
1.83M
    if (*pi_channels == 0) /* workaround broken streams */
354
279k
        *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
1.83M
    i_frame_size = ((p_buf[3] & 0x03) << 11) | (p_buf[4] << 3) |
362
1.83M
                   ((p_buf[5] >> 5) /*& 0x7*/);
363
    //uint16_t buffer_fullness = ((p_buf[5] & 0x1f) << 6) | (p_buf[6] >> 2);
364
1.83M
    unsigned short i_raw_blocks_in_frame = p_buf[6] & 0x03;
365
366
1.83M
    if (!*pi_sample_rate || !i_frame_size) {
367
515k
        msg_Warn(p_dec, "Invalid ADTS header");
368
515k
        return 0;
369
515k
    }
370
371
1.31M
    *pi_frame_length = 1024;
372
373
1.31M
    if (i_raw_blocks_in_frame == 0) {
374
976k
        if (b_crc) {
375
16.1k
            WARN_ONCE(WARN_CRC_UNSUPPORTED, "ADTS CRC not supported");
376
            //uint16_t crc = (p_buf[7] << 8) | p_buf[8];
377
16.1k
        }
378
976k
    } else {
379
337k
        msg_Err(p_dec, "Multiple blocks per frame in ADTS not supported");
380
337k
        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
337k
    }
405
406
407
    /* Build the decoder specific info header */
408
976k
    if (!p_dec->fmt_out.i_extra) {
409
5.43k
        p_dec->fmt_out.p_extra = malloc(2);
410
5.43k
        if (!p_dec->fmt_out.p_extra)
411
0
            return 0;
412
5.43k
        p_dec->fmt_out.i_extra = 2;
413
5.43k
        ((uint8_t *)p_dec->fmt_out.p_extra)[0] =
414
5.43k
            (i_profile + 1) << 3 | (i_sample_rate_idx >> 1);
415
5.43k
        ((uint8_t *)p_dec->fmt_out.p_extra)[1] =
416
5.43k
            ((i_sample_rate_idx & 0x01) << 7) | (*pi_channels <<3);
417
5.43k
    }
418
419
    /* ADTS header length */
420
976k
    *pi_header_size = b_crc ? 9 : 7;
421
422
976k
    return i_frame_size - *pi_header_size;
423
976k
}
424
425
/****************************************************************************
426
 * LOAS helpers
427
 ****************************************************************************/
428
static int LOASSyncInfo(uint8_t p_header[LOAS_HEADER_SIZE], unsigned int *pi_header_size)
429
500k
{
430
500k
    *pi_header_size = 3;
431
500k
    return ((p_header[1] & 0x1f) << 8) + p_header[2];
432
500k
}
433
434
static int LOASParse(decoder_t *p_dec, uint8_t *p_buffer, int i_buffer)
435
303k
{
436
303k
    decoder_sys_t *p_sys = p_dec->p_sys;
437
303k
    bs_t s;
438
303k
    int i_accumulated = 0;
439
440
303k
    bs_init(&s, p_buffer, i_buffer);
441
442
    /* Read the stream mux configuration if present */
443
303k
    if (!bs_read1(&s) && !MPEG4_parse_StreamMuxConfig(&s, &p_sys->latm) &&
444
165k
            p_sys->latm.i_streams > 0) {
445
165k
        const MPEG4_audio_stream_t *st = &p_sys->latm.stream[0];
446
447
165k
        if(st->cfg.i_samplerate == 0 || st->cfg.i_frame_length == 0 ||
448
157k
           ChannelConfigurationToVLC(st->cfg.i_channel_configuration) == 0)
449
16.7k
            return 0;
450
451
148k
        p_sys->i_channels = ChannelConfigurationToVLC(st->cfg.i_channel_configuration);
452
148k
        p_sys->i_rate = st->cfg.i_samplerate;
453
148k
        p_sys->i_frame_length = st->cfg.i_frame_length;
454
148k
        p_sys->i_aac_profile = AOTtoAACProfile(st->cfg.i_object_type);
455
456
148k
        if (p_sys->i_channels && p_sys->i_rate && p_sys->i_frame_length > 0)
457
148k
        {
458
148k
            if(p_dec->fmt_out.i_extra != st->i_extra ||
459
80.2k
               (p_dec->fmt_out.i_extra > 0 &&
460
79.3k
                memcmp(p_dec->fmt_out.p_extra, st->extra, st->i_extra)) )
461
105k
            {
462
105k
                if(p_dec->fmt_out.i_extra)
463
98.6k
                    free(p_dec->fmt_out.p_extra);
464
105k
                p_dec->fmt_out.p_extra = st->i_extra ? malloc(st->i_extra) : NULL;
465
105k
                if(p_dec->fmt_out.p_extra)
466
102k
                {
467
102k
                    p_dec->fmt_out.i_extra = st->i_extra;
468
102k
                    memcpy(p_dec->fmt_out.p_extra, st->extra, st->i_extra);
469
102k
                    p_sys->b_latm_cfg = true;
470
102k
                }
471
3.11k
                else
472
3.11k
                {
473
3.11k
                    p_dec->fmt_out.i_extra = 0;
474
3.11k
                    p_sys->b_latm_cfg = false;
475
3.11k
                }
476
105k
            }
477
148k
        }
478
148k
    }
479
480
    /* Wait for the configuration */
481
287k
    if (!p_sys->b_latm_cfg)
482
54.9k
    {
483
        /* WAVE_FORMAT_MPEG_LOAS, configuration provided as AAC header :/ */
484
54.9k
        if( p_dec->fmt_in->i_extra > 0 &&
485
1.29k
            p_sys->i_channels && p_sys->i_rate && p_sys->i_frame_length )
486
348
        {
487
348
            p_sys->b_latm_cfg = true;
488
348
        }
489
54.6k
        else return 0;
490
54.9k
    }
491
492
232k
    if(bs_eof(&s) && i_buffer)
493
75.1k
        goto truncated;
494
495
    /* FIXME do we need to split the subframe into independent packet ? */
496
157k
    if (p_sys->latm.numSubFrames != 0)
497
157k
        msg_Err(p_dec, "latm sub frames not yet supported, please send a sample");
498
499
1.56M
    for (uint8_t i_sub = 0; i_sub <= p_sys->latm.numSubFrames; i_sub++) {
500
1.42M
        unsigned pi_payload[MPEG4_STREAMMUX_MAX_PROGRAM][MPEG4_STREAMMUX_MAX_LAYER];
501
1.42M
        if (p_sys->latm.allStreamsSameTimeFraming) {
502
            /* Payload length */
503
5.10M
            for (uint8_t i_program = 0; i_program <= p_sys->latm.numProgram; i_program++) {
504
13.3M
                for (uint8_t i_layer = 0; i_layer <= p_sys->latm.p_numLayer[i_program]; i_layer++) {
505
9.56M
                    const MPEG4_audio_stream_t *st = &p_sys->latm.stream[p_sys->latm.pi_stream[i_program][i_layer]];
506
9.56M
                    if (st->i_frame_length_type == 0) {
507
3.88M
                        unsigned i_payload = 0;
508
4.07M
                        for (;;) {
509
4.07M
                            uint8_t i_tmp = bs_read(&s, 8);
510
4.07M
                            i_payload += i_tmp;
511
4.07M
                            if (i_tmp != 255)
512
3.88M
                                break;
513
4.07M
                        }
514
3.88M
                        pi_payload[i_program][i_layer] = i_payload;
515
5.67M
                    } else if (st->i_frame_length_type == 1) {
516
1.08M
                        pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
517
4.59M
                    } else if ((st->i_frame_length_type == 3) ||
518
4.16M
                             (st->i_frame_length_type == 5) ||
519
3.90M
                             (st->i_frame_length_type == 7)) {
520
2.49M
                        bs_skip(&s, 2); // muxSlotLengthCoded
521
2.49M
                        pi_payload[i_program][i_layer] = 0; /* TODO */
522
2.49M
                    } else {
523
2.10M
                        pi_payload[i_program][i_layer] = 0; /* TODO */
524
2.10M
                    }
525
9.56M
                }
526
3.83M
            }
527
528
            /* Payload Data */
529
5.03M
            for (uint8_t i_program = 0; i_program <= p_sys->latm.numProgram; i_program++) {
530
5.03M
                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
4.22M
                    if (i_program != 0 || i_layer != 0)
533
2.95M
                        break;
534
535
1.26M
                    if (pi_payload[i_program][i_layer] <= 0)
536
1.02M
                        continue;
537
538
                    /* FIXME that's slow (and a bit ugly to write in place) */
539
5.45M
                    for (unsigned i = 0; i < pi_payload[i_program][i_layer]; i++) {
540
5.24M
                        if (i_accumulated >= i_buffer)
541
0
                            return 0;
542
5.24M
                        p_buffer[i_accumulated++] = bs_read(&s, 8);
543
5.24M
                        if(bs_error(&s))
544
20.7k
                            goto truncated;
545
5.24M
                    }
546
238k
                }
547
3.78M
            }
548
1.26M
        } else {
549
158k
            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
158k
            msg_Err(p_dec, "latm without same time frameing not yet supported, please send a sample");
556
557
471k
            for (int i_chunk = 0; i_chunk < i_chunks; i_chunk++) {
558
313k
                const int streamIndex = bs_read(&s, 4);
559
313k
                const MPEG4_audio_stream_t *st = &p_sys->latm.stream[streamIndex];
560
313k
                const int i_program = st->i_program;
561
313k
                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
313k
                if (st->i_frame_length_type == 0) {
569
156k
                    int i_payload = 0;
570
236k
                    for (;;) {
571
236k
                        int i_tmp = bs_read(&s, 8);
572
236k
                        i_payload += i_tmp;
573
236k
                        if (i_tmp != 255)
574
156k
                            break;
575
236k
                    }
576
156k
                    pi_payload[i_program][i_layer] = i_payload;
577
156k
                    bs_skip(&s, 1); // auEndFlag
578
156k
                } else if (st->i_frame_length_type == 1) {
579
8.70k
                    pi_payload[i_program][i_layer] = st->i_frame_length / 8; /* XXX not correct */
580
147k
                } else if ((st->i_frame_length_type == 3) ||
581
132k
                         (st->i_frame_length_type == 5) ||
582
119k
                         (st->i_frame_length_type == 7)) {
583
51.6k
                    bs_skip(&s, 2); // muxSlotLengthCoded
584
51.6k
                }
585
313k
            }
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
158k
        }
595
1.42M
    }
596
597
598
136k
    bs_skip(&s, p_sys->latm.otherDataLenBits);
599
136k
    bs_align(&s);
600
601
136k
    return i_accumulated;
602
603
95.9k
truncated:
604
95.9k
    msg_Warn(p_dec,"Truncated LOAS packet. Wrong format ?");
605
95.9k
    return 0;
606
157k
}
607
608
/*****************************************************************************
609
 *
610
 *****************************************************************************/
611
static void SetupOutput(decoder_t *p_dec, block_t *p_block)
612
580k
{
613
580k
    decoder_sys_t *p_sys = p_dec->p_sys;
614
615
580k
    if (p_dec->fmt_out.audio.i_rate != p_sys->i_rate && p_sys->i_rate > 0)
616
118k
    {
617
118k
        msg_Info(p_dec, "AAC channels: %d samplerate: %d",
618
118k
                  p_sys->i_channels, p_sys->i_rate);
619
118k
        date_Change(&p_sys->end_date, p_sys->i_rate, 1);
620
118k
    }
621
622
580k
    p_dec->fmt_out.audio.i_rate     = p_sys->i_rate;
623
580k
    p_dec->fmt_out.audio.i_channels = p_sys->i_channels;
624
580k
    p_dec->fmt_out.audio.i_bytes_per_frame = p_sys->i_frame_size;
625
580k
    p_dec->fmt_out.audio.i_frame_length = p_sys->i_frame_length;
626
    /* Will reload extradata on change */
627
580k
    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
580k
    p_block->i_pts = p_block->i_dts = date_Get(&p_sys->end_date);
634
635
580k
    p_block->i_length =
636
580k
        date_Increment(&p_sys->end_date, p_sys->i_frame_length) - p_block->i_pts;
637
580k
}
638
639
/*****************************************************************************
640
 * FlushStreamBlock:
641
 *****************************************************************************/
642
static void Flush(decoder_t *p_dec)
643
24.6k
{
644
24.6k
    decoder_sys_t *p_sys = p_dec->p_sys;
645
646
24.6k
    p_sys->i_state = STATE_NOSYNC;
647
24.6k
    block_BytestreamEmpty(&p_sys->bytestream);
648
24.6k
    date_Set(&p_sys->end_date, VLC_TICK_INVALID);
649
24.6k
    p_sys->b_discontuinity = true;
650
24.6k
}
651
652
static inline bool HasADTSHeader( const uint8_t *p_header )
653
42.7M
{
654
42.7M
    return p_header[0] == 0xff && (p_header[1] & 0xf6) == 0xf0;
655
42.7M
}
656
657
static inline bool HasLoasHeader( const uint8_t *p_header )
658
56.0M
{
659
56.0M
    return p_header[0] == 0x56 && (p_header[1] & 0xe0) == 0xe0;
660
56.0M
}
661
662
/****************************************************************************
663
 * PacketizeStreamBlock: ADTS/LOAS packetizer
664
 ****************************************************************************/
665
static block_t *PacketizeStreamBlock(decoder_t *p_dec, block_t **pp_block)
666
991k
{
667
991k
    decoder_sys_t *p_sys = p_dec->p_sys;
668
991k
    uint8_t p_header[ADTS_HEADER_SIZE + LOAS_HEADER_SIZE];
669
991k
    block_t *p_out_buffer;
670
991k
    uint8_t *p_buf;
671
672
991k
    block_t *p_block = pp_block ? *pp_block : NULL;
673
674
991k
    if(p_block)
675
881k
    {
676
881k
        block_BytestreamPush(&p_sys->bytestream, p_block);
677
881k
        *pp_block = NULL;
678
881k
    }
679
680
5.88M
    for (;;) switch(p_sys->i_state) {
681
2.50M
    case STATE_NOSYNC:
682
96.6M
        while (block_PeekBytes(&p_sys->bytestream, p_header, 2) == VLC_SUCCESS) {
683
            /* Look for sync word - should be 0xfff(adts) or 0x2b7(loas) */
684
96.4M
            if ((p_sys->i_type == TYPE_ADTS || p_sys->i_type == TYPE_UNKNOWN_NONRAW) &&
685
41.4M
                HasADTSHeader( p_header ) )
686
1.83M
            {
687
1.83M
                if (p_sys->i_type != TYPE_ADTS)
688
1.83M
                    msg_Dbg(p_dec, "detected ADTS format");
689
690
1.83M
                p_sys->i_state = STATE_SYNC;
691
1.83M
                p_sys->i_type = TYPE_ADTS;
692
1.83M
                break;
693
1.83M
            }
694
94.6M
            else if ((p_sys->i_type == TYPE_LOAS || p_sys->i_type == TYPE_UNKNOWN_NONRAW) &&
695
55.2M
                      HasLoasHeader( p_header ) )
696
501k
            {
697
501k
                if (p_sys->i_type != TYPE_LOAS)
698
501k
                    msg_Dbg(p_dec, "detected LOAS format");
699
700
501k
                p_sys->i_state = STATE_SYNC;
701
501k
                p_sys->i_type = TYPE_LOAS;
702
501k
                break;
703
501k
            }
704
94.1M
            (void) block_SkipByte(&p_sys->bytestream);
705
94.1M
        }
706
2.50M
        if (p_sys->i_state != STATE_SYNC) {
707
168k
            block_BytestreamFlush(&p_sys->bytestream);
708
709
            /* Need more data */
710
168k
            return NULL;
711
168k
        }
712
        /* fallthrough */
713
714
2.33M
    case STATE_SYNC:
715
        /* New frame, set the Presentation Time Stamp */
716
2.33M
        p_sys->i_pts = p_sys->bytestream.p_block->i_pts;
717
2.33M
        if (p_sys->i_pts != VLC_TICK_INVALID &&
718
262k
            p_sys->i_pts != date_Get(&p_sys->end_date))
719
92.7k
            date_Set(&p_sys->end_date, p_sys->i_pts);
720
2.33M
        p_sys->i_state = STATE_HEADER;
721
2.33M
        break;
722
723
2.39M
    case STATE_HEADER:
724
2.39M
        if (p_sys->i_type == TYPE_ADTS) {
725
            /* Get ADTS frame header (ADTS_HEADER_SIZE bytes) */
726
1.88M
            if (block_PeekBytes(&p_sys->bytestream, p_header,
727
1.88M
                        ADTS_HEADER_SIZE) != VLC_SUCCESS)
728
58.9k
                return NULL; /* Need more data */
729
730
            /* Check if frame is valid and get frame info */
731
1.83M
            p_sys->i_frame_size = ADTSSyncInfo(p_dec, p_header,
732
1.83M
                    &p_sys->i_channels,
733
1.83M
                    &p_sys->i_rate,
734
1.83M
                    &p_sys->i_frame_length,
735
1.83M
                    &p_sys->i_header_size);
736
1.83M
        } else {
737
502k
            assert(p_sys->i_type == TYPE_LOAS);
738
            /* Get LOAS frame header (LOAS_HEADER_SIZE bytes) */
739
502k
            if (block_PeekBytes(&p_sys->bytestream, p_header,
740
502k
                        LOAS_HEADER_SIZE) != VLC_SUCCESS)
741
1.20k
                return NULL; /* Need more data */
742
743
            /* Check if frame is valid and get frame info */
744
500k
            p_sys->i_frame_size = LOASSyncInfo(p_header, &p_sys->i_header_size);
745
500k
        }
746
747
2.33M
        if (p_sys->i_frame_size <= 0) {
748
918k
            msg_Dbg(p_dec, "emulated sync word");
749
918k
            block_SkipByte(&p_sys->bytestream);
750
918k
            p_sys->i_state = STATE_NOSYNC;
751
918k
            break;
752
918k
        }
753
754
1.41M
        p_sys->i_state = STATE_NEXT_SYNC;
755
        /* fallthrough */
756
757
1.58M
    case STATE_NEXT_SYNC:
758
1.58M
        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
1.58M
        if (block_PeekOffsetBytes(&p_sys->bytestream, p_sys->i_frame_size
766
1.58M
                    + p_sys->i_header_size, p_header, 2) != VLC_SUCCESS)
767
184k
        {
768
184k
            if(p_block == NULL) /* drain */
769
8.45k
            {
770
8.45k
                p_sys->i_state = STATE_SEND_DATA;
771
8.45k
                break;
772
8.45k
            }
773
176k
            return NULL; /* Need more data */
774
184k
        }
775
776
1.58M
        assert((p_sys->i_type == TYPE_ADTS) || (p_sys->i_type == TYPE_LOAS));
777
1.40M
        if ( (p_sys->i_type == TYPE_ADTS && !HasADTSHeader( p_header )) ||
778
704k
             (p_sys->i_type == TYPE_LOAS && !HasLoasHeader( p_header )) )
779
1.15M
        {
780
            /* Check spacial padding case. Failing if need more bytes is ok since
781
               that should have been sent as a whole block */
782
1.15M
            if( block_PeekOffsetBytes(&p_sys->bytestream,
783
1.15M
                                      p_sys->i_frame_size + p_sys->i_header_size,
784
1.15M
                                      p_header, 3) == VLC_SUCCESS &&
785
1.13M
                p_header[0] == 0x00 &&
786
704k
               ((p_sys->i_type == TYPE_ADTS && HasADTSHeader( &p_header[1] )) ||
787
427k
                (p_sys->i_type == TYPE_LOAS && !HasLoasHeader( &p_header[1] ))))
788
551k
            {
789
551k
                p_sys->i_state = STATE_SEND_DATA;
790
551k
            }
791
601k
            else
792
601k
            {
793
601k
                msg_Dbg(p_dec, "emulated sync word (no sync on following frame)"
794
601k
                               " 0x%"PRIx8" 0x%"PRIx8, p_header[0], p_header[1] );
795
601k
                p_sys->i_state = STATE_NOSYNC;
796
601k
                block_SkipByte(&p_sys->bytestream);
797
601k
            }
798
1.15M
            break;
799
1.15M
        }
800
801
251k
        p_sys->i_state = STATE_SEND_DATA;
802
251k
        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
811k
    case STATE_SEND_DATA:
814
        /* When we reach this point we already know we have enough
815
         * data available. */
816
817
811k
        if (unlikely( block_BytestreamRemaining(&p_sys->bytestream) <
818
811k
                      p_sys->i_header_size + p_sys->i_frame_size ))
819
6.57k
            return NULL; // need more data
820
821
805k
        p_out_buffer = block_Alloc(p_sys->i_frame_size);
822
805k
        if (!p_out_buffer) {
823
0
            return NULL;
824
0
        }
825
805k
        p_buf = p_out_buffer->p_buffer;
826
827
        /* Skip the ADTS/LOAS header */
828
805k
        (void) block_SkipBytes(&p_sys->bytestream, p_sys->i_header_size);
829
830
        /* Copy the whole frame into the buffer */
831
805k
        (void) block_GetBytes(&p_sys->bytestream, p_buf, p_sys->i_frame_size);
832
805k
        if (p_sys->i_type != TYPE_ADTS) { /* parse/extract the whole frame */
833
303k
            assert(p_sys->i_type == TYPE_LOAS);
834
303k
            p_out_buffer->i_buffer = LOASParse(p_dec, p_buf, p_sys->i_frame_size);
835
303k
            if (p_out_buffer->i_buffer <= 0)
836
225k
            {
837
225k
                if (!p_sys->b_latm_cfg)
838
225k
                    msg_Warn(p_dec, "waiting for header");
839
840
225k
                block_Release(p_out_buffer);
841
225k
                p_out_buffer = NULL;
842
225k
                p_sys->i_state = STATE_NOSYNC;
843
225k
                break;
844
225k
            }
845
303k
        }
846
580k
        SetupOutput(p_dec, p_out_buffer);
847
        /* Make sure we don't reuse the same pts twice */
848
580k
        if (p_sys->i_pts == p_sys->bytestream.p_block->i_pts)
849
557k
            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
580k
        if( pp_block )
853
578k
            *pp_block = block_BytestreamPop(&p_sys->bytestream);
854
855
580k
        p_sys->i_state = STATE_NOSYNC;
856
857
580k
        return p_out_buffer;
858
859
0
    case STATE_CUSTOM_FIRST:
860
0
        break; // do nothing
861
5.88M
    }
862
863
0
    return NULL;
864
991k
}
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
2.32M
{
872
2.32M
    decoder_sys_t *p_sys = p_dec->p_sys;
873
2.32M
    block_t *p_block = pp_block ? *pp_block : NULL;
874
875
2.32M
    if(p_block)
876
1.56M
    {
877
1.56M
        if (p_block->i_flags & (BLOCK_FLAG_DISCONTINUITY|BLOCK_FLAG_CORRUPTED))
878
24.8k
        {
879
24.8k
            if(p_sys->i_type == TYPE_ADTS || p_sys->i_type == TYPE_LOAS)
880
7.62k
            {
881
                /* First always drain complete blocks before discontinuity */
882
7.62k
                block_t *p_drain = PacketizeStreamBlock(p_dec, NULL);
883
7.62k
                if(p_drain)
884
195
                    return p_drain;
885
7.62k
            }
886
887
24.6k
            Flush(p_dec);
888
889
24.6k
            if (p_block->i_flags & BLOCK_FLAG_CORRUPTED)
890
22.9k
            {
891
22.9k
                block_Release(p_block);
892
22.9k
                return NULL;
893
22.9k
            }
894
24.6k
        }
895
896
1.53M
        if ( p_block->i_pts == VLC_TICK_INVALID &&
897
633k
             date_Get(&p_sys->end_date) == VLC_TICK_INVALID )
898
15.0k
        {
899
            /* We've just started the stream, wait for the first PTS. */
900
15.0k
            block_Release(p_block);
901
15.0k
            return NULL;
902
15.0k
        }
903
1.53M
    }
904
905
2.28M
    if(p_block && p_sys->i_type == TYPE_UNKNOWN)
906
20.2k
    {
907
20.2k
        p_sys->i_type = TYPE_RAW;
908
20.2k
        if(p_block->i_buffer > 1)
909
19.9k
        {
910
19.9k
            if(p_block->p_buffer[0] == 0xff && (p_block->p_buffer[1] & 0xf6) == 0xf0)
911
1.29k
            {
912
1.29k
                p_sys->i_type = TYPE_ADTS;
913
1.29k
            }
914
18.6k
            else if(p_block->p_buffer[0] == 0x56 && (p_block->p_buffer[1] & 0xe0) == 0xe0)
915
639
            {
916
639
                p_sys->i_type = TYPE_LOAS;
917
639
            }
918
19.9k
        }
919
20.2k
    }
920
921
2.28M
    if(p_sys->i_type == TYPE_RAW)
922
1.30M
        p_block = ForwardRawBlock(p_dec, pp_block);
923
984k
    else
924
984k
        p_block = PacketizeStreamBlock(p_dec, pp_block);
925
926
2.28M
    if(p_block && p_sys->b_discontuinity)
927
55.9k
    {
928
55.9k
        p_block->i_flags |= BLOCK_FLAG_DISCONTINUITY;
929
55.9k
        p_sys->b_discontuinity = false;
930
55.9k
    }
931
932
2.28M
    return p_block;
933
2.32M
}