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

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,615 @@
1
+ package app.feedbackrelay.replay
2
+
3
+ import android.app.Activity
4
+ import android.app.Application
5
+ import android.annotation.TargetApi
6
+ import android.graphics.Bitmap
7
+ import android.media.MediaFormat
8
+ import android.media.MediaMuxer
9
+ import android.os.BatteryManager
10
+ import android.os.Build
11
+ import android.os.Bundle
12
+ import android.os.Handler
13
+ import android.os.HandlerThread
14
+ import android.os.Looper
15
+ import android.os.PowerManager
16
+ import android.os.Process
17
+ import android.os.SystemClock
18
+ import android.view.PixelCopy
19
+ import android.view.WindowManager
20
+ import app.feedbackrelay.sdk.RelayReplayAttachment
21
+ import app.feedbackrelay.sdk.RelayReplayDestination
22
+ import app.feedbackrelay.sdk.RelayReplayLease
23
+ import java.io.File
24
+ import java.io.InputStream
25
+ import java.io.IOException
26
+ import java.lang.ref.WeakReference
27
+ import java.net.URI
28
+ import java.nio.ByteBuffer
29
+ import java.util.concurrent.ArrayBlockingQueue
30
+ import java.util.concurrent.CancellationException
31
+ import java.util.concurrent.Future
32
+ import java.util.concurrent.ThreadPoolExecutor
33
+ import java.util.concurrent.TimeUnit
34
+ import java.util.concurrent.atomic.AtomicBoolean
35
+ import java.util.concurrent.atomic.AtomicInteger
36
+ import java.util.concurrent.atomic.AtomicReference
37
+ import java.util.UUID
38
+ import kotlin.math.roundToInt
39
+
40
+ /** A private MP4 valid only until its lease expires or is cancelled. No image crosses a JS bridge. */
41
+ data class RelayReplayMedia(
42
+ val file: File? = null,
43
+ val width: Int = 0,
44
+ val height: Int = 0,
45
+ val durationMs: Long = 0,
46
+ val startedBeforeEventMs: Long = 0,
47
+ val endedBeforeEventMs: Long = 0,
48
+ val omitted: String? = null,
49
+ val expiresAt: Long,
50
+ ) : AutoCloseable {
51
+ val byteSize: Long get() = file?.length() ?: 0
52
+ private val releaser = AtomicReference<(() -> Unit)?>(null)
53
+ internal fun borrowed(release: () -> Unit) { releaser.set(release) }
54
+ internal fun forgetRelease() { releaser.set(null) }
55
+ fun release() { releaser.getAndSet(null)?.invoke() }
56
+ override fun close() = release()
57
+ }
58
+
59
+ /** Shared native recorder used by the optional Kotlin facade and React Native adapter. */
60
+ class RelayReplayCapture(private val application: Application, fps: Int? = null) {
61
+ private val fps = fps?.takeIf { it in 1..10 }
62
+ private val owners = mutableSetOf<Owner>()
63
+ @Volatile private var destroyed = false
64
+ private class Preview(val owner: Owner, val lease: Lease, var callback: ((RelayReplayMedia) -> Unit)? = null)
65
+ @Volatile private var preview: Preview? = null
66
+ val currentFps: Int?
67
+ get() = synchronized(this) {
68
+ if (destroyed) null else owners.firstNotNullOfOrNull { owner ->
69
+ val engine = owner.engine
70
+ if (!owner.detached && owner.destination.captureEnabled && engine?.retiring == false) engine.currentFps else null
71
+ }
72
+ }
73
+
74
+ @Synchronized fun attach(destination: RelayReplayDestination): RelayReplayAttachment {
75
+ val key = Scope(application, scope(destination), destination.teamId, destination.appId)
76
+ synchronized(registry) {
77
+ bindWaiting()
78
+ val engine = if (!destroyed && destination.captureEnabled && Build.VERSION.SDK_INT >= 26) {
79
+ registry[key]?.takeIf { !it.retiring && it.fps == fps } ?: if (registry.isNotEmpty()) null else Engine(application, fps).also { registry[key] = it }
80
+ } else null
81
+ return Owner(destination, key, engine).also { owner ->
82
+ owners.add(owner); engine?.addOwner(owner)
83
+ if (!destroyed && destination.captureEnabled && Build.VERSION.SDK_INT >= 26 && engine == null && registry.values.any { it.retiring }) waiting.add(owner)
84
+ }
85
+ }
86
+ }
87
+
88
+ /** Supplies an already-resumed host when a native bridge initializes after onResume. */
89
+ fun observe(activity: Activity) { synchronized(this) { owners.toList() }.forEach { it.observe(activity) } }
90
+
91
+ /** Freezes a distinct offline lease. Native bridges can queue its materialization themselves. */
92
+ fun freezePreview(attachment: RelayReplayAttachment): RelayReplayLease {
93
+ val owner = attachment as? Owner ?: throw IllegalArgumentException("Preview requires this recorder's attachment.")
94
+ require(owner.capture === this) { "Preview requires this recorder's attachment." }
95
+ synchronized(this) {
96
+ if (preview != null) return Lease(owner, UUID.randomUUID().toString(), SystemClock.uptimeMillis(), "busy")
97
+ val lease = owner.freeze(UUID.randomUUID().toString(), null, true, false) as Lease
98
+ preview = Preview(owner, lease)
99
+ return lease
100
+ }
101
+ }
102
+
103
+ fun preview(callback: (RelayReplayMedia) -> Unit): AutoCloseable {
104
+ val owner = synchronized(this) {
105
+ owners.firstOrNull { it.destination.captureEnabled && it.engine?.retiring == false }
106
+ ?: owners.firstOrNull { it.destination.captureEnabled }
107
+ }
108
+ if (owner == null) { main.post { runCatching { callback(omission(if (destroyed) "destroyed" else "recording-disabled")) } }; return AutoCloseable {} }
109
+ val lease = freezePreview(owner) as Lease
110
+ val request = synchronized(this) { preview?.takeIf { it.lease === lease }?.also { it.callback = callback } }
111
+ if (request == null) { main.post { runCatching { callback(omission(lease.reason ?: "cancelled", lease)) } }; return AutoCloseable {} }
112
+ materialize(lease) { media ->
113
+ if (lease.cancelled.get() || SystemClock.elapsedRealtime() >= lease.deadline) { owner.cancel(lease); return@materialize }
114
+ val done = synchronized(this) { if (preview === request) request.callback.also { request.callback = null } else null }
115
+ if (done == null) { owner.cancel(lease); return@materialize }
116
+ media.borrowed { owner.cancel(lease) }
117
+ if (!runCatching { done(media) }.isSuccess || media.file == null) media.release()
118
+ }
119
+ return AutoCloseable { owner.cancel(lease) }
120
+ }
121
+
122
+ private fun previewCancelled(lease: Lease) {
123
+ if (preview?.lease !== lease) return
124
+ main.post {
125
+ val done = synchronized(this) { preview?.takeIf { it.lease === lease }?.let { it.callback.also { _ -> it.callback = null } } }
126
+ if (done != null) runCatching { done(omission(if (SystemClock.elapsedRealtime() >= lease.deadline) "expired" else "cancelled", lease)) }
127
+ }
128
+ }
129
+
130
+ private fun previewReleased(lease: Lease) {
131
+ if (preview?.lease === lease) main.post { synchronized(this) { if (preview?.lease === lease) preview = null } }
132
+ }
133
+
134
+ private fun previewTimedOut(lease: Lease) {
135
+ val request = synchronized(this) { preview?.takeIf { it.lease === lease } } ?: return
136
+ val done = synchronized(this) { request.callback.also { request.callback = null } }
137
+ if (done != null) runCatching { done(omission("timeout", lease)) }
138
+ request.owner.cancel(lease)
139
+ }
140
+
141
+ fun materialize(lease: RelayReplayLease, callback: (RelayReplayMedia) -> Unit) {
142
+ val value = lease as? Lease
143
+ if (value == null || value.owner.capture !== this) { main.post { runCatching { callback(omission("cancelled")) } }; return }
144
+ if (synchronized(value.owner) { value.owner.leases[value.id] !== value }) {
145
+ main.post { runCatching { callback(omission(value.reason ?: "resource-pressure", value)) } }; return
146
+ }
147
+ run(value, { reason -> main.post { runCatching { callback(omission(reason, value)) } } }) { media, _ -> main.post { runCatching { callback(media) } } }
148
+ }
149
+
150
+ fun clear() {
151
+ synchronized(this) { preview }?.let { it.owner.cancel(it.lease) }
152
+ val current = synchronized(this) { owners.toList() }
153
+ current.forEach { owner -> synchronized(owner) { owner.leases.values.toList() }.forEach(owner::cancel) }
154
+ current.mapNotNull(Owner::engine).distinct().forEach { it.clear() }
155
+ }
156
+
157
+ fun destroy() {
158
+ val current = synchronized(this) { if (destroyed) return; destroyed = true; owners.toList() }
159
+ current.forEach(Owner::detach)
160
+ synchronized(this) { preview }?.let { it.owner.cancel(it.lease) }
161
+ }
162
+
163
+ internal fun deliver(lease: RelayReplayLease, send: (String, RelayReplayMedia, ReplayJob) -> Unit) {
164
+ val value = lease as? Lease ?: return
165
+ if (value.owner.capture !== this) return
166
+ if (synchronized(value.owner) { value.owner.leases[value.id] !== value }) return
167
+ run(value) { media, job -> send(value.id, media, job); value.owner.cancel(value) }
168
+ }
169
+
170
+ private fun run(lease: Lease, rejected: ((String) -> Unit)? = null, action: (RelayReplayMedia, ReplayJob) -> Unit) {
171
+ if (lease.cancelled.get() || SystemClock.elapsedRealtime() >= lease.deadline) { rejected?.invoke("expired"); return }
172
+ if (!lease.started.compareAndSet(false, true)) { rejected?.invoke("already-submitted"); return }
173
+ val engine = lease.owner.engine
174
+ val job = ReplayJob(minOf(lease.deadline, SystemClock.elapsedRealtime() + JOB_MILLIS))
175
+ lease.job = job
176
+ val task = Runnable {
177
+ if (!job.start()) return@Runnable
178
+ var succeeded = false
179
+ try {
180
+ job.check()
181
+ val media = lease.media ?: try {
182
+ if (lease.cancelled.get()) omission("cancelled", lease) else engine?.mux(lease, job) ?: omission(lease.reason ?: "no-history", lease)
183
+ } catch (_: Exception) {
184
+ lease.file?.let { runCatching { it.delete() } }; lease.file = null
185
+ omission(if (job.expired()) "timeout" else "encoding-failed", lease)
186
+ }
187
+ lease.media = media
188
+ val available = if (media.file != null && !media.file.isFile) omission("file-unavailable", lease) else media
189
+ job.check(); action(available, job); succeeded = true
190
+ } catch (_: Exception) {
191
+ if (SystemClock.elapsedRealtime() >= lease.deadline) lease.owner.cancel(lease)
192
+ } finally {
193
+ job.release(); lease.timeout?.let(main::removeCallbacks); lease.timeout = null
194
+ if (lease.cancelled.get()) lease.cleanup() else if (!succeeded) lease.started.set(false)
195
+ }
196
+ }
197
+ try {
198
+ val executor = engine?.uploads ?: fallbackUploads
199
+ lease.future = executor.submit(task)
200
+ lease.timeout = Runnable { if (!job.finished.get()) {
201
+ job.cancel(); lease.future?.cancel(true)
202
+ if (job.cancelBeforeStart()) { lease.timeout = null; lease.started.set(false) }
203
+ previewTimedOut(lease)
204
+ } }.also { main.postDelayed(it, (job.deadline - SystemClock.elapsedRealtime()).coerceAtLeast(0)) }
205
+ } catch (_: Exception) {
206
+ job.cancel(); lease.future?.cancel(true)
207
+ if (job.cancelBeforeStart()) {
208
+ job.release()
209
+ if (lease.cancelled.get() || SystemClock.elapsedRealtime() >= lease.deadline) lease.owner.cancel(lease)
210
+ else lease.started.set(false)
211
+ }
212
+ rejected?.invoke("busy")
213
+ }
214
+ }
215
+
216
+ private inner class Owner(val destination: RelayReplayDestination, val key: Scope, @Volatile var engine: Engine?) : RelayReplayAttachment {
217
+ val capture get() = this@RelayReplayCapture
218
+ val leases = mutableMapOf<String, Lease>()
219
+ @Volatile var detached = false
220
+ @Volatile var observed = WeakReference<Activity>(null)
221
+
222
+ fun observe(activity: Activity) { observed = WeakReference(activity); synchronized(registry) { bindWaiting() }; engine?.observe(activity) }
223
+
224
+ override fun freeze(submissionId: String, activity: Activity?, captureEnabled: Boolean, isRetry: Boolean): RelayReplayLease {
225
+ val now = SystemClock.uptimeMillis()
226
+ val elapsed = SystemClock.elapsedRealtime()
227
+ synchronized(this) {
228
+ synchronized(registry) { bindWaiting() }
229
+ leases.values.filter { elapsed >= it.deadline }.toList().forEach(::cancel)
230
+ leases[submissionId]?.takeIf { !it.cancelled.get() && elapsed < it.deadline }?.let { current ->
231
+ if (captureEnabled && destination.captureEnabled) return current
232
+ cancel(current)
233
+ }
234
+ if (leases.size >= 4) return Lease(this, submissionId, now, "resource-pressure")
235
+ val reason = when {
236
+ detached || destroyed -> "destroyed"
237
+ !captureEnabled || !destination.captureEnabled -> "capture-disabled"
238
+ isRetry -> "retry-no-history"
239
+ Build.VERSION.SDK_INT < 26 -> "unsupported-platform"
240
+ engine == null -> "configuration-conflict"
241
+ else -> null
242
+ }
243
+ if (reason == null && activity != null) engine?.observe(activity)
244
+ val lease = engine?.freeze(this, submissionId, now, elapsed + LEASE_MILLIS, reason, activity) ?: Lease(this, submissionId, now, reason ?: "no-history", deadline = elapsed + LEASE_MILLIS)
245
+ leases[submissionId] = lease
246
+ lease.expiry = Runnable { cancel(lease) }.also { main.postDelayed(it, (lease.deadline - SystemClock.elapsedRealtime()).coerceAtLeast(0)) }
247
+ return lease
248
+ }
249
+ }
250
+
251
+ override fun accepted(lease: RelayReplayLease) = Unit
252
+
253
+ override fun cancel(lease: RelayReplayLease) {
254
+ val value = lease as? Lease ?: return
255
+ if (value.owner !== this || !value.cancelled.compareAndSet(false, true)) return
256
+ previewCancelled(value)
257
+ value.job?.cancel(); value.future?.cancel(true)
258
+ synchronized(this) { if (leases[value.id] === value) leases.remove(value.id) }
259
+ val job = value.job
260
+ if (job == null || job.cancelBeforeStart() || job.finished.get()) value.cleanup()
261
+ }
262
+
263
+ override fun detach() {
264
+ val current = synchronized(this) { if (detached) return; detached = true; leases.values.toList() }
265
+ current.forEach(::cancel)
266
+ synchronized(this@RelayReplayCapture) { owners.remove(this) }
267
+ val retire = synchronized(registry) {
268
+ waiting.remove(this)
269
+ val currentEngine = engine
270
+ if (currentEngine != null && currentEngine.removeOwner(this) && registry[key] === currentEngine) currentEngine.also { it.retiring = true } else null
271
+ }
272
+ retire?.destroy()
273
+ }
274
+ }
275
+
276
+ private class Lease(val owner: Owner, val id: String, val invoked: Long, var reason: String?, var frames: List<ReplayFrame> = emptyList(), var format: MediaFormat? = null, val reserved: Long = 0,
277
+ val deadline: Long = SystemClock.elapsedRealtime() + LEASE_MILLIS) : RelayReplayLease {
278
+ val expiresAt = System.currentTimeMillis() + (deadline - SystemClock.elapsedRealtime()).coerceAtLeast(0)
279
+ val cancelled = AtomicBoolean(false)
280
+ val started = AtomicBoolean(false)
281
+ private val cleaned = AtomicBoolean(false)
282
+ @Volatile var job: ReplayJob? = null
283
+ @Volatile var future: Future<*>? = null
284
+ @Volatile var file: File? = null
285
+ @Volatile var media: RelayReplayMedia? = null
286
+ var expiry: Runnable? = null
287
+ var timeout: Runnable? = null
288
+ fun cleanup() {
289
+ if (!cleaned.compareAndSet(false, true)) return
290
+ expiry?.let(main::removeCallbacks); expiry = null; timeout?.let(main::removeCallbacks); timeout = null
291
+ frames.forEach { it.bytes.fill(0) }; frames = emptyList(); format = null
292
+ file?.let { runCatching { it.delete() } }; file = null; media?.forgetRelease(); media = null
293
+ owner.engine?.release(this)
294
+ owner.capture.previewReleased(this)
295
+ }
296
+ }
297
+
298
+ @TargetApi(26)
299
+ private class Engine(val application: Application, val fps: Int?) {
300
+ private val lock = Any()
301
+ private val buffer = ReplayBuffer()
302
+ private val owners = mutableSetOf<Owner>()
303
+ private val leases = mutableSetOf<Lease>()
304
+ private val thread = HandlerThread("RelayReplayCodec").apply { start() }
305
+ private val codec = Handler(thread.looper)
306
+ private var uploadsStopped = false
307
+ private var codecStopped = false
308
+ @Volatile var retiring = false
309
+ val uploads = uploadExecutor { synchronized(lock) { uploadsStopped = true }; retireIfReady() }
310
+ private var encoder: ReplayEncoder? = null
311
+ private val cadences = mutableMapOf<Long, Long>()
312
+ private var format: MediaFormat? = null
313
+ private var host = WeakReference<Activity>(null)
314
+ private var resumed = false
315
+ @Volatile private var destroyed = false
316
+ @Volatile var currentFps: Int? = null
317
+ private set
318
+ private var generation = 0L
319
+ private var bitmapBusy = false
320
+ private var bitmapBytes = 0L
321
+ private var reason = "no-history"
322
+ private val automatic = ReplayAutoPolicy()
323
+ private var captureStarted = 0L
324
+ private var frameMillis = 0.0
325
+ private var missedSample = false
326
+ private var budgetPressure = false
327
+ private var nextTickAt = 0L
328
+ private var lastSignals = SystemClock.uptimeMillis()
329
+ private var lastCpu = Process.getElapsedCpuTime()
330
+ private var lastKeyframeRequest = 0L
331
+ private val lifecycle = object : Application.ActivityLifecycleCallbacks {
332
+ override fun onActivityResumed(activity: Activity) = observe(activity, true)
333
+ override fun onActivityPaused(activity: Activity) { if (host.get() === activity) { resumed = false; clear("background", false); host.clear() } }
334
+ override fun onActivityDestroyed(activity: Activity) = onActivityPaused(activity)
335
+ override fun onActivityCreated(activity: Activity, state: Bundle?) = Unit
336
+ override fun onActivityStarted(activity: Activity) = Unit
337
+ override fun onActivityStopped(activity: Activity) = Unit
338
+ override fun onActivitySaveInstanceState(activity: Activity, state: Bundle) = Unit
339
+ }
340
+ private val tick = object : Runnable {
341
+ override fun run() {
342
+ if (destroyed) return
343
+ if (fps == null && nextTickAt > 0 && SystemClock.uptimeMillis() - nextTickAt > 100) synchronized(lock) { missedSample = true }
344
+ try { sample() } catch (_: Exception) { clear("capture-failed", false) }
345
+ if (resumed) {
346
+ nextTickAt = SystemClock.uptimeMillis() + (1_000L / (fps ?: automatic.fps)).coerceAtLeast(100)
347
+ main.postAtTime(this, nextTickAt)
348
+ }
349
+ }
350
+ }
351
+ private val drain = object : Runnable {
352
+ override fun run() {
353
+ if (destroyed || !resumed || encoder == null) return
354
+ try { encoder?.drain(); synchronized(lock) { format = encoder?.format } } catch (_: Exception) { clear("encoding-failed", false) }
355
+ catch (_: OutOfMemoryError) { clear("resource-pressure", false) }
356
+ if (!destroyed && resumed && encoder != null) codec.postDelayed(this, 100)
357
+ }
358
+ }
359
+
360
+ init {
361
+ try { application.registerActivityLifecycleCallbacks(lifecycle); codec.post { try { ReplayCache.pruneOnce(application.cacheDir) } catch (_: Exception) { } } }
362
+ catch (error: Exception) { uploads.shutdownNow(); thread.quitSafely(); throw error }
363
+ }
364
+
365
+ fun addOwner(owner: Owner) { synchronized(lock) { owners.add(owner) } }
366
+ fun removeOwner(owner: Owner): Boolean = synchronized(lock) { owners.remove(owner); owners.isEmpty() }
367
+
368
+ fun observe(activity: Activity, fromResume: Boolean = false) {
369
+ main.post {
370
+ try {
371
+ if (destroyed || activity.isDestroyed || activity.isFinishing || activity.isChangingConfigurations || (!fromResume && !eligible(activity))) return@post
372
+ synchronized(lock) { owners.toList() }.forEach { owner -> synchronized(owner) { owner.leases.values.filter { SystemClock.elapsedRealtime() >= it.deadline }.toList() }.forEach(owner::cancel) }
373
+ if (host.get() === activity && resumed) return@post
374
+ if (host.get() !== activity) { clear("window-changed", false); host = WeakReference(activity) }
375
+ resumed = true; nextTickAt = SystemClock.uptimeMillis(); main.removeCallbacks(tick); main.post(tick)
376
+ } catch (_: Exception) { clear("capture-failed", false) }
377
+ }
378
+ }
379
+
380
+ fun clear(reason: String = "cleared", cancelLeases: Boolean = true) {
381
+ currentFps = null
382
+ val current = synchronized(lock) { generation++; buffer.clear(); format = null; this.reason = reason; if (cancelLeases) leases.toList() else emptyList() }
383
+ current.forEach { it.owner.cancel(it) }
384
+ codec.post { codec.removeCallbacks(drain); val currentEncoder = encoder; encoder = null; cadences.clear(); runCatching { currentEncoder?.close() } }
385
+ }
386
+
387
+ fun destroy() {
388
+ destroyed = true; resumed = false
389
+ main.removeCallbacks(tick); host.clear()
390
+ runCatching { application.unregisterActivityLifecycleCallbacks(lifecycle) }
391
+ clear("destroyed"); uploads.shutdownNow()
392
+ codec.post { codec.removeCallbacks(drain); synchronized(lock) { codecStopped = true }; thread.quitSafely(); retireIfReady() }
393
+ }
394
+
395
+ fun freeze(owner: Owner, id: String, invoked: Long, deadline: Long, omission: String?, activity: Activity?): Lease = synchronized(lock) {
396
+ if (omission != null) return@synchronized Lease(owner, id, invoked, omission, deadline = deadline)
397
+ val source = host.get()
398
+ val unavailable = try {
399
+ when {
400
+ !resumed || source == null || (activity != null && source !== activity) || !eligible(source) -> "no-foreground-window"
401
+ (source.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) != 0 -> "protected-content"
402
+ else -> null
403
+ }
404
+ } catch (_: Exception) { "capture-failed" }
405
+ if (unavailable != null) return@synchronized Lease(owner, id, invoked, unavailable, deadline = deadline)
406
+ val eligible = buffer.eligible(invoked * 1_000)
407
+ val bytes = eligible.sumOf { it.bytes.size.toLong() }
408
+ val reserve = bytes * 2 + 128 * 1024
409
+ if (eligible.isEmpty() || format == null) return@synchronized Lease(owner, id, invoked, reason, deadline = deadline)
410
+ if (leases.size >= 4 || buffer.byteSize + bitmapBytes + leases.sumOf(Lease::reserved) + reserve > TOTAL_BYTES)
411
+ return@synchronized Lease(owner, id, invoked, "resource-pressure", deadline = deadline)
412
+ val copied = ArrayList<ReplayFrame>()
413
+ try {
414
+ eligible.forEach { copied.add(it.copy(bytes = it.bytes.copyOf())) }
415
+ Lease(owner, id, invoked, null, copied, copyFormat(format!!), reserve, deadline).also { leases.add(it) }
416
+ } catch (_: Exception) { copied.forEach { it.bytes.fill(0) }; Lease(owner, id, invoked, "encoding-failed", deadline = deadline) }
417
+ catch (_: OutOfMemoryError) { copied.forEach { it.bytes.fill(0) }; Lease(owner, id, invoked, "resource-pressure", deadline = deadline) }
418
+ }
419
+
420
+ fun release(lease: Lease) { synchronized(lock) { leases.remove(lease) }; retireIfReady() }
421
+
422
+ private fun retireIfReady() {
423
+ val settled = synchronized(lock) { destroyed && codecStopped && uploadsStopped && !bitmapBusy && leases.isEmpty() }
424
+ if (settled) synchronized(registry) { registry.entries.removeAll { it.value === this }; bindWaiting() }
425
+ }
426
+
427
+ fun mux(lease: Lease, job: ReplayJob): RelayReplayMedia {
428
+ lease.reason?.let { return omission(it, lease) }
429
+ val frames = lease.frames
430
+ val mediaFormat = lease.format
431
+ if (lease.cancelled.get() || frames.isEmpty() || mediaFormat == null) return omission("no-history", lease)
432
+ val first = frames.first().timestampUs
433
+ val last = frames.last()
434
+ val clipEnd = minOf(lease.invoked, last.timestampUs / 1_000 + last.cadenceUs / 1_000)
435
+ val duration = clipEnd - first / 1_000
436
+ if (duration <= 0 || duration > 10_000) return omission("no-history", lease)
437
+ job.check()
438
+ val file = ReplayCache.create(application.cacheDir, lease.expiresAt).also { lease.file = it }
439
+ var muxer: MediaMuxer? = null
440
+ var started = false
441
+ try {
442
+ val writer = MediaMuxer(file.absolutePath, MediaMuxer.OutputFormat.MUXER_OUTPUT_MPEG_4).also { muxer = it }
443
+ val track = writer.addTrack(mediaFormat); writer.start(); started = true
444
+ frames.forEach { frame ->
445
+ job.check(); val info = android.media.MediaCodec.BufferInfo().apply { set(0, frame.bytes.size, frame.timestampUs - first, if (frame.keyframe) android.media.MediaCodec.BUFFER_FLAG_KEY_FRAME else 0) }
446
+ writer.writeSampleData(track, ByteBuffer.wrap(frame.bytes), info)
447
+ }
448
+ writer.writeSampleData(track, ByteBuffer.allocate(0), android.media.MediaCodec.BufferInfo().apply { set(0, 0, clipEnd * 1_000 - first, android.media.MediaCodec.BUFFER_FLAG_END_OF_STREAM) })
449
+ job.check(); writer.stop(); started = false
450
+ if (file.length() + frames.sumOf { it.bytes.size.toLong() } > lease.reserved) throw IllegalStateException("Replay storage limit exceeded")
451
+ return RelayReplayMedia(file, mediaFormat.getInteger(MediaFormat.KEY_WIDTH), mediaFormat.getInteger(MediaFormat.KEY_HEIGHT),
452
+ duration, lease.invoked - first / 1_000, lease.invoked - clipEnd,
453
+ expiresAt = lease.expiresAt)
454
+ } finally { if (started) runCatching { muxer?.stop() }; runCatching { muxer?.release() } }
455
+ }
456
+
457
+ private fun sample() {
458
+ val activity = host.get()
459
+ if (!resumed || activity == null || !eligible(activity)) { clear("no-foreground-window", false); return }
460
+ if ((activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) != 0) { clear("protected-content", false); return }
461
+ val view = activity.window.peekDecorView()
462
+ if (view == null || view.width <= 0 || view.height <= 0) { currentFps = null; return }
463
+ signals()
464
+ currentFps = fps ?: automatic.fps
465
+ val scale = minOf(1.0, 720.0 / maxOf(view.width, view.height))
466
+ val width = maxOf(2, ((view.width * scale).roundToInt() / 2) * 2)
467
+ val height = maxOf(2, ((view.height * scale).roundToInt() / 2) * 2)
468
+ val bytes = width.toLong() * height * 4
469
+ val epoch: Long
470
+ synchronized(lock) {
471
+ buffer.trim(SystemClock.uptimeMillis() * 1_000)
472
+ if (bitmapBusy) { if (fps == null) missedSample = true; return }
473
+ if (buffer.byteSize + leases.sumOf(Lease::reserved) + bytes > TOTAL_BYTES) {
474
+ if (fps == null) { missedSample = true; budgetPressure = true }; return
475
+ }
476
+ bitmapBusy = true; bitmapBytes = bytes; epoch = generation
477
+ if (fps == null) captureStarted = SystemClock.uptimeMillis()
478
+ }
479
+ val bitmap = try { Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) }
480
+ catch (_: Exception) { releaseBitmap(null); return }
481
+ catch (_: OutOfMemoryError) { releaseBitmap(null); return }
482
+ val timestampUs = SystemClock.uptimeMillis() * 1_000
483
+ val cadenceUs = 1_000_000L / (fps ?: automatic.fps)
484
+ try {
485
+ PixelCopy.request(activity.window, bitmap, { status ->
486
+ val usable = try { status == PixelCopy.SUCCESS && resumed && host.get() === activity && eligible(activity) && (activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) == 0 && synchronized(lock) { epoch == generation } } catch (_: Exception) { false }
487
+ if (!usable) { releaseBitmap(bitmap); return@request }
488
+ try { if (!codec.post {
489
+ try {
490
+ if (destroyed || !resumed || host.get() !== activity || !eligible(activity) || synchronized(lock) { epoch != generation }) return@post
491
+ if ((activity.window.attributes.flags and WindowManager.LayoutParams.FLAG_SECURE) != 0) { clear("protected-content", false); return@post }
492
+ if (encoder == null) { encoder = ReplayEncoder(width, height) { frame -> synchronized(lock) {
493
+ val cadence = cadences.remove(frame.timestampUs) ?: cadenceUs
494
+ if (epoch == generation) {
495
+ val available = (TOTAL_BYTES - bitmapBytes - leases.sumOf(Lease::reserved)).coerceIn(0, ReplayBuffer.MAX_BYTES.toLong()).toInt()
496
+ buffer.add(frame.copy(cadenceUs = cadence), available); reason = "no-history"
497
+ } else frame.bytes.fill(0)
498
+ } }; codec.postDelayed(drain, 100) }
499
+ if (timestampUs / 1_000 - lastKeyframeRequest >= 1_000) { encoder?.requestKeyframe(); lastKeyframeRequest = timestampUs / 1_000 }
500
+ cadences[timestampUs] = cadenceUs
501
+ if (cadences.size > 20) cadences.remove(cadences.keys.min())
502
+ encoder?.encode(bitmap, timestampUs)
503
+ synchronized(lock) { format = encoder?.format }
504
+ } catch (_: Exception) { clear("encoding-failed", false) }
505
+ catch (_: OutOfMemoryError) { clear("resource-pressure", false) }
506
+ finally { releaseBitmap(bitmap) }
507
+ }) releaseBitmap(bitmap) } catch (_: Exception) { releaseBitmap(bitmap) }
508
+ }, main)
509
+ } catch (_: Exception) { releaseBitmap(bitmap) }
510
+ }
511
+
512
+ private fun releaseBitmap(bitmap: Bitmap?) {
513
+ runCatching { bitmap?.recycle() }
514
+ synchronized(lock) {
515
+ if (fps == null && captureStarted > 0) {
516
+ if (bitmap == null) { budgetPressure = true; missedSample = true }
517
+ else {
518
+ val elapsed = (SystemClock.uptimeMillis() - captureStarted).coerceAtLeast(1).toDouble()
519
+ frameMillis = if (frameMillis == 0.0) elapsed else frameMillis * 0.75 + elapsed * 0.25
520
+ }
521
+ }
522
+ captureStarted = 0; bitmapBusy = false; bitmapBytes = 0
523
+ }
524
+ retireIfReady()
525
+ }
526
+
527
+ private fun signals() {
528
+ if (fps != null) return
529
+ val now = SystemClock.uptimeMillis(); if (now - lastSignals < 2_500) return
530
+ val cpu = Process.getElapsedCpuTime()
531
+ val cost: Double; val missed: Boolean; val pressure: Boolean
532
+ synchronized(lock) { cost = frameMillis; missed = missedSample; pressure = budgetPressure; missedSample = false; budgetPressure = false }
533
+ try {
534
+ val runtime = Runtime.getRuntime()
535
+ val memoryPressure = (runtime.totalMemory() - runtime.freeMemory()).toDouble() / runtime.maxMemory() > 0.8
536
+ val cpuPressure = lastSignals > 0 && (cpu - lastCpu).toDouble() / (now - lastSignals) > 0.7
537
+ val power = application.getSystemService(PowerManager::class.java)
538
+ val battery = application.getSystemService(BatteryManager::class.java)?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY) ?: -1
539
+ val thermal = Build.VERSION.SDK_INT >= 29 && power?.currentThermalStatus?.let { it >= PowerManager.THERMAL_STATUS_MODERATE } == true
540
+ automatic.update(pressure || memoryPressure || power?.isPowerSaveMode == true || battery in 0..14 || thermal, cpuPressure, cost, missed)
541
+ } catch (_: Exception) { automatic.update(true, false, cost, true) }
542
+ lastSignals = now; lastCpu = cpu
543
+ }
544
+
545
+ private fun eligible(activity: Activity): Boolean = !activity.isDestroyed && !activity.isFinishing && !activity.isChangingConfigurations && activity.hasWindowFocus() && activity.window.peekDecorView()?.isAttachedToWindow == true
546
+ }
547
+
548
+ companion object {
549
+ private const val LEASE_MILLIS = 60_000L
550
+ private const val JOB_MILLIS = 30_000L
551
+ private const val TOTAL_BYTES = 8 * 1024 * 1024L
552
+ private val main = Handler(Looper.getMainLooper())
553
+ private data class Scope(val application: Application, val backend: String, val teamId: String, val appId: String)
554
+ private val registry = mutableMapOf<Scope, Engine>()
555
+ private val waiting = mutableSetOf<Owner>()
556
+ private fun bindWaiting() {
557
+ waiting.removeAll { it.detached || it.capture.destroyed || !it.destination.captureEnabled }
558
+ if (registry.isNotEmpty()) return
559
+ val next = waiting.firstOrNull() ?: return
560
+ val engine = try { Engine(next.key.application, next.capture.fps) } catch (_: Exception) { return }
561
+ registry[next.key] = engine
562
+ val cohort = waiting.filter { it.key == next.key && it.capture.fps == next.capture.fps }
563
+ waiting.removeAll(cohort.toSet())
564
+ var attached = false
565
+ cohort.forEach { owner -> if (!owner.detached && !owner.capture.destroyed) {
566
+ owner.engine = engine; engine.addOwner(owner); attached = true; owner.observed.get()?.let(engine::observe)
567
+ } }
568
+ if (!attached) { engine.retiring = true; engine.destroy() }
569
+ }
570
+ private val fallbackUploads by lazy { uploadExecutor() }
571
+ private fun uploadExecutor(stopped: (() -> Unit)? = null) = object : ThreadPoolExecutor(1, 1, 30, TimeUnit.SECONDS, ArrayBlockingQueue<Runnable>(4), { task -> Thread(task, "RelayReplayUpload").apply { isDaemon = true } }) {
572
+ override fun terminated() { stopped?.invoke() }
573
+ }.apply { allowCoreThreadTimeOut(true) }
574
+ private fun scope(value: RelayReplayDestination): String {
575
+ val uri = URI(value.baseUrl.trimEnd('/'))
576
+ val port = if (uri.port >= 0) uri.port else if (uri.scheme.equals("https", true)) 443 else 80
577
+ return "${uri.scheme?.lowercase()}://${uri.host?.lowercase()}:$port${uri.rawPath}"
578
+ }
579
+ private fun omission(reason: String, lease: Lease? = null) = RelayReplayMedia(omitted = reason, expiresAt = lease?.expiresAt ?: System.currentTimeMillis())
580
+ private fun copyFormat(value: MediaFormat): MediaFormat = MediaFormat.createVideoFormat("video/avc", value.getInteger(MediaFormat.KEY_WIDTH), value.getInteger(MediaFormat.KEY_HEIGHT)).apply {
581
+ listOf("csd-0", "csd-1").forEach { key -> value.getByteBuffer(key)?.duplicate()?.let { buffer -> val bytes = ByteArray(buffer.remaining()); buffer.get(bytes); setByteBuffer(key, ByteBuffer.wrap(bytes)) } }
582
+ }
583
+ }
584
+ }
585
+
586
+ internal object ReplayCache {
587
+ private val pruned = AtomicBoolean(false)
588
+ private val ownedName = Regex("^(\\d{1,19})-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.mp4$")
589
+ fun create(cache: File, expiresAt: Long): File {
590
+ val folder = File(cache, "relay-replay")
591
+ if (!folder.isDirectory && !folder.mkdirs()) throw IOException("Replay cache is unavailable")
592
+ return File(folder, "$expiresAt-${UUID.randomUUID()}.mp4").also { if (!it.createNewFile()) throw IOException("Replay cache file is unavailable") }
593
+ }
594
+ fun pruneOnce(cache: File) { if (pruned.compareAndSet(false, true)) runCatching { prune(cache, System.currentTimeMillis()) } }
595
+ fun prune(cache: File, now: Long) {
596
+ File(cache, "relay-replay").listFiles()?.forEach { file ->
597
+ val expiry = ownedName.matchEntire(file.name)?.groupValues?.get(1)?.toLongOrNull()
598
+ if (expiry != null && expiry <= now && file.isFile) runCatching { file.delete() }
599
+ }
600
+ }
601
+ }
602
+
603
+ internal class ReplayJob(val deadline: Long) {
604
+ private val cancelled = AtomicBoolean(false)
605
+ val finished = AtomicBoolean(false)
606
+ private val state = AtomicInteger(0)
607
+ @Volatile var disconnect: (() -> Unit)? = null
608
+ @Volatile var input: InputStream? = null
609
+ fun expired() = SystemClock.elapsedRealtime() >= deadline
610
+ fun start() = state.compareAndSet(0, 1)
611
+ fun cancelBeforeStart(): Boolean = state.compareAndSet(0, 2).also { if (it) finished.set(true) }
612
+ fun check() { if (cancelled.get() || expired() || Thread.currentThread().isInterrupted) throw CancellationException() }
613
+ fun cancel() { cancelled.set(true); runCatching { input?.close() }; runCatching { disconnect?.invoke() } }
614
+ fun release() { state.set(2); finished.set(true); input = null; disconnect = null }
615
+ }
@@ -0,0 +1,53 @@
1
+ package app.feedbackrelay.replay
2
+
3
+ /** Conservative rate control; elapsed capture cost is a budget hint, not CPU attribution. */
4
+ internal class ReplayAutoPolicy {
5
+ var fps = 1
6
+ private set
7
+ private var healthy = 0
8
+
9
+ fun update(pressure: Boolean, elevatedCpu: Boolean, frameMillis: Double, missed: Boolean) {
10
+ val costCap = if (frameMillis > 0 && frameMillis.isFinite()) (50.0 / frameMillis).toInt().coerceIn(1, 5) else 1
11
+ var cap = minOf(costCap, if (pressure) 1 else if (elevatedCpu) 2 else 5)
12
+ if (missed) cap = minOf(cap, maxOf(1, fps - 1))
13
+ when {
14
+ cap < fps -> { fps = cap; healthy = 0 }
15
+ pressure || elevatedCpu || missed || cap == fps -> healthy = 0
16
+ ++healthy >= 3 -> { fps++; healthy = 0 }
17
+ }
18
+ }
19
+ }
20
+
21
+ /** Owned by the recorder lock. Leases copy bytes before the rolling buffer can erase them. */
22
+ internal class ReplayBuffer {
23
+ private val frames = ArrayDeque<ReplayFrame>()
24
+ var byteSize = 0L
25
+ private set
26
+
27
+ fun add(frame: ReplayFrame, maxBytes: Int = MAX_BYTES) {
28
+ val budget = maxBytes.coerceIn(0, MAX_BYTES)
29
+ if (frame.bytes.size > budget || (frames.isEmpty() && !frame.keyframe)) { frame.bytes.fill(0); trim(frame.timestampUs, budget); return }
30
+ if (frames.lastOrNull()?.timestampUs?.let { frame.timestampUs <= it } == true) { frame.bytes.fill(0); return }
31
+ frames.addLast(frame); byteSize += frame.bytes.size
32
+ trim(frame.timestampUs, budget)
33
+ }
34
+
35
+ fun trim(nowUs: Long, maxBytes: Int = MAX_BYTES) {
36
+ while (frames.isNotEmpty() && (frames.first().timestampUs < nowUs - HISTORY_US || byteSize > maxBytes.coerceIn(0, MAX_BYTES))) removeFirst()
37
+ while (frames.firstOrNull()?.keyframe == false) removeFirst()
38
+ }
39
+
40
+ fun eligible(eventUs: Long): List<ReplayFrame> {
41
+ trim(eventUs)
42
+ return frames.filter { it.timestampUs <= eventUs }
43
+ }
44
+
45
+ fun clear() { while (frames.isNotEmpty()) removeFirst() }
46
+
47
+ private fun removeFirst() { val frame = frames.removeFirst(); byteSize -= frame.bytes.size; frame.bytes.fill(0) }
48
+
49
+ companion object {
50
+ const val MAX_BYTES = 2 * 1024 * 1024
51
+ const val HISTORY_US = 10_000_000L
52
+ }
53
+ }