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