PlaylistFetcher.cpp revision dae1e733f7cd4abaa14791657fa0a1b0e44a27b6
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            for (size_t i = 0; i < mPacketSources.size(); i++) {
981                sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
982                packetSource->clear();
983            }
984            postMonitorQueue();
985            return;
986        } else if (err == ERROR_OUT_OF_RANGE) {
987            // reached stopping point
988            stopAsync(/* clear = */ false);
989            return;
990        } else if (err != OK) {
991            notifyError(err);
992            return;
993        }
994
995    } while (bytesRead != 0);
996
997    if (bufferStartsWithTsSyncByte(buffer)) {
998        // If we don't see a stream in the program table after fetching a full ts segment
999        // mark it as nonexistent.
1000        const size_t kNumTypes = ATSParser::NUM_SOURCE_TYPES;
1001        ATSParser::SourceType srcTypes[kNumTypes] =
1002                { ATSParser::VIDEO, ATSParser::AUDIO };
1003        LiveSession::StreamType streamTypes[kNumTypes] =
1004                { LiveSession::STREAMTYPE_VIDEO, LiveSession::STREAMTYPE_AUDIO };
1005
1006        for (size_t i = 0; i < kNumTypes; i++) {
1007            ATSParser::SourceType srcType = srcTypes[i];
1008            LiveSession::StreamType streamType = streamTypes[i];
1009
1010            sp<AnotherPacketSource> source =
1011                static_cast<AnotherPacketSource *>(
1012                    mTSParser->getSource(srcType).get());
1013
1014            if (!mTSParser->hasSource(srcType)) {
1015                ALOGW("MPEG2 Transport stream does not contain %s data.",
1016                      srcType == ATSParser::VIDEO ? "video" : "audio");
1017
1018                mStreamTypeMask &= ~streamType;
1019                mPacketSources.removeItem(streamType);
1020            }
1021        }
1022
1023    }
1024
1025    if (checkDecryptPadding(buffer) != OK) {
1026        ALOGE("Incorrect padding bytes after decryption.");
1027        notifyError(ERROR_MALFORMED);
1028        return;
1029    }
1030
1031    err = OK;
1032    if (tsBuffer != NULL) {
1033        AString method;
1034        CHECK(buffer->meta()->findString("cipher-method", &method));
1035        if ((tsBuffer->size() > 0 && method == "NONE")
1036                || tsBuffer->size() > 16) {
1037            ALOGE("MPEG2 transport stream is not an even multiple of 188 "
1038                    "bytes in length.");
1039            notifyError(ERROR_MALFORMED);
1040            return;
1041        }
1042    }
1043
1044    // bulk extract non-ts files
1045    if (tsBuffer == NULL) {
1046        err = extractAndQueueAccessUnits(buffer, itemMeta);
1047        if (err == -EAGAIN) {
1048            // starting sequence number too low/high
1049            postMonitorQueue();
1050            return;
1051        } else if (err == ERROR_OUT_OF_RANGE) {
1052            // reached stopping point
1053            stopAsync(/* clear = */false);
1054            return;
1055        }
1056    }
1057
1058    if (err != OK) {
1059        notifyError(err);
1060        return;
1061    }
1062
1063    ++mSeqNumber;
1064
1065    postMonitorQueue();
1066}
1067
1068int32_t PlaylistFetcher::getSeqNumberWithAnchorTime(int64_t anchorTimeUs) const {
1069    int32_t firstSeqNumberInPlaylist, lastSeqNumberInPlaylist;
1070    if (mPlaylist->meta() == NULL
1071            || !mPlaylist->meta()->findInt32("media-sequence", &firstSeqNumberInPlaylist)) {
1072        firstSeqNumberInPlaylist = 0;
1073    }
1074    lastSeqNumberInPlaylist = firstSeqNumberInPlaylist + mPlaylist->size() - 1;
1075
1076    int32_t index = mSeqNumber - firstSeqNumberInPlaylist - 1;
1077    while (index >= 0 && anchorTimeUs > mStartTimeUs) {
1078        sp<AMessage> itemMeta;
1079        CHECK(mPlaylist->itemAt(index, NULL /* uri */, &itemMeta));
1080
1081        int64_t itemDurationUs;
1082        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1083
1084        anchorTimeUs -= itemDurationUs;
1085        --index;
1086    }
1087
1088    int32_t newSeqNumber = firstSeqNumberInPlaylist + index + 1;
1089    if (newSeqNumber <= lastSeqNumberInPlaylist) {
1090        return newSeqNumber;
1091    } else {
1092        return lastSeqNumberInPlaylist;
1093    }
1094}
1095
1096int32_t PlaylistFetcher::getSeqNumberForDiscontinuity(size_t discontinuitySeq) const {
1097    int32_t firstSeqNumberInPlaylist;
1098    if (mPlaylist->meta() == NULL
1099            || !mPlaylist->meta()->findInt32("media-sequence", &firstSeqNumberInPlaylist)) {
1100        firstSeqNumberInPlaylist = 0;
1101    }
1102
1103    size_t curDiscontinuitySeq = mPlaylist->getDiscontinuitySeq();
1104    if (discontinuitySeq < curDiscontinuitySeq) {
1105        return firstSeqNumberInPlaylist <= 0 ? 0 : (firstSeqNumberInPlaylist - 1);
1106    }
1107
1108    size_t index = 0;
1109    while (index < mPlaylist->size()) {
1110        sp<AMessage> itemMeta;
1111        CHECK(mPlaylist->itemAt( index, NULL /* uri */, &itemMeta));
1112
1113        int64_t discontinuity;
1114        if (itemMeta->findInt64("discontinuity", &discontinuity)) {
1115            curDiscontinuitySeq++;
1116        }
1117
1118        if (curDiscontinuitySeq == discontinuitySeq) {
1119            return firstSeqNumberInPlaylist + index;
1120        }
1121
1122        ++index;
1123    }
1124
1125    return firstSeqNumberInPlaylist + mPlaylist->size();
1126}
1127
1128int32_t PlaylistFetcher::getSeqNumberForTime(int64_t timeUs) const {
1129    int32_t firstSeqNumberInPlaylist;
1130    if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
1131                "media-sequence", &firstSeqNumberInPlaylist)) {
1132        firstSeqNumberInPlaylist = 0;
1133    }
1134
1135    size_t index = 0;
1136    int64_t segmentStartUs = 0;
1137    while (index < mPlaylist->size()) {
1138        sp<AMessage> itemMeta;
1139        CHECK(mPlaylist->itemAt(
1140                    index, NULL /* uri */, &itemMeta));
1141
1142        int64_t itemDurationUs;
1143        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1144
1145        if (timeUs < segmentStartUs + itemDurationUs) {
1146            break;
1147        }
1148
1149        segmentStartUs += itemDurationUs;
1150        ++index;
1151    }
1152
1153    if (index >= mPlaylist->size()) {
1154        index = mPlaylist->size() - 1;
1155    }
1156
1157    return firstSeqNumberInPlaylist + index;
1158}
1159
1160const sp<ABuffer> &PlaylistFetcher::setAccessUnitProperties(
1161        const sp<ABuffer> &accessUnit, const sp<AnotherPacketSource> &source, bool discard) {
1162    sp<MetaData> format = source->getFormat();
1163    if (format != NULL) {
1164        // for simplicity, store a reference to the format in each unit
1165        accessUnit->meta()->setObject("format", format);
1166    }
1167
1168    if (discard) {
1169        accessUnit->meta()->setInt32("discard", discard);
1170    }
1171
1172    int32_t targetDurationSecs;
1173    if (mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs)) {
1174        accessUnit->meta()->setInt32("targetDuration", targetDurationSecs);
1175    }
1176
1177    accessUnit->meta()->setInt32("discontinuitySeq", mDiscontinuitySeq);
1178    accessUnit->meta()->setInt64("segmentStartTimeUs", getSegmentStartTimeUs(mSeqNumber));
1179    return accessUnit;
1180}
1181
1182status_t PlaylistFetcher::extractAndQueueAccessUnitsFromTs(const sp<ABuffer> &buffer) {
1183    if (mTSParser == NULL) {
1184        // Use TS_TIMESTAMPS_ARE_ABSOLUTE so pts carry over between fetchers.
1185        mTSParser = new ATSParser(ATSParser::TS_TIMESTAMPS_ARE_ABSOLUTE);
1186    }
1187
1188    if (mNextPTSTimeUs >= 0ll) {
1189        sp<AMessage> extra = new AMessage;
1190        // Since we are using absolute timestamps, signal an offset of 0 to prevent
1191        // ATSParser from skewing the timestamps of access units.
1192        extra->setInt64(IStreamListener::kKeyMediaTimeUs, 0);
1193
1194        mTSParser->signalDiscontinuity(
1195                ATSParser::DISCONTINUITY_TIME, extra);
1196
1197        mAbsoluteTimeAnchorUs = mNextPTSTimeUs;
1198        mNextPTSTimeUs = -1ll;
1199        mFirstPTSValid = false;
1200    }
1201
1202    size_t offset = 0;
1203    while (offset + 188 <= buffer->size()) {
1204        status_t err = mTSParser->feedTSPacket(buffer->data() + offset, 188);
1205
1206        if (err != OK) {
1207            return err;
1208        }
1209
1210        offset += 188;
1211    }
1212    // setRange to indicate consumed bytes.
1213    buffer->setRange(buffer->offset() + offset, buffer->size() - offset);
1214
1215    status_t err = OK;
1216    for (size_t i = mPacketSources.size(); i-- > 0;) {
1217        sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
1218
1219        const char *key;
1220        ATSParser::SourceType type;
1221        const LiveSession::StreamType stream = mPacketSources.keyAt(i);
1222        switch (stream) {
1223            case LiveSession::STREAMTYPE_VIDEO:
1224                type = ATSParser::VIDEO;
1225                key = "timeUsVideo";
1226                break;
1227
1228            case LiveSession::STREAMTYPE_AUDIO:
1229                type = ATSParser::AUDIO;
1230                key = "timeUsAudio";
1231                break;
1232
1233            case LiveSession::STREAMTYPE_SUBTITLES:
1234            {
1235                ALOGE("MPEG2 Transport streams do not contain subtitles.");
1236                return ERROR_MALFORMED;
1237                break;
1238            }
1239
1240            default:
1241                TRESPASS();
1242        }
1243
1244        sp<AnotherPacketSource> source =
1245            static_cast<AnotherPacketSource *>(
1246                    mTSParser->getSource(type).get());
1247
1248        if (source == NULL) {
1249            continue;
1250        }
1251
1252        int64_t timeUs;
1253        sp<ABuffer> accessUnit;
1254        status_t finalResult;
1255        while (source->hasBufferAvailable(&finalResult)
1256                && source->dequeueAccessUnit(&accessUnit) == OK) {
1257
1258            CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
1259
1260            if (mStartup) {
1261                if (!mFirstPTSValid) {
1262                    mFirstTimeUs = timeUs;
1263                    mFirstPTSValid = true;
1264                }
1265                if (mStartTimeUsRelative) {
1266                    timeUs -= mFirstTimeUs;
1267                    if (timeUs < 0) {
1268                        timeUs = 0;
1269                    }
1270                }
1271
1272                if (timeUs < mStartTimeUs) {
1273                    // buffer up to the closest preceding IDR frame
1274                    ALOGV("timeUs %" PRId64 " us < mStartTimeUs %" PRId64 " us",
1275                            timeUs, mStartTimeUs);
1276                    const char *mime;
1277                    sp<MetaData> format  = source->getFormat();
1278                    bool isAvc = false;
1279                    if (format != NULL && format->findCString(kKeyMIMEType, &mime)
1280                            && !strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC)) {
1281                        isAvc = true;
1282                    }
1283                    if (isAvc && IsIDR(accessUnit)) {
1284                        mVideoBuffer->clear();
1285                    }
1286                    if (isAvc) {
1287                        mVideoBuffer->queueAccessUnit(accessUnit);
1288                    }
1289
1290                    continue;
1291                }
1292            }
1293
1294            CHECK(accessUnit->meta()->findInt64("timeUs", &timeUs));
1295            if (mStartTimeUsNotify != NULL && timeUs > mStartTimeUs) {
1296                int32_t firstSeqNumberInPlaylist;
1297                if (mPlaylist->meta() == NULL || !mPlaylist->meta()->findInt32(
1298                            "media-sequence", &firstSeqNumberInPlaylist)) {
1299                    firstSeqNumberInPlaylist = 0;
1300                }
1301
1302                int32_t targetDurationSecs;
1303                CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
1304                int64_t targetDurationUs = targetDurationSecs * 1000000ll;
1305                // mStartup
1306                //   mStartup is true until we have queued a packet for all the streams
1307                //   we are fetching. We queue packets whose timestamps are greater than
1308                //   mStartTimeUs.
1309                // mSegmentStartTimeUs >= 0
1310                //   mSegmentStartTimeUs is non-negative when adapting or switching tracks
1311                // mSeqNumber > firstSeqNumberInPlaylist
1312                //   don't decrement mSeqNumber if it already points to the 1st segment
1313                // timeUs - mStartTimeUs > targetDurationUs:
1314                //   This and the 2 above conditions should only happen when adapting in a live
1315                //   stream; the old fetcher has already fetched to mStartTimeUs; the new fetcher
1316                //   would start fetching after timeUs, which should be greater than mStartTimeUs;
1317                //   the old fetcher would then continue fetching data until timeUs. We don't want
1318                //   timeUs to be too far ahead of mStartTimeUs because we want the old fetcher to
1319                //   stop as early as possible. The definition of being "too far ahead" is
1320                //   arbitrary; here we use targetDurationUs as threshold.
1321                if (mStartup && mSegmentStartTimeUs >= 0
1322                        && mSeqNumber > firstSeqNumberInPlaylist
1323                        && timeUs - mStartTimeUs > targetDurationUs) {
1324                    // we just guessed a starting timestamp that is too high when adapting in a
1325                    // live stream; re-adjust based on the actual timestamp extracted from the
1326                    // media segment; if we didn't move backward after the re-adjustment
1327                    // (newSeqNumber), start at least 1 segment prior.
1328                    int32_t newSeqNumber = getSeqNumberWithAnchorTime(timeUs);
1329                    if (newSeqNumber >= mSeqNumber) {
1330                        --mSeqNumber;
1331                    } else {
1332                        mSeqNumber = newSeqNumber;
1333                    }
1334                    mStartTimeUsNotify = mNotify->dup();
1335                    mStartTimeUsNotify->setInt32("what", kWhatStartedAt);
1336                    return -EAGAIN;
1337                }
1338
1339                int32_t seq;
1340                if (!mStartTimeUsNotify->findInt32("discontinuitySeq", &seq)) {
1341                    mStartTimeUsNotify->setInt32("discontinuitySeq", mDiscontinuitySeq);
1342                }
1343                int64_t startTimeUs;
1344                if (!mStartTimeUsNotify->findInt64(key, &startTimeUs)) {
1345                    mStartTimeUsNotify->setInt64(key, timeUs);
1346
1347                    uint32_t streamMask = 0;
1348                    mStartTimeUsNotify->findInt32("streamMask", (int32_t *) &streamMask);
1349                    streamMask |= mPacketSources.keyAt(i);
1350                    mStartTimeUsNotify->setInt32("streamMask", streamMask);
1351
1352                    if (streamMask == mStreamTypeMask) {
1353                        mStartup = false;
1354                        mStartTimeUsNotify->post();
1355                        mStartTimeUsNotify.clear();
1356                    }
1357                }
1358            }
1359
1360            if (mStopParams != NULL) {
1361                // Queue discontinuity in original stream.
1362                int32_t discontinuitySeq;
1363                int64_t stopTimeUs;
1364                if (!mStopParams->findInt32("discontinuitySeq", &discontinuitySeq)
1365                        || discontinuitySeq > mDiscontinuitySeq
1366                        || !mStopParams->findInt64(key, &stopTimeUs)
1367                        || (discontinuitySeq == mDiscontinuitySeq
1368                                && timeUs >= stopTimeUs)) {
1369                    packetSource->queueAccessUnit(mSession->createFormatChangeBuffer());
1370                    mStreamTypeMask &= ~stream;
1371                    mPacketSources.removeItemsAt(i);
1372                    break;
1373                }
1374            }
1375
1376            // Note that we do NOT dequeue any discontinuities except for format change.
1377            if (stream == LiveSession::STREAMTYPE_VIDEO) {
1378                const bool discard = true;
1379                status_t status;
1380                while (mVideoBuffer->hasBufferAvailable(&status)) {
1381                    sp<ABuffer> videoBuffer;
1382                    mVideoBuffer->dequeueAccessUnit(&videoBuffer);
1383                    setAccessUnitProperties(videoBuffer, source, discard);
1384                    packetSource->queueAccessUnit(videoBuffer);
1385                }
1386            }
1387
1388            setAccessUnitProperties(accessUnit, source);
1389            packetSource->queueAccessUnit(accessUnit);
1390        }
1391
1392        if (err != OK) {
1393            break;
1394        }
1395    }
1396
1397    if (err != OK) {
1398        for (size_t i = mPacketSources.size(); i-- > 0;) {
1399            sp<AnotherPacketSource> packetSource = mPacketSources.valueAt(i);
1400            packetSource->clear();
1401        }
1402        return err;
1403    }
1404
1405    if (!mStreamTypeMask) {
1406        // Signal gap is filled between original and new stream.
1407        ALOGV("ERROR OUT OF RANGE");
1408        return ERROR_OUT_OF_RANGE;
1409    }
1410
1411    return OK;
1412}
1413
1414/* static */
1415bool PlaylistFetcher::bufferStartsWithWebVTTMagicSequence(
1416        const sp<ABuffer> &buffer) {
1417    size_t pos = 0;
1418
1419    // skip possible BOM
1420    if (buffer->size() >= pos + 3 &&
1421            !memcmp("\xef\xbb\xbf", buffer->data() + pos, 3)) {
1422        pos += 3;
1423    }
1424
1425    // accept WEBVTT followed by SPACE, TAB or (CR) LF
1426    if (buffer->size() < pos + 6 ||
1427            memcmp("WEBVTT", buffer->data() + pos, 6)) {
1428        return false;
1429    }
1430    pos += 6;
1431
1432    if (buffer->size() == pos) {
1433        return true;
1434    }
1435
1436    uint8_t sep = buffer->data()[pos];
1437    return sep == ' ' || sep == '\t' || sep == '\n' || sep == '\r';
1438}
1439
1440status_t PlaylistFetcher::extractAndQueueAccessUnits(
1441        const sp<ABuffer> &buffer, const sp<AMessage> &itemMeta) {
1442    if (bufferStartsWithWebVTTMagicSequence(buffer)) {
1443        if (mStreamTypeMask != LiveSession::STREAMTYPE_SUBTITLES) {
1444            ALOGE("This stream only contains subtitles.");
1445            return ERROR_MALFORMED;
1446        }
1447
1448        const sp<AnotherPacketSource> packetSource =
1449            mPacketSources.valueFor(LiveSession::STREAMTYPE_SUBTITLES);
1450
1451        int64_t durationUs;
1452        CHECK(itemMeta->findInt64("durationUs", &durationUs));
1453        buffer->meta()->setInt64("timeUs", getSegmentStartTimeUs(mSeqNumber));
1454        buffer->meta()->setInt64("durationUs", durationUs);
1455        buffer->meta()->setInt64("segmentStartTimeUs", getSegmentStartTimeUs(mSeqNumber));
1456        buffer->meta()->setInt32("discontinuitySeq", mDiscontinuitySeq);
1457        buffer->meta()->setInt32("subtitleGeneration", mSubtitleGeneration);
1458
1459        packetSource->queueAccessUnit(buffer);
1460        return OK;
1461    }
1462
1463    if (mNextPTSTimeUs >= 0ll) {
1464        mFirstPTSValid = false;
1465        mAbsoluteTimeAnchorUs = mNextPTSTimeUs;
1466        mNextPTSTimeUs = -1ll;
1467    }
1468
1469    // This better be an ISO 13818-7 (AAC) or ISO 13818-1 (MPEG) audio
1470    // stream prefixed by an ID3 tag.
1471
1472    bool firstID3Tag = true;
1473    uint64_t PTS = 0;
1474
1475    for (;;) {
1476        // Make sure to skip all ID3 tags preceding the audio data.
1477        // At least one must be present to provide the PTS timestamp.
1478
1479        ID3 id3(buffer->data(), buffer->size(), true /* ignoreV1 */);
1480        if (!id3.isValid()) {
1481            if (firstID3Tag) {
1482                ALOGE("Unable to parse ID3 tag.");
1483                return ERROR_MALFORMED;
1484            } else {
1485                break;
1486            }
1487        }
1488
1489        if (firstID3Tag) {
1490            bool found = false;
1491
1492            ID3::Iterator it(id3, "PRIV");
1493            while (!it.done()) {
1494                size_t length;
1495                const uint8_t *data = it.getData(&length);
1496
1497                static const char *kMatchName =
1498                    "com.apple.streaming.transportStreamTimestamp";
1499                static const size_t kMatchNameLen = strlen(kMatchName);
1500
1501                if (length == kMatchNameLen + 1 + 8
1502                        && !strncmp((const char *)data, kMatchName, kMatchNameLen)) {
1503                    found = true;
1504                    PTS = U64_AT(&data[kMatchNameLen + 1]);
1505                }
1506
1507                it.next();
1508            }
1509
1510            if (!found) {
1511                ALOGE("Unable to extract transportStreamTimestamp from ID3 tag.");
1512                return ERROR_MALFORMED;
1513            }
1514        }
1515
1516        // skip the ID3 tag
1517        buffer->setRange(
1518                buffer->offset() + id3.rawSize(), buffer->size() - id3.rawSize());
1519
1520        firstID3Tag = false;
1521    }
1522
1523    if (mStreamTypeMask != LiveSession::STREAMTYPE_AUDIO) {
1524        ALOGW("This stream only contains audio data!");
1525
1526        mStreamTypeMask &= LiveSession::STREAMTYPE_AUDIO;
1527
1528        if (mStreamTypeMask == 0) {
1529            return OK;
1530        }
1531    }
1532
1533    sp<AnotherPacketSource> packetSource =
1534        mPacketSources.valueFor(LiveSession::STREAMTYPE_AUDIO);
1535
1536    if (packetSource->getFormat() == NULL && buffer->size() >= 7) {
1537        ABitReader bits(buffer->data(), buffer->size());
1538
1539        // adts_fixed_header
1540
1541        CHECK_EQ(bits.getBits(12), 0xfffu);
1542        bits.skipBits(3);  // ID, layer
1543        bool protection_absent = bits.getBits(1) != 0;
1544
1545        unsigned profile = bits.getBits(2);
1546        CHECK_NE(profile, 3u);
1547        unsigned sampling_freq_index = bits.getBits(4);
1548        bits.getBits(1);  // private_bit
1549        unsigned channel_configuration = bits.getBits(3);
1550        CHECK_NE(channel_configuration, 0u);
1551        bits.skipBits(2);  // original_copy, home
1552
1553        sp<MetaData> meta = MakeAACCodecSpecificData(
1554                profile, sampling_freq_index, channel_configuration);
1555
1556        meta->setInt32(kKeyIsADTS, true);
1557
1558        packetSource->setFormat(meta);
1559    }
1560
1561    int64_t numSamples = 0ll;
1562    int32_t sampleRate;
1563    CHECK(packetSource->getFormat()->findInt32(kKeySampleRate, &sampleRate));
1564
1565    int64_t timeUs = (PTS * 100ll) / 9ll;
1566    if (!mFirstPTSValid) {
1567        mFirstPTSValid = true;
1568        mFirstTimeUs = timeUs;
1569    }
1570
1571    size_t offset = 0;
1572    while (offset < buffer->size()) {
1573        const uint8_t *adtsHeader = buffer->data() + offset;
1574        CHECK_LT(offset + 5, buffer->size());
1575
1576        unsigned aac_frame_length =
1577            ((adtsHeader[3] & 3) << 11)
1578            | (adtsHeader[4] << 3)
1579            | (adtsHeader[5] >> 5);
1580
1581        if (aac_frame_length == 0) {
1582            const uint8_t *id3Header = adtsHeader;
1583            if (!memcmp(id3Header, "ID3", 3)) {
1584                ID3 id3(id3Header, buffer->size() - offset, true);
1585                if (id3.isValid()) {
1586                    offset += id3.rawSize();
1587                    continue;
1588                };
1589            }
1590            return ERROR_MALFORMED;
1591        }
1592
1593        CHECK_LE(offset + aac_frame_length, buffer->size());
1594
1595        int64_t unitTimeUs = timeUs + numSamples * 1000000ll / sampleRate;
1596        offset += aac_frame_length;
1597
1598        // Each AAC frame encodes 1024 samples.
1599        numSamples += 1024;
1600
1601        if (mStartup) {
1602            int64_t startTimeUs = unitTimeUs;
1603            if (mStartTimeUsRelative) {
1604                startTimeUs -= mFirstTimeUs;
1605                if (startTimeUs  < 0) {
1606                    startTimeUs = 0;
1607                }
1608            }
1609            if (startTimeUs < mStartTimeUs) {
1610                continue;
1611            }
1612
1613            if (mStartTimeUsNotify != NULL) {
1614                int32_t targetDurationSecs;
1615                CHECK(mPlaylist->meta()->findInt32("target-duration", &targetDurationSecs));
1616                int64_t targetDurationUs = targetDurationSecs * 1000000ll;
1617
1618                // Duplicated logic from how we handle .ts playlists.
1619                if (mStartup && mSegmentStartTimeUs >= 0
1620                        && timeUs - mStartTimeUs > targetDurationUs) {
1621                    int32_t newSeqNumber = getSeqNumberWithAnchorTime(timeUs);
1622                    if (newSeqNumber >= mSeqNumber) {
1623                        --mSeqNumber;
1624                    } else {
1625                        mSeqNumber = newSeqNumber;
1626                    }
1627                    return -EAGAIN;
1628                }
1629
1630                mStartTimeUsNotify->setInt64("timeUsAudio", timeUs);
1631                mStartTimeUsNotify->setInt32("discontinuitySeq", mDiscontinuitySeq);
1632                mStartTimeUsNotify->setInt32("streamMask", LiveSession::STREAMTYPE_AUDIO);
1633                mStartTimeUsNotify->post();
1634                mStartTimeUsNotify.clear();
1635                mStartup = false;
1636            }
1637        }
1638
1639        if (mStopParams != NULL) {
1640            // Queue discontinuity in original stream.
1641            int32_t discontinuitySeq;
1642            int64_t stopTimeUs;
1643            if (!mStopParams->findInt32("discontinuitySeq", &discontinuitySeq)
1644                    || discontinuitySeq > mDiscontinuitySeq
1645                    || !mStopParams->findInt64("timeUsAudio", &stopTimeUs)
1646                    || (discontinuitySeq == mDiscontinuitySeq && unitTimeUs >= stopTimeUs)) {
1647                packetSource->queueAccessUnit(mSession->createFormatChangeBuffer());
1648                mStreamTypeMask = 0;
1649                mPacketSources.clear();
1650                return ERROR_OUT_OF_RANGE;
1651            }
1652        }
1653
1654        sp<ABuffer> unit = new ABuffer(aac_frame_length);
1655        memcpy(unit->data(), adtsHeader, aac_frame_length);
1656
1657        unit->meta()->setInt64("timeUs", unitTimeUs);
1658        setAccessUnitProperties(unit, packetSource);
1659        packetSource->queueAccessUnit(unit);
1660    }
1661
1662    return OK;
1663}
1664
1665void PlaylistFetcher::updateDuration() {
1666    int64_t durationUs = 0ll;
1667    for (size_t index = 0; index < mPlaylist->size(); ++index) {
1668        sp<AMessage> itemMeta;
1669        CHECK(mPlaylist->itemAt(
1670                    index, NULL /* uri */, &itemMeta));
1671
1672        int64_t itemDurationUs;
1673        CHECK(itemMeta->findInt64("durationUs", &itemDurationUs));
1674
1675        durationUs += itemDurationUs;
1676    }
1677
1678    sp<AMessage> msg = mNotify->dup();
1679    msg->setInt32("what", kWhatDurationUpdate);
1680    msg->setInt64("durationUs", durationUs);
1681    msg->post();
1682}
1683
1684int64_t PlaylistFetcher::resumeThreshold(const sp<AMessage> &msg) {
1685    int64_t durationUs, threshold;
1686    if (msg->findInt64("durationUs", &durationUs) && durationUs > 0) {
1687        return kNumSkipFrames * durationUs;
1688    }
1689
1690    sp<RefBase> obj;
1691    msg->findObject("format", &obj);
1692    MetaData *format = static_cast<MetaData *>(obj.get());
1693
1694    const char *mime;
1695    CHECK(format->findCString(kKeyMIMEType, &mime));
1696    bool audio = !strncasecmp(mime, "audio/", 6);
1697    if (audio) {
1698        // Assumes 1000 samples per frame.
1699        int32_t sampleRate;
1700        CHECK(format->findInt32(kKeySampleRate, &sampleRate));
1701        return kNumSkipFrames  /* frames */ * 1000 /* samples */
1702                * (1000000 / sampleRate) /* sample duration (us) */;
1703    } else {
1704        int32_t frameRate;
1705        if (format->findInt32(kKeyFrameRate, &frameRate) && frameRate > 0) {
1706            return kNumSkipFrames * (1000000 / frameRate);
1707        }
1708    }
1709
1710    return 500000ll;
1711}
1712
1713}  // namespace android
1714