Streams.cpp 11.2 KB
Newer Older
1 2 3
/*
 * Streams.cpp
 *****************************************************************************
4
 * Copyright (C) 2014 - VideoLAN and VLC authors
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * 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.
 *****************************************************************************/
20 21 22 23 24

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

25
#include "Streams.hpp"
26
#include "http/HTTPConnection.hpp"
27
#include "http/HTTPConnectionManager.h"
28
#include "playlist/BaseRepresentation.h"
29
#include "playlist/SegmentChunk.hpp"
30 31 32
#include "plumbing/SourceStream.hpp"
#include "plumbing/CommandsQueue.hpp"
#include "tools/Debug.hpp"
33
#include <vlc_demux.h>
34

35 36
using namespace adaptive;
using namespace adaptive::http;
37

38
AbstractStream::AbstractStream(demux_t * demux_)
39
{
40
    p_realdemux = demux_;
41
    format = StreamFormat::UNSUPPORTED;
42 43
    currentChunk = NULL;
    eof = false;
44
    dead = false;
45
    disabled = false;
46
    discontinuity = false;
47
    segmentTracker = NULL;
48
    demuxersource = NULL;
49
    commandsqueue = NULL;
50 51
    demuxer = NULL;
    fakeesout = NULL;
52
}
53

54 55 56 57 58
bool AbstractStream::init(const StreamFormat &format_, SegmentTracker *tracker, HTTPConnectionManager *conn)
{
    /* Don't even try if not supported or already init */
    if((unsigned)format_ == StreamFormat::UNSUPPORTED || demuxersource)
        return false;
59 60

    demuxersource = new (std::nothrow) ChunksSourceStream( VLC_OBJECT(p_realdemux), this );
61
    if(demuxersource)
62
    {
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
        CommandsFactory *factory = new (std::nothrow) CommandsFactory();
        if(factory)
        {
            commandsqueue = new (std::nothrow) CommandsQueue(factory);
            if(commandsqueue)
            {
                fakeesout = new (std::nothrow) FakeESOut(p_realdemux->out, commandsqueue);
                if(fakeesout)
                {
                    /* All successfull */
                    fakeesout->setExtraInfoProvider( this );
                    format = format_;
                    segmentTracker = tracker;
                    segmentTracker->registerListener(this);
                    connManager = conn;
                    return true;
                }
                delete commandsqueue;
                commandsqueue = NULL;
            }
            else
            {
                delete factory;
            }
        }
88 89 90
        delete demuxersource;
    }

91
    return false;
92 93
}

94
AbstractStream::~AbstractStream()
95 96
{
    delete currentChunk;
97
    delete segmentTracker;
98 99 100 101

    delete demuxer;
    delete demuxersource;
    delete fakeesout;
102
    delete commandsqueue;
103 104
}

105
void AbstractStream::prepareFormatChange()
106
{
107 108 109 110 111 112 113
    if(demuxer)
    {
        /* Enqueue Del Commands for all current ES */
        demuxer->drain();
        /* Enqueue Del Commands for all current ES */
        fakeesout->scheduleAllForDeletion();
        fakeesout->schedulePCRReset();
114
        commandsqueue->Commit();
115
        /* ignoring demuxer's own Del commands */
116
        commandsqueue->setDrop(true);
117
        delete demuxer;
118
        commandsqueue->setDrop(false);
119 120
        demuxer = NULL;
    }
121 122
}

123
void AbstractStream::setLanguage(const std::string &lang)
124 125
{
    language = lang;
126 127
}

128
void AbstractStream::setDescription(const std::string &desc)
129 130 131 132
{
    description = desc;
}

133 134 135 136 137 138
bool AbstractStream::isEOF() const
{
    return dead;
}

mtime_t AbstractStream::getPCR() const
139
{
140
    return commandsqueue->getPCR();
141 142
}

143 144 145 146 147 148 149
mtime_t AbstractStream::getMinAheadTime() const
{
    if(!segmentTracker)
        return 0;
    return segmentTracker->getMinAheadTime();
}

150
mtime_t AbstractStream::getBufferingLevel() const
151
{
152
    return commandsqueue->getBufferingLevel();
153 154
}

155
mtime_t AbstractStream::getFirstDTS() const
156
{
157
    return commandsqueue->getFirstDTS();
158 159
}

