场景描述
在直播场景中,会有礼物、魔法等表情临时出现在画面,需要获取视频画面帧进行纹理更新后再渲染
通过OpenGL渲染视频画面帧。
⦁ 在ArkTS侧调用createAVPlayer()创建AVPlayer实例,初始化进入idle状态。设置业务需要的监听事件,设置资源:设置属性url,AVPlayer进入initialized状态。
⦁ 设置窗口:获取并设置属性SurfaceID,该surfaceId是native侧nativeImage的surfaceID,调用play方法开始播放。
⦁ 添加XComponent组件,在native侧通过OH_NativeXComponent_RegisterCallback注册XComponent回调。
⦁ 在napi 接口init的时候在Xcomponent的OnSurfaceCreatedCB回调中初始化渲染线程,通过OH_NativeImage_Create创建nativeImage。
⦁ 通过OH_NativeImage_GetSurfaceId获取surfaceID并传递到arkts侧。
⦁ 通过OH_NativeImage_SetOnFrameAvailableListener设置帧可用回调,通过NativeVsync接收系统信号,控制渲染。
⦁ 通过OH_NativeImage_UpdateSurfaceImage获取最新帧更新相关联的OpenGL ES纹理,通过eglSwapBuffers将纹理渲染上屏。
核心代码
创建nativeImage,获取nativeImage的id,设置帧可用回调。
bool RenderThread::CreateNativeImage()
{
nativeImage_ = OH_NativeImage_Create(-1, GL_TEXTURE_EXTERNAL_OES);
if (nativeImage_ == nullptr) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "RenderThread", "OH_NativeImage_Create failed.");
return false;
}
int ret = 0;
{
std::lock_guard<std::mutex> lock(nativeImageSurfaceIdMutex_);
ret = OH_NativeImage_GetSurfaceId(nativeImage_, &nativeImageSurfaceId_);
}
if (ret != 0) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "RenderThread",
"OH_NativeImage_GetSurfaceId failed, ret is %{public}d.", ret);
return false;
}
nativeImageFrameAvailableListener_.context = this;
nativeImageFrameAvailableListener_.onFrameAvailable = &RenderThread::OnNativeImageFrameAvailable;
ret = OH_NativeImage_SetOnFrameAvailableListener(nativeImage_, nativeImageFrameAvailableListener_);
if (ret != 0) {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "RenderThread",
"OH_NativeImage_SetOnFrameAvailableListener failed, ret is %{public}d.", ret);
return fa