Camera: Switch camera2 to auto-gen C++ binder interfaces

 - Move camera service AIDL files to frameworks/av
 - Build C++ interface stubs with AIDL tools
 - Add necessary native-side parcelables and update existing ones
 - Remove manually-written stubs, rearrange remaining manual stubs
 - Adjust implementations to work with auto-generated stubs
   - Adjust method signatures for auto-gen differences
   - Add rich error messages using binder::Status

Bug: 25091611
Change-Id: I6f69f34b9d1a3f8d1fb7db87357363f8fa8483ff
diff --git a/services/camera/libcameraservice/CameraService.h b/services/camera/libcameraservice/CameraService.h
index 66de77f..e29b01c 100644
--- a/services/camera/libcameraservice/CameraService.h
+++ b/services/camera/libcameraservice/CameraService.h
@@ -17,25 +17,22 @@
 #ifndef ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
 #define ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
 
+#include <android/hardware/BnCameraService.h>
+#include <android/hardware/ICameraServiceListener.h>
+
 #include <cutils/multiuser.h>
 #include <utils/Vector.h>
 #include <utils/KeyedVector.h>
 #include <binder/AppOpsManager.h>
 #include <binder/BinderService.h>
 #include <binder/IAppOpsCallback.h>
-#include <camera/ICameraService.h>
 #include <camera/ICameraServiceProxy.h>
 #include <hardware/camera.h>
 
-#include <camera/ICamera.h>
-#include <camera/ICameraClient.h>
-#include <camera/camera2/ICameraDeviceUser.h>
-#include <camera/camera2/ICameraDeviceCallbacks.h>
 #include <camera/VendorTagDescriptor.h>
 #include <camera/CaptureResult.h>
 #include <camera/CameraParameters.h>
 
-#include <camera/ICameraServiceListener.h>
 #include "CameraFlashlight.h"
 
 #include "common/CameraModule.h"
@@ -58,7 +55,7 @@
 
 class CameraService :
     public BinderService<CameraService>,
-    public BnCameraService,
+    public ::android::hardware::BnCameraService,
     public IBinder::DeathRecipient,
     public camera_module_callbacks_t
 {
@@ -101,55 +98,58 @@
     virtual void        onDeviceStatusChanged(camera_device_status_t cameraId,
                                               camera_device_status_t newStatus);
     virtual void        onTorchStatusChanged(const String8& cameraId,
-                                             ICameraServiceListener::TorchStatus
-                                                   newStatus);
+                                             int32_t newStatus);
 
     /////////////////////////////////////////////////////////////////////
     // ICameraService
-    virtual int32_t     getNumberOfCameras(int type);
-    virtual int32_t     getNumberOfCameras();
+    virtual binder::Status     getNumberOfCameras(int32_t type, int32_t* numCameras);
 
-    virtual status_t    getCameraInfo(int cameraId,
-                                      struct CameraInfo* cameraInfo);
-    virtual status_t    getCameraCharacteristics(int cameraId,
-                                                 CameraMetadata* cameraInfo);
-    virtual status_t    getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
-
-    virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
-            const String16& clientPackageName, int clientUid, int clientPid,
+    virtual binder::Status     getCameraInfo(int cameraId,
+            hardware::CameraInfo* cameraInfo);
+    virtual binder::Status     getCameraCharacteristics(int cameraId,
+            CameraMetadata* cameraInfo);
+    virtual binder::Status     getCameraVendorTagDescriptor(
             /*out*/
-            sp<ICamera>& device);
+            hardware::camera2::params::VendorTagDescriptor* desc);
 
-    virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
-            int halVersion, const String16& clientPackageName, int clientUid,
+    virtual binder::Status     connect(const sp<hardware::ICameraClient>& cameraClient,
+            int32_t cameraId, const String16& clientPackageName,
+            int32_t clientUid, int clientPid,
             /*out*/
-            sp<ICamera>& device);
+            sp<hardware::ICamera>* device);
 
-    virtual status_t connectDevice(
-            const sp<ICameraDeviceCallbacks>& cameraCb,
-            int cameraId,
-            const String16& clientPackageName,
-            int clientUid,
+    virtual binder::Status     connectLegacy(const sp<hardware::ICameraClient>& cameraClient,
+            int32_t cameraId, int32_t halVersion,
+            const String16& clientPackageName, int32_t clientUid,
             /*out*/
-            sp<ICameraDeviceUser>& device);
+            sp<hardware::ICamera>* device);
 
