Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / call / WebRtcInit.kt
WebRtcInit.kt48 lines · 1.9 KiBRaw
| 1 | package com.vayunmathur.communicate.data.call |
| 2 | |
| 3 | import android.content.Context |
| 4 | import com.vayunmathur.library.log.Log |
| 5 | import org.webrtc.NativeLibraryLoader |
| 6 | import org.webrtc.PeerConnectionFactory |
| 7 | import java.util.concurrent.atomic.AtomicBoolean |
| 8 | |
| 9 | /** |
| 10 | * One-time WebRTC initialization shared by every calling line. |
| 11 | * |
| 12 | * WebRTC here comes from RingRTC, which compiles its WebRTC **into** `libringrtc_rffi.so` rather than |
| 13 | * shipping a standalone `libjingle_peerconnection_so`. So the stock native loader has nothing to find: |
| 14 | * loading `ringrtc` pulls the WebRTC natives in as a side effect, and `PeerConnectionFactory` must then |
| 15 | * be initialized with a loader that does nothing. |
| 16 | * |
| 17 | * Getting this wrong compiles cleanly and fails at the first call with `UnsatisfiedLinkError`, which is |
| 18 | * why it lives in one place instead of at each call site. |
| 19 | */ |
| 20 | object WebRtcInit { |
| 21 | private const val TAG = "WebRtcInit" |
| 22 | |
| 23 | private val initialized = AtomicBoolean(false) |
| 24 | |
| 25 | /** Idempotent; safe to call before every call setup. */ |
| 26 | fun ensureInitialized(context: Context) { |
| 27 | if (!initialized.compareAndSet(false, true)) return |
| 28 | try { |
| 29 | // Brings in the WebRTC natives along with RingRTC's own. |
| 30 | System.loadLibrary("ringrtc") |
| 31 | PeerConnectionFactory.initialize( |
| 32 | PeerConnectionFactory.InitializationOptions.builder(context.applicationContext) |
| 33 | .setNativeLibraryLoader(AlreadyLoaded) |
| 34 | .setEnableInternalTracer(false) |
| 35 | .createInitializationOptions(), |
| 36 | ) |
| 37 | } catch (expected: Throwable) { |
| 38 | // Let the next attempt retry rather than leaving the flag set on a half-initialized stack. |
| 39 | initialized.set(false) |
| 40 | Log.error(TAG, "WebRTC initialization failed", expected) |
| 41 | throw expected |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | private object AlreadyLoaded : NativeLibraryLoader { |
| 46 | override fun load(name: String): Boolean = true |
| 47 | } |
| 48 | } |