1/*
2 * Copyright (C) 2011 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
17#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21
22#include <cutils/compiler.h>
23
24#include <gui/BitTube.h>
25#include <gui/IDisplayEventConnection.h>
26#include <gui/DisplayEventReceiver.h>
27
28#include <utils/Errors.h>
29#include <utils/String8.h>
30#include <utils/Trace.h>
31
32#include "EventThread.h"
33#include "SurfaceFlinger.h"
34
35// ---------------------------------------------------------------------------
36namespace android {
37// ---------------------------------------------------------------------------
38
39EventThread::EventThread(const sp<SurfaceFlinger>& flinger)
40    : mFlinger(flinger),
41      mUseSoftwareVSync(false),
42      mDebugVsyncEnabled(false) {
43
44    for (int32_t i=0 ; i<HWC_DISPLAY_TYPES_SUPPORTED ; i++) {
45        mVSyncEvent[i].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
46        mVSyncEvent[i].header.id = 0;
47        mVSyncEvent[i].header.timestamp = 0;
48        mVSyncEvent[i].vsync.count =  0;
49    }
50}
51
52void EventThread::onFirstRef() {
53    run("EventThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
54}
55
56sp<EventThread::Connection> EventThread::createEventConnection() const {
57    return new Connection(const_cast<EventThread*>(this));
58}
59
60status_t EventThread::registerDisplayEventConnection(
61        const sp<EventThread::Connection>& connection) {
62    Mutex::Autolock _l(mLock);
63    mDisplayEventConnections.add(connection);
64    mCondition.broadcast();
65    return NO_ERROR;
66}
67
68void EventThread::removeDisplayEventConnection(
69        const wp<EventThread::Connection>& connection) {
70    Mutex::Autolock _l(mLock);
71    mDisplayEventConnections.remove(connection);
72}
73
74void EventThread::setVsyncRate(uint32_t count,
75        const sp<EventThread::Connection>& connection) {
76    if (int32_t(count) >= 0) { // server must protect against bad params
77        Mutex::Autolock _l(mLock);
78        const int32_t new_count = (count == 0) ? -1 : count;
79        if (connection->count != new_count) {
80            connection->count = new_count;
81            mCondition.broadcast();
82        }
83    }
84}
85
86void EventThread::requestNextVsync(
87        const sp<EventThread::Connection>& connection) {
88    Mutex::Autolock _l(mLock);
89    if (connection->count < 0) {
90        connection->count = 0;
91        mCondition.broadcast();
92    }
93}
94
95void EventThread::onScreenReleased() {
96    Mutex::Autolock _l(mLock);
97    if (!mUseSoftwareVSync) {
98        // disable reliance on h/w vsync
99        mUseSoftwareVSync = true;
100        mCondition.broadcast();
101    }
102}
103
104void EventThread::onScreenAcquired() {
105    Mutex::Autolock _l(mLock);
106    if (mUseSoftwareVSync) {
107        // resume use of h/w vsync
108        mUseSoftwareVSync = false;
109        mCondition.broadcast();
110    }
111}
112
113
114void EventThread::onVSyncReceived(int type, nsecs_t timestamp) {
115    ALOGE_IF(type >= HWC_DISPLAY_TYPES_SUPPORTED,
116            "received event for an invalid display (id=%d)", type);
117
118    Mutex::Autolock _l(mLock);
119    if (type < HWC_DISPLAY_TYPES_SUPPORTED) {
120        mVSyncEvent[type].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
121        mVSyncEvent[type].header.id = type;
122        mVSyncEvent[type].header.timestamp = timestamp;
123        mVSyncEvent[type].vsync.count++;
124        mCondition.broadcast();
125    }
126}
127
128void EventThread::onHotplugReceived(int type, bool connected) {
129    ALOGE_IF(type >= HWC_DISPLAY_TYPES_SUPPORTED,
130            "received event for an invalid display (id=%d)", type);
131
132    Mutex::Autolock _l(mLock);
133    if (type < HWC_DISPLAY_TYPES_SUPPORTED) {
134        DisplayEventReceiver::Event event;
135        event.header.type = DisplayEventReceiver::DISPLAY_EVENT_HOTPLUG;
136        event.header.id = type;
137        event.header.timestamp = systemTime();
138        event.hotplug.connected = connected;
139        mPendingEvents.add(event);
140        mCondition.broadcast();
141    }
142}
143
144bool EventThread::threadLoop() {
145    DisplayEventReceiver::Event event;
146    Vector< sp<EventThread::Connection> > signalConnections;
147    signalConnections = waitForEvent(&event);
148
149    // dispatch events to listeners...
150    const size_t count = signalConnections.size();
151    for (size_t i=0 ; i<count ; i++) {
152        const sp<Connection>& conn(signalConnections[i]);
153        // now see if we still need to report this event
154        status_t err = conn->postEvent(event);
155        if (err == -EAGAIN || err == -EWOULDBLOCK) {
156            // The destination doesn't accept events anymore, it's probably
157            // full. For now, we just drop the events on the floor.
158            // FIXME: Note that some events cannot be dropped and would have
159            // to be re-sent later.
160            // Right-now we don't have the ability to do this.
161            ALOGW("EventThread: dropping event (%08x) for connection %p",
162                    event.header.type, conn.get());
163        } else if (err < 0) {
164            // handle any other error on the pipe as fatal. the only
165            // reasonable thing to do is to clean-up this connection.
166            // The most common error we'll get here is -EPIPE.
167            removeDisplayEventConnection(signalConnections[i]);
168        }
169    }
170    return true;
171}
172
173// This will return when (1) a vsync event has been received, and (2) there was
174// at least one connection interested in receiving it when we started waiting.
175Vector< sp<EventThread::Connection> > EventThread::waitForEvent(
176        DisplayEventReceiver::Event* event)
177{
178    Mutex::Autolock _l(mLock);
179    Vector< sp<EventThread::Connection> > signalConnections;
180
181    do {
182        bool eventPending = false;
183        bool waitForVSync = false;
184
185        size_t vsyncCount = 0;
186        nsecs_t timestamp = 0;
187        for (int32_t i=0 ; i<HWC_DISPLAY_TYPES_SUPPORTED ; i++) {
188            timestamp = mVSyncEvent[i].header.timestamp;
189            if (timestamp) {
190                // we have a vsync event to dispatch
191                *event = mVSyncEvent[i];
192                mVSyncEvent[i].header.timestamp = 0;
193                vsyncCount = mVSyncEvent[i].vsync.count;
194                break;
195            }
196        }
197
198        if (!timestamp) {
199            // no vsync event, see if there are some other event
200            eventPending = !mPendingEvents.isEmpty();
201            if (eventPending) {
202                // we have some other event to dispatch
203                *event = mPendingEvents[0];
204                mPendingEvents.removeAt(0);
205            }
206        }
207
208        // find out connections waiting for events
209        size_t count = mDisplayEventConnections.size();
210        for (size_t i=0 ; i<count ; i++) {
211            sp<Connection> connection(mDisplayEventConnections[i].promote());
212            if (connection != NULL) {
213                bool added = false;
214                if (connection->count >= 0) {
215                    // we need vsync events because at least
216                    // one connection is waiting for it
217                    waitForVSync = true;
218                    if (timestamp) {
219                        // we consume the event only if it's time
220                        // (ie: we received a vsync event)
221                        if (connection->count == 0) {
222                            // fired this time around
223                            connection->count = -1;
224                            signalConnections.add(connection);
225                            added = true;
226                        } else if (connection->count == 1 ||
227                                (vsyncCount % connection->count) == 0) {
228                            // continuous event, and time to report it
229                            signalConnections.add(connection);
230                            added = true;
231                        }
232                    }
233                }
234
235                if (eventPending && !timestamp && !added) {
236                    // we don't have a vsync event to process
237                    // (timestamp==0), but we have some pending
238                    // messages.
239                    signalConnections.add(connection);
240                }
241            } else {
242                // we couldn't promote this reference, the connection has
243                // died, so clean-up!
244                mDisplayEventConnections.removeAt(i);
245                --i; --count;
246            }
247        }
248
249        // Here we figure out if we need to enable or disable vsyncs
250        if (timestamp && !waitForVSync) {
251            // we received a VSYNC but we have no clients
252            // don't report it, and disable VSYNC events
253            disableVSyncLocked();
254        } else if (!timestamp && waitForVSync) {
255            // we have at least one client, so we want vsync enabled
256            // (TODO: this function is called right after we finish
257            // notifying clients of a vsync, so this call will be made
258            // at the vsync rate, e.g. 60fps.  If we can accurately
259            // track the current state we could avoid making this call
260            // so often.)
261            enableVSyncLocked();
262        }
263
264        // note: !timestamp implies signalConnections.isEmpty(), because we
265        // don't populate signalConnections if there's no vsync pending
266        if (!timestamp && !eventPending) {
267            // wait for something to happen
268            if (waitForVSync) {
269                // This is where we spend most of our time, waiting
270                // for vsync events and new client registrations.
271                //
272                // If the screen is off, we can't use h/w vsync, so we
273                // use a 16ms timeout instead.  It doesn't need to be
274                // precise, we just need to keep feeding our clients.
275                //
276                // We don't want to stall if there's a driver bug, so we
277                // use a (long) timeout when waiting for h/w vsync, and
278                // generate fake events when necessary.
279                bool softwareSync = mUseSoftwareVSync;
280                nsecs_t timeout = softwareSync ? ms2ns(16) : ms2ns(1000);
281                if (mCondition.waitRelative(mLock, timeout) == TIMED_OUT) {
282                    if (!softwareSync) {
283                        ALOGW("Timed out waiting for hw vsync; faking it");
284                    }
285                    // FIXME: how do we decide which display id the fake
286                    // vsync came from ?
287                    mVSyncEvent[0].header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
288                    mVSyncEvent[0].header.id = HWC_DISPLAY_PRIMARY;
289                    mVSyncEvent[0].header.timestamp = systemTime(SYSTEM_TIME_MONOTONIC);
290                    mVSyncEvent[0].vsync.count++;
291                }
292            } else {
293                // Nobody is interested in vsync, so we just want to sleep.
294                // h/w vsync should be disabled, so this will wait until we
295                // get a new connection, or an existing connection becomes
296                // interested in receiving vsync again.
297                mCondition.wait(mLock);
298            }
299        }
300    } while (signalConnections.isEmpty());
301
302    // here we're guaranteed to have a timestamp and some connections to signal
303    // (The connections might have dropped out of mDisplayEventConnections
304    // while we were asleep, but we'll still have strong references to them.)
305    return signalConnections;
306}
307
308void EventThread::enableVSyncLocked() {
309    if (!mUseSoftwareVSync) {
310        // never enable h/w VSYNC when screen is off
311        mFlinger->eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
312        mPowerHAL.vsyncHint(true);
313    }
314    mDebugVsyncEnabled = true;
315}
316
317void EventThread::disableVSyncLocked() {
318    mFlinger->eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
319    mPowerHAL.vsyncHint(false);
320    mDebugVsyncEnabled = false;
321}
322
323void EventThread::dump(String8& result, char* buffer, size_t SIZE) const {
324    Mutex::Autolock _l(mLock);
325    result.appendFormat("VSYNC state: %s\n",
326            mDebugVsyncEnabled?"enabled":"disabled");
327    result.appendFormat("  soft-vsync: %s\n",
328            mUseSoftwareVSync?"enabled":"disabled");
329    result.appendFormat("  numListeners=%u,\n  events-delivered: %u\n",
330            mDisplayEventConnections.size(),
331            mVSyncEvent[HWC_DISPLAY_PRIMARY].vsync.count);
332    for (size_t i=0 ; i<mDisplayEventConnections.size() ; i++) {
333        sp<Connection> connection =
334                mDisplayEventConnections.itemAt(i).promote();
335        result.appendFormat("    %p: count=%d\n",
336                connection.get(), connection!=NULL ? connection->count : 0);
337    }
338}
339
340// ---------------------------------------------------------------------------
341
342EventThread::Connection::Connection(
343        const sp<EventThread>& eventThread)
344    : count(-1), mEventThread(eventThread), mChannel(new BitTube())
345{
346}
347
348EventThread::Connection::~Connection() {
349    // do nothing here -- clean-up will happen automatically
350    // when the main thread wakes up
351}
352
353void EventThread::Connection::onFirstRef() {
354    // NOTE: mEventThread doesn't hold a strong reference on us
355    mEventThread->registerDisplayEventConnection(this);
356}
357
358sp<BitTube> EventThread::Connection::getDataChannel() const {
359    return mChannel;
360}
361
362void EventThread::Connection::setVsyncRate(uint32_t count) {
363    mEventThread->setVsyncRate(count, this);
364}
365
366void EventThread::Connection::requestNextVsync() {
367    mEventThread->requestNextVsync(this);
368}
369
370status_t EventThread::Connection::postEvent(
371        const DisplayEventReceiver::Event& event) {
372    ssize_t size = DisplayEventReceiver::sendEvents(mChannel, &event, 1);
373    return size < 0 ? status_t(size) : status_t(NO_ERROR);
374}
375
376// ---------------------------------------------------------------------------
377
378}; // namespace android
379