Camera: default implementation of device 3.2

Test: compile
Bug: 30985004
Change-Id: Ibb48673840de6a5f7c75dc6993d5457a272177a2
diff --git a/camera/device/3.2/default/Android.bp b/camera/device/3.2/default/Android.bp
new file mode 100644
index 0000000..9820220
--- /dev/null
+++ b/camera/device/3.2/default/Android.bp
@@ -0,0 +1,22 @@
+cc_library_shared {
+    name: "android.hardware.camera.device@3.2-impl",
+    srcs: ["CameraDevice.cpp",
+           "CameraDeviceSession.cpp",
+           "convert.cpp"],
+    shared_libs: [
+        "libhidlbase",
+        "libhidltransport",
+        "libhwbinder",
+        "libutils",
+        "libcutils",
+        "android.hardware.camera.device@3.2",
+        "android.hardware.camera.provider@2.4",
+        "liblog",
+        "libhardware",
+        "libcamera_metadata"
+    ],
+    static_libs: [
+        "android.hardware.camera.common@1.0-helper"
+    ],
+    export_include_dirs: ["."]
+}
diff --git a/camera/device/3.2/default/CameraDevice.cpp b/camera/device/3.2/default/CameraDevice.cpp
new file mode 100644
index 0000000..51a29ec
--- /dev/null
+++ b/camera/device/3.2/default/CameraDevice.cpp
@@ -0,0 +1,285 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define LOG_TAG "CamDev@3.2-impl"
+#include <android/log.h>
+
+#include <utils/Vector.h>
+#include <utils/Trace.h>
+#include "CameraDevice.h"
+#include <include/convert.h>
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+using ::android::hardware::camera::common::V1_0::Status;
+
+CameraDevice::CameraDevice(
+    sp<CameraModule> module, const std::string& cameraId,
+    const SortedVector<std::pair<std::string, std::string>>& cameraDeviceNames) :
+        mModule(module),
+        mCameraId(cameraId),
+        mDisconnected(false),
+        mCameraDeviceNames(cameraDeviceNames) {
+    mCameraIdInt = atoi(mCameraId.c_str());
+    // Should not reach here as provider also validate ID
+    if (mCameraIdInt < 0 || mCameraIdInt >= module->getNumberOfCameras()) {
+        ALOGE("%s: Invalid camera id: %s", __FUNCTION__, mCameraId.c_str());
+        mInitFail = true;
+    }
+
+    mDeviceVersion = mModule->getDeviceVersion(mCameraIdInt);
+    if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
+        ALOGE("%s: Camera id %s does not support HAL3.2+",
+                __FUNCTION__, mCameraId.c_str());
+        mInitFail = true;
+    }
+}
+
+CameraDevice::~CameraDevice() {}
+
+Status CameraDevice::initStatus() const {
+    Mutex::Autolock _l(mLock);
+    Status status = Status::OK;
+    if (mInitFail) {
+        status = Status::INTERNAL_ERROR;
+    } else if (mDisconnected) {
+        status = Status::CAMERA_DISCONNECTED;
+    }
+    return status;
+}
+
+void CameraDevice::setConnectionStatus(bool connected) {
+    Mutex::Autolock _l(mLock);
+    mDisconnected = !connected;
+    if (mSession == nullptr) {
+        return;
+    }
+    sp<CameraDeviceSession> session = mSession.promote();
+    if (session == nullptr) {
+        return;
+    }
+    // Only notify active session disconnect events.
+    // Users will need to re-open camera after disconnect event
+    if (!connected) {
+        session->disconnect();
+    }
+    return;
+}
+
+Status CameraDevice::getHidlStatus(int status) {
+    switch (status) {
+        case 0: return Status::OK;
+        case -ENOSYS: return Status::OPERATION_NOT_SUPPORTED;
+        case -EBUSY : return Status::CAMERA_IN_USE;
+        case -EUSERS: return Status::MAX_CAMERAS_IN_USE;
+        case -ENODEV: return Status::INTERNAL_ERROR;
+        case -EINVAL: return Status::ILLEGAL_ARGUMENT;
+        default:
+            ALOGE("%s: unknown HAL status code %d", __FUNCTION__, status);
+            return Status::INTERNAL_ERROR;
+    }
+}
+
+// Methods from ::android::hardware::camera::device::V3_2::ICameraDevice follow.
+Return<void> CameraDevice::getResourceCost(getResourceCost_cb _hidl_cb)  {
+    Status status = initStatus();
+    CameraResourceCost resCost;
+    if (status == Status::OK) {
+        int cost = 100;
+        std::vector<std::string> conflicting_devices;
+        struct camera_info info;
+
+        // If using post-2.4 module version, query the cost + conflicting devices from the HAL
+        if (mModule->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_4) {
+            int ret = mModule->getCameraInfo(mCameraIdInt, &info);
+            if (ret == OK) {
+                cost = info.resource_cost;
+                for (size_t i = 0; i < info.conflicting_devices_length; i++) {
+                    std::string cameraId(info.conflicting_devices[i]);
+                    for (const auto& pair : mCameraDeviceNames) {
+                        if (cameraId == pair.first) {
+                            conflicting_devices.push_back(pair.second);
+                        }
+                    }
+                }
+            } else {
+                status = Status::INTERNAL_ERROR;
+            }
+        }
+
+        if (status == Status::OK) {
+            resCost.resourceCost = cost;
+            resCost.conflictingDevices.resize(conflicting_devices.size());
+            for (size_t i = 0; i < conflicting_devices.size(); i++) {
+                resCost.conflictingDevices[i] = conflicting_devices[i];
+                ALOGV("CamDevice %s is conflicting with camDevice %s",
+                        mCameraId.c_str(), resCost.conflictingDevices[i].c_str());
+            }
+        }
+    }
+    _hidl_cb(status, resCost);
+    return Void();
+}
+
+Return<void> CameraDevice::getCameraCharacteristics(getCameraCharacteristics_cb _hidl_cb)  {
+    Status status = initStatus();
+    CameraMetadata cameraCharacteristics;
+    if (status == Status::OK) {
+        //Module 2.1+ codepath.
+        struct camera_info info;
+        int ret = mModule->getCameraInfo(mCameraIdInt, &info);
+        if (ret == OK) {
+            convertToHidl(info.static_camera_characteristics, &cameraCharacteristics);
+        } else {
+            ALOGE("%s: get camera info failed!", __FUNCTION__);
+            status = Status::INTERNAL_ERROR;
+        }
+    }
+    _hidl_cb(status, cameraCharacteristics);
+    return Void();
+}
+
+Return<Status> CameraDevice::setTorchMode(TorchMode mode)  {
+    if (!mModule->isSetTorchModeSupported()) {
+        return Status::METHOD_NOT_SUPPORTED;
+    }
+
+    Status status = initStatus();
+    if (status == Status::OK) {
+        bool enable = (mode == TorchMode::ON) ? true : false;
+        status = getHidlStatus(mModule->setTorchMode(mCameraId.c_str(), enable));
+    }
+    return status;
+}
+
+Return<void> CameraDevice::open(const sp<ICameraDeviceCallback>& callback, open_cb _hidl_cb)  {
+    Status status = initStatus();
+    sp<CameraDeviceSession> session = nullptr;
+
+    if (callback == nullptr) {
+        ALOGE("%s: cannot open camera %s. callback is null!",
+                __FUNCTION__, mCameraId.c_str());
+        _hidl_cb(Status::ILLEGAL_ARGUMENT, session);
+        return Void();
+    }
+
+    if (status != Status::OK) {
+        // Provider will never pass initFailed device to client, so
+        // this must be a disconnected camera
+        ALOGE("%s: cannot open camera %s. camera is disconnected!",
+                __FUNCTION__, mCameraId.c_str());
+        _hidl_cb(Status::CAMERA_DISCONNECTED, session);
+        return Void();
+    } else {
+        mLock.lock();
+
+        ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mCameraIdInt);
+        session = mSession.promote();
+        if (session != nullptr && !session->isClosed()) {
+            ALOGE("%s: cannot open an already opened camera!", __FUNCTION__);
+            mLock.unlock();
+            _hidl_cb(Status::CAMERA_IN_USE, nullptr);
+            return Void();
+        }
+
+        /** Open HAL device */
+        status_t res;
+        camera3_device_t *device;
+
+        ATRACE_BEGIN("camera3->open");
+        res = mModule->open(mCameraId.c_str(),
+                reinterpret_cast<hw_device_t**>(&device));
+        ATRACE_END();
+
+        if (res != OK) {
+            ALOGE("%s: cannot open camera %s!", __FUNCTION__, mCameraId.c_str());
+            mLock.unlock();
+            _hidl_cb(Status::INTERNAL_ERROR, nullptr);
+            return Void();
+        }
+
+        /** Cross-check device version */
+        if (device->common.version < CAMERA_DEVICE_API_VERSION_3_2) {
+            ALOGE("%s: Could not open camera: "
+                    "Camera device should be at least %x, reports %x instead",
+                    __FUNCTION__,
+                    CAMERA_DEVICE_API_VERSION_3_2,
+                    device->common.version);
+            device->common.close(&device->common);
+            mLock.unlock();
+            _hidl_cb(Status::ILLEGAL_ARGUMENT, nullptr);
+            return Void();
+        }
+
+        session = new CameraDeviceSession(device, callback);
+        if (session == nullptr) {
+            ALOGE("%s: camera device session allocation failed", __FUNCTION__);
+            mLock.unlock();
+            _hidl_cb(Status::INTERNAL_ERROR, nullptr);
+            return Void();
+        }
+        if (session->isInitFailed()) {
+            ALOGE("%s: camera device session init failed", __FUNCTION__);
+            session = nullptr;
+            mLock.unlock();
+            _hidl_cb(Status::INTERNAL_ERROR, nullptr);
+            return Void();
+        }
+        mSession = session;
+        mLock.unlock();
+    }
+    _hidl_cb(status, session);
+    return Void();
+}
+
+Return<void> CameraDevice::dumpState(const ::android::hardware::hidl_handle& handle)  {
+    Mutex::Autolock _l(mLock);
+    if (handle.getNativeHandle() == nullptr) {
+        ALOGE("%s: handle must not be null", __FUNCTION__);
+        return Void();
+    }
+    if (handle->numFds != 1 || handle->numInts != 0) {
+        ALOGE("%s: handle must contain 1 FD and 0 integers! Got %d FDs and %d ints",
+                __FUNCTION__, handle->numFds, handle->numInts);
+        return Void();
+    }
+    int fd = handle->data[0];
+    if (mSession == nullptr) {
+        dprintf(fd, "No active camera device session instance\n");
+        return Void();
+    }
+    sp<CameraDeviceSession> session = mSession.promote();
+    if (session == nullptr) {
+        dprintf(fd, "No active camera device session instance\n");
+        return Void();
+    }
+    // Call into active session to dump states
+    session->dumpState(handle);
+    return Void();
+}
+// End of methods from ::android::hardware::camera::device::V3_2::ICameraDevice.
+
+} // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
diff --git a/camera/device/3.2/default/CameraDevice.h b/camera/device/3.2/default/CameraDevice.h
new file mode 100644
index 0000000..317eea5
--- /dev/null
+++ b/camera/device/3.2/default/CameraDevice.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright (C) 2016 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 ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE_H
+#define ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE_H
+
+#include "utils/Mutex.h"
+#include "CameraModule.h"
+#include "CameraMetadata.h"
+#include "CameraDeviceSession.h"
+
+#include <android/hardware/camera/device/3.2/ICameraDevice.h>
+#include <hidl/Status.h>
+#include <hidl/MQDescriptor.h>
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+using ::android::hardware::camera::device::V3_2::RequestTemplate;
+using ::android::hardware::camera::device::V3_2::ICameraDevice;
+using ::android::hardware::camera::device::V3_2::ICameraDeviceCallback;
+using ::android::hardware::camera::device::V3_2::ICameraDeviceSession;
+using ::android::hardware::camera::common::V1_0::CameraResourceCost;
+using ::android::hardware::camera::common::V1_0::Status;
+using ::android::hardware::camera::common::V1_0::TorchMode;
+using ::android::hardware::camera::common::V1_0::helper::CameraModule;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+using ::android::Mutex;
+
+/*
+ * The camera device HAL implementation is opened lazily (via the open call)
+ */
+struct CameraDevice : public ICameraDevice {
+    // Called by provider HAL. Provider HAL must ensure the uniqueness of
+    // CameraDevice object per cameraId, or there could be multiple CameraDevice
+    // trying to access the same physical camera.
+    // Also, provider will have to keep track of all CameraDevice object in
+    // order to notify CameraDevice when the underlying camera is detached
+    CameraDevice(sp<CameraModule> module,
+                 const std::string& cameraId,
+                 const SortedVector<std::pair<std::string, std::string>>& cameraDeviceNames);
+    ~CameraDevice();
+    // Caller must use this method to check if CameraDevice ctor failed
+    bool isInitFailed() { return mInitFail; }
+    // Used by provider HAL to signal external camera disconnected
+    void setConnectionStatus(bool connected);
+
+    /* Methods from ::android::hardware::camera::device::V3_2::ICameraDevice follow. */
+    // The following method can be called without opening the actual camera device
+    Return<void> getResourceCost(getResourceCost_cb _hidl_cb) override;
+    Return<void> getCameraCharacteristics(getCameraCharacteristics_cb _hidl_cb) override;
+    Return<Status> setTorchMode(TorchMode mode) override;
+
+    // Open the device HAL and also return a default capture session
+    Return<void> open(const sp<ICameraDeviceCallback>& callback, open_cb _hidl_cb) override;
+
+
+    // Forward the dump call to the opened session, or do nothing
+    Return<void> dumpState(const ::android::hardware::hidl_handle& fd) override;
+    /* End of Methods from ::android::hardware::camera::device::V3_2::ICameraDevice */
+
+private:
+    // Passed from provider HAL. Should not change.
+    sp<CameraModule> mModule;
+    const std::string mCameraId;
+    // const after ctor
+    int   mCameraIdInt;
+    int   mDeviceVersion;
+    bool  mInitFail = false;
+    // Set by provider (when external camera is connected/disconnected)
+    bool  mDisconnected;
+    wp<CameraDeviceSession> mSession = nullptr;
+
+    const SortedVector<std::pair<std::string, std::string>>& mCameraDeviceNames;
+
+    // gating access to mSession and mDisconnected
+    mutable Mutex mLock;
+
+    // convert conventional HAL status to HIDL Status
+    static Status getHidlStatus(int);
+
+    Status initStatus() const;
+};
+
+}  // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
+
+#endif  // ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE_H
diff --git a/camera/device/3.2/default/CameraDeviceSession.cpp b/camera/device/3.2/default/CameraDeviceSession.cpp
new file mode 100644
index 0000000..7e43cd7
--- /dev/null
+++ b/camera/device/3.2/default/CameraDeviceSession.cpp
@@ -0,0 +1,646 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define LOG_TAG "CamDevSession@3.2-impl"
+#include <android/log.h>
+
+#include <utils/Trace.h>
+#include <hardware/gralloc.h>
+#include <hardware/gralloc1.h>
+#include "CameraDeviceSession.h"
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+namespace {
+
+// Copy pasted from Hwc.cpp. Use this until gralloc mapper HAL is working
+class HandleImporter {
+public:
+    HandleImporter() : mInitialized(false) {}
+
+    bool initialize()
+    {
+        // allow only one client
+        if (mInitialized) {
+            return false;
+        }
+
+        if (!openGralloc()) {
+            return false;
+        }
+
+        mInitialized = true;
+        return true;
+    }
+
+    void cleanup()
+    {
+        if (!mInitialized) {
+            return;
+        }
+
+        closeGralloc();
+        mInitialized = false;
+    }
+
+    // In IComposer, any buffer_handle_t is owned by the caller and we need to
+    // make a clone for hwcomposer2.  We also need to translate empty handle
+    // to nullptr.  This function does that, in-place.
+    bool importBuffer(buffer_handle_t& handle)
+    {
+        if (!handle->numFds && !handle->numInts) {
+            handle = nullptr;
+            return true;
+        }
+
+        buffer_handle_t clone = cloneBuffer(handle);
+        if (!clone) {
+            return false;
+        }
+
+        handle = clone;
+        return true;
+    }
+
+    void freeBuffer(buffer_handle_t handle)
+    {
+        if (!handle) {
+            return;
+        }
+
+        releaseBuffer(handle);
+    }
+
+    bool importFence(const native_handle_t* handle, int& fd)
+    {
+        if (handle == nullptr || handle->numFds == 0) {
+            fd = -1;
+        } else if (handle->numFds == 1) {
+            fd = dup(handle->data[0]);
+            if (fd < 0) {
+                ALOGE("failed to dup fence fd %d", handle->data[0]);
+                return false;
+            }
+        } else {
+            ALOGE("invalid fence handle with %d file descriptors",
+                    handle->numFds);
+            return false;
+        }
+
+        return true;
+    }
+
+    void closeFence(int fd)
+    {
+        if (fd >= 0) {
+            close(fd);
+        }
+    }
+
+private:
+    bool mInitialized;
+
+    // Some existing gralloc drivers do not support retaining more than once,
+    // when we are in passthrough mode.
+#ifdef BINDERIZED
+    bool openGralloc()
+    {
+        const hw_module_t* module;
+        int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
+        if (err) {
+            ALOGE("failed to get gralloc module");
+            return false;
+        }
+
+        uint8_t major = (module->module_api_version >> 8) & 0xff;
+        if (major > 1) {
+            ALOGE("unknown gralloc module major version %d", major);
+            return false;
+        }
+
+        if (major == 1) {
+            err = gralloc1_open(module, &mDevice);
+            if (err) {
+                ALOGE("failed to open gralloc1 device");
+                return false;
+            }
+
+            mRetain = reinterpret_cast<GRALLOC1_PFN_RETAIN>(
+                    mDevice->getFunction(mDevice, GRALLOC1_FUNCTION_RETAIN));
+            mRelease = reinterpret_cast<GRALLOC1_PFN_RELEASE>(
+                    mDevice->getFunction(mDevice, GRALLOC1_FUNCTION_RELEASE));
+            if (!mRetain || !mRelease) {
+                ALOGE("invalid gralloc1 device");
+                gralloc1_close(mDevice);
+                return false;
+            }
+        } else {
+            mModule = reinterpret_cast<const gralloc_module_t*>(module);
+        }
+
+        return true;
+    }
+
+    void closeGralloc()
+    {
+        if (mDevice) {
+            gralloc1_close(mDevice);
+        }
+    }
+
+    buffer_handle_t cloneBuffer(buffer_handle_t handle)
+    {
+        native_handle_t* clone = native_handle_clone(handle);
+        if (!clone) {
+            ALOGE("failed to clone buffer %p", handle);
+            return nullptr;
+        }
+
+        bool err;
+        if (mDevice) {
+            err = (mRetain(mDevice, clone) != GRALLOC1_ERROR_NONE);
+        } else {
+            err = (mModule->registerBuffer(mModule, clone) != 0);
+        }
+
+        if (err) {
+            ALOGE("failed to retain/register buffer %p", clone);
+            native_handle_close(clone);
+            native_handle_delete(clone);
+            return nullptr;
+        }
+
+        return clone;
+    }
+
+    void releaseBuffer(buffer_handle_t handle)
+    {
+        if (mDevice) {
+            mRelease(mDevice, handle);
+        } else {
+            mModule->unregisterBuffer(mModule, handle);
+            native_handle_close(handle);
+            native_handle_delete(const_cast<native_handle_t*>(handle));
+        }
+    }
+
+    // gralloc1
+    gralloc1_device_t* mDevice;
+    GRALLOC1_PFN_RETAIN mRetain;
+    GRALLOC1_PFN_RELEASE mRelease;
+
+    // gralloc0
+    const gralloc_module_t* mModule;
+#else
+    bool openGralloc() { return true; }
+    void closeGralloc() {}
+    buffer_handle_t cloneBuffer(buffer_handle_t handle) { return handle; }
+    void releaseBuffer(buffer_handle_t) {}
+#endif
+};
+
+HandleImporter sHandleImporter;
+
+} // Anonymous namespace
+
+CameraDeviceSession::CameraDeviceSession(
+    camera3_device_t* device, const sp<ICameraDeviceCallback>& callback) :
+        camera3_callback_ops({&sProcessCaptureResult, &sNotify}),
+        mDevice(device),
+        mCallback(callback) {
+
+    // For now, we init sHandleImporter but do not cleanup (keep it alive until
+    // HAL process ends)
+    sHandleImporter.initialize();
+
+    mInitFail = initialize();
+}
+
+bool CameraDeviceSession::initialize() {
+    /** Initialize device with callback functions */
+    ATRACE_BEGIN("camera3->initialize");
+    status_t res = mDevice->ops->initialize(mDevice, this);
+    ATRACE_END();
+
+    if (res != OK) {
+        ALOGE("%s: Unable to initialize HAL device: %s (%d)",
+                __FUNCTION__, strerror(-res), res);
+        mDevice->common.close(&mDevice->common);
+        mClosed = true;
+        return true;
+    }
+    return false;
+}
+
+CameraDeviceSession::~CameraDeviceSession() {
+    if (!isClosed()) {
+        ALOGE("CameraDeviceSession deleted before close!");
+        close();
+    }
+}
+
+bool CameraDeviceSession::isClosed() {
+    Mutex::Autolock _l(mStateLock);
+    return mClosed;
+}
+
+Status CameraDeviceSession::initStatus() const {
+    Mutex::Autolock _l(mStateLock);
+    Status status = Status::OK;
+    if (mInitFail) {
+        status = Status::INTERNAL_ERROR;
+    } else if (mDisconnected) {
+        status = Status::CAMERA_DISCONNECTED;
+    } else if (mClosed) {
+        status = Status::INTERNAL_ERROR;
+    }
+    return status;
+}
+
+void CameraDeviceSession::disconnect() {
+    Mutex::Autolock _l(mStateLock);
+    mDisconnected = true;
+    ALOGW("%s: Camera device is disconnected. Closing.", __FUNCTION__);
+    if (!mClosed) {
+        mDevice->common.close(&mDevice->common);
+        mClosed = true;
+    }
+}
+
+void CameraDeviceSession::dumpState(const native_handle_t* fd) {
+    if (!isClosed()) {
+        mDevice->ops->dump(mDevice, fd->data[0]);
+    }
+}
+
+Status CameraDeviceSession::importRequest(
+        const CaptureRequest& request,
+        hidl_vec<buffer_handle_t>& allBufs,
+        hidl_vec<int>& allFences) {
+    bool hasInputBuf = (request.inputBuffer.streamId != -1 &&
+            request.inputBuffer.buffer.getNativeHandle() == nullptr);
+    size_t numOutputBufs = request.outputBuffers.size();
+    size_t numBufs = numOutputBufs + (hasInputBuf ? 1 : 0);
+    // Validate all I/O buffers
+    allBufs.resize(numBufs);
+    allFences.resize(numBufs);
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        allBufs[i] = request.outputBuffers[i].buffer.getNativeHandle();
+    }
+    if (hasInputBuf) {
+        allBufs[numOutputBufs] = request.inputBuffer.buffer.getNativeHandle();
+    }
+    for (size_t i = 0; i < numBufs; i++) {
+        buffer_handle_t buf = allBufs[i];
+        sHandleImporter.importBuffer(buf);
+        if (buf == nullptr) {
+            ALOGE("%s: output buffer %zu is invalid!", __FUNCTION__, i);
+            cleanupInflightBufferFences(allBufs, i, allFences, 0);
+            return Status::INTERNAL_ERROR;
+        } else {
+            allBufs[i] = buf;
+        }
+    }
+
+    // All buffers are imported. Now validate output buffer acquire fences
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        if (!sHandleImporter.importFence(
+                request.outputBuffers[i].acquireFence, allFences[i])) {
+            ALOGE("%s: output buffer %zu acquire fence is invalid", __FUNCTION__, i);
+            cleanupInflightBufferFences(allBufs, numBufs, allFences, i);
+            return Status::INTERNAL_ERROR;
+        }
+    }
+
+    // Validate input buffer acquire fences
+    if (hasInputBuf) {
+        if (!sHandleImporter.importFence(
+                request.inputBuffer.acquireFence, allFences[numOutputBufs])) {
+            ALOGE("%s: input buffer acquire fence is invalid", __FUNCTION__);
+            cleanupInflightBufferFences(allBufs, numBufs, allFences, numOutputBufs);
+            return Status::INTERNAL_ERROR;
+        }
+    }
+    return Status::OK;
+}
+
+void CameraDeviceSession::cleanupInflightBufferFences(
+        hidl_vec<buffer_handle_t>& allBufs, size_t numBufs,
+        hidl_vec<int>& allFences, size_t numFences) {
+    for (size_t j = 0; j < numBufs; j++) {
+        sHandleImporter.freeBuffer(allBufs[j]);
+    }
+    for (size_t j = 0; j < numFences; j++) {
+        sHandleImporter.closeFence(allFences[j]);
+    }
+}
+
+// Methods from ::android::hardware::camera::device::V3_2::ICameraDeviceSession follow.
+Return<void> CameraDeviceSession::constructDefaultRequestSettings(
+        RequestTemplate type, constructDefaultRequestSettings_cb _hidl_cb)  {
+    Status status = initStatus();
+    CameraMetadata outMetadata;
+    const camera_metadata_t *rawRequest;
+    if (status == Status::OK) {
+        ATRACE_BEGIN("camera3->construct_default_request_settings");
+        rawRequest = mDevice->ops->construct_default_request_settings(mDevice, (int) type);
+        ATRACE_END();
+        if (rawRequest == nullptr) {
+            ALOGI("%s: template %d is not supported on this camera device",
+                  __FUNCTION__, type);
+            status = Status::ILLEGAL_ARGUMENT;
+        } else {
+            convertToHidl(rawRequest, &outMetadata);
+        }
+    }
+    _hidl_cb(status, outMetadata);
+    return Void();
+}
+
+Return<void> CameraDeviceSession::configureStreams(
+        const StreamConfiguration& requestedConfiguration, configureStreams_cb _hidl_cb)  {
+    Status status = initStatus();
+    if (!mInflightBuffers.empty()) {
+        ALOGE("%s: trying to configureStreams while there are still %zu inflight buffers!",
+                __FUNCTION__, mInflightBuffers.size());
+        status = Status::INTERNAL_ERROR;
+    }
+
+    HalStreamConfiguration outStreams;
+    if (status == Status::OK) {
+        camera3_stream_configuration_t stream_list;
+        hidl_vec<camera3_stream_t*> streams;
+
+        stream_list.operation_mode = (uint32_t) requestedConfiguration.operationMode;
+        stream_list.num_streams = requestedConfiguration.streams.size();
+        streams.resize(stream_list.num_streams);
+        stream_list.streams = streams.data();
+
+        mStreamMap.clear();
+        for (uint32_t i = 0; i < stream_list.num_streams; i++) {
+            Camera3Stream stream;
+            convertFromHidl(requestedConfiguration.streams[i], &stream);
+            mStreamMap[stream.mId] = stream;
+            streams[i] = &mStreamMap[stream.mId];
+        }
+
+        ATRACE_BEGIN("camera3->configure_streams");
+        status_t ret = mDevice->ops->configure_streams(mDevice, &stream_list);
+        ATRACE_END();
+
+        if (ret == -EINVAL) {
+            status = Status::ILLEGAL_ARGUMENT;
+        } else if (ret != OK) {
+            status = Status::INTERNAL_ERROR;
+        } else {
+            convertToHidl(stream_list, &outStreams);
+        }
+
+    }
+    _hidl_cb(status, outStreams);
+    return Void();
+}
+
+Return<Status> CameraDeviceSession::processCaptureRequest(const CaptureRequest& request)  {
+    Status status = initStatus();
+    if (status != Status::OK) {
+        ALOGE("%s: camera init failed or disconnected", __FUNCTION__);
+        return status;
+    }
+
+    camera3_capture_request_t halRequest;
+    halRequest.frame_number = request.frameNumber;
+    bool converted = convertFromHidl(request.settings, &halRequest.settings);
+    if (!converted) {
+        ALOGE("%s: capture request settings metadata is corrupt!", __FUNCTION__);
+        return Status::INTERNAL_ERROR;
+    }
+
+    hidl_vec<buffer_handle_t> allBufs;
+    hidl_vec<int> allFences;
+    bool hasInputBuf = (request.inputBuffer.streamId != -1 &&
+            request.inputBuffer.buffer.getNativeHandle() == nullptr);
+    size_t numOutputBufs = request.outputBuffers.size();
+    size_t numBufs = numOutputBufs + (hasInputBuf ? 1 : 0);
+    status = importRequest(request, allBufs, allFences);
+    if (status != Status::OK) {
+        return status;
+    }
+
+    if (hasInputBuf) {
+        auto key = std::make_pair(request.inputBuffer.streamId, request.frameNumber);
+        auto& bufCache = mInflightBuffers[key] = StreamBufferCache{};
+        // The last parameter (&bufCache) must be in heap, or we will
+        // send a pointer pointing to stack memory to HAL and later HAL will break
+        // when trying to accessing it after this call returned.
+        convertFromHidl(
+                allBufs[numOutputBufs], request.inputBuffer.status,
+                &mStreamMap[request.inputBuffer.streamId], allFences[numOutputBufs],
+                &bufCache);
+        halRequest.input_buffer = &(bufCache.mStreamBuffer);
+    } else {
+        halRequest.input_buffer = nullptr;
+    }
+
+    halRequest.num_output_buffers = numOutputBufs;
+    hidl_vec<camera3_stream_buffer_t> outHalBufs;
+    outHalBufs.resize(numOutputBufs);
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        auto key = std::make_pair(request.outputBuffers[i].streamId, request.frameNumber);
+        auto& bufCache = mInflightBuffers[key] = StreamBufferCache{};
+        // The last parameter (&bufCache) must be in heap, or we will
+        // send a pointer pointing to stack memory to HAL and later HAL will break
+        // when trying to accessing it after this call returned.
+        convertFromHidl(
+                allBufs[i], request.outputBuffers[i].status,
+                &mStreamMap[request.outputBuffers[i].streamId], allFences[i],
+                &bufCache);
+        outHalBufs[i] = bufCache.mStreamBuffer;
+    }
+    halRequest.output_buffers = outHalBufs.data();
+
+    ATRACE_ASYNC_BEGIN("frame capture", request.frameNumber);
+    ATRACE_BEGIN("camera3->process_capture_request");
+    status_t ret = mDevice->ops->process_capture_request(mDevice, &halRequest);
+    ATRACE_END();
+    if (ret != OK) {
+        ALOGE("%s: HAL process_capture_request call failed!", __FUNCTION__);
+
+        cleanupInflightBufferFences(allBufs, numBufs, allFences, numBufs);
+        if (hasInputBuf) {
+            auto key = std::make_pair(request.inputBuffer.streamId, request.frameNumber);
+            mInflightBuffers.erase(key);
+        }
+        for (size_t i = 0; i < numOutputBufs; i++) {
+            auto key = std::make_pair(request.outputBuffers[i].streamId, request.frameNumber);
+            mInflightBuffers.erase(key);
+        }
+        return Status::INTERNAL_ERROR;
+    }
+
+    return Status::OK;
+}
+
+Return<Status> CameraDeviceSession::flush()  {
+    Status status = initStatus();
+    if (status == Status::OK) {
+        // Flush is always supported on device 3.1 or later
+        status_t ret = mDevice->ops->flush(mDevice);
+        if (ret != OK) {
+            status = Status::INTERNAL_ERROR;
+        }
+    }
+    return status;
+}
+
+Return<void> CameraDeviceSession::close()  {
+    Mutex::Autolock _l(mStateLock);
+    if (!mClosed) {
+        ATRACE_BEGIN("camera3->close");
+        mDevice->common.close(&mDevice->common);
+        ATRACE_END();
+        mClosed = true;
+    }
+    return Void();
+}
+
+/**
+ * Static callback forwarding methods from HAL to instance
+ */
+void CameraDeviceSession::sProcessCaptureResult(
+        const camera3_callback_ops *cb,
+        const camera3_capture_result *hal_result) {
+    CameraDeviceSession *d =
+            const_cast<CameraDeviceSession*>(static_cast<const CameraDeviceSession*>(cb));
+
+    uint32_t frameNumber = hal_result->frame_number;
+    bool hasInputBuf = (hal_result->input_buffer != nullptr);
+    size_t numOutputBufs = hal_result->num_output_buffers;
+    size_t numBufs = numOutputBufs + (hasInputBuf ? 1 : 0);
+    Status status = Status::OK;
+    if (hasInputBuf) {
+        int streamId = static_cast<Camera3Stream*>(hal_result->input_buffer->stream)->mId;
+        // validate if buffer is inflight
+        auto key = std::make_pair(streamId, frameNumber);
+        if (d->mInflightBuffers.count(key) != 1) {
+            ALOGE("%s: input buffer for stream %d frame %d is not inflight!",
+                    __FUNCTION__, streamId, frameNumber);
+            return;
+        }
+    }
+
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        int streamId = static_cast<Camera3Stream*>(hal_result->output_buffers[i].stream)->mId;
+        // validate if buffer is inflight
+        auto key = std::make_pair(streamId, frameNumber);
+        if (d->mInflightBuffers.count(key) != 1) {
+            ALOGE("%s: output buffer for stream %d frame %d is not inflight!",
+                    __FUNCTION__, streamId, frameNumber);
+            return;
+        }
+    }
+    // We don't need to validate/import fences here since we will be passing them to camera service
+    // within the scope of this function
+
+    CaptureResult result;
+    hidl_vec<native_handle_t*> releaseFences;
+    releaseFences.resize(numBufs);
+    result.frameNumber = frameNumber;
+    result.partialResult = hal_result->partial_result;
+    convertToHidl(hal_result->result, &result.result);
+    if (hasInputBuf) {
+        result.inputBuffer.streamId =
+                static_cast<Camera3Stream*>(hal_result->input_buffer->stream)->mId;
+        result.inputBuffer.buffer = nullptr;
+        result.inputBuffer.status = (BufferStatus) hal_result->input_buffer->status;
+        // skip acquire fence since it's no use to camera service
+        if (hal_result->input_buffer->release_fence != -1) {
+            releaseFences[numOutputBufs] = native_handle_create(/*numFds*/1, /*numInts*/0);
+            releaseFences[numOutputBufs]->data[0] = hal_result->input_buffer->release_fence;
+            result.inputBuffer.releaseFence = releaseFences[numOutputBufs];
+        }
+    } else {
+        result.inputBuffer.streamId = -1;
+    }
+
+    result.outputBuffers.resize(numOutputBufs);
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        result.outputBuffers[i].streamId =
+                static_cast<Camera3Stream*>(hal_result->output_buffers[i].stream)->mId;
+        result.outputBuffers[i].buffer = nullptr;
+        result.outputBuffers[i].status = (BufferStatus) hal_result->output_buffers[i].status;
+        // skip acquire fence since it's of no use to camera service
+        if (hal_result->output_buffers[i].release_fence != -1) {
+            releaseFences[i] = native_handle_create(/*numFds*/1, /*numInts*/0);
+            releaseFences[i]->data[0] = hal_result->output_buffers[i].release_fence;
+            result.outputBuffers[i].releaseFence = releaseFences[i];
+        }
+    }
+
+    d->mCallback->processCaptureResult(result);
+
+    // Free cached buffer/fences.
+    if (hasInputBuf) {
+        int streamId = static_cast<Camera3Stream*>(hal_result->input_buffer->stream)->mId;
+        auto key = std::make_pair(streamId, frameNumber);
+        sHandleImporter.closeFence(d->mInflightBuffers[key].mStreamBuffer.acquire_fence);
+        sHandleImporter.freeBuffer(d->mInflightBuffers[key].mBuffer);
+        d->mInflightBuffers.erase(key);
+    }
+
+    for (size_t i = 0; i < numOutputBufs; i++) {
+        int streamId = static_cast<Camera3Stream*>(hal_result->output_buffers[i].stream)->mId;
+        auto key = std::make_pair(streamId, frameNumber);
+        sHandleImporter.closeFence(d->mInflightBuffers[key].mStreamBuffer.acquire_fence);
+        sHandleImporter.freeBuffer(d->mInflightBuffers[key].mBuffer);
+        d->mInflightBuffers.erase(key);
+    }
+
+    for (size_t i = 0; i < releaseFences.size(); i++) {
+        // We don't close the FD here as HAL needs to signal it later.
+        native_handle_delete(releaseFences[i]);
+    }
+
+}
+
+void CameraDeviceSession::sNotify(
+        const camera3_callback_ops *cb,
+        const camera3_notify_msg *msg) {
+    CameraDeviceSession *d =
+            const_cast<CameraDeviceSession*>(static_cast<const CameraDeviceSession*>(cb));
+    NotifyMsg hidlMsg;
+    convertToHidl(msg, &hidlMsg);
+    if (hidlMsg.type == (MsgType) CAMERA3_MSG_ERROR) {
+        if (d->mStreamMap.count(hidlMsg.msg.error.errorStreamId) != 1) {
+            ALOGE("%s: unknown stream ID %d reports an error!",
+                    __FUNCTION__, hidlMsg.msg.error.errorStreamId);
+        }
+        return;
+    }
+    d->mCallback->notify(hidlMsg);
+}
+
+} // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
diff --git a/camera/device/3.2/default/CameraDeviceSession.h b/camera/device/3.2/default/CameraDeviceSession.h
new file mode 100644
index 0000000..3e01b1a
--- /dev/null
+++ b/camera/device/3.2/default/CameraDeviceSession.h
@@ -0,0 +1,129 @@
+/*
+ * Copyright (C) 2016 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 ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE3SESSION_H
+#define ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE3SESSION_H
+
+#include "hardware/camera_common.h"
+#include "hardware/camera3.h"
+#include "utils/Mutex.h"
+#include <android/hardware/camera/device/3.2/ICameraDevice.h>
+#include <android/hardware/camera/device/3.2/ICameraDeviceSession.h>
+#include <hidl/Status.h>
+#include <hidl/MQDescriptor.h>
+#include <include/convert.h>
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+using ::android::hardware::camera::device::V3_2::CaptureRequest;
+using ::android::hardware::camera::device::V3_2::HalStreamConfiguration;
+using ::android::hardware::camera::device::V3_2::StreamConfiguration;
+using ::android::hardware::camera::device::V3_2::ICameraDeviceSession;
+using ::android::hardware::camera::common::V1_0::Status;
+using ::android::hardware::Return;
+using ::android::hardware::Void;
+using ::android::hardware::hidl_vec;
+using ::android::hardware::hidl_string;
+using ::android::sp;
+using ::android::Mutex;
+
+/**
+ * Function pointer types with C calling convention to
+ * use for HAL callback functions.
+ */
+extern "C" {
+    typedef void (callbacks_process_capture_result_t)(
+        const struct camera3_callback_ops *,
+        const camera3_capture_result_t *);
+
+    typedef void (callbacks_notify_t)(
+        const struct camera3_callback_ops *,
+        const camera3_notify_msg_t *);
+}
+
+struct CameraDeviceSession : public ICameraDeviceSession, private camera3_callback_ops  {
+
+    CameraDeviceSession(camera3_device_t*, const sp<ICameraDeviceCallback>&);
+    ~CameraDeviceSession();
+    // Call by CameraDevice to dump active device states
+    void dumpState(const native_handle_t* fd);
+    // Caller must use this method to check if CameraDeviceSession ctor failed
+    bool isInitFailed() { return mInitFail; }
+    // Used by CameraDevice to signal external camera disconnected
+    void disconnect();
+    bool isClosed();
+
+    // Methods from ::android::hardware::camera::device::V3_2::ICameraDeviceSession follow.
+    Return<void> constructDefaultRequestSettings(RequestTemplate type, constructDefaultRequestSettings_cb _hidl_cb) override;
+    Return<void> configureStreams(const StreamConfiguration& requestedConfiguration, configureStreams_cb _hidl_cb) override;
+    Return<Status> processCaptureRequest(const CaptureRequest& request) override;
+    Return<Status> flush() override;
+    Return<void> close() override;
+
+private:
+    // protecting mClosed/mDisconnected/mInitFail
+    mutable Mutex mStateLock;
+    // device is closed either
+    //    - closed by user
+    //    - init failed
+    //    - camera disconnected
+    bool mClosed = false;
+
+    // Set by CameraDevice (when external camera is disconnected)
+    bool mDisconnected = false;
+
+    camera3_device_t* mDevice;
+    const sp<ICameraDeviceCallback>& mCallback;
+    // Stream ID -> Camera3Stream cache
+    std::map<int, Camera3Stream> mStreamMap;
+    // (streamID, frameNumber) -> inflight buffer cache
+    std::map<std::pair<int, uint32_t>, StreamBufferCache>  mInflightBuffers;
+
+    bool mInitFail;
+    bool initialize();
+
+    Status initStatus() const;
+
+    // Validate and import request's input buffer and acquire fence
+    static Status importRequest(
+            const CaptureRequest& request,
+            hidl_vec<buffer_handle_t>& allBufs,
+            hidl_vec<int>& allFences);
+
+    static void cleanupInflightBufferFences(
+            hidl_vec<buffer_handle_t>& allBufs, size_t numBufs,
+            hidl_vec<int>& allFences, size_t numFences);
+
+    /**
+     * Static callback forwarding methods from HAL to instance
+     */
+    static callbacks_process_capture_result_t sProcessCaptureResult;
+    static callbacks_notify_t sNotify;
+};
+
+}  // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
+
+#endif  // ANDROID_HARDWARE_CAMERA_DEVICE_V3_2_CAMERADEVICE3SESSION_H
diff --git a/camera/device/3.2/default/convert.cpp b/camera/device/3.2/default/convert.cpp
new file mode 100644
index 0000000..ae83e7d
--- /dev/null
+++ b/camera/device/3.2/default/convert.cpp
@@ -0,0 +1,138 @@
+/*
+ * Copyright (C) 2016 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.
+ */
+
+#define LOG_TAG "android.hardware.camera.device@3.2-convert-impl"
+#include <android/log.h>
+
+#include "include/convert.h"
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+using ::android::hardware::graphics::common::V1_0::Dataspace;
+using ::android::hardware::graphics::common::V1_0::PixelFormat;
+using ::android::hardware::camera::device::V3_2::ConsumerUsageFlags;
+using ::android::hardware::camera::device::V3_2::ProducerUsageFlags;
+
+bool convertFromHidl(const CameraMetadata &src, const camera_metadata_t** dst) {
+    if (src.size() == 0) {
+        // Special case for null metadata
+        *dst = nullptr;
+        return true;
+    }
+
+    const uint8_t* data = src.data();
+    // sanity check the size of CameraMetadata match underlying camera_metadata_t
+    if (get_camera_metadata_size((camera_metadata_t*)data) != src.size()) {
+        ALOGE("%s: input CameraMetadata is corrupt!", __FUNCTION__);
+        return false;
+    }
+    *dst = (camera_metadata_t*) data;
+    return true;
+}
+
+// Note: existing data in dst will be gone. Caller still owns the memory of src
+void convertToHidl(const camera_metadata_t *src, CameraMetadata* dst) {
+    size_t size = get_camera_metadata_size(src);
+    dst->setToExternal((uint8_t *) src, size);
+    return;
+}
+
+void convertFromHidl(const Stream &src, Camera3Stream* dst) {
+    dst->mId = src.id;
+    dst->stream_type = (int) src.streamType;
+    dst->width = src.width;
+    dst->height = src.height;
+    dst->format = (int) src.format;
+    dst->data_space = (android_dataspace_t) src.dataSpace;
+    dst->rotation = (int) src.rotation;
+    dst->usage = (uint32_t) src.usage;
+    // Fields to be filled by HAL (max_buffers, priv) are initialized to 0
+    dst->max_buffers = 0;
+    dst->priv = 0;
+    return;
+}
+
+void convertToHidl(const Camera3Stream* src, HalStream* dst) {
+    dst->id = src->mId;
+    dst->overrideFormat = (PixelFormat) src->format;
+    dst->maxBuffers = src->max_buffers;
+    if (src->stream_type == CAMERA3_STREAM_OUTPUT) {
+        dst->consumerUsage = (ConsumerUsageFlags) 0;
+        dst->producerUsage = (ProducerUsageFlags) src->usage;
+    } else if (src->stream_type == CAMERA3_STREAM_INPUT) {
+        dst->producerUsage = (ProducerUsageFlags) 0;
+        dst->consumerUsage = (ConsumerUsageFlags) src->usage;
+    } else {
+        //Should not reach here per current HIDL spec, but we might end up adding
+        // bi-directional stream to HIDL.
+        ALOGW("%s: Stream type %d is not currently supported!",
+                __FUNCTION__, src->stream_type);
+    }
+}
+
+void convertToHidl(const camera3_stream_configuration_t& src, HalStreamConfiguration* dst) {
+    dst->streams.resize(src.num_streams);
+    for (uint32_t i = 0; i < src.num_streams; i++) {
+        convertToHidl(static_cast<Camera3Stream*>(src.streams[i]), &dst->streams[i]);
+    }
+    return;
+}
+
+void convertFromHidl(
+        buffer_handle_t bufIn, BufferStatus status, camera3_stream_t* stream, int acquireFence,
+        StreamBufferCache* dst) {
+    dst->mBuffer = bufIn;
+    dst->mStreamBuffer.stream = stream;
+    dst->mStreamBuffer.buffer = &dst->mBuffer;
+    dst->mStreamBuffer.status = (int) status;
+    dst->mStreamBuffer.acquire_fence = acquireFence;
+    dst->mStreamBuffer.release_fence = -1; // meant for HAL to fill in
+}
+
+void convertToHidl(const camera3_notify_msg* src, NotifyMsg* dst) {
+    dst->type = (MsgType) src->type;
+    switch (src->type) {
+        case CAMERA3_MSG_ERROR:
+            dst->msg.error.frameNumber = src->message.error.frame_number;
+            // The camera3_stream_t* must be the same as what wrapper HAL passed to conventional
+            // HAL, or the ID lookup will return garbage. Caller should validate the ID here is
+            // indeed one of active stream IDs
+            dst->msg.error.errorStreamId =
+                    static_cast<Camera3Stream*>(src->message.error.error_stream)->mId;
+            dst->msg.error.errorCode = (ErrorCode) src->message.error.error_code;
+            break;
+        case CAMERA3_MSG_SHUTTER:
+            dst->msg.shutter.frameNumber = src->message.shutter.frame_number;
+            dst->msg.shutter.timestamp = src->message.shutter.timestamp;
+            break;
+        default:
+            ALOGE("%s: HIDL type converion failed. Unknown msg type 0x%x",
+                    __FUNCTION__, src->type);
+    }
+    return;
+}
+
+}  // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
diff --git a/camera/device/3.2/default/include/convert.h b/camera/device/3.2/default/include/convert.h
new file mode 100644
index 0000000..f5ea564
--- /dev/null
+++ b/camera/device/3.2/default/include/convert.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2016 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 HARDWARE_INTERFACES_CAMERA_DEVICE_V3_2_DEFAULT_INCLUDE_CONVERT_H_
+
+#define HARDWARE_INTERFACES_CAMERA_DEVICE_V3_2_DEFAULT_INCLUDE_CONVERT_H_
+
+#include <set>
+
+
+#include <android/hardware/graphics/common/1.0/types.h>
+#include <android/hardware/camera/device/3.2/types.h>
+#include "hardware/camera3.h"
+
+namespace android {
+namespace hardware {
+namespace camera {
+namespace device {
+namespace V3_2 {
+namespace implementation {
+
+// Cacheing the buffer/fence from camera service so HAL can reference the pointer after the
+// processCaptureRequest call has returned.
+// Remove the cache when:
+//     1. HAL API call failed, or
+//     2. HAL returns the buffer and the callback to camera service has returned
+struct StreamBufferCache {
+    buffer_handle_t mBuffer;
+    camera3_stream_buffer_t mStreamBuffer;
+};
+
+// The camera3_stream_t sent to conventional HAL. Added mId fields to enable stream ID lookup
+// fromt a downcasted camera3_stream
+struct Camera3Stream : public camera3_stream {
+    int mId;
+};
+
+// *dst will point to the data owned by src, but src still owns the data after this call returns.
+bool convertFromHidl(const CameraMetadata &src, const camera_metadata_t** dst);
+void convertToHidl(const camera_metadata_t* src, CameraMetadata* dst);
+
+void convertFromHidl(const Stream &src, Camera3Stream* dst);
+void convertToHidl(const Camera3Stream* src, HalStream* dst);
+
+// dst->mStreamBuffer.buffer will be pointing to dst->mBuffer.
+// Most likely dst will be passed to HAL and HAL will try to access mStreamBuffer.buffer
+// after the API call returns. In that case caller must not use a local variable
+// within the scope of the API call to hold dst, because then dst->mStreamBuffer.buffer will be
+// invalid after the API call returns.
+void convertFromHidl(
+        buffer_handle_t, BufferStatus, camera3_stream_t*, int acquireFence, // inputs
+        StreamBufferCache* dst);
+
+void convertToHidl(const camera3_stream_configuration_t& src, HalStreamConfiguration* dst);
+
+// The camera3_stream_t* in src must be the same as what wrapper HAL passed to conventional
+// HAL, or the ID lookup will return garbage. Caller should validate the ID in ErrorMsg is
+// indeed one of active stream IDs
+void convertToHidl(const camera3_notify_msg* src, NotifyMsg* dst);
+
+}  // namespace implementation
+}  // namespace V3_2
+}  // namespace device
+}  // namespace camera
+}  // namespace hardware
+}  // namespace android
+
+#endif  // HARDWARE_INTERFACES_CAMERA_DEVICE_V3_2_DEFAULT_INCLUDE_CONVERT_H_