Coverage Report

Created: 2025-08-29 06:30

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