Home | History | Annotate | Download | only in api1
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #define LOG_TAG "Camera2Client"
     18 #define ATRACE_TAG ATRACE_TAG_CAMERA
     19 //#define LOG_NDEBUG 0
     20 
     21 #include <utils/Log.h>
     22 #include <utils/Trace.h>
     23 
     24 #include <cutils/properties.h>
     25 #include <gui/Surface.h>
     26 
     27 #include "api1/Camera2Client.h"
     28 
     29 #include "api1/client2/StreamingProcessor.h"
     30 #include "api1/client2/JpegProcessor.h"
     31 #include "api1/client2/CaptureSequencer.h"
     32 #include "api1/client2/CallbackProcessor.h"
     33 #include "api1/client2/ZslProcessor.h"
     34 #include "api1/client2/ZslProcessor3.h"
     35 
     36 #define ALOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
     37 #define ALOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
     38 
     39 namespace android {
     40 using namespace camera2;
     41 
     42 static int getCallingPid() {
     43     return IPCThreadState::self()->getCallingPid();
     44 }
     45 
     46 // Interface used by CameraService
     47 
     48 Camera2Client::Camera2Client(const sp<CameraService>& cameraService,
     49         const sp<ICameraClient>& cameraClient,
     50         const String16& clientPackageName,
     51         int cameraId,
     52         int cameraFacing,
     53         int clientPid,
     54         uid_t clientUid,
     55         int servicePid,
     56         int deviceVersion):
     57         Camera2ClientBase(cameraService, cameraClient, clientPackageName,
     58                 cameraId, cameraFacing, clientPid, clientUid, servicePid),
     59         mParameters(cameraId, cameraFacing),
     60         mDeviceVersion(deviceVersion)
     61 {
     62     ATRACE_CALL();
     63 
     64     SharedParameters::Lock l(mParameters);
     65     l.mParameters.state = Parameters::DISCONNECTED;
     66 }
     67 
     68 status_t Camera2Client::initialize(camera_module_t *module)
     69 {
     70     ATRACE_CALL();
     71     ALOGV("%s: Initializing client for camera %d", __FUNCTION__, mCameraId);
     72     status_t res;
     73 
     74     res = Camera2ClientBase::initialize(module);
     75     if (res != OK) {
     76         return res;
     77     }
     78 
     79     SharedParameters::Lock l(mParameters);
     80 
     81     res = l.mParameters.initialize(&(mDevice->info()));
     82     if (res != OK) {
     83         ALOGE("%s: Camera %d: unable to build defaults: %s (%d)",
     84                 __FUNCTION__, mCameraId, strerror(-res), res);
     85         return NO_INIT;
     86     }
     87 
     88     String8 threadName;
     89 
     90     mStreamingProcessor = new StreamingProcessor(this);
     91     threadName = String8::format("C2-%d-StreamProc",
     92             mCameraId);
     93     mStreamingProcessor->run(threadName.string());
     94 
     95     mFrameProcessor = new FrameProcessor(mDevice, this);
     96     threadName = String8::format("C2-%d-FrameProc",
     97             mCameraId);
     98     mFrameProcessor->run(threadName.string());
     99 
    100     mCaptureSequencer = new CaptureSequencer(this);
    101     threadName = String8::format("C2-%d-CaptureSeq",
    102             mCameraId);
    103     mCaptureSequencer->run(threadName.string());
    104 
    105     mJpegProcessor = new JpegProcessor(this, mCaptureSequencer);
    106     threadName = String8::format("C2-%d-JpegProc",
    107             mCameraId);
    108     mJpegProcessor->run(threadName.string());
    109 
    110     switch (mDeviceVersion) {
    111         case CAMERA_DEVICE_API_VERSION_2_0: {
    112             sp<ZslProcessor> zslProc =
    113                     new ZslProcessor(this, mCaptureSequencer);
    114             mZslProcessor = zslProc;
    115             mZslProcessorThread = zslProc;
    116             break;
    117         }
    118         case CAMERA_DEVICE_API_VERSION_3_0:{
    119             sp<ZslProcessor3> zslProc =
    120                     new ZslProcessor3(this, mCaptureSequencer);
    121             mZslProcessor = zslProc;
    122             mZslProcessorThread = zslProc;
    123             break;
    124         }
    125         default:
    126             break;
    127     }
    128     threadName = String8::format("C2-%d-ZslProc",
    129             mCameraId);
    130     mZslProcessorThread->run(threadName.string());
    131 
    132     mCallbackProcessor = new CallbackProcessor(this);
    133     threadName = String8::format("C2-%d-CallbkProc",
    134             mCameraId);
    135     mCallbackProcessor->run(threadName.string());
    136 
    137     if (gLogLevel >= 1) {
    138         ALOGD("%s: Default parameters converted from camera %d:", __FUNCTION__,
    139               mCameraId);
    140         ALOGD("%s", l.mParameters.paramsFlattened.string());
    141     }
    142 
    143     return OK;
    144 }
    145 
    146 Camera2Client::~Camera2Client() {
    147     ATRACE_CALL();
    148     ALOGV("~Camera2Client");
    149 
    150     mDestructionStarted = true;
    151 
    152     disconnect();
    153 
    154     ALOGI("Camera %d: Closed", mCameraId);
    155 }
    156 
    157 status_t Camera2Client::dump(int fd, const Vector<String16>& args) {
    158     String8 result;
    159     result.appendFormat("Client2[%d] (%p) Client: %s PID: %d, dump:\n",
    160             mCameraId,
    161             getRemoteCallback()->asBinder().get(),
    162             String8(mClientPackageName).string(),
    163             mClientPid);
    164     result.append("  State: ");
    165 #define CASE_APPEND_ENUM(x) case x: result.append(#x "\n"); break;
    166 
    167     const Parameters& p = mParameters.unsafeAccess();
    168 
    169     result.append(Parameters::getStateName(p.state));
    170 
    171     result.append("\n  Current parameters:\n");
    172     result.appendFormat("    Preview size: %d x %d\n",
    173             p.previewWidth, p.previewHeight);
    174     result.appendFormat("    Preview FPS range: %d - %d\n",
    175             p.previewFpsRange[0], p.previewFpsRange[1]);
    176     result.appendFormat("    Preview HAL pixel format: 0x%x\n",
    177             p.previewFormat);
    178     result.appendFormat("    Preview transform: %x\n",
    179             p.previewTransform);
    180     result.appendFormat("    Picture size: %d x %d\n",
    181             p.pictureWidth, p.pictureHeight);
    182     result.appendFormat("    Jpeg thumbnail size: %d x %d\n",
    183             p.jpegThumbSize[0], p.jpegThumbSize[1]);
    184     result.appendFormat("    Jpeg quality: %d, thumbnail quality: %d\n",
    185             p.jpegQuality, p.jpegThumbQuality);
    186     result.appendFormat("    Jpeg rotation: %d\n", p.jpegRotation);
    187     result.appendFormat("    GPS tags %s\n",
    188             p.gpsEnabled ? "enabled" : "disabled");
    189     if (p.gpsEnabled) {
    190         result.appendFormat("    GPS lat x long x alt: %f x %f x %f\n",
    191                 p.gpsCoordinates[0], p.gpsCoordinates[1],
    192                 p.gpsCoordinates[2]);
    193         result.appendFormat("    GPS timestamp: %lld\n",
    194                 p.gpsTimestamp);
    195         result.appendFormat("    GPS processing method: %s\n",
    196                 p.gpsProcessingMethod.string());
    197     }
    198 
    199     result.append("    White balance mode: ");
    200     switch (p.wbMode) {
    201         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_AUTO)
    202         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_INCANDESCENT)
    203         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_FLUORESCENT)
    204         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_WARM_FLUORESCENT)
    205         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_DAYLIGHT)
    206         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_CLOUDY_DAYLIGHT)
    207         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_TWILIGHT)
    208         CASE_APPEND_ENUM(ANDROID_CONTROL_AWB_MODE_SHADE)
    209         default: result.append("UNKNOWN\n");
    210     }
    211 
    212     result.append("    Effect mode: ");
    213     switch (p.effectMode) {
    214         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_OFF)
    215         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_MONO)
    216         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_NEGATIVE)
    217         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SOLARIZE)
    218         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_SEPIA)
    219         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_POSTERIZE)
    220         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_WHITEBOARD)
    221         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_BLACKBOARD)
    222         CASE_APPEND_ENUM(ANDROID_CONTROL_EFFECT_MODE_AQUA)
    223         default: result.append("UNKNOWN\n");
    224     }
    225 
    226     result.append("    Antibanding mode: ");
    227     switch (p.antibandingMode) {
    228         CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_AUTO)
    229         CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_OFF)
    230         CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_50HZ)
    231         CASE_APPEND_ENUM(ANDROID_CONTROL_AE_ANTIBANDING_MODE_60HZ)
    232         default: result.append("UNKNOWN\n");
    233     }
    234 
    235     result.append("    Scene mode: ");
    236     switch (p.sceneMode) {
    237         case ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED:
    238             result.append("AUTO\n"); break;
    239         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_ACTION)
    240         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PORTRAIT)
    241         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_LANDSCAPE)
    242         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT)
    243         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_NIGHT_PORTRAIT)
    244         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_THEATRE)
    245         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BEACH)
    246         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SNOW)
    247         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SUNSET)
    248         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_STEADYPHOTO)
    249         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_FIREWORKS)
    250         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_SPORTS)
    251         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_PARTY)
    252         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_CANDLELIGHT)
    253         CASE_APPEND_ENUM(ANDROID_CONTROL_SCENE_MODE_BARCODE)
    254         default: result.append("UNKNOWN\n");
    255     }
    256 
    257     result.append("    Flash mode: ");
    258     switch (p.flashMode) {
    259         CASE_APPEND_ENUM(Parameters::FLASH_MODE_OFF)
    260         CASE_APPEND_ENUM(Parameters::FLASH_MODE_AUTO)
    261         CASE_APPEND_ENUM(Parameters::FLASH_MODE_ON)
    262         CASE_APPEND_ENUM(Parameters::FLASH_MODE_TORCH)
    263         CASE_APPEND_ENUM(Parameters::FLASH_MODE_RED_EYE)
    264         CASE_APPEND_ENUM(Parameters::FLASH_MODE_INVALID)
    265         default: result.append("UNKNOWN\n");
    266     }
    267 
    268     result.append("    Focus mode: ");
    269     switch (p.focusMode) {
    270         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_AUTO)
    271         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_MACRO)
    272         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_VIDEO)
    273         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_CONTINUOUS_PICTURE)
    274         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_EDOF)
    275         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INFINITY)
    276         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_FIXED)
    277         CASE_APPEND_ENUM(Parameters::FOCUS_MODE_INVALID)
    278         default: result.append("UNKNOWN\n");
    279     }
    280 
    281     result.append("   Focus state: ");
    282     switch (p.focusState) {
    283         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_INACTIVE)
    284         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN)
    285         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED)
    286         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED)
    287         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN)
    288         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED)
    289         CASE_APPEND_ENUM(ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED)
    290         default: result.append("UNKNOWN\n");
    291     }
    292 
    293     result.append("    Focusing areas:\n");
    294     for (size_t i = 0; i < p.focusingAreas.size(); i++) {
    295         result.appendFormat("      [ (%d, %d, %d, %d), weight %d ]\n",
    296                 p.focusingAreas[i].left,
    297                 p.focusingAreas[i].top,
    298                 p.focusingAreas[i].right,
    299                 p.focusingAreas[i].bottom,
    300                 p.focusingAreas[i].weight);
    301     }
    302 
    303     result.appendFormat("    Exposure compensation index: %d\n",
    304             p.exposureCompensation);
    305 
    306     result.appendFormat("    AE lock %s, AWB lock %s\n",
    307             p.autoExposureLock ? "enabled" : "disabled",
    308             p.autoWhiteBalanceLock ? "enabled" : "disabled" );
    309 
    310     result.appendFormat("    Metering areas:\n");
    311     for (size_t i = 0; i < p.meteringAreas.size(); i++) {
    312         result.appendFormat("      [ (%d, %d, %d, %d), weight %d ]\n",
    313                 p.meteringAreas[i].left,
    314                 p.meteringAreas[i].top,
    315                 p.meteringAreas[i].right,
    316                 p.meteringAreas[i].bottom,
    317                 p.meteringAreas[i].weight);
    318     }
    319 
    320     result.appendFormat("    Zoom index: %d\n", p.zoom);
    321     result.appendFormat("    Video size: %d x %d\n", p.videoWidth,
    322             p.videoHeight);
    323 
    324     result.appendFormat("    Recording hint is %s\n",
    325             p.recordingHint ? "set" : "not set");
    326 
    327     result.appendFormat("    Video stabilization is %s\n",
    328             p.videoStabilization ? "enabled" : "disabled");
    329 
    330     result.appendFormat("    Selected still capture FPS range: %d - %d\n",
    331             p.fastInfo.bestStillCaptureFpsRange[0],
    332             p.fastInfo.bestStillCaptureFpsRange[1]);
    333 
    334     result.append("  Current streams:\n");
    335     result.appendFormat("    Preview stream ID: %d\n",
    336             getPreviewStreamId());
    337     result.appendFormat("    Capture stream ID: %d\n",
    338             getCaptureStreamId());
    339     result.appendFormat("    Recording stream ID: %d\n",
    340             getRecordingStreamId());
    341 
    342     result.append("  Quirks for this camera:\n");
    343     bool haveQuirk = false;
    344     if (p.quirks.triggerAfWithAuto) {
    345         result.appendFormat("    triggerAfWithAuto\n");
    346         haveQuirk = true;
    347     }
    348     if (p.quirks.useZslFormat) {
    349         result.appendFormat("    useZslFormat\n");
    350         haveQuirk = true;
    351     }
    352     if (p.quirks.meteringCropRegion) {
    353         result.appendFormat("    meteringCropRegion\n");
    354         haveQuirk = true;
    355     }
    356     if (!haveQuirk) {
    357         result.appendFormat("    none\n");
    358     }
    359 
    360     write(fd, result.string(), result.size());
    361 
    362     mStreamingProcessor->dump(fd, args);
    363 
    364     mCaptureSequencer->dump(fd, args);
    365 
    366     mFrameProcessor->dump(fd, args);
    367 
    368     mZslProcessor->dump(fd, args);
    369 
    370     return dumpDevice(fd, args);
    371 #undef CASE_APPEND_ENUM
    372 }
    373 
    374 // ICamera interface
    375 
    376 void Camera2Client::disconnect() {
    377     ATRACE_CALL();
    378     Mutex::Autolock icl(mBinderSerializationLock);
    379 
    380     // Allow both client and the media server to disconnect at all times
    381     int callingPid = getCallingPid();
    382     if (callingPid != mClientPid && callingPid != mServicePid) return;
    383 
    384     if (mDevice == 0) return;
    385 
    386     ALOGV("Camera %d: Shutting down", mCameraId);
    387 
    388     /**
    389      * disconnect() cannot call any methods that might need to promote a
    390      * wp<Camera2Client>, since disconnect can be called from the destructor, at
    391      * which point all such promotions will fail.
    392      */
    393 
    394     stopPreviewL();
    395 
    396     {
    397         SharedParameters::Lock l(mParameters);
    398         if (l.mParameters.state == Parameters::DISCONNECTED) return;
    399         l.mParameters.state = Parameters::DISCONNECTED;
    400     }
    401 
    402     mStreamingProcessor->deletePreviewStream();
    403     mStreamingProcessor->deleteRecordingStream();
    404     mJpegProcessor->deleteStream();
    405     mCallbackProcessor->deleteStream();
    406     mZslProcessor->deleteStream();
    407 
    408     mStreamingProcessor->requestExit();
    409     mFrameProcessor->requestExit();
    410     mCaptureSequencer->requestExit();
    411     mJpegProcessor->requestExit();
    412     mZslProcessorThread->requestExit();
    413     mCallbackProcessor->requestExit();
    414 
    415     ALOGV("Camera %d: Waiting for threads", mCameraId);
    416 
    417     mStreamingProcessor->join();
    418     mFrameProcessor->join();
    419     mCaptureSequencer->join();
    420     mJpegProcessor->join();
    421     mZslProcessorThread->join();
    422     mCallbackProcessor->join();
    423 
    424     ALOGV("Camera %d: Disconnecting device", mCameraId);
    425 
    426     mDevice->disconnect();
    427 
    428     mDevice.clear();
    429 
    430     CameraService::Client::disconnect();
    431 }
    432 
    433 status_t Camera2Client::connect(const sp<ICameraClient>& client) {
    434     ATRACE_CALL();
    435     ALOGV("%s: E", __FUNCTION__);
    436     Mutex::Autolock icl(mBinderSerializationLock);
    437 
    438     if (mClientPid != 0 && getCallingPid() != mClientPid) {
    439         ALOGE("%s: Camera %d: Connection attempt from pid %d; "
    440                 "current locked to pid %d", __FUNCTION__,
    441                 mCameraId, getCallingPid(), mClientPid);
    442         return BAD_VALUE;
    443     }
    444 
    445     mClientPid = getCallingPid();
    446 
    447     mRemoteCallback = client;
    448     mSharedCameraCallbacks = client;
    449 
    450     return OK;
    451 }
    452 
    453 status_t Camera2Client::lock() {
    454     ATRACE_CALL();
    455     ALOGV("%s: E", __FUNCTION__);
    456     Mutex::Autolock icl(mBinderSerializationLock);
    457     ALOGV("%s: Camera %d: Lock call from pid %d; current client pid %d",
    458             __FUNCTION__, mCameraId, getCallingPid(), mClientPid);
    459 
    460     if (mClientPid == 0) {
    461         mClientPid = getCallingPid();
    462         return OK;
    463     }
    464 
    465     if (mClientPid != getCallingPid()) {
    466         ALOGE("%s: Camera %d: Lock call from pid %d; currently locked to pid %d",
    467                 __FUNCTION__, mCameraId, getCallingPid(), mClientPid);
    468         return EBUSY;
    469     }
    470 
    471     return OK;
    472 }
    473 
    474 status_t Camera2Client::unlock() {
    475     ATRACE_CALL();
    476     ALOGV("%s: E", __FUNCTION__);
    477     Mutex::Autolock icl(mBinderSerializationLock);
    478     ALOGV("%s: Camera %d: Unlock call from pid %d; current client pid %d",
    479             __FUNCTION__, mCameraId, getCallingPid(), mClientPid);
    480 
    481     if (mClientPid == getCallingPid()) {
    482         SharedParameters::Lock l(mParameters);
    483         if (l.mParameters.state == Parameters::RECORD ||
    484                 l.mParameters.state == Parameters::VIDEO_SNAPSHOT) {
    485             ALOGD("Not allowed to unlock camera during recording.");
    486             return INVALID_OPERATION;
    487         }
    488         mClientPid = 0;
    489         mRemoteCallback.clear();
    490         mSharedCameraCallbacks.clear();
    491         return OK;
    492     }
    493 
    494     ALOGE("%s: Camera %d: Unlock call from pid %d; currently locked to pid %d",
    495             __FUNCTION__, mCameraId, getCallingPid(), mClientPid);
    496     return EBUSY;
    497 }
    498 
    499 status_t Camera2Client::setPreviewTarget(
    500         const sp<IGraphicBufferProducer>& bufferProducer) {
    501     ATRACE_CALL();
    502     ALOGV("%s: E", __FUNCTION__);
    503     Mutex::Autolock icl(mBinderSerializationLock);
    504     status_t res;
    505     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
    506 
    507     sp<IBinder> binder;
    508     sp<ANativeWindow> window;
    509     if (bufferProducer != 0) {
    510         binder = bufferProducer->asBinder();
    511         // Using controlledByApp flag to ensure that the buffer queue remains in
    512         // async mode for the old camera API, where many applications depend
    513         // on that behavior.
    514         window = new Surface(bufferProducer, /*controlledByApp*/ true);
    515     }
    516     return setPreviewWindowL(binder, window);
    517 }
    518 
    519 status_t Camera2Client::setPreviewWindowL(const sp<IBinder>& binder,
    520         sp<ANativeWindow> window) {
    521     ATRACE_CALL();
    522     status_t res;
    523 
    524     if (binder == mPreviewSurface) {
    525         ALOGV("%s: Camera %d: New window is same as old window",
    526                 __FUNCTION__, mCameraId);
    527         return NO_ERROR;
    528     }
    529 
    530     Parameters::State state;
    531     {
    532         SharedParameters::Lock l(mParameters);
    533         state = l.mParameters.state;
    534     }
    535     switch (state) {
    536         case Parameters::DISCONNECTED:
    537         case Parameters::RECORD:
    538         case Parameters::STILL_CAPTURE:
    539         case Parameters::VIDEO_SNAPSHOT:
    540             ALOGE("%s: Camera %d: Cannot set preview display while in state %s",
    541                     __FUNCTION__, mCameraId,
    542                     Parameters::getStateName(state));
    543             return INVALID_OPERATION;
    544         case Parameters::STOPPED:
    545         case Parameters::WAITING_FOR_PREVIEW_WINDOW:
    546             // OK
    547             break;
    548         case Parameters::PREVIEW:
    549             // Already running preview - need to stop and create a new stream
    550             res = stopStream();
    551             if (res != OK) {
    552                 ALOGE("%s: Unable to stop preview to swap windows: %s (%d)",
    553                         __FUNCTION__, strerror(-res), res);
    554                 return res;
    555             }
    556             state = Parameters::WAITING_FOR_PREVIEW_WINDOW;
    557             break;
    558     }
    559 
    560     mPreviewSurface = binder;
    561     res = mStreamingProcessor->setPreviewWindow(window);
    562     if (res != OK) {
    563         ALOGE("%s: Unable to set new preview window: %s (%d)",
    564                 __FUNCTION__, strerror(-res), res);
    565         return res;
    566     }
    567 
    568     if (state == Parameters::WAITING_FOR_PREVIEW_WINDOW) {
    569         SharedParameters::Lock l(mParameters);
    570         l.mParameters.state = state;
    571         return startPreviewL(l.mParameters, false);
    572     }
    573 
    574     return OK;
    575 }
    576 
    577 void Camera2Client::setPreviewCallbackFlag(int flag) {
    578     ATRACE_CALL();
    579     ALOGV("%s: Camera %d: Flag 0x%x", __FUNCTION__, mCameraId, flag);
    580     Mutex::Autolock icl(mBinderSerializationLock);
    581 
    582     if ( checkPid(__FUNCTION__) != OK) return;
    583 
    584     SharedParameters::Lock l(mParameters);
    585     setPreviewCallbackFlagL(l.mParameters, flag);
    586 }
    587 
    588 void Camera2Client::setPreviewCallbackFlagL(Parameters &params, int flag) {
    589     status_t res = OK;
    590 
    591     switch(params.state) {
    592         case Parameters::STOPPED:
    593         case Parameters::WAITING_FOR_PREVIEW_WINDOW:
    594         case Parameters::PREVIEW:
    595         case Parameters::STILL_CAPTURE:
    596             // OK
    597             break;
    598         default:
    599             if (flag & CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK) {
    600                 ALOGE("%s: Camera %d: Can't use preview callbacks "
    601                         "in state %d", __FUNCTION__, mCameraId, params.state);
    602                 return;
    603             }
    604     }
    605 
    606     if (flag & CAMERA_FRAME_CALLBACK_FLAG_ONE_SHOT_MASK) {
    607         ALOGV("%s: setting oneshot", __FUNCTION__);
    608         params.previewCallbackOneShot = true;
    609     }
    610     if (params.previewCallbackFlags != (uint32_t)flag) {
    611 
    612         if (params.previewCallbackSurface && flag != CAMERA_FRAME_CALLBACK_FLAG_NOOP) {
    613             // Disable any existing preview callback window when enabling
    614             // preview callback flags
    615             res = mCallbackProcessor->setCallbackWindow(NULL);
    616             if (res != OK) {
    617                 ALOGE("%s: Camera %d: Unable to clear preview callback surface:"
    618                         " %s (%d)", __FUNCTION__, mCameraId, strerror(-res), res);
    619                 return;
    620             }
    621             params.previewCallbackSurface = false;
    622         }
    623 
    624         params.previewCallbackFlags = flag;
    625 
    626         if (params.state == Parameters::PREVIEW) {
    627             res = startPreviewL(params, true);
    628             if (res != OK) {
    629                 ALOGE("%s: Camera %d: Unable to refresh request in state %s",
    630                         __FUNCTION__, mCameraId,
    631                         Parameters::getStateName(params.state));
    632             }
    633         }
    634     }
    635 }
    636 
    637 status_t Camera2Client::setPreviewCallbackTarget(
    638         const sp<IGraphicBufferProducer>& callbackProducer) {
    639     ATRACE_CALL();
    640     ALOGV("%s: E", __FUNCTION__);
    641     Mutex::Autolock icl(mBinderSerializationLock);
    642     status_t res;
    643     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
    644 
    645     sp<ANativeWindow> window;
    646     if (callbackProducer != 0) {
    647         window = new Surface(callbackProducer);
    648     }
    649 
    650     res = mCallbackProcessor->setCallbackWindow(window);
    651     if (res != OK) {
    652         ALOGE("%s: Camera %d: Unable to set preview callback surface: %s (%d)",
    653                 __FUNCTION__, mCameraId, strerror(-res), res);
    654         return res;
    655     }
    656 
    657     SharedParameters::Lock l(mParameters);
    658 
    659     if (window != NULL) {
    660         // Disable traditional callbacks when a valid callback target is given
    661         l.mParameters.previewCallbackFlags = CAMERA_FRAME_CALLBACK_FLAG_NOOP;
    662         l.mParameters.previewCallbackOneShot = false;
    663         l.mParameters.previewCallbackSurface = true;
    664     } else {
    665         // Disable callback target if given a NULL interface.
    666         l.mParameters.previewCallbackSurface = false;
    667     }
    668 
    669     switch(l.mParameters.state) {
    670         case Parameters::PREVIEW:
    671             res = startPreviewL(l.mParameters, true);
    672             break;
    673         case Parameters::RECORD:
    674         case Parameters::VIDEO_SNAPSHOT:
    675             res = startRecordingL(l.mParameters, true);
    676             break;
    677         default:
    678             break;
    679     }
    680     if (res != OK) {
    681         ALOGE("%s: Camera %d: Unable to refresh request in state %s",
    682                 __FUNCTION__, mCameraId,
    683                 Parameters::getStateName(l.mParameters.state));
    684     }
    685 
    686     return OK;
    687 }
    688 
    689 
    690 status_t Camera2Client::startPreview() {
    691     ATRACE_CALL();
    692     ALOGV("%s: E", __FUNCTION__);
    693     Mutex::Autolock icl(mBinderSerializationLock);
    694     status_t res;
    695     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
    696     SharedParameters::Lock l(mParameters);
    697     return startPreviewL(l.mParameters, false);
    698 }
    699 
    700 status_t Camera2Client::startPreviewL(Parameters &params, bool restart) {
    701     ATRACE_CALL();
    702     status_t res;
    703 
    704     ALOGV("%s: state == %d, restart = %d", __FUNCTION__, params.state, restart);
    705 
    706     if ( (params.state == Parameters::PREVIEW ||
    707                     params.state == Parameters::RECORD ||
    708                     params.state == Parameters::VIDEO_SNAPSHOT)
    709             && !restart) {
    710         // Succeed attempt to re-enter a streaming state
    711         ALOGI("%s: Camera %d: Preview already active, ignoring restart",
    712                 __FUNCTION__, mCameraId);
    713         return OK;
    714     }
    715     if (params.state > Parameters::PREVIEW && !restart) {
    716         ALOGE("%s: Can't start preview in state %s",
    717                 __FUNCTION__,
    718                 Parameters::getStateName(params.state));
    719         return INVALID_OPERATION;
    720     }
    721 
    722     if (!mStreamingProcessor->haveValidPreviewWindow()) {
    723         params.state = Parameters::WAITING_FOR_PREVIEW_WINDOW;
    724         return OK;
    725     }
    726     params.state = Parameters::STOPPED;
    727 
    728     res = mStreamingProcessor->updatePreviewStream(params);
    729     if (res != OK) {
    730         ALOGE("%s: Camera %d: Unable to update preview stream: %s (%d)",
    731                 __FUNCTION__, mCameraId, strerror(-res), res);
    732         return res;
    733     }
    734 
    735     // We could wait to create the JPEG output stream until first actual use
    736     // (first takePicture call). However, this would substantially increase the
    737     // first capture latency on HAL3 devices, and potentially on some HAL2
    738     // devices. So create it unconditionally at preview start. As a drawback,
    739     // this increases gralloc memory consumption for applications that don't
    740     // ever take a picture.
    741     // TODO: Find a better compromise, though this likely would involve HAL
    742     // changes.
    743     res = updateProcessorStream(mJpegProcessor, params);
    744     if (res != OK) {
    745         ALOGE("%s: Camera %d: Can't pre-configure still image "
    746                 "stream: %s (%d)",
    747                 __FUNCTION__, mCameraId, strerror(-res), res);
    748         return res;
    749     }
    750 
    751     Vector<int32_t> outputStreams;
    752     bool callbacksEnabled = (params.previewCallbackFlags &
    753             CAMERA_FRAME_CALLBACK_FLAG_ENABLE_MASK) ||
    754             params.previewCallbackSurface;
    755 
    756     if (callbacksEnabled) {
    757         // Can't have recording stream hanging around when enabling callbacks,
    758         // since it exceeds the max stream count on some devices.
    759         if (mStreamingProcessor->getRecordingStreamId() != NO_STREAM) {
    760             ALOGV("%s: Camera %d: Clearing out recording stream before "
    761                     "creating callback stream", __FUNCTION__, mCameraId);
    762             res = mStreamingProcessor->stopStream();
    763             if (res != OK) {
    764                 ALOGE("%s: Camera %d: Can't stop streaming to delete "
    765                         "recording stream", __FUNCTION__, mCameraId);
    766                 return res;
    767             }
    768             res = mStreamingProcessor->deleteRecordingStream();
    769             if (res != OK) {
    770                 ALOGE("%s: Camera %d: Unable to delete recording stream before "
    771                         "enabling callbacks: %s (%d)", __FUNCTION__, mCameraId,
    772                         strerror(-res), res);
    773                 return res;
    774             }
    775         }
    776 
    777         res = mCallbackProcessor->updateStream(params);
    778         if (res != OK) {
    779             ALOGE("%s: Camera %d: Unable to update callback stream: %s (%d)",
    780                     __FUNCTION__, mCameraId, strerror(-res), res);
    781             return res;
    782         }
    783         outputStreams.push(getCallbackStreamId());
    784     }
    785     if (params.zslMode && !params.recordingHint) {
    786         res = updateProcessorStream(mZslProcessor, params);
    787         if (res != OK) {
    788             ALOGE("%s: Camera %d: Unable to update ZSL stream: %s (%d)",
    789                     __FUNCTION__, mCameraId, strerror(-res), res);
    790             return res;
    791         }
    792         outputStreams.push(getZslStreamId());
    793     }
    794 
    795     outputStreams.push(getPreviewStreamId());
    796 
    797     if (!params.recordingHint) {
    798         if (!restart) {
    799             res = mStreamingProcessor->updatePreviewRequest(params);
    800             if (res != OK) {
    801                 ALOGE("%s: Camera %d: Can't set up preview request: "
    802                         "%s (%d)", __FUNCTION__, mCameraId,
    803                         strerror(-res), res);
    804                 return res;
    805             }
    806         }
    807         res = mStreamingProcessor->startStream(StreamingProcessor::PREVIEW,
    808                 outputStreams);
    809     } else {
    810         if (!restart) {
    811             res = mStreamingProcessor->updateRecordingRequest(params);
    812             if (res != OK) {
    813                 ALOGE("%s: Camera %d: Can't set up preview request with "
    814                         "record hint: %s (%d)", __FUNCTION__, mCameraId,
    815                         strerror(-res), res);
    816                 return res;
    817             }
    818         }
    819         res = mStreamingProcessor->startStream(StreamingProcessor::RECORD,
    820                 outputStreams);
    821     }
    822     if (res != OK) {
    823         ALOGE("%s: Camera %d: Unable to start streaming preview: %s (%d)",
    824                 __FUNCTION__, mCameraId, strerror(-res), res);
    825         return res;
    826     }
    827 
    828     params.state = Parameters::PREVIEW;
    829     return OK;
    830 }
    831 
    832 void Camera2Client::stopPreview() {
    833     ATRACE_CALL();
    834     ALOGV("%s: E", __FUNCTION__);
    835     Mutex::Autolock icl(mBinderSerializationLock);
    836     status_t res;
    837     if ( (res = checkPid(__FUNCTION__) ) != OK) return;
    838     stopPreviewL();
    839 }
    840 
    841 void Camera2Client::stopPreviewL() {
    842     ATRACE_CALL();
    843     status_t res;
    844     const nsecs_t kStopCaptureTimeout = 3000000000LL; // 3 seconds
    845     Parameters::State state;
    846     {
    847         SharedParameters::Lock l(mParameters);
    848         state = l.mParameters.state;
    849     }
    850 
    851     switch (state) {
    852         case Parameters::DISCONNECTED:
    853             // Nothing to do.
    854             break;
    855         case Parameters::STOPPED:
    856         case Parameters::VIDEO_SNAPSHOT:
    857         case Parameters::STILL_CAPTURE:
    858             mCaptureSequencer->waitUntilIdle(kStopCaptureTimeout);
    859             // no break
    860         case Parameters::RECORD:
    861         case Parameters::PREVIEW:
    862             syncWithDevice();
    863             res = stopStream();
    864             if (res != OK) {
    865                 ALOGE("%s: Camera %d: Can't stop streaming: %s (%d)",
    866                         __FUNCTION__, mCameraId, strerror(-res), res);
    867             }
    868             res = mDevice->waitUntilDrained();
    869             if (res != OK) {
    870                 ALOGE("%s: Camera %d: Waiting to stop streaming failed: %s (%d)",
    871                         __FUNCTION__, mCameraId, strerror(-res), res);
    872             }
    873             // no break
    874         case Parameters::WAITING_FOR_PREVIEW_WINDOW: {
    875             SharedParameters::Lock l(mParameters);
    876             l.mParameters.state = Parameters::STOPPED;
    877             commandStopFaceDetectionL(l.mParameters);
    878             break;
    879         }
    880         default:
    881             ALOGE("%s: Camera %d: Unknown state %d", __FUNCTION__, mCameraId,
    882                     state);
    883     }
    884 }
    885 
    886 bool Camera2Client::previewEnabled() {
    887     ATRACE_CALL();
    888     Mutex::Autolock icl(mBinderSerializationLock);
    889     status_t res;
    890     if ( (res = checkPid(__FUNCTION__) ) != OK) return false;
    891 
    892     SharedParameters::Lock l(mParameters);
    893     return l.mParameters.state == Parameters::PREVIEW;
    894 }
    895 
    896 status_t Camera2Client::storeMetaDataInBuffers(bool enabled) {
    897     ATRACE_CALL();
    898     Mutex::Autolock icl(mBinderSerializationLock);
    899     status_t res;
    900     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
    901 
    902     SharedParameters::Lock l(mParameters);
    903     switch (l.mParameters.state) {
    904         case Parameters::RECORD:
    905         case Parameters::VIDEO_SNAPSHOT:
    906             ALOGE("%s: Camera %d: Can't be called in state %s",
    907                     __FUNCTION__, mCameraId,
    908                     Parameters::getStateName(l.mParameters.state));
    909             return INVALID_OPERATION;
    910         default:
    911             // OK
    912             break;
    913     }
    914 
    915     l.mParameters.storeMetadataInBuffers = enabled;
    916 
    917     return OK;
    918 }
    919 
    920 status_t Camera2Client::startRecording() {
    921     ATRACE_CALL();
    922     ALOGV("%s: E", __FUNCTION__);
    923     Mutex::Autolock icl(mBinderSerializationLock);
    924     status_t res;
    925     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
    926     SharedParameters::Lock l(mParameters);
    927 
    928     return startRecordingL(l.mParameters, false);
    929 }
    930 
    931 status_t Camera2Client::startRecordingL(Parameters &params, bool restart) {
    932     status_t res;
    933 
    934     ALOGV("%s: state == %d, restart = %d", __FUNCTION__, params.state, restart);
    935 
    936     switch (params.state) {
    937         case Parameters::STOPPED:
    938             res = startPreviewL(params, false);
    939             if (res != OK) return res;
    940             break;
    941         case Parameters::PREVIEW:
    942             // Ready to go
    943             break;
    944         case Parameters::RECORD:
    945         case Parameters::VIDEO_SNAPSHOT:
    946             // OK to call this when recording is already on, just skip unless
    947             // we're looking to restart
    948             if (!restart) return OK;
    949             break;
    950         default:
    951             ALOGE("%s: Camera %d: Can't start recording in state %s",
    952                     __FUNCTION__, mCameraId,
    953                     Parameters::getStateName(params.state));
    954             return INVALID_OPERATION;
    955     };
    956 
    957     if (!params.storeMetadataInBuffers) {
    958         ALOGE("%s: Camera %d: Recording only supported in metadata mode, but "
    959                 "non-metadata recording mode requested!", __FUNCTION__,
    960                 mCameraId);
    961         return INVALID_OPERATION;
    962     }
    963 
    964     if (!restart) {
    965         mCameraService->playSound(CameraService::SOUND_RECORDING);
    966         mStreamingProcessor->updateRecordingRequest(params);
    967         if (res != OK) {
    968             ALOGE("%s: Camera %d: Unable to update recording request: %s (%d)",
    969                     __FUNCTION__, mCameraId, strerror(-res), res);
    970             return res;
    971         }
    972     }
    973 
    974     // Not all devices can support a preview callback stream and a recording
    975     // stream at the same time, so assume none of them can.
    976     if (mCallbackProcessor->getStreamId() != NO_STREAM) {
    977         ALOGV("%s: Camera %d: Clearing out callback stream before "
    978                 "creating recording stream", __FUNCTION__, mCameraId);
    979         res = mStreamingProcessor->stopStream();
    980         if (res != OK) {
    981             ALOGE("%s: Camera %d: Can't stop streaming to delete callback stream",
    982                     __FUNCTION__, mCameraId);
    983             return res;
    984         }
    985         res = mCallbackProcessor->deleteStream();
    986         if (res != OK) {
    987             ALOGE("%s: Camera %d: Unable to delete callback stream before "
    988                     "record: %s (%d)", __FUNCTION__, mCameraId,
    989                     strerror(-res), res);
    990             return res;
    991         }
    992     }
    993     // Disable callbacks if they're enabled; can't record and use callbacks,
    994     // and we can't fail record start without stagefright asserting.
    995     params.previewCallbackFlags = 0;
    996 
    997     res = updateProcessorStream<
    998             StreamingProcessor,
    999             &StreamingProcessor::updateRecordingStream>(mStreamingProcessor,
   1000                                                         params);
   1001     if (res != OK) {
   1002         ALOGE("%s: Camera %d: Unable to update recording stream: %s (%d)",
   1003                 __FUNCTION__, mCameraId, strerror(-res), res);
   1004         return res;
   1005     }
   1006 
   1007     Vector<int32_t> outputStreams;
   1008     outputStreams.push(getPreviewStreamId());
   1009     outputStreams.push(getRecordingStreamId());
   1010 
   1011     res = mStreamingProcessor->startStream(StreamingProcessor::RECORD,
   1012             outputStreams);
   1013     if (res != OK) {
   1014         ALOGE("%s: Camera %d: Unable to start recording stream: %s (%d)",
   1015                 __FUNCTION__, mCameraId, strerror(-res), res);
   1016         return res;
   1017     }
   1018 
   1019     if (params.state < Parameters::RECORD) {
   1020         params.state = Parameters::RECORD;
   1021     }
   1022 
   1023     return OK;
   1024 }
   1025 
   1026 void Camera2Client::stopRecording() {
   1027     ATRACE_CALL();
   1028     ALOGV("%s: E", __FUNCTION__);
   1029     Mutex::Autolock icl(mBinderSerializationLock);
   1030     SharedParameters::Lock l(mParameters);
   1031 
   1032     status_t res;
   1033     if ( (res = checkPid(__FUNCTION__) ) != OK) return;
   1034 
   1035     switch (l.mParameters.state) {
   1036         case Parameters::RECORD:
   1037             // OK to stop
   1038             break;
   1039         case Parameters::STOPPED:
   1040         case Parameters::PREVIEW:
   1041         case Parameters::STILL_CAPTURE:
   1042         case Parameters::VIDEO_SNAPSHOT:
   1043         default:
   1044             ALOGE("%s: Camera %d: Can't stop recording in state %s",
   1045                     __FUNCTION__, mCameraId,
   1046                     Parameters::getStateName(l.mParameters.state));
   1047             return;
   1048     };
   1049 
   1050     mCameraService->playSound(CameraService::SOUND_RECORDING);
   1051 
   1052     res = startPreviewL(l.mParameters, true);
   1053     if (res != OK) {
   1054         ALOGE("%s: Camera %d: Unable to return to preview",
   1055                 __FUNCTION__, mCameraId);
   1056     }
   1057 }
   1058 
   1059 bool Camera2Client::recordingEnabled() {
   1060     ATRACE_CALL();
   1061     Mutex::Autolock icl(mBinderSerializationLock);
   1062 
   1063     if ( checkPid(__FUNCTION__) != OK) return false;
   1064 
   1065     return recordingEnabledL();
   1066 }
   1067 
   1068 bool Camera2Client::recordingEnabledL() {
   1069     ATRACE_CALL();
   1070     SharedParameters::Lock l(mParameters);
   1071 
   1072     return (l.mParameters.state == Parameters::RECORD
   1073             || l.mParameters.state == Parameters::VIDEO_SNAPSHOT);
   1074 }
   1075 
   1076 void Camera2Client::releaseRecordingFrame(const sp<IMemory>& mem) {
   1077     ATRACE_CALL();
   1078     Mutex::Autolock icl(mBinderSerializationLock);
   1079     if ( checkPid(__FUNCTION__) != OK) return;
   1080 
   1081     mStreamingProcessor->releaseRecordingFrame(mem);
   1082 }
   1083 
   1084 status_t Camera2Client::autoFocus() {
   1085     ATRACE_CALL();
   1086     Mutex::Autolock icl(mBinderSerializationLock);
   1087     ALOGV("%s: Camera %d", __FUNCTION__, mCameraId);
   1088     status_t res;
   1089     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
   1090 
   1091     int triggerId;
   1092     bool notifyImmediately = false;
   1093     bool notifySuccess = false;
   1094     {
   1095         SharedParameters::Lock l(mParameters);
   1096         if (l.mParameters.state < Parameters::PREVIEW) {
   1097             return INVALID_OPERATION;
   1098         }
   1099 
   1100         /**
   1101           * If the camera does not support auto-focus, it is a no-op and
   1102           * onAutoFocus(boolean, Camera) callback will be called immediately
   1103           * with a fake value of success set to true.
   1104           *
   1105           * Similarly, if focus mode is set to INFINITY, there's no reason to
   1106           * bother the HAL.
   1107           */
   1108         if (l.mParameters.focusMode == Parameters::FOCUS_MODE_FIXED ||
   1109                 l.mParameters.focusMode == Parameters::FOCUS_MODE_INFINITY) {
   1110             notifyImmediately = true;
   1111             notifySuccess = true;
   1112         }
   1113         /**
   1114          * If we're in CAF mode, and AF has already been locked, just fire back
   1115          * the callback right away; the HAL would not send a notification since
   1116          * no state change would happen on a AF trigger.
   1117          */
   1118         if ( (l.mParameters.focusMode == Parameters::FOCUS_MODE_CONTINUOUS_PICTURE ||
   1119                 l.mParameters.focusMode == Parameters::FOCUS_MODE_CONTINUOUS_VIDEO) &&
   1120                 l.mParameters.focusState == ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED ) {
   1121             notifyImmediately = true;
   1122             notifySuccess = true;
   1123         }
   1124         /**
   1125          * Send immediate notification back to client
   1126          */
   1127         if (notifyImmediately) {
   1128             SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);
   1129             if (l.mRemoteCallback != 0) {
   1130                 l.mRemoteCallback->notifyCallback(CAMERA_MSG_FOCUS,
   1131                         notifySuccess ? 1 : 0, 0);
   1132             }
   1133             return OK;
   1134         }
   1135         /**
   1136          * Handle quirk mode for AF in scene modes
   1137          */
   1138         if (l.mParameters.quirks.triggerAfWithAuto &&
   1139                 l.mParameters.sceneMode != ANDROID_CONTROL_SCENE_MODE_UNSUPPORTED &&
   1140                 l.mParameters.focusMode != Parameters::FOCUS_MODE_AUTO &&
   1141                 !l.mParameters.focusingAreas[0].isEmpty()) {
   1142             ALOGV("%s: Quirk: Switching from focusMode %d to AUTO",
   1143                     __FUNCTION__, l.mParameters.focusMode);
   1144             l.mParameters.shadowFocusMode = l.mParameters.focusMode;
   1145             l.mParameters.focusMode = Parameters::FOCUS_MODE_AUTO;
   1146             updateRequests(l.mParameters);
   1147         }
   1148 
   1149         l.mParameters.currentAfTriggerId = ++l.mParameters.afTriggerCounter;
   1150         triggerId = l.mParameters.currentAfTriggerId;
   1151     }
   1152     ATRACE_ASYNC_BEGIN(kAutofocusLabel, triggerId);
   1153 
   1154     syncWithDevice();
   1155 
   1156     mDevice->triggerAutofocus(triggerId);
   1157 
   1158     return OK;
   1159 }
   1160 
   1161 status_t Camera2Client::cancelAutoFocus() {
   1162     ATRACE_CALL();
   1163     Mutex::Autolock icl(mBinderSerializationLock);
   1164     ALOGV("%s: Camera %d", __FUNCTION__, mCameraId);
   1165     status_t res;
   1166     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
   1167 
   1168     int triggerId;
   1169     {
   1170         SharedParameters::Lock l(mParameters);
   1171         // Canceling does nothing in FIXED or INFINITY modes
   1172         if (l.mParameters.focusMode == Parameters::FOCUS_MODE_FIXED ||
   1173                 l.mParameters.focusMode == Parameters::FOCUS_MODE_INFINITY) {
   1174             return OK;
   1175         }
   1176 
   1177         // An active AF trigger is canceled
   1178         if (l.mParameters.afTriggerCounter == l.mParameters.currentAfTriggerId) {
   1179             ATRACE_ASYNC_END(kAutofocusLabel, l.mParameters.currentAfTriggerId);
   1180         }
   1181 
   1182         triggerId = ++l.mParameters.afTriggerCounter;
   1183 
   1184         // When using triggerAfWithAuto quirk, may need to reset focus mode to
   1185         // the real state at this point. No need to cancel explicitly if
   1186         // changing the AF mode.
   1187         if (l.mParameters.shadowFocusMode != Parameters::FOCUS_MODE_INVALID) {
   1188             ALOGV("%s: Quirk: Restoring focus mode to %d", __FUNCTION__,
   1189                     l.mParameters.shadowFocusMode);
   1190             l.mParameters.focusMode = l.mParameters.shadowFocusMode;
   1191             l.mParameters.shadowFocusMode = Parameters::FOCUS_MODE_INVALID;
   1192             updateRequests(l.mParameters);
   1193 
   1194             return OK;
   1195         }
   1196     }
   1197     syncWithDevice();
   1198 
   1199     mDevice->triggerCancelAutofocus(triggerId);
   1200 
   1201     return OK;
   1202 }
   1203 
   1204 status_t Camera2Client::takePicture(int msgType) {
   1205     ATRACE_CALL();
   1206     Mutex::Autolock icl(mBinderSerializationLock);
   1207     status_t res;
   1208     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
   1209 
   1210     int takePictureCounter;
   1211     {
   1212         SharedParameters::Lock l(mParameters);
   1213         switch (l.mParameters.state) {
   1214             case Parameters::DISCONNECTED:
   1215             case Parameters::STOPPED:
   1216             case Parameters::WAITING_FOR_PREVIEW_WINDOW:
   1217                 ALOGE("%s: Camera %d: Cannot take picture without preview enabled",
   1218                         __FUNCTION__, mCameraId);
   1219                 return INVALID_OPERATION;
   1220             case Parameters::PREVIEW:
   1221                 // Good to go for takePicture
   1222                 res = commandStopFaceDetectionL(l.mParameters);
   1223                 if (res != OK) {
   1224                     ALOGE("%s: Camera %d: Unable to stop face detection for still capture",
   1225                             __FUNCTION__, mCameraId);
   1226                     return res;
   1227                 }
   1228                 l.mParameters.state = Parameters::STILL_CAPTURE;
   1229                 break;
   1230             case Parameters::RECORD:
   1231                 // Good to go for video snapshot
   1232                 l.mParameters.state = Parameters::VIDEO_SNAPSHOT;
   1233                 break;
   1234             case Parameters::STILL_CAPTURE:
   1235             case Parameters::VIDEO_SNAPSHOT:
   1236                 ALOGE("%s: Camera %d: Already taking a picture",
   1237                         __FUNCTION__, mCameraId);
   1238                 return INVALID_OPERATION;
   1239         }
   1240 
   1241         ALOGV("%s: Camera %d: Starting picture capture", __FUNCTION__, mCameraId);
   1242 
   1243         res = updateProcessorStream(mJpegProcessor, l.mParameters);
   1244         if (res != OK) {
   1245             ALOGE("%s: Camera %d: Can't set up still image stream: %s (%d)",
   1246                     __FUNCTION__, mCameraId, strerror(-res), res);
   1247             return res;
   1248         }
   1249         takePictureCounter = ++l.mParameters.takePictureCounter;
   1250     }
   1251 
   1252     ATRACE_ASYNC_BEGIN(kTakepictureLabel, takePictureCounter);
   1253 
   1254     // Need HAL to have correct settings before (possibly) triggering precapture
   1255     syncWithDevice();
   1256 
   1257     res = mCaptureSequencer->startCapture(msgType);
   1258     if (res != OK) {
   1259         ALOGE("%s: Camera %d: Unable to start capture: %s (%d)",
   1260                 __FUNCTION__, mCameraId, strerror(-res), res);
   1261     }
   1262 
   1263     return res;
   1264 }
   1265 
   1266 status_t Camera2Client::setParameters(const String8& params) {
   1267     ATRACE_CALL();
   1268     ALOGV("%s: Camera %d", __FUNCTION__, mCameraId);
   1269     Mutex::Autolock icl(mBinderSerializationLock);
   1270     status_t res;
   1271     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
   1272 
   1273     SharedParameters::Lock l(mParameters);
   1274 
   1275     res = l.mParameters.set(params);
   1276     if (res != OK) return res;
   1277 
   1278     res = updateRequests(l.mParameters);
   1279 
   1280     return res;
   1281 }
   1282 
   1283 String8 Camera2Client::getParameters() const {
   1284     ATRACE_CALL();
   1285     ALOGV("%s: Camera %d", __FUNCTION__, mCameraId);
   1286     Mutex::Autolock icl(mBinderSerializationLock);
   1287     if ( checkPid(__FUNCTION__) != OK) return String8();
   1288 
   1289     SharedParameters::ReadLock l(mParameters);
   1290 
   1291     return l.mParameters.get();
   1292 }
   1293 
   1294 status_t Camera2Client::sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) {
   1295     ATRACE_CALL();
   1296     Mutex::Autolock icl(mBinderSerializationLock);
   1297     status_t res;
   1298     if ( (res = checkPid(__FUNCTION__) ) != OK) return res;
   1299 
   1300     ALOGV("%s: Camera %d: Command %d (%d, %d)", __FUNCTION__, mCameraId,
   1301             cmd, arg1, arg2);
   1302 
   1303     switch (cmd) {
   1304         case CAMERA_CMD_START_SMOOTH_ZOOM:
   1305             return commandStartSmoothZoomL();
   1306         case CAMERA_CMD_STOP_SMOOTH_ZOOM:
   1307             return commandStopSmoothZoomL();
   1308         case CAMERA_CMD_SET_DISPLAY_ORIENTATION:
   1309             return commandSetDisplayOrientationL(arg1);
   1310         case CAMERA_CMD_ENABLE_SHUTTER_SOUND:
   1311             return commandEnableShutterSoundL(arg1 == 1);
   1312         case CAMERA_CMD_PLAY_RECORDING_SOUND:
   1313             return commandPlayRecordingSoundL();
   1314         case CAMERA_CMD_START_FACE_DETECTION:
   1315             return commandStartFaceDetectionL(arg1);
   1316         case CAMERA_CMD_STOP_FACE_DETECTION: {
   1317             SharedParameters::Lock l(mParameters);
   1318             return commandStopFaceDetectionL(l.mParameters);
   1319         }
   1320         case CAMERA_CMD_ENABLE_FOCUS_MOVE_MSG:
   1321             return commandEnableFocusMoveMsgL(arg1 == 1);
   1322         case CAMERA_CMD_PING:
   1323             return commandPingL();
   1324         case CAMERA_CMD_SET_VIDEO_BUFFER_COUNT:
   1325             return commandSetVideoBufferCountL(arg1);
   1326         default:
   1327             ALOGE("%s: Unknown command %d (arguments %d, %d)",
   1328                     __FUNCTION__, cmd, arg1, arg2);
   1329             return BAD_VALUE;
   1330     }
   1331 }
   1332 
   1333 status_t Camera2Client::commandStartSmoothZoomL() {
   1334     ALOGE("%s: Unimplemented!", __FUNCTION__);
   1335     return OK;
   1336 }
   1337 
   1338 status_t Camera2Client::commandStopSmoothZoomL() {
   1339     ALOGE("%s: Unimplemented!", __FUNCTION__);
   1340     return OK;
   1341 }
   1342 
   1343 status_t Camera2Client::commandSetDisplayOrientationL(int degrees) {
   1344     int transform = Parameters::degToTransform(degrees,
   1345             mCameraFacing == CAMERA_FACING_FRONT);
   1346     if (transform == -1) {
   1347         ALOGE("%s: Camera %d: Error setting %d as display orientation value",
   1348                 __FUNCTION__, mCameraId, degrees);
   1349         return BAD_VALUE;
   1350     }
   1351     SharedParameters::Lock l(mParameters);
   1352     if (transform != l.mParameters.previewTransform &&
   1353             getPreviewStreamId() != NO_STREAM) {
   1354         mDevice->setStreamTransform(getPreviewStreamId(), transform);
   1355     }
   1356     l.mParameters.previewTransform = transform;
   1357     return OK;
   1358 }
   1359 
   1360 status_t Camera2Client::commandEnableShutterSoundL(bool enable) {
   1361     SharedParameters::Lock l(mParameters);
   1362     if (enable) {
   1363         l.mParameters.playShutterSound = true;
   1364         return OK;
   1365     }
   1366 
   1367     // Disabling shutter sound may not be allowed. In that case only
   1368     // allow the mediaserver process to disable the sound.
   1369     char value[PROPERTY_VALUE_MAX];
   1370     property_get("ro.camera.sound.forced", value, "0");
   1371     if (strncmp(value, "0", 2) != 0) {
   1372         // Disabling shutter sound is not allowed. Deny if the current
   1373         // process is not mediaserver.
   1374         if (getCallingPid() != getpid()) {
   1375             ALOGE("Failed to disable shutter sound. Permission denied (pid %d)",
   1376                     getCallingPid());
   1377             return PERMISSION_DENIED;
   1378         }
   1379     }
   1380 
   1381     l.mParameters.playShutterSound = false;
   1382     return OK;
   1383 }
   1384 
   1385 status_t Camera2Client::commandPlayRecordingSoundL() {
   1386     mCameraService->playSound(CameraService::SOUND_RECORDING);
   1387     return OK;
   1388 }
   1389 
   1390 status_t Camera2Client::commandStartFaceDetectionL(int /*type*/) {
   1391     ALOGV("%s: Camera %d: Starting face detection",
   1392           __FUNCTION__, mCameraId);
   1393     status_t res;
   1394     SharedParameters::Lock l(mParameters);
   1395     switch (l.mParameters.state) {
   1396         case Parameters::DISCONNECTED:
   1397         case Parameters::STOPPED:
   1398         case Parameters::WAITING_FOR_PREVIEW_WINDOW:
   1399         case Parameters::STILL_CAPTURE:
   1400             ALOGE("%s: Camera %d: Cannot start face detection without preview active",
   1401                     __FUNCTION__, mCameraId);
   1402             return INVALID_OPERATION;
   1403         case Parameters::PREVIEW:
   1404         case Parameters::RECORD:
   1405         case Parameters::VIDEO_SNAPSHOT:
   1406             // Good to go for starting face detect
   1407             break;
   1408     }
   1409     // Ignoring type
   1410     if (l.mParameters.fastInfo.bestFaceDetectMode ==
   1411             ANDROID_STATISTICS_FACE_DETECT_MODE_OFF) {
   1412         ALOGE("%s: Camera %d: Face detection not supported",
   1413                 __FUNCTION__, mCameraId);
   1414         return BAD_VALUE;
   1415     }
   1416     if (l.mParameters.enableFaceDetect) return OK;
   1417 
   1418     l.mParameters.enableFaceDetect = true;
   1419 
   1420     res = updateRequests(l.mParameters);
   1421 
   1422     return res;
   1423 }
   1424 
   1425 status_t Camera2Client::commandStopFaceDetectionL(Parameters &params) {
   1426     status_t res = OK;
   1427     ALOGV("%s: Camera %d: Stopping face detection",
   1428           __FUNCTION__, mCameraId);
   1429 
   1430     if (!params.enableFaceDetect) return OK;
   1431 
   1432     params.enableFaceDetect = false;
   1433 
   1434     if (params.state == Parameters::PREVIEW
   1435             || params.state == Parameters::RECORD
   1436             || params.state == Parameters::VIDEO_SNAPSHOT) {
   1437         res = updateRequests(params);
   1438     }
   1439 
   1440     return res;
   1441 }
   1442 
   1443 status_t Camera2Client::commandEnableFocusMoveMsgL(bool enable) {
   1444     SharedParameters::Lock l(mParameters);
   1445     l.mParameters.enableFocusMoveMessages = enable;
   1446 
   1447     return OK;
   1448 }
   1449 
   1450 status_t Camera2Client::commandPingL() {
   1451     // Always ping back if access is proper and device is alive
   1452     SharedParameters::Lock l(mParameters);
   1453     if (l.mParameters.state != Parameters::DISCONNECTED) {
   1454         return OK;
   1455     } else {
   1456         return NO_INIT;
   1457     }
   1458 }
   1459 
   1460 status_t Camera2Client::commandSetVideoBufferCountL(size_t count) {
   1461     if (recordingEnabledL()) {
   1462         ALOGE("%s: Camera %d: Error setting video buffer count after "
   1463                 "recording was started", __FUNCTION__, mCameraId);
   1464         return INVALID_OPERATION;
   1465     }
   1466 
   1467     return mStreamingProcessor->setRecordingBufferCount(count);
   1468 }
   1469 
   1470 /** Device-related methods */
   1471 void Camera2Client::notifyAutoFocus(uint8_t newState, int triggerId) {
   1472     ALOGV("%s: Autofocus state now %d, last trigger %d",
   1473             __FUNCTION__, newState, triggerId);
   1474     bool sendCompletedMessage = false;
   1475     bool sendMovingMessage = false;
   1476 
   1477     bool success = false;
   1478     bool afInMotion = false;
   1479     {
   1480         SharedParameters::Lock l(mParameters);
   1481         // Trace end of AF state
   1482         char tmp[32];
   1483         if (l.mParameters.afStateCounter > 0) {
   1484             camera_metadata_enum_snprint(
   1485                 ANDROID_CONTROL_AF_STATE, l.mParameters.focusState, tmp, sizeof(tmp));
   1486             ATRACE_ASYNC_END(tmp, l.mParameters.afStateCounter);
   1487         }
   1488 
   1489         // Update state
   1490         l.mParameters.focusState = newState;
   1491         l.mParameters.afStateCounter++;
   1492 
   1493         // Trace start of AF state
   1494 
   1495         camera_metadata_enum_snprint(
   1496             ANDROID_CONTROL_AF_STATE, l.mParameters.focusState, tmp, sizeof(tmp));
   1497         ATRACE_ASYNC_BEGIN(tmp, l.mParameters.afStateCounter);
   1498 
   1499         switch (l.mParameters.focusMode) {
   1500             case Parameters::FOCUS_MODE_AUTO:
   1501             case Parameters::FOCUS_MODE_MACRO:
   1502                 // Don't send notifications upstream if they're not for the current AF
   1503                 // trigger. For example, if cancel was called in between, or if we
   1504                 // already sent a notification about this AF call.
   1505                 if (triggerId != l.mParameters.currentAfTriggerId) break;
   1506                 switch (newState) {
   1507                     case ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED:
   1508                         success = true;
   1509                         // no break
   1510                     case ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED:
   1511                         sendCompletedMessage = true;
   1512                         l.mParameters.currentAfTriggerId = -1;
   1513                         break;
   1514                     case ANDROID_CONTROL_AF_STATE_ACTIVE_SCAN:
   1515                         // Just starting focusing, ignore
   1516                         break;
   1517                     case ANDROID_CONTROL_AF_STATE_INACTIVE:
   1518                     case ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN:
   1519                     case ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED:
   1520                     case ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED:
   1521                     default:
   1522                         // Unexpected in AUTO/MACRO mode
   1523                         ALOGE("%s: Unexpected AF state transition in AUTO/MACRO mode: %d",
   1524                                 __FUNCTION__, newState);
   1525                         break;
   1526                 }
   1527                 break;
   1528             case Parameters::FOCUS_MODE_CONTINUOUS_VIDEO:
   1529             case Parameters::FOCUS_MODE_CONTINUOUS_PICTURE:
   1530                 switch (newState) {
   1531                     case ANDROID_CONTROL_AF_STATE_FOCUSED_LOCKED:
   1532                         success = true;
   1533                         // no break
   1534                     case ANDROID_CONTROL_AF_STATE_NOT_FOCUSED_LOCKED:
   1535                         // Don't send notifications upstream if they're not for
   1536                         // the current AF trigger. For example, if cancel was
   1537                         // called in between, or if we already sent a
   1538                         // notification about this AF call.
   1539                         // Send both a 'AF done' callback and a 'AF move' callback
   1540                         if (triggerId != l.mParameters.currentAfTriggerId) break;
   1541                         sendCompletedMessage = true;
   1542                         afInMotion = false;
   1543                         if (l.mParameters.enableFocusMoveMessages &&
   1544                                 l.mParameters.afInMotion) {
   1545                             sendMovingMessage = true;
   1546                         }
   1547                         l.mParameters.currentAfTriggerId = -1;
   1548                         break;
   1549                     case ANDROID_CONTROL_AF_STATE_INACTIVE:
   1550                         // Cancel was called, or we switched state; care if
   1551                         // currently moving
   1552                         afInMotion = false;
   1553                         if (l.mParameters.enableFocusMoveMessages &&
   1554                                 l.mParameters.afInMotion) {
   1555                             sendMovingMessage = true;
   1556                         }
   1557                         break;
   1558                     case ANDROID_CONTROL_AF_STATE_PASSIVE_SCAN:
   1559                         // Start passive scan, inform upstream
   1560                         afInMotion = true;
   1561                         // no break
   1562                     case ANDROID_CONTROL_AF_STATE_PASSIVE_FOCUSED:
   1563                     case ANDROID_CONTROL_AF_STATE_PASSIVE_UNFOCUSED:
   1564                         // Stop passive scan, inform upstream
   1565                         if (l.mParameters.enableFocusMoveMessages) {
   1566                             sendMovingMessage = true;
   1567                         }
   1568                         break;
   1569                 }
   1570                 l.mParameters.afInMotion = afInMotion;
   1571                 break;
   1572             case Parameters::FOCUS_MODE_EDOF:
   1573             case Parameters::FOCUS_MODE_INFINITY:
   1574             case Parameters::FOCUS_MODE_FIXED:
   1575             default:
   1576                 if (newState != ANDROID_CONTROL_AF_STATE_INACTIVE) {
   1577                     ALOGE("%s: Unexpected AF state change %d "
   1578                             "(ID %d) in focus mode %d",
   1579                           __FUNCTION__, newState, triggerId,
   1580                             l.mParameters.focusMode);
   1581                 }
   1582         }
   1583     }
   1584     if (sendMovingMessage) {
   1585         SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);
   1586         if (l.mRemoteCallback != 0) {
   1587             l.mRemoteCallback->notifyCallback(CAMERA_MSG_FOCUS_MOVE,
   1588                     afInMotion ? 1 : 0, 0);
   1589         }
   1590     }
   1591     if (sendCompletedMessage) {
   1592         ATRACE_ASYNC_END(kAutofocusLabel, triggerId);
   1593         SharedCameraCallbacks::Lock l(mSharedCameraCallbacks);
   1594         if (l.mRemoteCallback != 0) {
   1595             l.mRemoteCallback->notifyCallback(CAMERA_MSG_FOCUS,
   1596                     success ? 1 : 0, 0);
   1597         }
   1598     }
   1599 }
   1600 
   1601 void Camera2Client::notifyAutoExposure(uint8_t newState, int triggerId) {
   1602     ALOGV("%s: Autoexposure state now %d, last trigger %d",
   1603             __FUNCTION__, newState, triggerId);
   1604     mCaptureSequencer->notifyAutoExposure(newState, triggerId);
   1605 }
   1606 
   1607 camera2::SharedParameters& Camera2Client::getParameters() {
   1608     return mParameters;
   1609 }
   1610 
   1611 int Camera2Client::getPreviewStreamId() const {
   1612     return mStreamingProcessor->getPreviewStreamId();
   1613 }
   1614 
   1615 int Camera2Client::getCaptureStreamId() const {
   1616     return mJpegProcessor->getStreamId();
   1617 }
   1618 
   1619 int Camera2Client::getCallbackStreamId() const {
   1620     return mCallbackProcessor->getStreamId();
   1621 }
   1622 
   1623 int Camera2Client::getRecordingStreamId() const {
   1624     return mStreamingProcessor->getRecordingStreamId();
   1625 }
   1626 
   1627 int Camera2Client::getZslStreamId() const {
   1628     return mZslProcessor->getStreamId();
   1629 }
   1630 
   1631 status_t Camera2Client::registerFrameListener(int32_t minId, int32_t maxId,
   1632         wp<camera2::FrameProcessor::FilteredListener> listener) {
   1633     return mFrameProcessor->registerListener(minId, maxId, listener);
   1634 }
   1635 
   1636 status_t Camera2Client::removeFrameListener(int32_t minId, int32_t maxId,
   1637         wp<camera2::FrameProcessor::FilteredListener> listener) {
   1638     return mFrameProcessor->removeListener(minId, maxId, listener);
   1639 }
   1640 
   1641 status_t Camera2Client::stopStream() {
   1642     return mStreamingProcessor->stopStream();
   1643 }
   1644 
   1645 const int32_t Camera2Client::kPreviewRequestIdStart;
   1646 const int32_t Camera2Client::kPreviewRequestIdEnd;
   1647 const int32_t Camera2Client::kRecordingRequestIdStart;
   1648 const int32_t Camera2Client::kRecordingRequestIdEnd;
   1649 const int32_t Camera2Client::kCaptureRequestIdStart;
   1650 const int32_t Camera2Client::kCaptureRequestIdEnd;
   1651 
   1652 /** Utility methods */
   1653 
   1654 status_t Camera2Client::updateRequests(Parameters &params) {
   1655     status_t res;
   1656 
   1657     ALOGV("%s: Camera %d: state = %d", __FUNCTION__, getCameraId(), params.state);
   1658 
   1659     res = mStreamingProcessor->incrementStreamingIds();
   1660     if (res != OK) {
   1661         ALOGE("%s: Camera %d: Unable to increment request IDs: %s (%d)",
   1662                 __FUNCTION__, mCameraId, strerror(-res), res);
   1663         return res;
   1664     }
   1665 
   1666     res = mStreamingProcessor->updatePreviewRequest(params);
   1667     if (res != OK) {
   1668         ALOGE("%s: Camera %d: Unable to update preview request: %s (%d)",
   1669                 __FUNCTION__, mCameraId, strerror(-res), res);
   1670         return res;
   1671     }
   1672     res = mStreamingProcessor->updateRecordingRequest(params);
   1673     if (res != OK) {
   1674         ALOGE("%s: Camera %d: Unable to update recording request: %s (%d)",
   1675                 __FUNCTION__, mCameraId, strerror(-res), res);
   1676         return res;
   1677     }
   1678 
   1679     if (params.state == Parameters::PREVIEW) {
   1680         res = startPreviewL(params, true);
   1681         if (res != OK) {
   1682             ALOGE("%s: Camera %d: Error streaming new preview request: %s (%d)",
   1683                     __FUNCTION__, mCameraId, strerror(-res), res);
   1684             return res;
   1685         }
   1686     } else if (params.state == Parameters::RECORD ||
   1687             params.state == Parameters::VIDEO_SNAPSHOT) {
   1688         res = startRecordingL(params, true);
   1689         if (res != OK) {
   1690             ALOGE("%s: Camera %d: Error streaming new record request: %s (%d)",
   1691                     __FUNCTION__, mCameraId, strerror(-res), res);
   1692             return res;
   1693         }
   1694     }
   1695     return res;
   1696 }
   1697 
   1698 
   1699 size_t Camera2Client::calculateBufferSize(int width, int height,
   1700         int format, int stride) {
   1701     switch (format) {
   1702         case HAL_PIXEL_FORMAT_YCbCr_422_SP: // NV16
   1703             return width * height * 2;
   1704         case HAL_PIXEL_FORMAT_YCrCb_420_SP: // NV21
   1705             return width * height * 3 / 2;
   1706         case HAL_PIXEL_FORMAT_YCbCr_422_I: // YUY2
   1707             return width * height * 2;
   1708         case HAL_PIXEL_FORMAT_YV12: {      // YV12
   1709             size_t ySize = stride * height;
   1710             size_t uvStride = (stride / 2 + 0xF) & ~0xF;
   1711             size_t uvSize = uvStride * height / 2;
   1712             return ySize + uvSize * 2;
   1713         }
   1714         case HAL_PIXEL_FORMAT_RGB_565:
   1715             return width * height * 2;
   1716         case HAL_PIXEL_FORMAT_RGBA_8888:
   1717             return width * height * 4;
   1718         case HAL_PIXEL_FORMAT_RAW_SENSOR:
   1719             return width * height * 2;
   1720         default:
   1721             ALOGE("%s: Unknown preview format: %x",
   1722                     __FUNCTION__,  format);
   1723             return 0;
   1724     }
   1725 }
   1726 
   1727 status_t Camera2Client::syncWithDevice() {
   1728     ATRACE_CALL();
   1729     const nsecs_t kMaxSyncTimeout = 500000000; // 500 ms
   1730     status_t res;
   1731 
   1732     int32_t activeRequestId = mStreamingProcessor->getActiveRequestId();
   1733     if (activeRequestId == 0) return OK;
   1734 
   1735     res = mDevice->waitUntilRequestReceived(activeRequestId, kMaxSyncTimeout);
   1736     if (res == TIMED_OUT) {
   1737         ALOGE("%s: Camera %d: Timed out waiting sync with HAL",
   1738                 __FUNCTION__, mCameraId);
   1739     } else if (res != OK) {
   1740         ALOGE("%s: Camera %d: Error while waiting to sync with HAL",
   1741                 __FUNCTION__, mCameraId);
   1742     }
   1743     return res;
   1744 }
   1745 
   1746 template <typename ProcessorT>
   1747 status_t Camera2Client::updateProcessorStream(sp<ProcessorT> processor,
   1748                                               camera2::Parameters params) {
   1749     // No default template arguments until C++11, so we need this overload
   1750     return updateProcessorStream<ProcessorT, &ProcessorT::updateStream>(
   1751             processor, params);
   1752 }
   1753 
   1754 template <typename ProcessorT,
   1755           status_t (ProcessorT::*updateStreamF)(const Parameters &)>
   1756 status_t Camera2Client::updateProcessorStream(sp<ProcessorT> processor,
   1757                                               Parameters params) {
   1758     status_t res;
   1759 
   1760     // Get raw pointer since sp<T> doesn't have operator->*
   1761     ProcessorT *processorPtr = processor.get();
   1762     res = (processorPtr->*updateStreamF)(params);
   1763 
   1764     /**
   1765      * Can't update the stream if it's busy?
   1766      *
   1767      * Then we need to stop the device (by temporarily clearing the request
   1768      * queue) and then try again. Resume streaming once we're done.
   1769      */
   1770     if (res == -EBUSY) {
   1771         ALOGV("%s: Camera %d: Pausing to update stream", __FUNCTION__,
   1772                 mCameraId);
   1773         res = mStreamingProcessor->togglePauseStream(/*pause*/true);
   1774         if (res != OK) {
   1775             ALOGE("%s: Camera %d: Can't pause streaming: %s (%d)",
   1776                     __FUNCTION__, mCameraId, strerror(-res), res);
   1777         }
   1778 
   1779         res = mDevice->waitUntilDrained();
   1780         if (res != OK) {
   1781             ALOGE("%s: Camera %d: Waiting to stop streaming failed: %s (%d)",
   1782                     __FUNCTION__, mCameraId, strerror(-res), res);
   1783         }
   1784 
   1785         res = (processorPtr->*updateStreamF)(params);
   1786         if (res != OK) {
   1787             ALOGE("%s: Camera %d: Failed to update processing stream "
   1788                   " despite having halted streaming first: %s (%d)",
   1789                   __FUNCTION__, mCameraId, strerror(-res), res);
   1790         }
   1791 
   1792         res = mStreamingProcessor->togglePauseStream(/*pause*/false);
   1793         if (res != OK) {
   1794             ALOGE("%s: Camera %d: Can't unpause streaming: %s (%d)",
   1795                     __FUNCTION__, mCameraId, strerror(-res), res);
   1796         }
   1797     }
   1798 
   1799     return res;
   1800 }
   1801 
   1802 const char* Camera2Client::kAutofocusLabel = "autofocus";
   1803 const char* Camera2Client::kTakepictureLabel = "take_picture";
   1804 
   1805 } // namespace android
   1806