-    virtual status_t    addListener(const sp<ICameraServiceListener>& listener);
-    virtual status_t    removeListener(
-                                    const sp<ICameraServiceListener>& listener);
+    virtual binder::Status     connectDevice(
+            const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb, int32_t cameraId,
+            const String16& clientPackageName, int32_t clientUid,
+            /*out*/
+            sp<hardware::camera2::ICameraDeviceUser>* device);
 
-    virtual status_t    getLegacyParameters(
-            int cameraId,
+    virtual binder::Status    addListener(const sp<hardware::ICameraServiceListener>& listener);
+    virtual binder::Status    removeListener(
+            const sp<hardware::ICameraServiceListener>& listener);
+
+    virtual binder::Status    getLegacyParameters(
+            int32_t cameraId,
             /*out*/
             String16* parameters);
 
-    virtual status_t    setTorchMode(const String16& cameraId, bool enabled,
+    virtual binder::Status    setTorchMode(const String16& cameraId, bool enabled,
             const sp<IBinder>& clientBinder);
 
-    virtual void notifySystemEvent(int32_t eventId, const int32_t* args, size_t length);
+    virtual binder::Status    notifySystemEvent(int32_t eventId,
+            const std::vector<int32_t>& args);
 
     // OK = supports api of that version, -EOPNOTSUPP = does not support
-    virtual status_t    supportsCameraApi(
-            int cameraId, int apiVersion);
+    virtual binder::Status    supportsCameraApi(
+            int32_t cameraId, int32_t apiVersion,
+            /*out*/
+            bool *isSupported);
 
     // Extra permissions checks
     virtual status_t    onTransact(uint32_t code, const Parcel& data,
@@ -185,35 +185,35 @@
 
     /////////////////////////////////////////////////////////////////////
     // Shared utilities
-    static status_t     filterGetInfoErrorCode(status_t err);
+    static binder::Status filterGetInfoErrorCode(status_t err);
 
     /////////////////////////////////////////////////////////////////////
     // CameraClient functionality
 
     class BasicClient : public virtual RefBase {
     public:
-        virtual status_t    initialize(CameraModule *module) = 0;
-        virtual void        disconnect();
+        virtual status_t       initialize(CameraModule *module) = 0;
+        virtual binder::Status disconnect();
 
         // because we can't virtually inherit IInterface, which breaks
         // virtual inheritance
-        virtual sp<IBinder> asBinderWrapper() = 0;
+        virtual sp<IBinder>    asBinderWrapper() = 0;
 
         // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
-        sp<IBinder>         getRemote() {
+        sp<IBinder>            getRemote() {
             return mRemoteBinder;
         }
 
         // Disallows dumping over binder interface
-        virtual status_t      dump(int fd, const Vector<String16>& args);
+        virtual status_t dump(int fd, const Vector<String16>& args);
         // Internal dump method to be called by CameraService
-        virtual status_t      dumpClient(int fd, const Vector<String16>& args) = 0;
+        virtual status_t dumpClient(int fd, const Vector<String16>& args) = 0;
 
         // Return the package name for this client
         virtual String16 getPackageName() const;
 
         // Notify client about a fatal error
-        virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
+        virtual void notifyError(int32_t errorCode,
                 const CaptureResultExtras& resultExtras) = 0;
 
         // Get the UID of the application client using this
@@ -282,14 +282,14 @@
         virtual void opChanged(int32_t op, const String16& packageName);
     }; // class BasicClient
 
-    class Client : public BnCamera, public BasicClient
+    class Client : public hardware::BnCamera, public BasicClient
     {
     public:
-        typedef ICameraClient TCamCallbacks;
+        typedef hardware::ICameraClient TCamCallbacks;
 
         // ICamera interface (see ICamera for details)
-        virtual void          disconnect();
-        virtual status_t      connect(const sp<ICameraClient>& client) = 0;
+        virtual binder::Status disconnect();
+        virtual status_t      connect(const sp<hardware::ICameraClient>& client) = 0;
         virtual status_t      lock() = 0;
         virtual status_t      unlock() = 0;
         virtual status_t      setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
@@ -314,7 +314,7 @@
 
         // Interface used by CameraService
         Client(const sp<CameraService>& cameraService,
-                const sp<ICameraClient>& cameraClient,
+                const sp<hardware::ICameraClient>& cameraClient,
                 const String16& clientPackageName,
                 int cameraId,
                 int cameraFacing,
@@ -324,7 +324,7 @@
         ~Client();
 
         // return our camera client
-        const sp<ICameraClient>&    getRemoteCallback() {
+        const sp<hardware::ICameraClient>&    getRemoteCallback() {
             return mRemoteCallback;
         }
 
@@ -332,7 +332,7 @@
             return asBinder(this);
         }
 
-        virtual void         notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
+        virtual void         notifyError(int32_t errorCode,
                                          const CaptureResultExtras& resultExtras);
 
         // Check what API level is used for this client. This is used to determine which
@@ -345,7 +345,7 @@
         // Initialized in constructor
 
         // - The app-side Binder interface to receive callbacks from us
-        sp<ICameraClient>               mRemoteCallback;
+        sp<hardware::ICameraClient>               mRemoteCallback;
 
     }; // class Client
 
@@ -432,12 +432,12 @@
          *
          * This method acquires mStatusLock.
          */
-        ICameraServiceListener::Status getStatus() const;
+        int32_t getStatus() const;
 
         /**
          * This function updates the status for this camera device, unless the given status
          * is in the given list of rejected status states, and execute the function passed in
-         * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
+         * with a signature onStatusUpdateLocked(const String8&, int32_t)
          * if the status has changed.
          *
          * This method is idempotent, and will not result in the function passed to
@@ -445,8 +445,8 @@
          * This method aquires mStatusLock.
          */
         template<class Func>
-        void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
-                std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
+        void updateStatus(int32_t status, const String8& cameraId,
+                std::initializer_list<int32_t> rejectSourceStates,
                 Func onStatusUpdatedLocked);
 
         /**
@@ -477,7 +477,7 @@
 
     private:
         const String8 mId;
-        ICameraServiceListener::Status mStatus; // protected by mStatusLock
+        int32_t mStatus; // protected by mStatusLock
         const int mCost;
         std::set<String8> mConflicting;
         mutable Mutex mStatusLock;
@@ -488,8 +488,8 @@
     virtual void onFirstRef();
 
     // Check if we can connect, before we acquire the service lock.
-    status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid,
-            /*inout*/int& clientPid) const;
+    binder::Status validateConnectLocked(const String8& cameraId, const String8& clientName8,
+          /*inout*/int& clientUid, /*inout*/int& clientPid) const;
 
     // Handle active client evictions, and update service state.
     // Only call with with mServiceLock held.
@@ -501,8 +501,9 @@
 
     // Single implementation shared between the various connect calls
     template<class CALLBACK, class CLIENT>
-    status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
-            const String16& clientPackageName, int clientUid, int clientPid,
+    binder::Status connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
+            int halVersion, const String16& clientPackageName,
+            int clientUid, int clientPid,
             apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
             /*out*/sp<CLIENT>& device);
 
@@ -583,7 +584,7 @@
     /**
      * Handle a notification that the current device user has changed.
      */
-    void doUserSwitch(const int32_t* newUserId, size_t length);
+    void doUserSwitch(const std::vector<int32_t>& newUserIds);
 
     /**
      * Add an event log message.
@@ -651,7 +652,7 @@
     CameraModule*     mModule;
 
     // Guarded by mStatusListenerMutex
-    std::vector<sp<ICameraServiceListener>> mListenerList;
+    std::vector<sp<hardware::ICameraServiceListener>> mListenerList;
     Mutex       mStatusListenerLock;
 
     /**
@@ -662,9 +663,9 @@
      * This method must be idempotent.
      * This method acquires mStatusLock and mStatusListenerLock.
      */
-    void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
-            std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
-    void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
+    void updateStatus(int32_t status, const String8& cameraId,
+            std::initializer_list<int32_t> rejectedSourceStates);
+    void updateStatus(int32_t status, const String8& cameraId);
 
     // flashlight control
     sp<CameraFlashlight> mFlashlight;
@@ -675,7 +676,7 @@
     // guard mTorchUidMap
     Mutex                mTorchUidMapMutex;
     // camera id -> torch status
-    KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
+    KeyedVector<String8, int32_t> mTorchStatusMap;
     // camera id -> torch client binder
     // only store the last client that turns on each camera's torch mode
     KeyedVector<String8, sp<IBinder>> mTorchClientMap;
@@ -688,15 +689,15 @@
     // handle torch mode status change and invoke callbacks. mTorchStatusMutex
     // should be locked.
     void onTorchStatusChangedLocked(const String8& cameraId,
-            ICameraServiceListener::TorchStatus newStatus);
+            int32_t newStatus);
 
     // get a camera's torch status. mTorchStatusMutex should be locked.
     status_t getTorchStatusLocked(const String8 &cameraId,
-            ICameraServiceListener::TorchStatus *status) const;
+            int32_t *status) const;
 
     // set a camera's torch status. mTorchStatusMutex should be locked.
     status_t setTorchStatusLocked(const String8 &cameraId,
-            ICameraServiceListener::TorchStatus status);
+            int32_t status);
 
     // IBinder::DeathRecipient implementation
     virtual void        binderDied(const wp<IBinder> &who);
