blob: 53f1c72b76f2bf2c45fb381485085a3f8652f7ff [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
Igor Murashkin634a5152013-02-20 17:15:11 -080020#include <utils/Vector.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070021#include <utils/KeyedVector.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080022#include <binder/AppOpsManager.h>
Mathias Agopian5462fc92010-07-14 18:41:18 -070023#include <binder/BinderService.h>
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -080024#include <binder/IAppOpsCallback.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070025#include <camera/ICameraService.h>
Iliyan Malchev8951a972011-04-14 16:55:59 -070026#include <hardware/camera.h>
Mathias Agopian65ab4712010-07-14 17:59:35 -070027
Igor Murashkinc073ba52013-02-26 14:32:34 -080028#include <camera/ICamera.h>
29#include <camera/ICameraClient.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070030#include <camera/camera2/ICameraDeviceUser.h>
31#include <camera/camera2/ICameraDeviceCallbacks.h>
Ruben Brunkd1176ef2014-02-21 10:51:38 -080032#include <camera/VendorTagDescriptor.h>
Jianing Weicb0652e2014-03-12 18:29:36 -070033#include <camera/CaptureResult.h>
Ruben Brunkb2119af2014-05-09 19:57:56 -070034#include <camera/CameraParameters.h>
Igor Murashkinc073ba52013-02-26 14:32:34 -080035
Igor Murashkinbfc99152013-02-27 12:55:20 -080036#include <camera/ICameraServiceListener.h>
Chien-Yu Chen3068d732015-02-09 13:29:57 -080037#include "CameraFlashlight.h"
38
Yin-Chia Yehe074a932015-01-30 10:29:02 -080039#include "common/CameraModule.h"
Ruben Brunkcc776712015-02-17 20:18:47 -080040#include "utils/AutoConditionLock.h"
41#include "utils/ClientManager.h"
42#include "utils/RingBuffer.h"
Yin-Chia Yehe074a932015-01-30 10:29:02 -080043
Ruben Brunkcc776712015-02-17 20:18:47 -080044#include <set>
45#include <string>
46#include <map>
47#include <memory>
Mathias Agopian65ab4712010-07-14 17:59:35 -070048
49namespace android {
50
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070051extern volatile int32_t gLogLevel;
52
Mathias Agopian65ab4712010-07-14 17:59:35 -070053class MemoryHeapBase;
54class MediaPlayer;
55
Mathias Agopian5462fc92010-07-14 18:41:18 -070056class CameraService :
57 public BinderService<CameraService>,
Igor Murashkinecf17e82012-10-02 16:05:11 -070058 public BnCameraService,
Igor Murashkincba2c162013-03-20 15:56:31 -070059 public IBinder::DeathRecipient,
60 public camera_module_callbacks_t
Mathias Agopian65ab4712010-07-14 17:59:35 -070061{
Mathias Agopian5462fc92010-07-14 18:41:18 -070062 friend class BinderService<CameraService>;
Mathias Agopian65ab4712010-07-14 17:59:35 -070063public:
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -070064 class Client;
Igor Murashkin634a5152013-02-20 17:15:11 -080065 class BasicClient;
66
Ruben Brunkcc776712015-02-17 20:18:47 -080067 enum apiLevel {
68 API_1 = 1,
69 API_2 = 2
70 };
71
72 // Process States (mirrors frameworks/base/core/java/android/app/ActivityManager.java)
73 static const int PROCESS_STATE_NONEXISTENT = -1;
74 static const int PROCESS_STATE_PERSISTENT = 0;
75 static const int PROCESS_STATE_PERSISTENT_UI = 1;
76 static const int PROCESS_STATE_TOP = 2;
77 static const int PROCESS_STATE_IMPORTANT_FOREGROUND = 3;
78 static const int PROCESS_STATE_IMPORTANT_BACKGROUND = 4;
79 static const int PROCESS_STATE_BACKUP = 5;
80 static const int PROCESS_STATE_HEAVY_WEIGHT = 6;
81 static const int PROCESS_STATE_SERVICE = 7;
82 static const int PROCESS_STATE_RECEIVER = 8;
83 static const int PROCESS_STATE_HOME = 9;
84 static const int PROCESS_STATE_LAST_ACTIVITY = 10;
85 static const int PROCESS_STATE_CACHED_ACTIVITY = 11;
86 static const int PROCESS_STATE_CACHED_ACTIVITY_CLIENT = 12;
87 static const int PROCESS_STATE_CACHED_EMPTY = 13;
88
89 // 3 second busy timeout when other clients are connecting
90 static const nsecs_t DEFAULT_CONNECT_TIMEOUT_NS = 3000000000;
91
92 // Default number of messages to store in eviction log
93 static const size_t DEFAULT_EVICTION_LOG_LENGTH = 50;
94
Igor Murashkin634a5152013-02-20 17:15:11 -080095 // Implementation of BinderService<T>
Mathias Agopian5462fc92010-07-14 18:41:18 -070096 static char const* getServiceName() { return "media.camera"; }
Mathias Agopian65ab4712010-07-14 17:59:35 -070097
98 CameraService();
99 virtual ~CameraService();
100
Igor Murashkin634a5152013-02-20 17:15:11 -0800101 /////////////////////////////////////////////////////////////////////
Igor Murashkincba2c162013-03-20 15:56:31 -0700102 // HAL Callbacks
Ruben Brunkcc776712015-02-17 20:18:47 -0800103 virtual void onDeviceStatusChanged(camera_device_status_t cameraId,
104 camera_device_status_t newStatus);
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800105 virtual void onTorchStatusChanged(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800106 ICameraServiceListener::TorchStatus
107 newStatus);
Igor Murashkincba2c162013-03-20 15:56:31 -0700108
109 /////////////////////////////////////////////////////////////////////
Igor Murashkin634a5152013-02-20 17:15:11 -0800110 // ICameraService
Mathias Agopian65ab4712010-07-14 17:59:35 -0700111 virtual int32_t getNumberOfCameras();
112 virtual status_t getCameraInfo(int cameraId,
113 struct CameraInfo* cameraInfo);
Zhijun He2b59be82013-09-25 10:14:30 -0700114 virtual status_t getCameraCharacteristics(int cameraId,
115 CameraMetadata* cameraInfo);
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800116 virtual status_t getCameraVendorTagDescriptor(/*out*/ sp<VendorTagDescriptor>& desc);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800117
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700118 virtual status_t connect(const sp<ICameraClient>& cameraClient, int cameraId,
119 const String16& clientPackageName, int clientUid,
120 /*out*/
121 sp<ICamera>& device);
122
Zhijun Heb10cdad2014-06-16 16:38:35 -0700123 virtual status_t connectLegacy(const sp<ICameraClient>& cameraClient, int cameraId,
124 int halVersion, const String16& clientPackageName, int clientUid,
125 /*out*/
126 sp<ICamera>& device);
127
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700128 virtual status_t connectDevice(
Igor Murashkine7ee7632013-06-11 18:10:18 -0700129 const sp<ICameraDeviceCallbacks>& cameraCb,
130 int cameraId,
131 const String16& clientPackageName,
Ruben Brunk0f61d8f2013-08-08 13:07:18 -0700132 int clientUid,
133 /*out*/
134 sp<ICameraDeviceUser>& device);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700135
Igor Murashkinbfc99152013-02-27 12:55:20 -0800136 virtual status_t addListener(const sp<ICameraServiceListener>& listener);
137 virtual status_t removeListener(
138 const sp<ICameraServiceListener>& listener);
139
Igor Murashkin65d14b92014-06-17 12:03:20 -0700140 virtual status_t getLegacyParameters(
141 int cameraId,
142 /*out*/
143 String16* parameters);
144
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800145 virtual status_t setTorchMode(const String16& cameraId, bool enabled,
146 const sp<IBinder>& clientBinder);
147
Igor Murashkin65d14b92014-06-17 12:03:20 -0700148 // OK = supports api of that version, -EOPNOTSUPP = does not support
149 virtual status_t supportsCameraApi(
150 int cameraId, int apiVersion);
151
Igor Murashkin634a5152013-02-20 17:15:11 -0800152 // Extra permissions checks
Mathias Agopian65ab4712010-07-14 17:59:35 -0700153 virtual status_t onTransact(uint32_t code, const Parcel& data,
154 Parcel* reply, uint32_t flags);
Igor Murashkin634a5152013-02-20 17:15:11 -0800155
156 virtual status_t dump(int fd, const Vector<String16>& args);
157
158 /////////////////////////////////////////////////////////////////////
159 // Client functionality
Mathias Agopian65ab4712010-07-14 17:59:35 -0700160
161 enum sound_kind {
162 SOUND_SHUTTER = 0,
163 SOUND_RECORDING = 1,
164 NUM_SOUNDS
165 };
166
167 void loadSound();
168 void playSound(sound_kind kind);
169 void releaseSound();
170
Igor Murashkin98e24722013-06-19 19:51:04 -0700171 /////////////////////////////////////////////////////////////////////
172 // CameraDeviceFactory functionality
173 int getDeviceVersion(int cameraId, int* facing = NULL);
174
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700175 /////////////////////////////////////////////////////////////////////
176 // Shared utilities
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700177 static status_t filterGetInfoErrorCode(status_t err);
Igor Murashkin634a5152013-02-20 17:15:11 -0800178
179 /////////////////////////////////////////////////////////////////////
180 // CameraClient functionality
181
Igor Murashkin634a5152013-02-20 17:15:11 -0800182 class BasicClient : public virtual RefBase {
183 public:
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800184 virtual status_t initialize(CameraModule *module) = 0;
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700185 virtual void disconnect();
Igor Murashkin634a5152013-02-20 17:15:11 -0800186
Igor Murashkine7ee7632013-06-11 18:10:18 -0700187 // because we can't virtually inherit IInterface, which breaks
188 // virtual inheritance
189 virtual sp<IBinder> asBinderWrapper() = 0;
190
Ruben Brunk9efdf952015-03-18 23:11:57 -0700191 // Return the remote callback binder object (e.g. ICameraDeviceCallbacks)
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700192 sp<IBinder> getRemote() {
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800193 return mRemoteBinder;
Igor Murashkin634a5152013-02-20 17:15:11 -0800194 }
195
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -0700196 virtual status_t dump(int fd, const Vector<String16>& args) = 0;
Igor Murashkine7ee7632013-06-11 18:10:18 -0700197
Ruben Brunkcc776712015-02-17 20:18:47 -0800198 // Return the package name for this client
199 virtual String16 getPackageName() const;
200
201 // Notify client about a fatal error
202 virtual void notifyError(ICameraDeviceCallbacks::CameraErrorCode errorCode,
203 const CaptureResultExtras& resultExtras) = 0;
204
205 // Get the PID of the application client using this
206 virtual int getClientPid() const;
Igor Murashkin634a5152013-02-20 17:15:11 -0800207 protected:
208 BasicClient(const sp<CameraService>& cameraService,
209 const sp<IBinder>& remoteCallback,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800210 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
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800229 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,
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800296 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 Brunkcc776712015-02-17 20:18:47 -0800315 protected:
316 // Convert client from cookie.
317 static sp<CameraService::Client> getClientFromCookie(void* user);
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800318
Igor Murashkin634a5152013-02-20 17:15:11 -0800319 // Initialized in constructor
Eino-Ville Talvala5e08d602012-05-16 14:59:25 -0700320
Igor Murashkin634a5152013-02-20 17:15:11 -0800321 // - The app-side Binder interface to receive callbacks from us
Igor Murashkin44cfcf02013-03-01 16:22:28 -0800322 sp<ICameraClient> mRemoteCallback;
Eino-Ville Talvalaceb388d2013-02-19 10:40:14 -0800323
324 }; // class Client
Igor Murashkin634a5152013-02-20 17:15:11 -0800325
Ruben Brunkcc776712015-02-17 20:18:47 -0800326 typedef std::shared_ptr<resource_policy::ClientDescriptor<String8,
327 sp<CameraService::BasicClient>>> DescriptorPtr;
328
329 /**
330 * A container class for managing active camera clients that are using HAL devices. Active
331 * clients are represented by ClientDescriptor objects that contain strong pointers to the
332 * actual BasicClient subclass binder interface implementation.
333 *
334 * This class manages the eviction behavior for the camera clients. See the parent class
335 * implementation in utils/ClientManager for the specifics of this behavior.
336 */
337 class CameraClientManager :
338 public resource_policy::ClientManager<String8, sp<CameraService::BasicClient>> {
339 public:
340 virtual ~CameraClientManager();
341
342 /**
343 * Return a strong pointer to the active BasicClient for this camera ID, or an empty
344 * if none exists.
345 */
346 sp<CameraService::BasicClient> getCameraClient(const String8& id) const;
347
348 /**
349 * Return a string describing the current state.
350 */
351 String8 toString() const;
352
353 /**
354 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer.
355 */
356 static DescriptorPtr makeClientDescriptor(const String8& key, const sp<BasicClient>& value,
357 int32_t cost, const std::set<String8>& conflictingKeys, int32_t priority,
358 int32_t ownerId);
359
360 /**
361 * Make a ClientDescriptor object wrapping the given BasicClient strong pointer with
362 * values intialized from a prior ClientDescriptor.
363 */
364 static DescriptorPtr makeClientDescriptor(const sp<BasicClient>& value,
365 const CameraService::DescriptorPtr& partial);
366
367 }; // class CameraClientManager
368
Mathias Agopian65ab4712010-07-14 17:59:35 -0700369private:
Igor Murashkin634a5152013-02-20 17:15:11 -0800370
Ruben Brunkcc776712015-02-17 20:18:47 -0800371 /**
372 * Container class for the state of each logical camera device, including: ID, status, and
373 * dependencies on other devices. The mapping of camera ID -> state saved in mCameraStates
374 * represents the camera devices advertised by the HAL (and any USB devices, when we add
375 * those).
376 *
377 * This container does NOT represent an active camera client. These are represented using
378 * the ClientDescriptors stored in mActiveClientManager.
379 */
380 class CameraState {
381 public:
382 /**
383 * Make a new CameraState and set the ID, cost, and conflicting devices using the values
384 * returned in the HAL's camera_info struct for each device.
385 */
386 CameraState(const String8& id, int cost, const std::set<String8>& conflicting);
387 virtual ~CameraState();
388
389 /**
390 * Return the status for this device.
391 *
392 * This method acquires mStatusLock.
393 */
394 ICameraServiceListener::Status getStatus() const;
395
396 /**
397 * This function updates the status for this camera device, unless the given status
398 * is in the given list of rejected status states, and execute the function passed in
399 * with a signature onStatusUpdateLocked(const String8&, ICameraServiceListener::Status)
400 * if the status has changed.
401 *
402 * This method is idempotent, and will not result in the function passed to
403 * onStatusUpdateLocked being called more than once for the same arguments.
404 * This method aquires mStatusLock.
405 */
406 template<class Func>
407 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
408 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
409 Func onStatusUpdatedLocked);
410
411 /**
412 * Return the last set CameraParameters object generated from the information returned by
413 * the HAL for this device (or an empty CameraParameters object if none has been set).
414 */
415 CameraParameters getShimParams() const;
416
417 /**
418 * Set the CameraParameters for this device.
419 */
420 void setShimParams(const CameraParameters& params);
421
422 /**
423 * Return the resource_cost advertised by the HAL for this device.
424 */
425 int getCost() const;
426
427 /**
428 * Return a set of the IDs of conflicting devices advertised by the HAL for this device.
429 */
430 std::set<String8> getConflicting() const;
431
432 /**
433 * Return the ID of this camera device.
434 */
435 String8 getId() const;
436
437 private:
438 const String8 mId;
439 ICameraServiceListener::Status mStatus; // protected by mStatusLock
440 const int mCost;
441 std::set<String8> mConflicting;
442 mutable Mutex mStatusLock;
443 CameraParameters mShimParams;
444 }; // class CameraState
445
Igor Murashkin634a5152013-02-20 17:15:11 -0800446 // Delay-load the Camera HAL module
447 virtual void onFirstRef();
448
Ruben Brunkcc776712015-02-17 20:18:47 -0800449 // Check if we can connect, before we acquire the service lock.
450 status_t validateConnect(const String8& cameraId, /*inout*/int& clientUid) const;
Igor Murashkine6800ce2013-03-04 17:25:57 -0800451
Ruben Brunkcc776712015-02-17 20:18:47 -0800452 // Handle active client evictions, and update service state.
453 // Only call with with mServiceLock held.
454 status_t handleEvictionsLocked(const String8& cameraId, int clientPid,
455 apiLevel effectiveApiLevel, const sp<IBinder>& remoteCallback, const String8& packageName,
456 /*out*/
457 sp<BasicClient>* client,
458 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>>* partial);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800459
Ruben Brunkcc776712015-02-17 20:18:47 -0800460 // Single implementation shared between the various connect calls
461 template<class CALLBACK, class CLIENT>
462 status_t connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId, int halVersion,
463 const String16& clientPackageName, int clientUid, apiLevel effectiveApiLevel,
464 bool legacyMode, bool shimUpdateOnly, /*out*/sp<CLIENT>& device);
Igor Murashkine6800ce2013-03-04 17:25:57 -0800465
Igor Murashkin634a5152013-02-20 17:15:11 -0800466
Ruben Brunkcc776712015-02-17 20:18:47 -0800467 // Lock guarding camera service state
Mathias Agopian65ab4712010-07-14 17:59:35 -0700468 Mutex mServiceLock;
Ruben Brunkcc776712015-02-17 20:18:47 -0800469
470 // Condition to use with mServiceLock, used to handle simultaneous connect calls from clients
471 std::shared_ptr<WaitableMutexWrapper> mServiceLockWrapper;
472
473 // Return NO_ERROR if the device with a give ID can be connected to
474 status_t checkIfDeviceIsUsable(const String8& cameraId) const;
475
476 // Container for managing currently active application-layer clients
477 CameraClientManager mActiveClientManager;
478
479 // Mapping from camera ID -> state for each device, map is protected by mCameraStatesLock
480 std::map<String8, std::shared_ptr<CameraState>> mCameraStates;
481
482 // Mutex guarding mCameraStates map
483 mutable Mutex mCameraStatesLock;
484
485 // Circular buffer for storing event logging for dumps
486 RingBuffer<String8> mEventLog;
487
488 /**
489 * Get the camera state for a given camera id.
490 *
491 * This acquires mCameraStatesLock.
492 */
493 std::shared_ptr<CameraService::CameraState> getCameraState(const String8& cameraId) const;
494
495 /**
496 * Evict client who's remote binder has died. Returns true if this client was in the active
497 * list and was disconnected.
498 *
499 * This method acquires mServiceLock.
500 */
501 bool evictClientIdByRemote(const wp<IBinder>& cameraClient);
502
503 /**
504 * Remove the given client from the active clients list; does not disconnect the client.
505 *
506 * This method acquires mServiceLock.
507 */
508 void removeByClient(const BasicClient* client);
509
510 /**
511 * Add new client to active clients list after conflicting clients have disconnected using the
512 * values set in the partial descriptor passed in to construct the actual client descriptor.
513 * This is typically called at the end of a connect call.
514 *
515 * This method must be called with mServiceLock held.
516 */
517 void finishConnectLocked(const sp<BasicClient>& client, const DescriptorPtr& desc);
518
519 /**
520 * Returns the integer corresponding to the given camera ID string, or -1 on failure.
521 */
522 static int cameraIdToInt(const String8& cameraId);
523
524 /**
525 * Remove a single client corresponding to the given camera id from the list of active clients.
526 * If none exists, return an empty strongpointer.
527 *
528 * This method must be called with mServiceLock held.
529 */
530 sp<CameraService::BasicClient> removeClientLocked(const String8& cameraId);
531
532 /**
533 * Add a event log message that a client has been disconnected.
534 */
535 void logDisconnected(const String8& cameraId, int clientPid, const String8& clientPackage);
536
537 /**
538 * Add a event log message that a client has been connected.
539 */
540 void logConnected(const String8& cameraId, int clientPid, const String8& clientPackage);
541
Mathias Agopian65ab4712010-07-14 17:59:35 -0700542 int mNumberOfCameras;
543
Mathias Agopian65ab4712010-07-14 17:59:35 -0700544 // sounds
Chih-Chung Changff4f55c2011-10-17 19:03:12 +0800545 MediaPlayer* newMediaPlayer(const char *file);
546
Mathias Agopian65ab4712010-07-14 17:59:35 -0700547 Mutex mSoundLock;
548 sp<MediaPlayer> mSoundPlayer[NUM_SOUNDS];
549 int mSoundRef; // reference count (release all MediaPlayer when 0)
550
Yin-Chia Yehe074a932015-01-30 10:29:02 -0800551 CameraModule* mModule;
Igor Murashkinecf17e82012-10-02 16:05:11 -0700552
Ruben Brunkcc776712015-02-17 20:18:47 -0800553 // Guarded by mStatusListenerMutex
554 std::vector<sp<ICameraServiceListener>> mListenerList;
555 Mutex mStatusListenerLock;
Igor Murashkinbfc99152013-02-27 12:55:20 -0800556
Ruben Brunkcc776712015-02-17 20:18:47 -0800557 /**
558 * Update the status for the given camera id (if that device exists), and broadcast the
559 * status update to all current ICameraServiceListeners if the status has changed. Any
560 * statuses in rejectedSourceStates will be ignored.
561 *
562 * This method must be idempotent.
563 * This method acquires mStatusLock and mStatusListenerLock.
564 */
565 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId,
566 std::initializer_list<ICameraServiceListener::Status> rejectedSourceStates);
567 void updateStatus(ICameraServiceListener::Status status, const String8& cameraId);
Igor Murashkinbfc99152013-02-27 12:55:20 -0800568
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800569 // flashlight control
570 sp<CameraFlashlight> mFlashlight;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800571 // guard mTorchStatusMap
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800572 Mutex mTorchStatusMutex;
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800573 // guard mTorchClientMap
574 Mutex mTorchClientMapMutex;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800575 // camera id -> torch status
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800576 KeyedVector<String8, ICameraServiceListener::TorchStatus> mTorchStatusMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800577 // camera id -> torch client binder
578 // only store the last client that turns on each camera's torch mode
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800579 KeyedVector<String8, sp<IBinder> > mTorchClientMap;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800580
581 // check and handle if torch client's process has died
582 void handleTorchClientBinderDied(const wp<IBinder> &who);
583
584 // handle torch mode status change and invoke callbacks. mTorchStatusMutex
585 // should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800586 void onTorchStatusChangedLocked(const String8& cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800587 ICameraServiceListener::TorchStatus newStatus);
588
589 // get a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800590 status_t getTorchStatusLocked(const String8 &cameraId,
591 ICameraServiceListener::TorchStatus *status) const;
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800592
593 // set a camera's torch status. mTorchStatusMutex should be locked.
Chien-Yu Chen88da5262015-02-17 13:56:46 -0800594 status_t setTorchStatusLocked(const String8 &cameraId,
Chien-Yu Chen3068d732015-02-09 13:29:57 -0800595 ICameraServiceListener::TorchStatus status);
596
Igor Murashkinecf17e82012-10-02 16:05:11 -0700597 // IBinder::DeathRecipient implementation
Igor Murashkinbfc99152013-02-27 12:55:20 -0800598 virtual void binderDied(const wp<IBinder> &who);
Igor Murashkin634a5152013-02-20 17:15:11 -0800599
600 // Helpers
Igor Murashkinbfc99152013-02-27 12:55:20 -0800601
Ruben Brunkd1176ef2014-02-21 10:51:38 -0800602 bool setUpVendorTags();
Ruben Brunkb2119af2014-05-09 19:57:56 -0700603
604 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700605 * Initialize and cache the metadata used by the HAL1 shim for a given cameraId.
606 *
607 * Returns OK on success, or a negative error code.
608 */
609 status_t initializeShimMetadata(int cameraId);
610
611 /**
Igor Murashkin65d14b92014-06-17 12:03:20 -0700612 * Get the cached CameraParameters for the camera. If they haven't been
613 * cached yet, then initialize them for the first time.
614 *
615 * Returns OK on success, or a negative error code.
616 */
617 status_t getLegacyParametersLazy(int cameraId, /*out*/CameraParameters* parameters);
618
619 /**
Ruben Brunkb2119af2014-05-09 19:57:56 -0700620 * Generate the CameraCharacteristics metadata required by the Camera2 API
621 * from the available HAL1 CameraParameters and CameraInfo.
622 *
623 * Returns OK on success, or a negative error code.
624 */
625 status_t generateShimMetadata(int cameraId, /*out*/CameraMetadata* cameraInfo);
626
Ruben Brunkcc776712015-02-17 20:18:47 -0800627 static int getCallingPid();
628
629 static int getCallingUid();
630
Ruben Brunkb2119af2014-05-09 19:57:56 -0700631 /**
Ruben Brunkcc776712015-02-17 20:18:47 -0800632 * Get the current system time as a formatted string.
Ruben Brunkb2119af2014-05-09 19:57:56 -0700633 */
Ruben Brunkcc776712015-02-17 20:18:47 -0800634 static String8 getFormattedCurrentTime();
635
636 /**
637 * Get the camera eviction priority from the current process state given by ActivityManager.
638 */
639 static int getCameraPriorityFromProcState(int procState);
640
641 static status_t makeClient(const sp<CameraService>& cameraService,
642 const sp<IInterface>& cameraCb, const String16& packageName, const String8& cameraId,
643 int facing, int clientPid, uid_t clientUid, int servicePid, bool legacyMode,
644 int halVersion, int deviceVersion, apiLevel effectiveApiLevel,
645 /*out*/sp<BasicClient>* client);
Mathias Agopian65ab4712010-07-14 17:59:35 -0700646};
647
Ruben Brunkcc776712015-02-17 20:18:47 -0800648template<class Func>
649void CameraService::CameraState::updateStatus(ICameraServiceListener::Status status,
650 const String8& cameraId,
651 std::initializer_list<ICameraServiceListener::Status> rejectSourceStates,
652 Func onStatusUpdatedLocked) {
653 Mutex::Autolock lock(mStatusLock);
654 ICameraServiceListener::Status oldStatus = mStatus;
655 mStatus = status;
656
657 if (oldStatus == status) {
658 return;
659 }
660
661 ALOGV("%s: Status has changed for camera ID %s from %#x to %#x", __FUNCTION__,
662 cameraId.string(), oldStatus, status);
663
664 if (oldStatus == ICameraServiceListener::STATUS_NOT_PRESENT &&
665 (status != ICameraServiceListener::STATUS_PRESENT &&
666 status != ICameraServiceListener::STATUS_ENUMERATING)) {
667
668 ALOGW("%s: From NOT_PRESENT can only transition into PRESENT or ENUMERATING",
669 __FUNCTION__);
670 mStatus = oldStatus;
671 return;
672 }
673
674 /**
675 * Sometimes we want to conditionally do a transition.
676 * For example if a client disconnects, we want to go to PRESENT
677 * only if we weren't already in NOT_PRESENT or ENUMERATING.
678 */
679 for (auto& rejectStatus : rejectSourceStates) {
680 if (oldStatus == rejectStatus) {
681 ALOGV("%s: Rejecting status transition for Camera ID %s, since the source "
682 "state was was in one of the bad states.", __FUNCTION__, cameraId.string());
683 mStatus = oldStatus;
684 return;
685 }
686 }
687
688 onStatusUpdatedLocked(cameraId, status);
689}
690
691
692template<class CALLBACK, class CLIENT>
693status_t CameraService::connectHelper(const sp<CALLBACK>& cameraCb, const String8& cameraId,
694 int halVersion, const String16& clientPackageName, int clientUid,
695 apiLevel effectiveApiLevel, bool legacyMode, bool shimUpdateOnly,
696 /*out*/sp<CLIENT>& device) {
697 status_t ret = NO_ERROR;
698 String8 clientName8(clientPackageName);
699 int clientPid = getCallingPid();
700
701 ALOGI("CameraService::connect call E (PID %d \"%s\", camera ID %s) for HAL version %d and "
702 "Camera API version %d", clientPid, clientName8.string(), cameraId.string(),
703 halVersion, static_cast<int>(effectiveApiLevel));
704
705 // Enforce client permissions and do basic sanity checks
706 if((ret = validateConnect(cameraId, /*inout*/clientUid)) != NO_ERROR) {
707 return ret;
708 }
709
710 sp<CLIENT> client = nullptr;
711 {
712 // Acquire mServiceLock and prevent other clients from connecting
713 std::unique_ptr<AutoConditionLock> lock =
714 AutoConditionLock::waitAndAcquire(mServiceLockWrapper, DEFAULT_CONNECT_TIMEOUT_NS);
715 if (lock == nullptr) {
716 ALOGE("CameraService::connect X (PID %d) rejected (too many other clients connecting)."
717 , clientPid);
718 return -EBUSY;
719 }
720
721 // Check the shim parameters after acquiring lock, if they have already been updated and
722 // we were doing a shim update, return immediately
723 if (shimUpdateOnly) {
724 auto cameraState = getCameraState(cameraId);
725 if (cameraState != nullptr) {
726 if (!cameraState->getShimParams().isEmpty()) return NO_ERROR;
727 }
728 }
729
730 sp<BasicClient> clientTmp = nullptr;
731 std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
732 if ((ret = handleEvictionsLocked(cameraId, clientPid, effectiveApiLevel,
733 IInterface::asBinder(cameraCb), clientName8, /*out*/&clientTmp,
734 /*out*/&partial)) != NO_ERROR) {
735 return ret;
736 }
737
738 if (clientTmp.get() != nullptr) {
739 // Handle special case for API1 MediaRecorder where the existing client is returned
740 device = static_cast<CLIENT*>(clientTmp.get());
741 return NO_ERROR;
742 }
743
744 // give flashlight a chance to close devices if necessary.
745 mFlashlight->prepareDeviceOpen(cameraId);
746
747 // TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
748 int id = cameraIdToInt(cameraId);
749 if (id == -1) {
750 ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
751 cameraId.string());
752 return BAD_VALUE;
753 }
754
755 int facing = -1;
756 int deviceVersion = getDeviceVersion(id, /*out*/&facing);
757 sp<BasicClient> tmp = nullptr;
758 if((ret = makeClient(this, cameraCb, clientPackageName, cameraId, facing, clientPid,
759 clientUid, getpid(), legacyMode, halVersion, deviceVersion, effectiveApiLevel,
760 /*out*/&tmp)) != NO_ERROR) {
761 return ret;
762 }
763 client = static_cast<CLIENT*>(tmp.get());
764
765 LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
766 __FUNCTION__);
767
768 if ((ret = client->initialize(mModule)) != OK) {
769 ALOGE("%s: Could not initialize client from HAL module.", __FUNCTION__);
770 return ret;
771 }
772
773 sp<IBinder> remoteCallback = client->getRemote();
774 if (remoteCallback != nullptr) {
775 remoteCallback->linkToDeath(this);
776 }
777
778 // Update shim paremeters for legacy clients
779 if (effectiveApiLevel == API_1) {
780 // Assume we have always received a Client subclass for API1
781 sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
782 String8 rawParams = shimClient->getParameters();
783 CameraParameters params(rawParams);
784
785 auto cameraState = getCameraState(cameraId);
786 if (cameraState != nullptr) {
787 cameraState->setShimParams(params);
788 } else {
789 ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
790 __FUNCTION__, cameraId.string());
791 }
792 }
793
794 if (shimUpdateOnly) {
795 // If only updating legacy shim parameters, immediately disconnect client
796 mServiceLock.unlock();
797 client->disconnect();
798 mServiceLock.lock();
799 } else {
800 // Otherwise, add client to active clients list
801 finishConnectLocked(client, partial);
802 }
803 } // lock is destroyed, allow further connect calls
804
805 // Important: release the mutex here so the client can call back into the service from its
806 // destructor (can be at the end of the call)
807 device = client;
808 return NO_ERROR;
809}
810
Mathias Agopian65ab4712010-07-14 17:59:35 -0700811} // namespace android
812
813#endif