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