Coverage Report

Created: 2025-07-11 06:16

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