SF: Adding Layer History to SF.

Calculate average and median between the timestamp differences that come in for
individual layers, and store them to systrace.

See go/surface-flinger-scheduler for more details and systrace links.

Test: SF tests updated.
Bug: 113612090
Change-Id: I934bbe36ab57d16a5b219c7cb8e0580112238671
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
index dd1f24b..adfc071 100644
--- a/services/surfaceflinger/Scheduler/Scheduler.h
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -26,6 +26,7 @@
 #include "EventControlThread.h"
 #include "EventThread.h"
 #include "InjectVSyncSource.h"
+#include "LayerHistory.h"
 
 namespace android {
 
@@ -103,9 +104,15 @@
     void addPresentFence(const std::shared_ptr<FenceTime>& fenceTime);
     void setIgnorePresentFences(bool ignore);
     void makeHWSyncAvailable(bool makeAvailable);
-    void addNewFrameTimestamp(const nsecs_t newFrameTimestamp, bool isAutoTimestamp);
+    // Adds the present time for given layer to the history of present times.
+    void addFramePresentTimeForLayer(const nsecs_t framePresentTime, bool isAutoTimestamp,
+                                     const std::string layerName);
+    // Increments counter in the layer history to indicate that SF has started a new frame.
+    void incrementFrameCounter();
 
 protected:
+    friend class SchedulerTest;
+
     virtual std::unique_ptr<EventThread> makeEventThread(
             const std::string& connectionName, DispSync* dispSync, int64_t phaseOffsetNs,
             impl::EventThread::ResyncWithRateLimitCallback resyncCallback,
@@ -114,6 +121,15 @@
 private:
     nsecs_t calculateAverage() const;
     void updateFrameSkipping(const int64_t skipCount);
+    // Collects the statistical mean (average) and median between timestamp
+    // intervals for each frame for each layer.
+    void determineLayerTimestampStats(const std::string layerName, const nsecs_t framePresentTime);
+    // Calculates the statistical median in the vector. Return 0 if the vector is empty. The
+    // function modifies the vector contents.
+    int64_t calculateMedian(std::vector<int64_t>* v);
+    // Collects the average difference between timestamps for each frame regardless
+    // of which layer the timestamp came from.
+    void determineTimestampAverage(bool isAutoTimestamp, const nsecs_t framePresentTime);
 
     // TODO(b/113612090): Instead of letting BufferQueueLayer to access mDispSync directly, it
     // should make request to Scheduler to compute next refresh.
@@ -150,6 +166,8 @@
     static constexpr size_t ARRAY_SIZE = 30;
     std::array<int64_t, ARRAY_SIZE> mTimeDifferences;
     size_t mCounter = 0;
+
+    LayerHistory mLayerHistory;
 };
 
 } // namespace android