@mentra/glasses-media 3.5.0-dev.1492 → 3.5.0-dev.1493
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +22 -1
- package/android/src/main/java/com/mentra/glassesmedia/GlassesMediaRelayModule.kt +21 -4
- package/android/src/main/java/com/mentra/glassesmedia/passthrough/EncodedFrameBuffer.kt +82 -0
- package/android/src/main/java/com/mentra/glassesmedia/passthrough/PassthroughBridge.kt +96 -0
- package/android/src/main/java/com/mentra/glassesmedia/passthrough/PassthroughH264Decoder.kt +89 -0
- package/android/src/main/java/com/mentra/glassesmedia/passthrough/PassthroughH264Encoder.kt +136 -0
- package/android/src/main/java/com/mentra/glassesmedia/publisher/PhoneWhipPublisher.kt +69 -1
- package/android/src/main/java/com/mentra/glassesmedia/source/DecodedFrameTap.kt +49 -11
- package/android/src/main/java/com/mentra/glassesmedia/source/DecodedTrackRelay.kt +21 -0
- package/android/src/main/java/com/mentra/glassesmedia/source/FrameStallGate.kt +14 -0
- package/android/src/main/java/com/mentra/glassesmedia/source/IceDisconnectGrace.kt +53 -0
- package/android/src/main/java/com/mentra/glassesmedia/source/LocalWhipIngestSource.kt +34 -11
- package/android/src/main/java/com/mentra/glassesmedia/source/RelayFrameFanOut.kt +17 -0
- package/ios/CoreKit/Sources/GlassesMediaCore/DecodedFrameTapCore.swift +49 -8
- package/ios/DecodedFrameTap.swift +16 -6
- package/ios/GlassesMediaRelayModule.swift +6 -1
- package/ios/LocalWhipIngestSource.swift +2 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -43,7 +43,28 @@ Glasses MCU -- BLE LC3 --> phone PCM decoder ----------------------^
|
|
|
43
43
|
|
|
44
44
|
Only `ingest: "whip"` selects this route. Default SRT and explicit RTMP continue publishing directly from the glasses. WHIP never falls back to SRT/RTMP when Cloudflare omits its WHIP URL. The phone needs mobile data; the glasses need no internet Wi-Fi credentials. Livestreamer's Stream Here path skips its glasses Wi-Fi setup gate accordingly.
|
|
45
45
|
|
|
46
|
-
`MentraGlassesMediaRelay.prepare` joins the persistent hotspot, prepares both native peers, and returns a local WHIP URL for the BLE start command. Cloudflare credentials stay on the phone. Video queues hold at most one frame; decoded PCM is downmixed/resampled into a bounded 200ms, 48kHz mono queue. WebRTC re-encodes both tracks. No phone microphone is captured. Android uses the WebRTC library's external AudioRecord buffer mode; iOS uses a custom `RTCAudioDevice`.
|
|
46
|
+
`MentraGlassesMediaRelay.prepare` joins the persistent hotspot, prepares both native peers, and returns a local WHIP URL for the BLE start command. Cloudflare credentials stay on the phone. Video queues hold at most one frame; decoded PCM is downmixed/resampled into a bounded 200ms, 48kHz mono queue. Unless the caller asks for video passthrough (below), WebRTC re-encodes both tracks. No phone microphone is captured. Android uses the WebRTC library's external AudioRecord buffer mode; iOS uses a custom `RTCAudioDevice`.
|
|
47
|
+
|
|
48
|
+
### Video passthrough (Android)
|
|
49
|
+
|
|
50
|
+
`startStream({ingest: "whip", videoPassthrough: true})` has the phone forward the glasses' H.264 as it arrives instead of decoding it and encoding it again. The host advertises support as `hostFeatures.videoPassthrough`; a caller can pass the option without checking, and the iOS relay ignores it.
|
|
51
|
+
|
|
52
|
+
```text
|
|
53
|
+
Glasses -- H.264 over WHIP --> receiver (decoder that does not decode) --> publisher (encoder that does not encode) --> Cloudflare
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
libwebrtc only moves decoded pictures between a receiver and a sender, so `passthrough/` smuggles the encoded bytes inside a `VideoFrame.Buffer`. `PassthroughH264Decoder` wraps each access unit in an `EncodedFrameBuffer`, `DecodedTrackRelay` hands it to the publisher without touching pixels, and `PassthroughH264Encoder` returns the same bytes as the encoded result, with the key/delta marking and timestamp kept.
|
|
57
|
+
|
|
58
|
+
What that changes:
|
|
59
|
+
|
|
60
|
+
- **The phone does no video work.** No decode, no scale, no encode: less CPU and heat, and one fewer generation of picture quality.
|
|
61
|
+
- **A key frame can only come from the glasses.** The relay cannot make one. After a loss on the hotspot leg (`DecodeInfo.isMissingFrames`), a full publisher queue, or the uplink asking for one, `PassthroughBridge` waits for a key frame: the decoder returns `ERROR` for delta frames, which makes libwebrtc ask the glasses for a key frame and stop feeding deltas. Forwarding a delta after a gap would hand Cloudflare an undecodable stream it could never see the gap in, because the outgoing RTP is rebuilt here.
|
|
62
|
+
- **Frames queue in order and are not thinned.** The publisher holds up to 15 encoded frames. Past that it drops them all and waits for a key frame, instead of dropping single frames as the decoded path does.
|
|
63
|
+
- **The bitrate and picture size are the glasses'.** The encoder records the rate the uplink would allow (`uplinkTargetBps`, logged every 10 s) but cannot follow it, and degradation and scaling are turned off. A cellular uplink below the glasses' bitrate queues and delays instead of adapting. A BLE bitrate command would close that gap and does not exist yet.
|
|
64
|
+
- **No photo from the stream.** `StreamFrameGrab` needs pixels, so a photo taken during a passthrough stream is answered as it is for any stream the phone does not decode (`CAMERA_BUSY`).
|
|
65
|
+
- **Audio is unchanged.** BLE LC3 to PCM to Opus, as above.
|
|
66
|
+
|
|
67
|
+
The route is chosen when the relay is prepared and fixed for that stream. Teams and ACS calls, which need decoded frames, keep the real decoder. The log shows `video=passthrough` or `video=reencode` on the `ManagedRelay` audio-transport line, and `passthrough in=… out=… dropped=… keyRequests=…` every 10 s.
|
|
47
68
|
|
|
48
69
|
On Android hosts with microphone pinning and native PCM input, managed streams use the same BLE LC3 capture path as ACS SoftAP calls. An engine-owned `livestream` microphone session requests continuous glasses PCM; it leaves the configured gain in force and disables the call-specific loudness gate. The glasses receive `captureAudio: false`, avoiding SoC microphone capture and audio encoding, while the phone publishes video plus LC3-derived audio to Cloudflare. Attempt-scoped callbacks and native PCM gating reject late audio after stop/retry. Explicit `captureAudio: false` disables audio entirely. iOS and older hosts retain WHIP audio, matching ACS capability gating. ACS's measured 170ms audio delay is specific to its outgoing pipeline and is not applied to the Cloudflare publisher without calibration.
|
|
49
70
|
|
|
@@ -5,6 +5,8 @@ import com.mentra.bluetoothsdk.hotspot.ScopedNetworkError
|
|
|
5
5
|
import android.content.Intent
|
|
6
6
|
import android.os.Handler
|
|
7
7
|
import android.os.Looper
|
|
8
|
+
import android.net.wifi.WifiManager
|
|
9
|
+
import android.os.Build
|
|
8
10
|
import android.os.PowerManager
|
|
9
11
|
import android.provider.Settings
|
|
10
12
|
import android.util.Base64
|
|
@@ -12,6 +14,7 @@ import com.mentra.glassesmedia.grab.StreamFrameGrab
|
|
|
12
14
|
import com.mentra.glassesmedia.trace.MediaLog
|
|
13
15
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
14
16
|
import com.mentra.glassesmedia.network.*
|
|
17
|
+
import com.mentra.glassesmedia.passthrough.PassthroughBridge
|
|
15
18
|
import com.mentra.glassesmedia.publisher.PhoneWhipPublisher
|
|
16
19
|
import com.mentra.glassesmedia.publisher.RelayPcmInput
|
|
17
20
|
import com.mentra.glassesmedia.source.*
|
|
@@ -29,6 +32,8 @@ class GlassesMediaRelayModule : Module() {
|
|
|
29
32
|
private var source: LocalWhipIngestSource? = null
|
|
30
33
|
private var publisher: PhoneWhipPublisher? = null
|
|
31
34
|
private var wakeLock: PowerManager.WakeLock? = null
|
|
35
|
+
/** Keeps the Wi-Fi radio out of power save while it carries the glasses' video. */
|
|
36
|
+
private var wifiLock: WifiManager.WifiLock? = null
|
|
32
37
|
private val pcmInput = RelayPcmInput()
|
|
33
38
|
|
|
34
39
|
override fun definition() = ModuleDefinition {
|
|
@@ -65,14 +70,20 @@ class GlassesMediaRelayModule : Module() {
|
|
|
65
70
|
}
|
|
66
71
|
scoped.join(ssid, password, listener)
|
|
67
72
|
ScopedNetworkChangeDetector.registerRelayNetwork(scoped)
|
|
73
|
+
// Forward the glasses' encoded video untouched instead of decoding and encoding it again.
|
|
74
|
+
// Only when the caller asked, so an old caller and every other stream keep the re-encode.
|
|
75
|
+
val bridge = if (options["videoPassthrough"] == true) PassthroughBridge() else null
|
|
68
76
|
val outgoing = PhoneWhipPublisher(context, endpoint, options["captureAudio"] != false,
|
|
69
|
-
(options["bitrate"] as? Number)?.toInt() ?: 2_000_000) { state, reason -> emit(id, state, reason) }
|
|
77
|
+
(options["bitrate"] as? Number)?.toInt() ?: 2_000_000, bridge) { state, reason -> emit(id, state, reason) }
|
|
70
78
|
publisher = outgoing
|
|
71
79
|
val bleAudio = options["captureAudio"] != false && options["audioTransport"] == "ble-lc3"
|
|
72
80
|
if (bleAudio) pcmInput.attach(id, outgoing::onPcm)
|
|
73
|
-
Log.i("ManagedRelay", "Audio transport=${options["audioTransport"] ?: "whip"}
|
|
74
|
-
|
|
75
|
-
|
|
81
|
+
Log.i("ManagedRelay", "Audio transport=${options["audioTransport"] ?: "whip"} " +
|
|
82
|
+
"video=${if (bridge != null) "passthrough" else "reencode"} attempt=$id")
|
|
83
|
+
// Decoded frames go to the publisher, then to the phone's own preview of the stream.
|
|
84
|
+
val incoming = LocalWhipIngestSource(context, relayFrameFanOut(VideoFrameListener(outgoing::onVideoFrame)),
|
|
85
|
+
PcmListener(outgoing::onPcm), scopedNetwork = scoped, passthrough = bridge,
|
|
86
|
+
encodedListener = bridge?.let { EncodedFrameListener(outgoing::onEncodedFrame) })
|
|
76
87
|
source = incoming
|
|
77
88
|
incoming.setStateListener { state, reason ->
|
|
78
89
|
if (state == SourceState.FAILED) emit(id, "failed", "Glasses receiver: $reason")
|
|
@@ -85,6 +96,11 @@ class GlassesMediaRelayModule : Module() {
|
|
|
85
96
|
}
|
|
86
97
|
wakeLock = context.getSystemService(PowerManager::class.java)
|
|
87
98
|
.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Mentra:managed-relay").apply { acquire() }
|
|
99
|
+
wifiLock = context.getSystemService(WifiManager::class.java)?.createWifiLock(
|
|
100
|
+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) WifiManager.WIFI_MODE_FULL_LOW_LATENCY
|
|
101
|
+
else @Suppress("DEPRECATION") WifiManager.WIFI_MODE_FULL_HIGH_PERF,
|
|
102
|
+
"Mentra:managed-relay",
|
|
103
|
+
)?.apply { setReferenceCounted(false); acquire() }
|
|
88
104
|
outgoing.start()
|
|
89
105
|
promise.resolve(requireNotNull(incoming.ingestUrl))
|
|
90
106
|
} catch (error: Exception) {
|
|
@@ -152,6 +168,7 @@ class GlassesMediaRelayModule : Module() {
|
|
|
152
168
|
step { network?.let { it.release(); ScopedNetworkChangeDetector.releaseRelayNetwork(it) }; network = null }
|
|
153
169
|
step { internet?.close(); internet = null }
|
|
154
170
|
step { wakeLock?.let { if (it.isHeld) it.release() }; wakeLock = null }
|
|
171
|
+
step { wifiLock?.let { if (it.isHeld) it.release() }; wifiLock = null }
|
|
155
172
|
failure?.let { throw it }
|
|
156
173
|
activeId = null
|
|
157
174
|
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.passthrough
|
|
2
|
+
|
|
3
|
+
import java.nio.ByteBuffer
|
|
4
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
5
|
+
import org.webrtc.JavaI420Buffer
|
|
6
|
+
import org.webrtc.VideoFrame
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* One H.264 access unit, carried through libwebrtc's video frame types without being decoded.
|
|
10
|
+
*
|
|
11
|
+
* libwebrtc only moves decoded pictures between a receiver and a sender, so the managed relay's
|
|
12
|
+
* passthrough smuggles the encoded bytes in a [VideoFrame.Buffer]: [PassthroughH264Decoder] wraps each
|
|
13
|
+
* frame it is handed in one of these, and [PassthroughH264Encoder] unwraps it again.
|
|
14
|
+
*
|
|
15
|
+
* It has no pixels. Anything that asks for them is a bug in the wiring, not a case to serve, so
|
|
16
|
+
* [toI420] returns a black picture of the right size instead of throwing on a native thread, and
|
|
17
|
+
* [cropAndScale] cannot resize: it returns the same frame.
|
|
18
|
+
*/
|
|
19
|
+
class EncodedFrameBuffer(
|
|
20
|
+
/** Annex B bytes in a direct buffer at position 0. Never modified after construction. */
|
|
21
|
+
val data: ByteBuffer,
|
|
22
|
+
private val width: Int,
|
|
23
|
+
private val height: Int,
|
|
24
|
+
val isKeyFrame: Boolean,
|
|
25
|
+
/**
|
|
26
|
+
* A gap-free index the decoder stamps on every frame it produces, counted before libwebrtc can
|
|
27
|
+
* touch it. The sender's [PassthroughH264Encoder] compares consecutive values so it can see a
|
|
28
|
+
* frame that libwebrtc's own bitrate dropper discarded after the decoder and before encode, which
|
|
29
|
+
* no callback reports. [UNSET_SEQUENCE] on frames that do not track it, such as in tests.
|
|
30
|
+
*/
|
|
31
|
+
val sequence: Long = UNSET_SEQUENCE,
|
|
32
|
+
) : VideoFrame.Buffer {
|
|
33
|
+
private val references = AtomicInteger(1)
|
|
34
|
+
|
|
35
|
+
val sizeBytes: Int get() = data.limit()
|
|
36
|
+
|
|
37
|
+
override fun getWidth(): Int = width
|
|
38
|
+
|
|
39
|
+
override fun getHeight(): Int = height
|
|
40
|
+
|
|
41
|
+
override fun toI420(): VideoFrame.I420Buffer {
|
|
42
|
+
val black = JavaI420Buffer.allocate(width, height)
|
|
43
|
+
fill(black.dataY, 16)
|
|
44
|
+
fill(black.dataU, 128)
|
|
45
|
+
fill(black.dataV, 128)
|
|
46
|
+
return black
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
override fun retain() {
|
|
50
|
+
references.incrementAndGet()
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Nothing native is owned, so this only keeps the count honest for tests and logs. */
|
|
54
|
+
override fun release() {
|
|
55
|
+
references.decrementAndGet()
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** A passthrough frame has a fixed size: asking for another one gets the frame back, retained. */
|
|
59
|
+
override fun cropAndScale(
|
|
60
|
+
cropX: Int,
|
|
61
|
+
cropY: Int,
|
|
62
|
+
cropWidth: Int,
|
|
63
|
+
cropHeight: Int,
|
|
64
|
+
scaleWidth: Int,
|
|
65
|
+
scaleHeight: Int,
|
|
66
|
+
): VideoFrame.Buffer {
|
|
67
|
+
retain()
|
|
68
|
+
return this
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
internal fun referenceCount(): Int = references.get()
|
|
72
|
+
|
|
73
|
+
private fun fill(plane: ByteBuffer, value: Int) {
|
|
74
|
+
val target = plane.duplicate()
|
|
75
|
+
while (target.hasRemaining()) target.put(value.toByte())
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
companion object {
|
|
79
|
+
/** Marks a frame whose delivery order is not tracked, so the encoder skips gap detection. */
|
|
80
|
+
const val UNSET_SEQUENCE: Long = -1L
|
|
81
|
+
}
|
|
82
|
+
}
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.passthrough
|
|
2
|
+
|
|
3
|
+
import java.util.concurrent.atomic.AtomicLong
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* What the passthrough decoder and encoder have to agree on, which is one thing: whether the next
|
|
7
|
+
* frame forwarded must be a key frame.
|
|
8
|
+
*
|
|
9
|
+
* The relay does not re-encode, so it cannot make a key frame. It can only wait for the glasses to
|
|
10
|
+
* send one. Every delta frame sent downstream after a gap would be undecodable at Cloudflare, and
|
|
11
|
+
* because the outgoing RTP stream is rebuilt here, Cloudflare would never see the gap that made it
|
|
12
|
+
* so. Two events open the wait: a loss on the hotspot leg, and the uplink asking for a key frame
|
|
13
|
+
* because it lost packets of its own. The wait closes when a key frame goes through.
|
|
14
|
+
*
|
|
15
|
+
* Nothing here touches libwebrtc, so it is plain Kotlin and plain-JVM testable.
|
|
16
|
+
*/
|
|
17
|
+
class PassthroughBridge {
|
|
18
|
+
/** True until a key frame has gone through, so the first frame out is always one. */
|
|
19
|
+
@Volatile private var waitingForKeyFrame = true
|
|
20
|
+
|
|
21
|
+
private val sequence = AtomicLong()
|
|
22
|
+
private val framesIn = AtomicLong()
|
|
23
|
+
private val framesOut = AtomicLong()
|
|
24
|
+
private val keyFramesOut = AtomicLong()
|
|
25
|
+
private val framesDropped = AtomicLong()
|
|
26
|
+
private val keyFrameRequests = AtomicLong()
|
|
27
|
+
private val bytesOut = AtomicLong()
|
|
28
|
+
|
|
29
|
+
/** The bitrate the uplink would allow, as the encoder was last told. Informational: nothing adapts. */
|
|
30
|
+
@Volatile var uplinkTargetBps: Int = 0
|
|
31
|
+
|
|
32
|
+
/** Called when a wait opens, with why. Logged by the owner; never throws into libwebrtc. */
|
|
33
|
+
@Volatile var onKeyFrameWanted: ((String) -> Unit)? = null
|
|
34
|
+
|
|
35
|
+
fun isWaitingForKeyFrame(): Boolean = waitingForKeyFrame
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The next gap-free index for a forwarded frame. The decoder stamps it so the sender's encoder
|
|
39
|
+
* can tell when libwebrtc dropped a frame between the two, since only forwarded frames advance it
|
|
40
|
+
* and a jump at the encoder is a frame libwebrtc discarded.
|
|
41
|
+
*/
|
|
42
|
+
fun nextSequence(): Long = sequence.getAndIncrement()
|
|
43
|
+
|
|
44
|
+
/** Open the wait. Repeated requests while it is already open are not counted again. */
|
|
45
|
+
fun wantKeyFrame(reason: String) {
|
|
46
|
+
if (waitingForKeyFrame) return
|
|
47
|
+
waitingForKeyFrame = true
|
|
48
|
+
keyFrameRequests.incrementAndGet()
|
|
49
|
+
runCatching { onKeyFrameWanted?.invoke(reason) }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** A key frame is on its way out. */
|
|
53
|
+
fun keyFrameForwarded() {
|
|
54
|
+
waitingForKeyFrame = false
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
fun noteIn() {
|
|
58
|
+
framesIn.incrementAndGet()
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
fun noteDropped() {
|
|
62
|
+
framesDropped.incrementAndGet()
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
fun noteOut(bytes: Int, keyFrame: Boolean) {
|
|
66
|
+
framesOut.incrementAndGet()
|
|
67
|
+
bytesOut.addAndGet(bytes.toLong())
|
|
68
|
+
if (keyFrame) keyFramesOut.incrementAndGet()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
fun snapshot(): Snapshot = Snapshot(
|
|
72
|
+
framesIn = framesIn.get(),
|
|
73
|
+
framesOut = framesOut.get(),
|
|
74
|
+
keyFramesOut = keyFramesOut.get(),
|
|
75
|
+
framesDropped = framesDropped.get(),
|
|
76
|
+
keyFrameRequests = keyFrameRequests.get(),
|
|
77
|
+
bytesOut = bytesOut.get(),
|
|
78
|
+
uplinkTargetBps = uplinkTargetBps,
|
|
79
|
+
waitingForKeyFrame = waitingForKeyFrame,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
data class Snapshot(
|
|
83
|
+
val framesIn: Long,
|
|
84
|
+
val framesOut: Long,
|
|
85
|
+
val keyFramesOut: Long,
|
|
86
|
+
val framesDropped: Long,
|
|
87
|
+
val keyFrameRequests: Long,
|
|
88
|
+
val bytesOut: Long,
|
|
89
|
+
val uplinkTargetBps: Int,
|
|
90
|
+
val waitingForKeyFrame: Boolean,
|
|
91
|
+
) {
|
|
92
|
+
override fun toString(): String =
|
|
93
|
+
"in=$framesIn out=$framesOut key=$keyFramesOut dropped=$framesDropped keyRequests=$keyFrameRequests " +
|
|
94
|
+
"bytes=$bytesOut uplinkTargetBps=$uplinkTargetBps waitingForKey=$waitingForKeyFrame"
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.passthrough
|
|
2
|
+
|
|
3
|
+
import java.nio.ByteBuffer
|
|
4
|
+
import org.webrtc.EncodedImage
|
|
5
|
+
import org.webrtc.VideoCodecInfo
|
|
6
|
+
import org.webrtc.VideoCodecStatus
|
|
7
|
+
import org.webrtc.VideoDecoder
|
|
8
|
+
import org.webrtc.VideoDecoderFactory
|
|
9
|
+
import org.webrtc.VideoFrame
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* A decoder that does not decode. It copies the H.264 bytes libwebrtc hands it into an
|
|
13
|
+
* [EncodedFrameBuffer] and reports that as the decoded frame, so the encoded stream reaches
|
|
14
|
+
* [PassthroughH264Encoder] on the phone's uplink untouched.
|
|
15
|
+
*
|
|
16
|
+
* Two rules keep the forwarded stream decodable downstream:
|
|
17
|
+
*
|
|
18
|
+
* - A frame that follows a loss is dropped. [VideoDecoder.DecodeInfo.isMissingFrames] says the
|
|
19
|
+
* glasses' frames did not all arrive, and a delta frame after a gap references something that never
|
|
20
|
+
* made it. Returning [VideoCodecStatus.ERROR] is how libwebrtc is told to stop feeding delta
|
|
21
|
+
* frames and ask the glasses for a key frame, which is exactly the repair needed.
|
|
22
|
+
* - Frames wait for a key frame while the bridge says so, for the same reason.
|
|
23
|
+
*/
|
|
24
|
+
class PassthroughH264Decoder(private val bridge: PassthroughBridge) : VideoDecoder {
|
|
25
|
+
@Volatile private var callback: VideoDecoder.Callback? = null
|
|
26
|
+
|
|
27
|
+
override fun initDecode(settings: VideoDecoder.Settings, decodeCallback: VideoDecoder.Callback): VideoCodecStatus {
|
|
28
|
+
callback = decodeCallback
|
|
29
|
+
return VideoCodecStatus.OK
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
override fun release(): VideoCodecStatus {
|
|
33
|
+
callback = null
|
|
34
|
+
return VideoCodecStatus.OK
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// `info` is nullable on purpose: libwebrtc can hand this callback a null DecodeInfo over JNI, and a
|
|
38
|
+
// non-null Kotlin parameter turns that into an NPE inside the native thread, which aborts the app.
|
|
39
|
+
override fun decode(image: EncodedImage, info: VideoDecoder.DecodeInfo?): VideoCodecStatus {
|
|
40
|
+
val deliver = callback ?: return VideoCodecStatus.UNINITIALIZED
|
|
41
|
+
bridge.noteIn()
|
|
42
|
+
val key = image.frameType == EncodedImage.FrameType.VideoFrameKey
|
|
43
|
+
if (!key) {
|
|
44
|
+
if (info?.isMissingFrames == true) bridge.wantKeyFrame("frames lost on the glasses hotspot leg")
|
|
45
|
+
if (bridge.isWaitingForKeyFrame()) {
|
|
46
|
+
bridge.noteDropped()
|
|
47
|
+
return VideoCodecStatus.ERROR
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
val bytes = image.buffer.duplicate()
|
|
51
|
+
val copy = ByteBuffer.allocateDirect(bytes.remaining())
|
|
52
|
+
copy.put(bytes)
|
|
53
|
+
copy.flip()
|
|
54
|
+
// Opened by the key frame itself, here, rather than when it leaves the encoder: the delta frames
|
|
55
|
+
// right behind it arrive before the encoder thread has run, and must not be dropped for waiting.
|
|
56
|
+
if (key) bridge.keyFrameForwarded()
|
|
57
|
+
// Stamped here, before libwebrtc's sender-side bitrate dropper can discard it unannounced, so the
|
|
58
|
+
// encoder sees a gap in the order and can withhold the deltas that depend on what went missing.
|
|
59
|
+
val buffer = EncodedFrameBuffer(copy, image.encodedWidth, image.encodedHeight, key, bridge.nextSequence())
|
|
60
|
+
val frame = VideoFrame(buffer, image.rotation, image.captureTimeNs)
|
|
61
|
+
try {
|
|
62
|
+
deliver.onDecodedFrame(frame, null, null)
|
|
63
|
+
} finally {
|
|
64
|
+
buffer.release()
|
|
65
|
+
}
|
|
66
|
+
return VideoCodecStatus.OK
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
override fun getImplementationName(): String = IMPLEMENTATION_NAME
|
|
70
|
+
|
|
71
|
+
companion object {
|
|
72
|
+
const val IMPLEMENTATION_NAME = "MentraH264Passthrough"
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Decodes H.264 with [PassthroughH264Decoder] and everything else, which a glasses stream does not
|
|
78
|
+
* contain, with the platform factory it wraps. The supported list is the wrapped factory's, so what
|
|
79
|
+
* the receiver offers the glasses in the SDP is unchanged.
|
|
80
|
+
*/
|
|
81
|
+
class PassthroughDecoderFactory(
|
|
82
|
+
private val wrapped: VideoDecoderFactory,
|
|
83
|
+
private val bridge: PassthroughBridge,
|
|
84
|
+
) : VideoDecoderFactory {
|
|
85
|
+
override fun createDecoder(info: VideoCodecInfo): VideoDecoder? =
|
|
86
|
+
if (info.name.equals("H264", ignoreCase = true)) PassthroughH264Decoder(bridge) else wrapped.createDecoder(info)
|
|
87
|
+
|
|
88
|
+
override fun getSupportedCodecs(): Array<VideoCodecInfo> = wrapped.supportedCodecs
|
|
89
|
+
}
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.passthrough
|
|
2
|
+
|
|
3
|
+
import org.webrtc.EncodedImage
|
|
4
|
+
import org.webrtc.VideoCodecInfo
|
|
5
|
+
import org.webrtc.VideoCodecStatus
|
|
6
|
+
import org.webrtc.VideoEncoder
|
|
7
|
+
import org.webrtc.VideoEncoderFactory
|
|
8
|
+
import org.webrtc.VideoFrame
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* An encoder that does not encode: the frame it is given already carries the glasses' H.264, so it
|
|
12
|
+
* hands those bytes to libwebrtc as the encoded result, with the original key/delta marking.
|
|
13
|
+
*
|
|
14
|
+
* It cannot follow the bitrate libwebrtc asks for, because the glasses decide the rate. [setRates]
|
|
15
|
+
* records what the uplink would allow so a log can show a gap between the two, and nothing more.
|
|
16
|
+
*
|
|
17
|
+
* It cannot make a key frame either. When the uplink asks for one and this frame is a delta, the
|
|
18
|
+
* request goes to the bridge, which has the receiver ask the glasses for one.
|
|
19
|
+
*/
|
|
20
|
+
class PassthroughH264Encoder(private val bridge: PassthroughBridge) : VideoEncoder {
|
|
21
|
+
@Volatile private var callback: VideoEncoder.Callback? = null
|
|
22
|
+
private var sentKeyFrame = false
|
|
23
|
+
/** The last frame's sequence, to spot one libwebrtc dropped between the decoder and here. */
|
|
24
|
+
private var lastSequence = EncodedFrameBuffer.UNSET_SEQUENCE
|
|
25
|
+
/** Set when a drop or gap is detected; holds deltas back until a fresh key frame re-syncs. */
|
|
26
|
+
private var awaitingResync = false
|
|
27
|
+
|
|
28
|
+
override fun initEncode(settings: VideoEncoder.Settings, encodeCallback: VideoEncoder.Callback): VideoCodecStatus {
|
|
29
|
+
callback = encodeCallback
|
|
30
|
+
sentKeyFrame = false
|
|
31
|
+
lastSequence = EncodedFrameBuffer.UNSET_SEQUENCE
|
|
32
|
+
awaitingResync = false
|
|
33
|
+
return VideoCodecStatus.OK
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
override fun release(): VideoCodecStatus {
|
|
37
|
+
callback = null
|
|
38
|
+
return VideoCodecStatus.OK
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
override fun encode(frame: VideoFrame, info: VideoEncoder.EncodeInfo?): VideoCodecStatus {
|
|
42
|
+
val deliver = callback ?: return VideoCodecStatus.UNINITIALIZED
|
|
43
|
+
val source = frame.buffer as? EncodedFrameBuffer ?: return VideoCodecStatus.ERR_PARAMETER
|
|
44
|
+
val uplinkWantsKey = info?.frameTypes?.any { it == EncodedImage.FrameType.VideoFrameKey } ?: false
|
|
45
|
+
|
|
46
|
+
// libwebrtc's VideoStreamEncoder runs its own bitrate frame dropper before encode(), and
|
|
47
|
+
// DegradationPreference.DISABLED does not turn it off. When the uplink target falls below the
|
|
48
|
+
// glasses' fixed bitrate it can discard frames here without telling the bridge, so a gap in the
|
|
49
|
+
// decoder's gap-free sequence means a frame went missing on the way in. Every delta behind that
|
|
50
|
+
// gap references something downstream will never get, so treat it like a loss on the hotspot
|
|
51
|
+
// leg: ask the glasses for a key frame and hold the deltas until one arrives.
|
|
52
|
+
val previous = lastSequence
|
|
53
|
+
lastSequence = source.sequence
|
|
54
|
+
val gapBeforeThisFrame = !source.isKeyFrame &&
|
|
55
|
+
source.sequence != EncodedFrameBuffer.UNSET_SEQUENCE &&
|
|
56
|
+
previous != EncodedFrameBuffer.UNSET_SEQUENCE &&
|
|
57
|
+
source.sequence != previous + 1
|
|
58
|
+
|
|
59
|
+
if (source.isKeyFrame) {
|
|
60
|
+
// The key frame re-syncs the stream; whatever was lost before it no longer matters.
|
|
61
|
+
awaitingResync = false
|
|
62
|
+
} else {
|
|
63
|
+
// The first frame out must be a key frame, and one the uplink asked for cannot be made here.
|
|
64
|
+
if (!sentKeyFrame) {
|
|
65
|
+
bridge.noteDropped()
|
|
66
|
+
bridge.wantKeyFrame("no key frame has gone to the uplink yet")
|
|
67
|
+
return VideoCodecStatus.OK
|
|
68
|
+
}
|
|
69
|
+
if (gapBeforeThisFrame) {
|
|
70
|
+
awaitingResync = true
|
|
71
|
+
bridge.wantKeyFrame("frames dropped before the passthrough encoder")
|
|
72
|
+
}
|
|
73
|
+
if (uplinkWantsKey) bridge.wantKeyFrame("the uplink asked for a key frame")
|
|
74
|
+
// Hold deltas while recovering from a gap: forwarding one references frames the receiver
|
|
75
|
+
// never got, which corrupts or freezes the stream rebuilt at the uplink.
|
|
76
|
+
if (awaitingResync) {
|
|
77
|
+
bridge.noteDropped()
|
|
78
|
+
return VideoCodecStatus.OK
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
source.retain()
|
|
82
|
+
val image = EncodedImage.builder()
|
|
83
|
+
.setBuffer(source.data.duplicate(), Runnable { source.release() })
|
|
84
|
+
.setEncodedWidth(source.getWidth())
|
|
85
|
+
.setEncodedHeight(source.getHeight())
|
|
86
|
+
.setCaptureTimeNs(frame.timestampNs)
|
|
87
|
+
.setCaptureTimeMs(frame.timestampNs / 1_000_000)
|
|
88
|
+
.setFrameType(if (source.isKeyFrame) EncodedImage.FrameType.VideoFrameKey else EncodedImage.FrameType.VideoFrameDelta)
|
|
89
|
+
.setRotation(0)
|
|
90
|
+
.createEncodedImage()
|
|
91
|
+
if (source.isKeyFrame) sentKeyFrame = true
|
|
92
|
+
bridge.noteOut(source.sizeBytes, source.isKeyFrame)
|
|
93
|
+
deliver.onEncodedFrame(image, VideoEncoder.CodecSpecificInfoH264())
|
|
94
|
+
return VideoCodecStatus.OK
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
override fun setRateAllocation(allocation: VideoEncoder.BitrateAllocation, framerate: Int): VideoCodecStatus {
|
|
98
|
+
bridge.uplinkTargetBps = allocation.sum
|
|
99
|
+
return VideoCodecStatus.OK
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
override fun setRates(parameters: VideoEncoder.RateControlParameters): VideoCodecStatus {
|
|
103
|
+
bridge.uplinkTargetBps = parameters.bitrate.sum
|
|
104
|
+
return VideoCodecStatus.OK
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Never ask libwebrtc to shrink the picture: it cannot be resized here. */
|
|
108
|
+
override fun getScalingSettings(): VideoEncoder.ScalingSettings = VideoEncoder.ScalingSettings.OFF
|
|
109
|
+
|
|
110
|
+
override fun getImplementationName(): String = PassthroughH264Decoder.IMPLEMENTATION_NAME
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Offers H.264 only, in the two profiles libwebrtc's own factory offers, because the glasses'
|
|
115
|
+
* hardware encoder is H.264 and Cloudflare already accepts that on the Wi-Fi path. The profile in
|
|
116
|
+
* the offer is a label: what the decoder at the far end reads is the profile inside the stream.
|
|
117
|
+
*/
|
|
118
|
+
class PassthroughEncoderFactory(private val bridge: PassthroughBridge) : VideoEncoderFactory {
|
|
119
|
+
override fun createEncoder(info: VideoCodecInfo): VideoEncoder? =
|
|
120
|
+
if (info.name.equals("H264", ignoreCase = true)) PassthroughH264Encoder(bridge) else null
|
|
121
|
+
|
|
122
|
+
override fun getSupportedCodecs(): Array<VideoCodecInfo> = arrayOf(
|
|
123
|
+
h264(VideoCodecInfo.H264_CONSTRAINED_BASELINE_3_1),
|
|
124
|
+
h264(VideoCodecInfo.H264_CONSTRAINED_HIGH_3_1),
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
private fun h264(profileLevelId: String) = VideoCodecInfo(
|
|
128
|
+
"H264",
|
|
129
|
+
mapOf(
|
|
130
|
+
VideoCodecInfo.H264_FMTP_PROFILE_LEVEL_ID to profileLevelId,
|
|
131
|
+
VideoCodecInfo.H264_FMTP_LEVEL_ASYMMETRY_ALLOWED to "1",
|
|
132
|
+
VideoCodecInfo.H264_FMTP_PACKETIZATION_MODE to "1",
|
|
133
|
+
),
|
|
134
|
+
emptyList(),
|
|
135
|
+
)
|
|
136
|
+
}
|
|
@@ -6,11 +6,16 @@ import android.os.Handler
|
|
|
6
6
|
import android.os.HandlerThread
|
|
7
7
|
import com.mentra.glassesmedia.network.InternetHold
|
|
8
8
|
import com.mentra.bluetoothsdk.hotspot.SoftApTrace
|
|
9
|
+
import com.mentra.glassesmedia.trace.MediaLog
|
|
10
|
+
import com.mentra.glassesmedia.passthrough.EncodedFrameBuffer
|
|
11
|
+
import com.mentra.glassesmedia.passthrough.PassthroughBridge
|
|
12
|
+
import com.mentra.glassesmedia.passthrough.PassthroughEncoderFactory
|
|
9
13
|
import com.mentra.glassesmedia.source.I420Planes
|
|
10
14
|
import java.io.IOException
|
|
11
15
|
import java.util.concurrent.CountDownLatch
|
|
12
16
|
import java.util.concurrent.TimeUnit
|
|
13
17
|
import java.util.concurrent.atomic.AtomicBoolean
|
|
18
|
+
import java.util.concurrent.atomic.AtomicInteger
|
|
14
19
|
import okhttp3.Call
|
|
15
20
|
import okhttp3.Callback
|
|
16
21
|
import okhttp3.HttpUrl
|
|
@@ -27,17 +32,28 @@ import org.webrtc.audio.JavaAudioDeviceModule
|
|
|
27
32
|
* ASG WhipStreamingService's full-ICE offer/POST/answer/Location lifecycle, with decoded glasses
|
|
28
33
|
* tracks instead of camera/mic capture. One instance per attempt; the coordinator owns retries.
|
|
29
34
|
*/
|
|
35
|
+
private const val TAG = "ManagedRelay"
|
|
36
|
+
private const val MAX_PENDING_ENCODED_FRAMES = 15
|
|
37
|
+
private const val PASSTHROUGH_LOG_INTERVAL_MS = 10_000L
|
|
38
|
+
|
|
30
39
|
class PhoneWhipPublisher(
|
|
31
40
|
private val context: Context,
|
|
32
41
|
private val endpoint: String,
|
|
33
42
|
private val captureAudio: Boolean,
|
|
34
43
|
private val bitrate: Int,
|
|
44
|
+
/**
|
|
45
|
+
* Forward the glasses' encoded H.264 as it arrives instead of encoding decoded pictures. The
|
|
46
|
+
* receiver feeds [onEncodedFrame] rather than [onVideoFrame] on this route. Null encodes.
|
|
47
|
+
*/
|
|
48
|
+
private val passthrough: PassthroughBridge? = null,
|
|
35
49
|
private val onState: (String, String) -> Unit,
|
|
36
50
|
) {
|
|
37
51
|
private val thread = HandlerThread("Mentra WHIP uplink").apply { start() }
|
|
38
52
|
private val queue = Handler(thread.looper)
|
|
39
53
|
private val closed = AtomicBoolean(false)
|
|
40
54
|
private val frameBusy = AtomicBoolean(false)
|
|
55
|
+
/** Encoded frames waiting on [queue]. See [onEncodedFrame]. */
|
|
56
|
+
private val pendingEncoded = AtomicInteger(0)
|
|
41
57
|
private val closeDone = CountDownLatch(1)
|
|
42
58
|
@Volatile private var cleanupFailure: Throwable? = null
|
|
43
59
|
private val pcm = RelayPcmBuffer()
|
|
@@ -89,7 +105,10 @@ class PhoneWhipPublisher(
|
|
|
89
105
|
networkIgnoreMask = 2 or 8 or 16 // WIFI, VPN, LOOPBACK
|
|
90
106
|
})
|
|
91
107
|
.setAudioDeviceModule(adm)
|
|
92
|
-
.setVideoEncoderFactory(
|
|
108
|
+
.setVideoEncoderFactory(
|
|
109
|
+
if (passthrough != null) PassthroughEncoderFactory(passthrough)
|
|
110
|
+
else DefaultVideoEncoderFactory(egl!!.eglBaseContext, true, true),
|
|
111
|
+
)
|
|
93
112
|
.setVideoDecoderFactory(DefaultVideoDecoderFactory(egl!!.eglBaseContext))
|
|
94
113
|
.createPeerConnectionFactory()
|
|
95
114
|
val config = PeerConnection.RTCConfiguration(listOf(
|
|
@@ -104,6 +123,12 @@ class PhoneWhipPublisher(
|
|
|
104
123
|
if (h264.isNotEmpty()) transceiver.setCodecPreferences(h264)
|
|
105
124
|
val parameters = transceiver.sender.parameters
|
|
106
125
|
parameters.encodings.forEach { it.maxBitrateBps = bitrate.coerceIn(250_000, 12_000_000) }
|
|
126
|
+
// A forwarded stream cannot be resized to match the uplink: the picture is whatever size the
|
|
127
|
+
// glasses sent. DISABLED stops resolution/framerate adaptation; it does not stop libwebrtc's
|
|
128
|
+
// bitrate frame dropper, so when the uplink target dips below the glasses rate frames can
|
|
129
|
+
// still be dropped before the encoder. That is handled downstream: PassthroughH264Encoder
|
|
130
|
+
// spots the gap and withholds the dependent deltas until the glasses send a fresh key frame.
|
|
131
|
+
if (passthrough != null) parameters.degradationPreference = RtpParameters.DegradationPreference.DISABLED
|
|
107
132
|
transceiver.sender.parameters = parameters
|
|
108
133
|
if (captureAudio) {
|
|
109
134
|
val constraints = MediaConstraints().apply {
|
|
@@ -118,6 +143,16 @@ class PhoneWhipPublisher(
|
|
|
118
143
|
peer?.setLocalDescription(sdpObserver(onSet = { localSet = true; maybePost() }), offer)
|
|
119
144
|
}), MediaConstraints())
|
|
120
145
|
queue.postDelayed({ if (!connected && !closed.get()) fail("WHIP connection timed out") }, 35_000)
|
|
146
|
+
passthrough?.let { bridge ->
|
|
147
|
+
bridge.onKeyFrameWanted = { reason -> MediaLog.i(TAG, "passthrough waiting for a key frame: $reason") }
|
|
148
|
+
queue.postDelayed(object : Runnable {
|
|
149
|
+
override fun run() {
|
|
150
|
+
if (closed.get()) return
|
|
151
|
+
MediaLog.i(TAG, "passthrough ${bridge.snapshot()}")
|
|
152
|
+
queue.postDelayed(this, PASSTHROUGH_LOG_INTERVAL_MS)
|
|
153
|
+
}
|
|
154
|
+
}, PASSTHROUGH_LOG_INTERVAL_MS)
|
|
155
|
+
}
|
|
121
156
|
} catch (error: Exception) { fail(error.message ?: "WHIP startup failed") }
|
|
122
157
|
}
|
|
123
158
|
}
|
|
@@ -126,6 +161,39 @@ class PhoneWhipPublisher(
|
|
|
126
161
|
if (!closed.get() && captureAudio) pcm.push(bytes, rate, channels)
|
|
127
162
|
}
|
|
128
163
|
|
|
164
|
+
/**
|
|
165
|
+
* One encoded frame from the receiver, on the passthrough route. Unlike a decoded picture it
|
|
166
|
+
* cannot be dropped to catch up: every delta frame depends on the ones before it. So frames queue
|
|
167
|
+
* in order, and only when the queue overflows are they dropped, all of them, followed by a request
|
|
168
|
+
* for a key frame so the stream starts again from one.
|
|
169
|
+
*/
|
|
170
|
+
fun onEncodedFrame(frame: EncodedFrameBuffer, receivedAtNs: Long) {
|
|
171
|
+
val bridge = passthrough ?: return
|
|
172
|
+
if (closed.get()) return
|
|
173
|
+
if (pendingEncoded.incrementAndGet() > MAX_PENDING_ENCODED_FRAMES) {
|
|
174
|
+
pendingEncoded.decrementAndGet()
|
|
175
|
+
bridge.noteDropped()
|
|
176
|
+
bridge.wantKeyFrame("publisher queue full")
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
frame.retain()
|
|
180
|
+
val queued = queue.post {
|
|
181
|
+
try {
|
|
182
|
+
if (!closed.get()) {
|
|
183
|
+
lastTimestamp = maxOf(System.nanoTime(), lastTimestamp + 1)
|
|
184
|
+
videoSource?.capturerObserver?.onFrameCaptured(VideoFrame(frame, 0, lastTimestamp))
|
|
185
|
+
}
|
|
186
|
+
} finally {
|
|
187
|
+
frame.release()
|
|
188
|
+
pendingEncoded.decrementAndGet()
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (!queued) {
|
|
192
|
+
frame.release()
|
|
193
|
+
pendingEncoded.decrementAndGet()
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
129
197
|
fun onVideoFrame(planes: I420Planes) {
|
|
130
198
|
if (closed.get() || !planes.planesReadable() || !frameBusy.compareAndSet(false, true)) return
|
|
131
199
|
// Copy before returning to the receiver. At most one frame is waiting on the publisher queue.
|
|
@@ -3,7 +3,27 @@ package com.mentra.glassesmedia.source
|
|
|
3
3
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* Which pipeline decoded a frame offered to [DecodedFrameTap].
|
|
7
|
+
*
|
|
8
|
+
* Two decoders can run at once: a Teams call with Direct link off decodes the glasses stream for
|
|
9
|
+
* ACS while the managed relay decodes the same stream to republish it. A sink names the one it
|
|
10
|
+
* wants, so the picture on screen is always the one its lease was granted for.
|
|
11
|
+
*/
|
|
12
|
+
enum class DecodedFrameProducer(val wire: String) {
|
|
13
|
+
/** The decoder feeding the phone-native ACS meeting. */
|
|
14
|
+
ACS("acs"),
|
|
15
|
+
|
|
16
|
+
/** The decoder inside the managed glasses-to-Cloudflare relay. */
|
|
17
|
+
RELAY("relay");
|
|
18
|
+
|
|
19
|
+
companion object {
|
|
20
|
+
fun fromWire(value: String?): DecodedFrameProducer? = values().firstOrNull { it.wire == value }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* A second, optional consumer of decoded glasses video, sitting beside whoever decoded it: the ACS
|
|
26
|
+
* sender, or the managed relay's publisher.
|
|
7
27
|
*
|
|
8
28
|
* The call owns this pipeline; the preview is a guest. [offer] therefore never blocks, never lets
|
|
9
29
|
* a `Throwable` reach the decoder thread, and never does real work — a sink may only decide
|
|
@@ -15,9 +35,10 @@ import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
|
15
35
|
*
|
|
16
36
|
* ## Cost with nothing attached
|
|
17
37
|
*
|
|
18
|
-
* With no sink and telemetry off, [offer] is one volatile read and a return. Sink, error handler
|
|
19
|
-
* and the telemetry flag live in one immutable [State] so that read is the only thing the
|
|
20
|
-
* thread pays.
|
|
38
|
+
* With no sink and telemetry off, [offer] is one volatile read and a return. Sink, error handler,
|
|
39
|
+
* producer and the telemetry flag live in one immutable [State] so that read is the only thing the
|
|
40
|
+
* decoder thread pays. A frame from a producer the sink did not ask for costs that read plus one
|
|
41
|
+
* comparison.
|
|
21
42
|
*
|
|
22
43
|
* ## Why the metrics live here
|
|
23
44
|
*
|
|
@@ -58,6 +79,8 @@ object DecodedFrameTap {
|
|
|
58
79
|
val sink: VideoFrameListener?,
|
|
59
80
|
val onSinkError: ((Throwable) -> Unit)?,
|
|
60
81
|
val generation: Long,
|
|
82
|
+
/** The only producer whose frames reach the sink and the metrics. */
|
|
83
|
+
val producer: DecodedFrameProducer,
|
|
61
84
|
)
|
|
62
85
|
|
|
63
86
|
@Volatile
|
|
@@ -67,6 +90,9 @@ object DecodedFrameTap {
|
|
|
67
90
|
private var currentSink: VideoFrameListener? = null
|
|
68
91
|
private var currentOnSinkError: ((Throwable) -> Unit)? = null
|
|
69
92
|
|
|
93
|
+
/** With no sink, telemetry measures the ACS call, as it did before producers existed. */
|
|
94
|
+
private var currentProducer: DecodedFrameProducer = DecodedFrameProducer.ACS
|
|
95
|
+
|
|
70
96
|
@Volatile
|
|
71
97
|
var telemetryEnabled: Boolean = false
|
|
72
98
|
private set
|
|
@@ -84,16 +110,22 @@ object DecodedFrameTap {
|
|
|
84
110
|
private var lastOfferAtNs = 0L
|
|
85
111
|
|
|
86
112
|
/**
|
|
87
|
-
* Install [listener] and return the generation that owns it.
|
|
88
|
-
* thread after a throw has been caught and counted; it must
|
|
113
|
+
* Install [listener] for [producer]'s frames and return the generation that owns it.
|
|
114
|
+
* [onSinkError] runs on the decoder thread after a throw has been caught and counted; it must
|
|
115
|
+
* only schedule work elsewhere.
|
|
89
116
|
*/
|
|
90
117
|
@Synchronized
|
|
91
|
-
fun attach(
|
|
118
|
+
fun attach(
|
|
119
|
+
listener: VideoFrameListener,
|
|
120
|
+
producer: DecodedFrameProducer,
|
|
121
|
+
onSinkError: ((Throwable) -> Unit)? = null,
|
|
122
|
+
): Long {
|
|
92
123
|
generation += 1
|
|
93
124
|
currentSink = listener
|
|
94
125
|
currentOnSinkError = onSinkError
|
|
126
|
+
currentProducer = producer
|
|
95
127
|
publish()
|
|
96
|
-
Log.i(TAG, "tap attached generation=$generation")
|
|
128
|
+
Log.i(TAG, "tap attached generation=$generation producer=${producer.wire}")
|
|
97
129
|
return generation
|
|
98
130
|
}
|
|
99
131
|
|
|
@@ -103,6 +135,7 @@ object DecodedFrameTap {
|
|
|
103
135
|
if (generation != this.generation || currentSink == null) return false
|
|
104
136
|
currentSink = null
|
|
105
137
|
currentOnSinkError = null
|
|
138
|
+
currentProducer = DecodedFrameProducer.ACS
|
|
106
139
|
publish()
|
|
107
140
|
Log.i(TAG, "tap detached generation=$generation")
|
|
108
141
|
return true
|
|
@@ -126,7 +159,7 @@ object DecodedFrameTap {
|
|
|
126
159
|
state = if (currentSink == null && !telemetryEnabled) {
|
|
127
160
|
null
|
|
128
161
|
} else {
|
|
129
|
-
State(currentSink, currentOnSinkError, generation)
|
|
162
|
+
State(currentSink, currentOnSinkError, generation, currentProducer)
|
|
130
163
|
}
|
|
131
164
|
if (!wasCollecting && state != null) {
|
|
132
165
|
// The first gap after collection resumes would span the whole idle period.
|
|
@@ -169,13 +202,18 @@ object DecodedFrameTap {
|
|
|
169
202
|
}
|
|
170
203
|
|
|
171
204
|
/**
|
|
172
|
-
* Called on libwebrtc's decode thread
|
|
205
|
+
* Called on libwebrtc's decode thread by the pipeline that decoded [planes]: the ACS source just
|
|
206
|
+
* before the frame goes to ACS, the relay just after it goes to the publisher.
|
|
207
|
+
*
|
|
208
|
+
* A frame from any producer other than the attached one is dropped here, uncounted, so a second
|
|
209
|
+
* decoder running beside the wanted one can neither reach the sink nor skew its metrics.
|
|
173
210
|
*
|
|
174
211
|
* The catch is not defensive padding: the alternative is a preview bug throwing on the decoder
|
|
175
212
|
* thread and taking the wearer's call video with it.
|
|
176
213
|
*/
|
|
177
|
-
fun offer(planes: I420Planes) {
|
|
214
|
+
fun offer(planes: I420Planes, producer: DecodedFrameProducer) {
|
|
178
215
|
val current = state ?: return
|
|
216
|
+
if (current.producer != producer) return
|
|
179
217
|
val started = System.nanoTime()
|
|
180
218
|
val listener = current.sink
|
|
181
219
|
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.source
|
|
2
2
|
|
|
3
3
|
import com.mentra.glassesmedia.grab.StreamFrameGrab
|
|
4
|
+
import com.mentra.glassesmedia.passthrough.EncodedFrameBuffer
|
|
4
5
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
5
6
|
import com.mentra.glassesmedia.telemetry.PipelineStats
|
|
6
7
|
import com.mentra.glassesmedia.video.FrameGeometry
|
|
@@ -27,6 +28,13 @@ class DecodedTrackRelay(
|
|
|
27
28
|
private val videoListener: VideoFrameListener,
|
|
28
29
|
private val pcmListener: PcmListener,
|
|
29
30
|
private val stats: PipelineStats,
|
|
31
|
+
/**
|
|
32
|
+
* Set only on the managed relay's passthrough route, where the receiver's decoder does not decode
|
|
33
|
+
* and each frame is an [EncodedFrameBuffer]. Such a frame has no pixels, so it skips everything
|
|
34
|
+
* below that reads them and goes straight here. Before [onPromotableFrame] so that callers keep
|
|
35
|
+
* passing that one as the trailing lambda.
|
|
36
|
+
*/
|
|
37
|
+
private val encodedListener: EncodedFrameListener? = null,
|
|
30
38
|
/** Called on the first frame of each generation so the owner can promote itself to LIVE. */
|
|
31
39
|
private val onPromotableFrame: () -> Unit,
|
|
32
40
|
) {
|
|
@@ -60,6 +68,14 @@ class DecodedTrackRelay(
|
|
|
60
68
|
stats.age.record(sinkStart - frame.timestampNs)
|
|
61
69
|
}
|
|
62
70
|
val buffer = frame.buffer
|
|
71
|
+
if (buffer is EncodedFrameBuffer) {
|
|
72
|
+
// No pixels to scale, grab for a photo, or hand to ACS. A photo during a passthrough stream is
|
|
73
|
+
// answered as it is for any stream the phone does not decode.
|
|
74
|
+
stats.setSize(buffer.getWidth(), buffer.getHeight())
|
|
75
|
+
encodedListener?.onEncodedFrame(buffer, frame.timestampNs)
|
|
76
|
+
stats.sinkCb.record(System.nanoTime() - sinkStart)
|
|
77
|
+
return@VideoSink
|
|
78
|
+
}
|
|
63
79
|
stats.onFrameBuffer(classifyBuffer(buffer))
|
|
64
80
|
// Every phone-decoded glasses stream passes here, so this is where a photo taken during a
|
|
65
81
|
// stream gets its frame. One volatile write and one volatile read unless a photo is waiting.
|
|
@@ -149,3 +165,8 @@ class DecodedTrackRelay(
|
|
|
149
165
|
}
|
|
150
166
|
}
|
|
151
167
|
}
|
|
168
|
+
|
|
169
|
+
/** Receives each encoded frame on the passthrough route. Called on libwebrtc's decode thread. */
|
|
170
|
+
fun interface EncodedFrameListener {
|
|
171
|
+
fun onEncodedFrame(frame: EncodedFrameBuffer, timestampNs: Long)
|
|
172
|
+
}
|
|
@@ -59,3 +59,17 @@ internal class FrameStallGate(private val stallSamples: Int) {
|
|
|
59
59
|
return Verdict.Stalled(stalled)
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* How long a live ingest may go without decoded frames before it is failed.
|
|
65
|
+
*
|
|
66
|
+
* Measured on a Samsung phone with Mentra Live: the glasses' own publisher reported
|
|
67
|
+
* "Publisher disconnected", reconnected and was sending again about 6 s later, but 3 samples (6 s)
|
|
68
|
+
* failed the source one second before video resumed and tore the whole relay down for a 17 s
|
|
69
|
+
* rebuild. 8 samples (16 s) rides out one glasses-side reconnect and a keyframe, and is still
|
|
70
|
+
* shorter than the rebuild it avoids.
|
|
71
|
+
*/
|
|
72
|
+
internal object IngestStallPolicy {
|
|
73
|
+
const val SAMPLE_INTERVAL_MS = 2_000L
|
|
74
|
+
const val STALL_SAMPLES = 8
|
|
75
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.source
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Gives a transient ICE `DISCONNECTED` time to heal before it fails a source.
|
|
5
|
+
*
|
|
6
|
+
* libwebrtc reports DISCONNECTED as soon as consent checks stop being answered, and routinely
|
|
7
|
+
* returns to CONNECTED on its own once packets flow again. On the glasses hotspot that is exactly
|
|
8
|
+
* what a Wi-Fi hiccup or the glasses' own publisher reconnect looks like. Only `FAILED` is final.
|
|
9
|
+
* The phone-side publisher already waits [GRACE_MS] on DISCONNECTED; the receiver must not be
|
|
10
|
+
* stricter than the sender it is paired with.
|
|
11
|
+
*
|
|
12
|
+
* Free of `org.webrtc` and Android types so it is unit testable: the owner supplies the timer.
|
|
13
|
+
*/
|
|
14
|
+
internal class IceDisconnectGrace(
|
|
15
|
+
private val graceMs: Long = GRACE_MS,
|
|
16
|
+
private val schedule: (Runnable, Long) -> Unit,
|
|
17
|
+
private val cancelScheduled: (Runnable) -> Unit,
|
|
18
|
+
private val onExpired: () -> Unit,
|
|
19
|
+
) {
|
|
20
|
+
private var pending: Runnable? = null
|
|
21
|
+
|
|
22
|
+
val isWaiting: Boolean
|
|
23
|
+
@Synchronized get() = pending != null
|
|
24
|
+
|
|
25
|
+
/** DISCONNECTED: start the clock once; a second DISCONNECTED does not extend it. */
|
|
26
|
+
@Synchronized
|
|
27
|
+
fun onDisconnected() {
|
|
28
|
+
if (pending != null) return
|
|
29
|
+
val task = object : Runnable {
|
|
30
|
+
override fun run() {
|
|
31
|
+
synchronized(this@IceDisconnectGrace) {
|
|
32
|
+
if (pending !== this) return
|
|
33
|
+
pending = null
|
|
34
|
+
}
|
|
35
|
+
onExpired()
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
pending = task
|
|
39
|
+
schedule(task, graceMs)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** CONNECTED, COMPLETED, FAILED, or a torn-down peer: nothing left to wait for. */
|
|
43
|
+
@Synchronized
|
|
44
|
+
fun clear() {
|
|
45
|
+
pending?.let(cancelScheduled)
|
|
46
|
+
pending = null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
companion object {
|
|
50
|
+
/** Same allowance as `PhoneWhipPublisher`'s disconnect deadline. */
|
|
51
|
+
const val GRACE_MS = 10_000L
|
|
52
|
+
}
|
|
53
|
+
}
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.source
|
|
2
2
|
|
|
3
|
+
import com.mentra.glassesmedia.passthrough.PassthroughBridge
|
|
4
|
+
import com.mentra.glassesmedia.passthrough.PassthroughDecoderFactory
|
|
3
5
|
import android.content.Context
|
|
4
6
|
import android.media.AudioAttributes
|
|
5
7
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
@@ -64,16 +66,32 @@ class LocalWhipIngestSource(
|
|
|
64
66
|
* hotspot is visible without help.
|
|
65
67
|
*/
|
|
66
68
|
private val scopedNetwork: ScopedSoftApNetwork? = null,
|
|
69
|
+
/**
|
|
70
|
+
* The managed relay's passthrough route: when set, the glasses' H.264 is forwarded as received
|
|
71
|
+
* instead of being decoded, and [encodedListener] gets each frame. Null decodes, as ACS needs.
|
|
72
|
+
*/
|
|
73
|
+
private val passthrough: PassthroughBridge? = null,
|
|
74
|
+
encodedListener: EncodedFrameListener? = null,
|
|
67
75
|
) : GlassesMediaSource, WhipIngestServer.Negotiator {
|
|
68
76
|
|
|
69
|
-
private val relay = DecodedTrackRelay(videoListener, pcmListener, stats) { notePromotableFrame() }
|
|
77
|
+
private val relay = DecodedTrackRelay(videoListener, pcmListener, stats, encodedListener) { notePromotableFrame() }
|
|
70
78
|
private val firstFrame = FirstFrameGate()
|
|
71
|
-
private val frameStall = FrameStallGate(
|
|
79
|
+
private val frameStall = FrameStallGate(IngestStallPolicy.STALL_SAMPLES)
|
|
72
80
|
private val videoIds = TrackRegistry()
|
|
73
81
|
private val audioIds = TrackRegistry()
|
|
74
82
|
private val audioTracks = CopyOnWriteArrayList<AudioTrack>()
|
|
75
83
|
private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())
|
|
76
84
|
|
|
85
|
+
/** DISCONNECTED is usually a blip; only [IceDisconnectGrace.GRACE_MS] of it, or FAILED, is final. */
|
|
86
|
+
private val disconnectGrace = IceDisconnectGrace(
|
|
87
|
+
schedule = { task, delay -> mainHandler.postDelayed(task, delay) },
|
|
88
|
+
cancelScheduled = { task -> mainHandler.removeCallbacks(task) },
|
|
89
|
+
onExpired = {
|
|
90
|
+
Log.w(TAG, "SoftAP ingest ICE still disconnected after ${IceDisconnectGrace.GRACE_MS}ms")
|
|
91
|
+
transition(SourceState.FAILED, "ice_disconnected")
|
|
92
|
+
},
|
|
93
|
+
)
|
|
94
|
+
|
|
77
95
|
private var factory: PeerConnectionFactory? = null
|
|
78
96
|
private var egl: EglBase? = null
|
|
79
97
|
private var server: WhipIngestServer? = null
|
|
@@ -499,7 +517,11 @@ class LocalWhipIngestSource(
|
|
|
499
517
|
.setOptions(SoftApIcePolicy.factoryOptions())
|
|
500
518
|
.setAudioDeviceModule(adm)
|
|
501
519
|
.setVideoEncoderFactory(DefaultVideoEncoderFactory(shared, true, true))
|
|
502
|
-
.setVideoDecoderFactory(
|
|
520
|
+
.setVideoDecoderFactory(
|
|
521
|
+
DefaultVideoDecoderFactory(shared).let { platform ->
|
|
522
|
+
if (passthrough != null) PassthroughDecoderFactory(platform, passthrough) else platform
|
|
523
|
+
},
|
|
524
|
+
)
|
|
503
525
|
.createPeerConnectionFactory()
|
|
504
526
|
adm.release()
|
|
505
527
|
SoftApTrace.stage(
|
|
@@ -515,13 +537,16 @@ class LocalWhipIngestSource(
|
|
|
515
537
|
override fun onIceConnectionChange(state: PeerConnection.IceConnectionState) {
|
|
516
538
|
Log.i(TAG, "SoftAP ingest ICE $state")
|
|
517
539
|
if (gen != generation) return
|
|
518
|
-
if (state == PeerConnection.IceConnectionState.
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
540
|
+
if (state == PeerConnection.IceConnectionState.DISCONNECTED) {
|
|
541
|
+
// Consent freshness lapsed; libwebrtc often reconnects by itself. Wait like the publisher.
|
|
542
|
+
disconnectGrace.onDisconnected()
|
|
543
|
+
} else if (state == PeerConnection.IceConnectionState.FAILED) {
|
|
544
|
+
disconnectGrace.clear()
|
|
545
|
+
transition(SourceState.FAILED, "ice_failed")
|
|
522
546
|
} else if (state == PeerConnection.IceConnectionState.CONNECTED ||
|
|
523
547
|
state == PeerConnection.IceConnectionState.COMPLETED
|
|
524
548
|
) {
|
|
549
|
+
disconnectGrace.clear()
|
|
525
550
|
// Same bounce WHEP already handles: consent freshness can DISCONNECTED → CONNECTED
|
|
526
551
|
// without a new offer. Stay FAILED and the UI never leaves Reconnecting even after
|
|
527
552
|
// media is flowing again.
|
|
@@ -597,6 +622,7 @@ class LocalWhipIngestSource(
|
|
|
597
622
|
}
|
|
598
623
|
|
|
599
624
|
private fun disposePeer() {
|
|
625
|
+
disconnectGrace.clear()
|
|
600
626
|
val peer = pc
|
|
601
627
|
pc = null
|
|
602
628
|
try {
|
|
@@ -936,9 +962,6 @@ class LocalWhipIngestSource(
|
|
|
936
962
|
private const val SELECTED_PAIR_SAMPLE_GAP_MS = 1_200L
|
|
937
963
|
|
|
938
964
|
/** Matches the ACS-side `acs_bwe_sample` cadence so the two hops can be read side by side. */
|
|
939
|
-
private const val INGEST_SAMPLE_INTERVAL_MS =
|
|
940
|
-
|
|
941
|
-
/** Matches [FIRST_FRAME_TIMEOUT_MS] at the sample cadence: 6s of a frozen decoder. */
|
|
942
|
-
private const val INGEST_STALL_SAMPLES = 3
|
|
965
|
+
private const val INGEST_SAMPLE_INTERVAL_MS = IngestStallPolicy.SAMPLE_INTERVAL_MS
|
|
943
966
|
}
|
|
944
967
|
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.source
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The managed relay's per-frame fan-out: the publisher first, the phone's own preview second.
|
|
5
|
+
*
|
|
6
|
+
* [publisher] has returned before the preview is consulted, so nothing a preview does can delay,
|
|
7
|
+
* reorder or drop a frame on its way to Cloudflare. The preview's share is [DecodedFrameTap.offer],
|
|
8
|
+
* which contains anything its sink throws and returns without doing real work: the sink decides,
|
|
9
|
+
* retains the planes if it wants them past this callback, and packs on its own thread.
|
|
10
|
+
*
|
|
11
|
+
* Encoded passthrough frames never arrive here. They carry no pixels, so a passthrough stream has
|
|
12
|
+
* no local preview.
|
|
13
|
+
*/
|
|
14
|
+
fun relayFrameFanOut(publisher: VideoFrameListener): VideoFrameListener = VideoFrameListener { planes ->
|
|
15
|
+
publisher.onVideoFrame(planes)
|
|
16
|
+
DecodedFrameTap.offer(planes, DecodedFrameProducer.RELAY)
|
|
17
|
+
}
|
|
@@ -1,10 +1,23 @@
|
|
|
1
1
|
import Foundation
|
|
2
2
|
|
|
3
|
+
/// Which pipeline decoded a frame offered to the tap.
|
|
4
|
+
///
|
|
5
|
+
/// Two decoders can run at once: a Teams call with Direct link off decodes the glasses stream for
|
|
6
|
+
/// ACS while the managed relay decodes the same stream to republish it. A sink names the one it
|
|
7
|
+
/// wants, so the picture on screen is always the one its lease was granted for.
|
|
8
|
+
public enum DecodedFrameProducer: String, Sendable {
|
|
9
|
+
/// The decoder feeding the phone-native ACS meeting.
|
|
10
|
+
case acs
|
|
11
|
+
/// The decoder inside the managed glasses-to-Cloudflare relay.
|
|
12
|
+
case relay
|
|
13
|
+
}
|
|
14
|
+
|
|
3
15
|
/// The frame-agnostic half of `DecodedFrameTap`: sink ownership, failure isolation and metrics.
|
|
4
16
|
///
|
|
5
17
|
/// The call owns the decoder; a preview sink is a guest. `offer` never lets a thrown error reach
|
|
6
18
|
/// the decoder thread, and with no sink attached and telemetry off it costs one uncontended lock
|
|
7
19
|
/// around a single reference load (Swift has no portable atomics for iOS 15).
|
|
20
|
+
/// A frame from a producer the sink did not ask for costs that same load plus one comparison.
|
|
8
21
|
/// Swift runtime traps (force-unwraps, bounds failures) are process failures and cannot be caught
|
|
9
22
|
/// here; the preview prevents them by validating geometry before touching memory.
|
|
10
23
|
public final class DecodedFrameTapCore<Frame> {
|
|
@@ -38,9 +51,12 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
38
51
|
private final class State {
|
|
39
52
|
let sink: ((Frame) throws -> Void)?
|
|
40
53
|
let onSinkError: ((Error) -> Void)?
|
|
41
|
-
|
|
54
|
+
/// The only producer whose frames reach the sink and the metrics.
|
|
55
|
+
let producer: DecodedFrameProducer
|
|
56
|
+
init(sink: ((Frame) throws -> Void)?, onSinkError: ((Error) -> Void)?, producer: DecodedFrameProducer) {
|
|
42
57
|
self.sink = sink
|
|
43
58
|
self.onSinkError = onSinkError
|
|
59
|
+
self.producer = producer
|
|
44
60
|
}
|
|
45
61
|
}
|
|
46
62
|
|
|
@@ -50,6 +66,8 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
50
66
|
private var generation: UInt64 = 0
|
|
51
67
|
private var sink: ((Frame) throws -> Void)?
|
|
52
68
|
private var onSinkError: ((Error) -> Void)?
|
|
69
|
+
/// With no sink, telemetry measures the ACS call, as it did before producers existed.
|
|
70
|
+
private var producer: DecodedFrameProducer = .acs
|
|
53
71
|
public private(set) var telemetryEnabled = false
|
|
54
72
|
|
|
55
73
|
private let metricsLock = NSLock()
|
|
@@ -70,15 +88,21 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
70
88
|
self.clock = clock
|
|
71
89
|
}
|
|
72
90
|
|
|
73
|
-
/// Install the sink and return the generation that owns it.
|
|
74
|
-
/// thread after a thrown error has been caught and counted;
|
|
91
|
+
/// Install the sink for one producer's frames and return the generation that owns it.
|
|
92
|
+
/// `onSinkError` runs on the decoder thread after a thrown error has been caught and counted;
|
|
93
|
+
/// it must only schedule work.
|
|
75
94
|
@discardableResult
|
|
76
|
-
public func attach(
|
|
95
|
+
public func attach(
|
|
96
|
+
_ sink: @escaping (Frame) throws -> Void,
|
|
97
|
+
producer: DecodedFrameProducer,
|
|
98
|
+
onSinkError: ((Error) -> Void)? = nil
|
|
99
|
+
) -> UInt64 {
|
|
77
100
|
stateLock.lock()
|
|
78
101
|
defer { stateLock.unlock() }
|
|
79
102
|
generation &+= 1
|
|
80
103
|
self.sink = sink
|
|
81
104
|
self.onSinkError = onSinkError
|
|
105
|
+
self.producer = producer
|
|
82
106
|
publishLocked()
|
|
83
107
|
return generation
|
|
84
108
|
}
|
|
@@ -91,6 +115,7 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
91
115
|
guard generation == self.generation, sink != nil else { return false }
|
|
92
116
|
sink = nil
|
|
93
117
|
onSinkError = nil
|
|
118
|
+
producer = .acs
|
|
94
119
|
publishLocked()
|
|
95
120
|
return true
|
|
96
121
|
}
|
|
@@ -117,7 +142,9 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
117
142
|
|
|
118
143
|
private func publishLocked() {
|
|
119
144
|
let wasCollecting = state != nil
|
|
120
|
-
state = (sink == nil && !telemetryEnabled)
|
|
145
|
+
state = (sink == nil && !telemetryEnabled)
|
|
146
|
+
? nil
|
|
147
|
+
: State(sink: sink, onSinkError: onSinkError, producer: producer)
|
|
121
148
|
if !wasCollecting, state != nil {
|
|
122
149
|
// The first gap after collection resumes would span the whole idle period.
|
|
123
150
|
metricsLock.lock()
|
|
@@ -164,12 +191,26 @@ public final class DecodedFrameTapCore<Frame> {
|
|
|
164
191
|
metricsLock.unlock()
|
|
165
192
|
}
|
|
166
193
|
|
|
167
|
-
///
|
|
168
|
-
|
|
194
|
+
/// The managed relay's per-frame fan-out: the publisher first, the preview second.
|
|
195
|
+
///
|
|
196
|
+
/// `publish` has returned before the preview is consulted, so nothing a preview does can
|
|
197
|
+
/// delay, reorder or drop a frame on its way to the publisher. The preview's own share is
|
|
198
|
+
/// `offer`, which contains a throwing sink and returns without doing real work.
|
|
199
|
+
public func relay(_ frame: Frame, publish: (Frame) -> Void) {
|
|
200
|
+
publish(frame)
|
|
201
|
+
offer(frame, from: .relay)
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/// Called on the decoder thread by the pipeline that decoded `frame`: the ACS source just
|
|
205
|
+
/// before the frame goes to ACS, the relay just after it goes to the publisher.
|
|
206
|
+
///
|
|
207
|
+
/// A frame from any producer other than the attached one is dropped here, uncounted, so a
|
|
208
|
+
/// second decoder running beside the wanted one can neither reach the sink nor skew its metrics.
|
|
209
|
+
public func offer(_ frame: Frame, from producer: DecodedFrameProducer) {
|
|
169
210
|
stateLock.lock()
|
|
170
211
|
let current = state
|
|
171
212
|
stateLock.unlock()
|
|
172
|
-
guard let current else { return }
|
|
213
|
+
guard let current, current.producer == producer else { return }
|
|
173
214
|
|
|
174
215
|
let started = clock()
|
|
175
216
|
var failure: Error?
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import CoreVideo
|
|
2
2
|
import Foundation
|
|
3
3
|
|
|
4
|
-
/// A second, optional consumer of decoded glasses video, sitting beside
|
|
4
|
+
/// A second, optional consumer of decoded glasses video, sitting beside whoever decoded it: the
|
|
5
|
+
/// ACS sender, or the managed relay's publisher.
|
|
5
6
|
///
|
|
6
7
|
/// The call owns this pipeline; the preview is a guest. `offer` never blocks, never lets a thrown
|
|
7
8
|
/// error reach its caller, and never does real work — a sink may only decide whether it wants the
|
|
@@ -19,13 +20,14 @@ public final class DecodedFrameTap {
|
|
|
19
20
|
|
|
20
21
|
public init() {}
|
|
21
22
|
|
|
22
|
-
/// Install the preview sink and return the generation that owns it.
|
|
23
|
+
/// Install the preview sink for one producer's frames and return the generation that owns it.
|
|
23
24
|
@discardableResult
|
|
24
25
|
public func attach(
|
|
25
26
|
_ sink: @escaping (CVPixelBuffer) throws -> Void,
|
|
27
|
+
producer: DecodedFrameProducer,
|
|
26
28
|
onSinkError: ((Error) -> Void)? = nil
|
|
27
29
|
) -> UInt64 {
|
|
28
|
-
core.attach(sink, onSinkError: onSinkError)
|
|
30
|
+
core.attach(sink, producer: producer, onSinkError: onSinkError)
|
|
29
31
|
}
|
|
30
32
|
|
|
31
33
|
/// Remove the sink only if it is still the one this generation installed.
|
|
@@ -57,8 +59,16 @@ public final class DecodedFrameTap {
|
|
|
57
59
|
core.recordAcsSend()
|
|
58
60
|
}
|
|
59
61
|
|
|
60
|
-
///
|
|
61
|
-
|
|
62
|
-
|
|
62
|
+
/// The managed relay's per-frame fan-out: hand `buffer` to the publisher, then offer it to a
|
|
63
|
+
/// preview attached for relay frames. The buffer is only borrowed; a sink that wants it past
|
|
64
|
+
/// this call retains it.
|
|
65
|
+
public func relay(_ buffer: CVPixelBuffer, publish: (CVPixelBuffer) -> Void) {
|
|
66
|
+
core.relay(buffer, publish: publish)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/// Called on the decoder's thread by the pipeline that decoded `buffer`. Only frames from the
|
|
70
|
+
/// producer the sink attached for are delivered; the rest are dropped without being counted.
|
|
71
|
+
public func offer(_ buffer: CVPixelBuffer, from producer: DecodedFrameProducer) {
|
|
72
|
+
core.offer(buffer, from: producer)
|
|
63
73
|
}
|
|
64
74
|
}
|
|
@@ -180,7 +180,12 @@ private final class ManagedRelaySession {
|
|
|
180
180
|
self.publisher = publisher
|
|
181
181
|
let receiver = LocalWhipIngestSource()
|
|
182
182
|
self.receiver = receiver
|
|
183
|
-
|
|
183
|
+
// The publisher takes the frame first. The phone's own preview of the
|
|
184
|
+
// stream is a guest: it reads the pixels this relay already decoded, so
|
|
185
|
+
// showing the wearer their video downloads nothing.
|
|
186
|
+
receiver.onFrame = { [weak publisher] buffer in
|
|
187
|
+
DecodedFrameTap.shared.relay(buffer) { publisher?.onFrame($0) }
|
|
188
|
+
}
|
|
184
189
|
receiver.onPcm = { [weak publisher] in publisher?.onPcm($0, rate: $1, channels: $2) }
|
|
185
190
|
receiver.onStateChange = { state, reason in if state == .failed { onState("failed", "Glasses receiver: \(reason)") } }
|
|
186
191
|
receiver.setPcmDeliveryEnabled(captureAudio)
|
|
@@ -373,7 +373,8 @@ extension LocalWhipIngestSource: RTCPeerConnectionDelegate {
|
|
|
373
373
|
self.firstFrameSeen = false
|
|
374
374
|
self.transition(.connecting, "ice_disconnected")
|
|
375
375
|
let gen = self.generation
|
|
376
|
-
|
|
376
|
+
// Same 10 s allowance as the phone publisher: DISCONNECTED usually heals on its own.
|
|
377
|
+
self.queue.asyncAfter(deadline: .now() + 10) {
|
|
377
378
|
guard gen == self.generation, self.peer === peerConnection, !self.firstFrameSeen else { return }
|
|
378
379
|
self.fail(LocalMediaError("Local ICE disconnected"))
|
|
379
380
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mentra/glasses-media",
|
|
3
|
-
"version": "3.5.0-dev.
|
|
3
|
+
"version": "3.5.0-dev.1493",
|
|
4
4
|
"description": "Shared native glasses media receivers and local network transport",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Mentra Community",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
"access": "public"
|
|
17
17
|
},
|
|
18
18
|
"dependencies": {
|
|
19
|
-
"@mentra/bluetooth-sdk": "3.5.0-dev.
|
|
19
|
+
"@mentra/bluetooth-sdk": "3.5.0-dev.1493"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
22
|
"expo-modules-core": "~55.0.25"
|