Merge "NuPlayer2: support end position of data source"
diff --git a/media/extractors/ogg/OggExtractor.cpp b/media/extractors/ogg/OggExtractor.cpp
index 1b4fe27..2ae9b5a 100644
--- a/media/extractors/ogg/OggExtractor.cpp
+++ b/media/extractors/ogg/OggExtractor.cpp
@@ -84,7 +84,7 @@
 
     status_t seekToTime(int64_t timeUs);
     status_t seekToOffset(off64_t offset);
-    virtual status_t readNextPacket(MediaBufferBase **buffer) = 0;
+    virtual media_status_t readNextPacket(MediaBufferBase **buffer) = 0;
 
     status_t init();
 
@@ -145,7 +145,7 @@
     // 1 - bitstream identification header
     // 3 - comment header
     // 5 - codec setup header (Vorbis only)
-    virtual status_t verifyHeader(MediaBufferBase *buffer, uint8_t type) = 0;
+    virtual media_status_t verifyHeader(MediaBufferBase *buffer, uint8_t type) = 0;
 
     // Read the next ogg packet from the underlying data source; optionally
     // calculate the timestamp for the output packet whilst pretending
@@ -153,7 +153,7 @@
     //
     // *buffer is NULL'ed out immediately upon entry, and if successful a new buffer is allocated;
     // clients are responsible for releasing the original buffer.
-    status_t _readNextPacket(MediaBufferBase **buffer, bool calcVorbisTimestamp);
+    media_status_t _readNextPacket(MediaBufferBase **buffer, bool calcVorbisTimestamp);
 
     int32_t getPacketBlockSize(MediaBufferBase *buffer);
 
@@ -177,7 +177,7 @@
 
     virtual uint64_t approxBitrate() const;
 
-    virtual status_t readNextPacket(MediaBufferBase **buffer) {
+    virtual media_status_t readNextPacket(MediaBufferBase **buffer) {
         return _readNextPacket(buffer, /* calcVorbisTimestamp = */ true);
     }
 
@@ -189,7 +189,7 @@
         return granulePos * 1000000ll / mVi.rate;
     }
 
-    virtual status_t verifyHeader(MediaBufferBase *buffer, uint8_t type);
+    virtual media_status_t verifyHeader(MediaBufferBase *buffer, uint8_t type);
 };
 
 struct MyOpusExtractor : public MyOggExtractor {
@@ -207,15 +207,15 @@
         return 0;
     }
 
-    virtual status_t readNextPacket(MediaBufferBase **buffer);
+    virtual media_status_t readNextPacket(MediaBufferBase **buffer);
 
 protected:
     virtual int64_t getTimeUsOfGranule(uint64_t granulePos) const;
-    virtual status_t verifyHeader(MediaBufferBase *buffer, uint8_t type);
+    virtual media_status_t verifyHeader(MediaBufferBase *buffer, uint8_t type);
 
 private:
-    status_t verifyOpusHeader(MediaBufferBase *buffer);
-    status_t verifyOpusComments(MediaBufferBase *buffer);
+    media_status_t verifyOpusHeader(MediaBufferBase *buffer);
+    media_status_t verifyOpusComments(MediaBufferBase *buffer);
     uint32_t getNumSamplesInPacket(MediaBufferBase *buffer) const;
 
     uint8_t mChannelCount;
@@ -270,10 +270,10 @@
     }
 
     MediaBufferBase *packet;
-    status_t err = mExtractor->mImpl->readNextPacket(&packet);
+    media_status_t err = mExtractor->mImpl->readNextPacket(&packet);
 
-    if (err != OK) {
-        return AMEDIA_ERROR_UNKNOWN;
+    if (err != AMEDIA_OK) {
+        return err;
     }
 
 #if 0
@@ -507,27 +507,27 @@
         if (n < 0) {
             return n;
         } else if (n == 0) {
-            return ERROR_END_OF_STREAM;
+            return AMEDIA_ERROR_END_OF_STREAM;
         } else {
-            return ERROR_IO;
+            return AMEDIA_ERROR_IO;
         }
     }
 
     if (memcmp(header, "OggS", 4)) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     if (header[4] != 0) {
         // Wrong version.
 
-        return ERROR_UNSUPPORTED;
+        return AMEDIA_ERROR_UNSUPPORTED;
     }
 
     page->mFlags = header[5];
 
     if (page->mFlags & ~7) {
         // Only bits 0-2 are defined in version 0.
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     page->mGranulePosition = U64LE_AT(&header[6]);
@@ -544,7 +544,7 @@
     if (mSource->readAt(
                 offset + sizeof(header), page->mLace, page->mNumSegments)
             < (ssize_t)page->mNumSegments) {
-        return ERROR_IO;
+        return AMEDIA_ERROR_IO;
     }
 
     size_t totalSize = 0;;
@@ -567,7 +567,7 @@
     return sizeof(header) + page->mNumSegments + totalSize;
 }
 
