• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <atomic>
20 #include <chrono>
21 #include <deque>
22 #include <memory>
23 #include <mutex>
24 #include <optional>
25 #include <string>
26 
27 #include <gui/ISurfaceComposer.h>
28 #include <gui/JankInfo.h>
29 #include <gui/LayerMetadata.h>
30 #include <perfetto/trace/android/frame_timeline_event.pbzero.h>
31 #include <perfetto/tracing.h>
32 #include <ui/FenceTime.h>
33 #include <utils/RefBase.h>
34 #include <utils/String16.h>
35 #include <utils/Timers.h>
36 #include <utils/Vector.h>
37 
38 #include <scheduler/Fps.h>
39 
40 #include "../TimeStats/TimeStats.h"
41 
42 namespace android::frametimeline {
43 
44 class FrameTimelineTest;
45 
46 using namespace std::chrono_literals;
47 
48 // Metadata indicating how the frame was presented w.r.t expected present time.
49 enum class FramePresentMetadata : int8_t {
50     // Frame was presented on time
51     OnTimePresent,
52     // Frame was presented late
53     LatePresent,
54     // Frame was presented early
55     EarlyPresent,
56     // Unknown/initial state
57     UnknownPresent,
58 };
59 
60 // Metadata comparing the frame's actual finish time to the expected deadline.
61 enum class FrameReadyMetadata : int8_t {
62     // App/SF finished on time. Early finish is treated as on time since the goal of any component
63     // is to finish before the deadline.
64     OnTimeFinish,
65     // App/SF finished work later than expected
66     LateFinish,
67     // Unknown/initial state
68     UnknownFinish,
69 };
70 
71 // Metadata comparing the frame's actual start time to the expected start time.
72 enum class FrameStartMetadata : int8_t {
73     // App/SF started on time
74     OnTimeStart,
75     // App/SF started later than expected
76     LateStart,
77     // App/SF started earlier than expected
78     EarlyStart,
79     // Unknown/initial state
80     UnknownStart,
81 };
82 
83 /*
84  * Collection of timestamps that can be used for both predictions and actual times.
85  */
86 struct TimelineItem {
87     TimelineItem(const nsecs_t startTime = 0, const nsecs_t endTime = 0,
88                  const nsecs_t presentTime = 0, const nsecs_t desiredPresentTime = 0)
startTimeTimelineItem89           : startTime(startTime),
90             endTime(endTime),
91             presentTime(presentTime),
92             desiredPresentTime(desiredPresentTime) {}
93 
94     nsecs_t startTime;
95     nsecs_t endTime;
96     nsecs_t presentTime;
97     nsecs_t desiredPresentTime;
98 
99     bool operator==(const TimelineItem& other) const {
100         return startTime == other.startTime && endTime == other.endTime &&
101                 presentTime == other.presentTime && desiredPresentTime != other.desiredPresentTime;
102     }
103 
104     bool operator!=(const TimelineItem& other) const { return !(*this == other); }
105 };
106 
107 struct JankClassificationThresholds {
108     // The various thresholds for App and SF. If the actual timestamp falls within the threshold
109     // compared to prediction, we treat it as on time.
110     nsecs_t presentThresholdLegacy =
111             std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
112     nsecs_t presentThresholdExtended =
113             std::chrono::duration_cast<std::chrono::nanoseconds>(4ms).count();
114     nsecs_t deadlineThreshold = std::chrono::duration_cast<std::chrono::nanoseconds>(0ms).count();
115     nsecs_t startThreshold = std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
116 };
117 
118 /*
119  * TokenManager generates a running number token for a set of predictions made by VsyncPredictor. It
120  * saves these predictions for a short period of time and returns the predictions for a given token,
121  * if it hasn't expired.
122  */
123 class TokenManager {
124 public:
125     virtual ~TokenManager() = default;
126 
127     // Generates a token for the given set of predictions. Stores the predictions for 120ms and
128     // destroys it later.
129     virtual int64_t generateTokenForPredictions(TimelineItem&& prediction) = 0;
130 
131     // Returns the stored predictions for a given token, if the predictions haven't expired.
132     virtual std::optional<TimelineItem> getPredictionsForToken(int64_t token) const = 0;
133 };
134 
135 enum class PredictionState {
136     Valid,   // Predictions obtained successfully from the TokenManager
137     Expired, // TokenManager no longer has the predictions
138     None,    // Predictions are either not present or didn't come from TokenManager
139 };
140 
141 /*
142  * Trace cookie is used to send start and end timestamps of <Surface/Display>Frames separately
143  * without needing to resend all the other information. We send all info to perfetto, along with a
144  * new cookie, in the start of a frame. For the corresponding end, we just send the same cookie.
145  * This helps in reducing the amount of data emitted by the producer.
146  */
147 class TraceCookieCounter {
148 public:
149     int64_t getCookieForTracing();
150 
151 private:
152     // Friend class for testing
153     friend class android::frametimeline::FrameTimelineTest;
154 
155     std::atomic<int64_t> mTraceCookie = 0;
156 };
157 
158 class SurfaceFrame {
159 public:
160     enum class PresentState {
161         Presented, // Buffer was latched and presented by SurfaceFlinger
162         Dropped,   // Buffer was dropped by SurfaceFlinger
163         Unknown,   // Initial state, SurfaceFlinger hasn't seen this buffer yet
164     };
165 
166     // Only FrameTimeline can construct a SurfaceFrame as it provides Predictions(through
167     // TokenManager), Thresholds and TimeStats pointer.
168     SurfaceFrame(const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
169                  int32_t layerId, std::string layerName, std::string debugName,
170                  PredictionState predictionState, TimelineItem&& predictions,
171                  std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
172                  TraceCookieCounter* traceCookieCounter, bool isBuffer, GameMode);
173     ~SurfaceFrame() = default;
174 
175     bool isSelfJanky() const;
176 
177     // Returns std::nullopt if the frame hasn't been classified yet.
178     // Used by both SF and FrameTimeline.
179     std::optional<int32_t> getJankType() const;
180     std::optional<JankSeverityType> getJankSeverityType() const;
181 
182     // Functions called by SF
getToken()183     int64_t getToken() const { return mToken; };
getInputEventId()184     int32_t getInputEventId() const { return mInputEventId; };
getPredictions()185     TimelineItem getPredictions() const { return mPredictions; };
186     // Actual timestamps of the app are set individually at different functions.
187     // Start time (if the app provides) and Queue time are accessible after queueing the frame,
188     // whereas Acquire Fence time is available only during latch. Drop time is available at the time
189     // the buffer was dropped.
190     void setActualStartTime(nsecs_t actualStartTime);
191     void setActualQueueTime(nsecs_t actualQueueTime);
192     void setAcquireFenceTime(nsecs_t acquireFenceTime);
193     void setDesiredPresentTime(nsecs_t desiredPresentTime);
194     void setDropTime(nsecs_t dropTime);
195     void setPresentState(PresentState presentState, nsecs_t lastLatchTime = 0);
196     void setRenderRate(Fps renderRate);
197     // Return the render rate if it exists, otherwise returns the DisplayFrame's render rate.
198     Fps getRenderRate() const;
199     void setGpuComposition();
200 
201     // When a bufferless SurfaceFrame is promoted to a buffer SurfaceFrame, we also have to update
202     // isBuffer.
203     void promoteToBuffer();
204 
205     // Functions called by FrameTimeline
206     // BaseTime is the smallest timestamp in this SurfaceFrame.
207     // Used for dumping all timestamps relative to the oldest, making it easy to read.
208     nsecs_t getBaseTime() const;
209     // Sets the actual present time, appropriate metadata and classifies the jank.
210     // displayRefreshRate, displayDeadlineDelta, and displayPresentDelta are propagated from the
211     // display frame.
212     void onPresent(nsecs_t presentTime, int32_t displayFrameJankType, Fps refreshRate,
213                    Fps displayFrameRenderRate, nsecs_t displayDeadlineDelta,
214                    nsecs_t displayPresentDelta);
215     // Sets the frame as none janky as there was no real display frame.
216     void onCommitNotComposited(Fps refreshRate, Fps displayFrameRenderRate);
217     // All the timestamps are dumped relative to the baseTime
218     void dump(std::string& result, const std::string& indent, nsecs_t baseTime) const;
219     // Dumps only the layer, token, is buffer, jank metadata, prediction and present states.
220     std::string miniDump() const;
221     // Emits a packet for perfetto tracing. The function body will be executed only if tracing is
222     // enabled. The displayFrameToken is needed to link the SurfaceFrame to the corresponding
223     // DisplayFrame at the trace processor side. monoBootOffset is the difference
224     // between SYSTEM_TIME_BOOTTIME and SYSTEM_TIME_MONOTONIC.
225     void trace(int64_t displayFrameToken, nsecs_t monoBootOffset,
226                bool filterFramesBeforeTraceStarts) const;
227 
228     // Getter functions used only by FrameTimelineTests and SurfaceFrame internally
229     TimelineItem getActuals() const;
getOwnerPid()230     pid_t getOwnerPid() const { return mOwnerPid; };
getLayerId()231     int32_t getLayerId() const { return mLayerId; };
232     PredictionState getPredictionState() const;
233     PresentState getPresentState() const;
234     FrameReadyMetadata getFrameReadyMetadata() const;
235     FramePresentMetadata getFramePresentMetadata() const;
236     nsecs_t getDropTime() const;
237     bool getIsBuffer() const;
238 
239     // For prediction expired frames, this delta is subtracted from the actual end time to get a
240     // start time decent enough to see in traces.
241     // TODO(b/172587309): Remove this when we have actual start times.
242     static constexpr nsecs_t kPredictionExpiredStartTimeDelta =
243             std::chrono::duration_cast<std::chrono::nanoseconds>(2ms).count();
244 
245 private:
246     void tracePredictions(int64_t displayFrameToken, nsecs_t monoBootOffset,
247                           bool filterFramesBeforeTraceStarts) const;
248     void traceActuals(int64_t displayFrameToken, nsecs_t monoBootOffset,
249                       bool filterFramesBeforeTraceStarts) const;
250     void classifyJankLocked(int32_t displayFrameJankType, const Fps& refreshRate,
251                             Fps displayFrameRenderRate, nsecs_t* outDeadlineDelta) REQUIRES(mMutex);
252 
253     const int64_t mToken;
254     const int32_t mInputEventId;
255     const pid_t mOwnerPid;
256     const uid_t mOwnerUid;
257     const std::string mLayerName;
258     const std::string mDebugName;
259     const int32_t mLayerId;
260     PresentState mPresentState GUARDED_BY(mMutex);
261     const PredictionState mPredictionState;
262     const TimelineItem mPredictions;
263     TimelineItem mActuals GUARDED_BY(mMutex);
264     std::shared_ptr<TimeStats> mTimeStats;
265     const JankClassificationThresholds mJankClassificationThresholds;
266     nsecs_t mActualQueueTime GUARDED_BY(mMutex) = 0;
267     nsecs_t mDropTime GUARDED_BY(mMutex) = 0;
268     mutable std::mutex mMutex;
269     // Bitmask for the type of jank
270     int32_t mJankType GUARDED_BY(mMutex) = JankType::None;
271     // Enum for the severity of jank
272     JankSeverityType mJankSeverityType GUARDED_BY(mMutex) = JankSeverityType::None;
273     // Indicates if this frame was composited by the GPU or not
274     bool mGpuComposition GUARDED_BY(mMutex) = false;
275     // Refresh rate for this frame.
276     Fps mDisplayFrameRenderRate GUARDED_BY(mMutex);
277     // Rendering rate for this frame.
278     std::optional<Fps> mRenderRate GUARDED_BY(mMutex);
279     // Enum for the type of present
280     FramePresentMetadata mFramePresentMetadata GUARDED_BY(mMutex) =
281             FramePresentMetadata::UnknownPresent;
282     // Enum for the type of finish
283     FrameReadyMetadata mFrameReadyMetadata GUARDED_BY(mMutex) = FrameReadyMetadata::UnknownFinish;
284     // Time when the previous buffer from the same layer was latched by SF. This is used in checking
285     // for BufferStuffing where the current buffer is expected to be ready but the previous buffer
286     // was latched instead.
287     nsecs_t mLastLatchTime GUARDED_BY(mMutex) = 0;
288     // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto. Using a
289     // reference here because the counter is owned by FrameTimeline, which outlives SurfaceFrame.
290     TraceCookieCounter& mTraceCookieCounter;
291     // Tells if the SurfaceFrame is representing a buffer or a transaction without a
292     // buffer(animations)
293     bool mIsBuffer;
294     // GameMode from the layer. Used in metrics.
295     GameMode mGameMode = GameMode::Unsupported;
296 };
297 
298 /*
299  * Maintains a history of SurfaceFrames grouped together by the vsync time in which they were
300  * presented
301  */
302 class FrameTimeline {
303 public:
304     virtual ~FrameTimeline() = default;
305     virtual TokenManager* getTokenManager() = 0;
306 
307     // Initializes the Perfetto DataSource that emits DisplayFrame and SurfaceFrame events. Test
308     // classes can avoid double registration by mocking this function.
309     virtual void onBootFinished() = 0;
310 
311     // Create a new surface frame, set the predictions based on a token and return it to the caller.
312     // Debug name is the human-readable debugging string for dumpsys.
313     virtual std::shared_ptr<SurfaceFrame> createSurfaceFrameForToken(
314             const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
315             int32_t layerId, std::string layerName, std::string debugName, bool isBuffer,
316             GameMode) = 0;
317 
318     // Adds a new SurfaceFrame to the current DisplayFrame. Frames from multiple layers can be
319     // composited into one display frame.
320     virtual void addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame) = 0;
321 
322     // The first function called by SF for the current DisplayFrame. Fetches SF predictions based on
323     // the token and sets the actualSfWakeTime for the current DisplayFrame.
324     virtual void setSfWakeUp(int64_t token, nsecs_t wakeupTime, Fps refreshRate,
325                              Fps renderRate) = 0;
326 
327     // Sets the sfPresentTime and finalizes the current DisplayFrame. Tracks the
328     // given present fence until it's signaled, and updates the present timestamps of all presented
329     // SurfaceFrames in that vsync. If a gpuFence was also provided, its tracked in the
330     // corresponding DisplayFrame.
331     virtual void setSfPresent(nsecs_t sfPresentTime, const std::shared_ptr<FenceTime>& presentFence,
332                               const std::shared_ptr<FenceTime>& gpuFence) = 0;
333 
334     // Tells FrameTimeline that a frame was committed but not composited. This is used to flush
335     // all the associated surface frames.
336     virtual void onCommitNotComposited() = 0;
337 
338     // Args:
339     // -jank : Dumps only the Display Frames that are either janky themselves
340     //         or contain janky Surface Frames.
341     // -all : Dumps the entire list of DisplayFrames and the SurfaceFrames contained within
342     virtual void parseArgs(const Vector<String16>& args, std::string& result) = 0;
343 
344     // Sets the max number of display frames that can be stored. Called by SF backdoor.
345     virtual void setMaxDisplayFrames(uint32_t size) = 0;
346 
347     // Computes the historical fps for the provided set of layer IDs
348     // The fps is compted from the linear timeline of present timestamps for DisplayFrames
349     // containing at least one layer ID.
350     virtual float computeFps(const std::unordered_set<int32_t>& layerIds) = 0;
351 
352     // Supports the legacy FrameStats interface
353     virtual void generateFrameStats(int32_t layer, size_t count, FrameStats* outStats) const = 0;
354 
355     // Restores the max number of display frames to default. Called by SF backdoor.
356     virtual void reset() = 0;
357 };
358 
359 namespace impl {
360 
361 class TokenManager : public android::frametimeline::TokenManager {
362 public:
TokenManager()363     TokenManager() : mCurrentToken(FrameTimelineInfo::INVALID_VSYNC_ID + 1) {}
364     ~TokenManager() = default;
365 
366     int64_t generateTokenForPredictions(TimelineItem&& predictions) override;
367     std::optional<TimelineItem> getPredictionsForToken(int64_t token) const override;
368 
369 private:
370     // Friend class for testing
371     friend class android::frametimeline::FrameTimelineTest;
372 
373     void flushTokens(nsecs_t flushTime) REQUIRES(mMutex);
374 
375     std::map<int64_t, TimelineItem> mPredictions GUARDED_BY(mMutex);
376     int64_t mCurrentToken GUARDED_BY(mMutex);
377     mutable std::mutex mMutex;
378     static constexpr size_t kMaxTokens = 500;
379 };
380 
381 class FrameTimeline : public android::frametimeline::FrameTimeline {
382 public:
383     class FrameTimelineDataSource : public perfetto::DataSource<FrameTimelineDataSource> {
384     public:
getStartTime()385         nsecs_t getStartTime() const { return mTraceStartTime; }
386 
387     private:
OnSetup(const SetupArgs &)388         void OnSetup(const SetupArgs&) override {};
OnStart(const StartArgs &)389         void OnStart(const StartArgs&) override { mTraceStartTime = systemTime(); };
OnStop(const StopArgs &)390         void OnStop(const StopArgs&) override {};
391 
392         nsecs_t mTraceStartTime = 0;
393     };
394 
395     /*
396      * DisplayFrame should be used only internally within FrameTimeline. All members and methods are
397      * guarded by FrameTimeline's mMutex.
398      */
399     class DisplayFrame {
400     public:
401         DisplayFrame(std::shared_ptr<TimeStats> timeStats, JankClassificationThresholds thresholds,
402                      TraceCookieCounter* traceCookieCounter);
403         virtual ~DisplayFrame() = default;
404         // Dumpsys interface - dumps only if the DisplayFrame itself is janky or is at least one
405         // SurfaceFrame is janky.
406         void dumpJank(std::string& result, nsecs_t baseTime, int displayFrameCount) const;
407         // Dumpsys interface - dumps all data irrespective of jank
408         void dumpAll(std::string& result, nsecs_t baseTime) const;
409         // Emits a packet for perfetto tracing. The function body will be executed only if tracing
410         // is enabled. monoBootOffset is the difference between SYSTEM_TIME_BOOTTIME
411         // and SYSTEM_TIME_MONOTONIC.
412         nsecs_t trace(pid_t surfaceFlingerPid, nsecs_t monoBootOffset,
413                       nsecs_t previousPredictionPresentTime,
414                       bool filterFramesBeforeTraceStarts) const;
415         // Sets the token, vsyncPeriod, predictions and SF start time.
416         void onSfWakeUp(int64_t token, Fps refreshRate, Fps renderRate,
417                         std::optional<TimelineItem> predictions, nsecs_t wakeUpTime);
418         // Sets the appropriate metadata and classifies the jank.
419         void onPresent(nsecs_t signalTime, nsecs_t previousPresentTime);
420         // Flushes all the surface frames as those were not generating any actual display frames.
421         void onCommitNotComposited();
422         // Adds the provided SurfaceFrame to the current display frame.
423         void addSurfaceFrame(std::shared_ptr<SurfaceFrame> surfaceFrame);
424 
425         void setPredictions(PredictionState predictionState, TimelineItem predictions);
426         void setActualStartTime(nsecs_t actualStartTime);
427         void setActualEndTime(nsecs_t actualEndTime);
428         void setGpuFence(const std::shared_ptr<FenceTime>& gpuFence);
429 
430         // BaseTime is the smallest timestamp in a DisplayFrame.
431         // Used for dumping all timestamps relative to the oldest, making it easy to read.
432         nsecs_t getBaseTime() const;
433 
434         // Functions to be used only in testing.
getActuals()435         TimelineItem getActuals() const { return mSurfaceFlingerActuals; };
getPredictions()436         TimelineItem getPredictions() const { return mSurfaceFlingerPredictions; };
getFrameStartMetadata()437         FrameStartMetadata getFrameStartMetadata() const { return mFrameStartMetadata; };
getFramePresentMetadata()438         FramePresentMetadata getFramePresentMetadata() const { return mFramePresentMetadata; };
getFrameReadyMetadata()439         FrameReadyMetadata getFrameReadyMetadata() const { return mFrameReadyMetadata; };
getJankType()440         int32_t getJankType() const { return mJankType; }
getJankSeverityType()441         JankSeverityType getJankSeverityType() const { return mJankSeverityType; }
getSurfaceFrames()442         const std::vector<std::shared_ptr<SurfaceFrame>>& getSurfaceFrames() const {
443             return mSurfaceFrames;
444         }
445 
446     private:
447         void dump(std::string& result, nsecs_t baseTime) const;
448         void tracePredictions(pid_t surfaceFlingerPid, nsecs_t monoBootOffset,
449                               bool filterFramesBeforeTraceStarts) const;
450         void traceActuals(pid_t surfaceFlingerPid, nsecs_t monoBootOffset,
451                           bool filterFramesBeforeTraceStarts) const;
452         void addSkippedFrame(pid_t surfaceFlingerPid, nsecs_t monoBootOffset,
453                              nsecs_t previousActualPresentTime,
454                              bool filterFramesBeforeTraceStarts) const;
455         void classifyJank(nsecs_t& deadlineDelta, nsecs_t& deltaToVsync,
456                           nsecs_t previousPresentTime);
457 
458         int64_t mToken = FrameTimelineInfo::INVALID_VSYNC_ID;
459 
460         /* Usage of TimelineItem w.r.t SurfaceFlinger
461          * startTime    Time when SurfaceFlinger wakes up to handle transactions and buffer updates
462          * endTime      Time when SurfaceFlinger sends a composited frame to Display
463          * presentTime  Time when the composited frame was presented on screen
464          */
465         TimelineItem mSurfaceFlingerPredictions;
466         TimelineItem mSurfaceFlingerActuals;
467         std::shared_ptr<TimeStats> mTimeStats;
468         const JankClassificationThresholds mJankClassificationThresholds;
469 
470         // Collection of predictions and actual values sent over by Layers
471         std::vector<std::shared_ptr<SurfaceFrame>> mSurfaceFrames;
472 
473         PredictionState mPredictionState = PredictionState::None;
474         // Bitmask for the type of jank
475         int32_t mJankType = JankType::None;
476         // Enum for the severity of jank
477         JankSeverityType mJankSeverityType = JankSeverityType::None;
478         // A valid gpu fence indicates that the DisplayFrame was composited by the GPU
479         std::shared_ptr<FenceTime> mGpuFence = FenceTime::NO_FENCE;
480         // Enum for the type of present
481         FramePresentMetadata mFramePresentMetadata = FramePresentMetadata::UnknownPresent;
482         // Enum for the type of finish
483         FrameReadyMetadata mFrameReadyMetadata = FrameReadyMetadata::UnknownFinish;
484         // Enum for the type of start
485         FrameStartMetadata mFrameStartMetadata = FrameStartMetadata::UnknownStart;
486         // The refresh rate (vsync period) in nanoseconds as seen by SF during this DisplayFrame's
487         // timeline
488         Fps mRefreshRate;
489         // The current render rate for this DisplayFrame.
490         Fps mRenderRate;
491         // TraceCookieCounter is used to obtain the cookie for sendig trace packets to perfetto.
492         // Using a reference here because the counter is owned by FrameTimeline, which outlives
493         // DisplayFrame.
494         TraceCookieCounter& mTraceCookieCounter;
495     };
496 
497     FrameTimeline(std::shared_ptr<TimeStats> timeStats, pid_t surfaceFlingerPid,
498                   JankClassificationThresholds thresholds = {}, bool useBootTimeClock = true,
499                   bool filterFramesBeforeTraceStarts = true);
500     ~FrameTimeline() = default;
501 
getTokenManager()502     frametimeline::TokenManager* getTokenManager() override { return &mTokenManager; }
503     std::shared_ptr<SurfaceFrame> createSurfaceFrameForToken(
504             const FrameTimelineInfo& frameTimelineInfo, pid_t ownerPid, uid_t ownerUid,
505             int32_t layerId, std::string layerName, std::string debugName, bool isBuffer,
506             GameMode) override;
507     void addSurfaceFrame(std::shared_ptr<frametimeline::SurfaceFrame> surfaceFrame) override;
508     void setSfWakeUp(int64_t token, nsecs_t wakeupTime, Fps refreshRate, Fps renderRate) override;
509     void setSfPresent(nsecs_t sfPresentTime, const std::shared_ptr<FenceTime>& presentFence,
510                       const std::shared_ptr<FenceTime>& gpuFence = FenceTime::NO_FENCE) override;
511     void onCommitNotComposited() override;
512     void parseArgs(const Vector<String16>& args, std::string& result) override;
513     void setMaxDisplayFrames(uint32_t size) override;
514     float computeFps(const std::unordered_set<int32_t>& layerIds) override;
515     void generateFrameStats(int32_t layer, size_t count, FrameStats* outStats) const override;
516     void reset() override;
517 
518     // Sets up the perfetto tracing backend and data source.
519     void onBootFinished() override;
520     // Registers the data source with the perfetto backend. Called as part of onBootFinished()
521     // and should not be called manually outside of tests.
522     void registerDataSource();
523 
524     static constexpr char kFrameTimelineDataSource[] = "android.surfaceflinger.frametimeline";
525 
526 private:
527     // Friend class for testing
528     friend class android::frametimeline::FrameTimelineTest;
529 
530     void flushPendingPresentFences() REQUIRES(mMutex);
531     std::optional<size_t> getFirstSignalFenceIndex() const REQUIRES(mMutex);
532     void finalizeCurrentDisplayFrame() REQUIRES(mMutex);
533     void dumpAll(std::string& result);
534     void dumpJank(std::string& result);
535 
536     // Sliding window of display frames. TODO(b/168072834): compare perf with fixed size array
537     std::deque<std::shared_ptr<DisplayFrame>> mDisplayFrames GUARDED_BY(mMutex);
538     std::vector<std::pair<std::shared_ptr<FenceTime>, std::shared_ptr<DisplayFrame>>>
539             mPendingPresentFences GUARDED_BY(mMutex);
540     std::shared_ptr<DisplayFrame> mCurrentDisplayFrame GUARDED_BY(mMutex);
541     TokenManager mTokenManager;
542     TraceCookieCounter mTraceCookieCounter;
543     mutable std::mutex mMutex;
544     const bool mUseBootTimeClock;
545     const bool mFilterFramesBeforeTraceStarts;
546     uint32_t mMaxDisplayFrames;
547     std::shared_ptr<TimeStats> mTimeStats;
548     const pid_t mSurfaceFlingerPid;
549     nsecs_t mPreviousActualPresentTime = 0;
550     nsecs_t mPreviousPredictionPresentTime = 0;
551     const JankClassificationThresholds mJankClassificationThresholds;
552     static constexpr uint32_t kDefaultMaxDisplayFrames = 64;
553     // The initial container size for the vector<SurfaceFrames> inside display frame. Although
554     // this number doesn't represent any bounds on the number of surface frames that can go in a
555     // display frame, this is a good starting size for the vector so that we can avoid the
556     // internal vector resizing that happens with push_back.
557     static constexpr uint32_t kNumSurfaceFramesInitial = 10;
558 };
559 
560 } // namespace impl
561 } // namespace android::frametimeline
562