matroska_segment_seeker.cpp 14.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/*****************************************************************************
 * matroska_segment.hpp : matroska demuxer
 *****************************************************************************
 * Copyright (C) 2016 VLC authors and VideoLAN
 * $Id$
 *
 * Authors: Filip Roséen <filip@videolabs.io>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
 *****************************************************************************/

#include "matroska_segment_seeker.hpp"
#include "matroska_segment.hpp"
#include "demux.hpp"
#include "Ebml_parser.hpp"
#include "Ebml_dispatcher.hpp"
#include "util.hpp"
#include "stream_io_callback.hpp"

#include <sstream>
33
#include <limits>
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

namespace { 
    template<class It, class T>
    It greatest_lower_bound( It beg, It end, T const& value )
    {
        It it = std::upper_bound( beg, end, value );
        if( it != beg ) --it;
        return it;
    }

    // std::prev and std::next exists in C++11, in order to avoid ambiguity due
    // to ADL and iterators being defined within namespace std, these two
    // function-names have been postfixed with an underscore.

    template<class It> It prev_( It it ) { return --it; }
    template<class It> It next_( It it ) { return ++it; }
}

SegmentSeeker::cluster_positions_t::iterator
SegmentSeeker::add_cluster_position( fptr_t fpos )
{
    cluster_positions_t::iterator insertion_point = std::upper_bound(
      _cluster_positions.begin(),
      _cluster_positions.end(),
      fpos
    );

    return _cluster_positions.insert( insertion_point, fpos );
}

SegmentSeeker::cluster_map_t::iterator
SegmentSeeker::add_cluster( KaxCluster * const p_cluster )
{
    Cluster cinfo = {
        /* fpos     */ p_cluster->GetElementPosition(),
        /* pts      */ mtime_t( p_cluster->GlobalTimecode() / INT64_C( 1000 ) ),
        /* duration */ mtime_t( -1 ),
71
72
73
        /* size     */ p_cluster->IsFiniteSize()
            ? p_cluster->GetEndPosition() - p_cluster->GetElementPosition()
            : UINT64_MAX
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
    };

    add_cluster_position( cinfo.fpos );

    cluster_map_t::iterator it = _clusters.lower_bound( cinfo.pts );

    if( it != _clusters.end() && it->second.pts == cinfo.pts )
    {
        // cluster already known
    }
    else
    {
        it = _clusters.insert( cluster_map_t::value_type( cinfo.pts, cinfo ) ).first;
    }

    // ------------------------------------------------------------------
    // IF we have two adjecent clusters, update duration where applicable
    // ------------------------------------------------------------------

    struct Duration {
        static void fix( Cluster& prev, Cluster& next )
        {
            if( ( prev.fpos + prev.size) == next.fpos )
                prev.duration = next.pts - prev.pts; 
        }
    };

    if( it != _clusters.begin() )
    {
        Duration::fix( prev_( it )->second, it->second );
    }

    if( it != _clusters.end() && next_( it ) != _clusters.end() )
    {
        Duration::fix( it->second, next_( it )->second );
    }

    return it;
}

void
115
SegmentSeeker::add_seekpoint( track_id_t track_id, Seekpoint sp )
116
117
118
119
120
121
{
    seekpoints_t&  seekpoints = _tracks_seekpoints[ track_id ];
    seekpoints_t::iterator it = std::lower_bound( seekpoints.begin(), seekpoints.end(), sp );

    if( it != seekpoints.end() && it->pts == sp.pts )
    {
122
123
124
        if (sp.trust_level <= it->trust_level)
            return;

125
126
127
128
129
130
131
132
        *it = sp;
    }
    else
    {
        seekpoints.insert( it, sp );
    }
}

