1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#ifndef FLUTTER_SHELL_COMMON_VSYNC_WAITER_H_
6#define FLUTTER_SHELL_COMMON_VSYNC_WAITER_H_
7
8#include <functional>
9#include <memory>
10#include <mutex>
11
12#include "flutter/common/task_runners.h"
13#include "flutter/fml/time/time_point.h"
14
15namespace flutter {
16
17/// Abstract Base Class that represents a platform specific mechanism for
18/// getting callbacks when a vsync event happens.
19class VsyncWaiter : public std::enable_shared_from_this<VsyncWaiter> {
20 public:
21 using Callback = std::function<void(fml::TimePoint frame_start_time,
22 fml::TimePoint frame_target_time)>;
23
24 virtual ~VsyncWaiter();
25
26 void AsyncWaitForVsync(const Callback& callback);
27
28 /// Add a secondary callback for the next vsync.
29 ///
30 /// See also |PointerDataDispatcher::ScheduleSecondaryVsyncCallback|.
31 void ScheduleSecondaryCallback(const fml::closure& callback);
32
33 static constexpr float kUnknownRefreshRateFPS = 0.0;
34
35 // Get the display's maximum refresh rate in the unit of frame per second.
36 // Return kUnknownRefreshRateFPS if the refresh rate is unknown.
37 virtual float GetDisplayRefreshRate() const;
38
39 protected:
40 // On some backends, the |FireCallback| needs to be made from a static C
41 // method.
42 friend class VsyncWaiterAndroid;
43 friend class VsyncWaiterEmbedder;
44
45 const TaskRunners task_runners_;
46
47 VsyncWaiter(TaskRunners task_runners);
48
49 // Implementations are meant to override this method and arm their vsync
50 // latches when in response to this invocation. On vsync, they are meant to
51 // invoke the |FireCallback| method once (and only once) with the appropriate
52 // arguments. This method should not block the current thread.
53 virtual void AwaitVSync() = 0;
54
55 void FireCallback(fml::TimePoint frame_start_time,
56 fml::TimePoint frame_target_time);
57
58 private:
59 std::mutex callback_mutex_;
60 Callback callback_;
61
62 std::mutex secondary_callback_mutex_;
63 fml::closure secondary_callback_;
64
65 FML_DISALLOW_COPY_AND_ASSIGN(VsyncWaiter);
66};
67
68} // namespace flutter
69
70#endif // FLUTTER_SHELL_COMMON_VSYNC_WAITER_H_
71