@@ -708,25 +709,25 @@
     /**
      * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
      *
-     * Returns OK on success, or a negative error code.
+     * Sets Status to a service-specific error on failure
      */
-    status_t            initializeShimMetadata(int cameraId);
+    binder::Status      initializeShimMetadata(int cameraId);
 
     /**
      * Get the cached CameraParameters for the camera. If they haven't been
      * cached yet, then initialize them for the first time.
      *
-     * Returns OK on success, or a negative error code.
+     * Sets Status to a service-specific error on failure
      */
-    status_t            getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
+    binder::Status      getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
 
     /**
      * Generate the CameraCharacteristics metadata required by the Camera2 API
      * from the available HAL1 CameraParameters and CameraInfo.
      *
-     * Returns OK on success, or a negative error code.
+     * Sets Status to a service-specific error on failure
      */
-    status_t            generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
+    binder::Status      generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
 
     static int getCallingPid();
 
@@ -742,8 +743,8 @@
      */
     static int getCameraPriorityFromProcState(int procState);
 
-    static status_t makeClient(const sp<CameraService>& cameraService,
-            const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
+    static binder::Status makeClient(const sp<CameraService>& cameraService,
+            const sp<IInterface>& cameraCb, const String16& packageName, int cameraId,
             int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
             int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
             /*out*/sp<BasicClient>* client);
@@ -758,12 +759,12 @@
 };
 
 template<class Func>
