巴延興
深圳開鴻數字產業發展有限公司
資深OS框架開發工程師
一、簡介
媒體子系統為開發者提供了媒體相關的很多功能,本文針對其中的視頻錄制功能做個詳細的介紹。首先,我將通過媒體子系統提供的視頻錄制Test代碼作為切入點,給大家梳理一下整個錄制的流程。
二、目錄
foundation/multimedia/camera_framework
├──frameworks
│ ├── js
│ │ └── camera_napi #napi實現
│ │ └── src
│ │ ├── input #Camera輸入
│ │ ├── output #Camera輸出
│ │ └── session #會話管理
│ └── native #native實現
│ └── camera
│ ├── BUILD.gn
│ ├── src
│ │ ├── input #Camera輸入
│ │ ├── output #Camera輸出
│ │ └── session #會話管理
├── interfaces #接口定義
│ ├── inner_api #內部native實現
│ │ └── native
│ │ ├── camera
│ │ │ └── include
│ │ │ ├── input
│ │ │ ├── output
│ │ │ └── session
│ └── kits #napi接口
│ └── js
│ └── camera_napi
│ ├── BUILD.gn
│ ├── include
│ │ ├── input
│ │ ├── output
│ │ └── session
│ └── @ohos.multimedia.camera.d.ts
└── services #服務端
└── camera_service
├── binder
│ ├── base
│ ├── client #IPC的客戶端
│ │ └── src
│ └── server #IPC的服務端
│ └── src
└──src
三、錄制的總體流程
? ?四、Native接口使用
在OpenAtom OpenHarmony(以下簡稱“OpenHarmony”)系統中,多媒體子系統通過N-API接口提供給上層JS調用,N-API相當于是JS和Native之間的橋梁,在OpenHarmony源碼中,提供了C++直接調用視頻錄制功能的例子,foundation/multimedia/camera_framework/interfaces/inner_api/native/test目錄中。本文章主要參考了camera_video.cpp文件中的視頻錄制流程。 首先根據camera_video.cpp的main方法,了解下視頻錄制的主要流程代碼。
int main(int argc, char **argv)
{
......
// 創建CameraManager實例
sptr camManagerObj = CameraManager::GetInstance();
// 設置回調
camManagerObj->SetCallback(std::make_shared(testName));
// 獲取支持的相機設備列表
std::vector> cameraObjList = camManagerObj->GetSupportedCameras();
// 創建采集會話
sptr captureSession = camManagerObj->CreateCaptureSession();
// 開始配置采集會話
captureSession->BeginConfig();
// 創建CameraInput
sptr captureInput = camManagerObj->CreateCameraInput(cameraObjList[0]);
sptr cameraInput = (sptr &)captureInput;
// 開啟CameraInput
cameraInput->Open();
// 設置CameraInput的Error回調
cameraInput->SetErrorCallback(std::make_shared(testName));
// 添加CameraInput實例到采集會話中
ret = captureSession->AddInput(cameraInput);
sptr videoSurface = nullptr;
std::shared_ptr recorder = nullptr;
// 創建Video的Surface
videoSurface = Surface::CreateSurfaceAsConsumer();
sptr videoListener = new SurfaceListener("Video", SurfaceType::VIDEO, g_videoFd, videoSurface);
// 注冊Surface的事件監聽
videoSurface->RegisterConsumerListener((sptr &)videoListener);
// 視頻的配置
VideoProfile videoprofile = VideoProfile(static_cast(videoFormat), videosize, videoframerates);
// 創建VideoOutput實例
sptr videoOutput = camManagerObj->CreateVideoOutput(videoprofile, videoSurface);
// 設置VideoOutput的回調
((sptr &)videoOutput)->SetCallback(std::make_shared(testName));
// 添加videoOutput到采集會話中
ret = captureSession->AddOutput(videoOutput);
// 提交會話配置
ret = captureSession->CommitConfig();
// 開始錄制
ret = ((sptr &)videoOutput)->Start();
sleep(videoPauseDuration);
MEDIA_DEBUG_LOG("Resume video recording");
// 暫停錄制
ret = ((sptr &)videoOutput)->Resume();
MEDIA_DEBUG_LOG("Wait for 5 seconds before stop");
sleep(videoCaptureDuration);
MEDIA_DEBUG_LOG("Stop video recording");
// 停止錄制
ret = ((sptr &)videoOutput)->Stop();
MEDIA_DEBUG_LOG("Closing the session");
// 停止采集會話
ret = captureSession->Stop();
MEDIA_DEBUG_LOG("Releasing the session");
// 釋放會話采集
captureSession->Release();
// Close video file
TestUtils::SaveVideoFile(nullptr, 0, VideoSaveMode::CLOSE, g_videoFd);
cameraInput->Release();
camManagerObj->SetCallback(nullptr);
return 0;
}
以上是視頻錄制的整體流程,其過程主要通過Camera模塊支持的能力來實現,其中涉及幾個重要的類:CaptureSession、CameraInput、VideoOutput。CaptureSession是整個過程的控制者,CameraInput和VideoOutput相當于是設備的輸入和輸出。
五、調用流程
? ? ? 左右滑動查看更多 ?后續主要針對上面的調用流程,梳理具體的調用流程,方便我們對了解視頻錄制的整理架構有一個更加深入的了解。 1. 創建CameraManager實例通過CameraManager::GetInstance()獲取CameraManager的實例,后續的一些接口都是通過該實例進行調用的。GetInstance使用了單例模式,在OpenHarmony代碼中這種方式很常見。
sptr &CameraManager::GetInstance()
{
if (CameraManager::cameraManager_ == nullptr) {
MEDIA_INFO_LOG("Initializing camera manager for first time!");
CameraManager::cameraManager_ = new(std::nothrow) CameraManager();
if (CameraManager::cameraManager_ == nullptr) {
MEDIA_ERR_LOG("CameraManager::GetInstance failed to new CameraManager");
}
}
return CameraManager::cameraManager_;
}
2. 獲取支持的相機設備列表通過調用CameraManager的GetSupportedCameras()接口,獲取設備支持的CameraDevice列表。跟蹤代碼可以發現serviceProxy_->GetCameras最終會調用到Camera服務端的對應接口。
std::vector> CameraManager::GetSupportedCameras()
{
CAMERA_SYNC_TRACE;
std::lock_guard lock(mutex_);
std::vector cameraIds;
std::vector> cameraAbilityList;
int32_t retCode = -1;
sptr cameraObj = nullptr;
int32_t index = 0;
if (cameraObjList.size() > 0) {
cameraObjList.clear();
}
if (serviceProxy_ == nullptr) {
MEDIA_ERR_LOG("CameraManager::GetCameras serviceProxy_ is null, returning empty list!");
return cameraObjList;
}
std::vector> supportedCameras;
retCode = serviceProxy_->GetCameras(cameraIds, cameraAbilityList);
if (retCode == CAMERA_OK) {
for (auto& it : cameraIds) {
cameraObj = new(std::nothrow) CameraDevice(it, cameraAbilityList[index++]);
if (cameraObj == nullptr) {
MEDIA_ERR_LOG("CameraManager::GetCameras new CameraDevice failed for id={public}%s", it.c_str());
continue;
}
supportedCameras.emplace_back(cameraObj);
}
} else {
MEDIA_ERR_LOG("CameraManager::GetCameras failed!, retCode: %{public}d", retCode);
}
ChooseDeFaultCameras(supportedCameras);
return cameraObjList;
}
3. 創建采集會話下面是比較重要的環節,通過調用CameraManager的CreateCaptureSession接口創建采集會話。CameraManager創建采集會話,是通過serviceProxy_->CreateCaptureSession方式進行調用,這里涉及到了OpenHarmony中的IPC的調用,serviceProxy_是遠端服務在本地的代理,通過這個代理可以調用到具體的服務端,這里是HCameraService。
sptr CameraManager::CreateCaptureSession()
{
CAMERA_SYNC_TRACE;
sptr captureSession = nullptr;
sptr result = nullptr;
int32_t retCode = CAMERA_OK;
if (serviceProxy_ == nullptr) {
MEDIA_ERR_LOG("CameraManager::CreateCaptureSession serviceProxy_ is null");
return nullptr;
}
retCode = serviceProxy_->CreateCaptureSession(captureSession);
if (retCode == CAMERA_OK && captureSession != nullptr) {
result = new(std::nothrow) CaptureSession(captureSession);
if (result == nullptr) {
MEDIA_ERR_LOG("Failed to new CaptureSession");
}
} else {
MEDIA_ERR_LOG("Failed to get capture session object from hcamera service!, %{public}d", retCode);
}
return result;
}
代碼最終來到HCameraService::CreateCaptureSession中,該方法中new了一個HCaptureSession對象,并且將該對象傳遞給了參數session,所以前面的captureSession對象就是這里new出來的HCaptureSession,前面的CameraManager的CreateCaptureSession()方法中將captureSession封裝成CaptureSession對象返回給應用層使用。
int32_t HCameraService::CreateCaptureSession(sptr &session)
{
CAMERA_SYNC_TRACE;
sptr captureSession;
if (streamOperatorCallback_ == nullptr) {
streamOperatorCallback_ = new(std::nothrow) StreamOperatorCallback();
if (streamOperatorCallback_ == nullptr) {
MEDIA_ERR_LOG("HCameraService::CreateCaptureSession streamOperatorCallback_ allocation failed");
return CAMERA_ALLOC_ERROR;
}
}
std::lock_guard lock(mutex_);
OHOS::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID();
captureSession = new(std::nothrow) HCaptureSession(cameraHostManager_, streamOperatorCallback_, callerToken);
if (captureSession == nullptr) {
MEDIA_ERR_LOG("HCameraService::CreateCaptureSession HCaptureSession allocation failed");
return CAMERA_ALLOC_ERROR;
}
session = captureSession;
return CAMERA_OK;
}
4. 開始配置采集會話調用CaptureSession的BeginConfig進行采集會話的配置工作。這個工作最終調用到被封裝的HCaptureSession中。
int32_t HCaptureSession::BeginConfig()
{
CAMERA_SYNC_TRACE;
if (curState_ == CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
MEDIA_ERR_LOG("HCaptureSession::BeginConfig Already in config inprogress state!");
return CAMERA_INVALID_STATE;
}
std::lock_guard lock(sessionLock_);
prevState_ = curState_;
curState_ = CaptureSessionState::SESSION_CONFIG_INPROGRESS;
tempCameraDevices_.clear();
tempStreams_.clear();
deletedStreamIds_.clear();
return CAMERA_OK;
}
5. 創建CameraInput應用層通過camManagerObj->CreateCameraInput(cameraObjList[0])的方式進行CameraInput的創建,cameraObjList[0]就是前面獲取支持設備的第一個。根據CameraDevice創建對應的CameraInput對象。
sptr CameraManager::CreateCameraInput(sptr &camera)
{
CAMERA_SYNC_TRACE;
sptr cameraInput = nullptr;
sptr deviceObj = nullptr;
if (camera != nullptr) {
deviceObj = CreateCameraDevice(camera->GetID());
if (deviceObj != nullptr) {
cameraInput = new(std::nothrow) CameraInput(deviceObj, camera);
if (cameraInput == nullptr) {
MEDIA_ERR_LOG("failed to new CameraInput Returning null in CreateCameraInput");
return cameraInput;
}
} else {
MEDIA_ERR_LOG("Returning null in CreateCameraInput");
}
} else {
MEDIA_ERR_LOG("CameraManager: Camera object is null");
}
return cameraInput;
}
6. 開啟CameraInput調用了CameraInput的Open方法,進行輸入設備的啟動打開。
void CameraInput::Open()
{
int32_t retCode = deviceObj_->Open();
if (retCode != CAMERA_OK) {
MEDIA_ERR_LOG("Failed to open Camera Input, retCode: %{public}d", retCode);
}
}
7. 添加CameraInput實例到采集會話中通過調用captureSession的AddInput方法,將創建的CameraInput對象添加到采集會話的輸入中,這樣采集會話就知道采集輸入的設備。
int32_t CaptureSession::AddInput(sptr &input)
{
CAMERA_SYNC_TRACE;
if (input == nullptr) {
MEDIA_ERR_LOG("CaptureSession::AddInput input is null");
return CAMERA_INVALID_ARG;
}
input->SetSession(this);
inputDevice_ = input;
return captureSession_->AddInput(((sptr &)input)->GetCameraDevice());
}
最終調用到HCaptureSession的AddInput方法,該方法中核心的代碼是tempCameraDevices_.emplace_back(localCameraDevice),將需要添加的CameraDevice插入到tempCameraDevices_容器中。
int32_t HCaptureSession::AddInput(sptr cameraDevice)
{
CAMERA_SYNC_TRACE;
sptr localCameraDevice = nullptr;
if (cameraDevice == nullptr) {
MEDIA_ERR_LOG("HCaptureSession::AddInput cameraDevice is null");
return CAMERA_INVALID_ARG;
}
if (curState_ != CaptureSessionState::SESSION_CONFIG_INPROGRESS) {
MEDIA_ERR_LOG("HCaptureSession::AddInput Need to call BeginConfig before adding input");
return CAMERA_INVALID_STATE;
}
if (!tempCameraDevices_.empty() || (cameraDevice_ != nullptr && !cameraDevice_->IsReleaseCameraDevice())) {
MEDIA_ERR_LOG("HCaptureSession::AddInput Only one input is supported");
return CAMERA_INVALID_SESSION_CFG;
}
localCameraDevice = static_cast(cameraDevice.GetRefPtr());*>
if (cameraDevice_ == localCameraDevice) {
cameraDevice_->SetReleaseCameraDevice(false);
} else {
tempCameraDevices_.emplace_back(localCameraDevice);
CAMERA_SYSEVENT_STATISTIC(CreateMsg("CaptureSession::AddInput"));
}
sptr streamOperator;
int32_t rc = localCameraDevice->GetStreamOperator(streamOperatorCallback_, streamOperator);
if (rc != CAMERA_OK) {
MEDIA_ERR_LOG("HCaptureSession::GetCameraDevice GetStreamOperator returned %{public}d", rc);
localCameraDevice->Close();
return rc;
}
return CAMERA_OK;
}
8. 創建Video的Surface通過Surface::CreateSurfaceAsConsumer創建Surface。
sptr Surface::string name, bool isShared)
{
sptr surf = new ConsumerSurface(name, isShared);
GSError ret = surf->Init();
if (ret != GSERROR_OK) {
BLOGE("Failure, Reason: consumer surf init failed");
return nullptr;
}
return surf;
}
9. 創建VideoOutput實例通過調用CameraManager的CreateVideoOutput來創建VideoOutput實例。
sptr CameraManager::CreateVideoOutput(VideoProfile &profile, sptr &surface)
{
CAMERA_SYNC_TRACE;
sptr streamRepeat = nullptr;
sptr result = nullptr;
int32_t retCode = CAMERA_OK;
camera_format_t metaFormat;
metaFormat = GetCameraMetadataFormat(profile.GetCameraFormat());
retCode = serviceProxy_->CreateVideoOutput(surface->GetProducer(), metaFormat,
profile.GetSize().width, profile.GetSize().height, streamRepeat);
if (retCode == CAMERA_OK) {
result = new(std::nothrow) VideoOutput(streamRepeat);
if (result == nullptr) {
MEDIA_ERR_LOG("Failed to new VideoOutput");
} else {
std::vector videoFrameRates = profile.GetFrameRates();
if (videoFrameRates.size() >= 2) { // vaild frame rate range length is 2
result->SetFrameRateRange(videoFrameRates[0], videoFrameRates[1]);
}
POWERMGR_SYSEVENT_CAMERA_CONFIG(VIDEO,
profile.GetSize().width,
profile.GetSize().height);
}
} else {
MEDIA_ERR_LOG("VideoOutpout: Failed to get stream repeat object from hcamera service! %{public}d", retCode);
}
return result;
}
該方法中通過IPC的調用最終調用到了HCameraService的CreateVideoOutput(surface->GetProducer(), format, streamRepeat)。
int32_t HCameraService::CreateVideoOutput(const sptr &producer, int32_t format,
int32_t width, int32_t height,
sptr &videoOutput)
{
CAMERA_SYNC_TRACE;
sptr streamRepeatVideo;
if ((producer == nullptr) || (width == 0) || (height == 0)) {
MEDIA_ERR_LOG("HCameraService::CreateVideoOutput producer is null");
return CAMERA_INVALID_ARG;
}
streamRepeatVideo = new(std::nothrow) HStreamRepeat(producer, format, width, height, true);
if (streamRepeatVideo == nullptr) {
MEDIA_ERR_LOG("HCameraService::CreateVideoOutput HStreamRepeat allocation failed");
return CAMERA_ALLOC_ERROR;
}
POWERMGR_SYSEVENT_CAMERA_CONFIG(VIDEO, producer->GetDefaultWidth(),
producer->GetDefaultHeight());
videoOutput = streamRepeatVideo;
return CAMERA_OK;
}
HCameraService的CreateVideoOutput方法中主要創建了HStreamRepeat,并且通過參數傳遞給前面的CameraManager使用,CameraManager通過傳遞的HStreamRepeat對象,進行封裝,創建出VideoOutput對象。
10. 添加videoOutput到采集會話中,并且提交采集會話該步驟類似添加CameraInput到采集會話的過程,可以參考前面的流程。
11. 開始錄制通過調用VideoOutput的Start進行錄制的操作。
int32_t VideoOutput::Start()
{
return static_cast(GetStream().GetRefPtr())->Start();
}
該方法中會調用到HStreamRepeat的Start方法。
int32_t HStreamRepeat::Start()
{
CAMERA_SYNC_TRACE;
if (streamOperator_ == nullptr) {
return CAMERA_INVALID_STATE;
}
if (curCaptureID_ != 0) {
MEDIA_ERR_LOG("HStreamRepeat::Start, Already started with captureID: %{public}d", curCaptureID_);
return CAMERA_INVALID_STATE;
}
int32_t ret = AllocateCaptureId(curCaptureID_);
if (ret != CAMERA_OK) {
MEDIA_ERR_LOG("HStreamRepeat::Start Failed to allocate a captureId");
return ret;
}
std::vector ability;
OHOS::ConvertMetadataToVec(cameraAbility_, ability);
CaptureInfo captureInfo;
captureInfo.streamIds_ = {streamId_};
captureInfo.captureSetting_ = ability;
captureInfo.enableShutterCallback_ = false;
MEDIA_INFO_LOG("HStreamRepeat::Start Starting with capture ID: %{public}d", curCaptureID_);
CamRetCode rc = (CamRetCode)(streamOperator_->Capture(curCaptureID_, captureInfo, true));
if (rc != HDI::NO_ERROR) {
ReleaseCaptureId(curCaptureID_);
curCaptureID_ = 0;
MEDIA_ERR_LOG("HStreamRepeat::Start Failed with error Code:%{public}d", rc);
ret = HdiToServiceError(rc);
}
return ret;
}
核心的代碼是streamOperator_->Capture,其中最后一個參數true,表示采集連續數據。
12. 錄制結束,保存錄制文件
六、總結
本文主要對OpenHarmony 3.2 Beta多媒體子系統的視頻錄制進行介紹,首先梳理了整體的錄制流程,然后對錄制過程中的主要步驟進行了詳細地分析。視頻錄制主要分為以下幾個步驟:(1) 獲取CameraManager實例。(2) 創建采集會話CaptureSession。(3) 創建CameraInput實例,并且將輸入設備添加到CaptureSession中。(4) 創建Video錄制需要的Surface。(5) 創建VideoOutput實例,并且將輸出添加到CaptureSession中。(6) 提交采集會話的配置。(7) 調用VideoOutput的Start方法,進行視頻的錄制。(8) 錄制結束,保存錄制的文件。 關于OpenHarmony 3.2 Beta多媒體系列開發,我之前還分享過《OpenHarmony 3.2 Beta源碼分析之MediaLibrary》《OpenHarmony 3.2 Beta多媒體系列——音視頻播放框架》《OpenHarmony 3.2 Beta多媒體系列——音視頻播放gstreamer》這幾篇文章,歡迎感興趣的開發者進行閱讀。THE END
推薦閱讀
點擊圖片即可閱讀
關注深開鴻
了解更多資訊
深開鴻公眾號
深開鴻視頻號
深圳開鴻數字產業發展有限公司(簡稱“深開鴻”)于2021年成立于中國深圳,以數字化、智慧化改變人類的生產和生活方式為愿景,專注于自主軟件根技術的研發與持續創新,致力于打造萬物智聯核心技術、定義萬物智聯標準、引領萬物智聯時代發展。
深開鴻基于OpenHarmony,創新打造互通互聯互享的KaihongOS數字底座,上承可視可管可控的超級設備管理平臺,靈活擴展,柔性組合,聚合成全場景超級設備解決方案,實現更大范圍的以軟件定義硬件,引領智慧基建、智慧康養、智慧能源、智慧交通、智慧制造、智慧政務、智慧金融、智慧教育等多個行業變革,賦能、賦智、賦值千行百業的數智化轉型。
從開源中來,到行業中去,深開鴻以構筑行業數字化生態、培養生態人才為己任,持續突破行業邊界,立志成為萬物智聯時代的“國之重器”。
以數字化、智慧化改變人類的生產和生活方式
點擊在看和點贊,與更多的美好相遇 ↓
原文標題:OpenHarmony 3.2 Beta多媒體系列——視頻錄制
文章出處:【微信公眾號:深開鴻】歡迎添加關注!文章轉載請注明出處。
-
深開鴻
+關注
關注
1文章
333瀏覽量
2209
原文標題:OpenHarmony 3.2 Beta多媒體系列——視頻錄制
文章出處:【微信號:gh_15d2f062a168,微信公眾號:深開鴻】歡迎添加關注!文章轉載請注明出處。
發布評論請先 登錄
相關推薦
評論