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