@feedbackrelay/react-native-replay 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,268 @@
1
+ package app.feedbackrelay.replay
2
+
3
+ import android.annotation.TargetApi
4
+ import android.graphics.Bitmap
5
+ import android.media.MediaCodec
6
+ import android.media.MediaCodecInfo
7
+ import android.media.MediaCodecList
8
+ import android.media.MediaFormat
9
+ import android.opengl.EGL14
10
+ import android.opengl.EGLConfig
11
+ import android.opengl.EGLContext
12
+ import android.opengl.EGLDisplay
13
+ import android.opengl.EGLExt
14
+ import android.opengl.EGLSurface
15
+ import android.opengl.GLES20
16
+ import android.opengl.GLUtils
17
+ import android.os.Build
18
+ import android.os.Bundle
19
+ import android.os.Looper
20
+ import android.view.Surface
21
+ import java.nio.ByteBuffer
22
+ import java.nio.ByteOrder
23
+ import kotlin.math.roundToInt
24
+
25
+ internal data class ReplayFrame(val bytes: ByteArray, val timestampUs: Long, val keyframe: Boolean, val cadenceUs: Long = 100_000)
26
+
27
+ /** Owned exclusively by the recorder's background thread. */
28
+ @TargetApi(26)
29
+ internal class ReplayEncoder(val width: Int, val height: Int, private val emit: (ReplayFrame) -> Unit) : AutoCloseable {
30
+ private val owner = Thread.currentThread()
31
+ private var codec: MediaCodec? = null
32
+ private var started = false
33
+ private var inputSurface: Surface? = null
34
+ private var display: EGLDisplay = EGL14.EGL_NO_DISPLAY
35
+ private var context: EGLContext = EGL14.EGL_NO_CONTEXT
36
+ private var surface: EGLSurface = EGL14.EGL_NO_SURFACE
37
+ private var program = 0
38
+ private var texture = 0
39
+ private var positionLocation = -1
40
+ private var textureLocation = -1
41
+ private var samplerLocation = -1
42
+ private var closed = false
43
+ private var partial: ByteArray? = null
44
+ private var partialSize = 0
45
+ private var partialTimestampUs = 0L
46
+ private var partialKeyframe = false
47
+ private val positions = ByteBuffer.allocateDirect(8 * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
48
+ put(floatArrayOf(-1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f)); position(0)
49
+ }
50
+ private val coordinates = ByteBuffer.allocateDirect(8 * 4).order(ByteOrder.nativeOrder()).asFloatBuffer().apply {
51
+ // Bitmap row zero is the top row; GL's lower vertices must sample its bottom row.
52
+ put(floatArrayOf(0f, 1f, 1f, 1f, 0f, 0f, 1f, 0f)); position(0)
53
+ }
54
+ var format: MediaFormat? = null
55
+ private set
56
+
57
+ init {
58
+ check(Looper.myLooper() != Looper.getMainLooper()) { "Replay encoding must run off the main thread." }
59
+ require(width in 2..720 && height in 2..720 && width % 2 == 0 && height % 2 == 0) { "Replay dimensions must be even and no larger than 720 pixels." }
60
+ var ready = false
61
+ try {
62
+ val settings = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_AVC, width, height).apply {
63
+ setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
64
+ setInteger(MediaFormat.KEY_BIT_RATE, 500_000)
65
+ setInteger(MediaFormat.KEY_FRAME_RATE, 10)
66
+ setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)
67
+ setInteger(MediaFormat.KEY_PROFILE, MediaCodecInfo.CodecProfileLevel.AVCProfileBaseline)
68
+ if (Build.VERSION.SDK_INT >= 29) setInteger(MediaFormat.KEY_MAX_B_FRAMES, 0)
69
+ }
70
+ val hardware = if (Build.VERSION.SDK_INT >= 29) MediaCodecList(MediaCodecList.REGULAR_CODECS).codecInfos.firstOrNull { info ->
71
+ try {
72
+ info.isEncoder && info.isHardwareAccelerated && info.supportedTypes.any { it.equals(MediaFormat.MIMETYPE_VIDEO_AVC, true) } &&
73
+ info.getCapabilitiesForType(MediaFormat.MIMETYPE_VIDEO_AVC).isFormatSupported(settings)
74
+ } catch (_: Exception) { false }
75
+ }?.name else null
76
+ val encoder = if (hardware == null) MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC) else {
77
+ try { MediaCodec.createByCodecName(hardware) }
78
+ catch (_: Exception) { MediaCodec.createEncoderByType(MediaFormat.MIMETYPE_VIDEO_AVC) }
79
+ }
80
+ codec = encoder
81
+ encoder.configure(settings, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
82
+ inputSurface = encoder.createInputSurface()
83
+ encoder.start(); started = true
84
+ prepareGl(requireNotNull(inputSurface))
85
+ ready = true
86
+ } finally { if (!ready) close() }
87
+ }
88
+
89
+ fun encode(bitmap: Bitmap, timestampUs: Long) {
90
+ checkOpen()
91
+ require(!bitmap.isRecycled && bitmap.width > 0 && bitmap.height > 0) { "Replay bitmap is unavailable." }
92
+ require(timestampUs >= 0 && timestampUs <= Long.MAX_VALUE / 1_000) { "Invalid replay timestamp." }
93
+ drain()
94
+ check(EGL14.eglMakeCurrent(display, surface, surface, context)) { "Could not activate replay EGL context." }
95
+ GLES20.glViewport(0, 0, width, height)
96
+ GLES20.glClearColor(0f, 0f, 0f, 1f)
97
+ GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT)
98
+ val scale = minOf(width.toDouble() / bitmap.width, height.toDouble() / bitmap.height)
99
+ val drawnWidth = (bitmap.width * scale).roundToInt().coerceIn(1, width)
100
+ val drawnHeight = (bitmap.height * scale).roundToInt().coerceIn(1, height)
101
+ GLES20.glViewport((width - drawnWidth) / 2, (height - drawnHeight) / 2, drawnWidth, drawnHeight)
102
+ GLES20.glUseProgram(program)
103
+ GLES20.glActiveTexture(GLES20.GL_TEXTURE0)
104
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture)
105
+ GLES20.glPixelStorei(GLES20.GL_UNPACK_ALIGNMENT, 1)
106
+ GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
107
+ positions.position(0); coordinates.position(0)
108
+ GLES20.glVertexAttribPointer(positionLocation, 2, GLES20.GL_FLOAT, false, 0, positions)
109
+ GLES20.glVertexAttribPointer(textureLocation, 2, GLES20.GL_FLOAT, false, 0, coordinates)
110
+ GLES20.glEnableVertexAttribArray(positionLocation)
111
+ GLES20.glEnableVertexAttribArray(textureLocation)
112
+ GLES20.glUniform1i(samplerLocation, 0)
113
+ GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4)
114
+ check(GLES20.glGetError() == GLES20.GL_NO_ERROR) { "Could not draw replay frame." }
115
+ check(EGLExt.eglPresentationTimeANDROID(display, surface, timestampUs * 1_000)) { "Could not timestamp replay frame." }
116
+ check(EGL14.eglSwapBuffers(display, surface)) { "Could not submit replay frame." }
117
+ drain()
118
+ }
119
+
120
+ fun drain() {
121
+ checkOpen()
122
+ val encoder = requireNotNull(codec)
123
+ val info = MediaCodec.BufferInfo()
124
+ while (true) {
125
+ when (val index = encoder.dequeueOutputBuffer(info, 0)) {
126
+ MediaCodec.INFO_TRY_AGAIN_LATER -> return
127
+ MediaCodec.INFO_OUTPUT_FORMAT_CHANGED -> {
128
+ check(partial == null) { "Replay format changed during an incomplete frame." }
129
+ format = encoder.outputFormat
130
+ }
131
+ MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED -> Unit
132
+ else -> {
133
+ check(index >= 0) { "Unexpected replay encoder output." }
134
+ try {
135
+ if ((info.flags and MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) continue
136
+ check(info.size >= 0 && info.size <= MAX_FRAME_BYTES && info.offset >= 0) { "Replay frame exceeds its byte limit." }
137
+ val incomplete = (info.flags and MediaCodec.BUFFER_FLAG_PARTIAL_FRAME) != 0
138
+ val keyframe = (info.flags and MediaCodec.BUFFER_FLAG_KEY_FRAME) != 0
139
+ if (info.size == 0 && partial == null && !incomplete) continue
140
+ val bytes = if (partial != null || incomplete) {
141
+ if (partial == null) {
142
+ partial = ByteArray(MAX_FRAME_BYTES); partialTimestampUs = info.presentationTimeUs; partialKeyframe = false
143
+ }
144
+ check(partialTimestampUs == info.presentationTimeUs && partialSize.toLong() + info.size <= MAX_FRAME_BYTES) { "Invalid or oversized incomplete replay frame." }
145
+ partialKeyframe = partialKeyframe || keyframe
146
+ copyOutput(encoder, index, info, requireNotNull(partial), partialSize)
147
+ partialSize += info.size
148
+ if (incomplete) continue
149
+ requireNotNull(partial).copyOf(partialSize).also {
150
+ partial?.fill(0); partial = null; partialSize = 0
151
+ }
152
+ } else ByteArray(info.size).also { copyOutput(encoder, index, info, it, 0) }
153
+ var delivered = false
154
+ try {
155
+ emit(ReplayFrame(bytes, info.presentationTimeUs, keyframe || partialKeyframe))
156
+ delivered = true
157
+ } finally { if (!delivered) bytes.fill(0); partialKeyframe = false }
158
+ } finally { encoder.releaseOutputBuffer(index, false) }
159
+ }
160
+ }
161
+ }
162
+ }
163
+
164
+ fun requestKeyframe() {
165
+ checkOpen()
166
+ requireNotNull(codec).setParameters(Bundle().apply { putInt(MediaCodec.PARAMETER_KEY_REQUEST_SYNC_FRAME, 0) })
167
+ }
168
+
169
+ private fun copyOutput(encoder: MediaCodec, index: Int, info: MediaCodec.BufferInfo, destination: ByteArray, offset: Int) {
170
+ if (info.size == 0) return
171
+ val output = requireNotNull(encoder.getOutputBuffer(index)).duplicate()
172
+ val end = info.offset.toLong() + info.size
173
+ check(end <= output.capacity()) { "Invalid replay output buffer bounds." }
174
+ output.limit(end.toInt()); output.position(info.offset)
175
+ output.get(destination, offset, info.size)
176
+ }
177
+
178
+ private fun prepareGl(input: Surface) {
179
+ display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY)
180
+ check(display != EGL14.EGL_NO_DISPLAY && EGL14.eglInitialize(display, IntArray(2), 0, IntArray(2), 0)) { "Could not initialize replay EGL display." }
181
+ val configs = arrayOfNulls<EGLConfig>(1)
182
+ val count = IntArray(1)
183
+ val attributes = intArrayOf(EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8,
184
+ EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT,
185
+ EGL14.EGL_SURFACE_TYPE, EGL14.EGL_WINDOW_BIT, 0x3142, 1, EGL14.EGL_NONE)
186
+ check(EGL14.eglChooseConfig(display, attributes, 0, configs, 0, 1, count, 0) && count[0] > 0) { "No recordable replay EGL configuration." }
187
+ val config = requireNotNull(configs[0])
188
+ context = EGL14.eglCreateContext(display, config, EGL14.EGL_NO_CONTEXT, intArrayOf(EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE), 0)
189
+ check(context != EGL14.EGL_NO_CONTEXT) { "Could not create replay EGL context." }
190
+ surface = EGL14.eglCreateWindowSurface(display, config, input, intArrayOf(EGL14.EGL_NONE), 0)
191
+ check(surface != EGL14.EGL_NO_SURFACE && EGL14.eglMakeCurrent(display, surface, surface, context)) { "Could not create replay EGL surface." }
192
+ val vertex = compileShader(GLES20.GL_VERTEX_SHADER, "attribute vec2 position; attribute vec2 coordinate; varying vec2 uv; void main() { gl_Position = vec4(position, 0.0, 1.0); uv = coordinate; }")
193
+ var fragment = 0
194
+ try {
195
+ fragment = compileShader(GLES20.GL_FRAGMENT_SHADER, "precision mediump float; varying vec2 uv; uniform sampler2D image; void main() { gl_FragColor = texture2D(image, uv); }")
196
+ program = GLES20.glCreateProgram()
197
+ check(program != 0) { "Could not create replay GL program." }
198
+ GLES20.glAttachShader(program, vertex); GLES20.glAttachShader(program, fragment); GLES20.glLinkProgram(program)
199
+ val linked = IntArray(1); GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0)
200
+ check(linked[0] != 0) { "Could not link replay GL program: ${GLES20.glGetProgramInfoLog(program)}" }
201
+ } finally { GLES20.glDeleteShader(vertex); if (fragment != 0) GLES20.glDeleteShader(fragment) }
202
+ positionLocation = GLES20.glGetAttribLocation(program, "position")
203
+ textureLocation = GLES20.glGetAttribLocation(program, "coordinate")
204
+ samplerLocation = GLES20.glGetUniformLocation(program, "image")
205
+ check(positionLocation >= 0 && textureLocation >= 0 && samplerLocation >= 0) { "Replay GL shader inputs are unavailable." }
206
+ val textures = IntArray(1); GLES20.glGenTextures(1, textures, 0); texture = textures[0]
207
+ check(texture != 0) { "Could not create replay texture." }
208
+ GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture)
209
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
210
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
211
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE)
212
+ GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE)
213
+ check(GLES20.glGetError() == GLES20.GL_NO_ERROR) { "Could not initialize replay GL texture." }
214
+ }
215
+
216
+ private fun compileShader(type: Int, source: String): Int {
217
+ val shader = GLES20.glCreateShader(type)
218
+ check(shader != 0) { "Could not create replay GL shader." }
219
+ var compiled = false
220
+ try {
221
+ GLES20.glShaderSource(shader, source); GLES20.glCompileShader(shader)
222
+ val status = IntArray(1); GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, status, 0)
223
+ check(status[0] != 0) { "Could not compile replay GL shader: ${GLES20.glGetShaderInfoLog(shader)}" }
224
+ compiled = true
225
+ return shader
226
+ } finally { if (!compiled) GLES20.glDeleteShader(shader) }
227
+ }
228
+
229
+ private fun checkOpen() {
230
+ check(Thread.currentThread() === owner) { "Replay encoder must stay on its owner thread." }
231
+ check(!closed) { "Replay encoder is closed." }
232
+ }
233
+
234
+ override fun close() {
235
+ check(Thread.currentThread() === owner) { "Replay encoder must close on its owner thread." }
236
+ if (closed) return
237
+ closed = true
238
+ partial?.fill(0); partial = null; partialSize = 0
239
+ try {
240
+ if (display != EGL14.EGL_NO_DISPLAY && context != EGL14.EGL_NO_CONTEXT && surface != EGL14.EGL_NO_SURFACE && EGL14.eglMakeCurrent(display, surface, surface, context)) {
241
+ if (texture != 0) GLES20.glDeleteTextures(1, intArrayOf(texture), 0)
242
+ if (program != 0) GLES20.glDeleteProgram(program)
243
+ }
244
+ } catch (_: Exception) { }
245
+ finally {
246
+ try {
247
+ if (display != EGL14.EGL_NO_DISPLAY) {
248
+ try { EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT) } catch (_: Exception) { }
249
+ try { if (surface != EGL14.EGL_NO_SURFACE) EGL14.eglDestroySurface(display, surface) } catch (_: Exception) { }
250
+ try { if (context != EGL14.EGL_NO_CONTEXT) EGL14.eglDestroyContext(display, context) } catch (_: Exception) { }
251
+ try { EGL14.eglReleaseThread() } catch (_: Exception) { }
252
+ try { EGL14.eglTerminate(display) } catch (_: Exception) { }
253
+ }
254
+ } finally {
255
+ try { inputSurface?.release() } catch (_: Exception) { }
256
+ finally {
257
+ val encoder = codec; codec = null; inputSurface = null
258
+ if (encoder != null) {
259
+ try { if (started) encoder.stop() } catch (_: Exception) { }
260
+ finally { try { encoder.release() } catch (_: Exception) { } }
261
+ }
262
+ }
263
+ }
264
+ }
265
+ }
266
+
267
+ companion object { private const val MAX_FRAME_BYTES = 2 * 1024 * 1024 }
268
+ }
@@ -0,0 +1,29 @@
1
+ package app.feedbackrelay.sdk
2
+
3
+ import android.app.Activity
4
+
5
+ /** Implemented by the optional replay module. Core never loads an encoder itself. */
6
+ interface RelayReplayProvider {
7
+ fun attach(destination: RelayReplayDestination): RelayReplayAttachment
8
+ }
9
+
10
+ data class RelayReplayDestination(
11
+ val baseUrl: String,
12
+ val teamId: String,
13
+ val relayId: String,
14
+ val publishableKey: String,
15
+ val appId: String,
16
+ val connectTimeoutMillis: Int = 15_000,
17
+ val readTimeoutMillis: Int = 30_000,
18
+ val captureEnabled: Boolean = true,
19
+ )
20
+
21
+ /** Each client owns an attachment; frozen leases remain tied to their original destination. */
22
+ interface RelayReplayAttachment {
23
+ fun freeze(submissionId: String, activity: Activity? = null, captureEnabled: Boolean = true, isRetry: Boolean = false): RelayReplayLease
24
+ fun accepted(lease: RelayReplayLease)
25
+ fun cancel(lease: RelayReplayLease)
26
+ fun detach()
27
+ }
28
+
29
+ interface RelayReplayLease
@@ -0,0 +1,16 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3
+ <plist version="1.0"><dict>
4
+ <key>NSPrivacyTracking</key><false/>
5
+ <key>NSPrivacyTrackingDomains</key><array/>
6
+ <key>NSPrivacyAccessedAPITypes</key><array><dict>
7
+ <key>NSPrivacyAccessedAPIType</key><string>NSPrivacyAccessedAPICategorySystemBootTime</string>
8
+ <key>NSPrivacyAccessedAPITypeReasons</key><array><string>35F9.1</string></array>
9
+ </dict></array>
10
+ <key>NSPrivacyCollectedDataTypes</key><array><dict>
11
+ <key>NSPrivacyCollectedDataType</key><string>NSPrivacyCollectedDataTypePhotosorVideos</string>
12
+ <key>NSPrivacyCollectedDataTypeLinked</key><true/>
13
+ <key>NSPrivacyCollectedDataTypeTracking</key><false/>
14
+ <key>NSPrivacyCollectedDataTypePurposes</key><array><string>NSPrivacyCollectedDataTypePurposeAppFunctionality</string></array>
15
+ </dict></array>
16
+ </dict></plist>