133
SegmentSeeker::tracks_seekpoint_t
134
SegmentSeeker::find_greatest_seekpoints_in_range( fptr_t start_fpos, mtime_t end_pts, track_ids_t const& filter_tracks )
135
136
137
138
139
{
    tracks_seekpoint_t tpoints;

    for( tracks_seekpoints_t::const_iterator it = _tracks_seekpoints.begin(); it != _tracks_seekpoints.end(); ++it )
    {
140
141
142
        if ( std::find( filter_tracks.begin(), filter_tracks.end(), it->first ) == filter_tracks.end() )
            continue;

143
        Seekpoint sp = get_first_seekpoint_around( end_pts, it->second );
144
145
146
147
148
149
150
151
152
153
154
155
156

        if( sp.fpos < start_fpos )
            continue;

        if( sp.pts > end_pts )
            continue;

        tpoints.insert( tracks_seekpoint_t::value_type( it->first, sp ) );
    }

    return tpoints;
}

157
158
159
160
161
162
163
164
165
166
167
SegmentSeeker::Seekpoint
SegmentSeeker::get_first_seekpoint_around( mtime_t pts, seekpoints_t const& seekpoints,
                                           Seekpoint::TrustLevel trust_level )
{
    if( seekpoints.empty() )
    {
        return Seekpoint();
    }

    typedef seekpoints_t::const_iterator iterator;

168
    Seekpoint const needle ( std::numeric_limits<fptr_t>::max(), pts );
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

    iterator const it_begin  = seekpoints.begin();
    iterator const it_end    = seekpoints.end();
    iterator const it_middle = greatest_lower_bound( it_begin, it_end, needle );

    iterator it_before;

    // rewrind to _previous_ seekpoint with appropriate trust
    for( it_before = it_middle; it_before != it_begin; --it_before )
    {
        if( it_before->trust_level >= trust_level )
            return *it_before;
    }
    return *it_begin;
}

185
SegmentSeeker::seekpoint_pair_t
186
SegmentSeeker::get_seekpoints_around( mtime_t pts, seekpoints_t const& seekpoints )
187
188
189
190
191
192
193
194
{
    if( seekpoints.empty() )
    {
        return seekpoint_pair_t();
    }

    typedef seekpoints_t::const_iterator iterator;

195
    Seekpoint const needle ( std::numeric_limits<fptr_t>::max(), pts );
196
197
198
199
200

    iterator const it_begin  = seekpoints.begin();
    iterator const it_end    = seekpoints.end();
    iterator const it_middle = greatest_lower_bound( it_begin, it_end, needle );

201
202
    iterator it_before = it_middle;
    iterator it_after = it_middle == it_end ? it_middle : next_( it_middle ) ;
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232

    return seekpoint_pair_t( *it_before,
      it_after == it_end ? Seekpoint() : *it_after
    );
}

SegmentSeeker::seekpoint_pair_t
SegmentSeeker::get_seekpoints_around( mtime_t target_pts, track_ids_t const& priority_tracks )
{
    seekpoint_pair_t points;

    if( _tracks_seekpoints.empty() )
        return points;

    { // locate the max/min seekpoints for priority_tracks //

        typedef track_ids_t::const_iterator track_iterator;

        track_iterator const begin = priority_tracks.begin();
        track_iterator const end   = priority_tracks.end();

        for( track_iterator it = begin; it != end; ++it )
        {
            seekpoint_pair_t track_points = get_seekpoints_around( target_pts, _tracks_seekpoints[ *it ] );

            if( it == begin ) {
                points = track_points;
                continue;
            }

233
234
            if( track_points.first.trust_level > Seekpoint::DISABLED &&
                points.first.fpos > track_points.first.fpos )
235
236
                points.first = track_points.first;

237
238
            if( track_points.second.trust_level > Seekpoint::DISABLED &&
                points.second.fpos < track_points.second.fpos )
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
                points.second = track_points.second;
        }
    }

    { // check if we got a cluster which is closer to target_pts than the found cues //

        cluster_map_t::iterator it = _clusters.lower_bound( target_pts );

        if( it != _clusters.begin() && --it != _clusters.end() )
        {
            Cluster const& cluster = it->second;

            if( cluster.fpos > points.first.fpos )
            {
                points.first.fpos = cluster.fpos;
                points.first.pts  = cluster.pts;

                // do we need to update the max point? //

                if( points.second.fpos < points.first.fpos )
                {
                    points.second.fpos = cluster.fpos + cluster.size;
                    points.second.pts  = cluster.pts  + cluster.duration;
                }
            }
        }
    }

    return points;
}

