1// Copyright 2014 The Chromium 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 UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_
6#define UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_
7
8#include "base/memory/ref_counted.h"
9#include "base/observer_list_threadsafe.h"
10#include "base/synchronization/lock.h"
11#include "base/time/time.h"
12#include "ui/compositor/compositor_export.h"
13
14namespace ui {
15
16// This class manages vsync parameters for a compositor. It merges updates of
17// the parameters from different sources and sends the merged updates to
18// observers which register to it. This class is explicitly synchronized and is
19// safe to use and update from any thread. Observers of the manager will be
20// notified on the thread they have registered from, and should be removed from
21// the same thread.
22class COMPOSITOR_EXPORT CompositorVSyncManager
23    : public base::RefCountedThreadSafe<CompositorVSyncManager> {
24 public:
25  class Observer {
26   public:
27    virtual void OnUpdateVSyncParameters(base::TimeTicks timebase,
28                                         base::TimeDelta interval) = 0;
29  };
30
31  CompositorVSyncManager();
32
33  // The "authoritative" vsync interval, if provided, will override |interval|
34  // as reported by UpdateVSyncParameters() whenever it is called.  This is
35  // typically the value reported by a more reliable source, e.g. the platform
36  // display configuration.  In the particular case of ChromeOS -- this is the
37  // value queried through XRandR, which is more reliable than the value
38  // queried through the 3D context.
39  void SetAuthoritativeVSyncInterval(base::TimeDelta interval);
40
41  // The vsync parameters consist of |timebase|, which is the platform timestamp
42  // of the last vsync, and |interval|, which is the interval between vsyncs.
43  // |interval| may be overriden by SetAuthoritativeVSyncInterval() above.
44  void UpdateVSyncParameters(base::TimeTicks timebase,
45                             base::TimeDelta interval);
46
47  void AddObserver(Observer* observer);
48  void RemoveObserver(Observer* observer);
49
50 private:
51  friend class base::RefCountedThreadSafe<CompositorVSyncManager>;
52
53  ~CompositorVSyncManager();
54
55  void NotifyObservers(base::TimeTicks timebase, base::TimeDelta interval);
56
57  // List of observers.
58  scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
59
60  // Protects the cached vsync parameters below.
61  base::Lock vsync_parameters_lock_;
62  base::TimeTicks last_timebase_;
63  base::TimeDelta last_interval_;
64  base::TimeDelta authoritative_vsync_interval_;
65
66  DISALLOW_COPY_AND_ASSIGN(CompositorVSyncManager);
67};
68
69}  // namespace ui
70
71#endif  // UI_COMPOSITOR_COMPOSITOR_VSYNC_MANAGER_H_
72