1/*
2 * Copyright (C) 2013 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/Timers.h>
27#include <utils/List.h>
28
29#include "hardware/camera2.h"
30#include "hardware/camera3.h"
31#include "camera/CameraMetadata.h"
32#include "camera/CaptureResult.h"
33#include "gui/IGraphicBufferProducer.h"
34#include "device3/Camera3StreamInterface.h"
35#include "binder/Status.h"
36
37namespace android {
38
39class CameraProviderManager;
40
41// Mapping of output stream index to surface ids
42typedef std::unordered_map<int, std::vector<size_t> > SurfaceMap;
43
44/**
45 * Base interface for version >= 2 camera device classes, which interface to
46 * camera HAL device versions >= 2.
47 */
48class CameraDeviceBase : public virtual RefBase {
49  public:
50    virtual ~CameraDeviceBase();
51
52    /**
53     * The device's camera ID
54     */
55    virtual const String8& getId() const = 0;
56
57    virtual status_t initialize(sp<CameraProviderManager> manager) = 0;
58    virtual status_t disconnect() = 0;
59
60    virtual status_t dump(int fd, const Vector<String16> &args) = 0;
61
62    /**
63     * The device's static characteristics metadata buffer
64     */
65    virtual const CameraMetadata& info() const = 0;
66
67    /**
68     * Submit request for capture. The CameraDevice takes ownership of the
69     * passed-in buffer.
70     * Output lastFrameNumber is the expected frame number of this request.
71     */
72    virtual status_t capture(CameraMetadata &request, int64_t *lastFrameNumber = NULL) = 0;
73
74    /**
75     * Submit a list of requests.
76     * Output lastFrameNumber is the expected last frame number of the list of requests.
77     */
78    virtual status_t captureList(const List<const CameraMetadata> &requests,
79                                 const std::list<const SurfaceMap> &surfaceMaps,
80                                 int64_t *lastFrameNumber = NULL) = 0;
81
82    /**
83     * Submit request for streaming. The CameraDevice makes a copy of the
84     * passed-in buffer and the caller retains ownership.
85     * Output lastFrameNumber is the last frame number of the previous streaming request.
86     */
87    virtual status_t setStreamingRequest(const CameraMetadata &request,
88                                         int64_t *lastFrameNumber = NULL) = 0;
89
90    /**
91     * Submit a list of requests for streaming.
92     * Output lastFrameNumber is the last frame number of the previous streaming request.
93     */
94    virtual status_t setStreamingRequestList(const List<const CameraMetadata> &requests,
95                                             const std::list<const SurfaceMap> &surfaceMaps,
96                                             int64_t *lastFrameNumber = NULL) = 0;
97
98    /**
99     * Clear the streaming request slot.
100     * Output lastFrameNumber is the last frame number of the previous streaming request.
101     */
102    virtual status_t clearStreamingRequest(int64_t *lastFrameNumber = NULL) = 0;
103
104    /**
105     * Wait until a request with the given ID has been dequeued by the
106     * HAL. Returns TIMED_OUT if the timeout duration is reached. Returns
107     * immediately if the latest request received by the HAL has this id.
108     */
109    virtual status_t waitUntilRequestReceived(int32_t requestId,
110            nsecs_t timeout) = 0;
111
112    /**
113     * Create an output stream of the requested size, format, rotation and dataspace
114     *
115     * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
116     * logical dimensions of the buffer, not the number of bytes.
117     */
118    virtual status_t createStream(sp<Surface> consumer,
119            uint32_t width, uint32_t height, int format,
120            android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
121            int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
122            bool isShared = false, uint32_t consumerUsage = 0) = 0;
123
124    /**
125     * Create an output stream of the requested size, format, rotation and
126     * dataspace with a number of consumers.
127     *
128     * For HAL_PIXEL_FORMAT_BLOB formats, the width and height should be the
129     * logical dimensions of the buffer, not the number of bytes.
130     */
131    virtual status_t createStream(const std::vector<sp<Surface>>& consumers,
132            bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
133            android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
134            int streamSetId = camera3::CAMERA3_STREAM_SET_ID_INVALID,
135            bool isShared = false, uint32_t consumerUsage = 0) = 0;
136
137    /**
138     * Create an input stream of width, height, and format.
139     *
140     * Return value is the stream ID if non-negative and an error if negative.
141     */
142    virtual status_t createInputStream(uint32_t width, uint32_t height,
143            int32_t format, /*out*/ int32_t *id) = 0;
144
145    /**
146     * Get information about a given stream.
147     */
148    virtual status_t getStreamInfo(int id,
149            uint32_t *width, uint32_t *height,
150            uint32_t *format, android_dataspace *dataSpace) = 0;
151
152    /**
153     * Set stream gralloc buffer transform
154     */
155    virtual status_t setStreamTransform(int id, int transform) = 0;
156
157    /**
158     * Delete stream. Must not be called if there are requests in flight which
159     * reference that stream.
160     */
161    virtual status_t deleteStream(int id) = 0;
162
163    /**
164     * Take the currently-defined set of streams and configure the HAL to use
165     * them. This is a long-running operation (may be several hundered ms).
166     *
167     * The device must be idle (see waitUntilDrained) before calling this.
168     *
169     * Returns OK on success; otherwise on error:
170     * - BAD_VALUE if the set of streams was invalid (e.g. fmts or sizes)
171     * - INVALID_OPERATION if the device was in the wrong state
172     */
173    virtual status_t configureStreams(int operatingMode = 0) = 0;
174
175    // get the buffer producer of the input stream
176    virtual status_t getInputBufferProducer(
177            sp<IGraphicBufferProducer> *producer) = 0;
178
179    /**
180     * Create a metadata buffer with fields that the HAL device believes are
181     * best for the given use case
182     */
183    virtual status_t createDefaultRequest(int templateId,
184            CameraMetadata *request) = 0;
185
186    /**
187     * Wait until all requests have been processed. Returns INVALID_OPERATION if
188     * the streaming slot is not empty, or TIMED_OUT if the requests haven't
189     * finished processing in 10 seconds.
190     */
191    virtual status_t waitUntilDrained() = 0;
192
193    /**
194     * Get Jpeg buffer size for a given jpeg resolution.
195     * Negative values are error codes.
196     */
197    virtual ssize_t getJpegBufferSize(uint32_t width, uint32_t height) const = 0;
198
199    /**
200     * Abstract class for HAL notification listeners
201     */
202    class NotificationListener : public virtual RefBase {
203      public:
204        // The set of notifications is a merge of the notifications required for
205        // API1 and API2.
206
207        // Required for API 1 and 2
208        virtual void notifyError(int32_t errorCode,
209                                 const CaptureResultExtras &resultExtras) = 0;
210
211        // Required only for API2
212        virtual void notifyIdle() = 0;
213        virtual void notifyShutter(const CaptureResultExtras &resultExtras,
214                nsecs_t timestamp) = 0;
215        virtual void notifyPrepared(int streamId) = 0;
216        virtual void notifyRequestQueueEmpty() = 0;
217
218        // Required only for API1
219        virtual void notifyAutoFocus(uint8_t newState, int triggerId) = 0;
220        virtual void notifyAutoExposure(uint8_t newState, int triggerId) = 0;
221        virtual void notifyAutoWhitebalance(uint8_t newState,
222                int triggerId) = 0;
223        virtual void notifyRepeatingRequestError(long lastFrameNumber) = 0;
224      protected:
225        virtual ~NotificationListener();
226    };
227
228    /**
229     * Connect HAL notifications to a listener. Overwrites previous
230     * listener. Set to NULL to stop receiving notifications.
231     */
232    virtual status_t setNotifyCallback(wp<NotificationListener> listener) = 0;
233
234    /**
235     * Whether the device supports calling notifyAutofocus, notifyAutoExposure,
236     * and notifyAutoWhitebalance; if this returns false, the client must
237     * synthesize these notifications from received frame metadata.
238     */
239    virtual bool     willNotify3A() = 0;
240
241    /**
242     * Wait for a new frame to be produced, with timeout in nanoseconds.
243     * Returns TIMED_OUT when no frame produced within the specified duration
244     * May be called concurrently to most methods, except for getNextFrame
245     */
246    virtual status_t waitForNextFrame(nsecs_t timeout) = 0;
247
248    /**
249     * Get next capture result frame from the result queue. Returns NOT_ENOUGH_DATA
250     * if the queue is empty; caller takes ownership of the metadata buffer inside
251     * the capture result object's metadata field.
252     * May be called concurrently to most methods, except for waitForNextFrame.
253     */
254    virtual status_t getNextResult(CaptureResult *frame) = 0;
255
256    /**
257     * Trigger auto-focus. The latest ID used in a trigger autofocus or cancel
258     * autofocus call will be returned by the HAL in all subsequent AF
259     * notifications.
260     */
261    virtual status_t triggerAutofocus(uint32_t id) = 0;
262
263    /**
264     * Cancel auto-focus. The latest ID used in a trigger autofocus/cancel
265     * autofocus call will be returned by the HAL in all subsequent AF
266     * notifications.
267     */
268    virtual status_t triggerCancelAutofocus(uint32_t id) = 0;
269
270    /**
271     * Trigger pre-capture metering. The latest ID used in a trigger pre-capture
272     * call will be returned by the HAL in all subsequent AE and AWB
273     * notifications.
274     */
275    virtual status_t triggerPrecaptureMetering(uint32_t id) = 0;
276
277    /**
278     * Flush all pending and in-flight requests. Blocks until flush is
279     * complete.
280     * Output lastFrameNumber is the last frame number of the previous streaming request.
281     */
282    virtual status_t flush(int64_t *lastFrameNumber = NULL) = 0;
283
284    /**
285     * Prepare stream by preallocating buffers for it asynchronously.
286     * Calls notifyPrepared() once allocation is complete.
287     */
288    virtual status_t prepare(int streamId) = 0;
289
290    /**
291     * Free stream resources by dumping its unused gralloc buffers.
292     */
293    virtual status_t tearDown(int streamId) = 0;
294
295    /**
296     * Add buffer listener for a particular stream in the device.
297     */
298    virtual status_t addBufferListenerForStream(int streamId,
299            wp<camera3::Camera3StreamBufferListener> listener) = 0;
300
301    /**
302     * Prepare stream by preallocating up to maxCount buffers for it asynchronously.
303     * Calls notifyPrepared() once allocation is complete.
304     */
305    virtual status_t prepare(int maxCount, int streamId) = 0;
306
307    /**
308     * Set the deferred consumer surface and finish the rest of the stream configuration.
309     */
310    virtual status_t setConsumerSurfaces(int streamId,
311            const std::vector<sp<Surface>>& consumers) = 0;
312
313};
314
315}; // namespace android
316
317#endif
318