SegmentSeeker::tracks_seekpoint_t
271
272
SegmentSeeker::get_seekpoints( matroska_segment_c& ms, mtime_t target_pts,
                               track_ids_t const& priority_tracks, track_ids_t const& filter_tracks )
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
{
    struct contains_all_of_t {
        bool operator()( tracks_seekpoint_t const& haystack, track_ids_t const& track_ids )
        {
            for( track_ids_t::const_iterator it = track_ids.begin(); it != track_ids.end(); ++it ) {
                if( haystack.find( *it ) == haystack.end() )
                    return false;
            }

            return true;
        }
    };

    for( mtime_t needle_pts = target_pts; ; )
    {
        seekpoint_pair_t seekpoints = get_seekpoints_around( needle_pts, priority_tracks );

        Seekpoint const& start = seekpoints.first;
        Seekpoint const& end   = seekpoints.second;

        index_range( ms, Range( start.fpos, end.fpos ), needle_pts );

        {
296
            tracks_seekpoint_t tpoints = find_greatest_seekpoints_in_range( start.fpos, target_pts, filter_tracks );
297
298
299
300
301
302
303
304
305
306
307

            if( contains_all_of_t() ( tpoints, priority_tracks ) )
                return tpoints;
        }

        needle_pts = start.pts - 1;
    }

    vlc_assert_unreachable();
}

308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
void
SegmentSeeker::index_range( matroska_segment_c& ms, Range search_area, mtime_t max_pts )
{
    ranges_t areas_to_search = get_search_areas( search_area.start, search_area.end );

    for( ranges_t::const_iterator range_it = areas_to_search.begin(); range_it != areas_to_search.end(); ++range_it ) 
        index_unsearched_range( ms, *range_it, max_pts );
}

