Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
### Internal

- Add a `WebView.loadUrl` adapter for automatic WebView trace propagation in the Sentry Android Gradle Plugin ([#6592](https://github.com/getsentry/sentry-java/pull/6592))
- Session Replay: Add hooks for hybrid SDKs, such as `sentry-unity`, to record replays with their own recorder and hand in frames as raw pixels ([#6829](https://github.com/getsentry/sentry-java/pull/6829))

### Dependencies

Expand Down
12 changes: 11 additions & 1 deletion sentry-android-replay/api/sentry-android-replay.api
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,11 @@ public final class io/sentry/android/replay/ReplayCache : java/io/Closeable {
public static synthetic fun createVideoOf$default (Lio/sentry/android/replay/ReplayCache;JJIIIIILjava/io/File;ILjava/lang/Object;)Lio/sentry/android/replay/GeneratedVideo;
}

public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConnectionStatusProvider$IConnectionStatusObserver, io/sentry/Integration, io/sentry/ReplayController, io/sentry/android/replay/ScreenshotRecorderCallback, io/sentry/android/replay/WindowCallback, io/sentry/android/replay/gestures/TouchRecorderCallback, io/sentry/transport/RateLimiter$IRateLimitObserver, java/io/Closeable {
public abstract interface class io/sentry/android/replay/ReplayFrameReceiver {
public abstract fun onFrame ([BII)V
}

public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConnectionStatusProvider$IConnectionStatusObserver, io/sentry/Integration, io/sentry/ReplayController, io/sentry/android/replay/ReplayFrameReceiver, io/sentry/android/replay/ScreenshotRecorderCallback, io/sentry/android/replay/WindowCallback, io/sentry/android/replay/gestures/TouchRecorderCallback, io/sentry/transport/RateLimiter$IRateLimitObserver, java/io/Closeable {
public static final field $stable I
public fun <init> (Landroid/content/Context;Lio/sentry/transport/ICurrentDateProvider;)V
public fun <init> (Landroid/content/Context;Lio/sentry/transport/ICurrentDateProvider;Lkotlin/jvm/functions/Function0;Lkotlin/jvm/functions/Function1;)V
Expand All @@ -73,6 +77,7 @@ public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConne
public fun onAppSessionEnded ()V
public final fun onConfigurationChanged (Lio/sentry/android/replay/ScreenshotRecorderConfig;)V
public fun onConnectionStatusChanged (Lio/sentry/IConnectionStatusProvider$ConnectionStatus;)V
public fun onFrame ([BII)V
public fun onRateLimitChanged (Lio/sentry/transport/RateLimiter;)V
public fun onScreenshotRecorded (Landroid/graphics/Bitmap;)V
public fun onScreenshotRecorded (Ljava/io/File;J)V
Expand All @@ -86,11 +91,16 @@ public final class io/sentry/android/replay/ReplayIntegration : io/sentry/IConne
public fun resume ()V
public fun resumeTouchTracking ()V
public fun setBreadcrumbConverter (Lio/sentry/ReplayBreadcrumbConverter;)V
public final fun setRecorderFactory (Lio/sentry/android/replay/ReplayRecorderFactory;)V
public fun start ()V
public fun startBuffering ()V
public fun stop ()V
}

public abstract interface class io/sentry/android/replay/ReplayRecorderFactory {
public abstract fun create (Lio/sentry/android/replay/ReplayFrameReceiver;)Lio/sentry/android/replay/Recorder;
}

public abstract interface class io/sentry/android/replay/ScreenshotRecorderCallback {
public abstract fun onScreenshotRecorded (Landroid/graphics/Bitmap;)V
public abstract fun onScreenshotRecorded (Ljava/io/File;J)V
Expand Down
3 changes: 2 additions & 1 deletion sentry-android-replay/detekt-baseline.xml
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
<ID>FunctionParameterNaming:PixelCopyStrategyTest.kt$DeferredWindowPixelCopyShadow.Companion$_source: Window</ID>
<ID>LargeClass:CanvasStrategy.kt$TextIgnoringDelegateCanvas : Canvas</ID>
<ID>LargeClass:ReplayCacheTest.kt$ReplayCacheTest</ID>
<ID>LargeClass:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackReplayFrameReceiverTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback</ID>
<ID>LargeClass:ReplayIntegrationTest.kt$ReplayIntegrationTest</ID>
<ID>LongMethod:CaptureStrategy.kt$CaptureStrategy.Companion$@Suppress("NewApi") private fun buildReplay( options: SentryOptions, video: File, currentReplayId: SentryId, segmentTimestamp: Date, segmentId: Int, height: Int, width: Int, frameCount: Int, frameRate: Int, videoDuration: Long, replayType: ReplayType, screenAtStart: String?, breadcrumbs: List&lt;Breadcrumb>, events: Deque&lt;RRWebEvent>, traceIds: List&lt;String>, segmentNames: List&lt;String>, ): ReplaySegment</ID>
<ID>LongMethod:ComposeViewHierarchyNode.kt$ComposeViewHierarchyNode$private fun fromComposeNode( node: LayoutNode, parent: ViewHierarchyNode?, distance: Int, isComposeRoot: Boolean, options: SentryMaskingOptions, logger: ILogger, ): ViewHierarchyNode?</ID>
Expand Down Expand Up @@ -154,7 +155,7 @@
<ID>TooManyFunctions:CanvasStrategy.kt$TextIgnoringDelegateCanvas : Canvas</ID>
<ID>TooManyFunctions:CaptureStrategy.kt$CaptureStrategy</ID>
<ID>TooManyFunctions:PixelCopyStrategy.kt$PixelCopyStrategy : ScreenshotStrategy</ID>
<ID>TooManyFunctions:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback</ID>
<ID>TooManyFunctions:ReplayIntegration.kt$ReplayIntegration : IntegrationCloseableScreenshotRecorderCallbackReplayFrameReceiverTouchRecorderCallbackReplayControllerIConnectionStatusObserverIRateLimitObserverWindowCallback</ID>
<ID>TooManyFunctions:WindowRecorder.kt$WindowRecorder : RecorderOnRootViewsChangedListenerExecutorProvider</ID>
<ID>UnusedPrivateProperty:DebugOverlayDrawable.kt$DebugOverlayDrawable$private val padding = 6f</ID>
<ID>UseCheckOrError:ReplayShadowMediaCodec.kt$ReplayShadowMediaCodec$throw IllegalStateException("Simulated codec start failure")</ID>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
import io.sentry.util.Random
import java.io.Closeable
import java.io.File
import java.nio.ByteBuffer
import java.util.Date
import java.util.LinkedList
import java.util.concurrent.CopyOnWriteArraySet
Expand All @@ -66,6 +67,7 @@
import java.util.concurrent.TimeUnit.MILLISECONDS
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.atomic.AtomicReference
import org.jetbrains.annotations.ApiStatus

public class ReplayIntegration(
private val context: Context,
Expand All @@ -76,6 +78,7 @@
Integration,
Closeable,
ScreenshotRecorderCallback,
ReplayFrameReceiver,
Comment thread
bitsandfoxes marked this conversation as resolved.
Resolved
TouchRecorderCallback,
ReplayController,
IConnectionStatusObserver,
Expand All @@ -91,6 +94,8 @@
// read after the replay stopped, so the startup cleanup of previous replays must keep them.
// Shared across instances, because a second SDK init registers a new ReplayIntegration.
val replayIdsOfThisProcess = CopyOnWriteArraySet<String>()

private const val RGBA_BYTES_PER_PIXEL = 4
}

// needed for the Java's call site
Expand Down Expand Up @@ -118,6 +123,9 @@
private lateinit var options: SentryOptions
private var scopes: IScopes? = null
private var recorder: Recorder? = null
@Volatile private var recorderFactory: ReplayRecorderFactory? = null
// Only the replay executor, where the capture strategies store frames, touches it.
private var frameBitmap: Bitmap? = null
private var gestureRecorder: GestureRecorder? = null
private val random = ThreadLocal<Random>()
internal val rootViewsSpy by lazy { RootViewsSpy.install() }
Expand Down Expand Up @@ -150,6 +158,19 @@
private var gestureRecorderProvider: (() -> GestureRecorder)? = null
private val state = AtomicReference(ReplayState())

/**
* Sets the factory of the [Recorder] that captures frames in place of the replay's own one, which
* draws the app's views. It takes effect when this integration registers, so it must be set
* before, e.g. in the options configuration callback of `SentryAndroid.init`. The recorder hands
* its frames to [onFrame]. Nothing reports the frame size for it, so once the replay is recording
* the Hybrid SDK must call [onConfigurationChanged] with its frame size, and every frame must
* match the config's `recordingWidth` x `recordingHeight`: until then no segment is sent.
*/
@ApiStatus.Internal
public fun setRecorderFactory(factory: ReplayRecorderFactory?) {
recorderFactory = factory
}

override fun register(scopes: IScopes, options: SentryOptions) {
this.options = options

Expand All @@ -161,6 +182,7 @@
this.scopes = scopes
recorder =
recorderProvider?.invoke()
?: recorderFactory?.create(this)
?: WindowRecorder(options, this, this, mainLooperHandler, replayExecutor)
gestureRecorder = gestureRecorderProvider?.invoke() ?: GestureRecorder(options, this)
isEnabled.set(true)
Expand Down Expand Up @@ -478,23 +500,85 @@
var screen: String? = null
scopes?.configureScope { screen = it.screen?.substringAfterLast('.') }
state.get().captureStrategy?.onScreenshotRecorded(bitmap) { frameTimeStamp ->
val observer = options.sessionReplay.frameObserver
if (observer != null) {
val copy = bitmap.copy(bitmap.config!!, false)
if (copy != null) {
try {
val hint = Hint()
hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy)
observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen)
} catch (e: Throwable) {
options.logger.log(ERROR, "Error in ReplayFrameObserver", e)
copy.recycle()
}
addBitmapFrame(this, bitmap, frameTimeStamp, screen)
}
enqueueOnMainThread { checkCanRecord() }
}

/**
* Records a frame the recorder of [setRecorderFactory] captured. The calling thread only hands it
* over: the pixels are copied into a bitmap and stored on the replay's own thread. A frame that
* arrives while the replay is stopped or paused is dropped.
*/
override fun onFrame(pixels: ByteArray, width: Int, height: Int) {
val current = state.get()
if (current.lifecycleState != STARTED && current.lifecycleState != RESUMED) {
return
}
val captureStrategy = current.captureStrategy ?: return
if (
width <= 0 ||
height <= 0 ||
pixels.size.toLong() != width.toLong() * height * RGBA_BYTES_PER_PIXEL
) {
options.logger.log(
ERROR,
"Session replay dropped a frame of %d bytes, which doesn't hold %dx%d RGBA pixels",
pixels.size,
width,
height,
)
return
}

var screen: String? = null
scopes?.configureScope { screen = it.screen?.substringAfterLast('.') }
captureStrategy.onScreenshotRecorded { frameTimeStamp ->
addBitmapFrame(this, fillFrameBitmap(pixels, width, height), frameTimeStamp, screen)
}
enqueueOnMainThread { checkCanRecord() }
}

/** Copies [pixels] into [frameBitmap], which is reused while the frame size stays the same. */
private fun fillFrameBitmap(pixels: ByteArray, width: Int, height: Int): Bitmap {
val bitmap =
frameBitmap?.takeIf { it.width == width && it.height == height }
?: newFrameBitmap(width, height)
bitmap.copyPixelsFromBuffer(ByteBuffer.wrap(pixels))
return bitmap
}

Check warning on line 549 in sentry-android-replay/src/main/java/io/sentry/android/replay/ReplayIntegration.kt

View check run for this annotation

@sentry/warden / warden: code-review

onFrame RGBA pixels are stored with R/B swapped on Android

Documented RGBA frames are written with copyPixelsFromBuffer into an ARGB_8888 bitmap, so on little-endian Android devices red and blue channels are swapped in every hybrid replay frame.

private fun newFrameBitmap(width: Int, height: Int): Bitmap {
frameBitmap?.recycle()
// A failed allocation must not leave the recycled bitmap for a later frame of the old size.
frameBitmap = null
return Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888).also {
it.setHasAlpha(false)
frameBitmap = it
}
}

private fun addBitmapFrame(
cache: ReplayCache,
bitmap: Bitmap,
frameTimeStamp: Long,
screen: String?,
) {
val observer = options.sessionReplay.frameObserver
if (observer != null) {
val copy = bitmap.copy(bitmap.config!!, false)
if (copy != null) {
try {
val hint = Hint()
hint.set(TypeCheckHint.REPLAY_FRAME_BITMAP, copy)
observer.onMaskedFrameCaptured(hint, frameTimeStamp, screen)
} catch (e: Throwable) {
options.logger.log(ERROR, "Error in ReplayFrameObserver", e)
copy.recycle()
}
}
addFrame(bitmap, frameTimeStamp, screen)
}
enqueueOnMainThread { checkCanRecord() }
cache.addFrame(bitmap, frameTimeStamp, screen)
}

override fun onScreenshotRecorded(screenshot: File, frameTimestamp: Long) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package io.sentry.android.replay

import org.jetbrains.annotations.ApiStatus

/**
* Creates the [Recorder] that captures session replay frames in place of the replay's own one.
* Meant for Hybrid SDKs that capture frames themselves.
*/
@ApiStatus.Internal
public fun interface ReplayRecorderFactory {
/**
* @param frames takes the frames the returned recorder captures
* @return the recorder session replay starts, pauses, resumes and stops
*/
public fun create(frames: ReplayFrameReceiver): Recorder
}

/** Takes session replay frames that a [Recorder] captured as raw pixels. */
@ApiStatus.Internal
public interface ReplayFrameReceiver {
/**
* Takes one frame. The receiver owns [pixels] from then on: the caller must not change the array
* after the call. The frame must be [ScreenshotRecorderConfig.recordingWidth] x
* [ScreenshotRecorderConfig.recordingHeight] of the config last passed to
* [ReplayIntegration.onConfigurationChanged], or it is cropped or padded in the video.
*
* @param pixels [width] * [height] * 4 bytes, in RGBA order, top row first. Alpha is ignored.
* @param width the frame's width in pixels
* @param height the frame's height in pixels
*/
public fun onFrame(pixels: ByteArray, width: Int, height: Int)
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.CompressFormat.JPEG
import android.graphics.Bitmap.Config.ARGB_8888
import android.graphics.Color
import android.os.Looper
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
Expand Down Expand Up @@ -88,6 +89,7 @@ import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.robolectric.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode

@RunWith(AndroidJUnit4::class)
@Config(sdk = [30], shadows = [ReplayShadowMediaCodec::class])
Expand Down Expand Up @@ -1976,6 +1978,78 @@ class ReplayIntegrationTest {
assertTrue(replay.persistingExecutor.isShutdown)
}

@Test
fun `registers the recorder of the recorder factory, which hands frames to the integration`() {
val recorder = mock<Recorder>()
var receiver: ReplayFrameReceiver? = null
val replay = fixture.getSut(context)
replay.setRecorderFactory { frames ->
receiver = frames
recorder
}

replay.register(fixture.scopes, fixture.options)
replay.start()

assertThat(receiver).isSameInstanceAs(replay)
verify(recorder).start()
}

@Test
@GraphicsMode(GraphicsMode.Mode.NATIVE)
fun `onFrame stores the pixels as a frame of their size`() {
val frames = mutableListOf<Bitmap>()
whenever(fixture.replayCache.addFrame(any<Bitmap>(), any(), anyOrNull())).doAnswer {
val bitmap = it.arguments[0] as Bitmap
frames += bitmap.copy(bitmap.config!!, false)
}
val captureStrategy =
mock<CaptureStrategy> {
doAnswer {
((it.arguments[1] as ReplayCache.(frameTimestamp: Long) -> Unit)).invoke(
fixture.replayCache,
1720693523997,
)
}
.whenever(mock)
.onScreenshotRecorded(anyOrNull<Bitmap>(), any())
}
val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy })
fixture.scopes.configureScope { it.screen = "MainActivity" }
replay.register(fixture.scopes, fixture.options)
replay.start()

// Red and blue equal in both colours: Robolectric's native bitmaps use the host's byte order.
val green = byteArrayOf(0, -1, 0, -1)
val white = byteArrayOf(-1, -1, -1, -1)
replay.onFrame(green + white, 2, 1)
replay.onFrame(white + green, 1, 2)

verify(fixture.replayCache, times(2))
.addFrame(any<Bitmap>(), eq(1720693523997), eq("MainActivity"))
assertThat(frames.map { it.width to it.height }).containsExactly(2 to 1, 1 to 2).inOrder()
assertThat(frames[0].getPixel(0, 0)).isEqualTo(Color.GREEN)
assertThat(frames[0].getPixel(1, 0)).isEqualTo(Color.WHITE)
assertThat(frames[1].getPixel(0, 0)).isEqualTo(Color.WHITE)
assertThat(frames[1].getPixel(0, 1)).isEqualTo(Color.GREEN)
}

@Test
fun `onFrame drops frames while stopped or paused, or of the wrong size`() {
val captureStrategy = mock<CaptureStrategy>()
val replay = fixture.getSut(context, replayCaptureStrategyProvider = { captureStrategy })
replay.register(fixture.scopes, fixture.options)

replay.onFrame(ByteArray(8), 2, 1)
replay.start()
replay.onFrame(ByteArray(4), 2, 1)
replay.onFrame(ByteArray(0), 0, 0)
replay.pause()
replay.onFrame(ByteArray(8), 2, 1)

verify(captureStrategy, never()).onScreenshotRecorded(anyOrNull<Bitmap>(), any())
}

private fun getSessionCaptureStrategy(options: SentryOptions): SessionCaptureStrategy =
SessionCaptureStrategy(
options,
Expand Down
Loading