Coverage Report

Created: 2026-01-17 06:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/vlc/modules/demux/mp4/mp4.c
Line
Count
Source
1
/*****************************************************************************
2
 * mp4.c : MP4 file input module for vlc
3
 *****************************************************************************
4
 * Copyright (C) 2001-2004, 2010 VLC authors and VideoLAN
5
 *
6
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7
 *
8
 * This program is free software; you can redistribute it and/or modify it
9
 * under the terms of the GNU Lesser General Public License as published by
10
 * the Free Software Foundation; either version 2.1 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16
 * GNU Lesser General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU Lesser General Public License
19
 * along with this program; if not, write to the Free Software Foundation,
20
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
21
 *****************************************************************************/
22
#ifdef HAVE_CONFIG_H
23
# include "config.h"
24
#endif
25
26
/*****************************************************************************
27
 * Preamble
28
 *****************************************************************************/
29
#include "mp4.h"
30
31
#include <vlc_arrays.h>
32
#include <vlc_demux.h>
33
#include <vlc_charset.h>                           /* EnsureUTF8 */
34
#include <vlc_input.h>
35
#include <vlc_aout.h>
36
#include <vlc_plugin.h>
37
#include <vlc_dialog.h>
38
#include <vlc_url.h>
39
#include <vlc_replay_gain.h>
40
#include <assert.h>
41
#include <limits.h>
42
#include <math.h>
43
#include "meta.h"
44
#include "attachments.h"
45
#include "heif.h"
46
#include "../../codec/cc.h"
47
#include "../av1_unpack.h"
48
49
#include <stdlib.h>
50
51
/*****************************************************************************
52
 * Module descriptor
53
 *****************************************************************************/
54
static int  Open ( vlc_object_t * );
55
static void Close( vlc_object_t * );
56
57
#define CFG_PREFIX "mp4-"
58
59
#define MP4_M4A_TEXT     N_("M4A audio only")
60
#define MP4_M4A_LONGTEXT N_("Ignore non audio tracks from iTunes audio files")
61
62
#define MP4_ELST_TEXT       N_("Handle edit list")
63
64
#define HEIF_DURATION_TEXT N_("Duration in seconds")
65
#define HEIF_DURATION_LONGTEXT N_( \
66
    "Duration in seconds before simulating an end of file. " \
67
    "A negative value means an unlimited play time.")
68
69
108
vlc_module_begin ()
70
54
    set_subcategory( SUBCAT_INPUT_DEMUX )
71
54
    set_description( N_("MP4 stream demuxer") )
72
54
    set_shortname( N_("MP4") )
73
54
    set_capability( "demux", 240 )
74
108
    set_callbacks( Open, Close )
75
54
    add_file_extension("m4a")
76
54
    add_file_extension("m4v")
77
54
    add_file_extension("moov")
78
54
    add_file_extension("mov")
79
54
    add_file_extension("mp4")
80
81
54
    set_section("Hacks", NULL)
82
54
    add_bool( CFG_PREFIX"m4a-audioonly", false, MP4_M4A_TEXT, MP4_M4A_LONGTEXT )
83
54
    add_bool( CFG_PREFIX"editlist", true, MP4_ELST_TEXT, MP4_ELST_TEXT )
84
85
54
    add_submodule()
86
54
        set_subcategory( SUBCAT_INPUT_DEMUX )
87
54
        set_description( N_("HEIF demuxer") )
88
54
        set_shortname( "heif" )
89
54
        set_capability( "demux", 239 )
90
108
        set_callbacks( OpenHEIF, CloseHEIF )
91
54
        set_section( N_("HEIF demuxer"), NULL )
92
54
        add_float( "heif-image-duration", HEIF_DEFAULT_DURATION,
93
54
                   HEIF_DURATION_TEXT, HEIF_DURATION_LONGTEXT )
94
54
            change_safe()
95
54
vlc_module_end ()
96
97
/*****************************************************************************
98
 * Local prototypes
99
 *****************************************************************************/
100
static int   Demux   ( demux_t * );
101
0
static int   DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
102
static int   DemuxFrag( demux_t * );
103
static int   Control ( demux_t *, int, va_list );
104
105
typedef struct
106
{
107
    MP4_Box_t    *p_root;      /* container for the whole file */
108
109
    vlc_tick_t   i_pcr;
110
111
    uint64_t     i_moov_duration;
112
    uint64_t     i_duration;           /* Declared fragmented duration (movie time scale) */
113
    uint64_t     i_cumulated_duration; /* Same as above, but not from probing, (movie time scale) */
114
    uint32_t     i_timescale;          /* movie time scale */
115
    vlc_tick_t   i_nztime;             /* time position of the presentation (CLOCK_FREQ timescale) */
116
    vlc_tick_t   i_max_pts_offset;
117
    unsigned int i_tracks;       /* number of tracks */
118
    mp4_track_t  *track;         /* array of track */
119
    float        f_fps;          /* number of frame per seconds */
120
121
    bool         b_quicktime;
122
    bool         b_fragmented;   /* fMP4 */
123
    bool         b_seekable;
124
    bool         b_fastseekable;
125
    bool         b_error;        /* unrecoverable */
126
127
    bool            b_index_probed;     /* mFra sync points index */
128
    bool            b_fragments_probed; /* moof segments index created */
129
130
    MP4_Box_t *p_moov;
131
132
    struct
133
    {
134
        uint32_t        i_current_box_type;
135
        MP4_Box_t      *p_fragment_atom;
136
        uint64_t        i_post_mdat_offset;
137
        uint32_t        i_lastseqnumber;
138
    } context;
139
140
    /* */
141
    bool seekpoint_changed;
142
    int          i_seekpoint;
143
    input_title_t *p_title;
144
    vlc_meta_t    *p_meta;
145
    struct
146
    {
147
        uint32_t i_delay_samples;
148
        float f_replay_gain_norm;
149
        float f_replay_gain_peak;
150
        uint32_t i_target_bitrate;
151
    } qt;
152
153
    /* ASF in MP4 */
154
    asf_packet_sys_t asfpacketsys;
155
    vlc_tick_t i_preroll;       /* foobar */
156
    vlc_tick_t i_preroll_start;
157
158
    struct
159
    {
160
        enum es_format_category_e es_cat_filter;
161
    } hacks;
162
163
    mp4_fragments_index_t *p_fragsindex;
164
165
    ssize_t i_attachments;
166
    input_attachment_t **pp_attachments;
167
} demux_sys_t;
168
169
1.60G
#define DEMUX_INCREMENT VLC_TICK_FROM_MS(250) /* How far the pcr will go, each round */
170
0
#define DEMUX_TRACK_MAX_PRELOAD VLC_TICK_FROM_SEC(15) /* maximum preloading, to deal with interleaving */
171
172
179M
#define INVALID_PRELOAD  UINT_MAX
173
367M
#define UNKNOWN_DELTA    UINT32_MAX
174
5.22M
#define INVALID_PTS      VLC_TICK_MIN
175
176
1.02G
#define VLC_DEMUXER_EOS (VLC_DEMUXER_EGENERIC - 1)
177
164
#define VLC_DEMUXER_FATAL (VLC_DEMUXER_EGENERIC - 2)
178
179
/*****************************************************************************
180
 * Declaration of local function
181
 *****************************************************************************/
182
static void MP4_TrackSetup( demux_t *, mp4_track_t *, const MP4_Box_t  *, bool, bool );
183
static void MP4_TrackInit( mp4_track_t *, const MP4_Box_t * );
184
static void MP4_TrackClean( es_out_t *, mp4_track_t * );
185
186
static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
187
188
static void MP4_TrackSelect  ( demux_t *, mp4_track_t *, bool );
189
static int  MP4_TrackSeek   ( demux_t *, mp4_track_t *, vlc_tick_t );
190
191
static uint64_t MP4_TrackGetPos    ( mp4_track_t * );
192
static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
193
static int      MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
194
static void     MP4_TrackSetELST( demux_t *, mp4_track_t *, vlc_tick_t );
195
static void TrackUpdateSampleAndTimes( mp4_track_t *p_track );
196
197
static void     MP4_UpdateSeekpoint( demux_t *, vlc_tick_t );
198
199
static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
200
static void MP4_GetDefaultSizeAndDuration( MP4_Box_t *p_moov,
201
                                           const MP4_Box_data_tfhd_t *p_tfhd_data,
202
                                           uint32_t *pi_default_size,
203
                                           uint32_t *pi_default_duration );
204
205
static stime_t GetMoovTrackDuration( demux_sys_t *p_sys, unsigned i_track_ID );
206
207
static int  ProbeFragments( demux_t *p_demux, bool b_force, bool *pb_fragmented );
208
static int  ProbeFragmentsChecked( demux_t *p_demux );
209
static int  ProbeIndex( demux_t *p_demux );
210
211
static int FragCreateTrunIndex( demux_t *, MP4_Box_t *, MP4_Box_t *, stime_t );
212
213
static int FragGetMoofBySidxIndex( demux_t *p_demux, vlc_tick_t i_target_time,
214
                                   uint64_t *pi_moof_pos, vlc_tick_t *pi_sampletime );
215
static int FragGetMoofByTfraIndex( demux_t *p_demux, const vlc_tick_t i_target_time, unsigned i_track_ID,
216
                                   uint64_t *pi_moof_pos, vlc_tick_t *pi_sampletime );
217
static void FragResetContext( demux_sys_t * );
218
219
/* ASF Handlers */
220
static asf_track_info_t * MP4ASF_GetTrackInfo( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number );
221
static void MP4ASF_Send(asf_packet_sys_t *p_packetsys, uint8_t i_stream_number, block_t **pp_frame);
222
static void MP4ASF_ResetFrames( demux_sys_t *p_sys );
223
224
/* RTP Hint track */
225
static block_t * MP4_RTPHint_Convert( demux_t *p_demux, block_t *p_block, vlc_fourcc_t i_codec );
226
static block_t * MP4_RTPHintToFrame( demux_t *p_demux, block_t *p_block, uint32_t packetcount );
227
228
static int MP4_LoadMeta( demux_sys_t *p_sys, vlc_meta_t *p_meta );
229
230
/* Helpers */
231
232
static int64_t MP4_rescale( int64_t i_value, uint32_t i_timescale, uint32_t i_newscale )
233
3.99G
{
234
3.99G
    if( i_timescale == i_newscale )
235
950k
        return i_value;
236
237
3.99G
    if( i_value <= INT64_MAX / i_newscale )
238
3.92G
        return i_value * i_newscale / i_timescale;
239
240
    /* overflow */
241
72.4M
    int64_t q = i_value / i_timescale;
242
72.4M
    int64_t r = i_value % i_timescale;
243
72.4M
    return q * i_newscale + r * i_newscale / i_timescale;
244
3.99G
}
245
246
static vlc_tick_t MP4_rescale_mtime( int64_t i_value, uint32_t i_timescale )
247
1.80G
{
248
1.80G
    return MP4_rescale(i_value, i_timescale, CLOCK_FREQ);
249
1.80G
}
250
251
static int64_t MP4_rescale_qtime( vlc_tick_t i_value, uint32_t i_timescale )
252
417M
{
253
417M
    return MP4_rescale(i_value, CLOCK_FREQ, i_timescale);
254
417M
}
255
256
static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
257
0
{
258
0
    ssize_t i_return = 0;
259
0
    if ( i_toread > INT32_MAX )
260
0
    {
261
0
        i_return = vlc_stream_Read( s, p_read, (size_t) INT32_MAX );
262
0
        if ( i_return < INT32_MAX )
263
0
            return i_return;
264
0
        else
265
0
            i_toread -= INT32_MAX;
266
0
    }
267
0
    i_return += vlc_stream_Read( s, (uint8_t *)p_read + i_return, (size_t) i_toread );
268
0
    return i_return;
269
0
}
270
271
static int MP4_reftypeToFlag( vlc_fourcc_t i_reftype )
272
832
{
273
832
    switch( i_reftype )
274
832
    {
275
0
        case ATOM_chap:
276
0
            return USEAS_CHAPTERS;
277
86
        case VLC_FOURCC('t','m','c','d'):
278
86
            return USEAS_TIMECODE;
279
746
        default:
280
746
            return USEAS_NONE;
281
832
    }
282
832
}
283
284
static bool MP4_isMetadata( const mp4_track_t *tk )
285
2.65G
{
286
2.65G
    return tk->i_use_flags & (USEAS_CHAPTERS|USEAS_TIMECODE);
287
2.65G
}
288
289
static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
290
890
{
291
890
    if(!p_moov)
292
0
        return NULL;
293
890
    MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
294
1.13k
    while( p_trex )
295
899
    {
296
899
        if ( p_trex->i_type == ATOM_trex &&
297
851
             BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
298
659
                break;
299
240
        else
300
240
            p_trex = p_trex->p_next;
301
899
    }
302
890
    return p_trex;
303
890
}
304
305
/**
306
 * Return the track identified by tid
307
 */
308
static mp4_track_t *MP4_GetTrackByTrackID( demux_t *p_demux, const uint32_t tid )
309
9.90k
{
310
9.90k
    demux_sys_t *p_sys = p_demux->p_sys;
311
312
9.90k
    mp4_track_t *ret = NULL;
313
29.6k
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
314
20.8k
    {
315
20.8k
        ret = &p_sys->track[i];
316
20.8k
        if( ret->i_track_ID == tid )
317
1.13k
            return ret;
318
20.8k
    }
319
8.77k
    return NULL;
320
9.90k
}
321
322
static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
323
2.24k
{
324
2.24k
    MP4_Box_t *p_trak = MP4_BoxGet( p_moov, "trak" );
325
2.24k
    MP4_Box_t *p_tkhd;
326
2.84k
    while( p_trak )
327
2.79k
    {
328
2.79k
        if( p_trak->i_type == ATOM_trak &&
329
2.67k
            (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
330
2.52k
            BOXDATA(p_tkhd)->i_track_ID == i_id )
331
2.19k
                break;
332
603
        else
333
603
            p_trak = p_trak->p_next;
334
2.79k
    }
335
2.24k
    return p_trak;
336
2.24k
}
337
338
static MP4_Box_t * MP4_GetTrafByTrackID( MP4_Box_t *p_moof, const uint32_t i_id )
339
1.24k
{
340
1.24k
    MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
341
1.24k
    MP4_Box_t *p_tfhd;
342
1.55k
    while( p_traf )
343
950
    {
344
950
        if( p_traf->i_type == ATOM_traf &&
345
871
            (p_tfhd = MP4_BoxGet( p_traf, "tfhd" )) && BOXDATA(p_tfhd) &&
346
865
            BOXDATA(p_tfhd)->i_track_ID == i_id )
347
638
                break;
348
312
        else
349
312
            p_traf = p_traf->p_next;
350
950
    }
351
1.24k
    return p_traf;
352
1.24k
}
353
354
static const MP4_Box_t * MP4_GroupDescriptionByType( const MP4_Box_t *p_node,
355
                                                     uint32_t i_grouping_type )
356
0
{
357
0
    for( const MP4_Box_t *p_sgpd = MP4_BoxGet( p_node, "sgpd" );
358
0
                          p_sgpd; p_sgpd = p_sgpd->p_next )
359
0
    {
360
0
        const MP4_Box_data_sgpd_t *p_sgpd_data = BOXDATA(p_sgpd);
361
0
        if( p_sgpd->i_type != ATOM_sgpd || !p_sgpd_data ||
362
0
            p_sgpd_data->i_grouping_type != i_grouping_type )
363
0
            continue;
364
0
        return p_sgpd;
365
0
    }
366
0
    return NULL;
367
0
}
368
369
enum SampleGroupMatch
370
{
371
    SAMPLE_GROUP_MATCH_EXACT = 0,
372
    SAMPLE_GROUP_MATCH_LAST_VALID = 1,
373
};
374
375
static const MP4_Box_data_sbgp_entry_t *
376
    MP4_SampleToGroupInfo( const MP4_Box_t *p_node, uint32_t i_sample,
377
                           uint32_t i_grouping_type,
378
                           uint32_t i_grouping_type_parameter,
379
                           uint32_t *pi_group_sample,
380
                           enum SampleGroupMatch match,
381
                           const MP4_Box_data_sgpd_entry_t **pp_descentry )
382
175M
{
383
175M
    const MP4_Box_t *p_sbgp = MP4_BoxGet( p_node, "sbgp" );
384
175M
    const MP4_Box_data_sbgp_t *p_sbgp_data;
385
175M
    if( !p_sbgp )
386
175M
        return NULL;
387
388
66.2k
    do
389
73.7k
    {
390
73.7k
        p_sbgp_data = BOXDATA(p_sbgp);
391
73.7k
        if( p_sbgp->i_type == ATOM_sbgp && p_sbgp_data &&
392
73.7k
            p_sbgp_data->i_grouping_type == i_grouping_type &&
393
66.2k
            (i_grouping_type_parameter == 0 ||
394
0
             p_sbgp_data->i_grouping_type_parameter == i_grouping_type_parameter) )
395
66.2k
            break;
396
7.51k
        p_sbgp = p_sbgp->p_next;
397
7.51k
    } while(p_sbgp);
398
399
66.2k
    if( !p_sbgp )
400
28
        return NULL;
401
402
66.2k
    const MP4_Box_data_sbgp_entry_t *p_sampleentry = NULL;
403
66.2k
    uint32_t i_entry_start_sample = 0;
404
84.4k
    for ( uint32_t i=0; i<p_sbgp_data->i_entry_count; i++ )
405
82.7k
    {
406
82.7k
        const uint32_t next_entry_start_sample = i_entry_start_sample +
407
82.7k
                       p_sbgp_data->p_entries[i].i_sample_count;
408
82.7k
        if( i_sample >= next_entry_start_sample )
409
18.2k
        {
410
18.2k
            if( match == SAMPLE_GROUP_MATCH_LAST_VALID &&
411
18.2k
                p_sbgp_data->p_entries[i].i_group_description_index != 0 )
412
11.4k
            {
413
11.4k
                p_sampleentry = &p_sbgp_data->p_entries[i];
414
11.4k
                if( pi_group_sample )
415
11.4k
                    *pi_group_sample = i_entry_start_sample;
416
11.4k
            }
417
18.2k
            i_entry_start_sample = next_entry_start_sample;
418
18.2k
            continue;
419
18.2k
        }
420
421
        /* Sample has meaning for group */
422
64.4k
        if( p_sbgp_data->p_entries[i].i_group_description_index != 0 )
423
0
        {
424
0
            p_sampleentry = &p_sbgp_data->p_entries[i];
425
0
            if( pi_group_sample )
426
0
                *pi_group_sample = i_entry_start_sample;
427
0
        }
428
64.4k
        break;
429
82.7k
    }
430
431
    /* No meaning found for sample */
432
66.2k
    if( p_sampleentry == NULL )
433
60.4k
        return NULL;
434
435
    /* We have a sample entry in the group and maybe a description */
436
5.75k
    if( pp_descentry == NULL )
437
5.75k
        return p_sampleentry;
438
439
    /* Lookup designated group description */
440
0
    const MP4_Box_t *p_sgpd = MP4_GroupDescriptionByType( p_node, i_grouping_type );
441
0
    if( p_sgpd )
442
0
    {
443
0
        const MP4_Box_data_sgpd_t *p_descdata = BOXDATA(p_sgpd);
444
0
        if( p_sampleentry &&
445
0
            p_sampleentry->i_group_description_index <= p_descdata->i_entry_count )
446
0
        {
447
0
            *pp_descentry = &p_descdata->
448
0
                p_entries[p_sampleentry->i_group_description_index - 1];
449
0
        }
450
0
        else if( p_sampleentry == NULL &&
451
0
                 p_descdata->i_version >= 2 &&
452
0
                 p_descdata->i_default_sample_description_index &&
453
0
                 p_descdata->i_default_sample_description_index <= p_descdata->i_entry_count )
454
0
        {
455
0
            *pp_descentry = &p_descdata->
456
0
                p_entries[p_descdata->i_default_sample_description_index - 1];
457
0
        }
458
0
    }
459
460
0
    return p_sampleentry;
461
5.75k
}
462
463
static es_out_id_t * MP4_CreateES( es_out_t *out, const es_format_t *p_fmt,
464
                                   bool b_forced_spu )
465
3.02k
{
466
3.02k
    es_out_id_t *p_es = es_out_Add( out, p_fmt );
467
    /* Force SPU which isn't selected/defaulted */
468
3.02k
    if( p_fmt->i_cat == SPU_ES && p_es && b_forced_spu )
469
5
        es_out_Control( out, ES_OUT_SET_ES_DEFAULT, p_es );
470
471
3.02k
    return p_es;
472
3.02k
}
473
474
static int MP4_ChunkAllocEntries( size_t entries, uint32_t *smallbuf,
475
                                  uint32_t **dst0, uint32_t **dst1 )
476
324k
{
477
324k
    uint32_t *buf;
478
479
324k
    if( entries > MP4_CHUNK_SMALLBUF_ENTRIES )
480
1.54k
    {
481
1.54k
        buf = calloc( entries, sizeof( buf[0] ) * 2 );
482
1.54k
        if( unlikely(buf == NULL) )
483
0
            return VLC_ENOMEM;
484
1.54k
    }
485
322k
    else buf = smallbuf;
486
487
324k
    *dst0 = buf;
488
324k
    *dst1 = &buf[entries];
489
490
324k
    return VLC_SUCCESS;
491
324k
}
492
493
static void MP4_ChunkDestroy( mp4_chunk_t *ck )
494
240k
{
495
240k
    if( ck->p_sample_count_dts != ck->small_dts_buf )
496
10.6k
        free( ck->p_sample_count_dts );
497
240k
    if( ck->p_sample_count_pts != ck->small_pts_buf )
498
147k
        free( ck->p_sample_count_pts );
499
240k
}
500
501
static stime_t MP4_MapTrackTimeIntoTimeline( const mp4_track_t *p_track,
502
                                             uint32_t i_movie_timescale,
503
                                             stime_t i_time )
504
1.57G
{
505
1.57G
    if( !p_track->p_elst || p_track->BOXDATA(p_elst)->i_entry_count == 0 )
506
201M
        return i_time;
507
508
1.37G
    const MP4_Box_data_elst_entry_t *edit =
509
1.37G
            &p_track->BOXDATA(p_elst)->entries[p_track->i_elst];
510
511
    /* convert to offset in our current edit */
512
1.37G
    if( edit->i_media_time > 0 && p_track->i_start_dts >= edit->i_media_time )
513
522M
        i_time -= edit->i_media_time;
514
515
    /* convert media timeline to track timescale */
516
1.37G
    stime_t i_media_elst_start = MP4_rescale( p_track->i_elst_time,
517
1.37G
                                              i_movie_timescale,
518
1.37G
                                              p_track->i_timescale );
519
    /* add to timeline start in current edit */
520
1.37G
    i_time += i_media_elst_start;
521
522
1.37G
    return i_time;
523
1.57G
}
524
525
static stime_t MP4_MapMediaTimelineToTrackTime( const mp4_track_t *p_track,
526
                                                uint32_t i_movie_timescale,
527
                                                stime_t i_time )
528
200M
{
529
200M
    if( !p_track->p_elst || p_track->BOXDATA(p_elst)->i_entry_count == 0 )
530
0
        return i_time;
531
532
200M
    const MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
533
    /* convert media timeline to track timescale */
534
200M
    stime_t i_media_elst_start = MP4_rescale( p_track->i_elst_time,
535
200M
                                              i_movie_timescale,
536
200M
                                              p_track->i_timescale );
537
    /* convert to timeline offset in current edit */
538
200M
    i_time -= i_media_elst_start;
539
540
    /* add edit start in track samples time to get track sample time */
541
200M
    if( elst->entries[p_track->i_elst].i_media_time > 0 )
542
176M
        i_time += elst->entries[p_track->i_elst].i_media_time;
543
544
200M
    return i_time;
545
200M
}
546
547
static stime_t MP4_ChunkGetSampleDTS( const mp4_chunk_t *p_chunk,
548
                                      uint32_t i_sample )
549
183M
{
550
183M
    uint32_t i_index = 0;
551
183M
    stime_t sdts = p_chunk->i_first_dts;
552
184M
    while( i_sample > 0 && i_index < p_chunk->i_entries_dts )
553
6.20M
    {
554
6.20M
        if( i_sample > p_chunk->p_sample_count_dts[i_index] )
555
979k
        {
556
979k
            sdts += (stime_t)p_chunk->p_sample_count_dts[i_index] *
557
979k
                p_chunk->p_sample_delta_dts[i_index];
558
979k
            i_sample -= p_chunk->p_sample_count_dts[i_index++];
559
979k
        }
560
5.22M
        else
561
5.22M
        {
562
5.22M
            sdts += (stime_t)i_sample * p_chunk->p_sample_delta_dts[i_index];
563
5.22M
            break;
564
5.22M
        }
565
6.20M
    }
566
183M
    return sdts;
567
183M
}
568
569
static bool MP4_ChunkGetSampleCTSDelta( const mp4_chunk_t *p_chunk,
570
                                        uint32_t i_sample, stime_t *pi_delta )
571
183M
{
572
183M
    if( p_chunk->p_sample_count_pts && p_chunk->p_sample_offset_pts )
573
3.10M
    {
574
6.93M
        for( uint32_t i_index = 0; i_index < p_chunk->i_entries_pts ; i_index++ )
575
6.93M
        {
576
6.93M
            if( i_sample < p_chunk->p_sample_count_pts[i_index] )
577
3.10M
            {
578
3.10M
                *pi_delta = p_chunk->p_sample_offset_pts[i_index];
579
3.10M
                return true;
580
3.10M
            }
581
3.82M
            i_sample -= p_chunk->p_sample_count_pts[i_index];
582
3.82M
        }
583
3.10M
    }
584
180M
    return false;
585
183M
}
586
587
static vlc_tick_t MP4_TrackGetDTSPTS( demux_t *p_demux, const mp4_track_t *p_track,
588
                                      vlc_tick_t *pi_nzpts )
589
1.57G
{
590
1.57G
    demux_sys_t *p_sys = p_demux->p_sys;
591
592
1.57G
    stime_t sdts = p_track->i_next_dts;
593
1.57G
    uint32_t delta = p_track->i_next_delta;
594
595
    /* now handle elst */
596
1.57G
    sdts = MP4_MapTrackTimeIntoTimeline( p_track, p_sys->i_timescale, sdts );
597
598
1.57G
    vlc_tick_t i_dts = MP4_rescale_mtime( sdts, p_track->i_timescale);
599
600
1.57G
    if( pi_nzpts )
601
185M
    {
602
185M
        if( delta != UNKNOWN_DELTA )
603
2.02M
        {
604
2.02M
            *pi_nzpts = i_dts + MP4_rescale_mtime( delta, p_track->i_timescale );
605
2.02M
        }
606
183M
        else if( p_track->b_ignore_implicit_pts )
607
831
        {
608
831
            *pi_nzpts = INVALID_PTS;
609
831
        }
610
183M
        else *pi_nzpts = i_dts;
611
185M
    }
612
613
1.57G
    if( p_track->i_pts_offset )
614
2.53M
    {
615
2.53M
        if( pi_nzpts && *pi_nzpts != INVALID_PTS )
616
90.7k
            *pi_nzpts += p_track->i_pts_offset;
617
2.53M
        i_dts += p_track->i_pts_offset;
618
2.53M
    }
619
620
1.57G
    return i_dts;
621
1.57G
}
622
623
static stime_t MP4_GetChunkSamplesDuration( const mp4_chunk_t *p_chunk,
624
                                            uint32_t i_start_sample,
625
                                            uint32_t i_nb_samples )
626
5.13M
{
627
5.13M
    stime_t i_duration = 0;
628
629
    /* Forward to right index, and set remaining count in that index */
630
5.13M
    uint32_t i_index = 0;
631
5.13M
    uint32_t i_remain = 0;
632
5.13M
    for( uint32_t i = p_chunk->i_sample_first;
633
5.93M
         i<i_start_sample && i_index < p_chunk->i_entries_dts; )
634
4.63M
    {
635
4.63M
        if( i_start_sample - i >= p_chunk->p_sample_count_dts[i_index] )
636
801k
        {
637
801k
            i += p_chunk->p_sample_count_dts[i_index];
638
801k
            i_index++;
639
801k
        }
640
3.83M
        else
641
3.83M
        {
642
3.83M
            i_remain = i_start_sample - i;
643
3.83M
            break;
644
3.83M
        }
645
4.63M
    }
646
647
    /* Compute total duration from all samples from index */
648
5.64M
    while( i_nb_samples > 0 && i_index < p_chunk->i_entries_dts )
649
4.37M
    {
650
4.37M
        if( i_nb_samples >= p_chunk->p_sample_count_dts[i_index] - i_remain )
651
513k
        {
652
513k
            i_duration += (p_chunk->p_sample_count_dts[i_index] - i_remain) *
653
513k
                          (int64_t) p_chunk->p_sample_delta_dts[i_index];
654
513k
            i_nb_samples -= (p_chunk->p_sample_count_dts[i_index] - i_remain);
655
513k
            i_index++;
656
513k
            i_remain = 0;
657
513k
        }
658
3.85M
        else
659
3.85M
        {
660
3.85M
            i_duration += (stime_t)i_nb_samples * p_chunk->p_sample_delta_dts[i_index];
661
3.85M
            break;
662
3.85M
        }
663
4.37M
    }
664
665
5.13M
    return i_duration;
666
5.13M
}
667
668
static inline vlc_tick_t MP4_GetSamplesDuration( const mp4_track_t *p_track,
669
                                                 uint32_t i_nb_samples )
670
5.13M
{
671
5.13M
    stime_t i_duration = MP4_GetChunkSamplesDuration( &p_track->chunk[p_track->i_chunk],
672
5.13M
                                                      p_track->i_sample,
673
5.13M
                                                      i_nb_samples );
674
5.13M
    return MP4_rescale_mtime( i_duration, p_track->i_timescale );
675
5.13M
}
676
677
static inline vlc_tick_t MP4_GetMoviePTS(demux_sys_t *p_sys )
678
636M
{
679
636M
    return p_sys->i_nztime;
680
636M
}
681
682
static void LoadChapter( demux_t  *p_demux );
683
684
static int LoadInitFrag( demux_t *p_demux )
685
2.67k
{
686
2.67k
    demux_sys_t *p_sys = p_demux->p_sys;
687
688
    /* Load all boxes ( except raw data ) */
689
2.67k
    MP4_Box_t *p_root = MP4_BoxGetRoot( p_demux->s );
690
2.67k
    if( p_root == NULL || !MP4_BoxGet( p_root, "/moov" ) )
691
56
    {
692
56
        MP4_BoxFree( p_root );
693
56
        goto LoadInitFragError;
694
56
    }
695
696
2.61k
    p_sys->p_root = p_root;
697
698
2.61k
    return VLC_SUCCESS;
699
700
56
LoadInitFragError:
701
56
    msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
702
56
    return VLC_EGENERIC;
703
2.67k
}
704
705
static int CreateTracks( demux_t *p_demux, unsigned i_tracks )
706
2.58k
{
707
2.58k
    demux_sys_t *p_sys = p_demux->p_sys;
708
709
2.58k
    if( SIZE_MAX / i_tracks < sizeof(mp4_track_t) )
710
0
        return VLC_EGENERIC;
711
712
2.58k
    p_sys->track = vlc_alloc( i_tracks, sizeof(mp4_track_t)  );
713
2.58k
    if( p_sys->track == NULL )
714
0
        return VLC_ENOMEM;
715
2.58k
    p_sys->i_tracks = i_tracks;
716
717
6.50k
    for( unsigned i=0; i<i_tracks; i++ )
718
3.92k
    {
719
3.92k
        MP4_TrackInit( &p_sys->track[i],
720
3.92k
                       MP4_BoxGetVa( p_sys->p_root, "/moov/trak[%u]", i ) );
721
3.92k
    }
722
723
2.58k
    return VLC_SUCCESS;
724
2.58k
}
725
726
static block_t * MP4_CDP_Convert( block_t *p_block )
727
105
{
728
    /* FinalCut ST334-2 CDP put inside CC violation */
729
105
    if (p_block->i_buffer < 8 + 7)
730
0
        goto out;
731
732
105
    if(memcmp(&p_block->p_buffer[4], "ccdp", 4))
733
0
        goto out;
734
735
105
    uint_fast32_t ccdp_size = GetDWBE(p_block->p_buffer);
736
105
    if (ccdp_size > p_block->i_buffer || ccdp_size < 8)
737
99
        goto out;
738
739
6
    p_block->p_buffer += 8;
740
6
    p_block->i_buffer = ccdp_size - 8;
741
    /* Let cc.h handle extraction */
742
6
    cc_data_t cc;
743
6
    cc_Init(&cc);
744
6
    cc_Extract(&cc, CC_PAYLOAD_CDP, true, p_block->p_buffer, p_block->i_buffer);
745
6
    memcpy(p_block->p_buffer, cc.p_data, cc.i_data);
746
6
    p_block->i_buffer = cc.i_data;
747
748
105
out:
749
105
    return p_block;
750
6
}
751
752
static block_t * MP4_EIA608_Convert( block_t * p_block )
753
6.25k
{
754
    /* Rebuild codec data from encap */
755
6.25k
    block_t *p_newblock = NULL;
756
757
6.25k
    assert(p_block->i_buffer <= SSIZE_MAX);
758
    /* always need at least 10 bytes (atom size+header+1pair)*/
759
6.25k
    if (p_block->i_buffer < 8)
760
379
        goto out;
761
762
5.87k
    if(!memcmp(&p_block->p_buffer[4], "ccdp", 4))
763
105
        return MP4_CDP_Convert(p_block);
764
765
5.77k
    uint_fast32_t cdat_size = GetDWBE(p_block->p_buffer) - 8;
766
5.77k
    if (cdat_size > p_block->i_buffer)
767
5.61k
        goto out;
768
769
156
    const uint8_t *cdat = p_block->p_buffer + 8;
770
156
    if (memcmp(cdat - 4, "cdat", 4) != 0)
771
150
        goto out;
772
773
6
    p_block->p_buffer += cdat_size;
774
6
    p_block->i_buffer -= cdat_size;
775
6
    cdat_size &= ~1;
776
777
    /* cdt2 is optional */
778
6
    uint_fast32_t cdt2_size = 0;
779
6
    const uint8_t *cdt2 = NULL;
780
781
6
    if (p_block->i_buffer >= 8) {
782
6
        size_t size = GetDWBE(p_block->p_buffer) - 8;
783
784
6
        if (size <= p_block->i_buffer) {
785
3
            cdt2 = p_block->p_buffer + 8;
786
787
3
            if (memcmp(cdt2 - 4, "cdt2", 4) == 0)
788
0
                cdt2_size = size & ~1;
789
3
        }
790
6
    }
791
792
6
    p_newblock = block_Alloc((cdat_size + cdt2_size) / 2 * 3);
793
6
    if (unlikely(p_newblock == NULL))
794
0
        goto out;
795
796
6
    uint8_t *out = p_newblock->p_buffer;
797
798
105
    while (cdat_size > 0) {
799
99
         *(out++) = CC_PKT_BYTE0(0); /* cc1 == field 0 */
800
99
         *(out++) = *(cdat++);
801
99
         *(out++) = *(cdat++);
802
99
         cdat_size -= 2;
803
99
    }
804
805
6
    while (cdt2_size > 0) {
806
0
         *(out++) = CC_PKT_BYTE0(1); /* cc2 == field 1 */
807
0
         *(out++) = *(cdt2++);
808
0
         *(out++) = *(cdt2++);
809
0
         cdt2_size -= 2;
810
0
    }
811
812
6
    p_newblock->i_pts = p_block->i_dts;
813
6
    p_newblock->i_flags = BLOCK_FLAG_TYPE_P;
814
6.15k
out:
815
6.15k
    block_Release( p_block );
816
6.15k
    return p_newblock;
817
6
}
818
819
static uint32_t MP4_TrackGetRunSeq( mp4_track_t *p_track )
820
185M
{
821
185M
    if( p_track->i_chunk_count > 0 )
822
185M
        return p_track->chunk[p_track->i_chunk].i_virtual_run_number;
823
0
    return 0;
824
185M
}
825
826
/* Analyzes chunks to find max interleave length
827
 * sets flat flag if no interleaving is in use */
828
static void MP4_GetInterleaving( demux_t *p_demux, vlc_tick_t *pi_max_contiguous, bool *pb_flat )
829
0
{
830
0
    demux_sys_t *p_sys = p_demux->p_sys;
831
0
    *pi_max_contiguous = 0;
832
0
    *pb_flat = true;
833
834
    /* Find first recorded chunk */
835
0
    mp4_track_t *tk = NULL;
836
0
    uint64_t i_duration = 0;
837
0
    for( unsigned i=0; i < p_sys->i_tracks; i++ )
838
0
    {
839
0
        mp4_track_t *cur = &p_sys->track[i];
840
0
        if( !cur->i_chunk_count )
841
0
            continue;
842
843
0
        if( tk == NULL || cur->chunk[0].i_offset < tk->chunk[0].i_offset )
844
0
            tk = cur;
845
0
    }
846
847
0
    for( ; tk != NULL; )
848
0
    {
849
0
        i_duration += tk->chunk[tk->i_chunk].i_duration;
850
0
        tk->i_chunk++;
851
852
        /* Find next chunk in data order */
853
0
        mp4_track_t *nexttk = NULL;
854
0
        for( unsigned i=0; i < p_sys->i_tracks; i++ )
855
0
        {
856
0
            mp4_track_t *cur = &p_sys->track[i];
857
0
            if( cur->i_chunk == cur->i_chunk_count )
858
0
                continue;
859
860
0
            if( nexttk == NULL ||
861
0
                cur->chunk[cur->i_chunk].i_offset < nexttk->chunk[nexttk->i_chunk].i_offset )
862
0
                nexttk = cur;
863
0
        }
864
865
        /* copy previous run */
866
0
        if( nexttk && nexttk->i_chunk > 0 )
867
0
            nexttk->chunk[nexttk->i_chunk].i_virtual_run_number =
868
0
                    nexttk->chunk[nexttk->i_chunk - 1].i_virtual_run_number;
869
870
0
        if( tk != nexttk )
871
0
        {
872
0
            vlc_tick_t i_dur = MP4_rescale_mtime( i_duration, tk->i_timescale );
873
0
            if( i_dur > *pi_max_contiguous )
874
0
                *pi_max_contiguous = i_dur;
875
0
            i_duration = 0;
876
877
0
            if( tk->i_chunk != tk->i_chunk_count )
878
0
                *pb_flat = false;
879
880
0
            if( nexttk && nexttk->i_chunk > 0 ) /* new run number */
881
0
                nexttk->chunk[nexttk->i_chunk].i_virtual_run_number++;
882
0
        }
883
884
0
        tk = nexttk;
885
0
    }
886
887
    /* reset */
888
0
    for( unsigned i=0; i < p_sys->i_tracks; i++ )
889
0
        p_sys->track[i].i_chunk = 0;
890
0
}
891
892
static block_t * MP4_Block_Convert( demux_t *p_demux, const mp4_track_t *p_track, block_t *p_block )
893
5.13M
{
894
    /* might have some encap */
895
5.13M
    if( p_track->fmt.i_cat == SPU_ES )
896
1.80M
    {
897
1.80M
        switch( p_track->fmt.i_codec )
898
1.80M
        {
899
29.5k
            case VLC_CODEC_WEBVTT:
900
34.2k
            case VLC_CODEC_TTML:
901
37.7k
            case VLC_CODEC_QTXT:
902
84.6k
            case VLC_CODEC_TX3G:
903
1.73M
            case VLC_CODEC_SPU:
904
1.73M
            case VLC_CODEC_SUBT:
905
            /* accept as-is */
906
1.73M
            break;
907
5.42k
            case VLC_CODEC_CEA608:
908
6.25k
            case VLC_CODEC_CEA708:
909
6.25k
                p_block = MP4_EIA608_Convert( p_block );
910
6.25k
            break;
911
64.3k
        default:
912
64.3k
            p_block->i_buffer = 0;
913
64.3k
            break;
914
1.80M
        }
915
1.80M
    }
916
3.33M
    else if( p_track->fmt.i_codec == VLC_CODEC_AV1 )
917
1.43M
    {
918
1.43M
        p_block = AV1_Unpack_Sample( p_block );
919
1.43M
    }
920
1.90M
    else if( p_track->fmt.i_original_fourcc == ATOM_rrtp )
921
0
    {
922
0
        p_block = MP4_RTPHint_Convert( p_demux, p_block, p_track->fmt.i_codec );
923
0
    }
924
925
5.13M
    return p_block;
926
5.13M
}
927
928
static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
929
5.13M
{
930
5.13M
    demux_sys_t *p_sys = p_demux->p_sys;
931
932
5.13M
    p_block = MP4_Block_Convert( p_demux, p_track, p_block );
933
5.13M
    if( p_block == NULL )
934
6.14k
        return;
935
936
5.13M
    if ( p_track->i_chans_to_reorder )
937
0
    {
938
0
        aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
939
0
                             p_track->i_chans_to_reorder,
940
0
                             p_track->rgi_chans_reordering,
941
0
                             p_track->fmt.i_codec );
942
0
    }
943
944
5.13M
    p_block->i_flags |= p_track->i_block_flags;
945
5.13M
    if( p_track->i_next_block_flags )
946
0
    {
947
0
        p_block->i_flags |= p_track->i_next_block_flags;
948
0
        p_track->i_next_block_flags = 0;
949
0
    }
950
951
    /* ASF packets in mov */
952
5.13M
    if( p_track->p_asf )
953
0
    {
954
0
        p_sys->asfpacketsys.s = vlc_stream_MemoryNew( p_demux, p_block->p_buffer, p_block->i_buffer, true );
955
0
        if ( p_sys->asfpacketsys.s )
956
0
        {
957
0
            p_track->i_dts_backup = p_block->i_dts;
958
0
            p_track->i_pts_backup = p_block->i_pts;
959
            /* And demux it as ASF packet */
960
0
            uint64_t startpos;
961
0
            do
962
0
            {
963
0
                startpos = vlc_stream_Tell(p_sys->asfpacketsys.s);
964
0
                DemuxASFPacket( &p_sys->asfpacketsys,
965
0
                                p_block->i_buffer - startpos,
966
0
                                p_block->i_buffer - startpos,
967
0
                                0, p_block->i_buffer );
968
0
            } while( vlc_stream_Tell(p_sys->asfpacketsys.s) != p_block->i_buffer &&
969
0
                     vlc_stream_Tell(p_sys->asfpacketsys.s) != startpos );
970
0
            vlc_stream_Delete(p_sys->asfpacketsys.s);
971
0
        }
972
0
        block_Release(p_block);
973
0
    }
974
5.13M
    else
975
5.13M
        es_out_Send( p_demux->out, p_track->p_es, p_block );
976
5.13M
}
977
978
int  OpenHEIF ( vlc_object_t * );
979
void CloseHEIF( vlc_object_t * );
980
981
/*****************************************************************************
982
 * Open: check file and initializes MP4 structures
983
 *****************************************************************************/
984
static int Open( vlc_object_t * p_this )
985
5.23k
{
986
5.23k
    demux_t  *p_demux = (demux_t *)p_this;
987
5.23k
    demux_sys_t     *p_sys;
988
989
5.23k
    const uint8_t   *p_peek;
990
991
5.23k
    MP4_Box_t       *p_ftyp;
992
5.23k
    const MP4_Box_t *p_mvhd = NULL;
993
5.23k
    const MP4_Box_t *p_mvex = NULL;
994
995
5.23k
    bool      b_enabled_es;
996
997
    /* A little test to see if it could be a mp4 */
998
5.23k
    if( vlc_stream_Peek( p_demux->s, &p_peek, 12 ) < 12 ) return VLC_EGENERIC;
999
1000
5.23k
    switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
1001
5.23k
    {
1002
413
        case ATOM_moov:
1003
414
        case ATOM_foov:
1004
418
        case ATOM_moof:
1005
889
        case ATOM_mdat:
1006
890
        case ATOM_udta:
1007
893
        case ATOM_free:
1008
893
        case ATOM_skip:
1009
895
        case ATOM_wide:
1010
895
        case ATOM_uuid:
1011
895
        case VLC_FOURCC( 'p', 'n', 'o', 't' ):
1012
895
            break;
1013
1.81k
        case ATOM_ftyp:
1014
1.81k
        {
1015
            /* Early handle some brands */
1016
1.81k
            switch( VLC_FOURCC(p_peek[8], p_peek[9], p_peek[10], p_peek[11]) )
1017
1.81k
            {
1018
                /* HEIF pictures goes to heif demux */
1019
1
                case BRAND_heic:
1020
1
                case BRAND_heix:
1021
1
                case BRAND_mif1:
1022
1
                case BRAND_jpeg:
1023
9
                case BRAND_avci:
1024
33
                case BRAND_avif:
1025
                /* We don't yet support f4v, but avformat does. */
1026
33
                case BRAND_f4v:
1027
33
                    return VLC_EGENERIC;
1028
1.78k
                default:
1029
1.78k
                    break;
1030
1.81k
            }
1031
1.78k
            break;
1032
1.81k
        }
1033
2.52k
         default:
1034
2.52k
            return VLC_EGENERIC;
1035
5.23k
    }
1036
1037
    /* create our structure that will contains all data */
1038
2.67k
    p_sys = calloc( 1, sizeof( demux_sys_t ) );
1039
2.67k
    if ( !p_sys )
1040
0
        return VLC_EGENERIC;
1041
1042
    /* I need to seek */
1043
2.67k
    vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
1044
2.67k
    if( p_sys->b_seekable )
1045
2.67k
        vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
1046
1047
    /*Set exported functions */
1048
2.67k
    p_demux->pf_demux = Demux;
1049
2.67k
    p_demux->pf_control = Control;
1050
1051
2.67k
    p_sys->context.i_lastseqnumber = UINT32_MAX;
1052
2.67k
    p_sys->i_attachments = -1;
1053
2.67k
    p_sys->qt.f_replay_gain_norm = NAN;
1054
2.67k
    p_sys->qt.f_replay_gain_peak = NAN;
1055
1056
2.67k
    p_demux->p_sys = p_sys;
1057
1058
2.67k
    if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
1059
56
        goto error;
1060
1061
2.61k
    MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
1062
1063
2.61k
    if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
1064
1.74k
    {
1065
1.74k
        switch( BOXDATA(p_ftyp)->i_major_brand )
1066
1.74k
        {
1067
276
            case BRAND_isom:
1068
276
                msg_Dbg( p_demux,
1069
276
                         "ISO Media (isom) version %d.",
1070
276
                         BOXDATA(p_ftyp)->i_minor_version );
1071
276
                break;
1072
7
            case BRAND_3gp4:
1073
7
            case BRAND_3gp5:
1074
7
            case BRAND_3gp6:
1075
7
            case BRAND_3gp7:
1076
7
                msg_Dbg( p_demux, "3GPP Media Release: %4.4s",
1077
7
                         (char *)&BOXDATA(p_ftyp)->i_major_brand );
1078
7
                break;
1079
285
            case BRAND_qt__:
1080
285
                msg_Dbg( p_demux, "Apple QuickTime media" );
1081
285
                p_sys->b_quicktime = true;
1082
285
                break;
1083
130
            case BRAND_isml:
1084
130
                msg_Dbg( p_demux, "PIFF (= isml = fMP4) media" );
1085
130
                break;
1086
0
            case BRAND_dash:
1087
0
                msg_Dbg( p_demux, "DASH Stream" );
1088
0
                break;
1089
195
            case BRAND_M4A:
1090
195
                msg_Dbg( p_demux, "iTunes audio" );
1091
195
                if( var_InheritBool( p_demux, CFG_PREFIX"m4a-audioonly" ) )
1092
0
                    p_sys->hacks.es_cat_filter = AUDIO_ES;
1093
195
                break;
1094
856
            default:
1095
856
                msg_Dbg( p_demux,
1096
856
                         "unrecognized major media specification (%4.4s).",
1097
856
                          (char*)&BOXDATA(p_ftyp)->i_major_brand );
1098
856
                break;
1099
1.74k
        }
1100
        /* also lookup in compatibility list */
1101
7.28k
        for(uint32_t i=0; i<BOXDATA(p_ftyp)->i_compatible_brands_count; i++)
1102
5.53k
        {
1103
5.53k
            if (BOXDATA(p_ftyp)->i_compatible_brands[i] == BRAND_dash)
1104
82
            {
1105
82
                msg_Dbg( p_demux, "DASH Stream" );
1106
82
            }
1107
5.45k
            else if (BOXDATA(p_ftyp)->i_compatible_brands[i] == BRAND_smoo)
1108
35
            {
1109
35
                msg_Dbg( p_demux, "Handling VLC Smooth Stream" );
1110
35
            }
1111
5.53k
        }
1112
1.74k
    }
1113
870
    else
1114
870
    {
1115
870
        msg_Dbg( p_demux, "file type box missing (assuming ISO Media)" );
1116
870
    }
1117
1118
    /* the file need to have one moov box */
1119
2.61k
    p_sys->p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
1120
2.61k
    if( unlikely(!p_sys->p_moov) )
1121
0
    {
1122
0
        p_sys->p_moov = MP4_BoxGet( p_sys->p_root, "/foov" );
1123
0
        if( !p_sys->p_moov )
1124
0
        {
1125
0
            msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
1126
0
            goto error;
1127
0
        }
1128
        /* we have a free box as a moov, rename it */
1129
0
        p_sys->p_moov->i_type = ATOM_moov;
1130
0
    }
1131
1132
2.61k
    p_mvhd = MP4_BoxGet( p_sys->p_moov, "mvhd" );
1133
2.61k
    if( p_mvhd && BOXDATA(p_mvhd) && BOXDATA(p_mvhd)->i_timescale &&
1134
2.60k
        BOXDATA(p_mvhd)->i_duration < INT64_MAX )
1135
2.59k
    {
1136
2.59k
        p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
1137
2.59k
        p_sys->i_moov_duration =
1138
2.59k
        p_sys->i_duration =
1139
2.59k
        p_sys->i_cumulated_duration = BOXDATA(p_mvhd)->i_duration;
1140
2.59k
    }
1141
24
    else
1142
24
    {
1143
24
        msg_Warn( p_demux, "No valid mvhd found" );
1144
24
        goto error;
1145
24
    }
1146
1147
2.59k
    MP4_Box_t *p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" );
1148
2.59k
    if( p_rmra != NULL && p_demux->p_input_item != NULL )
1149
0
    {
1150
0
        int        i_count = MP4_BoxCount( p_rmra, "rmda" );
1151
0
        int        i;
1152
1153
0
        msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
1154
1155
0
        input_item_t *p_current = p_demux->p_input_item;
1156
1157
0
        input_item_node_t *p_subitems = input_item_node_Create( p_current );
1158
1159
0
        for( i = 0; i < i_count; i++ )
1160
0
        {
1161
0
            MP4_Box_t *p_rdrf = MP4_BoxGetVa( p_rmra, "rmda[%d]/rdrf", i );
1162
0
            char      *psz_ref;
1163
0
            uint32_t  i_ref_type;
1164
1165
0
            if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
1166
0
            {
1167
0
                continue;
1168
0
            }
1169
0
            i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
1170
1171
0
            msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
1172
0
                     psz_ref, (char*)&i_ref_type );
1173
1174
0
            if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
1175
0
            {
1176
0
                if( strstr( psz_ref, "qt5gateQT" ) )
1177
0
                {
1178
0
                    msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
1179
0
                    free( psz_ref );
1180
0
                    continue;
1181
0
                }
1182
0
                if( !strncmp( psz_ref, "http://", 7 ) ||
1183
0
                    !strncmp( psz_ref, "rtsp://", 7 ) )
1184
0
                {
1185
0
                    ;
1186
0
                }
1187
0
                else
1188
0
                {
1189
0
                    char *psz_absolute = vlc_uri_resolve( p_demux->psz_url,
1190
0
                                                          psz_ref );
1191
0
                    free( psz_ref );
1192
0
                    if( psz_absolute == NULL )
1193
0
                    {
1194
0
                        input_item_node_Delete( p_subitems );
1195
0
                        return VLC_ENOMEM;
1196
0
                    }
1197
0
                    psz_ref = psz_absolute;
1198
0
                }
1199
0
                msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
1200
0
                input_item_t *p_item = input_item_New( psz_ref, NULL );
1201
0
                input_item_node_AppendItem( p_subitems, p_item );
1202
0
                input_item_Release( p_item );
1203
0
            }
1204
0
            else
1205
0
            {
1206
0
                msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
1207
0
                         (char*)&BOXDATA(p_rdrf)->i_ref_type );
1208
0
            }
1209
0
            free( psz_ref );
1210
0
        }
1211
1212
        /* FIXME: create a stream_filter sub-module for this */
1213
0
        if (es_out_Control(p_demux->out, ES_OUT_POST_SUBNODE, p_subitems))
1214
0
            input_item_node_Delete(p_subitems);
1215
0
    }
