blob: 4d3d8bc31c82a0fea56ac107b43320c43719ad15 [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.
78 * Enable this via "adb shell setprop log.tag.InputTransportResampling DEBUG" (requires restart)
79 */
80const bool DEBUG_RESAMPLING =
81 __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "Resampling", ANDROID_LOG_INFO);
82
83} // namespace
84
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -070085using android::base::Result;
Michael Wright3dd60e22019-03-27 22:06:44 +000086using android::base::StringPrintf;
87
Jeff Brown5912f952013-07-01 19:10:31 -070088namespace android {
89
90// Socket buffer size. The default is typically about 128KB, which is much larger than
91// we really need. So we make it smaller. It just needs to be big enough to hold
92// a few dozen large multi-finger motion events in the case where an application gets
93// behind processing touches.
94static const size_t SOCKET_BUFFER_SIZE = 32 * 1024;
95
96// Nanoseconds per milliseconds.
97static const nsecs_t NANOS_PER_MS = 1000000;
98
99// Latency added during resampling. A few milliseconds doesn't hurt much but
100// reduces the impact of mispredicted touch positions.
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800101const std::chrono::duration RESAMPLE_LATENCY = 5ms;
Jeff Brown5912f952013-07-01 19:10:31 -0700102
103// Minimum time difference between consecutive samples before attempting to resample.
104static const nsecs_t RESAMPLE_MIN_DELTA = 2 * NANOS_PER_MS;
105
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -0700106// Maximum time difference between consecutive samples before attempting to resample
107// by extrapolation.
108static const nsecs_t RESAMPLE_MAX_DELTA = 20 * NANOS_PER_MS;
109
Jeff Brown5912f952013-07-01 19:10:31 -0700110// Maximum time to predict forward from the last known state, to avoid predicting too
111// far into the future. This time is further bounded by 50% of the last time delta.
112static const nsecs_t RESAMPLE_MAX_PREDICTION = 8 * NANOS_PER_MS;
113
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600114/**
115 * System property for enabling / disabling touch resampling.
116 * Resampling extrapolates / interpolates the reported touch event coordinates to better
117 * align them to the VSYNC signal, thus resulting in smoother scrolling performance.
118 * Resampling is not needed (and should be disabled) on hardware that already
119 * has touch events triggered by VSYNC.
120 * Set to "1" to enable resampling (default).
121 * Set to "0" to disable resampling.
122 * Resampling is enabled by default.
123 */
124static const char* PROPERTY_RESAMPLING_ENABLED = "ro.input.resampling";
125
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800126/**
127 * Crash if the events that are getting sent to the InputPublisher are inconsistent.
128 * Enable this via "adb shell setprop log.tag.InputTransportVerifyEvents DEBUG"
129 */
130static bool verifyEvents() {
131 return __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG "VerifyEvents", ANDROID_LOG_INFO);
132}
133
Jeff Brown5912f952013-07-01 19:10:31 -0700134template<typename T>
135inline static T min(const T& a, const T& b) {
136 return a < b ? a : b;
137}
138
139inline static float lerp(float a, float b, float alpha) {
140 return a + alpha * (b - a);
141}
142
Siarhei Vishniakou128eab12019-05-23 10:25:59 +0800143inline static bool isPointerEvent(int32_t source) {
144 return (source & AINPUT_SOURCE_CLASS_POINTER) == AINPUT_SOURCE_CLASS_POINTER;
145}
146
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800147inline static const char* toString(bool value) {
148 return value ? "true" : "false";
149}
150
Siarhei Vishniakou6d73f832022-07-21 17:27:03 -0700151static bool shouldResampleTool(ToolType toolType) {
152 return toolType == ToolType::FINGER || toolType == ToolType::UNKNOWN;
153}
154
Jeff Brown5912f952013-07-01 19:10:31 -0700155// --- InputMessage ---
156
157bool InputMessage::isValid(size_t actualSize) const {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000158 if (size() != actualSize) {
159 ALOGE("Received message of incorrect size %zu (expected %zu)", actualSize, size());
160 return false;
161 }
162
163 switch (header.type) {
164 case Type::KEY:
165 return true;
166 case Type::MOTION: {
167 const bool valid =
168 body.motion.pointerCount > 0 && body.motion.pointerCount <= MAX_POINTERS;
169 if (!valid) {
170 ALOGE("Received invalid MOTION: pointerCount = %" PRIu32, body.motion.pointerCount);
171 }
172 return valid;
173 }
174 case Type::FINISHED:
175 case Type::FOCUS:
176 case Type::CAPTURE:
177 case Type::DRAG:
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700178 case Type::TOUCH_MODE:
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000179 return true;
180 case Type::TIMELINE: {
181 const nsecs_t gpuCompletedTime =
182 body.timeline.graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
183 const nsecs_t presentTime =
184 body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
185 const bool valid = presentTime > gpuCompletedTime;
186 if (!valid) {
187 ALOGE("Received invalid TIMELINE: gpuCompletedTime = %" PRId64
188 " presentTime = %" PRId64,
189 gpuCompletedTime, presentTime);
190 }
191 return valid;
Jeff Brown5912f952013-07-01 19:10:31 -0700192 }
193 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000194 ALOGE("Invalid message type: %s", ftl::enum_string(header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700195 return false;
196}
197
198size_t InputMessage::size() const {
199 switch (header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700200 case Type::KEY:
201 return sizeof(Header) + body.key.size();
202 case Type::MOTION:
203 return sizeof(Header) + body.motion.size();
204 case Type::FINISHED:
205 return sizeof(Header) + body.finished.size();
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800206 case Type::FOCUS:
207 return sizeof(Header) + body.focus.size();
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800208 case Type::CAPTURE:
209 return sizeof(Header) + body.capture.size();
arthurhung7632c332020-12-30 16:58:01 +0800210 case Type::DRAG:
211 return sizeof(Header) + body.drag.size();
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000212 case Type::TIMELINE:
213 return sizeof(Header) + body.timeline.size();
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700214 case Type::TOUCH_MODE:
215 return sizeof(Header) + body.touchMode.size();
Jeff Brown5912f952013-07-01 19:10:31 -0700216 }
217 return sizeof(Header);
218}
219
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800220/**
221 * There could be non-zero bytes in-between InputMessage fields. Force-initialize the entire
222 * memory to zero, then only copy the valid bytes on a per-field basis.
223 */
224void InputMessage::getSanitizedCopy(InputMessage* msg) const {
225 memset(msg, 0, sizeof(*msg));
226
227 // Write the header
228 msg->header.type = header.type;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500229 msg->header.seq = header.seq;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800230
231 // Write the body
232 switch(header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700233 case InputMessage::Type::KEY: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800234 // int32_t eventId
235 msg->body.key.eventId = body.key.eventId;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800236 // nsecs_t eventTime
237 msg->body.key.eventTime = body.key.eventTime;
238 // int32_t deviceId
239 msg->body.key.deviceId = body.key.deviceId;
240 // int32_t source
241 msg->body.key.source = body.key.source;
242 // int32_t displayId
243 msg->body.key.displayId = body.key.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600244 // std::array<uint8_t, 32> hmac
245 msg->body.key.hmac = body.key.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800246 // int32_t action
247 msg->body.key.action = body.key.action;
248 // int32_t flags
249 msg->body.key.flags = body.key.flags;
250 // int32_t keyCode
251 msg->body.key.keyCode = body.key.keyCode;
252 // int32_t scanCode
253 msg->body.key.scanCode = body.key.scanCode;
254 // int32_t metaState
255 msg->body.key.metaState = body.key.metaState;
256 // int32_t repeatCount
257 msg->body.key.repeatCount = body.key.repeatCount;
258 // nsecs_t downTime
259 msg->body.key.downTime = body.key.downTime;
260 break;
261 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700262 case InputMessage::Type::MOTION: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800263 // int32_t eventId
264 msg->body.motion.eventId = body.motion.eventId;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700265 // uint32_t pointerCount
266 msg->body.motion.pointerCount = body.motion.pointerCount;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800267 // nsecs_t eventTime
268 msg->body.motion.eventTime = body.motion.eventTime;
269 // int32_t deviceId
270 msg->body.motion.deviceId = body.motion.deviceId;
271 // int32_t source
272 msg->body.motion.source = body.motion.source;
273 // int32_t displayId
274 msg->body.motion.displayId = body.motion.displayId;
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600275 // std::array<uint8_t, 32> hmac
276 msg->body.motion.hmac = body.motion.hmac;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800277 // int32_t action
278 msg->body.motion.action = body.motion.action;
279 // int32_t actionButton
280 msg->body.motion.actionButton = body.motion.actionButton;
281 // int32_t flags
282 msg->body.motion.flags = body.motion.flags;
283 // int32_t metaState
284 msg->body.motion.metaState = body.motion.metaState;
285 // int32_t buttonState
286 msg->body.motion.buttonState = body.motion.buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800287 // MotionClassification classification
288 msg->body.motion.classification = body.motion.classification;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800289 // int32_t edgeFlags
290 msg->body.motion.edgeFlags = body.motion.edgeFlags;
291 // nsecs_t downTime
292 msg->body.motion.downTime = body.motion.downTime;
chaviw9eaa22c2020-07-01 16:21:27 -0700293
294 msg->body.motion.dsdx = body.motion.dsdx;
295 msg->body.motion.dtdx = body.motion.dtdx;
296 msg->body.motion.dtdy = body.motion.dtdy;
297 msg->body.motion.dsdy = body.motion.dsdy;
298 msg->body.motion.tx = body.motion.tx;
299 msg->body.motion.ty = body.motion.ty;
300
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800301 // float xPrecision
302 msg->body.motion.xPrecision = body.motion.xPrecision;
303 // float yPrecision
304 msg->body.motion.yPrecision = body.motion.yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700305 // float xCursorPosition
306 msg->body.motion.xCursorPosition = body.motion.xCursorPosition;
307 // float yCursorPosition
308 msg->body.motion.yCursorPosition = body.motion.yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700309
310 msg->body.motion.dsdxRaw = body.motion.dsdxRaw;
311 msg->body.motion.dtdxRaw = body.motion.dtdxRaw;
312 msg->body.motion.dtdyRaw = body.motion.dtdyRaw;
313 msg->body.motion.dsdyRaw = body.motion.dsdyRaw;
314 msg->body.motion.txRaw = body.motion.txRaw;
315 msg->body.motion.tyRaw = body.motion.tyRaw;
316
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800317 //struct Pointer pointers[MAX_POINTERS]
318 for (size_t i = 0; i < body.motion.pointerCount; i++) {
319 // PointerProperties properties
320 msg->body.motion.pointers[i].properties.id = body.motion.pointers[i].properties.id;
321 msg->body.motion.pointers[i].properties.toolType =
322 body.motion.pointers[i].properties.toolType,
323 // PointerCoords coords
324 msg->body.motion.pointers[i].coords.bits = body.motion.pointers[i].coords.bits;
325 const uint32_t count = BitSet64::count(body.motion.pointers[i].coords.bits);
326 memcpy(&msg->body.motion.pointers[i].coords.values[0],
327 &body.motion.pointers[i].coords.values[0],
328 count * (sizeof(body.motion.pointers[i].coords.values[0])));
Philip Quinnafb31282022-12-20 18:17:55 -0800329 msg->body.motion.pointers[i].coords.isResampled =
330 body.motion.pointers[i].coords.isResampled;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800331 }
332 break;
333 }
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700334 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800335 msg->body.finished.handled = body.finished.handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000336 msg->body.finished.consumeTime = body.finished.consumeTime;
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800337 break;
338 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800339 case InputMessage::Type::FOCUS: {
Garfield Tan1c7bc862020-01-28 13:24:04 -0800340 msg->body.focus.eventId = body.focus.eventId;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800341 msg->body.focus.hasFocus = body.focus.hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800342 break;
343 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800344 case InputMessage::Type::CAPTURE: {
345 msg->body.capture.eventId = body.capture.eventId;
346 msg->body.capture.pointerCaptureEnabled = body.capture.pointerCaptureEnabled;
347 break;
348 }
arthurhung7632c332020-12-30 16:58:01 +0800349 case InputMessage::Type::DRAG: {
350 msg->body.drag.eventId = body.drag.eventId;
351 msg->body.drag.x = body.drag.x;
352 msg->body.drag.y = body.drag.y;
353 msg->body.drag.isExiting = body.drag.isExiting;
354 break;
355 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000356 case InputMessage::Type::TIMELINE: {
357 msg->body.timeline.eventId = body.timeline.eventId;
358 msg->body.timeline.graphicsTimeline = body.timeline.graphicsTimeline;
359 break;
360 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700361 case InputMessage::Type::TOUCH_MODE: {
362 msg->body.touchMode.eventId = body.touchMode.eventId;
363 msg->body.touchMode.isInTouchMode = body.touchMode.isInTouchMode;
364 }
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800365 }
366}
Jeff Brown5912f952013-07-01 19:10:31 -0700367
368// --- InputChannel ---
369
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500370std::unique_ptr<InputChannel> InputChannel::create(const std::string& name,
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500371 android::base::unique_fd fd, sp<IBinder> token) {
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700372 const int result = fcntl(fd, F_SETFL, O_NONBLOCK);
373 if (result != 0) {
374 LOG_ALWAYS_FATAL("channel '%s' ~ Could not make socket non-blocking: %s", name.c_str(),
375 strerror(errno));
376 return nullptr;
377 }
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500378 // using 'new' to access a non-public constructor
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500379 return std::unique_ptr<InputChannel>(new InputChannel(name, std::move(fd), token));
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700380}
381
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500382InputChannel::InputChannel(const std::string name, android::base::unique_fd fd, sp<IBinder> token)
383 : mName(std::move(name)), mFd(std::move(fd)), mToken(std::move(token)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000384 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel constructed: name='%s', fd=%d",
385 getName().c_str(), getFd().get());
Jeff Brown5912f952013-07-01 19:10:31 -0700386}
387
388InputChannel::~InputChannel() {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000389 ALOGD_IF(DEBUG_CHANNEL_LIFECYCLE, "Input channel destroyed: name='%s', fd=%d",
390 getName().c_str(), getFd().get());
Robert Carr3720ed02018-08-08 16:08:27 -0700391}
392
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800393status_t InputChannel::openInputChannelPair(const std::string& name,
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500394 std::unique_ptr<InputChannel>& outServerChannel,
395 std::unique_ptr<InputChannel>& outClientChannel) {
Jeff Brown5912f952013-07-01 19:10:31 -0700396 int sockets[2];
397 if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {
398 status_t result = -errno;
Siarhei Vishniakou09b02ac2021-04-14 22:24:04 +0000399 ALOGE("channel '%s' ~ Could not create socket pair. errno=%s(%d)", name.c_str(),
400 strerror(errno), errno);
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500401 outServerChannel.reset();
402 outClientChannel.reset();
Jeff Brown5912f952013-07-01 19:10:31 -0700403 return result;
404 }
405
406 int bufferSize = SOCKET_BUFFER_SIZE;
407 setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
408 setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
409 setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));
410 setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));
411
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700412 sp<IBinder> token = new BBinder();
413
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700414 std::string serverChannelName = name + " (server)";
415 android::base::unique_fd serverFd(sockets[0]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700416 outServerChannel = InputChannel::create(serverChannelName, std::move(serverFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700417
Josh Gao2ccbe3a2019-08-09 14:35:36 -0700418 std::string clientChannelName = name + " (client)";
419 android::base::unique_fd clientFd(sockets[1]);
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700420 outClientChannel = InputChannel::create(clientChannelName, std::move(clientFd), token);
Jeff Brown5912f952013-07-01 19:10:31 -0700421 return OK;
422}
423
424status_t InputChannel::sendMessage(const InputMessage* msg) {
Siarhei Vishniakou1f7c0e42018-11-16 22:18:53 -0800425 const size_t msgLength = msg->size();
426 InputMessage cleanMsg;
427 msg->getSanitizedCopy(&cleanMsg);
Jeff Brown5912f952013-07-01 19:10:31 -0700428 ssize_t nWrite;
429 do {
Chris Ye0783e992020-06-02 21:34:49 -0700430 nWrite = ::send(getFd(), &cleanMsg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);
Jeff Brown5912f952013-07-01 19:10:31 -0700431 } while (nWrite == -1 && errno == EINTR);
432
433 if (nWrite < 0) {
434 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000435 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ error sending message of type %s, %s",
436 mName.c_str(), ftl::enum_string(msg->header.type).c_str(), strerror(error));
Jeff Brown5912f952013-07-01 19:10:31 -0700437 if (error == EAGAIN || error == EWOULDBLOCK) {
438 return WOULD_BLOCK;
439 }
440 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {
441 return DEAD_OBJECT;
442 }
443 return -error;
444 }
445
446 if (size_t(nWrite) != msgLength) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000447 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
448 "channel '%s' ~ error sending message type %s, send was incomplete", mName.c_str(),
449 ftl::enum_string(msg->header.type).c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700450 return DEAD_OBJECT;
451 }
452
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000453 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ sent message of type %s", mName.c_str(),
454 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100455
456 if (ATRACE_ENABLED()) {
457 std::string message =
458 StringPrintf("sendMessage(inputChannel=%s, seq=0x%" PRIx32 ", type=0x%" PRIx32 ")",
459 mName.c_str(), msg->header.seq, msg->header.type);
460 ATRACE_NAME(message.c_str());
461 }
Jeff Brown5912f952013-07-01 19:10:31 -0700462 return OK;
463}
464
465status_t InputChannel::receiveMessage(InputMessage* msg) {
466 ssize_t nRead;
467 do {
Chris Ye0783e992020-06-02 21:34:49 -0700468 nRead = ::recv(getFd(), msg, sizeof(InputMessage), MSG_DONTWAIT);
Jeff Brown5912f952013-07-01 19:10:31 -0700469 } while (nRead == -1 && errno == EINTR);
470
471 if (nRead < 0) {
472 int error = errno;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000473 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ receive message failed, errno=%d",
474 mName.c_str(), errno);
Jeff Brown5912f952013-07-01 19:10:31 -0700475 if (error == EAGAIN || error == EWOULDBLOCK) {
476 return WOULD_BLOCK;
477 }
478 if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED) {
479 return DEAD_OBJECT;
480 }
481 return -error;
482 }
483
484 if (nRead == 0) { // check for EOF
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000485 ALOGD_IF(DEBUG_CHANNEL_MESSAGES,
486 "channel '%s' ~ receive message failed because peer was closed", mName.c_str());
Jeff Brown5912f952013-07-01 19:10:31 -0700487 return DEAD_OBJECT;
488 }
489
490 if (!msg->isValid(nRead)) {
Siarhei Vishniakoudbdb6732021-04-26 19:40:26 +0000491 ALOGE("channel '%s' ~ received invalid message of size %zd", mName.c_str(), nRead);
Jeff Brown5912f952013-07-01 19:10:31 -0700492 return BAD_VALUE;
493 }
494
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000495 ALOGD_IF(DEBUG_CHANNEL_MESSAGES, "channel '%s' ~ received message of type %s", mName.c_str(),
496 ftl::enum_string(msg->header.type).c_str());
Zimd8402b62023-06-02 11:56:26 +0100497
498 if (ATRACE_ENABLED()) {
499 std::string message = StringPrintf("receiveMessage(inputChannel=%s, seq=0x%" PRIx32
500 ", type=0x%" PRIx32 ")",
501 mName.c_str(), msg->header.seq, msg->header.type);
502 ATRACE_NAME(message.c_str());
503 }
Jeff Brown5912f952013-07-01 19:10:31 -0700504 return OK;
505}
506
Siarhei Vishniakoud2588272020-07-10 11:15:40 -0500507std::unique_ptr<InputChannel> InputChannel::dup() const {
Garfield Tan15601662020-09-22 15:32:38 -0700508 base::unique_fd newFd(dupFd());
Chris Ye0783e992020-06-02 21:34:49 -0700509 return InputChannel::create(getName(), std::move(newFd), getConnectionToken());
Jeff Brown5912f952013-07-01 19:10:31 -0700510}
511
Garfield Tan15601662020-09-22 15:32:38 -0700512void InputChannel::copyTo(InputChannel& outChannel) const {
513 outChannel.mName = getName();
514 outChannel.mFd = dupFd();
515 outChannel.mToken = getConnectionToken();
516}
517
Chris Ye0783e992020-06-02 21:34:49 -0700518status_t InputChannel::writeToParcel(android::Parcel* parcel) const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500519 if (parcel == nullptr) {
520 ALOGE("%s: Null parcel", __func__);
521 return BAD_VALUE;
522 }
523 return parcel->writeStrongBinder(mToken)
524 ?: parcel->writeUtf8AsUtf16(mName) ?: parcel->writeUniqueFileDescriptor(mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700525}
526
Chris Ye0783e992020-06-02 21:34:49 -0700527status_t InputChannel::readFromParcel(const android::Parcel* parcel) {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500528 if (parcel == nullptr) {
529 ALOGE("%s: Null parcel", __func__);
530 return BAD_VALUE;
531 }
532 mToken = parcel->readStrongBinder();
533 return parcel->readUtf8FromUtf16(&mName) ?: parcel->readUniqueFileDescriptor(&mFd);
Robert Carr3720ed02018-08-08 16:08:27 -0700534}
535
Siarhei Vishniakou26d3cfb2019-10-15 17:02:32 -0700536sp<IBinder> InputChannel::getConnectionToken() const {
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500537 return mToken;
Robert Carr803535b2018-08-02 16:38:15 -0700538}
539
Garfield Tan15601662020-09-22 15:32:38 -0700540base::unique_fd InputChannel::dupFd() const {
541 android::base::unique_fd newFd(::dup(getFd()));
542 if (!newFd.ok()) {
543 ALOGE("Could not duplicate fd %i for channel %s: %s", getFd().get(), getName().c_str(),
544 strerror(errno));
545 const bool hitFdLimit = errno == EMFILE || errno == ENFILE;
546 // If this process is out of file descriptors, then throwing that might end up exploding
547 // on the other side of a binder call, which isn't really helpful.
548 // Better to just crash here and hope that the FD leak is slow.
549 // Other failures could be client errors, so we still propagate those back to the caller.
550 LOG_ALWAYS_FATAL_IF(hitFdLimit, "Too many open files, could not duplicate input channel %s",
551 getName().c_str());
552 return {};
553 }
554 return newFd;
555}
556
Jeff Brown5912f952013-07-01 19:10:31 -0700557// --- InputPublisher ---
558
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800559InputPublisher::InputPublisher(const std::shared_ptr<InputChannel>& channel)
560 : mChannel(channel), mInputVerifier(channel->getName()) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700561
562InputPublisher::~InputPublisher() {
563}
564
Garfield Tan1c7bc862020-01-28 13:24:04 -0800565status_t InputPublisher::publishKeyEvent(uint32_t seq, int32_t eventId, int32_t deviceId,
566 int32_t source, int32_t displayId,
567 std::array<uint8_t, 32> hmac, int32_t action,
568 int32_t flags, int32_t keyCode, int32_t scanCode,
569 int32_t metaState, int32_t repeatCount, nsecs_t downTime,
570 nsecs_t eventTime) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000571 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000572 std::string message =
573 StringPrintf("publishKeyEvent(inputChannel=%s, action=%s, keyCode=%s)",
574 mChannel->getName().c_str(), KeyEvent::actionToString(action),
575 KeyEvent::getLabel(keyCode));
Michael Wright3dd60e22019-03-27 22:06:44 +0000576 ATRACE_NAME(message.c_str());
577 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000578 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000579 "channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000580 "action=%s, flags=0x%x, keyCode=%s, scanCode=%d, metaState=0x%x, repeatCount=%d,"
581 "downTime=%" PRId64 ", eventTime=%" PRId64,
Prabir Pradhan96282b02023-02-24 22:36:17 +0000582 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000583 inputEventSourceToString(source).c_str(), KeyEvent::actionToString(action), flags,
584 KeyEvent::getLabel(keyCode), scanCode, metaState, repeatCount, downTime, eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700585
586 if (!seq) {
587 ALOGE("Attempted to publish a key event with sequence number 0.");
588 return BAD_VALUE;
589 }
590
591 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700592 msg.header.type = InputMessage::Type::KEY;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500593 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800594 msg.body.key.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700595 msg.body.key.deviceId = deviceId;
596 msg.body.key.source = source;
Siarhei Vishniakoua62a8dd2018-06-08 21:17:33 +0100597 msg.body.key.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700598 msg.body.key.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700599 msg.body.key.action = action;
600 msg.body.key.flags = flags;
601 msg.body.key.keyCode = keyCode;
602 msg.body.key.scanCode = scanCode;
603 msg.body.key.metaState = metaState;
604 msg.body.key.repeatCount = repeatCount;
605 msg.body.key.downTime = downTime;
606 msg.body.key.eventTime = eventTime;
607 return mChannel->sendMessage(&msg);
608}
609
610status_t InputPublisher::publishMotionEvent(
Garfield Tan1c7bc862020-01-28 13:24:04 -0800611 uint32_t seq, int32_t eventId, int32_t deviceId, int32_t source, int32_t displayId,
Siarhei Vishniakou9c858ac2020-01-23 14:20:11 -0600612 std::array<uint8_t, 32> hmac, int32_t action, int32_t actionButton, int32_t flags,
613 int32_t edgeFlags, int32_t metaState, int32_t buttonState,
chaviw9eaa22c2020-07-01 16:21:27 -0700614 MotionClassification classification, const ui::Transform& transform, float xPrecision,
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700615 float yPrecision, float xCursorPosition, float yCursorPosition,
616 const ui::Transform& rawTransform, nsecs_t downTime, nsecs_t eventTime,
Evan Rosky09576692021-07-01 12:22:09 -0700617 uint32_t pointerCount, const PointerProperties* pointerProperties,
618 const PointerCoords* pointerCoords) {
Michael Wright3dd60e22019-03-27 22:06:44 +0000619 if (ATRACE_ENABLED()) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000620 std::string message = StringPrintf("publishMotionEvent(inputChannel=%s, action=%s)",
621 mChannel->getName().c_str(),
622 MotionEvent::actionToString(action).c_str());
Michael Wright3dd60e22019-03-27 22:06:44 +0000623 ATRACE_NAME(message.c_str());
624 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800625 if (verifyEvents()) {
Siarhei Vishniakou5c02a712023-05-15 15:45:02 -0700626 Result<void> result =
627 mInputVerifier.processMovement(deviceId, action, pointerCount, pointerProperties,
628 pointerCoords, flags);
629 if (!result.ok()) {
630 LOG(FATAL) << "Bad stream: " << result.error();
631 }
Siarhei Vishniakou92c8fd52023-01-29 14:57:43 -0800632 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000633 if (debugTransportPublisher()) {
chaviw9eaa22c2020-07-01 16:21:27 -0700634 std::string transformString;
chaviw85b44202020-07-24 11:46:21 -0700635 transform.dump(transformString, "transform", " ");
Prabir Pradhan96282b02023-02-24 22:36:17 +0000636 ALOGD("channel '%s' publisher ~ %s: seq=%u, id=%d, deviceId=%d, source=%s, "
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800637 "displayId=%" PRId32 ", "
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000638 "action=%s, actionButton=0x%08x, flags=0x%x, edgeFlags=0x%x, "
chaviw9eaa22c2020-07-01 16:21:27 -0700639 "metaState=0x%x, buttonState=0x%x, classification=%s,"
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800640 "xPrecision=%f, yPrecision=%f, downTime=%" PRId64 ", eventTime=%" PRId64 ", "
chaviw85b44202020-07-24 11:46:21 -0700641 "pointerCount=%" PRIu32 " \n%s",
Prabir Pradhan96282b02023-02-24 22:36:17 +0000642 mChannel->getName().c_str(), __func__, seq, eventId, deviceId,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000643 inputEventSourceToString(source).c_str(), displayId,
644 MotionEvent::actionToString(action).c_str(), actionButton, flags, edgeFlags,
645 metaState, buttonState, motionClassificationToString(classification), xPrecision,
646 yPrecision, downTime, eventTime, pointerCount, transformString.c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800647 }
Jeff Brown5912f952013-07-01 19:10:31 -0700648
649 if (!seq) {
650 ALOGE("Attempted to publish a motion event with sequence number 0.");
651 return BAD_VALUE;
652 }
653
654 if (pointerCount > MAX_POINTERS || pointerCount < 1) {
Michael Wright63ff3a82014-06-10 13:03:17 -0700655 ALOGE("channel '%s' publisher ~ Invalid number of pointers provided: %" PRIu32 ".",
Siarhei Vishniakouf93fcf42017-11-22 16:00:14 -0800656 mChannel->getName().c_str(), pointerCount);
Jeff Brown5912f952013-07-01 19:10:31 -0700657 return BAD_VALUE;
658 }
659
660 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700661 msg.header.type = InputMessage::Type::MOTION;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500662 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800663 msg.body.motion.eventId = eventId;
Jeff Brown5912f952013-07-01 19:10:31 -0700664 msg.body.motion.deviceId = deviceId;
665 msg.body.motion.source = source;
Tarandeep Singh58641502017-07-31 10:51:54 -0700666 msg.body.motion.displayId = displayId;
Edgar Arriagac6ae4bb2020-04-16 18:46:48 -0700667 msg.body.motion.hmac = std::move(hmac);
Jeff Brown5912f952013-07-01 19:10:31 -0700668 msg.body.motion.action = action;
Michael Wright7b159c92015-05-14 14:48:03 +0100669 msg.body.motion.actionButton = actionButton;
Jeff Brown5912f952013-07-01 19:10:31 -0700670 msg.body.motion.flags = flags;
671 msg.body.motion.edgeFlags = edgeFlags;
672 msg.body.motion.metaState = metaState;
673 msg.body.motion.buttonState = buttonState;
Siarhei Vishniakou16a2e302019-01-14 19:21:45 -0800674 msg.body.motion.classification = classification;
chaviw9eaa22c2020-07-01 16:21:27 -0700675 msg.body.motion.dsdx = transform.dsdx();
676 msg.body.motion.dtdx = transform.dtdx();
677 msg.body.motion.dtdy = transform.dtdy();
678 msg.body.motion.dsdy = transform.dsdy();
679 msg.body.motion.tx = transform.tx();
680 msg.body.motion.ty = transform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700681 msg.body.motion.xPrecision = xPrecision;
682 msg.body.motion.yPrecision = yPrecision;
Garfield Tan00f511d2019-06-12 16:55:40 -0700683 msg.body.motion.xCursorPosition = xCursorPosition;
684 msg.body.motion.yCursorPosition = yCursorPosition;
Prabir Pradhanb9b18502021-08-26 12:30:32 -0700685 msg.body.motion.dsdxRaw = rawTransform.dsdx();
686 msg.body.motion.dtdxRaw = rawTransform.dtdx();
687 msg.body.motion.dtdyRaw = rawTransform.dtdy();
688 msg.body.motion.dsdyRaw = rawTransform.dsdy();
689 msg.body.motion.txRaw = rawTransform.tx();
690 msg.body.motion.tyRaw = rawTransform.ty();
Jeff Brown5912f952013-07-01 19:10:31 -0700691 msg.body.motion.downTime = downTime;
692 msg.body.motion.eventTime = eventTime;
693 msg.body.motion.pointerCount = pointerCount;
Narayan Kamathbc6001b2014-05-02 17:53:33 +0100694 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -0700695 msg.body.motion.pointers[i].properties.copyFrom(pointerProperties[i]);
696 msg.body.motion.pointers[i].coords.copyFrom(pointerCoords[i]);
697 }
Atif Niyaz3d3fa522019-07-25 11:12:39 -0700698
Jeff Brown5912f952013-07-01 19:10:31 -0700699 return mChannel->sendMessage(&msg);
700}
701
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700702status_t InputPublisher::publishFocusEvent(uint32_t seq, int32_t eventId, bool hasFocus) {
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800703 if (ATRACE_ENABLED()) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -0700704 std::string message = StringPrintf("publishFocusEvent(inputChannel=%s, hasFocus=%s)",
705 mChannel->getName().c_str(), toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800706 ATRACE_NAME(message.c_str());
707 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000708 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: seq=%u, id=%d, hasFocus=%s",
709 mChannel->getName().c_str(), __func__, seq, eventId, toString(hasFocus));
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800710
711 InputMessage msg;
712 msg.header.type = InputMessage::Type::FOCUS;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500713 msg.header.seq = seq;
Garfield Tan1c7bc862020-01-28 13:24:04 -0800714 msg.body.focus.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000715 msg.body.focus.hasFocus = hasFocus;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800716 return mChannel->sendMessage(&msg);
717}
718
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800719status_t InputPublisher::publishCaptureEvent(uint32_t seq, int32_t eventId,
720 bool pointerCaptureEnabled) {
721 if (ATRACE_ENABLED()) {
722 std::string message =
723 StringPrintf("publishCaptureEvent(inputChannel=%s, pointerCaptureEnabled=%s)",
724 mChannel->getName().c_str(), toString(pointerCaptureEnabled));
725 ATRACE_NAME(message.c_str());
726 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000727 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000728 "channel '%s' publisher ~ %s: seq=%u, id=%d, pointerCaptureEnabled=%s",
729 mChannel->getName().c_str(), __func__, seq, eventId, toString(pointerCaptureEnabled));
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800730
731 InputMessage msg;
732 msg.header.type = InputMessage::Type::CAPTURE;
733 msg.header.seq = seq;
734 msg.body.capture.eventId = eventId;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +0000735 msg.body.capture.pointerCaptureEnabled = pointerCaptureEnabled;
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800736 return mChannel->sendMessage(&msg);
737}
738
arthurhung7632c332020-12-30 16:58:01 +0800739status_t InputPublisher::publishDragEvent(uint32_t seq, int32_t eventId, float x, float y,
740 bool isExiting) {
741 if (ATRACE_ENABLED()) {
742 std::string message =
743 StringPrintf("publishDragEvent(inputChannel=%s, x=%f, y=%f, isExiting=%s)",
744 mChannel->getName().c_str(), x, y, toString(isExiting));
745 ATRACE_NAME(message.c_str());
746 }
Prabir Pradhanb2bd83c2023-02-23 02:34:40 +0000747 ALOGD_IF(debugTransportPublisher(),
Prabir Pradhan96282b02023-02-24 22:36:17 +0000748 "channel '%s' publisher ~ %s: seq=%u, id=%d, x=%f, y=%f, isExiting=%s",
749 mChannel->getName().c_str(), __func__, seq, eventId, x, y, toString(isExiting));
arthurhung7632c332020-12-30 16:58:01 +0800750
751 InputMessage msg;
752 msg.header.type = InputMessage::Type::DRAG;
753 msg.header.seq = seq;
754 msg.body.drag.eventId = eventId;
755 msg.body.drag.isExiting = isExiting;
756 msg.body.drag.x = x;
757 msg.body.drag.y = y;
758 return mChannel->sendMessage(&msg);
759}
760
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700761status_t InputPublisher::publishTouchModeEvent(uint32_t seq, int32_t eventId, bool isInTouchMode) {
762 if (ATRACE_ENABLED()) {
763 std::string message =
764 StringPrintf("publishTouchModeEvent(inputChannel=%s, isInTouchMode=%s)",
765 mChannel->getName().c_str(), toString(isInTouchMode));
766 ATRACE_NAME(message.c_str());
767 }
Prabir Pradhan96282b02023-02-24 22:36:17 +0000768 ALOGD_IF(debugTransportPublisher(),
769 "channel '%s' publisher ~ %s: seq=%u, id=%d, isInTouchMode=%s",
770 mChannel->getName().c_str(), __func__, seq, eventId, toString(isInTouchMode));
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700771
772 InputMessage msg;
773 msg.header.type = InputMessage::Type::TOUCH_MODE;
774 msg.header.seq = seq;
775 msg.body.touchMode.eventId = eventId;
776 msg.body.touchMode.isInTouchMode = isInTouchMode;
777 return mChannel->sendMessage(&msg);
778}
779
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000780android::base::Result<InputPublisher::ConsumerResponse> InputPublisher::receiveConsumerResponse() {
Jeff Brown5912f952013-07-01 19:10:31 -0700781 InputMessage msg;
782 status_t result = mChannel->receiveMessage(&msg);
783 if (result) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000784 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
785 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000786 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700787 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000788 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000789 ALOGD_IF(debugTransportPublisher(),
790 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
791 mChannel->getName().c_str(), __func__, msg.header.seq,
792 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000793 return Finished{
794 .seq = msg.header.seq,
795 .handled = msg.body.finished.handled,
796 .consumeTime = msg.body.finished.consumeTime,
797 };
Jeff Brown5912f952013-07-01 19:10:31 -0700798 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000799
800 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000801 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
802 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000803 return Timeline{
804 .inputEventId = msg.body.timeline.eventId,
805 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
806 };
807 }
808
809 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800810 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000811 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700812}
813
814// --- InputConsumer ---
815
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500816InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800817 : InputConsumer(channel, isTouchResamplingEnabled()) {}
818
819InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
820 bool enableTouchResampling)
821 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700822
823InputConsumer::~InputConsumer() {
824}
825
826bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600827 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700828}
829
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800830status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
831 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000832 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
833 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
834 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700835
836 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700837 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700838
839 // Fetch the next input message.
840 // Loop until an event can be returned or no additional events are received.
841 while (!*outEvent) {
842 if (mMsgDeferred) {
843 // mMsg contains a valid input message from the previous call to consume
844 // that has not yet been processed.
845 mMsgDeferred = false;
846 } else {
847 // Receive a fresh message.
848 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000849 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800850 const auto [_, inserted] =
851 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
852 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
853 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000854 }
Jeff Brown5912f952013-07-01 19:10:31 -0700855 if (result) {
856 // Consume the next batched event unless batches are being held for later.
857 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800858 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700859 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000860 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
861 "channel '%s' consumer ~ consumed batch event, seq=%u",
862 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700863 break;
864 }
865 }
866 return result;
867 }
868 }
869
870 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700871 case InputMessage::Type::KEY: {
872 KeyEvent* keyEvent = factory->createKeyEvent();
873 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700874
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700875 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500876 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700877 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000878 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
879 "channel '%s' consumer ~ consumed key event, seq=%u",
880 mChannel->getName().c_str(), *outSeq);
881 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700882 }
Jeff Brown5912f952013-07-01 19:10:31 -0700883
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700884 case InputMessage::Type::MOTION: {
885 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
886 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500887 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700888 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500889 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000890 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
891 "channel '%s' consumer ~ appended to batch event",
892 mChannel->getName().c_str());
893 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700894 } else if (isPointerEvent(mMsg.body.motion.source) &&
895 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
896 // No need to process events that we are going to cancel anyways
897 const size_t count = batch.samples.size();
898 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500899 const InputMessage& msg = batch.samples[i];
900 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700901 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500902 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
903 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700904 } else {
905 // We cannot append to the batch in progress, so we need to consume
906 // the previous batch right now and defer the new message until later.
907 mMsgDeferred = true;
908 status_t result = consumeSamples(factory, batch, batch.samples.size(),
909 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500910 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700911 if (result) {
912 return result;
913 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000914 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
915 "channel '%s' consumer ~ consumed batch event and "
916 "deferred current event, seq=%u",
917 mChannel->getName().c_str(), *outSeq);
918 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700919 }
Jeff Brown5912f952013-07-01 19:10:31 -0700920 }
Jeff Brown5912f952013-07-01 19:10:31 -0700921
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800922 // Start a new batch if needed.
923 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
924 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500925 Batch batch;
926 batch.samples.push_back(mMsg);
927 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000928 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
929 "channel '%s' consumer ~ started batch event",
930 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800931 break;
932 }
Jeff Brown5912f952013-07-01 19:10:31 -0700933
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800934 MotionEvent* motionEvent = factory->createMotionEvent();
935 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700936
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800937 updateTouchState(mMsg);
938 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500939 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800940 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800941
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000942 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
943 "channel '%s' consumer ~ consumed motion event, seq=%u",
944 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800945 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700946 }
Jeff Brown5912f952013-07-01 19:10:31 -0700947
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000948 case InputMessage::Type::FINISHED:
949 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000950 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
951 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800952 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800953 break;
954 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800955
956 case InputMessage::Type::FOCUS: {
957 FocusEvent* focusEvent = factory->createFocusEvent();
958 if (!focusEvent) return NO_MEMORY;
959
960 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500961 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800962 *outEvent = focusEvent;
963 break;
964 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800965
966 case InputMessage::Type::CAPTURE: {
967 CaptureEvent* captureEvent = factory->createCaptureEvent();
968 if (!captureEvent) return NO_MEMORY;
969
970 initializeCaptureEvent(captureEvent, &mMsg);
971 *outSeq = mMsg.header.seq;
972 *outEvent = captureEvent;
973 break;
974 }
arthurhung7632c332020-12-30 16:58:01 +0800975
976 case InputMessage::Type::DRAG: {
977 DragEvent* dragEvent = factory->createDragEvent();
978 if (!dragEvent) return NO_MEMORY;
979
980 initializeDragEvent(dragEvent, &mMsg);
981 *outSeq = mMsg.header.seq;
982 *outEvent = dragEvent;
983 break;
984 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700985
986 case InputMessage::Type::TOUCH_MODE: {
987 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
988 if (!touchModeEvent) return NO_MEMORY;
989
990 initializeTouchModeEvent(touchModeEvent, &mMsg);
991 *outSeq = mMsg.header.seq;
992 *outEvent = touchModeEvent;
993 break;
994 }
Jeff Brown5912f952013-07-01 19:10:31 -0700995 }
996 }
997 return OK;
998}
999
1000status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001001 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001002 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001003 for (size_t i = mBatches.size(); i > 0; ) {
1004 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001005 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001006 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001007 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001008 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001009 return result;
1010 }
1011
Michael Wright32232172013-10-21 12:05:22 -07001012 nsecs_t sampleTime = frameTime;
1013 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001014 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001015 }
Jeff Brown5912f952013-07-01 19:10:31 -07001016 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1017 if (split < 0) {
1018 continue;
1019 }
1020
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001021 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001022 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001023 if (batch.samples.empty()) {
1024 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001025 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001026 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001027 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001028 }
Michael Wright32232172013-10-21 12:05:22 -07001029 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001030 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1031 }
1032 return result;
1033 }
1034
1035 return WOULD_BLOCK;
1036}
1037
1038status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001039 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001040 MotionEvent* motionEvent = factory->createMotionEvent();
1041 if (! motionEvent) return NO_MEMORY;
1042
1043 uint32_t chain = 0;
1044 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001045 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001046 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001047 if (i) {
1048 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001049 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001050 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001051 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001052 addSample(motionEvent, &msg);
1053 } else {
1054 initializeMotionEvent(motionEvent, &msg);
1055 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001056 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001057 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001058 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001059
1060 *outSeq = chain;
1061 *outEvent = motionEvent;
1062 return OK;
1063}
1064
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001065void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001066 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001067 return;
1068 }
1069
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001070 int32_t deviceId = msg.body.motion.deviceId;
1071 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001072
1073 // Update the touch state history to incorporate the new input message.
1074 // If the message is in the past relative to the most recently produced resampled
1075 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001076 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001077 case AMOTION_EVENT_ACTION_DOWN: {
1078 ssize_t index = findTouchState(deviceId, source);
1079 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001080 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001081 index = mTouchStates.size() - 1;
1082 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001083 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001084 touchState.initialize(deviceId, source);
1085 touchState.addHistory(msg);
1086 break;
1087 }
1088
1089 case AMOTION_EVENT_ACTION_MOVE: {
1090 ssize_t index = findTouchState(deviceId, source);
1091 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001092 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001093 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001094 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001095 }
1096 break;
1097 }
1098
1099 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1100 ssize_t index = findTouchState(deviceId, source);
1101 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001102 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001103 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001104 rewriteMessage(touchState, msg);
1105 }
1106 break;
1107 }
1108
1109 case AMOTION_EVENT_ACTION_POINTER_UP: {
1110 ssize_t index = findTouchState(deviceId, source);
1111 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001112 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001113 rewriteMessage(touchState, msg);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001114 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001115 }
1116 break;
1117 }
1118
1119 case AMOTION_EVENT_ACTION_SCROLL: {
1120 ssize_t index = findTouchState(deviceId, source);
1121 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001122 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001123 rewriteMessage(touchState, msg);
1124 }
1125 break;
1126 }
1127
1128 case AMOTION_EVENT_ACTION_UP:
1129 case AMOTION_EVENT_ACTION_CANCEL: {
1130 ssize_t index = findTouchState(deviceId, source);
1131 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001132 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001133 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001134 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001135 }
1136 break;
1137 }
1138 }
1139}
1140
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001141/**
1142 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1143 *
1144 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1145 * is in the past relative to msg and the past two events do not contain identical coordinates),
1146 * then invalidate the lastResample data for that pointer.
1147 * If the two past events have identical coordinates, then lastResample data for that pointer will
1148 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1149 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1150 * not equal to x0 is received.
1151 */
1152void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001153 nsecs_t eventTime = msg.body.motion.eventTime;
1154 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1155 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001156 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001157 if (eventTime < state.lastResample.eventTime ||
1158 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001159 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1160 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001161 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
1162 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1163 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001164 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1165 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001166 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001167 } else {
1168 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001169 }
Jeff Brown5912f952013-07-01 19:10:31 -07001170 }
1171 }
1172}
1173
1174void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1175 const InputMessage* next) {
1176 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001177 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001178 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1179 return;
1180 }
1181
1182 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1183 if (index < 0) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001184 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001185 return;
1186 }
1187
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001188 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001189 if (touchState.historySize < 1) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001190 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001191 return;
1192 }
1193
1194 // Ensure that the current sample has all of the pointers that need to be reported.
1195 const History* current = touchState.getHistory(0);
1196 size_t pointerCount = event->getPointerCount();
1197 for (size_t i = 0; i < pointerCount; i++) {
1198 uint32_t id = event->getPointerId(i);
1199 if (!current->idBits.hasBit(id)) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001200 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001201 return;
1202 }
1203 }
1204
1205 // Find the data to use for resampling.
1206 const History* other;
1207 History future;
1208 float alpha;
1209 if (next) {
1210 // Interpolate between current sample and future sample.
1211 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001212 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001213 other = &future;
1214 nsecs_t delta = future.eventTime - current->eventTime;
1215 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001216 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1217 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001218 return;
1219 }
1220 alpha = float(sampleTime - current->eventTime) / delta;
1221 } else if (touchState.historySize >= 2) {
1222 // Extrapolate future sample using current sample and past sample.
1223 // So other->eventTime <= current->eventTime <= sampleTime.
1224 other = touchState.getHistory(1);
1225 nsecs_t delta = current->eventTime - other->eventTime;
1226 if (delta < RESAMPLE_MIN_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001227 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too small: %" PRId64 " ns.",
1228 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001229 return;
1230 } else if (delta > RESAMPLE_MAX_DELTA) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001231 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, delta time is too large: %" PRId64 " ns.",
1232 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001233 return;
1234 }
1235 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1236 if (sampleTime > maxPredict) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001237 ALOGD_IF(DEBUG_RESAMPLING,
1238 "Sample time is too far in the future, adjusting prediction "
1239 "from %" PRId64 " to %" PRId64 " ns.",
1240 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001241 sampleTime = maxPredict;
1242 }
1243 alpha = float(current->eventTime - sampleTime) / delta;
1244 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001245 ALOGD_IF(DEBUG_RESAMPLING, "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001246 return;
1247 }
1248
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001249 if (current->eventTime == sampleTime) {
1250 // Prevents having 2 events with identical times and coordinates.
1251 return;
1252 }
1253
Jeff Brown5912f952013-07-01 19:10:31 -07001254 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001255 History oldLastResample;
1256 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001257 touchState.lastResample.eventTime = sampleTime;
1258 touchState.lastResample.idBits.clear();
1259 for (size_t i = 0; i < pointerCount; i++) {
1260 uint32_t id = event->getPointerId(i);
1261 touchState.lastResample.idToIndex[id] = i;
1262 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001263 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1264 // We maintain the previously resampled value for this pointer (stored in
1265 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1266 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001267 // The isResampled flag isn't cleared as the values don't reflect what the device is
1268 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001269
1270 // We know here that the coordinates for the pointer haven't changed because we
1271 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1272 // lastResample in place becasue the mapping from pointer ID to index may have changed.
1273 touchState.lastResample.pointers[i].copyFrom(oldLastResample.getPointerById(id));
1274 continue;
1275 }
1276
Jeff Brown5912f952013-07-01 19:10:31 -07001277 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1278 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001279 resampledCoords.copyFrom(currentCoords);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001280 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001281 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001282 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001283 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001284 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001285 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001286 resampledCoords.isResampled = true;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001287 ALOGD_IF(DEBUG_RESAMPLING,
1288 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1289 "other (%0.3f, %0.3f), alpha %0.3f",
1290 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1291 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001292 } else {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001293 ALOGD_IF(DEBUG_RESAMPLING, "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
1294 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1295 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001296 }
1297 }
1298
1299 event->addSample(sampleTime, touchState.lastResample.pointers);
1300}
1301
Jeff Brown5912f952013-07-01 19:10:31 -07001302status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001303 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1304 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1305 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001306
1307 if (!seq) {
1308 ALOGE("Attempted to send a finished signal with sequence number 0.");
1309 return BAD_VALUE;
1310 }
1311
1312 // Send finished signals for the batch sequence chain first.
1313 size_t seqChainCount = mSeqChains.size();
1314 if (seqChainCount) {
1315 uint32_t currentSeq = seq;
1316 uint32_t chainSeqs[seqChainCount];
1317 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001318 for (size_t i = seqChainCount; i > 0; ) {
1319 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001320 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001321 if (seqChain.seq == currentSeq) {
1322 currentSeq = seqChain.chain;
1323 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001324 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001325 }
1326 }
1327 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001328 while (!status && chainIndex > 0) {
1329 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001330 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1331 }
1332 if (status) {
1333 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001334 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001335 SeqChain seqChain;
1336 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1337 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001338 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001339 if (!chainIndex) break;
1340 chainIndex--;
1341 }
Jeff Brown5912f952013-07-01 19:10:31 -07001342 return status;
1343 }
1344 }
1345
1346 // Send finished signal for the last message in the batch.
1347 return sendUnchainedFinishedSignal(seq, handled);
1348}
1349
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001350status_t InputConsumer::sendTimeline(int32_t inputEventId,
1351 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001352 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1353 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1354 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1355 mChannel->getName().c_str(), inputEventId,
1356 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1357 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001358
1359 InputMessage msg;
1360 msg.header.type = InputMessage::Type::TIMELINE;
1361 msg.header.seq = 0;
1362 msg.body.timeline.eventId = inputEventId;
1363 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1364 return mChannel->sendMessage(&msg);
1365}
1366
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001367nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1368 auto it = mConsumeTimes.find(seq);
1369 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1370 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1371 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1372 seq);
1373 return it->second;
1374}
1375
1376void InputConsumer::popConsumeTime(uint32_t seq) {
1377 mConsumeTimes.erase(seq);
1378}
1379
Jeff Brown5912f952013-07-01 19:10:31 -07001380status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1381 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001382 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001383 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001384 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001385 msg.body.finished.consumeTime = getConsumeTime(seq);
1386 status_t result = mChannel->sendMessage(&msg);
1387 if (result == OK) {
1388 // Remove the consume time if the socket write succeeded. We will not need to ack this
1389 // message anymore. If the socket write did not succeed, we will try again and will still
1390 // need consume time.
1391 popConsumeTime(seq);
1392 }
1393 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001394}
1395
Jeff Brown5912f952013-07-01 19:10:31 -07001396bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001397 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001398}
1399
Arthur Hungc7812be2020-02-27 22:40:27 +08001400int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001401 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001402 return AINPUT_SOURCE_CLASS_NONE;
1403 }
1404
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001405 const Batch& batch = mBatches[0];
1406 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001407 return head.body.motion.source;
1408}
1409
Jeff Brown5912f952013-07-01 19:10:31 -07001410ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1411 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001412 const Batch& batch = mBatches[i];
1413 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001414 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1415 return i;
1416 }
1417 }
1418 return -1;
1419}
1420
1421ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1422 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001423 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001424 if (touchState.deviceId == deviceId && touchState.source == source) {
1425 return i;
1426 }
1427 }
1428 return -1;
1429}
1430
1431void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001432 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001433 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1434 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1435 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1436 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001437}
1438
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001439void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001440 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001441}
1442
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001443void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001444 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001445}
1446
arthurhung7632c332020-12-30 16:58:01 +08001447void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1448 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1449 msg->body.drag.isExiting);
1450}
1451
Jeff Brown5912f952013-07-01 19:10:31 -07001452void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001453 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001454 PointerProperties pointerProperties[pointerCount];
1455 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001456 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001457 pointerProperties[i].copyFrom(msg->body.motion.pointers[i].properties);
1458 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1459 }
1460
chaviw9eaa22c2020-07-01 16:21:27 -07001461 ui::Transform transform;
1462 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1463 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001464 ui::Transform displayTransform;
1465 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1466 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1467 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001468 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1469 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1470 msg->body.motion.actionButton, msg->body.motion.flags,
1471 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001472 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1473 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1474 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001475 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1476 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001477}
1478
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001479void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1480 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1481}
1482
Jeff Brown5912f952013-07-01 19:10:31 -07001483void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001484 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001485 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001486 for (uint32_t i = 0; i < pointerCount; i++) {
Jeff Brown5912f952013-07-01 19:10:31 -07001487 pointerCoords[i].copyFrom(msg->body.motion.pointers[i].coords);
1488 }
1489
1490 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1491 event->addSample(msg->body.motion.eventTime, pointerCoords);
1492}
1493
1494bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001495 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001496 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001497 if (head.body.motion.pointerCount != pointerCount
1498 || head.body.motion.action != msg->body.motion.action) {
1499 return false;
1500 }
1501 for (size_t i = 0; i < pointerCount; i++) {
1502 if (head.body.motion.pointers[i].properties
1503 != msg->body.motion.pointers[i].properties) {
1504 return false;
1505 }
1506 }
1507 return true;
1508}
1509
1510ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1511 size_t numSamples = batch.samples.size();
1512 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001513 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001514 index += 1;
1515 }
1516 return ssize_t(index) - 1;
1517}
1518
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001519std::string InputConsumer::dump() const {
1520 std::string out;
1521 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1522 out = out + "mChannel = " + mChannel->getName() + "\n";
1523 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1524 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001525 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001526 }
1527 out += "Batches:\n";
1528 for (const Batch& batch : mBatches) {
1529 out += " Batch:\n";
1530 for (const InputMessage& msg : batch.samples) {
1531 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001532 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001533 switch (msg.header.type) {
1534 case InputMessage::Type::KEY: {
1535 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1536 KeyEvent::actionToString(
1537 msg.body.key.action),
1538 msg.body.key.keyCode);
1539 break;
1540 }
1541 case InputMessage::Type::MOTION: {
1542 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1543 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1544 const float x = msg.body.motion.pointers[i].coords.getX();
1545 const float y = msg.body.motion.pointers[i].coords.getY();
1546 out += android::base::StringPrintf("\n Pointer %" PRIu32
1547 " : x=%.1f y=%.1f",
1548 i, x, y);
1549 }
1550 break;
1551 }
1552 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001553 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1554 toString(msg.body.finished.handled),
1555 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001556 break;
1557 }
1558 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001559 out += android::base::StringPrintf("hasFocus=%s",
1560 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001561 break;
1562 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001563 case InputMessage::Type::CAPTURE: {
1564 out += android::base::StringPrintf("hasCapture=%s",
1565 toString(msg.body.capture
1566 .pointerCaptureEnabled));
1567 break;
1568 }
arthurhung7632c332020-12-30 16:58:01 +08001569 case InputMessage::Type::DRAG: {
1570 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1571 msg.body.drag.x, msg.body.drag.y,
1572 toString(msg.body.drag.isExiting));
1573 break;
1574 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001575 case InputMessage::Type::TIMELINE: {
1576 const nsecs_t gpuCompletedTime =
1577 msg.body.timeline
1578 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1579 const nsecs_t presentTime =
1580 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1581 out += android::base::StringPrintf("inputEventId=%" PRId32
1582 ", gpuCompletedTime=%" PRId64
1583 ", presentTime=%" PRId64,
1584 msg.body.timeline.eventId, gpuCompletedTime,
1585 presentTime);
1586 break;
1587 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001588 case InputMessage::Type::TOUCH_MODE: {
1589 out += android::base::StringPrintf("isInTouchMode=%s",
1590 toString(msg.body.touchMode.isInTouchMode));
1591 break;
1592 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001593 }
1594 out += "\n";
1595 }
1596 }
1597 if (mBatches.empty()) {
1598 out += " <empty>\n";
1599 }
1600 out += "mSeqChains:\n";
1601 for (const SeqChain& chain : mSeqChains) {
1602 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1603 chain.chain);
1604 }
1605 if (mSeqChains.empty()) {
1606 out += " <empty>\n";
1607 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001608 out += "mConsumeTimes:\n";
1609 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1610 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1611 consumeTime);
1612 }
1613 if (mConsumeTimes.empty()) {
1614 out += " <empty>\n";
1615 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001616 return out;
1617}
1618
Jeff Brown5912f952013-07-01 19:10:31 -07001619} // namespace android