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