Merge "Don't CHECK on illegal state change"
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 361686c..5e4d81d 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -77,6 +77,7 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/soundfx/libreverbwrapper.so)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/soundfx/libbundlewrapper.so)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/soundfx/libaudiopreprocessing.so)
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/lib/libmediacodecservice.so)
 
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
diff --git a/drm/mediadrm/plugins/clearkey/Android.bp b/drm/mediadrm/plugins/clearkey/Android.bp
index f3ce65c..2973fcf 100644
--- a/drm/mediadrm/plugins/clearkey/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/Android.bp
@@ -38,7 +38,7 @@
     shared_libs: [
         "libcrypto",
         "liblog",
-        "libstagefright_foundation_vendor",
+        "libstagefright_foundation",
         "libutils",
     ],
 
diff --git a/drm/mediadrm/plugins/clearkey/tests/Android.bp b/drm/mediadrm/plugins/clearkey/tests/Android.bp
index 976c590..ac57d65 100644
--- a/drm/mediadrm/plugins/clearkey/tests/Android.bp
+++ b/drm/mediadrm/plugins/clearkey/tests/Android.bp
@@ -31,7 +31,7 @@
         "libcrypto",
         "libdrmclearkeyplugin",
         "liblog",
-        "libstagefright_foundation_vendor",
+        "libstagefright_foundation",
         "libutils",
     ],
 }
diff --git a/media/libaaudio/Android.bp b/media/libaaudio/Android.bp
index f539ba9..6e60f24 100644
--- a/media/libaaudio/Android.bp
+++ b/media/libaaudio/Android.bp
@@ -16,12 +16,14 @@
     name: "libAAudio_headers",
     from: "include",
     to: "",
-    srcs: ["include/aaudio/*.h"],
+    // omit AAudioTesting.h; supplied separately to those who need it
+    srcs: ["include/aaudio/AAudio.h"],
     license: "include/aaudio/NOTICE",
 }
 
 ndk_library {
     name: "libaaudio",
+    // deliberately includes symbols from AAudioTesting.h
     symbol_file: "libaaudio.map.txt",
     first_version: "26",
     unversioned_until: "current",
diff --git a/media/libmedia/Android.bp b/media/libmedia/Android.bp
index e9b99b4..750ff2d 100644
--- a/media/libmedia/Android.bp
+++ b/media/libmedia/Android.bp
@@ -19,24 +19,117 @@
     clang: true,
 }
 