-void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
+void CameraService::CameraState::updateStatus(int32_t status,
         const String8& cameraId,
-        std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
+        std::initializer_list<int32_t> rejectSourceStates,
         Func onStatusUpdatedLocked) {
     Mutex::Autolock lock(mStatusLock);
-    ICameraServiceListener::Status oldStatus = mStatus;
+    int32_t oldStatus = mStatus;
     mStatus = status;
 
     if (oldStatus == status) {
@@ -773,9 +774,9 @@
     ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
             cameraId.string(), oldStatus, status);
 
-    if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
-        (status != ICameraServiceListener::STATUS_PRESENT &&
-         status != ICameraServiceListener::STATUS_ENUMERATING)) {
+    if (oldStatus == hardware::ICameraServiceListener::STATUS_NOT_PRESENT &&
+            (status != hardware::ICameraServiceListener::STATUS_PRESENT &&
+             status != hardware::ICameraServiceListener::STATUS_ENUMERATING)) {
 
         ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
                 __FUNCTION__);
@@ -800,13 +801,22 @@
     onStatusUpdatedLocked(cameraId, status);
 }
 
+#define STATUS_ERROR(errorCode, errorString) \
+    binder::Status::fromServiceSpecificError(errorCode, \
+            String8::format("%s:%d: %s", __FUNCTION__, __LINE__, errorString))
+
+#define STATUS_ERROR_FMT(errorCode, errorString, ...) \
+    binder::Status::fromServiceSpecificError(errorCode, \
+            String8::format("%s:%d: " errorString, __FUNCTION__, __LINE__, __VA_ARGS__))
+
 
 template<class CALLBACK, class CLIENT>
