blob: 5e51bc6cc51e21d02e2ecfd2a0200639234968b2 [file] [log] [blame]
Jeff Brown5912f952013-07-01 19:10:31 -07001//
2// Copyright 2010 The Android Open Source Project
3//
4// Provides a shared memory transport for input events.
5//
6#define LOG_TAG "InputTransport"
Zimd8402b62023-06-02 11:56:26 +01007#define ATRACE_TAG ATRACE_TAG_INPUT
Jeff Brown5912f952013-07-01 19:10:31 -07008
Jeff Brown5912f952013-07-01 19:10:31 -07009#include <errno.h>
10#include <fcntl.h>
Michael Wrightd0a4a622014-06-09 19:03:32 -070011#include <inttypes.h>
Jeff Brown5912f952013-07-01 19:10:31 -070012#include <math.h>
Jeff Brown5912f952013-07-01 19:10:31 -070013#include <sys/socket.h>
Mark Salyzyna5e161b2016-09-29 08:08:05 -070014#include <sys/types.h>
Jeff Brown5912f952013-07-01 19:10:31 -070015#include <unistd.h>
16
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070017#include <android-base/logging.h>
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000018#include <android-base/properties.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000019#include <android-base/stringprintf.h>
20#include <binder/Parcel.h>
Jeff Brown5912f952013-07-01 19:10:31 -070021#include <cutils/properties.h>
Dominik Laskowski75788452021-02-09 18:51:25 -080022#include <ftl/enum.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070023#include <log/log.h>
Michael Wright3dd60e22019-03-27 22:06:44 +000024#include <utils/Trace.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070025
Jeff Brown5912f952013-07-01 19:10:31 -070026#include <input/InputTransport.h>
27
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000028namespace {
29
30/**
31 * Log debug messages about channel messages (send message, receive message).
32 * Enable this via "adb shell setprop log.tag.InputTransportMessages DEBUG"
33 * (requires restart)
34 */
35const bool DEBUG_CHANNEL_MESSAGES =
36 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Messages", ANDROID_LOG_INFO);
37
38/**
39 * Log debug messages whenever InputChannel objects are created/destroyed.
40 * Enable this via "adb shell setprop log.tag.InputTransportLifecycle DEBUG"
41 * (requires restart)
42 */
43const bool DEBUG_CHANNEL_LIFECYCLE =
44 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Lifecycle", ANDROID_LOG_INFO);
45
46/**
47 * Log debug messages relating to the consumer end of the transport channel.
48 * Enable this via "adb shell setprop log.tag.InputTransportConsumer DEBUG" (requires restart)
49 */
50
51const bool DEBUG_TRANSPORT_CONSUMER =
52 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Consumer", ANDROID_LOG_INFO);
53
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000054const bool IS_DEBUGGABLE_BUILD =
55#if defined(__ANDROID__)
56 android::base::GetBoolProperty("ro.debuggable", false);
57#else
58 true;
59#endif
60
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000061/**
62 * Log debug messages relating to the producer end of the transport channel.
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000063 * Enable this via "adb shell setprop log.tag.InputTransportPublisher DEBUG".
64 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
65 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000066 */
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +000067bool debugTransportPublisher() {
68 if (!IS_DEBUGGABLE_BUILD) {
69 static const bool DEBUG_TRANSPORT_PUBLISHER =
70 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
71 return DEBUG_TRANSPORT_PUBLISHER;
72 }
73 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Publisher", ANDROID_LOG_INFO);
74}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000075
76/**
77 * Log debug messages about touch event resampling.
Harry Cutts6c658cc2023-08-02 14:40:40 +000078 *
79 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG".
80 * This requires a restart on non-debuggable (e.g. user) builds, but should take effect immediately
81 * on debuggable builds (e.g. userdebug).
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000082 */
Harry Cutts6c658cc2023-08-02 14:40:40 +000083bool debugResampling() {
84 if (!IS_DEBUGGABLE_BUILD) {
85 static const bool DEBUG_TRANSPORT_RESAMPLING =
86 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling",
87 ANDROID_LOG_INFO);
88 return DEBUG_TRANSPORT_RESAMPLING;
89 }
90 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
91}
Prabir Pradhan60dd97a2023-02-23 02:23:02 +000092
93} // namespace
94
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070095using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +000096using android::base::StringPrintf;
97
Jeff Brown5912f952013-07-01 19:10:31 -070098namespace android {
99
100// Socket buffer size. The default is typically about 128KB, which is much larger than
101// we really need. So we make it smaller. It just needs to be big enough to hold
102// a few dozen large multi-finger motion events in the case where an application gets
103// behind processing touches.
104static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
105
106// Nanoseconds per milliseconds.
107static const nsecs_t NANOS_PER_MS = 1000000;
108
109// Latency added during resampling. A few milliseconds doesn't hurt much but
110// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800111const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700112
113// Minimum time difference between consecutive samples before attempting to resample.
114static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
115
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700116// Maximum time difference between consecutive samples before attempting to resample
117// by extrapolation.
118static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
119
Jeff Brown5912f952013-07-01 19:10:31 -0700120// Maximum time to predict forward from the last known state, to avoid predicting too
121// far into the future. This time is further bounded by 50% of the last time delta.
122static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
123
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600124/**
125 * System property for enabling / disabling touch resampling.
126 * Resampling extrapolates / interpolates the reported touch event coordinates to better
127 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
128 * Resampling is not needed (and should be disabled) on hardware that already
129 * has touch events triggered by VSYNC.
130 * Set to "1" to enable resampling (default).
131 * Set to "0" to disable resampling.
132 * Resampling is enabled by default.
133 */
134static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
135
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800136/**
137 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
138 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
139 */
140static bool verifyEvents() {
141 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
142}
143
Jeff Brown5912f952013-07-01 19:10:31 -0700144template<typename T>
145inline static T min(const T& a, const T& b) {
146 return a < b ? a : b;
147}
148
149inline static float lerp(float a, float b, float alpha) {
150 return a + alpha * (b - a);
151}
152
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800153inline static bool isPointerEvent(int32_t source) {
154 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
155}
156
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800157inline static const char* toString(bool value) {
158 return value ? "true" : "false";
159}
160
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700161static bool shouldResampleTool(ToolType toolType) {
162 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
163}
164
Jeff Brown5912f952013-07-01 19:10:31 -0700165// --- InputMessage ---
166
167bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000168 if (size() != actualSize) {
169 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
170 return false;
171 }
172
173 switch (header.type) {
174 case Type::KEY:
175 return true;
176 case Type::MOTION: {
177 const bool valid =
178 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
179 if (!valid) {
180 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
181 }
182 return valid;
183 }
184 case Type::FINISHED:
185 case Type::FOCUS:
186 case Type::CAPTURE:
187 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700188 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000189 return true;
190 case Type::TIMELINE: {
191 const nsecs_t gpuCompletedTime =
192 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
193 const nsecs_t presentTime =
194 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
195 const bool valid = presentTime > gpuCompletedTime;
196 if (!valid) {
197 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
198 " presentTime = %" PRId64,
199 gpuCompletedTime, presentTime);
200 }
201 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700202 }
203 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000204 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700205 return false;
206}
207
208size_t InputMessage::size() const {
209 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700210 case Type::KEY:
211 return sizeof(Header) + body.key.size();
212 case Type::MOTION:
213 return sizeof(Header) + body.motion.size();
214 case Type::FINISHED:
215 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800216 case Type::FOCUS:
217 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800218 case Type::CAPTURE:
219 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800220 case Type::DRAG:
221 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000222 case Type::TIMELINE:
223 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700224 case Type::TOUCH_MODE:
225 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700226 }
227 return sizeof(Header);
228}
229
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800230/**
231 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
232 * memory to zero, then only copy the valid bytes on a per-field basis.
233 */
234void InputMessage::getSanitizedCopy(InputMessage* msg) const {
235 memset(msg, 0, sizeof(*msg));
236
237 // Write the header
238 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500239 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800240
241 // Write the body
242 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700243 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800244 // int32_t eventId
245 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800246 // nsecs_t eventTime
247 msg->body.key.eventTime = body.key.eventTime;
248 // int32_t deviceId
249 msg->body.key.deviceId = body.key.deviceId;
250 // int32_t source
251 msg->body.key.source = body.key.source;
252 // int32_t displayId
253 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600254 // std::array<uint8_t, 32> hmac
255 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800256 // int32_t action
257 msg->body.key.action = body.key.action;
258 // int32_t flags
259 msg->body.key.flags = body.key.flags;
260 // int32_t keyCode
261 msg->body.key.keyCode = body.key.keyCode;
262 // int32_t scanCode
263 msg->body.key.scanCode = body.key.scanCode;
264 // int32_t metaState
265 msg->body.key.metaState = body.key.metaState;
266 // int32_t repeatCount
267 msg->body.key.repeatCount = body.key.repeatCount;
268 // nsecs_t downTime
269 msg->body.key.downTime = body.key.downTime;
270 break;
271 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700272 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800273 // int32_t eventId
274 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700275 // uint32_t pointerCount
276 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800277 // nsecs_t eventTime
278 msg->body.motion.eventTime = body.motion.eventTime;
279 // int32_t deviceId
280 msg->body.motion.deviceId = body.motion.deviceId;
281 // int32_t source
282 msg->body.motion.source = body.motion.source;
283 // int32_t displayId
284 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600285 // std::array<uint8_t, 32> hmac
286 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800287 // int32_t action
288 msg->body.motion.action = body.motion.action;
289 // int32_t actionButton
290 msg->body.motion.actionButton = body.motion.actionButton;
291 // int32_t flags
292 msg->body.motion.flags = body.motion.flags;
293 // int32_t metaState
294 msg->body.motion.metaState = body.motion.metaState;
295 // int32_t buttonState
296 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800297 // MotionClassification classification
298 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800299 // int32_t edgeFlags
300 msg->body.motion.edgeFlags = body.motion.edgeFlags;
301 // nsecs_t downTime
302 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700303
304 msg->body.motion.dsdx = body.motion.dsdx;
305 msg->body.motion.dtdx = body.motion.dtdx;
306 msg->body.motion.dtdy = body.motion.dtdy;
307 msg->body.motion.dsdy = body.motion.dsdy;
308 msg->body.motion.tx = body.motion.tx;
309 msg->body.motion.ty = body.motion.ty;
310
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800311 // float xPrecision
312 msg->body.motion.xPrecision = body.motion.xPrecision;
313 // float yPrecision
314 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700315 // float xCursorPosition
316 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
317 // float yCursorPosition
318 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700319
320 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
321 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
322 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
323 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
324 msg->body.motion.txRaw = body.motion.txRaw;
325 msg->body.motion.tyRaw = body.motion.tyRaw;
326
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800327 //struct Pointer pointers[MAX_POINTERS]
328 for (size_t i = 0; i < body.motion.pointerCount; i++) {
329 // PointerProperties properties
330 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
331 msg->body.motion.pointers[i].properties.toolType =
332 body.motion.pointers[i].properties.toolType,
333 // PointerCoords coords
334 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
335 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
336 memcpy(&msg->body.motion.pointers[i].coords.values[0],
337 &body.motion.pointers[i].coords.values[0],
338 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800339 msg->body.motion.pointers[i].coords.isResampled =
340 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800341 }
342 break;
343 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700344 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800345 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000346 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800347 break;
348 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800349 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800350 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800351 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800352 break;
353 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800354 case InputMessage::Type::CAPTURE: {
355 msg->body.capture.eventId = body.capture.eventId;
356 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
357 break;
358 }
arthurhung7632c332020-12-30 16:58:01 +0800359 case InputMessage::Type::DRAG: {
360 msg->body.drag.eventId = body.drag.eventId;
361 msg->body.drag.x = body.drag.x;
362 msg->body.drag.y = body.drag.y;
363 msg->body.drag.isExiting = body.drag.isExiting;
364 break;
365 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000366 case InputMessage::Type::TIMELINE: {
367 msg->body.timeline.eventId = body.timeline.eventId;
368 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
369 break;
370 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700371 case InputMessage::Type::TOUCH_MODE: {
372 msg->body.touchMode.eventId = body.touchMode.eventId;
373 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
374 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800375 }
376}
Jeff Brown5912f952013-07-01 19:10:31 -0700377
378// --- InputChannel ---
379
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500380std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500381 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700382 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
383 if (result != 0) {
384 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
385 strerror(errno));
386 return nullptr;
387 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500388 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500389 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700390}
391
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500392InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
393 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000394 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
395 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700396}
397
398InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000399 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
400 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700401}
402
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800403status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500404 std::unique_ptr<InputChannel>& outServerChannel,
405 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700406 int sockets[2];
407 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
408 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000409 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
410 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500411 outServerChannel.reset();
412 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700413 return result;
414 }
415
416 int bufferSize = SOCKET_BUFFER_SIZE;
417 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
418 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
419 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
420 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
421
Siarhei Vishniakou4c155eb2023-06-30 11:47:12 -0700422 sp<IBinder> token = sp<BBinder>::make();
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700423
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700424 std::string serverChannelName = name + " (server)";
425 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700426 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700427
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700428 std::string clientChannelName = name + " (client)";
429 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700430 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700431 return OK;
432}
433
434status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800435 const size_t msgLength = msg->size();
436 InputMessage cleanMsg;
437 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700438 ssize_t nWrite;
439 do {
Chris Ye0783e992020-06-02 21:34:49 -0700440 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700441 } while (nWrite == -1 && errno == EINTR);
442
443 if (nWrite < 0) {
444 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000445 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
446 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700447 if (error == EAGAIN || error == EWOULDBLOCK) {
448 return WOULD_BLOCK;
449 }
450 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
451 return DEAD_OBJECT;
452 }
453 return -error;
454 }
455
456 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000457 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
458 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
459 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700460 return DEAD_OBJECT;
461 }
462
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000463 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
464 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100465
466 if (ATRACE_ENABLED()) {
467 std::string message =
468 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32 ")",
469 mName.c_str(), msg->header.seq, msg->header.type);
470 ATRACE_NAME(message.c_str());
471 }
Jeff Brown5912f952013-07-01 19:10:31 -0700472 return OK;
473}
474
475status_t InputChannel::receiveMessage(InputMessage* msg) {
476 ssize_t nRead;
477 do {
Chris Ye0783e992020-06-02 21:34:49 -0700478 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700479 } while (nRead == -1 && errno == EINTR);
480
481 if (nRead < 0) {
482 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000483 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
484 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700485 if (error == EAGAIN || error == EWOULDBLOCK) {
486 return WOULD_BLOCK;
487 }
488 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
489 return DEAD_OBJECT;
490 }
491 return -error;
492 }
493
494 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000495 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
496 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700497 return DEAD_OBJECT;
498 }
499
500 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000501 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700502 return BAD_VALUE;
503 }
504
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000505 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
506 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100507
508 if (ATRACE_ENABLED()) {
509 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
510 ", type=0x%" PRIx32 ")",
511 mName.c_str(), msg->header.seq, msg->header.type);
512 ATRACE_NAME(message.c_str());
513 }
Jeff Brown5912f952013-07-01 19:10:31 -0700514 return OK;
515}
516
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500517std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700518 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700519 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700520}
521
Garfield Tan15601662020-09-22 15:32:38 -0700522void InputChannel::copyTo(InputChannel& outChannel) const {
523 outChannel.mName = getName();
524 outChannel.mFd = dupFd();
525 outChannel.mToken = getConnectionToken();
526}
527
Chris Ye0783e992020-06-02 21:34:49 -0700528status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500529 if (parcel == nullptr) {
530 ALOGE("%s: Null parcel", __func__);
531 return BAD_VALUE;
532 }
533 return parcel->writeStrongBinder(mToken)
534 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700535}
536
Chris Ye0783e992020-06-02 21:34:49 -0700537status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500538 if (parcel == nullptr) {
539 ALOGE("%s: Null parcel", __func__);
540 return BAD_VALUE;
541 }
542 mToken = parcel->readStrongBinder();
543 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700544}
545
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700546sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500547 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700548}
549
Garfield Tan15601662020-09-22 15:32:38 -0700550base::unique_fd InputChannel::dupFd() const {
551 android::base::unique_fd newFd(::dup(getFd()));
552 if (!newFd.ok()) {
553 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
554 strerror(errno));
555 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
556 // If this process is out of file descriptors, then throwing that might end up exploding
557 // on the other side of a binder call, which isn't really helpful.
558 // Better to just crash here and hope that the FD leak is slow.
559 // Other failures could be client errors, so we still propagate those back to the caller.
560 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
561 getName().c_str());
562 return {};
563 }
564 return newFd;
565}
566
Jeff Brown5912f952013-07-01 19:10:31 -0700567// --- InputPublisher ---
568
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800569InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
570 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700571
572InputPublisher::~InputPublisher() {
573}
574
Garfield Tan1c7bc862020-01-28 13:24:04 -0800575status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
576 int32_t source, int32_t displayId,
577 std::array<uint8_t, 32> hmac, int32_t action,
578 int32_t flags, int32_t keyCode, int32_t scanCode,
579 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
580 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000581 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000582 std::string message =
583 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
584 mChannel->getName().c_str(), KeyEvent::actionToString(action),
585 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000586 ATRACE_NAME(message.c_str());
587 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000588 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000589 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000590 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
591 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000592 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000593 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
594 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700595
596 if (!seq) {
597 ALOGE("Attempted to publish a key event with sequence number 0.");
598 return BAD_VALUE;
599 }
600
601 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700602 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500603 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800604 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700605 msg.body.key.deviceId = deviceId;
606 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100607 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700608 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700609 msg.body.key.action = action;
610 msg.body.key.flags = flags;
611 msg.body.key.keyCode = keyCode;
612 msg.body.key.scanCode = scanCode;
613 msg.body.key.metaState = metaState;
614 msg.body.key.repeatCount = repeatCount;
615 msg.body.key.downTime = downTime;
616 msg.body.key.eventTime = eventTime;
617 return mChannel->sendMessage(&msg);
618}
619
620status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800621 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600622 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
623 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700624 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700625 float yPrecision, float xCursorPosition, float yCursorPosition,
626 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700627 uint32_t pointerCount, const PointerProperties* pointerProperties,
628 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000629 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000630 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
631 mChannel->getName().c_str(),
632 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000633 ATRACE_NAME(message.c_str());
634 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800635 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700636 Result<void> result =
637 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
638 pointerCoords, flags);
639 if (!result.ok()) {
640 LOG(FATAL) << "Bad stream: " << result.error();
641 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800642 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000643 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700644 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700645 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000646 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800647 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000648 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700649 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800650 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700651 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000652 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000653 inputEventSourceToString(source).c_str(), displayId,
654 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
655 metaState, buttonState, motionClassificationToString(classification), xPrecision,
656 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800657 }
Jeff Brown5912f952013-07-01 19:10:31 -0700658
659 if (!seq) {
660 ALOGE("Attempted to publish a motion event with sequence number 0.");
661 return BAD_VALUE;
662 }
663
664 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700665 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800666 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700667 return BAD_VALUE;
668 }
669
670 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700671 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500672 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800673 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700674 msg.body.motion.deviceId = deviceId;
675 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700676 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700677 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700678 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100679 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700680 msg.body.motion.flags = flags;
681 msg.body.motion.edgeFlags = edgeFlags;
682 msg.body.motion.metaState = metaState;
683 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800684 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700685 msg.body.motion.dsdx = transform.dsdx();
686 msg.body.motion.dtdx = transform.dtdx();
687 msg.body.motion.dtdy = transform.dtdy();
688 msg.body.motion.dsdy = transform.dsdy();
689 msg.body.motion.tx = transform.tx();
690 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700691 msg.body.motion.xPrecision = xPrecision;
692 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700693 msg.body.motion.xCursorPosition = xCursorPosition;
694 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700695 msg.body.motion.dsdxRaw = rawTransform.dsdx();
696 msg.body.motion.dtdxRaw = rawTransform.dtdx();
697 msg.body.motion.dtdyRaw = rawTransform.dtdy();
698 msg.body.motion.dsdyRaw = rawTransform.dsdy();
699 msg.body.motion.txRaw = rawTransform.tx();
700 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700701 msg.body.motion.downTime = downTime;
702 msg.body.motion.eventTime = eventTime;
703 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100704 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -0700705 msg.body.motion.pointers[i].properties = pointerProperties[i];
706 msg.body.motion.pointers[i].coords = pointerCoords[i];
Jeff Brown5912f952013-07-01 19:10:31 -0700707 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700708
Jeff Brown5912f952013-07-01 19:10:31 -0700709 return mChannel->sendMessage(&msg);
710}
711
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700712status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800713 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700714 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
715 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800716 ATRACE_NAME(message.c_str());
717 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000718 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
719 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800720
721 InputMessage msg;
722 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500723 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800724 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000725 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800726 return mChannel->sendMessage(&msg);
727}
728
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800729status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
730 bool pointerCaptureEnabled) {
731 if (ATRACE_ENABLED()) {
732 std::string message =
733 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
734 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
735 ATRACE_NAME(message.c_str());
736 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000737 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000738 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
739 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800740
741 InputMessage msg;
742 msg.header.type = InputMessage::Type::CAPTURE;
743 msg.header.seq = seq;
744 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000745 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800746 return mChannel->sendMessage(&msg);
747}
748
arthurhung7632c332020-12-30 16:58:01 +0800749status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
750 bool isExiting) {
751 if (ATRACE_ENABLED()) {
752 std::string message =
753 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
754 mChannel->getName().c_str(), x, y, toString(isExiting));
755 ATRACE_NAME(message.c_str());
756 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000757 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000758 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
759 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800760
761 InputMessage msg;
762 msg.header.type = InputMessage::Type::DRAG;
763 msg.header.seq = seq;
764 msg.body.drag.eventId = eventId;
765 msg.body.drag.isExiting = isExiting;
766 msg.body.drag.x = x;
767 msg.body.drag.y = y;
768 return mChannel->sendMessage(&msg);
769}
770
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700771status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
772 if (ATRACE_ENABLED()) {
773 std::string message =
774 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
775 mChannel->getName().c_str(), toString(isInTouchMode));
776 ATRACE_NAME(message.c_str());
777 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000778 ALOGD_IF(debugTransportPublisher(),
779 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
780 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700781
782 InputMessage msg;
783 msg.header.type = InputMessage::Type::TOUCH_MODE;
784 msg.header.seq = seq;
785 msg.body.touchMode.eventId = eventId;
786 msg.body.touchMode.isInTouchMode = isInTouchMode;
787 return mChannel->sendMessage(&msg);
788}
789
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000790android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700791 InputMessage msg;
792 status_t result = mChannel->receiveMessage(&msg);
793 if (result) {
Siarhei Vishniakou69112652023-08-24 08:34:18 -0700794 if (debugTransportPublisher() && result != WOULD_BLOCK) {
795 LOG(INFO) << "channel '" << mChannel->getName() << "' publisher ~ " << __func__ << ": "
796 << strerror(result);
797 }
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000798 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700799 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000800 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000801 ALOGD_IF(debugTransportPublisher(),
802 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
803 mChannel->getName().c_str(), __func__, msg.header.seq,
804 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000805 return Finished{
806 .seq = msg.header.seq,
807 .handled = msg.body.finished.handled,
808 .consumeTime = msg.body.finished.consumeTime,
809 };
Jeff Brown5912f952013-07-01 19:10:31 -0700810 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000811
812 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000813 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
814 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000815 return Timeline{
816 .inputEventId = msg.body.timeline.eventId,
817 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
818 };
819 }
820
821 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800822 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000823 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700824}
825
826// --- InputConsumer ---
827
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500828InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800829 : InputConsumer(channel, isTouchResamplingEnabled()) {}
830
831InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
832 bool enableTouchResampling)
833 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700834
835InputConsumer::~InputConsumer() {
836}
837
838bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600839 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700840}
841
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800842status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
843 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000844 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
845 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
846 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700847
848 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700849 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700850
851 // Fetch the next input message.
852 // Loop until an event can be returned or no additional events are received.
853 while (!*outEvent) {
854 if (mMsgDeferred) {
855 // mMsg contains a valid input message from the previous call to consume
856 // that has not yet been processed.
857 mMsgDeferred = false;
858 } else {
859 // Receive a fresh message.
860 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000861 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800862 const auto [_, inserted] =
863 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
864 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
865 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000866 }
Jeff Brown5912f952013-07-01 19:10:31 -0700867 if (result) {
868 // Consume the next batched event unless batches are being held for later.
869 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800870 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700871 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000872 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
873 "channel '%s' consumer ~ consumed batch event, seq=%u",
874 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700875 break;
876 }
877 }
878 return result;
879 }
880 }
881
882 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700883 case InputMessage::Type::KEY: {
884 KeyEvent* keyEvent = factory->createKeyEvent();
885 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700886
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700887 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500888 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700889 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000890 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
891 "channel '%s' consumer ~ consumed key event, seq=%u",
892 mChannel->getName().c_str(), *outSeq);
893 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700894 }
Jeff Brown5912f952013-07-01 19:10:31 -0700895
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700896 case InputMessage::Type::MOTION: {
897 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
898 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500899 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700900 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500901 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000902 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
903 "channel '%s' consumer ~ appended to batch event",
904 mChannel->getName().c_str());
905 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700906 } else if (isPointerEvent(mMsg.body.motion.source) &&
907 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
908 // No need to process events that we are going to cancel anyways
909 const size_t count = batch.samples.size();
910 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500911 const InputMessage& msg = batch.samples[i];
912 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700913 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500914 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
915 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700916 } else {
917 // We cannot append to the batch in progress, so we need to consume
918 // the previous batch right now and defer the new message until later.
919 mMsgDeferred = true;
920 status_t result = consumeSamples(factory, batch, batch.samples.size(),
921 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500922 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700923 if (result) {
924 return result;
925 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000926 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
927 "channel '%s' consumer ~ consumed batch event and "
928 "deferred current event, seq=%u",
929 mChannel->getName().c_str(), *outSeq);
930 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700931 }
Jeff Brown5912f952013-07-01 19:10:31 -0700932 }
Jeff Brown5912f952013-07-01 19:10:31 -0700933
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800934 // Start a new batch if needed.
935 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
936 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500937 Batch batch;
938 batch.samples.push_back(mMsg);
939 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000940 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
941 "channel '%s' consumer ~ started batch event",
942 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800943 break;
944 }
Jeff Brown5912f952013-07-01 19:10:31 -0700945
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800946 MotionEvent* motionEvent = factory->createMotionEvent();
947 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700948
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800949 updateTouchState(mMsg);
950 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500951 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800952 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800953
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000954 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
955 "channel '%s' consumer ~ consumed motion event, seq=%u",
956 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800957 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700958 }
Jeff Brown5912f952013-07-01 19:10:31 -0700959
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000960 case InputMessage::Type::FINISHED:
961 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000962 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
963 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800964 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800965 break;
966 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800967
968 case InputMessage::Type::FOCUS: {
969 FocusEvent* focusEvent = factory->createFocusEvent();
970 if (!focusEvent) return NO_MEMORY;
971
972 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500973 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800974 *outEvent = focusEvent;
975 break;
976 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800977
978 case InputMessage::Type::CAPTURE: {
979 CaptureEvent* captureEvent = factory->createCaptureEvent();
980 if (!captureEvent) return NO_MEMORY;
981
982 initializeCaptureEvent(captureEvent, &mMsg);
983 *outSeq = mMsg.header.seq;
984 *outEvent = captureEvent;
985 break;
986 }
arthurhung7632c332020-12-30 16:58:01 +0800987
988 case InputMessage::Type::DRAG: {
989 DragEvent* dragEvent = factory->createDragEvent();
990 if (!dragEvent) return NO_MEMORY;
991
992 initializeDragEvent(dragEvent, &mMsg);
993 *outSeq = mMsg.header.seq;
994 *outEvent = dragEvent;
995 break;
996 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700997
998 case InputMessage::Type::TOUCH_MODE: {
999 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
1000 if (!touchModeEvent) return NO_MEMORY;
1001
1002 initializeTouchModeEvent(touchModeEvent, &mMsg);
1003 *outSeq = mMsg.header.seq;
1004 *outEvent = touchModeEvent;
1005 break;
1006 }
Jeff Brown5912f952013-07-01 19:10:31 -07001007 }
1008 }
1009 return OK;
1010}
1011
1012status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001013 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001014 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001015 for (size_t i = mBatches.size(); i > 0; ) {
1016 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001017 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001018 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001019 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001020 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001021 return result;
1022 }
1023
Michael Wright32232172013-10-21 12:05:22 -07001024 nsecs_t sampleTime = frameTime;
1025 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001026 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001027 }
Jeff Brown5912f952013-07-01 19:10:31 -07001028 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1029 if (split < 0) {
1030 continue;
1031 }
1032
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001033 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001034 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001035 if (batch.samples.empty()) {
1036 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001037 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001038 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001039 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001040 }
Michael Wright32232172013-10-21 12:05:22 -07001041 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001042 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1043 }
1044 return result;
1045 }
1046
1047 return WOULD_BLOCK;
1048}
1049
1050status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001051 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001052 MotionEvent* motionEvent = factory->createMotionEvent();
1053 if (! motionEvent) return NO_MEMORY;
1054
1055 uint32_t chain = 0;
1056 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001057 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001058 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001059 if (i) {
1060 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001061 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001062 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001063 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001064 addSample(motionEvent, &msg);
1065 } else {
1066 initializeMotionEvent(motionEvent, &msg);
1067 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001068 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001069 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001070 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001071
1072 *outSeq = chain;
1073 *outEvent = motionEvent;
1074 return OK;
1075}
1076
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001077void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001078 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001079 return;
1080 }
1081
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001082 int32_t deviceId = msg.body.motion.deviceId;
1083 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001084
1085 // Update the touch state history to incorporate the new input message.
1086 // If the message is in the past relative to the most recently produced resampled
1087 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001088 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001089 case AMOTION_EVENT_ACTION_DOWN: {
1090 ssize_t index = findTouchState(deviceId, source);
1091 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001092 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001093 index = mTouchStates.size() - 1;
1094 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001095 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001096 touchState.initialize(deviceId, source);
1097 touchState.addHistory(msg);
1098 break;
1099 }
1100
1101 case AMOTION_EVENT_ACTION_MOVE: {
1102 ssize_t index = findTouchState(deviceId, source);
1103 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001104 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001105 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001106 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001107 }
1108 break;
1109 }
1110
1111 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1112 ssize_t index = findTouchState(deviceId, source);
1113 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001114 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001115 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001116 rewriteMessage(touchState, msg);
1117 }
1118 break;
1119 }
1120
1121 case AMOTION_EVENT_ACTION_POINTER_UP: {
1122 ssize_t index = findTouchState(deviceId, source);
1123 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001124 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001125 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001126 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001127 }
1128 break;
1129 }
1130
1131 case AMOTION_EVENT_ACTION_SCROLL: {
1132 ssize_t index = findTouchState(deviceId, source);
1133 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001134 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001135 rewriteMessage(touchState, msg);
1136 }
1137 break;
1138 }
1139
1140 case AMOTION_EVENT_ACTION_UP:
1141 case AMOTION_EVENT_ACTION_CANCEL: {
1142 ssize_t index = findTouchState(deviceId, source);
1143 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001144 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001145 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001146 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001147 }
1148 break;
1149 }
1150 }
1151}
1152
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001153/**
1154 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1155 *
1156 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1157 * is in the past relative to msg and the past two events do not contain identical coordinates),
1158 * then invalidate the lastResample data for that pointer.
1159 * If the two past events have identical coordinates, then lastResample data for that pointer will
1160 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1161 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1162 * not equal to x0 is received.
1163 */
1164void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001165 nsecs_t eventTime = msg.body.motion.eventTime;
1166 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1167 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001168 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001169 if (eventTime < state.lastResample.eventTime ||
1170 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001171 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1172 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001173 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001174 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1175 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001176 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1177 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001178 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001179 } else {
1180 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001181 }
Jeff Brown5912f952013-07-01 19:10:31 -07001182 }
1183 }
1184}
1185
1186void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1187 const InputMessage* next) {
1188 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001189 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001190 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1191 return;
1192 }
1193
1194 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1195 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001196 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001197 return;
1198 }
1199
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001200 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001201 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001202 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001203 return;
1204 }
1205
1206 // Ensure that the current sample has all of the pointers that need to be reported.
1207 const History* current = touchState.getHistory(0);
1208 size_t pointerCount = event->getPointerCount();
1209 for (size_t i = 0; i < pointerCount; i++) {
1210 uint32_t id = event->getPointerId(i);
1211 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001212 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001213 return;
1214 }
1215 }
1216
1217 // Find the data to use for resampling.
1218 const History* other;
1219 History future;
1220 float alpha;
1221 if (next) {
1222 // Interpolate between current sample and future sample.
1223 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001224 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001225 other = &future;
1226 nsecs_t delta = future.eventTime - current->eventTime;
1227 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001228 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001229 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001230 return;
1231 }
1232 alpha = float(sampleTime - current->eventTime) / delta;
1233 } else if (touchState.historySize >= 2) {
1234 // Extrapolate future sample using current sample and past sample.
1235 // So other->eventTime <= current->eventTime <= sampleTime.
1236 other = touchState.getHistory(1);
1237 nsecs_t delta = current->eventTime - other->eventTime;
1238 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001239 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001240 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001241 return;
1242 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001243 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001244 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001245 return;
1246 }
1247 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1248 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001249 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001250 "Sample time is too far in the future, adjusting prediction "
1251 "from %" PRId64 " to %" PRId64 " ns.",
1252 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001253 sampleTime = maxPredict;
1254 }
1255 alpha = float(current->eventTime - sampleTime) / delta;
1256 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001257 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001258 return;
1259 }
1260
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001261 if (current->eventTime == sampleTime) {
1262 // Prevents having 2 events with identical times and coordinates.
1263 return;
1264 }
1265
Jeff Brown5912f952013-07-01 19:10:31 -07001266 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001267 History oldLastResample;
1268 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001269 touchState.lastResample.eventTime = sampleTime;
1270 touchState.lastResample.idBits.clear();
1271 for (size_t i = 0; i < pointerCount; i++) {
1272 uint32_t id = event->getPointerId(i);
1273 touchState.lastResample.idToIndex[id] = i;
1274 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001275 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1276 // We maintain the previously resampled value for this pointer (stored in
1277 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1278 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001279 // The isResampled flag isn't cleared as the values don't reflect what the device is
1280 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001281
1282 // We know here that the coordinates for the pointer haven't changed because we
1283 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1284 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001285 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001286 continue;
1287 }
1288
Jeff Brown5912f952013-07-01 19:10:31 -07001289 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1290 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001291 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001292 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001293 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001294 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001295 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001296 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001297 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001298 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001299 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001300 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1301 "other (%0.3f, %0.3f), alpha %0.3f",
1302 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1303 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001304 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001305 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001306 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1307 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001308 }
1309 }
1310
1311 event->addSample(sampleTime, touchState.lastResample.pointers);
1312}
1313
Jeff Brown5912f952013-07-01 19:10:31 -07001314status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001315 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1316 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1317 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001318
1319 if (!seq) {
1320 ALOGE("Attempted to send a finished signal with sequence number 0.");
1321 return BAD_VALUE;
1322 }
1323
1324 // Send finished signals for the batch sequence chain first.
1325 size_t seqChainCount = mSeqChains.size();
1326 if (seqChainCount) {
1327 uint32_t currentSeq = seq;
1328 uint32_t chainSeqs[seqChainCount];
1329 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001330 for (size_t i = seqChainCount; i > 0; ) {
1331 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001332 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001333 if (seqChain.seq == currentSeq) {
1334 currentSeq = seqChain.chain;
1335 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001336 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001337 }
1338 }
1339 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001340 while (!status && chainIndex > 0) {
1341 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001342 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1343 }
1344 if (status) {
1345 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001346 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001347 SeqChain seqChain;
1348 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1349 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001350 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001351 if (!chainIndex) break;
1352 chainIndex--;
1353 }
Jeff Brown5912f952013-07-01 19:10:31 -07001354 return status;
1355 }
1356 }
1357
1358 // Send finished signal for the last message in the batch.
1359 return sendUnchainedFinishedSignal(seq, handled);
1360}
1361
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001362status_t InputConsumer::sendTimeline(int32_t inputEventId,
1363 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001364 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1365 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1366 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1367 mChannel->getName().c_str(), inputEventId,
1368 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1369 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001370
1371 InputMessage msg;
1372 msg.header.type = InputMessage::Type::TIMELINE;
1373 msg.header.seq = 0;
1374 msg.body.timeline.eventId = inputEventId;
1375 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1376 return mChannel->sendMessage(&msg);
1377}
1378
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001379nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1380 auto it = mConsumeTimes.find(seq);
1381 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1382 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1383 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1384 seq);
1385 return it->second;
1386}
1387
1388void InputConsumer::popConsumeTime(uint32_t seq) {
1389 mConsumeTimes.erase(seq);
1390}
1391
Jeff Brown5912f952013-07-01 19:10:31 -07001392status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1393 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001394 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001395 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001396 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001397 msg.body.finished.consumeTime = getConsumeTime(seq);
1398 status_t result = mChannel->sendMessage(&msg);
1399 if (result == OK) {
1400 // Remove the consume time if the socket write succeeded. We will not need to ack this
1401 // message anymore. If the socket write did not succeed, we will try again and will still
1402 // need consume time.
1403 popConsumeTime(seq);
1404 }
1405 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001406}
1407
Jeff Brown5912f952013-07-01 19:10:31 -07001408bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001409 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001410}
1411
Arthur Hungc7812be2020-02-27 22:40:27 +08001412int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001413 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001414 return AINPUT_SOURCE_CLASS_NONE;
1415 }
1416
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001417 const Batch& batch = mBatches[0];
1418 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001419 return head.body.motion.source;
1420}
1421
Jeff Brown5912f952013-07-01 19:10:31 -07001422ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1423 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001424 const Batch& batch = mBatches[i];
1425 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001426 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1427 return i;
1428 }
1429 }
1430 return -1;
1431}
1432
1433ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1434 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001435 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001436 if (touchState.deviceId == deviceId && touchState.source == source) {
1437 return i;
1438 }
1439 }
1440 return -1;
1441}
1442
1443void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001444 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001445 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1446 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1447 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1448 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001449}
1450
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001451void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001452 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001453}
1454
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001455void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001456 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001457}
1458
arthurhung7632c332020-12-30 16:58:01 +08001459void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1460 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1461 msg->body.drag.isExiting);
1462}
1463
Jeff Brown5912f952013-07-01 19:10:31 -07001464void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001465 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001466 PointerProperties pointerProperties[pointerCount];
1467 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001468 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001469 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1470 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001471 }
1472
chaviw9eaa22c2020-07-01 16:21:27 -07001473 ui::Transform transform;
1474 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1475 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001476 ui::Transform displayTransform;
1477 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1478 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1479 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001480 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1481 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1482 msg->body.motion.actionButton, msg->body.motion.flags,
1483 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001484 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1485 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1486 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001487 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1488 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001489}
1490
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001491void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1492 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1493}
1494
Jeff Brown5912f952013-07-01 19:10:31 -07001495void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001496 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001497 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001498 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001499 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001500 }
1501
1502 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1503 event->addSample(msg->body.motion.eventTime, pointerCoords);
1504}
1505
1506bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001507 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001508 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001509 if (head.body.motion.pointerCount != pointerCount
1510 || head.body.motion.action != msg->body.motion.action) {
1511 return false;
1512 }
1513 for (size_t i = 0; i < pointerCount; i++) {
1514 if (head.body.motion.pointers[i].properties
1515 != msg->body.motion.pointers[i].properties) {
1516 return false;
1517 }
1518 }
1519 return true;
1520}
1521
1522ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1523 size_t numSamples = batch.samples.size();
1524 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001525 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001526 index += 1;
1527 }
1528 return ssize_t(index) - 1;
1529}
1530
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001531std::string InputConsumer::dump() const {
1532 std::string out;
1533 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1534 out = out + "mChannel = " + mChannel->getName() + "\n";
1535 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1536 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001537 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001538 }
1539 out += "Batches:\n";
1540 for (const Batch& batch : mBatches) {
1541 out += " Batch:\n";
1542 for (const InputMessage& msg : batch.samples) {
1543 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001544 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001545 switch (msg.header.type) {
1546 case InputMessage::Type::KEY: {
1547 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1548 KeyEvent::actionToString(
1549 msg.body.key.action),
1550 msg.body.key.keyCode);
1551 break;
1552 }
1553 case InputMessage::Type::MOTION: {
1554 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1555 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1556 const float x = msg.body.motion.pointers[i].coords.getX();
1557 const float y = msg.body.motion.pointers[i].coords.getY();
1558 out += android::base::StringPrintf("\n Pointer %" PRIu32
1559 " : x=%.1f y=%.1f",
1560 i, x, y);
1561 }
1562 break;
1563 }
1564 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001565 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1566 toString(msg.body.finished.handled),
1567 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001568 break;
1569 }
1570 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001571 out += android::base::StringPrintf("hasFocus=%s",
1572 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001573 break;
1574 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001575 case InputMessage::Type::CAPTURE: {
1576 out += android::base::StringPrintf("hasCapture=%s",
1577 toString(msg.body.capture
1578 .pointerCaptureEnabled));
1579 break;
1580 }
arthurhung7632c332020-12-30 16:58:01 +08001581 case InputMessage::Type::DRAG: {
1582 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1583 msg.body.drag.x, msg.body.drag.y,
1584 toString(msg.body.drag.isExiting));
1585 break;
1586 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001587 case InputMessage::Type::TIMELINE: {
1588 const nsecs_t gpuCompletedTime =
1589 msg.body.timeline
1590 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1591 const nsecs_t presentTime =
1592 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1593 out += android::base::StringPrintf("inputEventId=%" PRId32
1594 ", gpuCompletedTime=%" PRId64
1595 ", presentTime=%" PRId64,
1596 msg.body.timeline.eventId, gpuCompletedTime,
1597 presentTime);
1598 break;
1599 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001600 case InputMessage::Type::TOUCH_MODE: {
1601 out += android::base::StringPrintf("isInTouchMode=%s",
1602 toString(msg.body.touchMode.isInTouchMode));
1603 break;
1604 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001605 }
1606 out += "\n";
1607 }
1608 }
1609 if (mBatches.empty()) {
1610 out += " <empty>\n";
1611 }
1612 out += "mSeqChains:\n";
1613 for (const SeqChain& chain : mSeqChains) {
1614 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1615 chain.chain);
1616 }
1617 if (mSeqChains.empty()) {
1618 out += " <empty>\n";
1619 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001620 out += "mConsumeTimes:\n";
1621 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1622 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1623 consumeTime);
1624 }
1625 if (mConsumeTimes.empty()) {
1626 out += " <empty>\n";
1627 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001628 return out;
1629}
1630
Jeff Brown5912f952013-07-01 19:10:31 -07001631} // namespace android