Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / signal / call / SignalCamera.kt

SignalCamera.kt225 lines · 8.5 KiBRaw
1package com.vayunmathur.communicate.data.signal.call
2
3import android.content.Context
4import android.media.projection.MediaProjection
5import com.vayunmathur.library.log.Log
6import org.signal.ringrtc.CameraControl
7import org.webrtc.Camera2Capturer
8import org.webrtc.Camera2Enumerator
9import org.webrtc.CameraVideoCapturer
10import org.webrtc.CapturerObserver
11import org.webrtc.EglBase
12import org.webrtc.ScreenCapturerAndroid
13import org.webrtc.SurfaceTextureHelper
14import org.webrtc.VideoCapturer
15import org.webrtc.VideoFrame
16
17/**
18 * Camera plumbing for calls.
19 *
20 * Present even on an audio call, and that is the point: Signal's offer always carries a video m-line, and
21 * WebRTC requires an answer's m-lines to match the offer's in number and order. With no capturer RingRTC
22 * builds no video transceiver, the answer comes back audio-only, and the peer connection rejects it with
23 * "The order of m-lines in answer doesn't match order in offer" - so every inbound call failed instantly.
24 *
25 * The capture device is therefore created for every call but only *started* when video is enabled.
26 */
27class SignalCamera(
28 private val appContext: Context,
29 private val eglBase: EglBase,
30) : CameraControl, CameraVideoCapturer.CameraSwitchHandler {
31
32 private val capturer: CameraVideoCapturer? = createCapturer()
33 private var capturing = false
34 private var frontFacing = true
35
36 /**
37 * RingRTC's sink for captured frames, kept so the capture *source* can be swapped between the camera and
38 * the screen without tearing down the call's video track.
39 */
40 private var observer: CapturerObserver? = null
41 private var surfaceHelper: SurfaceTextureHelper? = null
42 private var screenCapturer: VideoCapturer? = null
43
44 /** True whenever the device has a usable camera, matching what the offer expects to negotiate. */
45 override fun hasCapturer(): Boolean = capturer != null
46
47 override fun initCapturer(observer: CapturerObserver) {
48 this.observer = observer
49 val capturer = this.capturer ?: return
50 try {
51 val helper = SurfaceTextureHelper.create("SignalCameraThread", eglBase.eglBaseContext)
52 surfaceHelper = helper
53 capturer.initialize(helper, appContext, observer)
54 } catch (expected: Throwable) {
55 Log.status(TAG, "could not initialize the camera capturer", expected)
56 }
57 }
58
59 override fun setEnabled(enable: Boolean) {
60 // While sharing the screen the camera stays off; the screen capturer is the source.
61 if (screenCapturer != null) return
62 val capturer = this.capturer ?: return
63 try {
64 if (enable && !capturing) {
65 capturer.startCapture(CAPTURE_WIDTH, CAPTURE_HEIGHT, CAPTURE_FPS)
66 capturing = true
67 } else if (!enable && capturing) {
68 capturer.stopCapture()
69 capturing = false
70 }
71 } catch (expected: Throwable) {
72 Log.status(TAG, "could not ${if (enable) "start" else "stop"} video capture", expected)
73 }
74 }
75
76 /**
77 * Swap the capture source between the camera and the screen.
78 *
79 * Screen capture reuses RingRTC's existing [CapturerObserver], so the outgoing video track and the
80 * negotiated media stay exactly as they were — only the frames' origin changes. [permission] is the
81 * `MediaProjection` consent result and is required to start.
82 */
83 fun setScreenShare(enabled: Boolean, permission: android.content.Intent?): Boolean {
84 val observer = this.observer ?: run {
85 Log.status(TAG, "no capturer observer yet; cannot share the screen")
86 return false
87 }
88 return if (enabled) startScreenShare(observer, permission) else stopScreenShare()
89 }
90
91 private fun startScreenShare(observer: CapturerObserver, permission: android.content.Intent?): Boolean {
92 if (permission == null) return false
93 if (screenCapturer != null) return true
94 return try {
95 // Stop the camera first: one source at a time feeds the track.
96 if (capturing) {
97 capturer?.stopCapture()
98 capturing = false
99 }
100 val capturer = ScreenCapturerAndroid(
101 permission,
102 object : MediaProjection.Callback() {
103 override fun onStop() {
104 Log.status(TAG, "screen capture stopped by the system")
105 }
106 },
107 )
108 val helper = SurfaceTextureHelper.create("SignalScreenThread", eglBase.eglBaseContext)
109 capturer.initialize(helper, appContext, observer)
110 val metrics = appContext.resources.displayMetrics
111 capturer.startCapture(metrics.widthPixels, metrics.heightPixels, SCREEN_FPS)
112 screenCapturer = capturer
113 Log.status(TAG, "sharing the screen at ${metrics.widthPixels}x${metrics.heightPixels}")
114 true
115 } catch (expected: Throwable) {
116 Log.status(TAG, "could not start screen capture", expected)
117 screenCapturer = null
118 false
119 }
120 }
121
122 private fun stopScreenShare(): Boolean {
123 val capturer = screenCapturer ?: return true
124 return try {
125 capturer.stopCapture()
126 capturer.dispose()
127 screenCapturer = null
128 true
129 } catch (expected: Throwable) {
130 Log.status(TAG, "could not stop screen capture", expected)
131 screenCapturer = null
132 false
133 }
134 }
135
136 override fun flip() {
137 frontFacing = !frontFacing
138 try {
139 capturer?.switchCamera(this)
140 } catch (expected: Throwable) {
141 Log.status(TAG, "could not switch camera", expected)
142 }
143 }
144
145 override fun setOrientation(orientation: Int?) = Unit
146
147 fun dispose() {
148 stopScreenShare()
149 try {
150 if (capturing) capturer?.stopCapture()
151 capturer?.dispose()
152 surfaceHelper?.dispose()
153 } catch (_: Throwable) {
154 }
155 capturing = false
156 observer = null
157 surfaceHelper = null
158 }
159
160 override fun onCameraSwitchDone(isFrontCamera: Boolean) {
161 frontFacing = isFrontCamera
162 }
163
164 override fun onCameraSwitchError(error: String?) {
165 Log.status(TAG, "camera switch failed: $error")
166 }
167
168 private fun createCapturer(): CameraVideoCapturer? {
169 if (!Camera2Enumerator.isSupported(appContext)) {
170 Log.status(TAG, "Camera2 unsupported; calls will negotiate without video")
171 return null
172 }
173 val enumerator = Camera2Enumerator(appContext)
174 val names = try { enumerator.deviceNames } catch (expected: Throwable) {
175 Log.status(TAG, "could not enumerate cameras", expected)
176 return null
177 }
178 // Front first, since that is what a video call would use; any camera is enough to negotiate.
179 val preferred = names.firstOrNull { enumerator.isFrontFacing(it) } ?: names.firstOrNull()
180 if (preferred == null) {
181 Log.status(TAG, "no camera on this device; calls will negotiate without video")
182 return null
183 }
184 return try {
185 Camera2Capturer(appContext, preferred, null)
186 } catch (expected: Throwable) {
187 Log.status(TAG, "could not create a camera capturer for $preferred", expected)
188 null
189 }
190 }
191
192 private companion object {
193 const val TAG = "SignalCamera"
194 const val CAPTURE_WIDTH = 640
195 const val CAPTURE_HEIGHT = 480
196 const val CAPTURE_FPS = 30
197
198 /** Screen content is mostly static, so a lower rate keeps text legible at the same bitrate. */
199 const val SCREEN_FPS = 15
200 }
201}
202
203/**
204 * Forwards frames to a renderer when one is attached, and drops them otherwise.
205 *
206 * RingRTC needs a sink at `proceed()` time, but the UI that renders video does not exist until later (and
207 * not at all for an audio call), so the destination is swappable.
208 *
209 * Note it must **not** release frames: the producer (`SurfaceTextureHelper`) releases its own reference
210 * once `onFrame` returns, so releasing here drops the refcount below zero and crashes the decoder thread
211 * with "release() called on an object with refcount < 1". A sink that wants to keep a frame calls
212 * `retain()`; a sink that wants to drop one simply returns.
213 */
214class SwappableVideoSink : org.webrtc.VideoSink {
215 @Volatile
216 private var delegate: org.webrtc.VideoSink? = null
217
218 fun attach(sink: org.webrtc.VideoSink?) {
219 delegate = sink
220 }
221
222 override fun onFrame(frame: VideoFrame?) {
223 delegate?.onFrame(frame)
224 }
225}