1216
1217
2.59k
    if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
1218
0
    {
1219
0
        if( !p_rmra )
1220
0
        {
1221
0
            msg_Err( p_demux, "cannot find /moov/mvhd" );
1222
0
            goto error;
1223
0
        }
1224
0
        else
1225
0
        {
1226
0
            msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
1227
0
            p_demux->pf_demux = DemuxRef;
1228
0
            return VLC_SUCCESS;
1229
0
        }
1230
0
    }
1231
2.59k
    else
1232
2.59k
    {
1233
2.59k
        p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
1234
2.59k
        if( p_sys->i_timescale == 0 || p_sys->i_timescale > 0x10000000 )
1235
2
        {
1236
2
            msg_Err( p_this, "bad timescale %" PRIu32, p_sys->i_timescale );
1237
2
            goto error;
1238
2
        }
1239
2.59k
    }
1240
1241
2.59k
    const unsigned i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" );
1242
2.59k
    if( i_tracks < 1 )
1243
9
    {
1244
9
        msg_Err( p_demux, "cannot find any /moov/trak" );
1245
9
        goto error;
1246
9
    }
1247
2.58k
    msg_Dbg( p_demux, "found %u track%c", i_tracks, i_tracks ? 's':' ' );
1248
1249
    /* reject old monolithically embedded mpeg */
1250
2.58k
    if( i_tracks == 1 )
1251
1.74k
    {
1252
1.74k
        const MP4_Box_t *p_hdlr = MP4_BoxGet( p_sys->p_root, "/moov/trak/mdia/hdlr" );
1253
1.74k
        if( p_hdlr && BOXDATA(p_hdlr) )
1254
1.72k
        {
1255
1.72k
            switch( BOXDATA(p_hdlr)->i_handler_type )
1256
1.72k
            {
1257
0
                case HANDLER_m1v:
1258
0
                case HANDLER_m1s:
1259
0
                case HANDLER_mpeg:
1260
0
                    msg_Dbg( p_demux, "Raw MPEG/PS not supported, passing to ps demux" );
1261
0
                    goto error;
1262
1.72k
                default:
1263
1.72k
                    break;
1264
1.72k
            }
1265
1.72k
        }
1266
1.74k
    }
1267
1268
2.58k
    if( CreateTracks( p_demux, i_tracks ) != VLC_SUCCESS )
1269
0
        goto error;
1270
1271
    /* set referenced tracks and
1272
     * check that at least 1 stream is enabled */
1273
2.58k
    b_enabled_es = false;
1274
6.50k
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
1275
3.92k
    {
1276
3.92k
        MP4_Box_t *p_trak = MP4_BoxGetVa( p_sys->p_root, "/moov/trak[%u]", i );
1277
1278
        /* Enabled check as explained above */
1279
3.92k
        MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
1280
3.92k
        if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
1281
2.83k
            b_enabled_es = true;
1282
1283
        /* Referenced tracks checks */
1284
3.92k
        MP4_Box_t *p_tref = MP4_BoxGet( p_trak, "tref" );
1285
3.92k
        if(!p_tref)
1286
3.38k
            continue;
1287
1288
1.07k
        for( MP4_Box_t *p_refbox = p_tref->p_first; p_refbox; p_refbox = p_refbox->p_next )
1289
538
        {
1290
538
            const MP4_Box_data_trak_reference_t *refdata = p_refbox->data.p_track_reference;
1291
538
            if(unlikely(!refdata))
1292
0
                continue;
1293
1294
            /* Assign reference types */
1295
10.1k
            for( uint32_t j = 0; j < refdata->i_entry_count; j++ )
1296
9.58k
            {
1297
9.58k
                mp4_track_t *reftk = MP4_GetTrackByTrackID(p_demux, refdata->i_track_ID[j]);
1298
9.58k
                if(reftk)
1299
832
                {
1300
832
                    msg_Dbg( p_demux, "track 0x%x refs track 0x%x for %4.4s", i,
1301
832
                             refdata->i_track_ID[j], (const char *) &p_refbox->i_type );
1302
832
                    reftk->i_use_flags |= MP4_reftypeToFlag( p_refbox->i_type );
1303
832
                }
1304
9.58k
            }
1305
538
        }
1306
536
    }
1307
1308
    /* Set and store metadata */
1309
2.58k
    if( (p_sys->p_meta = vlc_meta_New()) )
1310
2.58k
        MP4_LoadMeta( p_sys, p_sys->p_meta );
1311
1312
    /* now process each track and extract all useful information */
1313
6.50k
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
1314
3.92k
    {
1315
3.92k
        const MP4_Box_t *p_trakbox = MP4_BoxGetVa( p_sys->p_root, "/moov/trak[%u]", i );
1316
3.92k
        MP4_TrackSetup( p_demux, &p_sys->track[i], p_trakbox, true, !b_enabled_es );
1317
3.92k
        mp4_track_t *p_track = &p_sys->track[i];
1318
1319
3.92k
        if( p_track->b_ok && ! MP4_isMetadata(p_track) )
1320
2.99k
        {
1321
2.99k
            const char *psz_cat;
1322
2.99k
            switch( p_track->fmt.i_cat )
1323
2.99k
            {
1324
1.24k
                case( VIDEO_ES ):
1325
1.24k
                    psz_cat = "video";
1326
1.24k
                    break;
1327
1.00k
                case( AUDIO_ES ):
1328
1.00k
                    psz_cat = "audio";
1329
1.00k
                    break;
1330
558
                case( SPU_ES ):
1331
558
                    psz_cat = "subtitle";
1332
558
                    break;
1333
1334
175
                default:
1335
175
                    psz_cat = "unknown";
1336
175
                    break;
1337
2.99k
            }
1338
1339
2.99k
            msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
1340
2.99k
                     p_track->i_track_ID, psz_cat,
1341
2.99k
                     p_track->b_enable ? "enable":"disable",
1342
2.99k
                     p_track->fmt.psz_language ?
1343
2.99k
                     p_track->fmt.psz_language : "undef" );
1344
2.99k
        }
1345
935
        else if( p_track->b_ok && (p_track->i_use_flags & USEAS_CHAPTERS) )
1346
0
        {
1347
0
            msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
1348
0
                     p_track->i_track_ID,
1349
0
                     p_track->fmt.psz_language ?
1350
0
                     p_track->fmt.psz_language : "undef" );
1351
0
        }
1352
935
        else
1353
935
        {
1354
935
            msg_Dbg( p_demux, "ignoring track[Id 0x%x] %d refs %x",
1355
935
                     p_track->i_track_ID, p_track->b_ok, p_track->i_use_flags );
1356
935
        }
1357
1358
3.92k
        if( p_track->b_ok && p_track->i_cts_shift ) /* PTS shift handling pass 1 */
1359
201
        {
1360
201
            p_track->i_pts_offset = MP4_rescale_mtime( p_track->i_cts_shift,
1361
201
                                                       p_track->i_timescale );
1362
201
            if( p_track->i_pts_offset > p_sys->i_max_pts_offset )
1363
145
                p_sys->i_max_pts_offset = p_track->i_pts_offset;
1364
201
        }
1365
3.92k
    }
1366
1367
6.50k
    for( unsigned i = 0; i < p_sys->i_tracks; i++ ) /* PTS shift handling pass 2 */
1368
3.92k
    {
1369
3.92k
        mp4_track_t *p_track = &p_sys->track[i];
1370
3.92k
        if( !p_track->b_ok )
1371
917
            continue;
1372
3.00k
        p_track->i_pts_offset = p_sys->i_max_pts_offset - p_track->i_pts_offset;
1373
3.00k
    }
1374
1375
2.58k
    p_mvex = MP4_BoxGet( p_sys->p_moov, "mvex" );
1376
2.58k
    if( p_mvex != NULL )
1377
233
    {
1378
233
        const MP4_Box_t *p_mehd = MP4_BoxGet( p_mvex, "mehd");
1379
233
        if ( p_mehd && BOXDATA(p_mehd) )
1380
183
        {
1381
183
            if( BOXDATA(p_mehd)->i_fragment_duration > p_sys->i_duration )
1382
71
            {
1383
71
                p_sys->b_fragmented = true;
1384
71
                p_sys->i_duration = BOXDATA(p_mehd)->i_fragment_duration;
1385
71
            }
1386
183
        }
1387
1388
233
        const MP4_Box_t *p_sidx = MP4_BoxGet( p_sys->p_root, "sidx");
1389
233
        if( p_sidx )
1390
65
            p_sys->b_fragmented = true;
1391
1392
233
        if ( p_sys->b_seekable )
1393
233
        {
1394
233
            if( !p_sys->b_fragmented /* as unknown */ )
1395
155
            {
1396
                /* Probe remaining to check if there's really fragments
1397
                   or if that file is just ready to append fragments */
1398
155
                ProbeFragments( p_demux, (p_sys->i_duration == 0), &p_sys->b_fragmented );
1399
155
            }
1400
1401
233
            if( vlc_stream_Seek( p_demux->s, p_sys->p_moov->i_pos ) != VLC_SUCCESS )
1402
0
                goto error;
1403
233
        }
1404
0
        else /* Handle as fragmented by default as we can't see moof */
1405
0
        {
1406
0
            p_sys->context.p_fragment_atom = p_sys->p_moov;
1407
0
            p_sys->context.i_current_box_type = ATOM_moov;
1408
0
            p_sys->b_fragmented = true;
1409
0
        }
1410
233
    }
1411
1412
2.58k
    if( p_sys->b_fragmented )
1413
211
    {
1414
211
        p_demux->pf_demux = DemuxFrag;
1415
211
        msg_Dbg( p_demux, "Set Fragmented demux mode" );
1416
211
    }
1417
1418
2.58k
    if( !p_sys->b_seekable && p_demux->pf_demux == Demux )
1419
0
    {
1420
0
        msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
1421
0
        goto error;
1422
0
    }
1423
1424
2.58k
    if( p_sys->i_tracks > 1 && !p_sys->b_fastseekable )
1425
0
    {
1426
0
        vlc_tick_t i_max_continuity;
1427
0
        bool b_flat;
1428
0
        MP4_GetInterleaving( p_demux, &i_max_continuity, &b_flat );
1429
0
        if( b_flat )
1430
0
            msg_Warn( p_demux, "that media doesn't look interleaved, will need to seek");
1431
0
        else if( i_max_continuity > DEMUX_TRACK_MAX_PRELOAD )
1432
0
            msg_Warn( p_demux, "that media doesn't look properly interleaved, will need to seek");
1433
0
    }
1434
1435
    /* */
1436
2.58k
    LoadChapter( p_demux );
1437
1438
2.58k
    p_sys->asfpacketsys.priv = p_demux;
1439
2.58k
    p_sys->asfpacketsys.s = p_demux->s;
1440
2.58k
    p_sys->asfpacketsys.logger = p_demux->obj.logger;
1441
2.58k
    p_sys->asfpacketsys.pi_preroll = &p_sys->i_preroll;
1442
2.58k
    p_sys->asfpacketsys.pi_preroll_start = &p_sys->i_preroll_start;
1443
2.58k
    p_sys->asfpacketsys.b_deduplicate = true;
1444
2.58k
    p_sys->asfpacketsys.b_can_hold_multiple_packets = true;
1445
2.58k
    p_sys->asfpacketsys.pf_doskip = NULL;
1446
2.58k
    p_sys->asfpacketsys.pf_send = MP4ASF_Send;
1447
2.58k
    p_sys->asfpacketsys.pf_gettrackinfo = MP4ASF_GetTrackInfo;
1448
2.58k
    p_sys->asfpacketsys.pf_updatetime = NULL;
1449
2.58k
    p_sys->asfpacketsys.pf_setaspectratio = NULL;
1450
1451
2.58k
    p_sys->hacks.es_cat_filter = UNKNOWN_ES;
1452
1453
2.58k
    return VLC_SUCCESS;
1454
1455
91
error:
1456
91
    if( vlc_stream_Tell( p_demux->s ) > 0 )
1457
91
    {
1458
91
        if( vlc_stream_Seek( p_demux->s, 0 ) != VLC_SUCCESS )
1459
91
            msg_Warn( p_demux, "Can't reset stream position from probing" );
1460
91
    }
1461
1462
91
    Close( p_this );
1463
1464
91
    return VLC_EGENERIC;
1465
2.58k
}
1466
1467
const unsigned int SAMPLEHEADERSIZE = 4;
1468
const unsigned int RTPPACKETSIZE = 12;
1469
const unsigned int CONSTRUCTORSIZE = 16;
1470
1471
/*******************************************************************************
1472
 * MP4_RTPHintToFrame: converts RTP Reception Hint Track sample to H.264 frame
1473
 *******************************************************************************/
