xref: /aosp_15_r20/frameworks/av/services/camera/libcameraservice/common/CameraDeviceBase.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_CAMERADEVICEBASE_H
18 #define ANDROID_SERVERS_CAMERA_CAMERADEVICEBASE_H
19 
20 #include <list>
21 
22 #include <utils/RefBase.h>
23 #include <utils/String16.h>
24 #include <utils/Vector.h>
25 #include <utils/KeyedVector.h>
26 #include <utils/Timers.h>
27 #include <utils/List.h>
28 #include <gui/Flags.h>
29 
30 #include "hardware/camera2.h"
31 #include "camera/CameraMetadata.h"
32 #include "camera/CaptureResult.h"
33 #include "gui/IGraphicBufferProducer.h"
34 #include "device3/Camera3StreamInterface.h"
35 #include "device3/StatusTracker.h"
36 #include "binder/Status.h"
37 #include "FrameProducer.h"
38 #include "utils/IPCTransport.h"
39 #include "utils/SessionConfigurationUtils.h"
40 
41 #include "CameraOfflineSessionBase.h"
42 
43 namespace android {
44 
45 namespace camera3 {
46 
47 typedef enum camera_stream_configuration_mode {
48     CAMERA_STREAM_CONFIGURATION_NORMAL_MODE = 0,
49     CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE = 1,
50     CAMERA_STREAM_CONFIGURATION_SHARED_MODE = 2,
51     CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START = 0x8000
52 } camera_stream_configuration_mode_t;
53 
54 // Matches definition of camera3_jpeg_blob in camera3.h and HIDL definition
55 // [email protected]:types.hal, needs to stay around till HIDL support is removed (for
56 // HIDL -> AIDL cameraBlob translation)
57 typedef struct camera_jpeg_blob {
58     uint16_t jpeg_blob_id;
59     uint32_t jpeg_size;
60 } camera_jpeg_blob_t;
61 
62 enum {
63     CAMERA_JPEG_BLOB_ID = 0x00FF,
64     CAMERA_JPEG_APP_SEGMENTS_BLOB_ID = 0x0100,
65 };
66 
67 } // namespace camera3
68 
69 using camera3::camera_request_template_t;;
70 using camera3::camera_stream_configuration_mode_t;
71 using camera3::camera_stream_rotation_t;
72 using camera3::SurfaceHolder;
73 
74 class CameraProviderManager;
75 
76 // Mapping of output stream index to surface ids
77 typedef std::unordered_map<int, std::vector<size_t> > SurfaceMap;
78 
79 /**
80  * Base interface for version >= 2 camera device classes, which interface to
81  * camera HAL device versions >= 2.
82  */
83 class CameraDeviceBase : public virtual FrameProducer {
84   public:
85     virtual ~CameraDeviceBase();
86 
87     virtual IPCTransport getTransportType() const = 0;
88 
89     /**
90      * The device vendor tag ID
91      */
92     virtual metadata_vendor_id_t getVendorTagId() const = 0;
93 
94     virtual status_t initialize(sp<CameraProviderManager> manager,
95             const std::string& monitorTags) = 0;
96     virtual status_t disconnect() = 0;
disconnectClient(int)97     virtual status_t disconnectClient(int) {return OK;};
98 
99     virtual status_t dump(int fd, const Vector<String16> &args) = 0;
100     virtual status_t startWatchingTags(const std::string &tags) = 0;
101     virtual status_t stopWatchingTags() = 0;
102     virtual status_t dumpWatchedEventsToVector(std::vector<std::string> &out) = 0;
103 
104     /**
105      * The physical camera device's static characteristics metadata buffer, or
106      * the logical camera's static characteristics if physical id is empty.
107      */
108     virtual const CameraMetadata& infoPhysical(const std::string& physicalId) const = 0;
109 
isCompositeJpegRDisabled()110     virtual bool isCompositeJpegRDisabled() const { return false; };
111 
112     struct PhysicalCameraSettings {
113         std::string cameraId;
114         CameraMetadata metadata;
115 
116         // Whether the physical camera supports testPatternMode/testPatternData
117         bool mHasTestPatternModeTag = true;
118         bool mHasTestPatternDataTag = true;
119 
120         // Original value of TEST_PATTERN_MODE and DATA so that they can be
121         // restored when sensor muting is turned off
122         int32_t mOriginalTestPatternMode = 0;
123         int32_t mOriginalTestPatternData[4] = {};
124 
125         // Original value of SETTINGS_OVERRIDE so that they can be restored if
126         // camera service isn't overwriting the app value.
127         int32_t mOriginalSettingsOverride = ANDROID_CONTROL_SETTINGS_OVERRIDE_OFF;
128     };
129     typedef List<PhysicalCameraSettings> PhysicalCameraSettingsList;
130 
131     /**
132      * Submit request for capture. The CameraDevice takes ownership of the
133      * passed-in buffer.
134      * Output lastFrameNumber is the expected frame number of this request.
135      */
136     virtual status_t capture(CameraMetadata &request, int64_t *lastFrameNumber = NULL) = 0;
137 
138     /**
139      * Submit a list of requests.
140      * Output lastFrameNumber is the expected last frame number of the list of requests.
141      */
142     virtual status_t captureList(const List<const PhysicalCameraSettingsList> &requests,
143                                  const std::list<SurfaceMap> &surfaceMaps,
144                                  int64_t *lastFrameNumber = NULL) = 0;
145 
146     /**
147      * Submit request for streaming. The CameraDevice makes a copy of the
148      * passed-in buffer and the caller retains ownership.
149      * Output lastFrameNumber is the last frame number of the previous streaming request.
150      */
151     virtual status_t setStreamingRequest(const CameraMetadata &request,
152                                          int64_t *lastFrameNumber = NULL) = 0;
153 
154     /**
155      * Submit a list of requests for streaming.
156      * Output lastFrameNumber is the last frame number of the previous streaming request.
157      */
158     virtual status_t setStreamingRequestList(const List<const PhysicalCameraSettingsList> &requests,
159                                              const std::list<SurfaceMap> &surfaceMaps,
160                                              int64_t *lastFrameNumber = NULL) = 0;
161 
162     /**
163      * Clear the streaming request slot.
164      * Output lastFrameNumber is the last frame number of the previous streaming request.
165      */
166     virtual status_t clearStreamingRequest(int64_t *lastFrameNumber = NULL) = 0;
167 
168     /**
169      * Wait until a request with the given ID has been dequeued by the
170      * HAL. Returns TIMED_OUT if the timeout duration is reached. Returns
171      * immediately if the latest request received by the HAL has this id.
172      */
173     virtual status_t waitUntilRequestReceived(int32_t requestId,
174             nsecs_t timeout) = 0;
175 
176     /**
177      * Create an output stream of the requested size, format, rotation and dataspace
178      *
179      * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
180      * logical dimensions of the buffer, not the number of bytes.
181      */
182     virtual status_t createStream(sp<Surface> consumer,
183             uint32_t width, uint32_t height, int format,
184             android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
185             const std::string& physicalCameraId,
186             const std::unordered_set<int32_t>  &sensorPixelModesUsed,
187             std::vector<int> *surfaceIds = nullptr,
188             int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
189             bool isShared = false, bool isMultiResolution = false,
190             uint64_t consumerUsage = 0,
191             int64_t dynamicProfile = ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
192             int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
193             int timestampBase = OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
194             int mirrorMode = OutputConfiguration::MIRROR_MODE_AUTO,
195             int32_t colorSpace = ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED,
196             bool useReadoutTimestamp = false)
197             = 0;
198 
199     /**
200      * Create an output stream of the requested size, format, rotation and
201      * dataspace with a number of consumers.
202      *
203      * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
204      * logical dimensions of the buffer, not the number of bytes.
205      */
206     virtual status_t createStream(const std::vector<SurfaceHolder>& consumers,
207             bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
208             android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
209             const std::string& physicalCameraId,
210             const std::unordered_set<int32_t> &sensorPixelModesUsed,
211             std::vector<int> *surfaceIds = nullptr,
212             int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
213             bool isShared = false, bool isMultiResolution = false,
214             uint64_t consumerUsage = 0,
215             int64_t dynamicProfile = ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD,
216             int64_t streamUseCase = ANDROID_SCALER_AVAILABLE_STREAM_USE_CASES_DEFAULT,
217             int timestampBase = OutputConfiguration::TIMESTAMP_BASE_DEFAULT,
218             int32_t colorSpace = ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED,
219             bool useReadoutTimestamp = false)
220             = 0;
221 
222     /**
223      * Create an input stream of width, height, and format.
224      *
225      * Return value is the stream ID if non-negative and an error if negative.
226      */
227     virtual status_t createInputStream(uint32_t width, uint32_t height,
228             int32_t format, bool multiResolution, /*out*/ int32_t *id) = 0;
229 
230     struct StreamInfo {
231         uint32_t width;
232         uint32_t height;
233 
234         uint32_t format;
235         bool formatOverridden;
236         uint32_t originalFormat;
237 
238         android_dataspace dataSpace;
239         bool dataSpaceOverridden;
240         android_dataspace originalDataSpace;
241         int64_t dynamicRangeProfile;
242         int32_t colorSpace;
243 
StreamInfoStreamInfo244         StreamInfo() : width(0), height(0), format(0), formatOverridden(false), originalFormat(0),
245                 dataSpace(HAL_DATASPACE_UNKNOWN), dataSpaceOverridden(false),
246                 originalDataSpace(HAL_DATASPACE_UNKNOWN),
247                 dynamicRangeProfile(ANDROID_REQUEST_AVAILABLE_DYNAMIC_RANGE_PROFILES_MAP_STANDARD),
248                 colorSpace(ANDROID_REQUEST_AVAILABLE_COLOR_SPACE_PROFILES_MAP_UNSPECIFIED) {}
249         /**
250          * Check whether the format matches the current or the original one in case
251          * it got overridden.
252          */
matchFormatStreamInfo253         bool matchFormat(uint32_t clientFormat) const {
254             if ((formatOverridden && (originalFormat == clientFormat)) ||
255                     (format == clientFormat)) {
256                 return true;
257             }
258             return false;
259         }
260 
261         /**
262          * Check whether the dataspace matches the current or the original one in case
263          * it got overridden.
264          */
matchDataSpaceStreamInfo265         bool matchDataSpace(android_dataspace clientDataSpace) const {
266             if ((dataSpaceOverridden && (originalDataSpace == clientDataSpace)) ||
267                     (dataSpace == clientDataSpace)) {
268                 return true;
269             }
270             return false;
271         }
272 
273     };
274 
275     /**
276      * Get information about a given stream.
277      */
278     virtual status_t getStreamInfo(int id, StreamInfo *streamInfo) = 0;
279 
280     /**
281      * Set stream gralloc buffer transform
282      */
283     virtual status_t setStreamTransform(int id, int transform) = 0;
284 
285     /**
286      * Delete stream. Must not be called if there are requests in flight which
287      * reference that stream.
288      */
289     virtual status_t deleteStream(int id) = 0;
290 
291 
292     /**
293      * This function is responsible for configuring camera streams at the start of a session.
294      * In shared session mode, where multiple clients may access the camera, camera service
295      * applies a predetermined shared session configuration. If the camera is opened in non-shared
296      * mode, this function is a no-op.
297      */
298     virtual status_t beginConfigure() = 0;
299 
300     /**
301      * In shared session mode, this function retrieves the stream ID associated with a specific
302      * output configuration.
303      */
304     virtual status_t getSharedStreamId(const OutputConfiguration &config, int *streamId) = 0;
305 
306     /**
307      * In shared session mode, this function add surfaces to an existing shared stream ID.
308      */
309     virtual status_t addSharedSurfaces(int streamId,
310             const std::vector<android::camera3::OutputStreamInfo> &outputInfo,
311             const std::vector<SurfaceHolder>& surfaces, std::vector<int> *surfaceIds = nullptr) = 0;
312 
313     /**
314      * In shared session mode, this function remove surfaces from an existing shared stream ID.
315      */
316     virtual status_t removeSharedSurfaces(int streamId, const std::vector<size_t> &surfaceIds) = 0;
317 
318     /**
319      * Take the currently-defined set of streams and configure the HAL to use
320      * them. This is a long-running operation (may be several hundered ms).
321      *
322      * The device must be idle (see waitUntilDrained) before calling this.
323      *
324      * Returns OK on success; otherwise on error:
325      * - BAD_VALUE if the set of streams was invalid (e.g. fmts or sizes)
326      * - INVALID_OPERATION if the device was in the wrong state
327      */
328     virtual status_t configureStreams(const CameraMetadata& sessionParams,
329             int operatingMode =
330             camera_stream_configuration_mode_t::CAMERA_STREAM_CONFIGURATION_NORMAL_MODE) = 0;
331 
332     /**
333      * Retrieve a list of all stream ids that were advertised as capable of
334      * supporting offline processing mode by Hal after the last stream configuration.
335      */
336     virtual void getOfflineStreamIds(std::vector<int> *offlineStreamIds) = 0;
337 
338 #if WB_CAMERA3_AND_PROCESSORS_WITH_DEPENDENCIES
339     // get the surface of the input stream
340     virtual status_t getInputSurface(sp<Surface> *surface) = 0;
341 #else
342     // get the buffer producer of the input stream
343     virtual status_t getInputBufferProducer(
344             sp<IGraphicBufferProducer> *producer) = 0;
345 #endif
346 
347     /**
348      * Create a metadata buffer with fields that the HAL device believes are
349      * best for the given use case
350      */
351     virtual status_t createDefaultRequest(camera_request_template_t templateId,
352             CameraMetadata *request) = 0;
353 
354     /**
355      * Wait until all requests have been processed. Returns INVALID_OPERATION if
356      * the streaming slot is not empty, or TIMED_OUT if the requests haven't
357      * finished processing in 10 seconds.
358      */
359     virtual status_t waitUntilDrained() = 0;
360 
361     /**
362      * Get Jpeg buffer size for a given jpeg resolution.
363      * Negative values are error codes.
364      */
365     virtual ssize_t getJpegBufferSize(const CameraMetadata &info, uint32_t width,
366             uint32_t height) const = 0;
367 
368     /**
369      * Connect HAL notifications to a listener. Overwrites previous
370      * listener. Set to NULL to stop receiving notifications.
371      */
372     virtual status_t setNotifyCallback(wp<NotificationListener> listener) = 0;
373 
374     /**
375      * Whether the device supports calling notifyAutofocus, notifyAutoExposure,
376      * and notifyAutoWhitebalance; if this returns false, the client must
377      * synthesize these notifications from received frame metadata.
378      */
379     virtual bool     willNotify3A() = 0;
380 
381     /**
382      * Trigger auto-focus. The latest ID used in a trigger autofocus or cancel
383      * autofocus call will be returned by the HAL in all subsequent AF
384      * notifications.
385      */
386     virtual status_t triggerAutofocus(uint32_t id) = 0;
387 
388     /**
389      * Cancel auto-focus. The latest ID used in a trigger autofocus/cancel
390      * autofocus call will be returned by the HAL in all subsequent AF
391      * notifications.
392      */
393     virtual status_t triggerCancelAutofocus(uint32_t id) = 0;
394 
395     /**
396      * Trigger pre-capture metering. The latest ID used in a trigger pre-capture
397      * call will be returned by the HAL in all subsequent AE and AWB
398      * notifications.
399      */
400     virtual status_t triggerPrecaptureMetering(uint32_t id) = 0;
401 
402     /**
403      * Flush all pending and in-flight requests. Blocks until flush is
404      * complete.
405      * Output lastFrameNumber is the last frame number of the previous streaming request.
406      */
407     virtual status_t flush(int64_t *lastFrameNumber = NULL) = 0;
408 
409     /**
410      * Prepare stream by preallocating buffers for it asynchronously.
411      * Calls notifyPrepared() once allocation is complete.
412      */
413     virtual status_t prepare(int streamId) = 0;
414 
415     /**
416      * Free stream resources by dumping its unused gralloc buffers.
417      */
418     virtual status_t tearDown(int streamId) = 0;
419 
420     /**
421      * Add buffer listener for a particular stream in the device.
422      */
423     virtual status_t addBufferListenerForStream(int streamId,
424             wp<camera3::Camera3StreamBufferListener> listener) = 0;
425 
426     /**
427      * Prepare stream by preallocating up to maxCount buffers for it asynchronously.
428      * Calls notifyPrepared() once allocation is complete.
429      */
430     virtual status_t prepare(int maxCount, int streamId) = 0;
431 
432     /**
433      * Set the deferred consumer surface and finish the rest of the stream configuration.
434      */
435     virtual status_t setConsumerSurfaces(int streamId,
436             const std::vector<SurfaceHolder>& consumers, std::vector<int> *surfaceIds /*out*/) = 0;
437 
438     /**
439      * Update a given stream.
440      */
441     virtual status_t updateStream(int streamId, const std::vector<SurfaceHolder> &newSurfaces,
442             const std::vector<android::camera3::OutputStreamInfo> &outputInfo,
443             const std::vector<size_t> &removedSurfaceIds,
444             KeyedVector<sp<Surface>, size_t> *outputMap/*out*/) = 0;
445 
446     /**
447      * Drop buffers for stream of streamId if dropping is true. If dropping is false, do not
448      * drop buffers for stream of streamId.
449      */
450     virtual status_t dropStreamBuffers(bool /*dropping*/, int /*streamId*/) = 0;
451 
452     /**
453      * Returns the maximum expected time it'll take for all currently in-flight
454      * requests to complete, based on their settings
455      */
456     virtual nsecs_t getExpectedInFlightDuration() = 0;
457 
458     /**
459      * switch to offline session
460      */
461     virtual status_t switchToOffline(
462             const std::vector<int32_t>& streamsToKeep,
463             /*out*/ sp<CameraOfflineSessionBase>* session) = 0;
464 
465     /**
466      * Set the current behavior for the ROTATE_AND_CROP control when in AUTO.
467      *
468      * The value must be one of the ROTATE_AND_CROP_* values besides AUTO,
469      * and defaults to NONE.
470      */
471     virtual status_t setRotateAndCropAutoBehavior(
472             camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue,
473             bool fromHal = false) = 0;
474 
475     /**
476      * Set the current behavior for the AUTOFRAMING control when in AUTO.
477      *
478      * The value must be one of the AUTOFRAMING_* values besides AUTO.
479      */
480     virtual status_t setAutoframingAutoBehavior(
481             camera_metadata_enum_android_control_autoframing_t autoframingValue) = 0;
482 
483     /**
484      * Whether camera muting (producing black-only output) is supported.
485      *
486      * Calling setCameraMute(true) when this returns false will return an
487      * INVALID_OPERATION error.
488      */
489     virtual bool supportsCameraMute() = 0;
490 
491     /**
492      * Mute the camera.
493      *
494      * When muted, black image data is output on all output streams.
495      */
496     virtual status_t setCameraMute(bool enabled) = 0;
497 
498     /**
499      * Whether the camera device supports zoom override.
500      */
501     virtual bool supportsZoomOverride() = 0;
502 
503     // Set/reset zoom override
504     virtual status_t setZoomOverride(int32_t zoomOverride) = 0;
505 
506     /**
507      * Enable/disable camera service watchdog
508      */
509     virtual status_t setCameraServiceWatchdog(bool enabled) = 0;
510 
511     /**
512      * Get the status tracker of the camera device
513      */
514     virtual wp<camera3::StatusTracker> getStatusTracker() = 0;
515 
516     /**
517      * If the device is in eror state
518      */
519     virtual bool hasDeviceError() = 0;
520 
521     /**
522      * Set bitmask for image dump flag
523      */
setImageDumpMask(int mask)524     void setImageDumpMask(int mask) { mImageDumpMask = mask; }
525 
526     /**
527      * Set stream use case overrides
528      */
setStreamUseCaseOverrides(const std::vector<int64_t> & useCaseOverrides)529     void setStreamUseCaseOverrides(const std::vector<int64_t>& useCaseOverrides) {
530           mStreamUseCaseOverrides = useCaseOverrides;
531     }
532 
clearStreamUseCaseOverrides()533     void clearStreamUseCaseOverrides() {}
534 
535     /**
536      * The injection camera session to replace the internal camera
537      * session.
538      */
539     virtual status_t injectCamera(const std::string& injectedCamId,
540             sp<CameraProviderManager> manager) = 0;
541 
542     /**
543      * Stop the injection camera and restore to internal camera session.
544      */
545     virtual status_t stopInjection() = 0;
546 
547     // Inject session parameters into an existing client.
548     virtual status_t injectSessionParams(
549         const CameraMetadata& sessionParams) = 0;
550 
551 protected:
552     bool mImageDumpMask = 0;
553     std::vector<int64_t> mStreamUseCaseOverrides;
554 };
555 
556 }; // namespace android
557 
558 #endif
559