-
-
Notifications
You must be signed in to change notification settings - Fork 476
Expand file tree
/
Copy pathPixelCopyStrategy.kt
More file actions
438 lines (402 loc) · 14 KB
/
Copy pathPixelCopyStrategy.kt
File metadata and controls
438 lines (402 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
package io.sentry.android.replay.screenshot
import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Matrix
import android.graphics.Paint
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.view.PixelCopy
import android.view.View
import io.sentry.SentryLevel.DEBUG
import io.sentry.SentryLevel.INFO
import io.sentry.SentryLevel.WARNING
import io.sentry.SentryOptions
import io.sentry.android.replay.ExecutorProvider
import io.sentry.android.replay.ScreenshotRecorderCallback
import io.sentry.android.replay.ScreenshotRecorderConfig
import io.sentry.android.replay.phoneWindow
import io.sentry.android.replay.util.DebugOverlayDrawable
import io.sentry.android.replay.util.MaskRenderer
import io.sentry.android.replay.util.ReplayRunnable
import io.sentry.android.replay.util.traverse
import io.sentry.android.replay.viewhierarchy.ViewHierarchyNode
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicInteger
import kotlin.LazyThreadSafetyMode.NONE
@SuppressLint("UseKtx")
internal class PixelCopyStrategy(
executorProvider: ExecutorProvider,
private val screenshotRecorderCallback: ScreenshotRecorderCallback?,
private val options: SentryOptions,
private val config: ScreenshotRecorderConfig,
private val debugOverlayDrawable: DebugOverlayDrawable,
// Lets the strategy re-arm the recorder's contentChanged gate so frames keep being captured
// when SurfaceViews are present (their redraws don't trigger ViewTreeObserver.OnDrawListener).
private val markContentChanged: () -> Unit = {},
) : ScreenshotStrategy {
private companion object {
/**
* An unstable capture means the view hierarchy changed while PixelCopy was in flight. Cap
* skipped unstable captures so continuous animations don't stop replay recording.
*/
const val MAX_UNSTABLE_CAPTURES_TO_SKIP = 1
}
private val executor = executorProvider.getExecutor()
private val mainLooperHandler = executorProvider.getMainLooperHandler()
private val screenshot =
Bitmap.createBitmap(
config.recordingWidth,
config.recordingHeight,
if (options.sessionReplay.isCaptureSurfaceViews) {
Bitmap.Config.ARGB_8888
} else {
Bitmap.Config.RGB_565
},
)
private val prescaledMatrix by
lazy(NONE) { Matrix().apply { preScale(config.scaleFactorX, config.scaleFactorY) } }
private val lastCaptureSuccessful = AtomicBoolean(false)
private val maskRenderer = MaskRenderer()
private val contentChanged = AtomicBoolean(false)
private val unstableCaptures = AtomicInteger(0)
private val isClosed = AtomicBoolean(false)
private val frameInFlight = AtomicBoolean(false)
private val cleanupScheduled = AtomicBoolean(false)
private val dstOverPaint by
lazy(NONE) { Paint().apply { xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OVER) } }
private val screenshotCanvas by lazy(NONE) { Canvas(screenshot) }
private val tmpSrcRect = Rect()
private val tmpDstRect = RectF()
private val windowLocation = IntArray(2)
private val svLocation = IntArray(2)
private class SurfaceViewCapture(val bitmap: Bitmap, val x: Int, val y: Int)
@SuppressLint("NewApi")
override fun capture(root: View) {
val window = root.phoneWindow
if (window == null) {
options.logger.log(DEBUG, "Window is invalid, not capturing screenshot")
return
}
if (!frameInFlight.compareAndSet(false, true)) {
options.logger.log(DEBUG, "PixelCopyStrategy capture is already in flight, skipping")
markContentChanged()
return
}
if (isClosed.get()) {
options.logger.log(DEBUG, "PixelCopyStrategy is closed, not capturing screenshot")
finishFrame()
return
}
try {
contentChanged.set(false)
PixelCopy.request(
window,
screenshot,
{ copyResult: Int ->
if (isClosed.get()) {
options.logger.log(DEBUG, "PixelCopyStrategy is closed, ignoring capture result")
finishFrame()
return@request
}
if (copyResult != PixelCopy.SUCCESS) {
options.logger.log(INFO, "Failed to capture replay recording: %d", copyResult)
unstableCaptures.set(0)
lastCaptureSuccessful.set(false)
finishFrame()
return@request
}
val changedDuringCapture = contentChanged.get()
if (changedDuringCapture && shouldSkipUnstableCapture()) {
finishFrame()
return@request
}
// TODO: disableAllMasking here and dont traverse?
val viewHierarchy = ViewHierarchyNode.fromView(root, null, 0, options.sessionReplay)
val surfaceViewNodes =
if (options.sessionReplay.isCaptureSurfaceViews) {
mutableListOf<ViewHierarchyNode.SurfaceViewHierarchyNode>()
} else {
null
}
root.traverse(viewHierarchy, options.sessionReplay, options.logger, surfaceViewNodes)
if (surfaceViewNodes.isNullOrEmpty()) {
val submitted =
executor.submit(
ReplayRunnable("screenshot_recorder.mask") {
try {
applyMaskingAndNotify(
root,
viewHierarchy,
resetUnstableCaptures = !changedDuringCapture,
)
} finally {
finishFrame()
}
}
)
if (submitted == null) {
finishFrame()
}
} else {
// Re-arm the recorder's contentChanged gate; SurfaceView redraws don't trigger
// ViewTreeObserver.OnDrawListener, so we'd otherwise emit the same frame forever.
markContentChanged()
captureSurfaceViews(
root,
surfaceViewNodes,
viewHierarchy,
resetUnstableCaptures = !changedDuringCapture,
)
}
},
mainLooperHandler.handler,
)
} catch (e: Throwable) {
options.logger.log(WARNING, "Failed to capture replay recording", e)
unstableCaptures.set(0)
lastCaptureSuccessful.set(false)
finishFrame()
}
}
private fun shouldSkipUnstableCapture(): Boolean {
if (unstableCaptures.incrementAndGet() <= MAX_UNSTABLE_CAPTURES_TO_SKIP) {
options.logger.log(INFO, "Failed to determine view hierarchy, not capturing")
lastCaptureSuccessful.set(false)
return true
}
return false
}
private fun applyMaskingAndNotify(
root: View,
viewHierarchy: ViewHierarchyNode,
resetUnstableCaptures: Boolean,
) {
if (isClosed.get() || screenshot.isRecycled) {
options.logger.log(DEBUG, "PixelCopyStrategy is closed, skipping masking")
return
}
val debugMasks = maskRenderer.renderMasks(screenshot, viewHierarchy, prescaledMatrix)
if (options.replayController.isDebugMaskingOverlayEnabled()) {
mainLooperHandler.post {
if (debugOverlayDrawable.callback == null) {
root.overlay.add(debugOverlayDrawable)
}
debugOverlayDrawable.updateMasks(debugMasks)
root.postInvalidate()
}
}
screenshotRecorderCallback?.onScreenshotRecorded(screenshot)
lastCaptureSuccessful.set(true)
contentChanged.set(false)
if (resetUnstableCaptures) {
unstableCaptures.set(0)
}
}
@SuppressLint("NewApi")
private fun captureSurfaceViews(
root: View,
surfaceViewNodes: List<ViewHierarchyNode.SurfaceViewHierarchyNode>,
viewHierarchy: ViewHierarchyNode,
resetUnstableCaptures: Boolean,
) {
// Snapshot the window location into locals so the executor-side compositor reads stable
// values even if a new capture cycle starts and overwrites the field.
root.getLocationOnScreen(windowLocation)
val windowX = windowLocation[0]
val windowY = windowLocation[1]
val captures = arrayOfNulls<SurfaceViewCapture>(surfaceViewNodes.size)
val remaining = AtomicInteger(surfaceViewNodes.size)
fun onCaptureComplete() {
if (remaining.decrementAndGet() == 0) {
compositeSurfaceViewsAndMask(
root,
captures,
viewHierarchy,
windowX,
windowY,
resetUnstableCaptures,
)
}
}
for ((index, node) in surfaceViewNodes.withIndex()) {
val surfaceView = node.surfaceViewRef.get()
// holder.surface can be null before the surface is created — guard against NPE.
val surface = surfaceView?.holder?.surface
if (surfaceView == null || surface == null || !surface.isValid) {
onCaptureComplete()
continue
}
var svBitmap: Bitmap? = null
try {
svBitmap =
Bitmap.createBitmap(surfaceView.width, surfaceView.height, Bitmap.Config.ARGB_8888)
val bitmapToCapture = svBitmap
surfaceView.getLocationOnScreen(svLocation)
val capturedX = svLocation[0]
val capturedY = svLocation[1]
PixelCopy.request(
surfaceView,
bitmapToCapture,
{ copyResult: Int ->
if (isClosed.get()) {
bitmapToCapture.recycle()
// still drive the completion latch so any prior captures get recycled by the
// composite step's early-return path.
onCaptureComplete()
return@request
}
if (copyResult == PixelCopy.SUCCESS) {
captures[index] = SurfaceViewCapture(bitmapToCapture, capturedX, capturedY)
} else {
bitmapToCapture.recycle()
options.logger.log(INFO, "Failed to capture SurfaceView: %d", copyResult)
}
onCaptureComplete()
},
mainLooperHandler.handler,
)
// Ownership transferred to the PixelCopy callback — clear local so catch doesn't
// double-recycle if the recycle paths above already ran.
svBitmap = null
} catch (e: Throwable) {
options.logger.log(WARNING, "Failed to capture SurfaceView", e)
svBitmap?.recycle()
onCaptureComplete()
}
}
}
private fun compositeSurfaceViewsAndMask(
root: View,
captures: Array<SurfaceViewCapture?>,
viewHierarchy: ViewHierarchyNode,
windowX: Int,
windowY: Int,
resetUnstableCaptures: Boolean,
) {
val submitted =
executor.submit(
ReplayRunnable("screenshot_recorder.composite") {
try {
if (isClosed.get() || screenshot.isRecycled) {
options.logger.log(DEBUG, "PixelCopyStrategy is closed, skipping compositing")
recycleCaptures(captures)
return@ReplayRunnable
}
for (capture in captures) {
if (capture == null) continue
if (capture.bitmap.isRecycled) continue
compositeSurfaceViewInto(
screenshotCanvas,
dstOverPaint,
tmpSrcRect,
tmpDstRect,
capture.bitmap,
capture.x,
capture.y,
windowX,
windowY,
config.scaleFactorX,
config.scaleFactorY,
)
capture.bitmap.recycle()
}
applyMaskingAndNotify(root, viewHierarchy, resetUnstableCaptures)
} finally {
finishFrame()
}
}
)
if (submitted == null) {
recycleCaptures(captures)
finishFrame()
}
}
private fun recycleCaptures(captures: Array<SurfaceViewCapture?>) {
for (capture in captures) {
if (capture != null && !capture.bitmap.isRecycled) {
capture.bitmap.recycle()
}
}
}
override fun onContentChanged() {
contentChanged.set(true)
}
override fun lastCaptureSuccessful(): Boolean {
return lastCaptureSuccessful.get()
}
override fun emitLastScreenshot() {
if (!frameInFlight.get() && lastCaptureSuccessful() && !screenshot.isRecycled) {
screenshotRecorderCallback?.onScreenshotRecorded(screenshot)
}
}
override fun close() {
isClosed.set(true)
unstableCaptures.set(0)
if (!frameInFlight.get()) {
scheduleCleanup()
}
}
private fun finishFrame() {
frameInFlight.set(false)
if (isClosed.get()) {
scheduleCleanup()
}
}
private fun scheduleCleanup() {
if (!cleanupScheduled.compareAndSet(false, true)) {
return
}
executor.submit(
ReplayRunnable(
"PixelCopyStrategy.close",
{
if (!screenshot.isRecycled) {
synchronized(screenshot) {
if (!screenshot.isRecycled) {
screenshot.recycle()
}
}
}
maskRenderer.close()
},
)
)
}
}
/**
* Composites [sourceBitmap] (a SurfaceView capture) onto [destCanvas] (wrapping the recording
* screenshot) using [destPaint] (expected to have DST_OVER xfermode), so the SurfaceView content
* draws _behind_ existing Window content — filling the transparent holes the Window PixelCopy
* leaves where SurfaceViews are.
*
* Extracted for testability — the compositing is pure drawing logic that can be driven with
* hand-built bitmaps, while the surrounding [PixelCopyStrategy.captureSurfaceViews] flow depends on
* a real SurfaceView producer that Robolectric cannot provide.
*/
internal fun compositeSurfaceViewInto(
destCanvas: Canvas,
destPaint: Paint,
tmpSrc: Rect,
tmpDst: RectF,
sourceBitmap: Bitmap,
sourceX: Int,
sourceY: Int,
windowX: Int,
windowY: Int,
scaleFactorX: Float,
scaleFactorY: Float,
) {
val left = (sourceX - windowX) * scaleFactorX
val top = (sourceY - windowY) * scaleFactorY
tmpSrc.set(0, 0, sourceBitmap.width, sourceBitmap.height)
tmpDst.set(
left,
top,
left + sourceBitmap.width * scaleFactorX,
top + sourceBitmap.height * scaleFactorY,
)
destCanvas.drawBitmap(sourceBitmap, tmpSrc, tmpDst, destPaint)
}