【WebRTC 专栏】--创建相机预览

目录

技术答疑,成长进阶,可以加入我的知识星球:音视频领域专业问答的小圈子

用 WebRTC 创建相机预览,不到 50 行核心代码就可以轻松搞定了。

WebRTC 依赖版本

直接使用官方给的版本就好了,不需要再去额外编译。

1implementation 'org.webrtc:google-webrtc:1.0.30039'
CPP

后面都会使用该版本做测试的。

相机权限申请

WebRTC 虽说功能强大,代码简洁,但是并没有封装一个应用权限申请的接口,这需要自己去操作了。

相机预览

有个段子是把大象放进冰箱有多少步骤,共三步,打开冰箱,塞进大象,关上冰箱。

用 WebRTC 创建相机预览和上面的段子步骤一样,打开相机,设置接收,开启预览。

至于中间的繁琐步骤,比如相机创建的内部实现,预览绘制的内部实现都不用去关心了,调用好接口,设置好参数就行。

创建相机实例

在 WebRTC 中相机实例统一继承了 VideoCapturer 接口,不管是 Camera1 还是 Camera2 。

 1public interface VideoCapturer {
 2    void initialize(SurfaceTextureHelper var1, Context var2, CapturerObserver var3);
 3
 4    void startCapture(int var1, int var2, int var3);
 5
 6    void stopCapture() throws InterruptedException;
 7
 8    void changeCaptureFormat(int var1, int var2, int var3);
 9
10    void dispose();
11
12    boolean isScreencast();
13}
CPP

该接口也比较简单,只需要相机实例对外提供一些简单的预览能力就好。

创建相机实例的代码如下:

 1private fun createVideoCapture(): VideoCapturer? {
 2    val enumerator = Camera1Enumerator(false)
 3    val deviceNames = enumerator.deviceNames
 4
 5    for (deviceName in deviceNames) {
 6        if (enumerator.isFrontFacing(deviceName)) {
 7            val videoCapture = enumerator.createCapturer(deviceName, null)
 8            if (videoCapture != null) {
 9                return videoCapture
10            }
11        }
12    }
13    return null
14}
CPP

Camera1Enumerator 是用来枚举设备上有多少摄像头的,一般只有前置和后置两种,,也可以用 Camera2Enumerator 来获取 Camera2 的相机调用。

deviceNames 对应 getDeviceNames 方法,只不过用了 kotlin 变成缩写了,它表示设备上的摄像头集合,这个接口其实就已经屏蔽了 Camera1 和 Camera2 内部检索不同摄像头的实现。

满足前后置条件时,调用 createCapturer 来创建相机实例就好了。

相机预览接收

需要有分别对应的组件去接收相机输出的画面并且显示到屏幕上。

显示到屏幕上的控件既不是 SurfaceView 也不是 TextureView ,而是 WebRTC 自己封装的控件 SurfaceViewRenderer 。

它其实就是继承了 SurfaceView ,并且内部有个 SurfaceEglRenderer 变量,用来将外界传递的 VideoFrame 绘制到屏幕上。

1<org.webrtc.SurfaceViewRenderer android:id="@+id/localView"
2                            android:layout_width="match_parent"
3                            android:layout_height="match_parent"/>
4
5// SurfaceViewRenderer 的绘制方法
6public void onFrame(VideoFrame frame) {
7        this.eglRenderer.onFrame(frame);
8}
CPP

SurfaceEglRenderer 也是走的 OpenGL 渲染进行预览,在创建 OpenGL 环境可以决定是否要以 ShareContext 的形式创建。

1val eglBaseContext = EglBase.create().eglBaseContext
2localView.init(eglBaseContext, null)
CPP

接收相机预览流的组件就是 SurfaceTexture ,只不过 WebRTC 将它包装到了 SurfaceTextureHelper 变量中。

创建 SurfaceTextureHelper 的方法如下:

1val eglBaseContext = EglBase.create().eglBaseContext
2val surfaceTextureHelper = surfaceTextureHelper.create("CaptureThread", eglBaseContext)
CPP

SurfaceTextureHelper 内部会创建一个线程,并且也可以通过外部传递 EGLContext 以决定是否要走 ShareContext 方式的调用。

有了相机实例 VideoCapturer 和接收预览的组件 SurfaceTextureHelper ,就可以将他们关联起来:

