blob: 4cb7fa72d468449c868e092ca055e8188f84d0da [file] [log] [blame]
Mathias Agopian65ab4712010-07-14 17:59:35 -07001/*
Ruben Brunkd1176ef2014-02-21 10:51:38 -08002 * Copyright (C) 2008 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 */
Mathias Agopian65ab4712010-07-14 17:59:35 -070016
17#ifndef ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
18#define ANDROID_SERVERS_CAMERA_CAMERASERVICE_H
19
Ruben Brunk36597b22015-03-20 22:15:57 -070020#include <cutils/multiuser.h>
Igor Murashkin634a5152013-02-20 17:15:11 -080021#include <utils/Vector.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070022#include <utils/KeyedVector.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080023#include <binder/AppOpsManager.h>
Mathias Agopian5462fc92010-07-14 18:41:18 -070024#include <binder/BinderService.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080025#include <binder/IAppOpsCallback.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070026#include <camera/ICameraService.h>
Iliyan Malchev8951a972011-04-14 16:55:59 -070027#include <hardware/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070028
Igor Murashkinc073ba52013-02-26 14:32:34 -080029#include <camera/ICamera.h>
30#include <camera/ICameraClient.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070031#include <camera/camera2/ICameraDeviceUser.h>
32#include <camera/camera2/ICameraDeviceCallbacks.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080033#include <camera/VendorTagDescriptor.h>
Jianing Weicb0652e2014-03-12 18:29:36 -070034#include <camera/CaptureResult.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070035#include <camera/CameraParameters.h>
Igor Murashkinc073ba52013-02-26 14:32:34 -080036
Igor Murashkinbfc99152013-02-27 12:55:20 -080037#include <camera/ICameraServiceListener.h>
Chien-Yu Chen3068d732015-02-09 13:29:57 -080038#include "CameraFlashlight.h"
39
Yin-Chia Yehe074a932015-01-30 10:29:02 -080040#include "common/CameraModule.h"
Ruben Brunkcc776712015-02-17 20:18:47 -080041#include "utils/AutoConditionLock.h"
42#include "utils/ClientManager.h"
43#include "utils/RingBuffer.h"
Yin-Chia Yehe074a932015-01-30 10:29:02 -080044
Ruben Brunkcc776712015-02-17 20:18:47 -080045#include <set>
46#include <string>
47#include <map>
48#include <memory>
Mathias Agopian65ab4712010-07-14 17:59:35 -070049
50namespace android {
51
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070052extern volatile int32_t gLogLevel;
53
Mathias Agopian65ab4712010-07-14 17:59:35 -070054class MemoryHeapBase;
55class MediaPlayer;
56
Mathias Agopian5462fc92010-07-14 18:41:18 -070057class CameraService :
58 public BinderService<CameraService>,
Igor Murashkinecf17e82012-10-02 16:05:11 -070059 public BnCameraService,
Igor Murashkincba2c162013-03-20 15:56:31 -070060 public IBinder::DeathRecipient,
61 public camera_module_callbacks_t
Mathias Agopian65ab4712010-07-14 17:59:35 -070062{
Mathias Agopian5462fc92010-07-14 18:41:18 -070063 friend class BinderService<CameraService>;
Mathias Agopian65ab4712010-07-14 17:59:35 -070064public:
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070065 class Client;
Igor Murashkin634a5152013-02-20 17:15:11 -080066 class BasicClient;
67
Ruben Brunk0bbf8b22015-04-30 14:35:42 -070068 // The effective API level. The Camera2 API running in LEGACY mode counts as API_1.
Ruben Brunkcc776712015-02-17 20:18:47 -080069 enum apiLevel {
70 API_1 = 1,
71 API_2 = 2
72 };
73
Ruben Brunkbe0b6b42015-05-12 16:10:52 -070074 // Process state (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
Ruben Brunkcc776712015-02-17 20:18:47 -080075 static const int PROCESS_STATE_NONEXISTENT = -1;
Ruben Brunkcc776712015-02-17 20:18:47 -080076
77 // 3 second busy timeout when other clients are connecting
78 static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
79
Ruben Brunk4f9576b2015-04-10 17:26:56 -070080 // 1 second busy timeout when other clients are disconnecting
81 static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
82
Ruben Brunkcc776712015-02-17 20:18:47 -080083 // Default number of messages to store in eviction log
Ruben Brunka8ca9152015-04-07 14:23:40 -070084 static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
Ruben Brunkcc776712015-02-17 20:18:47 -080085
Ruben Brunk36597b22015-03-20 22:15:57 -070086 enum {
87 // Default last user id
88 DEFAULT_LAST_USER_ID = 0,
89 };
90
Igor Murashkin634a5152013-02-20 17:15:11 -080091 // Implementation of BinderService<T>
Mathias Agopian5462fc92010-07-14 18:41:18 -070092 static char const* getServiceName() { return "media.camera"; }
Mathias Agopian65ab4712010-07-14 17:59:35 -070093
94 CameraService();
95 virtual ~CameraService();
96
Igor Murashkin634a5152013-02-20 17:15:11 -080097 /////////////////////////////////////////////////////////////////////
Igor Murashkincba2c162013-03-20 15:56:31 -070098 // HAL Callbacks
Ruben Brunkcc776712015-02-17 20:18:47 -080099 virtual void onDeviceStatusChanged(camera_device_status_t cameraId,
100 camera_device_status_t newStatus);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800101 virtual void onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800102 ICameraServiceListener::TorchStatus
103 newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700104
105 /////////////////////////////////////////////////////////////////////
Igor Murashkin634a5152013-02-20 17:15:11 -0800106 // ICameraService
Mathias Agopian65ab4712010-07-14 17:59:35 -0700107 virtual int32_t getNumberOfCameras();
108 virtual status_t getCameraInfo(int cameraId,
109 struct CameraInfo* cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -0700110 virtual status_t getCameraCharacteristics(int cameraId,
111 CameraMetadata* cameraInfo);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800112 virtual status_t getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800113
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700114 virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700115 const String16& opPackageName, int clientUid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700116 /*out*/
117 sp<ICamera>& device);
118
Zhijun Heb10cdad2014-06-16 16:38:35 -0700119 virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700120 int halVersion, const String16& opPackageName, int clientUid,
Zhijun Heb10cdad2014-06-16 16:38:35 -0700121 /*out*/
122 sp<ICamera>& device);
123
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700124 virtual status_t connectDevice(
Igor Murashkine7ee7632013-06-11 18:10:18 -0700125 const sp<ICameraDeviceCallbacks>& cameraCb,
126 int cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700127 const String16& opPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700128 int clientUid,
129 /*out*/
130 sp<ICameraDeviceUser>& device);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700131
Igor Murashkinbfc99152013-02-27 12:55:20 -0800132 virtual status_t addListener(const sp<ICameraServiceListener>& listener);
133 virtual status_t removeListener(
134 const sp<ICameraServiceListener>& listener);
135
Igor Murashkin65d14b92014-06-17 12:03:20 -0700136 virtual status_t getLegacyParameters(
137 int cameraId,
138 /*out*/
139 String16* parameters);
140
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800141 virtual status_t setTorchMode(const String16& cameraId, bool enabled,
142 const sp<IBinder>& clientBinder);
143
Ruben Brunk36597b22015-03-20 22:15:57 -0700144 virtual void notifySystemEvent(int eventId, int arg0);
145
Igor Murashkin65d14b92014-06-17 12:03:20 -0700146 // OK = supports api of that version, -EOPNOTSUPP = does not support
147 virtual status_t supportsCameraApi(
148 int cameraId, int apiVersion);
149
Igor Murashkin634a5152013-02-20 17:15:11 -0800150 // Extra permissions checks
Mathias Agopian65ab4712010-07-14 17:59:35 -0700151 virtual status_t onTransact(uint32_t code, const Parcel& data,
152 Parcel* reply, uint32_t flags);
Igor Murashkin634a5152013-02-20 17:15:11 -0800153
154 virtual status_t dump(int fd, const Vector<String16>& args);
155
156 /////////////////////////////////////////////////////////////////////
157 // Client functionality
Mathias Agopian65ab4712010-07-14 17:59:35 -0700158
159 enum sound_kind {
160 SOUND_SHUTTER = 0,
161 SOUND_RECORDING = 1,
162 NUM_SOUNDS
163 };
164
165 void loadSound();
166 void playSound(sound_kind kind);
167 void releaseSound();
168
Igor Murashkin98e24722013-06-19 19:51:04 -0700169 /////////////////////////////////////////////////////////////////////
170 // CameraDeviceFactory functionality
171 int getDeviceVersion(int cameraId, int* facing = NULL);
172
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700173 /////////////////////////////////////////////////////////////////////
174 // Shared utilities
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700175 static status_t filterGetInfoErrorCode(status_t err);
Igor Murashkin634a5152013-02-20 17:15:11 -0800176
177 /////////////////////////////////////////////////////////////////////
178 // CameraClient functionality
179
Igor Murashkin634a5152013-02-20 17:15:11 -0800180 class BasicClient : public virtual RefBase {
181 public:
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800182 virtual status_t initialize(CameraModule *module) = 0;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700183 virtual void disconnect();
Igor Murashkin634a5152013-02-20 17:15:11 -0800184
Igor Murashkine7ee7632013-06-11 18:10:18 -0700185 // because we can't virtually inherit IInterface, which breaks
186 // virtual inheritance
187 virtual sp<IBinder> asBinderWrapper() = 0;
188
Ruben Brunk9efdf952015-03-18 23:11:57 -0700189 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700190 sp<IBinder> getRemote() {
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800191 return mRemoteBinder;
Igor Murashkin634a5152013-02-20 17:15:11 -0800192 }
193
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700194 virtual status_t dump(int fd, const Vector<String16>& args) = 0;
Igor Murashkine7ee7632013-06-11 18:10:18 -0700195
Ruben Brunkcc776712015-02-17 20:18:47 -0800196 // Return the package name for this client
197 virtual String16 getPackageName() const;
198
199 // Notify client about a fatal error
200 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
201 const CaptureResultExtras& resultExtras) = 0;
202
203 // Get the PID of the application client using this
204 virtual int getClientPid() const;
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700205
206 // Check what API level is used for this client. This is used to determine which
207 // superclass this can be cast to.
208 virtual bool canCastToApiClient(apiLevel level) const;
Igor Murashkin634a5152013-02-20 17:15:11 -0800209 protected:
210 BasicClient(const sp<CameraService>& cameraService,
211 const sp<IBinder>& remoteCallback,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700212 const String16& opPackageName,
Igor Murashkin634a5152013-02-20 17:15:11 -0800213 int cameraId,
214 int cameraFacing,
215 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800216 uid_t clientUid,
Igor Murashkin634a5152013-02-20 17:15:11 -0800217 int servicePid);
218
219 virtual ~BasicClient();
220
221 // the instance is in the middle of destruction. When this is set,
222 // the instance should not be accessed from callback.
223 // CameraService's mClientLock should be acquired to access this.
224 // - subclasses should set this to true in their destructors.
225 bool mDestructionStarted;
226
227 // these are initialized in the constructor.
228 sp<CameraService> mCameraService; // immutable after constructor
229 int mCameraId; // immutable after constructor
230 int mCameraFacing; // immutable after constructor
Svet Ganov32fa6d02015-05-01 20:47:20 -0700231 const String16 mOpPackageName;
Igor Murashkin634a5152013-02-20 17:15:11 -0800232 pid_t mClientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800233 uid_t mClientUid; // immutable after constructor
Igor Murashkin634a5152013-02-20 17:15:11 -0800234 pid_t mServicePid; // immutable after constructor
Ruben Brunkcc776712015-02-17 20:18:47 -0800235 bool mDisconnected;
Igor Murashkin634a5152013-02-20 17:15:11 -0800236
237 // - The app-side Binder interface to receive callbacks from us
Igor Murashkine7ee7632013-06-11 18:10:18 -0700238 sp<IBinder> mRemoteBinder; // immutable after constructor
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800239
240 // permissions management
241 status_t startCameraOps();
242 status_t finishCameraOps();
243
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800244 private:
245 AppOpsManager mAppOpsManager;
246
247 class OpsCallback : public BnAppOpsCallback {
248 public:
249 OpsCallback(wp<BasicClient> client);
250 virtual void opChanged(int32_t op, const String16& packageName);
251
252 private:
253 wp<BasicClient> mClient;
254
255 }; // class OpsCallback
256
257 sp<OpsCallback> mOpsCallback;
258 // Track whether startCameraOps was called successfully, to avoid
259 // finishing what we didn't start.
260 bool mOpsActive;
261
262 // IAppOpsCallback interface, indirected through opListener
263 virtual void opChanged(int32_t op, const String16& packageName);
264 }; // class BasicClient
Igor Murashkin634a5152013-02-20 17:15:11 -0800265
266 class Client : public BnCamera, public BasicClient
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700267 {
268 public:
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800269 typedef ICameraClient TCamCallbacks;
270
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700271 // ICamera interface (see ICamera for details)
272 virtual void disconnect();
273 virtual status_t connect(const sp<ICameraClient>& client) = 0;
274 virtual status_t lock() = 0;
275 virtual status_t unlock() = 0;
Eino-Ville Talvala1ce7c342013-08-21 13:57:21 -0700276 virtual status_t setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700277 virtual void setPreviewCallbackFlag(int flag) = 0;
Eino-Ville Talvala3ee35502013-04-02 15:45:11 -0700278 virtual status_t setPreviewCallbackTarget(
279 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700280 virtual status_t startPreview() = 0;
281 virtual void stopPreview() = 0;
282 virtual bool previewEnabled() = 0;
283 virtual status_t storeMetaDataInBuffers(bool enabled) = 0;
284 virtual status_t startRecording() = 0;
285 virtual void stopRecording() = 0;
286 virtual bool recordingEnabled() = 0;
287 virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
288 virtual status_t autoFocus() = 0;
289 virtual status_t cancelAutoFocus() = 0;
290 virtual status_t takePicture(int msgType) = 0;
291 virtual status_t setParameters(const String8& params) = 0;
292 virtual String8 getParameters() const = 0;
293 virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
294
295 // Interface used by CameraService
296 Client(const sp<CameraService>& cameraService,
297 const sp<ICameraClient>& cameraClient,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700298 const String16& opPackageName,
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700299 int cameraId,
300 int cameraFacing,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700301 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800302 uid_t clientUid,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700303 int servicePid);
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700304 ~Client();
305
306 // return our camera client
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800307 const sp<ICameraClient>& getRemoteCallback() {
308 return mRemoteCallback;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700309 }
310
Igor Murashkine7ee7632013-06-11 18:10:18 -0700311 virtual sp<IBinder> asBinderWrapper() {
Marco Nelissen06b46062014-11-14 07:58:25 -0800312 return asBinder(this);
Igor Murashkine7ee7632013-06-11 18:10:18 -0700313 }
314
Jianing Weicb0652e2014-03-12 18:29:36 -0700315 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
316 const CaptureResultExtras& resultExtras);
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700317
318 // Check what API level is used for this client. This is used to determine which
319 // superclass this can be cast to.
320 virtual bool canCastToApiClient(apiLevel level) const;
Ruben Brunkcc776712015-02-17 20:18:47 -0800321 protected:
322 // Convert client from cookie.
323 static sp<CameraService::Client> getClientFromCookie(void* user);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800324
Igor Murashkin634a5152013-02-20 17:15:11 -0800325 // Initialized in constructor
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700326
Igor Murashkin634a5152013-02-20 17:15:11 -0800327 // - The app-side Binder interface to receive callbacks from us
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800328 sp<ICameraClient> mRemoteCallback;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800329
330 }; // class Client
Igor Murashkin634a5152013-02-20 17:15:11 -0800331
Ruben Brunkcc776712015-02-17 20:18:47 -0800332 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
333 sp<CameraService::BasicClient>>> DescriptorPtr;
334
335 /**
336 * A container class for managing active camera clients that are using HAL devices. Active
337 * clients are represented by ClientDescriptor objects that contain strong pointers to the
338 * actual BasicClient subclass binder interface implementation.
339 *
340 * This class manages the eviction behavior for the camera clients. See the parent class
341 * implementation in utils/ClientManager for the specifics of this behavior.
342 */
343 class CameraClientManager :
344 public resource_policy::ClientManager<String8, sp<CameraService::BasicClient>> {
345 public:
346 virtual ~CameraClientManager();
347
348 /**
349 * Return a strong pointer to the active BasicClient for this camera ID, or an empty
350 * if none exists.
351 */
352 sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
353
354 /**
355 * Return a string describing the current state.
356 */
357 String8 toString() const;
358
359 /**
360 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
361 */
362 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
363 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
364 int32_t ownerId);
365
366 /**
367 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
368 * values intialized from a prior ClientDescriptor.
369 */
370 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
371 const CameraService::DescriptorPtr& partial);
372
373 }; // class CameraClientManager
374
Mathias Agopian65ab4712010-07-14 17:59:35 -0700375private:
Igor Murashkin634a5152013-02-20 17:15:11 -0800376
Ruben Brunkcc776712015-02-17 20:18:47 -0800377 /**
378 * Container class for the state of each logical camera device, including: ID, status, and
379 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates
380 * represents the camera devices advertised by the HAL (and any USB devices, when we add
381 * those).
382 *
383 * This container does NOT represent an active camera client. These are represented using
384 * the ClientDescriptors stored in mActiveClientManager.
385 */
386 class CameraState {
387 public:
388 /**
389 * Make a new CameraState and set the ID, cost, and conflicting devices using the values
390 * returned in the HAL's camera_info struct for each device.
391 */
392 CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
393 virtual ~CameraState();
394
395 /**
396 * Return the status for this device.
397 *
398 * This method acquires mStatusLock.
399 */
400 ICameraServiceListener::Status getStatus() const;
401
402 /**
403 * This function updates the status for this camera device, unless the given status
404 * is in the given list of rejected status states, and execute the function passed in
405 * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
406 * if the status has changed.
407 *
408 * This method is idempotent, and will not result in the function passed to
409 * onStatusUpdateLocked being called more than once for the same arguments.
410 * This method aquires mStatusLock.
411 */
412 template<class Func>
413 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
414 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
415 Func onStatusUpdatedLocked);
416
417 /**
418 * Return the last set CameraParameters object generated from the information returned by
419 * the HAL for this device (or an empty CameraParameters object if none has been set).
420 */
421 CameraParameters getShimParams() const;
422
423 /**
424 * Set the CameraParameters for this device.
425 */
426 void setShimParams(const CameraParameters& params);
427
428 /**
429 * Return the resource_cost advertised by the HAL for this device.
430 */
431 int getCost() const;
432
433 /**
434 * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
435 */
436 std::set<String8> getConflicting() const;
437
438 /**
439 * Return the ID of this camera device.
440 */
441 String8 getId() const;
442
443 private:
444 const String8 mId;
445 ICameraServiceListener::Status mStatus; // protected by mStatusLock
446 const int mCost;
447 std::set<String8> mConflicting;
448 mutable Mutex mStatusLock;
449 CameraParameters mShimParams;
450 }; // class CameraState
451
Igor Murashkin634a5152013-02-20 17:15:11 -0800452 // Delay-load the Camera HAL module
453 virtual void onFirstRef();
454
Ruben Brunkcc776712015-02-17 20:18:47 -0800455 // Check if we can connect, before we acquire the service lock.
Ruben Brunk36597b22015-03-20 22:15:57 -0700456 status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid) const;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800457
Ruben Brunkcc776712015-02-17 20:18:47 -0800458 // Handle active client evictions, and update service state.
459 // Only call with with mServiceLock held.
460 status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
461 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
462 /*out*/
463 sp<BasicClient>* client,
464 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800465
Ruben Brunkcc776712015-02-17 20:18:47 -0800466 // Single implementation shared between the various connect calls
467 template<class CALLBACK, class CLIENT>
468 status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700469 const String16& opPackageName, int clientUid, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 bool legacyMode, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800471
Igor Murashkin634a5152013-02-20 17:15:11 -0800472
Ruben Brunkcc776712015-02-17 20:18:47 -0800473 // Lock guarding camera service state
Mathias Agopian65ab4712010-07-14 17:59:35 -0700474 Mutex mServiceLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800475
476 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
477 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
478
479 // Return NO_ERROR if the device with a give ID can be connected to
480 status_t checkIfDeviceIsUsable(const String8& cameraId) const;
481
482 // Container for managing currently active application-layer clients
483 CameraClientManager mActiveClientManager;
484
485 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
486 std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
487
488 // Mutex guarding mCameraStates map
489 mutable Mutex mCameraStatesLock;
490
491 // Circular buffer for storing event logging for dumps
492 RingBuffer<String8> mEventLog;
Ruben Brunka8ca9152015-04-07 14:23:40 -0700493 Mutex mLogLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800494
Ruben Brunk36597b22015-03-20 22:15:57 -0700495 // UID of last user.
496 int mLastUserId;
497
Ruben Brunkcc776712015-02-17 20:18:47 -0800498 /**
499 * Get the camera state for a given camera id.
500 *
501 * This acquires mCameraStatesLock.
502 */
503 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
504
505 /**
506 * Evict client who's remote binder has died. Returns true if this client was in the active
507 * list and was disconnected.
508 *
509 * This method acquires mServiceLock.
510 */
511 bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
512
513 /**
514 * Remove the given client from the active clients list; does not disconnect the client.
515 *
516 * This method acquires mServiceLock.
517 */
518 void removeByClient(const BasicClient* client);
519
520 /**
521 * Add new client to active clients list after conflicting clients have disconnected using the
522 * values set in the partial descriptor passed in to construct the actual client descriptor.
523 * This is typically called at the end of a connect call.
524 *
525 * This method must be called with mServiceLock held.
526 */
527 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
528
529 /**
530 * Returns the integer corresponding to the given camera ID string, or -1 on failure.
531 */
532 static int cameraIdToInt(const String8& cameraId);
533
534 /**
535 * Remove a single client corresponding to the given camera id from the list of active clients.
536 * If none exists, return an empty strongpointer.
537 *
538 * This method must be called with mServiceLock held.
539 */
540 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
541
542 /**
Ruben Brunk36597b22015-03-20 22:15:57 -0700543 * Handle a notification that the current device user has changed.
544 */
545 void doUserSwitch(int newUserId);
546
547 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700548 * Add an event log message.
Ruben Brunkcc776712015-02-17 20:18:47 -0800549 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700550 void logEvent(const char* event);
Ruben Brunkcc776712015-02-17 20:18:47 -0800551
552 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700553 * Add an event log message that a client has been disconnected.
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700555 void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
556
557 /**
558 * Add an event log message that a client has been connected.
559 */
560 void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
561
562 /**
563 * Add an event log message that a client's connect attempt has been rejected.
564 */
565 void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
566 const char* reason);
567
568 /**
569 * Add an event log message that the current device user has been switched.
570 */
571 void logUserSwitch(int oldUserId, int newUserId);
572
573 /**
574 * Add an event log message that a device has been removed by the HAL
575 */
576 void logDeviceRemoved(const char* cameraId, const char* reason);
577
578 /**
579 * Add an event log message that a device has been added by the HAL
580 */
581 void logDeviceAdded(const char* cameraId, const char* reason);
582
583 /**
584 * Add an event log message that a client has unexpectedly died.
585 */
586 void logClientDied(int clientPid, const char* reason);
Ruben Brunkcc776712015-02-17 20:18:47 -0800587
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700588 /**
589 * Add a event log message that a serious service-level error has occured
590 */
591 void logServiceError(const char* msg, int errorCode);
592
593 /**
594 * Dump the event log to an FD
595 */
596 void dumpEventLog(int fd);
597
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 int mNumberOfCameras;
599
Mathias Agopian65ab4712010-07-14 17:59:35 -0700600 // sounds
Chih-Chung Changff4f55c2011-10-17 19:03:12 +0800601 MediaPlayer* newMediaPlayer(const char *file);
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 Mutex mSoundLock;
604 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS];
605 int mSoundRef; // reference count (release all MediaPlayer when 0)
606
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800607 CameraModule* mModule;
Igor Murashkinecf17e82012-10-02 16:05:11 -0700608
Ruben Brunkcc776712015-02-17 20:18:47 -0800609 // Guarded by mStatusListenerMutex
610 std::vector<sp<ICameraServiceListener>> mListenerList;
611 Mutex mStatusListenerLock;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800612
Ruben Brunkcc776712015-02-17 20:18:47 -0800613 /**
614 * Update the status for the given camera id (if that device exists), and broadcast the
615 * status update to all current ICameraServiceListeners if the status has changed. Any
616 * statuses in rejectedSourceStates will be ignored.
617 *
618 * This method must be idempotent.
619 * This method acquires mStatusLock and mStatusListenerLock.
620 */
621 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
622 std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
623 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
Igor Murashkinbfc99152013-02-27 12:55:20 -0800624
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800625 // flashlight control
626 sp<CameraFlashlight> mFlashlight;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800627 // guard mTorchStatusMap
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800628 Mutex mTorchStatusMutex;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800629 // guard mTorchClientMap
630 Mutex mTorchClientMapMutex;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800631 // camera id -> torch status
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800632 KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800633 // camera id -> torch client binder
634 // only store the last client that turns on each camera's torch mode
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800635 KeyedVector<String8, sp<IBinder> > mTorchClientMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636
637 // check and handle if torch client's process has died
638 void handleTorchClientBinderDied(const wp<IBinder> &who);
639
640 // handle torch mode status change and invoke callbacks. mTorchStatusMutex
641 // should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800642 void onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800643 ICameraServiceListener::TorchStatus newStatus);
644
645 // get a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800646 status_t getTorchStatusLocked(const String8 &cameraId,
647 ICameraServiceListener::TorchStatus *status) const;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800648
649 // set a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800650 status_t setTorchStatusLocked(const String8 &cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800651 ICameraServiceListener::TorchStatus status);
652
Igor Murashkinecf17e82012-10-02 16:05:11 -0700653 // IBinder::DeathRecipient implementation
Igor Murashkinbfc99152013-02-27 12:55:20 -0800654 virtual void binderDied(const wp<IBinder> &who);
Igor Murashkin634a5152013-02-20 17:15:11 -0800655
656 // Helpers
Igor Murashkinbfc99152013-02-27 12:55:20 -0800657
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800658 bool setUpVendorTags();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700659
660 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700661 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
662 *
663 * Returns OK on success, or a negative error code.
664 */
665 status_t initializeShimMetadata(int cameraId);
666
667 /**
Igor Murashkin65d14b92014-06-17 12:03:20 -0700668 * Get the cached CameraParameters for the camera. If they haven't been
669 * cached yet, then initialize them for the first time.
670 *
671 * Returns OK on success, or a negative error code.
672 */
673 status_t getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
674
675 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700676 * Generate the CameraCharacteristics metadata required by the Camera2 API
677 * from the available HAL1 CameraParameters and CameraInfo.
678 *
679 * Returns OK on success, or a negative error code.
680 */
681 status_t generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
682
Ruben Brunkcc776712015-02-17 20:18:47 -0800683 static int getCallingPid();
684
685 static int getCallingUid();
686
Ruben Brunkb2119af2014-05-09 19:57:56 -0700687 /**
Ruben Brunkcc776712015-02-17 20:18:47 -0800688 * Get the current system time as a formatted string.
Ruben Brunkb2119af2014-05-09 19:57:56 -0700689 */
Ruben Brunkcc776712015-02-17 20:18:47 -0800690 static String8 getFormattedCurrentTime();
691
692 /**
693 * Get the camera eviction priority from the current process state given by ActivityManager.
694 */
695 static int getCameraPriorityFromProcState(int procState);
696
697 static status_t makeClient(const sp<CameraService>& cameraService,
698 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
699 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
700 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
701 /*out*/sp<BasicClient>* client);
Svet Ganov32fa6d02015-05-01 20:47:20 -0700702
703 status_t checkCameraAccess(const String16& opPackageName);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700704};
705
Ruben Brunkcc776712015-02-17 20:18:47 -0800706template<class Func>
707void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
708 const String8& cameraId,
709 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
710 Func onStatusUpdatedLocked) {
711 Mutex::Autolock lock(mStatusLock);
712 ICameraServiceListener::Status oldStatus = mStatus;
713 mStatus = status;
714
715 if (oldStatus == status) {
716 return;
717 }
718
719 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
720 cameraId.string(), oldStatus, status);
721
722 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
723 (status != ICameraServiceListener::STATUS_PRESENT &&
724 status != ICameraServiceListener::STATUS_ENUMERATING)) {
725
726 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
727 __FUNCTION__);
728 mStatus = oldStatus;
729 return;
730 }
731
732 /**
733 * Sometimes we want to conditionally do a transition.
734 * For example if a client disconnects, we want to go to PRESENT
735 * only if we weren't already in NOT_PRESENT or ENUMERATING.
736 */
737 for (auto& rejectStatus : rejectSourceStates) {
738 if (oldStatus == rejectStatus) {
739 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
740 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
741 mStatus = oldStatus;
742 return;
743 }
744 }
745
746 onStatusUpdatedLocked(cameraId, status);
747}
748
749
750template<class CALLBACK, class CLIENT>
751status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Svet Ganov32fa6d02015-05-01 20:47:20 -0700752 int halVersion, const String16& opPackageName, int clientUid,
Ruben Brunkcc776712015-02-17 20:18:47 -0800753 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
754 /*out*/sp<CLIENT>& device) {
755 status_t ret = NO_ERROR;
Svet Ganov32fa6d02015-05-01 20:47:20 -0700756 String8 clientName8(opPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -0800757 int clientPid = getCallingPid();
758
Ruben Brunka8ca9152015-04-07 14:23:40 -0700759 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
Ruben Brunkcc776712015-02-17 20:18:47 -0800760 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Ruben Brunka8ca9152015-04-07 14:23:40 -0700761 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
762 static_cast<int>(effectiveApiLevel));
Ruben Brunkcc776712015-02-17 20:18:47 -0800763
Ruben Brunkcc776712015-02-17 20:18:47 -0800764 sp<CLIENT> client = nullptr;
765 {
766 // Acquire mServiceLock and prevent other clients from connecting
767 std::unique_ptr<AutoConditionLock> lock =
768 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
Ruben Brunk36597b22015-03-20 22:15:57 -0700769
Ruben Brunkcc776712015-02-17 20:18:47 -0800770 if (lock == nullptr) {
771 ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
772 , clientPid);
773 return -EBUSY;
774 }
775
Ruben Brunk36597b22015-03-20 22:15:57 -0700776 // Enforce client permissions and do basic sanity checks
777 if((ret = validateConnectLocked(cameraId, /*inout*/clientUid)) != NO_ERROR) {
778 return ret;
779 }
Ruben Brunka8ca9152015-04-07 14:23:40 -0700780 int userId = multiuser_get_user_id(clientUid);
781
782 if (userId != mLastUserId && clientPid != getpid() ) {
783 // If no previous user ID had been set, set to the user of the caller.
784 logUserSwitch(mLastUserId, userId);
785 LOG_ALWAYS_FATAL_IF(mLastUserId != DEFAULT_LAST_USER_ID,
786 "Invalid state: Should never update user ID here unless was default");
787 mLastUserId = userId;
788 }
Ruben Brunk36597b22015-03-20 22:15:57 -0700789
Ruben Brunkcc776712015-02-17 20:18:47 -0800790 // Check the shim parameters after acquiring lock, if they have already been updated and
791 // we were doing a shim update, return immediately
792 if (shimUpdateOnly) {
793 auto cameraState = getCameraState(cameraId);
794 if (cameraState != nullptr) {
795 if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
796 }
797 }
798
799 sp<BasicClient> clientTmp = nullptr;
800 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
801 if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
802 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
803 /*out*/&partial)) != NO_ERROR) {
804 return ret;
805 }
806
807 if (clientTmp.get() != nullptr) {
808 // Handle special case for API1 MediaRecorder where the existing client is returned
809 device = static_cast<CLIENT*>(clientTmp.get());
810 return NO_ERROR;
811 }
812
813 // give flashlight a chance to close devices if necessary.
814 mFlashlight->prepareDeviceOpen(cameraId);
815
816 // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
817 int id = cameraIdToInt(cameraId);
818 if (id == -1) {
819 ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
820 cameraId.string());
821 return BAD_VALUE;
822 }
823
824 int facing = -1;
825 int deviceVersion = getDeviceVersion(id, /*out*/&facing);
826 sp<BasicClient> tmp = nullptr;
Svet Ganov32fa6d02015-05-01 20:47:20 -0700827 if((ret = makeClient(this, cameraCb, opPackageName, cameraId, facing, clientPid,
Ruben Brunkcc776712015-02-17 20:18:47 -0800828 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
829 /*out*/&tmp)) != NO_ERROR) {
830 return ret;
831 }
832 client = static_cast<CLIENT*>(tmp.get());
833
834 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
835 __FUNCTION__);
836
837 if ((ret = client->initialize(mModule)) != OK) {
838 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
839 return ret;
840 }
841
842 sp<IBinder> remoteCallback = client->getRemote();
843 if (remoteCallback != nullptr) {
844 remoteCallback->linkToDeath(this);
845 }
846
847 // Update shim paremeters for legacy clients
848 if (effectiveApiLevel == API_1) {
849 // Assume we have always received a Client subclass for API1
850 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
851 String8 rawParams = shimClient->getParameters();
852 CameraParameters params(rawParams);
853
854 auto cameraState = getCameraState(cameraId);
855 if (cameraState != nullptr) {
856 cameraState->setShimParams(params);
857 } else {
858 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
859 __FUNCTION__, cameraId.string());
860 }
861 }
862
863 if (shimUpdateOnly) {
864 // If only updating legacy shim parameters, immediately disconnect client
865 mServiceLock.unlock();
866 client->disconnect();
867 mServiceLock.lock();
868 } else {
869 // Otherwise, add client to active clients list
870 finishConnectLocked(client, partial);
871 }
872 } // lock is destroyed, allow further connect calls
873
874 // Important: release the mutex here so the client can call back into the service from its
875 // destructor (can be at the end of the call)
876 device = client;
877 return NO_ERROR;
878}
879
Mathias Agopian65ab4712010-07-14 17:59:35 -0700880} // namespace android
881
882#endif