blob: b18f0c314d5ce67dc4aa57b9c2b2598f7ce782f3 [file] [log] [blame]
Ari Hausman-Cohen73442152016-06-08 15:50:49 -07001/*
2 * Copyright (C) 2016 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// Modified from hardware/libhardware/modules/camera/Camera.cpp
18
19#include <cstdlib>
20#include <stdio.h>
21#include <hardware/camera3.h>
22#include <sync/sync.h>
23#include <system/camera_metadata.h>
24#include <system/graphics.h>
25#include <utils/Mutex.h>
26#include "Stream.h"
27
28//#define LOG_NDEBUG 0
29#define LOG_TAG "Camera"
30#include <cutils/log.h>
31
32#define ATRACE_TAG (ATRACE_TAG_CAMERA | ATRACE_TAG_HAL)
33#include <utils/Trace.h>
34
35#include "Camera.h"
36
37#define CAMERA_SYNC_TIMEOUT 5000 // in msecs
38
39namespace default_camera_hal {
40
41extern "C" {
42// Shim passed to the framework to close an opened device.
43static int close_device(hw_device_t* dev)
44{
45 camera3_device_t* cam_dev = reinterpret_cast<camera3_device_t*>(dev);
46 Camera* cam = static_cast<Camera*>(cam_dev->priv);
47 return cam->close();
48}
49} // extern "C"
50
51Camera::Camera(int id)
52 : mId(id),
53 mStaticInfo(NULL),
54 mBusy(false),
55 mCallbackOps(NULL),
56 mStreams(NULL),
57 mNumStreams(0),
58 mSettings(NULL)
59{
60 memset(&mTemplates, 0, sizeof(mTemplates));
61 memset(&mDevice, 0, sizeof(mDevice));
62 mDevice.common.tag = HARDWARE_DEVICE_TAG;
63 mDevice.common.version = CAMERA_DEVICE_API_VERSION_3_0;
64 mDevice.common.close = close_device;
65 mDevice.ops = const_cast<camera3_device_ops_t*>(&sOps);
66 mDevice.priv = this;
67}
68
69Camera::~Camera()
70{
71 if (mStaticInfo != NULL) {
72 free_camera_metadata(mStaticInfo);
73 }
74 if (mSettings != NULL) {
75 free_camera_metadata(mSettings);
76 }
77 for (camera_metadata_t* metadata : mTemplates) {
78 if (metadata != NULL) {
79 free_camera_metadata(metadata);
80 }
81 }
82}
83
84int Camera::open(const hw_module_t *module, hw_device_t **device)
85{
86 ALOGI("%s:%d: Opening camera device", __func__, mId);
87 ATRACE_CALL();
88 android::Mutex::Autolock al(mDeviceLock);
89
90 if (mBusy) {
91 ALOGE("%s:%d: Error! Camera device already opened", __func__, mId);
92 return -EBUSY;
93 }
94
95 // TODO: open camera dev nodes, etc
96 mBusy = true;
97 mDevice.common.module = const_cast<hw_module_t*>(module);
98 *device = &mDevice.common;
99 return 0;
100}
101
102int Camera::getInfo(struct camera_info *info)
103{
104 android::Mutex::Autolock al(mStaticInfoLock);
105
106 info->device_version = mDevice.common.version;
107 initDeviceInfo(info);
108 if (mStaticInfo == NULL) {
109 mStaticInfo = initStaticInfo();
110 }
111
112 info->static_camera_characteristics = mStaticInfo;
113 return 0;
114}
115
116int Camera::close()
117{
118 ALOGI("%s:%d: Closing camera device", __func__, mId);
119 ATRACE_CALL();
120 android::Mutex::Autolock al(mDeviceLock);
121
122 if (!mBusy) {
123 ALOGE("%s:%d: Error! Camera device not open", __func__, mId);
124 return -EINVAL;
125 }
126
127 // TODO: close camera dev nodes, etc
128 mBusy = false;
129 return 0;
130}
131
132int Camera::initialize(const camera3_callback_ops_t *callback_ops)
133{
134 int res;
135
136 ALOGV("%s:%d: callback_ops=%p", __func__, mId, callback_ops);
137 mCallbackOps = callback_ops;
138 // per-device specific initialization
139 res = initDevice();
140 if (res != 0) {
141 ALOGE("%s:%d: Failed to initialize device!", __func__, mId);
142 return res;
143 }
144 return 0;
145}
146
147int Camera::configureStreams(camera3_stream_configuration_t *stream_config)
148{
149 camera3_stream_t *astream;
150 Stream **newStreams = NULL;
151
152 ALOGV("%s:%d: stream_config=%p", __func__, mId, stream_config);
153 ATRACE_CALL();
154 android::Mutex::Autolock al(mDeviceLock);
155
156 if (stream_config == NULL) {
157 ALOGE("%s:%d: NULL stream configuration array", __func__, mId);
158 return -EINVAL;
159 }
160 if (stream_config->num_streams == 0) {
161 ALOGE("%s:%d: Empty stream configuration array", __func__, mId);
162 return -EINVAL;
163 }
164
165 // Create new stream array
166 newStreams = new Stream*[stream_config->num_streams];
167 ALOGV("%s:%d: Number of Streams: %d", __func__, mId,
168 stream_config->num_streams);
169
170 // Mark all current streams unused for now
171 for (int i = 0; i < mNumStreams; i++)
172 mStreams[i]->mReuse = false;
173 // Fill new stream array with reused streams and new streams
174 for (unsigned int i = 0; i < stream_config->num_streams; i++) {
175 astream = stream_config->streams[i];
176 if (astream->max_buffers > 0) {
177 ALOGV("%s:%d: Reusing stream %d", __func__, mId, i);
178 newStreams[i] = reuseStream(astream);
179 } else {
180 ALOGV("%s:%d: Creating new stream %d", __func__, mId, i);
181 newStreams[i] = new Stream(mId, astream);
182 }
183
184 if (newStreams[i] == NULL) {
185 ALOGE("%s:%d: Error processing stream %d", __func__, mId, i);
186 goto err_out;
187 }
188 astream->priv = newStreams[i];
189 }
190
191 // Verify the set of streams in aggregate
192 if (!isValidStreamSet(newStreams, stream_config->num_streams)) {
193 ALOGE("%s:%d: Invalid stream set", __func__, mId);
194 goto err_out;
195 }
196
197 // Set up all streams (calculate usage/max_buffers for each)
198 setupStreams(newStreams, stream_config->num_streams);
199
200 // Destroy all old streams and replace stream array with new one
201 destroyStreams(mStreams, mNumStreams);
202 mStreams = newStreams;
203 mNumStreams = stream_config->num_streams;
204
205 // Clear out last seen settings metadata
206 setSettings(NULL);
207 return 0;
208
209err_out:
210 // Clean up temporary streams, preserve existing mStreams/mNumStreams
211 destroyStreams(newStreams, stream_config->num_streams);
212 return -EINVAL;
213}
214
215void Camera::destroyStreams(Stream **streams, int count)
216{
217 if (streams == NULL)
218 return;
219 for (int i = 0; i < count; i++) {
220 // Only destroy streams that weren't reused
221 if (streams[i] != NULL && !streams[i]->mReuse)
222 delete streams[i];
223 }
224 delete [] streams;
225}
226
227Stream *Camera::reuseStream(camera3_stream_t *astream)
228{
229 Stream *priv = reinterpret_cast<Stream*>(astream->priv);
230 // Verify the re-used stream's parameters match
231 if (!priv->isValidReuseStream(mId, astream)) {
232 ALOGE("%s:%d: Mismatched parameter in reused stream", __func__, mId);
233 return NULL;
234 }
235 // Mark stream to be reused
236 priv->mReuse = true;
237 return priv;
238}
239
240bool Camera::isValidStreamSet(Stream **streams, int count)
241{
242 int inputs = 0;
243 int outputs = 0;
244
245 if (streams == NULL) {
246 ALOGE("%s:%d: NULL stream configuration streams", __func__, mId);
247 return false;
248 }
249 if (count == 0) {
250 ALOGE("%s:%d: Zero count stream configuration streams", __func__, mId);
251 return false;
252 }
253 // Validate there is at most one input stream and at least one output stream
254 for (int i = 0; i < count; i++) {
255 // A stream may be both input and output (bidirectional)
256 if (streams[i]->isInputType())
257 inputs++;
258 if (streams[i]->isOutputType())
259 outputs++;
260 }
261 ALOGV("%s:%d: Configuring %d output streams and %d input streams",
262 __func__, mId, outputs, inputs);
263 if (outputs < 1) {
264 ALOGE("%s:%d: Stream config must have >= 1 output", __func__, mId);
265 return false;
266 }
267 if (inputs > 1) {
268 ALOGE("%s:%d: Stream config must have <= 1 input", __func__, mId);
269 return false;
270 }
271 // TODO: check for correct number of Bayer/YUV/JPEG/Encoder streams
272 return true;
273}
274
275void Camera::setupStreams(Stream **streams, int count)
276{
277 /*
278 * This is where the HAL has to decide internally how to handle all of the
279 * streams, and then produce usage and max_buffer values for each stream.
280 * Note, the stream array has been checked before this point for ALL invalid
281 * conditions, so it must find a successful configuration for this stream
282 * array. The HAL may not return an error from this point.
283 *
284 * In this demo HAL, we just set all streams to be the same dummy values;
285 * real implementations will want to avoid USAGE_SW_{READ|WRITE}_OFTEN.
286 */
287 for (int i = 0; i < count; i++) {
288 uint32_t usage = 0;
289
290 if (streams[i]->isOutputType())
291 usage |= GRALLOC_USAGE_SW_WRITE_OFTEN |
292 GRALLOC_USAGE_HW_CAMERA_WRITE;
293 if (streams[i]->isInputType())
294 usage |= GRALLOC_USAGE_SW_READ_OFTEN |
295 GRALLOC_USAGE_HW_CAMERA_READ;
296
297 streams[i]->setUsage(usage);
298 streams[i]->setMaxBuffers(1);
299 }
300}
301
302int Camera::registerStreamBuffers(const camera3_stream_buffer_set_t *buf_set)
303{
304 ALOGV("%s:%d: buffer_set=%p", __func__, mId, buf_set);
305 if (buf_set == NULL) {
306 ALOGE("%s:%d: NULL buffer set", __func__, mId);
307 return -EINVAL;
308 }
309 if (buf_set->stream == NULL) {
310 ALOGE("%s:%d: NULL stream handle", __func__, mId);
311 return -EINVAL;
312 }
313 Stream *stream = reinterpret_cast<Stream*>(buf_set->stream->priv);
314 return stream->registerBuffers(buf_set);
315}
316
317bool Camera::isValidTemplateType(int type)
318{
319 return type < 1 || type >= CAMERA3_TEMPLATE_COUNT;
320}
321
322const camera_metadata_t* Camera::constructDefaultRequestSettings(int type)
323{
324 ALOGV("%s:%d: type=%d", __func__, mId, type);
325
326 if (!isValidTemplateType(type)) {
327 ALOGE("%s:%d: Invalid template request type: %d", __func__, mId, type);
328 return NULL;
329 }
330 return mTemplates[type];
331}
332
333int Camera::processCaptureRequest(camera3_capture_request_t *request)
334{
335 camera3_capture_result result;
336
337 ALOGV("%s:%d: request=%p", __func__, mId, request);
338 ATRACE_CALL();
339
340 if (request == NULL) {
341 ALOGE("%s:%d: NULL request recieved", __func__, mId);
342 return -EINVAL;
343 }
344
345 ALOGV("%s:%d: Request Frame:%d Settings:%p", __func__, mId,
346 request->frame_number, request->settings);
347
348 // NULL indicates use last settings
349 if (request->settings == NULL) {
350 if (mSettings == NULL) {
351 ALOGE("%s:%d: NULL settings without previous set Frame:%d Req:%p",
352 __func__, mId, request->frame_number, request);
353 return -EINVAL;
354 }
355 } else {
356 setSettings(request->settings);
357 }
358
359 if (request->input_buffer != NULL) {
360 ALOGV("%s:%d: Reprocessing input buffer %p", __func__, mId,
361 request->input_buffer);
362
363 if (!isValidReprocessSettings(request->settings)) {
364 ALOGE("%s:%d: Invalid settings for reprocess request: %p",
365 __func__, mId, request->settings);
366 return -EINVAL;
367 }
368 } else {
369 ALOGV("%s:%d: Capturing new frame.", __func__, mId);
370
371 if (!isValidCaptureSettings(request->settings)) {
372 ALOGE("%s:%d: Invalid settings for capture request: %p",
373 __func__, mId, request->settings);
374 return -EINVAL;
375 }
376 }
377
378 if (request->num_output_buffers <= 0) {
379 ALOGE("%s:%d: Invalid number of output buffers: %d", __func__, mId,
380 request->num_output_buffers);
381 return -EINVAL;
382 }
383 result.num_output_buffers = request->num_output_buffers;
384 result.output_buffers = new camera3_stream_buffer_t[result.num_output_buffers];
385 for (unsigned int i = 0; i < request->num_output_buffers; i++) {
386 int res = processCaptureBuffer(&request->output_buffers[i],
387 const_cast<camera3_stream_buffer_t*>(&result.output_buffers[i]));
388 if (res)
389 goto err_out;
390 }
391
392 result.frame_number = request->frame_number;
393 // TODO: return actual captured/reprocessed settings
394 result.result = request->settings;
395 // TODO: asynchronously return results
396 notifyShutter(request->frame_number, 0);
397 mCallbackOps->process_capture_result(mCallbackOps, &result);
398
399 return 0;
400
401err_out:
402 delete [] result.output_buffers;
403 // TODO: this should probably be a total device failure; transient for now
404 return -EINVAL;
405}
406
407void Camera::setSettings(const camera_metadata_t *new_settings)
408{
409 if (mSettings != NULL) {
410 free_camera_metadata(mSettings);
411 mSettings = NULL;
412 }
413
414 if (new_settings != NULL)
415 mSettings = clone_camera_metadata(new_settings);
416}
417
418bool Camera::isValidReprocessSettings(const camera_metadata_t* /*settings*/)
419{
420 // TODO: reject settings that cannot be reprocessed
421 // input buffers unimplemented, use this to reject reprocessing requests
422 ALOGE("%s:%d: Input buffer reprocessing not implemented", __func__, mId);
423 return false;
424}
425
426int Camera::processCaptureBuffer(const camera3_stream_buffer_t *in,
427 camera3_stream_buffer_t *out)
428{
429 if (in->acquire_fence != -1) {
430 int res = sync_wait(in->acquire_fence, CAMERA_SYNC_TIMEOUT);
431 if (res == -ETIME) {
432 ALOGE("%s:%d: Timeout waiting on buffer acquire fence",
433 __func__, mId);
434 return res;
435 } else if (res) {
436 ALOGE("%s:%d: Error waiting on buffer acquire fence: %s(%d)",
437 __func__, mId, strerror(-res), res);
438 return res;
439 }
440 }
441
442 out->stream = in->stream;
443 out->buffer = in->buffer;
444 out->status = CAMERA3_BUFFER_STATUS_OK;
445 // TODO: use driver-backed release fences
446 out->acquire_fence = -1;
447 out->release_fence = -1;
448
449 // TODO: lock and software-paint buffer
450 return 0;
451}
452
453void Camera::notifyShutter(uint32_t frame_number, uint64_t timestamp)
454{
455 int res;
456 struct timespec ts;
457
458 // If timestamp is 0, get timestamp from right now instead
459 if (timestamp == 0) {
460 ALOGW("%s:%d: No timestamp provided, using CLOCK_BOOTTIME",
461 __func__, mId);
462 res = clock_gettime(CLOCK_BOOTTIME, &ts);
463 if (res == 0) {
464 timestamp = ts.tv_sec * 1000000000ULL + ts.tv_nsec;
465 } else {
466 ALOGE("%s:%d: No timestamp and failed to get CLOCK_BOOTTIME %s(%d)",
467 __func__, mId, strerror(errno), errno);
468 }
469 }
470 camera3_notify_msg_t m;
471 memset(&m, 0, sizeof(m));
472 m.type = CAMERA3_MSG_SHUTTER;
473 m.message.shutter.frame_number = frame_number;
474 m.message.shutter.timestamp = timestamp;
475 mCallbackOps->notify(mCallbackOps, &m);
476}
477
478void Camera::dump(int fd)
479{
480 ALOGV("%s:%d: Dumping to fd %d", __func__, mId, fd);
481 ATRACE_CALL();
482 android::Mutex::Autolock al(mDeviceLock);
483
484 dprintf(fd, "Camera ID: %d (Busy: %d)\n", mId, mBusy);
485
486 // TODO: dump all settings
487 dprintf(fd, "Most Recent Settings: (%p)\n", mSettings);
488
489 dprintf(fd, "Number of streams: %d\n", mNumStreams);
490 for (int i = 0; i < mNumStreams; i++) {
491 dprintf(fd, "Stream %d/%d:\n", i, mNumStreams);
492 mStreams[i]->dump(fd);
493 }
494}
495
496const char* Camera::templateToString(int type)
497{
498 switch (type) {
499 case CAMERA3_TEMPLATE_PREVIEW:
500 return "CAMERA3_TEMPLATE_PREVIEW";
501 case CAMERA3_TEMPLATE_STILL_CAPTURE:
502 return "CAMERA3_TEMPLATE_STILL_CAPTURE";
503 case CAMERA3_TEMPLATE_VIDEO_RECORD:
504 return "CAMERA3_TEMPLATE_VIDEO_RECORD";
505 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
506 return "CAMERA3_TEMPLATE_VIDEO_SNAPSHOT";
507 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
508 return "CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG";
509 }
510 // TODO: support vendor templates
511 return "Invalid template type!";
512}
513
514int Camera::setTemplate(int type, camera_metadata_t *settings)
515{
516 android::Mutex::Autolock al(mDeviceLock);
517
518 if (!isValidTemplateType(type)) {
519 ALOGE("%s:%d: Invalid template request type: %d", __func__, mId, type);
520 return -EINVAL;
521 }
522
523 if (mTemplates[type] != NULL) {
524 ALOGE("%s:%d: Setting already constructed template type %s(%d)",
525 __func__, mId, templateToString(type), type);
526 return -EINVAL;
527 }
528
529 // Make a durable copy of the underlying metadata
530 mTemplates[type] = clone_camera_metadata(settings);
531 if (mTemplates[type] == NULL) {
532 ALOGE("%s:%d: Failed to clone metadata %p for template type %s(%d)",
533 __func__, mId, settings, templateToString(type), type);
534 return -EINVAL;
535 }
536 return 0;
537}
538
539extern "C" {
540// Get handle to camera from device priv data
541static Camera *camdev_to_camera(const camera3_device_t *dev)
542{
543 return reinterpret_cast<Camera*>(dev->priv);
544}
545
546static int initialize(const camera3_device_t *dev,
547 const camera3_callback_ops_t *callback_ops)
548{
549 return camdev_to_camera(dev)->initialize(callback_ops);
550}
551
552static int configure_streams(const camera3_device_t *dev,
553 camera3_stream_configuration_t *stream_list)
554{
555 return camdev_to_camera(dev)->configureStreams(stream_list);
556}
557
558static int register_stream_buffers(const camera3_device_t *dev,
559 const camera3_stream_buffer_set_t *buffer_set)
560{
561 return camdev_to_camera(dev)->registerStreamBuffers(buffer_set);
562}
563
564static const camera_metadata_t *construct_default_request_settings(
565 const camera3_device_t *dev, int type)
566{
567 return camdev_to_camera(dev)->constructDefaultRequestSettings(type);
568}
569
570static int process_capture_request(const camera3_device_t *dev,
571 camera3_capture_request_t *request)
572{
573 return camdev_to_camera(dev)->processCaptureRequest(request);
574}
575
576static void dump(const camera3_device_t *dev, int fd)
577{
578 camdev_to_camera(dev)->dump(fd);
579}
580
581static int flush(const camera3_device_t*)
582{
583 ALOGE("%s: unimplemented.", __func__);
584 return -1;
585}
586
587} // extern "C"
588
589const camera3_device_ops_t Camera::sOps = {
590 .initialize = default_camera_hal::initialize,
591 .configure_streams = default_camera_hal::configure_streams,
592 .register_stream_buffers = default_camera_hal::register_stream_buffers,
593 .construct_default_request_settings
594 = default_camera_hal::construct_default_request_settings,
595 .process_capture_request = default_camera_hal::process_capture_request,
596 .get_metadata_vendor_tag_ops = NULL,
597 .dump = default_camera_hal::dump,
598 .flush = default_camera_hal::flush,
599 .reserved = {0},
600};
601
602} // namespace default_camera_hal