1videoCapture?.initialize(surfaceTextureHelper, applicationContext, videoSource?.capturerObserver)
2videoCapture?.startCapture(480, 640, 30)
CPP

videoCapture 调用 initialize 方法实现两者的关联,同时 startCapture 方法决定相机采集的宽高和帧率。

开启相机预览

在开启相机预览时,就需要涉及到和 WebRTC 相关内容了。

WebRTC 本身是用来做即时通信的,它将音频和视频流都抽象成了一个个轨道 MediaStreamTrack ,有音频轨 AudioTrack 也有视频轨 VideoTrack。

而轨道上的内容来源就对应 MedisSource ,有音频源 AudioSource 和视频源 VideoSource 。

相机输出就是提供视频源的,需要将 VideoCapturer 和 VideoSource 关联起来。

在上面代码中 initialize 方法实际上就建立了关联。

1videoSource = videoCapture?.isScreencast?.let { factory.createVideoSource(it) }
2videoCapture?.initialize(surfaceTextureHelper, applicationContext, videoSource?.capturerObserver)
CPP

initialize 方法的最后一个参数就是一个回调,典型的观察者模式,VideoCapturer 相关的状态都会通过 capturerObserver 通知到 VideoSource ,从而实现关联。

创建 videoSource 的 factory ,对应的就是一条即时通信端对端的连接,而 videoTrack 和 audioTrack 就是这条连接上的内容。

创建 factory 的代码比较固定:

1val options = PeerConnectionFactory.InitializationOptions.builder(this).createInitializationOptions();
2PeerConnectionFactory.initialize(options)
3factory = PeerConnectionFactory.builder().createPeerConnectionFactory()
CPP

创建 VideoTrack 的代码如下,需要将视频源和视频轨道关联起来。

1videoTrack = factory.createVideoTrack("101",videoSource)
CPP

完成了所有的创建和关联之后,就可以开启预览了。需要将视频轨道内容显示到画面上,也就是上面的 SurfaceViewRenderer 控件上。

1videoTrack?.addSink(localView)
CPP

完整代码示例:

 1class CameraActivity : AppCompatActivity() {
 2
 3    private lateinit var factory: PeerConnectionFactory
 4    private var videoCapture:VideoCapturer? = null
 5    private var videoSource: VideoSource? = null
 6    private var videoTrack: VideoTrack? = null
 7    private lateinit var localView:SurfaceViewRenderer
 8
 9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11
12        setContentView(R.layout.activity_camera)
13        localView = findViewById(R.id.localView)
14        
15        val options = PeerConnectionFactory.InitializationOptions.builder(this).createInitializationOptions();
16        PeerConnectionFactory.initialize(options)
17        factory = PeerConnectionFactory.builder().createPeerConnectionFactory()
18
19        val eglBaseContext = EglBase.create().eglBaseContext
20        val surfaceTextureHelper = SurfaceTextureHelper.create("CaptureThread", eglBaseContext)
21
22        videoCapture = createVideoCapture()
23        videoSource = videoCapture?.isScreencast?.let { factory.createVideoSource(it) }
24
25        videoCapture?.initialize(surfaceTextureHelper, applicationContext, videoSource?.capturerObserver)
26        videoCapture?.startCapture(480, 640, 30)
27
28        localView.setMirror(true)
29        localView.init(eglBaseContext, null)
30
31        videoTrack = factory.createVideoTrack("101",videoSource)
32        videoTrack?.addSink(localView)
33    }
34
35    private fun createVideoCapture(): VideoCapturer? {
36        val enumerator = Camera1Enumerator(false)
37        val deviceNames = enumerator.deviceNames
38
39        for (deviceName in deviceNames) {
40            if (enumerator.isFrontFacing(deviceName)) {
41                val videoCapture = enumerator.createCapturer(deviceName, null)
42                if (videoCapture != null) {
43                    return videoCapture
44                }
45            }
46        }
47        return null
48    }
49}
CPP

不到 50 行代码就完成了相机预览,Github 仓库地址后续会给出。

这篇文章就先讲到这里,持续更新中~~

欢迎关注微信公众号:音视频开发进阶

Licensed under CC BY-NC-SA 4.0
粤ICP备20067247号
使用 Hugo 构建    主题 StackedJimmy 设计,Jacob 修改