2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #include <sys/types.h>
22 #include <cutils/compiler.h>
24 #include <gui/IDisplayEventConnection.h>
25 #include <gui/DisplayEventReceiver.h>
27 #include <utils/Errors.h>
28 #include <utils/String8.h>
29 #include <utils/Trace.h>
31 #include "EventThread.h"
32 #include "SurfaceFlinger.h"
34 // ---------------------------------------------------------------------------
36 // ---------------------------------------------------------------------------
37 // time to wait between VSYNC requests before sending a VSYNC OFF power hint: 40msec.
38 const long vsyncHintOffDelay = 40000000;
40 static void vsyncOffCallback(union sigval val) {
41 EventThread *ev = (EventThread *)val.sival_ptr;
42 ev->sendVsyncHintOff();
46 EventThread::EventThread(const sp<VSyncSource>& src, SurfaceFlinger& flinger, bool interceptVSyncs)
49 mUseSoftwareVSync(false),
51 mDebugVsyncEnabled(false),
52 mVsyncHintSent(false),
53 mInterceptVSyncs(interceptVSyncs) {
55 for (int32_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
56 mVSyncEvent[i].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
57 mVSyncEvent[i].header.id = 0;
58 mVSyncEvent[i].header.timestamp = 0;
59 mVSyncEvent[i].vsync.count = 0;
62 se.sigev_notify = SIGEV_THREAD;
63 se.sigev_value.sival_ptr = this;
64 se.sigev_notify_function = vsyncOffCallback;
65 se.sigev_notify_attributes = NULL;
66 timer_create(CLOCK_MONOTONIC, &se, &mTimerId);
69 void EventThread::sendVsyncHintOff() {
70 Mutex::Autolock _l(mLock);
71 mPowerHAL.vsyncHint(false);
72 mVsyncHintSent = false;
75 void EventThread::setPhaseOffset(nsecs_t phaseOffset) {
76 Mutex::Autolock _l(mLock);
77 mVSyncSource->setPhaseOffset(phaseOffset);
80 void EventThread::sendVsyncHintOnLocked() {
83 mPowerHAL.vsyncHint(true);
84 mVsyncHintSent = true;
86 ts.it_value.tv_sec = 0;
87 ts.it_value.tv_nsec = vsyncHintOffDelay;
88 ts.it_interval.tv_sec = 0;
89 ts.it_interval.tv_nsec = 0;
90 timer_settime(mTimerId, 0, &ts, NULL);
93 void EventThread::onFirstRef() {
94 run("EventThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
97 sp<EventThread::Connection> EventThread::createEventConnection() const {
98 return new Connection(const_cast<EventThread*>(this));
101 status_t EventThread::registerDisplayEventConnection(
102 const sp<EventThread::Connection>& connection) {
103 Mutex::Autolock _l(mLock);
104 mDisplayEventConnections.add(connection);
105 mCondition.broadcast();
109 void EventThread::removeDisplayEventConnection(
110 const wp<EventThread::Connection>& connection) {
111 Mutex::Autolock _l(mLock);
112 mDisplayEventConnections.remove(connection);
115 void EventThread::setVsyncRate(uint32_t count,
116 const sp<EventThread::Connection>& connection) {
117 if (int32_t(count) >= 0) { // server must protect against bad params
118 Mutex::Autolock _l(mLock);
119 const int32_t new_count = (count == 0) ? -1 : count;
120 if (connection->count != new_count) {
121 connection->count = new_count;
122 mCondition.broadcast();
127 void EventThread::requestNextVsync(
128 const sp<EventThread::Connection>& connection) {
129 Mutex::Autolock _l(mLock);
131 mFlinger.resyncWithRateLimit();
133 if (connection->count < 0) {
134 connection->count = 0;
135 mCondition.broadcast();
139 void EventThread::onScreenReleased() {
140 Mutex::Autolock _l(mLock);
141 if (!mUseSoftwareVSync) {
142 // disable reliance on h/w vsync
143 mUseSoftwareVSync = true;
144 mCondition.broadcast();
148 void EventThread::onScreenAcquired() {
149 Mutex::Autolock _l(mLock);
150 if (mUseSoftwareVSync) {
151 // resume use of h/w vsync
152 mUseSoftwareVSync = false;
153 mCondition.broadcast();
157 void EventThread::onVSyncEvent(nsecs_t timestamp) {
158 Mutex::Autolock _l(mLock);
159 mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
160 mVSyncEvent[0].header.id = 0;
161 mVSyncEvent[0].header.timestamp = timestamp;
162 mVSyncEvent[0].vsync.count++;
163 mCondition.broadcast();
166 void EventThread::onHotplugReceived(int type, bool connected) {
167 ALOGE_IF(type >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES,
168 "received hotplug event for an invalid display (id=%d)", type);
170 Mutex::Autolock _l(mLock);
171 if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
172 DisplayEventReceiver::Event event;
173 event.header.type = DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG;
174 event.header.id = type;
175 event.header.timestamp = systemTime();
176 event.hotplug.connected = connected;
177 mPendingEvents.add(event);
178 mCondition.broadcast();
182 bool EventThread::threadLoop() {
183 DisplayEventReceiver::Event event;
184 Vector< sp<EventThread::Connection> > signalConnections;
185 signalConnections = waitForEvent(&event);
187 // dispatch events to listeners...
188 const size_t count = signalConnections.size();
189 for (size_t i=0 ; i<count ; i++) {
190 const sp<Connection>& conn(signalConnections[i]);
191 // now see if we still need to report this event
192 status_t err = conn->postEvent(event);
193 if (err == -EAGAIN || err == -EWOULDBLOCK) {
194 // The destination doesn't accept events anymore, it's probably
195 // full. For now, we just drop the events on the floor.
196 // FIXME: Note that some events cannot be dropped and would have
197 // to be re-sent later.
198 // Right-now we don't have the ability to do this.
199 ALOGW("EventThread: dropping event (%08x) for connection %p",
200 event.header.type, conn.get());
201 } else if (err < 0) {
202 // handle any other error on the pipe as fatal. the only
203 // reasonable thing to do is to clean-up this connection.
204 // The most common error we'll get here is -EPIPE.
205 removeDisplayEventConnection(signalConnections[i]);
211 // This will return when (1) a vsync event has been received, and (2) there was
212 // at least one connection interested in receiving it when we started waiting.
213 Vector< sp<EventThread::Connection> > EventThread::waitForEvent(
214 DisplayEventReceiver::Event* event)
216 Mutex::Autolock _l(mLock);
217 Vector< sp<EventThread::Connection> > signalConnections;
220 bool eventPending = false;
221 bool waitForVSync = false;
223 size_t vsyncCount = 0;
224 nsecs_t timestamp = 0;
225 for (int32_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
226 timestamp = mVSyncEvent[i].header.timestamp;
228 // we have a vsync event to dispatch
229 if (mInterceptVSyncs) {
230 mFlinger.mInterceptor.saveVSyncEvent(timestamp);
232 *event = mVSyncEvent[i];
233 mVSyncEvent[i].header.timestamp = 0;
234 vsyncCount = mVSyncEvent[i].vsync.count;
240 // no vsync event, see if there are some other event
241 eventPending = !mPendingEvents.isEmpty();
243 // we have some other event to dispatch
244 *event = mPendingEvents[0];
245 mPendingEvents.removeAt(0);
249 // find out connections waiting for events
250 size_t count = mDisplayEventConnections.size();
251 for (size_t i=0 ; i<count ; i++) {
252 sp<Connection> connection(mDisplayEventConnections[i].promote());
253 if (connection != NULL) {
255 if (connection->count >= 0) {
256 // we need vsync events because at least
257 // one connection is waiting for it
260 // we consume the event only if it's time
261 // (ie: we received a vsync event)
262 if (connection->count == 0) {
263 // fired this time around
264 connection->count = -1;
265 signalConnections.add(connection);
267 } else if (connection->count == 1 ||
268 (vsyncCount % connection->count) == 0) {
269 // continuous event, and time to report it
270 signalConnections.add(connection);
276 if (eventPending && !timestamp && !added) {
277 // we don't have a vsync event to process
278 // (timestamp==0), but we have some pending
280 signalConnections.add(connection);
283 // we couldn't promote this reference, the connection has
284 // died, so clean-up!
285 mDisplayEventConnections.removeAt(i);
290 // Here we figure out if we need to enable or disable vsyncs
292 // we have no clients waiting on next VSYNC
293 // just disable VSYNC events.
294 disableVSyncLocked();
295 } else if (!timestamp) {
296 // we have at least one client, so we want vsync enabled
297 // (TODO: this function is called right after we finish
298 // notifying clients of a vsync, so this call will be made
299 // at the vsync rate, e.g. 60fps. If we can accurately
300 // track the current state we could avoid making this call
305 // note: !timestamp implies signalConnections.isEmpty(), because we
306 // don't populate signalConnections if there's no vsync pending
307 if (!timestamp && !eventPending) {
308 // wait for something to happen
310 // This is where we spend most of our time, waiting
311 // for vsync events and new client registrations.
313 // If the screen is off, we can't use h/w vsync, so we
314 // use a 16ms timeout instead. It doesn't need to be
315 // precise, we just need to keep feeding our clients.
317 // We don't want to stall if there's a driver bug, so we
318 // use a (long) timeout when waiting for h/w vsync, and
319 // generate fake events when necessary.
320 bool softwareSync = mUseSoftwareVSync;
321 nsecs_t timeout = softwareSync ? ms2ns(16) : ms2ns(1000);
322 if (mCondition.waitRelative(mLock, timeout) == TIMED_OUT) {
324 ALOGW("Timed out waiting for hw vsync; faking it");
326 // FIXME: how do we decide which display id the fake
328 mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
329 mVSyncEvent[0].header.id = DisplayDevice::DISPLAY_PRIMARY;
330 mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
331 mVSyncEvent[0].vsync.count++;
334 // Nobody is interested in vsync, so we just want to sleep.
335 // h/w vsync should be disabled, so this will wait until we
336 // get a new connection, or an existing connection becomes
337 // interested in receiving vsync again.
338 mCondition.wait(mLock);
341 } while (signalConnections.isEmpty());
343 // here we're guaranteed to have a timestamp and some connections to signal
344 // (The connections might have dropped out of mDisplayEventConnections
345 // while we were asleep, but we'll still have strong references to them.)
346 return signalConnections;
349 void EventThread::enableVSyncLocked() {
350 if (!mUseSoftwareVSync) {
351 // never enable h/w VSYNC when screen is off
352 if (!mVsyncEnabled) {
353 mVsyncEnabled = true;
354 mVSyncSource->setCallback(static_cast<VSyncSource::Callback*>(this));
355 mVSyncSource->setVSyncEnabled(true);
358 mDebugVsyncEnabled = true;
359 sendVsyncHintOnLocked();
362 void EventThread::disableVSyncLocked() {
364 mVsyncEnabled = false;
365 mVSyncSource->setVSyncEnabled(false);
366 mDebugVsyncEnabled = false;
370 void EventThread::dump(String8& result) const {
371 Mutex::Autolock _l(mLock);
372 result.appendFormat("VSYNC state: %s\n",
373 mDebugVsyncEnabled?"enabled":"disabled");
374 result.appendFormat(" soft-vsync: %s\n",
375 mUseSoftwareVSync?"enabled":"disabled");
376 result.appendFormat(" numListeners=%zu,\n events-delivered: %u\n",
377 mDisplayEventConnections.size(),
378 mVSyncEvent[DisplayDevice::DISPLAY_PRIMARY].vsync.count);
379 for (size_t i=0 ; i<mDisplayEventConnections.size() ; i++) {
380 sp<Connection> connection =
381 mDisplayEventConnections.itemAt(i).promote();
382 result.appendFormat(" %p: count=%d\n",
383 connection.get(), connection!=NULL ? connection->count : 0);
387 // ---------------------------------------------------------------------------
389 EventThread::Connection::Connection(
390 const sp<EventThread>& eventThread)
391 : count(-1), mEventThread(eventThread), mChannel(gui::BitTube::DefaultSize)
395 EventThread::Connection::~Connection() {
396 // do nothing here -- clean-up will happen automatically
397 // when the main thread wakes up
400 void EventThread::Connection::onFirstRef() {
401 // NOTE: mEventThread doesn't hold a strong reference on us
402 mEventThread->registerDisplayEventConnection(this);
405 status_t EventThread::Connection::stealReceiveChannel(gui::BitTube* outChannel) {
406 outChannel->setReceiveFd(mChannel.moveReceiveFd());
410 status_t EventThread::Connection::setVsyncRate(uint32_t count) {
411 mEventThread->setVsyncRate(count, this);
415 void EventThread::Connection::requestNextVsync() {
416 mEventThread->requestNextVsync(this);
419 status_t EventThread::Connection::postEvent(
420 const DisplayEventReceiver::Event& event) {
421 ssize_t size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
422 return size < 0 ? status_t(size) : status_t(NO_ERROR);
425 // ---------------------------------------------------------------------------
427 }; // namespace android