PageRenderTime 44ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/frameworks/av/services/camera/libcameraservice/CameraService.cpp

https://gitlab.com/brian0218/rk3066_r-box_android4.2.2_sdk
C++ | 589 lines | 423 code | 101 blank | 65 comment | 87 complexity | e95b051c4ba1fbeba4e4d1ae5cef9e79 MD5 | raw file
  1. /*
  2. **
  3. ** Copyright (C) 2008, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #define LOG_TAG "CameraService"
  18. //#define LOG_NDEBUG 0
  19. #include <stdio.h>
  20. #include <sys/types.h>
  21. #include <pthread.h>
  22. #include <binder/IPCThreadState.h>
  23. #include <binder/IServiceManager.h>
  24. #include <binder/MemoryBase.h>
  25. #include <binder/MemoryHeapBase.h>
  26. #include <cutils/atomic.h>
  27. #include <cutils/properties.h>
  28. #include <gui/SurfaceTextureClient.h>
  29. #include <gui/Surface.h>
  30. #include <hardware/hardware.h>
  31. #include <media/AudioSystem.h>
  32. #include <media/mediaplayer.h>
  33. #include <utils/Errors.h>
  34. #include <utils/Log.h>
  35. #include <utils/String16.h>
  36. #include "CameraService.h"
  37. #include "CameraClient.h"
  38. #include "Camera2Client.h"
  39. namespace android {
  40. // ----------------------------------------------------------------------------
  41. // Logging support -- this is for debugging only
  42. // Use "adb shell dumpsys media.camera -v 1" to change it.
  43. volatile int32_t gLogLevel = 0;
  44. #define LOG1(...) ALOGD_IF(gLogLevel >= 1, __VA_ARGS__);
  45. #define LOG2(...) ALOGD_IF(gLogLevel >= 2, __VA_ARGS__);
  46. static void setLogLevel(int level) {
  47. android_atomic_write(level, &gLogLevel);
  48. }
  49. // ----------------------------------------------------------------------------
  50. static int getCallingPid() {
  51. return IPCThreadState::self()->getCallingPid();
  52. }
  53. static int getCallingUid() {
  54. return IPCThreadState::self()->getCallingUid();
  55. }
  56. // ----------------------------------------------------------------------------
  57. // This is ugly and only safe if we never re-create the CameraService, but
  58. // should be ok for now.
  59. static CameraService *gCameraService;
  60. CameraService::CameraService()
  61. :mSoundRef(0), mModule(0)
  62. {
  63. ALOGI("CameraService started (pid=%d)", getpid());
  64. gCameraService = this;
  65. }
  66. void CameraService::onFirstRef()
  67. {
  68. BnCameraService::onFirstRef();
  69. if (hw_get_module(CAMERA_HARDWARE_MODULE_ID,
  70. (const hw_module_t **)&mModule) < 0) {
  71. ALOGE("Could not load camera HAL module");
  72. mNumberOfCameras = 0;
  73. }
  74. else {
  75. mNumberOfCameras = mModule->get_number_of_cameras();
  76. if (mNumberOfCameras > MAX_CAMERAS) {
  77. ALOGE("Number of cameras(%d) > MAX_CAMERAS(%d).",
  78. mNumberOfCameras, MAX_CAMERAS);
  79. mNumberOfCameras = MAX_CAMERAS;
  80. }
  81. for (int i = 0; i < mNumberOfCameras; i++) {
  82. setCameraFree(i);
  83. }
  84. }
  85. }
  86. CameraService::~CameraService() {
  87. for (int i = 0; i < mNumberOfCameras; i++) {
  88. if (mBusy[i]) {
  89. ALOGE("camera %d is still in use in destructor!", i);
  90. }
  91. }
  92. gCameraService = NULL;
  93. }
  94. int32_t CameraService::getNumberOfCameras() {
  95. if(mNumberOfCameras == 0) {
  96. ALOGE("no camera found before! check again...");
  97. onFirstRef();
  98. }
  99. return mNumberOfCameras;
  100. }
  101. status_t CameraService::getCameraInfo(int cameraId,
  102. struct CameraInfo* cameraInfo) {
  103. if (!mModule) {
  104. return NO_INIT;
  105. }
  106. if (cameraId < 0 || cameraId >= mNumberOfCameras) {
  107. return BAD_VALUE;
  108. }
  109. struct camera_info info;
  110. status_t rc = mModule->get_camera_info(cameraId, &info);
  111. cameraInfo->facing = info.facing;
  112. cameraInfo->orientation = info.orientation;
  113. return rc;
  114. }
  115. sp<ICamera> CameraService::connect(
  116. const sp<ICameraClient>& cameraClient, int cameraId) {
  117. int callingPid = getCallingPid();
  118. LOG1("CameraService::connect E (pid %d, id %d)", callingPid, cameraId);
  119. if (!mModule) {
  120. ALOGE("Camera HAL module not loaded");
  121. return NULL;
  122. }
  123. sp<Client> client;
  124. if (cameraId < 0 || cameraId >= mNumberOfCameras) {
  125. ALOGE("CameraService::connect X (pid %d) rejected (invalid cameraId %d).",
  126. callingPid, cameraId);
  127. return NULL;
  128. }
  129. char value[PROPERTY_VALUE_MAX];
  130. property_get("sys.secpolicy.camera.disabled", value, "0");
  131. if (strcmp(value, "1") == 0) {
  132. // Camera is disabled by DevicePolicyManager.
  133. ALOGI("Camera is disabled. connect X (pid %d) rejected", callingPid);
  134. return NULL;
  135. }
  136. Mutex::Autolock lock(mServiceLock);
  137. if (mClient[cameraId] != 0) {
  138. client = mClient[cameraId].promote();
  139. if (client != 0) {
  140. if (cameraClient->asBinder() == client->getCameraClient()->asBinder()) {
  141. LOG1("CameraService::connect X (pid %d) (the same client)",
  142. callingPid);
  143. return client;
  144. } else {
  145. ALOGW("CameraService::connect X (pid %d) rejected (existing client).",
  146. callingPid);
  147. return NULL;
  148. }
  149. }
  150. mClient[cameraId].clear();
  151. }
  152. if (mBusy[cameraId]) {
  153. ALOGW("CameraService::connect X (pid %d) rejected"
  154. " (camera %d is still busy).", callingPid, cameraId);
  155. return NULL;
  156. }
  157. struct camera_info info;
  158. if (mModule->get_camera_info(cameraId, &info) != OK) {
  159. ALOGE("Invalid camera id %d", cameraId);
  160. return NULL;
  161. }
  162. int deviceVersion;
  163. if (mModule->common.module_api_version == CAMERA_MODULE_API_VERSION_2_0) {
  164. deviceVersion = info.device_version;
  165. } else {
  166. deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
  167. }
  168. switch(deviceVersion) {
  169. case CAMERA_DEVICE_API_VERSION_1_0:
  170. client = new CameraClient(this, cameraClient, cameraId,
  171. info.facing, callingPid, getpid());
  172. break;
  173. case CAMERA_DEVICE_API_VERSION_2_0:
  174. client = new Camera2Client(this, cameraClient, cameraId,
  175. info.facing, callingPid, getpid());
  176. break;
  177. default:
  178. ALOGE("Unknown camera device HAL version: %d", deviceVersion);
  179. return NULL;
  180. }
  181. if (client->initialize(mModule) != OK) {
  182. return NULL;
  183. }
  184. cameraClient->asBinder()->linkToDeath(this);
  185. mClient[cameraId] = client;
  186. LOG1("CameraService::connect X (id %d, this pid is %d)", cameraId, getpid());
  187. return client;
  188. }
  189. void CameraService::removeClient(const sp<ICameraClient>& cameraClient) {
  190. int callingPid = getCallingPid();
  191. LOG1("CameraService::removeClient E (pid %d)", callingPid);
  192. // Declare this before the lock to make absolutely sure the
  193. // destructor won't be called with the lock held.
  194. Mutex::Autolock lock(mServiceLock);
  195. int outIndex;
  196. sp<Client> client = findClientUnsafe(cameraClient->asBinder(), outIndex);
  197. if (client != 0) {
  198. // Found our camera, clear and leave.
  199. LOG1("removeClient: clear camera %d", outIndex);
  200. mClient[outIndex].clear();
  201. client->unlinkToDeath(this);
  202. }
  203. LOG1("CameraService::removeClient X (pid %d)", callingPid);
  204. }
  205. sp<CameraService::Client> CameraService::findClientUnsafe(
  206. const wp<IBinder>& cameraClient, int& outIndex) {
  207. sp<Client> client;
  208. for (int i = 0; i < mNumberOfCameras; i++) {
  209. // This happens when we have already disconnected (or this is
  210. // just another unused camera).
  211. if (mClient[i] == 0) continue;
  212. // Promote mClient. It can fail if we are called from this path:
  213. // Client::~Client() -> disconnect() -> removeClient().
  214. client = mClient[i].promote();
  215. // Clean up stale client entry
  216. if (client == NULL) {
  217. mClient[i].clear();
  218. continue;
  219. }
  220. if (cameraClient == client->getCameraClient()->asBinder()) {
  221. // Found our camera
  222. outIndex = i;
  223. return client;
  224. }
  225. }
  226. outIndex = -1;
  227. return NULL;
  228. }
  229. CameraService::Client* CameraService::getClientByIdUnsafe(int cameraId) {
  230. if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
  231. return mClient[cameraId].unsafe_get();
  232. }
  233. Mutex* CameraService::getClientLockById(int cameraId) {
  234. if (cameraId < 0 || cameraId >= mNumberOfCameras) return NULL;
  235. return &mClientLock[cameraId];
  236. }
  237. sp<CameraService::Client> CameraService::getClientByRemote(
  238. const wp<IBinder>& cameraClient) {
  239. // Declare this before the lock to make absolutely sure the
  240. // destructor won't be called with the lock held.
  241. sp<Client> client;
  242. Mutex::Autolock lock(mServiceLock);
  243. int outIndex;
  244. client = findClientUnsafe(cameraClient, outIndex);
  245. return client;
  246. }
  247. status_t CameraService::onTransact(
  248. uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) {
  249. // Permission checks
  250. switch (code) {
  251. case BnCameraService::CONNECT:
  252. const int pid = getCallingPid();
  253. const int self_pid = getpid();
  254. if (pid != self_pid) {
  255. // we're called from a different process, do the real check
  256. if (!checkCallingPermission(
  257. String16("android.permission.CAMERA"))) {
  258. const int uid = getCallingUid();
  259. ALOGE("Permission Denial: "
  260. "can't use the camera pid=%d, uid=%d", pid, uid);
  261. return PERMISSION_DENIED;
  262. }
  263. }
  264. break;
  265. }
  266. return BnCameraService::onTransact(code, data, reply, flags);
  267. }
  268. // The reason we need this busy bit is a new CameraService::connect() request
  269. // may come in while the previous Client's destructor has not been run or is
  270. // still running. If the last strong reference of the previous Client is gone
  271. // but the destructor has not been finished, we should not allow the new Client
  272. // to be created because we need to wait for the previous Client to tear down
  273. // the hardware first.
  274. void CameraService::setCameraBusy(int cameraId) {
  275. android_atomic_write(1, &mBusy[cameraId]);
  276. ALOGV("setCameraBusy cameraId=%d", cameraId);
  277. }
  278. void CameraService::setCameraFree(int cameraId) {
  279. android_atomic_write(0, &mBusy[cameraId]);
  280. ALOGV("setCameraFree cameraId=%d", cameraId);
  281. }
  282. // We share the media players for shutter and recording sound for all clients.
  283. // A reference count is kept to determine when we will actually release the
  284. // media players.
  285. MediaPlayer* CameraService::newMediaPlayer(const char *file) {
  286. MediaPlayer* mp = new MediaPlayer();
  287. if (mp->setDataSource(file, NULL) == NO_ERROR) {
  288. mp->setAudioStreamType(AUDIO_STREAM_ENFORCED_AUDIBLE);
  289. mp->prepare();
  290. } else {
  291. ALOGE("Failed to load CameraService sounds: %s", file);
  292. return NULL;
  293. }
  294. return mp;
  295. }
  296. void CameraService::loadSound() {
  297. Mutex::Autolock lock(mSoundLock);
  298. LOG1("CameraService::loadSound ref=%d", mSoundRef);
  299. if (mSoundRef++) return;
  300. mSoundPlayer[SOUND_SHUTTER] = newMediaPlayer("/system/media/audio/ui/camera_click.ogg");
  301. mSoundPlayer[SOUND_RECORDING] = newMediaPlayer("/system/media/audio/ui/VideoRecord.ogg");
  302. }
  303. void CameraService::releaseSound() {
  304. Mutex::Autolock lock(mSoundLock);
  305. LOG1("CameraService::releaseSound ref=%d", mSoundRef);
  306. if (--mSoundRef) return;
  307. for (int i = 0; i < NUM_SOUNDS; i++) {
  308. if (mSoundPlayer[i] != 0) {
  309. mSoundPlayer[i]->disconnect();
  310. mSoundPlayer[i].clear();
  311. }
  312. }
  313. }
  314. void CameraService::playSound(sound_kind kind) {
  315. LOG1("playSound(%d)", kind);
  316. Mutex::Autolock lock(mSoundLock);
  317. sp<MediaPlayer> player = mSoundPlayer[kind];
  318. if (player != 0) {
  319. player->seekTo(0);
  320. player->start();
  321. }
  322. }
  323. // ----------------------------------------------------------------------------
  324. CameraService::Client::Client(const sp<CameraService>& cameraService,
  325. const sp<ICameraClient>& cameraClient,
  326. int cameraId, int cameraFacing, int clientPid, int servicePid) {
  327. int callingPid = getCallingPid();
  328. LOG1("Client::Client E (pid %d, id %d)", callingPid, cameraId);
  329. mCameraService = cameraService;
  330. mCameraClient = cameraClient;
  331. mCameraId = cameraId;
  332. mCameraFacing = cameraFacing;
  333. mClientPid = clientPid;
  334. mServicePid = servicePid;
  335. mDestructionStarted = false;
  336. cameraService->setCameraBusy(cameraId);
  337. cameraService->loadSound();
  338. LOG1("Client::Client X (pid %d, id %d)", callingPid, cameraId);
  339. }
  340. // tear down the client
  341. CameraService::Client::~Client() {
  342. mCameraService->releaseSound();
  343. // unconditionally disconnect. function is idempotent
  344. Client::disconnect();
  345. }
  346. // ----------------------------------------------------------------------------
  347. Mutex* CameraService::Client::getClientLockFromCookie(void* user) {
  348. return gCameraService->getClientLockById((int) user);
  349. }
  350. // Provide client pointer for callbacks. Client lock returned from getClientLockFromCookie should
  351. // be acquired for this to be safe
  352. CameraService::Client* CameraService::Client::getClientFromCookie(void* user) {
  353. Client* client = gCameraService->getClientByIdUnsafe((int) user);
  354. // This could happen if the Client is in the process of shutting down (the
  355. // last strong reference is gone, but the destructor hasn't finished
  356. // stopping the hardware).
  357. if (client == NULL) return NULL;
  358. // destruction already started, so should not be accessed
  359. if (client->mDestructionStarted) return NULL;
  360. return client;
  361. }
  362. // NOTE: function is idempotent
  363. void CameraService::Client::disconnect() {
  364. mCameraService->removeClient(mCameraClient);
  365. mCameraService->setCameraFree(mCameraId);
  366. }
  367. // ----------------------------------------------------------------------------
  368. static const int kDumpLockRetries = 50;
  369. static const int kDumpLockSleep = 60000;
  370. static bool tryLock(Mutex& mutex)
  371. {
  372. bool locked = false;
  373. for (int i = 0; i < kDumpLockRetries; ++i) {
  374. if (mutex.tryLock() == NO_ERROR) {
  375. locked = true;
  376. break;
  377. }
  378. usleep(kDumpLockSleep);
  379. }
  380. return locked;
  381. }
  382. status_t CameraService::dump(int fd, const Vector<String16>& args) {
  383. String8 result;
  384. if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
  385. result.appendFormat("Permission Denial: "
  386. "can't dump CameraService from pid=%d, uid=%d\n",
  387. getCallingPid(),
  388. getCallingUid());
  389. write(fd, result.string(), result.size());
  390. } else {
  391. bool locked = tryLock(mServiceLock);
  392. // failed to lock - CameraService is probably deadlocked
  393. if (!locked) {
  394. result.append("CameraService may be deadlocked\n");
  395. write(fd, result.string(), result.size());
  396. }
  397. bool hasClient = false;
  398. if (!mModule) {
  399. result = String8::format("No camera module available!\n");
  400. write(fd, result.string(), result.size());
  401. return NO_ERROR;
  402. }
  403. result = String8::format("Camera module HAL API version: 0x%x\n",
  404. mModule->common.hal_api_version);
  405. result.appendFormat("Camera module API version: 0x%x\n",
  406. mModule->common.module_api_version);
  407. result.appendFormat("Camera module name: %s\n",
  408. mModule->common.name);
  409. result.appendFormat("Camera module author: %s\n",
  410. mModule->common.author);
  411. result.appendFormat("Number of camera devices: %d\n\n", mNumberOfCameras);
  412. write(fd, result.string(), result.size());
  413. for (int i = 0; i < mNumberOfCameras; i++) {
  414. result = String8::format("Camera %d static information:\n", i);
  415. camera_info info;
  416. status_t rc = mModule->get_camera_info(i, &info);
  417. if (rc != OK) {
  418. result.appendFormat(" Error reading static information!\n");
  419. write(fd, result.string(), result.size());
  420. } else {
  421. result.appendFormat(" Facing: %s\n",
  422. info.facing == CAMERA_FACING_BACK ? "BACK" : "FRONT");
  423. result.appendFormat(" Orientation: %d\n", info.orientation);
  424. int deviceVersion;
  425. if (mModule->common.module_api_version <
  426. CAMERA_MODULE_API_VERSION_2_0) {
  427. deviceVersion = CAMERA_DEVICE_API_VERSION_1_0;
  428. } else {
  429. deviceVersion = info.device_version;
  430. }
  431. result.appendFormat(" Device version: 0x%x\n", deviceVersion);
  432. if (deviceVersion >= CAMERA_DEVICE_API_VERSION_2_0) {
  433. result.appendFormat(" Device static metadata:\n");
  434. write(fd, result.string(), result.size());
  435. dump_indented_camera_metadata(info.static_camera_characteristics,
  436. fd, 2, 4);
  437. } else {
  438. write(fd, result.string(), result.size());
  439. }
  440. }
  441. sp<Client> client = mClient[i].promote();
  442. if (client == 0) {
  443. result = String8::format(" Device is closed, no client instance\n");
  444. write(fd, result.string(), result.size());
  445. continue;
  446. }
  447. hasClient = true;
  448. result = String8::format(" Device is open. Client instance dump:\n");
  449. write(fd, result.string(), result.size());
  450. client->dump(fd, args);
  451. }
  452. if (!hasClient) {
  453. result = String8::format("\nNo active camera clients yet.\n");
  454. write(fd, result.string(), result.size());
  455. }
  456. if (locked) mServiceLock.unlock();
  457. // change logging level
  458. int n = args.size();
  459. for (int i = 0; i + 1 < n; i++) {
  460. String16 verboseOption("-v");
  461. if (args[i] == verboseOption) {
  462. String8 levelStr(args[i+1]);
  463. int level = atoi(levelStr.string());
  464. result = String8::format("\nSetting log level to %d.\n", level);
  465. setLogLevel(level);
  466. write(fd, result.string(), result.size());
  467. }
  468. }
  469. }
  470. return NO_ERROR;
  471. }
  472. /*virtual*/void CameraService::binderDied(
  473. const wp<IBinder> &who) {
  474. /**
  475. * While tempting to promote the wp<IBinder> into a sp,
  476. * it's actually not supported by the binder driver
  477. */
  478. ALOGV("java clients' binder died");
  479. sp<Client> cameraClient = getClientByRemote(who);
  480. if (cameraClient == 0) {
  481. ALOGV("java clients' binder death already cleaned up (normal case)");
  482. return;
  483. }
  484. ALOGW("Disconnecting camera client %p since the binder for it "
  485. "died (this pid %d)", cameraClient.get(), getCallingPid());
  486. cameraClient->disconnect();
  487. }
  488. }; // namespace android