-status_t MyOpusExtractor::readNextPacket(MediaBufferBase **out) {
+media_status_t MyOpusExtractor::readNextPacket(MediaBufferBase **out) {
     if (mOffset <= mFirstDataOffset && mStartGranulePosition < 0) {
         // The first sample might not start at time 0; find out where by subtracting
         // the number of samples on the first page from the granule position
@@ -577,12 +577,12 @@
         uint32_t numSamples = 0;
         uint64_t curGranulePosition = 0;
         while (true) {
-            status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
-            if (err != OK && err != ERROR_END_OF_STREAM) {
+            media_status_t err = _readNextPacket(&mBuf, /* calcVorbisTimestamp = */false);
+            if (err != AMEDIA_OK && err != AMEDIA_ERROR_END_OF_STREAM) {
                 return err;
             }
             // First two pages are header pages.
-            if (err == ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
+            if (err == AMEDIA_ERROR_END_OF_STREAM || mCurrentPage.mPageNo > 2) {
                 if (mBuf != NULL) {
                     mBuf->release();
                     mBuf = NULL;
@@ -603,8 +603,8 @@
         seekToOffset(0);
     }
 
-    status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
-    if (err != OK) {
+    media_status_t err = _readNextPacket(out, /* calcVorbisTimestamp = */false);
+    if (err != AMEDIA_OK) {
         return err;
     }
 
@@ -625,7 +625,7 @@
 
     uint32_t frames = getNumSamplesInPacket(*out);
     mCurGranulePosition += frames;
-    return OK;
+    return AMEDIA_OK;
 }
 
 uint32_t MyOpusExtractor::getNumSamplesInPacket(MediaBufferBase *buffer) const {
@@ -674,7 +674,7 @@
     return numSamples;
 }
 
-status_t MyOggExtractor::_readNextPacket(MediaBufferBase **out, bool calcVorbisTimestamp) {
+media_status_t MyOggExtractor::_readNextPacket(MediaBufferBase **out, bool calcVorbisTimestamp) {
     *out = NULL;
 
     MediaBufferBase *buffer = NULL;
@@ -711,7 +711,7 @@
                     buffer->release();
                 }
                 ALOGE("b/36592202");
-                return ERROR_MALFORMED;
+                return AMEDIA_ERROR_MALFORMED;
             }
             MediaBufferBase *tmp = MediaBufferBase::Create(fullSize);
             if (tmp == NULL) {
@@ -719,7 +719,7 @@
                     buffer->release();
                 }
                 ALOGE("b/36592202");
-                return ERROR_MALFORMED;
+                return AMEDIA_ERROR_MALFORMED;
             }
             if (buffer != NULL) {
                 memcpy(tmp->data(), buffer->data(), buffer->range_length());
@@ -739,7 +739,7 @@
                 buffer->release();
                 ALOGV("failed to read %zu bytes at %#016llx, got %zd bytes",
                         packetSize, (long long)dataOffset, n);
-                return ERROR_IO;
+                return AMEDIA_ERROR_IO;
             }
 
             buffer->set_range(0, fullSize);
@@ -776,7 +776,7 @@
                 }
                 *out = buffer;
 
-                return OK;
+                return AMEDIA_OK;
             }
 
             // fall through, the buffer now contains the start of the packet.
@@ -795,7 +795,7 @@
 
             ALOGV("readPage returned %zd", n);
 
-            return n < 0 ? n : (status_t)ERROR_END_OF_STREAM;
+            return n < 0 ? (media_status_t) n : AMEDIA_ERROR_END_OF_STREAM;
         }
 
         // Prevent a harmless unsigned integer overflow by clamping to 0
@@ -827,7 +827,7 @@
 
                 *out = buffer;
 
-                return OK;
+                return AMEDIA_OK;
             }
         }
     }
