blob: 4d3ae33a7820b62f632eac8933d8d33c0df36461 [file] [log] [blame]
Ana Krulec98b5b242018-08-10 15:03:23 -07001/*
2 * Copyright 2018 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
Ana Krulec7ab56032018-11-02 20:51:06 +010017#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
Ana Krulec98b5b242018-08-10 15:03:23 -070019#include "Scheduler.h"
20
21#include <cinttypes>
22#include <cstdint>
23#include <memory>
Ana Krulec7ab56032018-11-02 20:51:06 +010024#include <numeric>
Ana Krulec98b5b242018-08-10 15:03:23 -070025
Ana Krulece588e312018-09-18 12:32:24 -070026#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
27#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
29#include <configstore/Utils.h>
30
Ana Krulec98b5b242018-08-10 15:03:23 -070031#include <gui/ISurfaceComposer.h>
Ana Krulece588e312018-09-18 12:32:24 -070032#include <ui/DisplayStatInfo.h>
Ana Krulec3084c052018-11-21 20:27:17 +010033#include <utils/Timers.h>
Ana Krulec7ab56032018-11-02 20:51:06 +010034#include <utils/Trace.h>
Ana Krulec98b5b242018-08-10 15:03:23 -070035
36#include "DispSync.h"
37#include "DispSyncSource.h"
Ana Krulece588e312018-09-18 12:32:24 -070038#include "EventControlThread.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070039#include "EventThread.h"
40#include "InjectVSyncSource.h"
41
42namespace android {
43
Ana Krulece588e312018-09-18 12:32:24 -070044using namespace android::hardware::configstore;
45using namespace android::hardware::configstore::V1_0;
46
Ana Krulec0c8cd522018-08-31 12:27:28 -070047#define RETURN_VALUE_IF_INVALID(value) \
48 if (handle == nullptr || mConnections.count(handle->id) == 0) return value
49#define RETURN_IF_INVALID() \
50 if (handle == nullptr || mConnections.count(handle->id) == 0) return
51
Ana Krulec98b5b242018-08-10 15:03:23 -070052std::atomic<int64_t> Scheduler::sNextId = 0;
53
Ana Krulece588e312018-09-18 12:32:24 -070054Scheduler::Scheduler(impl::EventControlThread::SetVSyncEnabledFunction function)
55 : mHasSyncFramework(
56 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasSyncFramework>(true)),
57 mDispSyncPresentTimeOffset(
58 getInt64<ISurfaceFlingerConfigs,
59 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0)),
60 mPrimaryHWVsyncEnabled(false),
61 mHWVsyncAvailable(false) {
62 // Note: We create a local temporary with the real DispSync implementation
63 // type temporarily so we can initialize it with the configured values,
64 // before storing it for more generic use using the interface type.
65 auto primaryDispSync = std::make_unique<impl::DispSync>("SchedulerDispSync");
66 primaryDispSync->init(mHasSyncFramework, mDispSyncPresentTimeOffset);
67 mPrimaryDispSync = std::move(primaryDispSync);
68 mEventControlThread = std::make_unique<impl::EventControlThread>(function);
69}
70
Ana Krulec0c8cd522018-08-31 12:27:28 -070071Scheduler::~Scheduler() = default;
72
Ana Krulec98b5b242018-08-10 15:03:23 -070073sp<Scheduler::ConnectionHandle> Scheduler::createConnection(
Ana Krulece588e312018-09-18 12:32:24 -070074 const std::string& connectionName, int64_t phaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -070075 impl::EventThread::ResyncWithRateLimitCallback resyncCallback,
76 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
77 const int64_t id = sNextId++;
78 ALOGV("Creating a connection handle with ID: %" PRId64 "\n", id);
79
Ana Krulec98b5b242018-08-10 15:03:23 -070080 std::unique_ptr<EventThread> eventThread =
Ana Krulece588e312018-09-18 12:32:24 -070081 makeEventThread(connectionName, mPrimaryDispSync.get(), phaseOffsetNs, resyncCallback,
Ana Krulec0c8cd522018-08-31 12:27:28 -070082 interceptCallback);
Ana Krulec98b5b242018-08-10 15:03:23 -070083 auto connection = std::make_unique<Connection>(new ConnectionHandle(id),
84 eventThread->createEventConnection(),
85 std::move(eventThread));
86 mConnections.insert(std::make_pair(id, std::move(connection)));
87 return mConnections[id]->handle;
88}
89
Ana Krulec0c8cd522018-08-31 12:27:28 -070090std::unique_ptr<EventThread> Scheduler::makeEventThread(
Ana Krulec1f027912018-09-10 21:36:25 +000091 const std::string& connectionName, DispSync* dispSync, int64_t phaseOffsetNs,
Ana Krulec0c8cd522018-08-31 12:27:28 -070092 impl::EventThread::ResyncWithRateLimitCallback resyncCallback,
93 impl::EventThread::InterceptVSyncsCallback interceptCallback) {
Ana Krulec1f027912018-09-10 21:36:25 +000094 const std::string sourceName = connectionName + "Source";
Ana Krulec0c8cd522018-08-31 12:27:28 -070095 std::unique_ptr<VSyncSource> eventThreadSource =
Ana Krulec1f027912018-09-10 21:36:25 +000096 std::make_unique<DispSyncSource>(dispSync, phaseOffsetNs, true, sourceName.c_str());
97 const std::string threadName = connectionName + "Thread";
Ana Krulec0c8cd522018-08-31 12:27:28 -070098 return std::make_unique<impl::EventThread>(std::move(eventThreadSource), resyncCallback,
Ana Krulec1f027912018-09-10 21:36:25 +000099 interceptCallback, threadName.c_str());
Ana Krulec0c8cd522018-08-31 12:27:28 -0700100}
101
Ana Krulec98b5b242018-08-10 15:03:23 -0700102sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
103 const sp<Scheduler::ConnectionHandle>& handle) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700104 RETURN_VALUE_IF_INVALID(nullptr);
105 return mConnections[handle->id]->thread->createEventConnection();
Ana Krulec98b5b242018-08-10 15:03:23 -0700106}
107
108EventThread* Scheduler::getEventThread(const sp<Scheduler::ConnectionHandle>& handle) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700109 RETURN_VALUE_IF_INVALID(nullptr);
110 return mConnections[handle->id]->thread.get();
Ana Krulec98b5b242018-08-10 15:03:23 -0700111}
112
113sp<BnDisplayEventConnection> Scheduler::getEventConnection(const sp<ConnectionHandle>& handle) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700114 RETURN_VALUE_IF_INVALID(nullptr);
115 return mConnections[handle->id]->eventConnection;
Ana Krulec98b5b242018-08-10 15:03:23 -0700116}
117
118void Scheduler::hotplugReceived(const sp<Scheduler::ConnectionHandle>& handle,
119 EventThread::DisplayType displayType, bool connected) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700120 RETURN_IF_INVALID();
121 mConnections[handle->id]->thread->onHotplugReceived(displayType, connected);
Ana Krulec98b5b242018-08-10 15:03:23 -0700122}
123
124void Scheduler::onScreenAcquired(const sp<Scheduler::ConnectionHandle>& handle) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700125 RETURN_IF_INVALID();
126 mConnections[handle->id]->thread->onScreenAcquired();
Ana Krulec98b5b242018-08-10 15:03:23 -0700127}
128
129void Scheduler::onScreenReleased(const sp<Scheduler::ConnectionHandle>& handle) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700130 RETURN_IF_INVALID();
131 mConnections[handle->id]->thread->onScreenReleased();
Ana Krulec98b5b242018-08-10 15:03:23 -0700132}
133
134void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, String8& result) const {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700135 RETURN_IF_INVALID();
136 mConnections.at(handle->id)->thread->dump(result);
Ana Krulec98b5b242018-08-10 15:03:23 -0700137}
138
139void Scheduler::setPhaseOffset(const sp<Scheduler::ConnectionHandle>& handle, nsecs_t phaseOffset) {
Ana Krulec0c8cd522018-08-31 12:27:28 -0700140 RETURN_IF_INVALID();
141 mConnections[handle->id]->thread->setPhaseOffset(phaseOffset);
Ana Krulec98b5b242018-08-10 15:03:23 -0700142}
Ana Krulece588e312018-09-18 12:32:24 -0700143
144void Scheduler::getDisplayStatInfo(DisplayStatInfo* stats) {
145 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
146 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
147}
148
149void Scheduler::enableHardwareVsync() {
150 std::lock_guard<std::mutex> lock(mHWVsyncLock);
151 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
152 mPrimaryDispSync->beginResync();
153 mEventControlThread->setVsyncEnabled(true);
154 mPrimaryHWVsyncEnabled = true;
155 }
156}
157
158void Scheduler::disableHardwareVsync(bool makeUnavailable) {
159 std::lock_guard<std::mutex> lock(mHWVsyncLock);
160 if (mPrimaryHWVsyncEnabled) {
161 mEventControlThread->setVsyncEnabled(false);
162 mPrimaryDispSync->endResync();
163 mPrimaryHWVsyncEnabled = false;
164 }
165 if (makeUnavailable) {
166 mHWVsyncAvailable = false;
167 }
168}
169
170void Scheduler::setVsyncPeriod(const nsecs_t period) {
171 mPrimaryDispSync->reset();
172 mPrimaryDispSync->setPeriod(period);
173 enableHardwareVsync();
174}
175
176void Scheduler::addResyncSample(const nsecs_t timestamp) {
177 bool needsHwVsync = false;
178 { // Scope for the lock
179 std::lock_guard<std::mutex> lock(mHWVsyncLock);
180 if (mPrimaryHWVsyncEnabled) {
181 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
182 }
183 }
184
185 if (needsHwVsync) {
186 enableHardwareVsync();
187 } else {
188 disableHardwareVsync(false);
189 }
190}
191
192void Scheduler::addPresentFence(const std::shared_ptr<FenceTime>& fenceTime) {
193 if (mPrimaryDispSync->addPresentFence(fenceTime)) {
194 enableHardwareVsync();
195 } else {
196 disableHardwareVsync(false);
197 }
198}
199
200void Scheduler::setIgnorePresentFences(bool ignore) {
201 mPrimaryDispSync->setIgnorePresentFences(ignore);
202}
203
Ana Krulec7ab56032018-11-02 20:51:06 +0100204void Scheduler::makeHWSyncAvailable(bool makeAvailable) {
205 std::lock_guard<std::mutex> lock(mHWVsyncLock);
206 mHWVsyncAvailable = makeAvailable;
207}
208
Ana Krulec3084c052018-11-21 20:27:17 +0100209void Scheduler::addFramePresentTimeForLayer(const nsecs_t framePresentTime, bool isAutoTimestamp,
210 const std::string layerName) {
211 // This is V1 logic. It calculates the average FPS based on the timestamp frequency
212 // regardless of which layer the timestamp came from.
213 // For now, the averages and FPS are recorded in the systrace.
214 determineTimestampAverage(isAutoTimestamp, framePresentTime);
215
216 // This is V2 logic. It calculates the average and median timestamp difference based on the
217 // individual layer history. The results are recorded in the systrace.
218 determineLayerTimestampStats(layerName, framePresentTime);
219}
220
221void Scheduler::incrementFrameCounter() {
222 mLayerHistory.incrementCounter();
223}
224
225nsecs_t Scheduler::calculateAverage() const {
226 nsecs_t sum = std::accumulate(mTimeDifferences.begin(), mTimeDifferences.end(), 0);
227 return (sum / ARRAY_SIZE);
228}
229
230void Scheduler::updateFrameSkipping(const int64_t skipCount) {
231 ATRACE_INT("FrameSkipCount", skipCount);
232 if (mSkipCount != skipCount) {
233 // Only update DispSync if it hasn't been updated yet.
234 mPrimaryDispSync->setRefreshSkipCount(skipCount);
235 mSkipCount = skipCount;
236 }
237}
238
239void Scheduler::determineLayerTimestampStats(const std::string layerName,
240 const nsecs_t framePresentTime) {
241 mLayerHistory.insert(layerName, framePresentTime);
242 std::vector<int64_t> differencesMs;
243
244 // Traverse through the layer history, and determine the differences in present times.
245 nsecs_t newestPresentTime = framePresentTime;
246 for (int i = 1; i < mLayerHistory.getSize(); i++) {
247 std::unordered_map<std::string, nsecs_t> layers = mLayerHistory.get(i);
248 for (auto layer : layers) {
249 if (layer.first != layerName) {
250 continue;
251 }
252 int64_t differenceMs = (newestPresentTime - layer.second) / 1000000;
253 ALOGD("%d Layer %s: %" PRId64, i, layerName.c_str(), differenceMs);
254 // Dismiss noise.
255 if (differenceMs > 10 && differenceMs < 60) {
256 differencesMs.push_back(differenceMs);
257 }
258 newestPresentTime = layer.second;
259 }
260 }
261 // Average is a good indicator for when 24fps videos are playing, because the frames come in
262 // 33, and 49 ms intervals with occasional 41ms.
263 int64_t average =
264 std::accumulate(differencesMs.begin(), differencesMs.end(), 0) / differencesMs.size();
265 const auto tag = "TimestampAvg_" + layerName;
266 ATRACE_INT(tag.c_str(), average);
267
268 // Mode and median are good indicators for 30 and 60 fps videos, because the majority of frames
269 // come in 16, or 33 ms intervals.
270 // TODO(b/113612090): Calculate mode. Median is good for now, since we want a given interval to
271 // repeat at least ARRAY_SIZE/2 + 1 times.
272 if (differencesMs.size() > 0) {
273 const auto tagMedian = "TimestampMedian_" + layerName;
274 ATRACE_INT(tagMedian.c_str(), calculateMedian(&differencesMs));
275 }
276}
277
278int64_t Scheduler::calculateMedian(std::vector<int64_t>* v) {
279 if (!v || v->size() == 0) {
280 return 0;
281 }
282
283 size_t n = v->size() / 2;
284 nth_element(v->begin(), v->begin() + n, v->end());
285 return v->at(n);
286}
287
288void Scheduler::determineTimestampAverage(bool isAutoTimestamp, const nsecs_t framePresentTime) {
Ana Krulec7ab56032018-11-02 20:51:06 +0100289 ATRACE_INT("AutoTimestamp", isAutoTimestamp);
Ana Krulec3084c052018-11-21 20:27:17 +0100290
Ana Krulec7ab56032018-11-02 20:51:06 +0100291 // Video does not have timestamp automatically set, so we discard timestamps that are
292 // coming in from other sources for now.
293 if (isAutoTimestamp) {
294 return;
295 }
Ana Krulec3084c052018-11-21 20:27:17 +0100296 int64_t differenceMs = (framePresentTime - mPreviousFrameTimestamp) / 1000000;
297 mPreviousFrameTimestamp = framePresentTime;
Ana Krulec7ab56032018-11-02 20:51:06 +0100298
299 if (differenceMs < 10 || differenceMs > 100) {
300 // Dismiss noise.
301 return;
302 }
303 ATRACE_INT("TimestampDiff", differenceMs);
304
305 mTimeDifferences[mCounter % ARRAY_SIZE] = differenceMs;
306 mCounter++;
307 nsecs_t average = calculateAverage();
308 ATRACE_INT("TimestampAverage", average);
309
310 // TODO(b/113612090): This are current numbers from trial and error while running videos
311 // from YouTube at 24, 30, and 60 fps.
312 if (average > 14 && average < 18) {
313 ATRACE_INT("FPS", 60);
314 } else if (average > 31 && average < 34) {
315 ATRACE_INT("FPS", 30);
316 updateFrameSkipping(1);
317 return;
318 } else if (average > 39 && average < 42) {
319 ATRACE_INT("FPS", 24);
320 }
321 updateFrameSkipping(0);
322}
323
Ana Krulec98b5b242018-08-10 15:03:23 -0700324} // namespace android