1474
static block_t * MP4_RTPHintToFrame( demux_t *p_demux, block_t *p_block, uint32_t packetcount )
1475
0
{
1476
0
    uint8_t *p_slice = p_block->p_buffer + SAMPLEHEADERSIZE;
1477
0
    block_t *p_newblock = NULL;
1478
0
    size_t i_payload = 0;
1479
1480
0
    if( p_block->i_buffer < SAMPLEHEADERSIZE + RTPPACKETSIZE + CONSTRUCTORSIZE )
1481
0
    {
1482
0
        msg_Err( p_demux, "Sample not large enough for necessary structs");
1483
0
        block_Release( p_block );
1484
0
        return NULL;
1485
0
    }
1486
1487
0
    for( uint32_t i = 0; i < packetcount; ++i )
1488
0
    {
1489
0
        if( (size_t)(p_slice - p_block->p_buffer) + RTPPACKETSIZE + CONSTRUCTORSIZE > p_block->i_buffer )
1490
0
            goto error;
1491
1492
        /* skip RTP header in sample. Could be used to detect packet losses */
1493
0
        p_slice += RTPPACKETSIZE;
1494
1495
0
        mp4_rtpsampleconstructor_t sample_cons;
1496
1497
0
        sample_cons.type =                      p_slice[0];
1498
0
        sample_cons.trackrefindex =             p_slice[1];
1499
0
        sample_cons.length =          GetWBE(  &p_slice[2] );
1500
0
        sample_cons.samplenumber =    GetDWBE( &p_slice[4] );
1501
0
        sample_cons.sampleoffset =    GetDWBE( &p_slice[8] );
1502
0
        sample_cons.bytesperblock =   GetWBE(  &p_slice[12] );
1503
0
        sample_cons.samplesperblock = GetWBE(  &p_slice[14] );
1504
1505
        /* skip packet constructor */
1506
0
        p_slice += CONSTRUCTORSIZE;
1507
1508
        /* check that is RTPsampleconstructor, referencing itself and no weird audio stuff */
1509
0
        if( sample_cons.type != 2||sample_cons.trackrefindex != -1
1510
0
            ||sample_cons.samplesperblock != 1||sample_cons.bytesperblock != 1 )
1511
0
        {
1512
0
            msg_Err(p_demux, "Unhandled constructor in RTP Reception Hint Track. Type:%u", sample_cons.type);
1513
0
            goto error;
1514
0
        }
1515
1516
        /* slice doesn't fit in buffer */
1517
0
        if( sample_cons.sampleoffset + sample_cons.length > p_block->i_buffer)
1518
0
        {
1519
0
            msg_Err(p_demux, "Sample buffer is smaller than sample" );
1520
0
            goto error;
1521
0
        }
1522
1523
0
        block_t *p_realloc = ( p_newblock ) ?
1524
0
                             block_Realloc( p_newblock, 0, i_payload + sample_cons.length + 4 ):
1525
0
                             block_Alloc( i_payload + sample_cons.length + 4 );
1526
0
        if( !p_realloc )
1527
0
            goto error;
1528
1529
0
        p_newblock = p_realloc;
1530
0
        uint8_t *p_dst = &p_newblock->p_buffer[i_payload];
1531
1532
0
        const uint8_t* p_src = p_block->p_buffer + sample_cons.sampleoffset;
1533
0
        uint8_t i_type = (*p_src) & ((1<<5)-1);
1534
1535
0
        const uint8_t synccode[4] = { 0, 0, 0, 1 };
1536
0
        if( memcmp( p_src, synccode, 4 ) )
1537
0
        {
1538
0
            if( i_type == 7 || i_type == 8 )
1539
0
                *p_dst++=0;
1540
1541
0
            p_dst[0] = 0;
1542
0
            p_dst[1] = 0;
1543
0
            p_dst[2] = 1;
1544
0
            p_dst += 3;
1545
0
        }
1546
1547
0
        memcpy( p_dst, p_src, sample_cons.length );
1548
0
        p_dst += sample_cons.length;
1549
1550
0
        i_payload = p_dst - p_newblock->p_buffer;
1551
0
    }
1552
1553
0
    block_Release( p_block );
1554
0
    if( p_newblock )
1555
0
        p_newblock->i_buffer = i_payload;
1556
0
    return p_newblock;
1557
1558
0
error:
1559
0
    block_Release( p_block );
1560
0
    if( p_newblock )
1561
0
        block_Release( p_newblock );
1562
0
    return NULL;
1563
0
}
1564
1565
/* RTP Reception Hint Track */
1566
static block_t * MP4_RTPHint_Convert( demux_t *p_demux, block_t *p_block, vlc_fourcc_t i_codec )
1567
0
{
1568
0
    block_t *p_converted = NULL;
1569
0
    if( p_block->i_buffer < 2 )
1570
0
    {
1571
0
        block_Release( p_block );
1572
0
        return NULL;
1573
0
    }
1574
1575
    /* number of RTP packets contained in this sample */
1576
0
    const uint16_t i_packets = GetWBE( p_block->p_buffer );
1577
0
    if( i_packets <= 1 || i_codec != VLC_CODEC_H264 )
1578
0
    {
1579
0
        const size_t i_skip = SAMPLEHEADERSIZE + i_packets * ( RTPPACKETSIZE + CONSTRUCTORSIZE );
1580
0
        if( i_packets == 1 && i_skip < p_block->i_buffer )
1581
0
        {
1582
0
            p_block->p_buffer += i_skip;
1583
0
            p_converted = p_block;
1584
0
        }
1585
0
        else
1586
0
        {
1587
0
            block_Release( p_block );
1588
0
        }
1589
0
    }
1590
0
    else
1591
0
    {
1592
0
        p_converted = MP4_RTPHintToFrame( p_demux, p_block, i_packets );
1593
0
    }
1594
1595
0
    return p_converted;
1596
0
}
1597
1598
static uint64_t OverflowCheck( demux_t *p_demux, mp4_track_t *tk,
1599
                               uint64_t i_readpos, uint64_t i_samplessize )
1600
180M
{
1601
180M
    demux_sys_t *p_sys = p_demux->p_sys;
1602
180M
    if( !p_sys->b_seekable && p_sys->b_fragmented &&
1603
0
         p_sys->context.i_post_mdat_offset )
1604
0
    {
1605
        /* avoid breaking non seekable demux */
1606
0
        if( i_readpos + i_samplessize > p_sys->context.i_post_mdat_offset )
1607
0
        {
1608
0
            msg_Err(p_demux, "Broken file. track[0x%x] "
1609
0
                             "Sample @%" PRIu64 " overflowing "
1610
0
                             "parent mdat by %" PRIu64,
1611
0
                    tk->i_track_ID, i_readpos,
1612
0
                    i_readpos + i_samplessize - p_sys->context.i_post_mdat_offset );
1613
0
            i_samplessize = p_sys->context.i_post_mdat_offset - i_readpos;
1614
0
        }
1615
0
    }
1616
180M
    return i_samplessize;
1617
180M
}
1618
1619
/*****************************************************************************
1620
 * Demux: read packet and send them to decoders
1621
 *****************************************************************************
1622
 * TODO check for newly selected track (ie audio upt to now )
1623
 *****************************************************************************/
1624
static int DemuxTrack( demux_t *p_demux, mp4_track_t *tk, uint64_t i_readpos,
1625
                       vlc_tick_t i_max_preload )
1626
179M
{
1627
179M
    demux_sys_t *p_sys = p_demux->p_sys;
1628
179M
    uint32_t i_nb_samples = 0;
1629
179M
    uint32_t i_samplessize = 0;
1630
1631
179M
    if( !tk->b_ok || tk->i_sample >= tk->i_sample_count )
1632
0
        return VLC_DEMUXER_EOS;
1633
1634
179M
    if( tk->i_use_flags & USEAS_CHAPTERS )
1635
0
        return VLC_DEMUXER_SUCCESS;
1636
1637
179M
    uint32_t i_run_seq = MP4_TrackGetRunSeq( tk );
1638
179M
    vlc_tick_t i_current_nzpts;
1639
179M
    vlc_tick_t i_current_nzdts = MP4_TrackGetDTSPTS( p_demux, tk, &i_current_nzpts );
1640
179M
    const vlc_tick_t i_demux_max_nzdts =i_max_preload < INVALID_PRELOAD
1641
179M
                                    ? i_current_nzdts + i_max_preload
1642
179M
                                    : VLC_TICK_MAX;
1643
1644
185M
    for( ; i_demux_max_nzdts >= i_current_nzdts; )
1645
180M
    {
1646
180M
        if( tk->i_sample >= tk->i_sample_count )
1647
0
            return VLC_DEMUXER_EOS;
1648
1649
#if 0
1650
        msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, tk->i_track_ID,
1651
                 MP4_TrackGetDTSPTS( p_demux, tk, NULL ),
1652
                 MP4_GetMoviePTS( p_demux->p_sys ), i_readpos );
1653
#endif
1654
1655
180M
        i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
1656
180M
        if( i_samplessize > 0 )
1657
180M
        {
1658
180M
            block_t *p_block;
1659
1660
180M
            if( vlc_stream_Tell( p_demux->s ) != i_readpos )
1661
747k
            {
1662
747k
                if( MP4_Seek( p_demux->s, i_readpos ) != VLC_SUCCESS )
1663
0
                {
1664
0
                    msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1665
0
                                       ": Failed to seek to %"PRIu64,
1666
0
                              tk->i_track_ID, i_readpos );
1667
0
                    MP4_TrackSelect( p_demux, tk, false );
1668
0
                    goto end;
1669
0
                }
1670
747k
            }
1671
1672
180M
            i_samplessize = OverflowCheck( p_demux, tk, i_readpos, i_samplessize );
1673
1674
            /* now read pes */
1675
180M
            if( !(p_block = vlc_stream_Block( p_demux->s, i_samplessize )) )
1676
175M
            {
1677
175M
                msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1678
175M
                                   ": Failed to read %d bytes sample at %"PRIu64,
1679
175M
                          tk->i_track_ID, i_samplessize, i_readpos );
1680
175M
                MP4_TrackSelect( p_demux, tk, false );
1681
175M
                goto end;
1682
175M
            }
1683
1684
            /* !important! Ensure clock is set before sending data */
1685
5.13M
            if( p_sys->i_pcr == VLC_TICK_INVALID )
1686
1.97k
            {
1687
1.97k
                es_out_SetPCR( p_demux->out, VLC_TICK_0 + i_current_nzdts );
1688
1.97k
                p_sys->i_pcr = VLC_TICK_0 + i_current_nzdts;
1689
1.97k
            }
1690
1691
            /* dts */
1692
5.13M
            p_block->i_dts = VLC_TICK_0 + i_current_nzdts;
1693
            /* pts */
1694
5.13M
            p_block->i_pts = i_current_nzpts != INVALID_PTS
1695
5.13M
                           ? VLC_TICK_0 + i_current_nzpts
1696
5.13M
                           : VLC_TICK_INVALID;
1697
1698
5.13M
            p_block->i_length = MP4_GetSamplesDuration( tk, i_nb_samples );
1699
1700
5.13M
            if ( tk->fmt.i_codec == VLC_CODEC_APV )
1701
0
            {
1702
                // the APU are preceeded by 4 bytes containing the size of the data
1703
                // this is not used by decoder like libavcodec or openapv.
1704
0
                p_block->p_buffer += 4;
1705
0
                p_block->i_buffer -= 4;
1706
0
            }
1707
1708
5.13M
            MP4_Block_Send( p_demux, tk, p_block );
1709
5.13M
        }
1710
1711
        /* Next sample */
1712
5.13M
        if ( i_nb_samples && /* sample size could be 0, need to go fwd. see return */
1713
5.13M
             MP4_TrackNextSample( p_demux, tk, i_nb_samples ) )
1714
690
            goto end;
1715
1716
5.13M
        uint32_t i_next_run_seq = MP4_TrackGetRunSeq( tk );
1717
5.13M
        if( i_next_run_seq != i_run_seq )
1718
0
            break;
1719
1720
5.13M
        i_current_nzdts = MP4_TrackGetDTSPTS( p_demux, tk, &i_current_nzpts );
1721
5.13M
        i_readpos = MP4_TrackGetPos( tk );
1722
5.13M
    }
1723
1724
4.31M
    return VLC_DEMUXER_SUCCESS;
1725
1726
175M
end:
1727
175M
    return VLC_DEMUXER_EGENERIC;
