Camera3Device.cpp revision 2f876f9ee63396e4e0117f85c5b3132cac7e2c9d
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#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0  // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
28// Convenience macro for transient errors
29#define CLOGE(fmt, ...) ALOGE("Camera %d: %s: " fmt, mId, __FUNCTION__, \
30            ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState(   \
34    "%s: " fmt, __FUNCTION__,              \
35    ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37    "%s: " fmt, __FUNCTION__,                    \
38    ##__VA_ARGS__)
39
40#include <utils/Log.h>
41#include <utils/Trace.h>
42#include <utils/Timers.h>
43
44#include "device3/Camera3Device.h"
45#include "device3/Camera3OutputStream.h"
46#include "device3/Camera3InputStream.h"
47#include "device3/Camera3ZslStream.h"
48
49using namespace android::camera3;
50
51namespace android {
52
53Camera3Device::Camera3Device(int id):
54        mId(id),
55        mHal3Device(NULL),
56        mStatus(STATUS_UNINITIALIZED),
57        mNextResultFrameNumber(0),
58        mNextShutterFrameNumber(0),
59        mListener(NULL)
60{
61    ATRACE_CALL();
62    camera3_callback_ops::notify = &sNotify;
63    camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
64    ALOGV("%s: Created device for camera %d", __FUNCTION__, id);
65}
66
67Camera3Device::~Camera3Device()
68{
69    ATRACE_CALL();
70    ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId);
71    disconnect();
72}
73
74int Camera3Device::getId() const {
75    return mId;
76}
77
78/**
79 * CameraDeviceBase interface
80 */
81
82status_t Camera3Device::initialize(camera_module_t *module)
83{
84    ATRACE_CALL();
85    Mutex::Autolock l(mLock);
86
87    ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId);
88    if (mStatus != STATUS_UNINITIALIZED) {
89        CLOGE("Already initialized!");
90        return INVALID_OPERATION;
91    }
92
93    /** Open HAL device */
94
95    status_t res;
96    String8 deviceName = String8::format("%d", mId);
97
98    camera3_device_t *device;
99
100    res = module->common.methods->open(&module->common, deviceName.string(),
101            reinterpret_cast<hw_device_t**>(&device));
102
103    if (res != OK) {
104        SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
105        return res;
106    }
107
108    /** Cross-check device version */
109
110    if (device->common.version != CAMERA_DEVICE_API_VERSION_3_0) {
111        SET_ERR_L("Could not open camera: "
112                "Camera device is not version %x, reports %x instead",
113                CAMERA_DEVICE_API_VERSION_3_0,
114                device->common.version);
115        device->common.close(&device->common);
116        return BAD_VALUE;
117    }
118
119    camera_info info;
120    res = module->get_camera_info(mId, &info);
121    if (res != OK) return res;
122
123    if (info.device_version != device->common.version) {
124        SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
125                " and device version (%x).",
126                device->common.version, info.device_version);
127        device->common.close(&device->common);
128        return BAD_VALUE;
129    }
130
131    /** Initialize device with callback functions */
132
133    ATRACE_BEGIN("camera3->initialize");
134    res = device->ops->initialize(device, this);
135    ATRACE_END();
136
137    if (res != OK) {
138        SET_ERR_L("Unable to initialize HAL device: %s (%d)",
139                strerror(-res), res);
140        device->common.close(&device->common);
141        return BAD_VALUE;
142    }
143
144    /** Get vendor metadata tags */
145
146    mVendorTagOps.get_camera_vendor_section_name = NULL;
147
148    ATRACE_BEGIN("camera3->get_metadata_vendor_tag_ops");
149    device->ops->get_metadata_vendor_tag_ops(device, &mVendorTagOps);
150    ATRACE_END();
151
152    if (mVendorTagOps.get_camera_vendor_section_name != NULL) {
153        res = set_camera_metadata_vendor_tag_ops(&mVendorTagOps);
154        if (res != OK) {
155            SET_ERR_L("Unable to set tag ops: %s (%d)",
156                    strerror(-res), res);
157            device->common.close(&device->common);
158            return res;
159        }
160    }
161
162    /** Start up request queue thread */
163
164    mRequestThread = new RequestThread(this, device);
165    res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string());
166    if (res != OK) {
167        SET_ERR_L("Unable to start request queue thread: %s (%d)",
168                strerror(-res), res);
169        device->common.close(&device->common);
170        mRequestThread.clear();
171        return res;
172    }
173
174    /** Everything is good to go */
175
176    mDeviceInfo = info.static_camera_characteristics;
177    mHal3Device = device;
178    mStatus = STATUS_IDLE;
179    mNextStreamId = 0;
180    mNeedConfig = true;
181
182    return OK;
183}
184
185status_t Camera3Device::disconnect() {
186    ATRACE_CALL();
187    Mutex::Autolock l(mLock);
188
189    ALOGV("%s: E", __FUNCTION__);
190
191    status_t res = OK;
192    if (mStatus == STATUS_UNINITIALIZED) return res;
193
194    if (mStatus == STATUS_ACTIVE ||
195            (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
196        res = mRequestThread->clearRepeatingRequests();
197        if (res != OK) {
198            SET_ERR_L("Can't stop streaming");
199            // Continue to close device even in case of error
200        } else {
201            res = waitUntilDrainedLocked();
202            if (res != OK) {
203                SET_ERR_L("Timeout waiting for HAL to drain");
204                // Continue to close device even in case of error
205            }
206        }
207    }
208    assert(mStatus == STATUS_IDLE || mStatus == STATUS_ERROR);
209
210    if (mStatus == STATUS_ERROR) {
211        CLOGE("Shutting down in an error state");
212    }
213
214    if (mRequestThread != NULL) {
215        mRequestThread->requestExit();
216    }
217
218    mOutputStreams.clear();
219    mInputStream.clear();
220
221    if (mRequestThread != NULL) {
222        if (mStatus != STATUS_ERROR) {
223            // HAL may be in a bad state, so waiting for request thread
224            // (which may be stuck in the HAL processCaptureRequest call)
225            // could be dangerous.
226            mRequestThread->join();
227        }
228        mRequestThread.clear();
229    }
230
231    if (mHal3Device != NULL) {
232        mHal3Device->common.close(&mHal3Device->common);
233        mHal3Device = NULL;
234    }
235
236    mStatus = STATUS_UNINITIALIZED;
237
238    ALOGV("%s: X", __FUNCTION__);
239    return res;
240}
241
242status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
243    ATRACE_CALL();
244    (void)args;
245    String8 lines;
246
247    const char *status =
248            mStatus == STATUS_ERROR         ? "ERROR" :
249            mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
250            mStatus == STATUS_IDLE          ? "IDLE" :
251            mStatus == STATUS_ACTIVE        ? "ACTIVE" :
252            "Unknown";
253    lines.appendFormat("    Device status: %s\n", status);
254    if (mStatus == STATUS_ERROR) {
255        lines.appendFormat("    Error cause: %s\n", mErrorCause.string());
256    }
257    lines.appendFormat("    Stream configuration:\n");
258
259    if (mInputStream != NULL) {
260        write(fd, lines.string(), lines.size());
261        mInputStream->dump(fd, args);
262    } else {
263        lines.appendFormat("      No input stream.\n");
264        write(fd, lines.string(), lines.size());
265    }
266    for (size_t i = 0; i < mOutputStreams.size(); i++) {
267        mOutputStreams[i]->dump(fd,args);
268    }
269
270    lines = String8("    In-flight requests:\n");
271    if (mInFlightMap.size() == 0) {
272        lines.append("      None\n");
273    } else {
274        for (size_t i = 0; i < mInFlightMap.size(); i++) {
275            InFlightRequest r = mInFlightMap.valueAt(i);
276            lines.appendFormat("      Frame %d |  Timestamp: %lld, metadata"
277                    " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
278                    r.captureTimestamp, r.haveResultMetadata ? "true" : "false",
279                    r.numBuffersLeft);
280        }
281    }
282    write(fd, lines.string(), lines.size());
283
284    {
285        lines = String8("    Last request sent:\n");
286        write(fd, lines.string(), lines.size());
287
288        CameraMetadata lastRequest = getLatestRequest();
289        lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
290    }
291
292    if (mHal3Device != NULL) {
293        lines = String8("    HAL device dump:\n");
294        write(fd, lines.string(), lines.size());
295        mHal3Device->ops->dump(mHal3Device, fd);
296    }
297
298    return OK;
299}
300
301const CameraMetadata& Camera3Device::info() const {
302    ALOGVV("%s: E", __FUNCTION__);
303    if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
304                    mStatus == STATUS_ERROR)) {
305        ALOGW("%s: Access to static info %s!", __FUNCTION__,
306                mStatus == STATUS_ERROR ?
307                "when in error state" : "before init");
308    }
309    return mDeviceInfo;
310}
311
312status_t Camera3Device::capture(CameraMetadata &request) {
313    ATRACE_CALL();
314    Mutex::Autolock l(mLock);
315
316    // TODO: take ownership of the request
317
318    switch (mStatus) {
319        case STATUS_ERROR:
320            CLOGE("Device has encountered a serious error");
321            return INVALID_OPERATION;
322        case STATUS_UNINITIALIZED:
323            CLOGE("Device not initialized");
324            return INVALID_OPERATION;
325        case STATUS_IDLE:
326        case STATUS_ACTIVE:
327            // OK
328            break;
329        default:
330            SET_ERR_L("Unexpected status: %d", mStatus);
331            return INVALID_OPERATION;
332    }
333
334    sp<CaptureRequest> newRequest = setUpRequestLocked(request);
335    if (newRequest == NULL) {
336        CLOGE("Can't create capture request");
337        return BAD_VALUE;
338    }
339
340    return mRequestThread->queueRequest(newRequest);
341}
342
343
344status_t Camera3Device::setStreamingRequest(const CameraMetadata &request) {
345    ATRACE_CALL();
346    Mutex::Autolock l(mLock);
347
348    switch (mStatus) {
349        case STATUS_ERROR:
350            CLOGE("Device has encountered a serious error");
351            return INVALID_OPERATION;
352        case STATUS_UNINITIALIZED:
353            CLOGE("Device not initialized");
354            return INVALID_OPERATION;
355        case STATUS_IDLE:
356        case STATUS_ACTIVE:
357            // OK
358            break;
359        default:
360            SET_ERR_L("Unexpected status: %d", mStatus);
361            return INVALID_OPERATION;
362    }
363
364    sp<CaptureRequest> newRepeatingRequest = setUpRequestLocked(request);
365    if (newRepeatingRequest == NULL) {
366        CLOGE("Can't create repeating request");
367        return BAD_VALUE;
368    }
369
370    RequestList newRepeatingRequests;
371    newRepeatingRequests.push_back(newRepeatingRequest);
372
373    return mRequestThread->setRepeatingRequests(newRepeatingRequests);
374}
375
376
377sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
378        const CameraMetadata &request) {
379    status_t res;
380
381    if (mStatus == STATUS_IDLE) {
382        res = configureStreamsLocked();
383        if (res != OK) {
384            SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res);
385            return NULL;
386        }
387    }
388
389    sp<CaptureRequest> newRequest = createCaptureRequest(request);
390    return newRequest;
391}
392
393status_t Camera3Device::clearStreamingRequest() {
394    ATRACE_CALL();
395    Mutex::Autolock l(mLock);
396
397    switch (mStatus) {
398        case STATUS_ERROR:
399            CLOGE("Device has encountered a serious error");
400            return INVALID_OPERATION;
401        case STATUS_UNINITIALIZED:
402            CLOGE("Device not initialized");
403            return INVALID_OPERATION;
404        case STATUS_IDLE:
405        case STATUS_ACTIVE:
406            // OK
407            break;
408        default:
409            SET_ERR_L("Unexpected status: %d", mStatus);
410            return INVALID_OPERATION;
411    }
412
413    return mRequestThread->clearRepeatingRequests();
414}
415
416status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
417    ATRACE_CALL();
418
419    return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
420}
421
422status_t Camera3Device::createInputStream(
423        uint32_t width, uint32_t height, int format, int *id) {
424    ATRACE_CALL();
425    Mutex::Autolock l(mLock);
426
427    status_t res;
428    bool wasActive = false;
429
430    switch (mStatus) {
431        case STATUS_ERROR:
432            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
433            return INVALID_OPERATION;
434        case STATUS_UNINITIALIZED:
435            ALOGE("%s: Device not initialized", __FUNCTION__);
436            return INVALID_OPERATION;
437        case STATUS_IDLE:
438            // OK
439            break;
440        case STATUS_ACTIVE:
441            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
442            mRequestThread->setPaused(true);
443            res = waitUntilDrainedLocked();
444            if (res != OK) {
445                ALOGE("%s: Can't pause captures to reconfigure streams!",
446                        __FUNCTION__);
447                mStatus = STATUS_ERROR;
448                return res;
449            }
450            wasActive = true;
451            break;
452        default:
453            ALOGE("%s: Unexpected status: %d", __FUNCTION__, mStatus);
454            return INVALID_OPERATION;
455    }
456    assert(mStatus == STATUS_IDLE);
457
458    if (mInputStream != 0) {
459        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
460        return INVALID_OPERATION;
461    }
462
463    sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
464                width, height, format);
465
466    mInputStream = newStream;
467
468    *id = mNextStreamId++;
469
470    // Continue captures if active at start
471    if (wasActive) {
472        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
473        res = configureStreamsLocked();
474        if (res != OK) {
475            ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
476                    __FUNCTION__, mNextStreamId, strerror(-res), res);
477            return res;
478        }
479        mRequestThread->setPaused(false);
480    }
481
482    return OK;
483}
484
485
486status_t Camera3Device::createZslStream(
487            uint32_t width, uint32_t height,
488            int depth,
489            /*out*/
490            int *id,
491            sp<Camera3ZslStream>* zslStream) {
492    ATRACE_CALL();
493    Mutex::Autolock l(mLock);
494
495    status_t res;
496    bool wasActive = false;
497
498    switch (mStatus) {
499        case STATUS_ERROR:
500            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
501            return INVALID_OPERATION;
502        case STATUS_UNINITIALIZED:
503            ALOGE("%s: Device not initialized", __FUNCTION__);
504            return INVALID_OPERATION;
505        case STATUS_IDLE:
506            // OK
507            break;
508        case STATUS_ACTIVE:
509            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
510            mRequestThread->setPaused(true);
511            res = waitUntilDrainedLocked();
512            if (res != OK) {
513                ALOGE("%s: Can't pause captures to reconfigure streams!",
514                        __FUNCTION__);
515                mStatus = STATUS_ERROR;
516                return res;
517            }
518            wasActive = true;
519            break;
520        default:
521            ALOGE("%s: Unexpected status: %d", __FUNCTION__, mStatus);
522            return INVALID_OPERATION;
523    }
524    assert(mStatus == STATUS_IDLE);
525
526    if (mInputStream != 0) {
527        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
528        return INVALID_OPERATION;
529    }
530
531    sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
532                width, height, depth);
533
534    res = mOutputStreams.add(mNextStreamId, newStream);
535    if (res < 0) {
536        ALOGE("%s: Can't add new stream to set: %s (%d)",
537                __FUNCTION__, strerror(-res), res);
538        return res;
539    }
540    mInputStream = newStream;
541
542    *id = mNextStreamId++;
543    *zslStream = newStream;
544
545    // Continue captures if active at start
546    if (wasActive) {
547        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
548        res = configureStreamsLocked();
549        if (res != OK) {
550            ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
551                    __FUNCTION__, mNextStreamId, strerror(-res), res);
552            return res;
553        }
554        mRequestThread->setPaused(false);
555    }
556
557    return OK;
558}
559
560status_t Camera3Device::createStream(sp<ANativeWindow> consumer,
561        uint32_t width, uint32_t height, int format, size_t size, int *id) {
562    ATRACE_CALL();
563    Mutex::Autolock l(mLock);
564
565    status_t res;
566    bool wasActive = false;
567
568    switch (mStatus) {
569        case STATUS_ERROR:
570            CLOGE("Device has encountered a serious error");
571            return INVALID_OPERATION;
572        case STATUS_UNINITIALIZED:
573            CLOGE("Device not initialized");
574            return INVALID_OPERATION;
575        case STATUS_IDLE:
576            // OK
577            break;
578        case STATUS_ACTIVE:
579            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
580            mRequestThread->setPaused(true);
581            res = waitUntilDrainedLocked();
582            if (res != OK) {
583                ALOGE("%s: Can't pause captures to reconfigure streams!",
584                        __FUNCTION__);
585                return res;
586            }
587            wasActive = true;
588            break;
589        default:
590            SET_ERR_L("Unexpected status: %d", mStatus);
591            return INVALID_OPERATION;
592    }
593    assert(mStatus == STATUS_IDLE);
594
595    sp<Camera3OutputStream> newStream;
596    if (format == HAL_PIXEL_FORMAT_BLOB) {
597        newStream = new Camera3OutputStream(mNextStreamId, consumer,
598                width, height, size, format);
599    } else {
600        newStream = new Camera3OutputStream(mNextStreamId, consumer,
601                width, height, format);
602    }
603
604    res = mOutputStreams.add(mNextStreamId, newStream);
605    if (res < 0) {
606        SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
607        return res;
608    }
609
610    *id = mNextStreamId++;
611    mNeedConfig = true;
612
613    // Continue captures if active at start
614    if (wasActive) {
615        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
616        res = configureStreamsLocked();
617        if (res != OK) {
618            CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
619                    mNextStreamId, strerror(-res), res);
620            return res;
621        }
622        mRequestThread->setPaused(false);
623    }
624
625    return OK;
626}
627
628status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
629    ATRACE_CALL();
630    (void)outputId; (void)id;
631
632    CLOGE("Unimplemented");
633    return INVALID_OPERATION;
634}
635
636
637status_t Camera3Device::getStreamInfo(int id,
638        uint32_t *width, uint32_t *height, uint32_t *format) {
639    ATRACE_CALL();
640    Mutex::Autolock l(mLock);
641
642    switch (mStatus) {
643        case STATUS_ERROR:
644            CLOGE("Device has encountered a serious error");
645            return INVALID_OPERATION;
646        case STATUS_UNINITIALIZED:
647            CLOGE("Device not initialized!");
648            return INVALID_OPERATION;
649        case STATUS_IDLE:
650        case STATUS_ACTIVE:
651            // OK
652            break;
653        default:
654            SET_ERR_L("Unexpected status: %d", mStatus);
655            return INVALID_OPERATION;
656    }
657
658    ssize_t idx = mOutputStreams.indexOfKey(id);
659    if (idx == NAME_NOT_FOUND) {
660        CLOGE("Stream %d is unknown", id);
661        return idx;
662    }
663
664    if (width) *width  = mOutputStreams[idx]->getWidth();
665    if (height) *height = mOutputStreams[idx]->getHeight();
666    if (format) *format = mOutputStreams[idx]->getFormat();
667
668    return OK;
669}
670
671status_t Camera3Device::setStreamTransform(int id,
672        int transform) {
673    ATRACE_CALL();
674    Mutex::Autolock l(mLock);
675
676    switch (mStatus) {
677        case STATUS_ERROR:
678            CLOGE("Device has encountered a serious error");
679            return INVALID_OPERATION;
680        case STATUS_UNINITIALIZED:
681            CLOGE("Device not initialized");
682            return INVALID_OPERATION;
683        case STATUS_IDLE:
684        case STATUS_ACTIVE:
685            // OK
686            break;
687        default:
688            SET_ERR_L("Unexpected status: %d", mStatus);
689            return INVALID_OPERATION;
690    }
691
692    ssize_t idx = mOutputStreams.indexOfKey(id);
693    if (idx == NAME_NOT_FOUND) {
694        CLOGE("Stream %d does not exist",
695                id);
696        return BAD_VALUE;
697    }
698
699    return mOutputStreams.editValueAt(idx)->setTransform(transform);
700}
701
702status_t Camera3Device::deleteStream(int id) {
703    ATRACE_CALL();
704    Mutex::Autolock l(mLock);
705    status_t res;
706
707    ALOGV("%s: Camera %d: Deleting stream %d", __FUNCTION__, mId, id);
708
709    // CameraDevice semantics require device to already be idle before
710    // deleteStream is called, unlike for createStream.
711    if (mStatus != STATUS_IDLE) {
712        ALOGV("%s: Camera %d: Device not idle", __FUNCTION__, mId);
713        return -EBUSY;
714    }
715
716    sp<Camera3StreamInterface> deletedStream;
717    if (mInputStream != NULL && id == mInputStream->getId()) {
718        deletedStream = mInputStream;
719        mInputStream.clear();
720    } else {
721        ssize_t idx = mOutputStreams.indexOfKey(id);
722        if (idx == NAME_NOT_FOUND) {
723            CLOGE("Stream %d does not exist", id);
724            return BAD_VALUE;
725        }
726        deletedStream = mOutputStreams.editValueAt(idx);
727        mOutputStreams.removeItem(id);
728    }
729
730    // Free up the stream endpoint so that it can be used by some other stream
731    res = deletedStream->disconnect();
732    if (res != OK) {
733        SET_ERR_L("Can't disconnect deleted stream %d", id);
734        // fall through since we want to still list the stream as deleted.
735    }
736    mDeletedStreams.add(deletedStream);
737    mNeedConfig = true;
738
739    return res;
740}
741
742status_t Camera3Device::deleteReprocessStream(int id) {
743    ATRACE_CALL();
744    (void)id;
745
746    CLOGE("Unimplemented");
747    return INVALID_OPERATION;
748}
749
750
751status_t Camera3Device::createDefaultRequest(int templateId,
752        CameraMetadata *request) {
753    ATRACE_CALL();
754    ALOGV("%s: for template %d", __FUNCTION__, templateId);
755    Mutex::Autolock l(mLock);
756
757    switch (mStatus) {
758        case STATUS_ERROR:
759            CLOGE("Device has encountered a serious error");
760            return INVALID_OPERATION;
761        case STATUS_UNINITIALIZED:
762            CLOGE("Device is not initialized!");
763            return INVALID_OPERATION;
764        case STATUS_IDLE:
765        case STATUS_ACTIVE:
766            // OK
767            break;
768        default:
769            SET_ERR_L("Unexpected status: %d", mStatus);
770            return INVALID_OPERATION;
771    }
772
773    const camera_metadata_t *rawRequest;
774    ATRACE_BEGIN("camera3->construct_default_request_settings");
775    rawRequest = mHal3Device->ops->construct_default_request_settings(
776        mHal3Device, templateId);
777    ATRACE_END();
778    if (rawRequest == NULL) {
779        SET_ERR_L("HAL is unable to construct default settings for template %d",
780                templateId);
781        return DEAD_OBJECT;
782    }
783    *request = rawRequest;
784
785    return OK;
786}
787
788status_t Camera3Device::waitUntilDrained() {
789    ATRACE_CALL();
790    Mutex::Autolock l(mLock);
791
792    return waitUntilDrainedLocked();
793}
794
795status_t Camera3Device::waitUntilDrainedLocked() {
796    ATRACE_CALL();
797    status_t res;
798
799    switch (mStatus) {
800        case STATUS_UNINITIALIZED:
801        case STATUS_IDLE:
802            ALOGV("%s: Already idle", __FUNCTION__);
803            return OK;
804        case STATUS_ERROR:
805        case STATUS_ACTIVE:
806            // Need to shut down
807            break;
808        default:
809            SET_ERR_L("Unexpected status: %d",mStatus);
810            return INVALID_OPERATION;
811    }
812
813    if (mRequestThread != NULL) {
814        res = mRequestThread->waitUntilPaused(kShutdownTimeout);
815        if (res != OK) {
816            SET_ERR_L("Can't stop request thread in %f seconds!",
817                    kShutdownTimeout/1e9);
818            return res;
819        }
820    }
821    if (mInputStream != NULL) {
822        res = mInputStream->waitUntilIdle(kShutdownTimeout);
823        if (res != OK) {
824            SET_ERR_L("Can't idle input stream %d in %f seconds!",
825                    mInputStream->getId(), kShutdownTimeout/1e9);
826            return res;
827        }
828    }
829    for (size_t i = 0; i < mOutputStreams.size(); i++) {
830        res = mOutputStreams.editValueAt(i)->waitUntilIdle(kShutdownTimeout);
831        if (res != OK) {
832            SET_ERR_L("Can't idle output stream %d in %f seconds!",
833                    mOutputStreams.keyAt(i), kShutdownTimeout/1e9);
834            return res;
835        }
836    }
837
838    if (mStatus != STATUS_ERROR) {
839        mStatus = STATUS_IDLE;
840    }
841
842    return OK;
843}
844
845status_t Camera3Device::setNotifyCallback(NotificationListener *listener) {
846    ATRACE_CALL();
847    Mutex::Autolock l(mOutputLock);
848
849    if (listener != NULL && mListener != NULL) {
850        ALOGW("%s: Replacing old callback listener", __FUNCTION__);
851    }
852    mListener = listener;
853
854    return OK;
855}
856
857bool Camera3Device::willNotify3A() {
858    return false;
859}
860
861status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
862    ATRACE_CALL();
863    status_t res;
864    Mutex::Autolock l(mOutputLock);
865
866    while (mResultQueue.empty()) {
867        res = mResultSignal.waitRelative(mOutputLock, timeout);
868        if (res == TIMED_OUT) {
869            return res;
870        } else if (res != OK) {
871            ALOGW("%s: Camera %d: No frame in %lld ns: %s (%d)",
872                    __FUNCTION__, mId, timeout, strerror(-res), res);
873            return res;
874        }
875    }
876    return OK;
877}
878
879status_t Camera3Device::getNextFrame(CameraMetadata *frame) {
880    ATRACE_CALL();
881    Mutex::Autolock l(mOutputLock);
882
883    if (mResultQueue.empty()) {
884        return NOT_ENOUGH_DATA;
885    }
886
887    CameraMetadata &result = *(mResultQueue.begin());
888    frame->acquire(result);
889    mResultQueue.erase(mResultQueue.begin());
890
891    return OK;
892}
893
894status_t Camera3Device::triggerAutofocus(uint32_t id) {
895    ATRACE_CALL();
896
897    ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
898    // Mix-in this trigger into the next request and only the next request.
899    RequestTrigger trigger[] = {
900        {
901            ANDROID_CONTROL_AF_TRIGGER,
902            ANDROID_CONTROL_AF_TRIGGER_START
903        },
904        {
905            ANDROID_CONTROL_AF_TRIGGER_ID,
906            static_cast<int32_t>(id)
907        },
908    };
909
910    return mRequestThread->queueTrigger(trigger,
911                                        sizeof(trigger)/sizeof(trigger[0]));
912}
913
914status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
915    ATRACE_CALL();
916
917    ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
918    // Mix-in this trigger into the next request and only the next request.
919    RequestTrigger trigger[] = {
920        {
921            ANDROID_CONTROL_AF_TRIGGER,
922            ANDROID_CONTROL_AF_TRIGGER_CANCEL
923        },
924        {
925            ANDROID_CONTROL_AF_TRIGGER_ID,
926            static_cast<int32_t>(id)
927        },
928    };
929
930    return mRequestThread->queueTrigger(trigger,
931                                        sizeof(trigger)/sizeof(trigger[0]));
932}
933
934status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
935    ATRACE_CALL();
936
937    ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
938    // Mix-in this trigger into the next request and only the next request.
939    RequestTrigger trigger[] = {
940        {
941            ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
942            ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
943        },
944        {
945            ANDROID_CONTROL_AE_PRECAPTURE_ID,
946            static_cast<int32_t>(id)
947        },
948    };
949
950    return mRequestThread->queueTrigger(trigger,
951                                        sizeof(trigger)/sizeof(trigger[0]));
952}
953
954status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
955        buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
956    ATRACE_CALL();
957    (void)reprocessStreamId; (void)buffer; (void)listener;
958
959    CLOGE("Unimplemented");
960    return INVALID_OPERATION;
961}
962
963status_t Camera3Device::flush() {
964    ATRACE_CALL();
965    ALOGV("%s: Camera %d: Flushing all requests", __FUNCTION__, mId);
966
967    Mutex::Autolock l(mLock);
968
969    mRequestThread->clear();
970    return mHal3Device->ops->flush(mHal3Device);
971}
972
973/**
974 * Camera3Device private methods
975 */
976
977sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
978        const CameraMetadata &request) {
979    ATRACE_CALL();
980    status_t res;
981
982    sp<CaptureRequest> newRequest = new CaptureRequest;
983    newRequest->mSettings = request;
984
985    camera_metadata_entry_t inputStreams =
986            newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
987    if (inputStreams.count > 0) {
988        if (mInputStream == NULL ||
989                mInputStream->getId() != inputStreams.data.i32[0]) {
990            CLOGE("Request references unknown input stream %d",
991                    inputStreams.data.u8[0]);
992            return NULL;
993        }
994        // Lazy completion of stream configuration (allocation/registration)
995        // on first use
996        if (mInputStream->isConfiguring()) {
997            res = mInputStream->finishConfiguration(mHal3Device);
998            if (res != OK) {
999                SET_ERR_L("Unable to finish configuring input stream %d:"
1000                        " %s (%d)",
1001                        mInputStream->getId(), strerror(-res), res);
1002                return NULL;
1003            }
1004        }
1005
1006        newRequest->mInputStream = mInputStream;
1007        newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1008    }
1009
1010    camera_metadata_entry_t streams =
1011            newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1012    if (streams.count == 0) {
1013        CLOGE("Zero output streams specified!");
1014        return NULL;
1015    }
1016
1017    for (size_t i = 0; i < streams.count; i++) {
1018        int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
1019        if (idx == NAME_NOT_FOUND) {
1020            CLOGE("Request references unknown stream %d",
1021                    streams.data.u8[i]);
1022            return NULL;
1023        }
1024        sp<Camera3OutputStreamInterface> stream =
1025                mOutputStreams.editValueAt(idx);
1026
1027        // Lazy completion of stream configuration (allocation/registration)
1028        // on first use
1029        if (stream->isConfiguring()) {
1030            res = stream->finishConfiguration(mHal3Device);
1031            if (res != OK) {
1032                SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
1033                        stream->getId(), strerror(-res), res);
1034                return NULL;
1035            }
1036        }
1037
1038        newRequest->mOutputStreams.push(stream);
1039    }
1040    newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
1041
1042    return newRequest;
1043}
1044
1045status_t Camera3Device::configureStreamsLocked() {
1046    ATRACE_CALL();
1047    status_t res;
1048
1049    if (mStatus != STATUS_IDLE) {
1050        CLOGE("Not idle");
1051        return INVALID_OPERATION;
1052    }
1053
1054    if (!mNeedConfig) {
1055        ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
1056        mStatus = STATUS_ACTIVE;
1057        return OK;
1058    }
1059
1060    // Start configuring the streams
1061
1062    camera3_stream_configuration config;
1063
1064    config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
1065
1066    Vector<camera3_stream_t*> streams;
1067    streams.setCapacity(config.num_streams);
1068
1069    if (mInputStream != NULL) {
1070        camera3_stream_t *inputStream;
1071        inputStream = mInputStream->startConfiguration();
1072        if (inputStream == NULL) {
1073            SET_ERR_L("Can't start input stream configuration");
1074            return INVALID_OPERATION;
1075        }
1076        streams.add(inputStream);
1077    }
1078
1079    for (size_t i = 0; i < mOutputStreams.size(); i++) {
1080
1081        // Don't configure bidi streams twice, nor add them twice to the list
1082        if (mOutputStreams[i].get() ==
1083            static_cast<Camera3StreamInterface*>(mInputStream.get())) {
1084
1085            config.num_streams--;
1086            continue;
1087        }
1088
1089        camera3_stream_t *outputStream;
1090        outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
1091        if (outputStream == NULL) {
1092            SET_ERR_L("Can't start output stream configuration");
1093            return INVALID_OPERATION;
1094        }
1095        streams.add(outputStream);
1096    }
1097
1098    config.streams = streams.editArray();
1099
1100    // Do the HAL configuration; will potentially touch stream
1101    // max_buffers, usage, priv fields.
1102    ATRACE_BEGIN("camera3->configure_streams");
1103    res = mHal3Device->ops->configure_streams(mHal3Device, &config);
1104    ATRACE_END();
1105
1106    if (res != OK) {
1107        SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
1108                strerror(-res), res);
1109        return res;
1110    }
1111
1112    // Finish all stream configuration immediately.
1113    // TODO: Try to relax this later back to lazy completion, which should be
1114    // faster
1115
1116    if (mInputStream != NULL && mInputStream->isConfiguring()) {
1117        res = mInputStream->finishConfiguration(mHal3Device);
1118        if (res != OK) {
1119            SET_ERR_L("Can't finish configuring input stream %d: %s (%d)",
1120                    mInputStream->getId(), strerror(-res), res);
1121            return res;
1122        }
1123    }
1124
1125    for (size_t i = 0; i < mOutputStreams.size(); i++) {
1126        sp<Camera3OutputStreamInterface> outputStream =
1127            mOutputStreams.editValueAt(i);
1128        if (outputStream->isConfiguring()) {
1129            res = outputStream->finishConfiguration(mHal3Device);
1130            if (res != OK) {
1131                SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1132                        outputStream->getId(), strerror(-res), res);
1133                return res;
1134            }
1135        }
1136    }
1137
1138    // Request thread needs to know to avoid using repeat-last-settings protocol
1139    // across configure_streams() calls
1140    mRequestThread->configurationComplete();
1141
1142    // Finish configuring the streams lazily on first reference
1143
1144    mStatus = STATUS_ACTIVE;
1145    mNeedConfig = false;
1146
1147    return OK;
1148}
1149
1150void Camera3Device::setErrorState(const char *fmt, ...) {
1151    Mutex::Autolock l(mLock);
1152    va_list args;
1153    va_start(args, fmt);
1154
1155    setErrorStateLockedV(fmt, args);
1156
1157    va_end(args);
1158}
1159
1160void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
1161    Mutex::Autolock l(mLock);
1162    setErrorStateLockedV(fmt, args);
1163}
1164
1165void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
1166    va_list args;
1167    va_start(args, fmt);
1168
1169    setErrorStateLockedV(fmt, args);
1170
1171    va_end(args);
1172}
1173
1174void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
1175    // Print out all error messages to log
1176    String8 errorCause = String8::formatV(fmt, args);
1177    ALOGE("Camera %d: %s", mId, errorCause.string());
1178
1179    // But only do error state transition steps for the first error
1180    if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
1181
1182    mErrorCause = errorCause;
1183
1184    mRequestThread->setPaused(true);
1185    mStatus = STATUS_ERROR;
1186}
1187
1188/**
1189 * In-flight request management
1190 */
1191
1192status_t Camera3Device::registerInFlight(int32_t frameNumber,
1193        int32_t numBuffers) {
1194    ATRACE_CALL();
1195    Mutex::Autolock l(mInFlightLock);
1196
1197    ssize_t res;
1198    res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers));
1199    if (res < 0) return res;
1200
1201    return OK;
1202}
1203
1204/**
1205 * Camera HAL device callback methods
1206 */
1207
1208void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
1209    ATRACE_CALL();
1210
1211    status_t res;
1212
1213    uint32_t frameNumber = result->frame_number;
1214    if (result->result == NULL && result->num_output_buffers == 0) {
1215        SET_ERR("No result data provided by HAL for frame %d",
1216                frameNumber);
1217        return;
1218    }
1219
1220    // Get capture timestamp from list of in-flight requests, where it was added
1221    // by the shutter notification for this frame. Then update the in-flight
1222    // status and remove the in-flight entry if all result data has been
1223    // received.
1224    nsecs_t timestamp = 0;
1225    {
1226        Mutex::Autolock l(mInFlightLock);
1227        ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
1228        if (idx == NAME_NOT_FOUND) {
1229            SET_ERR("Unknown frame number for capture result: %d",
1230                    frameNumber);
1231            return;
1232        }
1233        InFlightRequest &request = mInFlightMap.editValueAt(idx);
1234        timestamp = request.captureTimestamp;
1235        if (timestamp == 0) {
1236            SET_ERR("Called before shutter notify for frame %d",
1237                    frameNumber);
1238            return;
1239        }
1240
1241        if (result->result != NULL) {
1242            if (request.haveResultMetadata) {
1243                SET_ERR("Called multiple times with metadata for frame %d",
1244                        frameNumber);
1245                return;
1246            }
1247            request.haveResultMetadata = true;
1248        }
1249
1250        request.numBuffersLeft -= result->num_output_buffers;
1251
1252        if (request.numBuffersLeft < 0) {
1253            SET_ERR("Too many buffers returned for frame %d",
1254                    frameNumber);
1255            return;
1256        }
1257
1258        if (request.haveResultMetadata && request.numBuffersLeft == 0) {
1259            ATRACE_ASYNC_END("frame capture", frameNumber);
1260            mInFlightMap.removeItemsAt(idx, 1);
1261        }
1262
1263        // Sanity check - if we have too many in-flight frames, something has
1264        // likely gone wrong
1265        if (mInFlightMap.size() > kInFlightWarnLimit) {
1266            CLOGE("In-flight list too large: %d", mInFlightMap.size());
1267        }
1268
1269    }
1270
1271    // Process the result metadata, if provided
1272    if (result->result != NULL) {
1273        Mutex::Autolock l(mOutputLock);
1274
1275        if (frameNumber != mNextResultFrameNumber) {
1276            SET_ERR("Out-of-order capture result metadata submitted! "
1277                    "(got frame number %d, expecting %d)",
1278                    frameNumber, mNextResultFrameNumber);
1279            return;
1280        }
1281        mNextResultFrameNumber++;
1282
1283        CameraMetadata &captureResult =
1284                *mResultQueue.insert(mResultQueue.end(), CameraMetadata());
1285
1286        captureResult = result->result;
1287        if (captureResult.update(ANDROID_REQUEST_FRAME_COUNT,
1288                        (int32_t*)&frameNumber, 1) != OK) {
1289            SET_ERR("Failed to set frame# in metadata (%d)",
1290                    frameNumber);
1291        } else {
1292            ALOGVV("%s: Camera %d: Set frame# in metadata (%d)",
1293                    __FUNCTION__, mId, frameNumber);
1294        }
1295
1296        // Check that there's a timestamp in the result metadata
1297
1298        camera_metadata_entry entry =
1299                captureResult.find(ANDROID_SENSOR_TIMESTAMP);
1300        if (entry.count == 0) {
1301            SET_ERR("No timestamp provided by HAL for frame %d!",
1302                    frameNumber);
1303        } else if (timestamp != entry.data.i64[0]) {
1304            SET_ERR("Timestamp mismatch between shutter notify and result"
1305                    " metadata for frame %d (%lld vs %lld respectively)",
1306                    frameNumber, timestamp, entry.data.i64[0]);
1307        }
1308    } // scope for mOutputLock
1309
1310    // Return completed buffers to their streams with the timestamp
1311
1312    for (size_t i = 0; i < result->num_output_buffers; i++) {
1313        Camera3Stream *stream =
1314                Camera3Stream::cast(result->output_buffers[i].stream);
1315        res = stream->returnBuffer(result->output_buffers[i], timestamp);
1316        // Note: stream may be deallocated at this point, if this buffer was the
1317        // last reference to it.
1318        if (res != OK) {
1319            SET_ERR("Can't return buffer %d for frame %d to its stream: "
1320                    " %s (%d)", i, frameNumber, strerror(-res), res);
1321        }
1322    }
1323
1324    // Finally, signal any waiters for new frames
1325
1326    if (result->result != NULL) {
1327        mResultSignal.signal();
1328    }
1329
1330}
1331
1332
1333
1334void Camera3Device::notify(const camera3_notify_msg *msg) {
1335    ATRACE_CALL();
1336    NotificationListener *listener;
1337    {
1338        Mutex::Autolock l(mOutputLock);
1339        listener = mListener;
1340    }
1341
1342    if (msg == NULL) {
1343        SET_ERR("HAL sent NULL notify message!");
1344        return;
1345    }
1346
1347    switch (msg->type) {
1348        case CAMERA3_MSG_ERROR: {
1349            int streamId = 0;
1350            if (msg->message.error.error_stream != NULL) {
1351                Camera3Stream *stream =
1352                        Camera3Stream::cast(
1353                                  msg->message.error.error_stream);
1354                streamId = stream->getId();
1355            }
1356            ALOGV("Camera %d: %s: HAL error, frame %d, stream %d: %d",
1357                    mId, __FUNCTION__, msg->message.error.frame_number,
1358                    streamId, msg->message.error.error_code);
1359            if (listener != NULL) {
1360                listener->notifyError(msg->message.error.error_code,
1361                        msg->message.error.frame_number, streamId);
1362            }
1363            break;
1364        }
1365        case CAMERA3_MSG_SHUTTER: {
1366            ssize_t idx;
1367            uint32_t frameNumber = msg->message.shutter.frame_number;
1368            nsecs_t timestamp = msg->message.shutter.timestamp;
1369            // Verify ordering of shutter notifications
1370            {
1371                Mutex::Autolock l(mOutputLock);
1372                if (frameNumber != mNextShutterFrameNumber) {
1373                    SET_ERR("Shutter notification out-of-order. Expected "
1374                            "notification for frame %d, got frame %d",
1375                            mNextShutterFrameNumber, frameNumber);
1376                    break;
1377                }
1378                mNextShutterFrameNumber++;
1379            }
1380
1381            // Set timestamp for the request in the in-flight tracking
1382            {
1383                Mutex::Autolock l(mInFlightLock);
1384                idx = mInFlightMap.indexOfKey(frameNumber);
1385                if (idx >= 0) {
1386                    mInFlightMap.editValueAt(idx).captureTimestamp = timestamp;
1387                }
1388            }
1389            if (idx < 0) {
1390                SET_ERR("Shutter notification for non-existent frame number %d",
1391                        frameNumber);
1392                break;
1393            }
1394            ALOGVV("Camera %d: %s: Shutter fired for frame %d at %lld",
1395                    mId, __FUNCTION__, frameNumber, timestamp);
1396            // Call listener, if any
1397            if (listener != NULL) {
1398                listener->notifyShutter(frameNumber, timestamp);
1399            }
1400            break;
1401        }
1402        default:
1403            SET_ERR("Unknown notify message from HAL: %d",
1404                    msg->type);
1405    }
1406}
1407
1408CameraMetadata Camera3Device::getLatestRequest() {
1409    ALOGV("%s", __FUNCTION__);
1410
1411    bool locked = false;
1412
1413    /**
1414     * Why trylock instead of autolock?
1415     *
1416     * We want to be able to call this function from
1417     * dumpsys, which often happens during deadlocks.
1418     */
1419    for (size_t i = 0; i < kDumpLockAttempts; ++i) {
1420        if (mLock.tryLock() == NO_ERROR) {
1421            locked = true;
1422            break;
1423        } else {
1424            usleep(kDumpSleepDuration);
1425        }
1426    }
1427
1428    if (!locked) {
1429        ALOGW("%s: Possible deadlock detected", __FUNCTION__);
1430    }
1431
1432    CameraMetadata retVal;
1433
1434    if (mRequestThread != NULL) {
1435        retVal = mRequestThread->getLatestRequest();
1436    }
1437
1438    if (locked) {
1439        mLock.unlock();
1440    }
1441
1442    return retVal;
1443}
1444
1445/**
1446 * RequestThread inner class methods
1447 */
1448
1449Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
1450        camera3_device_t *hal3Device) :
1451        Thread(false),
1452        mParent(parent),
1453        mHal3Device(hal3Device),
1454        mId(getId(parent)),
1455        mReconfigured(false),
1456        mDoPause(false),
1457        mPaused(true),
1458        mFrameNumber(0),
1459        mLatestRequestId(NAME_NOT_FOUND) {
1460}
1461
1462void Camera3Device::RequestThread::configurationComplete() {
1463    Mutex::Autolock l(mRequestLock);
1464    mReconfigured = true;
1465}
1466
1467status_t Camera3Device::RequestThread::queueRequest(
1468         sp<CaptureRequest> request) {
1469    Mutex::Autolock l(mRequestLock);
1470    mRequestQueue.push_back(request);
1471
1472    unpauseForNewRequests();
1473
1474    return OK;
1475}
1476
1477
1478status_t Camera3Device::RequestThread::queueTrigger(
1479        RequestTrigger trigger[],
1480        size_t count) {
1481
1482    Mutex::Autolock l(mTriggerMutex);
1483    status_t ret;
1484
1485    for (size_t i = 0; i < count; ++i) {
1486        ret = queueTriggerLocked(trigger[i]);
1487
1488        if (ret != OK) {
1489            return ret;
1490        }
1491    }
1492
1493    return OK;
1494}
1495
1496int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
1497    sp<Camera3Device> d = device.promote();
1498    if (d != NULL) return d->mId;
1499    return 0;
1500}
1501
1502status_t Camera3Device::RequestThread::queueTriggerLocked(
1503        RequestTrigger trigger) {
1504
1505    uint32_t tag = trigger.metadataTag;
1506    ssize_t index = mTriggerMap.indexOfKey(tag);
1507
1508    switch (trigger.getTagType()) {
1509        case TYPE_BYTE:
1510        // fall-through
1511        case TYPE_INT32:
1512            break;
1513        default:
1514            ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
1515                    trigger.getTagType());
1516            return INVALID_OPERATION;
1517    }
1518
1519    /**
1520     * Collect only the latest trigger, since we only have 1 field
1521     * in the request settings per trigger tag, and can't send more than 1
1522     * trigger per request.
1523     */
1524    if (index != NAME_NOT_FOUND) {
1525        mTriggerMap.editValueAt(index) = trigger;
1526    } else {
1527        mTriggerMap.add(tag, trigger);
1528    }
1529
1530    return OK;
1531}
1532
1533status_t Camera3Device::RequestThread::setRepeatingRequests(
1534        const RequestList &requests) {
1535    Mutex::Autolock l(mRequestLock);
1536    mRepeatingRequests.clear();
1537    mRepeatingRequests.insert(mRepeatingRequests.begin(),
1538            requests.begin(), requests.end());
1539
1540    unpauseForNewRequests();
1541
1542    return OK;
1543}
1544
1545status_t Camera3Device::RequestThread::clearRepeatingRequests() {
1546    Mutex::Autolock l(mRequestLock);
1547    mRepeatingRequests.clear();
1548    return OK;
1549}
1550
1551status_t Camera3Device::RequestThread::clear() {
1552    Mutex::Autolock l(mRequestLock);
1553    mRepeatingRequests.clear();
1554    mRequestQueue.clear();
1555    mTriggerMap.clear();
1556    return OK;
1557}
1558
1559void Camera3Device::RequestThread::setPaused(bool paused) {
1560    Mutex::Autolock l(mPauseLock);
1561    mDoPause = paused;
1562    mDoPauseSignal.signal();
1563}
1564
1565status_t Camera3Device::RequestThread::waitUntilPaused(nsecs_t timeout) {
1566    ATRACE_CALL();
1567    status_t res;
1568    Mutex::Autolock l(mPauseLock);
1569    while (!mPaused) {
1570        res = mPausedSignal.waitRelative(mPauseLock, timeout);
1571        if (res == TIMED_OUT) {
1572            return res;
1573        }
1574    }
1575    return OK;
1576}
1577
1578status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
1579        int32_t requestId, nsecs_t timeout) {
1580    Mutex::Autolock l(mLatestRequestMutex);
1581    status_t res;
1582    while (mLatestRequestId != requestId) {
1583        nsecs_t startTime = systemTime();
1584
1585        res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
1586        if (res != OK) return res;
1587
1588        timeout -= (systemTime() - startTime);
1589    }
1590
1591    return OK;
1592}
1593
1594
1595
1596bool Camera3Device::RequestThread::threadLoop() {
1597
1598    status_t res;
1599
1600    // Handle paused state.
1601    if (waitIfPaused()) {
1602        return true;
1603    }
1604
1605    // Get work to do
1606
1607    sp<CaptureRequest> nextRequest = waitForNextRequest();
1608    if (nextRequest == NULL) {
1609        return true;
1610    }
1611
1612    // Create request to HAL
1613    camera3_capture_request_t request = camera3_capture_request_t();
1614    Vector<camera3_stream_buffer_t> outputBuffers;
1615
1616    // Insert any queued triggers (before metadata is locked)
1617    int32_t triggerCount;
1618    res = insertTriggers(nextRequest);
1619    if (res < 0) {
1620        SET_ERR("RequestThread: Unable to insert triggers "
1621                "(capture request %d, HAL device: %s (%d)",
1622                (mFrameNumber+1), strerror(-res), res);
1623        cleanUpFailedRequest(request, nextRequest, outputBuffers);
1624        return false;
1625    }
1626    triggerCount = res;
1627
1628    bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
1629
1630    // If the request is the same as last, or we had triggers last time
1631    if (mPrevRequest != nextRequest || triggersMixedIn) {
1632        /**
1633         * HAL workaround:
1634         * Insert a dummy trigger ID if a trigger is set but no trigger ID is
1635         */
1636        res = addDummyTriggerIds(nextRequest);
1637        if (res != OK) {
1638            SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
1639                    "(capture request %d, HAL device: %s (%d)",
1640                    (mFrameNumber+1), strerror(-res), res);
1641            cleanUpFailedRequest(request, nextRequest, outputBuffers);
1642            return false;
1643        }
1644
1645        /**
1646         * The request should be presorted so accesses in HAL
1647         *   are O(logn). Sidenote, sorting a sorted metadata is nop.
1648         */
1649        nextRequest->mSettings.sort();
1650        request.settings = nextRequest->mSettings.getAndLock();
1651        mPrevRequest = nextRequest;
1652        ALOGVV("%s: Request settings are NEW", __FUNCTION__);
1653
1654        IF_ALOGV() {
1655            camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
1656            find_camera_metadata_ro_entry(
1657                    request.settings,
1658                    ANDROID_CONTROL_AF_TRIGGER,
1659                    &e
1660            );
1661            if (e.count > 0) {
1662                ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
1663                      __FUNCTION__,
1664                      mFrameNumber+1,
1665                      e.data.u8[0]);
1666            }
1667        }
1668    } else {
1669        // leave request.settings NULL to indicate 'reuse latest given'
1670        ALOGVV("%s: Request settings are REUSED",
1671               __FUNCTION__);
1672    }
1673
1674    camera3_stream_buffer_t inputBuffer;
1675
1676    // Fill in buffers
1677
1678    if (nextRequest->mInputStream != NULL) {
1679        request.input_buffer = &inputBuffer;
1680        res = nextRequest->mInputStream->getInputBuffer(&inputBuffer);
1681        if (res != OK) {
1682            SET_ERR("RequestThread: Can't get input buffer, skipping request:"
1683                    " %s (%d)", strerror(-res), res);
1684            cleanUpFailedRequest(request, nextRequest, outputBuffers);
1685            return true;
1686        }
1687    } else {
1688        request.input_buffer = NULL;
1689    }
1690
1691    outputBuffers.insertAt(camera3_stream_buffer_t(), 0,
1692            nextRequest->mOutputStreams.size());
1693    request.output_buffers = outputBuffers.array();
1694    for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) {
1695        res = nextRequest->mOutputStreams.editItemAt(i)->
1696                getBuffer(&outputBuffers.editItemAt(i));
1697        if (res != OK) {
1698            SET_ERR("RequestThread: Can't get output buffer, skipping request:"
1699                    "%s (%d)", strerror(-res), res);
1700            cleanUpFailedRequest(request, nextRequest, outputBuffers);
1701            return true;
1702        }
1703        request.num_output_buffers++;
1704    }
1705
1706    request.frame_number = mFrameNumber++;
1707
1708    // Log request in the in-flight queue
1709    sp<Camera3Device> parent = mParent.promote();
1710    if (parent == NULL) {
1711        CLOGE("RequestThread: Parent is gone");
1712        cleanUpFailedRequest(request, nextRequest, outputBuffers);
1713        return false;
1714    }
1715
1716    res = parent->registerInFlight(request.frame_number,
1717            request.num_output_buffers);
1718    if (res != OK) {
1719        SET_ERR("RequestThread: Unable to register new in-flight request:"
1720                " %s (%d)", strerror(-res), res);
1721        cleanUpFailedRequest(request, nextRequest, outputBuffers);
1722        return false;
1723    }
1724
1725    // Submit request and block until ready for next one
1726    ATRACE_ASYNC_BEGIN("frame capture", request.frame_number);
1727    ATRACE_BEGIN("camera3->process_capture_request");
1728    res = mHal3Device->ops->process_capture_request(mHal3Device, &request);
1729    ATRACE_END();
1730
1731    if (res != OK) {
1732        SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
1733                " device: %s (%d)", request.frame_number, strerror(-res), res);
1734        cleanUpFailedRequest(request, nextRequest, outputBuffers);
1735        return false;
1736    }
1737
1738    // Update the latest request sent to HAL
1739    if (request.settings != NULL) { // Don't update them if they were unchanged
1740        Mutex::Autolock al(mLatestRequestMutex);
1741
1742        camera_metadata_t* cloned = clone_camera_metadata(request.settings);
1743        mLatestRequest.acquire(cloned);
1744    }
1745
1746    if (request.settings != NULL) {
1747        nextRequest->mSettings.unlock(request.settings);
1748    }
1749
1750    // Remove any previously queued triggers (after unlock)
1751    res = removeTriggers(mPrevRequest);
1752    if (res != OK) {
1753        SET_ERR("RequestThread: Unable to remove triggers "
1754              "(capture request %d, HAL device: %s (%d)",
1755              request.frame_number, strerror(-res), res);
1756        return false;
1757    }
1758    mPrevTriggers = triggerCount;
1759
1760    // Read android.request.id from the request settings metadata
1761    // - inform waitUntilRequestProcessed thread of a new request ID
1762    {
1763        Mutex::Autolock al(mLatestRequestMutex);
1764
1765        camera_metadata_entry_t requestIdEntry =
1766                nextRequest->mSettings.find(ANDROID_REQUEST_ID);
1767        if (requestIdEntry.count > 0) {
1768            mLatestRequestId = requestIdEntry.data.i32[0];
1769        } else {
1770            ALOGW("%s: Did not have android.request.id set in the request",
1771                  __FUNCTION__);
1772            mLatestRequestId = NAME_NOT_FOUND;
1773        }
1774
1775        mLatestRequestSignal.signal();
1776    }
1777
1778    // Return input buffer back to framework
1779    if (request.input_buffer != NULL) {
1780        Camera3Stream *stream =
1781            Camera3Stream::cast(request.input_buffer->stream);
1782        res = stream->returnInputBuffer(*(request.input_buffer));
1783        // Note: stream may be deallocated at this point, if this buffer was the
1784        // last reference to it.
1785        if (res != OK) {
1786            ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
1787                    "  its stream:%s (%d)",  __FUNCTION__,
1788                    request.frame_number, strerror(-res), res);
1789            // TODO: Report error upstream
1790        }
1791    }
1792
1793
1794
1795    return true;
1796}
1797
1798CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
1799    Mutex::Autolock al(mLatestRequestMutex);
1800
1801    ALOGV("RequestThread::%s", __FUNCTION__);
1802
1803    return mLatestRequest;
1804}
1805
1806void Camera3Device::RequestThread::cleanUpFailedRequest(
1807        camera3_capture_request_t &request,
1808        sp<CaptureRequest> &nextRequest,
1809        Vector<camera3_stream_buffer_t> &outputBuffers) {
1810
1811    if (request.settings != NULL) {
1812        nextRequest->mSettings.unlock(request.settings);
1813    }
1814    if (request.input_buffer != NULL) {
1815        request.input_buffer->status = CAMERA3_BUFFER_STATUS_ERROR;
1816        nextRequest->mInputStream->returnInputBuffer(*(request.input_buffer));
1817    }
1818    for (size_t i = 0; i < request.num_output_buffers; i++) {
1819        outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
1820        nextRequest->mOutputStreams.editItemAt(i)->returnBuffer(
1821            outputBuffers[i], 0);
1822    }
1823}
1824
1825sp<Camera3Device::CaptureRequest>
1826        Camera3Device::RequestThread::waitForNextRequest() {
1827    status_t res;
1828    sp<CaptureRequest> nextRequest;
1829
1830    // Optimized a bit for the simple steady-state case (single repeating
1831    // request), to avoid putting that request in the queue temporarily.
1832    Mutex::Autolock l(mRequestLock);
1833
1834    while (mRequestQueue.empty()) {
1835        if (!mRepeatingRequests.empty()) {
1836            // Always atomically enqueue all requests in a repeating request
1837            // list. Guarantees a complete in-sequence set of captures to
1838            // application.
1839            const RequestList &requests = mRepeatingRequests;
1840            RequestList::const_iterator firstRequest =
1841                    requests.begin();
1842            nextRequest = *firstRequest;
1843            mRequestQueue.insert(mRequestQueue.end(),
1844                    ++firstRequest,
1845                    requests.end());
1846            // No need to wait any longer
1847            break;
1848        }
1849
1850        res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
1851
1852        if (res == TIMED_OUT) {
1853            // Signal that we're paused by starvation
1854            Mutex::Autolock pl(mPauseLock);
1855            if (mPaused == false) {
1856                mPaused = true;
1857                mPausedSignal.signal();
1858            }
1859            // Stop waiting for now and let thread management happen
1860            return NULL;
1861        }
1862    }
1863
1864    if (nextRequest == NULL) {
1865        // Don't have a repeating request already in hand, so queue
1866        // must have an entry now.
1867        RequestList::iterator firstRequest =
1868                mRequestQueue.begin();
1869        nextRequest = *firstRequest;
1870        mRequestQueue.erase(firstRequest);
1871    }
1872
1873    // In case we've been unpaused by setPaused clearing mDoPause, need to
1874    // update internal pause state (capture/setRepeatingRequest unpause
1875    // directly).
1876    Mutex::Autolock pl(mPauseLock);
1877    mPaused = false;
1878
1879    // Check if we've reconfigured since last time, and reset the preview
1880    // request if so. Can't use 'NULL request == repeat' across configure calls.
1881    if (mReconfigured) {
1882        mPrevRequest.clear();
1883        mReconfigured = false;
1884    }
1885
1886    return nextRequest;
1887}
1888
1889bool Camera3Device::RequestThread::waitIfPaused() {
1890    status_t res;
1891    Mutex::Autolock l(mPauseLock);
1892    while (mDoPause) {
1893        // Signal that we're paused by request
1894        if (mPaused == false) {
1895            mPaused = true;
1896            mPausedSignal.signal();
1897        }
1898        res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
1899        if (res == TIMED_OUT) {
1900            return true;
1901        }
1902    }
1903    // We don't set mPaused to false here, because waitForNextRequest needs
1904    // to further manage the paused state in case of starvation.
1905    return false;
1906}
1907
1908void Camera3Device::RequestThread::unpauseForNewRequests() {
1909    // With work to do, mark thread as unpaused.
1910    // If paused by request (setPaused), don't resume, to avoid
1911    // extra signaling/waiting overhead to waitUntilPaused
1912    Mutex::Autolock p(mPauseLock);
1913    if (!mDoPause) {
1914        mPaused = false;
1915    }
1916}
1917
1918void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
1919    sp<Camera3Device> parent = mParent.promote();
1920    if (parent != NULL) {
1921        va_list args;
1922        va_start(args, fmt);
1923
1924        parent->setErrorStateV(fmt, args);
1925
1926        va_end(args);
1927    }
1928}
1929
1930status_t Camera3Device::RequestThread::insertTriggers(
1931        const sp<CaptureRequest> &request) {
1932
1933    Mutex::Autolock al(mTriggerMutex);
1934
1935    CameraMetadata &metadata = request->mSettings;
1936    size_t count = mTriggerMap.size();
1937
1938    for (size_t i = 0; i < count; ++i) {
1939        RequestTrigger trigger = mTriggerMap.valueAt(i);
1940
1941        uint32_t tag = trigger.metadataTag;
1942        camera_metadata_entry entry = metadata.find(tag);
1943
1944        if (entry.count > 0) {
1945            /**
1946             * Already has an entry for this trigger in the request.
1947             * Rewrite it with our requested trigger value.
1948             */
1949            RequestTrigger oldTrigger = trigger;
1950
1951            oldTrigger.entryValue = entry.data.u8[0];
1952
1953            mTriggerReplacedMap.add(tag, oldTrigger);
1954        } else {
1955            /**
1956             * More typical, no trigger entry, so we just add it
1957             */
1958            mTriggerRemovedMap.add(tag, trigger);
1959        }
1960
1961        status_t res;
1962
1963        switch (trigger.getTagType()) {
1964            case TYPE_BYTE: {
1965                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
1966                res = metadata.update(tag,
1967                                      &entryValue,
1968                                      /*count*/1);
1969                break;
1970            }
1971            case TYPE_INT32:
1972                res = metadata.update(tag,
1973                                      &trigger.entryValue,
1974                                      /*count*/1);
1975                break;
1976            default:
1977                ALOGE("%s: Type not supported: 0x%x",
1978                      __FUNCTION__,
1979                      trigger.getTagType());
1980                return INVALID_OPERATION;
1981        }
1982
1983        if (res != OK) {
1984            ALOGE("%s: Failed to update request metadata with trigger tag %s"
1985                  ", value %d", __FUNCTION__, trigger.getTagName(),
1986                  trigger.entryValue);
1987            return res;
1988        }
1989
1990        ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
1991              trigger.getTagName(),
1992              trigger.entryValue);
1993    }
1994
1995    mTriggerMap.clear();
1996
1997    return count;
1998}
1999
2000status_t Camera3Device::RequestThread::removeTriggers(
2001        const sp<CaptureRequest> &request) {
2002    Mutex::Autolock al(mTriggerMutex);
2003
2004    CameraMetadata &metadata = request->mSettings;
2005
2006    /**
2007     * Replace all old entries with their old values.
2008     */
2009    for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
2010        RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
2011
2012        status_t res;
2013
2014        uint32_t tag = trigger.metadataTag;
2015        switch (trigger.getTagType()) {
2016            case TYPE_BYTE: {
2017                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
2018                res = metadata.update(tag,
2019                                      &entryValue,
2020                                      /*count*/1);
2021                break;
2022            }
2023            case TYPE_INT32:
2024                res = metadata.update(tag,
2025                                      &trigger.entryValue,
2026                                      /*count*/1);
2027                break;
2028            default:
2029                ALOGE("%s: Type not supported: 0x%x",
2030                      __FUNCTION__,
2031                      trigger.getTagType());
2032                return INVALID_OPERATION;
2033        }
2034
2035        if (res != OK) {
2036            ALOGE("%s: Failed to restore request metadata with trigger tag %s"
2037                  ", trigger value %d", __FUNCTION__,
2038                  trigger.getTagName(), trigger.entryValue);
2039            return res;
2040        }
2041    }
2042    mTriggerReplacedMap.clear();
2043
2044    /**
2045     * Remove all new entries.
2046     */
2047    for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
2048        RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
2049        status_t res = metadata.erase(trigger.metadataTag);
2050
2051        if (res != OK) {
2052            ALOGE("%s: Failed to erase metadata with trigger tag %s"
2053                  ", trigger value %d", __FUNCTION__,
2054                  trigger.getTagName(), trigger.entryValue);
2055            return res;
2056        }
2057    }
2058    mTriggerRemovedMap.clear();
2059
2060    return OK;
2061}
2062
2063status_t Camera3Device::RequestThread::addDummyTriggerIds(
2064        const sp<CaptureRequest> &request) {
2065    // Trigger ID 0 has special meaning in the HAL2 spec, so avoid it here
2066    static const int32_t dummyTriggerId = 1;
2067    status_t res;
2068
2069    CameraMetadata &metadata = request->mSettings;
2070
2071    // If AF trigger is active, insert a dummy AF trigger ID if none already
2072    // exists
2073    camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
2074    camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
2075    if (afTrigger.count > 0 &&
2076            afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
2077            afId.count == 0) {
2078        res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
2079        if (res != OK) return res;
2080    }
2081
2082    // If AE precapture trigger is active, insert a dummy precapture trigger ID
2083    // if none already exists
2084    camera_metadata_entry pcTrigger =
2085            metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
2086    camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
2087    if (pcTrigger.count > 0 &&
2088            pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
2089            pcId.count == 0) {
2090        res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
2091                &dummyTriggerId, 1);
2092        if (res != OK) return res;
2093    }
2094
2095    return OK;
2096}
2097
2098
2099/**
2100 * Static callback forwarding methods from HAL to instance
2101 */
2102
2103void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
2104        const camera3_capture_result *result) {
2105    Camera3Device *d =
2106            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
2107    d->processCaptureResult(result);
2108}
2109
2110void Camera3Device::sNotify(const camera3_callback_ops *cb,
2111        const camera3_notify_msg *msg) {
2112    Camera3Device *d =
2113            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
2114    d->notify(msg);
2115}
2116
2117}; // namespace android
2118