package com.vayunmathur.communicate.data.signal.call import android.content.Context import android.media.projection.MediaProjection import com.vayunmathur.library.log.Log import org.signal.ringrtc.CameraControl import org.webrtc.Camera2Capturer import org.webrtc.Camera2Enumerator import org.webrtc.CameraVideoCapturer import org.webrtc.CapturerObserver import org.webrtc.EglBase import org.webrtc.ScreenCapturerAndroid import org.webrtc.SurfaceTextureHelper import org.webrtc.VideoCapturer import org.webrtc.VideoFrame /** * Camera plumbing for calls. * * Present even on an audio call, and that is the point: Signal's offer always carries a video m-line, and * WebRTC requires an answer's m-lines to match the offer's in number and order. With no capturer RingRTC * builds no video transceiver, the answer comes back audio-only, and the peer connection rejects it with * "The order of m-lines in answer doesn't match order in offer" - so every inbound call failed instantly. * * The capture device is therefore created for every call but only *started* when video is enabled. */ class SignalCamera( private val appContext: Context, private val eglBase: EglBase, ) : CameraControl, CameraVideoCapturer.CameraSwitchHandler { private val capturer: CameraVideoCapturer? = createCapturer() private var capturing = false private var frontFacing = true /** * RingRTC's sink for captured frames, kept so the capture *source* can be swapped between the camera and * the screen without tearing down the call's video track. */ private var observer: CapturerObserver? = null private var surfaceHelper: SurfaceTextureHelper? = null private var screenCapturer: VideoCapturer? = null /** True whenever the device has a usable camera, matching what the offer expects to negotiate. */ override fun hasCapturer(): Boolean = capturer != null override fun initCapturer(observer: CapturerObserver) { this.observer = observer val capturer = this.capturer ?: return try { val helper = SurfaceTextureHelper.create("SignalCameraThread", eglBase.eglBaseContext) surfaceHelper = helper capturer.initialize(helper, appContext, observer) } catch (expected: Throwable) { Log.status(TAG, "could not initialize the camera capturer", expected) } } override fun setEnabled(enable: Boolean) { // While sharing the screen the camera stays off; the screen capturer is the source. if (screenCapturer != null) return val capturer = this.capturer ?: return try { if (enable && !capturing) { capturer.startCapture(CAPTURE_WIDTH, CAPTURE_HEIGHT, CAPTURE_FPS) capturing = true } else if (!enable && capturing) { capturer.stopCapture() capturing = false } } catch (expected: Throwable) { Log.status(TAG, "could not ${if (enable) "start" else "stop"} video capture", expected) } } /** * Swap the capture source between the camera and the screen. * * Screen capture reuses RingRTC's existing [CapturerObserver], so the outgoing video track and the * negotiated media stay exactly as they were — only the frames' origin changes. [permission] is the * `MediaProjection` consent result and is required to start. */ fun setScreenShare(enabled: Boolean, permission: android.content.Intent?): Boolean { val observer = this.observer ?: run { Log.status(TAG, "no capturer observer yet; cannot share the screen") return false } return if (enabled) startScreenShare(observer, permission) else stopScreenShare() } private fun startScreenShare(observer: CapturerObserver, permission: android.content.Intent?): Boolean { if (permission == null) return false if (screenCapturer != null) return true return try { // Stop the camera first: one source at a time feeds the track. if (capturing) { capturer?.stopCapture() capturing = false } val capturer = ScreenCapturerAndroid( permission, object : MediaProjection.Callback() { override fun onStop() { Log.status(TAG, "screen capture stopped by the system") } }, ) val helper = SurfaceTextureHelper.create("SignalScreenThread", eglBase.eglBaseContext) capturer.initialize(helper, appContext, observer) val metrics = appContext.resources.displayMetrics capturer.startCapture(metrics.widthPixels, metrics.heightPixels, SCREEN_FPS) screenCapturer = capturer Log.status(TAG, "sharing the screen at ${metrics.widthPixels}x${metrics.heightPixels}") true } catch (expected: Throwable) { Log.status(TAG, "could not start screen capture", expected) screenCapturer = null false } } private fun stopScreenShare(): Boolean { val capturer = screenCapturer ?: return true return try { capturer.stopCapture() capturer.dispose() screenCapturer = null true } catch (expected: Throwable) { Log.status(TAG, "could not stop screen capture", expected) screenCapturer = null false } } override fun flip() { frontFacing = !frontFacing try { capturer?.switchCamera(this) } catch (expected: Throwable) { Log.status(TAG, "could not switch camera", expected) } } override fun setOrientation(orientation: Int?) = Unit fun dispose() { stopScreenShare() try { if (capturing) capturer?.stopCapture() capturer?.dispose() surfaceHelper?.dispose() } catch (_: Throwable) { } capturing = false observer = null surfaceHelper = null } override fun onCameraSwitchDone(isFrontCamera: Boolean) { frontFacing = isFrontCamera } override fun onCameraSwitchError(error: String?) { Log.status(TAG, "camera switch failed: $error") } private fun createCapturer(): CameraVideoCapturer? { if (!Camera2Enumerator.isSupported(appContext)) { Log.status(TAG, "Camera2 unsupported; calls will negotiate without video") return null } val enumerator = Camera2Enumerator(appContext) val names = try { enumerator.deviceNames } catch (expected: Throwable) { Log.status(TAG, "could not enumerate cameras", expected) return null } // Front first, since that is what a video call would use; any camera is enough to negotiate. val preferred = names.firstOrNull { enumerator.isFrontFacing(it) } ?: names.firstOrNull() if (preferred == null) { Log.status(TAG, "no camera on this device; calls will negotiate without video") return null } return try { Camera2Capturer(appContext, preferred, null) } catch (expected: Throwable) { Log.status(TAG, "could not create a camera capturer for $preferred", expected) null } } private companion object { const val TAG = "SignalCamera" const val CAPTURE_WIDTH = 640 const val CAPTURE_HEIGHT = 480 const val CAPTURE_FPS = 30 /** Screen content is mostly static, so a lower rate keeps text legible at the same bitrate. */ const val SCREEN_FPS = 15 } } /** * Forwards frames to a renderer when one is attached, and drops them otherwise. * * RingRTC needs a sink at `proceed()` time, but the UI that renders video does not exist until later (and * not at all for an audio call), so the destination is swappable. * * Note it must **not** release frames: the producer (`SurfaceTextureHelper`) releases its own reference * once `onFrame` returns, so releasing here drops the refcount below zero and crashes the decoder thread * with "release() called on an object with refcount < 1". A sink that wants to keep a frame calls * `retain()`; a sink that wants to drop one simply returns. */ class SwappableVideoSink : org.webrtc.VideoSink { @Volatile private var delegate: org.webrtc.VideoSink? = null fun attach(sink: org.webrtc.VideoSink?) { delegate = sink } override fun onFrame(frame: VideoFrame?) { delegate?.onFrame(frame) } }