blob: 9b7163aa1ddf4c41722e426cac078edffb92833f [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"
Ronghua Wu022ed722015-05-11 15:15:09 -070041#include "media/RingBuffer.h"
Ruben Brunkcc776712015-02-17 20:18:47 -080042#include "utils/AutoConditionLock.h"
43#include "utils/ClientManager.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
Igor Murashkin634a5152013-02-20 17:15:11 -080086 // Implementation of BinderService<T>
Mathias Agopian5462fc92010-07-14 18:41:18 -070087 static char const* getServiceName() { return "media.camera"; }
Mathias Agopian65ab4712010-07-14 17:59:35 -070088
89 CameraService();
90 virtual ~CameraService();
91
Igor Murashkin634a5152013-02-20 17:15:11 -080092 /////////////////////////////////////////////////////////////////////
Igor Murashkincba2c162013-03-20 15:56:31 -070093 // HAL Callbacks
Ruben Brunkcc776712015-02-17 20:18:47 -080094 virtual void onDeviceStatusChanged(camera_device_status_t cameraId,
95 camera_device_status_t newStatus);
Chien-Yu Chen88da5262015-02-17 13:56:46 -080096 virtual void onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -080097 ICameraServiceListener::TorchStatus
98 newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -070099
100 /////////////////////////////////////////////////////////////////////
Igor Murashkin634a5152013-02-20 17:15:11 -0800101 // ICameraService
Mathias Agopian65ab4712010-07-14 17:59:35 -0700102 virtual int32_t getNumberOfCameras();
103 virtual status_t getCameraInfo(int cameraId,
104 struct CameraInfo* cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -0700105 virtual status_t getCameraCharacteristics(int cameraId,
106 CameraMetadata* cameraInfo);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800107 virtual status_t getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800108
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700109 virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000110 const String16& clientPackageName, int clientUid,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700111 /*out*/
112 sp<ICamera>& device);
113
Zhijun Heb10cdad2014-06-16 16:38:35 -0700114 virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000115 int halVersion, const String16& clientPackageName, int clientUid,
Zhijun Heb10cdad2014-06-16 16:38:35 -0700116 /*out*/
117 sp<ICamera>& device);
118
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700119 virtual status_t connectDevice(
Igor Murashkine7ee7632013-06-11 18:10:18 -0700120 const sp<ICameraDeviceCallbacks>& cameraCb,
121 int cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000122 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700123 int clientUid,
124 /*out*/
125 sp<ICameraDeviceUser>& device);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700126
Igor Murashkinbfc99152013-02-27 12:55:20 -0800127 virtual status_t addListener(const sp<ICameraServiceListener>& listener);
128 virtual status_t removeListener(
129 const sp<ICameraServiceListener>& listener);
130
Igor Murashkin65d14b92014-06-17 12:03:20 -0700131 virtual status_t getLegacyParameters(
132 int cameraId,
133 /*out*/
134 String16* parameters);
135
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800136 virtual status_t setTorchMode(const String16& cameraId, bool enabled,
137 const sp<IBinder>& clientBinder);
138
Ruben Brunk6267b532015-04-30 17:44:07 -0700139 virtual void notifySystemEvent(int32_t eventId, const int32_t* args, size_t length);
Ruben Brunk36597b22015-03-20 22:15:57 -0700140
Igor Murashkin65d14b92014-06-17 12:03:20 -0700141 // OK = supports api of that version, -EOPNOTSUPP = does not support
142 virtual status_t supportsCameraApi(
143 int cameraId, int apiVersion);
144
Igor Murashkin634a5152013-02-20 17:15:11 -0800145 // Extra permissions checks
Mathias Agopian65ab4712010-07-14 17:59:35 -0700146 virtual status_t onTransact(uint32_t code, const Parcel& data,
147 Parcel* reply, uint32_t flags);
Igor Murashkin634a5152013-02-20 17:15:11 -0800148
149 virtual status_t dump(int fd, const Vector<String16>& args);
150
151 /////////////////////////////////////////////////////////////////////
152 // Client functionality
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153
154 enum sound_kind {
155 SOUND_SHUTTER = 0,
156 SOUND_RECORDING = 1,
157 NUM_SOUNDS
158 };
159
160 void loadSound();
161 void playSound(sound_kind kind);
162 void releaseSound();
163
Igor Murashkin98e24722013-06-19 19:51:04 -0700164 /////////////////////////////////////////////////////////////////////
165 // CameraDeviceFactory functionality
166 int getDeviceVersion(int cameraId, int* facing = NULL);
167
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700168 /////////////////////////////////////////////////////////////////////
169 // Shared utilities
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700170 static status_t filterGetInfoErrorCode(status_t err);
Igor Murashkin634a5152013-02-20 17:15:11 -0800171
172 /////////////////////////////////////////////////////////////////////
173 // CameraClient functionality
174
Igor Murashkin634a5152013-02-20 17:15:11 -0800175 class BasicClient : public virtual RefBase {
176 public:
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800177 virtual status_t initialize(CameraModule *module) = 0;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700178 virtual void disconnect();
Igor Murashkin634a5152013-02-20 17:15:11 -0800179
Igor Murashkine7ee7632013-06-11 18:10:18 -0700180 // because we can't virtually inherit IInterface, which breaks
181 // virtual inheritance
182 virtual sp<IBinder> asBinderWrapper() = 0;
183
Ruben Brunk9efdf952015-03-18 23:11:57 -0700184 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700185 sp<IBinder> getRemote() {
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800186 return mRemoteBinder;
Igor Murashkin634a5152013-02-20 17:15:11 -0800187 }
188
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700189 virtual status_t dump(int fd, const Vector<String16>& args) = 0;
Igor Murashkine7ee7632013-06-11 18:10:18 -0700190
Ruben Brunkcc776712015-02-17 20:18:47 -0800191 // Return the package name for this client
192 virtual String16 getPackageName() const;
193
194 // Notify client about a fatal error
195 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
196 const CaptureResultExtras& resultExtras) = 0;
197
Ruben Brunk6267b532015-04-30 17:44:07 -0700198 // Get the UID of the application client using this
199 virtual uid_t getClientUid() const;
200
Ruben Brunkcc776712015-02-17 20:18:47 -0800201 // Get the PID of the application client using this
202 virtual int getClientPid() const;
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700203
204 // Check what API level is used for this client. This is used to determine which
205 // superclass this can be cast to.
206 virtual bool canCastToApiClient(apiLevel level) const;
Igor Murashkin634a5152013-02-20 17:15:11 -0800207 protected:
208 BasicClient(const sp<CameraService>& cameraService,
209 const sp<IBinder>& remoteCallback,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000210 const String16& clientPackageName,
Igor Murashkin634a5152013-02-20 17:15:11 -0800211 int cameraId,
212 int cameraFacing,
213 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800214 uid_t clientUid,
Igor Murashkin634a5152013-02-20 17:15:11 -0800215 int servicePid);
216
217 virtual ~BasicClient();
218
219 // the instance is in the middle of destruction. When this is set,
220 // the instance should not be accessed from callback.
221 // CameraService's mClientLock should be acquired to access this.
222 // - subclasses should set this to true in their destructors.
223 bool mDestructionStarted;
224
225 // these are initialized in the constructor.
226 sp<CameraService> mCameraService; // immutable after constructor
227 int mCameraId; // immutable after constructor
228 int mCameraFacing; // immutable after constructor
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000229 const String16 mClientPackageName;
Igor Murashkin634a5152013-02-20 17:15:11 -0800230 pid_t mClientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800231 uid_t mClientUid; // immutable after constructor
Igor Murashkin634a5152013-02-20 17:15:11 -0800232 pid_t mServicePid; // immutable after constructor
Ruben Brunkcc776712015-02-17 20:18:47 -0800233 bool mDisconnected;
Igor Murashkin634a5152013-02-20 17:15:11 -0800234
235 // - The app-side Binder interface to receive callbacks from us
Igor Murashkine7ee7632013-06-11 18:10:18 -0700236 sp<IBinder> mRemoteBinder; // immutable after constructor
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800237
238 // permissions management
239 status_t startCameraOps();
240 status_t finishCameraOps();
241
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800242 private:
243 AppOpsManager mAppOpsManager;
244
245 class OpsCallback : public BnAppOpsCallback {
246 public:
247 OpsCallback(wp<BasicClient> client);
248 virtual void opChanged(int32_t op, const String16& packageName);
249
250 private:
251 wp<BasicClient> mClient;
252
253 }; // class OpsCallback
254
255 sp<OpsCallback> mOpsCallback;
256 // Track whether startCameraOps was called successfully, to avoid
257 // finishing what we didn't start.
258 bool mOpsActive;
259
260 // IAppOpsCallback interface, indirected through opListener
261 virtual void opChanged(int32_t op, const String16& packageName);
262 }; // class BasicClient
Igor Murashkin634a5152013-02-20 17:15:11 -0800263
264 class Client : public BnCamera, public BasicClient
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700265 {
266 public:
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800267 typedef ICameraClient TCamCallbacks;
268
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700269 // ICamera interface (see ICamera for details)
270 virtual void disconnect();
271 virtual status_t connect(const sp<ICameraClient>& client) = 0;
272 virtual status_t lock() = 0;
273 virtual status_t unlock() = 0;
Eino-Ville Talvala1ce7c342013-08-21 13:57:21 -0700274 virtual status_t setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700275 virtual void setPreviewCallbackFlag(int flag) = 0;
Eino-Ville Talvala3ee35502013-04-02 15:45:11 -0700276 virtual status_t setPreviewCallbackTarget(
277 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700278 virtual status_t startPreview() = 0;
279 virtual void stopPreview() = 0;
280 virtual bool previewEnabled() = 0;
281 virtual status_t storeMetaDataInBuffers(bool enabled) = 0;
282 virtual status_t startRecording() = 0;
283 virtual void stopRecording() = 0;
284 virtual bool recordingEnabled() = 0;
285 virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
286 virtual status_t autoFocus() = 0;
287 virtual status_t cancelAutoFocus() = 0;
288 virtual status_t takePicture(int msgType) = 0;
289 virtual status_t setParameters(const String8& params) = 0;
290 virtual String8 getParameters() const = 0;
291 virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
292
293 // Interface used by CameraService
294 Client(const sp<CameraService>& cameraService,
295 const sp<ICameraClient>& cameraClient,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000296 const String16& clientPackageName,
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700297 int cameraId,
298 int cameraFacing,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700299 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800300 uid_t clientUid,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700301 int servicePid);
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700302 ~Client();
303
304 // return our camera client
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800305 const sp<ICameraClient>& getRemoteCallback() {
306 return mRemoteCallback;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700307 }
308
Igor Murashkine7ee7632013-06-11 18:10:18 -0700309 virtual sp<IBinder> asBinderWrapper() {
Marco Nelissen06b46062014-11-14 07:58:25 -0800310 return asBinder(this);
Igor Murashkine7ee7632013-06-11 18:10:18 -0700311 }
312
Jianing Weicb0652e2014-03-12 18:29:36 -0700313 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
314 const CaptureResultExtras& resultExtras);
Ruben Brunk0bbf8b22015-04-30 14:35:42 -0700315
316 // Check what API level is used for this client. This is used to determine which
317 // superclass this can be cast to.
318 virtual bool canCastToApiClient(apiLevel level) const;
Ruben Brunkcc776712015-02-17 20:18:47 -0800319 protected:
320 // Convert client from cookie.
321 static sp<CameraService::Client> getClientFromCookie(void* user);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800322
Igor Murashkin634a5152013-02-20 17:15:11 -0800323 // Initialized in constructor
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700324
Igor Murashkin634a5152013-02-20 17:15:11 -0800325 // - The app-side Binder interface to receive callbacks from us
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800326 sp<ICameraClient> mRemoteCallback;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800327
328 }; // class Client
Igor Murashkin634a5152013-02-20 17:15:11 -0800329
Ruben Brunkcc776712015-02-17 20:18:47 -0800330 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
331 sp<CameraService::BasicClient>>> DescriptorPtr;
332
333 /**
334 * A container class for managing active camera clients that are using HAL devices. Active
335 * clients are represented by ClientDescriptor objects that contain strong pointers to the
336 * actual BasicClient subclass binder interface implementation.
337 *
338 * This class manages the eviction behavior for the camera clients. See the parent class
339 * implementation in utils/ClientManager for the specifics of this behavior.
340 */
341 class CameraClientManager :
342 public resource_policy::ClientManager<String8, sp<CameraService::BasicClient>> {
343 public:
344 virtual ~CameraClientManager();
345
346 /**
347 * Return a strong pointer to the active BasicClient for this camera ID, or an empty
348 * if none exists.
349 */
350 sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
351
352 /**
353 * Return a string describing the current state.
354 */
355 String8 toString() const;
356
357 /**
358 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
359 */
360 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
361 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
362 int32_t ownerId);
363
364 /**
365 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
366 * values intialized from a prior ClientDescriptor.
367 */
368 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
369 const CameraService::DescriptorPtr& partial);
370
371 }; // class CameraClientManager
372
Mathias Agopian65ab4712010-07-14 17:59:35 -0700373private:
Igor Murashkin634a5152013-02-20 17:15:11 -0800374
Ruben Brunkcc776712015-02-17 20:18:47 -0800375 /**
376 * Container class for the state of each logical camera device, including: ID, status, and
377 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates
378 * represents the camera devices advertised by the HAL (and any USB devices, when we add
379 * those).
380 *
381 * This container does NOT represent an active camera client. These are represented using
382 * the ClientDescriptors stored in mActiveClientManager.
383 */
384 class CameraState {
385 public:
386 /**
387 * Make a new CameraState and set the ID, cost, and conflicting devices using the values
388 * returned in the HAL's camera_info struct for each device.
389 */
390 CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
391 virtual ~CameraState();
392
393 /**
394 * Return the status for this device.
395 *
396 * This method acquires mStatusLock.
397 */
398 ICameraServiceListener::Status getStatus() const;
399
400 /**
401 * This function updates the status for this camera device, unless the given status
402 * is in the given list of rejected status states, and execute the function passed in
403 * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
404 * if the status has changed.
405 *
406 * This method is idempotent, and will not result in the function passed to
407 * onStatusUpdateLocked being called more than once for the same arguments.
408 * This method aquires mStatusLock.
409 */
410 template<class Func>
411 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
412 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
413 Func onStatusUpdatedLocked);
414
415 /**
416 * Return the last set CameraParameters object generated from the information returned by
417 * the HAL for this device (or an empty CameraParameters object if none has been set).
418 */
419 CameraParameters getShimParams() const;
420
421 /**
422 * Set the CameraParameters for this device.
423 */
424 void setShimParams(const CameraParameters& params);
425
426 /**
427 * Return the resource_cost advertised by the HAL for this device.
428 */
429 int getCost() const;
430
431 /**
432 * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
433 */
434 std::set<String8> getConflicting() const;
435
436 /**
437 * Return the ID of this camera device.
438 */
439 String8 getId() const;
440
441 private:
442 const String8 mId;
443 ICameraServiceListener::Status mStatus; // protected by mStatusLock
444 const int mCost;
445 std::set<String8> mConflicting;
446 mutable Mutex mStatusLock;
447 CameraParameters mShimParams;
448 }; // class CameraState
449
Igor Murashkin634a5152013-02-20 17:15:11 -0800450 // Delay-load the Camera HAL module
451 virtual void onFirstRef();
452
Ruben Brunkcc776712015-02-17 20:18:47 -0800453 // Check if we can connect, before we acquire the service lock.
Ruben Brunk36597b22015-03-20 22:15:57 -0700454 status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid) const;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800455
Ruben Brunkcc776712015-02-17 20:18:47 -0800456 // Handle active client evictions, and update service state.
457 // Only call with with mServiceLock held.
458 status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
459 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
460 /*out*/
461 sp<BasicClient>* client,
462 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800463
Ruben Brunkcc776712015-02-17 20:18:47 -0800464 // Single implementation shared between the various connect calls
465 template<class CALLBACK, class CLIENT>
466 status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000467 const String16& clientPackageName, int clientUid, apiLevel effectiveApiLevel,
Ruben Brunkcc776712015-02-17 20:18:47 -0800468 bool legacyMode, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800469
Ruben Brunkcc776712015-02-17 20:18:47 -0800470 // Lock guarding camera service state
Mathias Agopian65ab4712010-07-14 17:59:35 -0700471 Mutex mServiceLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800472
473 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
474 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
475
476 // Return NO_ERROR if the device with a give ID can be connected to
477 status_t checkIfDeviceIsUsable(const String8& cameraId) const;
478
479 // Container for managing currently active application-layer clients
480 CameraClientManager mActiveClientManager;
481
482 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
483 std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
484
485 // Mutex guarding mCameraStates map
486 mutable Mutex mCameraStatesLock;
487
488 // Circular buffer for storing event logging for dumps
489 RingBuffer<String8> mEventLog;
Ruben Brunka8ca9152015-04-07 14:23:40 -0700490 Mutex mLogLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800491
Ruben Brunk6267b532015-04-30 17:44:07 -0700492 // Currently allowed user IDs
493 std::set<userid_t> mAllowedUsers;
Ruben Brunk36597b22015-03-20 22:15:57 -0700494
Ruben Brunkcc776712015-02-17 20:18:47 -0800495 /**
496 * Get the camera state for a given camera id.
497 *
498 * This acquires mCameraStatesLock.
499 */
500 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
501
502 /**
503 * Evict client who's remote binder has died. Returns true if this client was in the active
504 * list and was disconnected.
505 *
506 * This method acquires mServiceLock.
507 */
508 bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
509
510 /**
511 * Remove the given client from the active clients list; does not disconnect the client.
512 *
513 * This method acquires mServiceLock.
514 */
515 void removeByClient(const BasicClient* client);
516
517 /**
518 * Add new client to active clients list after conflicting clients have disconnected using the
519 * values set in the partial descriptor passed in to construct the actual client descriptor.
520 * This is typically called at the end of a connect call.
521 *
522 * This method must be called with mServiceLock held.
523 */
524 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
525
526 /**
527 * Returns the integer corresponding to the given camera ID string, or -1 on failure.
528 */
529 static int cameraIdToInt(const String8& cameraId);
530
531 /**
532 * Remove a single client corresponding to the given camera id from the list of active clients.
533 * If none exists, return an empty strongpointer.
534 *
535 * This method must be called with mServiceLock held.
536 */
537 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
538
539 /**
Ruben Brunk36597b22015-03-20 22:15:57 -0700540 * Handle a notification that the current device user has changed.
541 */
Ruben Brunk6267b532015-04-30 17:44:07 -0700542 void doUserSwitch(const int32_t* newUserId, size_t length);
Ruben Brunk36597b22015-03-20 22:15:57 -0700543
544 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700545 * Add an event log message.
Ruben Brunkcc776712015-02-17 20:18:47 -0800546 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700547 void logEvent(const char* event);
Ruben Brunkcc776712015-02-17 20:18:47 -0800548
549 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700550 * Add an event log message that a client has been disconnected.
Ruben Brunkcc776712015-02-17 20:18:47 -0800551 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700552 void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
553
554 /**
555 * Add an event log message that a client has been connected.
556 */
557 void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
558
559 /**
560 * Add an event log message that a client's connect attempt has been rejected.
561 */
562 void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
563 const char* reason);
564
565 /**
566 * Add an event log message that the current device user has been switched.
567 */
Ruben Brunk6267b532015-04-30 17:44:07 -0700568 void logUserSwitch(const std::set<userid_t>& oldUserIds,
569 const std::set<userid_t>& newUserIds);
Ruben Brunka8ca9152015-04-07 14:23:40 -0700570
571 /**
572 * Add an event log message that a device has been removed by the HAL
573 */
574 void logDeviceRemoved(const char* cameraId, const char* reason);
575
576 /**
577 * Add an event log message that a device has been added by the HAL
578 */
579 void logDeviceAdded(const char* cameraId, const char* reason);
580
581 /**
582 * Add an event log message that a client has unexpectedly died.
583 */
584 void logClientDied(int clientPid, const char* reason);
Ruben Brunkcc776712015-02-17 20:18:47 -0800585
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700586 /**
587 * Add a event log message that a serious service-level error has occured
588 */
589 void logServiceError(const char* msg, int errorCode);
590
591 /**
592 * Dump the event log to an FD
593 */
594 void dumpEventLog(int fd);
595
Mathias Agopian65ab4712010-07-14 17:59:35 -0700596 int mNumberOfCameras;
597
Mathias Agopian65ab4712010-07-14 17:59:35 -0700598 // sounds
Chih-Chung Changff4f55c2011-10-17 19:03:12 +0800599 MediaPlayer* newMediaPlayer(const char *file);
600
Mathias Agopian65ab4712010-07-14 17:59:35 -0700601 Mutex mSoundLock;
602 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS];
603 int mSoundRef; // reference count (release all MediaPlayer when 0)
604
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800605 CameraModule* mModule;
Igor Murashkinecf17e82012-10-02 16:05:11 -0700606
Ruben Brunkcc776712015-02-17 20:18:47 -0800607 // Guarded by mStatusListenerMutex
608 std::vector<sp<ICameraServiceListener>> mListenerList;
609 Mutex mStatusListenerLock;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800610
Ruben Brunkcc776712015-02-17 20:18:47 -0800611 /**
612 * Update the status for the given camera id (if that device exists), and broadcast the
613 * status update to all current ICameraServiceListeners if the status has changed. Any
614 * statuses in rejectedSourceStates will be ignored.
615 *
616 * This method must be idempotent.
617 * This method acquires mStatusLock and mStatusListenerLock.
618 */
619 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
620 std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
621 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
Igor Murashkinbfc99152013-02-27 12:55:20 -0800622
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800623 // flashlight control
624 sp<CameraFlashlight> mFlashlight;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800625 // guard mTorchStatusMap
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800626 Mutex mTorchStatusMutex;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800627 // guard mTorchClientMap
628 Mutex mTorchClientMapMutex;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800629 // camera id -> torch status
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800630 KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800631 // camera id -> torch client binder
632 // only store the last client that turns on each camera's torch mode
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800633 KeyedVector<String8, sp<IBinder> > mTorchClientMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800634
635 // check and handle if torch client's process has died
636 void handleTorchClientBinderDied(const wp<IBinder> &who);
637
638 // handle torch mode status change and invoke callbacks. mTorchStatusMutex
639 // should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800640 void onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800641 ICameraServiceListener::TorchStatus newStatus);
642
643 // get a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800644 status_t getTorchStatusLocked(const String8 &cameraId,
645 ICameraServiceListener::TorchStatus *status) const;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800646
647 // set a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800648 status_t setTorchStatusLocked(const String8 &cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800649 ICameraServiceListener::TorchStatus status);
650
Igor Murashkinecf17e82012-10-02 16:05:11 -0700651 // IBinder::DeathRecipient implementation
Igor Murashkinbfc99152013-02-27 12:55:20 -0800652 virtual void binderDied(const wp<IBinder> &who);
Igor Murashkin634a5152013-02-20 17:15:11 -0800653
654 // Helpers
Igor Murashkinbfc99152013-02-27 12:55:20 -0800655
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800656 bool setUpVendorTags();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700657
658 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700659 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
660 *
661 * Returns OK on success, or a negative error code.
662 */
663 status_t initializeShimMetadata(int cameraId);
664
665 /**
Igor Murashkin65d14b92014-06-17 12:03:20 -0700666 * Get the cached CameraParameters for the camera. If they haven't been
667 * cached yet, then initialize them for the first time.
668 *
669 * Returns OK on success, or a negative error code.
670 */
671 status_t getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
672
673 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700674 * Generate the CameraCharacteristics metadata required by the Camera2 API
675 * from the available HAL1 CameraParameters and CameraInfo.
676 *
677 * Returns OK on success, or a negative error code.
678 */
679 status_t generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
680
Ruben Brunkcc776712015-02-17 20:18:47 -0800681 static int getCallingPid();
682
683 static int getCallingUid();
684
Ruben Brunkb2119af2014-05-09 19:57:56 -0700685 /**
Ruben Brunkcc776712015-02-17 20:18:47 -0800686 * Get the current system time as a formatted string.
Ruben Brunkb2119af2014-05-09 19:57:56 -0700687 */
Ruben Brunkcc776712015-02-17 20:18:47 -0800688 static String8 getFormattedCurrentTime();
689
690 /**
691 * Get the camera eviction priority from the current process state given by ActivityManager.
692 */
693 static int getCameraPriorityFromProcState(int procState);
694
695 static status_t makeClient(const sp<CameraService>& cameraService,
696 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
697 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
698 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
699 /*out*/sp<BasicClient>* client);
Ruben Brunk6267b532015-04-30 17:44:07 -0700700
701 status_t checkCameraAccess(const String16& opPackageName);
702
703 static String8 toString(std::set<userid_t> intSet);
704
Mathias Agopian65ab4712010-07-14 17:59:35 -0700705};
706
Ruben Brunkcc776712015-02-17 20:18:47 -0800707template<class Func>
708void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
709 const String8& cameraId,
710 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
711 Func onStatusUpdatedLocked) {
712 Mutex::Autolock lock(mStatusLock);
713 ICameraServiceListener::Status oldStatus = mStatus;
714 mStatus = status;
715
716 if (oldStatus == status) {
717 return;
718 }
719
720 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
721 cameraId.string(), oldStatus, status);
722
723 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
724 (status != ICameraServiceListener::STATUS_PRESENT &&
725 status != ICameraServiceListener::STATUS_ENUMERATING)) {
726
727 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
728 __FUNCTION__);
729 mStatus = oldStatus;
730 return;
731 }
732
733 /**
734 * Sometimes we want to conditionally do a transition.
735 * For example if a client disconnects, we want to go to PRESENT
736 * only if we weren't already in NOT_PRESENT or ENUMERATING.
737 */
738 for (auto& rejectStatus : rejectSourceStates) {
739 if (oldStatus == rejectStatus) {
740 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
741 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
742 mStatus = oldStatus;
743 return;
744 }
745 }
746
747 onStatusUpdatedLocked(cameraId, status);
748}
749
750
751template<class CALLBACK, class CLIENT>
752status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000753 int halVersion, const String16& clientPackageName, int clientUid,
Ruben Brunkcc776712015-02-17 20:18:47 -0800754 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
755 /*out*/sp<CLIENT>& device) {
756 status_t ret = NO_ERROR;
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000757 String8 clientName8(clientPackageName);
Ruben Brunkcc776712015-02-17 20:18:47 -0800758 int clientPid = getCallingPid();
759
Ruben Brunka8ca9152015-04-07 14:23:40 -0700760 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
Ruben Brunkcc776712015-02-17 20:18:47 -0800761 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Ruben Brunka8ca9152015-04-07 14:23:40 -0700762 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
763 static_cast<int>(effectiveApiLevel));
Ruben Brunkcc776712015-02-17 20:18:47 -0800764
Ruben Brunkcc776712015-02-17 20:18:47 -0800765 sp<CLIENT> client = nullptr;
766 {
767 // Acquire mServiceLock and prevent other clients from connecting
768 std::unique_ptr<AutoConditionLock> lock =
769 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
Ruben Brunk36597b22015-03-20 22:15:57 -0700770
Ruben Brunkcc776712015-02-17 20:18:47 -0800771 if (lock == nullptr) {
772 ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
773 , clientPid);
774 return -EBUSY;
775 }
776
Ruben Brunk36597b22015-03-20 22:15:57 -0700777 // Enforce client permissions and do basic sanity checks
778 if((ret = validateConnectLocked(cameraId, /*inout*/clientUid)) != NO_ERROR) {
779 return ret;
780 }
Ruben Brunk36597b22015-03-20 22:15:57 -0700781
Ruben Brunkcc776712015-02-17 20:18:47 -0800782 // Check the shim parameters after acquiring lock, if they have already been updated and
783 // we were doing a shim update, return immediately
784 if (shimUpdateOnly) {
785 auto cameraState = getCameraState(cameraId);
786 if (cameraState != nullptr) {
787 if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
788 }
789 }
790
791 sp<BasicClient> clientTmp = nullptr;
792 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
793 if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
794 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
795 /*out*/&partial)) != NO_ERROR) {
796 return ret;
797 }
798
799 if (clientTmp.get() != nullptr) {
800 // Handle special case for API1 MediaRecorder where the existing client is returned
801 device = static_cast<CLIENT*>(clientTmp.get());
802 return NO_ERROR;
803 }
804
805 // give flashlight a chance to close devices if necessary.
806 mFlashlight->prepareDeviceOpen(cameraId);
807
808 // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
809 int id = cameraIdToInt(cameraId);
810 if (id == -1) {
811 ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
812 cameraId.string());
813 return BAD_VALUE;
814 }
815
816 int facing = -1;
817 int deviceVersion = getDeviceVersion(id, /*out*/&facing);
818 sp<BasicClient> tmp = nullptr;
Svetoslav Ganov280405a2015-05-12 02:19:27 +0000819 if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
Ruben Brunkcc776712015-02-17 20:18:47 -0800820 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
821 /*out*/&tmp)) != NO_ERROR) {
822 return ret;
823 }
824 client = static_cast<CLIENT*>(tmp.get());
825
826 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
827 __FUNCTION__);
828
829 if ((ret = client->initialize(mModule)) != OK) {
830 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
831 return ret;
832 }
833
834 sp<IBinder> remoteCallback = client->getRemote();
835 if (remoteCallback != nullptr) {
836 remoteCallback->linkToDeath(this);
837 }
838
839 // Update shim paremeters for legacy clients
840 if (effectiveApiLevel == API_1) {
841 // Assume we have always received a Client subclass for API1
842 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
843 String8 rawParams = shimClient->getParameters();
844 CameraParameters params(rawParams);
845
846 auto cameraState = getCameraState(cameraId);
847 if (cameraState != nullptr) {
848 cameraState->setShimParams(params);
849 } else {
850 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
851 __FUNCTION__, cameraId.string());
852 }
853 }
854
855 if (shimUpdateOnly) {
856 // If only updating legacy shim parameters, immediately disconnect client
857 mServiceLock.unlock();
858 client->disconnect();
859 mServiceLock.lock();
860 } else {
861 // Otherwise, add client to active clients list
862 finishConnectLocked(client, partial);
863 }
864 } // lock is destroyed, allow further connect calls
865
866 // Important: release the mutex here so the client can call back into the service from its
867 // destructor (can be at the end of the call)
868 device = client;
869 return NO_ERROR;
870}
871
Mathias Agopian65ab4712010-07-14 17:59:35 -0700872} // namespace android
873
874#endif