160
int AbstractStream::esCount() const
161
{
162
    return fakeesout->esCount();
163 164
}

165
bool AbstractStream::seekAble() const
166
{
167 168 169
    return (demuxer &&
            !fakeesout->restarting() &&
            !discontinuity &&
170
            !commandsqueue->isFlushing() );
171 172
}

173
bool AbstractStream::isSelected() const
174
{
175
    return fakeesout->hasSelectedEs();
176 177
}

178
bool AbstractStream::reactivate(mtime_t basetime)
179 180 181 182 183 184 185 186 187 188 189 190 191
{
    if(setPosition(basetime, false))
    {
        disabled = false;
        return true;
    }
    else
    {
        eof = true; /* can't reactivate */
        return false;
    }
}

192 193 194 195 196
bool AbstractStream::startDemux()
{
    if(demuxer)
        return false;

197 198 199
    demuxersource->Reset();
    demuxer = createDemux(format);
    if(!demuxer)
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
        msg_Err(p_realdemux, "Failed to create demuxer");

    return !!demuxer;
}

bool AbstractStream::restartDemux()
{
    if(!demuxer)
    {
        return startDemux();
    }
    else if(demuxer->reinitsOnSeek())
    {
        /* Push all ES as recycling candidates */
        fakeesout->recycleAll();
        /* Restart with ignoring pushes to queue */
216
        return demuxer->restart(commandsqueue);
217
    }
218
    commandsqueue->Commit();
219 220 221 222
    return true;
}

bool AbstractStream::isDisabled() const
223 224 225 226
{
    return disabled;
}

227 228 229 230 231
bool AbstractStream::drain()
{
    return fakeesout->drain();
}

232
AbstractStream::status AbstractStream::demux(mtime_t nz_deadline, bool send)
233
{
234
    /* Ensure it is configured */
235
    if(!segmentTracker || !connManager || dead)
236
        return AbstractStream::status_eof;
237

238
    if(commandsqueue->isFlushing())
239 240 241 242
    {
        if(!send)
            return AbstractStream::status_buffering;

243
        (void) commandsqueue->Process(p_realdemux->out, VLC_TS_0 + nz_deadline);
244
        if(!commandsqueue->isEmpty())
245 246
            return AbstractStream::status_demuxed;

247
        commandsqueue->Abort(true); /* reset buffering level */
248 249 250
        return AbstractStream::status_dis;
    }

251
    if(!demuxer)
252
    {
253 254
        format = segmentTracker->initialFormat();
        if(!startDemux())
255
        {
256 257 258 259 260 261
            /* If demux fails because of probing failure / wrong format*/
            if(discontinuity)
            {
                msg_Dbg( p_realdemux, "Flushing on format change" );
                prepareFormatChange();
                discontinuity = false;
262
                commandsqueue->setFlush();
263 264 265 266
                return AbstractStream::status_buffering;
            }
            dead = true; /* Prevent further retries */
            return AbstractStream::status_eof;
267
        }
268
        setTimeOffset();
269 270 271
    }

    if(nz_deadline + VLC_TS_0 > getBufferingLevel()) /* not already demuxed */
272
    {
273 274 275
        if(!segmentTracker->segmentsListReady()) /* Live Streams */
            return AbstractStream::status_buffering_ahead;

276
        /* need to read, demuxer still buffering, ... */
277
        if(demuxer->demux(nz_deadline) != VLC_DEMUXER_SUCCESS)
278
        {
279
            if(discontinuity)
280 281 282 283
            {
                msg_Dbg( p_realdemux, "Flushing on discontinuity" );
                prepareFormatChange();
                discontinuity = false;
284
                commandsqueue->setFlush();
285 286
                return AbstractStream::status_buffering;
            }
287
        }
288
        else if(nz_deadline + VLC_TS_0 > getBufferingLevel()) /* need to read more */
289
        {
290
            return AbstractStream::status_buffering;
291
        }
292 293
    }

294 295 296
    AdvDebug(msg_Dbg(p_realdemux, "Stream %s pcr %ld dts %ld deadline %ld buflevel %ld",
             description.c_str(), getPCR(), getFirstDTS(), nz_deadline, getBufferingLevel()));

297
    if(send)
298
        (void) commandsqueue->Process( p_realdemux->out, VLC_TS_0 + nz_deadline );
299

300 301 302 303 304 305 306
    /* Disable streams that are not selected (alternate streams) */
    if(esCount() && !isSelected() && !fakeesout->restarting())
    {
        disabled = true;
        segmentTracker->reset();
    }

307
    return AbstractStream::status_demuxed;
308 309
}