1728
179M
}
1729
1730
static int DemuxMoov( demux_t *p_demux )
1731
409M
{
1732
409M
    demux_sys_t *p_sys = p_demux->p_sys;
1733
409M
    unsigned int i_track;
1734
1735
    /* check for newly selected/unselected track */
1736
1.23G
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1737
828M
    {
1738
828M
        mp4_track_t *tk = &p_sys->track[i_track];
1739
828M
        bool b = true;
1740
1741
828M
        if( !tk->b_ok || MP4_isMetadata( tk ) ||
1742
627M
            ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
1743
201M
        {
1744
201M
            continue;
1745
201M
        }
1746
1747
626M
        if( p_sys->b_seekable )
1748
626M
            es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1749
1750
626M
        if( tk->b_selected && !b )
1751
0
        {
1752
0
            MP4_TrackSelect( p_demux, tk, false );
1753
0
        }
1754
626M
        else if( !tk->b_selected && b)
1755
216M
        {
1756
216M
            MP4_TrackSeek( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
1757
216M
        }
1758
626M
    }
1759
1760
409M
    const vlc_tick_t i_nztime = MP4_GetMoviePTS( p_sys );
1761
1762
    /* We demux/set pcr, even without selected tracks, (empty edits, ...) */
1763
409M
    if( p_sys->i_pcr != VLC_TICK_INVALID /* not after a seek */ )
1764
409M
    {
1765
409M
        bool b_eof = true;
1766
1.23G
        for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1767
827M
        {
1768
827M
            mp4_track_t *tk = &p_sys->track[i_track];
1769
827M
            if( !tk->b_ok || MP4_isMetadata( tk ) || tk->i_sample >= tk->i_sample_count )
1770
201M
                continue;
1771
            /* Test for EOF on each track (samples count, edit list) */
1772
625M
            b_eof &= ( i_nztime > MP4_TrackGetDTSPTS( p_demux, tk, NULL ) );
1773
625M
        }
1774
409M
        if( b_eof )
1775
0
            return VLC_DEMUXER_EOS;
1776
409M
    }
1777
1778
409M
    const vlc_tick_t i_max_preload = ( p_sys->b_fastseekable ) ? 0 : ( p_sys->b_seekable ) ? DEMUX_TRACK_MAX_PRELOAD : INVALID_PRELOAD;
1779
409M
    int i_status;
1780
    /* demux up to increment amount of data on every track, or just set pcr if empty data */
1781
409M
    for( ;; )
1782
589M
    {
1783
589M
        mp4_track_t *tk = NULL;
1784
589M
        i_status = VLC_DEMUXER_EOS;
1785
1786
        /* First pass, find any track within our target increment, ordered by position */
1787
1.95G
        for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1788
1.36G
        {
1789
1.36G
            mp4_track_t *tk_tmp = &p_sys->track[i_track];
1790
1.36G
            if( !tk_tmp->b_ok || MP4_isMetadata( tk_tmp ) ||
1791
984M
                tk_tmp->i_sample >= tk_tmp->i_sample_count ||
1792
983M
                (!tk_tmp->b_selected && p_sys->b_seekable) )
1793
595M
                continue;
1794
1795
            /* At least still have data to demux on this or next turns */
1796
766M
            i_status = VLC_DEMUXER_SUCCESS;
1797
1798
766M
            if ( MP4_TrackGetDTSPTS( p_demux, tk_tmp, NULL ) <= i_nztime + DEMUX_INCREMENT )
1799
180M
            {
1800
180M
                if( tk == NULL || MP4_TrackGetPos( tk_tmp ) < MP4_TrackGetPos( tk ) )
1801
179M
                    tk = tk_tmp;
1802
180M
            }
1803
766M
        }
1804
1805
589M
        if( tk )
1806
179M
        {
1807
            /* Second pass, refine and find any best candidate having a chunk pos closer than
1808
             * current candidate (avoids seeks when increment falls between the 2) from
1809
             * current position, but within extended interleave time */
1810
179M
            for( i_track = 0; i_max_preload != 0 && i_track < p_sys->i_tracks; i_track++ )
1811
0
            {
1812
0
                mp4_track_t *tk_tmp = &p_sys->track[i_track];
1813
0
                if( tk_tmp == tk ||
1814
0
                    !tk_tmp->b_ok || MP4_isMetadata( tk_tmp ) ||
1815
0
                   (!tk_tmp->b_selected && p_sys->b_seekable) ||
1816
0
                    tk_tmp->i_sample >= tk_tmp->i_sample_count )
1817
0
                    continue;
1818
1819
0
                vlc_tick_t i_nzdts = MP4_TrackGetDTSPTS( p_demux, tk_tmp, NULL );
1820
0
                if ( i_nzdts <= i_nztime + DEMUX_TRACK_MAX_PRELOAD )
1821
0
                {
1822
                    /* Found a better candidate to avoid seeking */
1823
0
                    if( MP4_TrackGetPos( tk_tmp ) < MP4_TrackGetPos( tk ) )
1824
0
                        tk = tk_tmp;
1825
                    /* Note: previous candidate will be repicked on next loop */
1826
0
                }
1827
0
            }
1828
1829
179M
            uint64_t i_pos = MP4_TrackGetPos( tk );
1830
179M
            int i_ret = DemuxTrack( p_demux, tk, i_pos, i_max_preload );
1831
1832
179M
            if( i_ret == VLC_DEMUXER_SUCCESS )
1833
4.31M
                i_status = VLC_DEMUXER_SUCCESS;
1834
179M
        }
1835
1836
589M
        if( i_status != VLC_DEMUXER_SUCCESS || !tk )
1837
409M
            break;
1838
589M
    }
1839
1840
409M
    p_sys->i_nztime += DEMUX_INCREMENT;
1841
409M
    if( p_sys->i_pcr != VLC_TICK_INVALID )
1842
409M
    {
1843
409M
        p_sys->i_pcr = VLC_TICK_0 + p_sys->i_nztime;
1844
409M
        es_out_SetPCR( p_demux->out, p_sys->i_pcr );
1845
409M
    }
1846
1847
    /* */
1848
409M
    MP4_UpdateSeekpoint( p_demux, i_nztime + DEMUX_INCREMENT );
1849
1850
409M
    return i_status;
1851
409M
}
1852
1853
static int Demux( demux_t *p_demux )
1854
409M
{
1855
409M
    demux_sys_t *p_sys = p_demux->p_sys;
1856
1857
409M
    assert( ! p_sys->b_fragmented );
1858
1859
409M
    int i_status = DemuxMoov( p_demux );
1860
1861
409M
    if( i_status == VLC_DEMUXER_EOS )
1862
2.37k
        i_status = VLC_DEMUXER_EOF;
1863
1864
409M
    return i_status;
1865
409M
}
1866
1867
static void MP4_UpdateSeekpoint( demux_t *p_demux, vlc_tick_t i_time )
1868
409M
{
1869
409M
    demux_sys_t *p_sys = p_demux->p_sys;
1870
409M
    int i;
1871
409M
    if( !p_sys->p_title )
1872
409M
        return;
1873
216
    for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
1874
216
    {
1875
216
        if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
1876
216
            break;
1877
216
    }
1878
216
    i--;
1879
1880
216
    if( i != p_sys->i_seekpoint && i >= 0 )
1881
0
    {
1882
0
        p_sys->i_seekpoint = i;
1883
0
        p_sys->seekpoint_changed = true;
1884
0
    }
1885
216
}
1886
/*****************************************************************************
1887
 * Seek: Go to i_date
1888
******************************************************************************/
1889
static int Seek( demux_t *p_demux, vlc_tick_t i_date, bool b_accurate )
1890
0
{
1891
0
    demux_sys_t *p_sys = p_demux->p_sys;
1892
0
    unsigned int i_track;
1893
1894
    /* Now for each stream try to go to this time */
1895
0
    vlc_tick_t i_start = i_date;
1896
0
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1897
0
    {
1898
0
        mp4_track_t *tk = &p_sys->track[i_track];
1899
        /* FIXME: we should find the lowest time from tracks with indexes.
1900
           considering only video for now */
1901
0
        if( tk->fmt.i_cat != VIDEO_ES || MP4_isMetadata( tk ) || !tk->b_ok )
1902
0
            continue;
1903
0
        if( MP4_TrackSeek( p_demux, tk, i_date ) == VLC_SUCCESS )
1904
0
        {
1905
0
            vlc_tick_t i_seeked = MP4_TrackGetDTSPTS( p_demux, tk, NULL );
1906
0
            if( i_seeked < i_start )
1907
0
                i_start = i_seeked;
1908
0
        }
1909
0
    }
1910
1911
0
    msg_Dbg( p_demux, "seeking with %"PRId64 "ms %s to %"PRId64,
1912
0
             MS_FROM_VLC_TICK(i_date - i_start),
1913
0
            !b_accurate ? "alignment" : "preroll (use input-fast-seek to avoid)", i_date );
1914
1915
0
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1916
0
    {
1917
0
        mp4_track_t *tk = &p_sys->track[i_track];
1918
0
        tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
1919
0
        if( tk->fmt.i_cat == VIDEO_ES || !tk->b_ok )
1920
0
            continue;
1921
0
        MP4_TrackSeek( p_demux, tk, i_start );
1922
0
    }
1923
1924
0
    MP4_UpdateSeekpoint( p_demux, i_date );
1925
0
    MP4ASF_ResetFrames( p_sys );
1926
    /* update global time */
1927
0
    p_sys->i_nztime = i_start;
1928
0
    p_sys->i_pcr  = VLC_TICK_INVALID;
1929
1930
0
    if( b_accurate )
1931
0
        es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1932
1933
0
    return VLC_SUCCESS;
1934
0
}
1935
1936
static int FragPrepareChunk( demux_t *p_demux, MP4_Box_t *p_moof,
1937
                             MP4_Box_t *p_sidx, stime_t i_moof_time, bool b_discontinuity )
1938
429
{
1939
429
    demux_sys_t *p_sys = p_demux->p_sys;
1940
1941
429
    if( b_discontinuity )
1942
299
    {
1943
817
        for( unsigned i=0; i<p_sys->i_tracks; i++ )
1944
518
            p_sys->track[i].context.b_resync_time_offset = true;
1945
299
    }
1946
1947
429
    if( FragCreateTrunIndex( p_demux, p_moof, p_sidx, i_moof_time ) == VLC_SUCCESS )
1948
429
    {
1949
1.15k
        for( unsigned i=0; i<p_sys->i_tracks; i++ )
1950
722
        {
1951
722
            mp4_track_t *p_track = &p_sys->track[i];
1952
722
            if( p_track->context.runs.i_count )
1953
291
            {
1954
291
                const mp4_run_t *p_run = &p_track->context.runs.p_array[0];
1955
291
                p_track->context.i_trun_sample_pos = p_run->i_offset;
1956
291
                p_track->context.i_trun_sample = 0;
1957
291
                p_track->i_time = p_run->i_first_dts;
1958
291
            }
1959
722
        }
1960
429
        return VLC_SUCCESS;
1961
429
    }
1962
1963
0
    return VLC_EGENERIC;
1964
429
}
1965
1966
static vlc_tick_t FragGetDemuxTimeFromTracksTime( demux_sys_t *p_sys )
1967
299
{
1968
299
    vlc_tick_t i_time = VLC_TICK_MAX;
1969
817
    for( unsigned int i = 0; i < p_sys->i_tracks; i++ )
1970
518
    {
1971
518
        if( p_sys->track[i].context.runs.i_count == 0 )
1972
335
            continue;
1973
183
        vlc_tick_t i_ttime = MP4_rescale_mtime( p_sys->track[i].i_time,
1974
183
                                             p_sys->track[i].i_timescale );
1975
183
        i_time = __MIN( i_time, i_ttime );
1976
183
    }
1977
299
    return i_time;
1978
299
}
1979
1980
static uint32_t FragGetMoofSequenceNumber( MP4_Box_t *p_moof )
1981
453
{
1982
453
    const MP4_Box_t *p_mfhd = MP4_BoxGet( p_moof, "mfhd" );
1983
453
    if( p_mfhd && BOXDATA(p_mfhd) )
1984
333
        return BOXDATA(p_mfhd)->i_sequence_number;
1985
120
    return 0;
1986
453
}
1987
1988
static int FragSeekLoadFragment( demux_t *p_demux, uint32_t i_moox )
1989
0
{
1990
0
    demux_sys_t *p_sys = p_demux->p_sys;
1991
0
    MP4_Box_t *p_moox;
1992
1993
0
    if( i_moox == ATOM_moov )
1994
0
    {
1995
0
        p_moox = p_sys->p_moov;
1996
0
    }
1997
0
    else
1998
0
    {
1999
0
        const uint8_t *p_peek;
2000
0
        if( vlc_stream_Peek( p_demux->s, &p_peek, 8 ) != 8 )
2001
0
            return VLC_EGENERIC;
2002
2003
0
        if( ATOM_moof != VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
2004
0
            return VLC_EGENERIC;
2005
2006
0
        MP4_Box_t *p_vroot = MP4_BoxGetNextChunk( p_demux->s );
2007
0
        if(!p_vroot)
2008
0
            return VLC_EGENERIC;
2009
0
        p_moox = MP4_BoxExtract( &p_vroot->p_first, ATOM_moof );
2010
0
        MP4_BoxFree( p_vroot );
2011
2012
0
        if(!p_moox)
2013
0
            return VLC_EGENERIC;
2014
0
    }
2015
2016
0
    FragResetContext( p_sys );
2017
2018
    /* map context */
2019
0
    p_sys->context.p_fragment_atom = p_moox;
2020
0
    p_sys->context.i_current_box_type = i_moox;
2021
2022
0
    msg_Dbg( p_demux, "seeked to %4.4s at pos %" PRIu64, (char *) &i_moox, p_moox->i_pos );
2023
0
    return VLC_SUCCESS;
2024
0
}
2025
2026
static unsigned GetSeekTrackIndex( demux_sys_t *p_sys )
2027
0
{
2028
0
    unsigned cand = 0;
2029
0
    for( unsigned i=0; i<p_sys->i_tracks; i++ )
2030
0
    {
2031
0
        if( p_sys->track[i].fmt.i_cat == VIDEO_ES ||
2032
0
            p_sys->track[i].fmt.i_cat == AUDIO_ES )
2033
0
        {
2034
0
            if( cand != i && !p_sys->track[cand].b_selected )
2035
0
                cand = i;
2036
0
        }
2037
0
    }
2038
0
    return cand;
2039
0
}
2040
2041
static void FragTrunSeekToTime( mp4_track_t *p_track, stime_t i_target_time )
2042
0
{
2043
0
    if( !p_track->b_ok || p_track->context.runs.i_count < 1 )
2044
0
        return;
2045
2046
0
    unsigned i_run = 0;
2047
0
    unsigned i_sample = 0;
2048
0
    uint64_t i_pos = p_track->context.runs.p_array[0].i_offset;
2049
0
    stime_t  i_time = p_track->context.runs.p_array[0].i_first_dts;
2050
2051
0
    for( unsigned r = 0; r < p_track->context.runs.i_count; r++ )
2052
0
    {
2053
0
        const mp4_run_t *p_run = &p_track->context.runs.p_array[r];
2054
0
        const MP4_Box_data_trun_t *p_data =
2055
0
                    p_track->context.runs.p_array[r].p_trun->data.p_trun;
2056
0
        if( i_time > i_target_time )
2057
0
            break;
2058
2059
0
        i_run = r;
2060
0
        i_time = p_run->i_first_dts;
2061
0
        i_pos = p_run->i_offset;
2062
0
        i_sample = 0;
2063
2064
0
        uint32_t dur = p_track->context.i_default_sample_duration;
2065
0
        uint32_t len = p_track->context.i_default_sample_size;
2066
0
        for ( unsigned i=0; i<p_data->i_sample_count; i++ )
2067
0
        {
2068
0
            if( p_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
2069
0
                dur = p_data->p_samples[i].i_duration;
2070
2071
            /* check condition */
2072
0
            if( i_time + dur > i_target_time )
2073
0
                break;
2074
2075
0
            if( p_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
2076
0
                len = p_data->p_samples[i].i_size;
2077
2078
0
            i_time += dur;
2079
0
            i_pos += len;
2080
0
            i_sample++;
2081
0
        }
2082
0
    }
2083
0
    p_track->context.i_trun_sample = i_sample;
2084
0
    p_track->context.i_trun_sample_pos = i_pos;
2085
0
    p_track->context.runs.i_current = i_run;
2086
0
    p_track->i_time = i_time;
2087
0
}
2088
2089
440
#define INVALID_SEGMENT_TIME  VLC_TICK_MAX
2090
2091
static int FragSeekToTime( demux_t *p_demux, vlc_tick_t i_nztime, bool b_accurate )
2092
0
{
2093
0
    demux_sys_t *p_sys = p_demux->p_sys;
2094
0
    uint64_t i64 = UINT64_MAX;
2095
0
    uint32_t i_segment_type = ATOM_moof;
2096
0
    stime_t  i_segment_time = INVALID_SEGMENT_TIME;
2097
0
    vlc_tick_t i_sync_time = i_nztime;
2098
2099
0
    const uint64_t i_duration = __MAX(p_sys->i_duration, p_sys->i_cumulated_duration);
2100
0
    if ( !p_sys->i_timescale || !i_duration || !p_sys->b_seekable )
2101
0
         return VLC_EGENERIC;
2102
2103
0
    uint64_t i_backup_pos = vlc_stream_Tell( p_demux->s );
2104
2105
0
    if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
2106
0
    {
2107
0
        ProbeIndex( p_demux );
2108
0
        p_sys->b_index_probed = true;
2109
0
    }
2110
2111
0
    const unsigned i_seek_track_index = GetSeekTrackIndex( p_sys );
2112
0
    const unsigned i_seek_track_ID = p_sys->track[i_seek_track_index].i_track_ID;
2113
2114
0
    if( MP4_rescale_qtime( i_nztime, p_sys->i_timescale )
2115
0
                     < GetMoovTrackDuration( p_sys, i_seek_track_ID ) )
2116
0
    {
2117
0
        i64 = p_sys->p_moov->i_pos;
2118
0
        i_segment_type = ATOM_moov;
2119
0
    }
2120
0
    else if( FragGetMoofBySidxIndex( p_demux, i_nztime, &i64, &i_sync_time ) == VLC_SUCCESS )
2121
0
    {
2122
        /* provides base offset */
2123
0
        i_segment_time = MP4_rescale_qtime( i_sync_time, p_sys->i_timescale );
2124
0
        msg_Dbg( p_demux, "seeking to sidx moof pos %" PRId64 " %" PRId64, i64, i_sync_time );
2125
0
    }
2126
0
    else
2127
0
    {
2128
0
        if( FragGetMoofByTfraIndex( p_demux, i_nztime, i_seek_track_ID, &i64, &i_sync_time ) == VLC_SUCCESS )
2129
0
        {
2130
            /* Does only provide segment position and a sync sample time */
2131
0
            msg_Dbg( p_demux, "seeking to sync point %" PRId64, i_sync_time );
2132
0
        }
2133
0
        else if( !p_sys->b_fragments_probed )
2134
0
        {
2135
0
            int i_ret = ProbeFragmentsChecked( p_demux );
2136
0
            if( i_ret != VLC_SUCCESS )
2137
0
                return i_ret;
2138
0
        }
2139
2140
0
        if( p_sys->b_fragments_probed && p_sys->p_fragsindex )
2141
0
        {
2142
0
            stime_t i_basetime = MP4_rescale_qtime( i_sync_time, p_sys->i_timescale );
2143
0
            if( !MP4_Fragments_Index_Lookup( p_sys->p_fragsindex, &i_basetime, &i64, i_seek_track_index ) )
2144
0
            {
2145
0
                p_sys->b_error = (vlc_stream_Seek( p_demux->s, i_backup_pos ) != VLC_SUCCESS);
2146
0
                return VLC_EGENERIC;
2147
0
            }
2148
0
            msg_Dbg( p_demux, "seeking to fragment index pos %" PRId64 " %" PRId64, i64,
2149
0
                     MP4_rescale_mtime( i_basetime, p_sys->i_timescale ) );
2150
0
        }
2151
0
    }
2152
2153
0
    if( i64 == UINT64_MAX )
2154
0
    {
2155
0
        msg_Warn( p_demux, "seek by index failed" );
2156
0
        p_sys->b_error = (vlc_stream_Seek( p_demux->s, i_backup_pos ) != VLC_SUCCESS);
2157
0
        return VLC_EGENERIC;
2158
0
    }
2159
2160
0
    msg_Dbg( p_demux, "final seek to fragment at %"PRId64, i64 );
2161
0
    if( vlc_stream_Seek( p_demux->s, i64 ) )
2162
0
    {
2163
0
        msg_Err( p_demux, "seek failed to %"PRId64, i64 );
2164
0
        p_sys->b_error = (vlc_stream_Seek( p_demux->s, i_backup_pos ) != VLC_SUCCESS);
2165
0
        return VLC_EGENERIC;
2166
0
    }
2167
2168
    /* Context is killed on success */
2169
0
    if( FragSeekLoadFragment( p_demux, i_segment_type ) != VLC_SUCCESS )
2170
0
    {
2171
0
        p_sys->b_error = (vlc_stream_Seek( p_demux->s, i_backup_pos ) != VLC_SUCCESS);
2172
0
        return VLC_EGENERIC;
2173
0
    }
2174
0
    if( i_segment_type == ATOM_moof )
2175
0
    {
2176
0
        MP4_Box_t *p_moox = p_sys->context.p_fragment_atom;
2177
0
        FragPrepareChunk( p_demux, p_moox, NULL, i_segment_time, true );
2178
0
        p_sys->context.i_lastseqnumber = FragGetMoofSequenceNumber( p_moox );
2179
2180
0
        p_sys->i_nztime = FragGetDemuxTimeFromTracksTime( p_sys );
2181
0
    }
2182
0
    else
2183
0
    {
2184
0
        p_sys->i_nztime = i_sync_time;
2185
0
    }
2186
2187
0
    p_sys->i_pcr  = VLC_TICK_INVALID;
2188
2189
0
    for( unsigned i=0; i<p_sys->i_tracks; i++ )
2190
0
    {
2191
0
        if( i_segment_type == ATOM_moov )
2192
0
        {
2193
0
            MP4_TrackSeek( p_demux, &p_sys->track[i], i_sync_time );
2194
0
            p_sys->i_pcr  = VLC_TICK_INVALID;
2195
0
        }
2196
0
        else
2197
0
        {
2198
0
            stime_t i_tst = MP4_rescale_qtime( i_sync_time, p_sys->track[i].i_timescale );
2199
0
            FragTrunSeekToTime( &p_sys->track[i], i_tst );
2200
0
            p_sys->track[i].i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
2201
0
        }
2202
0
    }
2203
2204
0
    MP4ASF_ResetFrames( p_sys );
2205
    /* And set next display time in that trun/fragment */
2206
0
    if( b_accurate )
2207
0
        es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TICK_0 + i_nztime );
2208
0
    return VLC_SUCCESS;
2209
0
}
2210
2211
static int FragSeekToPos( demux_t *p_demux, double f, bool b_accurate )
2212
0
{
2213
0
    demux_sys_t *p_sys = p_demux->p_sys;
2214
2215
0
    if ( !p_sys->b_seekable || !p_sys->i_timescale )
2216
0
        return VLC_EGENERIC;
2217
2218
0
    uint64_t i_duration = __MAX(p_sys->i_duration, p_sys->i_cumulated_duration);
2219
0
    if( !i_duration && !p_sys->b_fragments_probed )
2220
0
    {
2221
0
        int i_ret = ProbeFragmentsChecked( p_demux );
2222
0
        if( i_ret != VLC_SUCCESS )
2223
0
            return i_ret;
2224
0
        i_duration = __MAX(p_sys->i_duration, p_sys->i_cumulated_duration);
2225
0
    }
2226
2227
0
    if( !i_duration )
2228
0
        return VLC_EGENERIC;
2229
2230
0
    return FragSeekToTime( p_demux, (vlc_tick_t)( f *
2231
0
                           MP4_rescale_mtime( i_duration, p_sys->i_timescale ) ), b_accurate );
2232
0
}
2233
2234
static void ItunMetaCallback( const struct qt_itunes_triplet_data *data, void *priv )
2235
32
{
2236
32
    demux_sys_t *p_sys = priv;
2237
32
    if( data->type == iTunSMPB )
2238
8
    {
2239
8
        p_sys->qt.i_delay_samples = data->SMPB.delay;
2240
8
    }
2241
24
    else if( data->type == iTunNORM )
2242
6
    {
2243
6
        p_sys->qt.f_replay_gain_norm = data->NORM.volume_adjust;
2244
6
        p_sys->qt.f_replay_gain_peak = data->NORM.peak;
2245
6
    }
2246
18
    else if( data->type == iTunEncodingParams )
2247
18
    {
2248
18
        p_sys->qt.i_target_bitrate = data->EncodingParams.target_bitrate;
2249
18
    }
2250
32
}
2251
2252
static int MP4_LoadMeta( demux_sys_t *p_sys, vlc_meta_t *p_meta )
2253
2.58k
{
2254
2.58k
    if( !p_meta )
2255
0
        return VLC_EGENERIC;
2256
2257
2.58k
    const char *psz_metapath;
2258
2.58k
    const MP4_Box_t *p_metaroot = MP4_GetMetaRoot( p_sys->p_root, &psz_metapath );
2259
2260
2.58k
    MP4_GetCoverMetaURI( p_sys->p_root, p_metaroot, psz_metapath, p_meta );
2261
2262
2.58k
    if( p_metaroot )
2263
887
        SetupMeta( p_meta, p_metaroot, ItunMetaCallback, p_sys );
2264
2265
2.58k
    return VLC_SUCCESS;
2266
2.58k
}
2267
2268
/*****************************************************************************
2269
 * Control:
2270
 *****************************************************************************/
2271
static int Control( demux_t *p_demux, int i_query, va_list args )
2272
0
{
2273
0
    demux_sys_t *p_sys = p_demux->p_sys;
2274
2275
0
    double f, *pf;
2276
0
    vlc_tick_t i64;
2277
0
    bool b;
2278
2279
0
    const uint64_t i_duration = __MAX(p_sys->i_duration, p_sys->i_cumulated_duration);
2280
2281
0
    switch( i_query )
2282
0
    {
2283
0
        case DEMUX_CAN_SEEK:
2284
0
            *va_arg( args, bool * ) = p_sys->b_seekable;
2285
0
            return VLC_SUCCESS;
2286
2287
0
        case DEMUX_GET_POSITION:
2288
0
            pf = va_arg( args, double * );
2289
0
            if( i_duration > 0 )
2290
0
            {
2291
0
                *pf = (double)p_sys->i_nztime /
2292
0
                      MP4_rescale_mtime( i_duration, p_sys->i_timescale );
2293
0
            }
2294
0
            else
2295
0
            {
2296
0
                *pf = 0.0;
2297
0
            }
2298
0
            return VLC_SUCCESS;
2299
2300
0
        case DEMUX_GET_SEEKPOINT:
2301
0
            *va_arg( args, int * ) = p_sys->i_seekpoint;
2302
0
            return VLC_SUCCESS;
2303
2304
0
        case DEMUX_SET_POSITION:
2305
0
            f = va_arg( args, double );
2306
0
            b = va_arg( args, int );
2307
0
            if ( p_demux->pf_demux == DemuxFrag )
2308
0
                return FragSeekToPos( p_demux, f, b );
2309
0
            else if( p_sys->i_timescale > 0 )
2310
0
            {
2311
0
                i64 = (vlc_tick_t)( f * MP4_rescale_mtime( p_sys->i_duration,
2312
0
                                                        p_sys->i_timescale ) );
2313
0
                return Seek( p_demux, i64, b );
2314
0
            }
2315
0
            else return VLC_EGENERIC;
2316
2317
0
        case DEMUX_GET_TIME:
2318
0
            *va_arg( args, vlc_tick_t * ) = (p_sys->i_max_pts_offset < p_sys->i_nztime)
2319
0
                                          ? p_sys->i_nztime - p_sys->i_max_pts_offset : 0;
2320
0
            return VLC_SUCCESS;
2321
2322
0
        case DEMUX_SET_TIME:
2323
0
            i64 = va_arg( args, vlc_tick_t );
2324
0
            b = va_arg( args, int );
2325
0
            if ( p_demux->pf_demux == DemuxFrag )
2326
0
                return FragSeekToTime( p_demux, i64, b );
2327
0
            else
2328
0
                return Seek( p_demux, i64, b );
2329
2330
0
        case DEMUX_GET_LENGTH:
2331
0
            if( p_sys->i_timescale > 0 )
2332
0
            {
2333
0
                *va_arg( args, vlc_tick_t * ) = MP4_rescale_mtime( i_duration,
2334
0
                                                           p_sys->i_timescale );
2335
0
            }
2336
0
            else *va_arg( args, vlc_tick_t * ) = 0;
2337
0
            return VLC_SUCCESS;
2338
2339
0
        case DEMUX_GET_FPS:
2340
0
            pf = va_arg( args, double * );
2341
0
            *pf = p_sys->f_fps;
2342
0
            return VLC_SUCCESS;
2343
2344
0
        case DEMUX_GET_ATTACHMENTS:
2345
0
        {
2346
0
            input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
2347
0
            int *pi_int = va_arg( args, int * );
2348
2349
0
            if( p_sys->i_attachments == -1 )
2350
0
                p_sys->i_attachments = MP4_GetAttachments( p_sys->p_root, &p_sys->pp_attachments );
2351
0
            if( !p_sys->i_attachments )
2352
0
                return VLC_EGENERIC;
2353
0
            *ppp_attach = calloc( p_sys->i_attachments, sizeof(**ppp_attach ) );
2354
0
            if( !*ppp_attach )
2355
0
                return VLC_ENOMEM;
2356
0
            for ( ssize_t i = 0; i < p_sys->i_attachments; ++i )
2357
0
            {
2358
0
                (*ppp_attach)[i] = vlc_input_attachment_Hold( p_sys->pp_attachments[i] );
2359
0
                msg_Dbg( p_demux, "adding attachment %s", (*ppp_attach)[i]->psz_name );
2360
0
            }
2361
0
            *pi_int = p_sys->i_attachments;
2362
2363
0
            return VLC_SUCCESS;
2364
0
        }
2365
2366
0
        case DEMUX_GET_META:
2367
0
        {
2368
0
            vlc_meta_t *p_meta = va_arg( args, vlc_meta_t *);
2369
2370
0
            if( !p_sys->p_meta )
2371
0
                return VLC_EGENERIC;
2372
2373
0
            vlc_meta_Merge( p_meta, p_sys->p_meta );
2374
2375
0
            return VLC_SUCCESS;
2376
0
        }
2377
2378
0
        case DEMUX_GET_TITLE_INFO:
2379
0
        {
2380
0
            input_title_t ***ppp_title = va_arg( args, input_title_t *** );
2381
0
            int *pi_int = va_arg( args, int* );
2382
0
            int *pi_title_offset = va_arg( args, int* );
2383
0
            int *pi_seekpoint_offset = va_arg( args, int* );
2384
2385
0
            if( !p_sys->p_title )
2386
0
                return VLC_EGENERIC;
2387
2388
0
            *pi_int = 1;
2389
0
            input_title_t **titles = malloc(sizeof(*titles));
2390
0
            if (titles == NULL)
2391
0
                return VLC_ENOMEM;
2392
2393
0
            titles[0] = vlc_input_title_Duplicate(p_sys->p_title);
2394
0
            if (titles[0] == NULL)
2395
0
            {
2396
0
                free(titles);
2397
0
                return VLC_ENOMEM;
2398
0
            }
2399
0
            *ppp_title = titles;
2400
0
            *pi_title_offset = 0;
2401
0
            *pi_seekpoint_offset = 0;
2402
0
            return VLC_SUCCESS;
2403
0
        }
2404
0
        case DEMUX_SET_TITLE:
2405
0
        {
2406
0
            const int i_title = va_arg( args, int );
2407
0
            if( !p_sys->p_title || i_title != 0 )
2408
0
                return VLC_EGENERIC;
2409
0
            return VLC_SUCCESS;
2410
0
        }
2411
0
        case DEMUX_SET_SEEKPOINT:
2412
0
        {
2413
0
            const int i_seekpoint = va_arg( args, int );
2414
0
            if( !p_sys->p_title )
2415
0
                return VLC_EGENERIC;
2416
0
            return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset, true );
2417
0
        }
2418
0
        case DEMUX_TEST_AND_CLEAR_FLAGS:
2419
0
        {
2420
0
            unsigned *restrict flags = va_arg( args, unsigned * );
2421
2422
0
            if ((*flags & INPUT_UPDATE_SEEKPOINT) && p_sys->seekpoint_changed)
2423
0
            {
2424
0
                *flags = INPUT_UPDATE_SEEKPOINT;
2425
0
                p_sys->seekpoint_changed = false;
2426
0
            }
2427
0
            else
2428
0
                *flags = 0;
2429
0
            return VLC_SUCCESS;
2430
0
        }
2431
2432
0
        case DEMUX_GET_PTS_DELAY:
2433
0
        {
2434
0
            for( unsigned int i = 0; i < p_sys->i_tracks; i++ )
2435
0
            {
2436
0
                const MP4_Box_t *p_load;
2437
0
                if ( (p_load = MP4_BoxGet( p_sys->track[i].p_track, "load" )) &&
2438
0
                     BOXDATA(p_load)->i_duration > 0 )
2439
0
                {
2440
0
                    *va_arg(args, vlc_tick_t *) =
2441
0
                            MP4_rescale_mtime( BOXDATA(p_load)->i_duration,
2442
0
                                               p_sys->track[i].i_timescale );
2443
0
                    return VLC_SUCCESS;
2444
0
                }
2445
0
            }
2446
0
            return demux_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
2447
0
        }
2448
0
        case DEMUX_SET_NEXT_DEMUX_TIME:
2449
0
        case DEMUX_SET_GROUP_DEFAULT:
2450
0
        case DEMUX_SET_GROUP_ALL:
2451
0
        case DEMUX_SET_GROUP_LIST:
2452
0
        case DEMUX_HAS_UNSUPPORTED_META:
2453
0
        case DEMUX_CAN_RECORD:
2454
0
            return VLC_EGENERIC;
2455
2456
0
        case DEMUX_CAN_PAUSE:
2457
0
        case DEMUX_SET_PAUSE_STATE:
2458
0
        case DEMUX_CAN_CONTROL_PACE:
2459
0
            return demux_vaControlHelper( p_demux->s, 0, -1, 0, 1, i_query, args );
2460
2461
0
        default:
2462
0
            return VLC_EGENERIC;
2463
0
    }
2464
0
}
2465
2466
/*****************************************************************************
2467
 * Close: frees unused data
2468
 *****************************************************************************/
2469
static void Close ( vlc_object_t * p_this )
2470
2.67k
{
2471
2.67k
    demux_t *  p_demux = (demux_t *)p_this;
2472
2.67k
    demux_sys_t *p_sys = p_demux->p_sys;
2473
2.67k
    unsigned int i_track;
2474
2475
2.67k
    msg_Dbg( p_demux, "freeing all memory" );
2476
2477
2.67k
    FragResetContext( p_sys );
2478
2479
2.67k
    MP4_BoxFree( p_sys->p_root );
2480
2481
2.67k
    if( p_sys->p_title )
2482
4
        vlc_input_title_Delete( p_sys->p_title );
2483
2484
2.67k
    if( p_sys->p_meta )
2485
2.58k
        vlc_meta_Delete( p_sys->p_meta );
2486
2487
2.67k
    MP4_Fragments_Index_Delete( p_sys->p_fragsindex );
2488
2489
6.60k
    for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
2490
3.92k
        MP4_TrackClean( p_demux->out, &p_sys->track[i_track] );
2491
2.67k
    free( p_sys->track );
2492
2493
2.67k
    for ( ssize_t i = 0; i < p_sys->i_attachments; ++i )
2494
0
        vlc_input_attachment_Release( p_sys->pp_attachments[i] );
2495
2.67k
    free( p_sys->pp_attachments );
2496
2497
2.67k
    free( p_sys );
2498
2.67k
}
2499
2500
2501
2502
/****************************************************************************
2503
 * Local functions, specific to vlc
2504
 ****************************************************************************/
2505
/* Chapters */
2506
static void LoadChapterGpac( demux_t  *p_demux, MP4_Box_t *p_chpl )
2507
0
{
2508
0
    demux_sys_t *p_sys = p_demux->p_sys;
2509
2510
0
    if( BOXDATA(p_chpl)->i_chapter == 0 )
2511
0
        return;
2512
2513
0
    p_sys->p_title = vlc_input_title_New();
2514
0
    if (p_sys->p_title == NULL)
2515
0
        return;
2516
2517
0
    for( int i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
2518
0
    {
2519
0
        seekpoint_t *s = vlc_seekpoint_New();
2520
0
        if( s == NULL) continue;
2521
2522
0
        s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
2523
0
        if( s->psz_name == NULL)
2524
0
        {
2525
0
            vlc_seekpoint_Delete( s );
2526
0
            continue;
2527
0
        }
2528
2529
0
        EnsureUTF8( s->psz_name );
2530
0
        msftime_t offset = BOXDATA(p_chpl)->chapter[i].i_start;
2531
0
        s->i_time_offset = VLC_TICK_FROM_MSFTIME(offset);
2532
0
        TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
2533
0
    }
2534
0
}
2535
static void LoadChapterGoPro( demux_t *p_demux, MP4_Box_t *p_hmmt )
2536
4
{
2537
4
    demux_sys_t *p_sys = p_demux->p_sys;
2538
2539
4
    p_sys->p_title = vlc_input_title_New();
2540
4
    if( p_sys->p_title )
2541
116
        for( unsigned i = 0; i < BOXDATA(p_hmmt)->i_chapter_count; i++ )
2542
112
        {
2543
112
            seekpoint_t *s = vlc_seekpoint_New();
2544
112
            if( s == NULL)
2545
0
                continue;
2546
2547
112
            if( asprintf( &s->psz_name, "HiLight tag #%u", i+1 ) == -1 )
2548
0
            {
2549
0
                s->psz_name = NULL;
2550
0
                vlc_seekpoint_Delete( s );
2551
0
                continue;
2552
0
            }
2553
2554
112
            EnsureUTF8( s->psz_name );
2555
            /* HiLights are stored in ms so we convert them to µs */
2556
112
            s->i_time_offset = VLC_TICK_FROM_MS( BOXDATA(p_hmmt)->pi_chapter_start[i] );
2557
112
            TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
2558
112
        }
2559
4
}
2560
static void LoadChapterApple( demux_t  *p_demux, mp4_track_t *tk )
2561
0
{
2562
0
    demux_sys_t *p_sys = p_demux->p_sys;
2563
2564
0
    for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
2565
0
    {
2566
0
        if( tk->i_sample >= tk->chunk[tk->i_chunk].i_sample_first +
2567
0
                            tk->chunk[tk->i_chunk].i_sample_count )
2568
0
            tk->i_chunk++;
2569
0
        TrackUpdateSampleAndTimes( tk );
2570
2571
0
        vlc_tick_t i_pts;
2572
0
        MP4_TrackGetDTSPTS( p_demux, tk, &i_pts );
2573
0
        uint32_t i_nb_samples = 0;
2574
0
        const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
2575
2576
0
        if( i_nb_samples > 1 )
2577
0
            break; /* should not happen */
2578
2579
0
        if( i_size > 0 && !vlc_stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
2580
0
        {
2581
0
            char p_buffer[256];
2582
0
            const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
2583
0
                                                    __MIN( sizeof(p_buffer), i_size ) );
2584
0
            if( i_read > 2 )
2585
0
            {
2586
0
                const uint32_t i_string = __MIN( GetWBE(p_buffer), i_read-2 );
2587
0
                const char *psnz_string = &p_buffer[2];
2588
2589
0
                seekpoint_t *s = vlc_seekpoint_New();
2590
0
                if( s == NULL ) continue;
2591
2592
0
                if( i_string > 1 && !memcmp( psnz_string, "\xFF\xFE", 2 ) )
2593
0
                    s->psz_name = FromCharset( "UTF-16LE", psnz_string, i_string );
2594
0
                else
2595
0
                    s->psz_name = strndup( psnz_string, i_string );
2596
2597
0
                if( s->psz_name == NULL )
2598
0
                {
2599
0
                    vlc_seekpoint_Delete( s );
2600
0
                    continue;
2601
0
                }
2602
2603
0
                EnsureUTF8( s->psz_name );
2604
0
                s->i_time_offset = i_pts;
2605
2606
0
                if( !p_sys->p_title )
2607
0
                    p_sys->p_title = vlc_input_title_New();
2608
0
                TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
2609
0
            }
2610
0
        }
2611
0
    }
2612
0
}
2613
static void LoadChapter( demux_t  *p_demux )
2614
2.58k
{
2615
2.58k
    demux_sys_t *p_sys = p_demux->p_sys;
2616
2.58k
    MP4_Box_t *p_chpl;
2617
2.58k
    MP4_Box_t *p_hmmt;
2618
2619
2.58k
    if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
2620
0
          BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
2621
0
    {
2622
0
        LoadChapterGpac( p_demux, p_chpl );
2623
0
    }
2624
2.58k
    else if( ( p_hmmt = MP4_BoxGet( p_sys->p_root, "/moov/udta/HMMT" ) ) &&
2625
4
             BOXDATA(p_hmmt) && BOXDATA(p_hmmt)->pi_chapter_start && BOXDATA(p_hmmt)->i_chapter_count > 0 )
2626
4
    {
2627
4
        LoadChapterGoPro( p_demux, p_hmmt );
2628
4
    }
2629
2.58k
    else
2630
2.58k
    {
2631
        /* Load the first subtitle track like quicktime */
2632
6.50k
        for( unsigned i = 0; i < p_sys->i_tracks; i++ )
2633
3.92k
        {
2634
3.92k
            mp4_track_t *tk = &p_sys->track[i];
2635
3.92k
            if ( tk->b_ok && (tk->i_use_flags & USEAS_CHAPTERS) && tk->fmt.i_cat == SPU_ES )
2636
0
            {
2637
0
                LoadChapterApple( p_demux, tk );
2638
0
                break;
2639
0
            }
2640
3.92k
        }
2641
2.58k
    }
2642
2643
    /* Add duration if titles are enabled */
2644
2.58k
    if( p_sys->p_title )
2645
4
    {
2646
4
        const uint64_t i_duration = __MAX(p_sys->i_duration, p_sys->i_cumulated_duration);
2647
4
        p_sys->p_title->i_length =
2648
4
                MP4_rescale_mtime( i_duration, p_sys->i_timescale );
2649
4
    }
2650
2.58k
}
2651
2652
/* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
2653
static int TrackCreateChunksIndex( demux_t *p_demux,
2654
                                   mp4_track_t *p_demux_track )
2655
3.23k
{
2656
3.23k
    MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
2657
3.23k
    MP4_Box_t *p_stsc;
2658
2659
3.23k
    unsigned int i_chunk;
2660
3.23k
    unsigned int i_index, i_last;
2661
2662
3.23k
    if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
2663
142
          !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
2664
3.10k
        ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
2665
146
    {
2666
146
        return( VLC_EGENERIC );
2667
146
    }
2668
2669
3.09k
    p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
2670
3.09k
    if( !p_demux_track->i_chunk_count )
2671
250
    {
2672
250
        msg_Warn( p_demux, "no chunk defined" );
2673
250
    }
2674
3.09k
    p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
2675
3.09k
                                   sizeof( mp4_chunk_t ) );
2676
3.09k
    if( p_demux_track->chunk == NULL )
2677
0
    {
2678
0
        return VLC_ENOMEM;
2679
0
    }
2680
2681
    /* first we read chunk offset */
2682
243k
    for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2683
240k
    {
2684
240k
        mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2685
2686
240k
        ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
2687
2688
240k
        ck->i_first_dts = 0;
2689
240k
        ck->i_entries_dts = 0;
2690
240k
        ck->p_sample_count_dts = NULL;
2691
240k
        ck->p_sample_delta_dts = NULL;
2692
240k
        ck->i_entries_pts = 0;
2693
240k
        ck->p_sample_count_pts = NULL;
2694
240k
        ck->p_sample_offset_pts = NULL;
2695
240k
    }
2696
2697
    /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
2698
        to be used for the sample XXX begin to 1
2699
        We construct it beginning at the end */
2700
3.09k
    i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
2701
3.09k
    i_index = BOXDATA(p_stsc)->i_entry_count;
2702
2703
16.3k
    while( i_index-- > 0 )
2704
13.2k
    {
2705
13.2k
        for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
2706
250k
             i_chunk < i_last; i_chunk++ )
2707
237k
        {
2708
237k
            if( i_chunk >= p_demux_track->i_chunk_count )
2709
23
            {
2710
23
                msg_Warn( p_demux, "corrupted chunk table" );
2711
23
                return VLC_EGENERIC;
2712
23
            }
2713
2714
237k
            p_demux_track->chunk[i_chunk].i_sample_description_index =
2715
237k
                    BOXDATA(p_stsc)->i_sample_description_index[i_index];
2716
237k
            p_demux_track->chunk[i_chunk].i_sample_count =
2717
237k
                    BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
2718
237k
        }
2719
13.2k
        i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
2720
13.2k
    }
2721
2722
3.06k
    p_demux_track->i_sample_count = 0;
2723
3.06k
    bool b_broken = false;
2724
3.06k
    if ( p_demux_track->i_chunk_count )
2725
2.81k
    {
2726
2.81k
        p_demux_track->chunk[0].i_sample_first = 0;
2727
2.81k
        p_demux_track->i_sample_count += p_demux_track->chunk[0].i_sample_count;
2728
2729
2.81k
        const mp4_chunk_t *prev = &p_demux_track->chunk[0];
2730
232k
        for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2731
230k
        {
2732
230k
            mp4_chunk_t *cur = &p_demux_track->chunk[i_chunk];
2733
230k
            if( unlikely(UINT32_MAX - cur->i_sample_count < p_demux_track->i_sample_count) )
2734
1
            {
2735
1
                b_broken = true;
2736
1
                break;
2737
1
            }
2738
230k
            p_demux_track->i_sample_count += cur->i_sample_count;
2739
230k
            cur->i_sample_first = prev->i_sample_first + prev->i_sample_count;
2740
230k
            prev = cur;
2741
230k
        }
2742
2.81k
    }
2743
2744
3.06k
    if( unlikely(b_broken) )
2745
1
    {
2746
1
        msg_Err( p_demux, "Overflow in chunks total samples count" );
2747
1
        return VLC_EGENERIC;
2748
1
    }
2749
2750
3.06k
    msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
2751
3.06k
             p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
2752
2753
3.06k
    return VLC_SUCCESS;
2754
3.06k
}
2755
2756
static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
2757
                              const uint32_t i_index,
2758
                              uint32_t i_index_samples_left,
2759
                              uint32_t i_sample_count,
2760
                              const uint32_t *pi_index_sample_count,
2761
                              const uint32_t i_table_count )
2762
324k
{
2763
324k
    uint32_t i_array_offset;
2764
367k
    while( i_sample_count > 0 )
2765
333k
    {
2766
333k
        if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
2767
333k
            i_array_offset = i_index + *pi_entry;
2768
0
        else
2769
0
            return VLC_EGENERIC;
2770
2771
333k
        if ( i_array_offset >= i_table_count )
2772
12.9k
        {
2773
12.9k
            msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset,  i_table_count );
2774
12.9k
            return VLC_EINVAL;
2775
12.9k
        }
2776
2777
320k
        if ( i_index_samples_left )
2778
279k
        {
2779
279k
            if ( i_index_samples_left > i_sample_count )
2780
277k
            {
2781
277k
                i_index_samples_left -= i_sample_count;
2782
277k
                i_sample_count = 0;
2783
277k
                *pi_entry +=1; /* No samples left, go copy */
2784
277k
                break;
2785
277k
            }
2786
1.47k
            else
2787
1.47k
            {
2788
1.47k
                i_sample_count -= i_index_samples_left;
2789
1.47k
                i_index_samples_left = 0;
2790
1.47k
                *pi_entry += 1;
2791
1.47k
                continue;
2792
1.47k
            }
2793
279k
        }
2794
41.6k
        else
2795
41.6k
        {
2796
41.6k
            i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
2797
41.6k
            *pi_entry += 1;
2798
41.6k
        }
2799
320k
    }
2800
2801
311k
    return VLC_SUCCESS;
2802
324k
}
2803
2804
static int TrackCreateSamplesIndex( demux_t *p_demux,
2805
                                    mp4_track_t *p_demux_track )
2806
3.06k
{
2807
3.06k
    MP4_Box_t *p_box;
2808
3.06k
    MP4_Box_data_stsz_t *stsz;
2809
    /* TODO use also stss and stsh table for seeking */
2810
    /* FIXME use edit table */
2811
2812
    /* Find stsz or stz2
2813
     *  Gives the sample size for each samples. */
2814
3.06k
    p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
2815
3.06k
    if( !p_box )
2816
3
        p_box = MP4_BoxGet( p_demux_track->p_stbl, "stz2" );
2817
3.06k
    if( !p_box )
2818
3
    {
2819
3
        msg_Warn( p_demux, "cannot find STSZ or STZ2 box" );
2820
3
        return VLC_EGENERIC;
2821
3
    }
2822
3.06k
    stsz = p_box->data.p_stsz;
2823
2824
    /* Use stsz table to create a sample number -> sample size table */
2825
3.06k
    if( p_demux_track->i_sample_count != stsz->i_sample_count )
2826
1.20k
    {
2827
1.20k
        msg_Warn( p_demux, "Incorrect total samples stsc %" PRIu32 " <> stsz %"PRIu32 ", "
2828
1.20k
                           " expect truncated media playback",
2829
1.20k
                           p_demux_track->i_sample_count, stsz->i_sample_count );
2830
1.20k
        p_demux_track->i_sample_count = __MIN(p_demux_track->i_sample_count, stsz->i_sample_count);
2831
1.20k
    }
2832
2833
3.06k
    if( stsz->i_sample_size )
2834
2.16k
    {
2835
        /* 1: all sample have the same size, so no need to construct a table */
2836
2.16k
        p_demux_track->i_sample_size = stsz->i_sample_size;
2837
2.16k
        p_demux_track->p_sample_size = NULL;
2838
2.16k
    }
2839
899
    else
2840
899
    {
2841
        /* 2: each sample can have a different size */
2842
899
        p_demux_track->i_sample_size = 0;
2843
899
        p_demux_track->p_sample_size =
2844
899
            calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
2845
899
        if( p_demux_track->p_sample_size == NULL )
2846
0
            return VLC_ENOMEM;
2847
2848
477k
        for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
2849
476k
        {
2850
476k
            p_demux_track->p_sample_size[i_sample] =
2851
476k
                    stsz->i_entry_size[i_sample];
2852
476k
        }
2853
899
    }
2854
2855
3.06k
    if ( p_demux_track->i_chunk_count && p_demux_track->i_sample_size == 0 )
2856
659
    {
2857
659
        const mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
2858
659
        if( (uint64_t)lastchunk->i_sample_count + p_demux_track->i_chunk_count - 1 > stsz->i_sample_count )
2859
4
        {
2860
4
            msg_Err( p_demux, "invalid samples table: stsz table is too small" );
2861
4
            return VLC_EGENERIC;
2862
4
        }
2863
659
    }
2864
2865
    /* Use stts table to create a sample number -> dts table.
2866
     * XXX: if we don't want to waste too much memory, we can't expand
2867
     *  the box! so each chunk will contain an "extract" of this table
2868
     *  for fast research (problem with raw stream where a sample is sometime
2869
     *  just channels*bits_per_sample/8 */
2870
2871
     /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
2872
      *        differing in 2/2 fields and 1 signedness */
2873
2874
3.05k
    int64_t i_next_dts = 0;
2875
    /* Find stts
2876
     *  Gives mapping between sample and decoding time
2877
     */
2878
3.05k
    p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
2879
3.05k
    if( !p_box )
2880
10
    {
2881
10
        msg_Warn( p_demux, "cannot find STTS box" );
2882
10
        return VLC_EGENERIC;
2883
10
    }
2884
3.04k
    else
2885
3.04k
    {
2886
3.04k
        MP4_Box_data_stts_t *stts = p_box->data.p_stts;
2887
2888
3.04k
        msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
2889
2890
        /* Create sample -> dts table per chunk */
2891
3.04k
        uint32_t i_index = 0;
2892
3.04k
        uint32_t i_current_index_samples_left = 0;
2893
2894
233k
        for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2895
230k
        {
2896
230k
            mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2897
230k
            uint32_t i_sample_count;
2898
2899
            /* save first dts */
2900
230k
            ck->i_first_dts = i_next_dts;
2901
2902
            /* count how many entries are needed for this chunk
2903
             * for p_sample_delta_dts and p_sample_count_dts */
2904
230k
            ck->i_entries_dts = 0;
2905
2906
230k
            int i_ret = xTTS_CountEntries( p_demux, &ck->i_entries_dts, i_index,
2907
230k
                                           i_current_index_samples_left,
2908
230k
                                           ck->i_sample_count,
2909
230k
                                           stts->pi_sample_count,
2910
230k
                                           stts->i_entry_count );
2911
230k
            if ( i_ret == VLC_EGENERIC )
2912
0
                return i_ret;
2913
2914
            /* allocate them */
2915
230k
            i_ret = MP4_ChunkAllocEntries( ck->i_entries_dts,
2916
230k
                                           ck->small_dts_buf,
2917
230k
                                           &ck->p_sample_count_dts,
2918
230k
                                           &ck->p_sample_delta_dts );
2919
230k
            if( i_ret )
2920
0
            {
2921
0
                msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, ck->i_entries_dts );
2922
0
                ck->i_entries_dts = 0;
2923
0
                return i_ret;
2924
0
            }
2925
2926
            /* now copy */
2927
230k
            i_sample_count = ck->i_sample_count;
2928
2929
240k
            for( uint32_t i = 0; i < ck->i_entries_dts; i++ )
2930
218k
            {
2931
218k
                if ( i_current_index_samples_left )
2932
209k
                {
2933
209k
                    if ( i_current_index_samples_left > i_sample_count )
2934
208k
                    {
2935
208k
                        ck->p_sample_count_dts[i] = i_sample_count;
2936
208k
                        ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2937
208k
                        i_next_dts += (int64_t)ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2938
208k
                        if ( i_sample_count ) ck->i_duration = i_next_dts - ck->i_first_dts;
2939
208k
                        i_current_index_samples_left -= i_sample_count;
2940
208k
                        i_sample_count = 0;
2941
208k
                        assert( i == ck->i_entries_dts - 1 );
2942
208k
                        break;
2943
208k
                    }
2944
1.03k
                    else
2945
1.03k
                    {
2946
1.03k
                        ck->p_sample_count_dts[i] = i_current_index_samples_left;
2947
1.03k
                        ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2948
1.03k
                        i_next_dts += (int64_t)ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2949
1.03k
                        if ( i_current_index_samples_left ) ck->i_duration = i_next_dts - ck->i_first_dts;
2950
1.03k
                        i_sample_count -= i_current_index_samples_left;
2951
1.03k
                        i_current_index_samples_left = 0;
2952
1.03k
                        i_index++;
2953
1.03k
                    }
2954
209k
                }
2955
8.63k
                else
2956
8.63k
                {
2957
8.63k
                    if ( stts->pi_sample_count[i_index] > i_sample_count )
2958
1.72k
                    {
2959
1.72k
                        ck->p_sample_count_dts[i] = i_sample_count;
2960
1.72k
                        ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2961
1.72k
                        i_next_dts += (int64_t)ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2962
1.72k
                        if ( i_sample_count ) ck->i_duration = i_next_dts - ck->i_first_dts;
2963
1.72k
                        i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
2964
1.72k
                        i_sample_count = 0;
2965
1.72k
                        assert( i == ck->i_entries_dts - 1 );
2966
                        // keep building from same index
2967
1.72k
                    }
2968
6.91k
                    else
2969
6.91k
                    {
2970
6.91k
                        ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
2971
6.91k
                        ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2972
6.91k
                        i_next_dts += (int64_t)ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2973
6.91k
                        if ( stts->pi_sample_count[i_index] ) ck->i_duration = i_next_dts - ck->i_first_dts;
2974
6.91k
                        i_sample_count -= stts->pi_sample_count[i_index];
2975
6.91k
                        i_index++;
2976
6.91k
                    }
2977
8.63k
                }
2978
2979
218k
            }
2980
230k
        }
2981
3.04k
    }
