Camera3Device.cpp revision a1530f1b16f093a91edbbbaf7dac9f9809867817
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 <inttypes.h>
41
42#include <utils/Log.h>
43#include <utils/Trace.h>
44#include <utils/Timers.h>
45
46#include "utils/CameraTraces.h"
47#include "device3/Camera3Device.h"
48#include "device3/Camera3OutputStream.h"
49#include "device3/Camera3InputStream.h"
50#include "device3/Camera3ZslStream.h"
51#include "device3/Camera3DummyStream.h"
52#include "CameraService.h"
53
54using namespace android::camera3;
55
56namespace android {
57
58Camera3Device::Camera3Device(int id):
59        mId(id),
60        mHal3Device(NULL),
61        mStatus(STATUS_UNINITIALIZED),
62        mUsePartialResult(false),
63        mNumPartialResults(1),
64        mNextResultFrameNumber(0),
65        mNextShutterFrameNumber(0),
66        mListener(NULL)
67{
68    ATRACE_CALL();
69    camera3_callback_ops::notify = &sNotify;
70    camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
71    ALOGV("%s: Created device for camera %d", __FUNCTION__, id);
72}
73
74Camera3Device::~Camera3Device()
75{
76    ATRACE_CALL();
77    ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId);
78    disconnect();
79}
80
81int Camera3Device::getId() const {
82    return mId;
83}
84
85/**
86 * CameraDeviceBase interface
87 */
88
89status_t Camera3Device::initialize(camera_module_t *module)
90{
91    ATRACE_CALL();
92    Mutex::Autolock il(mInterfaceLock);
93    Mutex::Autolock l(mLock);
94
95    ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId);
96    if (mStatus != STATUS_UNINITIALIZED) {
97        CLOGE("Already initialized!");
98        return INVALID_OPERATION;
99    }
100
101    /** Open HAL device */
102
103    status_t res;
104    String8 deviceName = String8::format("%d", mId);
105
106    camera3_device_t *device;
107
108    ATRACE_BEGIN("camera3->open");
109    res = CameraService::filterOpenErrorCode(module->common.methods->open(
110        &module->common, deviceName.string(),
111        reinterpret_cast<hw_device_t**>(&device)));
112    ATRACE_END();
113
114    if (res != OK) {
115        SET_ERR_L("Could not open camera: %s (%d)", strerror(-res), res);
116        return res;
117    }
118
119    /** Cross-check device version */
120    if (device->common.version < CAMERA_DEVICE_API_VERSION_3_0) {
121        SET_ERR_L("Could not open camera: "
122                "Camera device should be at least %x, reports %x instead",
123                CAMERA_DEVICE_API_VERSION_3_0,
124                device->common.version);
125        device->common.close(&device->common);
126        return BAD_VALUE;
127    }
128
129    camera_info info;
130    res = CameraService::filterGetInfoErrorCode(module->get_camera_info(
131        mId, &info));
132    if (res != OK) return res;
133
134    if (info.device_version != device->common.version) {
135        SET_ERR_L("HAL reporting mismatched camera_info version (%x)"
136                " and device version (%x).",
137                info.device_version, device->common.version);
138        device->common.close(&device->common);
139        return BAD_VALUE;
140    }
141
142    /** Initialize device with callback functions */
143
144    ATRACE_BEGIN("camera3->initialize");
145    res = device->ops->initialize(device, this);
146    ATRACE_END();
147
148    if (res != OK) {
149        SET_ERR_L("Unable to initialize HAL device: %s (%d)",
150                strerror(-res), res);
151        device->common.close(&device->common);
152        return BAD_VALUE;
153    }
154
155    /** Start up status tracker thread */
156    mStatusTracker = new StatusTracker(this);
157    res = mStatusTracker->run(String8::format("C3Dev-%d-Status", mId).string());
158    if (res != OK) {
159        SET_ERR_L("Unable to start status tracking thread: %s (%d)",
160                strerror(-res), res);
161        device->common.close(&device->common);
162        mStatusTracker.clear();
163        return res;
164    }
165
166    /** Start up request queue thread */
167
168    mRequestThread = new RequestThread(this, mStatusTracker, device);
169    res = mRequestThread->run(String8::format("C3Dev-%d-ReqQueue", mId).string());
170    if (res != OK) {
171        SET_ERR_L("Unable to start request queue thread: %s (%d)",
172                strerror(-res), res);
173        device->common.close(&device->common);
174        mRequestThread.clear();
175        return res;
176    }
177
178    /** Everything is good to go */
179
180    mDeviceVersion = device->common.version;
181    mDeviceInfo = info.static_camera_characteristics;
182    mHal3Device = device;
183    mStatus = STATUS_UNCONFIGURED;
184    mNextStreamId = 0;
185    mDummyStreamId = NO_STREAM;
186    mNeedConfig = true;
187    mPauseStateNotify = false;
188
189    // Will the HAL be sending in early partial result metadata?
190    if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
191        camera_metadata_entry partialResultsCount =
192                mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
193        if (partialResultsCount.count > 0) {
194            mNumPartialResults = partialResultsCount.data.i32[0];
195            mUsePartialResult = (mNumPartialResults > 1);
196        }
197    } else {
198        camera_metadata_entry partialResultsQuirk =
199                mDeviceInfo.find(ANDROID_QUIRKS_USE_PARTIAL_RESULT);
200        if (partialResultsQuirk.count > 0 && partialResultsQuirk.data.u8[0] == 1) {
201            mUsePartialResult = true;
202        }
203    }
204
205    return OK;
206}
207
208status_t Camera3Device::disconnect() {
209    ATRACE_CALL();
210    Mutex::Autolock il(mInterfaceLock);
211
212    ALOGV("%s: E", __FUNCTION__);
213
214    status_t res = OK;
215
216    {
217        Mutex::Autolock l(mLock);
218        if (mStatus == STATUS_UNINITIALIZED) return res;
219
220        if (mStatus == STATUS_ACTIVE ||
221                (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
222            res = mRequestThread->clearRepeatingRequests();
223            if (res != OK) {
224                SET_ERR_L("Can't stop streaming");
225                // Continue to close device even in case of error
226            } else {
227                res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
228                if (res != OK) {
229                    SET_ERR_L("Timeout waiting for HAL to drain");
230                    // Continue to close device even in case of error
231                }
232            }
233        }
234
235        if (mStatus == STATUS_ERROR) {
236            CLOGE("Shutting down in an error state");
237        }
238
239        if (mStatusTracker != NULL) {
240            mStatusTracker->requestExit();
241        }
242
243        if (mRequestThread != NULL) {
244            mRequestThread->requestExit();
245        }
246
247        mOutputStreams.clear();
248        mInputStream.clear();
249    }
250
251    // Joining done without holding mLock, otherwise deadlocks may ensue
252    // as the threads try to access parent state
253    if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
254        // HAL may be in a bad state, so waiting for request thread
255        // (which may be stuck in the HAL processCaptureRequest call)
256        // could be dangerous.
257        mRequestThread->join();
258    }
259
260    if (mStatusTracker != NULL) {
261        mStatusTracker->join();
262    }
263
264    {
265        Mutex::Autolock l(mLock);
266
267        mRequestThread.clear();
268        mStatusTracker.clear();
269
270        if (mHal3Device != NULL) {
271            ATRACE_BEGIN("camera3->close");
272            mHal3Device->common.close(&mHal3Device->common);
273            ATRACE_END();
274            mHal3Device = NULL;
275        }
276
277        mStatus = STATUS_UNINITIALIZED;
278    }
279
280    ALOGV("%s: X", __FUNCTION__);
281    return res;
282}
283
284// For dumping/debugging only -
285// try to acquire a lock a few times, eventually give up to proceed with
286// debug/dump operations
287bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
288    bool gotLock = false;
289    for (size_t i = 0; i < kDumpLockAttempts; ++i) {
290        if (lock.tryLock() == NO_ERROR) {
291            gotLock = true;
292            break;
293        } else {
294            usleep(kDumpSleepDuration);
295        }
296    }
297    return gotLock;
298}
299
300Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
301    int32_t maxJpegWidth = 0, maxJpegHeight = 0;
302    if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
303        const int STREAM_CONFIGURATION_SIZE = 4;
304        const int STREAM_FORMAT_OFFSET = 0;
305        const int STREAM_WIDTH_OFFSET = 1;
306        const int STREAM_HEIGHT_OFFSET = 2;
307        const int STREAM_IS_INPUT_OFFSET = 3;
308        camera_metadata_ro_entry_t availableStreamConfigs =
309                mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
310        if (availableStreamConfigs.count == 0 ||
311                availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
312            return Size(0, 0);
313        }
314
315        // Get max jpeg size (area-wise).
316        for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
317            int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
318            int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
319            int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
320            int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
321            if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
322                    && format == HAL_PIXEL_FORMAT_BLOB &&
323                    (width * height > maxJpegWidth * maxJpegHeight)) {
324                maxJpegWidth = width;
325                maxJpegHeight = height;
326            }
327        }
328    } else {
329        camera_metadata_ro_entry availableJpegSizes =
330                mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_JPEG_SIZES);
331        if (availableJpegSizes.count == 0 || availableJpegSizes.count % 2 != 0) {
332            return Size(0, 0);
333        }
334
335        // Get max jpeg size (area-wise).
336        for (size_t i = 0; i < availableJpegSizes.count; i += 2) {
337            if ((availableJpegSizes.data.i32[i] * availableJpegSizes.data.i32[i + 1])
338                    > (maxJpegWidth * maxJpegHeight)) {
339                maxJpegWidth = availableJpegSizes.data.i32[i];
340                maxJpegHeight = availableJpegSizes.data.i32[i + 1];
341            }
342        }
343    }
344    return Size(maxJpegWidth, maxJpegHeight);
345}
346
347ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
348    // Get max jpeg size (area-wise).
349    Size maxJpegResolution = getMaxJpegResolution();
350    if (maxJpegResolution.width == 0) {
351        ALOGE("%s: Camera %d: Can't find find valid available jpeg sizes in static metadata!",
352                __FUNCTION__, mId);
353        return BAD_VALUE;
354    }
355
356    // Get max jpeg buffer size
357    ssize_t maxJpegBufferSize = 0;
358    camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
359    if (jpegBufMaxSize.count == 0) {
360        ALOGE("%s: Camera %d: Can't find maximum JPEG size in static metadata!", __FUNCTION__, mId);
361        return BAD_VALUE;
362    }
363    maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
364
365    // Calculate final jpeg buffer size for the given resolution.
366    float scaleFactor = ((float) (width * height)) /
367            (maxJpegResolution.width * maxJpegResolution.height);
368    ssize_t jpegBufferSize = scaleFactor * maxJpegBufferSize;
369    // Bound the buffer size to [MIN_JPEG_BUFFER_SIZE, maxJpegBufferSize].
370    if (jpegBufferSize > maxJpegBufferSize) {
371        jpegBufferSize = maxJpegBufferSize;
372    } else if (jpegBufferSize < kMinJpegBufferSize) {
373        jpegBufferSize = kMinJpegBufferSize;
374    }
375
376    return jpegBufferSize;
377}
378
379status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
380    ATRACE_CALL();
381    (void)args;
382
383    // Try to lock, but continue in case of failure (to avoid blocking in
384    // deadlocks)
385    bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
386    bool gotLock = tryLockSpinRightRound(mLock);
387
388    ALOGW_IF(!gotInterfaceLock,
389            "Camera %d: %s: Unable to lock interface lock, proceeding anyway",
390            mId, __FUNCTION__);
391    ALOGW_IF(!gotLock,
392            "Camera %d: %s: Unable to lock main lock, proceeding anyway",
393            mId, __FUNCTION__);
394
395    String8 lines;
396
397    const char *status =
398            mStatus == STATUS_ERROR         ? "ERROR" :
399            mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
400            mStatus == STATUS_UNCONFIGURED  ? "UNCONFIGURED" :
401            mStatus == STATUS_CONFIGURED    ? "CONFIGURED" :
402            mStatus == STATUS_ACTIVE        ? "ACTIVE" :
403            "Unknown";
404
405    lines.appendFormat("    Device status: %s\n", status);
406    if (mStatus == STATUS_ERROR) {
407        lines.appendFormat("    Error cause: %s\n", mErrorCause.string());
408    }
409    lines.appendFormat("    Stream configuration:\n");
410
411    if (mInputStream != NULL) {
412        write(fd, lines.string(), lines.size());
413        mInputStream->dump(fd, args);
414    } else {
415        lines.appendFormat("      No input stream.\n");
416        write(fd, lines.string(), lines.size());
417    }
418    for (size_t i = 0; i < mOutputStreams.size(); i++) {
419        mOutputStreams[i]->dump(fd,args);
420    }
421
422    lines = String8("    In-flight requests:\n");
423    if (mInFlightMap.size() == 0) {
424        lines.append("      None\n");
425    } else {
426        for (size_t i = 0; i < mInFlightMap.size(); i++) {
427            InFlightRequest r = mInFlightMap.valueAt(i);
428            lines.appendFormat("      Frame %d |  Timestamp: %" PRId64 ", metadata"
429                    " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
430                    r.captureTimestamp, r.haveResultMetadata ? "true" : "false",
431                    r.numBuffersLeft);
432        }
433    }
434    write(fd, lines.string(), lines.size());
435
436    {
437        lines = String8("    Last request sent:\n");
438        write(fd, lines.string(), lines.size());
439
440        CameraMetadata lastRequest = getLatestRequestLocked();
441        lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
442    }
443
444    if (mHal3Device != NULL) {
445        lines = String8("    HAL device dump:\n");
446        write(fd, lines.string(), lines.size());
447        mHal3Device->ops->dump(mHal3Device, fd);
448    }
449
450    if (gotLock) mLock.unlock();
451    if (gotInterfaceLock) mInterfaceLock.unlock();
452
453    return OK;
454}
455
456const CameraMetadata& Camera3Device::info() const {
457    ALOGVV("%s: E", __FUNCTION__);
458    if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
459                    mStatus == STATUS_ERROR)) {
460        ALOGW("%s: Access to static info %s!", __FUNCTION__,
461                mStatus == STATUS_ERROR ?
462                "when in error state" : "before init");
463    }
464    return mDeviceInfo;
465}
466
467status_t Camera3Device::checkStatusOkToCaptureLocked() {
468    switch (mStatus) {
469        case STATUS_ERROR:
470            CLOGE("Device has encountered a serious error");
471            return INVALID_OPERATION;
472        case STATUS_UNINITIALIZED:
473            CLOGE("Device not initialized");
474            return INVALID_OPERATION;
475        case STATUS_UNCONFIGURED:
476        case STATUS_CONFIGURED:
477        case STATUS_ACTIVE:
478            // OK
479            break;
480        default:
481            SET_ERR_L("Unexpected status: %d", mStatus);
482            return INVALID_OPERATION;
483    }
484    return OK;
485}
486
487status_t Camera3Device::convertMetadataListToRequestListLocked(
488        const List<const CameraMetadata> &metadataList, RequestList *requestList) {
489    if (requestList == NULL) {
490        CLOGE("requestList cannot be NULL.");
491        return BAD_VALUE;
492    }
493
494    int32_t burstId = 0;
495    for (List<const CameraMetadata>::const_iterator it = metadataList.begin();
496            it != metadataList.end(); ++it) {
497        sp<CaptureRequest> newRequest = setUpRequestLocked(*it);
498        if (newRequest == 0) {
499            CLOGE("Can't create capture request");
500            return BAD_VALUE;
501        }
502
503        // Setup burst Id and request Id
504        newRequest->mResultExtras.burstId = burstId++;
505        if (it->exists(ANDROID_REQUEST_ID)) {
506            if (it->find(ANDROID_REQUEST_ID).count == 0) {
507                CLOGE("RequestID entry exists; but must not be empty in metadata");
508                return BAD_VALUE;
509            }
510            newRequest->mResultExtras.requestId = it->find(ANDROID_REQUEST_ID).data.i32[0];
511        } else {
512            CLOGE("RequestID does not exist in metadata");
513            return BAD_VALUE;
514        }
515
516        requestList->push_back(newRequest);
517
518        ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
519    }
520    return OK;
521}
522
523status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
524    ATRACE_CALL();
525
526    List<const CameraMetadata> requests;
527    requests.push_back(request);
528    return captureList(requests, /*lastFrameNumber*/NULL);
529}
530
531status_t Camera3Device::submitRequestsHelper(
532        const List<const CameraMetadata> &requests, bool repeating,
533        /*out*/
534        int64_t *lastFrameNumber) {
535    ATRACE_CALL();
536    Mutex::Autolock il(mInterfaceLock);
537    Mutex::Autolock l(mLock);
538
539    status_t res = checkStatusOkToCaptureLocked();
540    if (res != OK) {
541        // error logged by previous call
542        return res;
543    }
544
545    RequestList requestList;
546
547    res = convertMetadataListToRequestListLocked(requests, /*out*/&requestList);
548    if (res != OK) {
549        // error logged by previous call
550        return res;
551    }
552
553    if (repeating) {
554        res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
555    } else {
556        res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
557    }
558
559    if (res == OK) {
560        waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
561        if (res != OK) {
562            SET_ERR_L("Can't transition to active in %f seconds!",
563                    kActiveTimeout/1e9);
564        }
565        ALOGV("Camera %d: Capture request %" PRId32 " enqueued", mId,
566              (*(requestList.begin()))->mResultExtras.requestId);
567    } else {
568        CLOGE("Cannot queue request. Impossible.");
569        return BAD_VALUE;
570    }
571
572    return res;
573}
574
575status_t Camera3Device::captureList(const List<const CameraMetadata> &requests,
576                                    int64_t *lastFrameNumber) {
577    ATRACE_CALL();
578
579    return submitRequestsHelper(requests, /*repeating*/false, lastFrameNumber);
580}
581
582status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
583                                            int64_t* /*lastFrameNumber*/) {
584    ATRACE_CALL();
585
586    List<const CameraMetadata> requests;
587    requests.push_back(request);
588    return setStreamingRequestList(requests, /*lastFrameNumber*/NULL);
589}
590
591status_t Camera3Device::setStreamingRequestList(const List<const CameraMetadata> &requests,
592                                                int64_t *lastFrameNumber) {
593    ATRACE_CALL();
594
595    return submitRequestsHelper(requests, /*repeating*/true, lastFrameNumber);
596}
597
598sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
599        const CameraMetadata &request) {
600    status_t res;
601
602    if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
603        res = configureStreamsLocked();
604        // Stream configuration failed due to unsupported configuration.
605        // Device back to unconfigured state. Client might try other configuraitons
606        if (res == BAD_VALUE && mStatus == STATUS_UNCONFIGURED) {
607            CLOGE("No streams configured");
608            return NULL;
609        }
610        // Stream configuration failed for other reason. Fatal.
611        if (res != OK) {
612            SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res);
613            return NULL;
614        }
615        // Stream configuration successfully configure to empty stream configuration.
616        if (mStatus == STATUS_UNCONFIGURED) {
617            CLOGE("No streams configured");
618            return NULL;
619        }
620    }
621
622    sp<CaptureRequest> newRequest = createCaptureRequest(request);
623    return newRequest;
624}
625
626status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
627    ATRACE_CALL();
628    Mutex::Autolock il(mInterfaceLock);
629    Mutex::Autolock l(mLock);
630
631    switch (mStatus) {
632        case STATUS_ERROR:
633            CLOGE("Device has encountered a serious error");
634            return INVALID_OPERATION;
635        case STATUS_UNINITIALIZED:
636            CLOGE("Device not initialized");
637            return INVALID_OPERATION;
638        case STATUS_UNCONFIGURED:
639        case STATUS_CONFIGURED:
640        case STATUS_ACTIVE:
641            // OK
642            break;
643        default:
644            SET_ERR_L("Unexpected status: %d", mStatus);
645            return INVALID_OPERATION;
646    }
647    ALOGV("Camera %d: Clearing repeating request", mId);
648
649    return mRequestThread->clearRepeatingRequests(lastFrameNumber);
650}
651
652status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
653    ATRACE_CALL();
654    Mutex::Autolock il(mInterfaceLock);
655
656    return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
657}
658
659status_t Camera3Device::createInputStream(
660        uint32_t width, uint32_t height, int format, int *id) {
661    ATRACE_CALL();
662    Mutex::Autolock il(mInterfaceLock);
663    Mutex::Autolock l(mLock);
664    ALOGV("Camera %d: Creating new input stream %d: %d x %d, format %d",
665            mId, mNextStreamId, width, height, format);
666
667    status_t res;
668    bool wasActive = false;
669
670    switch (mStatus) {
671        case STATUS_ERROR:
672            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
673            return INVALID_OPERATION;
674        case STATUS_UNINITIALIZED:
675            ALOGE("%s: Device not initialized", __FUNCTION__);
676            return INVALID_OPERATION;
677        case STATUS_UNCONFIGURED:
678        case STATUS_CONFIGURED:
679            // OK
680            break;
681        case STATUS_ACTIVE:
682            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
683            res = internalPauseAndWaitLocked();
684            if (res != OK) {
685                SET_ERR_L("Can't pause captures to reconfigure streams!");
686                return res;
687            }
688            wasActive = true;
689            break;
690        default:
691            SET_ERR_L("%s: Unexpected status: %d", mStatus);
692            return INVALID_OPERATION;
693    }
694    assert(mStatus != STATUS_ACTIVE);
695
696    if (mInputStream != 0) {
697        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
698        return INVALID_OPERATION;
699    }
700
701    sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
702                width, height, format);
703    newStream->setStatusTracker(mStatusTracker);
704
705    mInputStream = newStream;
706
707    *id = mNextStreamId++;
708
709    // Continue captures if active at start
710    if (wasActive) {
711        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
712        res = configureStreamsLocked();
713        if (res != OK) {
714            ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
715                    __FUNCTION__, mNextStreamId, strerror(-res), res);
716            return res;
717        }
718        internalResumeLocked();
719    }
720
721    ALOGV("Camera %d: Created input stream", mId);
722    return OK;
723}
724
725
726status_t Camera3Device::createZslStream(
727            uint32_t width, uint32_t height,
728            int depth,
729            /*out*/
730            int *id,
731            sp<Camera3ZslStream>* zslStream) {
732    ATRACE_CALL();
733    Mutex::Autolock il(mInterfaceLock);
734    Mutex::Autolock l(mLock);
735    ALOGV("Camera %d: Creating ZSL stream %d: %d x %d, depth %d",
736            mId, mNextStreamId, width, height, depth);
737
738    status_t res;
739    bool wasActive = false;
740
741    switch (mStatus) {
742        case STATUS_ERROR:
743            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
744            return INVALID_OPERATION;
745        case STATUS_UNINITIALIZED:
746            ALOGE("%s: Device not initialized", __FUNCTION__);
747            return INVALID_OPERATION;
748        case STATUS_UNCONFIGURED:
749        case STATUS_CONFIGURED:
750            // OK
751            break;
752        case STATUS_ACTIVE:
753            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
754            res = internalPauseAndWaitLocked();
755            if (res != OK) {
756                SET_ERR_L("Can't pause captures to reconfigure streams!");
757                return res;
758            }
759            wasActive = true;
760            break;
761        default:
762            SET_ERR_L("Unexpected status: %d", mStatus);
763            return INVALID_OPERATION;
764    }
765    assert(mStatus != STATUS_ACTIVE);
766
767    if (mInputStream != 0) {
768        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
769        return INVALID_OPERATION;
770    }
771
772    sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
773                width, height, depth);
774    newStream->setStatusTracker(mStatusTracker);
775
776    res = mOutputStreams.add(mNextStreamId, newStream);
777    if (res < 0) {
778        ALOGE("%s: Can't add new stream to set: %s (%d)",
779                __FUNCTION__, strerror(-res), res);
780        return res;
781    }
782    mInputStream = newStream;
783
784    mNeedConfig = true;
785
786    *id = mNextStreamId++;
787    *zslStream = newStream;
788
789    // Continue captures if active at start
790    if (wasActive) {
791        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
792        res = configureStreamsLocked();
793        if (res != OK) {
794            ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
795                    __FUNCTION__, mNextStreamId, strerror(-res), res);
796            return res;
797        }
798        internalResumeLocked();
799    }
800
801    ALOGV("Camera %d: Created ZSL stream", mId);
802    return OK;
803}
804
805status_t Camera3Device::createStream(sp<ANativeWindow> consumer,
806        uint32_t width, uint32_t height, int format, int *id) {
807    ATRACE_CALL();
808    Mutex::Autolock il(mInterfaceLock);
809    Mutex::Autolock l(mLock);
810    ALOGV("Camera %d: Creating new stream %d: %d x %d, format %d",
811            mId, mNextStreamId, width, height, format);
812
813    status_t res;
814    bool wasActive = false;
815
816    switch (mStatus) {
817        case STATUS_ERROR:
818            CLOGE("Device has encountered a serious error");
819            return INVALID_OPERATION;
820        case STATUS_UNINITIALIZED:
821            CLOGE("Device not initialized");
822            return INVALID_OPERATION;
823        case STATUS_UNCONFIGURED:
824        case STATUS_CONFIGURED:
825            // OK
826            break;
827        case STATUS_ACTIVE:
828            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
829            res = internalPauseAndWaitLocked();
830            if (res != OK) {
831                SET_ERR_L("Can't pause captures to reconfigure streams!");
832                return res;
833            }
834            wasActive = true;
835            break;
836        default:
837            SET_ERR_L("Unexpected status: %d", mStatus);
838            return INVALID_OPERATION;
839    }
840    assert(mStatus != STATUS_ACTIVE);
841
842    sp<Camera3OutputStream> newStream;
843    if (format == HAL_PIXEL_FORMAT_BLOB) {
844        ssize_t jpegBufferSize = getJpegBufferSize(width, height);
845        if (jpegBufferSize <= 0) {
846            SET_ERR_L("Invalid jpeg buffer size %zd", jpegBufferSize);
847            return BAD_VALUE;
848        }
849
850        newStream = new Camera3OutputStream(mNextStreamId, consumer,
851                width, height, jpegBufferSize, format);
852    } else {
853        newStream = new Camera3OutputStream(mNextStreamId, consumer,
854                width, height, format);
855    }
856    newStream->setStatusTracker(mStatusTracker);
857
858    res = mOutputStreams.add(mNextStreamId, newStream);
859    if (res < 0) {
860        SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
861        return res;
862    }
863
864    *id = mNextStreamId++;
865    mNeedConfig = true;
866
867    // Continue captures if active at start
868    if (wasActive) {
869        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
870        res = configureStreamsLocked();
871        if (res != OK) {
872            CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
873                    mNextStreamId, strerror(-res), res);
874            return res;
875        }
876        internalResumeLocked();
877    }
878    ALOGV("Camera %d: Created new stream", mId);
879    return OK;
880}
881
882status_t Camera3Device::createReprocessStreamFromStream(int outputId, int *id) {
883    ATRACE_CALL();
884    (void)outputId; (void)id;
885
886    CLOGE("Unimplemented");
887    return INVALID_OPERATION;
888}
889
890
891status_t Camera3Device::getStreamInfo(int id,
892        uint32_t *width, uint32_t *height, uint32_t *format) {
893    ATRACE_CALL();
894    Mutex::Autolock il(mInterfaceLock);
895    Mutex::Autolock l(mLock);
896
897    switch (mStatus) {
898        case STATUS_ERROR:
899            CLOGE("Device has encountered a serious error");
900            return INVALID_OPERATION;
901        case STATUS_UNINITIALIZED:
902            CLOGE("Device not initialized!");
903            return INVALID_OPERATION;
904        case STATUS_UNCONFIGURED:
905        case STATUS_CONFIGURED:
906        case STATUS_ACTIVE:
907            // OK
908            break;
909        default:
910            SET_ERR_L("Unexpected status: %d", mStatus);
911            return INVALID_OPERATION;
912    }
913
914    ssize_t idx = mOutputStreams.indexOfKey(id);
915    if (idx == NAME_NOT_FOUND) {
916        CLOGE("Stream %d is unknown", id);
917        return idx;
918    }
919
920    if (width) *width  = mOutputStreams[idx]->getWidth();
921    if (height) *height = mOutputStreams[idx]->getHeight();
922    if (format) *format = mOutputStreams[idx]->getFormat();
923
924    return OK;
925}
926
927status_t Camera3Device::setStreamTransform(int id,
928        int transform) {
929    ATRACE_CALL();
930    Mutex::Autolock il(mInterfaceLock);
931    Mutex::Autolock l(mLock);
932
933    switch (mStatus) {
934        case STATUS_ERROR:
935            CLOGE("Device has encountered a serious error");
936            return INVALID_OPERATION;
937        case STATUS_UNINITIALIZED:
938            CLOGE("Device not initialized");
939            return INVALID_OPERATION;
940        case STATUS_UNCONFIGURED:
941        case STATUS_CONFIGURED:
942        case STATUS_ACTIVE:
943            // OK
944            break;
945        default:
946            SET_ERR_L("Unexpected status: %d", mStatus);
947            return INVALID_OPERATION;
948    }
949
950    ssize_t idx = mOutputStreams.indexOfKey(id);
951    if (idx == NAME_NOT_FOUND) {
952        CLOGE("Stream %d does not exist",
953                id);
954        return BAD_VALUE;
955    }
956
957    return mOutputStreams.editValueAt(idx)->setTransform(transform);
958}
959
960status_t Camera3Device::deleteStream(int id) {
961    ATRACE_CALL();
962    Mutex::Autolock il(mInterfaceLock);
963    Mutex::Autolock l(mLock);
964    status_t res;
965
966    ALOGV("%s: Camera %d: Deleting stream %d", __FUNCTION__, mId, id);
967
968    // CameraDevice semantics require device to already be idle before
969    // deleteStream is called, unlike for createStream.
970    if (mStatus == STATUS_ACTIVE) {
971        ALOGV("%s: Camera %d: Device not idle", __FUNCTION__, mId);
972        return -EBUSY;
973    }
974
975    sp<Camera3StreamInterface> deletedStream;
976    ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
977    if (mInputStream != NULL && id == mInputStream->getId()) {
978        deletedStream = mInputStream;
979        mInputStream.clear();
980    } else {
981        if (outputStreamIdx == NAME_NOT_FOUND) {
982            CLOGE("Stream %d does not exist", id);
983            return BAD_VALUE;
984        }
985    }
986
987    // Delete output stream or the output part of a bi-directional stream.
988    if (outputStreamIdx != NAME_NOT_FOUND) {
989        deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
990        mOutputStreams.removeItem(id);
991    }
992
993    // Free up the stream endpoint so that it can be used by some other stream
994    res = deletedStream->disconnect();
995    if (res != OK) {
996        SET_ERR_L("Can't disconnect deleted stream %d", id);
997        // fall through since we want to still list the stream as deleted.
998    }
999    mDeletedStreams.add(deletedStream);
1000    mNeedConfig = true;
1001
1002    return res;
1003}
1004
1005status_t Camera3Device::deleteReprocessStream(int id) {
1006    ATRACE_CALL();
1007    (void)id;
1008
1009    CLOGE("Unimplemented");
1010    return INVALID_OPERATION;
1011}
1012
1013status_t Camera3Device::configureStreams() {
1014    ATRACE_CALL();
1015    ALOGV("%s: E", __FUNCTION__);
1016
1017    Mutex::Autolock il(mInterfaceLock);
1018    Mutex::Autolock l(mLock);
1019
1020    return configureStreamsLocked();
1021}
1022
1023status_t Camera3Device::createDefaultRequest(int templateId,
1024        CameraMetadata *request) {
1025    ATRACE_CALL();
1026    ALOGV("%s: for template %d", __FUNCTION__, templateId);
1027    Mutex::Autolock il(mInterfaceLock);
1028    Mutex::Autolock l(mLock);
1029
1030    switch (mStatus) {
1031        case STATUS_ERROR:
1032            CLOGE("Device has encountered a serious error");
1033            return INVALID_OPERATION;
1034        case STATUS_UNINITIALIZED:
1035            CLOGE("Device is not initialized!");
1036            return INVALID_OPERATION;
1037        case STATUS_UNCONFIGURED:
1038        case STATUS_CONFIGURED:
1039        case STATUS_ACTIVE:
1040            // OK
1041            break;
1042        default:
1043            SET_ERR_L("Unexpected status: %d", mStatus);
1044            return INVALID_OPERATION;
1045    }
1046
1047    if (!mRequestTemplateCache[templateId].isEmpty()) {
1048        *request = mRequestTemplateCache[templateId];
1049        return OK;
1050    }
1051
1052    const camera_metadata_t *rawRequest;
1053    ATRACE_BEGIN("camera3->construct_default_request_settings");
1054    rawRequest = mHal3Device->ops->construct_default_request_settings(
1055        mHal3Device, templateId);
1056    ATRACE_END();
1057    if (rawRequest == NULL) {
1058        SET_ERR_L("HAL is unable to construct default settings for template %d",
1059                templateId);
1060        return DEAD_OBJECT;
1061    }
1062    *request = rawRequest;
1063    mRequestTemplateCache[templateId] = rawRequest;
1064
1065    return OK;
1066}
1067
1068status_t Camera3Device::waitUntilDrained() {
1069    ATRACE_CALL();
1070    Mutex::Autolock il(mInterfaceLock);
1071    Mutex::Autolock l(mLock);
1072
1073    return waitUntilDrainedLocked();
1074}
1075
1076status_t Camera3Device::waitUntilDrainedLocked() {
1077    switch (mStatus) {
1078        case STATUS_UNINITIALIZED:
1079        case STATUS_UNCONFIGURED:
1080            ALOGV("%s: Already idle", __FUNCTION__);
1081            return OK;
1082        case STATUS_CONFIGURED:
1083            // To avoid race conditions, check with tracker to be sure
1084        case STATUS_ERROR:
1085        case STATUS_ACTIVE:
1086            // Need to verify shut down
1087            break;
1088        default:
1089            SET_ERR_L("Unexpected status: %d",mStatus);
1090            return INVALID_OPERATION;
1091    }
1092
1093    ALOGV("%s: Camera %d: Waiting until idle", __FUNCTION__, mId);
1094    status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1095    return res;
1096}
1097
1098// Pause to reconfigure
1099status_t Camera3Device::internalPauseAndWaitLocked() {
1100    mRequestThread->setPaused(true);
1101    mPauseStateNotify = true;
1102
1103    ALOGV("%s: Camera %d: Internal wait until idle", __FUNCTION__, mId);
1104    status_t res = waitUntilStateThenRelock(/*active*/ false, kShutdownTimeout);
1105    if (res != OK) {
1106        SET_ERR_L("Can't idle device in %f seconds!",
1107                kShutdownTimeout/1e9);
1108    }
1109
1110    return res;
1111}
1112
1113// Resume after internalPauseAndWaitLocked
1114status_t Camera3Device::internalResumeLocked() {
1115    status_t res;
1116
1117    mRequestThread->setPaused(false);
1118
1119    res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1120    if (res != OK) {
1121        SET_ERR_L("Can't transition to active in %f seconds!",
1122                kActiveTimeout/1e9);
1123    }
1124    mPauseStateNotify = false;
1125    return OK;
1126}
1127
1128status_t Camera3Device::waitUntilStateThenRelock(bool active,
1129        nsecs_t timeout) {
1130    status_t res = OK;
1131    if (active == (mStatus == STATUS_ACTIVE)) {
1132        // Desired state already reached
1133        return res;
1134    }
1135
1136    bool stateSeen = false;
1137    do {
1138        mRecentStatusUpdates.clear();
1139
1140        res = mStatusChanged.waitRelative(mLock, timeout);
1141        if (res != OK) break;
1142
1143        // Check state change history during wait
1144        for (size_t i = 0; i < mRecentStatusUpdates.size(); i++) {
1145            if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1146                stateSeen = true;
1147                break;
1148            }
1149        }
1150    } while (!stateSeen);
1151
1152    return res;
1153}
1154
1155
1156status_t Camera3Device::setNotifyCallback(NotificationListener *listener) {
1157    ATRACE_CALL();
1158    Mutex::Autolock l(mOutputLock);
1159
1160    if (listener != NULL && mListener != NULL) {
1161        ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1162    }
1163    mListener = listener;
1164    mRequestThread->setNotifyCallback(listener);
1165
1166    return OK;
1167}
1168
1169bool Camera3Device::willNotify3A() {
1170    return false;
1171}
1172
1173status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
1174    status_t res;
1175    Mutex::Autolock l(mOutputLock);
1176
1177    while (mResultQueue.empty()) {
1178        res = mResultSignal.waitRelative(mOutputLock, timeout);
1179        if (res == TIMED_OUT) {
1180            return res;
1181        } else if (res != OK) {
1182            ALOGW("%s: Camera %d: No frame in %" PRId64 " ns: %s (%d)",
1183                    __FUNCTION__, mId, timeout, strerror(-res), res);
1184            return res;
1185        }
1186    }
1187    return OK;
1188}
1189
1190status_t Camera3Device::getNextResult(CaptureResult *frame) {
1191    ATRACE_CALL();
1192    Mutex::Autolock l(mOutputLock);
1193
1194    if (mResultQueue.empty()) {
1195        return NOT_ENOUGH_DATA;
1196    }
1197
1198    if (frame == NULL) {
1199        ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1200        return BAD_VALUE;
1201    }
1202
1203    CaptureResult &result = *(mResultQueue.begin());
1204    frame->mResultExtras = result.mResultExtras;
1205    frame->mMetadata.acquire(result.mMetadata);
1206    mResultQueue.erase(mResultQueue.begin());
1207
1208    return OK;
1209}
1210
1211status_t Camera3Device::triggerAutofocus(uint32_t id) {
1212    ATRACE_CALL();
1213    Mutex::Autolock il(mInterfaceLock);
1214
1215    ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1216    // Mix-in this trigger into the next request and only the next request.
1217    RequestTrigger trigger[] = {
1218        {
1219            ANDROID_CONTROL_AF_TRIGGER,
1220            ANDROID_CONTROL_AF_TRIGGER_START
1221        },
1222        {
1223            ANDROID_CONTROL_AF_TRIGGER_ID,
1224            static_cast<int32_t>(id)
1225        }
1226    };
1227
1228    return mRequestThread->queueTrigger(trigger,
1229                                        sizeof(trigger)/sizeof(trigger[0]));
1230}
1231
1232status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1233    ATRACE_CALL();
1234    Mutex::Autolock il(mInterfaceLock);
1235
1236    ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1237    // Mix-in this trigger into the next request and only the next request.
1238    RequestTrigger trigger[] = {
1239        {
1240            ANDROID_CONTROL_AF_TRIGGER,
1241            ANDROID_CONTROL_AF_TRIGGER_CANCEL
1242        },
1243        {
1244            ANDROID_CONTROL_AF_TRIGGER_ID,
1245            static_cast<int32_t>(id)
1246        }
1247    };
1248
1249    return mRequestThread->queueTrigger(trigger,
1250                                        sizeof(trigger)/sizeof(trigger[0]));
1251}
1252
1253status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1254    ATRACE_CALL();
1255    Mutex::Autolock il(mInterfaceLock);
1256
1257    ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1258    // Mix-in this trigger into the next request and only the next request.
1259    RequestTrigger trigger[] = {
1260        {
1261            ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1262            ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1263        },
1264        {
1265            ANDROID_CONTROL_AE_PRECAPTURE_ID,
1266            static_cast<int32_t>(id)
1267        }
1268    };
1269
1270    return mRequestThread->queueTrigger(trigger,
1271                                        sizeof(trigger)/sizeof(trigger[0]));
1272}
1273
1274status_t Camera3Device::pushReprocessBuffer(int reprocessStreamId,
1275        buffer_handle_t *buffer, wp<BufferReleasedListener> listener) {
1276    ATRACE_CALL();
1277    (void)reprocessStreamId; (void)buffer; (void)listener;
1278
1279    CLOGE("Unimplemented");
1280    return INVALID_OPERATION;
1281}
1282
1283status_t Camera3Device::flush(int64_t *frameNumber) {
1284    ATRACE_CALL();
1285    ALOGV("%s: Camera %d: Flushing all requests", __FUNCTION__, mId);
1286    Mutex::Autolock il(mInterfaceLock);
1287
1288    NotificationListener* listener;
1289    {
1290        Mutex::Autolock l(mOutputLock);
1291        listener = mListener;
1292    }
1293
1294    {
1295        Mutex::Autolock l(mLock);
1296        mRequestThread->clear(listener, /*out*/frameNumber);
1297    }
1298
1299    status_t res;
1300    if (mHal3Device->common.version >= CAMERA_DEVICE_API_VERSION_3_1) {
1301        res = mHal3Device->ops->flush(mHal3Device);
1302    } else {
1303        Mutex::Autolock l(mLock);
1304        res = waitUntilDrainedLocked();
1305    }
1306
1307    return res;
1308}
1309
1310uint32_t Camera3Device::getDeviceVersion() {
1311    ATRACE_CALL();
1312    Mutex::Autolock il(mInterfaceLock);
1313    return mDeviceVersion;
1314}
1315
1316/**
1317 * Methods called by subclasses
1318 */
1319
1320void Camera3Device::notifyStatus(bool idle) {
1321    {
1322        // Need mLock to safely update state and synchronize to current
1323        // state of methods in flight.
1324        Mutex::Autolock l(mLock);
1325        // We can get various system-idle notices from the status tracker
1326        // while starting up. Only care about them if we've actually sent
1327        // in some requests recently.
1328        if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
1329            return;
1330        }
1331        ALOGV("%s: Camera %d: Now %s", __FUNCTION__, mId,
1332                idle ? "idle" : "active");
1333        mStatus = idle ? STATUS_CONFIGURED : STATUS_ACTIVE;
1334        mRecentStatusUpdates.add(mStatus);
1335        mStatusChanged.signal();
1336
1337        // Skip notifying listener if we're doing some user-transparent
1338        // state changes
1339        if (mPauseStateNotify) return;
1340    }
1341    NotificationListener *listener;
1342    {
1343        Mutex::Autolock l(mOutputLock);
1344        listener = mListener;
1345    }
1346    if (idle && listener != NULL) {
1347        listener->notifyIdle();
1348    }
1349}
1350
1351/**
1352 * Camera3Device private methods
1353 */
1354
1355sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
1356        const CameraMetadata &request) {
1357    ATRACE_CALL();
1358    status_t res;
1359
1360    sp<CaptureRequest> newRequest = new CaptureRequest;
1361    newRequest->mSettings = request;
1362
1363    camera_metadata_entry_t inputStreams =
1364            newRequest->mSettings.find(ANDROID_REQUEST_INPUT_STREAMS);
1365    if (inputStreams.count > 0) {
1366        if (mInputStream == NULL ||
1367                mInputStream->getId() != inputStreams.data.i32[0]) {
1368            CLOGE("Request references unknown input stream %d",
1369                    inputStreams.data.u8[0]);
1370            return NULL;
1371        }
1372        // Lazy completion of stream configuration (allocation/registration)
1373        // on first use
1374        if (mInputStream->isConfiguring()) {
1375            res = mInputStream->finishConfiguration(mHal3Device);
1376            if (res != OK) {
1377                SET_ERR_L("Unable to finish configuring input stream %d:"
1378                        " %s (%d)",
1379                        mInputStream->getId(), strerror(-res), res);
1380                return NULL;
1381            }
1382        }
1383
1384        newRequest->mInputStream = mInputStream;
1385        newRequest->mSettings.erase(ANDROID_REQUEST_INPUT_STREAMS);
1386    }
1387
1388    camera_metadata_entry_t streams =
1389            newRequest->mSettings.find(ANDROID_REQUEST_OUTPUT_STREAMS);
1390    if (streams.count == 0) {
1391        CLOGE("Zero output streams specified!");
1392        return NULL;
1393    }
1394
1395    for (size_t i = 0; i < streams.count; i++) {
1396        int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
1397        if (idx == NAME_NOT_FOUND) {
1398            CLOGE("Request references unknown stream %d",
1399                    streams.data.u8[i]);
1400            return NULL;
1401        }
1402        sp<Camera3OutputStreamInterface> stream =
1403                mOutputStreams.editValueAt(idx);
1404
1405        // Lazy completion of stream configuration (allocation/registration)
1406        // on first use
1407        if (stream->isConfiguring()) {
1408            res = stream->finishConfiguration(mHal3Device);
1409            if (res != OK) {
1410                SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
1411                        stream->getId(), strerror(-res), res);
1412                return NULL;
1413            }
1414        }
1415
1416        newRequest->mOutputStreams.push(stream);
1417    }
1418    newRequest->mSettings.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
1419
1420    return newRequest;
1421}
1422
1423status_t Camera3Device::configureStreamsLocked() {
1424    ATRACE_CALL();
1425    status_t res;
1426
1427    if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
1428        CLOGE("Not idle");
1429        return INVALID_OPERATION;
1430    }
1431
1432    if (!mNeedConfig) {
1433        ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
1434        return OK;
1435    }
1436
1437    // Workaround for device HALv3.2 or older spec bug - zero streams requires
1438    // adding a dummy stream instead.
1439    // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
1440    if (mOutputStreams.size() == 0) {
1441        addDummyStreamLocked();
1442    } else {
1443        tryRemoveDummyStreamLocked();
1444    }
1445
1446    // Start configuring the streams
1447    ALOGV("%s: Camera %d: Starting stream configuration", __FUNCTION__, mId);
1448
1449    camera3_stream_configuration config;
1450
1451    config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
1452
1453    Vector<camera3_stream_t*> streams;
1454    streams.setCapacity(config.num_streams);
1455
1456    if (mInputStream != NULL) {
1457        camera3_stream_t *inputStream;
1458        inputStream = mInputStream->startConfiguration();
1459        if (inputStream == NULL) {
1460            SET_ERR_L("Can't start input stream configuration");
1461            return INVALID_OPERATION;
1462        }
1463        streams.add(inputStream);
1464    }
1465
1466    for (size_t i = 0; i < mOutputStreams.size(); i++) {
1467
1468        // Don't configure bidi streams twice, nor add them twice to the list
1469        if (mOutputStreams[i].get() ==
1470            static_cast<Camera3StreamInterface*>(mInputStream.get())) {
1471
1472            config.num_streams--;
1473            continue;
1474        }
1475
1476        camera3_stream_t *outputStream;
1477        outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
1478        if (outputStream == NULL) {
1479            SET_ERR_L("Can't start output stream configuration");
1480            return INVALID_OPERATION;
1481        }
1482        streams.add(outputStream);
1483    }
1484
1485    config.streams = streams.editArray();
1486
1487    // Do the HAL configuration; will potentially touch stream
1488    // max_buffers, usage, priv fields.
1489    ATRACE_BEGIN("camera3->configure_streams");
1490    res = mHal3Device->ops->configure_streams(mHal3Device, &config);
1491    ATRACE_END();
1492
1493    if (res == BAD_VALUE) {
1494        // HAL rejected this set of streams as unsupported, clean up config
1495        // attempt and return to unconfigured state
1496        if (mInputStream != NULL && mInputStream->isConfiguring()) {
1497            res = mInputStream->cancelConfiguration();
1498            if (res != OK) {
1499                SET_ERR_L("Can't cancel configuring input stream %d: %s (%d)",
1500                        mInputStream->getId(), strerror(-res), res);
1501                return res;
1502            }
1503        }
1504
1505        for (size_t i = 0; i < mOutputStreams.size(); i++) {
1506            sp<Camera3OutputStreamInterface> outputStream =
1507                    mOutputStreams.editValueAt(i);
1508            if (outputStream->isConfiguring()) {
1509                res = outputStream->cancelConfiguration();
1510                if (res != OK) {
1511                    SET_ERR_L(
1512                        "Can't cancel configuring output stream %d: %s (%d)",
1513                        outputStream->getId(), strerror(-res), res);
1514                    return res;
1515                }
1516            }
1517        }
1518
1519        // Return state to that at start of call, so that future configures
1520        // properly clean things up
1521        mStatus = STATUS_UNCONFIGURED;
1522        mNeedConfig = true;
1523
1524        ALOGV("%s: Camera %d: Stream configuration failed", __FUNCTION__, mId);
1525        return BAD_VALUE;
1526    } else if (res != OK) {
1527        // Some other kind of error from configure_streams - this is not
1528        // expected
1529        SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
1530                strerror(-res), res);
1531        return res;
1532    }
1533
1534    // Finish all stream configuration immediately.
1535    // TODO: Try to relax this later back to lazy completion, which should be
1536    // faster
1537
1538    if (mInputStream != NULL && mInputStream->isConfiguring()) {
1539        res = mInputStream->finishConfiguration(mHal3Device);
1540        if (res != OK) {
1541            SET_ERR_L("Can't finish configuring input stream %d: %s (%d)",
1542                    mInputStream->getId(), strerror(-res), res);
1543            return res;
1544        }
1545    }
1546
1547    for (size_t i = 0; i < mOutputStreams.size(); i++) {
1548        sp<Camera3OutputStreamInterface> outputStream =
1549            mOutputStreams.editValueAt(i);
1550        if (outputStream->isConfiguring()) {
1551            res = outputStream->finishConfiguration(mHal3Device);
1552            if (res != OK) {
1553                SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
1554                        outputStream->getId(), strerror(-res), res);
1555                return res;
1556            }
1557        }
1558    }
1559
1560    // Request thread needs to know to avoid using repeat-last-settings protocol
1561    // across configure_streams() calls
1562    mRequestThread->configurationComplete();
1563
1564    // Update device state
1565
1566    mNeedConfig = false;
1567
1568    if (mDummyStreamId == NO_STREAM) {
1569        mStatus = STATUS_CONFIGURED;
1570    } else {
1571        mStatus = STATUS_UNCONFIGURED;
1572    }
1573
1574    ALOGV("%s: Camera %d: Stream configuration complete", __FUNCTION__, mId);
1575
1576    // tear down the deleted streams after configure streams.
1577    mDeletedStreams.clear();
1578
1579    return OK;
1580}
1581
1582status_t Camera3Device::addDummyStreamLocked() {
1583    ATRACE_CALL();
1584    status_t res;
1585
1586    if (mDummyStreamId != NO_STREAM) {
1587        // Should never be adding a second dummy stream when one is already
1588        // active
1589        SET_ERR_L("%s: Camera %d: A dummy stream already exists!",
1590                __FUNCTION__, mId);
1591        return INVALID_OPERATION;
1592    }
1593
1594    ALOGV("%s: Camera %d: Adding a dummy stream", __FUNCTION__, mId);
1595
1596    sp<Camera3OutputStreamInterface> dummyStream =
1597            new Camera3DummyStream(mNextStreamId);
1598
1599    res = mOutputStreams.add(mNextStreamId, dummyStream);
1600    if (res < 0) {
1601        SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
1602        return res;
1603    }
1604
1605    mDummyStreamId = mNextStreamId;
1606    mNextStreamId++;
1607
1608    return OK;
1609}
1610
1611status_t Camera3Device::tryRemoveDummyStreamLocked() {
1612    ATRACE_CALL();
1613    status_t res;
1614
1615    if (mDummyStreamId == NO_STREAM) return OK;
1616    if (mOutputStreams.size() == 1) return OK;
1617
1618    ALOGV("%s: Camera %d: Removing the dummy stream", __FUNCTION__, mId);
1619
1620    // Ok, have a dummy stream and there's at least one other output stream,
1621    // so remove the dummy
1622
1623    sp<Camera3StreamInterface> deletedStream;
1624    ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
1625    if (outputStreamIdx == NAME_NOT_FOUND) {
1626        SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
1627        return INVALID_OPERATION;
1628    }
1629
1630    deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
1631    mOutputStreams.removeItemsAt(outputStreamIdx);
1632
1633    // Free up the stream endpoint so that it can be used by some other stream
1634    res = deletedStream->disconnect();
1635    if (res != OK) {
1636        SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
1637        // fall through since we want to still list the stream as deleted.
1638    }
1639    mDeletedStreams.add(deletedStream);
1640    mDummyStreamId = NO_STREAM;
1641
1642    return res;
1643}
1644
1645void Camera3Device::setErrorState(const char *fmt, ...) {
1646    Mutex::Autolock l(mLock);
1647    va_list args;
1648    va_start(args, fmt);
1649
1650    setErrorStateLockedV(fmt, args);
1651
1652    va_end(args);
1653}
1654
1655void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
1656    Mutex::Autolock l(mLock);
1657    setErrorStateLockedV(fmt, args);
1658}
1659
1660void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
1661    va_list args;
1662    va_start(args, fmt);
1663
1664    setErrorStateLockedV(fmt, args);
1665
1666    va_end(args);
1667}
1668
1669void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
1670    // Print out all error messages to log
1671    String8 errorCause = String8::formatV(fmt, args);
1672    ALOGE("Camera %d: %s", mId, errorCause.string());
1673
1674    // But only do error state transition steps for the first error
1675    if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
1676
1677    mErrorCause = errorCause;
1678
1679    mRequestThread->setPaused(true);
1680    mStatus = STATUS_ERROR;
1681
1682    // Notify upstream about a device error
1683    if (mListener != NULL) {
1684        mListener->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
1685                CaptureResultExtras());
1686    }
1687
1688    // Save stack trace. View by dumping it later.
1689    CameraTraces::saveTrace();
1690    // TODO: consider adding errorCause and client pid/procname
1691}
1692
1693/**
1694 * In-flight request management
1695 */
1696
1697status_t Camera3Device::registerInFlight(uint32_t frameNumber,
1698        int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput) {
1699    ATRACE_CALL();
1700    Mutex::Autolock l(mInFlightLock);
1701
1702    ssize_t res;
1703    res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput));
1704    if (res < 0) return res;
1705
1706    return OK;
1707}
1708
1709/**
1710 * Check if all 3A fields are ready, and send off a partial 3A-only result
1711 * to the output frame queue
1712 */
1713bool Camera3Device::processPartial3AResult(
1714        uint32_t frameNumber,
1715        const CameraMetadata& partial, const CaptureResultExtras& resultExtras) {
1716
1717    // Check if all 3A states are present
1718    // The full list of fields is
1719    //   android.control.afMode
1720    //   android.control.awbMode
1721    //   android.control.aeState
1722    //   android.control.awbState
1723    //   android.control.afState
1724    //   android.control.afTriggerID
1725    //   android.control.aePrecaptureID
1726    // TODO: Add android.control.aeMode
1727
1728    bool gotAllStates = true;
1729
1730    uint8_t afMode;
1731    uint8_t awbMode;
1732    uint8_t aeState;
1733    uint8_t afState;
1734    uint8_t awbState;
1735
1736    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_MODE,
1737        &afMode, frameNumber);
1738
1739    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_MODE,
1740        &awbMode, frameNumber);
1741
1742    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AE_STATE,
1743        &aeState, frameNumber);
1744
1745    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_STATE,
1746        &afState, frameNumber);
1747
1748    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_STATE,
1749        &awbState, frameNumber);
1750
1751    if (!gotAllStates) return false;
1752
1753    ALOGVV("%s: Camera %d: Frame %d, Request ID %d: AF mode %d, AWB mode %d, "
1754        "AF state %d, AE state %d, AWB state %d, "
1755        "AF trigger %d, AE precapture trigger %d",
1756        __FUNCTION__, mId, frameNumber, resultExtras.requestId,
1757        afMode, awbMode,
1758        afState, aeState, awbState,
1759        resultExtras.afTriggerId, resultExtras.precaptureTriggerId);
1760
1761    // Got all states, so construct a minimal result to send
1762    // In addition to the above fields, this means adding in
1763    //   android.request.frameCount
1764    //   android.request.requestId
1765    //   android.quirks.partialResult (for HAL version below HAL3.2)
1766
1767    const size_t kMinimal3AResultEntries = 10;
1768
1769    Mutex::Autolock l(mOutputLock);
1770
1771    CaptureResult captureResult;
1772    captureResult.mResultExtras = resultExtras;
1773    captureResult.mMetadata = CameraMetadata(kMinimal3AResultEntries, /*dataCapacity*/ 0);
1774    // TODO: change this to sp<CaptureResult>. This will need other changes, including,
1775    // but not limited to CameraDeviceBase::getNextResult
1776    CaptureResult& min3AResult =
1777            *mResultQueue.insert(mResultQueue.end(), captureResult);
1778
1779    if (!insert3AResult(min3AResult.mMetadata, ANDROID_REQUEST_FRAME_COUNT,
1780            // TODO: This is problematic casting. Need to fix CameraMetadata.
1781            reinterpret_cast<int32_t*>(&frameNumber), frameNumber)) {
1782        return false;
1783    }
1784
1785    int32_t requestId = resultExtras.requestId;
1786    if (!insert3AResult(min3AResult.mMetadata, ANDROID_REQUEST_ID,
1787            &requestId, frameNumber)) {
1788        return false;
1789    }
1790
1791    if (mDeviceVersion < CAMERA_DEVICE_API_VERSION_3_2) {
1792        static const uint8_t partialResult = ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL;
1793        if (!insert3AResult(min3AResult.mMetadata, ANDROID_QUIRKS_PARTIAL_RESULT,
1794                &partialResult, frameNumber)) {
1795            return false;
1796        }
1797    }
1798
1799    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_MODE,
1800            &afMode, frameNumber)) {
1801        return false;
1802    }
1803
1804    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AWB_MODE,
1805            &awbMode, frameNumber)) {
1806        return false;
1807    }
1808
1809    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AE_STATE,
1810            &aeState, frameNumber)) {
1811        return false;
1812    }
1813
1814    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_STATE,
1815            &afState, frameNumber)) {
1816        return false;
1817    }
1818
1819    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AWB_STATE,
1820            &awbState, frameNumber)) {
1821        return false;
1822    }
1823
1824    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AF_TRIGGER_ID,
1825            &resultExtras.afTriggerId, frameNumber)) {
1826        return false;
1827    }
1828
1829    if (!insert3AResult(min3AResult.mMetadata, ANDROID_CONTROL_AE_PRECAPTURE_ID,
1830            &resultExtras.precaptureTriggerId, frameNumber)) {
1831        return false;
1832    }
1833
1834    // We only send the aggregated partial when all 3A related metadata are available
1835    // For both API1 and API2.
1836    // TODO: we probably should pass through all partials to API2 unconditionally.
1837    mResultSignal.signal();
1838
1839    return true;
1840}
1841
1842template<typename T>
1843bool Camera3Device::get3AResult(const CameraMetadata& result, int32_t tag,
1844        T* value, uint32_t frameNumber) {
1845    (void) frameNumber;
1846
1847    camera_metadata_ro_entry_t entry;
1848
1849    entry = result.find(tag);
1850    if (entry.count == 0) {
1851        ALOGVV("%s: Camera %d: Frame %d: No %s provided by HAL!", __FUNCTION__,
1852            mId, frameNumber, get_camera_metadata_tag_name(tag));
1853        return false;
1854    }
1855
1856    if (sizeof(T) == sizeof(uint8_t)) {
1857        *value = entry.data.u8[0];
1858    } else if (sizeof(T) == sizeof(int32_t)) {
1859        *value = entry.data.i32[0];
1860    } else {
1861        ALOGE("%s: Unexpected type", __FUNCTION__);
1862        return false;
1863    }
1864    return true;
1865}
1866
1867template<typename T>
1868bool Camera3Device::insert3AResult(CameraMetadata& result, int32_t tag,
1869        const T* value, uint32_t frameNumber) {
1870    if (result.update(tag, value, 1) != NO_ERROR) {
1871        mResultQueue.erase(--mResultQueue.end(), mResultQueue.end());
1872        SET_ERR("Frame %d: Failed to set %s in partial metadata",
1873                frameNumber, get_camera_metadata_tag_name(tag));
1874        return false;
1875    }
1876    return true;
1877}
1878
1879/**
1880 * Camera HAL device callback methods
1881 */
1882
1883void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
1884    ATRACE_CALL();
1885
1886    status_t res;
1887
1888    uint32_t frameNumber = result->frame_number;
1889    if (result->result == NULL && result->num_output_buffers == 0 &&
1890            result->input_buffer == NULL) {
1891        SET_ERR("No result data provided by HAL for frame %d",
1892                frameNumber);
1893        return;
1894    }
1895
1896    // For HAL3.2 or above, If HAL doesn't support partial, it must always set
1897    // partial_result to 1 when metadata is included in this result.
1898    if (!mUsePartialResult &&
1899            mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2 &&
1900            result->result != NULL &&
1901            result->partial_result != 1) {
1902        SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
1903                " if partial result is not supported",
1904                frameNumber, result->partial_result);
1905        return;
1906    }
1907
1908    bool isPartialResult = false;
1909    CameraMetadata collectedPartialResult;
1910    CaptureResultExtras resultExtras;
1911    bool hasInputBufferInRequest = false;
1912
1913    // Get capture timestamp and resultExtras from list of in-flight requests,
1914    // where it was added by the shutter notification for this frame.
1915    // Then update the in-flight status and remove the in-flight entry if
1916    // all result data has been received.
1917    nsecs_t timestamp = 0;
1918    {
1919        Mutex::Autolock l(mInFlightLock);
1920        ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
1921        if (idx == NAME_NOT_FOUND) {
1922            SET_ERR("Unknown frame number for capture result: %d",
1923                    frameNumber);
1924            return;
1925        }
1926        InFlightRequest &request = mInFlightMap.editValueAt(idx);
1927        ALOGVV("%s: got InFlightRequest requestId = %" PRId32 ", frameNumber = %" PRId64
1928                ", burstId = %" PRId32,
1929                __FUNCTION__, request.resultExtras.requestId, request.resultExtras.frameNumber,
1930                request.resultExtras.burstId);
1931        // Always update the partial count to the latest one. When framework aggregates adjacent
1932        // partial results into one, the latest partial count will be used.
1933        request.resultExtras.partialResultCount = result->partial_result;
1934
1935        // Check if this result carries only partial metadata
1936        if (mUsePartialResult && result->result != NULL) {
1937            if (mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
1938                if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
1939                    SET_ERR("Result is malformed for frame %d: partial_result %u must be  in"
1940                            " the range of [1, %d] when metadata is included in the result",
1941                            frameNumber, result->partial_result, mNumPartialResults);
1942                    return;
1943                }
1944                isPartialResult = (result->partial_result < mNumPartialResults);
1945                if (isPartialResult) {
1946                    request.partialResult.collectedResult.append(result->result);
1947                }
1948            } else {
1949                camera_metadata_ro_entry_t partialResultEntry;
1950                res = find_camera_metadata_ro_entry(result->result,
1951                        ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
1952                if (res != NAME_NOT_FOUND &&
1953                        partialResultEntry.count > 0 &&
1954                        partialResultEntry.data.u8[0] ==
1955                        ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
1956                    // A partial result. Flag this as such, and collect this
1957                    // set of metadata into the in-flight entry.
1958                    isPartialResult = true;
1959                    request.partialResult.collectedResult.append(
1960                        result->result);
1961                    request.partialResult.collectedResult.erase(
1962                        ANDROID_QUIRKS_PARTIAL_RESULT);
1963                }
1964            }
1965
1966            if (isPartialResult) {
1967                // Fire off a 3A-only result if possible
1968                if (!request.partialResult.haveSent3A) {
1969                    request.partialResult.haveSent3A =
1970                            processPartial3AResult(frameNumber,
1971                                    request.partialResult.collectedResult,
1972                                    request.resultExtras);
1973                }
1974            }
1975        }
1976
1977        timestamp = request.captureTimestamp;
1978        resultExtras = request.resultExtras;
1979        hasInputBufferInRequest = request.hasInputBuffer;
1980
1981        /**
1982         * One of the following must happen before it's legal to call process_capture_result,
1983         * unless partial metadata is being provided:
1984         * - CAMERA3_MSG_SHUTTER (expected during normal operation)
1985         * - CAMERA3_MSG_ERROR (expected during flush)
1986         */
1987        if (request.requestStatus == OK && timestamp == 0 && !isPartialResult) {
1988            SET_ERR("Called before shutter notify for frame %d",
1989                    frameNumber);
1990            return;
1991        }
1992
1993        // Did we get the (final) result metadata for this capture?
1994        if (result->result != NULL && !isPartialResult) {
1995            if (request.haveResultMetadata) {
1996                SET_ERR("Called multiple times with metadata for frame %d",
1997                        frameNumber);
1998                return;
1999            }
2000            if (mUsePartialResult &&
2001                    !request.partialResult.collectedResult.isEmpty()) {
2002                collectedPartialResult.acquire(
2003                    request.partialResult.collectedResult);
2004            }
2005            request.haveResultMetadata = true;
2006        }
2007
2008        uint32_t numBuffersReturned = result->num_output_buffers;
2009        if (result->input_buffer != NULL) {
2010            if (hasInputBufferInRequest) {
2011                numBuffersReturned += 1;
2012            } else {
2013                ALOGW("%s: Input buffer should be NULL if there is no input"
2014                        " buffer sent in the request",
2015                        __FUNCTION__);
2016            }
2017        }
2018        request.numBuffersLeft -= numBuffersReturned;
2019        if (request.numBuffersLeft < 0) {
2020            SET_ERR("Too many buffers returned for frame %d",
2021                    frameNumber);
2022            return;
2023        }
2024
2025        // Check if everything has arrived for this result (buffers and metadata), remove it from
2026        // InFlightMap if both arrived or HAL reports error for this request (i.e. during flush).
2027        if ((request.requestStatus != OK) ||
2028                (request.haveResultMetadata && request.numBuffersLeft == 0)) {
2029            ATRACE_ASYNC_END("frame capture", frameNumber);
2030            mInFlightMap.removeItemsAt(idx, 1);
2031        }
2032
2033        // Sanity check - if we have too many in-flight frames, something has
2034        // likely gone wrong
2035        if (mInFlightMap.size() > kInFlightWarnLimit) {
2036            CLOGE("In-flight list too large: %zu", mInFlightMap.size());
2037        }
2038
2039    }
2040
2041    // Process the result metadata, if provided
2042    bool gotResult = false;
2043    if (result->result != NULL && !isPartialResult) {
2044        Mutex::Autolock l(mOutputLock);
2045
2046        gotResult = true;
2047
2048        // TODO: need to track errors for tighter bounds on expected frame number
2049        if (frameNumber < mNextResultFrameNumber) {
2050            SET_ERR("Out-of-order capture result metadata submitted! "
2051                    "(got frame number %d, expecting %d)",
2052                    frameNumber, mNextResultFrameNumber);
2053            return;
2054        }
2055        mNextResultFrameNumber = frameNumber + 1;
2056
2057        CaptureResult captureResult;
2058        captureResult.mResultExtras = resultExtras;
2059        captureResult.mMetadata = result->result;
2060
2061        if (captureResult.mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2062                (int32_t*)&frameNumber, 1) != OK) {
2063            SET_ERR("Failed to set frame# in metadata (%d)",
2064                    frameNumber);
2065            gotResult = false;
2066        } else {
2067            ALOGVV("%s: Camera %d: Set frame# in metadata (%d)",
2068                    __FUNCTION__, mId, frameNumber);
2069        }
2070
2071        // Append any previous partials to form a complete result
2072        if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
2073            captureResult.mMetadata.append(collectedPartialResult);
2074        }
2075
2076        captureResult.mMetadata.sort();
2077
2078        // Check that there's a timestamp in the result metadata
2079
2080        camera_metadata_entry entry =
2081                captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
2082        if (entry.count == 0) {
2083            SET_ERR("No timestamp provided by HAL for frame %d!",
2084                    frameNumber);
2085            gotResult = false;
2086        } else if (timestamp != entry.data.i64[0]) {
2087            SET_ERR("Timestamp mismatch between shutter notify and result"
2088                    " metadata for frame %d (%" PRId64 " vs %" PRId64 " respectively)",
2089                    frameNumber, timestamp, entry.data.i64[0]);
2090            gotResult = false;
2091        }
2092
2093        if (gotResult) {
2094            // Valid result, insert into queue
2095            List<CaptureResult>::iterator queuedResult =
2096                    mResultQueue.insert(mResultQueue.end(), CaptureResult(captureResult));
2097            ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2098                   ", burstId = %" PRId32, __FUNCTION__,
2099                   queuedResult->mResultExtras.requestId,
2100                   queuedResult->mResultExtras.frameNumber,
2101                   queuedResult->mResultExtras.burstId);
2102        }
2103    } // scope for mOutputLock
2104
2105    // Return completed buffers to their streams with the timestamp
2106
2107    for (size_t i = 0; i < result->num_output_buffers; i++) {
2108        Camera3Stream *stream =
2109                Camera3Stream::cast(result->output_buffers[i].stream);
2110        res = stream->returnBuffer(result->output_buffers[i], timestamp);
2111        // Note: stream may be deallocated at this point, if this buffer was the
2112        // last reference to it.
2113        if (res != OK) {
2114            ALOGE("Can't return buffer %zu for frame %d to its stream: "
2115                    " %s (%d)", i, frameNumber, strerror(-res), res);
2116        }
2117    }
2118
2119    if (result->input_buffer != NULL) {
2120        if (hasInputBufferInRequest) {
2121            Camera3Stream *stream =
2122                Camera3Stream::cast(result->input_buffer->stream);
2123            res = stream->returnInputBuffer(*(result->input_buffer));
2124            // Note: stream may be deallocated at this point, if this buffer was the
2125            // last reference to it.
2126            if (res != OK) {
2127                ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2128                      "  its stream:%s (%d)",  __FUNCTION__,
2129                      frameNumber, strerror(-res), res);
2130            }
2131        } else {
2132            ALOGW("%s: Input buffer should be NULL if there is no input"
2133                    " buffer sent in the request, skipping input buffer return.",
2134                    __FUNCTION__);
2135        }
2136    }
2137
2138    // Finally, signal any waiters for new frames
2139
2140    if (gotResult) {
2141        mResultSignal.signal();
2142    }
2143
2144}
2145
2146void Camera3Device::notify(const camera3_notify_msg *msg) {
2147    ATRACE_CALL();
2148    NotificationListener *listener;
2149    {
2150        Mutex::Autolock l(mOutputLock);
2151        listener = mListener;
2152    }
2153
2154    if (msg == NULL) {
2155        SET_ERR("HAL sent NULL notify message!");
2156        return;
2157    }
2158
2159    switch (msg->type) {
2160        case CAMERA3_MSG_ERROR: {
2161            notifyError(msg->message.error, listener);
2162            break;
2163        }
2164        case CAMERA3_MSG_SHUTTER: {
2165            notifyShutter(msg->message.shutter, listener);
2166            break;
2167        }
2168        default:
2169            SET_ERR("Unknown notify message from HAL: %d",
2170                    msg->type);
2171    }
2172}
2173
2174void Camera3Device::notifyError(const camera3_error_msg_t &msg,
2175        NotificationListener *listener) {
2176
2177    // Map camera HAL error codes to ICameraDeviceCallback error codes
2178    // Index into this with the HAL error code
2179    static const ICameraDeviceCallbacks::CameraErrorCode
2180            halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
2181        // 0 = Unused error code
2182        ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
2183        // 1 = CAMERA3_MSG_ERROR_DEVICE
2184        ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
2185        // 2 = CAMERA3_MSG_ERROR_REQUEST
2186        ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
2187        // 3 = CAMERA3_MSG_ERROR_RESULT
2188        ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
2189        // 4 = CAMERA3_MSG_ERROR_BUFFER
2190        ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
2191    };
2192
2193    ICameraDeviceCallbacks::CameraErrorCode errorCode =
2194            ((msg.error_code >= 0) &&
2195                    (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
2196            halErrorMap[msg.error_code] :
2197            ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
2198
2199    int streamId = 0;
2200    if (msg.error_stream != NULL) {
2201        Camera3Stream *stream =
2202                Camera3Stream::cast(msg.error_stream);
2203        streamId = stream->getId();
2204    }
2205    ALOGV("Camera %d: %s: HAL error, frame %d, stream %d: %d",
2206            mId, __FUNCTION__, msg.frame_number,
2207            streamId, msg.error_code);
2208
2209    CaptureResultExtras resultExtras;
2210    switch (errorCode) {
2211        case ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
2212            // SET_ERR calls notifyError
2213            SET_ERR("Camera HAL reported serious device error");
2214            break;
2215        case ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
2216        case ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
2217        case ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
2218            {
2219                Mutex::Autolock l(mInFlightLock);
2220                ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
2221                if (idx >= 0) {
2222                    InFlightRequest &r = mInFlightMap.editValueAt(idx);
2223                    r.requestStatus = msg.error_code;
2224                    resultExtras = r.resultExtras;
2225                } else {
2226                    resultExtras.frameNumber = msg.frame_number;
2227                    ALOGE("Camera %d: %s: cannot find in-flight request on "
2228                            "frame %" PRId64 " error", mId, __FUNCTION__,
2229                            resultExtras.frameNumber);
2230                }
2231            }
2232            if (listener != NULL) {
2233                listener->notifyError(errorCode, resultExtras);
2234            } else {
2235                ALOGE("Camera %d: %s: no listener available", mId, __FUNCTION__);
2236            }
2237            break;
2238        default:
2239            // SET_ERR calls notifyError
2240            SET_ERR("Unknown error message from HAL: %d", msg.error_code);
2241            break;
2242    }
2243}
2244
2245void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
2246        NotificationListener *listener) {
2247    ssize_t idx;
2248    // Verify ordering of shutter notifications
2249    {
2250        Mutex::Autolock l(mOutputLock);
2251        // TODO: need to track errors for tighter bounds on expected frame number.
2252        if (msg.frame_number < mNextShutterFrameNumber) {
2253            SET_ERR("Shutter notification out-of-order. Expected "
2254                    "notification for frame %d, got frame %d",
2255                    mNextShutterFrameNumber, msg.frame_number);
2256            return;
2257        }
2258        mNextShutterFrameNumber = msg.frame_number + 1;
2259    }
2260
2261    CaptureResultExtras resultExtras;
2262
2263    // Set timestamp for the request in the in-flight tracking
2264    // and get the request ID to send upstream
2265    {
2266        Mutex::Autolock l(mInFlightLock);
2267        idx = mInFlightMap.indexOfKey(msg.frame_number);
2268        if (idx >= 0) {
2269            InFlightRequest &r = mInFlightMap.editValueAt(idx);
2270            r.captureTimestamp = msg.timestamp;
2271            resultExtras = r.resultExtras;
2272        }
2273    }
2274    if (idx < 0) {
2275        SET_ERR("Shutter notification for non-existent frame number %d",
2276                msg.frame_number);
2277        return;
2278    }
2279    ALOGVV("Camera %d: %s: Shutter fired for frame %d (id %d) at %" PRId64,
2280            mId, __FUNCTION__,
2281            msg.frame_number, resultExtras.requestId, msg.timestamp);
2282    // Call listener, if any
2283    if (listener != NULL) {
2284        listener->notifyShutter(resultExtras, msg.timestamp);
2285    }
2286}
2287
2288
2289CameraMetadata Camera3Device::getLatestRequestLocked() {
2290    ALOGV("%s", __FUNCTION__);
2291
2292    CameraMetadata retVal;
2293
2294    if (mRequestThread != NULL) {
2295        retVal = mRequestThread->getLatestRequest();
2296    }
2297
2298    return retVal;
2299}
2300
2301
2302/**
2303 * RequestThread inner class methods
2304 */
2305
2306Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
2307        sp<StatusTracker> statusTracker,
2308        camera3_device_t *hal3Device) :
2309        Thread(false),
2310        mParent(parent),
2311        mStatusTracker(statusTracker),
2312        mHal3Device(hal3Device),
2313        mId(getId(parent)),
2314        mReconfigured(false),
2315        mDoPause(false),
2316        mPaused(true),
2317        mFrameNumber(0),
2318        mLatestRequestId(NAME_NOT_FOUND),
2319        mCurrentAfTriggerId(0),
2320        mCurrentPreCaptureTriggerId(0),
2321        mRepeatingLastFrameNumber(NO_IN_FLIGHT_REPEATING_FRAMES) {
2322    mStatusId = statusTracker->addComponent();
2323}
2324
2325void Camera3Device::RequestThread::setNotifyCallback(
2326        NotificationListener *listener) {
2327    Mutex::Autolock l(mRequestLock);
2328    mListener = listener;
2329}
2330
2331void Camera3Device::RequestThread::configurationComplete() {
2332    Mutex::Autolock l(mRequestLock);
2333    mReconfigured = true;
2334}
2335
2336status_t Camera3Device::RequestThread::queueRequestList(
2337        List<sp<CaptureRequest> > &requests,
2338        /*out*/
2339        int64_t *lastFrameNumber) {
2340    Mutex::Autolock l(mRequestLock);
2341    for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
2342            ++it) {
2343        mRequestQueue.push_back(*it);
2344    }
2345
2346    if (lastFrameNumber != NULL) {
2347        *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
2348        ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
2349              __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
2350              *lastFrameNumber);
2351    }
2352
2353    unpauseForNewRequests();
2354
2355    return OK;
2356}
2357
2358
2359status_t Camera3Device::RequestThread::queueTrigger(
2360        RequestTrigger trigger[],
2361        size_t count) {
2362
2363    Mutex::Autolock l(mTriggerMutex);
2364    status_t ret;
2365
2366    for (size_t i = 0; i < count; ++i) {
2367        ret = queueTriggerLocked(trigger[i]);
2368
2369        if (ret != OK) {
2370            return ret;
2371        }
2372    }
2373
2374    return OK;
2375}
2376
2377int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
2378    sp<Camera3Device> d = device.promote();
2379    if (d != NULL) return d->mId;
2380    return 0;
2381}
2382
2383status_t Camera3Device::RequestThread::queueTriggerLocked(
2384        RequestTrigger trigger) {
2385
2386    uint32_t tag = trigger.metadataTag;
2387    ssize_t index = mTriggerMap.indexOfKey(tag);
2388
2389    switch (trigger.getTagType()) {
2390        case TYPE_BYTE:
2391        // fall-through
2392        case TYPE_INT32:
2393            break;
2394        default:
2395            ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
2396                    trigger.getTagType());
2397            return INVALID_OPERATION;
2398    }
2399
2400    /**
2401     * Collect only the latest trigger, since we only have 1 field
2402     * in the request settings per trigger tag, and can't send more than 1
2403     * trigger per request.
2404     */
2405    if (index != NAME_NOT_FOUND) {
2406        mTriggerMap.editValueAt(index) = trigger;
2407    } else {
2408        mTriggerMap.add(tag, trigger);
2409    }
2410
2411    return OK;
2412}
2413
2414status_t Camera3Device::RequestThread::setRepeatingRequests(
2415        const RequestList &requests,
2416        /*out*/
2417        int64_t *lastFrameNumber) {
2418    Mutex::Autolock l(mRequestLock);
2419    if (lastFrameNumber != NULL) {
2420        *lastFrameNumber = mRepeatingLastFrameNumber;
2421    }
2422    mRepeatingRequests.clear();
2423    mRepeatingRequests.insert(mRepeatingRequests.begin(),
2424            requests.begin(), requests.end());
2425
2426    unpauseForNewRequests();
2427
2428    mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES;
2429    return OK;
2430}
2431
2432bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest> requestIn) {
2433    if (mRepeatingRequests.empty()) {
2434        return false;
2435    }
2436    int32_t requestId = requestIn->mResultExtras.requestId;
2437    const RequestList &repeatRequests = mRepeatingRequests;
2438    // All repeating requests are guaranteed to have same id so only check first quest
2439    const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
2440    return (firstRequest->mResultExtras.requestId == requestId);
2441}
2442
2443status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
2444    Mutex::Autolock l(mRequestLock);
2445    mRepeatingRequests.clear();
2446    if (lastFrameNumber != NULL) {
2447        *lastFrameNumber = mRepeatingLastFrameNumber;
2448    }
2449    mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES;
2450    return OK;
2451}
2452
2453status_t Camera3Device::RequestThread::clear(
2454        NotificationListener *listener,
2455        /*out*/int64_t *lastFrameNumber) {
2456    Mutex::Autolock l(mRequestLock);
2457    ALOGV("RequestThread::%s:", __FUNCTION__);
2458
2459    mRepeatingRequests.clear();
2460
2461    // Send errors for all requests pending in the request queue, including
2462    // pending repeating requests
2463    if (listener != NULL) {
2464        for (RequestList::iterator it = mRequestQueue.begin();
2465                 it != mRequestQueue.end(); ++it) {
2466            // Set the frame number this request would have had, if it
2467            // had been submitted; this frame number will not be reused.
2468            // The requestId and burstId fields were set when the request was
2469            // submitted originally (in convertMetadataListToRequestListLocked)
2470            (*it)->mResultExtras.frameNumber = mFrameNumber++;
2471            listener->notifyError(ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
2472                    (*it)->mResultExtras);
2473        }
2474    }
2475    mRequestQueue.clear();
2476    mTriggerMap.clear();
2477    if (lastFrameNumber != NULL) {
2478        *lastFrameNumber = mRepeatingLastFrameNumber;
2479    }
2480    mRepeatingLastFrameNumber = NO_IN_FLIGHT_REPEATING_FRAMES;
2481    return OK;
2482}
2483
2484void Camera3Device::RequestThread::setPaused(bool paused) {
2485    Mutex::Autolock l(mPauseLock);
2486    mDoPause = paused;
2487    mDoPauseSignal.signal();
2488}
2489
2490status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
2491        int32_t requestId, nsecs_t timeout) {
2492    Mutex::Autolock l(mLatestRequestMutex);
2493    status_t res;
2494    while (mLatestRequestId != requestId) {
2495        nsecs_t startTime = systemTime();
2496
2497        res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
2498        if (res != OK) return res;
2499
2500        timeout -= (systemTime() - startTime);
2501    }
2502
2503    return OK;
2504}
2505
2506void Camera3Device::RequestThread::requestExit() {
2507    // Call parent to set up shutdown
2508    Thread::requestExit();
2509    // The exit from any possible waits
2510    mDoPauseSignal.signal();
2511    mRequestSignal.signal();
2512}
2513
2514bool Camera3Device::RequestThread::threadLoop() {
2515
2516    status_t res;
2517
2518    // Handle paused state.
2519    if (waitIfPaused()) {
2520        return true;
2521    }
2522
2523    // Get work to do
2524
2525    sp<CaptureRequest> nextRequest = waitForNextRequest();
2526    if (nextRequest == NULL) {
2527        return true;
2528    }
2529
2530    // Create request to HAL
2531    camera3_capture_request_t request = camera3_capture_request_t();
2532    request.frame_number = nextRequest->mResultExtras.frameNumber;
2533    Vector<camera3_stream_buffer_t> outputBuffers;
2534
2535    // Get the request ID, if any
2536    int requestId;
2537    camera_metadata_entry_t requestIdEntry =
2538            nextRequest->mSettings.find(ANDROID_REQUEST_ID);
2539    if (requestIdEntry.count > 0) {
2540        requestId = requestIdEntry.data.i32[0];
2541    } else {
2542        ALOGW("%s: Did not have android.request.id set in the request",
2543                __FUNCTION__);
2544        requestId = NAME_NOT_FOUND;
2545    }
2546
2547    // Insert any queued triggers (before metadata is locked)
2548    int32_t triggerCount;
2549    res = insertTriggers(nextRequest);
2550    if (res < 0) {
2551        SET_ERR("RequestThread: Unable to insert triggers "
2552                "(capture request %d, HAL device: %s (%d)",
2553                request.frame_number, strerror(-res), res);
2554        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2555        return false;
2556    }
2557    triggerCount = res;
2558
2559    bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
2560
2561    // If the request is the same as last, or we had triggers last time
2562    if (mPrevRequest != nextRequest || triggersMixedIn) {
2563        /**
2564         * HAL workaround:
2565         * Insert a dummy trigger ID if a trigger is set but no trigger ID is
2566         */
2567        res = addDummyTriggerIds(nextRequest);
2568        if (res != OK) {
2569            SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
2570                    "(capture request %d, HAL device: %s (%d)",
2571                    request.frame_number, strerror(-res), res);
2572            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2573            return false;
2574        }
2575
2576        /**
2577         * The request should be presorted so accesses in HAL
2578         *   are O(logn). Sidenote, sorting a sorted metadata is nop.
2579         */
2580        nextRequest->mSettings.sort();
2581        request.settings = nextRequest->mSettings.getAndLock();
2582        mPrevRequest = nextRequest;
2583        ALOGVV("%s: Request settings are NEW", __FUNCTION__);
2584
2585        IF_ALOGV() {
2586            camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
2587            find_camera_metadata_ro_entry(
2588                    request.settings,
2589                    ANDROID_CONTROL_AF_TRIGGER,
2590                    &e
2591            );
2592            if (e.count > 0) {
2593                ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
2594                      __FUNCTION__,
2595                      request.frame_number,
2596                      e.data.u8[0]);
2597            }
2598        }
2599    } else {
2600        // leave request.settings NULL to indicate 'reuse latest given'
2601        ALOGVV("%s: Request settings are REUSED",
2602               __FUNCTION__);
2603    }
2604
2605    camera3_stream_buffer_t inputBuffer;
2606    uint32_t totalNumBuffers = 0;
2607
2608    // Fill in buffers
2609
2610    if (nextRequest->mInputStream != NULL) {
2611        request.input_buffer = &inputBuffer;
2612        res = nextRequest->mInputStream->getInputBuffer(&inputBuffer);
2613        if (res != OK) {
2614            // Can't get input buffer from gralloc queue - this could be due to
2615            // disconnected queue or other producer misbehavior, so not a fatal
2616            // error
2617            ALOGE("RequestThread: Can't get input buffer, skipping request:"
2618                    " %s (%d)", strerror(-res), res);
2619            Mutex::Autolock l(mRequestLock);
2620            if (mListener != NULL) {
2621                mListener->notifyError(
2622                        ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
2623                        nextRequest->mResultExtras);
2624            }
2625            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2626            return true;
2627        }
2628        totalNumBuffers += 1;
2629    } else {
2630        request.input_buffer = NULL;
2631    }
2632
2633    outputBuffers.insertAt(camera3_stream_buffer_t(), 0,
2634            nextRequest->mOutputStreams.size());
2635    request.output_buffers = outputBuffers.array();
2636    for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) {
2637        res = nextRequest->mOutputStreams.editItemAt(i)->
2638                getBuffer(&outputBuffers.editItemAt(i));
2639        if (res != OK) {
2640            // Can't get output buffer from gralloc queue - this could be due to
2641            // abandoned queue or other consumer misbehavior, so not a fatal
2642            // error
2643            ALOGE("RequestThread: Can't get output buffer, skipping request:"
2644                    " %s (%d)", strerror(-res), res);
2645            Mutex::Autolock l(mRequestLock);
2646            if (mListener != NULL) {
2647                mListener->notifyError(
2648                        ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
2649                        nextRequest->mResultExtras);
2650            }
2651            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2652            return true;
2653        }
2654        request.num_output_buffers++;
2655    }
2656    totalNumBuffers += request.num_output_buffers;
2657
2658    // Log request in the in-flight queue
2659    sp<Camera3Device> parent = mParent.promote();
2660    if (parent == NULL) {
2661        // Should not happen, and nowhere to send errors to, so just log it
2662        CLOGE("RequestThread: Parent is gone");
2663        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2664        return false;
2665    }
2666
2667    res = parent->registerInFlight(request.frame_number,
2668            totalNumBuffers, nextRequest->mResultExtras,
2669            /*hasInput*/request.input_buffer != NULL);
2670    ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
2671           ", burstId = %" PRId32 ".",
2672            __FUNCTION__,
2673            nextRequest->mResultExtras.requestId, nextRequest->mResultExtras.frameNumber,
2674            nextRequest->mResultExtras.burstId);
2675    if (res != OK) {
2676        SET_ERR("RequestThread: Unable to register new in-flight request:"
2677                " %s (%d)", strerror(-res), res);
2678        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2679        return false;
2680    }
2681
2682    // Inform waitUntilRequestProcessed thread of a new request ID
2683    {
2684        Mutex::Autolock al(mLatestRequestMutex);
2685
2686        mLatestRequestId = requestId;
2687        mLatestRequestSignal.signal();
2688    }
2689
2690    // Submit request and block until ready for next one
2691    ATRACE_ASYNC_BEGIN("frame capture", request.frame_number);
2692    ATRACE_BEGIN("camera3->process_capture_request");
2693    res = mHal3Device->ops->process_capture_request(mHal3Device, &request);
2694    ATRACE_END();
2695
2696    if (res != OK) {
2697        // Should only get a failure here for malformed requests or device-level
2698        // errors, so consider all errors fatal.  Bad metadata failures should
2699        // come through notify.
2700        SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
2701                " device: %s (%d)", request.frame_number, strerror(-res), res);
2702        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2703        return false;
2704    }
2705
2706    // Update the latest request sent to HAL
2707    if (request.settings != NULL) { // Don't update them if they were unchanged
2708        Mutex::Autolock al(mLatestRequestMutex);
2709
2710        camera_metadata_t* cloned = clone_camera_metadata(request.settings);
2711        mLatestRequest.acquire(cloned);
2712    }
2713
2714    if (request.settings != NULL) {
2715        nextRequest->mSettings.unlock(request.settings);
2716    }
2717
2718    // Remove any previously queued triggers (after unlock)
2719    res = removeTriggers(mPrevRequest);
2720    if (res != OK) {
2721        SET_ERR("RequestThread: Unable to remove triggers "
2722              "(capture request %d, HAL device: %s (%d)",
2723              request.frame_number, strerror(-res), res);
2724        return false;
2725    }
2726    mPrevTriggers = triggerCount;
2727
2728    return true;
2729}
2730
2731CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
2732    Mutex::Autolock al(mLatestRequestMutex);
2733
2734    ALOGV("RequestThread::%s", __FUNCTION__);
2735
2736    return mLatestRequest;
2737}
2738
2739
2740void Camera3Device::RequestThread::cleanUpFailedRequest(
2741        camera3_capture_request_t &request,
2742        sp<CaptureRequest> &nextRequest,
2743        Vector<camera3_stream_buffer_t> &outputBuffers) {
2744
2745    if (request.settings != NULL) {
2746        nextRequest->mSettings.unlock(request.settings);
2747    }
2748    if (request.input_buffer != NULL) {
2749        request.input_buffer->status = CAMERA3_BUFFER_STATUS_ERROR;
2750        nextRequest->mInputStream->returnInputBuffer(*(request.input_buffer));
2751    }
2752    for (size_t i = 0; i < request.num_output_buffers; i++) {
2753        outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
2754        nextRequest->mOutputStreams.editItemAt(i)->returnBuffer(
2755            outputBuffers[i], 0);
2756    }
2757}
2758
2759sp<Camera3Device::CaptureRequest>
2760        Camera3Device::RequestThread::waitForNextRequest() {
2761    status_t res;
2762    sp<CaptureRequest> nextRequest;
2763
2764    // Optimized a bit for the simple steady-state case (single repeating
2765    // request), to avoid putting that request in the queue temporarily.
2766    Mutex::Autolock l(mRequestLock);
2767
2768    while (mRequestQueue.empty()) {
2769        if (!mRepeatingRequests.empty()) {
2770            // Always atomically enqueue all requests in a repeating request
2771            // list. Guarantees a complete in-sequence set of captures to
2772            // application.
2773            const RequestList &requests = mRepeatingRequests;
2774            RequestList::const_iterator firstRequest =
2775                    requests.begin();
2776            nextRequest = *firstRequest;
2777            mRequestQueue.insert(mRequestQueue.end(),
2778                    ++firstRequest,
2779                    requests.end());
2780            // No need to wait any longer
2781
2782            mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
2783
2784            break;
2785        }
2786
2787        res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
2788
2789        if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
2790                exitPending()) {
2791            Mutex::Autolock pl(mPauseLock);
2792            if (mPaused == false) {
2793                ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
2794                mPaused = true;
2795                // Let the tracker know
2796                sp<StatusTracker> statusTracker = mStatusTracker.promote();
2797                if (statusTracker != 0) {
2798                    statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
2799                }
2800            }
2801            // Stop waiting for now and let thread management happen
2802            return NULL;
2803        }
2804    }
2805
2806    if (nextRequest == NULL) {
2807        // Don't have a repeating request already in hand, so queue
2808        // must have an entry now.
2809        RequestList::iterator firstRequest =
2810                mRequestQueue.begin();
2811        nextRequest = *firstRequest;
2812        mRequestQueue.erase(firstRequest);
2813    }
2814
2815    // In case we've been unpaused by setPaused clearing mDoPause, need to
2816    // update internal pause state (capture/setRepeatingRequest unpause
2817    // directly).
2818    Mutex::Autolock pl(mPauseLock);
2819    if (mPaused) {
2820        ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
2821        sp<StatusTracker> statusTracker = mStatusTracker.promote();
2822        if (statusTracker != 0) {
2823            statusTracker->markComponentActive(mStatusId);
2824        }
2825    }
2826    mPaused = false;
2827
2828    // Check if we've reconfigured since last time, and reset the preview
2829    // request if so. Can't use 'NULL request == repeat' across configure calls.
2830    if (mReconfigured) {
2831        mPrevRequest.clear();
2832        mReconfigured = false;
2833    }
2834
2835    if (nextRequest != NULL) {
2836        nextRequest->mResultExtras.frameNumber = mFrameNumber++;
2837        nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
2838        nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
2839    }
2840    return nextRequest;
2841}
2842
2843bool Camera3Device::RequestThread::waitIfPaused() {
2844    status_t res;
2845    Mutex::Autolock l(mPauseLock);
2846    while (mDoPause) {
2847        if (mPaused == false) {
2848            mPaused = true;
2849            ALOGV("%s: RequestThread: Paused", __FUNCTION__);
2850            // Let the tracker know
2851            sp<StatusTracker> statusTracker = mStatusTracker.promote();
2852            if (statusTracker != 0) {
2853                statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
2854            }
2855        }
2856
2857        res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
2858        if (res == TIMED_OUT || exitPending()) {
2859            return true;
2860        }
2861    }
2862    // We don't set mPaused to false here, because waitForNextRequest needs
2863    // to further manage the paused state in case of starvation.
2864    return false;
2865}
2866
2867void Camera3Device::RequestThread::unpauseForNewRequests() {
2868    // With work to do, mark thread as unpaused.
2869    // If paused by request (setPaused), don't resume, to avoid
2870    // extra signaling/waiting overhead to waitUntilPaused
2871    mRequestSignal.signal();
2872    Mutex::Autolock p(mPauseLock);
2873    if (!mDoPause) {
2874        ALOGV("%s: RequestThread: Going active", __FUNCTION__);
2875        if (mPaused) {
2876            sp<StatusTracker> statusTracker = mStatusTracker.promote();
2877            if (statusTracker != 0) {
2878                statusTracker->markComponentActive(mStatusId);
2879            }
2880        }
2881        mPaused = false;
2882    }
2883}
2884
2885void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
2886    sp<Camera3Device> parent = mParent.promote();
2887    if (parent != NULL) {
2888        va_list args;
2889        va_start(args, fmt);
2890
2891        parent->setErrorStateV(fmt, args);
2892
2893        va_end(args);
2894    }
2895}
2896
2897status_t Camera3Device::RequestThread::insertTriggers(
2898        const sp<CaptureRequest> &request) {
2899
2900    Mutex::Autolock al(mTriggerMutex);
2901
2902    sp<Camera3Device> parent = mParent.promote();
2903    if (parent == NULL) {
2904        CLOGE("RequestThread: Parent is gone");
2905        return DEAD_OBJECT;
2906    }
2907
2908    CameraMetadata &metadata = request->mSettings;
2909    size_t count = mTriggerMap.size();
2910
2911    for (size_t i = 0; i < count; ++i) {
2912        RequestTrigger trigger = mTriggerMap.valueAt(i);
2913        uint32_t tag = trigger.metadataTag;
2914
2915        if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
2916            bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
2917            uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
2918            if (isAeTrigger) {
2919                request->mResultExtras.precaptureTriggerId = triggerId;
2920                mCurrentPreCaptureTriggerId = triggerId;
2921            } else {
2922                request->mResultExtras.afTriggerId = triggerId;
2923                mCurrentAfTriggerId = triggerId;
2924            }
2925            if (parent->mDeviceVersion >= CAMERA_DEVICE_API_VERSION_3_2) {
2926                continue; // Trigger ID tag is deprecated since device HAL 3.2
2927            }
2928        }
2929
2930        camera_metadata_entry entry = metadata.find(tag);
2931
2932        if (entry.count > 0) {
2933            /**
2934             * Already has an entry for this trigger in the request.
2935             * Rewrite it with our requested trigger value.
2936             */
2937            RequestTrigger oldTrigger = trigger;
2938
2939            oldTrigger.entryValue = entry.data.u8[0];
2940
2941            mTriggerReplacedMap.add(tag, oldTrigger);
2942        } else {
2943            /**
2944             * More typical, no trigger entry, so we just add it
2945             */
2946            mTriggerRemovedMap.add(tag, trigger);
2947        }
2948
2949        status_t res;
2950
2951        switch (trigger.getTagType()) {
2952            case TYPE_BYTE: {
2953                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
2954                res = metadata.update(tag,
2955                                      &entryValue,
2956                                      /*count*/1);
2957                break;
2958            }
2959            case TYPE_INT32:
2960                res = metadata.update(tag,
2961                                      &trigger.entryValue,
2962                                      /*count*/1);
2963                break;
2964            default:
2965                ALOGE("%s: Type not supported: 0x%x",
2966                      __FUNCTION__,
2967                      trigger.getTagType());
2968                return INVALID_OPERATION;
2969        }
2970
2971        if (res != OK) {
2972            ALOGE("%s: Failed to update request metadata with trigger tag %s"
2973                  ", value %d", __FUNCTION__, trigger.getTagName(),
2974                  trigger.entryValue);
2975            return res;
2976        }
2977
2978        ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
2979              trigger.getTagName(),
2980              trigger.entryValue);
2981    }
2982
2983    mTriggerMap.clear();
2984
2985    return count;
2986}
2987
2988status_t Camera3Device::RequestThread::removeTriggers(
2989        const sp<CaptureRequest> &request) {
2990    Mutex::Autolock al(mTriggerMutex);
2991
2992    CameraMetadata &metadata = request->mSettings;
2993
2994    /**
2995     * Replace all old entries with their old values.
2996     */
2997    for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
2998        RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
2999
3000        status_t res;
3001
3002        uint32_t tag = trigger.metadataTag;
3003        switch (trigger.getTagType()) {
3004            case TYPE_BYTE: {
3005                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
3006                res = metadata.update(tag,
3007                                      &entryValue,
3008                                      /*count*/1);
3009                break;
3010            }
3011            case TYPE_INT32:
3012                res = metadata.update(tag,
3013                                      &trigger.entryValue,
3014                                      /*count*/1);
3015                break;
3016            default:
3017                ALOGE("%s: Type not supported: 0x%x",
3018                      __FUNCTION__,
3019                      trigger.getTagType());
3020                return INVALID_OPERATION;
3021        }
3022
3023        if (res != OK) {
3024            ALOGE("%s: Failed to restore request metadata with trigger tag %s"
3025                  ", trigger value %d", __FUNCTION__,
3026                  trigger.getTagName(), trigger.entryValue);
3027            return res;
3028        }
3029    }
3030    mTriggerReplacedMap.clear();
3031
3032    /**
3033     * Remove all new entries.
3034     */
3035    for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
3036        RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
3037        status_t res = metadata.erase(trigger.metadataTag);
3038
3039        if (res != OK) {
3040            ALOGE("%s: Failed to erase metadata with trigger tag %s"
3041                  ", trigger value %d", __FUNCTION__,
3042                  trigger.getTagName(), trigger.entryValue);
3043            return res;
3044        }
3045    }
3046    mTriggerRemovedMap.clear();
3047
3048    return OK;
3049}
3050
3051status_t Camera3Device::RequestThread::addDummyTriggerIds(
3052        const sp<CaptureRequest> &request) {
3053    // Trigger ID 0 has special meaning in the HAL2 spec, so avoid it here
3054    static const int32_t dummyTriggerId = 1;
3055    status_t res;
3056
3057    CameraMetadata &metadata = request->mSettings;
3058
3059    // If AF trigger is active, insert a dummy AF trigger ID if none already
3060    // exists
3061    camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
3062    camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
3063    if (afTrigger.count > 0 &&
3064            afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
3065            afId.count == 0) {
3066        res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
3067        if (res != OK) return res;
3068    }
3069
3070    // If AE precapture trigger is active, insert a dummy precapture trigger ID
3071    // if none already exists
3072    camera_metadata_entry pcTrigger =
3073            metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
3074    camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
3075    if (pcTrigger.count > 0 &&
3076            pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
3077            pcId.count == 0) {
3078        res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
3079                &dummyTriggerId, 1);
3080        if (res != OK) return res;
3081    }
3082
3083    return OK;
3084}
3085
3086
3087/**
3088 * Static callback forwarding methods from HAL to instance
3089 */
3090
3091void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
3092        const camera3_capture_result *result) {
3093    Camera3Device *d =
3094            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
3095    d->processCaptureResult(result);
3096}
3097
3098void Camera3Device::sNotify(const camera3_callback_ops *cb,
3099        const camera3_notify_msg *msg) {
3100    Camera3Device *d =
3101            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
3102    d->notify(msg);
3103}
3104
3105}; // namespace android
3106