Camera.java
中的 open()
方法做爲切入點。做爲打開攝像頭的方法,不管哪一種 Camera 應用都須要調用到它。Camera.open()
被調用開始,這一指令是如何經過 Framework 層走到 C/C++ 層,又是如何進入 HAL 層從而使得指令可以到達設備端。Framework -> Android Runtime -> C/C++ Libraries -> HAL
的順序去分析整個調用流程。frameworks/base/core/java/android/hardware/Camera.java
Open()
方法開始:
Camera
設備的個數。new Camera(int)
構造對應的攝像頭實例。null
。open(int)
,它能夠直接指定打開的攝像頭。/***
java
* Creates a new Camera object to access
android
* the first back-facing camera on the
shell
* device. If the device does not have a back-facing camera,
api
* this returns null.
架構
* @see #open(int)
ide
*/
函數
public static Camera open() {
oop
int numberOfCameras = getNumberOfCameras();
源碼分析
CameraInfo cameraInfo = new CameraInfo();
ui
for (int i = 0; i < numberOfCameras; i++) {
getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
return new Camera(i);
}
}
return null;
}
Camera(int cameraId)
:
cameraInitNormal(Id)
方法對指定攝像頭進行初始化。/** used by Camera#open, Camera#open(int) */
Camera(int cameraId) {
int err = cameraInitNormal(cameraId);
if (checkInitErrors(err)) {
if (err == -EACCES) {
throw new RuntimeException("Fail to connect to camera service");
} else if (err == -ENODEV) {
throw new RuntimeException("Camera initialization failed");
}
// Should never hit this.
throw new RuntimeException("Unknown camera error");
}
}
cameraInitNormal(int cameraId)
:
halVersion
參數。cameraInitVersion(int cameraId, int halVersion)
。private int cameraInitNormal(int cameraId) {
return cameraInitVersion(cameraId,
CAMERA_HAL_API_VERSION_NORMAL_CONNECT);
}
cameraInitVersion(int cameraId, int halVersion)
:
Looper
的做用沒有仔細研究,從代碼邏輯上看,可能與事件的監聽(須要循環操做)有關。Looper
對事件處理對象進行實例化後,就調用 native_setup
方法進入 JNI(Java Native Interface)
庫中調用對應的函數。open()
方法開始進入 Android Runtime
層。private int cameraInitVersion(int cameraId,
int halVersion) {
mShutterCallback = null;
mRawImageCallback = null;
mJpegCallback = null;
mPreviewCallback = null;
mPostviewCallback = null;
mUsingPreviewAllocation = false;
mZoomListener = null;
Looper looper;
if ((looper = Looper.myLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else if ((looper = Looper.getMainLooper()) != null) {
mEventHandler = new EventHandler(this, looper);
} else {
mEventHandler = null;
}
return native_setup(new WeakReference<Camera>(this),
cameraId, halVersion,
ActivityThread.currentOpPackageName());
}
frameworks/base/core/jni/android_hardware_Camera.cpp
native_setup()
:
clientPackageName
作一個類型轉換,變成 clientName
。Camera
類型的 StrongPointer(sp)
。Camera::connect()
或 Camera::connectLegacy()
,讓客戶端與服務端進行鏈接,並返回相應的 Camera
實例。connect()
的時候,就進入了 C/C++ Libraries
的 C/S 結構中,而 Camera
則屬於 Client
。// connect to camera service
static jint android_hardware_Camera_native_setup(JNIEnv *env,
jobject thiz, jobject weak_this,
jint cameraId, jint halVersion,
jstring clientPackageName)
{
// convert jstring to String16(clientPackageName -> clientName)
......
......
sp<Camera> camera;
if (halVersion == CAMERA_HAL_API_VERSION_NORMAL_CONNECT) {
/***** NOTE THIS *****/
// Default path: hal version is don't care, do normal camera connect.
camera = Camera::connect(cameraId, clientName,
Camera::USE_CALLING_UID,
Camera::USE_CALLING_PID);
} else {
jint status = Camera::connectLegacy(cameraId,
halVersion, clientName,
Camera::USE_CALLING_UID, camera);
if (status != NO_ERROR) {
return status;
}
}
if (camera == NULL) {
return -EACCES;
}
// make sure camera hardware is alive
if (camera->getStatus() != NO_ERROR) {
return NO_INIT;
}
// save context in opaque field
......
......
}
frameworks/av/include/camera/Camera.h
CameraTraits<Camera>
的結構體:template <>
struct CameraTraits<Camera>
{
typedef CameraListener TCamListener;
typedef ::android::hardware::ICamera TCamUser;
typedef ::android::hardware::ICameraClient TCamCallbacks;
typedef ::android::binder::Status(::android::hardware::ICameraService::*TCamConnectService)
(const sp<::android::hardware::ICameraClient>&,
int, const String16&, int, int,
/*out*/
sp<::android::hardware::ICamera>*);
static TCamConnectService fnConnectService;
};
framework/av/camera/Camera.cpp
fnConnectService
是對應到 ICameraService::connect
函數的。CameraTraits<Camera>::TCamConnectService CameraTraits<Camera>::fnConnectService =
&::android::hardware::ICameraService::connect;
Camera::connect
:
CameraBaseT::connect()
這是定義在 CameraBase.cpp
中的函數。sp<Camera> Camera::connect(int cameraId,
const String16& clientPackageName,
int clientUid, int clientPid)
{
return CameraBaseT::connect(cameraId,
clientPackageName, clientUid, clientPid);
}
frameworks/av/include/camera/CameraBase.h
TCam
對應 Camera
。TCamTraits
對應 CameraTraits<Camera>
。template <typename TCam, typename TCamTraits = CameraTraits<TCam> >
CameraBaseT
對應 CameraBase<Camera>
。sp<TCamUser> mCamera;
status_t mStatus;
sp<TCamListener> mListener;
const int mCameraId;
/***** NOTE THIS *****/
typedef CameraBase<TCam> CameraBaseT;
framework/av/camera/CameraBase.cpp
connect()
:
Camera
Camera
獲取 ICameraClient
指針。getCameraService()
函數獲取 ICameraService
。ICameraService::connect()
函數得到一個 mCamera
, 即 ICamera
實例。ICamera
實例與 Binder
創建聯繫。template <typename TCam, typename TCamTraits>
sp<TCam> CameraBase<TCam, TCamTraits>::connect(int cameraId,
const String16& clientPackageName,
int clientUid, int clientPid)
{
ALOGV("%s: connect", __FUNCTION__);
/***** NOTE THIS *****/
sp<TCam> c = new TCam(cameraId);
sp<TCamCallbacks> cl = c;
const sp<::android::hardware::ICameraService> cs = getCameraService();
binder::Status ret;
if (cs != nullptr) {
/***** NOTE THIS *****/
TCamConnectService fnConnectService = TCamTraits::fnConnectService;
ret = (cs.get()->*fnConnectService)(cl, cameraId,
clientPackageName, clientUid,
clientPid, /*out*/ &c->mCamera);
}
if (ret.isOk() && c->mCamera != nullptr) {
/***** NOTE THIS *****/
IInterface::asBinder(c->mCamera)->linkToDeath(c);
c->mStatus = NO_ERROR;
} else {
ALOGW("An error occurred while connecting to camera %d: %s", cameraId,
(cs != nullptr) ? "Service not available" : ret.toString8().string());
c.clear();
}
return c;
}
getCameraService()
:
gCameraService
是一個 ICameraService
。ICameraService
的 get
函數,若是能獲取到 ICameraService
則返回。IServiceManager
來獲取一個 ICameraService
,這個過程當中主要是經過 IBinder
來進行數據的獲取的,其中機制暫時忽略,只要知道經過 Binder
咱們獲取了一個 ICameraService
就好。// establish binder interface to camera service
template <typename TCam, typename TCamTraits>
const sp<::android::hardware::ICameraService> CameraBase<TCam, TCamTraits>::getCameraService()
{
Mutex::Autolock _l(gLock);
/***** NOTE THIS *****/
if (gCameraService.get() == 0) {
char value[PROPERTY_VALUE_MAX];
property_get("config.disable_cameraservice", value, "0");
if (strncmp(value, "0", 2) != 0 && strncasecmp(value, "false", 6) != 0) {
return gCameraService;
}
/***** NOTE THIS *****/
sp<IServiceManager> sm = defaultServiceManager();
sp<IBinder> binder;
do {
binder = sm->getService(String16(kCameraServiceName));
if (binder != 0) {
break;
}
ALOGW("CameraService not published, waiting...");
usleep(kCameraServicePollDelay);
} while(true);
if (gDeathNotifier == NULL) {
gDeathNotifier = new DeathNotifier();
}
binder->linkToDeath(gDeathNotifier);
/***** NOTE THIS *****/
gCameraService = interface_cast<::android::hardware::ICameraService>(binder);
}
ALOGE_IF(gCameraService == 0, "no CameraService!?");
return gCameraService;
}
CameraBase
中,所調用的 connect
對應的是 CameraService::connect()
,在下一節中再進行分析。frameworks/av/camera/aidl/android/hardware/ICameraService.aidl
aidl
是一種內部進程通信的描述語言,經過它咱們能夠定義通信的接口。/**
* Binder interface for the native camera service running in mediaserver.
*
* @hide
*/
connect
接口:
Camera API
,即 API 1
。/**
* Open a camera device through the old camera API
*/
ICamera connect(ICameraClient client,
int cameraId,
String opPackageName,
int clientUid, int clientPid);
out/target/product/generic/obj/SHARED_LIBRARIES/libcamera_client_intermediates/aidl-generated/src/aidl/android/hardware/ICameraService.cpp
out
文件夾是源碼編譯後才生成的.ICameraService.cpp
以及其頭文件 ICameraService.h
都是根據其對應的 aidl
文件自動生成的。BpCameraService::connect()
:
BpCameraservice
,它繼承了 ICameraService
,同時也繼承了 BpInterface
。Parcel
能夠當作是 Binder
通信中的信息傳遞中介。Parcel
。remote()
中的處理函數 transact()
。reply
數據判斷是否有 error
。::android::binder::Status BpCameraService::connect(const ::android::sp<::android::hardware::ICameraClient>& client,
int32_t cameraId, const ::android::String16& opPackageName,
int32_t clientUid, int32_t clientPid,
::android::sp<::android::hardware::ICamera>* _aidl_return)
{
::android::Parcel _aidl_data;
::android::Parcel _aidl_reply;
::android::status_t _aidl_ret_status = ::android::OK;
::android::binder::Status _aidl_status;
_aidl_ret_status = _aidl_data.writeInterfaceToken(getInterfaceDescriptor());
/***** NOTE THIS *****/
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_data.writeStrongBinder(::android::hardware::ICameraClient::asBinder(client));
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_data.writeInt32(cameraId);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_data.writeString16(opPackageName);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_data.writeInt32(clientUid);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_data.writeInt32(clientPid);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
/***** NOTE THIS *****/
_aidl_ret_status = remote()->transact(ICameraService::CONNECT, _aidl_data, &_aidl_reply);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_ret_status = _aidl_status.readFromParcel(_aidl_reply);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
if (!_aidl_status.isOk()) {
return _aidl_status;
}
_aidl_ret_status = _aidl_reply.readStrongBinder(_aidl_return);
if (((_aidl_ret_status) != (::android::OK))) {
goto _aidl_error;
}
_aidl_error:
_aidl_status.setFromStatusT(_aidl_ret_status);
return _aidl_status;
}
BnCameraService::onTransact()
:
CONNECT
相關的一段。BpCameraService
經過 Binder
封裝了接口,而 BnCameraService
則具體實現接口。Bp
傳來的數據,而後調用了具體的 connect
函數獲取 ICamera
而且返回。case Call::CONNECT:
{
::android::sp<::android::hardware::ICameraClient> in_client;
int32_t in_cameraId;
::android::String16 in_opPackageName;
int32_t in_clientUid;
int32_t in_clientPid;
/***** NOTE THIS *****/
::android::sp<::android::hardware::ICamera> _aidl_return;
if (!(_aidl_data.checkInterface(this))) {
_aidl_ret_status = ::android::BAD_TYPE;
break;
}
_aidl_ret_status = _aidl_data.readStrongBinder(&in_client);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
_aidl_ret_status = _aidl_data.readInt32(&in_cameraId);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
_aidl_ret_status = _aidl_data.readString16(&in_opPackageName);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
_aidl_ret_status = _aidl_data.readInt32(&in_clientUid);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
_aidl_ret_status = _aidl_data.readInt32(&in_clientPid);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
/***** NOTE THIS *****/
::android::binder::Status _aidl_status(connect(in_client, in_cameraId, in_opPackageName, in_clientUid, in_clientPid, &_aidl_return));
_aidl_ret_status = _aidl_status.writeToParcel(_aidl_reply);
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
if (!_aidl_status.isOk()) {
break;
}
/***** NOTE THIS *****/
_aidl_ret_status = _aidl_reply->writeStrongBinder(::android::hardware::ICamera::asBinder(_aidl_return));
if (((_aidl_ret_status) != (::android::OK))) {
break;
}
}
break;
CameraBase
關於 connect()
函數的調用中。frameworks/av/camera/ICamera.cpp
BpCamera
類只提供給 Client
調用的接口。BpCamera
類中,有 connect()
函數:virtual status_t connect(const sp<ICameraClient>& cameraClient)
{
Parcel data, reply;
data.writeInterfaceToken(ICamera::getInterfaceDescriptor());
data.writeStrongBinder(IInterface::asBinder(cameraClient));
remote()->transact(CONNECT, data, &reply);
return reply.readInt32();
}
BnCamera
類應負責實現接口,但這裏有一點特殊,它是經過 CameraService::Client
來實現具體接口的。BnCamera
類中,onTransact
函數則有相應的處理:case CONNECT: {
CHECK_INTERFACE(ICamera, data, reply);
sp<ICameraClient> cameraClient = interface_cast<ICameraClient>(data.readStrongBinder());
reply->writeInt32(connect(cameraClient));
return NO_ERROR;
} break;
frameworks/av/services/camera/libcameraservice/CameraService.cpp
connect()
:
connectHelper()
函數中。*device
返回。Status CameraService::connect(
const sp<ICameraClient>& cameraClient,
int cameraId,
const String16& clientPackageName,
int clientUid,
int clientPid,
/*out*/
sp<ICamera>* device) {
ATRACE_CALL();
Status ret = Status::ok();
String8 id = String8::format("%d", cameraId);
sp<Client> client = nullptr;
ret = connectHelper<ICameraClient,Client>(cameraClient, id,
CAMERA_HAL_API_VERSION_UNSPECIFIED, clientPackageName, clientUid, clientPid, API_1,
/*legacyMode*/ false, /*shimUpdateOnly*/ false,
/*out*/client);
if(!ret.isOk()) {
logRejected(id, getCallingPid(), String8(clientPackageName),
ret.toString8());
return ret;
}
*device = client;
return ret;
}
frameworks/av/services/camera/libcameraservice/CameraService.h
connectHelper()
:
MediaRecorder
,則直接將其取出返回。deviceVersion
,而後再調用 makeClient()
函數建立一個客戶端。initialize()
函數進行初始化,注意其傳入的參數是 mModule
,這個參數是鏈接 Libraries
與 HAL
的關鍵參數。sp<BasicClient> clientTmp = nullptr;
std::shared_ptr<resource_policy::ClientDescriptor<String8, sp<BasicClient>>> partial;
if ((err = handleEvictionsLocked(cameraId,
originalClientPid, effectiveApiLevel,
IInterface::asBinder(cameraCb), clientName8,
/*out*/&clientTmp,
/*out*/&partial)) != NO_ERROR) {
/***** do something *****/
}
/***** NOTE THIS *****/
if (clientTmp.get() != nullptr) {
// Handle special case for API1 MediaRecorder where the existing client is returned
device = static_cast<CLIENT*>(clientTmp.get());
return ret;
}
// give flashlight a chance to close devices if necessary.
mFlashlight->prepareDeviceOpen(cameraId);
// TODO: Update getDeviceVersion + HAL interface to use strings for Camera IDs
int id = cameraIdToInt(cameraId);
if (id == -1) {
ALOGE("%s: Invalid camera ID %s, cannot get device version from HAL.", __FUNCTION__,
cameraId.string());
return STATUS_ERROR_FMT(ERROR_ILLEGAL_ARGUMENT,
"Bad camera ID \"%s\" passed to camera open", cameraId.string());
}
int facing = -1;
/***** NOTE THIS *****/
int deviceVersion = getDeviceVersion(id, /*out*/&facing);
sp<BasicClient> tmp = nullptr;
if(!(ret = makeClient(this, cameraCb,
clientPackageName, id, facing, clientPid,
clientUid, getpid(), legacyMode, halVersion,
deviceVersion, effectiveApiLevel,
/*out*/&tmp)).isOk()) {
return ret;
}
client = static_cast<CLIENT*>(tmp.get());
LOG_ALWAYS_FATAL_IF(client.get() == nullptr, "%s: CameraService in invalid state",
__FUNCTION__);
/***** NOTE THIS *****/
if ((err = client->initialize(mModule)) != OK) {
/***** do somthing *****/
}
// Update shim paremeters for legacy clients
if (effectiveApiLevel == API_1) {
// Assume we have always received a Client subclass for API1
sp<Client> shimClient = reinterpret_cast<Client*>(client.get());
String8 rawParams = shimClient->getParameters();
CameraParameters params(rawParams);
auto cameraState = getCameraState(cameraId);
if (cameraState != nullptr) {
cameraState->setShimParams(params);
} else {
ALOGE("%s: Cannot update shim parameters for camera %s, no such device exists.",
__FUNCTION__, cameraId.string());
}
}
if (shimUpdateOnly) {
// If only updating legacy shim parameters, immediately disconnect client
mServiceLock.unlock();
client->disconnect();
mServiceLock.lock();
} else {
// Otherwise, add client to active clients list
finishConnectLocked(client, partial);
}
} // lock is destroyed, allow further connect calls
// Important: release the mutex here so the client can call back into the service from its
// destructor (can be at the end of the call)
device = client;
frameworks/av/services/camera/libcameraservice/api1/CameraClient.cpp
Camera API 1
的流程。CameraClient
繼承了 CameraService::Client
。CameraClient::initialize()
:
CameraHardwareInterface
實例。mHardware
進行初始化。status_t CameraClient::initialize(CameraModule *module) {
int callingPid = getCallingPid();
status_t res;
LOG1("CameraClient::initialize E (pid %d, id %d)", callingPid, mCameraId);
// Verify ops permissions
res = startCameraOps();
if (res != OK) {
return res;
}
char camera_device_name[10];
snprintf(camera_device_name, sizeof(camera_device_name), "%d", mCameraId);
/***** NOTE THIS *****/
mHardware = new CameraHardwareInterface(camera_device_name);
res = mHardware->initialize(module);
if (res != OK) {
ALOGE("%s: Camera %d: unable to initialize device: %s (%d)",
__FUNCTION__, mCameraId, strerror(-res), res);
mHardware.clear();
return res;
}
mHardware->setCallbacks(notifyCallback,
dataCallback,
dataCallbackTimestamp,
(void *)(uintptr_t)mCameraId);
// Enable zoom, error, focus, and metadata messages by default
enableMsgType(CAMERA_MSG_ERROR | CAMERA_MSG_ZOOM | CAMERA_MSG_FOCUS |
CAMERA_MSG_PREVIEW_METADATA | CAMERA_MSG_FOCUS_MOVE);
LOG1("CameraClient::initialize X (pid %d, id %d)", callingPid, mCameraId);
return OK;
}
Libraries
層的 open
流程就結束了,接下來進入到 HAL
層。frameworks/av/services/camera/libcameraservice/device1/CameraHardwareInterface.h
initialize()
:
module
,從 HAL
層的庫中調用相關的函數獲取 Camera
設備信息。API
的版本,判斷是用 open
函數仍是用 openLegacy
。open
後,經過 HAL
中的庫,咱們的指令就能傳遞到 Linux Kernel
,從而下達到具體的設備上。(與具體的驅動相關,暫時不去分析)status_t initialize(CameraModule *module)
{
ALOGI("Opening camera %s", mName.string());
camera_info info;
status_t res = module->getCameraInfo(atoi(mName.string()), &info);
if (res != OK) {
return res;
}
int rc = OK;
if (module->getModuleApiVersion() >= CAMERA_MODULE_API_VERSION_2_3 &&
info.device_version > CAMERA_DEVICE_API_VERSION_1_0) {
// Open higher version camera device as HAL1.0 device.
rc = module->openLegacy(mName.string(),
CAMERA_DEVICE_API_VERSION_1_0,
(hw_device_t **)&mDevice);
} else {
rc = module->open(mName.string(), (hw_device_t **)&mDevice);
}
if (rc != OK) {
ALOGE("Could not open camera %s: %d", mName.string(), rc);
return rc;
}
initHalPreviewWindow();
return rc;
}
Camera Open
整個調用流程就已經比較清晰了。Camera.open()
方法被調用開始,對源碼進行追溯,從而一層層地瞭解了它的一個調用的過程,與過程當中比較重要的一些邏輯。Camera
架構有一個更深入的認識,可是其中可能還有一些知識點沒有理清,不過我認爲不會影響對於整個架構的瞭解。Libraries
中,關於客戶端與服務端交互的部分。這一部分我在閱讀源碼的時候花了不少時間去理解,實際上目前爲止,也只是有比較基礎的概念。對這部分,還有不少更深刻的內容須要去探究,在系統源碼分析1一書中,有關於 Binder
的很詳細的解析,經過深刻了解 Binder
機制,我認爲應該能更清楚 C/S
相關的內容。HAL
層接觸的這一部分,mModule
這個變量很是關鍵,可是我認爲它的相關內容單獨放在一篇筆記中分析,會比較清晰,因此下一篇筆記就先探究 module
相關的內容。