2982
2983
2984
    /* Find ctts
2985
     *  Gives the delta between decoding time (dts) and composition table (pts)
2986
     */
2987
3.04k
    p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
2988
3.04k
    if( p_box && p_box->data.p_ctts )
2989
461
    {
2990
461
        MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
2991
2992
461
        msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
2993
2994
461
        int64_t i_cts_shift = 0;
2995
461
        const MP4_Box_t *p_cslg = MP4_BoxGet( p_demux_track->p_stbl, "cslg" );
2996
461
        if( p_cslg && BOXDATA(p_cslg) )
2997
194
        {
2998
194
            i_cts_shift = BOXDATA(p_cslg)->ct_to_dts_shift;
2999
194
        }
3000
267
        else if( ctts->i_entry_count ) /* Compute for Quicktime */
3001
89
        {
3002
107k
            for( uint32_t i = 0; i < ctts->i_entry_count; i++ )
3003
106k
            {
3004
106k
                if( ctts->pi_sample_offset[i] < 0 && ctts->pi_sample_offset[i] < -i_cts_shift )
3005
239
                    i_cts_shift = -ctts->pi_sample_offset[i];
3006
106k
            }
3007
89
        }
3008
461
        p_demux_track->i_cts_shift = i_cts_shift;
3009
3010
        /* Create pts-dts table per chunk */
3011
461
        uint32_t i_index = 0;
3012
461
        uint32_t i_current_index_samples_left = 0;
3013
3014
94.4k
        for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
3015
93.9k
        {
3016
93.9k
            mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
3017
93.9k
            uint32_t i_sample_count;
3018
3019
            /* count how many entries are needed for this chunk
3020
             * for p_sample_offset_pts and p_sample_count_pts */
3021
93.9k
            ck->i_entries_pts = 0;
3022
93.9k
            int i_ret = xTTS_CountEntries( p_demux, &ck->i_entries_pts, i_index,
3023
93.9k
                                           i_current_index_samples_left,
3024
93.9k
                                           ck->i_sample_count,
3025
93.9k
                                           ctts->pi_sample_count,
3026
93.9k
                                           ctts->i_entry_count );
3027
93.9k
            if ( i_ret == VLC_EGENERIC )
3028
0
                return i_ret;
3029
3030
            /* allocate them */
3031
93.9k
            i_ret = MP4_ChunkAllocEntries( ck->i_entries_pts,
3032
93.9k
                                           ck->small_pts_buf,
3033
93.9k
                                           &ck->p_sample_count_pts,
3034
93.9k
                                           &ck->p_sample_offset_pts );
3035
93.9k
            if( i_ret )
3036
0
            {
3037
0
                msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, ck->i_entries_pts );
3038
0
                ck->i_entries_pts = 0;
3039
0
                return i_ret;
3040
0
            }
3041
3042
            /* now copy */
3043
93.9k
            i_sample_count = ck->i_sample_count;
3044
3045
127k
            for( uint32_t i = 0; i < ck->i_entries_pts; i++ )
3046
102k
            {
3047
102k
                int64_t i_ctsdelta = ctts->pi_sample_offset[i_index] + i_cts_shift;
3048
102k
                if( i_ctsdelta < 0 ) /* should not */
3049
1.58k
                    i_ctsdelta = 0;
3050
102k
                ck->p_sample_offset_pts[i] = i_ctsdelta;
3051
102k
                if ( i_current_index_samples_left )
3052
69.5k
                {
3053
69.5k
                    if ( i_current_index_samples_left > i_sample_count )
3054
69.1k
                    {
3055
69.1k
                        ck->p_sample_count_pts[i] = i_sample_count;
3056
69.1k
                        i_current_index_samples_left -= i_sample_count;
3057
69.1k
                        i_sample_count = 0;
3058
69.1k
                        assert( i == ck->i_entries_pts - 1 );
3059
69.1k
                        break;
3060
69.1k
                    }
3061
443
                    else
3062
443
                    {
3063
443
                        ck->p_sample_count_pts[i] = i_current_index_samples_left;
3064
443
                        i_sample_count -= i_current_index_samples_left;
3065
443
                        i_current_index_samples_left = 0;
3066
443
                        i_index++;
3067
443
                    }
3068
69.5k
                }
3069
32.9k
                else
3070
32.9k
                {
3071
32.9k
                    if ( ctts->pi_sample_count[i_index] > i_sample_count )
3072
619
                    {
3073
619
                        ck->p_sample_count_pts[i] = i_sample_count;
3074
619
                        i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
3075
619
                        i_sample_count = 0;
3076
619
                        assert( i == ck->i_entries_pts - 1 );
3077
                        // keep building from same index
3078
619
                    }
3079
32.3k
                    else
3080
32.3k
                    {
3081
32.3k
                        ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
3082
32.3k
                        i_sample_count -= ctts->pi_sample_count[i_index];
3083
32.3k
                        i_index++;
3084
32.3k
                    }
3085
32.9k
                }
3086
102k
            }
3087
93.9k
        }
3088
461
    }
3089
3090
3.04k
    msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
3091
3.04k
             p_demux_track->i_track_ID, p_demux_track->i_sample_count,
3092
3.04k
             i_next_dts / p_demux_track->i_timescale );
3093
3094
3.04k
    return VLC_SUCCESS;
3095
3.04k
}
3096
3097
3098
/**
3099
 * It computes the sample rate for a video track using the given sample
3100
 * description index
3101
 */
3102
static void TrackGetESSampleRate( demux_t *p_demux,
3103
                                  unsigned *pi_num, unsigned *pi_den,
3104
                                  const mp4_track_t *p_track,
3105
                                  unsigned i_sd_index,
3106
                                  unsigned i_chunk )
3107
1.25k
{
3108
1.25k
    demux_sys_t *p_sys = p_demux->p_sys;
3109
1.25k
    *pi_num = 0;
3110
1.25k
    *pi_den = 0;
3111
3112
1.25k
    MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_sys->p_root,
3113
1.25k
                                                          "/moov" ),
3114
1.25k
                                              p_track->i_track_ID );
3115
1.25k
    MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
3116
1.25k
    if ( p_mdhd && BOXDATA(p_mdhd) )
3117
1.25k
    {
3118
1.25k
        vlc_ureduce( pi_num, pi_den,
3119
1.25k
                     (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
3120
1.25k
                     (uint64_t) BOXDATA(p_mdhd)->i_duration,
3121
1.25k
                     UINT16_MAX );
3122
1.25k
        return;
3123
1.25k
    }
3124
3125
0
    if( p_track->i_chunk_count == 0 )
3126
0
        return;
3127
3128
    /* */
3129
0
    const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
3130
0
    while( p_chunk > &p_track->chunk[0] &&
3131
0
           p_chunk[-1].i_sample_description_index == i_sd_index )
3132
0
    {
3133
0
        p_chunk--;
3134
0
    }
3135
3136
0
    uint64_t i_sample = 0;
3137
0
    uint64_t i_total_duration = 0;
3138
0
    do
3139
0
    {
3140
0
        i_sample += p_chunk->i_sample_count;
3141
0
        i_total_duration += p_chunk->i_duration;
3142
0
        p_chunk++;
3143
0
    }
3144
0
    while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
3145
0
           p_chunk->i_sample_description_index == i_sd_index );
3146
3147
0
    if( i_sample > 0 && i_total_duration )
3148
0
        vlc_ureduce( pi_num, pi_den,
3149
0
                     i_sample * p_track->i_timescale,
3150
0
                     i_total_duration,
3151
0
                     UINT16_MAX);
3152
0
}
3153
3154
static void TrackConfigInit( track_config_t *p_cfg )
3155
3.07k
{
3156
3.07k
    memset( p_cfg, 0, sizeof(*p_cfg) );
3157
3.07k
}
3158
3159
static void TrackConfigApply( const track_config_t *p_cfg,
3160
                              mp4_track_t *p_track )
3161
3.03k
{
3162
3.03k
    if( p_cfg->i_timescale_override )
3163
3
        p_track->i_timescale = p_cfg->i_timescale_override;
3164
3.03k
     if( p_cfg->i_sample_size_override )
3165
0
        p_track->i_sample_size = p_cfg->i_sample_size_override;
3166
3.03k
     p_track->p_asf = p_cfg->p_asf;
3167
3.03k
     memcpy( p_track->rgi_chans_reordering, p_cfg->rgi_chans_reordering,
3168
3.03k
             AOUT_CHAN_MAX * sizeof(p_cfg->rgi_chans_reordering[0]) );
3169
3.03k
     p_track->i_chans_to_reorder = p_cfg->i_chans_to_reorder;
3170
3.03k
     p_track->b_forced_spu = p_cfg->b_forced_spu;
3171
3.03k
     p_track->i_block_flags = p_cfg->i_block_flags;
3172
3.03k
     p_track->b_ignore_implicit_pts = p_cfg->b_ignore_implicit_pts;
3173
3.03k
}
3174
3175
static int TrackFillConfig( demux_t *p_demux, const mp4_track_t *p_track,
3176
                            const MP4_Box_t *p_sample,unsigned i_chunk,
3177
                            es_format_t *p_fmt, track_config_t *p_cfg )
3178
3.07k
{
3179
    /* */
3180
3.07k
    switch( p_track->fmt.i_cat )
3181
3.07k
    {
3182
1.25k
    case VIDEO_ES:
3183
1.25k
        if ( p_sample->i_handler != ATOM_vide ||
3184
1.25k
             !SetupVideoES( p_demux, p_track, p_sample, p_fmt, p_cfg ) )
3185
0
            return VLC_EGENERIC;
3186
3187
        /* Set frame rate */
3188
1.25k
        TrackGetESSampleRate( p_demux,
3189
1.25k
                              &p_fmt->video.i_frame_rate,
3190
1.25k
                              &p_fmt->video.i_frame_rate_base,
3191
1.25k
                              p_track, p_sample->i_index, i_chunk );
3192
1.25k
        break;
3193
3194
1.02k
    case AUDIO_ES:
3195
1.02k
        if ( p_sample->i_handler != ATOM_soun ||
3196
1.02k
             !SetupAudioES( p_demux, p_track, p_sample, p_fmt, p_cfg ) )
3197
3
            return VLC_EGENERIC;
3198
1.02k
        break;
3199
3200
1.02k
    case SPU_ES:
3201
612
        if ( ( p_sample->i_handler != ATOM_text &&
3202
612
               p_sample->i_handler != ATOM_subt &&
3203
612
               p_sample->i_handler != ATOM_sbtl &&
3204
0
               p_sample->i_handler != ATOM_clcp ) ||
3205
612
             !SetupSpuES( p_demux, p_track, p_sample, p_fmt, p_cfg ) )
3206
0
           return VLC_EGENERIC;
3207
612
        break;
3208
3209
612
    default:
3210
179
        break;
3211
3.07k
    }
3212
3213
3.07k
    return VLC_SUCCESS;
3214
3.07k
}
3215
3216
/*
3217
 * TrackCreateES:
3218
 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
3219
 */
3220
static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
3221
                          unsigned int i_chunk, es_out_id_t **pp_es )
3222
3.04k
{
3223
3.04k
    demux_sys_t *p_sys = p_demux->p_sys;
3224
3.04k
    unsigned int i_sample_description_index;
3225
3226
3.04k
    if( p_sys->b_fragmented || p_track->i_chunk_count == 0 )
3227
249
        i_sample_description_index = 1; /* XXX */
3228
2.80k
    else
3229
2.80k
        i_sample_description_index =
3230
2.80k
                p_track->chunk[i_chunk].i_sample_description_index;
3231
3232
3.04k
    if( pp_es )
3233
3.03k
        *pp_es = NULL;
3234
3235
3.04k
    if( !i_sample_description_index )
3236
14
    {
3237
14
        msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
3238
14
                  p_track->i_track_ID );
3239
14
        return VLC_EGENERIC;
3240
14
    }
3241
3242
3.03k
    const MP4_Box_t *p_sample = MP4_BoxGetVa( p_track->p_stsd, "[%u]",
3243
3.03k
                                            i_sample_description_index - 1 );
3244
3.03k
    if( !p_sample ||
3245
3.01k
        ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
3246
24
    {
3247
24
        msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
3248
24
                  p_track->i_track_ID );
3249
24
        return VLC_EGENERIC;
3250
24
    }
3251
3252
3.01k
    track_config_t cfg;
3253
3.01k
    TrackConfigInit( &cfg );
3254
3.01k
    es_format_t *p_fmt = &p_track->fmt;
3255
3256
3.01k
    p_track->fmt.i_id = p_track->i_track_ID;
3257
3258
3.01k
    if( TrackFillConfig( p_demux, p_track, p_sample, i_chunk,
3259
3.01k
                         p_fmt, &cfg ) != VLC_SUCCESS )
3260
3
    {
3261
3
        return VLC_EGENERIC;
3262
3
    }
3263
3264
3.00k
    TrackConfigApply( &cfg, p_track );
3265
3266
3.00k
    switch( p_fmt->i_cat )
3267
3.00k
    {
3268
1.25k
        case VIDEO_ES:
3269
1.25k
            p_sys->f_fps = (float)p_fmt->video.i_frame_rate /
3270
1.25k
                    (float)p_fmt->video.i_frame_rate_base;
3271
1.25k
            break;
3272
1.02k
        case AUDIO_ES:
3273
1.02k
        {
3274
1.02k
            int i_ret = VLC_EGENERIC;
3275
1.02k
            if( p_sys->p_meta )
3276
1.02k
            {
3277
1.02k
                i_ret = vlc_replay_gain_CopyFromMeta( &p_fmt->audio_replay_gain, p_sys->p_meta );
3278
1.02k
            }
3279
3280
            /* use replay gain if available; otherwise use sound check */
3281
1.02k
            if( i_ret != VLC_SUCCESS )
3282
1.02k
            {
3283
1.02k
                audio_replay_gain_t *p_arg = &p_fmt->audio_replay_gain;
3284
1.02k
                replay_gain_Reset( p_arg );
3285
3286
1.02k
                if( isfinite(p_sys->qt.f_replay_gain_norm) )
3287
5
                {
3288
5
                    p_arg->pb_gain[AUDIO_REPLAY_GAIN_TRACK] = true;
3289
5
                    p_arg->pf_gain[AUDIO_REPLAY_GAIN_TRACK] = p_sys->qt.f_replay_gain_norm;
3290
5
                }
3291
3292
1.02k
                if( isfinite(p_sys->qt.f_replay_gain_peak) )
3293
5
                {
3294
5
                    p_arg->pb_peak[AUDIO_REPLAY_GAIN_TRACK] = true;
3295
5
                    p_arg->pf_peak[AUDIO_REPLAY_GAIN_TRACK] = p_sys->qt.f_replay_gain_peak;
3296
5
                }
3297
3298
1.02k
                if( p_arg->pb_gain[AUDIO_REPLAY_GAIN_TRACK] )
3299
5
                {
3300
                    /* sound check uses -16 LUFS as the reference level */
3301
5
                    p_arg->pb_reference_loudness = true;
3302
5
                    p_arg->pf_reference_loudness = -16.f;
3303
5
                }
3304
1.02k
            }
3305
3306
1.02k
            if( p_sys->qt.i_target_bitrate )
3307
4
            {
3308
4
                p_fmt->i_bitrate = p_sys->qt.i_target_bitrate;
3309
4
            }
3310
3311
1.02k
            switch( p_fmt->i_codec )
3312
1.02k
            {
3313
                /* When not specified, set max standard decoder delay */
3314
58
                case VLC_CODEC_MP4A:
3315
59
                case VLC_CODEC_OPUS:
3316
62
                case VLC_CODEC_MP3:
3317
67
                case VLC_CODEC_MP2:
3318
79
                case VLC_CODEC_MPGA:
3319
79
                {
3320
79
                    const unsigned i_rate = p_fmt->audio.i_rate ? p_fmt->audio.i_rate : p_track->i_timescale;
3321
79
                    const MP4_Box_t *p_elst = p_track->p_elst;
3322
79
                    if( p_elst && BOXDATA(p_elst)->i_entry_count &&
3323
25
                        BOXDATA(p_elst)->entries[0].i_media_time < 0 )
3324
3
                    {
3325
3
                        p_track->i_decoder_delay = MP4_rescale( BOXDATA(p_elst)->entries[0].i_segment_duration,
3326
3
                                                                p_sys->i_timescale,
3327
3
                                                                p_track->i_timescale );
3328
3
                    }
3329
76
                    else if( p_sys->qt.i_delay_samples > 0 )
3330
3
                    {
3331
3
                        p_track->i_decoder_delay =  MP4_rescale(
3332
3
                                    p_sys->qt.i_delay_samples, i_rate,
3333
3
                                    p_track->i_timescale );
3334
3
                    }
3335
                    /* AAC historical Apple decoder delay 2112 > 2048 */
3336
73
                    else if( p_fmt->i_codec == VLC_CODEC_MP4A )
3337
52
                    {
3338
52
                        p_track->i_decoder_delay =  MP4_rescale(
3339
52
                                    2112, i_rate,
3340
52
                                    p_track->i_timescale );
3341
52
                    }
3342
                    /* Opus has an expected 80ms discard on seek */
3343
21
                    else if( p_fmt->i_codec == VLC_CODEC_OPUS )
3344
1
                    {
3345
1
                        p_track->i_decoder_delay =  MP4_rescale(
3346
1
                                    80 * 48, 48000,
3347
1
                                    p_track->i_timescale );
3348
1
                    }
3349
                    /* MPEG have One frame delay */
3350
20
                    else if( p_fmt->i_codec == VLC_CODEC_MP3 )
3351
3
                    {
3352
                        /* https://lame.sourceforge.io/tech-FAQ.txt
3353
                         * https://www.compuphase.com/mp3/mp3loops.htm
3354
                           https://www.iis.fraunhofer.de/content/dam/iis/de/doc/ame/conference/AES-116-Convention_guideline-to-audio-codec-delay_AES116.pdf */
3355
3
                        p_track->i_decoder_delay =  MP4_rescale(
3356
3
                                    576, i_rate,
3357
3
                                    p_track->i_timescale );
3358
3
                    }
3359
17
                    else if( p_fmt->i_codec == VLC_CODEC_MPGA ||
3360
5
                             p_fmt->i_codec == VLC_CODEC_MP2 )
3361
17
                    {
3362
17
                        p_track->i_decoder_delay =  MP4_rescale(
3363
17
                                    240, i_rate,
3364
17
                                    p_track->i_timescale );
3365
17
                    }
3366
79
                }
3367
79
                break;
3368
946
                default:
3369
946
                    break;
3370
1.02k
            }
3371
1.02k
            break;
3372
1.02k
        }
3373
1.02k
        default:
3374
733
            break;
3375
3.00k
    }
3376
3377
3.00k
    p_track->p_sample = p_sample;
3378
3379
3.00k
    if( pp_es )
3380
2.99k
        *pp_es = MP4_CreateES( p_demux->out, p_fmt, p_track->b_forced_spu );
3381
3382
3.00k
    return ( !pp_es || *pp_es ) ? VLC_SUCCESS : VLC_EGENERIC;
3383
3.00k
}
3384
3385
/* *** Try to find nearest sync points *** */
3386
static int TrackGetNearestSeekPoint( demux_t *p_demux, mp4_track_t *p_track,
3387
                                     uint32_t i_sample, uint32_t *pi_sync_sample )
3388
175M
{
3389
175M
    int i_ret = VLC_EGENERIC;
3390
175M
    *pi_sync_sample = i_sample;
3391
3392
175M
    const MP4_Box_t *p_stss;
3393
    /* try sync points without recovery roll */
3394
175M
    if( ( p_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
3395
403k
    {
3396
        /* XXX in libmp4 sample begin at 0 */
3397
403k
        const uint32_t stts_sample = i_sample + 1;
3398
403k
        const MP4_Box_data_stss_t *p_stss_data = BOXDATA(p_stss);
3399
403k
        msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
3400
403k
                 p_track->i_track_ID );
3401
2.30M
        for( unsigned i_index = 0; i_index < p_stss_data->i_entry_count; i_index++ )
3402
2.07M
        {
3403
2.07M
            if(( i_index == p_stss_data->i_entry_count - 1 ||
3404
1.97M
                stts_sample < p_stss_data->i_sample_number[i_index+1] ) &&
3405
374k
                p_stss_data->i_sample_number[i_index] != 0 )
3406
172k
            {
3407
172k
                *pi_sync_sample = p_stss_data->i_sample_number[i_index] - 1;
3408
172k
                msg_Dbg( p_demux, "stss gives %d --> %" PRIu32 " (sample number)",
3409
172k
                         i_sample, *pi_sync_sample );
3410
172k
                i_ret = VLC_SUCCESS;
3411
172k
                break;
3412
172k
            }
3413
2.07M
        }
3414
403k
    }
3415
3416
175M
    if (*pi_sync_sample != i_sample)
3417
167k
    {
3418
        /* try or refine using RAP with recovery roll info */
3419
167k
        uint32_t i_alternative_sync_sample = i_sample;
3420
167k
        if( MP4_SampleToGroupInfo( p_track->p_stbl, i_sample, SAMPLEGROUP_rap,
3421
167k
                                0, &i_alternative_sync_sample, true, NULL ) )
3422
5.75k
        {
3423
5.75k
            msg_Dbg( p_demux, "tk %u sbgp gives %d --> %" PRIu32 " (sample number)",
3424
5.75k
                    p_track->i_track_ID, i_sample, i_alternative_sync_sample );
3425
5.75k
            if( i_alternative_sync_sample > *pi_sync_sample &&
3426
0
                i_alternative_sync_sample < i_sample )
3427
0
                *pi_sync_sample = i_alternative_sync_sample;
3428
5.75k
        }
3429
167k
    }
3430
3431
175M
    return i_ret;
3432
175M
}
3433
3434
struct cmplowestchunkdts_ctx
3435
{
3436
    uint64_t dts;
3437
    const mp4_chunk_t **pp_lowest;
3438
};
3439
3440
static int cmplowestchunkdts( const void *key, const void *other )
3441
1.49G
{
3442
1.49G
    const struct cmplowestchunkdts_ctx *ctx = key;
3443
1.49G
    const mp4_chunk_t *ck = other;
3444
1.49G
    if(ctx->dts > ck->i_first_dts)
3445
1.49G
    {
3446
1.49G
        *ctx->pp_lowest = ck;
3447
1.49G
        return 1;
3448
1.49G
    }
3449
1.92M
    else if(ctx->dts < ck->i_first_dts)
3450
1.92M
    {
3451
1.92M
        return -1;
3452
1.92M
    }
3453
1.22k
    else
3454
1.22k
    {
3455
1.22k
        *ctx->pp_lowest = ck;
3456
1.22k
        return 0;
3457
1.22k
    }
3458
1.49G
}
3459
3460
static int STTSToSampleChunk(const mp4_track_t *p_track, uint64_t i_dts,
3461
                             uint32_t *pi_chunk, uint32_t *pi_sample)
3462
217M
{
3463
217M
    const mp4_chunk_t *ck = NULL;
3464
3465
217M
    if( p_track->i_chunk_count > 1 &&  /* start heuristic */
3466
194M
        (uint64_t) i_dts < p_track->chunk[1].i_first_dts )
3467
278k
    {
3468
278k
        ck = &p_track->chunk[0];
3469
278k
    }
3470
217M
    else
3471
217M
    {
3472
217M
        const mp4_chunk_t *lowestchunk = NULL;
3473
217M
        struct cmplowestchunkdts_ctx bsearchkeyctx = { .dts = i_dts,
3474
217M
                                                       .pp_lowest = &lowestchunk };
3475
217M
        ck = bsearch( &bsearchkeyctx, p_track->chunk, p_track->i_chunk_count,
3476
217M
                      sizeof(*p_track->chunk), cmplowestchunkdts );
3477
217M
        if( ck == NULL )
3478
217M
            ck = lowestchunk;
3479
217M
        if( unlikely(ck == NULL) )
3480
            /* if we default to last chunk, it will be checked searching i_sample */
3481
0
            ck = &p_track->chunk[p_track->i_chunk_count - 1];
3482
217M
    }
3483
3484
    /* *** find sample in the chunk *** */
3485
217M
    uint32_t i_sample = ck->i_sample_first;
3486
217M
    uint64_t i_entrydts = ck->i_first_dts;
3487
3488
217M
    for( uint_fast32_t i = 0;
3489
244M
         i < ck->i_entries_dts && i_sample < ck->i_sample_count;
3490
217M
         i++ )
3491
26.6M
    {
3492
26.6M
        uint64_t i_entry_duration = ck->p_sample_count_dts[i] * (uint64_t)
3493
26.6M
                                    ck->p_sample_delta_dts[i];
3494
26.6M
        if( i_entrydts + i_entry_duration < i_dts )
3495
26.3M
        {
3496
26.3M
            i_entrydts += i_entry_duration;
3497
26.3M
            i_sample += ck->p_sample_count_dts[i];
3498
26.3M
        }
3499
280k
        else
3500
280k
        {
3501
280k
            if( ck->p_sample_delta_dts[i] > 0 )
3502
280k
                i_sample += ( i_dts - i_entrydts ) / ck->p_sample_delta_dts[i];
3503
280k
            break;
3504
280k
        }
3505
26.6M
    }
3506
3507
217M
    *pi_chunk = ck - p_track->chunk;
3508
217M
    *pi_sample = i_sample;
3509
3510
217M
    if( i_sample >= p_track->i_sample_count )
3511
40.9M
        return VLC_EGENERIC;
3512
3513
177M
    return VLC_SUCCESS;
3514
217M
}
3515
3516
/* given a time it return sample/chunk
3517
 * it also update elst field of the track
3518
 */
3519
static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
3520
                                   vlc_tick_t start, uint32_t *pi_chunk,
3521
                                   uint32_t *pi_sample )
3522
216M
{
3523
216M
    demux_sys_t *p_sys = p_demux->p_sys;
3524
216M
    stime_t      i_start;
3525
3526
    /* FIXME see if it's needed to check p_track->i_chunk_count */
3527
216M
    if( p_track->i_chunk_count == 0 )
3528
344k
        return( VLC_EGENERIC );
3529
3530
    /* handle elst (find the correct one) */
3531
216M
    MP4_TrackSetELST( p_demux, p_track, start );
3532
216M
    if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3533
200M
    {
3534
        /* now calculate i_start for this elst */
3535
        /* offset */
3536
200M
        if( start < MP4_rescale_mtime( p_track->i_elst_time, p_sys->i_timescale ) )
3537
3
        {
3538
3
            *pi_chunk = 0;
3539
3
            *pi_sample= 0;
3540
3541
3
            return VLC_SUCCESS;
3542
3
        }
3543
        /* to track time scale */
3544
200M
        i_start = MP4_rescale_qtime( start, p_track->i_timescale );
3545
        /* map through elst offset */
3546
200M
        i_start = MP4_MapMediaTimelineToTrackTime( p_track, p_sys->i_timescale, i_start );
3547
3548
200M
        msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
3549
200M
                 "ms (track)", p_track->i_elst,
3550
200M
                 MS_FROM_VLC_TICK(start),
3551
200M
                 MP4_rescale( i_start, p_track->i_timescale, 1000 ) );
3552
200M
    }
3553
15.7M
    else
3554
15.7M
    {
3555
        /* convert absolute time to in timescale unit */
3556
15.7M
        i_start = MP4_rescale_qtime( start, p_track->i_timescale );
3557
15.7M
    }
3558
3559
    /* *** find good chunk *** */
3560
216M
    uint32_t i_sample, i_chunk;
3561
216M
    if( STTSToSampleChunk( p_track, i_start, &i_chunk, &i_sample ) != VLC_SUCCESS )
3562
40.9M
    {
3563
40.9M
        msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
3564
40.9M
                  "(seeking too far) chunk=%"PRIu32" sample=%"PRIu32,
3565
40.9M
                  p_track->i_track_ID, i_chunk, i_sample );
3566
40.9M
        return( VLC_EGENERIC );
3567
40.9M
    }
3568
3569
3570
    /* *** Try to find nearest sync points *** */
3571
175M
    uint32_t i_sync_sample = i_sample;
3572
175M
    if( VLC_SUCCESS ==
3573
175M
        TrackGetNearestSeekPoint( p_demux, p_track, i_sample, &i_sync_sample ) )
3574
172k
    {
3575
172k
        msg_Dbg(p_demux,"track[Id 0x%x] sync point found sample %"PRIu32"(-%"PRIu32")",
3576
172k
                p_track->i_track_ID, i_sync_sample, i_sample - i_sync_sample);
3577
172k
    }
3578
175M
    else
3579
175M
    {
3580
175M
        const MP4_Box_data_sgpd_entry_t *p_entrydesc;
3581
175M
        if( MP4_SampleToGroupInfo( p_track->p_stbl, i_sample,
3582
175M
                                  SAMPLEGROUP_roll, 0, &i_sync_sample,
3583
175M
                                  SAMPLE_GROUP_MATCH_EXACT, &p_entrydesc ) )
3584
0
        {
3585
0
            msg_Dbg(p_demux, "track[Id 0x%x] preroll offset: %"PRId16" samples",
3586
0
                    p_track->i_track_ID, p_entrydesc->roll.i_roll_distance );
3587
0
            if( p_entrydesc->roll.i_roll_distance < 0 )
3588
0
            {
3589
0
                if( i_sync_sample > (uint32_t)-p_entrydesc->roll.i_roll_distance )
3590
0
                    i_sync_sample += p_entrydesc->roll.i_roll_distance;
3591
0
                else
3592
0
                    i_sync_sample = 0;
3593
0
            }
3594
0
        }
3595
175M
        else if( p_track->i_decoder_delay > 0 &&
3596
1.40M
                 p_track->i_decoder_delay <= i_start )
3597
1.40M
        {
3598
1.40M
            uint32_t i_withdelay_sample, i_withdelay_chunk;
3599
1.40M
            if( STTSToSampleChunk( p_track, i_start - p_track->i_decoder_delay,
3600
1.40M
                                   &i_withdelay_chunk,
3601
1.40M
                                   &i_withdelay_sample ) == VLC_SUCCESS )
3602
1.40M
            {
3603
1.40M
                msg_Warn( p_demux, "track[Id 0x%x] has %" PRId64 "µs decoder delay from %" PRId64,
3604
1.40M
                          p_track->i_track_ID,
3605
1.40M
                          MP4_rescale_mtime( p_track->i_decoder_delay, p_track->i_timescale),
3606
1.40M
                          i_start );
3607
1.40M
                *pi_chunk  = i_withdelay_chunk;
3608
1.40M
                *pi_sample = i_withdelay_sample;
3609
1.40M
                return VLC_SUCCESS;
3610
1.40M
            }
3611
1.40M
        }
3612
175M
    }
3613
3614
    /* Go to sync point chunk */
3615
174M
    if( i_sync_sample <= i_sample )
3616
174M
    {
3617
177M
        while( i_chunk > 0 &&
3618
177M
               i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
3619
3.62M
            i_chunk--;
3620
174M
    }
3621
42
    else
3622
42
    {
3623
1.79k
        while( i_chunk < p_track->i_chunk_count - 1 &&
3624
1.78k
               i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
3625
1.78k
                                p_track->chunk[i_chunk].i_sample_count )
3626
1.75k
            i_chunk++;
3627
42
    }
3628
3629
174M
    *pi_chunk  = i_chunk;
3630
174M
    *pi_sample = i_sync_sample;
3631
3632
174M
    return VLC_SUCCESS;
3633
175M
}
3634
3635
static bool FormatIsCompatible( const es_format_t *p_fmt1, const es_format_t *p_fmt2 )
3636
66
{
3637
66
    if( p_fmt1->i_original_fourcc != p_fmt2->i_original_fourcc )
3638
0
        return false;
3639
66
    if( (p_fmt1->i_extra > 0) ^ (p_fmt2->i_extra > 0) )
3640
16
        return false;
3641
3642
50
    if( p_fmt1->i_codec == p_fmt2->i_codec &&
3643
43
        p_fmt1->i_extra && p_fmt2->i_extra &&
3644
37
        p_fmt1->i_extra == p_fmt2->i_extra )
3645
33
    {
3646
33
       return !!memcmp( p_fmt1->p_extra, p_fmt2->p_extra, p_fmt1->i_extra );
3647
33
    }
3648
3649
17
    if( p_fmt1->i_cat == AUDIO_ES )
3650
0
    {
3651
        /* Reject audio streams with different or unknown rates */
3652
0
        if( p_fmt1->audio.i_rate != p_fmt2->audio.i_rate || !p_fmt1->audio.i_rate )
3653
0
            return false;
3654
0
    }
3655
3656
17
    return es_format_IsSimilar( p_fmt1, p_fmt2 );
3657
17
}
3658
3659
static int TrackUpdateFormat( demux_t *p_demux, mp4_track_t *p_track,
3660
                              uint32_t i_previous_chunk )
