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