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/String8.h>
24 #include <utils/String16.h>
25 #include <utils/Vector.h>
26 #include <utils/KeyedVector.h>
27 #include <utils/Timers.h>
28 #include <utils/List.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 
39 #include "CameraOfflineSessionBase.h"
40 
41 namespace android {
42 
43 namespace camera3 {
44 
45 typedef enum camera_request_template {
46     CAMERA_TEMPLATE_PREVIEW = 1,
47     CAMERA_TEMPLATE_STILL_CAPTURE = 2,
48     CAMERA_TEMPLATE_VIDEO_RECORD = 3,
49     CAMERA_TEMPLATE_VIDEO_SNAPSHOT = 4,
50     CAMERA_TEMPLATE_ZERO_SHUTTER_LAG = 5,
51     CAMERA_TEMPLATE_MANUAL = 6,
52     CAMERA_TEMPLATE_COUNT,
53     CAMERA_VENDOR_TEMPLATE_START = 0x40000000
54 } camera_request_template_t;
55 
56 typedef enum camera_stream_configuration_mode {
57     CAMERA_STREAM_CONFIGURATION_NORMAL_MODE = 0,
58     CAMERA_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE = 1,
59     CAMERA_VENDOR_STREAM_CONFIGURATION_MODE_START = 0x8000
60 } camera_stream_configuration_mode_t;
61 
62 typedef struct camera_jpeg_blob {
63     uint16_t jpeg_blob_id;
64     uint32_t jpeg_size;
65 } camera_jpeg_blob_t;
66 
67 enum {
68     CAMERA_JPEG_BLOB_ID = 0x00FF,
69     CAMERA_JPEG_APP_SEGMENTS_BLOB_ID = 0x0100,
70 };
71 
72 } // namespace camera3
73 
74 using camera3::camera_request_template_t;;
75 using camera3::camera_stream_configuration_mode_t;
76 using camera3::camera_stream_rotation_t;
77 
78 class CameraProviderManager;
79 
80 // Mapping of output stream index to surface ids
81 typedef std::unordered_map<int, std::vector<size_t> > SurfaceMap;
82 
83 /**
84  * Base interface for version >= 2 camera device classes, which interface to
85  * camera HAL device versions >= 2.
86  */
87 class CameraDeviceBase : public virtual FrameProducer {
88   public:
89     virtual ~CameraDeviceBase();
90 
91     /**
92      * The device vendor tag ID
93      */
94     virtual metadata_vendor_id_t getVendorTagId() const = 0;
95 
96     virtual status_t initialize(sp<CameraProviderManager> manager, const String8& monitorTags) = 0;
97     virtual status_t disconnect() = 0;
98 
99     virtual status_t dump(int fd, const Vector<String16> &args) = 0;
100 
101     /**
102      * The physical camera device's static characteristics metadata buffer, or
103      * the logical camera's static characteristics if physical id is empty.
104      */
105     virtual const CameraMetadata& infoPhysical(const String8& physicalId) const = 0;
106 
107     struct PhysicalCameraSettings {
108         std::string cameraId;
109         CameraMetadata metadata;
110 
111         // Whether the physical camera supports testPatternMode/testPatternData
112         bool mHasTestPatternModeTag = true;
113         bool mHasTestPatternDataTag = true;
114 
115         // Original value of TEST_PATTERN_MODE and DATA so that they can be
116         // restored when sensor muting is turned off
117         int32_t mOriginalTestPatternMode = 0;
118         int32_t mOriginalTestPatternData[4] = {};
119 
120     };
121     typedef List<PhysicalCameraSettings> PhysicalCameraSettingsList;
122 
123     /**
124      * Submit request for capture. The CameraDevice takes ownership of the
125      * passed-in buffer.
126      * Output lastFrameNumber is the expected frame number of this request.
127      */
128     virtual status_t capture(CameraMetadata &request, int64_t *lastFrameNumber = NULL) = 0;
129 
130     /**
131      * Submit a list of requests.
132      * Output lastFrameNumber is the expected last frame number of the list of requests.
133      */
134     virtual status_t captureList(const List<const PhysicalCameraSettingsList> &requests,
135                                  const std::list<const SurfaceMap> &surfaceMaps,
136                                  int64_t *lastFrameNumber = NULL) = 0;
137 
138     /**
139      * Submit request for streaming. The CameraDevice makes a copy of the
140      * passed-in buffer and the caller retains ownership.
141      * Output lastFrameNumber is the last frame number of the previous streaming request.
142      */
143     virtual status_t setStreamingRequest(const CameraMetadata &request,
144                                          int64_t *lastFrameNumber = NULL) = 0;
145 
146     /**
147      * Submit a list of requests for streaming.
148      * Output lastFrameNumber is the last frame number of the previous streaming request.
149      */
150     virtual status_t setStreamingRequestList(const List<const PhysicalCameraSettingsList> &requests,
151                                              const std::list<const SurfaceMap> &surfaceMaps,
152                                              int64_t *lastFrameNumber = NULL) = 0;
153 
154     /**
155      * Clear the streaming request slot.
156      * Output lastFrameNumber is the last frame number of the previous streaming request.
157      */
158     virtual status_t clearStreamingRequest(int64_t *lastFrameNumber = NULL) = 0;
159 
160     /**
161      * Wait until a request with the given ID has been dequeued by the
162      * HAL. Returns TIMED_OUT if the timeout duration is reached. Returns
163      * immediately if the latest request received by the HAL has this id.
164      */
165     virtual status_t waitUntilRequestReceived(int32_t requestId,
166             nsecs_t timeout) = 0;
167 
168     /**
169      * Create an output stream of the requested size, format, rotation and dataspace
170      *
171      * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
172      * logical dimensions of the buffer, not the number of bytes.
173      */
174     virtual status_t createStream(sp<Surface> consumer,
175             uint32_t width, uint32_t height, int format,
176             android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
177             const String8& physicalCameraId,
178             const std::unordered_set<int32_t>  &sensorPixelModesUsed,
179             std::vector<int> *surfaceIds = nullptr,
180             int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
181             bool isShared = false, bool isMultiResolution = false,
182             uint64_t consumerUsage = 0) = 0;
183 
184     /**
185      * Create an output stream of the requested size, format, rotation and
186      * dataspace with a number of consumers.
187      *
188      * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
189      * logical dimensions of the buffer, not the number of bytes.
190      */
191     virtual status_t createStream(const std::vector<sp<Surface>>& consumers,
192             bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
193             android_dataspace dataSpace, camera_stream_rotation_t rotation, int *id,
194             const String8& physicalCameraId,
195             const std::unordered_set<int32_t> &sensorPixelModesUsed,
196             std::vector<int> *surfaceIds = nullptr,
197             int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
198             bool isShared = false, bool isMultiResolution = false,
199             uint64_t consumerUsage = 0) = 0;
200 
201     /**
202      * Create an input stream of width, height, and format.
203      *
204      * Return value is the stream ID if non-negative and an error if negative.
205      */
206     virtual status_t createInputStream(uint32_t width, uint32_t height,
207             int32_t format, bool multiResolution, /*out*/ int32_t *id) = 0;
208 
209     struct StreamInfo {
210         uint32_t width;
211         uint32_t height;
212 
213         uint32_t format;
214         bool formatOverridden;
215         uint32_t originalFormat;
216 
217         android_dataspace dataSpace;
218         bool dataSpaceOverridden;
219         android_dataspace originalDataSpace;
220 
StreamInfoStreamInfo221         StreamInfo() : width(0), height(0), format(0), formatOverridden(false), originalFormat(0),
222                 dataSpace(HAL_DATASPACE_UNKNOWN), dataSpaceOverridden(false),
223                 originalDataSpace(HAL_DATASPACE_UNKNOWN) {}
224         /**
225          * Check whether the format matches the current or the original one in case
226          * it got overridden.
227          */
matchFormatStreamInfo228         bool matchFormat(uint32_t clientFormat) const {
229             if ((formatOverridden && (originalFormat == clientFormat)) ||
230                     (format == clientFormat)) {
231                 return true;
232             }
233             return false;
234         }
235 
236         /**
237          * Check whether the dataspace matches the current or the original one in case
238          * it got overridden.
239          */
matchDataSpaceStreamInfo240         bool matchDataSpace(android_dataspace clientDataSpace) const {
241             if ((dataSpaceOverridden && (originalDataSpace == clientDataSpace)) ||
242                     (dataSpace == clientDataSpace)) {
243                 return true;
244             }
245             return false;
246         }
247 
248     };
249 
250     /**
251      * Get information about a given stream.
252      */
253     virtual status_t getStreamInfo(int id, StreamInfo *streamInfo) = 0;
254 
255     /**
256      * Set stream gralloc buffer transform
257      */
258     virtual status_t setStreamTransform(int id, int transform) = 0;
259 
260     /**
261      * Delete stream. Must not be called if there are requests in flight which
262      * reference that stream.
263      */
264     virtual status_t deleteStream(int id) = 0;
265 
266     /**
267      * Take the currently-defined set of streams and configure the HAL to use
268      * them. This is a long-running operation (may be several hundered ms).
269      *
270      * The device must be idle (see waitUntilDrained) before calling this.
271      *
272      * Returns OK on success; otherwise on error:
273      * - BAD_VALUE if the set of streams was invalid (e.g. fmts or sizes)
274      * - INVALID_OPERATION if the device was in the wrong state
275      */
276     virtual status_t configureStreams(const CameraMetadata& sessionParams,
277             int operatingMode =
278             camera_stream_configuration_mode_t::CAMERA_STREAM_CONFIGURATION_NORMAL_MODE) = 0;
279 
280     /**
281      * Retrieve a list of all stream ids that were advertised as capable of
282      * supporting offline processing mode by Hal after the last stream configuration.
283      */
284     virtual void getOfflineStreamIds(std::vector<int> *offlineStreamIds) = 0;
285 
286     // get the buffer producer of the input stream
287     virtual status_t getInputBufferProducer(
288             sp<IGraphicBufferProducer> *producer) = 0;
289 
290     /**
291      * Create a metadata buffer with fields that the HAL device believes are
292      * best for the given use case
293      */
294     virtual status_t createDefaultRequest(camera_request_template_t templateId,
295             CameraMetadata *request) = 0;
296 
297     /**
298      * Wait until all requests have been processed. Returns INVALID_OPERATION if
299      * the streaming slot is not empty, or TIMED_OUT if the requests haven't
300      * finished processing in 10 seconds.
301      */
302     virtual status_t waitUntilDrained() = 0;
303 
304     /**
305      * Get Jpeg buffer size for a given jpeg resolution.
306      * Negative values are error codes.
307      */
308     virtual ssize_t getJpegBufferSize(const CameraMetadata &info, uint32_t width,
309             uint32_t height) const = 0;
310 
311     /**
312      * Connect HAL notifications to a listener. Overwrites previous
313      * listener. Set to NULL to stop receiving notifications.
314      */
315     virtual status_t setNotifyCallback(wp<NotificationListener> listener) = 0;
316 
317     /**
318      * Whether the device supports calling notifyAutofocus, notifyAutoExposure,
319      * and notifyAutoWhitebalance; if this returns false, the client must
320      * synthesize these notifications from received frame metadata.
321      */
322     virtual bool     willNotify3A() = 0;
323 
324     /**
325      * Trigger auto-focus. The latest ID used in a trigger autofocus or cancel
326      * autofocus call will be returned by the HAL in all subsequent AF
327      * notifications.
328      */
329     virtual status_t triggerAutofocus(uint32_t id) = 0;
330 
331     /**
332      * Cancel auto-focus. The latest ID used in a trigger autofocus/cancel
333      * autofocus call will be returned by the HAL in all subsequent AF
334      * notifications.
335      */
336     virtual status_t triggerCancelAutofocus(uint32_t id) = 0;
337 
338     /**
339      * Trigger pre-capture metering. The latest ID used in a trigger pre-capture
340      * call will be returned by the HAL in all subsequent AE and AWB
341      * notifications.
342      */
343     virtual status_t triggerPrecaptureMetering(uint32_t id) = 0;
344 
345     /**
346      * Flush all pending and in-flight requests. Blocks until flush is
347      * complete.
348      * Output lastFrameNumber is the last frame number of the previous streaming request.
349      */
350     virtual status_t flush(int64_t *lastFrameNumber = NULL) = 0;
351 
352     /**
353      * Prepare stream by preallocating buffers for it asynchronously.
354      * Calls notifyPrepared() once allocation is complete.
355      */
356     virtual status_t prepare(int streamId) = 0;
357 
358     /**
359      * Free stream resources by dumping its unused gralloc buffers.
360      */
361     virtual status_t tearDown(int streamId) = 0;
362 
363     /**
364      * Add buffer listener for a particular stream in the device.
365      */
366     virtual status_t addBufferListenerForStream(int streamId,
367             wp<camera3::Camera3StreamBufferListener> listener) = 0;
368 
369     /**
370      * Prepare stream by preallocating up to maxCount buffers for it asynchronously.
371      * Calls notifyPrepared() once allocation is complete.
372      */
373     virtual status_t prepare(int maxCount, int streamId) = 0;
374 
375     /**
376      * Set the deferred consumer surface and finish the rest of the stream configuration.
377      */
378     virtual status_t setConsumerSurfaces(int streamId,
379             const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds /*out*/) = 0;
380 
381     /**
382      * Update a given stream.
383      */
384     virtual status_t updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
385             const std::vector<android::camera3::OutputStreamInfo> &outputInfo,
386             const std::vector<size_t> &removedSurfaceIds,
387             KeyedVector<sp<Surface>, size_t> *outputMap/*out*/) = 0;
388 
389     /**
390      * Drop buffers for stream of streamId if dropping is true. If dropping is false, do not
391      * drop buffers for stream of streamId.
392      */
393     virtual status_t dropStreamBuffers(bool /*dropping*/, int /*streamId*/) = 0;
394 
395     /**
396      * Returns the maximum expected time it'll take for all currently in-flight
397      * requests to complete, based on their settings
398      */
399     virtual nsecs_t getExpectedInFlightDuration() = 0;
400 
401     /**
402      * switch to offline session
403      */
404     virtual status_t switchToOffline(
405             const std::vector<int32_t>& streamsToKeep,
406             /*out*/ sp<CameraOfflineSessionBase>* session) = 0;
407 
408     /**
409      * Set the current behavior for the ROTATE_AND_CROP control when in AUTO.
410      *
411      * The value must be one of the ROTATE_AND_CROP_* values besides AUTO,
412      * and defaults to NONE.
413      */
414     virtual status_t setRotateAndCropAutoBehavior(
415             camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) = 0;
416 
417     /**
418      * Whether camera muting (producing black-only output) is supported.
419      *
420      * Calling setCameraMute(true) when this returns false will return an
421      * INVALID_OPERATION error.
422      */
423     virtual bool supportsCameraMute() = 0;
424 
425     /**
426      * Mute the camera.
427      *
428      * When muted, black image data is output on all output streams.
429      */
430     virtual status_t setCameraMute(bool enabled) = 0;
431 
432     /**
433      * Get the status tracker of the camera device
434      */
435     virtual wp<camera3::StatusTracker> getStatusTracker() = 0;
436 
437     /**
438      * Set bitmask for image dump flag
439      */
setImageDumpMask(int mask)440     void setImageDumpMask(int mask) { mImageDumpMask = mask; }
441 
442 protected:
443     bool mImageDumpMask = 0;
444 };
445 
446 }; // namespace android
447 
448 #endif
449