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