-cc_library_shared {
-    name: "libmedia",
+// TODO(b/35449087): merge back with libmedia when OMX implementatoins
+// no longer use aidl wrappers (or remove OMX component form libmedia)
+cc_defaults {
+    name: "libmedia_omx_defaults",
+
+    srcs: [
+        "aidl/android/IGraphicBufferSource.aidl",
+        "aidl/android/IOMXBufferSource.aidl",
+
+        "IMediaCodecList.cpp",
+        "IMediaCodecService.cpp",
+        "IOMX.cpp",
+        "MediaCodecBuffer.cpp",
+        "MediaCodecInfo.cpp",
+        "MediaDefs.cpp",
+        "OMXBuffer.cpp",
+        "omx/1.0/WGraphicBufferSource.cpp",
+        "omx/1.0/WOmx.cpp",
+        "omx/1.0/WOmxBufferSource.cpp",
+        "omx/1.0/WOmxNode.cpp",
+        "omx/1.0/WOmxObserver.cpp",
+    ],
 
     aidl: {
         local_include_dirs: ["aidl"],
         export_aidl_headers: true,
     },
 
-    srcs: [
-        "aidl/android/IGraphicBufferSource.aidl",
-        "aidl/android/IOMXBufferSource.aidl",
+    shared_libs: [
+        "android.hidl.memory@1.0",
+        "android.hidl.token@1.0-utils",
+        "android.hardware.media.omx@1.0",
+        "android.hardware.media@1.0",
+        "libbase",
+        "libbinder",
+        "libcutils",
+        "libgui",
+        "libhidlbase",
+        "libhidlmemory",
+        "libhidltransport",
+        "libhwbinder",
+        "liblog",
+        "libstagefright_foundation",
+        "libui",
+        "libutils",
+    ],
 
+    include_dirs: [
+        "frameworks/av/include", // for media/vndk/xmlparser/1.0/MediaCodecsXmlParser.h
+        "frameworks/av/include/media",
+        "frameworks/native/include", // for media/hardware/MetadataBufferType.h
+        "frameworks/native/include/media/openmax",
+        "frameworks/av/media/libstagefright",
+    ],
+
+    export_shared_lib_headers: [
+        "android.hidl.memory@1.0",
+        "android.hidl.token@1.0-utils",
+        "android.hardware.media.omx@1.0",
+        "android.hardware.media@1.0",
+        "libhidlmemory",
+        "libstagefright_foundation",
+        "libui",
+    ],
+
+    header_libs: [
+        "libmedia_headers",
+    ],
+
+    export_header_lib_headers: [
+        "libmedia_headers",
+    ],
+
+    export_include_dirs: [
+        "aidl",
+    ],
+
+    cflags: [
+        "-Werror",
+        "-Wno-error=deprecated-declarations",
+        "-Wall",
+    ],
+
+    sanitize: {
+        misc_undefined: [
+            "unsigned-integer-overflow",
+            "signed-integer-overflow",
+        ],
+        cfi: true,
+        diag: {
+            cfi: true,
+        },
+    },
+}
+
+cc_library_shared {
+    name: "libmedia_omx",
+    vendor_available: true,
+
+    defaults: ["libmedia_omx_defaults"],
+}
+
+cc_library_shared {
+    name: "libmedia",
+    defaults: ["libmedia_omx_defaults"],
+
+    srcs: [
         "IDataSource.cpp",
         "IHDCP.cpp",
         "BufferingSettings.cpp",
         "mediaplayer.cpp",
-        "IMediaCodecList.cpp",
-        "IMediaCodecService.cpp",
         "IMediaHTTPConnection.cpp",
         "IMediaHTTPService.cpp",
         "IMediaExtractor.cpp",
@@ -52,9 +145,6 @@
         "IResourceManagerClient.cpp",
         "IResourceManagerService.cpp",
         "IStreamSource.cpp",
-        "MediaCodecBuffer.cpp",
-        "MediaCodecInfo.cpp",
-        "MediaDefs.cpp",
         "MediaUtils.cpp",
         "Metadata.cpp",
         "mediarecorder.cpp",
@@ -63,7 +153,6 @@
         "MidiDeviceInfo.cpp",
         "MidiIoWrapper.cpp",
         "JetPlayer.cpp",
-        "IOMX.cpp",
         "MediaScanner.cpp",
         "MediaScannerClient.cpp",
         "CharacterEncodingDetector.cpp",
@@ -71,14 +160,8 @@
         "MediaProfiles.cpp",
         "MediaResource.cpp",
         "MediaResourcePolicy.cpp",
-        "OMXBuffer.cpp",
         "Visualizer.cpp",
         "StringArray.cpp",
-        "omx/1.0/WGraphicBufferSource.cpp",
-        "omx/1.0/WOmx.cpp",
-        "omx/1.0/WOmxBufferSource.cpp",
-        "omx/1.0/WOmxNode.cpp",
-        "omx/1.0/WOmxObserver.cpp",
     ],
 
     shared_libs: [
@@ -106,11 +189,8 @@
         "libhwbinder",
         "libhidlmemory",
         "android.hidl.memory@1.0",
-        "android.hidl.token@1.0-utils",
         "android.hardware.graphics.common@1.0",
         "android.hardware.graphics.bufferqueue@1.0",
-        "android.hardware.media@1.0",
-        "android.hardware.media.omx@1.0",
     ],
 
     export_shared_lib_headers: [
@@ -119,8 +199,6 @@
         "libicui18n",
         "libsonivox",
         "libmediadrm",
-        "android.hidl.token@1.0-utils",
-        "android.hardware.media.omx@1.0",
         "android.hidl.memory@1.0",
     ],
 
@@ -136,7 +214,6 @@
     ],
 
     export_include_dirs: [
-        "aidl",
         "include",
     ],
     cflags: [
diff --git a/media/libstagefright/Android.bp b/media/libstagefright/Android.bp
index 5b8a0d1..ab75c65 100644
--- a/media/libstagefright/Android.bp
+++ b/media/libstagefright/Android.bp
@@ -89,7 +89,6 @@
         "libmediautils",
         "libnetd_client",
         "libsonivox",
-        "libstagefright_omx",
         "libui",
         "libutils",
         "libvorbisidec",
@@ -114,6 +113,7 @@
         "libstagefright_aacenc",
         "libstagefright_matroska",
         "libstagefright_mediafilter",
+        "libstagefright_omx_utils",
         "libstagefright_webm",
         "libstagefright_timedtext",
         "libvpx",
diff --git a/media/libstagefright/MPEG4Extractor.cpp b/media/libstagefright/MPEG4Extractor.cpp
index 941c759..65e172a 100644
--- a/media/libstagefright/MPEG4Extractor.cpp
+++ b/media/libstagefright/MPEG4Extractor.cpp
@@ -463,6 +463,66 @@
         return NULL;
     }
 
+    int64_t duration;
+    int32_t samplerate;
+    if (track->has_elst && mHeaderTimescale != 0 &&
+            track->meta->findInt64(kKeyDuration, &duration) &&
+            track->meta->findInt32(kKeySampleRate, &samplerate)) {
+
+        track->has_elst = false;
+
+        if (track->elst_segment_duration > INT64_MAX) {
+            goto editlistoverflow;
+        }
+        int64_t segment_duration = track->elst_segment_duration;
+        int64_t media_time = track->elst_media_time;
+        int64_t halfscale = mHeaderTimescale / 2;
+
+        int64_t delay;
+        // delay = ((media_time * samplerate) + halfscale) / mHeaderTimescale;
+        if (__builtin_mul_overflow(media_time, samplerate, &delay) ||
+                __builtin_add_overflow(delay, halfscale, &delay) ||
+                (delay /= mHeaderTimescale, false) ||
+                delay > INT32_MAX ||
+                delay < INT32_MIN) {
+            goto editlistoverflow;
+        }
+        track->meta->setInt32(kKeyEncoderDelay, delay);
+
+        int64_t scaled_duration;
+        // scaled_duration = ((duration * mHeaderTimescale) + 500000) / 1000000;
+        if (__builtin_mul_overflow(duration, mHeaderTimescale, &scaled_duration) ||
+                __builtin_add_overflow(scaled_duration, 500000, &scaled_duration)) {
+            goto editlistoverflow;
+        }
+        scaled_duration /= 1000000;
+
+        int64_t segment_end;
+        int64_t padding;
+        if (__builtin_add_overflow(segment_duration, media_time, &segment_end) ||
+                __builtin_sub_overflow(scaled_duration, segment_end, &padding)) {
+            goto editlistoverflow;
+        }
+
+        if (padding < 0) {
+            // track duration from media header (which is what kKeyDuration is) might
+            // be slightly shorter than the segment duration, which would make the
+            // padding negative. Clamp to zero.
+            padding = 0;
+        }
+
+        int64_t paddingsamples;
+        // paddingsamples = ((padding * samplerate) + halfscale) / mHeaderTimescale;
+        if (__builtin_mul_overflow(padding, samplerate, &paddingsamples) ||
+                __builtin_add_overflow(paddingsamples, halfscale, &paddingsamples) ||
+                (paddingsamples /= mHeaderTimescale, false) ||
+                paddingsamples > INT32_MAX) {
+            goto editlistoverflow;
+        }
+        track->meta->setInt32(kKeyEncoderPadding, paddingsamples);
+    }
+    editlistoverflow:
+
     if ((flags & kIncludeExtensiveMetaData)
             && !track->includes_expensive_metadata) {
         track->includes_expensive_metadata = true;
@@ -989,6 +1049,7 @@
                 track->skipTrack = false;
                 track->timescale = 0;
                 track->meta->setCString(kKeyMIMEType, "application/octet-stream");
+                track->has_elst = false;
             }
 
             off64_t stop_offset = *offset + chunk_size;
@@ -1055,6 +1116,10 @@
         {
             *offset += chunk_size;
 
+            if (!mLastTrack) {
+                return ERROR_MALFORMED;
+            }
+
             // See 14496-12 8.6.6
             uint8_t version;
             if (mDataSource->readAt(data_offset, &version, 1) < 1) {
@@ -1069,8 +1134,6 @@
             if (entry_count != 1) {
                 // we only support a single entry at the moment, for gapless playback
                 ALOGW("ignoring edit list with %d entries", entry_count);
-            } else if (mHeaderTimescale == 0) {
-                ALOGW("ignoring edit list because timescale is 0");
             } else {
                 off64_t entriesoffset = data_offset + 8;
                 uint64_t segment_duration;
@@ -1094,31 +1157,12 @@
                     return ERROR_IO;
                 }
 
-                uint64_t halfscale = mHeaderTimescale / 2;
-                segment_duration = (segment_duration * 1000000 + halfscale)/ mHeaderTimescale;
-                media_time = (media_time * 1000000 + halfscale) / mHeaderTimescale;
-
-                int64_t duration;
-                int32_t samplerate;
-                if (!mLastTrack) {
-                    return ERROR_MALFORMED;
-                }
-                if (mLastTrack->meta->findInt64(kKeyDuration, &duration) &&
-                        mLastTrack->meta->findInt32(kKeySampleRate, &samplerate)) {
-
-                    int64_t delay = (media_time  * samplerate + 500000) / 1000000;
-                    mLastTrack->meta->setInt32(kKeyEncoderDelay, delay);
-
-                    int64_t paddingus = duration - (int64_t)(segment_duration + media_time);
-                    if (paddingus < 0) {
-                        // track duration from media header (which is what kKeyDuration is) might
-                        // be slightly shorter than the segment duration, which would make the
-                        // padding negative. Clamp to zero.
-                        paddingus = 0;
-                    }
-                    int64_t paddingsamples = (paddingus * samplerate + 500000) / 1000000;
-                    mLastTrack->meta->setInt32(kKeyEncoderPadding, paddingsamples);
-                }
+                // save these for later, because the elst atom might precede
+                // the atoms that actually gives us the duration and sample rate
+                // needed to calculate the padding and delay values
+                mLastTrack->has_elst = true;
+                mLastTrack->elst_media_time = media_time;
+                mLastTrack->elst_segment_duration = segment_duration;
             }
             break;
         }
diff --git a/media/libstagefright/SampleIterator.cpp b/media/libstagefright/SampleIterator.cpp
index 4f31c5f..75f744d 100644
--- a/media/libstagefright/SampleIterator.cpp
+++ b/media/libstagefright/SampleIterator.cpp
@@ -172,7 +172,7 @@
         if (mSampleToChunkIndex + 1 < mTable->mNumSampleToChunkOffsets) {
             mStopChunk = entry[1].startChunk;
 
-            if (mStopChunk < mFirstChunk ||
+            if (mSamplesPerChunk == 0 || mStopChunk < mFirstChunk ||
                 (mStopChunk - mFirstChunk) > UINT32_MAX / mSamplesPerChunk ||
                 ((mStopChunk - mFirstChunk) * mSamplesPerChunk >
                  UINT32_MAX - mFirstChunkSampleIndex)) {
diff --git a/media/libstagefright/avc_utils.cpp b/media/libstagefright/avc_utils.cpp
index 7193435..ce6d50f 100644
--- a/media/libstagefright/avc_utils.cpp
+++ b/media/libstagefright/avc_utils.cpp
@@ -191,10 +191,22 @@
              frame_crop_top_offset, frame_crop_bottom_offset,
              cropUnitX, cropUnitY);
 
-        *width -=
-            (frame_crop_left_offset + frame_crop_right_offset) * cropUnitX;
-        *height -=
-            (frame_crop_top_offset + frame_crop_bottom_offset) * cropUnitY;
+
+        // *width -= (frame_crop_left_offset + frame_crop_right_offset) * cropUnitX;
+        if(__builtin_add_overflow(frame_crop_left_offset, frame_crop_right_offset, &frame_crop_left_offset) ||
+            __builtin_mul_overflow(frame_crop_left_offset, cropUnitX, &frame_crop_left_offset) ||
+            __builtin_sub_overflow(*width, frame_crop_left_offset, width) ||
+            *width < 0) {
+            *width = 0;
+        }
+
+        //*height -= (frame_crop_top_offset + frame_crop_bottom_offset) * cropUnitY;
+        if(__builtin_add_overflow(frame_crop_top_offset, frame_crop_bottom_offset, &frame_crop_top_offset) ||
+            __builtin_mul_overflow(frame_crop_top_offset, cropUnitY, &frame_crop_top_offset) ||
+            __builtin_sub_overflow(*height, frame_crop_top_offset, height) ||
+            *height < 0) {
+            *height = 0;
+        }
     }
 
     if (sarWidth != NULL) {
diff --git a/media/libstagefright/foundation/Android.bp b/media/libstagefright/foundation/Android.bp
index eeeb284..91462c8 100644
--- a/media/libstagefright/foundation/Android.bp
+++ b/media/libstagefright/foundation/Android.bp
@@ -1,35 +1,6 @@
-COMMON_SRCS = [
-        "AAtomizer.cpp",
-        "ABitReader.cpp",
-        "ABuffer.cpp",
-        "ADebug.cpp",
-        "AHandler.cpp",
-        "AHierarchicalStateMachine.cpp",
-        "ALooper.cpp",
-        "ALooperRoster.cpp",
-        "AMessage.cpp",
-        "ANetworkSession.cpp",
-        "AString.cpp",
-        "AStringUtils.cpp",
-        "ColorUtils.cpp",
-        "MediaBuffer.cpp",
-        "MediaBufferGroup.cpp",
-        "MetaData.cpp",
-        "ParsedMessage.cpp",
-        "base64.cpp",
-        "hexdump.cpp",
-]
-
-COMMON_LIBS = [
-        "libbinder",
-        "libutils",
-        "libui",
-        "libcutils",
-        "liblog",
-]
-
-cc_defaults {
-    name: "libstagefright_foundation-defaults",
+cc_library_shared {
+    name: "libstagefright_foundation",
+    vendor_available: true,
 
     include_dirs: [
         "frameworks/av/include",
@@ -59,6 +30,45 @@
         "-Wall",
     ],
 
+    shared_libs: [
+        "libbinder",
+        "libutils",
+        "libui",
+        "libcutils",
+        "liblog",
+        "libpowermanager",
+    ],
+
+    srcs: [
+        "AAtomizer.cpp",
+        "ABitReader.cpp",
+        "ABuffer.cpp",
+        "ADebug.cpp",
+        "AHandler.cpp",
+        "AHierarchicalStateMachine.cpp",
+        "ALooper.cpp",
+        "ALooperRoster.cpp",
+        "AMessage.cpp",
+        "ANetworkSession.cpp",
+        "AString.cpp",
+        "AStringUtils.cpp",
+        "AWakeLock.cpp",
+        "ColorUtils.cpp",
+        "MediaBuffer.cpp",
+        "MediaBufferGroup.cpp",
+        "MetaData.cpp",
+        "ParsedMessage.cpp",
+        "base64.cpp",
+        "hexdump.cpp",
+    ],
+
+    target: {
+        vendor: {
+            exclude_shared_libs: ["libpowermanager"],
+            exclude_srcs: ["AWakeLock.cpp"],
+        },
+    },
+
     clang: true,
 
     sanitize: {
@@ -72,20 +82,3 @@
         },
     },
 }
-
-cc_library_shared {
-    name: "libstagefright_foundation",
-    defaults: ["libstagefright_foundation-defaults"],
-
-    srcs: COMMON_SRCS + ["AWakeLock.cpp"],
-    shared_libs: COMMON_LIBS + ["libpowermanager"],
-}
-
-cc_library_shared {
-    name: "libstagefright_foundation_vendor",
-    defaults: ["libstagefright_foundation-defaults"],
-    vendor: true,
-
-    srcs: COMMON_SRCS,
-    shared_libs: COMMON_LIBS,
-}
diff --git a/media/libstagefright/include/MPEG4Extractor.h b/media/libstagefright/include/MPEG4Extractor.h
index f847119..1efe6b9 100644
--- a/media/libstagefright/include/MPEG4Extractor.h
+++ b/media/libstagefright/include/MPEG4Extractor.h
@@ -82,6 +82,9 @@
         sp<SampleTable> sampleTable;
         bool includes_expensive_metadata;
         bool skipTrack;
+        bool has_elst;
+        int64_t elst_media_time;
+        uint64_t elst_segment_duration;
     };
 
     Vector<SidxEntry> mSidxEntries;
diff --git a/media/libstagefright/include/media/stagefright/DataUriSource.h b/media/libstagefright/include/media/stagefright/DataUriSource.h
deleted file mode 100644
index d223c06..0000000
--- a/media/libstagefright/include/media/stagefright/DataUriSource.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (C) 2011 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-#ifndef DATA_URI_SOURCE_H_
-
-#define DATA_URI_SOURCE_H_
-
-#include <stdio.h>
-
-#include <media/stagefright/DataSource.h>
-#include <media/stagefright/MediaErrors.h>
-#include <media/stagefright/foundation/AString.h>
-
-namespace android {
-
-class DataUriSource : public DataSource {
-public:
-    DataUriSource(const char *uri);
-
-    virtual status_t initCheck() const {
-        return mInited;
-    }
-
-    virtual ssize_t readAt(off64_t offset, void *data, size_t size);
-
-    virtual status_t getSize(off64_t *size) {
-        if (mInited != OK) {
-            return mInited;
-        }
-
-        *size = mData.size();
-        return OK;
-    }
-
-    virtual String8 getUri() {
-        return mDataUri;
-    }
-
-    virtual String8 getMIMEType() const {
-        return mMimeType;
-    }
-
-protected:
-    virtual ~DataUriSource() {
-        // Nothing to delete.
-    }
-
-private:
-    const String8 mDataUri;
-
-    String8 mMimeType;
-    // Use AString because individual bytes may not be valid UTF8 chars.
-    AString mData;
-    status_t mInited;
-
-    // Disallow copy and assign.
-    DataUriSource(const DataUriSource &);
-    DataUriSource &operator=(const DataUriSource &);
-};
-
-}  // namespace android
-
-#endif  // DATA_URI_SOURCE_H_
diff --git a/media/libstagefright/omx/Android.bp b/media/libstagefright/omx/Android.bp
index ff5b841..2d921f9 100644
--- a/media/libstagefright/omx/Android.bp
+++ b/media/libstagefright/omx/Android.bp
@@ -1,5 +1,6 @@
 cc_library_shared {
     name: "libstagefright_omx",
+    vendor_available: true,
 
     srcs: [
         "FrameDropper.cpp",
@@ -25,16 +26,19 @@
     ],
 
     include_dirs: [
+        "frameworks/av/include", // for media/vndk/xmlparser/1.0/MediaCodecsXmlParser.h
+        "frameworks/av/include/media/",
         "frameworks/av/media/libstagefright",
+        "frameworks/av/media/libstagefright/include",
+        "frameworks/native/include", // for media/hardware/MetadataBufferType.h
         "frameworks/native/include/media/hardware",
-        // TODO: export this?
         "frameworks/native/include/media/openmax",
     ],
 
     shared_libs: [
         "libbase",
         "libbinder",
-        "libmedia",
+        "libmedia_omx",
         "libutils",
         "liblog",
         "libui",
@@ -45,8 +49,10 @@
         "libhidlbase",
         "libhidlmemory",
         "libhidltransport",
+        "libnativewindow", // TODO(b/62923479): use header library
         "libstagefright_xmlparser@1.0",
         "android.hidl.memory@1.0",
+        "android.hidl.token@1.0-utils",
         "android.hardware.media@1.0",
         "android.hardware.media.omx@1.0",
         "android.hardware.graphics.common@1.0",
@@ -74,6 +80,27 @@
     },
 }
 
+cc_library_static {
+    name: "libstagefright_omx_utils",
+    srcs: ["OMXUtils.cpp"],
+    include_dirs: [
+        "frameworks/av/media/libstagefright",
+        "frameworks/native/include/media/hardware",
+        "frameworks/native/include/media/openmax",
+    ],
+    shared_libs: ["libmedia"],
+    sanitize: {
+        misc_undefined: [
+            "signed-integer-overflow",
+            "unsigned-integer-overflow",
+        ],
+        cfi: true,
+        diag: {
+            cfi: true,
+        },
+    },
+}
+
 //###############################################################################
 
 subdirs = ["tests"]
diff --git a/media/ndk/include/media/NdkMediaCodec.h b/media/ndk/include/media/NdkMediaCodec.h
index 7e7e81e..12e8f0f 100644
--- a/media/ndk/include/media/NdkMediaCodec.h
+++ b/media/ndk/include/media/NdkMediaCodec.h
@@ -149,6 +149,7 @@
 
 #if (defined(__cplusplus) && __cplusplus >= 201103L) || \
     __STDC_VERSION__ >= 201112L
+#include <assert.h>
 static_assert(sizeof(_off_t_compat) == sizeof(long),
               "_off_t_compat does not match the NDK ABI. See "
               "https://github.com/android-ndk/ndk/issues/459.");
@@ -208,6 +209,8 @@
 media_status_t AMediaCodec_releaseOutputBufferAtTime(
         AMediaCodec *mData, size_t idx, int64_t timestampNs);
 
+#if __ANDROID_API__ >= 26
+
 /**
  * Creates a Surface that can be used as the input to encoder, in place of input buffers
  *
@@ -278,7 +281,7 @@
  */
 media_status_t AMediaCodec_signalEndOfInputStream(AMediaCodec *mData);
 
-
+#endif /* __ANDROID_API__ >= 26 */
 
 typedef enum {
     AMEDIACODECRYPTOINFO_MODE_CLEAR = 0,
diff --git a/media/vndk/Android.bp b/media/vndk/Android.bp
index a233d6c..e93fd16 100644
--- a/media/vndk/Android.bp
+++ b/media/vndk/Android.bp
@@ -1,4 +1,4 @@
 subdirs = [
-    "*",
+    "xmlparser/1.0",
 ]
 
diff --git a/media/vndk/xmlparser/1.0/Android.bp b/media/vndk/xmlparser/1.0/Android.bp
index c48703c..2f10cb1 100644
--- a/media/vndk/xmlparser/1.0/Android.bp
+++ b/media/vndk/xmlparser/1.0/Android.bp
@@ -1,6 +1,6 @@
 cc_library_shared {
-
     name: "libstagefright_xmlparser@1.0",
+    vendor_available: true,
 
     srcs: [
         "MediaCodecsXmlParser.cpp",
diff --git a/media/vndk/xmlparser/Android.bp b/media/vndk/xmlparser/Android.bp
deleted file mode 100644
index a233d6c..0000000
--- a/media/vndk/xmlparser/Android.bp
+++ /dev/null
@@ -1,4 +0,0 @@
-subdirs = [
-    "*",
-]
-
diff --git a/services/audiopolicy/common/managerdefinitions/include/AudioPort.h b/services/audiopolicy/common/managerdefinitions/include/AudioPort.h
index ded2285..4f79ed2 100644
--- a/services/audiopolicy/common/managerdefinitions/include/AudioPort.h
+++ b/services/audiopolicy/common/managerdefinitions/include/AudioPort.h
@@ -71,7 +71,7 @@
 
     virtual void toAudioPort(struct audio_port *port) const;
 
-    virtual void importAudioPort(const sp<AudioPort>& port);
+    virtual void importAudioPort(const sp<AudioPort>& port, bool force = false);
 
     void addAudioProfile(const sp<AudioProfile> &profile) { mProfiles.add(profile); }
 
diff --git a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
index 9a52d22..1a644d7 100644
--- a/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
+++ b/services/audiopolicy/common/managerdefinitions/include/DeviceDescriptor.h
@@ -48,7 +48,7 @@
     // AudioPort
     virtual void attach(const sp<HwModule>& module);
     virtual void toAudioPort(struct audio_port *port) const;
-    virtual void importAudioPort(const sp<AudioPort>& port);
+    virtual void importAudioPort(const sp<AudioPort>& port, bool force = false);
 
     audio_port_handle_t getId() const;
     status_t dump(int fd, int spaces, int index, bool verbose = true) const;
diff --git a/services/audiopolicy/common/managerdefinitions/src/AudioPort.cpp b/services/audiopolicy/common/managerdefinitions/src/AudioPort.cpp
index 6ed2cb7..fcf9070 100644
--- a/services/audiopolicy/common/managerdefinitions/src/AudioPort.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/AudioPort.cpp
@@ -128,7 +128,7 @@
     port->num_gains = i;
 }
 
-void AudioPort::importAudioPort(const sp<AudioPort>& port)
+void AudioPort::importAudioPort(const sp<AudioPort>& port, bool force __unused)
 {
     size_t indexToImport;
     for (indexToImport = 0; indexToImport < port->mProfiles.size(); indexToImport++) {
diff --git a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
index f0e48b6..a2c1165 100644
--- a/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
+++ b/services/audiopolicy/common/managerdefinitions/src/DeviceDescriptor.cpp
@@ -263,7 +263,10 @@
     strncpy(port->ext.device.address, mAddress.string(), AUDIO_DEVICE_MAX_ADDRESS_LEN);
 }
 
-void DeviceDescriptor::importAudioPort(const sp<AudioPort>& port) {
+void DeviceDescriptor::importAudioPort(const sp<AudioPort>& port, bool force) {
+    if (!force && !port->hasDynamicAudioProfile()) {
+        return;
+    }
     AudioPort::importAudioPort(port);
     port->pickAudioProfile(mSamplingRate, mChannelMask, mFormat);
 }
diff --git a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
index e8e531a..d9859ea 100644
--- a/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
+++ b/services/audiopolicy/managerdefault/AudioPolicyManager.cpp
@@ -3647,7 +3647,7 @@
                         sp<DeviceDescriptor> devDesc = mAvailableInputDevices[index];
                         if (!devDesc->isAttached()) {
                             devDesc->attach(mHwModules[i]);
-                            devDesc->importAudioPort(inProfile);
+                            devDesc->importAudioPort(inProfile, true);
                         }
                     }
                 }
@@ -4010,8 +4010,8 @@
                 continue;
             }
 
-            ALOGV("opening output for device %08x with params %s profile %p",
-                                                      device, address.string(), profile.get());
+            ALOGV("opening output for device %08x with params %s profile %p name %s",
+                  device, address.string(), profile.get(), profile->getName().string());
             desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
             desc->mDevice = device;
             audio_config_t config = AUDIO_CONFIG_INITIALIZER;
@@ -4260,6 +4260,10 @@
             config.channel_mask = desc->mChannelMask;
             config.format = desc->mFormat;
             audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
+
+            ALOGV("opening inputput for device %08x with params %s profile %p name %s",
+                  desc->mDevice, address.string(), profile.get(), profile->getName().string());
+
             status_t status = mpClientInterface->openInput(profile->getModuleHandle(),
                                                            &input,
                                                            &config,
diff --git a/services/camera/libcameraservice/CameraService.cpp b/services/camera/libcameraservice/CameraService.cpp
index c2b71a2..c175259 100644
--- a/services/camera/libcameraservice/CameraService.cpp
+++ b/services/camera/libcameraservice/CameraService.cpp
@@ -231,29 +231,33 @@
 
     for (auto& cameraId : mCameraProviderManager->getCameraDeviceIds()) {
         String8 id8 = String8(cameraId.c_str());
+        bool cameraFound = false;
         {
+
             Mutex::Autolock lock(mCameraStatesLock);
             auto iter = mCameraStates.find(id8);
             if (iter != mCameraStates.end()) {
-                continue;
+                cameraFound = true;
             }
         }
 
-        hardware::camera::common::V1_0::CameraResourceCost cost;
-        res = mCameraProviderManager->getResourceCost(cameraId, &cost);
-        if (res != OK) {
-            ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
-            continue;
-        }
-        std::set<String8> conflicting;
-        for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
-            conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
-        }
+        if (!cameraFound) {
+            hardware::camera::common::V1_0::CameraResourceCost cost;
+            res = mCameraProviderManager->getResourceCost(cameraId, &cost);
+            if (res != OK) {
+                ALOGE("Failed to query device resource cost: %s (%d)", strerror(-res), res);
+                continue;
+            }
+            std::set<String8> conflicting;
+            for (size_t i = 0; i < cost.conflictingDevices.size(); i++) {
+                conflicting.emplace(String8(cost.conflictingDevices[i].c_str()));
+            }
 
-        {
-            Mutex::Autolock lock(mCameraStatesLock);
-            mCameraStates.emplace(id8,
-                std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
+            {
+                Mutex::Autolock lock(mCameraStatesLock);
+                mCameraStates.emplace(id8,
+                    std::make_shared<CameraState>(id8, cost.resourceCost, conflicting));
+            }
         }
 
         onDeviceStatusChanged(id8, CameraDeviceStatus::PRESENT);
diff --git a/services/camera/libcameraservice/device1/CameraHardwareInterface.cpp b/services/camera/libcameraservice/device1/CameraHardwareInterface.cpp
index 469c86c..b7f7af0 100644
--- a/services/camera/libcameraservice/device1/CameraHardwareInterface.cpp
+++ b/services/camera/libcameraservice/device1/CameraHardwareInterface.cpp
@@ -108,11 +108,13 @@
         ALOGE("%s: CameraHeapMemory has FD %d (expect >= 0)", __FUNCTION__, memPoolId);
         return 0;
     }
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     mHidlMemPoolMap.insert(std::make_pair(memPoolId, mem));
     return memPoolId;
 }
 
 hardware::Return<void> CameraHardwareInterface::unregisterMemory(uint32_t memId) {
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     if (mHidlMemPoolMap.count(memId) == 0) {
         ALOGE("%s: memory pool ID %d not found", __FUNCTION__, memId);
         return hardware::Void();
@@ -126,6 +128,7 @@
 hardware::Return<void> CameraHardwareInterface::dataCallback(
         DataCallbackMsg msgType, uint32_t data, uint32_t bufferIndex,
         const hardware::camera::device::V1_0::CameraFrameMetadata& metadata) {
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     if (mHidlMemPoolMap.count(data) == 0) {
         ALOGE("%s: memory pool ID %d not found", __FUNCTION__, data);
         return hardware::Void();
@@ -140,6 +143,7 @@
 hardware::Return<void> CameraHardwareInterface::dataCallbackTimestamp(
         DataCallbackMsg msgType, uint32_t data,
         uint32_t bufferIndex, int64_t timestamp) {
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     if (mHidlMemPoolMap.count(data) == 0) {
         ALOGE("%s: memory pool ID %d not found", __FUNCTION__, data);
         return hardware::Void();
@@ -151,6 +155,7 @@
 hardware::Return<void> CameraHardwareInterface::handleCallbackTimestamp(
         DataCallbackMsg msgType, const hidl_handle& frameData, uint32_t data,
         uint32_t bufferIndex, int64_t timestamp) {
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     if (mHidlMemPoolMap.count(data) == 0) {
         ALOGE("%s: memory pool ID %d not found", __FUNCTION__, data);
         return hardware::Void();
@@ -169,6 +174,7 @@
     std::vector<android::HandleTimestampMessage> msgs;
     msgs.reserve(messages.size());
 
+    std::lock_guard<std::mutex> lock(mHidlMemPoolMapLock);
     for (const auto& hidl_msg : messages) {
         if (mHidlMemPoolMap.count(hidl_msg.data) == 0) {
             ALOGE("%s: memory pool ID %d not found", __FUNCTION__, hidl_msg.data);
diff --git a/services/camera/libcameraservice/device1/CameraHardwareInterface.h b/services/camera/libcameraservice/device1/CameraHardwareInterface.h
index 1c38d00..2f1e2e9 100644
--- a/services/camera/libcameraservice/device1/CameraHardwareInterface.h
+++ b/services/camera/libcameraservice/device1/CameraHardwareInterface.h
@@ -523,6 +523,7 @@
     uint64_t mNextBufferId = 1;
     static const uint64_t BUFFER_ID_NO_BUFFER = 0;
 
+    std::mutex mHidlMemPoolMapLock; // protecting mHidlMemPoolMap
     std::unordered_map<int, camera_memory_t*> mHidlMemPoolMap;
 };
 
diff --git a/services/camera/libcameraservice/device3/Camera3Device.cpp b/services/camera/libcameraservice/device3/Camera3Device.cpp
index e8b9b20..0c83ed0 100644
--- a/services/camera/libcameraservice/device3/Camera3Device.cpp
+++ b/services/camera/libcameraservice/device3/Camera3Device.cpp
@@ -2326,7 +2326,11 @@
     if (res < 0) return res;
 
     if (mInFlightMap.size() == 1) {
-        mStatusTracker->markComponentActive(mInFlightStatusId);
+        // hold mLock to prevent race with disconnect
+        Mutex::Autolock l(mLock);
+        if (mStatusTracker != nullptr) {
+            mStatusTracker->markComponentActive(mInFlightStatusId);
+        }
     }
 
     return OK;
@@ -2353,7 +2357,11 @@
 
     // Indicate idle inFlightMap to the status tracker
     if (mInFlightMap.size() == 0) {
-        mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
+        // hold mLock to prevent race with disconnect
+        Mutex::Autolock l(mLock);
+        if (mStatusTracker != nullptr) {
+            mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
+        }
     }
 }
 
diff --git a/services/mediacodec/Android.mk b/services/mediacodec/Android.mk
index d3df52c..6997b5a 100644
--- a/services/mediacodec/Android.mk
+++ b/services/mediacodec/Android.mk
@@ -4,46 +4,52 @@
 include $(CLEAR_VARS)
 LOCAL_SRC_FILES := MediaCodecService.cpp
 LOCAL_SHARED_LIBRARIES := \
-    libmedia \
+    libmedia_omx \
     libbinder \
     libgui \
     libutils \
     liblog \
     libstagefright_omx
 LOCAL_C_INCLUDES := \
+    frameworks/av/include \
     frameworks/av/media/libstagefright \
+    frameworks/av/media/libstagefright/include \
+    frameworks/native/include \
     frameworks/native/include/media/openmax
 LOCAL_MODULE:= libmediacodecservice
+LOCAL_VENDOR_MODULE := true
 LOCAL_32_BIT_ONLY := true
 include $(BUILD_SHARED_LIBRARY)
 
-
 # service executable
 include $(CLEAR_VARS)
 LOCAL_REQUIRED_MODULES_arm := mediacodec.policy
 LOCAL_SRC_FILES := main_codecservice.cpp
 LOCAL_SHARED_LIBRARIES := \
-    libmedia \
+    libmedia_omx \
     libmediacodecservice \
     libbinder \
     libutils \
     libgui \
     liblog \
     libbase \
-    libavservices_minijail \
+    libavservices_minijail_vendor \
     libcutils \
     libhwbinder \
     libhidltransport \
     libstagefright_omx \
     android.hardware.media.omx@1.0 \
     android.hidl.memory@1.0
+
 LOCAL_C_INCLUDES := \
+    frameworks/av/include \
     frameworks/av/media/libstagefright \
     frameworks/av/media/libstagefright/include \
+    frameworks/native/include \
     frameworks/native/include/media/openmax
 LOCAL_MODULE := android.hardware.media.omx@1.0-service
 LOCAL_MODULE_RELATIVE_PATH := hw
-LOCAL_PROPRIETARY_MODULE := true
+LOCAL_VENDOR_MODULE := true
 LOCAL_32_BIT_ONLY := true
 LOCAL_INIT_RC := android.hardware.media.omx@1.0-service.rc
 include $(BUILD_EXECUTABLE)
diff --git a/services/minijail/Android.mk b/services/minijail/Android.mk
index 3e63f97..b6fcacc 100644
--- a/services/minijail/Android.mk
+++ b/services/minijail/Android.mk
@@ -8,6 +8,14 @@
 LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
 include $(BUILD_SHARED_LIBRARY)
 
+# Small library for media.extractor and media.codec sandboxing.
+include $(CLEAR_VARS)
+LOCAL_MODULE := libavservices_minijail_vendor
+LOCAL_VENDOR_MODULE := true
+LOCAL_SRC_FILES := minijail.cpp
+LOCAL_SHARED_LIBRARIES := libbase libminijail_vendor
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)
+include $(BUILD_SHARED_LIBRARY)
 
 # Unit tests.
 include $(CLEAR_VARS)