3661
180M
{
3662
180M
    uint32_t i_chunk = p_track->i_chunk;
3663
    /* now see if actual es is ok */
3664
180M
    if( i_previous_chunk != i_chunk &&
3665
509k
        p_track->chunk[i_previous_chunk].i_sample_description_index !=
3666
509k
        p_track->chunk[i_chunk].i_sample_description_index )
3667
126
    {
3668
126
        msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
3669
126
                  p_track->i_track_ID );
3670
3671
126
        const MP4_Box_t *p_newsample = MP4_BoxGetVa( p_track->p_stsd, "[%d]",
3672
126
                                                   p_track->chunk[i_chunk].i_sample_description_index - 1 );
3673
126
        if( p_newsample == NULL )
3674
60
        {
3675
60
            msg_Err( p_demux, "Can't change track[Id 0x%x] format for sample desc %" PRIu32,
3676
60
                     p_track->i_track_ID, p_track->chunk[i_chunk].i_sample_description_index );
3677
60
            p_track->b_ok = false;
3678
60
            p_track->b_selected = false;
3679
60
            return VLC_EGENERIC;
3680
60
        }
3681
3682
66
        track_config_t cfg;
3683
66
        TrackConfigInit( &cfg );
3684
66
        es_format_t tmpfmt;
3685
66
        es_format_Init( &tmpfmt, p_track->fmt.i_cat, 0 );
3686
66
        tmpfmt.i_id = p_track->i_track_ID;
3687
66
        if( TrackFillConfig( p_demux, p_track, p_newsample, i_chunk, &tmpfmt, &cfg ) == VLC_SUCCESS &&
3688
66
            !FormatIsCompatible( &p_track->fmt, &tmpfmt ) )
3689
30
        {
3690
30
            bool b_reselect = false;
3691
3692
30
            es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
3693
30
                            p_track->p_es, &b_reselect );
3694
3695
30
            es_out_Del( p_demux->out, p_track->p_es );
3696
3697
30
            p_track->p_es = MP4_CreateES( p_demux->out, &tmpfmt, cfg.b_forced_spu );
3698
30
            if( !p_track->p_es )
3699
0
            {
3700
0
                msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3701
0
                         p_track->i_track_ID );
3702
3703
0
                p_track->b_ok       = false;
3704
0
                p_track->b_selected = false;
3705
0
                es_format_Clean( &tmpfmt );
3706
0
                return VLC_EGENERIC;
3707
0
            }
3708
3709
            /* select again the new decoder */
3710
30
            if( b_reselect )
3711
30
                es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
3712
3713
30
            TrackConfigApply( &cfg, p_track );
3714
30
            es_format_Clean( &p_track->fmt );
3715
30
            es_format_Init( &p_track->fmt, tmpfmt.i_cat, tmpfmt.i_codec );
3716
30
            es_format_Copy( &p_track->fmt, &tmpfmt );
3717
30
            p_track->p_sample = p_newsample;
3718
30
        }
3719
66
        es_format_Clean( &tmpfmt );
3720
66
    }
3721
3722
180M
    return VLC_SUCCESS;
3723
180M
}
3724
3725
static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
3726
                                 uint32_t i_chunk, uint32_t i_sample )
3727
175M
{
3728
175M
    if( TrackUpdateFormat( p_demux, p_track, p_track->i_chunk ) != VLC_SUCCESS )
3729
0
        return VLC_EGENERIC;
3730
3731
175M
    p_track->i_chunk    = i_chunk;
3732
175M
    p_track->i_sample   = i_sample;
3733
3734
175M
    return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3735
175M
}
3736
3737
static void TrackUpdateStarttimes( mp4_track_t *p_track )
3738
175M
{
3739
175M
    assert(p_track->i_chunk < p_track->i_chunk_count);
3740
3741
175M
    p_track->i_start_dts = p_track->i_next_dts;
3742
175M
    p_track->i_start_delta = p_track->i_next_delta;
3743
3744
    /* Probe the 16 first B frames */
3745
175M
    uint32_t i_chunk = p_track->i_chunk;
3746
175M
    if( !p_track->chunk[i_chunk].i_entries_pts )
3747
175M
        return;
3748
3749
162k
    stime_t lowest = p_track->i_start_dts;
3750
162k
    if( p_track->i_start_delta != UNKNOWN_DELTA )
3751
162k
        lowest += p_track->i_start_delta;
3752
3753
1.58M
    for( uint32_t i=1; i<16; i++ )
3754
1.57M
    {
3755
1.57M
        uint32_t i_nextsample = p_track->i_sample + i;
3756
1.57M
        if( i_nextsample >= p_track->i_sample_count )
3757
150k
            break;
3758
1.42M
        const mp4_chunk_t *ck = NULL;
3759
2.25M
        for( ; i_chunk < p_track->i_chunk_count; i_chunk++ )
3760
2.25M
        {
3761
2.25M
            ck = &p_track->chunk[i_chunk];
3762
2.25M
            if( i_nextsample < ck->i_sample_first + ck->i_sample_count )
3763
1.42M
                break;
3764
2.25M
        }
3765
1.42M
        if( !ck )
3766
0
            break;
3767
1.42M
        assert(i_nextsample >= ck->i_sample_first);
3768
1.42M
        stime_t pts;
3769
1.42M
        stime_t dts = pts = MP4_ChunkGetSampleDTS( ck, i_nextsample - ck->i_sample_first );
3770
1.42M
        stime_t delta = UNKNOWN_DELTA;
3771
1.42M
        if( MP4_ChunkGetSampleCTSDelta( ck, i_nextsample - ck->i_sample_first, &delta ) )
3772
1.42M
            pts += delta;
3773
1.42M
        if( pts < lowest )
3774
309k
        {
3775
309k
            p_track->i_start_dts = dts;
3776
309k
            p_track->i_start_delta = delta;
3777
309k
        }
3778
1.42M
    }
3779
162k
}
3780
3781
static void TrackUpdateSampleAndTimes( mp4_track_t *p_track )
3782
182M
{
3783
182M
    const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3784
182M
    uint32_t i_chunk_sample = p_track->i_sample - p_chunk->i_sample_first;
3785
182M
    if( i_chunk_sample > p_chunk->i_sample_count && p_chunk->i_sample_count )
3786
20
        i_chunk_sample = p_chunk->i_sample_count - 1;
3787
182M
    p_track->i_next_dts = MP4_ChunkGetSampleDTS( p_chunk, i_chunk_sample );
3788
182M
    stime_t i_next_delta;
3789
182M
    if( !MP4_ChunkGetSampleCTSDelta( p_chunk, i_chunk_sample, &i_next_delta ) )
3790
180M
        p_track->i_next_delta = UNKNOWN_DELTA;
3791
1.68M
    else
3792
1.68M
        p_track->i_next_delta = i_next_delta;
3793
182M
}
3794
3795
/****************************************************************************
3796
 * MP4_TrackSetup:
3797
 ****************************************************************************
3798
 * Parse track information and create all needed data to run a track
3799
 * If it succeed b_ok is set to 1 else to 0
3800
 ****************************************************************************/
3801
static void MP4_TrackSetup( demux_t *p_demux, mp4_track_t *p_track,
3802
                             const MP4_Box_t *p_box_trak,
3803
                             bool b_create_es, bool b_force_enable )
3804
3.92k
{
3805
3.92k
    demux_sys_t *p_sys = p_demux->p_sys;
3806
3807
3.92k
    p_track->p_track = p_box_trak;
3808
3809
3.92k
    char language[4] = { '\0' };
3810
3.92k
    char sdp_media_type[8] = { '\0' };
3811
3812
3.92k
    const MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
3813
3.92k
    if( !p_tkhd )
3814
52
    {
3815
52
        return;
3816
52
    }
3817
3818
    /* do we launch this track by default ? */
3819
3.87k
    p_track->b_enable =
3820
3.87k
        ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
3821
3822
3.87k
    p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
3823
3.87k
    p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
3824
3.87k
    p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
3825
3.87k
    p_track->i_flip = BOXDATA(p_tkhd)->i_flip;
3826
3827
    /* FIXME: unhandled box: tref */
3828
3829
3.87k
    const MP4_Box_t *p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
3830
3.87k
    const MP4_Box_t *p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
3831
3832
3.87k
    if( ( !p_mdhd )||( !p_hdlr ) )
3833
254
    {
3834
254
        return;
3835
254
    }
3836
3837
3.61k
    if( BOXDATA(p_mdhd)->i_timescale == 0 )
3838
6
    {
3839
6
        msg_Warn( p_demux, "Invalid track timescale " );
3840
6
        return;
3841
6
    }
3842
3.61k
    p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
3843
3844
3.61k
    memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
3845
3.61k
    p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
3846
3847
3.61k
    switch( p_hdlr->data.p_hdlr->i_handler_type )
3848
3.61k
    {
3849
1.17k
        case( ATOM_soun ):
3850
1.17k
            if( !MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) )
3851
6
            {
3852
6
                return;
3853
6
            }
3854
1.16k
            es_format_Change( &p_track->fmt, AUDIO_ES, 0 );
3855
1.16k
            break;
3856
3857
0
        case( ATOM_pict ): /* heif */
3858
0
            es_format_Change( &p_track->fmt, VIDEO_ES, 0 );
3859
0
            break;
3860
3861
1.41k
        case( ATOM_vide ):
3862
1.41k
            if( !MP4_BoxGet( p_box_trak, "mdia/minf/vmhd") )
3863
11
            {
3864
11
                return;
3865
11
            }
3866
1.40k
            es_format_Change( &p_track->fmt, VIDEO_ES, 0 );
3867
1.40k
            break;
3868
3869
322
        case( ATOM_hint ):
3870
            /* RTP Reception Hint tracks */
3871
322
            if( !MP4_BoxGet( p_box_trak, "mdia/minf/hmhd" ) ||
3872
159
                !MP4_BoxGet( p_box_trak, "mdia/minf/stbl/stsd/rrtp" ) )
3873
322
            {
3874
322
                break;
3875
322
            }
3876
0
            MP4_Box_t *p_sdp;
3877
3878
            /* parse the sdp message to find out whether the RTP stream contained audio or video */
3879
0
            if( !( p_sdp  = MP4_BoxGet( p_box_trak, "udta/hnti/sdp " ) ) )
3880
0
            {
3881
0
                msg_Warn( p_demux, "Didn't find sdp box to determine stream type" );
3882
0
                return;
3883
0
            }
3884
3885
0
            memcpy( sdp_media_type, BOXDATA(p_sdp)->psz_text, 7 );
3886
0
            if( !strcmp(sdp_media_type, "m=audio") )
3887
0
            {
3888
0
                msg_Dbg( p_demux, "Found audio Rtp: %s", sdp_media_type );
3889
0
                es_format_Change( &p_track->fmt, AUDIO_ES, 0 );
3890
0
            }
3891
0
            else if( !strcmp(sdp_media_type, "m=video") )
3892
0
            {
3893
0
                msg_Dbg( p_demux, "Found video Rtp: %s", sdp_media_type );
3894
0
                es_format_Change( &p_track->fmt, VIDEO_ES, 0 );
3895
0
            }
3896
0
            else
3897
0
            {
3898
0
                msg_Warn( p_demux, "Malformed track SDP message: %s", sdp_media_type );
3899
0
                return;
3900
0
            }
3901
0
            break;
3902
3903
332
        case( ATOM_tx3g ):
3904
618
        case( ATOM_text ):
3905
618
        case( ATOM_subp ):
3906
618
        case( ATOM_subt ): /* ttml */
3907
618
        case( ATOM_sbtl ):
3908
618
        case( ATOM_clcp ): /* closed captions */
3909
618
            es_format_Change( &p_track->fmt, SPU_ES, 0 );
3910
618
            break;
3911
3912
82
        default:
3913
82
            return;
3914
3.61k
    }
3915
3916
3.51k
    p_track->asfinfo.i_cat = p_track->fmt.i_cat;
3917
3918
3.51k
    const MP4_Box_t *p_elst;
3919
3.51k
    p_track->i_elst = 0;
3920
3.51k
    p_track->i_elst_time = 0;
3921
3.51k
    p_track->p_elst = NULL;
3922
3.51k
    if( ( p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
3923
2.04k
    {
3924
2.04k
        MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
3925
2.04k
        unsigned int i;
3926
3927
2.04k
        msg_Warn( p_demux, "elst box found" );
3928
2.04k
        bool use_editlist = var_InheritBool( p_demux, CFG_PREFIX"editlist" );
3929
3.99k
        for( i = 0; i < elst->i_entry_count; i++ )
3930
1.95k
        {
3931
1.95k
            const MP4_Box_data_elst_entry_t *edit = &elst->entries[i];
3932
1.95k
            if ( edit->i_segment_duration > INT64_MAX / CLOCK_FREQ ||
3933
1.95k
                 ( edit->i_media_time >= 0 && edit->i_media_time > INT64_MAX / CLOCK_FREQ ) )
3934
2
            {
3935
2
                use_editlist = false;
3936
2
                msg_Dbg( p_demux, "   - [%d] bogus duration=%" PRId64 " media time=%" PRId64 ")",
3937
2
                         i, edit->i_segment_duration, edit->i_media_time );
3938
2
            }
3939
1.95k
            else
3940
1.95k
            msg_Dbg( p_demux, "   - [%d] duration=%"PRId64"ms media time=%"PRId64
3941
1.95k
                     "ms) rate=%d.%d", i,
3942
1.95k
                     MP4_rescale( edit->i_segment_duration, p_sys->i_timescale, 1000 ),
3943
1.95k
                     edit->i_media_time >= 0 ?
3944
1.95k
                        MP4_rescale( edit->i_media_time, p_track->i_timescale, 1000 ) :
3945
1.95k
                        INT64_C(-1),
3946
1.95k
                     edit->i_media_rate_integer,
3947
1.95k
                     edit->i_media_rate_fraction );
3948
1.95k
        }
3949
3950
2.04k
        if( use_editlist )
3951
2.04k
            p_track->p_elst = p_elst;
3952
1
        else
3953
2.04k
            msg_Dbg( p_demux, "ignore editlist" );
3954
2.04k
    }
3955
3956
/*  TODO
3957
    add support for:
3958
    p_dinf = MP4_BoxGet( p_minf, "dinf" );
3959
*/
3960
3.51k
    if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
3961
3.27k
        !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
3962
278
    {
3963
278
        return;
3964
278
    }
3965
3966
    /* Set language */
3967
3.23k
    if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
3968
2.05k
    {
3969
2.05k
        p_track->fmt.psz_language = strdup( language );
3970
2.05k
    }
3971
3972
3.23k
    const MP4_Box_t *p_udta = MP4_BoxGet( p_box_trak, "udta" );
3973
3.23k
    if( p_udta )
3974
557
    {
3975
557
        const MP4_Box_t *p_box_iter;
3976
1.04k
        for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
3977
557
                 p_box_iter = p_box_iter->p_next )
3978
492
        {
3979
492
            switch( p_box_iter->i_type )
3980
492
            {
3981
0
                case ATOM_0xa9nam:
3982
174
                case ATOM_name:
3983
174
                    p_track->fmt.psz_description =
3984
174
                        strndup( p_box_iter->data.p_binary->p_blob,
3985
174
                                 p_box_iter->data.p_binary->i_blob );
3986
492
                default:
3987
492
                    break;
3988
492
            }
3989
492
        }
3990
557
    }
3991
3992
    /* Create chunk index table and sample index table */
3993
3.23k
    if( TrackCreateChunksIndex( p_demux,p_track  ) ||
3994
3.06k
        TrackCreateSamplesIndex( p_demux, p_track ) )
3995
187
    {
3996
187
        msg_Err( p_demux, "cannot create chunks index" );
3997
187
        return; /* cannot create chunks index */
3998
187
    }
3999
4000
3.04k
    p_track->i_next_dts = 0;
4001
3.04k
    p_track->i_next_delta = UNKNOWN_DELTA;
4002
3.04k
    p_track->i_chunk  = 0;
4003
3.04k
    p_track->i_sample = 0;
4004
4005
    /* Disable chapter only track */
4006
3.04k
    if( (p_track->i_use_flags & USEAS_CHAPTERS) && !p_sys->b_quicktime )
4007
0
        p_track->b_enable = false;
4008
4009
3.04k
    const MP4_Box_t *p_tsel;
4010
    /* now create es */
4011
3.04k
    if( b_force_enable &&
4012
546
        ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
4013
77
    {
4014
77
        msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
4015
77
                  p_track->i_track_ID );
4016
77
        p_track->b_enable = true;
4017
77
        p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
4018
77
    }
4019
2.97k
    else if ( (p_tsel = MP4_BoxGet( p_box_trak, "udta/tsel" )) )
4020
18
    {
4021
18
        if ( BOXDATA(p_tsel) && BOXDATA(p_tsel)->i_switch_group )
4022
1
        {
4023
1
            p_track->i_switch_group = BOXDATA(p_tsel)->i_switch_group;
4024
1
            int i_priority = ES_PRIORITY_SELECTABLE_MIN;
4025
3
            for ( unsigned int i = 0; i < p_sys->i_tracks; i++ )
4026
2
            {
4027
2
                const mp4_track_t *p_other = &p_sys->track[i];
4028
2
                if( p_other && p_other != p_track &&
4029
1
                    p_other->fmt.i_cat == p_track->fmt.i_cat &&
4030
0
                    p_track->i_switch_group == p_other->i_switch_group )
4031
0
                        i_priority = __MAX( i_priority, p_other->fmt.i_priority + 1 );
4032
2
            }
4033
            /* VLC only support ES priority for AUDIO_ES and SPU_ES.
4034
               If there's another VIDEO_ES in the same group, we need to unselect it then */
4035
1
            if ( p_track->fmt.i_cat == VIDEO_ES && i_priority > ES_PRIORITY_SELECTABLE_MIN )
4036
0
                p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
4037
1
            else
4038
1
                p_track->fmt.i_priority = i_priority;
4039
1
        }
4040
18
    }
4041
    /* If there's no tsel, try to enable the track coming first in edit list */
4042
2.95k
    else if ( p_track->p_elst && p_track->fmt.i_priority == ES_PRIORITY_SELECTABLE_MIN )
4043
1.68k
    {
4044
1.68k
#define MAX_SELECTABLE (INT_MAX - ES_PRIORITY_SELECTABLE_MIN)
4045
1.81k
        for ( uint32_t i=0; i<p_track->BOXDATA(p_elst)->i_entry_count; i++ )
4046
1.59k
        {
4047
1.59k
            const MP4_Box_data_elst_entry_t *edit = &p_track->BOXDATA(p_elst)->entries[i];
4048
1.59k
            if ( edit->i_media_time >= 0 && edit->i_segment_duration )
4049
1.46k
            {
4050
                /* We do selection by inverting start time into priority.
4051
                   The track with earliest edit will have the highest prio */
4052
1.46k
                const int i_time = __MIN( MAX_SELECTABLE, edit->i_media_time );
4053
1.46k
                p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + MAX_SELECTABLE - i_time;
4054
1.46k
                break;
4055
1.46k
            }
4056
1.59k
        }
4057
1.68k
    }
4058
4059
3.04k
    if( p_sys->hacks.es_cat_filter != UNKNOWN_ES &&
4060
0
        p_sys->hacks.es_cat_filter != p_track->fmt.i_cat )
4061
0
    {
4062
0
        p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
4063
0
    }
4064
4065
3.04k
    if( !p_track->b_enable || (p_track->i_use_flags & USEAS_CHAPTERS) )
4066
672
        p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
4067
4068
3.04k
    if( !p_sys->b_quicktime || (p_track->i_use_flags & USEAS_CHAPTERS) == 0 )
4069
3.04k
        b_create_es &= !MP4_isMetadata( p_track );
4070
4071
3.04k
    if( TrackCreateES( p_demux,
4072
3.04k
                       p_track, p_track->i_chunk,
4073
3.04k
                       !b_create_es ? NULL : &p_track->p_es ) )
4074
41
    {
4075
41
        msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
4076
41
                 p_track->i_track_ID );
4077
41
        return;
4078
41
    }
4079
4080
3.00k
    p_track->b_ok = true;
4081
3.00k
}
4082
4083
/****************************************************************************
4084
 * MP4_TrackClean:
4085
 ****************************************************************************
4086
 * Cleans a track created by MP4_TrackCreate.
4087
 ****************************************************************************/
4088
static void MP4_TrackClean( es_out_t *out, mp4_track_t *p_track )
4089
3.92k
{
4090
3.92k
    es_format_Clean( &p_track->fmt );
4091
4092
3.92k
    if( p_track->p_es )
4093
2.99k
        es_out_Del( out, p_track->p_es );
4094
4095
3.92k
    if( p_track->chunk )
4096
3.09k
    {
4097
243k
        for( unsigned int i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
4098
240k
            MP4_ChunkDestroy( &p_track->chunk[i_chunk] );
4099
3.09k
    }
4100
3.92k
    free( p_track->chunk );
4101
4102
3.92k
    if( !p_track->i_sample_size )
4103
1.76k
        free( p_track->p_sample_size );
4104
4105
3.92k
    ASFPacketTrackReset( &p_track->asfinfo );
4106
4107
3.92k
    free( p_track->context.runs.p_array );
4108
3.92k
}
4109
4110
static void MP4_TrackInit( mp4_track_t *p_track, const MP4_Box_t *p_trackbox )
4111
3.92k
{
4112
3.92k
    memset( p_track, 0, sizeof(mp4_track_t) );
4113
3.92k
    es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
4114
3.92k
    p_track->i_timescale = 1;
4115
3.92k
    p_track->p_track = p_trackbox;
4116
3.92k
    const MP4_Box_t *p_tkhd = MP4_BoxGet( p_trackbox, "tkhd" );
4117
3.92k
    if(likely(p_tkhd) && BOXDATA(p_tkhd))
4118
3.87k
        p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
4119
3.92k
    ASFPacketTrackInit( &p_track->asfinfo );
4120
3.92k
}
4121
4122
static void MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track, bool b_select )
4123
175M
{
4124
175M
    if( !p_track->b_ok || MP4_isMetadata(p_track) )
4125
60
        return;
4126
4127
175M
    if( b_select == p_track->b_selected )
4128
0
        return;
4129
4130
175M
    if( !b_select && p_track->p_es )
4131
175M
    {
4132
175M
        es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
4133
175M
                        p_track->p_es, false );
4134
175M
    }
4135
4136
175M
    p_track->b_selected = b_select;
4137
175M
}
4138
4139
static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
4140
                          vlc_tick_t i_start )
4141
216M
{
4142
216M
    uint32_t i_chunk;
4143
216M
    uint32_t i_sample;
4144
4145
216M
    if( !p_track->b_ok || MP4_isMetadata( p_track ) )
4146
0
        return VLC_EGENERIC;
4147
4148
216M
    p_track->b_selected = false;
4149
4150
216M
    if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
4151
216M
                                &i_chunk, &i_sample ) )
4152
41.2M
    {
4153
41.2M
        msg_Warn( p_demux, "cannot select track[Id 0x%x]",
4154
41.2M
                  p_track->i_track_ID );
4155
41.2M
        return VLC_EGENERIC;
4156
41.2M
    }
4157
4158
175M
    p_track->b_selected = true;
4159
175M
    if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
4160
175M
    {
4161
175M
        p_track->b_selected = true;
4162
175M
        TrackUpdateSampleAndTimes( p_track );
4163
175M
        TrackUpdateStarttimes( p_track );
4164
175M
    }
4165
4166
175M
    return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
4167
216M
}
4168
4169
4170
/*
4171
 * 3 types: for audio
4172
 *
4173
 */
4174
//#define MP4_DEBUG_AUDIO_SAMPLES
4175
static inline uint32_t MP4_GetAudioFrameInfo( const mp4_track_t *p_track,
4176
                                              const MP4_Box_data_sample_soun_t *p_soun,
4177
                                              uint32_t *pi_size )
4178
351M
{
4179
351M
    uint32_t i_samples_per_frame = p_soun->i_sample_per_packet;
4180
351M
    uint32_t i_bytes_per_frame = p_soun->i_bytes_per_frame;
4181
4182
351M
    switch( p_track->fmt.i_codec )
4183
351M
    {
4184
        /* Quicktime builtin support, _must_ ignore sample tables */
4185
344M
        case VLC_CODEC_GSM:
4186
344M
            i_samples_per_frame = 160;
4187
344M
            i_bytes_per_frame = 33;
4188
344M
            break;
4189
1.73k
        case VLC_CODEC_ADPCM_IMA_QT:
4190
1.73k
            i_samples_per_frame = 64;
4191
1.73k
            i_bytes_per_frame = 34 * p_soun->i_channelcount;
4192
1.73k
            break;
4193
0
        case VLC_CODEC_MACE3:
4194
0
            i_samples_per_frame = 6;
4195
0
            i_bytes_per_frame = 2 * p_soun->i_channelcount;
4196
0
            break;
4197
0
        case VLC_CODEC_MACE6:
4198
0
            i_samples_per_frame = 6;
4199
0
            i_bytes_per_frame = 1 * p_soun->i_channelcount;
4200
0
            break;
4201
1.79k
        case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
4202
1.79k
            i_samples_per_frame = 1;
4203
1.79k
            i_bytes_per_frame = p_soun->i_channelcount;
4204
1.79k
            break;
4205
225
        case VLC_CODEC_ALAW:
4206
3.19k
        case VLC_CODEC_U8:
4207
3.29k
        case VLC_CODEC_S8:
4208
208k
        case VLC_CODEC_S16L:
4209
222k
        case VLC_CODEC_S16B:
4210
222k
        case VLC_CODEC_S24L:
4211
223k
        case VLC_CODEC_S24B:
4212
223k
        case VLC_CODEC_S32L:
4213
223k
        case VLC_CODEC_S32B:
4214
229k
        case VLC_CODEC_F32L:
4215
229k
        case VLC_CODEC_F32B:
4216
230k
        case VLC_CODEC_F64L:
4217
230k
        case VLC_CODEC_F64B:
4218
230k
            i_samples_per_frame = 1;
4219
230k
            i_bytes_per_frame = (aout_BitsPerSample( p_track->fmt.i_codec ) *
4220
230k
                                 p_soun->i_channelcount) >> 3;
4221
230k
            assert(i_bytes_per_frame);
4222
230k
            break;
4223
230k
        case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
4224
0
        case ATOM_twos:
4225
0
        case ATOM_sowt:
4226
0
        case ATOM_raw:
4227
0
            if( p_soun->i_sample_per_packet && p_soun->i_bytes_per_frame )
4228
0
            {
4229
0
                i_samples_per_frame = p_soun->i_sample_per_packet;
4230
0
                i_bytes_per_frame = p_soun->i_bytes_per_frame;
4231
0
            }
4232
0
            else
4233
0
            {
4234
0
                i_samples_per_frame = 1;
4235
0
                i_bytes_per_frame = (p_soun->i_samplesize+7) >> 3;
4236
0
                i_bytes_per_frame *= p_soun->i_channelcount;
4237
0
            }
4238
0
            break;
4239
6.53M
        default:
4240
6.53M
            break;
4241
351M
    }
4242
4243
    /* Group audio packets so we don't call demux for single sample unit */
4244
351M
    if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
4245
205
        p_soun->i_constLPCMframesperaudiopacket &&
4246
0
        p_soun->i_constbytesperaudiopacket )
4247
0
    {
4248
0
        i_samples_per_frame = p_soun->i_constLPCMframesperaudiopacket;
4249
0
        i_bytes_per_frame = p_soun->i_constbytesperaudiopacket;
4250
0
    }
4251
#ifdef MP4_DEBUG_AUDIO_SAMPLES
4252
    printf("qtv%d comp%x ss %d chan %d ba %d spp %d bpf %d / %d %d\n",
4253
           p_soun->i_qt_version, p_soun->i_compressionid,
4254
           p_soun->i_samplesize, p_soun->i_channelcount,
4255
           p_track->fmt.audio.i_blockalign,
4256
           p_soun->i_sample_per_packet, p_soun->i_bytes_per_frame,
4257
           i_samples_per_frame, i_bytes_per_frame);
4258
#endif
4259
4260
351M
    *pi_size = i_bytes_per_frame;
4261
351M
    return i_samples_per_frame;
4262
351M
}
4263
4264
static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
4265
180M
{
4266
180M
    uint32_t i_size = 0;
4267
180M
    *pi_nb_samples = 0;
4268
4269
180M
    if ( p_track->i_sample == p_track->i_sample_count )
4270
0
        return 0;
4271
4272
180M
    if ( p_track->fmt.i_cat != AUDIO_ES )
4273
5.52M
    {
4274
5.52M
        *pi_nb_samples = 1;
4275
4276
5.52M
        if( p_track->i_sample_size == 0 ) /* all sizes are different */
4277
1.76M
            return p_track->p_sample_size[p_track->i_sample];
4278
3.75M
        else
4279
3.75M
            return p_track->i_sample_size;
4280
5.52M
    }
4281
175M
    else
4282
175M
    {
4283
175M
        const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
4284
175M
        const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
4285
4286
        /* v0:
4287
         * - isobmff: codec is not using v1 fields
4288
         * - qt: codec is usually uncompressed and 1 stored sample == 1 byte
4289
         * and you need to packetize/group samples. hardcoded codecs.
4290
         * if compressed, samplesize == 16 and codec is also hardcoded (ex: adpcm)
4291
         * v1:
4292
         * - samplesize is meaningless, always 16
4293
         * - compressed frames/packet size parameters applies, but samplesize can
4294
         * still be bytes. use packet size to deinterleave, but samples per frames
4295
         * are not the number of stored samples. The chunk can also be a packet in some
4296
         *  (qcelp) cases, in that case we need to return chunk (return 1 stored sample).
4297
         * If the codec has -2 compression, this is vbr, we can't deinterleave or group
4298
         * samples at all. (return 1 stored sample)
4299
         * Again, some hardcoded codecs can exist in qt and we can't trust parameters.
4300
         * v2:
4301
         * - lpcm extensions provides additional parameters to group samples, but
4302
         * 1 stored sample is usually too small in length/bytes, so we need to
4303
         * packetize group them. Again, 1 stored sample != 1 audio sample. */
4304
4305
175M
        if( p_track->fmt.i_original_fourcc == VLC_FOURCC('r','r','t','p') )
4306
0
        {
4307
0
            *pi_nb_samples = 1;
4308
0
            return p_track->i_sample_size;
4309
0
        }
4310
4311
        /* all samples have a different size */
4312
175M
        if( p_track->i_sample_size == 0 )
4313
15.7k
        {
4314
15.7k
            *pi_nb_samples = 1;
4315
15.7k
            return p_track->p_sample_size[p_track->i_sample];
4316
15.7k
        }
4317
4318
        /* If we are compressed but not v2 LPCM frames extensions */
4319
175M
        if ( p_soun->i_compressionid == 0xFFFE && p_soun->i_qt_version < 2 )
4320
1.79k
        {
4321
1.79k
            *pi_nb_samples = 1; /* != number of audio samples */
4322
1.79k
            if ( p_track->i_sample_size )
4323
1.79k
                return p_track->i_sample_size;
4324
0
            else
4325
0
                return p_track->p_sample_size[p_track->i_sample];
4326
1.79k
        }
4327
4328
        /* More regular V0 cases */
4329
175M
        uint32_t i_max_v0_samples;
4330
175M
        switch( p_track->fmt.i_codec )
4331
175M
        {
4332
            /* Compressed samples in V0 */
4333
266
            case VLC_CODEC_AMR_NB:
4334
3.48k
            case VLC_CODEC_AMR_WB:
4335
3.48k
                i_max_v0_samples = 16;
4336
3.48k
                break;
4337
1.40M
            case VLC_CODEC_MPGA:
4338
1.40M
            case VLC_CODEC_MP2:
4339
1.40M
            case VLC_CODEC_MP3:
4340
1.40M
            case VLC_CODEC_DTS:
4341
1.40M
            case VLC_CODEC_MP4A:
4342
1.40M
            case VLC_CODEC_A52:
4343
1.40M
            case VLC_CODEC_OPUS:
4344
1.40M
                i_max_v0_samples = 1;
4345
1.40M
                break;
4346
                /* fixme, reverse using a list of uncompressed codecs */
4347
173M
            default:
4348
                /* Read 25ms of samples (uncompressed) */
4349
173M
                i_max_v0_samples = p_track->fmt.audio.i_rate / 40 *
4350
173M
                                   p_track->fmt.audio.i_channels;
4351
173M
                if( i_max_v0_samples < 1 )
4352
22.7k
                    i_max_v0_samples = 1;
4353
173M
                break;
4354
175M
        }
4355
4356
175M
        *pi_nb_samples = 0;
4357
4358
175M
        if( p_track->i_sample_size > 0 )
4359
175M
        {
4360
175M
            uint32_t i_bytes_per_frame;
4361
175M
            uint32_t i_samples_per_frame =
4362
175M
                    MP4_GetAudioFrameInfo( p_track, p_soun, &i_bytes_per_frame );
4363
175M
            uint32_t i_chunk_remaining_samples = p_chunk->i_sample_count -
4364
175M
                    (p_track->i_sample - p_chunk->i_sample_first);
4365
4366
175M
            if( i_max_v0_samples > i_chunk_remaining_samples )
4367
446k
                i_max_v0_samples = i_chunk_remaining_samples;
4368
4369
175M
            if( i_samples_per_frame && i_bytes_per_frame )
4370
172M
            {
4371
                /* GSM, ADPCM,  */
4372
172M
                if( i_samples_per_frame > 64 &&
4373
172M
                    i_samples_per_frame > i_bytes_per_frame )
4374
172M
                {
4375
172M
                    *pi_nb_samples = i_samples_per_frame;
4376
172M
                    i_size = i_bytes_per_frame;
4377
172M
                }
4378
78.6k
                else
4379
78.6k
                {
4380
                    /* Regular cases */
4381
78.6k
                    uint32_t i_frames = __MAX(i_max_v0_samples / i_samples_per_frame, 1);
4382
78.6k
                    *pi_nb_samples = i_frames * i_samples_per_frame;
4383
78.6k
                    i_size = i_frames * i_bytes_per_frame;
4384
78.6k
                }
4385
172M
            }
4386
2.85M
            else
4387
2.85M
            {
4388
2.85M
                *pi_nb_samples = 1;
4389
2.85M
                return p_track->i_sample_size;
4390
2.85M
            }
4391
#ifdef MP4_DEBUG_AUDIO_SAMPLES
4392
            printf("demuxing qtv%d comp %x, ss%d, spf %d bpf %d samples %d maxsamples %d remain samples %d\n",
4393
                    p_soun->i_qt_version, p_soun->i_compressionid, p_track->i_sample_size,
4394
                    i_samples_per_frame, i_bytes_per_frame,
4395
                    *pi_nb_samples, i_max_v0_samples, i_chunk_remaining_samples);
4396
#endif
4397
175M
        }
4398
0
        else /* Compressed */
4399
0
        {
4400
0
            for( uint32_t i=p_track->i_sample;
4401
0
                 i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
4402
0
                 i<p_track->i_sample_count;
4403
0
                 i++ )
4404
0
            {
4405
0
                i_size += p_track->p_sample_size[i];
4406
0
                (*pi_nb_samples)++;
4407
4408
                /* Try to detect compression in ISO */
4409
0
                if(p_soun->i_compressionid != 0)
4410
0
                {
4411
                    /* Return only 1 sample */
4412
0
                    break;
4413
0
                }
4414
4415
0
                if ( *pi_nb_samples == i_max_v0_samples )
4416
0
                    break;
4417
0
            }
4418
0
        }
4419
175M
    }
4420
4421
172M
    return i_size;
4422
180M
}
4423
4424
static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
4425
185M
{
4426
185M
    unsigned int i_sample;
4427
185M
    uint64_t i_pos;
4428
4429
185M
    i_pos = p_track->chunk[p_track->i_chunk].i_offset;
4430
4431
185M
    if( p_track->i_sample_size )
4432
182M
    {
4433
        /* chunk offset in samples */
4434
182M
        uint32_t i_samples = p_track->i_sample -
4435
182M
                             p_track->chunk[p_track->i_chunk].i_sample_first;
4436
4437
182M
        if( p_track->fmt.i_cat == AUDIO_ES )
4438
176M
        {
4439
176M
            MP4_Box_data_sample_soun_t *p_soun =
4440
176M
                p_track->p_sample->data.p_sample_soun;
4441
4442
176M
            if( p_soun->i_compressionid != 0xFFFE )
4443
176M
            {
4444
176M
                uint32_t i_bytes_per_frame;
4445
176M
                uint32_t i_samples_per_frame = MP4_GetAudioFrameInfo( p_track, p_soun, &i_bytes_per_frame );
4446
176M
                if( i_bytes_per_frame && i_samples_per_frame )
4447
172M
                {
4448
                    /* we read chunk by chunk unless a blockalign is requested */
4449
172M
                    return i_pos + i_samples /
4450
172M
                                   i_samples_per_frame * (uint64_t) i_bytes_per_frame;
4451
172M
                }
4452
176M
            }
4453
176M
        }
4454
4455
10.3M
        i_pos += i_samples * (uint64_t) p_track->i_sample_size;
4456
10.3M
    }
4457
2.37M
    else
4458
2.37M
    {
4459
2.37M
        for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
4460
11.7M
             i_sample < p_track->i_sample; i_sample++ )
4461
9.33M
        {
4462
9.33M
            i_pos += p_track->p_sample_size[i_sample];
4463
9.33M
        }
4464
2.37M
    }
