Capture initial screenshot when starting frame timing trace (#55720)

Summary:
Pull Request resolved: https://github.com/facebook/react-native/pull/55720

Changelog: [internal]

When tracing starts, the frame metrics listener only fires when new frames are rendered. This means if no UI changes occur during a trace, no screenshots are captured. This also causes the initial state of the UI to be missing from the trace.

This change captures an initial screenshot immediately when `start()` is called, ensuring there's always at least one frame recorded at the beginning of a trace regardless of whether UI changes occur.

The implementation also refactors the frame emission logic into a shared `emitFrameTiming()` method to eliminate code duplication between the frame metrics listener and the initial capture.

Reviewed By: huntie

Differential Revision: D94223073

fbshipit-source-id: b84edae7caa15e24b437ef151e9a6c42916817d3
This commit is contained in:
Rubén Norte authored and meta-codesync[bot] committed 2026-02-24 10:46:05 -08:00
1 parent f31bb88aae
commit 863f5c0fd1
1 file changed
+25 -17
@@ -38,23 +38,7 @@ internal class FrameTimingsObserver(
Window.OnFrameMetricsAvailableListener { _, frameMetrics, _dropCount ->
val beginTimestamp = frameMetrics.getMetric(FrameMetrics.VSYNC_TIMESTAMP)
val endTimestamp = beginTimestamp + frameMetrics.getMetric(FrameMetrics.TOTAL_DURATION)
val frameId = frameCounter++
val threadId = Process.myTid()
CoroutineScope(Dispatchers.Default).launch {
val screenshot = if (screenshotsEnabled) captureScreenshot() else null
onFrameTimingSequence(
FrameTimingSequence(
frameId,
threadId,
beginTimestamp,
endTimestamp,
screenshot,
)
)
}
emitFrameTiming(beginTimestamp, endTimestamp)
}
private suspend fun captureScreenshot(): String? = suspendCoroutine { continuation ->
@@ -123,9 +107,33 @@ internal class FrameTimingsObserver(
return
}
// Capture initial screenshot to ensure there's always at least one frame
// recorded at the start of tracing, even if no UI changes occur
val timestamp = System.nanoTime()
emitFrameTiming(timestamp, timestamp)
window.addOnFrameMetricsAvailableListener(frameMetricsListener, handler)
}
private fun emitFrameTiming(beginTimestamp: Long, endTimestamp: Long) {
val frameId = frameCounter++
val threadId = Process.myTid()
CoroutineScope(Dispatchers.Default).launch {
val screenshot = if (screenshotsEnabled) captureScreenshot() else null
onFrameTimingSequence(
FrameTimingSequence(
frameId,
threadId,
beginTimestamp,
endTimestamp,
screenshot,
)
)
}
}
fun stop() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
return