xref: /aosp_15_r20/frameworks/av/services/camera/libcameraservice/api2/CameraDeviceClient.h (revision ec779b8e0859a360c3d303172224686826e6e0e1)
1 /*
2  * Copyright (C) 2013-2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ANDROID_SERVERS_CAMERA_PHOTOGRAPHY_CAMERADEVICECLIENT_H
18 #define ANDROID_SERVERS_CAMERA_PHOTOGRAPHY_CAMERADEVICECLIENT_H
19 
20 #include <android/hardware/camera2/BnCameraDeviceUser.h>
21 #include <android/hardware/camera2/ICameraDeviceCallbacks.h>
22 #include <camera/camera2/OutputConfiguration.h>
23 #include <camera/camera2/SessionConfiguration.h>
24 #include <camera/camera2/SubmitInfo.h>
25 #include <unordered_map>
26 #include <gui/Flags.h>  // remove with WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
27 
28 #include <fmq/AidlMessageQueueCpp.h>
29 
30 #include "CameraOfflineSessionClient.h"
31 #include "CameraService.h"
32 #include "common/FrameProcessorBase.h"
33 #include "common/Camera2ClientBase.h"
34 #include "CompositeStream.h"
35 #include "utils/CameraServiceProxyWrapper.h"
36 #include "utils/SessionConfigurationUtils.h"
37 
38 using android::camera3::OutputStreamInfo;
39 using android::camera3::CompositeStream;
40 
41 namespace android {
42 
43 #if WB_LIBCAMERASERVICE_WITH_DEPENDENCIES
44 typedef uint64_t SurfaceKey;
45 #else
46 typedef sp<IBinder> SurfaceKey;
47 #endif
48 
49 struct CameraDeviceClientBase :
50          public CameraService::BasicClient,
51          public hardware::camera2::BnCameraDeviceUser
52 {
53     typedef hardware::camera2::ICameraDeviceCallbacks TCamCallbacks;
54 
getRemoteCallbackCameraDeviceClientBase55     const sp<hardware::camera2::ICameraDeviceCallbacks>& getRemoteCallback() {
56         return mRemoteCallback;
57     }
58 
59 protected:
60     CameraDeviceClientBase(
61             const sp<CameraService>& cameraService,
62             const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
63             std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
64             const AttributionSourceState& clientAttribution, int callingPid,
65             bool systemNativeClient, const std::string& cameraId, int api1CameraId,
66             int cameraFacing, int sensorOrientation, int servicePid, int rotationOverride,
67             bool sharedMode);
68 
69     sp<hardware::camera2::ICameraDeviceCallbacks> mRemoteCallback;
70 };
71 
72 /**
73  * Implements the binder ICameraDeviceUser API,
74  * meant for HAL3-public implementation of
75  * android.hardware.photography.CameraDevice
76  */
77 class CameraDeviceClient :
78         public Camera2ClientBase<CameraDeviceClientBase>,
79         public camera2::FrameProcessorBase::FilteredListener
80 {
81 public:
82     /**
83      * ICameraDeviceUser interface (see ICameraDeviceUser for details)
84      */
85 
86     // Note that the callee gets a copy of the metadata.
87     virtual binder::Status submitRequest(
88             const hardware::camera2::CaptureRequest& request,
89             bool streaming = false,
90             /*out*/
91             hardware::camera2::utils::SubmitInfo *submitInfo = nullptr) override;
92     // List of requests are copied.
93     virtual binder::Status submitRequestList(
94             const std::vector<hardware::camera2::CaptureRequest>& requests,
95             bool streaming = false,
96             /*out*/
97             hardware::camera2::utils::SubmitInfo *submitInfo = nullptr) override;
98     virtual binder::Status cancelRequest(int requestId,
99             /*out*/
100             int64_t* lastFrameNumber = NULL) override;
101 
102     virtual binder::Status beginConfigure() override;
103 
104     virtual binder::Status endConfigure(int operatingMode,
105             const hardware::camera2::impl::CameraMetadataNative& sessionParams,
106             int64_t startTimeMs,
107             /*out*/
108             std::vector<int>* offlineStreamIds) override;
109 
110     // Verify specific session configuration.
111     virtual binder::Status isSessionConfigurationSupported(
112             const SessionConfiguration& sessionConfiguration,
113             /*out*/
114             bool* streamStatus) override;
115 
116     // Returns -EBUSY if device is not idle or in error state
117     virtual binder::Status deleteStream(int streamId) override;
118 
119     virtual binder::Status createStream(
120             const hardware::camera2::params::OutputConfiguration &outputConfiguration,
121             /*out*/
122             int32_t* newStreamId = NULL) override;
123 
124     // Create an input stream of width, height, and format.
125     virtual binder::Status createInputStream(int width, int height, int format,
126             bool isMultiResolution,
127             /*out*/
128             int32_t* newStreamId = NULL) override;
129 
130     // Get the buffer producer of the input stream
131     virtual binder::Status getInputSurface(
132             /*out*/
133             view::Surface *inputSurface) override;
134 
135     // Create a request object from a template.
136     virtual binder::Status createDefaultRequest(int templateId,
137             /*out*/
138             hardware::camera2::impl::CameraMetadataNative* request) override;
139 
140     // Get the static metadata for the camera
141     // -- Caller owns the newly allocated metadata
142     virtual binder::Status getCameraInfo(
143             /*out*/
144             hardware::camera2::impl::CameraMetadataNative* cameraCharacteristics) override;
145 
146     // Wait until all the submitted requests have finished processing
147     virtual binder::Status waitUntilIdle() override;
148 
149     // Flush all active and pending requests as fast as possible
150     virtual binder::Status flush(
151             /*out*/
152             int64_t* lastFrameNumber = NULL) override;
153 
154     // Prepare stream by preallocating its buffers
155     virtual binder::Status prepare(int32_t streamId) override;
156 
157     // Tear down stream resources by freeing its unused buffers
158     virtual binder::Status tearDown(int32_t streamId) override;
159 
160     // Prepare stream by preallocating up to maxCount of its buffers
161     virtual binder::Status prepare2(int32_t maxCount, int32_t streamId) override;
162 
163     // Update an output configuration
164     virtual binder::Status updateOutputConfiguration(int streamId,
165             const hardware::camera2::params::OutputConfiguration &outputConfiguration) override;
166 
167     // Finalize the output configurations with surfaces not added before.
168     virtual binder::Status finalizeOutputConfigurations(int32_t streamId,
169             const hardware::camera2::params::OutputConfiguration &outputConfiguration) override;
170 
171     virtual binder::Status setCameraAudioRestriction(int32_t mode) override;
172 
173     virtual binder::Status getCaptureResultMetadataQueue(
174           android::hardware::common::fmq::MQDescriptor<
175           int8_t, android::hardware::common::fmq::SynchronizedReadWrite>*
176           aidl_return) override;
177 
178     virtual binder::Status getGlobalAudioRestriction(/*out*/int32_t* outMode) override;
179 
180     virtual binder::Status switchToOffline(
181             const sp<hardware::camera2::ICameraDeviceCallbacks>& cameraCb,
182             const std::vector<int>& offlineOutputIds,
183             /*out*/
184             sp<hardware::camera2::ICameraOfflineSession>* session) override;
185 
186     virtual binder::Status isPrimaryClient(/*out*/bool* isPrimary) override;
187 
188     /**
189      * Interface used by CameraService
190      */
191 
192     CameraDeviceClient(const sp<CameraService>& cameraService,
193                        const sp<hardware::camera2::ICameraDeviceCallbacks>& remoteCallback,
194                        std::shared_ptr<CameraServiceProxyWrapper> cameraServiceProxyWrapper,
195                        std::shared_ptr<AttributionAndPermissionUtils> attributionAndPermissionUtils,
196                        const AttributionSourceState& clientAttribution, int callingPid,
197                        bool clientPackageOverride, const std::string& cameraId, int cameraFacing,
198                        int sensorOrientation, int servicePid, bool overrideForPerfClass,
199                        int rotationOverride, const std::string& originalCameraId, bool sharedMode,
200                        bool isVendorClient);
201     virtual ~CameraDeviceClient();
202 
203     virtual status_t      initialize(sp<CameraProviderManager> manager,
204             const std::string& monitorTags) override;
205 
206     virtual status_t      setRotateAndCropOverride(uint8_t rotateAndCrop,
207             bool fromHal = false) override;
208 
209     virtual status_t      setAutoframingOverride(uint8_t autoframingValue) override;
210 
211     virtual bool          supportsCameraMute();
212     virtual status_t      setCameraMute(bool enabled);
213 
214     virtual bool          supportsZoomOverride() override;
215     virtual status_t      setZoomOverride(int32_t zoomOverride) override;
216 
217     virtual status_t      dump(int fd, const Vector<String16>& args);
218 
219     virtual status_t      dumpClient(int fd, const Vector<String16>& args);
220 
221     virtual status_t      startWatchingTags(const std::string &tags, int out);
222     virtual status_t      stopWatchingTags(int out);
223     virtual status_t      dumpWatchedEventsToVector(std::vector<std::string> &out);
224 
225     virtual status_t      setCameraServiceWatchdog(bool enabled);
226 
227     virtual void          setStreamUseCaseOverrides(const std::vector<int64_t>& useCaseOverrides);
228     virtual void          clearStreamUseCaseOverrides() override;
229 
230     /**
231      * Device listener interface
232      */
233 
234     virtual void notifyIdle(int64_t requestCount, int64_t resultErrorCount, bool deviceError,
235                             std::pair<int32_t, int32_t> mostRequestedFpsRange,
236                             const std::vector<hardware::CameraStreamStats>& streamStats);
237     virtual void notifyError(int32_t errorCode,
238                              const CaptureResultExtras& resultExtras);
239     virtual void notifyShutter(const CaptureResultExtras& resultExtras, nsecs_t timestamp);
240     virtual void notifyPrepared(int streamId);
241     virtual void notifyRequestQueueEmpty();
242     virtual void notifyRepeatingRequestError(long lastFrameNumber);
243     virtual void notifyClientSharedAccessPriorityChanged(bool primaryClient);
244 
setImageDumpMask(int mask)245     void setImageDumpMask(int mask) { if (mDevice != nullptr) mDevice->setImageDumpMask(mask); }
246     /**
247      * Interface used by independent components of CameraDeviceClient.
248      */
249 protected:
250     /** FilteredListener implementation **/
251 
252     size_t writeResultMetadataIntoResultQueue(const CameraMetadata &result);
253     std::vector<PhysicalCaptureResultInfo> convertToFMQ(
254             const std::vector<PhysicalCaptureResultInfo> &physicalResults);
255     virtual void          onResultAvailable(const CaptureResult& result);
256     virtual void          detachDevice();
257 
258     bool supportsUltraHighResolutionCapture(const std::string &cameraId);
259 
260     bool isSensorPixelModeConsistent(const std::list<int> &streamIdList,
261             const CameraMetadata &settings);
262 
263     const CameraMetadata &getStaticInfo(const std::string &cameraId);
264 
265 private:
266     using MetadataQueue = AidlMessageQueueCpp<
267             int8_t, android::hardware::common::fmq::SynchronizedReadWrite>;
268     using CameraMetadataInfo = android::hardware::camera2::CameraMetadataInfo;
269     status_t CreateMetadataQueue(
270             std::unique_ptr<MetadataQueue>* metadata_queue, uint32_t default_size);
271     // StreamSurfaceId encapsulates streamId + surfaceId for a particular surface.
272     // streamId specifies the index of the stream the surface belongs to, and the
273     // surfaceId specifies the index of the surface within the stream. (one stream
274     // could contain multiple surfaces.)
275     class StreamSurfaceId final {
276     public:
StreamSurfaceId()277         StreamSurfaceId() {
278             mStreamId = -1;
279             mSurfaceId = -1;
280         }
StreamSurfaceId(int32_t streamId,int32_t surfaceId)281         StreamSurfaceId(int32_t streamId, int32_t surfaceId) {
282             mStreamId = streamId;
283             mSurfaceId = surfaceId;
284         }
streamId()285         int32_t streamId() const {
286             return mStreamId;
287         }
surfaceId()288         int32_t surfaceId() const {
289             return mSurfaceId;
290         }
291 
292     private:
293         int32_t mStreamId;
294         int32_t mSurfaceId;
295 
296     }; // class StreamSurfaceId
297 
298 private:
299     /** ICameraDeviceUser interface-related private members */
300 
301     /** Preview callback related members */
302     sp<camera2::FrameProcessorBase> mFrameProcessor;
303 
304     std::vector<int32_t> mSupportedPhysicalRequestKeys;
305 
306     template<typename TProviderPtr>
307     status_t      initializeImpl(TProviderPtr providerPtr, const std::string& monitorTags);
308 
309     /** Utility members */
310     binder::Status checkPidStatus(const char* checkLocation);
311     bool enforceRequestPermissions(CameraMetadata& metadata);
312 
313     // Create an output stream with surface deferred for future.
314     binder::Status createDeferredSurfaceStreamLocked(
315             const hardware::camera2::params::OutputConfiguration &outputConfiguration,
316             bool isShared,
317             int* newStreamId = NULL);
318 
319     // Utility method to insert the surface into SurfaceMap
320     binder::Status insertSurfaceLocked(const ParcelableSurfaceType& surface,
321             /*out*/SurfaceMap* surfaceMap, /*out*/Vector<int32_t>* streamIds,
322             /*out*/int32_t*  currentStreamId);
323 
324     // A ParcelableSurfaceType can be either a view::Surface or IGBP.
325     // We use this type of surface when we need to be able to have a parcelable data type.
326     // view::Surface has helper functions to make converting between a regular Surface and a
327     // view::Surface easy.
328     status_t getSurfaceKey(ParcelableSurfaceType surface, SurfaceKey* out) const;
329     // Surface only
330     status_t getSurfaceKey(sp<Surface> surface, SurfaceKey* out) const;
331 
332     // IGraphicsBufferProducer binder -> Stream ID + Surface ID for output streams
333     KeyedVector<SurfaceKey, StreamSurfaceId> mStreamMap;
334 
335     // Stream ID -> OutputConfiguration. Used for looking up Surface by stream/surface index
336     KeyedVector<int32_t, hardware::camera2::params::OutputConfiguration> mConfiguredOutputs;
337 
338     // Dynamic range profile id -> Supported dynamic profiles bitmap within an single capture
339     // request
340     std::unordered_map<int64_t, int64_t> mDynamicProfileMap;
341 
342     struct InputStreamConfiguration {
343         bool configured;
344         int32_t width;
345         int32_t height;
346         int32_t format;
347         int32_t id;
348     } mInputStream;
349 
350     // Streaming request ID
351     int32_t mStreamingRequestId;
352     Mutex mStreamingRequestIdLock;
353     static const int32_t REQUEST_ID_NONE = -1;
354 
355     int32_t mRequestIdCounter;
356 
357     // Metadata queue to write the result metadata to.
358     std::unique_ptr<MetadataQueue> mResultMetadataQueue;
359 
360     std::vector<std::string> mPhysicalCameraIds;
361 
362     // The list of output streams whose surfaces are deferred. We have to track them separately
363     // as there are no surfaces available and can not be put into mStreamMap. Once the deferred
364     // Surface is configured, the stream id will be moved to mStreamMap.
365     Vector<int32_t> mDeferredStreams;
366 
367     // stream ID -> outputStreamInfo mapping
368     std::unordered_map<int32_t, OutputStreamInfo> mStreamInfoMap;
369 
370     // map high resolution camera id (logical / physical) -> list of stream ids configured
371     std::unordered_map<std::string, std::unordered_set<int>> mHighResolutionCameraIdToStreamIdSet;
372 
373     // set of high resolution camera id (logical / physical)
374     std::unordered_set<std::string> mHighResolutionSensors;
375 
376     // Synchronize access to 'mCompositeStreamMap'
377     Mutex mCompositeLock;
378     KeyedVector<SurfaceKey, sp<CompositeStream>> mCompositeStreamMap;
379 
380     sp<CameraProviderManager> mProviderManager;
381 
382     // Override the camera characteristics for performance class primary cameras.
383     bool mOverrideForPerfClass;
384 
385     // Various fields used to collect session statistics
386     struct RunningSessionStats {
387         // The string representation of object passed into CaptureRequest.setTag.
388         std::string mUserTag;
389         // The last set video stabilization mode
390         int mVideoStabilizationMode = -1;
391         // Whether a zoom_ratio < 1.0 has been used during this session
392         bool mUsedUltraWide = false;
393         // Whether a zoom settings override has been used during this session
394         bool mUsedSettingsOverrideZoom = false;
395     } mRunningSessionStats;
396 
397     // This only exists in case of camera ID Remapping.
398     const std::string mOriginalCameraId;
399 
400     bool mIsVendorClient = false;
401 };
402 
403 }; // namespace android
404 
405 #endif
406