4465
4466
12.7M
    return i_pos;
4467
185M
}
4468
4469
4470
static int MP4_TrackSetNextELST( mp4_track_t *tk )
4471
917k
{
4472
917k
    if( !tk->p_elst ||
4473
917k
         tk->i_elst == UINT32_MAX - 1 ||
4474
917k
         tk->i_elst + 1 >= tk->BOXDATA(p_elst)->i_entry_count )
4475
917k
        return VLC_EGENERIC;
4476
4477
2
    tk->i_elst_time += tk->BOXDATA(p_elst)->entries[tk->i_elst++].i_segment_duration;
4478
4479
2
    return VLC_SUCCESS;
4480
917k
}
4481
4482
static int MP4_TrackUpdateELST( mp4_track_t *tk, uint32_t i_movie_timescale,
4483
                                stime_t i_track_time, uint32_t i_track_sample )
4484
1.67M
{
4485
1.67M
    if( !tk->p_elst || tk->BOXDATA(p_elst)->i_entry_count == 0 )
4486
37.6k
        return VLC_SUCCESS;
4487
4488
1.64M
    if( i_track_sample >= tk->i_sample_count )
4489
543
        return MP4_TrackSetNextELST( tk );
4490
4491
1.64M
    vlc_tick_t i_time = MP4_rescale_mtime( i_track_time, tk->i_timescale );
4492
1.64M
    for(;;)
4493
1.64M
    {
4494
1.64M
        const MP4_Box_data_elst_entry_t *edit = &tk->BOXDATA(p_elst)->entries[tk->i_elst];
4495
1.64M
        vlc_tick_t i_end = MP4_rescale_mtime( edit->i_media_time, tk->i_timescale ) +
4496
1.64M
                           MP4_rescale_mtime( edit->i_segment_duration, i_movie_timescale );
4497
1.64M
        if ( i_time < i_end || MP4_TrackSetNextELST( tk ) )
4498
1.64M
            break;
4499
1.64M
    }
4500
4501
1.64M
    return VLC_SUCCESS;
4502
1.64M
}
4503
4504
static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
4505
5.13M
{
4506
5.13M
    demux_sys_t *p_sys = p_demux->p_sys;
4507
4508
5.13M
    if ( UINT32_MAX - p_track->i_sample < i_samples )
4509
0
        i_samples = UINT32_MAX - p_track->i_sample; /* Ensure we won't overflow next add */
4510
4511
5.13M
    p_track->i_sample += i_samples;
4512
5.13M
    const uint32_t i_previous_chunk = p_track->i_chunk;
4513
4514
5.13M
    if( p_track->i_sample < p_track->i_sample_count )
4515
5.13M
    {
4516
        /* Have we changed chunk ? */
4517
5.64M
        while( p_track->i_sample >=
4518
5.64M
               p_track->chunk[p_track->i_chunk].i_sample_first +
4519
5.64M
               p_track->chunk[p_track->i_chunk].i_sample_count &&
4520
509k
               p_track->i_chunk < p_track->i_chunk_count - 1 )
4521
509k
        {
4522
509k
            p_track->i_chunk++;
4523
509k
        }
4524
5.13M
    }
4525
4526
5.13M
    if( p_track->p_elst ) /* Update */
4527
1.67M
    {
4528
1.67M
        uint32_t i_prev_elst = p_track->i_elst;
4529
1.67M
        TrackUpdateSampleAndTimes( p_track );
4530
1.67M
        MP4_TrackUpdateELST( p_track, p_sys->i_timescale, p_track->i_next_dts, p_track->i_sample);
4531
1.67M
        if( p_track->i_elst != i_prev_elst )
4532
2
        {
4533
2
            msg_Dbg( p_demux, "changed elst %u -> %u", i_prev_elst, p_track->i_elst);
4534
            /* *** find good chunk *** */
4535
2
            uint32_t i_sample, i_chunk;
4536
2
            stime_t i_start = p_track->BOXDATA(p_elst)->entries[p_track->i_elst].i_media_time;
4537
2
            if( STTSToSampleChunk( p_track, i_start, &i_chunk, &i_sample ) != VLC_SUCCESS )
4538
0
            {
4539
0
                msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
4540
0
                          "(seeking too far) chunk=%"PRIu32" sample=%"PRIu32,
4541
0
                          p_track->i_track_ID, i_chunk, i_sample );
4542
0
                return VLC_EGENERIC;
4543
0
            }
4544
2
            p_track->i_chunk = i_chunk;
4545
2
            p_track->i_sample = i_sample;
4546
2
        }
4547
1.67M
    }
4548
4549
5.13M
    TrackUpdateSampleAndTimes( p_track );
4550
4551
5.13M
    if( TrackUpdateFormat( p_demux, p_track, i_previous_chunk ) != VLC_SUCCESS )
4552
60
    {
4553
60
        msg_Warn( p_demux, "track[0x%x] will be disabled "
4554
60
                  "(cannot restart decoder)", p_track->i_track_ID );
4555
60
        MP4_TrackSelect( p_demux, p_track, false );
4556
60
        return VLC_EGENERIC;
4557
60
    }
4558
4559
5.13M
    if( !p_track->b_selected || p_track->i_sample >= p_track->i_sample_count )
4560
630
        return VLC_EGENERIC;
4561
4562
5.13M
    return VLC_SUCCESS;
4563
5.13M
}
4564
4565
static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
4566
                              vlc_tick_t i_time )
4567
216M
{
4568
216M
    demux_sys_t *p_sys = p_demux->p_sys;
4569
216M
    uint32_t i_elst_last = tk->i_elst;
4570
4571
    /* handle elst (find the correct one) */
4572
216M
    tk->i_elst      = 0;
4573
216M
    tk->i_elst_time = 0;
4574
216M
    if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
4575
200M
    {
4576
200M
        MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
4577
200M
        int64_t i_mvt= MP4_rescale_qtime( i_time, p_sys->i_timescale );
4578
4579
397M
        for( tk->i_elst = 0; tk->i_elst < elst->i_entry_count; tk->i_elst++ )
4580
200M
        {
4581
200M
            uint64_t i_dur = elst->entries[tk->i_elst].i_segment_duration;
4582
4583
200M
            if( elst->entries[tk->i_elst].i_media_time >=0 &&
4584
200M
                tk->i_elst_time <= i_mvt &&
4585
200M
                i_mvt < (int64_t)(tk->i_elst_time + i_dur) )
4586
3.86M
            {
4587
3.86M
                break;
4588
3.86M
            }
4589
196M
            tk->i_elst_time += i_dur;
4590
196M
        }
4591
4592
200M
        if( tk->i_elst >= elst->i_entry_count )
4593
196M
        {
4594
            /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
4595
196M
            tk->i_elst = elst->i_entry_count - 1;
4596
196M
            tk->i_elst_time -= elst->entries[tk->i_elst].i_segment_duration;
4597
196M
        }
4598
4599
200M
        if( i_elst_last != tk->i_elst )
4600
3
        {
4601
3
            msg_Warn( p_demux, "elst old=%d new=%"PRIu32, i_elst_last, tk->i_elst );
4602
3
            if( i_elst_last < elst->i_entry_count &&
4603
3
                elst->entries[i_elst_last].i_media_time >= 0 )
4604
0
                tk->i_next_block_flags |= BLOCK_FLAG_DISCONTINUITY;
4605
3
        }
4606
200M
    }
4607
216M
}
4608
4609
/******************************************************************************
4610
 *     Here are the functions used for fragmented MP4
4611
 *****************************************************************************/
4612
#if 0
4613
/**
4614
 * Re-init decoder.
4615
 * \Note If we call that function too soon,
4616
 * before the track has been selected by MP4_TrackSelect
4617
 * (during the first execution of Demux), then the track gets disabled
4618
 */
4619
static int ReInitDecoder( demux_t *p_demux, const MP4_Box_t *p_root,
4620
                          mp4_track_t *p_track )
4621
{
4622
    MP4_Box_t *p_paramsbox = MP4_BoxGet( p_root, "/moov/trak[0]" );
4623
    if( !p_paramsbox )
4624
        return VLC_EGENERIC;
4625
4626
    MP4_TrackRestart( p_demux, p_track, p_paramsbox );
4627
4628
    /* Temporary hack until we support track selection */
4629
    p_track->b_selected = true;
4630
    p_track->b_enable = true;
4631
4632
    return VLC_SUCCESS;
4633
}
4634
#endif
4635
4636
static stime_t GetCumulatedDuration( demux_t *p_demux )
4637
48
{
4638
48
    demux_sys_t *p_sys = p_demux->p_sys;
4639
48
    stime_t i_max_duration = 0;
4640
4641
155
    for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
4642
107
    {
4643
107
        MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->p_moov, p_sys->track[i].i_track_ID );
4644
107
        const MP4_Box_t *p_stsz;
4645
107
        const MP4_Box_t *p_tkhd;
4646
107
        if ( (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) &&
4647
83
             (p_stsz = MP4_BoxGet( p_trak, "mdia/minf/stbl/stsz" )) &&
4648
             /* duration might be wrong an be set to whole duration :/ */
4649
60
             BOXDATA(p_stsz)->i_sample_count > 0 )
4650
32
        {
4651
32
            i_max_duration = __MAX( (uint64_t)i_max_duration, BOXDATA(p_tkhd)->i_duration );
4652
32
        }
4653
107
    }
4654
48
    if( p_sys->p_fragsindex )
4655
27
    {
4656
27
        stime_t i_tracks_duration = MP4_Fragment_Index_GetTracksDuration( p_sys->p_fragsindex );
4657
27
        i_max_duration = __MAX( i_max_duration, i_tracks_duration );
4658
27
    }
4659
4660
48
    return i_max_duration;
4661
48
}
4662
4663
static int ProbeIndex( demux_t *p_demux )
4664
0
{
4665
0
    demux_sys_t *p_sys = p_demux->p_sys;
4666
0
    uint64_t i_stream_size;
4667
0
    uint8_t mfro[MP4_MFRO_BOXSIZE];
4668
0
    assert( p_sys->b_seekable );
4669
4670
0
    if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4671
0
        return VLC_EGENERIC;
4672
4673
0
    if ( vlc_stream_GetSize( p_demux->s, &i_stream_size ) != VLC_SUCCESS )
4674
0
        return VLC_EGENERIC;
4675
4676
0
    if ( i_stream_size < MP4_MFRO_BOXSIZE ||
4677
0
         vlc_stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4678
0
    {
4679
0
        msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4680
0
        return VLC_EGENERIC;
4681
0
    }
4682
4683
0
    if ( vlc_stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4684
0
         VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4685
0
         GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4686
0
    {
4687
0
        uint32_t i_offset = GetDWBE( &mfro[12] );
4688
0
        msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4689
0
        if ( i_stream_size > i_offset &&
4690
0
             vlc_stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4691
0
        {
4692
0
            msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4693
0
            const uint32_t stoplist[] = { ATOM_mfra, 0 };
4694
0
            MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, stoplist );
4695
0
        }
4696
0
        return VLC_SUCCESS;
4697
0
    }
4698
0
    return VLC_EGENERIC;
4699
0
}
4700
4701
static stime_t GetMoovTrackDuration( demux_sys_t *p_sys, unsigned i_track_ID )
4702
286
{
4703
286
    MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->p_moov, i_track_ID );
4704
286
    const MP4_Box_t *p_stsz;
4705
286
    const MP4_Box_t *p_tkhd;
4706
286
    if ( (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) &&
4707
259
         (p_stsz = MP4_BoxGet( p_trak, "mdia/minf/stbl/stsz" )) &&
4708
         /* duration might be wrong an be set to whole duration :/ */
4709
210
         BOXDATA(p_stsz)->i_sample_count > 0 )
4710
12
    {
4711
12
        if( BOXDATA(p_tkhd)->i_duration <= p_sys->i_moov_duration )
4712
12
            return BOXDATA(p_tkhd)->i_duration; /* In movie / mvhd scale */
4713
0
        else
4714
0
            return p_sys->i_moov_duration;
4715
12
    }
4716
274
    return 0;
4717
286
}
4718
4719
static bool GetMoofTrackDuration( MP4_Box_t *p_moov, MP4_Box_t *p_moof,
4720
                                  unsigned i_track_ID, stime_t *p_duration )
4721
1.24k
{
4722
1.24k
    if ( !p_moof || !p_moov )
4723
0
        return false;
4724
4725
1.24k
    MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4726
1.65k
    while ( p_traf )
4727
950
    {
4728
950
        if ( p_traf->i_type != ATOM_traf )
4729
79
        {
4730
79
           p_traf = p_traf->p_next;
4731
79
           continue;
4732
79
        }
4733
4734
871
        const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4735
871
        const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4736
871
        if ( !p_tfhd || !p_trun || i_track_ID != BOXDATA(p_tfhd)->i_track_ID )
4737
281
        {
4738
281
           p_traf = p_traf->p_next;
4739
281
           continue;
4740
281
        }
4741
4742
590
        uint32_t i_track_timescale = 0;
4743
590
        uint32_t i_track_defaultsampleduration = 0;
4744
4745
        /* set trex for defaults */
4746
590
        MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moov, BOXDATA(p_tfhd)->i_track_ID );
4747
590
        if ( p_trex )
4748
476
        {
4749
476
            i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4750
476
        }
4751
4752
590
        MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_moov, BOXDATA(p_tfhd)->i_track_ID );
4753
590
        if ( p_trak )
4754
590
        {
4755
590
            MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4756
590
            if ( p_mdhd )
4757
534
                i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4758
590
        }
4759
4760
590
        if ( !i_track_timescale )
4761
56
        {
4762
56
           p_traf = p_traf->p_next;
4763
56
           continue;
4764
56
        }
4765
4766
534
        uint64_t i_traf_duration = 0;
4767
1.27k
        while ( p_trun && p_tfhd )
4768
736
        {
4769
736
            if ( p_trun->i_type != ATOM_trun )
4770
200
            {
4771
200
               p_trun = p_trun->p_next;
4772
200
               continue;
4773
200
            }
4774
536
            const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4775
4776
            /* Sum total time */
4777
536
            if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4778
528
            {
4779
5.33k
                for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4780
4.80k
                    i_traf_duration += p_trundata->p_samples[i].i_duration;
4781
528
            }
4782
8
            else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4783
0
            {
4784
0
                i_traf_duration += (uint64_t)p_trundata->i_sample_count *
4785
0
                        BOXDATA(p_tfhd)->i_default_sample_duration;
4786
0
            }
4787
8
            else
4788
8
            {
4789
8
                i_traf_duration += (uint64_t)p_trundata->i_sample_count *
4790
8
                        i_track_defaultsampleduration;
4791
8
            }
4792
4793
536
            p_trun = p_trun->p_next;
4794
536
        }
4795
4796
534
        *p_duration = i_traf_duration;
4797
534
        return true;
4798
590
    }
4799
4800
707
    return false;
4801
1.24k
}
4802
4803
static int ProbeFragments( demux_t *p_demux, bool b_force, bool *pb_fragmented )
4804
155
{
4805
155
    demux_sys_t *p_sys = p_demux->p_sys;
4806
4807
155
    msg_Dbg( p_demux, "probing fragments from %"PRId64, vlc_stream_Tell( p_demux->s ) );
4808
4809
155
    assert( p_sys->p_root );
4810
4811
155
    MP4_Box_t *p_vroot = MP4_BoxNew(ATOM_root);
4812
155
    if( !p_vroot )
4813
0
        return VLC_EGENERIC;
4814
4815
155
    if( p_sys->b_seekable && (p_sys->b_fastseekable || b_force) )
4816
155
    {
4817
155
        MP4_ReadBoxContainerChildren( p_demux->s, p_vroot, NULL ); /* Get the rest of the file */
4818
155
        p_sys->b_fragments_probed = true;
4819
4820
155
        const unsigned i_moof = MP4_BoxCount( p_vroot, "/moof" );
4821
155
        if( i_moof )
4822
133
        {
4823
133
            *pb_fragmented = true;
4824
133
            p_sys->p_fragsindex = MP4_Fragments_Index_New( p_sys->i_tracks, i_moof );
4825
133
            if( !p_sys->p_fragsindex )
4826
0
            {
4827
0
                MP4_BoxFree( p_vroot );
4828
0
                return VLC_EGENERIC;
4829
0
            }
4830
4831
133
            stime_t *pi_track_times = calloc( p_sys->i_tracks, sizeof(*pi_track_times) );
4832
133
            if( !pi_track_times )
4833
0
            {
4834
0
                MP4_Fragments_Index_Delete( p_sys->p_fragsindex );
4835
0
                p_sys->p_fragsindex = NULL;
4836
0
                MP4_BoxFree( p_vroot );
4837
0
                return VLC_EGENERIC;
4838
0
            }
4839
4840
133
            unsigned index = 0;
4841
4842
2.26k
            for( MP4_Box_t *p_moof = p_vroot->p_first; p_moof; p_moof = p_moof->p_next )
4843
2.13k
            {
4844
2.13k
                if( p_moof->i_type != ATOM_moof )
4845
1.45k
                    continue;
4846
4847
1.91k
                for( unsigned i=0; i<p_sys->i_tracks; i++ )
4848
1.24k
                {
4849
1.24k
                    MP4_Box_t *p_tfdt = NULL;
4850
1.24k
                    MP4_Box_t *p_traf = MP4_GetTrafByTrackID( p_moof, p_sys->track[i].i_track_ID );
4851
1.24k
                    if( p_traf )
4852
638
                        p_tfdt = MP4_BoxGet( p_traf, "tfdt" );
4853
4854
1.24k
                    if( p_tfdt && BOXDATA(p_tfdt) )
4855
0
                    {
4856
0
                        pi_track_times[i] = p_tfdt->data.p_tfdt->i_base_media_decode_time;
4857
0
                    }
4858
1.24k
                    else if( index == 0 ) /* Set first fragment time offset from moov */
4859
273
                    {
4860
273
                        stime_t i_duration = GetMoovTrackDuration( p_sys, p_sys->track[i].i_track_ID );
4861
273
                        pi_track_times[i] = MP4_rescale( i_duration, p_sys->i_timescale, p_sys->track[i].i_timescale );
4862
273
                    }
4863
4864
1.24k
                    stime_t i_movietime = MP4_rescale( pi_track_times[i], p_sys->track[i].i_timescale, p_sys->i_timescale );
4865
1.24k
                    p_sys->p_fragsindex->p_times[index * p_sys->i_tracks + i] = i_movietime;
4866
4867
1.24k
                    stime_t i_duration = 0;
4868
1.24k
                    if( GetMoofTrackDuration( p_sys->p_moov, p_moof, p_sys->track[i].i_track_ID, &i_duration ) )
4869
534
                        pi_track_times[i] += i_duration;
4870
1.24k
                }
4871
4872
678
                p_sys->p_fragsindex->pi_pos[index++] = p_moof->i_pos;
4873
678
            }
4874
4875
406
            for( unsigned i=0; i<p_sys->i_tracks; i++ )
4876
273
            {
4877
273
                stime_t i_movietime = MP4_rescale( pi_track_times[i], p_sys->track[i].i_timescale, p_sys->i_timescale );
4878
273
                if( p_sys->p_fragsindex->i_last_time < i_movietime )
4879
91
                    p_sys->p_fragsindex->i_last_time = i_movietime;
4880
273
            }
4881
4882
133
            free( pi_track_times );
4883
133
#ifdef MP4_VERBOSE
4884
133
            MP4_Fragments_Index_Dump( VLC_OBJECT(p_demux), p_sys->p_fragsindex, p_sys->i_timescale );
4885
133
#endif
4886
133
        }
4887
155
    }
4888
0
    else
4889
0
    {
4890
        /* We stop at first moof, which validates our fragmentation condition
4891
         * and we'll find others while reading. */
4892
0
        const uint32_t excllist[] = { ATOM_moof, 0 };
4893
0
        MP4_ReadBoxContainerRestricted( p_demux->s, p_vroot, NULL, excllist );
4894
        /* Peek since we stopped before restriction */
4895
0
        const uint8_t *p_peek;
4896
0
        if ( vlc_stream_Peek( p_demux->s, &p_peek, 8 ) == 8 )
4897
0
            *pb_fragmented = (VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) == ATOM_moof);
4898
0
        else
4899
0
            *pb_fragmented = false;
4900
0
    }
4901
4902
155
    MP4_BoxFree( p_vroot );
4903
4904
155
    MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->p_moov, "mvex/mehd");
4905
155
    if ( !p_mehd )
4906
48
           p_sys->i_cumulated_duration = GetCumulatedDuration( p_demux );
4907
4908
155
    return VLC_SUCCESS;
4909
155
}
4910
4911
static int ProbeFragmentsChecked( demux_t *p_demux )
4912
0
{
4913
0
    demux_sys_t *p_sys = p_demux->p_sys;
4914
4915
0
    if( p_sys->b_fragments_probed )
4916
0
        return VLC_SUCCESS;
4917
4918
0
    if( !p_sys->b_fastseekable )
4919
0
    {
4920
0
        const char *psz_msg = _(
4921
0
            "Because this file index is broken or missing, "
4922
0
            "seeking will not work correctly.\n"
4923
0
            "VLC won't repair your file but can temporary fix this "
4924
0
            "problem by building an index in memory.\n"
4925
0
            "This step might take a long time on a large file.\n"
4926
0
            "What do you want to do?");
4927
0
        bool b_continue = vlc_dialog_wait_question( p_demux,
4928
0
                                               VLC_DIALOG_QUESTION_NORMAL,
4929
0
                                               _("Do not seek"),
4930
0
                                               _("Build index"),
4931
0
                                               NULL,
4932
0
                                               _("Broken or missing Index"),
4933
0
                                               "%s", psz_msg );
4934
0
        if( !b_continue )
4935
0
            return VLC_EGENERIC;
4936
0
    }
4937
4938
0
    const uint64_t i_backup_pos = vlc_stream_Tell( p_demux->s );
4939
0
    int i_ret = vlc_stream_Seek( p_demux->s, p_sys->p_moov->i_pos + p_sys->p_moov->i_size );
4940
0
    if( i_ret == VLC_SUCCESS )
4941
0
    {
4942
0
        bool foo;
4943
0
        i_ret = ProbeFragments( p_demux, true, &foo );
4944
0
        p_sys->b_fragments_probed = true;
4945
0
    }
4946
4947
0
    if( i_ret != VLC_SUCCESS )
4948
0
        p_sys->b_error = (vlc_stream_Seek( p_demux->s, i_backup_pos ) != VLC_SUCCESS);
4949
4950
0
    return i_ret;
4951
0
}
4952
4953
static void FragResetContext( demux_sys_t *p_sys )
4954
3.30k
{
4955
3.30k
    if( p_sys->context.p_fragment_atom )
4956
631
    {
4957
631
        if( p_sys->context.p_fragment_atom != p_sys->p_moov )
4958
429
            MP4_BoxFree( p_sys->context.p_fragment_atom );
4959
631
        p_sys->context.p_fragment_atom = NULL;
4960
631
    }
4961
3.30k
    p_sys->context.i_current_box_type = 0;
4962
4963
8.28k
    for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
4964
4.97k
    {
4965
4.97k
        mp4_track_t *p_track = &p_sys->track[i];
4966
4.97k
        p_track->context.i_default_sample_size = 0;
4967
4.97k
        p_track->context.i_default_sample_duration = 0;
4968
4.97k
    }
4969
3.30k
}
4970
4971
static int FragDemuxTrack( demux_t *p_demux, mp4_track_t *p_track,
4972
                           vlc_tick_t i_max_preload )
4973
2.82k
{
4974
2.82k
    if( !p_track->b_ok ||
4975
2.82k
         p_track->context.runs.i_current >= p_track->context.runs.i_count )
4976
0
        return VLC_DEMUXER_EOS;
4977
4978
2.82k
    const MP4_Box_data_trun_t *p_trun =
4979
2.82k
            p_track->context.runs.p_array[p_track->context.runs.i_current].p_trun->data.p_trun;
4980
4981
2.82k
    uint32_t dur = p_track->context.i_default_sample_duration,
4982
2.82k
             len = p_track->context.i_default_sample_size;
4983
4984
2.82k
    if( vlc_stream_Tell(p_demux->s) != p_track->context.i_trun_sample_pos &&
4985
205
        MP4_Seek( p_demux->s, p_track->context.i_trun_sample_pos ) != VLC_SUCCESS )
4986
0
        return VLC_DEMUXER_EOF;
4987
4988
2.82k
    const stime_t i_demux_max_dts = (i_max_preload < INVALID_PRELOAD) ?
4989
2.82k
                p_track->i_time + MP4_rescale_qtime( i_max_preload, p_track->i_timescale ) :
4990
2.82k
                VLC_TICK_MAX;
4991
4992
5.69k
    for( uint32_t i = p_track->context.i_trun_sample; i < p_trun->i_sample_count; i++ )
4993
5.57k
    {
4994
5.57k
        const stime_t i_dts = p_track->i_time;
4995
5.57k
        stime_t i_pts = i_dts;
4996
4997
5.57k
        if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4998
2.27k
            dur = p_trun->p_samples[i].i_duration;
4999
5000
5.57k
        if( i_dts > i_demux_max_dts )
5001
2.62k
            return VLC_DEMUXER_SUCCESS;
5002
5003
2.95k
        p_track->i_time += dur;
5004
2.95k
        p_track->context.i_trun_sample = i + 1;
5005
5006
2.95k
        if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
5007
1.25k
        {
5008
1.25k
            if ( p_trun->i_version == 1 )
5009
0
                i_pts += p_trun->p_samples[i].i_composition_time_offset.v1;
5010
1.25k
            else if( p_trun->p_samples[i].i_composition_time_offset.v0 < 0xFF000000 )
5011
1.24k
                i_pts += p_trun->p_samples[i].i_composition_time_offset.v0;
5012
11
            else /* version 0 with negative */
5013
11
                i_pts += p_trun->p_samples[i].i_composition_time_offset.v1;
5014
1.25k
        }
5015
5016
2.95k
        if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
5017
2.61k
            len = p_trun->p_samples[i].i_size;
5018
5019
2.95k
        if( !dur )
5020
2.95k
            msg_Warn(p_demux, "Zero duration sample in trun.");
5021
5022
2.95k
        if( !len )
5023
2.95k
            msg_Warn(p_demux, "Zero length sample in trun.");
5024
5025
2.95k
        len = OverflowCheck( p_demux, p_track, vlc_stream_Tell(p_demux->s), len );
5026
5027
2.95k
        block_t *p_block = vlc_stream_Block( p_demux->s, len );
5028
2.95k
        uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
5029
2.95k
        p_track->context.i_trun_sample_pos += i_read;
5030
2.95k
        if( i_read < len || p_block == NULL )
5031
82
        {
5032
82
            if( p_block )
5033
76
                block_Release( p_block );
5034
82
            return VLC_DEMUXER_FATAL;
5035
82
        }
5036
5037
#if 0
5038
        msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, p_track->i_track_ID,
5039
                 VLC_TICK_0 + MP4_rescale_mtime( i_dts, p_track->i_timescale ),
5040
                 VLC_TICK_0 + MP4_rescale_mtime( i_pts, p_track->i_timescale ),
5041
                 p_track->context.i_trun_sample_pos - i_read );
5042
#endif
5043
2.87k
        if ( p_track->p_es )
5044
2.87k
        {
5045
2.87k
            p_block->i_dts = VLC_TICK_0 + MP4_rescale_mtime( i_dts, p_track->i_timescale );
5046
2.87k
            if( p_track->fmt.i_cat == VIDEO_ES && !( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET ) )
5047
1.34k
                p_block->i_pts = VLC_TICK_INVALID;
5048
1.52k
            else
5049
1.52k
                p_block->i_pts = VLC_TICK_0 + MP4_rescale_mtime( i_pts, p_track->i_timescale );
5050
2.87k
            p_block->i_length = MP4_rescale_mtime( dur, p_track->i_timescale );
5051
2.87k
            MP4_Block_Send( p_demux, p_track, p_block );
5052
2.87k
        }
5053
0
        else block_Release( p_block );
5054
2.87k
    }
5055
5056
123
    if( p_track->context.i_trun_sample == p_trun->i_sample_count )
5057
123
    {
5058
123
        p_track->context.i_trun_sample = 0;
5059
123
        if( ++p_track->context.runs.i_current < p_track->context.runs.i_count )
5060
0
        {
5061
0
            p_track->i_time = p_track->context.runs.p_array[p_track->context.runs.i_current].i_first_dts;
5062
0
            p_track->context.i_trun_sample_pos = p_track->context.runs.p_array[p_track->context.runs.i_current].i_offset;
5063
0
        }
5064
123
    }
5065
5066
123
    return VLC_DEMUXER_SUCCESS;
