LocalVideoTrack.kt
3.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package io.livekit.android.room.track
import android.content.Context
import com.github.ajalt.timberkt.Timber
import org.webrtc.*
import java.util.*
/**
* A representation of a local video track (generally input coming from camera or screen).
*
* [startCapture] should be called before use.
*/
class LocalVideoTrack(
private val capturer: VideoCapturer,
private val source: VideoSource,
name: String,
private val options: LocalVideoTrackOptions,
rtcTrack: org.webrtc.VideoTrack
) : VideoTrack(name, rtcTrack) {
fun startCapture() {
capturer.startCapture(options.captureParams.width, options.captureParams.height, options.captureParams.maxFps)
}
override fun stop() {
capturer.stopCapture()
super.stop()
}
companion object {
internal fun createTrack(
peerConnectionFactory: PeerConnectionFactory,
context: Context,
name: String,
options: LocalVideoTrackOptions,
rootEglBase: EglBase,
): LocalVideoTrack {
val source = peerConnectionFactory.createVideoSource(options.isScreencast)
val capturer = createVideoCapturer(context, options.position) ?: TODO()
capturer.initialize(
SurfaceTextureHelper.create("VideoCaptureThread", rootEglBase.eglBaseContext),
context,
source.capturerObserver
)
val track = peerConnectionFactory.createVideoTrack(UUID.randomUUID().toString(), source)
return LocalVideoTrack(
capturer = capturer,
source = source,
options = options,
name = name,
rtcTrack = track,
)
}
private fun createVideoCapturer(context: Context, position: CameraPosition): VideoCapturer? {
val videoCapturer: VideoCapturer? = if (Camera2Enumerator.isSupported(context)) {
createCameraCapturer(Camera2Enumerator(context), position)
} else {
createCameraCapturer(Camera1Enumerator(true), position)
}
if (videoCapturer == null) {
Timber.d { "Failed to open camera" }
return null
}
return videoCapturer
}
private fun createCameraCapturer(enumerator: CameraEnumerator, position: CameraPosition): VideoCapturer? {
val deviceNames = enumerator.deviceNames
for (deviceName in deviceNames) {
if (enumerator.isFrontFacing(deviceName) && position == CameraPosition.FRONT) {
Timber.v { "Creating front facing camera capturer." }
val videoCapturer = enumerator.createCapturer(deviceName, null)
if (videoCapturer != null) {
return videoCapturer
}
} else if (enumerator.isBackFacing(deviceName) && position == CameraPosition.BACK) {
Timber.v { "Creating back facing camera capturer." }
val videoCapturer = enumerator.createCapturer(deviceName, null)
if (videoCapturer != null) {
return videoCapturer
}
}
}
return null
}
}
}