summaryrefslogtreecommitdiffstats
path: root/chromium/ui/gfx/rendering_pipeline.cc
blob: 174b10b0c4ae5924c025e72518817129ebe0e672 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/rendering_pipeline.h"

#include "base/containers/flat_map.h"
#include "base/task/current_thread.h"
#include "base/task/sequence_manager/task_time_observer.h"
#include "base/thread_annotations.h"
#include "base/threading/thread_checker.h"
#include "ui/gfx/rendering_stage_scheduler.h"

namespace gfx {
namespace {

class ThreadSafeTimeObserver : public base::sequence_manager::TaskTimeObserver {
 public:
  explicit ThreadSafeTimeObserver(
      scoped_refptr<base::SingleThreadTaskRunner> task_runner)
      : task_runner_(std::move(task_runner)) {}
  ~ThreadSafeTimeObserver() override {
    // If the observer is being used on the target thread, unregister now. If it
    // was being used on a different thread, then the target thread should have
    // been torn down already.
    SetEnabled(false);
  }

  ThreadSafeTimeObserver(const ThreadSafeTimeObserver&) = delete;
  ThreadSafeTimeObserver& operator=(const ThreadSafeTimeObserver&) = delete;

  void SetEnabled(bool enabled) {
    {
      base::AutoLock hold(time_lock_);
      if (enabled_ == enabled)
        return;
      enabled_ = enabled;
    }

    if (!task_runner_)
      return;

    if (task_runner_->BelongsToCurrentThread()) {
      UpdateOnTargetThread(enabled);
      return;
    }

    task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&ThreadSafeTimeObserver::UpdateOnTargetThread,
                                  base::Unretained(this), enabled));
  }

  base::TimeDelta GetAndResetTimeSinceLastFrame() {
    base::AutoLock hold(time_lock_);

    if (!start_time_active_task_.is_null()) {
      auto now = base::TimeTicks::Now();
      time_since_last_frame_ += now - start_time_active_task_;
      start_time_active_task_ = now;
    }

    auto result = time_since_last_frame_;
    time_since_last_frame_ = base::TimeDelta();
    return result;
  }

  // TaskTimeObserver impl.
  void WillProcessTask(base::TimeTicks start_time) override {
    base::AutoLock hold(time_lock_);
    if (!enabled_)
      return;

    DCHECK(start_time_active_task_.is_null());
    start_time_active_task_ = start_time;
  }

  void DidProcessTask(base::TimeTicks start_time,
                      base::TimeTicks end_time) override {
    base::AutoLock hold(time_lock_);
    if (!enabled_) {
      start_time_active_task_ = base::TimeTicks();
      return;
    }

    // This should be null for the task which adds this object to the observer
    // list.
    if (start_time_active_task_.is_null())
      return;

    if (start_time_active_task_ <= end_time) {
      time_since_last_frame_ += (end_time - start_time_active_task_);
    } else {
      // This could happen if |GetAndResetTimeSinceLastFrame| is called on a
      // different thread and the observed thread had to wait to acquire the
      // lock to call DidProcessTask. Assume the time for this task is already
      // recorded in |GetAndResetTimeSinceLastFrame|.
      DCHECK_NE(start_time_active_task_, start_time);
    }

    start_time_active_task_ = base::TimeTicks();
  }

 private:
  void UpdateOnTargetThread(bool enabled) {
    if (enabled) {
      base::CurrentThread::Get().AddTaskTimeObserver(this);

      base::AutoLock hold(time_lock_);
      start_time_active_task_ = base::TimeTicks();
      time_since_last_frame_ = base::TimeDelta();
    } else {
      base::CurrentThread::Get().RemoveTaskTimeObserver(this);
    }
  }

  // Accessed only on the calling thread. The caller ensures no concurrent
  // access.
  scoped_refptr<base::SingleThreadTaskRunner> task_runner_;

  // Accessed on calling and target thread.
  base::Lock time_lock_;
  bool enabled_ GUARDED_BY(time_lock_) = false;
  base::TimeTicks start_time_active_task_ GUARDED_BY(time_lock_);
  base::TimeDelta time_since_last_frame_ GUARDED_BY(time_lock_);
};

}  // namespace

class RenderingPipelineImpl final : public RenderingPipeline {
 public:
  explicit RenderingPipelineImpl(const char* pipeline_type)
      : pipeline_type_(pipeline_type) {
    DETACH_FROM_THREAD(bound_thread_);
  }
  ~RenderingPipelineImpl() override { TearDown(); }

  RenderingPipelineImpl(const RenderingPipelineImpl&) = delete;
  RenderingPipelineImpl& operator=(const RenderingPipelineImpl&) = delete;

  void SetTargetDuration(base::TimeDelta target_duration) override {
    DCHECK_CALLED_ON_VALID_THREAD(bound_thread_);
    DCHECK(!target_duration.is_zero());

    if (target_duration_ == target_duration)
      return;

    target_duration_ = target_duration;
    if (should_use_scheduler())
      SetUp();
  }

