NuCachedSource2.cpp revision 20574aa637780b76984e5e5d60d5e0068cda283f
1/*
2 * Copyright (C) 2010 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#include <inttypes.h>
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "NuCachedSource2"
21#include <utils/Log.h>
22
23#include "include/NuCachedSource2.h"
24#include "include/HTTPBase.h"
25
26#include <cutils/properties.h>
27#include <media/stagefright/foundation/ADebug.h>
28#include <media/stagefright/foundation/AMessage.h>
29#include <media/stagefright/MediaErrors.h>
30
31namespace android {
32
33struct PageCache {
34    PageCache(size_t pageSize);
35    ~PageCache();
36
37    struct Page {
38        void *mData;
39        size_t mSize;
40    };
41
42    Page *acquirePage();
43    void releasePage(Page *page);
44
45    void appendPage(Page *page);
46    size_t releaseFromStart(size_t maxBytes);
47
48    size_t totalSize() const {
49        return mTotalSize;
50    }
51
52    void copy(size_t from, void *data, size_t size);
53
54private:
55    size_t mPageSize;
56    size_t mTotalSize;
57
58    List<Page *> mActivePages;
59    List<Page *> mFreePages;
60
61    void freePages(List<Page *> *list);
62
63    DISALLOW_EVIL_CONSTRUCTORS(PageCache);
64};
65
66PageCache::PageCache(size_t pageSize)
67    : mPageSize(pageSize),
68      mTotalSize(0) {
69}
70
71PageCache::~PageCache() {
72    freePages(&mActivePages);
73    freePages(&mFreePages);
74}
75
76void PageCache::freePages(List<Page *> *list) {
77    List<Page *>::iterator it = list->begin();
78    while (it != list->end()) {
79        Page *page = *it;
80
81        free(page->mData);
82        delete page;
83        page = NULL;
84
85        ++it;
86    }
87}
88
89PageCache::Page *PageCache::acquirePage() {
90    if (!mFreePages.empty()) {
91        List<Page *>::iterator it = mFreePages.begin();
92        Page *page = *it;
93        mFreePages.erase(it);
94
95        return page;
96    }
97
98    Page *page = new Page;
99    page->mData = malloc(mPageSize);
100    page->mSize = 0;
101
102    return page;
103}
104
105void PageCache::releasePage(Page *page) {
106    page->mSize = 0;
107    mFreePages.push_back(page);
108}
109
110void PageCache::appendPage(Page *page) {
111    mTotalSize += page->mSize;
112    mActivePages.push_back(page);
113}
114
115size_t PageCache::releaseFromStart(size_t maxBytes) {
116    size_t bytesReleased = 0;
117
118    while (maxBytes > 0 && !mActivePages.empty()) {
119        List<Page *>::iterator it = mActivePages.begin();
120
121        Page *page = *it;
122
123        if (maxBytes < page->mSize) {
124            break;
125        }
126
127        mActivePages.erase(it);
128
129        maxBytes -= page->mSize;
130        bytesReleased += page->mSize;
131
132        releasePage(page);
133    }
134
135    mTotalSize -= bytesReleased;
136    return bytesReleased;
137}
138
139void PageCache::copy(size_t from, void *data, size_t size) {
140    ALOGV("copy from %zu size %zu", from, size);
141
142    if (size == 0) {
143        return;
144    }
145
146    CHECK_LE(from + size, mTotalSize);
147
148    size_t offset = 0;
149    List<Page *>::iterator it = mActivePages.begin();
150    while (from >= offset + (*it)->mSize) {
151        offset += (*it)->mSize;
152        ++it;
153    }
154
155    size_t delta = from - offset;
156    size_t avail = (*it)->mSize - delta;
157
158    if (avail >= size) {
159        memcpy(data, (const uint8_t *)(*it)->mData + delta, size);
160        return;
161    }
162
163    memcpy(data, (const uint8_t *)(*it)->mData + delta, avail);
164    ++it;
165    data = (uint8_t *)data + avail;
166    size -= avail;
167
168    while (size > 0) {
169        size_t copy = (*it)->mSize;
170        if (copy > size) {
171            copy = size;
172        }
173        memcpy(data, (*it)->mData, copy);
174        data = (uint8_t *)data + copy;
175        size -= copy;
176        ++it;
177    }
178}
179
180////////////////////////////////////////////////////////////////////////////////
181
182NuCachedSource2::NuCachedSource2(
183        const sp<DataSource> &source,
184        const char *cacheConfig,
185        bool disconnectAtHighwatermark)
186    : mSource(source),
187      mReflector(new AHandlerReflector<NuCachedSource2>(this)),
188      mLooper(new ALooper),
189      mCache(new PageCache(kPageSize)),
190      mCacheOffset(0),
191      mFinalStatus(OK),
192      mLastAccessPos(0),
193      mFetching(true),
194      mDisconnecting(false),
195      mLastFetchTimeUs(-1),
196      mNumRetriesLeft(kMaxNumRetries),
197      mHighwaterThresholdBytes(kDefaultHighWaterThreshold),
198      mLowwaterThresholdBytes(kDefaultLowWaterThreshold),
199      mKeepAliveIntervalUs(kDefaultKeepAliveIntervalUs),
200      mDisconnectAtHighwatermark(disconnectAtHighwatermark) {
201    // We are NOT going to support disconnect-at-highwatermark indefinitely
202    // and we are not guaranteeing support for client-specified cache
203    // parameters. Both of these are temporary measures to solve a specific
204    // problem that will be solved in a better way going forward.
205
206    updateCacheParamsFromSystemProperty();
207
208    if (cacheConfig != NULL) {
209        updateCacheParamsFromString(cacheConfig);
210    }
211
212    if (mDisconnectAtHighwatermark) {
213        // Makes no sense to disconnect and do keep-alives...
214        mKeepAliveIntervalUs = 0;
215    }
216
217    mLooper->setName("NuCachedSource2");
218    mLooper->registerHandler(mReflector);
219
220    // Since it may not be obvious why our looper thread needs to be
221    // able to call into java since it doesn't appear to do so at all...
222    // IMediaHTTPConnection may be (and most likely is) implemented in JAVA
223    // and a local JAVA IBinder will call directly into JNI methods.
224    // So whenever we call DataSource::readAt it may end up in a call to
225    // IMediaHTTPConnection::readAt and therefore call back into JAVA.
226    mLooper->start(false /* runOnCallingThread */, true /* canCallJava */);
227
228    Mutex::Autolock autoLock(mLock);
229    (new AMessage(kWhatFetchMore, mReflector->id()))->post();
230}
231
232NuCachedSource2::~NuCachedSource2() {
233    mLooper->stop();
234    mLooper->unregisterHandler(mReflector->id());
235
236    delete mCache;
237    mCache = NULL;
238}
239
240status_t NuCachedSource2::getEstimatedBandwidthKbps(int32_t *kbps) {
241    if (mSource->flags() & kIsHTTPBasedSource) {
242        HTTPBase* source = static_cast<HTTPBase *>(mSource.get());
243        return source->getEstimatedBandwidthKbps(kbps);
244    }
245    return ERROR_UNSUPPORTED;
246}
247
248void NuCachedSource2::disconnect() {
249    if (mSource->flags() & kIsHTTPBasedSource) {
250        ALOGV("disconnecting HTTPBasedSource");
251
252        {
253            Mutex::Autolock autoLock(mLock);
254            // set mDisconnecting to true, if a fetch returns after
255            // this, the source will be marked as EOS.
256            mDisconnecting = true;
257
258            // explicitly signal mCondition so that the pending readAt()
259            // will immediately return
260            mCondition.signal();
261        }
262
263        // explicitly disconnect from the source, to allow any
264        // pending reads to return more promptly
265        static_cast<HTTPBase *>(mSource.get())->disconnect();
266    }
267}
268
269status_t NuCachedSource2::setCacheStatCollectFreq(int32_t freqMs) {
270    if (mSource->flags() & kIsHTTPBasedSource) {
271        HTTPBase *source = static_cast<HTTPBase *>(mSource.get());
272        return source->setBandwidthStatCollectFreq(freqMs);
273    }
274    return ERROR_UNSUPPORTED;
275}
276
277status_t NuCachedSource2::initCheck() const {
278    return mSource->initCheck();
279}
280
281status_t NuCachedSource2::getSize(off64_t *size) {
282    return mSource->getSize(size);
283}
284
285uint32_t NuCachedSource2::flags() {
286    // Remove HTTP related flags since NuCachedSource2 is not HTTP-based.
287    uint32_t flags = mSource->flags() & ~(kWantsPrefetching | kIsHTTPBasedSource);
288    return (flags | kIsCachingDataSource);
289}
290
291void NuCachedSource2::onMessageReceived(const sp<AMessage> &msg) {
292    switch (msg->what()) {
293        case kWhatFetchMore:
294        {
295            onFetch();
296            break;
297        }
298
299        case kWhatRead:
300        {
301            onRead(msg);
302            break;
303        }
304
305        default:
306            TRESPASS();
307    }
308}
309
310void NuCachedSource2::fetchInternal() {
311    ALOGV("fetchInternal");
312
313    bool reconnect = false;
314
315    {
316        Mutex::Autolock autoLock(mLock);
317        CHECK(mFinalStatus == OK || mNumRetriesLeft > 0);
318
319        if (mFinalStatus != OK) {
320            --mNumRetriesLeft;
321
322            reconnect = true;
323        }
324    }
325
326    if (reconnect) {
327        status_t err =
328            mSource->reconnectAtOffset(mCacheOffset + mCache->totalSize());
329
330        Mutex::Autolock autoLock(mLock);
331
332        if (mDisconnecting) {
333            mNumRetriesLeft = 0;
334            mFinalStatus = ERROR_END_OF_STREAM;
335            return;
336        } else if (err == ERROR_UNSUPPORTED || err == -EPIPE) {
337            // These are errors that are not likely to go away even if we
338            // retry, i.e. the server doesn't support range requests or similar.
339            mNumRetriesLeft = 0;
340            return;
341        } else if (err != OK) {
342            ALOGI("The attempt to reconnect failed, %d retries remaining",
343                 mNumRetriesLeft);
344
345            return;
346        }
347    }
348
349    PageCache::Page *page = mCache->acquirePage();
350
351    ssize_t n = mSource->readAt(
352            mCacheOffset + mCache->totalSize(), page->mData, kPageSize);
353
354    Mutex::Autolock autoLock(mLock);
355
356    if (n == 0 || mDisconnecting) {
357        ALOGI("ERROR_END_OF_STREAM");
358
359        mNumRetriesLeft = 0;
360        mFinalStatus = ERROR_END_OF_STREAM;
361
362        mCache->releasePage(page);
363    } else if (n < 0) {
364        mFinalStatus = n;
365        if (n == ERROR_UNSUPPORTED || n == -EPIPE) {
366            // These are errors that are not likely to go away even if we
367            // retry, i.e. the server doesn't support range requests or similar.
368            mNumRetriesLeft = 0;
369        }
370
371        ALOGE("source returned error %zd, %d retries left", n, mNumRetriesLeft);
372        mCache->releasePage(page);
373    } else {
374        if (mFinalStatus != OK) {
375            ALOGI("retrying a previously failed read succeeded.");
376        }
377        mNumRetriesLeft = kMaxNumRetries;
378        mFinalStatus = OK;
379
380        page->mSize = n;
381        mCache->appendPage(page);
382    }
383}
384
385void NuCachedSource2::onFetch() {
386    ALOGV("onFetch");
387
388    if (mFinalStatus != OK && mNumRetriesLeft == 0) {
389        ALOGV("EOS reached, done prefetching for now");
390        mFetching = false;
391    }
392
393    bool keepAlive =
394        !mFetching
395            && mFinalStatus == OK
396            && mKeepAliveIntervalUs > 0
397            && ALooper::GetNowUs() >= mLastFetchTimeUs + mKeepAliveIntervalUs;
398
399    if (mFetching || keepAlive) {
400        if (keepAlive) {
401            ALOGI("Keep alive");
402        }
403
404        fetchInternal();
405
406        mLastFetchTimeUs = ALooper::GetNowUs();
407
408        if (mFetching && mCache->totalSize() >= mHighwaterThresholdBytes) {
409            ALOGI("Cache full, done prefetching for now");
410            mFetching = false;
411
412            if (mDisconnectAtHighwatermark
413                    && (mSource->flags() & DataSource::kIsHTTPBasedSource)) {
414                ALOGV("Disconnecting at high watermark");
415                static_cast<HTTPBase *>(mSource.get())->disconnect();
416                mFinalStatus = -EAGAIN;
417            }
418        }
419    } else {
420        Mutex::Autolock autoLock(mLock);
421        restartPrefetcherIfNecessary_l();
422    }
423
424    int64_t delayUs;
425    if (mFetching) {
426        if (mFinalStatus != OK && mNumRetriesLeft > 0) {
427            // We failed this time and will try again in 3 seconds.
428            delayUs = 3000000ll;
429        } else {
430            delayUs = 0;
431        }
432    } else {
433        delayUs = 100000ll;
434    }
435
436    (new AMessage(kWhatFetchMore, mReflector->id()))->post(delayUs);
437}
438
439void NuCachedSource2::onRead(const sp<AMessage> &msg) {
440    ALOGV("onRead");
441
442    int64_t offset;
443    CHECK(msg->findInt64("offset", &offset));
444
445    void *data;
446    CHECK(msg->findPointer("data", &data));
447
448    size_t size;
449    CHECK(msg->findSize("size", &size));
450
451    ssize_t result = readInternal(offset, data, size);
452
453    if (result == -EAGAIN) {
454        msg->post(50000);
455        return;
456    }
457
458    Mutex::Autolock autoLock(mLock);
459
460    CHECK(mAsyncResult == NULL);
461
462    mAsyncResult = new AMessage;
463    mAsyncResult->setInt32("result", result);
464
465    mCondition.signal();
466}
467
468void NuCachedSource2::restartPrefetcherIfNecessary_l(
469        bool ignoreLowWaterThreshold, bool force) {
470    static const size_t kGrayArea = 1024 * 1024;
471
472    if (mFetching || (mFinalStatus != OK && mNumRetriesLeft == 0)) {
473        return;
474    }
475
476    if (!ignoreLowWaterThreshold && !force
477            && mCacheOffset + mCache->totalSize() - mLastAccessPos
478                >= mLowwaterThresholdBytes) {
479        return;
480    }
481
482    size_t maxBytes = mLastAccessPos - mCacheOffset;
483
484    if (!force) {
485        if (maxBytes < kGrayArea) {
486            return;
487        }
488
489        maxBytes -= kGrayArea;
490    }
491
492    size_t actualBytes = mCache->releaseFromStart(maxBytes);
493    mCacheOffset += actualBytes;
494
495    ALOGI("restarting prefetcher, totalSize = %zu", mCache->totalSize());
496    mFetching = true;
497}
498
499ssize_t NuCachedSource2::readAt(off64_t offset, void *data, size_t size) {
500    Mutex::Autolock autoSerializer(mSerializer);
501
502    ALOGV("readAt offset %lld, size %zu", offset, size);
503
504    Mutex::Autolock autoLock(mLock);
505
506    // If the request can be completely satisfied from the cache, do so.
507
508    if (offset >= mCacheOffset
509            && offset + size <= mCacheOffset + mCache->totalSize()) {
510        size_t delta = offset - mCacheOffset;
511        mCache->copy(delta, data, size);
512
513        mLastAccessPos = offset + size;
514
515        return size;
516    }
517
518    sp<AMessage> msg = new AMessage(kWhatRead, mReflector->id());
519    msg->setInt64("offset", offset);
520    msg->setPointer("data", data);
521    msg->setSize("size", size);
522
523    CHECK(mAsyncResult == NULL);
524    msg->post();
525
526    while (mAsyncResult == NULL && !mDisconnecting) {
527        mCondition.wait(mLock);
528    }
529
530    if (mDisconnecting) {
531        return ERROR_END_OF_STREAM;
532    }
533
534    int32_t result;
535    CHECK(mAsyncResult->findInt32("result", &result));
536
537    mAsyncResult.clear();
538
539    if (result > 0) {
540        mLastAccessPos = offset + result;
541    }
542
543    return (ssize_t)result;
544}
545
546size_t NuCachedSource2::cachedSize() {
547    Mutex::Autolock autoLock(mLock);
548    return mCacheOffset + mCache->totalSize();
549}
550
551size_t NuCachedSource2::approxDataRemaining(status_t *finalStatus) const {
552    Mutex::Autolock autoLock(mLock);
553    return approxDataRemaining_l(finalStatus);
554}
555
556size_t NuCachedSource2::approxDataRemaining_l(status_t *finalStatus) const {
557    *finalStatus = mFinalStatus;
558
559    if (mFinalStatus != OK && mNumRetriesLeft > 0) {
560        // Pretend that everything is fine until we're out of retries.
561        *finalStatus = OK;
562    }
563
564    off64_t lastBytePosCached = mCacheOffset + mCache->totalSize();
565    if (mLastAccessPos < lastBytePosCached) {
566        return lastBytePosCached - mLastAccessPos;
567    }
568    return 0;
569}
570
571ssize_t NuCachedSource2::readInternal(off64_t offset, void *data, size_t size) {
572    CHECK_LE(size, (size_t)mHighwaterThresholdBytes);
573
574    ALOGV("readInternal offset %lld size %zu", offset, size);
575
576    Mutex::Autolock autoLock(mLock);
577
578    if (!mFetching) {
579        mLastAccessPos = offset;
580        restartPrefetcherIfNecessary_l(
581                false, // ignoreLowWaterThreshold
582                true); // force
583    }
584
585    if (offset < mCacheOffset
586            || offset >= (off64_t)(mCacheOffset + mCache->totalSize())) {
587        static const off64_t kPadding = 256 * 1024;
588
589        // In the presence of multiple decoded streams, once of them will
590        // trigger this seek request, the other one will request data "nearby"
591        // soon, adjust the seek position so that that subsequent request
592        // does not trigger another seek.
593        off64_t seekOffset = (offset > kPadding) ? offset - kPadding : 0;
594
595        seekInternal_l(seekOffset);
596    }
597
598    size_t delta = offset - mCacheOffset;
599
600    if (mFinalStatus != OK && mNumRetriesLeft == 0) {
601        if (delta >= mCache->totalSize()) {
602            return mFinalStatus;
603        }
604
605        size_t avail = mCache->totalSize() - delta;
606
607        if (avail > size) {
608            avail = size;
609        }
610
611        mCache->copy(delta, data, avail);
612
613        return avail;
614    }
615
616    if (offset + size <= mCacheOffset + mCache->totalSize()) {
617        mCache->copy(delta, data, size);
618
619        return size;
620    }
621
622    ALOGV("deferring read");
623
624    return -EAGAIN;
625}
626
627status_t NuCachedSource2::seekInternal_l(off64_t offset) {
628    mLastAccessPos = offset;
629
630    if (offset >= mCacheOffset
631            && offset <= (off64_t)(mCacheOffset + mCache->totalSize())) {
632        return OK;
633    }
634
635    ALOGI("new range: offset= %lld", offset);
636
637    mCacheOffset = offset;
638
639    size_t totalSize = mCache->totalSize();
640    CHECK_EQ(mCache->releaseFromStart(totalSize), totalSize);
641
642    mNumRetriesLeft = kMaxNumRetries;
643    mFetching = true;
644
645    return OK;
646}
647
648void NuCachedSource2::resumeFetchingIfNecessary() {
649    Mutex::Autolock autoLock(mLock);
650
651    restartPrefetcherIfNecessary_l(true /* ignore low water threshold */);
652}
653
654sp<DecryptHandle> NuCachedSource2::DrmInitialization(const char* mime) {
655    return mSource->DrmInitialization(mime);
656}
657
658void NuCachedSource2::getDrmInfo(sp<DecryptHandle> &handle, DrmManagerClient **client) {
659    mSource->getDrmInfo(handle, client);
660}
661
662String8 NuCachedSource2::getUri() {
663    return mSource->getUri();
664}
665
666String8 NuCachedSource2::getMIMEType() const {
667    return mSource->getMIMEType();
668}
669
670void NuCachedSource2::updateCacheParamsFromSystemProperty() {
671    char value[PROPERTY_VALUE_MAX];
672    if (!property_get("media.stagefright.cache-params", value, NULL)) {
673        return;
674    }
675
676    updateCacheParamsFromString(value);
677}
678
679void NuCachedSource2::updateCacheParamsFromString(const char *s) {
680    ssize_t lowwaterMarkKb, highwaterMarkKb;
681    int keepAliveSecs;
682
683    if (sscanf(s, "%zd/%zd/%d",
684               &lowwaterMarkKb, &highwaterMarkKb, &keepAliveSecs) != 3) {
685        ALOGE("Failed to parse cache parameters from '%s'.", s);
686        return;
687    }
688
689    if (lowwaterMarkKb >= 0) {
690        mLowwaterThresholdBytes = lowwaterMarkKb * 1024;
691    } else {
692        mLowwaterThresholdBytes = kDefaultLowWaterThreshold;
693    }
694
695    if (highwaterMarkKb >= 0) {
696        mHighwaterThresholdBytes = highwaterMarkKb * 1024;
697    } else {
698        mHighwaterThresholdBytes = kDefaultHighWaterThreshold;
699    }
700
701    if (mLowwaterThresholdBytes >= mHighwaterThresholdBytes) {
702        ALOGE("Illegal low/highwater marks specified, reverting to defaults.");
703
704        mLowwaterThresholdBytes = kDefaultLowWaterThreshold;
705        mHighwaterThresholdBytes = kDefaultHighWaterThreshold;
706    }
707
708    if (keepAliveSecs >= 0) {
709        mKeepAliveIntervalUs = keepAliveSecs * 1000000ll;
710    } else {
711        mKeepAliveIntervalUs = kDefaultKeepAliveIntervalUs;
712    }
713
714    ALOGV("lowwater = %zu bytes, highwater = %zu bytes, keepalive = %" PRId64 " us",
715         mLowwaterThresholdBytes,
716         mHighwaterThresholdBytes,
717         mKeepAliveIntervalUs);
718}
719
720// static
721void NuCachedSource2::RemoveCacheSpecificHeaders(
722        KeyedVector<String8, String8> *headers,
723        String8 *cacheConfig,
724        bool *disconnectAtHighwatermark) {
725    *cacheConfig = String8();
726    *disconnectAtHighwatermark = false;
727
728    if (headers == NULL) {
729        return;
730    }
731
732    ssize_t index;
733    if ((index = headers->indexOfKey(String8("x-cache-config"))) >= 0) {
734        *cacheConfig = headers->valueAt(index);
735
736        headers->removeItemsAt(index);
737
738        ALOGV("Using special cache config '%s'", cacheConfig->string());
739    }
740
741    if ((index = headers->indexOfKey(
742                    String8("x-disconnect-at-highwatermark"))) >= 0) {
743        *disconnectAtHighwatermark = true;
744        headers->removeItemsAt(index);
745
746        ALOGV("Client requested disconnection at highwater mark");
747    }
748}
749
750}  // namespace android
751