@mentra/glasses-media 3.5.0-dev.1367 → 3.5.0-dev.1369
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 +23 -0
- package/android/src/main/java/com/mentra/glassesmedia/GlassesMediaRelayModule.kt +24 -0
- package/android/src/main/java/com/mentra/glassesmedia/grab/FrameGrabGate.kt +70 -0
- package/android/src/main/java/com/mentra/glassesmedia/grab/Nv21.kt +55 -0
- package/android/src/main/java/com/mentra/glassesmedia/grab/StreamFrameGrab.kt +139 -0
- package/android/src/main/java/com/mentra/glassesmedia/source/DecodedTrackRelay.kt +4 -0
- package/ios/GlassesMedia.podspec +1 -1
- package/ios/GlassesMediaRelayModule.swift +24 -0
- package/ios/LocalWhipIngestSource.swift +2 -0
- package/ios/StreamFrameGrab.swift +131 -0
- package/ios/WhepVideoSource.swift +2 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,6 +57,29 @@ An attempt-specific ID isolates late callbacks and glasses status. Reconnect tea
|
|
|
57
57
|
|
|
58
58
|
Device qualification for this outgoing pipeline must include Android and iPhone: audio/video playback on the provisioned WHEP URL, mute/video-only capture, last-subscriber stop, cancellation at each setup step, cellular/hotspot/BLE loss and recovery, repeated starts, screen-off/background operation and a sustained thermal/audio-sync run. Unit tests and platform compilation cover lifecycle/format contracts; they do not establish those hardware results.
|
|
59
59
|
|
|
60
|
+
## Photos from a stream
|
|
61
|
+
|
|
62
|
+
The glasses camera cannot take a photo while it streams. `StreamFrameGrab` (Android `grab/`,
|
|
63
|
+
iOS `StreamFrameGrab.swift`) turns the next decoded frame of any stream this library receives
|
|
64
|
+
into a JPEG, so a miniapp's `takePhoto()` keeps working during an ACS call or a managed WebRTC
|
|
65
|
+
relay without pausing either.
|
|
66
|
+
|
|
67
|
+
- The tap is where every receiver hands over a decoded frame: `DecodedTrackRelay` on Android,
|
|
68
|
+
before scaling, so the photo has the stream's resolution and not the size ACS negotiated down
|
|
69
|
+
to; `LocalWhipIngestSource` and `WhepVideoSource` on iOS.
|
|
70
|
+
- Nothing is stored between photos. A request waits for the next frame, retains it, and encodes
|
|
71
|
+
on its own thread. With no request waiting, a frame costs one volatile write and one volatile
|
|
72
|
+
read on Android, and one uncontended lock on iOS.
|
|
73
|
+
- `streamFrameAgeMs()` is how the host knows a stream is passing through the phone at all. With
|
|
74
|
+
no frame in the last second, the host sends the ordinary photo command, and glasses that are
|
|
75
|
+
streaming some other way (SRT, RTMP) answer `CAMERA_BUSY`.
|
|
76
|
+
- Android applies the frame's rotation to the JPEG. iOS does not: its receivers drop rotation
|
|
77
|
+
before the frame reaches this library, as the relay's own publisher does.
|
|
78
|
+
|
|
79
|
+
The host side is `PhonePhotoCoordinator` and `StreamFrameSource` in `@mentra/engine`. A caller
|
|
80
|
+
that paused the stream to take a full-size photo (Mentra Call's photo pause) is given the camera,
|
|
81
|
+
not a frame.
|
|
82
|
+
|
|
60
83
|
### Incoming OTA server and outgoing media clients
|
|
61
84
|
|
|
62
85
|
Hotspot association verifies the glasses SSID and the Wi-Fi interface/address for
|
|
@@ -8,6 +8,7 @@ import android.os.Looper
|
|
|
8
8
|
import android.os.PowerManager
|
|
9
9
|
import android.provider.Settings
|
|
10
10
|
import android.util.Base64
|
|
11
|
+
import com.mentra.glassesmedia.grab.StreamFrameGrab
|
|
11
12
|
import com.mentra.glassesmedia.trace.MediaLog
|
|
12
13
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
13
14
|
import com.mentra.glassesmedia.network.*
|
|
@@ -98,6 +99,29 @@ class GlassesMediaRelayModule : Module() {
|
|
|
98
99
|
bytes != null && pcmInput.push(attemptId, bytes, sampleRate, channels)
|
|
99
100
|
}
|
|
100
101
|
|
|
102
|
+
// Milliseconds since this phone last decoded a glasses frame, or -1. Covers ACS calls too:
|
|
103
|
+
// they decode through the same receivers.
|
|
104
|
+
Function("streamFrameAgeMs") { -> StreamFrameGrab.frameAgeMs().toDouble() }
|
|
105
|
+
|
|
106
|
+
AsyncFunction("grabStreamFrame") { options: Map<String, Any?>, promise: Promise ->
|
|
107
|
+
val quality = ((options["quality"] as? Number)?.toInt() ?: 90).coerceIn(1, 100)
|
|
108
|
+
val timeoutMs = ((options["timeoutMs"] as? Number)?.toLong() ?: 1_500L).coerceIn(100L, 5_000L)
|
|
109
|
+
StreamFrameGrab.grab(quality, timeoutMs) { frame, reason ->
|
|
110
|
+
if (frame == null) {
|
|
111
|
+
promise.reject("STREAM_FRAME_UNAVAILABLE", reason ?: "unknown", null)
|
|
112
|
+
} else {
|
|
113
|
+
promise.resolve(
|
|
114
|
+
mapOf(
|
|
115
|
+
"base64" to Base64.encodeToString(frame.jpeg, Base64.NO_WRAP),
|
|
116
|
+
"width" to frame.width,
|
|
117
|
+
"height" to frame.height,
|
|
118
|
+
"bytes" to frame.jpeg.size,
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
101
125
|
AsyncFunction("stop") { attemptId: String, promise: Promise ->
|
|
102
126
|
worker.execute {
|
|
103
127
|
try {
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.grab
|
|
2
|
+
|
|
3
|
+
import java.util.concurrent.atomic.AtomicBoolean
|
|
4
|
+
import java.util.concurrent.atomic.AtomicReference
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The decoder-thread half of a stream frame grab: one waiting request, and when the last frame
|
|
8
|
+
* was decoded.
|
|
9
|
+
*
|
|
10
|
+
* A grab takes the next decoded frame, not a stored one. Keeping a copy of every frame would cost
|
|
11
|
+
* a full-frame copy fifteen times a second for a photo that is taken a few times a minute.
|
|
12
|
+
*
|
|
13
|
+
* With nothing waiting, a frame costs one volatile write ([noteFrame]) and one volatile read
|
|
14
|
+
* ([claim]). Frame-agnostic so the ordering rules can be tested without WebRTC.
|
|
15
|
+
*/
|
|
16
|
+
class FrameGrabGate<F>(private val clock: () -> Long) {
|
|
17
|
+
/** Settles once: a frame, or the reason there was none. Later calls do nothing. */
|
|
18
|
+
class Request<F>(private val onFrame: (F) -> Unit, private val onFail: (String) -> Unit) {
|
|
19
|
+
private val settled = AtomicBoolean(false)
|
|
20
|
+
|
|
21
|
+
/** False when the request had already settled, so the caller still owns [frame]. */
|
|
22
|
+
fun deliver(frame: F): Boolean {
|
|
23
|
+
if (!settled.compareAndSet(false, true)) return false
|
|
24
|
+
onFrame(frame)
|
|
25
|
+
return true
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
fun fail(reason: String) {
|
|
29
|
+
if (settled.compareAndSet(false, true)) onFail(reason)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@Volatile
|
|
34
|
+
private var lastFrameAt = NEVER
|
|
35
|
+
|
|
36
|
+
private val pending = AtomicReference<Request<F>?>(null)
|
|
37
|
+
|
|
38
|
+
/** Decoder thread, every frame. */
|
|
39
|
+
fun noteFrame() {
|
|
40
|
+
lastFrameAt = clock()
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Milliseconds since the last decoded frame, or -1 when there has never been one. */
|
|
44
|
+
fun frameAgeMs(): Long {
|
|
45
|
+
val at = lastFrameAt
|
|
46
|
+
return if (at == NEVER) -1 else (clock() - at).coerceAtLeast(0)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A frame was decoded within [maxAgeMs]: a stream is running through this phone. */
|
|
50
|
+
fun isLive(maxAgeMs: Long): Boolean {
|
|
51
|
+
val age = frameAgeMs()
|
|
52
|
+
return age in 0..maxAgeMs
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Wait for the next frame. False when another request is already waiting. */
|
|
56
|
+
fun arm(request: Request<F>): Boolean = pending.compareAndSet(null, request)
|
|
57
|
+
|
|
58
|
+
/** Decoder thread, every frame: the waiting request, removed, or null. */
|
|
59
|
+
fun claim(): Request<F>? {
|
|
60
|
+
if (pending.get() == null) return null
|
|
61
|
+
return pending.getAndSet(null)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Stop waiting. False when a frame already claimed [request]. */
|
|
65
|
+
fun expire(request: Request<F>): Boolean = pending.compareAndSet(request, null)
|
|
66
|
+
|
|
67
|
+
companion object {
|
|
68
|
+
private const val NEVER = Long.MIN_VALUE
|
|
69
|
+
}
|
|
70
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.grab
|
|
2
|
+
|
|
3
|
+
import java.nio.ByteBuffer
|
|
4
|
+
|
|
5
|
+
/** I420 planes to the NV21 layout `YuvImage` encodes: Y rows, then interleaved V,U rows. */
|
|
6
|
+
object Nv21 {
|
|
7
|
+
/**
|
|
8
|
+
* [width] and [height] must be even and positive, and no larger than the planes. Strides may be
|
|
9
|
+
* wider than the rows. The buffers' positions are not moved.
|
|
10
|
+
*/
|
|
11
|
+
fun fromI420(
|
|
12
|
+
y: ByteBuffer,
|
|
13
|
+
strideY: Int,
|
|
14
|
+
u: ByteBuffer,
|
|
15
|
+
strideU: Int,
|
|
16
|
+
v: ByteBuffer,
|
|
17
|
+
strideV: Int,
|
|
18
|
+
width: Int,
|
|
19
|
+
height: Int,
|
|
20
|
+
): ByteArray {
|
|
21
|
+
require(width > 0 && height > 0 && width % 2 == 0 && height % 2 == 0) { "bad size ${width}x$height" }
|
|
22
|
+
val chromaWidth = width / 2
|
|
23
|
+
val chromaHeight = height / 2
|
|
24
|
+
require(strideY >= width && strideU >= chromaWidth && strideV >= chromaWidth) { "stride narrower than row" }
|
|
25
|
+
val ySrc = y.duplicate()
|
|
26
|
+
val uSrc = u.duplicate()
|
|
27
|
+
val vSrc = v.duplicate()
|
|
28
|
+
val yBase = ySrc.position()
|
|
29
|
+
val uBase = uSrc.position()
|
|
30
|
+
val vBase = vSrc.position()
|
|
31
|
+
require(ySrc.remaining() >= strideY * (height - 1) + width) { "Y plane too small" }
|
|
32
|
+
require(uSrc.remaining() >= strideU * (chromaHeight - 1) + chromaWidth) { "U plane too small" }
|
|
33
|
+
require(vSrc.remaining() >= strideV * (chromaHeight - 1) + chromaWidth) { "V plane too small" }
|
|
34
|
+
|
|
35
|
+
val out = ByteArray(width * height * 3 / 2)
|
|
36
|
+
for (row in 0 until height) {
|
|
37
|
+
ySrc.position(yBase + row * strideY)
|
|
38
|
+
ySrc.get(out, row * width, width)
|
|
39
|
+
}
|
|
40
|
+
val uRow = ByteArray(chromaWidth)
|
|
41
|
+
val vRow = ByteArray(chromaWidth)
|
|
42
|
+
var offset = width * height
|
|
43
|
+
for (row in 0 until chromaHeight) {
|
|
44
|
+
uSrc.position(uBase + row * strideU)
|
|
45
|
+
uSrc.get(uRow, 0, chromaWidth)
|
|
46
|
+
vSrc.position(vBase + row * strideV)
|
|
47
|
+
vSrc.get(vRow, 0, chromaWidth)
|
|
48
|
+
for (column in 0 until chromaWidth) {
|
|
49
|
+
out[offset++] = vRow[column]
|
|
50
|
+
out[offset++] = uRow[column]
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return out
|
|
54
|
+
}
|
|
55
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
package com.mentra.glassesmedia.grab
|
|
2
|
+
|
|
3
|
+
import android.graphics.Bitmap
|
|
4
|
+
import android.graphics.BitmapFactory
|
|
5
|
+
import android.graphics.ImageFormat
|
|
6
|
+
import android.graphics.Matrix
|
|
7
|
+
import android.graphics.Rect
|
|
8
|
+
import android.graphics.YuvImage
|
|
9
|
+
import android.os.SystemClock
|
|
10
|
+
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
11
|
+
import java.io.ByteArrayOutputStream
|
|
12
|
+
import java.util.concurrent.RejectedExecutionException
|
|
13
|
+
import java.util.concurrent.ScheduledThreadPoolExecutor
|
|
14
|
+
import java.util.concurrent.TimeUnit
|
|
15
|
+
import org.webrtc.VideoFrame
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* A photo taken from the glasses stream this phone is already decoding.
|
|
19
|
+
*
|
|
20
|
+
* While the glasses stream, their camera cannot also take a photo. Every stream that passes
|
|
21
|
+
* through this phone (an ACS call on either transport, the managed WebRTC relay) is decoded here,
|
|
22
|
+
* so the next decoded frame is the photo: nothing is asked of the glasses and the stream does not
|
|
23
|
+
* pause. A stream the glasses publish straight to the internet (RTMP, SRT) never reaches
|
|
24
|
+
* [offer], [isLive] stays false, and the caller's ordinary photo request gets the glasses'
|
|
25
|
+
* CAMERA_BUSY.
|
|
26
|
+
*
|
|
27
|
+
* The stream owns the decoder thread; the grab is a guest. [offer] only retains the frame and
|
|
28
|
+
* hands it to a worker, and nothing it does can throw into the decoder.
|
|
29
|
+
*/
|
|
30
|
+
object StreamFrameGrab {
|
|
31
|
+
private const val TAG = "FRAME-GRAB"
|
|
32
|
+
|
|
33
|
+
/** A stream that has not decoded a frame for this long is not one a photo can come from. */
|
|
34
|
+
const val LIVE_WINDOW_MS = 1_000L
|
|
35
|
+
|
|
36
|
+
class Frame(val jpeg: ByteArray, val width: Int, val height: Int)
|
|
37
|
+
|
|
38
|
+
private class Captured(val i420: VideoFrame.I420Buffer, val rotation: Int)
|
|
39
|
+
|
|
40
|
+
private val gate = FrameGrabGate<Captured> { SystemClock.elapsedRealtime() }
|
|
41
|
+
|
|
42
|
+
private val worker = ScheduledThreadPoolExecutor(1) { task ->
|
|
43
|
+
Thread(task, "stream-frame-grab").apply { isDaemon = true }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
fun frameAgeMs(): Long = gate.frameAgeMs()
|
|
47
|
+
|
|
48
|
+
fun isLive(): Boolean = gate.isLive(LIVE_WINDOW_MS)
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Called on libwebrtc's decode thread for every decoded glasses frame, before any scaling, so a
|
|
52
|
+
* grab gets the stream's own resolution rather than the size ACS negotiated down to.
|
|
53
|
+
*/
|
|
54
|
+
fun offer(buffer: VideoFrame.Buffer, rotation: Int) {
|
|
55
|
+
gate.noteFrame()
|
|
56
|
+
val request = gate.claim() ?: return
|
|
57
|
+
try {
|
|
58
|
+
val i420 = buffer.toI420()
|
|
59
|
+
if (i420 == null) {
|
|
60
|
+
request.fail("frame_unreadable")
|
|
61
|
+
} else if (!request.deliver(Captured(i420, rotation))) {
|
|
62
|
+
i420.release()
|
|
63
|
+
}
|
|
64
|
+
} catch (error: Throwable) {
|
|
65
|
+
// Only toI420 can throw here: a delivered frame is handed over or released by the request.
|
|
66
|
+
runCatching { request.fail("frame_unreadable") }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Encode the next decoded frame as a JPEG. [onResult] is called exactly once, on the worker
|
|
72
|
+
* thread or the caller's, with the frame or the reason there is none: `not_live`, `busy`,
|
|
73
|
+
* `no_frame`, `frame_unreadable` or `encode_failed`.
|
|
74
|
+
*/
|
|
75
|
+
fun grab(quality: Int, timeoutMs: Long, onResult: (Frame?, String?) -> Unit) {
|
|
76
|
+
if (!isLive()) {
|
|
77
|
+
onResult(null, "not_live")
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
val request = FrameGrabGate.Request<Captured>(
|
|
81
|
+
onFrame = { captured ->
|
|
82
|
+
try {
|
|
83
|
+
worker.execute {
|
|
84
|
+
val frame = try {
|
|
85
|
+
encode(captured, quality)
|
|
86
|
+
} catch (error: Throwable) {
|
|
87
|
+
Log.w(TAG, "encode failed ${captured.i420.width}x${captured.i420.height}", error)
|
|
88
|
+
null
|
|
89
|
+
} finally {
|
|
90
|
+
captured.i420.release()
|
|
91
|
+
}
|
|
92
|
+
onResult(frame, if (frame == null) "encode_failed" else null)
|
|
93
|
+
}
|
|
94
|
+
} catch (error: RejectedExecutionException) {
|
|
95
|
+
captured.i420.release()
|
|
96
|
+
onResult(null, "encode_failed")
|
|
97
|
+
}
|
|
98
|
+
},
|
|
99
|
+
onFail = { reason -> onResult(null, reason) },
|
|
100
|
+
)
|
|
101
|
+
if (!gate.arm(request)) {
|
|
102
|
+
onResult(null, "busy")
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
worker.schedule({ if (gate.expire(request)) request.fail("no_frame") }, timeoutMs, TimeUnit.MILLISECONDS)
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private fun encode(captured: Captured, quality: Int): Frame {
|
|
109
|
+
val i420 = captured.i420
|
|
110
|
+
// YuvImage needs whole chroma samples. An odd edge loses one pixel.
|
|
111
|
+
val width = i420.width and 1.inv()
|
|
112
|
+
val height = i420.height and 1.inv()
|
|
113
|
+
val nv21 = Nv21.fromI420(
|
|
114
|
+
i420.dataY, i420.strideY, i420.dataU, i420.strideU, i420.dataV, i420.strideV, width, height,
|
|
115
|
+
)
|
|
116
|
+
val out = ByteArrayOutputStream(nv21.size / 6)
|
|
117
|
+
check(YuvImage(nv21, ImageFormat.NV21, width, height, null).compressToJpeg(Rect(0, 0, width, height), quality, out)) {
|
|
118
|
+
"JPEG encoder refused the frame"
|
|
119
|
+
}
|
|
120
|
+
val rotation = ((captured.rotation % 360) + 360) % 360
|
|
121
|
+
if (rotation == 0) return Frame(out.toByteArray(), width, height)
|
|
122
|
+
|
|
123
|
+
// The stream carries rotation as metadata beside unrotated pixels. A photo has to carry it in
|
|
124
|
+
// the pixels: nothing downstream of a JPEG upload reads that metadata.
|
|
125
|
+
val upright = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size())
|
|
126
|
+
?: error("could not decode the frame to rotate it")
|
|
127
|
+
val rotated = Bitmap.createBitmap(
|
|
128
|
+
upright, 0, 0, upright.width, upright.height, Matrix().apply { postRotate(rotation.toFloat()) }, true,
|
|
129
|
+
)
|
|
130
|
+
try {
|
|
131
|
+
val turned = ByteArrayOutputStream(out.size())
|
|
132
|
+
check(rotated.compress(Bitmap.CompressFormat.JPEG, quality, turned)) { "JPEG encoder refused the rotated frame" }
|
|
133
|
+
return Frame(turned.toByteArray(), rotated.width, rotated.height)
|
|
134
|
+
} finally {
|
|
135
|
+
if (rotated !== upright) rotated.recycle()
|
|
136
|
+
upright.recycle()
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
package com.mentra.glassesmedia.source
|
|
2
2
|
|
|
3
|
+
import com.mentra.glassesmedia.grab.StreamFrameGrab
|
|
3
4
|
import com.mentra.glassesmedia.trace.MediaLog as Log
|
|
4
5
|
import com.mentra.glassesmedia.telemetry.PipelineStats
|
|
5
6
|
import com.mentra.glassesmedia.video.FrameGeometry
|
|
@@ -60,6 +61,9 @@ class DecodedTrackRelay(
|
|
|
60
61
|
}
|
|
61
62
|
val buffer = frame.buffer
|
|
62
63
|
stats.onFrameBuffer(classifyBuffer(buffer))
|
|
64
|
+
// Every phone-decoded glasses stream passes here, so this is where a photo taken during a
|
|
65
|
+
// stream gets its frame. One volatile write and one volatile read unless a photo is waiting.
|
|
66
|
+
StreamFrameGrab.offer(buffer, frame.rotation)
|
|
63
67
|
val geometry = FrameGeometry.packSize(buffer.width, buffer.height, frame.rotation)
|
|
64
68
|
if (geometry.rotationNonZero) {
|
|
65
69
|
stats.onRotation()
|
package/ios/GlassesMedia.podspec
CHANGED
|
@@ -14,7 +14,7 @@ Pod::Spec.new do |s|
|
|
|
14
14
|
s.dependency 'ExpoModulesCore'
|
|
15
15
|
# Keep in sync with the iOS-only @livekit/react-native-webrtc podspec patch.
|
|
16
16
|
s.dependency 'WebRTC-SDK', '144.7559.15'
|
|
17
|
-
s.frameworks = 'AVFoundation', 'CoreMedia', 'CoreVideo', 'CoreLocation', 'Network', 'NetworkExtension'
|
|
17
|
+
s.frameworks = 'AVFoundation', 'CoreImage', 'CoreMedia', 'CoreVideo', 'CoreLocation', 'ImageIO', 'Network', 'NetworkExtension'
|
|
18
18
|
s.source_files = '*.{swift,h,m,mm}', 'CoreKit/Sources/GlassesMediaCore/*.swift'
|
|
19
19
|
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
|
|
20
20
|
end
|
|
@@ -89,6 +89,30 @@ public final class GlassesMediaRelayModule: Module {
|
|
|
89
89
|
}
|
|
90
90
|
}
|
|
91
91
|
|
|
92
|
+
// Milliseconds since this phone last decoded a glasses frame, or -1. Covers ACS calls
|
|
93
|
+
// too: they decode through the same receivers.
|
|
94
|
+
Function("streamFrameAgeMs") { () -> Double in
|
|
95
|
+
StreamFrameGrab.shared.frameAgeMs()
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
AsyncFunction("grabStreamFrame") { (options: [String: Any], promise: Promise) in
|
|
99
|
+
let quality = min(max((options["quality"] as? NSNumber)?.doubleValue ?? 90, 1), 100)
|
|
100
|
+
let timeoutMs = min(max((options["timeoutMs"] as? NSNumber)?.intValue ?? 1500, 100), 5000)
|
|
101
|
+
StreamFrameGrab.shared.grab(quality: quality / 100, timeoutMs: timeoutMs) { result in
|
|
102
|
+
switch result {
|
|
103
|
+
case let .success(frame):
|
|
104
|
+
promise.resolve([
|
|
105
|
+
"base64": frame.jpeg.base64EncodedString(),
|
|
106
|
+
"width": frame.width,
|
|
107
|
+
"height": frame.height,
|
|
108
|
+
"bytes": frame.jpeg.count,
|
|
109
|
+
])
|
|
110
|
+
case let .failure(error):
|
|
111
|
+
promise.reject("STREAM_FRAME_UNAVAILABLE", error.reason)
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
92
116
|
AsyncFunction("stop") { (id: String, promise: Promise) in
|
|
93
117
|
self.queue.async {
|
|
94
118
|
guard let session = self.session, session.id == id else { promise.resolve(nil); return }
|
|
@@ -334,6 +334,8 @@ public final class LocalWhipIngestSource: NSObject, DecodedGlassesMediaSource {
|
|
|
334
334
|
guard gen == generation, peer != nil, !stopping else { return }
|
|
335
335
|
firstFrameSeen = true
|
|
336
336
|
transition(.live, "first_frame")
|
|
337
|
+
// Where a photo taken during this stream gets its frame.
|
|
338
|
+
StreamFrameGrab.shared.offer(buffer)
|
|
337
339
|
onFrame?(buffer)
|
|
338
340
|
}
|
|
339
341
|
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import CoreImage
|
|
2
|
+
import CoreVideo
|
|
3
|
+
import Foundation
|
|
4
|
+
import ImageIO
|
|
5
|
+
|
|
6
|
+
/// A photo taken from the glasses stream this phone is already decoding.
|
|
7
|
+
///
|
|
8
|
+
/// While the glasses stream, their camera cannot also take a photo. Every stream that passes
|
|
9
|
+
/// through this phone (an ACS call on either transport, the managed WebRTC relay) is decoded
|
|
10
|
+
/// here, so the next decoded frame is the photo: nothing is asked of the glasses and the stream
|
|
11
|
+
/// does not pause. A stream the glasses publish straight to the internet (RTMP, SRT) never
|
|
12
|
+
/// reaches `offer`, `isLive` stays false, and the caller's ordinary photo request gets the
|
|
13
|
+
/// glasses' CAMERA_BUSY.
|
|
14
|
+
///
|
|
15
|
+
/// The stream owns the decoder; the grab is a guest. `offer` only retains the buffer and hands it
|
|
16
|
+
/// to a worker queue. With nothing waiting it costs one uncontended lock.
|
|
17
|
+
public final class StreamFrameGrab {
|
|
18
|
+
public static let shared = StreamFrameGrab()
|
|
19
|
+
|
|
20
|
+
/// A stream that has not decoded a frame for this long is not one a photo can come from.
|
|
21
|
+
public static let liveWindowMs: Double = 1000
|
|
22
|
+
|
|
23
|
+
public struct Frame {
|
|
24
|
+
public let jpeg: Data
|
|
25
|
+
public let width: Int
|
|
26
|
+
public let height: Int
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/// `not_live`, `busy`, `no_frame` or `encode_failed`.
|
|
30
|
+
public struct Unavailable: Error {
|
|
31
|
+
public let reason: String
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
private final class Request {
|
|
35
|
+
let onFrame: (CVPixelBuffer) -> Void
|
|
36
|
+
let onFail: (String) -> Void
|
|
37
|
+
init(onFrame: @escaping (CVPixelBuffer) -> Void, onFail: @escaping (String) -> Void) {
|
|
38
|
+
self.onFrame = onFrame
|
|
39
|
+
self.onFail = onFail
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
private let lock = NSLock()
|
|
44
|
+
private var lastFrameAt: UInt64?
|
|
45
|
+
private var pending: Request?
|
|
46
|
+
private let worker = DispatchQueue(label: "com.mentra.glassesmedia.stream-frame-grab", qos: .userInitiated)
|
|
47
|
+
private lazy var context = CIContext()
|
|
48
|
+
|
|
49
|
+
public init() {}
|
|
50
|
+
|
|
51
|
+
/// Milliseconds since the last decoded frame, or -1 when there has never been one.
|
|
52
|
+
public func frameAgeMs() -> Double {
|
|
53
|
+
lock.lock()
|
|
54
|
+
let at = lastFrameAt
|
|
55
|
+
lock.unlock()
|
|
56
|
+
guard let at else { return -1 }
|
|
57
|
+
let now = DispatchTime.now().uptimeNanoseconds
|
|
58
|
+
return now > at ? Double(now - at) / 1_000_000 : 0
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
public var isLive: Bool {
|
|
62
|
+
let age = frameAgeMs()
|
|
63
|
+
return age >= 0 && age <= Self.liveWindowMs
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/// Called for every decoded glasses frame, on the source's delivery thread.
|
|
67
|
+
public func offer(_ buffer: CVPixelBuffer) {
|
|
68
|
+
lock.lock()
|
|
69
|
+
lastFrameAt = DispatchTime.now().uptimeNanoseconds
|
|
70
|
+
let request = pending
|
|
71
|
+
pending = nil
|
|
72
|
+
lock.unlock()
|
|
73
|
+
// The closure retains the buffer, which keeps it out of the decoder's pool until encoded.
|
|
74
|
+
request?.onFrame(buffer)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/// Encode the next decoded frame as a JPEG. `completion` is called exactly once, on the
|
|
78
|
+
/// worker queue or the caller's.
|
|
79
|
+
public func grab(quality: Double, timeoutMs: Int, completion: @escaping (Result<Frame, Unavailable>) -> Void) {
|
|
80
|
+
guard isLive else {
|
|
81
|
+
completion(.failure(Unavailable(reason: "not_live")))
|
|
82
|
+
return
|
|
83
|
+
}
|
|
84
|
+
let request = Request(
|
|
85
|
+
onFrame: { [weak self] buffer in
|
|
86
|
+
guard let self else {
|
|
87
|
+
completion(.failure(Unavailable(reason: "no_frame")))
|
|
88
|
+
return
|
|
89
|
+
}
|
|
90
|
+
self.worker.async {
|
|
91
|
+
if let frame = self.encode(buffer, quality: quality) {
|
|
92
|
+
completion(.success(frame))
|
|
93
|
+
} else {
|
|
94
|
+
completion(.failure(Unavailable(reason: "encode_failed")))
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
onFail: { reason in completion(.failure(Unavailable(reason: reason))) }
|
|
99
|
+
)
|
|
100
|
+
lock.lock()
|
|
101
|
+
let busy = pending != nil
|
|
102
|
+
if !busy { pending = request }
|
|
103
|
+
lock.unlock()
|
|
104
|
+
if busy {
|
|
105
|
+
completion(.failure(Unavailable(reason: "busy")))
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
worker.asyncAfter(deadline: .now() + .milliseconds(timeoutMs)) { [weak self] in
|
|
109
|
+
guard let self else { return }
|
|
110
|
+
// Still waiting means no frame claimed it. A claimed request is no longer `pending`,
|
|
111
|
+
// so a frame and this timeout can never both answer.
|
|
112
|
+
self.lock.lock()
|
|
113
|
+
let expired = self.pending === request
|
|
114
|
+
if expired { self.pending = nil }
|
|
115
|
+
self.lock.unlock()
|
|
116
|
+
if expired { request.onFail("no_frame") }
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
private func encode(_ buffer: CVPixelBuffer, quality: Double) -> Frame? {
|
|
121
|
+
guard let colorSpace = CGColorSpace(name: CGColorSpace.sRGB) else { return nil }
|
|
122
|
+
let image = CIImage(cvPixelBuffer: buffer)
|
|
123
|
+
let options: [CIImageRepresentationOption: Any] = [
|
|
124
|
+
CIImageRepresentationOption(rawValue: kCGImageDestinationLossyCompressionQuality as String): quality,
|
|
125
|
+
]
|
|
126
|
+
guard let jpeg = context.jpegRepresentation(of: image, colorSpace: colorSpace, options: options) else {
|
|
127
|
+
return nil
|
|
128
|
+
}
|
|
129
|
+
return Frame(jpeg: jpeg, width: CVPixelBufferGetWidth(buffer), height: CVPixelBufferGetHeight(buffer))
|
|
130
|
+
}
|
|
131
|
+
}
|
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.1369",
|
|
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.1369"
|
|
20
20
|
},
|
|
21
21
|
"peerDependencies": {
|
|
22
22
|
"expo-modules-core": "~55.0.25"
|