void
SegmentSeeker::index_unsearched_range( matroska_segment_c& ms, Range search_area, mtime_t max_pts )
{
    mkv_jump_to( ms, search_area.start );

    search_area.start = ms.es.I_O().getFilePointer();

    fptr_t  block_pos = search_area.start;
325
    mtime_t block_pts;
326
327
328
329
330
331
332
333
334

    while( block_pos < search_area.end )
    {
        KaxBlock * block;
        KaxSimpleBlock * simpleblock;

        bool     b_key_picture;
        bool     b_discardable_picture;
        int64_t  i_block_duration;
335
        track_id_t track_id;
336
337

        if( ms.BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
338
            break;
339
340
341
342

        if( simpleblock ) {
            block_pos = simpleblock->GetElementPosition();
            block_pts = simpleblock->GlobalTimecode() / 1000;
343
            track_id  = simpleblock->TrackNum();
344
345
346
347
        }
        else {
            block_pos = block->GetElementPosition();
            block_pts = block->GlobalTimecode() / 1000;
348
            track_id  = block->TrackNum();
349
350
        }

351
        bool const b_valid_track = ms.FindTrackByBlock( block, simpleblock ) != NULL;
352
353
354
355

        delete block;

        if( b_valid_track )
356
357
        {
            if( b_key_picture )
358
                add_seekpoint( track_id, Seekpoint( block_pos, block_pts ) );
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421

            if( max_pts < block_pts )
                break;
        }
    }

    search_area.end = ms.es.I_O().getFilePointer();

    mark_range_as_searched( search_area );
}

void
SegmentSeeker::mark_range_as_searched( Range data )
{
    /* TODO: this is utterly ugly, we should do the insertion in-place */

    _ranges_searched.insert( std::upper_bound( _ranges_searched.begin(), _ranges_searched.end(), data ), data );

    {
        ranges_t merged;

        for( ranges_t::iterator it = _ranges_searched.begin(); it != _ranges_searched.end(); ++it )
        {
            if( merged.size() )
            {
                Range& last_entry = *merged.rbegin();

                if( last_entry.end+1 >= it->start && last_entry.end < it->end )
                {
                    last_entry.end = it->end;
                    continue;
                }

                if( it->start >= last_entry.start && it->end <= last_entry.end )
                {
                    last_entry.end = std::max( last_entry.end, it->end );
                    continue;
                }
            }

            merged.push_back( *it );
        }

        _ranges_searched = merged;
    }
}


SegmentSeeker::ranges_t
SegmentSeeker::get_search_areas( fptr_t start, fptr_t end ) const
{
    ranges_t areas_to_search;
    Range needle ( start, end );

    ranges_t::const_iterator it = greatest_lower_bound( _ranges_searched.begin(), _ranges_searched.end(), needle );

    for( ; it != _ranges_searched.end() && needle.start < needle.end; ++it )
    {
        if( needle.start < it->start )
        {
            areas_to_search.push_back( Range( needle.start, it->start ) );
        }

422
423
        if( needle.start <= it->end )
            needle.start = it->end + 1;
424
425
    }

426
    needle.start = std::max( needle.start, start );
427
428
429
430
431
432
433
434
435
436
437
    if( it == _ranges_searched.end() && needle.start < needle.end )
    {
        areas_to_search.push_back( needle );
    }

    return areas_to_search;
}

void
SegmentSeeker::mkv_jump_to( matroska_segment_c& ms, fptr_t fpos )
{
438
439
    fptr_t i_cluster_pos = -1;
    ms.cluster = NULL;
440
441
442
443
444
445
446
447
448
449

    {
        cluster_positions_t::iterator cluster_it = greatest_lower_bound(
          _cluster_positions.begin(), _cluster_positions.end(), fpos
        );

        ms.es.I_O().setFilePointer( *cluster_it );
        ms.ep->reconstruct( &ms.es, ms.segment, &ms.sys.demuxer );
    }

450
451
    while( ms.cluster == NULL || (
          ms.cluster->IsFiniteSize() && ms.cluster->GetEndPosition() < fpos ) )
452
    {
453
454
455
456
457
458
        if( !( ms.cluster = static_cast<KaxCluster*>( ms.ep->Get() ) ) )
        {
            msg_Err( &ms.sys.demuxer, "unable to read KaxCluster during seek, giving up" );
            return;
        }

459
        i_cluster_pos = ms.cluster->GetElementPosition();
460

461
        add_cluster_position( i_cluster_pos );
462

463
        mark_range_as_searched( Range( i_cluster_pos, ms.es.I_O().getFilePointer() ) );
464
465
466
467
468
469
470
471
472
473
474
475
476
477
    }

    ms.ep->Down();

    /* read until cluster/timecode to initialize cluster */

    while( EbmlElement * el = ms.ep->Get() )
    {
        if( MKV_CHECKED_PTR_DECL( p_tc, KaxClusterTimecode, el ) )
        {
            p_tc->ReadData( ms.es.I_O(), SCOPE_ALL_DATA );
            ms.cluster->InitTimecode( static_cast<uint64>( *p_tc ), ms.i_timescale );
            break;
        }
478
479
480
481
        else if( MKV_CHECKED_PTR_DECL( p_tc, EbmlCrc32, el ) )
        {
            p_tc->ReadData( ms.es.I_O(), SCOPE_ALL_DATA ); /* avoid a skip that may fail */
        }
482
483
484
485
    }

    /* TODO: add error handling; what if we never get a KaxCluster and/or KaxClusterTimecode? */

486
    mark_range_as_searched( Range( i_cluster_pos, ms.es.I_O().getFilePointer() ) );
487
488
489
490
491
492

    /* jump to desired position */

    ms.es.I_O().setFilePointer( fpos );
}