PlaylistFetcher.cpp revision 9dee2e592e89e90097cbb3b5065cffa768917b56
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//#define LOG_NDEBUG 0
18#define LOG_TAG "PlaylistFetcher"
19#include <utils/Log.h>
20
21#include "PlaylistFetcher.h"
22
23#include "LiveDataSource.h"
24#include "LiveSession.h"
25#include "M3UParser.h"
26
27#include "include/avc_utils.h"
28#include "include/HTTPBase.h"
29#include "include/ID3.h"
30#include "mpeg2ts/AnotherPacketSource.h"
31
32#include <media/IStreamSource.h>
33#include <media/stagefright/foundation/ABitReader.h>
34#include <media/stagefright/foundation/ABuffer.h>
35#include <media/stagefright/foundation/ADebug.h>
36#include <media/stagefright/foundation/hexdump.h>
37#include <media/stagefright/FileSource.h>
38#include <media/stagefright/MediaDefs.h>
39#include <media/stagefright/MetaData.h>
40#include <media/stagefright/Utils.h>
41
42#include <ctype.h>
43#include <inttypes.h>
44#include <openssl/aes.h>
45#include <openssl/md5.h>
46
47namespace android {
48
49// static
50const int64_t PlaylistFetcher::kMinBufferedDurationUs = 10000000ll;
51const int64_t PlaylistFetcher::kMaxMonitorDelayUs = 3000000ll;
52const int32_t PlaylistFetcher::kDownloadBlockSize = 2048;
53const int32_t PlaylistFetcher::kNumSkipFrames = 10;
54
55PlaylistFetcher::PlaylistFetcher(
56        const sp<AMessage> &notify,
57        const sp<LiveSession> &session,
58        const char *uri,
59        int32_t subtitleGeneration)
60    : mNotify(notify),
61      mStartTimeUsNotify(notify->dup()),
62      mSession(session),
63      mURI(uri),
64      mStreamTypeMask(0),
65      mStartTimeUs(-1ll),
66      mSegmentStartTimeUs(-1ll),
67      mDiscontinuitySeq(-1ll),
68      mStartTimeUsRelative(false),
69      mLastPlaylistFetchTimeUs(-1ll),
70      mSeqNumber(-1),
71      mNumRetries(0),
72      mStartup(true),
73      mAdaptive(false),
74      mPrepared(false),
75      mNextPTSTimeUs(-1ll),
76      mMonitorQueueGeneration(0),
77      mSubtitleGeneration(subtitleGeneration),
78      mRefreshState(INITIAL_MINIMUM_RELOAD_DELAY),
79      mFirstPTSValid(false),
80      mAbsoluteTimeAnchorUs(0ll),
81      mVideoBuffer(new AnotherPacketSource(NULL)) {
82    memset(mPlaylistHash, 0, sizeof(mPlaylistHash));
83    mStartTimeUsNotify->setInt32("what", kWhatStartedAt);
84    mStartTimeUsNotify->setInt32("streamMask", 0);
85}
86
87PlaylistFetcher::~PlaylistFetcher() {
88}
89
90int64_t PlaylistFetcher::getSegmentStartTimeUs(int32_t seqNumber) const {
91    CHECK(mPlaylist != NULL);
92
93    int32_t firstSeqNumberInPlaylist;
94    if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
95                "media-sequence", &firstSeqNumberInPlaylist)) {
96        firstSeqNumberInPlaylist = 0;
97    }
98
99    int32_t lastSeqNumberInPlaylist =
100        firstSeqNumberInPlaylist + (int32_t)mPlaylist->size() - 1;
101
102    CHECK_GE(seqNumber, firstSeqNumberInPlaylist);
103    CHECK_LE(seqNumber, lastSeqNumberInPlaylist);
104
105    int64_t segmentStartUs = 0ll;
106    for (int32_t index = 0;
107            index < seqNumber - firstSeqNumberInPlaylist; ++index) {
108        sp<AMessage> itemMeta;
109        CHECK(mPlaylist->itemAt(
110                    index, NULL /* uri */, &itemMeta));
111
112        int64_t itemDurationUs;
113        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
114
115        segmentStartUs += itemDurationUs;
116    }
117
118    return segmentStartUs;
119}
120
121int64_t PlaylistFetcher::delayUsToRefreshPlaylist() const {
122    int64_t nowUs = ALooper::GetNowUs();
123
124    if (mPlaylist == NULL || mLastPlaylistFetchTimeUs < 0ll) {
125        CHECK_EQ((int)mRefreshState, (int)INITIAL_MINIMUM_RELOAD_DELAY);
126        return 0ll;
127    }
128
129    if (mPlaylist->isComplete()) {
130        return (~0llu >> 1);
131    }
132
133    int32_t targetDurationSecs;
134    CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
135
136    int64_t targetDurationUs = targetDurationSecs * 1000000ll;
137
138    int64_t minPlaylistAgeUs;
139
140    switch (mRefreshState) {
141        case INITIAL_MINIMUM_RELOAD_DELAY:
142        {
143            size_t n = mPlaylist->size();
144            if (n > 0) {
145                sp<AMessage> itemMeta;
146                CHECK(mPlaylist->itemAt(n - 1, NULL /* uri */, &itemMeta));
147
148                int64_t itemDurationUs;
149                CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
150
151                minPlaylistAgeUs = itemDurationUs;
152                break;
153            }
154
155            // fall through
156        }
157
158        case FIRST_UNCHANGED_RELOAD_ATTEMPT:
159        {
160            minPlaylistAgeUs = targetDurationUs / 2;
161            break;
162        }
163
164        case SECOND_UNCHANGED_RELOAD_ATTEMPT:
165        {
166            minPlaylistAgeUs = (targetDurationUs * 3) / 2;
167            break;
168        }
169
170        case THIRD_UNCHANGED_RELOAD_ATTEMPT:
171        {
172            minPlaylistAgeUs = targetDurationUs * 3;
173            break;
174        }
175
176        default:
177            TRESPASS();
178            break;
179    }
180
181    int64_t delayUs = mLastPlaylistFetchTimeUs + minPlaylistAgeUs - nowUs;
182    return delayUs > 0ll ? delayUs : 0ll;
183}
184
185status_t PlaylistFetcher::decryptBuffer(
186        size_t playlistIndex, const sp<ABuffer> &buffer,
187        bool first) {
188    sp<AMessage> itemMeta;
189    bool found = false;
190    AString method;
191
192    for (ssize_t i = playlistIndex; i >= 0; --i) {
193        AString uri;
194        CHECK(mPlaylist->itemAt(i, &uri, &itemMeta));
195
196        if (itemMeta->findString("cipher-method", &method)) {
197            found = true;
198            break;
199        }
200    }
201
202    if (!found) {
203        method = "NONE";
204    }
205    buffer->meta()->setString("cipher-method", method.c_str());
206
207    if (method == "NONE") {
208        return OK;
209    } else if (!(method == "AES-128")) {
210        ALOGE("Unsupported cipher method '%s'", method.c_str());
211        return ERROR_UNSUPPORTED;
212    }
213
214    AString keyURI;
215    if (!itemMeta->findString("cipher-uri", &keyURI)) {
216        ALOGE("Missing key uri");
217        return ERROR_MALFORMED;
218    }
219
220    ssize_t index = mAESKeyForURI.indexOfKey(keyURI);
221
222    sp<ABuffer> key;
223    if (index >= 0) {
224        key = mAESKeyForURI.valueAt(index);
225    } else {
226        ssize_t err = mSession->fetchFile(keyURI.c_str(), &key);
227
228        if (err < 0) {
229            ALOGE("failed to fetch cipher key from '%s'.", keyURI.c_str());
230            return ERROR_IO;
231        } else if (key->size() != 16) {
232            ALOGE("key file '%s' wasn't 16 bytes in size.", keyURI.c_str());
233            return ERROR_MALFORMED;
234        }
235
236        mAESKeyForURI.add(keyURI, key);
237    }
238
239    AES_KEY aes_key;
240    if (AES_set_decrypt_key(key->data(), 128, &aes_key) != 0) {
241        ALOGE("failed to set AES decryption key.");
242        return UNKNOWN_ERROR;
243    }
244
245    size_t n = buffer->size();
246    if (!n) {
247        return OK;
248    }
249    CHECK(n % 16 == 0);
250
251    if (first) {
252        // If decrypting the first block in a file, read the iv from the manifest
253        // or derive the iv from the file's sequence number.
254
255        AString iv;
256        if (itemMeta->findString("cipher-iv", &iv)) {
257            if ((!iv.startsWith("0x") && !iv.startsWith("0X"))
258                    || iv.size() != 16 * 2 + 2) {
259                ALOGE("malformed cipher IV '%s'.", iv.c_str());
260                return ERROR_MALFORMED;
261            }
262
263            memset(mAESInitVec, 0, sizeof(mAESInitVec));
264            for (size_t i = 0; i < 16; ++i) {
265                char c1 = tolower(iv.c_str()[2 + 2 * i]);
266                char c2 = tolower(iv.c_str()[3 + 2 * i]);
267                if (!isxdigit(c1) || !isxdigit(c2)) {
268                    ALOGE("malformed cipher IV '%s'.", iv.c_str());
269                    return ERROR_MALFORMED;
270                }
271                uint8_t nibble1 = isdigit(c1) ? c1 - '0' : c1 - 'a' + 10;
272                uint8_t nibble2 = isdigit(c2) ? c2 - '0' : c2 - 'a' + 10;
273
274                mAESInitVec[i] = nibble1 << 4 | nibble2;
275            }
276        } else {
277            memset(mAESInitVec, 0, sizeof(mAESInitVec));
278            mAESInitVec[15] = mSeqNumber & 0xff;
279            mAESInitVec[14] = (mSeqNumber >> 8) & 0xff;
280            mAESInitVec[13] = (mSeqNumber >> 16) & 0xff;
281            mAESInitVec[12] = (mSeqNumber >> 24) & 0xff;
282        }
283    }
284
285    AES_cbc_encrypt(
286            buffer->data(), buffer->data(), buffer->size(),
287            &aes_key, mAESInitVec, AES_DECRYPT);
288
289    return OK;
290}
291
292status_t PlaylistFetcher::checkDecryptPadding(const sp<ABuffer> &buffer) {
293    status_t err;
294    AString method;
295    CHECK(buffer->meta()->findString("cipher-method", &method));
296    if (method == "NONE") {
297        return OK;
298    }
299
300    uint8_t padding = 0;
301    if (buffer->size() > 0) {
302        padding = buffer->data()[buffer->size() - 1];
303    }
304
305    if (padding > 16) {
306        return ERROR_MALFORMED;
307    }
308
309    for (size_t i = buffer->size() - padding; i < padding; i++) {
310        if (buffer->data()[i] != padding) {
311            return ERROR_MALFORMED;
312        }
313    }
314
315    buffer->setRange(buffer->offset(), buffer->size() - padding);
316    return OK;
317}
318
319void PlaylistFetcher::postMonitorQueue(int64_t delayUs, int64_t minDelayUs) {
320    int64_t maxDelayUs = delayUsToRefreshPlaylist();
321    if (maxDelayUs < minDelayUs) {
322        maxDelayUs = minDelayUs;
323    }
324    if (delayUs > maxDelayUs) {
325        ALOGV("Need to refresh playlist in %" PRId64 , maxDelayUs);
326        delayUs = maxDelayUs;
327    }
328    sp<AMessage> msg = new AMessage(kWhatMonitorQueue, id());
329    msg->setInt32("generation", mMonitorQueueGeneration);
330    msg->post(delayUs);
331}
332
333void PlaylistFetcher::cancelMonitorQueue() {
334    ++mMonitorQueueGeneration;
335}
336
337void PlaylistFetcher::startAsync(
338        const sp<AnotherPacketSource> &audioSource,
339        const sp<AnotherPacketSource> &videoSource,
340        const sp<AnotherPacketSource> &subtitleSource,
341        int64_t startTimeUs,
342        int64_t segmentStartTimeUs,
343        int32_t startDiscontinuitySeq,
344        bool adaptive) {
345    sp<AMessage> msg = new AMessage(kWhatStart, id());
346
347    uint32_t streamTypeMask = 0ul;
348
349    if (audioSource != NULL) {
350        msg->setPointer("audioSource", audioSource.get());
351        streamTypeMask |= LiveSession::STREAMTYPE_AUDIO;
352    }
353
354    if (videoSource != NULL) {
355        msg->setPointer("videoSource", videoSource.get());
356        streamTypeMask |= LiveSession::STREAMTYPE_VIDEO;
357    }
358
359    if (subtitleSource != NULL) {
360        msg->setPointer("subtitleSource", subtitleSource.get());
361        streamTypeMask |= LiveSession::STREAMTYPE_SUBTITLES;
362    }
363
364    msg->setInt32("streamTypeMask", streamTypeMask);
365    msg->setInt64("startTimeUs", startTimeUs);
366    msg->setInt64("segmentStartTimeUs", segmentStartTimeUs);
367    msg->setInt32("startDiscontinuitySeq", startDiscontinuitySeq);
368    msg->setInt32("adaptive", adaptive);
369    msg->post();
370}
371
372void PlaylistFetcher::pauseAsync() {
373    (new AMessage(kWhatPause, id()))->post();
374}
375
376void PlaylistFetcher::stopAsync(bool clear) {
377    sp<AMessage> msg = new AMessage(kWhatStop, id());
378    msg->setInt32("clear", clear);
379    msg->post();
380}
381
382void PlaylistFetcher::resumeUntilAsync(const sp<AMessage> &params) {
383    AMessage* msg = new AMessage(kWhatResumeUntil, id());
384    msg->setMessage("params", params);
385    msg->post();
386}
387
388void PlaylistFetcher::onMessageReceived(const sp<AMessage> &msg) {
389    switch (msg->what()) {
390        case kWhatStart:
391        {
392            status_t err = onStart(msg);
393
394            sp<AMessage> notify = mNotify->dup();
395            notify->setInt32("what", kWhatStarted);
396            notify->setInt32("err", err);
397            notify->post();
398            break;
399        }
400
401        case kWhatPause:
402        {
403            onPause();
404
405            sp<AMessage> notify = mNotify->dup();
406            notify->setInt32("what", kWhatPaused);
407            notify->post();
408            break;
409        }
410
411        case kWhatStop:
412        {
413            onStop(msg);
414
415            sp<AMessage> notify = mNotify->dup();
416            notify->setInt32("what", kWhatStopped);
417            notify->post();
418            break;
419        }
420
421        case kWhatMonitorQueue:
422        case kWhatDownloadNext:
423        {
424            int32_t generation;
425            CHECK(msg->findInt32("generation", &generation));
426
427            if (generation != mMonitorQueueGeneration) {
428                // Stale event
429                break;
430            }
431
432            if (msg->what() == kWhatMonitorQueue) {
433                onMonitorQueue();
434            } else {
435                onDownloadNext();
436            }
437            break;
438        }
439
440        case kWhatResumeUntil:
441        {
442            onResumeUntil(msg);
443            break;
444        }
445
446        default:
447            TRESPASS();
448    }
449}
450
451status_t PlaylistFetcher::onStart(const sp<AMessage> &msg) {
452    mPacketSources.clear();
453
454    uint32_t streamTypeMask;
455    CHECK(msg->findInt32("streamTypeMask", (int32_t *)&streamTypeMask));
456
457    int64_t startTimeUs;
458    int64_t segmentStartTimeUs;
459    int32_t startDiscontinuitySeq;
460    int32_t adaptive;
461    CHECK(msg->findInt64("startTimeUs", &startTimeUs));
462    CHECK(msg->findInt64("segmentStartTimeUs", &segmentStartTimeUs));
463    CHECK(msg->findInt32("startDiscontinuitySeq", &startDiscontinuitySeq));
464    CHECK(msg->findInt32("adaptive", &adaptive));
465
466    if (streamTypeMask & LiveSession::STREAMTYPE_AUDIO) {
467        void *ptr;
468        CHECK(msg->findPointer("audioSource", &ptr));
469
470        mPacketSources.add(
471                LiveSession::STREAMTYPE_AUDIO,
472                static_cast<AnotherPacketSource *>(ptr));
473    }
474
475    if (streamTypeMask & LiveSession::STREAMTYPE_VIDEO) {
476        void *ptr;
477        CHECK(msg->findPointer("videoSource", &ptr));
478
479        mPacketSources.add(
480                LiveSession::STREAMTYPE_VIDEO,
481                static_cast<AnotherPacketSource *>(ptr));
482    }
483
484    if (streamTypeMask & LiveSession::STREAMTYPE_SUBTITLES) {
485        void *ptr;
486        CHECK(msg->findPointer("subtitleSource", &ptr));
487
488        mPacketSources.add(
489                LiveSession::STREAMTYPE_SUBTITLES,
490                static_cast<AnotherPacketSource *>(ptr));
491    }
492
493    mStreamTypeMask = streamTypeMask;
494
495    mSegmentStartTimeUs = segmentStartTimeUs;
496    mDiscontinuitySeq = startDiscontinuitySeq;
497
498    if (startTimeUs >= 0) {
499        mStartTimeUs = startTimeUs;
500        mSeqNumber = -1;
501        mStartup = true;
502        mPrepared = false;
503        mAdaptive = adaptive;
504    }
505
506    postMonitorQueue();
507
508    return OK;
509}
510
511void PlaylistFetcher::onPause() {
512    cancelMonitorQueue();
513}
514
515void PlaylistFetcher::onStop(const sp<AMessage> &msg) {
516    cancelMonitorQueue();
517
518    int32_t clear;
519    CHECK(msg->findInt32("clear", &clear));
520    if (clear) {
521        for (size_t i = 0; i < mPacketSources.size(); i++) {
522            sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
523            packetSource->clear();
524        }
525    }
526
527    mPacketSources.clear();
528    mStreamTypeMask = 0;
529}
530
531// Resume until we have reached the boundary timestamps listed in `msg`; when
532// the remaining time is too short (within a resume threshold) stop immediately
533// instead.
534status_t PlaylistFetcher::onResumeUntil(const sp<AMessage> &msg) {
535    sp<AMessage> params;
536    CHECK(msg->findMessage("params", &params));
537
538    bool stop = false;
539    for (size_t i = 0; i < mPacketSources.size(); i++) {
540        sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
541
542        const char *stopKey;
543        int streamType = mPacketSources.keyAt(i);
544        switch (streamType) {
545        case LiveSession::STREAMTYPE_VIDEO:
546            stopKey = "timeUsVideo";
547            break;
548
549        case LiveSession::STREAMTYPE_AUDIO:
550            stopKey = "timeUsAudio";
551            break;
552
553        case LiveSession::STREAMTYPE_SUBTITLES:
554            stopKey = "timeUsSubtitle";
555            break;
556
557        default:
558            TRESPASS();
559        }
560
561        // Don't resume if we would stop within a resume threshold.
562        int32_t discontinuitySeq;
563        int64_t latestTimeUs = 0, stopTimeUs = 0;
564        sp<AMessage> latestMeta = packetSource->getLatestDequeuedMeta();
565        if (latestMeta != NULL
566                && latestMeta->findInt32("discontinuitySeq", &discontinuitySeq)
567                && discontinuitySeq == mDiscontinuitySeq
568                && latestMeta->findInt64("timeUs", &latestTimeUs)
569                && params->findInt64(stopKey, &stopTimeUs)
570                && stopTimeUs - latestTimeUs < resumeThreshold(latestMeta)) {
571            stop = true;
572        }
573    }
574
575    if (stop) {
576        for (size_t i = 0; i < mPacketSources.size(); i++) {
577            mPacketSources.valueAt(i)->queueAccessUnit(mSession->createFormatChangeBuffer());
578        }
579        stopAsync(/* clear = */ false);
580        return OK;
581    }
582
583    mStopParams = params;
584    postMonitorQueue();
585
586    return OK;
587}
588
589void PlaylistFetcher::notifyError(status_t err) {
590    sp<AMessage> notify = mNotify->dup();
591    notify->setInt32("what", kWhatError);
592    notify->setInt32("err", err);
593    notify->post();
594}
595
596void PlaylistFetcher::queueDiscontinuity(
597        ATSParser::DiscontinuityType type, const sp<AMessage> &extra) {
598    for (size_t i = 0; i < mPacketSources.size(); ++i) {
599        // do not discard buffer upon #EXT-X-DISCONTINUITY tag
600        // (seek will discard buffer by abandoning old fetchers)
601        mPacketSources.valueAt(i)->queueDiscontinuity(
602                type, extra, false /* discard */);
603    }
604}
605
606void PlaylistFetcher::onMonitorQueue() {
607    bool downloadMore = false;
608    refreshPlaylist();
609
610    int32_t targetDurationSecs;
611    int64_t targetDurationUs = kMinBufferedDurationUs;
612    if (mPlaylist != NULL) {
613        if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
614                "target-duration", &targetDurationSecs)) {
615            ALOGE("Playlist is missing required EXT-X-TARGETDURATION tag");
616            notifyError(ERROR_MALFORMED);
617            return;
618        }
619        targetDurationUs = targetDurationSecs * 1000000ll;
620    }
621
622    // buffer at least 3 times the target duration, or up to 10 seconds
623    int64_t durationToBufferUs = targetDurationUs * 3;
624    if (durationToBufferUs > kMinBufferedDurationUs)  {
625        durationToBufferUs = kMinBufferedDurationUs;
626    }
627
628    int64_t bufferedDurationUs = 0ll;
629    status_t finalResult = NOT_ENOUGH_DATA;
630    if (mStreamTypeMask == LiveSession::STREAMTYPE_SUBTITLES) {
631        sp<AnotherPacketSource> packetSource =
632            mPacketSources.valueFor(LiveSession::STREAMTYPE_SUBTITLES);
633
634        bufferedDurationUs =
635                packetSource->getBufferedDurationUs(&finalResult);
636        finalResult = OK;
637    } else {
638        // Use max stream duration to prevent us from waiting on a non-existent stream;
639        // when we cannot make out from the manifest what streams are included in a playlist
640        // we might assume extra streams.
641        for (size_t i = 0; i < mPacketSources.size(); ++i) {
642            if ((mStreamTypeMask & mPacketSources.keyAt(i)) == 0) {
643                continue;
644            }
645
646            int64_t bufferedStreamDurationUs =
647                mPacketSources.valueAt(i)->getBufferedDurationUs(&finalResult);
648            ALOGV("buffered %" PRId64 " for stream %d",
649                    bufferedStreamDurationUs, mPacketSources.keyAt(i));
650            if (bufferedStreamDurationUs > bufferedDurationUs) {
651                bufferedDurationUs = bufferedStreamDurationUs;
652            }
653        }
654    }
655    downloadMore = (bufferedDurationUs < durationToBufferUs);
656
657    // signal start if buffered up at least the target size
658    if (!mPrepared && bufferedDurationUs > targetDurationUs && downloadMore) {
659        mPrepared = true;
660
661        ALOGV("prepared, buffered=%" PRId64 " > %" PRId64 "",
662                bufferedDurationUs, targetDurationUs);
663        sp<AMessage> msg = mNotify->dup();
664        msg->setInt32("what", kWhatTemporarilyDoneFetching);
665        msg->post();
666    }
667
668    if (finalResult == OK && downloadMore) {
669        ALOGV("monitoring, buffered=%" PRId64 " < %" PRId64 "",
670                bufferedDurationUs, durationToBufferUs);
671        // delay the next download slightly; hopefully this gives other concurrent fetchers
672        // a better chance to run.
673        // onDownloadNext();
674        sp<AMessage> msg = new AMessage(kWhatDownloadNext, id());
675        msg->setInt32("generation", mMonitorQueueGeneration);
676        msg->post(1000l);
677    } else {
678        // Nothing to do yet, try again in a second.
679
680        sp<AMessage> msg = mNotify->dup();
681        msg->setInt32("what", kWhatTemporarilyDoneFetching);
682        msg->post();
683
684        int64_t delayUs = mPrepared ? kMaxMonitorDelayUs : targetDurationUs / 2;
685        ALOGV("pausing for %" PRId64 ", buffered=%" PRId64 " > %" PRId64 "",
686                delayUs, bufferedDurationUs, durationToBufferUs);
687        // :TRICKY: need to enforce minimum delay because the delay to
688        // refresh the playlist will become 0
689        postMonitorQueue(delayUs, mPrepared ? targetDurationUs * 2 : 0);
690    }
691}
692
693status_t PlaylistFetcher::refreshPlaylist() {
694    if (delayUsToRefreshPlaylist() <= 0) {
695        bool unchanged;
696        sp<M3UParser> playlist = mSession->fetchPlaylist(
697                mURI.c_str(), mPlaylistHash, &unchanged);
698
699        if (playlist == NULL) {
700            if (unchanged) {
701                // We succeeded in fetching the playlist, but it was
702                // unchanged from the last time we tried.
703
704                if (mRefreshState != THIRD_UNCHANGED_RELOAD_ATTEMPT) {
705                    mRefreshState = (RefreshState)(mRefreshState + 1);
706                }
707            } else {
708                ALOGE("failed to load playlist at url '%s'", uriDebugString(mURI).c_str());
709                return ERROR_IO;
710            }
711        } else {
712            mRefreshState = INITIAL_MINIMUM_RELOAD_DELAY;
713            mPlaylist = playlist;
714
715            if (mPlaylist->isComplete() || mPlaylist->isEvent()) {
716                updateDuration();
717            }
718        }
719
720        mLastPlaylistFetchTimeUs = ALooper::GetNowUs();
721    }
722    return OK;
723}
724
725// static
726bool PlaylistFetcher::bufferStartsWithTsSyncByte(const sp<ABuffer>& buffer) {
727    return buffer->size() > 0 && buffer->data()[0] == 0x47;
728}
729
730void PlaylistFetcher::onDownloadNext() {
731    status_t err = refreshPlaylist();
732    int32_t firstSeqNumberInPlaylist = 0;
733    int32_t lastSeqNumberInPlaylist = 0;
734    bool discontinuity = false;
735
736    if (mPlaylist != NULL) {
737        if (mPlaylist->meta() != NULL) {
738            mPlaylist->meta()->findInt32("media-sequence", &firstSeqNumberInPlaylist);
739        }
740
741        lastSeqNumberInPlaylist =
742                firstSeqNumberInPlaylist + (int32_t)mPlaylist->size() - 1;
743
744        if (mDiscontinuitySeq < 0) {
745            mDiscontinuitySeq = mPlaylist->getDiscontinuitySeq();
746        }
747    }
748
749    if (mPlaylist != NULL && mSeqNumber < 0) {
750        CHECK_GE(mStartTimeUs, 0ll);
751
752        if (mSegmentStartTimeUs < 0) {
753            if (!mPlaylist->isComplete() && !mPlaylist->isEvent()) {
754                // If this is a live session, start 3 segments from the end on connect
755                mSeqNumber = lastSeqNumberInPlaylist - 3;
756                if (mSeqNumber < firstSeqNumberInPlaylist) {
757                    mSeqNumber = firstSeqNumberInPlaylist;
758                }
759            } else {
760                mSeqNumber = getSeqNumberForTime(mStartTimeUs);
761                mStartTimeUs -= getSegmentStartTimeUs(mSeqNumber);
762            }
763            mStartTimeUsRelative = true;
764            ALOGV("Initial sequence number for time %" PRId64 " is %d from (%d .. %d)",
765                    mStartTimeUs, mSeqNumber, firstSeqNumberInPlaylist,
766                    lastSeqNumberInPlaylist);
767        } else {
768            mSeqNumber = getSeqNumberForTime(mSegmentStartTimeUs);
769            if (mAdaptive) {
770                // avoid double fetch/decode
771                mSeqNumber += 1;
772            }
773            ssize_t minSeq = getSeqNumberForDiscontinuity(mDiscontinuitySeq);
774            if (mSeqNumber < minSeq) {
775                mSeqNumber = minSeq;
776            }
777
778            if (mSeqNumber < firstSeqNumberInPlaylist) {
779                mSeqNumber = firstSeqNumberInPlaylist;
780            }
781
782            if (mSeqNumber > lastSeqNumberInPlaylist) {
783                mSeqNumber = lastSeqNumberInPlaylist;
784            }
785            ALOGV("Initial sequence number for live event %d from (%d .. %d)",
786                    mSeqNumber, firstSeqNumberInPlaylist,
787                    lastSeqNumberInPlaylist);
788        }
789    }
790
791    // if mPlaylist is NULL then err must be non-OK; but the other way around might not be true
792    if (mSeqNumber < firstSeqNumberInPlaylist
793            || mSeqNumber > lastSeqNumberInPlaylist
794            || err != OK) {
795        if ((err != OK || !mPlaylist->isComplete()) && mNumRetries < kMaxNumRetries) {
796            ++mNumRetries;
797
798            if (mSeqNumber > lastSeqNumberInPlaylist || err != OK) {
799                // make sure we reach this retry logic on refresh failures
800                // by adding an err != OK clause to all enclosing if's.
801
802                // refresh in increasing fraction (1/2, 1/3, ...) of the
803                // playlist's target duration or 3 seconds, whichever is less
804                int64_t delayUs = kMaxMonitorDelayUs;
805                if (mPlaylist != NULL && mPlaylist->meta() != NULL) {
806                    int32_t targetDurationSecs;
807                    CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
808                    delayUs = mPlaylist->size() * targetDurationSecs *
809                            1000000ll / (1 + mNumRetries);
810                }
811                if (delayUs > kMaxMonitorDelayUs) {
812                    delayUs = kMaxMonitorDelayUs;
813                }
814                ALOGV("sequence number high: %d from (%d .. %d), "
815                      "monitor in %" PRId64 " (retry=%d)",
816                        mSeqNumber, firstSeqNumberInPlaylist,
817                        lastSeqNumberInPlaylist, delayUs, mNumRetries);
818                postMonitorQueue(delayUs);
819                return;
820            }
821
822            if (err != OK) {
823                notifyError(err);
824                return;
825            }
826
827            // we've missed the boat, let's start 3 segments prior to the latest sequence
828            // number available and signal a discontinuity.
829
830            ALOGI("We've missed the boat, restarting playback."
831                  "  mStartup=%d, was  looking for %d in %d-%d",
832                    mStartup, mSeqNumber, firstSeqNumberInPlaylist,
833                    lastSeqNumberInPlaylist);
834            if (mStopParams != NULL) {
835                // we should have kept on fetching until we hit the boundaries in mStopParams,
836                // but since the segments we are supposed to fetch have already rolled off
837                // the playlist, i.e. we have already missed the boat, we inevitably have to
838                // skip.
839                for (size_t i = 0; i < mPacketSources.size(); i++) {
840                    sp<ABuffer> formatChange = mSession->createFormatChangeBuffer();
841                    mPacketSources.valueAt(i)->queueAccessUnit(formatChange);
842                }
843                stopAsync(/* clear = */ false);
844                return;
845            }
846            mSeqNumber = lastSeqNumberInPlaylist - 3;
847            if (mSeqNumber < firstSeqNumberInPlaylist) {
848                mSeqNumber = firstSeqNumberInPlaylist;
849            }
850            discontinuity = true;
851
852            // fall through
853        } else {
854            ALOGE("Cannot find sequence number %d in playlist "
855                 "(contains %d - %d)",
856                 mSeqNumber, firstSeqNumberInPlaylist,
857                  firstSeqNumberInPlaylist + (int32_t)mPlaylist->size() - 1);
858
859            notifyError(ERROR_END_OF_STREAM);
860            return;
861        }
862    }
863
864    mNumRetries = 0;
865
866    AString uri;
867    sp<AMessage> itemMeta;
868    CHECK(mPlaylist->itemAt(
869                mSeqNumber - firstSeqNumberInPlaylist,
870                &uri,
871                &itemMeta));
872
873    int32_t val;
874    if (itemMeta->findInt32("discontinuity", &val) && val != 0) {
875        mDiscontinuitySeq++;
876        discontinuity = true;
877    }
878
879    int64_t range_offset, range_length;
880    if (!itemMeta->findInt64("range-offset", &range_offset)
881            || !itemMeta->findInt64("range-length", &range_length)) {
882        range_offset = 0;
883        range_length = -1;
884    }
885
886    ALOGV("fetching segment %d from (%d .. %d)",
887          mSeqNumber, firstSeqNumberInPlaylist, lastSeqNumberInPlaylist);
888
889    ALOGV("fetching '%s'", uri.c_str());
890
891    sp<DataSource> source;
892    sp<ABuffer> buffer, tsBuffer;
893    // decrypt a junk buffer to prefetch key; since a session uses only one http connection,
894    // this avoids interleaved connections to the key and segment file.
895    {
896        sp<ABuffer> junk = new ABuffer(16);
897        junk->setRange(0, 16);
898        status_t err = decryptBuffer(mSeqNumber - firstSeqNumberInPlaylist, junk,
899                true /* first */);
900        if (err != OK) {
901            notifyError(err);
902            return;
903        }
904    }
905
906    // block-wise download
907    bool startup = mStartup;
908    ssize_t bytesRead;
909    do {
910        bytesRead = mSession->fetchFile(
911                uri.c_str(), &buffer, range_offset, range_length, kDownloadBlockSize, &source);
912
913        if (bytesRead < 0) {
914            status_t err = bytesRead;
915            ALOGE("failed to fetch .ts segment at url '%s'", uri.c_str());
916            notifyError(err);
917            return;
918        }
919
920        CHECK(buffer != NULL);
921
922        size_t size = buffer->size();
923        // Set decryption range.
924        buffer->setRange(size - bytesRead, bytesRead);
925        status_t err = decryptBuffer(mSeqNumber - firstSeqNumberInPlaylist, buffer,
926                buffer->offset() == 0 /* first */);
927        // Unset decryption range.
928        buffer->setRange(0, size);
929
930        if (err != OK) {
931            ALOGE("decryptBuffer failed w/ error %d", err);
932
933            notifyError(err);
934            return;
935        }
936
937        if (startup || discontinuity) {
938            // Signal discontinuity.
939
940            if (mPlaylist->isComplete() || mPlaylist->isEvent()) {
941                // If this was a live event this made no sense since
942                // we don't have access to all the segment before the current
943                // one.
944                mNextPTSTimeUs = getSegmentStartTimeUs(mSeqNumber);
945            }
946
947            if (discontinuity) {
948                ALOGI("queueing discontinuity (explicit=%d)", discontinuity);
949
950                queueDiscontinuity(
951                        ATSParser::DISCONTINUITY_FORMATCHANGE,
952                        NULL /* extra */);
953
954                discontinuity = false;
955            }
956
957            startup = false;
958        }
959
960        err = OK;
961        if (bufferStartsWithTsSyncByte(buffer)) {
962            // Incremental extraction is only supported for MPEG2 transport streams.
963            if (tsBuffer == NULL) {
964                tsBuffer = new ABuffer(buffer->data(), buffer->capacity());
965                tsBuffer->setRange(0, 0);
966            } else if (tsBuffer->capacity() != buffer->capacity()) {
967                size_t tsOff = tsBuffer->offset(), tsSize = tsBuffer->size();
968                tsBuffer = new ABuffer(buffer->data(), buffer->capacity());
969                tsBuffer->setRange(tsOff, tsSize);
970            }
971            tsBuffer->setRange(tsBuffer->offset(), tsBuffer->size() + bytesRead);
972
973            err = extractAndQueueAccessUnitsFromTs(tsBuffer);
974        }
975
976        if (err == -EAGAIN) {
977            // starting sequence number too low/high
978            mTSParser.clear();
979            postMonitorQueue();
980            return;
981        } else if (err == ERROR_OUT_OF_RANGE) {
982            // reached stopping point
983            stopAsync(/* clear = */ false);
984            return;
985        } else if (err != OK) {
986            notifyError(err);
987            return;
988        }
989
990    } while (bytesRead != 0);
991
992    if (bufferStartsWithTsSyncByte(buffer)) {
993        // If we don't see a stream in the program table after fetching a full ts segment
994        // mark it as nonexistent.
995        const size_t kNumTypes = ATSParser::NUM_SOURCE_TYPES;
996        ATSParser::SourceType srcTypes[kNumTypes] =
997                { ATSParser::VIDEO, ATSParser::AUDIO };
998        LiveSession::StreamType streamTypes[kNumTypes] =
999                { LiveSession::STREAMTYPE_VIDEO, LiveSession::STREAMTYPE_AUDIO };
1000
1001        for (size_t i = 0; i < kNumTypes; i++) {
1002            ATSParser::SourceType srcType = srcTypes[i];
1003            LiveSession::StreamType streamType = streamTypes[i];
1004
1005            sp<AnotherPacketSource> source =
1006                static_cast<AnotherPacketSource *>(
1007                    mTSParser->getSource(srcType).get());
1008
1009            if (!mTSParser->hasSource(srcType)) {
1010                ALOGW("MPEG2 Transport stream does not contain %s data.",
1011                      srcType == ATSParser::VIDEO ? "video" : "audio");
1012
1013                mStreamTypeMask &= ~streamType;
1014                mPacketSources.removeItem(streamType);
1015            }
1016        }
1017
1018    }
1019
1020    if (checkDecryptPadding(buffer) != OK) {
1021        ALOGE("Incorrect padding bytes after decryption.");
1022        notifyError(ERROR_MALFORMED);
1023        return;
1024    }
1025
1026    err = OK;
1027    if (tsBuffer != NULL) {
1028        AString method;
1029        CHECK(buffer->meta()->findString("cipher-method", &method));
1030        if ((tsBuffer->size() > 0 && method == "NONE")
1031                || tsBuffer->size() > 16) {
1032            ALOGE("MPEG2 transport stream is not an even multiple of 188 "
1033                    "bytes in length.");
1034            notifyError(ERROR_MALFORMED);
1035            return;
1036        }
1037    }
1038
1039    // bulk extract non-ts files
1040    if (tsBuffer == NULL) {
1041        err = extractAndQueueAccessUnits(buffer, itemMeta);
1042        if (err == -EAGAIN) {
1043            // starting sequence number too low/high
1044            postMonitorQueue();
1045            return;
1046        } else if (err == ERROR_OUT_OF_RANGE) {
1047            // reached stopping point
1048            stopAsync(/* clear = */false);
1049            return;
1050        }
1051    }
1052
1053    if (err != OK) {
1054        notifyError(err);
1055        return;
1056    }
1057
1058    ++mSeqNumber;
1059
1060    postMonitorQueue();
1061}
1062
1063int32_t PlaylistFetcher::getSeqNumberWithAnchorTime(int64_t anchorTimeUs) const {
1064    int32_t firstSeqNumberInPlaylist, lastSeqNumberInPlaylist;
1065    if (mPlaylist->meta() == NULL
1066            || !mPlaylist->meta()->findInt32("media-sequence", &firstSeqNumberInPlaylist)) {
1067        firstSeqNumberInPlaylist = 0;
1068    }
1069    lastSeqNumberInPlaylist = firstSeqNumberInPlaylist + mPlaylist->size() - 1;
1070
1071    int32_t index = mSeqNumber - firstSeqNumberInPlaylist - 1;
1072    while (index >= 0 && anchorTimeUs > mStartTimeUs) {
1073        sp<AMessage> itemMeta;
1074        CHECK(mPlaylist->itemAt(index, NULL /* uri */, &itemMeta));
1075
1076        int64_t itemDurationUs;
1077        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1078
1079        anchorTimeUs -= itemDurationUs;
1080        --index;
1081    }
1082
1083    int32_t newSeqNumber = firstSeqNumberInPlaylist + index + 1;
1084    if (newSeqNumber <= lastSeqNumberInPlaylist) {
1085        return newSeqNumber;
1086    } else {
1087        return lastSeqNumberInPlaylist;
1088    }
1089}
1090
1091int32_t PlaylistFetcher::getSeqNumberForDiscontinuity(size_t discontinuitySeq) const {
1092    int32_t firstSeqNumberInPlaylist;
1093    if (mPlaylist->meta() == NULL
1094            || !mPlaylist->meta()->findInt32("media-sequence", &firstSeqNumberInPlaylist)) {
1095        firstSeqNumberInPlaylist = 0;
1096    }
1097
1098    size_t curDiscontinuitySeq = mPlaylist->getDiscontinuitySeq();
1099    if (discontinuitySeq < curDiscontinuitySeq) {
1100        return firstSeqNumberInPlaylist <= 0 ? 0 : (firstSeqNumberInPlaylist - 1);
1101    }
1102
1103    size_t index = 0;
1104    while (index < mPlaylist->size()) {
1105        sp<AMessage> itemMeta;
1106        CHECK(mPlaylist->itemAt( index, NULL /* uri */, &itemMeta));
1107
1108        int64_t discontinuity;
1109        if (itemMeta->findInt64("discontinuity", &discontinuity)) {
1110            curDiscontinuitySeq++;
1111        }
1112
1113        if (curDiscontinuitySeq == discontinuitySeq) {
1114            return firstSeqNumberInPlaylist + index;
1115        }
1116
1117        ++index;
1118    }
1119
1120    return firstSeqNumberInPlaylist + mPlaylist->size();
1121}
1122
1123int32_t PlaylistFetcher::getSeqNumberForTime(int64_t timeUs) const {
1124    int32_t firstSeqNumberInPlaylist;
1125    if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
1126                "media-sequence", &firstSeqNumberInPlaylist)) {
1127        firstSeqNumberInPlaylist = 0;
1128    }
1129
1130    size_t index = 0;
1131    int64_t segmentStartUs = 0;
1132    while (index < mPlaylist->size()) {
1133        sp<AMessage> itemMeta;
1134        CHECK(mPlaylist->itemAt(
1135                    index, NULL /* uri */, &itemMeta));
1136
1137        int64_t itemDurationUs;
1138        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1139
1140        if (timeUs < segmentStartUs + itemDurationUs) {
1141            break;
1142        }
1143
1144        segmentStartUs += itemDurationUs;
1145        ++index;
1146    }
1147
1148    if (index >= mPlaylist->size()) {
1149        index = mPlaylist->size() - 1;
1150    }
1151
1152    return firstSeqNumberInPlaylist + index;
1153}
1154
1155const sp<ABuffer> &PlaylistFetcher::setAccessUnitProperties(
1156        const sp<ABuffer> &accessUnit, const sp<AnotherPacketSource> &source, bool discard) {
1157    sp<MetaData> format = source->getFormat();
1158    if (format != NULL) {
1159        // for simplicity, store a reference to the format in each unit
1160        accessUnit->meta()->setObject("format", format);
1161    }
1162
1163    if (discard) {
1164        accessUnit->meta()->setInt32("discard", discard);
1165    }
1166
1167    int32_t targetDurationSecs;
1168    if (mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs)) {
1169        accessUnit->meta()->setInt32("targetDuration", targetDurationSecs);
1170    }
1171
1172    accessUnit->meta()->setInt32("discontinuitySeq", mDiscontinuitySeq);
1173    accessUnit->meta()->setInt64("segmentStartTimeUs", getSegmentStartTimeUs(mSeqNumber));
1174    return accessUnit;
1175}
1176
1177status_t PlaylistFetcher::extractAndQueueAccessUnitsFromTs(const sp<ABuffer> &buffer) {
1178    if (mTSParser == NULL) {
1179        // Use TS_TIMESTAMPS_ARE_ABSOLUTE so pts carry over between fetchers.
1180        mTSParser = new ATSParser(ATSParser::TS_TIMESTAMPS_ARE_ABSOLUTE);
1181    }
1182
1183    if (mNextPTSTimeUs >= 0ll) {
1184        sp<AMessage> extra = new AMessage;
1185        // Since we are using absolute timestamps, signal an offset of 0 to prevent
1186        // ATSParser from skewing the timestamps of access units.
1187        extra->setInt64(IStreamListener::kKeyMediaTimeUs, 0);
1188
1189        mTSParser->signalDiscontinuity(
1190                ATSParser::DISCONTINUITY_TIME, extra);
1191
1192        mAbsoluteTimeAnchorUs = mNextPTSTimeUs;
1193        mNextPTSTimeUs = -1ll;
1194        mFirstPTSValid = false;
1195    }
1196
1197    size_t offset = 0;
1198    while (offset + 188 <= buffer->size()) {
1199        status_t err = mTSParser->feedTSPacket(buffer->data() + offset, 188);
1200
1201        if (err != OK) {
1202            return err;
1203        }
1204
1205        offset += 188;
1206    }
1207    // setRange to indicate consumed bytes.
1208    buffer->setRange(buffer->offset() + offset, buffer->size() - offset);
1209
1210    status_t err = OK;
1211    for (size_t i = mPacketSources.size(); i-- > 0;) {
1212        sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
1213
1214        const char *key;
1215        ATSParser::SourceType type;
1216        const LiveSession::StreamType stream = mPacketSources.keyAt(i);
1217        switch (stream) {
1218            case LiveSession::STREAMTYPE_VIDEO:
1219                type = ATSParser::VIDEO;
1220                key = "timeUsVideo";
1221                break;
1222
1223            case LiveSession::STREAMTYPE_AUDIO:
1224                type = ATSParser::AUDIO;
1225                key = "timeUsAudio";
1226                break;
1227
1228            case LiveSession::STREAMTYPE_SUBTITLES:
1229            {
1230                ALOGE("MPEG2 Transport streams do not contain subtitles.");
1231                return ERROR_MALFORMED;
1232                break;
1233            }
1234
1235            default:
1236                TRESPASS();
1237        }
1238
1239        sp<AnotherPacketSource> source =
1240            static_cast<AnotherPacketSource *>(
1241                    mTSParser->getSource(type).get());
1242
1243        if (source == NULL) {
1244            continue;
1245        }
1246
1247        int64_t timeUs;
1248        sp<ABuffer> accessUnit;
1249        status_t finalResult;
1250        while (source->hasBufferAvailable(&finalResult)
1251                && source->dequeueAccessUnit(&accessUnit) == OK) {
1252
1253            CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
1254
1255            if (mStartup) {
1256                if (!mFirstPTSValid) {
1257                    mFirstTimeUs = timeUs;
1258                    mFirstPTSValid = true;
1259                }
1260                if (mStartTimeUsRelative) {
1261                    timeUs -= mFirstTimeUs;
1262                    if (timeUs < 0) {
1263                        timeUs = 0;
1264                    }
1265                }
1266
1267                if (timeUs < mStartTimeUs) {
1268                    // buffer up to the closest preceding IDR frame
1269                    ALOGV("timeUs %" PRId64 " us < mStartTimeUs %" PRId64 " us",
1270                            timeUs, mStartTimeUs);
1271                    const char *mime;
1272                    sp<MetaData> format  = source->getFormat();
1273                    bool isAvc = false;
1274                    if (format != NULL && format->findCString(kKeyMIMEType, &mime)
1275                            && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1276                        isAvc = true;
1277                    }
1278                    if (isAvc && IsIDR(accessUnit)) {
1279                        mVideoBuffer->clear();
1280                    }
1281                    if (isAvc) {
1282                        mVideoBuffer->queueAccessUnit(accessUnit);
1283                    }
1284
1285                    continue;
1286                }
1287            }
1288
1289            CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
1290            if (mStartTimeUsNotify != NULL && timeUs > mStartTimeUs) {
1291                int32_t firstSeqNumberInPlaylist;
1292                if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
1293                            "media-sequence", &firstSeqNumberInPlaylist)) {
1294                    firstSeqNumberInPlaylist = 0;
1295                }
1296
1297                int32_t targetDurationSecs;
1298                CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
1299                int64_t targetDurationUs = targetDurationSecs * 1000000ll;
1300                // mStartup
1301                //   mStartup is true until we have queued a packet for all the streams
1302                //   we are fetching. We queue packets whose timestamps are greater than
1303                //   mStartTimeUs.
1304                // mSegmentStartTimeUs >= 0
1305                //   mSegmentStartTimeUs is non-negative when adapting or switching tracks
1306                // mSeqNumber > firstSeqNumberInPlaylist
1307                //   don't decrement mSeqNumber if it already points to the 1st segment
1308                // timeUs - mStartTimeUs > targetDurationUs:
1309                //   This and the 2 above conditions should only happen when adapting in a live
1310                //   stream; the old fetcher has already fetched to mStartTimeUs; the new fetcher
1311                //   would start fetching after timeUs, which should be greater than mStartTimeUs;
1312                //   the old fetcher would then continue fetching data until timeUs. We don't want
1313                //   timeUs to be too far ahead of mStartTimeUs because we want the old fetcher to
1314                //   stop as early as possible. The definition of being "too far ahead" is
1315                //   arbitrary; here we use targetDurationUs as threshold.
1316                if (mStartup && mSegmentStartTimeUs >= 0
1317                        && mSeqNumber > firstSeqNumberInPlaylist
1318                        && timeUs - mStartTimeUs > targetDurationUs) {
1319                    // we just guessed a starting timestamp that is too high when adapting in a
1320                    // live stream; re-adjust based on the actual timestamp extracted from the
1321                    // media segment; if we didn't move backward after the re-adjustment
1322                    // (newSeqNumber), start at least 1 segment prior.
1323                    int32_t newSeqNumber = getSeqNumberWithAnchorTime(timeUs);
1324                    if (newSeqNumber >= mSeqNumber) {
1325                        --mSeqNumber;
1326                    } else {
1327                        mSeqNumber = newSeqNumber;
1328                    }
1329                    mStartTimeUsNotify = mNotify->dup();
1330                    mStartTimeUsNotify->setInt32("what", kWhatStartedAt);
1331                    return -EAGAIN;
1332                }
1333
1334                int32_t seq;
1335                if (!mStartTimeUsNotify->findInt32("discontinuitySeq", &seq)) {
1336                    mStartTimeUsNotify->setInt32("discontinuitySeq", mDiscontinuitySeq);
1337                }
1338                int64_t startTimeUs;
1339                if (!mStartTimeUsNotify->findInt64(key, &startTimeUs)) {
1340                    mStartTimeUsNotify->setInt64(key, timeUs);
1341
1342                    uint32_t streamMask = 0;
1343                    mStartTimeUsNotify->findInt32("streamMask", (int32_t *) &streamMask);
1344                    streamMask |= mPacketSources.keyAt(i);
1345                    mStartTimeUsNotify->setInt32("streamMask", streamMask);
1346
1347                    if (streamMask == mStreamTypeMask) {
1348                        mStartup = false;
1349                        mStartTimeUsNotify->post();
1350                        mStartTimeUsNotify.clear();
1351                    }
1352                }
1353            }
1354
1355            if (mStopParams != NULL) {
1356                // Queue discontinuity in original stream.
1357                int32_t discontinuitySeq;
1358                int64_t stopTimeUs;
1359                if (!mStopParams->findInt32("discontinuitySeq", &discontinuitySeq)
1360                        || discontinuitySeq > mDiscontinuitySeq
1361                        || !mStopParams->findInt64(key, &stopTimeUs)
1362                        || (discontinuitySeq == mDiscontinuitySeq
1363                                && timeUs >= stopTimeUs)) {
1364                    packetSource->queueAccessUnit(mSession->createFormatChangeBuffer());
1365                    mStreamTypeMask &= ~stream;
1366                    mPacketSources.removeItemsAt(i);
1367                    break;
1368                }
1369            }
1370
1371            // Note that we do NOT dequeue any discontinuities except for format change.
1372            if (stream == LiveSession::STREAMTYPE_VIDEO) {
1373                const bool discard = true;
1374                status_t status;
1375                while (mVideoBuffer->hasBufferAvailable(&status)) {
1376                    sp<ABuffer> videoBuffer;
1377                    mVideoBuffer->dequeueAccessUnit(&videoBuffer);
1378                    setAccessUnitProperties(videoBuffer, source, discard);
1379                    packetSource->queueAccessUnit(videoBuffer);
1380                }
1381            }
1382
1383            setAccessUnitProperties(accessUnit, source);
1384            packetSource->queueAccessUnit(accessUnit);
1385        }
1386
1387        if (err != OK) {
1388            break;
1389        }
1390    }
1391
1392    if (err != OK) {
1393        for (size_t i = mPacketSources.size(); i-- > 0;) {
1394            sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
1395            packetSource->clear();
1396        }
1397        return err;
1398    }
1399
1400    if (!mStreamTypeMask) {
1401        // Signal gap is filled between original and new stream.
1402        ALOGV("ERROR OUT OF RANGE");
1403        return ERROR_OUT_OF_RANGE;
1404    }
1405
1406    return OK;
1407}
1408
1409/* static */
1410bool PlaylistFetcher::bufferStartsWithWebVTTMagicSequence(
1411        const sp<ABuffer> &buffer) {
1412    size_t pos = 0;
1413
1414    // skip possible BOM
1415    if (buffer->size() >= pos + 3 &&
1416            !memcmp("\xef\xbb\xbf", buffer->data() + pos, 3)) {
1417        pos += 3;
1418    }
1419
1420    // accept WEBVTT followed by SPACE, TAB or (CR) LF
1421    if (buffer->size() < pos + 6 ||
1422            memcmp("WEBVTT", buffer->data() + pos, 6)) {
1423        return false;
1424    }
1425    pos += 6;
1426
1427    if (buffer->size() == pos) {
1428        return true;
1429    }
1430
1431    uint8_t sep = buffer->data()[pos];
1432    return sep == ' ' || sep == '\t' || sep == '\n' || sep == '\r';
1433}
1434
1435status_t PlaylistFetcher::extractAndQueueAccessUnits(
1436        const sp<ABuffer> &buffer, const sp<AMessage> &itemMeta) {
1437    if (bufferStartsWithWebVTTMagicSequence(buffer)) {
1438        if (mStreamTypeMask != LiveSession::STREAMTYPE_SUBTITLES) {
1439            ALOGE("This stream only contains subtitles.");
1440            return ERROR_MALFORMED;
1441        }
1442
1443        const sp<AnotherPacketSource> packetSource =
1444            mPacketSources.valueFor(LiveSession::STREAMTYPE_SUBTITLES);
1445
1446        int64_t durationUs;
1447        CHECK(itemMeta->findInt64("durationUs", &durationUs));
1448        buffer->meta()->setInt64("timeUs", getSegmentStartTimeUs(mSeqNumber));
1449        buffer->meta()->setInt64("durationUs", durationUs);
1450        buffer->meta()->setInt64("segmentStartTimeUs", getSegmentStartTimeUs(mSeqNumber));
1451        buffer->meta()->setInt32("discontinuitySeq", mDiscontinuitySeq);
1452        buffer->meta()->setInt32("subtitleGeneration", mSubtitleGeneration);
1453
1454        packetSource->queueAccessUnit(buffer);
1455        return OK;
1456    }
1457
1458    if (mNextPTSTimeUs >= 0ll) {
1459        mFirstPTSValid = false;
1460        mAbsoluteTimeAnchorUs = mNextPTSTimeUs;
1461        mNextPTSTimeUs = -1ll;
1462    }
1463
1464    // This better be an ISO 13818-7 (AAC) or ISO 13818-1 (MPEG) audio
1465    // stream prefixed by an ID3 tag.
1466
1467    bool firstID3Tag = true;
1468    uint64_t PTS = 0;
1469
1470    for (;;) {
1471        // Make sure to skip all ID3 tags preceding the audio data.
1472        // At least one must be present to provide the PTS timestamp.
1473
1474        ID3 id3(buffer->data(), buffer->size(), true /* ignoreV1 */);
1475        if (!id3.isValid()) {
1476            if (firstID3Tag) {
1477                ALOGE("Unable to parse ID3 tag.");
1478                return ERROR_MALFORMED;
1479            } else {
1480                break;
1481            }
1482        }
1483
1484        if (firstID3Tag) {
1485            bool found = false;
1486
1487            ID3::Iterator it(id3, "PRIV");
1488            while (!it.done()) {
1489                size_t length;
1490                const uint8_t *data = it.getData(&length);
1491
1492                static const char *kMatchName =
1493                    "com.apple.streaming.transportStreamTimestamp";
1494                static const size_t kMatchNameLen = strlen(kMatchName);
1495
1496                if (length == kMatchNameLen + 1 + 8
1497                        && !strncmp((const char *)data, kMatchName, kMatchNameLen)) {
1498                    found = true;
1499                    PTS = U64_AT(&data[kMatchNameLen + 1]);
1500                }
1501
1502                it.next();
1503            }
1504
1505            if (!found) {
1506                ALOGE("Unable to extract transportStreamTimestamp from ID3 tag.");
1507                return ERROR_MALFORMED;
1508            }
1509        }
1510
1511        // skip the ID3 tag
1512        buffer->setRange(
1513                buffer->offset() + id3.rawSize(), buffer->size() - id3.rawSize());
1514
1515        firstID3Tag = false;
1516    }
1517
1518    if (mStreamTypeMask != LiveSession::STREAMTYPE_AUDIO) {
1519        ALOGW("This stream only contains audio data!");
1520
1521        mStreamTypeMask &= LiveSession::STREAMTYPE_AUDIO;
1522
1523        if (mStreamTypeMask == 0) {
1524            return OK;
1525        }
1526    }
1527
1528    sp<AnotherPacketSource> packetSource =
1529        mPacketSources.valueFor(LiveSession::STREAMTYPE_AUDIO);
1530
1531    if (packetSource->getFormat() == NULL && buffer->size() >= 7) {
1532        ABitReader bits(buffer->data(), buffer->size());
1533
1534        // adts_fixed_header
1535
1536        CHECK_EQ(bits.getBits(12), 0xfffu);
1537        bits.skipBits(3);  // ID, layer
1538        bool protection_absent = bits.getBits(1) != 0;
1539
1540        unsigned profile = bits.getBits(2);
1541        CHECK_NE(profile, 3u);
1542        unsigned sampling_freq_index = bits.getBits(4);
1543        bits.getBits(1);  // private_bit
1544        unsigned channel_configuration = bits.getBits(3);
1545        CHECK_NE(channel_configuration, 0u);
1546        bits.skipBits(2);  // original_copy, home
1547
1548        sp<MetaData> meta = MakeAACCodecSpecificData(
1549                profile, sampling_freq_index, channel_configuration);
1550
1551        meta->setInt32(kKeyIsADTS, true);
1552
1553        packetSource->setFormat(meta);
1554    }
1555
1556    int64_t numSamples = 0ll;
1557    int32_t sampleRate;
1558    CHECK(packetSource->getFormat()->findInt32(kKeySampleRate, &sampleRate));
1559
1560    int64_t timeUs = (PTS * 100ll) / 9ll;
1561    if (!mFirstPTSValid) {
1562        mFirstPTSValid = true;
1563        mFirstTimeUs = timeUs;
1564    }
1565
1566    size_t offset = 0;
1567    while (offset < buffer->size()) {
1568        const uint8_t *adtsHeader = buffer->data() + offset;
1569        CHECK_LT(offset + 5, buffer->size());
1570
1571        unsigned aac_frame_length =
1572            ((adtsHeader[3] & 3) << 11)
1573            | (adtsHeader[4] << 3)
1574            | (adtsHeader[5] >> 5);
1575
1576        if (aac_frame_length == 0) {
1577            const uint8_t *id3Header = adtsHeader;
1578            if (!memcmp(id3Header, "ID3", 3)) {
1579                ID3 id3(id3Header, buffer->size() - offset, true);
1580                if (id3.isValid()) {
1581                    offset += id3.rawSize();
1582                    continue;
1583                };
1584            }
1585            return ERROR_MALFORMED;
1586        }
1587
1588        CHECK_LE(offset + aac_frame_length, buffer->size());
1589
1590        int64_t unitTimeUs = timeUs + numSamples * 1000000ll / sampleRate;
1591        offset += aac_frame_length;
1592
1593        // Each AAC frame encodes 1024 samples.
1594        numSamples += 1024;
1595
1596        if (mStartup) {
1597            int64_t startTimeUs = unitTimeUs;
1598            if (mStartTimeUsRelative) {
1599                startTimeUs -= mFirstTimeUs;
1600                if (startTimeUs  < 0) {
1601                    startTimeUs = 0;
1602                }
1603            }
1604            if (startTimeUs < mStartTimeUs) {
1605                continue;
1606            }
1607
1608            if (mStartTimeUsNotify != NULL) {
1609                int32_t targetDurationSecs;
1610                CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
1611                int64_t targetDurationUs = targetDurationSecs * 1000000ll;
1612
1613                // Duplicated logic from how we handle .ts playlists.
1614                if (mStartup && mSegmentStartTimeUs >= 0
1615                        && timeUs - mStartTimeUs > targetDurationUs) {
1616                    int32_t newSeqNumber = getSeqNumberWithAnchorTime(timeUs);
1617                    if (newSeqNumber >= mSeqNumber) {
1618                        --mSeqNumber;
1619                    } else {
1620                        mSeqNumber = newSeqNumber;
1621                    }
1622                    return -EAGAIN;
1623                }
1624
1625                mStartTimeUsNotify->setInt64("timeUsAudio", timeUs);
1626                mStartTimeUsNotify->setInt32("discontinuitySeq", mDiscontinuitySeq);
1627                mStartTimeUsNotify->setInt32("streamMask", LiveSession::STREAMTYPE_AUDIO);
1628                mStartTimeUsNotify->post();
1629                mStartTimeUsNotify.clear();
1630                mStartup = false;
1631            }
1632        }
1633
1634        if (mStopParams != NULL) {
1635            // Queue discontinuity in original stream.
1636            int32_t discontinuitySeq;
1637            int64_t stopTimeUs;
1638            if (!mStopParams->findInt32("discontinuitySeq", &discontinuitySeq)
1639                    || discontinuitySeq > mDiscontinuitySeq
1640                    || !mStopParams->findInt64("timeUsAudio", &stopTimeUs)
1641                    || (discontinuitySeq == mDiscontinuitySeq && unitTimeUs >= stopTimeUs)) {
1642                packetSource->queueAccessUnit(mSession->createFormatChangeBuffer());
1643                mStreamTypeMask = 0;
1644                mPacketSources.clear();
1645                return ERROR_OUT_OF_RANGE;
1646            }
1647        }
1648
1649        sp<ABuffer> unit = new ABuffer(aac_frame_length);
1650        memcpy(unit->data(), adtsHeader, aac_frame_length);
1651
1652        unit->meta()->setInt64("timeUs", unitTimeUs);
1653        setAccessUnitProperties(unit, packetSource);
1654        packetSource->queueAccessUnit(unit);
1655    }
1656
1657    return OK;
1658}
1659
1660void PlaylistFetcher::updateDuration() {
1661    int64_t durationUs = 0ll;
1662    for (size_t index = 0; index < mPlaylist->size(); ++index) {
1663        sp<AMessage> itemMeta;
1664        CHECK(mPlaylist->itemAt(
1665                    index, NULL /* uri */, &itemMeta));
1666
1667        int64_t itemDurationUs;
1668        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1669
1670        durationUs += itemDurationUs;
1671    }
1672
1673    sp<AMessage> msg = mNotify->dup();
1674    msg->setInt32("what", kWhatDurationUpdate);
1675    msg->setInt64("durationUs", durationUs);
1676    msg->post();
1677}
1678
1679int64_t PlaylistFetcher::resumeThreshold(const sp<AMessage> &msg) {
1680    int64_t durationUs, threshold;
1681    if (msg->findInt64("durationUs", &durationUs)) {
1682        return kNumSkipFrames * durationUs;
1683    }
1684
1685    sp<RefBase> obj;
1686    msg->findObject("format", &obj);
1687    MetaData *format = static_cast<MetaData *>(obj.get());
1688
1689    const char *mime;
1690    CHECK(format->findCString(kKeyMIMEType, &mime));
1691    bool audio = !strncasecmp(mime, "audio/", 6);
1692    if (audio) {
1693        // Assumes 1000 samples per frame.
1694        int32_t sampleRate;
1695        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
1696        return kNumSkipFrames  /* frames */ * 1000 /* samples */
1697                * (1000000 / sampleRate) /* sample duration (us) */;
1698    } else {
1699        int32_t frameRate;
1700        if (format->findInt32(kKeyFrameRate, &frameRate) && frameRate > 0) {
1701            return kNumSkipFrames * (1000000 / frameRate);
1702        }
1703    }
1704
1705    return 500000ll;
1706}
1707
1708}  // namespace android
1709