5067
2.82k
}
5068
5069
static int DemuxMoof( demux_t *p_demux )
5070
9.80M
{
5071
9.80M
    demux_sys_t *p_sys = p_demux->p_sys;
5072
9.80M
    int i_status;
5073
5074
9.80M
    const vlc_tick_t i_max_preload = ( p_sys->b_fastseekable ) ? 0 : ( p_sys->b_seekable ) ? DEMUX_TRACK_MAX_PRELOAD : INVALID_PRELOAD;
5075
5076
9.80M
    const vlc_tick_t i_nztime = MP4_GetMoviePTS( p_sys );
5077
5078
    /* !important! Ensure clock is set before sending data */
5079
9.80M
    if( p_sys->i_pcr == VLC_TICK_INVALID )
5080
175
        es_out_SetPCR( p_demux->out, VLC_TICK_0 + i_nztime );
5081
5082
    /* Set per track read state */
5083
19.6M
    for( unsigned i = 0; i < p_sys->i_tracks; i++ )
5084
9.82M
        p_sys->track[i].context.i_temp = VLC_DEMUXER_SUCCESS;
5085
5086
    /* demux up to increment amount of data on every track, or just set pcr if empty data */
5087
9.80M
    for( ;; )
5088
9.80M
    {
5089
9.80M
        mp4_track_t *tk = NULL;
5090
9.80M
        i_status = VLC_DEMUXER_EOS;
5091
5092
        /* First pass, find any track within our target increment, ordered by position */
5093
19.6M
        for( unsigned i = 0; i < p_sys->i_tracks; i++ )
5094
9.82M
        {
5095
9.82M
            mp4_track_t *tk_tmp = &p_sys->track[i];
5096
5097
9.82M
            if( !tk_tmp->b_ok || MP4_isMetadata( tk_tmp ) ||
5098
9.82M
               (!tk_tmp->b_selected && p_sys->b_seekable) ||
5099
9.82M
                tk_tmp->context.runs.i_current >= tk_tmp->context.runs.i_count ||
5100
9.80M
                tk_tmp->context.i_temp != VLC_DEMUXER_SUCCESS )
5101
20.4k
                continue;
5102
5103
            /* At least still have data to demux on this or next turns */
5104
9.80M
            i_status = VLC_DEMUXER_SUCCESS;
5105
5106
9.80M
            if( MP4_rescale_mtime( tk_tmp->i_time, tk_tmp->i_timescale ) <= i_nztime + DEMUX_INCREMENT )
5107
2.82k
            {
5108
2.82k
                if( tk == NULL || tk_tmp->context.i_trun_sample_pos < tk->context.i_trun_sample_pos )
5109
2.82k
                    tk = tk_tmp;
5110
2.82k
            }
5111
9.80M
        }
5112
5113
9.80M
        if( tk )
5114
2.82k
        {
5115
            /* Second pass, refine and find any best candidate having a chunk pos closer than
5116
             * current candidate (avoids seeks when increment falls between the 2) from
5117
             * current position, but within extended interleave time */
5118
2.82k
            for( unsigned i = 0; i_max_preload != 0 && i < p_sys->i_tracks; i++ )
5119
0
            {
5120
0
                mp4_track_t *tk_tmp = &p_sys->track[i];
5121
0
                if( tk_tmp == tk ||
5122
0
                    !tk_tmp->b_ok || MP4_isMetadata( tk_tmp ) ||
5123
0
                   (!tk_tmp->b_selected && p_sys->b_seekable) ||
5124
0
                    tk_tmp->context.runs.i_current >= tk_tmp->context.runs.i_count ||
5125
0
                    tk_tmp->context.i_temp != VLC_DEMUXER_SUCCESS )
5126
0
                    continue;
5127
5128
0
                vlc_tick_t i_nzdts = MP4_rescale_mtime( tk_tmp->i_time, tk_tmp->i_timescale );
5129
0
                if ( i_nzdts <= i_nztime + DEMUX_TRACK_MAX_PRELOAD )
5130
0
                {
5131
                    /* Found a better candidate to avoid seeking */
5132
0
                    if( tk_tmp->context.i_trun_sample_pos < tk->context.i_trun_sample_pos )
5133
0
                        tk = tk_tmp;
5134
                    /* Note: previous candidate will be repicked on next loop */
5135
0
                }
5136
0
            }
5137
5138
2.82k
            int i_ret = FragDemuxTrack( p_demux, tk, i_max_preload );
5139
5140
2.82k
            tk->context.i_temp = i_ret;
5141
2.82k
            if( i_ret == VLC_DEMUXER_SUCCESS )
5142
2.74k
                i_status = VLC_DEMUXER_SUCCESS;
5143
82
            else if( i_ret == VLC_DEMUXER_FATAL )
5144
82
                i_status = VLC_DEMUXER_EOF;
5145
2.82k
        }
5146
5147
9.80M
        if( i_status != VLC_DEMUXER_SUCCESS || !tk )
5148
9.80M
            break;
5149
9.80M
    }
5150
5151
9.80M
    if( i_status != VLC_DEMUXER_EOS )
5152
9.80M
    {
5153
9.80M
        p_sys->i_nztime += DEMUX_INCREMENT;
5154
9.80M
        p_sys->i_pcr = VLC_TICK_0 + p_sys->i_nztime;
5155
9.80M
        es_out_SetPCR( p_demux->out, p_sys->i_pcr );
5156
9.80M
    }
5157
206
    else
5158
206
    {
5159
206
        vlc_tick_t i_segment_end = VLC_TICK_MAX;
5160
526
        for( unsigned i = 0; i < p_sys->i_tracks; i++ )
5161
320
        {
5162
320
            mp4_track_t *tk = &p_sys->track[i];
5163
320
            if( tk->b_ok || MP4_isMetadata( tk ) ||
5164
82
               (!tk->b_selected && !p_sys->b_seekable) )
5165
238
                continue;
5166
82
            vlc_tick_t i_track_end = MP4_rescale_mtime( tk->i_time, tk->i_timescale );
5167
82
            if( i_track_end < i_segment_end  )
5168
82
                i_segment_end = i_track_end;
5169
82
        }
5170
206
        if( i_segment_end != VLC_TICK_MAX )
5171
82
        {
5172
82
            p_sys->i_nztime = i_segment_end;
5173
82
            p_sys->i_pcr = VLC_TICK_0 + p_sys->i_nztime;
5174
82
            es_out_SetPCR( p_demux->out, p_sys->i_pcr );
5175
82
        }
5176
206
    }
5177
5178
9.80M
    return i_status;
5179
9.80M
}
5180
5181
static int FragCreateTrunIndex( demux_t *p_demux, MP4_Box_t *p_moof,
5182
                                MP4_Box_t *p_chunksidx, stime_t i_moof_time )
5183
429
{
5184
429
    demux_sys_t *p_sys = p_demux->p_sys;
5185
5186
429
    uint64_t i_traf_base_data_offset = p_moof->i_pos;
5187
429
    uint32_t i_traf = 0;
5188
429
    uint64_t i_prev_traf_end = 0;
5189
5190
1.15k
    for( unsigned i=0; i<p_sys->i_tracks; i++ )
5191
722
    {
5192
722
        mp4_track_t *p_track = &p_sys->track[i];
5193
722
        if( p_track->context.runs.p_array )
5194
134
            free( p_track->context.runs.p_array );
5195
722
        p_track->context.runs.p_array = NULL;
5196
722
        p_track->context.runs.i_count = 0;
5197
722
        p_track->context.runs.i_current = 0;
5198
722
    }
5199
5200
429
    for( MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
5201
820
                    p_traf ; p_traf = p_traf->p_next )
5202
391
    {
5203
391
        if ( p_traf->i_type != ATOM_traf )
5204
67
            continue;
5205
5206
324
        const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
5207
324
        uint32_t i_trun_count = MP4_BoxCount( p_traf, "trun" );
5208
324
        if ( !p_tfhd || !i_trun_count )
5209
6
            continue;
5210
5211
318
        mp4_track_t *p_track = MP4_GetTrackByTrackID( p_demux, BOXDATA(p_tfhd)->i_track_ID );
5212
318
        if( !p_track )
5213
18
            continue;
5214
5215
300
        p_track->context.runs.p_array = realloc_or_free(p_track->context.runs.p_array,
5216
300
            (i_trun_count + p_track->context.runs.i_count) * sizeof(mp4_run_t));
5217
300
        if(!p_track->context.runs.p_array)
5218
0
            continue;
5219
300
        memset(&p_track->context.runs.p_array[i_trun_count], 0, p_track->context.runs.i_count * sizeof(mp4_run_t));
5220
300
        i_trun_count += p_track->context.runs.i_count;
5221
5222
        /* Get defaults for this/these RUN */
5223
300
        uint32_t i_track_defaultsamplesize = 0;
5224
300
        uint32_t i_track_defaultsampleduration = 0;
5225
300
        MP4_GetDefaultSizeAndDuration( p_sys->p_moov, BOXDATA(p_tfhd),
5226
300
                                       &i_track_defaultsamplesize,
5227
300
                                       &i_track_defaultsampleduration );
5228
300
        p_track->context.i_default_sample_size = i_track_defaultsamplesize;
5229
300
        p_track->context.i_default_sample_duration = i_track_defaultsampleduration;
5230
5231
300
        stime_t  i_traf_start_time = p_track->i_time;
5232
300
        bool     b_has_base_media_decode_time = false;
5233
5234
300
        if( p_track->context.b_resync_time_offset ) /* We NEED start time offset for each track */
5235
192
        {
5236
192
            p_track->context.b_resync_time_offset = false;
5237
5238
            /* Find start time */
5239
192
            const MP4_Box_t *p_tfdt = MP4_BoxGet( p_traf, "tfdt" );
5240
192
            if( p_tfdt )
5241
60
            {
5242
60
                i_traf_start_time = BOXDATA(p_tfdt)->i_base_media_decode_time;
5243
60
                b_has_base_media_decode_time = true;
5244
60
            }
5245
5246
            /* Try using Tfxd for base offset (Smooth) */
5247
192
            if( !b_has_base_media_decode_time && p_sys->i_tracks == 1 )
5248
15
            {
5249
15
                const MP4_Box_t *p_uuid = MP4_BoxGet( p_traf, "uuid" );
5250
15
                for( ; p_uuid; p_uuid = p_uuid->p_next )
5251
0
                {
5252
0
                    if( p_uuid->i_type == ATOM_uuid &&
5253
0
                       !CmpUUID( &p_uuid->i_uuid, &TfxdBoxUUID ) && p_uuid->data.p_tfxd )
5254
0
                    {
5255
0
                        i_traf_start_time = p_uuid->data.p_tfxd->i_fragment_abs_time;
5256
0
                        b_has_base_media_decode_time = true;
5257
0
                        break;
5258
0
                    }
5259
0
                }
5260
15
            }
5261
5262
            /* After seek we should have probed fragments */
5263
192
            if( !b_has_base_media_decode_time && p_sys->p_fragsindex )
5264
108
            {
5265
108
                unsigned i_track_index = (p_track - p_sys->track);
5266
108
                assert(&p_sys->track[i_track_index] == p_track);
5267
108
                i_traf_start_time = MP4_Fragment_Index_GetTrackStartTime( p_sys->p_fragsindex,
5268
108
                                                                          i_track_index, p_moof->i_pos );
5269
108
                i_traf_start_time = MP4_rescale( i_traf_start_time,
5270
108
                                                 p_sys->i_timescale, p_track->i_timescale );
5271
108
                b_has_base_media_decode_time = true;
5272
108
            }
5273
5274
192
            if( !b_has_base_media_decode_time && p_chunksidx )
5275
0
            {
5276
                /* Try using SIDX as base offset.
5277
                 * This can not work for global sidx but only when sent within each fragment (dash) */
5278
0
                const MP4_Box_data_sidx_t *p_data = p_chunksidx->data.p_sidx;
5279
0
                if( p_data && p_data->i_timescale && p_data->i_reference_count == 1 )
5280
0
                {
5281
0
                    i_traf_start_time = MP4_rescale( p_data->i_earliest_presentation_time,
5282
0
                                                     p_data->i_timescale, p_track->i_timescale );
5283
0
                    b_has_base_media_decode_time = true;
5284
0
                }
5285
0
            }
5286
5287
            /* First contiguous segment (moov->moof) and there's no tfdt not probed index (yet) */
5288
192
            if( !b_has_base_media_decode_time && FragGetMoofSequenceNumber( p_moof ) == 1 )
5289
13
            {
5290
13
                i_traf_start_time = MP4_rescale( GetMoovTrackDuration( p_sys, p_track->i_track_ID ),
5291
13
                                                 p_sys->i_timescale, p_track->i_timescale );
5292
13
                b_has_base_media_decode_time = true;
5293
13
            }
5294
5295
            /* Use global sidx moof time, in case moof does not carry tfdt */
5296
192
            if( !b_has_base_media_decode_time )
5297
11
            {
5298
11
                if( i_moof_time != INVALID_SEGMENT_TIME )
5299
0
                    i_traf_start_time = MP4_rescale( i_moof_time, p_sys->i_timescale, p_track->i_timescale );
5300
11
                else if ( p_sys->i_nztime != VLC_TICK_MAX ) /* That should not happen */
5301
9
                    i_traf_start_time = MP4_rescale_qtime( p_sys->i_nztime, p_track->i_timescale );
5302
2
                else /* That should not happen */
5303
2
                    i_traf_start_time = p_track->i_time;
5304
11
            }
5305
192
        }
5306
5307
        /* Parse TRUN data */
5308
5309
300
        if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
5310
2
        {
5311
2
            i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
5312
2
        }
5313
        /* ignored if MP4_TFHD_BASE_DATA_OFFSET */
5314
298
        else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5315
127
        {
5316
127
            i_traf_base_data_offset = p_moof->i_pos /* + 8*/;
5317
127
        }
5318
171
        else
5319
171
        {
5320
171
            if ( i_traf == 0 )
5321
162
                i_traf_base_data_offset = p_moof->i_pos /*+ 8*/;
5322
9
            else
5323
9
                i_traf_base_data_offset = i_prev_traf_end;
5324
171
        }
5325
5326
300
        uint64_t i_trun_dts = i_traf_start_time;
5327
300
        uint64_t i_trun_data_offset = i_traf_base_data_offset;
5328
300
        uint32_t i_trun_size = 0;
5329
5330
300
        for( const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
5331
854
                              p_trun && p_tfhd;  p_trun = p_trun->p_next )
5332
554
        {
5333
554
            if ( p_trun->i_type != ATOM_trun )
5334
252
               continue;
5335
5336
302
            const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
5337
5338
            /* Get data offset */
5339
302
            if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
5340
295
            {
5341
                /* Fix for broken Trun data offset relative to tfhd instead of moof, as seen in smooth */
5342
295
                if( (BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET) == 0 &&
5343
293
                    i_traf == 0 &&
5344
284
                    i_traf_base_data_offset + p_trundata->i_data_offset < p_moof->i_pos + p_moof->i_size + 8 )
5345
33
                {
5346
33
                    i_trun_data_offset += p_moof->i_size + 8;
5347
33
                }
5348
262
                else if( (BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET) )
5349
2
                {
5350
2
                    i_trun_data_offset = BOXDATA(p_tfhd)->i_base_data_offset + p_trundata->i_data_offset;
5351
2
                }
5352
                /* ignored if MP4_TFHD_BASE_DATA_OFFSET */
5353
260
                else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5354
127
                {
5355
127
                    i_trun_data_offset = p_moof->i_pos + p_trundata->i_data_offset;
5356
127
                }
5357
133
                else
5358
133
                {
5359
133
                    i_trun_data_offset += p_trundata->i_data_offset;
5360
133
                }
5361
295
            }
5362
7
            else
5363
7
            {
5364
7
                i_trun_data_offset += i_trun_size;
5365
7
            }
5366
5367
302
            i_trun_size = 0;
5368
302
#ifndef NDEBUG
5369
302
            msg_Dbg( p_demux,
5370
302
                     "tk %u run %" PRIu32 " dflt dur %"PRIu32" size %"PRIu32" firstdts %"PRId64" offset %"PRIu64,
5371
302
                     p_track->i_track_ID,
5372
302
                     p_track->context.runs.i_count,
5373
302
                     i_track_defaultsampleduration,
5374
302
                     i_track_defaultsamplesize,
5375
302
                     MP4_rescale_mtime( i_trun_dts, p_track->i_timescale ), i_trun_data_offset );
5376
302
#endif
5377
            //************
5378
302
            assert(p_track->context.runs.i_count < i_trun_count);
5379
302
            mp4_run_t *p_run = &p_track->context.runs.p_array[p_track->context.runs.i_count++];
5380
302
            p_run->i_first_dts = i_trun_dts;
5381
302
            p_run->i_offset = i_trun_data_offset;
5382
302
            p_run->p_trun = p_trun;
5383
5384
            //************
5385
            /* Sum total time */
5386
302
            if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
5387
171
            {
5388
2.30k
                for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
5389
2.13k
                    i_trun_dts += p_trundata->p_samples[i].i_duration;
5390
171
            }
5391
131
            else
5392
131
            {
5393
131
                i_trun_dts += (uint64_t)p_trundata->i_sample_count *
5394
131
                        i_track_defaultsampleduration;
5395
131
            }
5396
5397
            /* Get total traf size */
5398
302
            if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
5399
143
            {
5400
3.73k
                for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
5401
3.59k
                    i_trun_size += p_trundata->p_samples[i].i_size;
5402
143
            }
5403
159
            else
5404
159
            {
5405
159
                i_trun_size += p_trundata->i_sample_count *
5406
159
                        i_track_defaultsamplesize;
5407
159
            }
5408
5409
302
            i_prev_traf_end = i_trun_data_offset + i_trun_size;
5410
302
        }
5411
5412
300
        i_traf++;
5413
300
    }
5414
5415
429
    return VLC_SUCCESS;
5416
429
}
5417
5418
static int FragGetMoofBySidxIndex( demux_t *p_demux, vlc_tick_t target_time,
5419
                                   uint64_t *pi_moof_pos, vlc_tick_t *pi_sampletime )
5420
0
{
5421
0
    demux_sys_t *p_sys = p_demux->p_sys;
5422
0
    const MP4_Box_t *p_sidx = MP4_BoxGet( p_sys->p_root, "sidx" );
5423
0
    for( ; p_sidx ; p_sidx = p_sidx->p_next )
5424
0
    {
5425
0
        if( p_sidx->i_type != ATOM_sidx )
5426
0
            continue;
5427
5428
0
        const MP4_Box_data_sidx_t *p_data = BOXDATA(p_sidx);
5429
0
        if( !p_data || !p_data->i_timescale )
5430
0
            break;
5431
5432
0
        stime_t i_target_time = MP4_rescale_qtime( target_time, p_data->i_timescale );
5433
5434
        /* sidx refers to offsets from end of sidx pos in the file + first offset */
5435
0
        uint64_t i_pos = p_data->i_first_offset + p_sidx->i_pos + p_sidx->i_size;
5436
0
        stime_t i_time = 0;
5437
0
        for( uint16_t i=0; i<p_data->i_reference_count; i++ )
5438
0
        {
5439
0
            if(p_data->p_items[i].b_reference_type != 0)
5440
0
                continue;
5441
0
            if( i_time + p_data->p_items[i].i_subsegment_duration > i_target_time )
5442
0
            {
5443
0
                *pi_sampletime = MP4_rescale_mtime( i_time, p_data->i_timescale );
5444
0
                *pi_moof_pos = i_pos;
5445
0
                return VLC_SUCCESS;
5446
0
            }
5447
0
            i_pos += p_data->p_items[i].i_referenced_size;
5448
0
            i_time += p_data->p_items[i].i_subsegment_duration;
5449
0
        }
5450
0
    }
5451
0
    return VLC_EGENERIC;
5452
0
}
5453
5454
static int FragGetMoofByTfraIndex( demux_t *p_demux, const vlc_tick_t i_target_time, unsigned i_track_ID,
5455
                                   uint64_t *pi_moof_pos, vlc_tick_t *pi_sampletime )
5456
0
{
5457
0
    demux_sys_t *p_sys = p_demux->p_sys;
5458
0
    MP4_Box_t *p_tfra = MP4_BoxGet( p_sys->p_root, "mfra/tfra" );
5459
0
    for( ; p_tfra; p_tfra = p_tfra->p_next )
5460
0
    {
5461
0
        if ( p_tfra->i_type == ATOM_tfra )
5462
0
        {
5463
0
            const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
5464
0
            if( !p_data || p_data->i_track_ID != i_track_ID )
5465
0
                continue;
5466
5467
0
            uint64_t i_pos = 0;
5468
0
            mp4_track_t *p_track = MP4_GetTrackByTrackID( p_demux, p_data->i_track_ID );
5469
0
            if ( p_track )
5470
0
            {
5471
0
                stime_t i_track_target_time = MP4_rescale_qtime( i_target_time, p_track->i_timescale );
5472
0
                for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
5473
0
                {
5474
0
                    stime_t i_time = p_data->p_time[i];
5475
0
                    uint64_t i_offset = p_data->p_moof_offset[i];
5476
5477
0
                    if ( i_time >= i_track_target_time )
5478
0
                    {
5479
0
                        if ( i_pos == 0 ) /* Not in this traf */
5480
0
                            break;
5481
5482
0
                        *pi_moof_pos = i_pos;
5483
0
                        *pi_sampletime = MP4_rescale_mtime( i_time, p_track->i_timescale );
5484
0
                        return VLC_SUCCESS;
5485
0
                    }
5486
0
                    else
5487
0
                        i_pos = i_offset;
5488
0
                }
5489
0
            }
5490
0
        }
5491
0
    }
5492
0
    return VLC_EGENERIC;
5493
0
}
5494
5495
static void MP4_GetDefaultSizeAndDuration( MP4_Box_t *p_moov,
5496
                                           const MP4_Box_data_tfhd_t *p_tfhd_data,
5497
                                           uint32_t *pi_default_size,
5498
                                           uint32_t *pi_default_duration )
5499
300
{
5500
300
    if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
5501
34
        *pi_default_duration = p_tfhd_data->i_default_sample_duration;
5502
5503
300
    if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
5504
162
        *pi_default_size = p_tfhd_data->i_default_sample_size;
5505
5506
300
    if( !*pi_default_duration || !*pi_default_size )
5507
300
    {
5508
300
        const MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moov, p_tfhd_data->i_track_ID );
5509
300
        if ( p_trex )
5510
183
        {
5511
183
            if ( !*pi_default_duration )
5512
165
                *pi_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
5513
183
            if ( !*pi_default_size )
5514
113
                *pi_default_size = BOXDATA(p_trex)->i_default_sample_size;
5515
183
        }
5516
300
    }
5517
300
}
5518
5519
static int DemuxFrag( demux_t *p_demux )
5520
9.80M
{
5521
9.80M
    demux_sys_t *p_sys = p_demux->p_sys;
5522
9.80M
    unsigned i_track_selected = 0;
5523
9.80M
    int i_status = VLC_DEMUXER_SUCCESS;
5524
5525
9.80M
    if( unlikely(p_sys->b_error) )
5526
0
    {
5527
0
        msg_Warn( p_demux, "unrecoverable error" );
5528
0
        i_status = VLC_DEMUXER_EOF;
5529
0
        goto end;
5530
0
    }
5531
5532
    /* check for newly selected/unselected track */
5533
19.6M
    for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5534
9.82M
    {
5535
9.82M
        mp4_track_t *tk = &p_sys->track[i_track];
5536
9.82M
        bool b = true;
5537
5538
9.82M
        if( !tk->b_ok || MP4_isMetadata( tk ) )
5539
4.34k
            continue;
5540
5541
9.82M
        if( p_sys->b_seekable )
5542
9.82M
            es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5543
5544
9.82M
        if(tk->b_selected != b)
5545
239
        {
5546
239
            msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5547
239
            MP4_TrackSelect( p_demux, tk, b );
5548
239
        }
5549
5550
9.82M
        if( tk->b_selected )
5551
9.82M
            i_track_selected++;
5552
9.82M
    }
5553
5554
9.80M
    if( i_track_selected <= 0 )
5555
19
    {
5556
19
        msg_Warn( p_demux, "no track selected, exiting..." );
5557
19
        i_status = VLC_DEMUXER_EOF;
5558
19
        goto end;
5559
19
    }
5560
5561
9.80M
    if ( p_sys->context.i_current_box_type != ATOM_mdat )
5562
1.21k
    {
5563
        /* Otherwise mdat is skipped. FIXME: mdat reading ! */
5564
1.21k
        const uint8_t *p_peek;
5565
1.21k
        if( vlc_stream_Peek( p_demux->s, &p_peek, 8 ) != 8 )
5566
110
        {
5567
110
            i_status = VLC_DEMUXER_EOF;
5568
110
            goto end;
5569
110
        }
5570
5571
1.10k
        p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5572
1.10k
        if( p_sys->context.i_current_box_type != ATOM_moof &&
5573
678
            p_sys->context.i_current_box_type != ATOM_moov )
5574
476
        {
5575
476
            uint64_t i_pos = vlc_stream_Tell( p_demux->s );
5576
476
            uint64_t i_size = GetDWBE( p_peek );
5577
476
            if ( i_size == 1 )
5578
6
            {
5579
6
                if( vlc_stream_Peek( p_demux->s, &p_peek, 16 ) != 16 )
5580
0
                {
5581
0
                    i_status = VLC_DEMUXER_EOF;
5582
0
                    goto end;
5583
0
                }
5584
6
                i_size = GetQWBE( p_peek + 8 );
5585
6
            }
5586
5587
476
            if( UINT64_MAX - i_pos < i_size )
5588
0
            {
5589
0
                i_status = VLC_DEMUXER_EOF;
5590
0
                goto end;
5591
0
            }
5592
5593
476
            if( p_sys->context.i_current_box_type == ATOM_mdat )
5594
291
            {
5595
                /* We'll now read mdat using context atom,
5596
                 * but we'll need post mdat offset, as we'll never seek backward */
5597
291
                p_sys->context.i_post_mdat_offset = i_pos + i_size;
5598
291
            }
5599
185
            else if( MP4_Seek( p_demux->s, i_pos + i_size ) != VLC_SUCCESS ) /* skip other atoms */
5600
0
            {
5601
0
                i_status = VLC_DEMUXER_EOF;
5602
0
                goto end;
5603
0
            }
5604
476
        }
5605
631
        else
5606
631
        {
5607
631
            MP4_Box_t *p_vroot = MP4_BoxGetNextChunk( p_demux->s );
5608
631
            if(!p_vroot)
5609
0
            {
5610
0
                i_status = VLC_DEMUXER_EOF;
5611
0
                goto end;
5612
0
            }
5613
5614
631
            MP4_Box_t *p_box = NULL;
5615
631
            for( p_box = p_vroot->p_first; p_box; p_box = p_box->p_next )
5616
631
            {
5617
631
                if( p_box->i_type == ATOM_moof ||
5618
202
                    p_box->i_type == ATOM_moov )
5619
631
                    break;
5620
631
            }
5621
5622
631
            if( p_box )
5623
631
            {
5624
631
                FragResetContext( p_sys );
5625
5626
631
                if( p_box->i_type == ATOM_moov )
5627
202
                {
5628
202
                    p_sys->context.p_fragment_atom = p_sys->p_moov;
5629
202
                }
5630
429
                else
5631
429
                {
5632
429
                    p_sys->context.p_fragment_atom = MP4_BoxExtract( &p_vroot->p_first, p_box->i_type );
5633
5634
                    /* Detect and Handle Passive Seek */
5635
429
                    const uint32_t i_sequence_number = FragGetMoofSequenceNumber( p_sys->context.p_fragment_atom );
5636
429
                    const bool b_discontinuity = ( i_sequence_number != p_sys->context.i_lastseqnumber + 1 );
5637
429
                    if( b_discontinuity )
5638
429
                        msg_Info( p_demux, "Fragment sequence discontinuity detected %"PRIu32" != %"PRIu32,
5639
429
                                            i_sequence_number, p_sys->context.i_lastseqnumber + 1 );
5640
429
                    p_sys->context.i_lastseqnumber = i_sequence_number;
5641
5642
                    /* Prepare chunk */
5643
429
                    if( FragPrepareChunk( p_demux, p_sys->context.p_fragment_atom,
5644
429
                                          MP4_BoxGet( p_vroot, "sidx"), INVALID_SEGMENT_TIME,
5645
429
                                          b_discontinuity ) != VLC_SUCCESS )
5646
0
                    {
5647
0
                        MP4_BoxFree( p_vroot );
5648
0
                        i_status = VLC_DEMUXER_EOF;
5649
0
                        goto end;
5650
0
                    }
5651
5652
429
                    if( b_discontinuity )
5653
299
                    {
5654
299
                        p_sys->i_nztime = FragGetDemuxTimeFromTracksTime( p_sys );
5655
299
                        p_sys->i_pcr = VLC_TICK_INVALID;
5656
299
                    }
5657
                    /* !Prepare chunk */
5658
429
                }
5659
5660
631
                p_sys->context.i_current_box_type = p_box->i_type;
5661
631
            }
5662
5663
631
            MP4_BoxFree( p_vroot );
5664
5665
631
            if( p_sys->context.p_fragment_atom == NULL )
5666
0
            {
5667
0
                msg_Info(p_demux, "no moof or moov in current chunk");
5668
0
                return VLC_DEMUXER_SUCCESS;
5669
0
            }
5670
631
        }
5671
1.10k
    }
5672
5673
9.80M
    if ( p_sys->context.i_current_box_type == ATOM_mdat )
5674
9.80M
    {
5675
9.80M
        assert(p_sys->context.p_fragment_atom);
5676
5677
9.80M
        if ( p_sys->context.p_fragment_atom )
5678
9.80M
        switch( p_sys->context.p_fragment_atom->i_type )
5679
9.80M
        {
5680
3
            case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5681
3
                i_status = DemuxMoov( p_demux );
5682
3
            break;
5683
9.80M
            case ATOM_moof:
5684
9.80M
                i_status = DemuxMoof( p_demux );
5685
9.80M
              break;
5686
0
        default:
5687
0
             msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment_atom->i_type );
5688
0
             break;
5689
9.80M
        }
5690
5691
9.80M
        if( i_status == VLC_DEMUXER_EOS )
5692
209
        {
5693
209
            i_status = VLC_DEMUXER_SUCCESS;
5694
            /* Skip if we didn't reach the end of mdat box */
5695
209
            uint64_t i_pos = vlc_stream_Tell( p_demux->s );
5696
209
            if( i_pos != p_sys->context.i_post_mdat_offset && i_status != VLC_DEMUXER_EOF )
5697
99
            {
5698
99
                if( i_pos > p_sys->context.i_post_mdat_offset )
5699
99
                    msg_Err( p_demux, " Overread mdat by %" PRIu64, i_pos - p_sys->context.i_post_mdat_offset );
5700
88
                else if( !p_sys->b_seekable )
5701
0
                    msg_Warn( p_demux, "mdat had still %"PRIu64" bytes unparsed as samples",
5702
99
                                        p_sys->context.i_post_mdat_offset - i_pos );
5703
99
                if( MP4_Seek( p_demux->s, p_sys->context.i_post_mdat_offset ) != VLC_SUCCESS )
5704
0
                    i_status = VLC_DEMUXER_EGENERIC;
5705
99
            }
5706
209
            p_sys->context.i_current_box_type = 0;
5707
5708
209
        }
5709
9.80M
    }
5710
5711
9.80M
end:
5712
9.80M
    if( i_status == VLC_DEMUXER_EOF )
5713
211
    {
5714
211
        vlc_tick_t i_demux_end = VLC_TICK_MIN;
5715
568
        for( unsigned i = 0; i < p_sys->i_tracks; i++ )
5716
357
        {
5717
357
            const mp4_track_t *tk = &p_sys->track[i];
5718
357
            vlc_tick_t i_track_end = MP4_rescale_mtime( tk->i_time, tk->i_timescale );
5719
357
            if( i_track_end > i_demux_end  )
5720
220
                i_demux_end = i_track_end;
5721
357
        }
5722
211
        if( i_demux_end != VLC_TICK_MIN )
5723
211
            es_out_SetPCR( p_demux->out, VLC_TICK_0 + i_demux_end );
5724
211
    }
5725
5726
9.80M
    return i_status;
5727
9.80M
}
5728
5729
/* ASF Handlers */
5730
inline static mp4_track_t *MP4ASF_GetTrack( asf_packet_sys_t *p_packetsys,
5731
                                            uint8_t i_stream_number )
5732
0
{
5733
0
    demux_t *p_demux = p_packetsys->priv;
5734
0
    demux_sys_t *p_sys = p_demux->p_sys;
5735
0
    for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
5736
0
    {
5737
0
        if ( p_sys->track[i].p_asf &&
5738
0
             i_stream_number == p_sys->track[i].BOXDATA(p_asf)->i_stream_number )
5739
0
        {
5740
0
            return &p_sys->track[i];
5741
0
        }
5742
0
    }
5743
0
    return NULL;
5744
0
}
5745
5746
static asf_track_info_t * MP4ASF_GetTrackInfo( asf_packet_sys_t *p_packetsys,
5747
                                               uint8_t i_stream_number )
5748
0
{
5749
0
    mp4_track_t *p_track = MP4ASF_GetTrack( p_packetsys, i_stream_number );
5750
0
    if ( p_track )
5751
0
        return &p_track->asfinfo;
5752
0
    else
5753
0
        return NULL;
5754
0
}
5755
5756
static void MP4ASF_Send( asf_packet_sys_t *p_packetsys, uint8_t i_stream_number,
5757
                         block_t **pp_frame )
5758
0
{
5759
0
    demux_t *p_demux = p_packetsys->priv;
5760
0
    mp4_track_t *p_track = MP4ASF_GetTrack( p_packetsys, i_stream_number );
5761
0
    if ( !p_track )
5762
0
    {
5763
0
        block_Release( *pp_frame );
5764
0
    }
5765
0
    else
5766
0
    {
5767
0
        block_t *p_gather = block_ChainGather( *pp_frame );
5768
0
        p_gather->i_dts = p_track->i_dts_backup;
5769
0
        p_gather->i_pts = p_track->i_pts_backup;
5770
0
        es_out_Send( p_demux->out, p_track->p_es, p_gather );
5771
0
    }
5772
5773
0
    *pp_frame = NULL;
5774
0
}
5775
5776
static void MP4ASF_ResetFrames( demux_sys_t *p_sys )
5777
0
{
5778
0
    for ( unsigned int i=0; i<p_sys->i_tracks; i++ )
5779
0
    {
5780
0
        mp4_track_t *p_track = &p_sys->track[i];
5781
0
        ASFPacketTrackReset( &p_track->asfinfo );
5782
0
    }
5783
0
}