  void AddSequenceManagerThread(
      base::PlatformThreadId thread_id,
      scoped_refptr<base::SingleThreadTaskRunner> task_runner) override {
    base::AutoLock lock(lock_);
    DCHECK(time_observers_.find(thread_id) == time_observers_.end());
    time_observers_[thread_id] =
        std::make_unique<ThreadSafeTimeObserver>(task_runner);
    if (scheduler_)
      CreateSchedulerAndEnableWithLockAcquired();
  }

  base::sequence_manager::TaskTimeObserver* AddSimpleThread(
      base::PlatformThreadId thread_id) override {
    base::AutoLock lock(lock_);
    DCHECK(time_observers_.find(thread_id) == time_observers_.end());
    time_observers_[thread_id] =
        std::make_unique<ThreadSafeTimeObserver>(nullptr);

    if (scheduler_)
      CreateSchedulerAndEnableWithLockAcquired();
    return time_observers_[thread_id].get();
  }

  void NotifyFrameFinished() override {
    DCHECK_CALLED_ON_VALID_THREAD(bound_thread_);

    base::AutoLock lock(lock_);
    if (!scheduler_)
      return;

    // TODO(crbug.com/1157620): This can be optimized to exclude tasks which can
    // be paused during rendering. The best use-case is idle tasks on the
    // renderer main thread. If all non-optional work is close to the frame
    // budget then the scheduler dynamically adjusts to pause work like idle
    // tasks.
    base::TimeDelta total_time;
    for (auto& it : time_observers_) {
      total_time += it.second->GetAndResetTimeSinceLastFrame();
    }
    scheduler_->ReportCpuCompletionTime(total_time + gpu_latency_);
  }

  void SetGpuLatency(base::TimeDelta gpu_latency) override {
    DCHECK_CALLED_ON_VALID_THREAD(bound_thread_);
    gpu_latency_ = gpu_latency;
  }

  void UpdateActiveCount(bool active) override {
    DCHECK_CALLED_ON_VALID_THREAD(bound_thread_);

    if (active) {
      active_count_++;
    } else {
      DCHECK_GT(active_count_, 0);
      active_count_--;
    }

    if (should_use_scheduler()) {
      SetUp();
    } else {
      TearDown();
    }
  }

 private:
  bool should_use_scheduler() const {
    // TODO(crbug.com/1157620) : Figure out what we should be doing if multiple
    // independent pipelines of a type are running simultaneously. The common
    // use-case for this in practice would be multi-window. The tabs could be
    // hosted in the same renderer process and each window is composited
    // independently by the GPU process.
    return active_count_ == 1 && !target_duration_.is_zero();
  }

  void SetUp() {
    base::AutoLock lock(lock_);
    CreateSchedulerAndEnableWithLockAcquired();
  }

  void CreateSchedulerAndEnableWithLockAcquired() {
    lock_.AssertAcquired();
    scheduler_.reset();

    std::vector<base::PlatformThreadId> platform_threads;
    for (auto& it : time_observers_) {
      platform_threads.push_back(it.first);
      it.second->SetEnabled(true);
    }

    scheduler_ = RenderingStageScheduler::CreateAdpf(
        pipeline_type_, std::move(platform_threads), target_duration_);
  }

  void TearDown() {
    base::AutoLock lock(lock_);
    for (auto& it : time_observers_)
      it.second->SetEnabled(false);
    scheduler_.reset();
  }

  THREAD_CHECKER(bound_thread_);

  base::Lock lock_;
  base::flat_map<base::PlatformThreadId,
                 std::unique_ptr<ThreadSafeTimeObserver>>
      time_observers_ GUARDED_BY(lock_);
  std::unique_ptr<RenderingStageScheduler> scheduler_ GUARDED_BY(lock_);

  // Pipeline name, for tracing and metrics.
  const char* pipeline_type_;

  // The number of currently active pipelines of this type.
  int active_count_ = 0;

  // The target time for this rendering stage for a frame.
  base::TimeDelta target_duration_;

  base::TimeDelta gpu_latency_;
};

RenderingPipeline::ScopedPipelineActive::ScopedPipelineActive(
    RenderingPipeline* pipeline)
    : pipeline_(pipeline) {
  pipeline_->UpdateActiveCount(true);
}

RenderingPipeline::ScopedPipelineActive::~ScopedPipelineActive() {
  pipeline_->UpdateActiveCount(false);
}

std::unique_ptr<RenderingPipeline> RenderingPipeline::CreateRendererMain() {
  static constexpr char kRendererMain[] = "RendererMain";
  return std::make_unique<RenderingPipelineImpl>(kRendererMain);
}

std::unique_ptr<RenderingPipeline>
RenderingPipeline::CreateRendererCompositor() {
  static constexpr char kRendererCompositor[] = "RendererCompositor";
  return std::make_unique<RenderingPipelineImpl>(kRendererCompositor);
}

std::unique_ptr<RenderingPipeline> RenderingPipeline::CreateGpu() {
  static constexpr char kGpu[] = "Gpu";
  return std::make_unique<RenderingPipelineImpl>(kGpu);
}

}  // namespace gfx