Camera3Device.cpp revision 213ce79e943a3b51d7859a184d8211c859c960a0
15821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/*
25821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * Copyright (C) 2013 The Android Open Source Project
35821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) *
45821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * Licensed under the Apache License, Version 2.0 (the "License");
58bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles) * you may not use this file except in compliance with the License.
68bcbed890bc3ce4d7a057a8f32cab53fa534672eTorne (Richard Coles) * You may obtain a copy of the License at
75821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) *
85821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) *      http://www.apache.org/licenses/LICENSE-2.0
95821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) *
105821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * Unless required by applicable law or agreed to in writing, software
115821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * distributed under the License is distributed on an "AS IS" BASIS,
125821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
135821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * See the License for the specific language governing permissions and
145821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * limitations under the License.
155821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) */
165821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
175821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define LOG_TAG "Camera3-Device"
185821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ATRACE_TAG ATRACE_TAG_CAMERA
195821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//#define LOG_NDEBUG 0
205821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)//#define LOG_NNDEBUG 0  // Per-frame verbose logging
215821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
225821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#ifdef LOG_NNDEBUG
235821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ALOGVV(...) ALOGV(__VA_ARGS__)
245821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#else
255821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define ALOGVV(...) ((void)0)
265821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#endif
275821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
285821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Convenience macro for transient errors
295821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define CLOGE(fmt, ...) ALOGE("Camera %d: %s: " fmt, mId, __FUNCTION__, \
305821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)            ##__VA_ARGS__)
315821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
325821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)// Convenience macros for transitioning to the error state
335821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define SET_ERR(fmt, ...) setErrorState(   \
345821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    "%s: " fmt, __FUNCTION__,              \
355821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ##__VA_ARGS__)
365821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
375821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    "%s: " fmt, __FUNCTION__,                    \
385821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ##__VA_ARGS__)
395821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
405821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <utils/Log.h>
415821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <utils/Trace.h>
425821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include <utils/Timers.h>
435821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
445821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "utils/CameraTraces.h"
455821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "device3/Camera3Device.h"
465821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "device3/Camera3OutputStream.h"
475821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "device3/Camera3InputStream.h"
485821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)#include "device3/Camera3ZslStream.h"
495821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
505821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)using namespace android::camera3;
515821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
525821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)namespace android {
535821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
545821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)Camera3Device::Camera3Device(int id):
555821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mId(id),
565821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mHal3Device(NULL),
575821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mStatus(STATUS_UNINITIALIZED),
585821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mUsePartialResultQuirk(false),
595821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mNextResultFrameNumber(0),
605821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mNextShutterFrameNumber(0),
615821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        mListener(NULL)
625821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){
635821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ATRACE_CALL();
645821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    camera3_callback_ops::notify = &sNotify;
655821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
665821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ALOGV("%s: Created device for camera %d", __FUNCTION__, id);
675821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
685821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
695821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)Camera3Device::~Camera3Device()
705821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){
715821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ATRACE_CALL();
725821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ALOGV("%s: Tearing down for camera id %d", __FUNCTION__, mId);
735821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    disconnect();
745821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
755821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
765821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)int Camera3Device::getId() const {
775821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    return mId;
785821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)}
795821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
805821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)/**
815821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) * CameraDeviceBase interface
825821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles) */
835821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
845821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)status_t Camera3Device::initialize(camera_module_t *module)
855821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles){
865821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ATRACE_CALL();
875821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Mutex::Autolock il(mInterfaceLock);
885821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    Mutex::Autolock l(mLock);
895821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
905821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    ALOGV("%s: Initializing device for camera %d", __FUNCTION__, mId);
915821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    if (mStatus != STATUS_UNINITIALIZED) {
925821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        CLOGE("Already initialized!");
935821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)        return INVALID_OPERATION;
945821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    }
955821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
965821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    /** Open HAL device */
975821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
985821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    status_t res;
995821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)    String8 deviceName = String8::format("%d", mId);
1005821806d5e7f356e8fa4b058a389a808ea183019Torne (Richard Coles)
101    camera3_device_t *device;
102
103    ATRACE_BEGIN("camera3->open");
104    res = module->common.methods->open(&module->common, deviceName.string(),
105            reinterpret_cast<hw_device_t**>(&device));
106    ATRACE_END();
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            ATRACE_BEGIN("camera3->close");
275            mHal3Device->common.close(&mHal3Device->common);
276            ATRACE_END();
277            mHal3Device = NULL;
278        }
279
280        mStatus = STATUS_UNINITIALIZED;
281    }
282
283    ALOGV("%s: X", __FUNCTION__);
284    return res;
285}
286
287// For dumping/debugging only -
288// try to acquire a lock a few times, eventually give up to proceed with
289// debug/dump operations
290bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
291    bool gotLock = false;
292    for (size_t i = 0; i < kDumpLockAttempts; ++i) {
293        if (lock.tryLock() == NO_ERROR) {
294            gotLock = true;
295            break;
296        } else {
297            usleep(kDumpSleepDuration);
298        }
299    }
300    return gotLock;
301}
302
303status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
304    ATRACE_CALL();
305    (void)args;
306
307    // Try to lock, but continue in case of failure (to avoid blocking in
308    // deadlocks)
309    bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
310    bool gotLock = tryLockSpinRightRound(mLock);
311
312    ALOGW_IF(!gotInterfaceLock,
313            "Camera %d: %s: Unable to lock interface lock, proceeding anyway",
314            mId, __FUNCTION__);
315    ALOGW_IF(!gotLock,
316            "Camera %d: %s: Unable to lock main lock, proceeding anyway",
317            mId, __FUNCTION__);
318
319    String8 lines;
320
321    const char *status =
322            mStatus == STATUS_ERROR         ? "ERROR" :
323            mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
324            mStatus == STATUS_UNCONFIGURED  ? "UNCONFIGURED" :
325            mStatus == STATUS_CONFIGURED    ? "CONFIGURED" :
326            mStatus == STATUS_ACTIVE        ? "ACTIVE" :
327            "Unknown";
328
329    lines.appendFormat("    Device status: %s\n", status);
330    if (mStatus == STATUS_ERROR) {
331        lines.appendFormat("    Error cause: %s\n", mErrorCause.string());
332    }
333    lines.appendFormat("    Stream configuration:\n");
334
335    if (mInputStream != NULL) {
336        write(fd, lines.string(), lines.size());
337        mInputStream->dump(fd, args);
338    } else {
339        lines.appendFormat("      No input stream.\n");
340        write(fd, lines.string(), lines.size());
341    }
342    for (size_t i = 0; i < mOutputStreams.size(); i++) {
343        mOutputStreams[i]->dump(fd,args);
344    }
345
346    lines = String8("    In-flight requests:\n");
347    if (mInFlightMap.size() == 0) {
348        lines.append("      None\n");
349    } else {
350        for (size_t i = 0; i < mInFlightMap.size(); i++) {
351            InFlightRequest r = mInFlightMap.valueAt(i);
352            lines.appendFormat("      Frame %d |  Timestamp: %lld, metadata"
353                    " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
354                    r.captureTimestamp, r.haveResultMetadata ? "true" : "false",
355                    r.numBuffersLeft);
356        }
357    }
358    write(fd, lines.string(), lines.size());
359
360    {
361        lines = String8("    Last request sent:\n");
362        write(fd, lines.string(), lines.size());
363
364        CameraMetadata lastRequest = getLatestRequestLocked();
365        lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
366    }
367
368    if (mHal3Device != NULL) {
369        lines = String8("    HAL device dump:\n");
370        write(fd, lines.string(), lines.size());
371        mHal3Device->ops->dump(mHal3Device, fd);
372    }
373
374    if (gotLock) mLock.unlock();
375    if (gotInterfaceLock) mInterfaceLock.unlock();
376
377    return OK;
378}
379
380const CameraMetadata& Camera3Device::info() const {
381    ALOGVV("%s: E", __FUNCTION__);
382    if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
383                    mStatus == STATUS_ERROR)) {
384        ALOGW("%s: Access to static info %s!", __FUNCTION__,
385                mStatus == STATUS_ERROR ?
386                "when in error state" : "before init");
387    }
388    return mDeviceInfo;
389}
390
391status_t Camera3Device::capture(CameraMetadata &request) {
392    ATRACE_CALL();
393    status_t res;
394    Mutex::Autolock il(mInterfaceLock);
395    Mutex::Autolock l(mLock);
396
397    // TODO: take ownership of the request
398
399    switch (mStatus) {
400        case STATUS_ERROR:
401            CLOGE("Device has encountered a serious error");
402            return INVALID_OPERATION;
403        case STATUS_UNINITIALIZED:
404            CLOGE("Device not initialized");
405            return INVALID_OPERATION;
406        case STATUS_UNCONFIGURED:
407            // May be lazily configuring streams, will check during setup
408        case STATUS_CONFIGURED:
409        case STATUS_ACTIVE:
410            // OK
411            break;
412        default:
413            SET_ERR_L("Unexpected status: %d", mStatus);
414            return INVALID_OPERATION;
415    }
416
417    sp<CaptureRequest> newRequest = setUpRequestLocked(request);
418    if (newRequest == NULL) {
419        CLOGE("Can't create capture request");
420        return BAD_VALUE;
421    }
422
423    res = mRequestThread->queueRequest(newRequest);
424    if (res == OK) {
425        waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
426        if (res != OK) {
427            SET_ERR_L("Can't transition to active in %f seconds!",
428                    kActiveTimeout/1e9);
429        }
430        ALOGV("Camera %d: Capture request enqueued", mId);
431    }
432    return res;
433}
434
435
436status_t Camera3Device::setStreamingRequest(const CameraMetadata &request) {
437    ATRACE_CALL();
438    status_t res;
439    Mutex::Autolock il(mInterfaceLock);
440    Mutex::Autolock l(mLock);
441
442    switch (mStatus) {
443        case STATUS_ERROR:
444            CLOGE("Device has encountered a serious error");
445            return INVALID_OPERATION;
446        case STATUS_UNINITIALIZED:
447            CLOGE("Device not initialized");
448            return INVALID_OPERATION;
449        case STATUS_UNCONFIGURED:
450            // May be lazily configuring streams, will check during setup
451        case STATUS_CONFIGURED:
452        case STATUS_ACTIVE:
453            // OK
454            break;
455        default:
456            SET_ERR_L("Unexpected status: %d", mStatus);
457            return INVALID_OPERATION;
458    }
459
460    sp<CaptureRequest> newRepeatingRequest = setUpRequestLocked(request);
461    if (newRepeatingRequest == NULL) {
462        CLOGE("Can't create repeating request");
463        return BAD_VALUE;
464    }
465
466    RequestList newRepeatingRequests;
467    newRepeatingRequests.push_back(newRepeatingRequest);
468
469    res = mRequestThread->setRepeatingRequests(newRepeatingRequests);
470    if (res == OK) {
471        waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
472        if (res != OK) {
473            SET_ERR_L("Can't transition to active in %f seconds!",
474                    kActiveTimeout/1e9);
475        }
476        ALOGV("Camera %d: Repeating request set", mId);
477    }
478    return res;
479}
480
481
482sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
483        const CameraMetadata &request) {
484    status_t res;
485
486    if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
487        res = configureStreamsLocked();
488        if (res != OK) {
489            SET_ERR_L("Can't set up streams: %s (%d)", strerror(-res), res);
490            return NULL;
491        }
492        if (mStatus == STATUS_UNCONFIGURED) {
493            CLOGE("No streams configured");
494            return NULL;
495        }
496    }
497
498    sp<CaptureRequest> newRequest = createCaptureRequest(request);
499    return newRequest;
500}
501
502status_t Camera3Device::clearStreamingRequest() {
503    ATRACE_CALL();
504    Mutex::Autolock il(mInterfaceLock);
505    Mutex::Autolock l(mLock);
506
507    switch (mStatus) {
508        case STATUS_ERROR:
509            CLOGE("Device has encountered a serious error");
510            return INVALID_OPERATION;
511        case STATUS_UNINITIALIZED:
512            CLOGE("Device not initialized");
513            return INVALID_OPERATION;
514        case STATUS_UNCONFIGURED:
515        case STATUS_CONFIGURED:
516        case STATUS_ACTIVE:
517            // OK
518            break;
519        default:
520            SET_ERR_L("Unexpected status: %d", mStatus);
521            return INVALID_OPERATION;
522    }
523    ALOGV("Camera %d: Clearing repeating request", mId);
524    return mRequestThread->clearRepeatingRequests();
525}
526
527status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
528    ATRACE_CALL();
529    Mutex::Autolock il(mInterfaceLock);
530
531    return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
532}
533
534status_t Camera3Device::createInputStream(
535        uint32_t width, uint32_t height, int format, int *id) {
536    ATRACE_CALL();
537    Mutex::Autolock il(mInterfaceLock);
538    Mutex::Autolock l(mLock);
539    ALOGV("Camera %d: Creating new input stream %d: %d x %d, format %d",
540            mId, mNextStreamId, width, height, format);
541
542    status_t res;
543    bool wasActive = false;
544
545    switch (mStatus) {
546        case STATUS_ERROR:
547            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
548            return INVALID_OPERATION;
549        case STATUS_UNINITIALIZED:
550            ALOGE("%s: Device not initialized", __FUNCTION__);
551            return INVALID_OPERATION;
552        case STATUS_UNCONFIGURED:
553        case STATUS_CONFIGURED:
554            // OK
555            break;
556        case STATUS_ACTIVE:
557            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
558            res = internalPauseAndWaitLocked();
559            if (res != OK) {
560                SET_ERR_L("Can't pause captures to reconfigure streams!");
561                return res;
562            }
563            wasActive = true;
564            break;
565        default:
566            SET_ERR_L("%s: Unexpected status: %d", mStatus);
567            return INVALID_OPERATION;
568    }
569    assert(mStatus != STATUS_ACTIVE);
570
571    if (mInputStream != 0) {
572        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
573        return INVALID_OPERATION;
574    }
575
576    sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
577                width, height, format);
578    newStream->setStatusTracker(mStatusTracker);
579
580    mInputStream = newStream;
581
582    *id = mNextStreamId++;
583
584    // Continue captures if active at start
585    if (wasActive) {
586        ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
587        res = configureStreamsLocked();
588        if (res != OK) {
589            ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
590                    __FUNCTION__, mNextStreamId, strerror(-res), res);
591            return res;
592        }
593        internalResumeLocked();
594    }
595
596    ALOGV("Camera %d: Created input stream", mId);
597    return OK;
598}
599
600
601status_t Camera3Device::createZslStream(
602            uint32_t width, uint32_t height,
603            int depth,
604            /*out*/
605            int *id,
606            sp<Camera3ZslStream>* zslStream) {
607    ATRACE_CALL();
608    Mutex::Autolock il(mInterfaceLock);
609    Mutex::Autolock l(mLock);
610    ALOGV("Camera %d: Creating ZSL stream %d: %d x %d, depth %d",
611            mId, mNextStreamId, width, height, depth);
612
613    status_t res;
614    bool wasActive = false;
615
616    switch (mStatus) {
617        case STATUS_ERROR:
618            ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
619            return INVALID_OPERATION;
620        case STATUS_UNINITIALIZED:
621            ALOGE("%s: Device not initialized", __FUNCTION__);
622            return INVALID_OPERATION;
623        case STATUS_UNCONFIGURED:
624        case STATUS_CONFIGURED:
625            // OK
626            break;
627        case STATUS_ACTIVE:
628            ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
629            res = internalPauseAndWaitLocked();
630            if (res != OK) {
631                SET_ERR_L("Can't pause captures to reconfigure streams!");
632                return res;
633            }
634            wasActive = true;
635            break;
636        default:
637            SET_ERR_L("Unexpected status: %d", mStatus);
638            return INVALID_OPERATION;
639    }
640    assert(mStatus != STATUS_ACTIVE);
641
642    if (mInputStream != 0) {
643        ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
644        return INVALID_OPERATION;
645    }
646
647    sp<Camera3ZslStream> newStream = new Camera3ZslStream(mNextStreamId,
648                width, height, depth);
649    newStream->setStatusTracker(mStatusTracker);
650
651    res = mOutputStreams.add(mNextStreamId, newStream);
652    if (res < 0) {
653        ALOGE("%s: Can't add new stream to set: %s (%d)",
654                __FUNCTION__, strerror(-res), res);
655        return res;
656    }
657    mInputStream = newStream;
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 %d",
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 %lld 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(int32_t frameNumber,
1413        const CameraMetadata& partial) {
1414
1415    // Check if all 3A states are present
1416    // The full list of fields is
1417    //   android.control.afMode
1418    //   android.control.awbMode
1419    //   android.control.aeState
1420    //   android.control.awbState
1421    //   android.control.afState
1422    //   android.control.afTriggerID
1423    //   android.control.aePrecaptureID
1424    // TODO: Add android.control.aeMode
1425
1426    bool gotAllStates = true;
1427
1428    uint8_t afMode;
1429    uint8_t awbMode;
1430    uint8_t aeState;
1431    uint8_t afState;
1432    uint8_t awbState;
1433    int32_t afTriggerId;
1434    int32_t aeTriggerId;
1435
1436    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_MODE,
1437        &afMode, frameNumber);
1438
1439    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_MODE,
1440        &awbMode, frameNumber);
1441
1442    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AE_STATE,
1443        &aeState, frameNumber);
1444
1445    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_STATE,
1446        &afState, frameNumber);
1447
1448    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AWB_STATE,
1449        &awbState, frameNumber);
1450
1451    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AF_TRIGGER_ID,
1452        &afTriggerId, frameNumber);
1453
1454    gotAllStates &= get3AResult(partial, ANDROID_CONTROL_AE_PRECAPTURE_ID,
1455        &aeTriggerId, frameNumber);
1456
1457    if (!gotAllStates) return false;
1458
1459    ALOGVV("%s: Camera %d: Frame %d: AF mode %d, AWB mode %d, "
1460        "AF state %d, AE state %d, AWB state %d, "
1461        "AF trigger %d, AE precapture trigger %d",
1462        __FUNCTION__, mId, frameNumber,
1463        afMode, awbMode,
1464        afState, aeState, awbState,
1465        afTriggerId, aeTriggerId);
1466
1467    // Got all states, so construct a minimal result to send
1468    // In addition to the above fields, this means adding in
1469    //   android.request.frameCount
1470    //   android.quirks.partialResult
1471
1472    const size_t kMinimal3AResultEntries = 7;
1473
1474    Mutex::Autolock l(mOutputLock);
1475
1476    CameraMetadata& min3AResult =
1477            *mResultQueue.insert(
1478                mResultQueue.end(),
1479                CameraMetadata(kMinimal3AResultEntries, /*dataCapacity*/ 0));
1480
1481    if (!insert3AResult(min3AResult, ANDROID_REQUEST_FRAME_COUNT,
1482            &frameNumber, frameNumber)) {
1483        return false;
1484    }
1485
1486    static const uint8_t partialResult = ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL;
1487    if (!insert3AResult(min3AResult, ANDROID_QUIRKS_PARTIAL_RESULT,
1488            &partialResult, frameNumber)) {
1489        return false;
1490    }
1491
1492    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AF_MODE,
1493            &afMode, frameNumber)) {
1494        return false;
1495    }
1496
1497    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AWB_MODE,
1498            &awbMode, frameNumber)) {
1499        return false;
1500    }
1501
1502    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AE_STATE,
1503            &aeState, frameNumber)) {
1504        return false;
1505    }
1506
1507    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AF_STATE,
1508            &afState, frameNumber)) {
1509        return false;
1510    }
1511
1512    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AWB_STATE,
1513            &awbState, frameNumber)) {
1514        return false;
1515    }
1516
1517    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AF_TRIGGER_ID,
1518            &afTriggerId, frameNumber)) {
1519        return false;
1520    }
1521
1522    if (!insert3AResult(min3AResult, ANDROID_CONTROL_AE_PRECAPTURE_ID,
1523            &aeTriggerId, frameNumber)) {
1524        return false;
1525    }
1526
1527    mResultSignal.signal();
1528
1529    return true;
1530}
1531
1532template<typename T>
1533bool Camera3Device::get3AResult(const CameraMetadata& result, int32_t tag,
1534        T* value, int32_t frameNumber) {
1535    (void) frameNumber;
1536
1537    camera_metadata_ro_entry_t entry;
1538
1539    entry = result.find(tag);
1540    if (entry.count == 0) {
1541        ALOGVV("%s: Camera %d: Frame %d: No %s provided by HAL!", __FUNCTION__,
1542            mId, frameNumber, get_camera_metadata_tag_name(tag));
1543        return false;
1544    }
1545
1546    if (sizeof(T) == sizeof(uint8_t)) {
1547        *value = entry.data.u8[0];
1548    } else if (sizeof(T) == sizeof(int32_t)) {
1549        *value = entry.data.i32[0];
1550    } else {
1551        ALOGE("%s: Unexpected type", __FUNCTION__);
1552        return false;
1553    }
1554    return true;
1555}
1556
1557template<typename T>
1558bool Camera3Device::insert3AResult(CameraMetadata& result, int32_t tag,
1559        const T* value, int32_t frameNumber) {
1560    if (result.update(tag, value, 1) != NO_ERROR) {
1561        mResultQueue.erase(--mResultQueue.end(), mResultQueue.end());
1562        SET_ERR("Frame %d: Failed to set %s in partial metadata",
1563                frameNumber, get_camera_metadata_tag_name(tag));
1564        return false;
1565    }
1566    return true;
1567}
1568
1569/**
1570 * Camera HAL device callback methods
1571 */
1572
1573void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
1574    ATRACE_CALL();
1575
1576    status_t res;
1577
1578    uint32_t frameNumber = result->frame_number;
1579    if (result->result == NULL && result->num_output_buffers == 0) {
1580        SET_ERR("No result data provided by HAL for frame %d",
1581                frameNumber);
1582        return;
1583    }
1584    bool partialResultQuirk = false;
1585    CameraMetadata collectedQuirkResult;
1586
1587    // Get capture timestamp from list of in-flight requests, where it was added
1588    // by the shutter notification for this frame. Then update the in-flight
1589    // status and remove the in-flight entry if all result data has been
1590    // received.
1591    nsecs_t timestamp = 0;
1592    {
1593        Mutex::Autolock l(mInFlightLock);
1594        ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
1595        if (idx == NAME_NOT_FOUND) {
1596            SET_ERR("Unknown frame number for capture result: %d",
1597                    frameNumber);
1598            return;
1599        }
1600        InFlightRequest &request = mInFlightMap.editValueAt(idx);
1601
1602        // Check if this result carries only partial metadata
1603        if (mUsePartialResultQuirk && result->result != NULL) {
1604            camera_metadata_ro_entry_t partialResultEntry;
1605            res = find_camera_metadata_ro_entry(result->result,
1606                    ANDROID_QUIRKS_PARTIAL_RESULT, &partialResultEntry);
1607            if (res != NAME_NOT_FOUND &&
1608                    partialResultEntry.count > 0 &&
1609                    partialResultEntry.data.u8[0] ==
1610                    ANDROID_QUIRKS_PARTIAL_RESULT_PARTIAL) {
1611                // A partial result. Flag this as such, and collect this
1612                // set of metadata into the in-flight entry.
1613                partialResultQuirk = true;
1614                request.partialResultQuirk.collectedResult.append(
1615                    result->result);
1616                request.partialResultQuirk.collectedResult.erase(
1617                    ANDROID_QUIRKS_PARTIAL_RESULT);
1618                // Fire off a 3A-only result if possible
1619                if (!request.partialResultQuirk.haveSent3A) {
1620                    request.partialResultQuirk.haveSent3A =
1621                            processPartial3AQuirk(frameNumber,
1622                                request.partialResultQuirk.collectedResult);
1623                }
1624            }
1625        }
1626
1627        timestamp = request.captureTimestamp;
1628        /**
1629         * One of the following must happen before it's legal to call process_capture_result,
1630         * unless partial metadata is being provided:
1631         * - CAMERA3_MSG_SHUTTER (expected during normal operation)
1632         * - CAMERA3_MSG_ERROR (expected during flush)
1633         */
1634        if (request.requestStatus == OK && timestamp == 0 && !partialResultQuirk) {
1635            SET_ERR("Called before shutter notify for frame %d",
1636                    frameNumber);
1637            return;
1638        }
1639
1640        // Did we get the (final) result metadata for this capture?
1641        if (result->result != NULL && !partialResultQuirk) {
1642            if (request.haveResultMetadata) {
1643                SET_ERR("Called multiple times with metadata for frame %d",
1644                        frameNumber);
1645                return;
1646            }
1647            if (mUsePartialResultQuirk &&
1648                    !request.partialResultQuirk.collectedResult.isEmpty()) {
1649                collectedQuirkResult.acquire(
1650                    request.partialResultQuirk.collectedResult);
1651            }
1652            request.haveResultMetadata = true;
1653        }
1654
1655        request.numBuffersLeft -= result->num_output_buffers;
1656
1657        if (request.numBuffersLeft < 0) {
1658            SET_ERR("Too many buffers returned for frame %d",
1659                    frameNumber);
1660            return;
1661        }
1662
1663        // Check if everything has arrived for this result (buffers and metadata)
1664        if (request.haveResultMetadata && request.numBuffersLeft == 0) {
1665            ATRACE_ASYNC_END("frame capture", frameNumber);
1666            mInFlightMap.removeItemsAt(idx, 1);
1667        }
1668
1669        // Sanity check - if we have too many in-flight frames, something has
1670        // likely gone wrong
1671        if (mInFlightMap.size() > kInFlightWarnLimit) {
1672            CLOGE("In-flight list too large: %d", mInFlightMap.size());
1673        }
1674
1675    }
1676
1677    // Process the result metadata, if provided
1678    bool gotResult = false;
1679    if (result->result != NULL && !partialResultQuirk) {
1680        Mutex::Autolock l(mOutputLock);
1681
1682        gotResult = true;
1683
1684        if (frameNumber != mNextResultFrameNumber) {
1685            SET_ERR("Out-of-order capture result metadata submitted! "
1686                    "(got frame number %d, expecting %d)",
1687                    frameNumber, mNextResultFrameNumber);
1688            return;
1689        }
1690        mNextResultFrameNumber++;
1691
1692        CameraMetadata captureResult;
1693        captureResult = result->result;
1694
1695        if (captureResult.update(ANDROID_REQUEST_FRAME_COUNT,
1696                        (int32_t*)&frameNumber, 1) != OK) {
1697            SET_ERR("Failed to set frame# in metadata (%d)",
1698                    frameNumber);
1699            gotResult = false;
1700        } else {
1701            ALOGVV("%s: Camera %d: Set frame# in metadata (%d)",
1702                    __FUNCTION__, mId, frameNumber);
1703        }
1704
1705        // Append any previous partials to form a complete result
1706        if (mUsePartialResultQuirk && !collectedQuirkResult.isEmpty()) {
1707            captureResult.append(collectedQuirkResult);
1708        }
1709
1710        captureResult.sort();
1711
1712        // Check that there's a timestamp in the result metadata
1713
1714        camera_metadata_entry entry =
1715                captureResult.find(ANDROID_SENSOR_TIMESTAMP);
1716        if (entry.count == 0) {
1717            SET_ERR("No timestamp provided by HAL for frame %d!",
1718                    frameNumber);
1719            gotResult = false;
1720        } else if (timestamp != entry.data.i64[0]) {
1721            SET_ERR("Timestamp mismatch between shutter notify and result"
1722                    " metadata for frame %d (%lld vs %lld respectively)",
1723                    frameNumber, timestamp, entry.data.i64[0]);
1724            gotResult = false;
1725        }
1726
1727        if (gotResult) {
1728            // Valid result, insert into queue
1729            CameraMetadata& queuedResult =
1730                *mResultQueue.insert(mResultQueue.end(), CameraMetadata());
1731            queuedResult.swap(captureResult);
1732        }
1733    } // scope for mOutputLock
1734
1735    // Return completed buffers to their streams with the timestamp
1736
1737    for (size_t i = 0; i < result->num_output_buffers; i++) {
1738        Camera3Stream *stream =
1739                Camera3Stream::cast(result->output_buffers[i].stream);
1740        res = stream->returnBuffer(result->output_buffers[i], timestamp);
1741        // Note: stream may be deallocated at this point, if this buffer was the
1742        // last reference to it.
1743        if (res != OK) {
1744            ALOGE("Can't return buffer %d for frame %d to its stream: "
1745                    " %s (%d)", i, frameNumber, strerror(-res), res);
1746        }
1747    }
1748
1749    // Finally, signal any waiters for new frames
1750
1751    if (gotResult) {
1752        mResultSignal.signal();
1753    }
1754
1755}
1756
1757
1758
1759void Camera3Device::notify(const camera3_notify_msg *msg) {
1760    ATRACE_CALL();
1761    NotificationListener *listener;
1762    {
1763        Mutex::Autolock l(mOutputLock);
1764        listener = mListener;
1765    }
1766
1767    if (msg == NULL) {
1768        SET_ERR("HAL sent NULL notify message!");
1769        return;
1770    }
1771
1772    switch (msg->type) {
1773        case CAMERA3_MSG_ERROR: {
1774            int streamId = 0;
1775            if (msg->message.error.error_stream != NULL) {
1776                Camera3Stream *stream =
1777                        Camera3Stream::cast(
1778                                  msg->message.error.error_stream);
1779                streamId = stream->getId();
1780            }
1781            ALOGV("Camera %d: %s: HAL error, frame %d, stream %d: %d",
1782                    mId, __FUNCTION__, msg->message.error.frame_number,
1783                    streamId, msg->message.error.error_code);
1784
1785            // Set request error status for the request in the in-flight tracking
1786            {
1787                Mutex::Autolock l(mInFlightLock);
1788                ssize_t idx = mInFlightMap.indexOfKey(msg->message.error.frame_number);
1789                if (idx >= 0) {
1790                    mInFlightMap.editValueAt(idx).requestStatus = msg->message.error.error_code;
1791                }
1792            }
1793
1794            if (listener != NULL) {
1795                listener->notifyError(msg->message.error.error_code,
1796                        msg->message.error.frame_number, streamId);
1797            }
1798            break;
1799        }
1800        case CAMERA3_MSG_SHUTTER: {
1801            ssize_t idx;
1802            uint32_t frameNumber = msg->message.shutter.frame_number;
1803            nsecs_t timestamp = msg->message.shutter.timestamp;
1804            // Verify ordering of shutter notifications
1805            {
1806                Mutex::Autolock l(mOutputLock);
1807                if (frameNumber != mNextShutterFrameNumber) {
1808                    SET_ERR("Shutter notification out-of-order. Expected "
1809                            "notification for frame %d, got frame %d",
1810                            mNextShutterFrameNumber, frameNumber);
1811                    break;
1812                }
1813                mNextShutterFrameNumber++;
1814            }
1815
1816            int32_t requestId = -1;
1817
1818            // Set timestamp for the request in the in-flight tracking
1819            // and get the request ID to send upstream
1820            {
1821                Mutex::Autolock l(mInFlightLock);
1822                idx = mInFlightMap.indexOfKey(frameNumber);
1823                if (idx >= 0) {
1824                    InFlightRequest &r = mInFlightMap.editValueAt(idx);
1825                    r.captureTimestamp = timestamp;
1826                    requestId = r.requestId;
1827                }
1828            }
1829            if (idx < 0) {
1830                SET_ERR("Shutter notification for non-existent frame number %d",
1831                        frameNumber);
1832                break;
1833            }
1834            ALOGVV("Camera %d: %s: Shutter fired for frame %d (id %d) at %lld",
1835                    mId, __FUNCTION__, frameNumber, requestId, timestamp);
1836            // Call listener, if any
1837            if (listener != NULL) {
1838                listener->notifyShutter(requestId, timestamp);
1839            }
1840            break;
1841        }
1842        default:
1843            SET_ERR("Unknown notify message from HAL: %d",
1844                    msg->type);
1845    }
1846}
1847
1848CameraMetadata Camera3Device::getLatestRequestLocked() {
1849    ALOGV("%s", __FUNCTION__);
1850
1851    CameraMetadata retVal;
1852
1853    if (mRequestThread != NULL) {
1854        retVal = mRequestThread->getLatestRequest();
1855    }
1856
1857    return retVal;
1858}
1859
1860/**
1861 * RequestThread inner class methods
1862 */
1863
1864Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
1865        sp<StatusTracker> statusTracker,
1866        camera3_device_t *hal3Device) :
1867        Thread(false),
1868        mParent(parent),
1869        mStatusTracker(statusTracker),
1870        mHal3Device(hal3Device),
1871        mId(getId(parent)),
1872        mReconfigured(false),
1873        mDoPause(false),
1874        mPaused(true),
1875        mFrameNumber(0),
1876        mLatestRequestId(NAME_NOT_FOUND) {
1877    mStatusId = statusTracker->addComponent();
1878}
1879
1880void Camera3Device::RequestThread::configurationComplete() {
1881    Mutex::Autolock l(mRequestLock);
1882    mReconfigured = true;
1883}
1884
1885status_t Camera3Device::RequestThread::queueRequest(
1886         sp<CaptureRequest> request) {
1887    Mutex::Autolock l(mRequestLock);
1888    mRequestQueue.push_back(request);
1889
1890    unpauseForNewRequests();
1891
1892    return OK;
1893}
1894
1895
1896status_t Camera3Device::RequestThread::queueTrigger(
1897        RequestTrigger trigger[],
1898        size_t count) {
1899
1900    Mutex::Autolock l(mTriggerMutex);
1901    status_t ret;
1902
1903    for (size_t i = 0; i < count; ++i) {
1904        ret = queueTriggerLocked(trigger[i]);
1905
1906        if (ret != OK) {
1907            return ret;
1908        }
1909    }
1910
1911    return OK;
1912}
1913
1914int Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
1915    sp<Camera3Device> d = device.promote();
1916    if (d != NULL) return d->mId;
1917    return 0;
1918}
1919
1920status_t Camera3Device::RequestThread::queueTriggerLocked(
1921        RequestTrigger trigger) {
1922
1923    uint32_t tag = trigger.metadataTag;
1924    ssize_t index = mTriggerMap.indexOfKey(tag);
1925
1926    switch (trigger.getTagType()) {
1927        case TYPE_BYTE:
1928        // fall-through
1929        case TYPE_INT32:
1930            break;
1931        default:
1932            ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
1933                    trigger.getTagType());
1934            return INVALID_OPERATION;
1935    }
1936
1937    /**
1938     * Collect only the latest trigger, since we only have 1 field
1939     * in the request settings per trigger tag, and can't send more than 1
1940     * trigger per request.
1941     */
1942    if (index != NAME_NOT_FOUND) {
1943        mTriggerMap.editValueAt(index) = trigger;
1944    } else {
1945        mTriggerMap.add(tag, trigger);
1946    }
1947
1948    return OK;
1949}
1950
1951status_t Camera3Device::RequestThread::setRepeatingRequests(
1952        const RequestList &requests) {
1953    Mutex::Autolock l(mRequestLock);
1954    mRepeatingRequests.clear();
1955    mRepeatingRequests.insert(mRepeatingRequests.begin(),
1956            requests.begin(), requests.end());
1957
1958    unpauseForNewRequests();
1959
1960    return OK;
1961}
1962
1963status_t Camera3Device::RequestThread::clearRepeatingRequests() {
1964    Mutex::Autolock l(mRequestLock);
1965    mRepeatingRequests.clear();
1966    return OK;
1967}
1968
1969status_t Camera3Device::RequestThread::clear() {
1970    Mutex::Autolock l(mRequestLock);
1971    mRepeatingRequests.clear();
1972    mRequestQueue.clear();
1973    mTriggerMap.clear();
1974    return OK;
1975}
1976
1977void Camera3Device::RequestThread::setPaused(bool paused) {
1978    Mutex::Autolock l(mPauseLock);
1979    mDoPause = paused;
1980    mDoPauseSignal.signal();
1981}
1982
1983status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
1984        int32_t requestId, nsecs_t timeout) {
1985    Mutex::Autolock l(mLatestRequestMutex);
1986    status_t res;
1987    while (mLatestRequestId != requestId) {
1988        nsecs_t startTime = systemTime();
1989
1990        res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
1991        if (res != OK) return res;
1992
1993        timeout -= (systemTime() - startTime);
1994    }
1995
1996    return OK;
1997}
1998
1999void Camera3Device::RequestThread::requestExit() {
2000    // Call parent to set up shutdown
2001    Thread::requestExit();
2002    // The exit from any possible waits
2003    mDoPauseSignal.signal();
2004    mRequestSignal.signal();
2005}
2006
2007bool Camera3Device::RequestThread::threadLoop() {
2008
2009    status_t res;
2010
2011    // Handle paused state.
2012    if (waitIfPaused()) {
2013        return true;
2014    }
2015
2016    // Get work to do
2017
2018    sp<CaptureRequest> nextRequest = waitForNextRequest();
2019    if (nextRequest == NULL) {
2020        return true;
2021    }
2022
2023    // Create request to HAL
2024    camera3_capture_request_t request = camera3_capture_request_t();
2025    Vector<camera3_stream_buffer_t> outputBuffers;
2026
2027    // Get the request ID, if any
2028    int requestId;
2029    camera_metadata_entry_t requestIdEntry =
2030            nextRequest->mSettings.find(ANDROID_REQUEST_ID);
2031    if (requestIdEntry.count > 0) {
2032        requestId = requestIdEntry.data.i32[0];
2033    } else {
2034        ALOGW("%s: Did not have android.request.id set in the request",
2035                __FUNCTION__);
2036        requestId = NAME_NOT_FOUND;
2037    }
2038
2039    // Insert any queued triggers (before metadata is locked)
2040    int32_t triggerCount;
2041    res = insertTriggers(nextRequest);
2042    if (res < 0) {
2043        SET_ERR("RequestThread: Unable to insert triggers "
2044                "(capture request %d, HAL device: %s (%d)",
2045                (mFrameNumber+1), strerror(-res), res);
2046        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2047        return false;
2048    }
2049    triggerCount = res;
2050
2051    bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
2052
2053    // If the request is the same as last, or we had triggers last time
2054    if (mPrevRequest != nextRequest || triggersMixedIn) {
2055        /**
2056         * HAL workaround:
2057         * Insert a dummy trigger ID if a trigger is set but no trigger ID is
2058         */
2059        res = addDummyTriggerIds(nextRequest);
2060        if (res != OK) {
2061            SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
2062                    "(capture request %d, HAL device: %s (%d)",
2063                    (mFrameNumber+1), strerror(-res), res);
2064            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2065            return false;
2066        }
2067
2068        /**
2069         * The request should be presorted so accesses in HAL
2070         *   are O(logn). Sidenote, sorting a sorted metadata is nop.
2071         */
2072        nextRequest->mSettings.sort();
2073        request.settings = nextRequest->mSettings.getAndLock();
2074        mPrevRequest = nextRequest;
2075        ALOGVV("%s: Request settings are NEW", __FUNCTION__);
2076
2077        IF_ALOGV() {
2078            camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
2079            find_camera_metadata_ro_entry(
2080                    request.settings,
2081                    ANDROID_CONTROL_AF_TRIGGER,
2082                    &e
2083            );
2084            if (e.count > 0) {
2085                ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
2086                      __FUNCTION__,
2087                      mFrameNumber+1,
2088                      e.data.u8[0]);
2089            }
2090        }
2091    } else {
2092        // leave request.settings NULL to indicate 'reuse latest given'
2093        ALOGVV("%s: Request settings are REUSED",
2094               __FUNCTION__);
2095    }
2096
2097    camera3_stream_buffer_t inputBuffer;
2098
2099    // Fill in buffers
2100
2101    if (nextRequest->mInputStream != NULL) {
2102        request.input_buffer = &inputBuffer;
2103        res = nextRequest->mInputStream->getInputBuffer(&inputBuffer);
2104        if (res != OK) {
2105            ALOGE("RequestThread: Can't get input buffer, skipping request:"
2106                    " %s (%d)", strerror(-res), res);
2107            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2108            return true;
2109        }
2110    } else {
2111        request.input_buffer = NULL;
2112    }
2113
2114    outputBuffers.insertAt(camera3_stream_buffer_t(), 0,
2115            nextRequest->mOutputStreams.size());
2116    request.output_buffers = outputBuffers.array();
2117    for (size_t i = 0; i < nextRequest->mOutputStreams.size(); i++) {
2118        res = nextRequest->mOutputStreams.editItemAt(i)->
2119                getBuffer(&outputBuffers.editItemAt(i));
2120        if (res != OK) {
2121            ALOGE("RequestThread: Can't get output buffer, skipping request:"
2122                    " %s (%d)", strerror(-res), res);
2123            cleanUpFailedRequest(request, nextRequest, outputBuffers);
2124            return true;
2125        }
2126        request.num_output_buffers++;
2127    }
2128
2129    request.frame_number = mFrameNumber++;
2130
2131    // Log request in the in-flight queue
2132    sp<Camera3Device> parent = mParent.promote();
2133    if (parent == NULL) {
2134        CLOGE("RequestThread: Parent is gone");
2135        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2136        return false;
2137    }
2138
2139    res = parent->registerInFlight(request.frame_number, requestId,
2140            request.num_output_buffers);
2141    if (res != OK) {
2142        SET_ERR("RequestThread: Unable to register new in-flight request:"
2143                " %s (%d)", strerror(-res), res);
2144        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2145        return false;
2146    }
2147
2148    // Inform waitUntilRequestProcessed thread of a new request ID
2149    {
2150        Mutex::Autolock al(mLatestRequestMutex);
2151
2152        mLatestRequestId = requestId;
2153        mLatestRequestSignal.signal();
2154    }
2155
2156    // Submit request and block until ready for next one
2157    ATRACE_ASYNC_BEGIN("frame capture", request.frame_number);
2158    ATRACE_BEGIN("camera3->process_capture_request");
2159    res = mHal3Device->ops->process_capture_request(mHal3Device, &request);
2160    ATRACE_END();
2161
2162    if (res != OK) {
2163        SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
2164                " device: %s (%d)", request.frame_number, strerror(-res), res);
2165        cleanUpFailedRequest(request, nextRequest, outputBuffers);
2166        return false;
2167    }
2168
2169    // Update the latest request sent to HAL
2170    if (request.settings != NULL) { // Don't update them if they were unchanged
2171        Mutex::Autolock al(mLatestRequestMutex);
2172
2173        camera_metadata_t* cloned = clone_camera_metadata(request.settings);
2174        mLatestRequest.acquire(cloned);
2175    }
2176
2177    if (request.settings != NULL) {
2178        nextRequest->mSettings.unlock(request.settings);
2179    }
2180
2181    // Remove any previously queued triggers (after unlock)
2182    res = removeTriggers(mPrevRequest);
2183    if (res != OK) {
2184        SET_ERR("RequestThread: Unable to remove triggers "
2185              "(capture request %d, HAL device: %s (%d)",
2186              request.frame_number, strerror(-res), res);
2187        return false;
2188    }
2189    mPrevTriggers = triggerCount;
2190
2191    // Return input buffer back to framework
2192    if (request.input_buffer != NULL) {
2193        Camera3Stream *stream =
2194            Camera3Stream::cast(request.input_buffer->stream);
2195        res = stream->returnInputBuffer(*(request.input_buffer));
2196        // Note: stream may be deallocated at this point, if this buffer was the
2197        // last reference to it.
2198        if (res != OK) {
2199            ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
2200                    "  its stream:%s (%d)",  __FUNCTION__,
2201                    request.frame_number, strerror(-res), res);
2202            // TODO: Report error upstream
2203        }
2204    }
2205
2206    return true;
2207}
2208
2209CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
2210    Mutex::Autolock al(mLatestRequestMutex);
2211
2212    ALOGV("RequestThread::%s", __FUNCTION__);
2213
2214    return mLatestRequest;
2215}
2216
2217void Camera3Device::RequestThread::cleanUpFailedRequest(
2218        camera3_capture_request_t &request,
2219        sp<CaptureRequest> &nextRequest,
2220        Vector<camera3_stream_buffer_t> &outputBuffers) {
2221
2222    if (request.settings != NULL) {
2223        nextRequest->mSettings.unlock(request.settings);
2224    }
2225    if (request.input_buffer != NULL) {
2226        request.input_buffer->status = CAMERA3_BUFFER_STATUS_ERROR;
2227        nextRequest->mInputStream->returnInputBuffer(*(request.input_buffer));
2228    }
2229    for (size_t i = 0; i < request.num_output_buffers; i++) {
2230        outputBuffers.editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
2231        nextRequest->mOutputStreams.editItemAt(i)->returnBuffer(
2232            outputBuffers[i], 0);
2233    }
2234}
2235
2236sp<Camera3Device::CaptureRequest>
2237        Camera3Device::RequestThread::waitForNextRequest() {
2238    status_t res;
2239    sp<CaptureRequest> nextRequest;
2240
2241    // Optimized a bit for the simple steady-state case (single repeating
2242    // request), to avoid putting that request in the queue temporarily.
2243    Mutex::Autolock l(mRequestLock);
2244
2245    while (mRequestQueue.empty()) {
2246        if (!mRepeatingRequests.empty()) {
2247            // Always atomically enqueue all requests in a repeating request
2248            // list. Guarantees a complete in-sequence set of captures to
2249            // application.
2250            const RequestList &requests = mRepeatingRequests;
2251            RequestList::const_iterator firstRequest =
2252                    requests.begin();
2253            nextRequest = *firstRequest;
2254            mRequestQueue.insert(mRequestQueue.end(),
2255                    ++firstRequest,
2256                    requests.end());
2257            // No need to wait any longer
2258            break;
2259        }
2260
2261        res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
2262
2263        if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
2264                exitPending()) {
2265            Mutex::Autolock pl(mPauseLock);
2266            if (mPaused == false) {
2267                ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
2268                mPaused = true;
2269                // Let the tracker know
2270                sp<StatusTracker> statusTracker = mStatusTracker.promote();
2271                if (statusTracker != 0) {
2272                    statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
2273                }
2274            }
2275            // Stop waiting for now and let thread management happen
2276            return NULL;
2277        }
2278    }
2279
2280    if (nextRequest == NULL) {
2281        // Don't have a repeating request already in hand, so queue
2282        // must have an entry now.
2283        RequestList::iterator firstRequest =
2284                mRequestQueue.begin();
2285        nextRequest = *firstRequest;
2286        mRequestQueue.erase(firstRequest);
2287    }
2288
2289    // In case we've been unpaused by setPaused clearing mDoPause, need to
2290    // update internal pause state (capture/setRepeatingRequest unpause
2291    // directly).
2292    Mutex::Autolock pl(mPauseLock);
2293    if (mPaused) {
2294        ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
2295        sp<StatusTracker> statusTracker = mStatusTracker.promote();
2296        if (statusTracker != 0) {
2297            statusTracker->markComponentActive(mStatusId);
2298        }
2299    }
2300    mPaused = false;
2301
2302    // Check if we've reconfigured since last time, and reset the preview
2303    // request if so. Can't use 'NULL request == repeat' across configure calls.
2304    if (mReconfigured) {
2305        mPrevRequest.clear();
2306        mReconfigured = false;
2307    }
2308
2309    return nextRequest;
2310}
2311
2312bool Camera3Device::RequestThread::waitIfPaused() {
2313    status_t res;
2314    Mutex::Autolock l(mPauseLock);
2315    while (mDoPause) {
2316        if (mPaused == false) {
2317            mPaused = true;
2318            ALOGV("%s: RequestThread: Paused", __FUNCTION__);
2319            // Let the tracker know
2320            sp<StatusTracker> statusTracker = mStatusTracker.promote();
2321            if (statusTracker != 0) {
2322                statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
2323            }
2324        }
2325
2326        res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
2327        if (res == TIMED_OUT || exitPending()) {
2328            return true;
2329        }
2330    }
2331    // We don't set mPaused to false here, because waitForNextRequest needs
2332    // to further manage the paused state in case of starvation.
2333    return false;
2334}
2335
2336void Camera3Device::RequestThread::unpauseForNewRequests() {
2337    // With work to do, mark thread as unpaused.
2338    // If paused by request (setPaused), don't resume, to avoid
2339    // extra signaling/waiting overhead to waitUntilPaused
2340    mRequestSignal.signal();
2341    Mutex::Autolock p(mPauseLock);
2342    if (!mDoPause) {
2343        ALOGV("%s: RequestThread: Going active", __FUNCTION__);
2344        if (mPaused) {
2345            sp<StatusTracker> statusTracker = mStatusTracker.promote();
2346            if (statusTracker != 0) {
2347                statusTracker->markComponentActive(mStatusId);
2348            }
2349        }
2350        mPaused = false;
2351    }
2352}
2353
2354void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
2355    sp<Camera3Device> parent = mParent.promote();
2356    if (parent != NULL) {
2357        va_list args;
2358        va_start(args, fmt);
2359
2360        parent->setErrorStateV(fmt, args);
2361
2362        va_end(args);
2363    }
2364}
2365
2366status_t Camera3Device::RequestThread::insertTriggers(
2367        const sp<CaptureRequest> &request) {
2368
2369    Mutex::Autolock al(mTriggerMutex);
2370
2371    CameraMetadata &metadata = request->mSettings;
2372    size_t count = mTriggerMap.size();
2373
2374    for (size_t i = 0; i < count; ++i) {
2375        RequestTrigger trigger = mTriggerMap.valueAt(i);
2376
2377        uint32_t tag = trigger.metadataTag;
2378        camera_metadata_entry entry = metadata.find(tag);
2379
2380        if (entry.count > 0) {
2381            /**
2382             * Already has an entry for this trigger in the request.
2383             * Rewrite it with our requested trigger value.
2384             */
2385            RequestTrigger oldTrigger = trigger;
2386
2387            oldTrigger.entryValue = entry.data.u8[0];
2388
2389            mTriggerReplacedMap.add(tag, oldTrigger);
2390        } else {
2391            /**
2392             * More typical, no trigger entry, so we just add it
2393             */
2394            mTriggerRemovedMap.add(tag, trigger);
2395        }
2396
2397        status_t res;
2398
2399        switch (trigger.getTagType()) {
2400            case TYPE_BYTE: {
2401                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
2402                res = metadata.update(tag,
2403                                      &entryValue,
2404                                      /*count*/1);
2405                break;
2406            }
2407            case TYPE_INT32:
2408                res = metadata.update(tag,
2409                                      &trigger.entryValue,
2410                                      /*count*/1);
2411                break;
2412            default:
2413                ALOGE("%s: Type not supported: 0x%x",
2414                      __FUNCTION__,
2415                      trigger.getTagType());
2416                return INVALID_OPERATION;
2417        }
2418
2419        if (res != OK) {
2420            ALOGE("%s: Failed to update request metadata with trigger tag %s"
2421                  ", value %d", __FUNCTION__, trigger.getTagName(),
2422                  trigger.entryValue);
2423            return res;
2424        }
2425
2426        ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
2427              trigger.getTagName(),
2428              trigger.entryValue);
2429    }
2430
2431    mTriggerMap.clear();
2432
2433    return count;
2434}
2435
2436status_t Camera3Device::RequestThread::removeTriggers(
2437        const sp<CaptureRequest> &request) {
2438    Mutex::Autolock al(mTriggerMutex);
2439
2440    CameraMetadata &metadata = request->mSettings;
2441
2442    /**
2443     * Replace all old entries with their old values.
2444     */
2445    for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
2446        RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
2447
2448        status_t res;
2449
2450        uint32_t tag = trigger.metadataTag;
2451        switch (trigger.getTagType()) {
2452            case TYPE_BYTE: {
2453                uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
2454                res = metadata.update(tag,
2455                                      &entryValue,
2456                                      /*count*/1);
2457                break;
2458            }
2459            case TYPE_INT32:
2460                res = metadata.update(tag,
2461                                      &trigger.entryValue,
2462                                      /*count*/1);
2463                break;
2464            default:
2465                ALOGE("%s: Type not supported: 0x%x",
2466                      __FUNCTION__,
2467                      trigger.getTagType());
2468                return INVALID_OPERATION;
2469        }
2470
2471        if (res != OK) {
2472            ALOGE("%s: Failed to restore request metadata with trigger tag %s"
2473                  ", trigger value %d", __FUNCTION__,
2474                  trigger.getTagName(), trigger.entryValue);
2475            return res;
2476        }
2477    }
2478    mTriggerReplacedMap.clear();
2479
2480    /**
2481     * Remove all new entries.
2482     */
2483    for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
2484        RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
2485        status_t res = metadata.erase(trigger.metadataTag);
2486
2487        if (res != OK) {
2488            ALOGE("%s: Failed to erase metadata with trigger tag %s"
2489                  ", trigger value %d", __FUNCTION__,
2490                  trigger.getTagName(), trigger.entryValue);
2491            return res;
2492        }
2493    }
2494    mTriggerRemovedMap.clear();
2495
2496    return OK;
2497}
2498
2499status_t Camera3Device::RequestThread::addDummyTriggerIds(
2500        const sp<CaptureRequest> &request) {
2501    // Trigger ID 0 has special meaning in the HAL2 spec, so avoid it here
2502    static const int32_t dummyTriggerId = 1;
2503    status_t res;
2504
2505    CameraMetadata &metadata = request->mSettings;
2506
2507    // If AF trigger is active, insert a dummy AF trigger ID if none already
2508    // exists
2509    camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
2510    camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
2511    if (afTrigger.count > 0 &&
2512            afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
2513            afId.count == 0) {
2514        res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
2515        if (res != OK) return res;
2516    }
2517
2518    // If AE precapture trigger is active, insert a dummy precapture trigger ID
2519    // if none already exists
2520    camera_metadata_entry pcTrigger =
2521            metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
2522    camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
2523    if (pcTrigger.count > 0 &&
2524            pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
2525            pcId.count == 0) {
2526        res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
2527                &dummyTriggerId, 1);
2528        if (res != OK) return res;
2529    }
2530
2531    return OK;
2532}
2533
2534
2535/**
2536 * Static callback forwarding methods from HAL to instance
2537 */
2538
2539void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
2540        const camera3_capture_result *result) {
2541    Camera3Device *d =
2542            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
2543    d->processCaptureResult(result);
2544}
2545
2546void Camera3Device::sNotify(const camera3_callback_ops *cb,
2547        const camera3_notify_msg *msg) {
2548    Camera3Device *d =
2549            const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
2550    d->notify(msg);
2551}
2552
2553}; // namespace android
2554