310
block_t * AbstractStream::readNextBlock()
311
{
312 313
    if (currentChunk == NULL && !eof)
        currentChunk = segmentTracker->getNextChunk(!fakeesout->restarting(), connManager);
314

315
    if(discontinuity)
316
    {
317 318
        msg_Info(p_realdemux, "Encountered discontinuity");
        /* Force stream/demuxer to end for this call */
319 320 321
        return NULL;
    }

322
    if(currentChunk == NULL)
323
    {
324
        eof = true;
325 326
        return NULL;
    }
327

328
    const bool b_segment_head_chunk = (currentChunk->getBytesRead() == 0);
329

330
    block_t *block = currentChunk->readBlock();
331
    if(block == NULL)
332
    {
333
        delete currentChunk;
334
        currentChunk = NULL;
335
        return NULL;
336 337
    }

338
    if (currentChunk->isEmpty())
339
    {
340
        delete currentChunk;
341
        currentChunk = NULL;
342 343
    }

344
    block = checkBlock(block, b_segment_head_chunk);
345

346
    return block;
347 348
}

349
bool AbstractStream::setPosition(mtime_t time, bool tryonly)
350
{
351
    if(!seekAble())
352 353
        return false;

354
    bool ret = segmentTracker->setPositionByTime(time, demuxer->reinitsOnSeek(), tryonly);
355
    if(!tryonly && ret)
356
    {
357
        if(demuxer->reinitsOnSeek())
358 359 360 361
        {
            if(currentChunk)
                delete currentChunk;
            currentChunk = NULL;
362

363 364
            if( !restartDemux() )
                dead = true;
365

366
            setTimeOffset();
367
        }
368
        else commandsqueue->Abort( true );
369 370 371

        es_out_Control(p_realdemux->out, ES_OUT_SET_NEXT_DISPLAY_TIME,
                       VLC_TS_0 + time);
372
    }
373 374 375
    return ret;
}

376
mtime_t AbstractStream::getPlaybackTime() const
377
{
378
    return segmentTracker->getPlaybackTime();
379
}
380

381
void AbstractStream::runUpdates()
382 383 384 385
{
    if(!isDisabled())
        segmentTracker->updateSelected();
}
386 387 388 389 390 391 392 393 394

void AbstractStream::fillExtraFMTInfo( es_format_t *p_fmt ) const
{
    if(!p_fmt->psz_language && !language.empty())
        p_fmt->psz_language = strdup(language.c_str());
    if(!p_fmt->psz_description && !description.empty())
        p_fmt->psz_description = strdup(description.c_str());
}

395 396 397 398 399 400 401 402 403 404
void AbstractStream::setTimeOffset()
{
    /* Check if we need to set an offset as the demuxer
     * will start from zero from seek point */
    if(demuxer && demuxer->alwaysStartsFromZero())
        fakeesout->setTimestampOffset(segmentTracker->getPlaybackTime());
    else
        fakeesout->setTimestampOffset(0);
}

405 406 407 408 409 410 411 412 413 414 415 416 417
void AbstractStream::trackerEvent(const SegmentTrackerEvent &event)
{
    switch(event.type)
    {
        case SegmentTrackerEvent::DISCONTINUITY:
            discontinuity = true;
            break;

        case SegmentTrackerEvent::FORMATCHANGE:
            /* Check if our current demux is still valid */
            if(*event.u.format.f != format)
            {
                /* Format has changed between segments, we need to drain and change demux */
418 419
                msg_Info(p_realdemux, "Changing stream format %s -> %s",
                         format.str().c_str(), event.u.format.f->str().c_str());
420 421 422 423 424 425 426 427 428 429 430 431
                format = *event.u.format.f;

                /* This is an implict discontinuity */
                discontinuity = true;
            }
            break;

        case SegmentTrackerEvent::SWITCHING:
        default:
            break;
    }
}