blob: 84e61c5f2814b6cb3bb1b82c9d6c1aa41075abf4 [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 Brunkcc776712015-02-17 20:18:47 -080068 enum apiLevel {
69 API_1 = 1,
70 API_2 = 2
71 };
72
73 // Process States (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
74 static const int PROCESS_STATE_NONEXISTENT = -1;
75 static const int PROCESS_STATE_PERSISTENT = 0;
76 static const int PROCESS_STATE_PERSISTENT_UI = 1;
77 static const int PROCESS_STATE_TOP = 2;
78 static const int PROCESS_STATE_IMPORTANT_FOREGROUND = 3;
79 static const int PROCESS_STATE_IMPORTANT_BACKGROUND = 4;
80 static const int PROCESS_STATE_BACKUP = 5;
81 static const int PROCESS_STATE_HEAVY_WEIGHT = 6;
82 static const int PROCESS_STATE_SERVICE = 7;
83 static const int PROCESS_STATE_RECEIVER = 8;
84 static const int PROCESS_STATE_HOME = 9;
85 static const int PROCESS_STATE_LAST_ACTIVITY = 10;
86 static const int PROCESS_STATE_CACHED_ACTIVITY = 11;
87 static const int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12;
88 static const int PROCESS_STATE_CACHED_EMPTY = 13;
89
90 // 3 second busy timeout when other clients are connecting
91 static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
92
Ruben Brunk4f9576b2015-04-10 17:26:56 -070093 // 1 second busy timeout when other clients are disconnecting
94 static const nsecs_t DEFAULT_DISCONNECT_TIMEOUT_NS = 1000000000;
95
Ruben Brunkcc776712015-02-17 20:18:47 -080096 // Default number of messages to store in eviction log
Ruben Brunka8ca9152015-04-07 14:23:40 -070097 static const size_t DEFAULT_EVENT_LOG_LENGTH = 100;
Ruben Brunkcc776712015-02-17 20:18:47 -080098
Ruben Brunk36597b22015-03-20 22:15:57 -070099 enum {
100 // Default last user id
101 DEFAULT_LAST_USER_ID = 0,
102 };
103
Igor Murashkin634a5152013-02-20 17:15:11 -0800104 // Implementation of BinderService<T>
Mathias Agopian5462fc92010-07-14 18:41:18 -0700105 static char const* getServiceName() { return "media.camera"; }
Mathias Agopian65ab4712010-07-14 17:59:35 -0700106
107 CameraService();
108 virtual ~CameraService();
109
Igor Murashkin634a5152013-02-20 17:15:11 -0800110 /////////////////////////////////////////////////////////////////////
Igor Murashkincba2c162013-03-20 15:56:31 -0700111 // HAL Callbacks
Ruben Brunkcc776712015-02-17 20:18:47 -0800112 virtual void onDeviceStatusChanged(camera_device_status_t cameraId,
113 camera_device_status_t newStatus);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800114 virtual void onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800115 ICameraServiceListener::TorchStatus
116 newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700117
118 /////////////////////////////////////////////////////////////////////
Igor Murashkin634a5152013-02-20 17:15:11 -0800119 // ICameraService
Mathias Agopian65ab4712010-07-14 17:59:35 -0700120 virtual int32_t getNumberOfCameras();
121 virtual status_t getCameraInfo(int cameraId,
122 struct CameraInfo* cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -0700123 virtual status_t getCameraCharacteristics(int cameraId,
124 CameraMetadata* cameraInfo);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800125 virtual status_t getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800126
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700127 virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
128 const String16& clientPackageName, int clientUid,
129 /*out*/
130 sp<ICamera>& device);
131
Zhijun Heb10cdad2014-06-16 16:38:35 -0700132 virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
133 int halVersion, const String16& clientPackageName, int clientUid,
134 /*out*/
135 sp<ICamera>& device);
136
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700137 virtual status_t connectDevice(
Igor Murashkine7ee7632013-06-11 18:10:18 -0700138 const sp<ICameraDeviceCallbacks>& cameraCb,
139 int cameraId,
140 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700141 int clientUid,
142 /*out*/
143 sp<ICameraDeviceUser>& device);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700144
Igor Murashkinbfc99152013-02-27 12:55:20 -0800145 virtual status_t addListener(const sp<ICameraServiceListener>& listener);
146 virtual status_t removeListener(
147 const sp<ICameraServiceListener>& listener);
148
Igor Murashkin65d14b92014-06-17 12:03:20 -0700149 virtual status_t getLegacyParameters(
150 int cameraId,
151 /*out*/
152 String16* parameters);
153
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800154 virtual status_t setTorchMode(const String16& cameraId, bool enabled,
155 const sp<IBinder>& clientBinder);
156
Ruben Brunk36597b22015-03-20 22:15:57 -0700157 virtual void notifySystemEvent(int eventId, int arg0);
158
Igor Murashkin65d14b92014-06-17 12:03:20 -0700159 // OK = supports api of that version, -EOPNOTSUPP = does not support
160 virtual status_t supportsCameraApi(
161 int cameraId, int apiVersion);
162
Igor Murashkin634a5152013-02-20 17:15:11 -0800163 // Extra permissions checks
Mathias Agopian65ab4712010-07-14 17:59:35 -0700164 virtual status_t onTransact(uint32_t code, const Parcel& data,
165 Parcel* reply, uint32_t flags);
Igor Murashkin634a5152013-02-20 17:15:11 -0800166
167 virtual status_t dump(int fd, const Vector<String16>& args);
168
169 /////////////////////////////////////////////////////////////////////
170 // Client functionality
Mathias Agopian65ab4712010-07-14 17:59:35 -0700171
172 enum sound_kind {
173 SOUND_SHUTTER = 0,
174 SOUND_RECORDING = 1,
175 NUM_SOUNDS
176 };
177
178 void loadSound();
179 void playSound(sound_kind kind);
180 void releaseSound();
181
Igor Murashkin98e24722013-06-19 19:51:04 -0700182 /////////////////////////////////////////////////////////////////////
183 // CameraDeviceFactory functionality
184 int getDeviceVersion(int cameraId, int* facing = NULL);
185
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700186 /////////////////////////////////////////////////////////////////////
187 // Shared utilities
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700188 static status_t filterGetInfoErrorCode(status_t err);
Igor Murashkin634a5152013-02-20 17:15:11 -0800189
190 /////////////////////////////////////////////////////////////////////
191 // CameraClient functionality
192
Igor Murashkin634a5152013-02-20 17:15:11 -0800193 class BasicClient : public virtual RefBase {
194 public:
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800195 virtual status_t initialize(CameraModule *module) = 0;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700196 virtual void disconnect();
Igor Murashkin634a5152013-02-20 17:15:11 -0800197
Igor Murashkine7ee7632013-06-11 18:10:18 -0700198 // because we can't virtually inherit IInterface, which breaks
199 // virtual inheritance
200 virtual sp<IBinder> asBinderWrapper() = 0;
201
Ruben Brunk9efdf952015-03-18 23:11:57 -0700202 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700203 sp<IBinder> getRemote() {
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800204 return mRemoteBinder;
Igor Murashkin634a5152013-02-20 17:15:11 -0800205 }
206
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700207 virtual status_t dump(int fd, const Vector<String16>& args) = 0;
Igor Murashkine7ee7632013-06-11 18:10:18 -0700208
Ruben Brunkcc776712015-02-17 20:18:47 -0800209 // Return the package name for this client
210 virtual String16 getPackageName() const;
211
212 // Notify client about a fatal error
213 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
214 const CaptureResultExtras& resultExtras) = 0;
215
216 // Get the PID of the application client using this
217 virtual int getClientPid() const;
Igor Murashkin634a5152013-02-20 17:15:11 -0800218 protected:
219 BasicClient(const sp<CameraService>& cameraService,
220 const sp<IBinder>& remoteCallback,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800221 const String16& clientPackageName,
Igor Murashkin634a5152013-02-20 17:15:11 -0800222 int cameraId,
223 int cameraFacing,
224 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800225 uid_t clientUid,
Igor Murashkin634a5152013-02-20 17:15:11 -0800226 int servicePid);
227
228 virtual ~BasicClient();
229
230 // the instance is in the middle of destruction. When this is set,
231 // the instance should not be accessed from callback.
232 // CameraService's mClientLock should be acquired to access this.
233 // - subclasses should set this to true in their destructors.
234 bool mDestructionStarted;
235
236 // these are initialized in the constructor.
237 sp<CameraService> mCameraService; // immutable after constructor
238 int mCameraId; // immutable after constructor
239 int mCameraFacing; // immutable after constructor
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800240 const String16 mClientPackageName;
Igor Murashkin634a5152013-02-20 17:15:11 -0800241 pid_t mClientPid;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800242 uid_t mClientUid; // immutable after constructor
Igor Murashkin634a5152013-02-20 17:15:11 -0800243 pid_t mServicePid; // immutable after constructor
Ruben Brunkcc776712015-02-17 20:18:47 -0800244 bool mDisconnected;
Igor Murashkin634a5152013-02-20 17:15:11 -0800245
246 // - The app-side Binder interface to receive callbacks from us
Igor Murashkine7ee7632013-06-11 18:10:18 -0700247 sp<IBinder> mRemoteBinder; // immutable after constructor
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800248
249 // permissions management
250 status_t startCameraOps();
251 status_t finishCameraOps();
252
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800253 private:
254 AppOpsManager mAppOpsManager;
255
256 class OpsCallback : public BnAppOpsCallback {
257 public:
258 OpsCallback(wp<BasicClient> client);
259 virtual void opChanged(int32_t op, const String16& packageName);
260
261 private:
262 wp<BasicClient> mClient;
263
264 }; // class OpsCallback
265
266 sp<OpsCallback> mOpsCallback;
267 // Track whether startCameraOps was called successfully, to avoid
268 // finishing what we didn't start.
269 bool mOpsActive;
270
271 // IAppOpsCallback interface, indirected through opListener
272 virtual void opChanged(int32_t op, const String16& packageName);
273 }; // class BasicClient
Igor Murashkin634a5152013-02-20 17:15:11 -0800274
275 class Client : public BnCamera, public BasicClient
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700276 {
277 public:
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800278 typedef ICameraClient TCamCallbacks;
279
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700280 // ICamera interface (see ICamera for details)
281 virtual void disconnect();
282 virtual status_t connect(const sp<ICameraClient>& client) = 0;
283 virtual status_t lock() = 0;
284 virtual status_t unlock() = 0;
Eino-Ville Talvala1ce7c342013-08-21 13:57:21 -0700285 virtual status_t setPreviewTarget(const sp<IGraphicBufferProducer>& bufferProducer)=0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700286 virtual void setPreviewCallbackFlag(int flag) = 0;
Eino-Ville Talvala3ee35502013-04-02 15:45:11 -0700287 virtual status_t setPreviewCallbackTarget(
288 const sp<IGraphicBufferProducer>& callbackProducer) = 0;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700289 virtual status_t startPreview() = 0;
290 virtual void stopPreview() = 0;
291 virtual bool previewEnabled() = 0;
292 virtual status_t storeMetaDataInBuffers(bool enabled) = 0;
293 virtual status_t startRecording() = 0;
294 virtual void stopRecording() = 0;
295 virtual bool recordingEnabled() = 0;
296 virtual void releaseRecordingFrame(const sp<IMemory>& mem) = 0;
297 virtual status_t autoFocus() = 0;
298 virtual status_t cancelAutoFocus() = 0;
299 virtual status_t takePicture(int msgType) = 0;
300 virtual status_t setParameters(const String8& params) = 0;
301 virtual String8 getParameters() const = 0;
302 virtual status_t sendCommand(int32_t cmd, int32_t arg1, int32_t arg2) = 0;
303
304 // Interface used by CameraService
305 Client(const sp<CameraService>& cameraService,
306 const sp<ICameraClient>& cameraClient,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800307 const String16& clientPackageName,
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700308 int cameraId,
309 int cameraFacing,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700310 int clientPid,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800311 uid_t clientUid,
Igor Murashkinecf17e82012-10-02 16:05:11 -0700312 int servicePid);
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700313 ~Client();
314
315 // return our camera client
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800316 const sp<ICameraClient>& getRemoteCallback() {
317 return mRemoteCallback;
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700318 }
319
Igor Murashkine7ee7632013-06-11 18:10:18 -0700320 virtual sp<IBinder> asBinderWrapper() {
Marco Nelissen06b46062014-11-14 07:58:25 -0800321 return asBinder(this);
Igor Murashkine7ee7632013-06-11 18:10:18 -0700322 }
323
Jianing Weicb0652e2014-03-12 18:29:36 -0700324 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
325 const CaptureResultExtras& resultExtras);
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 protected:
327 // Convert client from cookie.
328 static sp<CameraService::Client> getClientFromCookie(void* user);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800329
Igor Murashkin634a5152013-02-20 17:15:11 -0800330 // Initialized in constructor
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700331
Igor Murashkin634a5152013-02-20 17:15:11 -0800332 // - The app-side Binder interface to receive callbacks from us
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800333 sp<ICameraClient> mRemoteCallback;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800334
335 }; // class Client
Igor Murashkin634a5152013-02-20 17:15:11 -0800336
Ruben Brunkcc776712015-02-17 20:18:47 -0800337 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
338 sp<CameraService::BasicClient>>> DescriptorPtr;
339
340 /**
341 * A container class for managing active camera clients that are using HAL devices. Active
342 * clients are represented by ClientDescriptor objects that contain strong pointers to the
343 * actual BasicClient subclass binder interface implementation.
344 *
345 * This class manages the eviction behavior for the camera clients. See the parent class
346 * implementation in utils/ClientManager for the specifics of this behavior.
347 */
348 class CameraClientManager :
349 public resource_policy::ClientManager<String8, sp<CameraService::BasicClient>> {
350 public:
351 virtual ~CameraClientManager();
352
353 /**
354 * Return a strong pointer to the active BasicClient for this camera ID, or an empty
355 * if none exists.
356 */
357 sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
358
359 /**
360 * Return a string describing the current state.
361 */
362 String8 toString() const;
363
364 /**
365 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
366 */
367 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
368 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
369 int32_t ownerId);
370
371 /**
372 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
373 * values intialized from a prior ClientDescriptor.
374 */
375 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
376 const CameraService::DescriptorPtr& partial);
377
378 }; // class CameraClientManager
379
Mathias Agopian65ab4712010-07-14 17:59:35 -0700380private:
Igor Murashkin634a5152013-02-20 17:15:11 -0800381
Ruben Brunkcc776712015-02-17 20:18:47 -0800382 /**
383 * Container class for the state of each logical camera device, including: ID, status, and
384 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates
385 * represents the camera devices advertised by the HAL (and any USB devices, when we add
386 * those).
387 *
388 * This container does NOT represent an active camera client. These are represented using
389 * the ClientDescriptors stored in mActiveClientManager.
390 */
391 class CameraState {
392 public:
393 /**
394 * Make a new CameraState and set the ID, cost, and conflicting devices using the values
395 * returned in the HAL's camera_info struct for each device.
396 */
397 CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
398 virtual ~CameraState();
399
400 /**
401 * Return the status for this device.
402 *
403 * This method acquires mStatusLock.
404 */
405 ICameraServiceListener::Status getStatus() const;
406
407 /**
408 * This function updates the status for this camera device, unless the given status
409 * is in the given list of rejected status states, and execute the function passed in
410 * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
411 * if the status has changed.
412 *
413 * This method is idempotent, and will not result in the function passed to
414 * onStatusUpdateLocked being called more than once for the same arguments.
415 * This method aquires mStatusLock.
416 */
417 template<class Func>
418 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
419 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
420 Func onStatusUpdatedLocked);
421
422 /**
423 * Return the last set CameraParameters object generated from the information returned by
424 * the HAL for this device (or an empty CameraParameters object if none has been set).
425 */
426 CameraParameters getShimParams() const;
427
428 /**
429 * Set the CameraParameters for this device.
430 */
431 void setShimParams(const CameraParameters& params);
432
433 /**
434 * Return the resource_cost advertised by the HAL for this device.
435 */
436 int getCost() const;
437
438 /**
439 * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
440 */
441 std::set<String8> getConflicting() const;
442
443 /**
444 * Return the ID of this camera device.
445 */
446 String8 getId() const;
447
448 private:
449 const String8 mId;
450 ICameraServiceListener::Status mStatus; // protected by mStatusLock
451 const int mCost;
452 std::set<String8> mConflicting;
453 mutable Mutex mStatusLock;
454 CameraParameters mShimParams;
455 }; // class CameraState
456
Igor Murashkin634a5152013-02-20 17:15:11 -0800457 // Delay-load the Camera HAL module
458 virtual void onFirstRef();
459
Ruben Brunkcc776712015-02-17 20:18:47 -0800460 // Check if we can connect, before we acquire the service lock.
Ruben Brunk36597b22015-03-20 22:15:57 -0700461 status_t validateConnectLocked(const String8& cameraId, /*inout*/int& clientUid) const;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800462
Ruben Brunkcc776712015-02-17 20:18:47 -0800463 // Handle active client evictions, and update service state.
464 // Only call with with mServiceLock held.
465 status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
466 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
467 /*out*/
468 sp<BasicClient>* client,
469 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800470
Ruben Brunkcc776712015-02-17 20:18:47 -0800471 // Single implementation shared between the various connect calls
472 template<class CALLBACK, class CLIENT>
473 status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
474 const String16& clientPackageName, int clientUid, apiLevel effectiveApiLevel,
475 bool legacyMode, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800476
Igor Murashkin634a5152013-02-20 17:15:11 -0800477
Ruben Brunkcc776712015-02-17 20:18:47 -0800478 // Lock guarding camera service state
Mathias Agopian65ab4712010-07-14 17:59:35 -0700479 Mutex mServiceLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800480
481 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
482 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
483
484 // Return NO_ERROR if the device with a give ID can be connected to
485 status_t checkIfDeviceIsUsable(const String8& cameraId) const;
486
487 // Container for managing currently active application-layer clients
488 CameraClientManager mActiveClientManager;
489
490 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
491 std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
492
493 // Mutex guarding mCameraStates map
494 mutable Mutex mCameraStatesLock;
495
496 // Circular buffer for storing event logging for dumps
497 RingBuffer<String8> mEventLog;
Ruben Brunka8ca9152015-04-07 14:23:40 -0700498 Mutex mLogLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800499
Ruben Brunk36597b22015-03-20 22:15:57 -0700500 // UID of last user.
501 int mLastUserId;
502
Ruben Brunkcc776712015-02-17 20:18:47 -0800503 /**
504 * Get the camera state for a given camera id.
505 *
506 * This acquires mCameraStatesLock.
507 */
508 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
509
510 /**
511 * Evict client who's remote binder has died. Returns true if this client was in the active
512 * list and was disconnected.
513 *
514 * This method acquires mServiceLock.
515 */
516 bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
517
518 /**
519 * Remove the given client from the active clients list; does not disconnect the client.
520 *
521 * This method acquires mServiceLock.
522 */
523 void removeByClient(const BasicClient* client);
524
525 /**
526 * Add new client to active clients list after conflicting clients have disconnected using the
527 * values set in the partial descriptor passed in to construct the actual client descriptor.
528 * This is typically called at the end of a connect call.
529 *
530 * This method must be called with mServiceLock held.
531 */
532 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
533
534 /**
535 * Returns the integer corresponding to the given camera ID string, or -1 on failure.
536 */
537 static int cameraIdToInt(const String8& cameraId);
538
539 /**
540 * Remove a single client corresponding to the given camera id from the list of active clients.
541 * If none exists, return an empty strongpointer.
542 *
543 * This method must be called with mServiceLock held.
544 */
545 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
546
547 /**
Ruben Brunk36597b22015-03-20 22:15:57 -0700548 * Handle a notification that the current device user has changed.
549 */
550 void doUserSwitch(int newUserId);
551
552 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700553 * Add an event log message.
Ruben Brunkcc776712015-02-17 20:18:47 -0800554 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700555 void logEvent(const char* event);
Ruben Brunkcc776712015-02-17 20:18:47 -0800556
557 /**
Ruben Brunka8ca9152015-04-07 14:23:40 -0700558 * Add an event log message that a client has been disconnected.
Ruben Brunkcc776712015-02-17 20:18:47 -0800559 */
Ruben Brunka8ca9152015-04-07 14:23:40 -0700560 void logDisconnected(const char* cameraId, int clientPid, const char* clientPackage);
561
562 /**
563 * Add an event log message that a client has been connected.
564 */
565 void logConnected(const char* cameraId, int clientPid, const char* clientPackage);
566
567 /**
568 * Add an event log message that a client's connect attempt has been rejected.
569 */
570 void logRejected(const char* cameraId, int clientPid, const char* clientPackage,
571 const char* reason);
572
573 /**
574 * Add an event log message that the current device user has been switched.
575 */
576 void logUserSwitch(int oldUserId, int newUserId);
577
578 /**
579 * Add an event log message that a device has been removed by the HAL
580 */
581 void logDeviceRemoved(const char* cameraId, const char* reason);
582
583 /**
584 * Add an event log message that a device has been added by the HAL
585 */
586 void logDeviceAdded(const char* cameraId, const char* reason);
587
588 /**
589 * Add an event log message that a client has unexpectedly died.
590 */
591 void logClientDied(int clientPid, const char* reason);
Ruben Brunkcc776712015-02-17 20:18:47 -0800592
Eino-Ville Talvala1527f072015-04-07 15:55:31 -0700593 /**
594 * Add a event log message that a serious service-level error has occured
595 */
596 void logServiceError(const char* msg, int errorCode);
597
598 /**
599 * Dump the event log to an FD
600 */
601 void dumpEventLog(int fd);
602
Mathias Agopian65ab4712010-07-14 17:59:35 -0700603 int mNumberOfCameras;
604
Mathias Agopian65ab4712010-07-14 17:59:35 -0700605 // sounds
Chih-Chung Changff4f55c2011-10-17 19:03:12 +0800606 MediaPlayer* newMediaPlayer(const char *file);
607
Mathias Agopian65ab4712010-07-14 17:59:35 -0700608 Mutex mSoundLock;
609 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS];
610 int mSoundRef; // reference count (release all MediaPlayer when 0)
611
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800612 CameraModule* mModule;
Igor Murashkinecf17e82012-10-02 16:05:11 -0700613
Ruben Brunkcc776712015-02-17 20:18:47 -0800614 // Guarded by mStatusListenerMutex
615 std::vector<sp<ICameraServiceListener>> mListenerList;
616 Mutex mStatusListenerLock;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800617
Ruben Brunkcc776712015-02-17 20:18:47 -0800618 /**
619 * Update the status for the given camera id (if that device exists), and broadcast the
620 * status update to all current ICameraServiceListeners if the status has changed. Any
621 * statuses in rejectedSourceStates will be ignored.
622 *
623 * This method must be idempotent.
624 * This method acquires mStatusLock and mStatusListenerLock.
625 */
626 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
627 std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
628 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
Igor Murashkinbfc99152013-02-27 12:55:20 -0800629
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800630 // flashlight control
631 sp<CameraFlashlight> mFlashlight;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800632 // guard mTorchStatusMap
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800633 Mutex mTorchStatusMutex;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800634 // guard mTorchClientMap
635 Mutex mTorchClientMapMutex;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800636 // camera id -> torch status
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800637 KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800638 // camera id -> torch client binder
639 // only store the last client that turns on each camera's torch mode
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800640 KeyedVector<String8, sp<IBinder> > mTorchClientMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800641
642 // check and handle if torch client's process has died
643 void handleTorchClientBinderDied(const wp<IBinder> &who);
644
645 // handle torch mode status change and invoke callbacks. mTorchStatusMutex
646 // should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800647 void onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800648 ICameraServiceListener::TorchStatus newStatus);
649
650 // get a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800651 status_t getTorchStatusLocked(const String8 &cameraId,
652 ICameraServiceListener::TorchStatus *status) const;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800653
654 // set a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800655 status_t setTorchStatusLocked(const String8 &cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800656 ICameraServiceListener::TorchStatus status);
657
Igor Murashkinecf17e82012-10-02 16:05:11 -0700658 // IBinder::DeathRecipient implementation
Igor Murashkinbfc99152013-02-27 12:55:20 -0800659 virtual void binderDied(const wp<IBinder> &who);
Igor Murashkin634a5152013-02-20 17:15:11 -0800660
661 // Helpers
Igor Murashkinbfc99152013-02-27 12:55:20 -0800662
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800663 bool setUpVendorTags();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700664
665 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700666 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
667 *
668 * Returns OK on success, or a negative error code.
669 */
670 status_t initializeShimMetadata(int cameraId);
671
672 /**
Igor Murashkin65d14b92014-06-17 12:03:20 -0700673 * Get the cached CameraParameters for the camera. If they haven't been
674 * cached yet, then initialize them for the first time.
675 *
676 * Returns OK on success, or a negative error code.
677 */
678 status_t getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
679
680 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700681 * Generate the CameraCharacteristics metadata required by the Camera2 API
682 * from the available HAL1 CameraParameters and CameraInfo.
683 *
684 * Returns OK on success, or a negative error code.
685 */
686 status_t generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
687
Ruben Brunkcc776712015-02-17 20:18:47 -0800688 static int getCallingPid();
689
690 static int getCallingUid();
691
Ruben Brunkb2119af2014-05-09 19:57:56 -0700692 /**
Ruben Brunkcc776712015-02-17 20:18:47 -0800693 * Get the current system time as a formatted string.
Ruben Brunkb2119af2014-05-09 19:57:56 -0700694 */
Ruben Brunkcc776712015-02-17 20:18:47 -0800695 static String8 getFormattedCurrentTime();
696
697 /**
698 * Get the camera eviction priority from the current process state given by ActivityManager.
699 */
700 static int getCameraPriorityFromProcState(int procState);
701
702 static status_t makeClient(const sp<CameraService>& cameraService,
703 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
704 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
705 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
706 /*out*/sp<BasicClient>* client);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700707};
708
Ruben Brunkcc776712015-02-17 20:18:47 -0800709template<class Func>
710void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
711 const String8& cameraId,
712 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
713 Func onStatusUpdatedLocked) {
714 Mutex::Autolock lock(mStatusLock);
715 ICameraServiceListener::Status oldStatus = mStatus;
716 mStatus = status;
717
718 if (oldStatus == status) {
719 return;
720 }
721
722 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
723 cameraId.string(), oldStatus, status);
724
725 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
726 (status != ICameraServiceListener::STATUS_PRESENT &&
727 status != ICameraServiceListener::STATUS_ENUMERATING)) {
728
729 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
730 __FUNCTION__);
731 mStatus = oldStatus;
732 return;
733 }
734
735 /**
736 * Sometimes we want to conditionally do a transition.
737 * For example if a client disconnects, we want to go to PRESENT
738 * only if we weren't already in NOT_PRESENT or ENUMERATING.
739 */
740 for (auto& rejectStatus : rejectSourceStates) {
741 if (oldStatus == rejectStatus) {
742 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
743 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
744 mStatus = oldStatus;
745 return;
746 }
747 }
748
749 onStatusUpdatedLocked(cameraId, status);
750}
751
752
753template<class CALLBACK, class CLIENT>
754status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
755 int halVersion, const String16& clientPackageName, int clientUid,
756 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
757 /*out*/sp<CLIENT>& device) {
758 status_t ret = NO_ERROR;
759 String8 clientName8(clientPackageName);
760 int clientPid = getCallingPid();
761
Ruben Brunka8ca9152015-04-07 14:23:40 -0700762 ALOGI("CameraService::connect call (PID %d \"%s\", camera ID %s) for HAL version %s and "
Ruben Brunkcc776712015-02-17 20:18:47 -0800763 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
Ruben Brunka8ca9152015-04-07 14:23:40 -0700764 (halVersion == -1) ? "default" : std::to_string(halVersion).c_str(),
765 static_cast<int>(effectiveApiLevel));
Ruben Brunkcc776712015-02-17 20:18:47 -0800766
Ruben Brunkcc776712015-02-17 20:18:47 -0800767 sp<CLIENT> client = nullptr;
768 {
769 // Acquire mServiceLock and prevent other clients from connecting
770 std::unique_ptr<AutoConditionLock> lock =
771 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
Ruben Brunk36597b22015-03-20 22:15:57 -0700772
Ruben Brunkcc776712015-02-17 20:18:47 -0800773 if (lock == nullptr) {
774 ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
775 , clientPid);
776 return -EBUSY;
777 }
778
Ruben Brunk36597b22015-03-20 22:15:57 -0700779 // Enforce client permissions and do basic sanity checks
780 if((ret = validateConnectLocked(cameraId, /*inout*/clientUid)) != NO_ERROR) {
781 return ret;
782 }
Ruben Brunka8ca9152015-04-07 14:23:40 -0700783 int userId = multiuser_get_user_id(clientUid);
784
785 if (userId != mLastUserId && clientPid != getpid() ) {
786 // If no previous user ID had been set, set to the user of the caller.
787 logUserSwitch(mLastUserId, userId);
788 LOG_ALWAYS_FATAL_IF(mLastUserId != DEFAULT_LAST_USER_ID,
789 "Invalid state: Should never update user ID here unless was default");
790 mLastUserId = userId;
791 }
Ruben Brunk36597b22015-03-20 22:15:57 -0700792
Ruben Brunkcc776712015-02-17 20:18:47 -0800793 // Check the shim parameters after acquiring lock, if they have already been updated and
794 // we were doing a shim update, return immediately
795 if (shimUpdateOnly) {
796 auto cameraState = getCameraState(cameraId);
797 if (cameraState != nullptr) {
798 if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
799 }
800 }
801
802 sp<BasicClient> clientTmp = nullptr;
803 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
804 if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
805 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
806 /*out*/&partial)) != NO_ERROR) {
807 return ret;
808 }
809
810 if (clientTmp.get() != nullptr) {
811 // Handle special case for API1 MediaRecorder where the existing client is returned
812 device = static_cast<CLIENT*>(clientTmp.get());
813 return NO_ERROR;
814 }
815
816 // give flashlight a chance to close devices if necessary.
817 mFlashlight->prepareDeviceOpen(cameraId);
818
819 // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
820 int id = cameraIdToInt(cameraId);
821 if (id == -1) {
822 ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
823 cameraId.string());
824 return BAD_VALUE;
825 }
826
827 int facing = -1;
828 int deviceVersion = getDeviceVersion(id, /*out*/&facing);
829 sp<BasicClient> tmp = nullptr;
830 if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
831 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
832 /*out*/&tmp)) != NO_ERROR) {
833 return ret;
834 }
835 client = static_cast<CLIENT*>(tmp.get());
836
837 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
838 __FUNCTION__);
839
840 if ((ret = client->initialize(mModule)) != OK) {
841 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
842 return ret;
843 }
844
845 sp<IBinder> remoteCallback = client->getRemote();
846 if (remoteCallback != nullptr) {
847 remoteCallback->linkToDeath(this);
848 }
849
850 // Update shim paremeters for legacy clients
851 if (effectiveApiLevel == API_1) {
852 // Assume we have always received a Client subclass for API1
853 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
854 String8 rawParams = shimClient->getParameters();
855 CameraParameters params(rawParams);
856
857 auto cameraState = getCameraState(cameraId);
858 if (cameraState != nullptr) {
859 cameraState->setShimParams(params);
860 } else {
861 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
862 __FUNCTION__, cameraId.string());
863 }
864 }
865
866 if (shimUpdateOnly) {
867 // If only updating legacy shim parameters, immediately disconnect client
868 mServiceLock.unlock();
869 client->disconnect();
870 mServiceLock.lock();
871 } else {
872 // Otherwise, add client to active clients list
873 finishConnectLocked(client, partial);
874 }
875 } // lock is destroyed, allow further connect calls
876
877 // Important: release the mutex here so the client can call back into the service from its
878 // destructor (can be at the end of the call)
879 device = client;
880 return NO_ERROR;
881}
882
Mathias Agopian65ab4712010-07-14 17:59:35 -0700883} // namespace android
884
885#endif