@@ -836,18 +836,18 @@
 status_t MyOggExtractor::init() {
     AMediaFormat_setString(mMeta, AMEDIAFORMAT_KEY_MIME, mMimeType);
 
-    status_t err;
+    media_status_t err;
     MediaBufferBase *packet;
     for (size_t i = 0; i < mNumHeaders; ++i) {
         // ignore timestamp for configuration packets
-        if ((err = _readNextPacket(&packet, /* calcVorbisTimestamp = */ false)) != OK) {
+        if ((err = _readNextPacket(&packet, /* calcVorbisTimestamp = */ false)) != AMEDIA_OK) {
             return err;
         }
         ALOGV("read packet of size %zu\n", packet->range_length());
         err = verifyHeader(packet, /* type = */ i * 2 + 1);
         packet->release();
         packet = NULL;
-        if (err != OK) {
+        if (err != AMEDIA_OK) {
             return err;
         }
     }
@@ -872,7 +872,7 @@
         buildTableOfContents();
     }
 
-    return OK;
+    return AMEDIA_OK;
 }
 
 void MyOggExtractor::buildTableOfContents() {
@@ -954,7 +954,7 @@
     return pcmSamplePosition * 1000000ll / kOpusSampleRate;
 }
 
-status_t MyOpusExtractor::verifyHeader(MediaBufferBase *buffer, uint8_t type) {
+media_status_t MyOpusExtractor::verifyHeader(MediaBufferBase *buffer, uint8_t type) {
     switch (type) {
         // there are actually no header types defined in the Opus spec; we choose 1 and 3 to mean
         // header and comments such that we can share code with MyVorbisExtractor.
@@ -963,11 +963,11 @@
         case 3:
             return verifyOpusComments(buffer);
         default:
-            return INVALID_OPERATION;
+            return AMEDIA_ERROR_INVALID_OPERATION;
     }
 }
 
-status_t MyOpusExtractor::verifyOpusHeader(MediaBufferBase *buffer) {
+media_status_t MyOpusExtractor::verifyOpusHeader(MediaBufferBase *buffer) {
     const size_t kOpusHeaderSize = 19;
     const uint8_t *data =
         (const uint8_t *)buffer->data() + buffer->range_offset();
@@ -977,7 +977,7 @@
     if (size < kOpusHeaderSize
             || memcmp(data, "OpusHead", 8)
             || /* version = */ data[8] != 1) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     mChannelCount = data[9];
@@ -993,16 +993,16 @@
     AMediaFormat_setInt64(mMeta, AMEDIAFORMAT_KEY_CSD_1,
             mCodecDelay /* sample/s */ * 1000000000ll / kOpusSampleRate);
 
-    return OK;
+    return AMEDIA_OK;
 }
 
-status_t MyOpusExtractor::verifyOpusComments(MediaBufferBase *buffer) {
+media_status_t MyOpusExtractor::verifyOpusComments(MediaBufferBase *buffer) {
     // add artificial framing bit so we can reuse _vorbis_unpack_comment
     int32_t commentSize = buffer->range_length() + 1;
     auto tmp = heapbuffer<uint8_t>(commentSize);
     uint8_t *commentData = tmp.get();
     if (commentData == nullptr) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     memcpy(commentData,
@@ -1031,14 +1031,14 @@
     for (int i = 0; i < headerLen; ++i) {
         char chr = oggpack_read(&bits, 8);
         if (chr != OpusTags[i]) {
-            return ERROR_MALFORMED;
+            return AMEDIA_ERROR_MALFORMED;
         }
     }
 
     int32_t vendorLen = oggpack_read(&bits, 32);
     framingBitOffset += 4;
     if (vendorLen < 0 || vendorLen > commentSize - 8) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
     // skip vendor string
     framingBitOffset += vendorLen;
@@ -1049,13 +1049,13 @@
     int32_t n = oggpack_read(&bits, 32);
     framingBitOffset += 4;
     if (n < 0 || n > ((commentSize - oggpack_bytes(&bits)) >> 2)) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
     for (int i = 0; i < n; ++i) {
         int32_t len = oggpack_read(&bits, 32);
         framingBitOffset += 4;
         if (len  < 0 || len  > (commentSize - oggpack_bytes(&bits))) {
-            return ERROR_MALFORMED;
+            return AMEDIA_ERROR_MALFORMED;
         }
         framingBitOffset += len;
         for (int j = 0; j < len; ++j) {
@@ -1063,7 +1063,7 @@
         }
     }
     if (framingBitOffset < 0 || framingBitOffset >= commentSize) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
     commentData[framingBitOffset] = 1;
 
@@ -1080,14 +1080,14 @@
     oggpack_readinit(&bits, &ref);
     int err = _vorbis_unpack_comment(&mVc, &bits);
     if (0 != err) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     parseFileMetaData();
-    return OK;
+    return AMEDIA_OK;
 }
 
-status_t MyVorbisExtractor::verifyHeader(
+media_status_t MyVorbisExtractor::verifyHeader(
         MediaBufferBase *buffer, uint8_t type) {
     const uint8_t *data =
         (const uint8_t *)buffer->data() + buffer->range_offset();
@@ -1095,7 +1095,7 @@
     size_t size = buffer->range_length();
 
     if (size < 7 || data[0] != type || memcmp(&data[1], "vorbis", 6)) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
 
     ogg_buffer buf;
@@ -1114,7 +1114,7 @@
     oggpack_readinit(&bits, &ref);
 
     if (oggpack_read(&bits, 8) != type) {
-        return ERROR_MALFORMED;
+        return AMEDIA_ERROR_MALFORMED;
     }
     for (size_t i = 0; i < 6; ++i) {
         oggpack_read(&bits, 8);  // skip 'vorbis'
@@ -1124,7 +1124,7 @@
         case 1:
         {
             if (0 != _vorbis_unpack_info(&mVi, &bits)) {
-                return ERROR_MALFORMED;
+                return AMEDIA_ERROR_MALFORMED;
             }
 
             AMediaFormat_setBuffer(mMeta, AMEDIAFORMAT_KEY_CSD_0, data, size);
@@ -1154,7 +1154,7 @@
         case 3:
         {
             if (0 != _vorbis_unpack_comment(&mVc, &bits)) {
-                return ERROR_MALFORMED;
+                return AMEDIA_ERROR_MALFORMED;
             }
 
             parseFileMetaData();
@@ -1164,7 +1164,7 @@
         case 5:
         {
             if (0 != _vorbis_unpack_books(&mVi, &bits)) {
-                return ERROR_MALFORMED;
+                return AMEDIA_ERROR_MALFORMED;
             }
 
             AMediaFormat_setBuffer(mMeta, AMEDIAFORMAT_KEY_CSD_1, data, size);
@@ -1172,7 +1172,7 @@
         }
     }
 
-    return OK;
+    return AMEDIA_OK;
 }
 
 uint64_t MyVorbisExtractor::approxBitrate() const {
diff --git a/media/libaudioclient/AudioRecord.cpp b/media/libaudioclient/AudioRecord.cpp
index 34c5428..038c854 100644
--- a/media/libaudioclient/AudioRecord.cpp
+++ b/media/libaudioclient/AudioRecord.cpp
@@ -1300,10 +1300,7 @@
     mNewPosition = position + mUpdatePeriod;
     status_t result = createRecord_l(position, mOpPackageName);
 
-    if (result != NO_ERROR) {
-        ALOGW("%s(%d): createRecord_l failed, do not retry", __func__, mId);
-        retries = 0;
-    } else {
+    if (result == NO_ERROR) {
         if (mActive) {
             // callback thread or sync event hasn't changed
             // FIXME this fails if we have a new AudioFlinger instance
@@ -1316,13 +1313,15 @@
     if (result != NO_ERROR) {
         ALOGW("%s(%d): failed status %d, retries %d", __func__, mId, result, retries);
         if (--retries > 0) {
+            // leave time for an eventual race condition to clear before retrying
+            usleep(500000);
             goto retry;
         }
-    }
-
-    if (result != NO_ERROR) {
-        ALOGW("%s(%d): failed status %d", __func__, mId, result);
-        mActive = false;
+        // if no retries left, set invalid bit to force restoring at next occasion
+        // and avoid inconsistent active state on client and server sides
+        if (mCblk != nullptr) {
+            android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
+        }
     }
 
     return result;
diff --git a/media/libaudioclient/AudioTrack.cpp b/media/libaudioclient/AudioTrack.cpp
index e77abc6..c86d4ce 100644
--- a/media/libaudioclient/AudioTrack.cpp
+++ b/media/libaudioclient/AudioTrack.cpp
@@ -2308,10 +2308,7 @@
     // If a new IAudioTrack cannot be created, the previous (dead) instance will be left intact.
     status_t result = createTrack_l();
 
-    if (result != NO_ERROR) {
-        ALOGW("%s(%d): createTrack_l failed, do not retry", __func__, mId);
-        retries = 0;
-    } else {
+    if (result == NO_ERROR) {
         // take the frames that will be lost by track recreation into account in saved position
         // For streaming tracks, this is the amount we obtained from the user/client
         // (not the number actually consumed at the server - those are already lost).
@@ -2358,12 +2355,16 @@
     if (result != NO_ERROR) {
         ALOGW("%s(%d): failed status %d, retries %d", __func__, mId, result, retries);
         if (--retries > 0) {
+            // leave time for an eventual race condition to clear before retrying
+            usleep(500000);
             goto retry;
         }
-        mState = STATE_STOPPED;
-        mReleased = 0;
+        // if no retries left, set invalid bit to force restoring at next occasion
+        // and avoid inconsistent active state on client and server sides
+        if (mCblk != nullptr) {
+            android_atomic_or(CBLK_INVALID, &mCblk->mFlags);
+        }
     }
-
     return result;
 }
 
diff --git a/media/libmedia/NdkMediaErrorPriv.cpp b/media/libmedia/NdkMediaErrorPriv.cpp
index d061f5a..ba3b919 100644
--- a/media/libmedia/NdkMediaErrorPriv.cpp
+++ b/media/libmedia/NdkMediaErrorPriv.cpp
@@ -29,6 +29,12 @@
         return AMEDIA_ERROR_END_OF_STREAM;
     } else if (err == ERROR_IO) {
         return AMEDIA_ERROR_IO;
+    } else if (err == ERROR_MALFORMED) {
+        return AMEDIA_ERROR_MALFORMED;
+    } else if (err == INVALID_OPERATION) {
+        return AMEDIA_ERROR_INVALID_OPERATION;
+    } else if (err == UNKNOWN_ERROR) {
+        return AMEDIA_ERROR_UNKNOWN;
     }
 
     ALOGE("sf error code: %d", err);
@@ -45,6 +51,12 @@
         return ERROR_IO;
     } else if (err == AMEDIA_ERROR_WOULD_BLOCK) {
         return WOULD_BLOCK;
+    } else if (err == AMEDIA_ERROR_MALFORMED) {
+        return ERROR_MALFORMED;
+    } else if (err == AMEDIA_ERROR_INVALID_OPERATION) {
+        return INVALID_OPERATION;
+    } else if (err == AMEDIA_ERROR_UNKNOWN) {
+        return UNKNOWN_ERROR;
     }
 
     ALOGE("ndk error code: %d", err);
diff --git a/media/libmedia/NdkWrapper.cpp b/media/libmedia/NdkWrapper.cpp
index 7d67262..9e09c7e 100644
--- a/media/libmedia/NdkWrapper.cpp
+++ b/media/libmedia/NdkWrapper.cpp
@@ -1244,37 +1244,15 @@
     return new AMediaCodecCryptoInfoWrapper(AMediaExtractor_getSampleCryptoInfo(mAMediaExtractor));
 }
 
-ssize_t AMediaDataSourceWrapper::AMediaDataSourceWrapper_getSize(void *userdata) {
-    DataSource *source = static_cast<DataSource *>(userdata);
-    off64_t size = -1;
-    source->getSize(&size);
-    return size;
-}
-
-ssize_t AMediaDataSourceWrapper::AMediaDataSourceWrapper_readAt(void *userdata, off64_t offset, void * buf, size_t size) {
-    DataSource *source = static_cast<DataSource *>(userdata);
-    return source->readAt(offset, buf, size);
-}
-
-void AMediaDataSourceWrapper::AMediaDataSourceWrapper_close(void *userdata) {
-    DataSource *source = static_cast<DataSource *>(userdata);
-    source->close();
-}
-
-AMediaDataSourceWrapper::AMediaDataSourceWrapper(const sp<DataSource> &dataSource)
-    : mDataSource(dataSource),
-      mAMediaDataSource(AMediaDataSource_new()) {
-    ALOGV("setDataSource (source: %p)", dataSource.get());
-    AMediaDataSource_setUserdata(mAMediaDataSource, dataSource.get());
-    AMediaDataSource_setReadAt(mAMediaDataSource, AMediaDataSourceWrapper_readAt);
-    AMediaDataSource_setGetSize(mAMediaDataSource, AMediaDataSourceWrapper_getSize);
-    AMediaDataSource_setClose(mAMediaDataSource, AMediaDataSourceWrapper_close);
+AMediaDataSourceWrapper::AMediaDataSourceWrapper(AMediaDataSource *aDataSource)
+    : mAMediaDataSource(aDataSource) {
 }
 
 AMediaDataSourceWrapper::~AMediaDataSourceWrapper() {
     if (mAMediaDataSource == NULL) {
         return;
     }
+    AMediaDataSource_close(mAMediaDataSource);
     AMediaDataSource_delete(mAMediaDataSource);
     mAMediaDataSource = NULL;
 }
@@ -1283,4 +1261,8 @@
     return mAMediaDataSource;
 }
 
+void AMediaDataSourceWrapper::close() {
+    AMediaDataSource_close(mAMediaDataSource);
+}
+
 }  // namespace android
diff --git a/media/libmedia/include/media/NdkWrapper.h b/media/libmedia/include/media/NdkWrapper.h
index 191665a..b3b0688 100644
--- a/media/libmedia/include/media/NdkWrapper.h
+++ b/media/libmedia/include/media/NdkWrapper.h
@@ -278,6 +278,30 @@
     DISALLOW_EVIL_CONSTRUCTORS(AMediaCodecWrapper);
 };
 
+struct AMediaDataSourceWrapper : public RefBase {
+
+    AMediaDataSourceWrapper(AMediaDataSource*);
+    AMediaDataSourceWrapper(int fd, int64_t offset, int64_t length);
+
+    AMediaDataSource *getAMediaDataSource();
+    int getFd() { return mFd; }
+    int64_t getOffset() { return mOffset; }
+    int64_t getLength() { return mLength; }
+
+    void close();
+
+protected:
+    virtual ~AMediaDataSourceWrapper();
+
+private:
+    AMediaDataSource *mAMediaDataSource;
+    int mFd;
+    int64_t mOffset;
+    int64_t mLength;
+
+    DISALLOW_EVIL_CONSTRUCTORS(AMediaDataSourceWrapper);
+};
+
 struct AMediaExtractorWrapper : public RefBase {
 
     AMediaExtractorWrapper(AMediaExtractor *aMediaExtractor);
@@ -337,31 +361,6 @@
     DISALLOW_EVIL_CONSTRUCTORS(AMediaExtractorWrapper);
 };
 
-struct AMediaDataSourceWrapper : public RefBase {
-
-    static status_t translate_error(media_status_t err);
-
-    static ssize_t AMediaDataSourceWrapper_getSize(void *userdata);
-
-    static ssize_t AMediaDataSourceWrapper_readAt(void *userdata, off64_t offset, void * buf, size_t size);
-
-    static void AMediaDataSourceWrapper_close(void *userdata);
-
-    AMediaDataSourceWrapper(const sp<DataSource> &dataSource);
-
-    AMediaDataSource *getAMediaDataSource();
-
-protected:
-    virtual ~AMediaDataSourceWrapper();
-
-private:
-    sp<DataSource> mDataSource;
-
-    AMediaDataSource *mAMediaDataSource;
-
-    DISALLOW_EVIL_CONSTRUCTORS(AMediaDataSourceWrapper);
-};
-
 }  // namespace android
 
 #endif  // NDK_WRAPPER_H_
diff --git a/media/libmediaplayer2/Android.bp b/media/libmediaplayer2/Android.bp
index a26cc81..75d1df0 100644
--- a/media/libmediaplayer2/Android.bp
+++ b/media/libmediaplayer2/Android.bp
@@ -28,6 +28,7 @@
         "libcrypto",
         "libmediametrics",
         "libmediandk",
+        "libmediandk_utils",
         "libmediautils",
         "libmemunreachable",
         "libnativewindow",
diff --git a/media/libmediaplayer2/nuplayer2/Android.bp b/media/libmediaplayer2/nuplayer2/Android.bp
index 26da491..c3c94b6 100644
--- a/media/libmediaplayer2/nuplayer2/Android.bp
+++ b/media/libmediaplayer2/nuplayer2/Android.bp
@@ -28,6 +28,7 @@
         "frameworks/av/media/libstagefright/mpeg2ts",
         "frameworks/av/media/libstagefright/rtsp",
         "frameworks/av/media/libstagefright/timedtext",
+        "frameworks/av/media/ndk",
     ],
 
     cflags: [
@@ -49,6 +50,7 @@
         "libgui",
         "libmedia",
         "libmediandk",
+        "libmediandk_utils",
         "libpowermanager",
     ],
 
diff --git a/media/libmediaplayer2/nuplayer2/GenericSource2.cpp b/media/libmediaplayer2/nuplayer2/GenericSource2.cpp
index bf76e3a..6056ad9 100644
--- a/media/libmediaplayer2/nuplayer2/GenericSource2.cpp
+++ b/media/libmediaplayer2/nuplayer2/GenericSource2.cpp
@@ -21,29 +21,20 @@
 #include "NuPlayer2Drm.h"
 
 #include "AnotherPacketSource.h"
-#include <binder/IServiceManager.h>
 #include <cutils/properties.h>
 #include <media/DataSource.h>
 #include <media/MediaBufferHolder.h>
-#include <media/IMediaExtractorService.h>
-#include <media/IMediaSource.h>
-#include <media/MediaHTTPService.h>
-#include <media/MediaSource.h>
 #include <media/NdkWrapper.h>
 #include <media/stagefright/foundation/ABuffer.h>
 #include <media/stagefright/foundation/ADebug.h>
 #include <media/stagefright/foundation/AMessage.h>
-#include <media/stagefright/ClearDataSourceFactory.h>
-#include <media/stagefright/InterfaceUtils.h>
 #include <media/stagefright/MediaBuffer.h>
 #include <media/stagefright/MediaClock.h>
 #include <media/stagefright/MediaDefs.h>
-#include <media/stagefright/MediaExtractorFactory.h>
 #include <media/stagefright/MetaData.h>
 #include <media/stagefright/NdkUtils.h>
 #include <media/stagefright/Utils.h>
-#include "../../libstagefright/include/NuCachedSource2.h"
-#include "../../libstagefright/include/HTTPBase.h"
+#include "NdkMediaDataSourceCallbacksPriv.h"
 
 namespace android {
 
@@ -88,9 +79,6 @@
 void NuPlayer2::GenericSource2::resetDataSource() {
     ALOGV("resetDataSource");
 
-    mHTTPService.clear();
-    mHttpSource.clear();
-    mDisconnected = false;
     mUri.clear();
     mUriHeaders.clear();
     if (mFd >= 0) {
@@ -109,7 +97,6 @@
 }
 
 status_t NuPlayer2::GenericSource2::setDataSource(
-        const sp<MediaHTTPService> &httpService,
         const char *url,
         const KeyedVector<String8, String8> *headers) {
     Mutex::Autolock _l(mLock);
@@ -117,7 +104,6 @@
 
     resetDataSource();
 
-    mHTTPService = httpService;
     mUri = url;
 
     if (headers) {
@@ -150,7 +136,8 @@
     ALOGV("setDataSource (source: %p)", source.get());
 
     resetDataSource();
-    mDataSource = source;
+    AMediaDataSource *aSource = convertDataSourceToAMediaDataSource(source);
+    mDataSourceWrapper = new AMediaDataSourceWrapper(aSource);
     return OK;
 }
 
@@ -161,24 +148,21 @@
 
 status_t NuPlayer2::GenericSource2::initFromDataSource() {
     mExtractor = new AMediaExtractorWrapper(AMediaExtractor_new());
-    CHECK(mDataSource != NULL || mFd != -1);
-    sp<DataSource> dataSource = mDataSource;
+    CHECK(mFd >=0 || mDataSourceWrapper != NULL);
+    sp<AMediaDataSourceWrapper> aSourceWrapper = mDataSourceWrapper;
     const int fd = mFd;
-    const int64_t offset = mOffset;
-    const int64_t length = mLength;
 
     mLock.unlock();
     // This might take long time if data source is not reliable.
     status_t err;
-    if (dataSource != nullptr) {
-        mDataSourceWrapper = new AMediaDataSourceWrapper(dataSource);
-        err = mExtractor->setDataSource(mDataSourceWrapper->getAMediaDataSource());
+    if (aSourceWrapper != NULL) {
+        err = mExtractor->setDataSource(aSourceWrapper->getAMediaDataSource());
     } else {
-        err = mExtractor->setDataSource(fd, offset, length);
+        err = mExtractor->setDataSource(fd, mOffset, mLength);
     }
 
     if (err != OK) {
-        ALOGE("initFromDataSource, failed to create data source!");
+        ALOGE("initFromDataSource, failed to set extractor data source!");
         mLock.lock();
         return UNKNOWN_ERROR;
     }
@@ -190,10 +174,8 @@
         return UNKNOWN_ERROR;
     }
 
-    mLock.lock();
-    mFd = -1;
-    mDataSource = dataSource;
     mFileMeta = convertMediaFormatWrapperToMetaData(mExtractor->getFormat());
+    mLock.lock();
     if (mFileMeta != NULL) {
         int64_t duration;
         if (mFileMeta->findInt64(kKeyDuration, &duration)) {
@@ -214,11 +196,7 @@
         }
 
         sp<AMediaExtractorWrapper> trackExtractor = new AMediaExtractorWrapper(AMediaExtractor_new());
-        if (mDataSourceWrapper != nullptr) {
-            err = trackExtractor->setDataSource(mDataSourceWrapper->getAMediaDataSource());
-        } else {
-            err = trackExtractor->setDataSource(fd, offset, length);
-        }
+        trackExtractor->setDataSource(mDataSourceWrapper->getAMediaDataSource());
 
         const char *mime;
         sp<MetaData> meta = convertMediaFormatWrapperToMetaData(trackFormat);
@@ -329,8 +307,8 @@
         mLooper->unregisterHandler(id());
         mLooper->stop();
     }
-    if (mDataSource != NULL) {
-        mDataSource->close();
+    if (mDataSourceWrapper != NULL) {
+        mDataSourceWrapper->close();
     }
     resetDataSource();
 }
@@ -356,55 +334,39 @@
 }
 
 void NuPlayer2::GenericSource2::onPrepareAsync(int64_t startTimeUs) {
-    ALOGV("onPrepareAsync: mDataSource: %d", (mDataSource != NULL));
+    ALOGV("onPrepareAsync: mFd %d mUri %s mDataSourceWrapper: %p",
+            mFd, mUri.c_str(), mDataSourceWrapper.get());
 
-    // delayed data source creation
-    if (mDataSource == NULL) {
-        // set to false first, if the extractor
-        // comes back as secure, set it to true then.
-        mIsSecure = false;
-
-        if (!mUri.empty()) {
-            const char* uri = mUri.c_str();
-            String8 contentType;
-
-            if (!strncasecmp("http://", uri, 7) || !strncasecmp("https://", uri, 8)) {
-                mHttpSource = ClearDataSourceFactory::CreateMediaHTTP(mHTTPService);
-                if (mHttpSource == NULL) {
-                    ALOGE("Failed to create http source!");
-                    notifyPreparedAndCleanup(UNKNOWN_ERROR);
-                    return;
-                }
-            }
-
-            mLock.unlock();
-            // This might take long time if connection has some issue.
-            sp<DataSource> dataSource = ClearDataSourceFactory::CreateFromURI(
-                   mHTTPService, uri, &mUriHeaders, &contentType,
-                   static_cast<HTTPBase *>(mHttpSource.get()));
-            mLock.lock();
-            if (!mDisconnected) {
-                mDataSource = dataSource;
-            }
+    if (!mUri.empty()) {
+        const char* uri = mUri.c_str();
+        size_t numheaders = mUriHeaders.size();
+        const char **key_values = numheaders ? new const char *[numheaders * 2] : NULL;
+        for (size_t i = 0; i < numheaders; ++i) {
+            key_values[i * 2] = mUriHeaders.keyAt(i).c_str();
+            key_values[i * 2 + 1] =  mUriHeaders.valueAt(i).c_str();
         }
-
-        if (mFd == -1 && mDataSource == NULL) {
-            ALOGE("Failed to create data source!");
-            notifyPreparedAndCleanup(UNKNOWN_ERROR);
-            return;
-        }
+        mLock.unlock();
+        AMediaDataSource *aSource = AMediaDataSource_newUri(uri, numheaders, key_values);
+        mLock.lock();
+        mDataSourceWrapper = aSource ? new AMediaDataSourceWrapper(aSource) : NULL;
+        delete[] key_values;
+        // For cached streaming cases, we need to wait for enough
+        // buffering before reporting prepared.
+        mIsStreaming = !strncasecmp("http://", uri, 7) || !strncasecmp("https://", uri, 8);
     }
 
-    if (mDataSource != nullptr && mDataSource->flags() & DataSource::kIsCachingDataSource) {
-        mCachedSource = static_cast<NuCachedSource2 *>(mDataSource.get());
+    if (mDisconnected || (mFd < 0 && mDataSourceWrapper == NULL)) {
+        ALOGE("mDisconnected(%d) or Failed to create data source!", mDisconnected);
+        notifyPreparedAndCleanup(UNKNOWN_ERROR);
+        return;
     }
 
-    // For cached streaming cases, we need to wait for enough
-    // buffering before reporting prepared.
-    mIsStreaming = (mCachedSource != NULL);
-
     // init extractor from data source
     status_t err = initFromDataSource();
+    if (mFd >= 0) {
+        close(mFd);
+        mFd = -1;
+    }
 
     if (err != OK) {
         ALOGE("Failed to init from data source!");
@@ -441,7 +403,6 @@
     ALOGV("finishPrepareAsync");
 
     if (mIsStreaming) {
-        mCachedSource->resumeFetchingIfNecessary();
         mPreparing = true;
         ++mPollBufferingGeneration;
         schedulePollBuffering();
@@ -460,9 +421,7 @@
 
 void NuPlayer2::GenericSource2::notifyPreparedAndCleanup(status_t err) {
     if (err != OK) {
-        mDataSource.clear();
-        mCachedSource.clear();
-        mHttpSource.clear();
+        mDataSourceWrapper.clear();
 
         mBitrate = -1;
         mPrevBufferPercentage = -1;
@@ -502,47 +461,19 @@
 }
 
 void NuPlayer2::GenericSource2::disconnect() {
-    sp<DataSource> dataSource, httpSource;
     {
         Mutex::Autolock _l(mLock);
-        dataSource = mDataSource;
-        httpSource = mHttpSource;
         mDisconnected = true;
     }
-
-    if (dataSource != NULL) {
-        // disconnect data source
-        if (dataSource->flags() & DataSource::kIsCachingDataSource) {
-            static_cast<NuCachedSource2 *>(dataSource.get())->disconnect();
-        }
-    } else if (httpSource != NULL) {
-        static_cast<HTTPBase *>(httpSource.get())->disconnect();
+    if (mDataSourceWrapper != NULL) {
+        mDataSourceWrapper->close();
     }
-
-    mDataSourceWrapper = NULL;
-
 }
 
 status_t NuPlayer2::GenericSource2::feedMoreTSData() {
     return OK;
 }
 
-void NuPlayer2::GenericSource2::sendCacheStats() {
-    int32_t kbps = 0;
-    status_t err = UNKNOWN_ERROR;
-
-    if (mCachedSource != NULL) {
-        err = mCachedSource->getEstimatedBandwidthKbps(&kbps);
-    }
-
-    if (err == OK) {
-        sp<AMessage> notify = dupNotify();
-        notify->setInt32("what", kWhatCacheStats);
-        notify->setInt32("bandwidth", kbps);
-        notify->post();
-    }
-}
-
 void NuPlayer2::GenericSource2::onMessageReceived(const sp<AMessage> &msg) {
     Mutex::Autolock _l(mLock);
     switch (msg->what()) {
@@ -840,8 +771,6 @@
             }
             if (track->mPackets->getAvailableBufferCount(&finalResult) < 2
                 && !mSentPauseOnBuffering && !mPreparing) {
-                mCachedSource->resumeFetchingIfNecessary();
-                sendCacheStats();
                 mSentPauseOnBuffering = true;
                 sp<AMessage> notify = dupNotify();
                 notify->setInt32("what", kWhatPauseOnBufferingStart);
@@ -1397,7 +1326,6 @@
                         notifyPrepared();
                         mPreparing = false;
                     } else {
-                        sendCacheStats();
                         mSentPauseOnBuffering = false;
                         sp<AMessage> notify = dupNotify();
                         notify->setInt32("what", kWhatResumeOnBufferingEnd);
@@ -1458,40 +1386,22 @@
 }
 
 void NuPlayer2::GenericSource2::onPollBuffering() {
-    status_t finalStatus = UNKNOWN_ERROR;
     int64_t cachedDurationUs = -1ll;
-    ssize_t cachedDataRemaining = -1;
 
-    if (mCachedSource != NULL) {
-        cachedDataRemaining = mCachedSource->approxDataRemaining(&finalStatus);
-
-        if (finalStatus == OK) {
-            off64_t size;
-            int64_t bitrate = 0ll;
-            if (mDurationUs > 0 && mCachedSource->getSize(&size) == OK) {
-                // |bitrate| uses bits/second unit, while size is number of bytes.
-                bitrate = size * 8000000ll / mDurationUs;
-            } else if (mBitrate > 0) {
-                bitrate = mBitrate;
-            }
-            if (bitrate > 0) {
-                cachedDurationUs = cachedDataRemaining * 8000000ll / bitrate;
-            }
-        }
+    sp<AMediaExtractorWrapper> extractor;
+    if (mVideoTrack.mExtractor != NULL) {
+        extractor = mVideoTrack.mExtractor;
+    } else if (mAudioTrack.mExtractor != NULL) {
+        extractor = mAudioTrack.mExtractor;
     }
 
-    if (finalStatus != OK) {
-        ALOGV("onPollBuffering: EOS (finalStatus = %d)", finalStatus);
-
-        if (finalStatus == ERROR_END_OF_STREAM) {
-            notifyBufferingUpdate(100);
-        }
-
-        return;
+    if (extractor != NULL) {
+        cachedDurationUs = extractor->getCachedDuration();
     }
 
     if (cachedDurationUs >= 0ll) {
-        if (mDurationUs > 0ll) {
+        ssize_t sampleSize = extractor->getSampleSize();
+        if (sampleSize >= 0ll) {
             int64_t cachedPosUs = getLastReadPosition() + cachedDurationUs;
             int percentage = 100.0 * cachedPosUs / mDurationUs;
             if (percentage > 100) {
@@ -1499,9 +1409,11 @@
             }
 
             notifyBufferingUpdate(percentage);
+            ALOGV("onPollBuffering: cachedDurationUs %.1f sec", cachedDurationUs / 1000000.0f);
+        } else {
+            notifyBufferingUpdate(100);
+            ALOGV("onPollBuffering: EOS");
         }
-
-        ALOGV("onPollBuffering: cachedDurationUs %.1f sec", cachedDurationUs / 1000000.0f);
     }
 
     schedulePollBuffering();
diff --git a/media/libmediaplayer2/nuplayer2/GenericSource2.h b/media/libmediaplayer2/nuplayer2/GenericSource2.h
index 3cac809..ade1aa3 100644
--- a/media/libmediaplayer2/nuplayer2/GenericSource2.h
+++ b/media/libmediaplayer2/nuplayer2/GenericSource2.h
@@ -37,11 +37,9 @@
 class DataSource;
 class IDataSource;
 class IMediaSource;
-struct MediaHTTPService;
 struct MediaSource;
 class MediaBuffer;
 struct MediaClock;
-struct NuCachedSource2;
 
 struct NuPlayer2::GenericSource2 : public NuPlayer2::Source,
                                    public MediaBufferObserver // Modular DRM
@@ -50,7 +48,6 @@
                    const sp<MediaClock> &mediaClock);
 
     status_t setDataSource(
-            const sp<MediaHTTPService> &httpService,
             const char *url,
             const KeyedVector<String8, String8> *headers);
 
@@ -151,7 +148,6 @@
     bool mIsStreaming;
     uid_t mUID;
     const sp<MediaClock> mMediaClock;
-    sp<MediaHTTPService> mHTTPService;
     AString mUri;
     KeyedVector<String8, String8> mUriHeaders;
     int mFd;
@@ -159,9 +155,6 @@
     int64_t mLength;
 
     bool mDisconnected;
-    sp<DataSource> mDataSource;
-    sp<NuCachedSource2> mCachedSource;
-    sp<DataSource> mHttpSource;
     sp<MetaData> mFileMeta;
     sp<AMediaDataSourceWrapper> mDataSourceWrapper;
     sp<AMediaExtractorWrapper> mExtractor;
@@ -232,8 +225,6 @@
     void onPollBuffering();
     void notifyBufferingUpdate(int32_t percentage);
 
-    void sendCacheStats();
-
     sp<AMessage> getFormat_l(bool audio);
     sp<MetaData> getFormatMeta_l(bool audio);
     int32_t getDataGeneration(media_track_type type) const;
diff --git a/media/libmediaplayer2/nuplayer2/NuPlayer2.cpp b/media/libmediaplayer2/nuplayer2/NuPlayer2.cpp
index 5b7bf4a..7b9ff30 100644
--- a/media/libmediaplayer2/nuplayer2/NuPlayer2.cpp
+++ b/media/libmediaplayer2/nuplayer2/NuPlayer2.cpp
@@ -308,7 +308,7 @@
                 sp<GenericSource2> genericSource =
                         new GenericSource2(notify, mUID, mMediaClock);
 
-                err = genericSource->setDataSource(httpService, url, headers);
+                err = genericSource->setDataSource(url, headers);
 
                 if (err == OK) {
                     *source = genericSource;
diff --git a/media/ndk/NdkMediaDataSource.cpp b/media/ndk/NdkMediaDataSource.cpp
index 43c89bb..3c10024 100644
--- a/media/ndk/NdkMediaDataSource.cpp
+++ b/media/ndk/NdkMediaDataSource.cpp
@@ -224,6 +224,11 @@
     }
 
     sp<DataSource> source = DataSourceFactory::CreateFromURI(service, uri, &headers);
+    if (source == NULL) {
+        ALOGE("AMediaDataSource_newUri source is null");
+        return NULL;
+    }
+    ALOGI("AMediaDataSource_newUri source %s flags %u", source->toString().c_str(), source->flags());
     AMediaDataSource* aSource = convertDataSourceToAMediaDataSource(source);
     aSource->mImpl = source;
     aSource->mFlags = source->flags();
diff --git a/media/ndk/libmediandk.map.txt b/media/ndk/libmediandk.map.txt
index bf4802d..d3bdbae 100644
--- a/media/ndk/libmediandk.map.txt
+++ b/media/ndk/libmediandk.map.txt
@@ -166,6 +166,8 @@
     AMediaDrm_setOnEventListener;
     AMediaDrm_setPropertyByteArray;
     AMediaDrm_setPropertyString;
+    AMediaDrm_setOnExpirationUpdateListener; # introduced=29
+    AMediaDrm_setOnKeysChangeListener; # introduced=29
     AMediaDrm_sign;
     AMediaDrm_verify;
     AMediaExtractor_advance;