-status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
+binder::Status CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
         int halVersion, const String16& clientPackageName, int clientUid, int clientPid,
         apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
         /*out*/sp<CLIENT>& device) {
-    status_t ret = NO_ERROR;
+    binder::Status ret = binder::Status::ok();
+
     String8 clientName8(clientPackageName);
 
     ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
@@ -821,14 +831,16 @@
                 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
 
         if (lock == nullptr) {
-            ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
+            ALOGE("CameraService::connect (PID %d) rejected (too many other clients connecting)."
                     , clientPid);
-            return -EBUSY;
+            return STATUS_ERROR_FMT(ERROR_MAX_CAMERAS_IN_USE,
+                    "Cannot open camera %s for \"%s\" (PID %d): Too many other clients connecting",
+                    cameraId.string(), clientName8.string(), clientPid);
         }
 
         // Enforce client permissions and do basic sanity checks
-        if((ret = validateConnectLocked(cameraId, /*inout*/clientUid, /*inout*/clientPid)) !=
-                NO_ERROR) {
+        if(!(ret = validateConnectLocked(cameraId, clientName8,
+                /*inout*/clientUid, /*inout*/clientPid)).isOk()) {
             return ret;
         }
 
@@ -837,22 +849,37 @@
         if (shimUpdateOnly) {
             auto cameraState = getCameraState(cameraId);
             if (cameraState != nullptr) {
-                if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
+                if (!cameraState->getShimParams().isEmpty()) return ret;
             }
         }
 
+        status_t err;
+
         sp<BasicClient> clientTmp = nullptr;
         std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
-        if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
+        if ((err = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
                 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
                 /*out*/&partial)) != NO_ERROR) {
-            return ret;
+            switch (err) {
+                case -ENODEV:
+                    return STATUS_ERROR_FMT(ERROR_DISCONNECTED,
+                            "No camera device with ID \"%s\" currently available",
+                            cameraId.string());
+                case -EBUSY:
+                    return STATUS_ERROR_FMT(ERROR_CAMERA_IN_USE,
+                            "Higher-priority client using camera, ID \"%s\" currently unavailable",
+                            cameraId.string());
+                default:
+                    return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
+                            "Unexpected error %s (%d) opening camera \"%s\"",
+                            strerror(-err), err, cameraId.string());
+            }
         }
 
         if (clientTmp.get() != nullptr) {
             // Handle special case for API1 MediaRecorder where the existing client is returned
             device = static_cast<CLIENT*>(clientTmp.get());
-            return NO_ERROR;
+            return ret;
         }
 
         // give flashlight a chance to close devices if necessary.
@@ -863,15 +890,16 @@
         if (id == -1) {
             ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
                     cameraId.string());
-            return BAD_VALUE;
+            return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
+                    "Bad camera ID \"%s\" passed to camera open", cameraId.string());
         }
 
         int facing = -1;
         int deviceVersion = getDeviceVersion(id, /*out*/&facing);
         sp<BasicClient> tmp = nullptr;
-        if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
+        if(!(ret = makeClient(this, cameraCb, clientPackageName, id, facing, clientPid,
                 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
-                /*out*/&tmp)) != NO_ERROR) {
+                /*out*/&tmp)).isOk()) {
             return ret;
         }
         client = static_cast<CLIENT*>(tmp.get());
@@ -879,9 +907,11 @@
         LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
                 __FUNCTION__);
 
-        if ((ret = client->initialize(mModule)) != OK) {
+        if ((err = client->initialize(mModule)) != OK) {
             ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
-            return ret;
+            return STATUS_ERROR_FMT(ERROR_INVALID_OPERATION,
+                    "Failed to initialize camera \"%s\": %s (%d)", cameraId.string(),
+                    strerror(-err), err);
         }
 
         // Update shim paremeters for legacy clients
@@ -914,9 +944,12 @@
     // Important: release the mutex here so the client can call back into the service from its
     // destructor (can be at the end of the call)
     device = client;
-    return NO_ERROR;
+    return ret;
 }
 
+#undef STATUS_ERROR_FMT
+#undef STATUS_ERROR
+
 } // namespace android
 
 #endif