blob: 3446540ccfa2197eb8e1215ef40716264371068e [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) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000794 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: %s",
795 mChannel->getName().c_str(), __func__, strerror(result));
Siarhei Vishniakoueedd0fc2021-03-12 09:50:36 +0000796 return android::base::Error(result);
Jeff Brown5912f952013-07-01 19:10:31 -0700797 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000798 if (msg.header.type == InputMessage::Type::FINISHED) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000799 ALOGD_IF(debugTransportPublisher(),
800 "channel '%s' publisher ~ %s: finished: seq=%u, handled=%s",
801 mChannel->getName().c_str(), __func__, msg.header.seq,
802 toString(msg.body.finished.handled));
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000803 return Finished{
804 .seq = msg.header.seq,
805 .handled = msg.body.finished.handled,
806 .consumeTime = msg.body.finished.consumeTime,
807 };
Jeff Brown5912f952013-07-01 19:10:31 -0700808 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000809
810 if (msg.header.type == InputMessage::Type::TIMELINE) {
Prabir Pradhan96282b02023-02-24 22:36:17 +0000811 ALOGD_IF(debugTransportPublisher(), "channel '%s' publisher ~ %s: timeline: id=%d",
812 mChannel->getName().c_str(), __func__, msg.body.timeline.eventId);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000813 return Timeline{
814 .inputEventId = msg.body.timeline.eventId,
815 .graphicsTimeline = msg.body.timeline.graphicsTimeline,
816 };
817 }
818
819 ALOGE("channel '%s' publisher ~ Received unexpected %s message from consumer",
Dominik Laskowski75788452021-02-09 18:51:25 -0800820 mChannel->getName().c_str(), ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000821 return android::base::Error(UNKNOWN_ERROR);
Jeff Brown5912f952013-07-01 19:10:31 -0700822}
823
824// --- InputConsumer ---
825
Siarhei Vishniakouce5ab082020-07-09 17:03:21 -0500826InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel)
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800827 : InputConsumer(channel, isTouchResamplingEnabled()) {}
828
829InputConsumer::InputConsumer(const std::shared_ptr<InputChannel>& channel,
830 bool enableTouchResampling)
831 : mResampleTouch(enableTouchResampling), mChannel(channel), mMsgDeferred(false) {}
Jeff Brown5912f952013-07-01 19:10:31 -0700832
833InputConsumer::~InputConsumer() {
834}
835
836bool InputConsumer::isTouchResamplingEnabled() {
Siarhei Vishniakoub5433e92019-02-21 09:27:39 -0600837 return property_get_bool(PROPERTY_RESAMPLING_ENABLED, true);
Jeff Brown5912f952013-07-01 19:10:31 -0700838}
839
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800840status_t InputConsumer::consume(InputEventFactoryInterface* factory, bool consumeBatches,
841 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000842 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
843 "channel '%s' consumer ~ consume: consumeBatches=%s, frameTime=%" PRId64,
844 mChannel->getName().c_str(), toString(consumeBatches), frameTime);
Jeff Brown5912f952013-07-01 19:10:31 -0700845
846 *outSeq = 0;
Yi Kong5bed83b2018-07-17 12:53:47 -0700847 *outEvent = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -0700848
849 // Fetch the next input message.
850 // Loop until an event can be returned or no additional events are received.
851 while (!*outEvent) {
852 if (mMsgDeferred) {
853 // mMsg contains a valid input message from the previous call to consume
854 // that has not yet been processed.
855 mMsgDeferred = false;
856 } else {
857 // Receive a fresh message.
858 status_t result = mChannel->receiveMessage(&mMsg);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000859 if (result == OK) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -0800860 const auto [_, inserted] =
861 mConsumeTimes.emplace(mMsg.header.seq, systemTime(SYSTEM_TIME_MONOTONIC));
862 LOG_ALWAYS_FATAL_IF(!inserted, "Already have a consume time for seq=%" PRIu32,
863 mMsg.header.seq);
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -1000864 }
Jeff Brown5912f952013-07-01 19:10:31 -0700865 if (result) {
866 // Consume the next batched event unless batches are being held for later.
867 if (consumeBatches || result != WOULD_BLOCK) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800868 result = consumeBatch(factory, frameTime, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -0700869 if (*outEvent) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000870 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
871 "channel '%s' consumer ~ consumed batch event, seq=%u",
872 mChannel->getName().c_str(), *outSeq);
Jeff Brown5912f952013-07-01 19:10:31 -0700873 break;
874 }
875 }
876 return result;
877 }
878 }
879
880 switch (mMsg.header.type) {
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700881 case InputMessage::Type::KEY: {
882 KeyEvent* keyEvent = factory->createKeyEvent();
883 if (!keyEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700884
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700885 initializeKeyEvent(keyEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500886 *outSeq = mMsg.header.seq;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700887 *outEvent = keyEvent;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000888 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
889 "channel '%s' consumer ~ consumed key event, seq=%u",
890 mChannel->getName().c_str(), *outSeq);
891 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700892 }
Jeff Brown5912f952013-07-01 19:10:31 -0700893
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700894 case InputMessage::Type::MOTION: {
895 ssize_t batchIndex = findBatch(mMsg.body.motion.deviceId, mMsg.body.motion.source);
896 if (batchIndex >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500897 Batch& batch = mBatches[batchIndex];
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700898 if (canAddSample(batch, &mMsg)) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500899 batch.samples.push_back(mMsg);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000900 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
901 "channel '%s' consumer ~ appended to batch event",
902 mChannel->getName().c_str());
903 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700904 } else if (isPointerEvent(mMsg.body.motion.source) &&
905 mMsg.body.motion.action == AMOTION_EVENT_ACTION_CANCEL) {
906 // No need to process events that we are going to cancel anyways
907 const size_t count = batch.samples.size();
908 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500909 const InputMessage& msg = batch.samples[i];
910 sendFinishedSignal(msg.header.seq, false);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700911 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500912 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
913 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700914 } else {
915 // We cannot append to the batch in progress, so we need to consume
916 // the previous batch right now and defer the new message until later.
917 mMsgDeferred = true;
918 status_t result = consumeSamples(factory, batch, batch.samples.size(),
919 outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500920 mBatches.erase(mBatches.begin() + batchIndex);
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700921 if (result) {
922 return result;
923 }
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000924 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
925 "channel '%s' consumer ~ consumed batch event and "
926 "deferred current event, seq=%u",
927 mChannel->getName().c_str(), *outSeq);
928 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700929 }
Jeff Brown5912f952013-07-01 19:10:31 -0700930 }
Jeff Brown5912f952013-07-01 19:10:31 -0700931
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800932 // Start a new batch if needed.
933 if (mMsg.body.motion.action == AMOTION_EVENT_ACTION_MOVE ||
934 mMsg.body.motion.action == AMOTION_EVENT_ACTION_HOVER_MOVE) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500935 Batch batch;
936 batch.samples.push_back(mMsg);
937 mBatches.push_back(batch);
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000938 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
939 "channel '%s' consumer ~ started batch event",
940 mChannel->getName().c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800941 break;
942 }
Jeff Brown5912f952013-07-01 19:10:31 -0700943
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800944 MotionEvent* motionEvent = factory->createMotionEvent();
945 if (!motionEvent) return NO_MEMORY;
Jeff Brown5912f952013-07-01 19:10:31 -0700946
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800947 updateTouchState(mMsg);
948 initializeMotionEvent(motionEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500949 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800950 *outEvent = motionEvent;
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -0800951
Prabir Pradhan60dd97a2023-02-23 02:23:02 +0000952 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
953 "channel '%s' consumer ~ consumed motion event, seq=%u",
954 mChannel->getName().c_str(), *outSeq);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800955 break;
Siarhei Vishniakou52402772019-10-22 09:32:30 -0700956 }
Jeff Brown5912f952013-07-01 19:10:31 -0700957
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +0000958 case InputMessage::Type::FINISHED:
959 case InputMessage::Type::TIMELINE: {
Siarhei Vishniakou7766c032021-03-02 20:32:20 +0000960 LOG_ALWAYS_FATAL("Consumed a %s message, which should never be seen by "
961 "InputConsumer!",
Dominik Laskowski75788452021-02-09 18:51:25 -0800962 ftl::enum_string(mMsg.header.type).c_str());
Siarhei Vishniakou3b37f9a2019-11-23 13:42:41 -0800963 break;
964 }
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800965
966 case InputMessage::Type::FOCUS: {
967 FocusEvent* focusEvent = factory->createFocusEvent();
968 if (!focusEvent) return NO_MEMORY;
969
970 initializeFocusEvent(focusEvent, &mMsg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -0500971 *outSeq = mMsg.header.seq;
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -0800972 *outEvent = focusEvent;
973 break;
974 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -0800975
976 case InputMessage::Type::CAPTURE: {
977 CaptureEvent* captureEvent = factory->createCaptureEvent();
978 if (!captureEvent) return NO_MEMORY;
979
980 initializeCaptureEvent(captureEvent, &mMsg);
981 *outSeq = mMsg.header.seq;
982 *outEvent = captureEvent;
983 break;
984 }
arthurhung7632c332020-12-30 16:58:01 +0800985
986 case InputMessage::Type::DRAG: {
987 DragEvent* dragEvent = factory->createDragEvent();
988 if (!dragEvent) return NO_MEMORY;
989
990 initializeDragEvent(dragEvent, &mMsg);
991 *outSeq = mMsg.header.seq;
992 *outEvent = dragEvent;
993 break;
994 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -0700995
996 case InputMessage::Type::TOUCH_MODE: {
997 TouchModeEvent* touchModeEvent = factory->createTouchModeEvent();
998 if (!touchModeEvent) return NO_MEMORY;
999
1000 initializeTouchModeEvent(touchModeEvent, &mMsg);
1001 *outSeq = mMsg.header.seq;
1002 *outEvent = touchModeEvent;
1003 break;
1004 }
Jeff Brown5912f952013-07-01 19:10:31 -07001005 }
1006 }
1007 return OK;
1008}
1009
1010status_t InputConsumer::consumeBatch(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001011 nsecs_t frameTime, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001012 status_t result;
Dan Austin1faef802015-09-22 14:28:07 -07001013 for (size_t i = mBatches.size(); i > 0; ) {
1014 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001015 Batch& batch = mBatches[i];
Michael Wright32232172013-10-21 12:05:22 -07001016 if (frameTime < 0) {
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001017 result = consumeSamples(factory, batch, batch.samples.size(), outSeq, outEvent);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001018 mBatches.erase(mBatches.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001019 return result;
1020 }
1021
Michael Wright32232172013-10-21 12:05:22 -07001022 nsecs_t sampleTime = frameTime;
1023 if (mResampleTouch) {
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001024 sampleTime -= std::chrono::nanoseconds(RESAMPLE_LATENCY).count();
Michael Wright32232172013-10-21 12:05:22 -07001025 }
Jeff Brown5912f952013-07-01 19:10:31 -07001026 ssize_t split = findSampleNoLaterThan(batch, sampleTime);
1027 if (split < 0) {
1028 continue;
1029 }
1030
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001031 result = consumeSamples(factory, batch, split + 1, outSeq, outEvent);
Jeff Brown5912f952013-07-01 19:10:31 -07001032 const InputMessage* next;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001033 if (batch.samples.empty()) {
1034 mBatches.erase(mBatches.begin() + i);
Yi Kong5bed83b2018-07-17 12:53:47 -07001035 next = nullptr;
Jeff Brown5912f952013-07-01 19:10:31 -07001036 } else {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001037 next = &batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001038 }
Michael Wright32232172013-10-21 12:05:22 -07001039 if (!result && mResampleTouch) {
Jeff Brown5912f952013-07-01 19:10:31 -07001040 resampleTouchState(sampleTime, static_cast<MotionEvent*>(*outEvent), next);
1041 }
1042 return result;
1043 }
1044
1045 return WOULD_BLOCK;
1046}
1047
1048status_t InputConsumer::consumeSamples(InputEventFactoryInterface* factory,
Siarhei Vishniakou777a10b2018-01-31 16:45:06 -08001049 Batch& batch, size_t count, uint32_t* outSeq, InputEvent** outEvent) {
Jeff Brown5912f952013-07-01 19:10:31 -07001050 MotionEvent* motionEvent = factory->createMotionEvent();
1051 if (! motionEvent) return NO_MEMORY;
1052
1053 uint32_t chain = 0;
1054 for (size_t i = 0; i < count; i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001055 InputMessage& msg = batch.samples[i];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001056 updateTouchState(msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001057 if (i) {
1058 SeqChain seqChain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001059 seqChain.seq = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001060 seqChain.chain = chain;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001061 mSeqChains.push_back(seqChain);
Jeff Brown5912f952013-07-01 19:10:31 -07001062 addSample(motionEvent, &msg);
1063 } else {
1064 initializeMotionEvent(motionEvent, &msg);
1065 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001066 chain = msg.header.seq;
Jeff Brown5912f952013-07-01 19:10:31 -07001067 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001068 batch.samples.erase(batch.samples.begin(), batch.samples.begin() + count);
Jeff Brown5912f952013-07-01 19:10:31 -07001069
1070 *outSeq = chain;
1071 *outEvent = motionEvent;
1072 return OK;
1073}
1074
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001075void InputConsumer::updateTouchState(InputMessage& msg) {
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001076 if (!mResampleTouch || !isPointerEvent(msg.body.motion.source)) {
Jeff Brown5912f952013-07-01 19:10:31 -07001077 return;
1078 }
1079
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001080 int32_t deviceId = msg.body.motion.deviceId;
1081 int32_t source = msg.body.motion.source;
Jeff Brown5912f952013-07-01 19:10:31 -07001082
1083 // Update the touch state history to incorporate the new input message.
1084 // If the message is in the past relative to the most recently produced resampled
1085 // touch, then use the resampled time and coordinates instead.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001086 switch (msg.body.motion.action & AMOTION_EVENT_ACTION_MASK) {
Jeff Brown5912f952013-07-01 19:10:31 -07001087 case AMOTION_EVENT_ACTION_DOWN: {
1088 ssize_t index = findTouchState(deviceId, source);
1089 if (index < 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001090 mTouchStates.push_back({});
Jeff Brown5912f952013-07-01 19:10:31 -07001091 index = mTouchStates.size() - 1;
1092 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001093 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001094 touchState.initialize(deviceId, source);
1095 touchState.addHistory(msg);
1096 break;
1097 }
1098
1099 case AMOTION_EVENT_ACTION_MOVE: {
1100 ssize_t index = findTouchState(deviceId, source);
1101 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001102 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001103 touchState.addHistory(msg);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001104 rewriteMessage(touchState, msg);
Jeff Brown5912f952013-07-01 19:10:31 -07001105 }
1106 break;
1107 }
1108
1109 case AMOTION_EVENT_ACTION_POINTER_DOWN: {
1110 ssize_t index = findTouchState(deviceId, source);
1111 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001112 TouchState& touchState = mTouchStates[index];
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001113 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001114 rewriteMessage(touchState, msg);
1115 }
1116 break;
1117 }
1118
1119 case AMOTION_EVENT_ACTION_POINTER_UP: {
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);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001124 touchState.lastResample.idBits.clearBit(msg.body.motion.getActionId());
Jeff Brown5912f952013-07-01 19:10:31 -07001125 }
1126 break;
1127 }
1128
1129 case AMOTION_EVENT_ACTION_SCROLL: {
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);
1134 }
1135 break;
1136 }
1137
1138 case AMOTION_EVENT_ACTION_UP:
1139 case AMOTION_EVENT_ACTION_CANCEL: {
1140 ssize_t index = findTouchState(deviceId, source);
1141 if (index >= 0) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001142 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001143 rewriteMessage(touchState, msg);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001144 mTouchStates.erase(mTouchStates.begin() + index);
Jeff Brown5912f952013-07-01 19:10:31 -07001145 }
1146 break;
1147 }
1148 }
1149}
1150
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001151/**
1152 * Replace the coordinates in msg with the coordinates in lastResample, if necessary.
1153 *
1154 * If lastResample is no longer valid for a specific pointer (i.e. the lastResample time
1155 * is in the past relative to msg and the past two events do not contain identical coordinates),
1156 * then invalidate the lastResample data for that pointer.
1157 * If the two past events have identical coordinates, then lastResample data for that pointer will
1158 * remain valid, and will be used to replace these coordinates. Thus, if a certain coordinate x0 is
1159 * resampled to the new value x1, then x1 will always be used to replace x0 until some new value
1160 * not equal to x0 is received.
1161 */
1162void InputConsumer::rewriteMessage(TouchState& state, InputMessage& msg) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001163 nsecs_t eventTime = msg.body.motion.eventTime;
1164 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1165 uint32_t id = msg.body.motion.pointers[i].properties.id;
Jeff Brown5912f952013-07-01 19:10:31 -07001166 if (state.lastResample.idBits.hasBit(id)) {
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001167 if (eventTime < state.lastResample.eventTime ||
1168 state.recentCoordinatesAreIdentical(id)) {
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001169 PointerCoords& msgCoords = msg.body.motion.pointers[i].coords;
1170 const PointerCoords& resampleCoords = state.lastResample.getPointerById(id);
Harry Cutts6c658cc2023-08-02 14:40:40 +00001171 ALOGD_IF(debugResampling(), "[%d] - rewrite (%0.3f, %0.3f), old (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001172 resampleCoords.getX(), resampleCoords.getY(), msgCoords.getX(),
1173 msgCoords.getY());
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001174 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_X, resampleCoords.getX());
1175 msgCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, resampleCoords.getY());
Philip Quinnafb31282022-12-20 18:17:55 -08001176 msgCoords.isResampled = true;
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001177 } else {
1178 state.lastResample.idBits.clearBit(id);
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001179 }
Jeff Brown5912f952013-07-01 19:10:31 -07001180 }
1181 }
1182}
1183
1184void InputConsumer::resampleTouchState(nsecs_t sampleTime, MotionEvent* event,
1185 const InputMessage* next) {
1186 if (!mResampleTouch
Siarhei Vishniakou128eab12019-05-23 10:25:59 +08001187 || !(isPointerEvent(event->getSource()))
Jeff Brown5912f952013-07-01 19:10:31 -07001188 || event->getAction() != AMOTION_EVENT_ACTION_MOVE) {
1189 return;
1190 }
1191
1192 ssize_t index = findTouchState(event->getDeviceId(), event->getSource());
1193 if (index < 0) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001194 ALOGD_IF(debugResampling(), "Not resampled, no touch state for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001195 return;
1196 }
1197
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001198 TouchState& touchState = mTouchStates[index];
Jeff Brown5912f952013-07-01 19:10:31 -07001199 if (touchState.historySize < 1) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001200 ALOGD_IF(debugResampling(), "Not resampled, no history for device.");
Jeff Brown5912f952013-07-01 19:10:31 -07001201 return;
1202 }
1203
1204 // Ensure that the current sample has all of the pointers that need to be reported.
1205 const History* current = touchState.getHistory(0);
1206 size_t pointerCount = event->getPointerCount();
1207 for (size_t i = 0; i < pointerCount; i++) {
1208 uint32_t id = event->getPointerId(i);
1209 if (!current->idBits.hasBit(id)) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001210 ALOGD_IF(debugResampling(), "Not resampled, missing id %d", id);
Jeff Brown5912f952013-07-01 19:10:31 -07001211 return;
1212 }
1213 }
1214
1215 // Find the data to use for resampling.
1216 const History* other;
1217 History future;
1218 float alpha;
1219 if (next) {
1220 // Interpolate between current sample and future sample.
1221 // So current->eventTime <= sampleTime <= future.eventTime.
Siarhei Vishniakou0aeec072017-06-12 15:01:41 +01001222 future.initializeFrom(*next);
Jeff Brown5912f952013-07-01 19:10:31 -07001223 other = &future;
1224 nsecs_t delta = future.eventTime - current->eventTime;
1225 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001226 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001227 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001228 return;
1229 }
1230 alpha = float(sampleTime - current->eventTime) / delta;
1231 } else if (touchState.historySize >= 2) {
1232 // Extrapolate future sample using current sample and past sample.
1233 // So other->eventTime <= current->eventTime <= sampleTime.
1234 other = touchState.getHistory(1);
1235 nsecs_t delta = current->eventTime - other->eventTime;
1236 if (delta < RESAMPLE_MIN_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001237 ALOGD_IF(debugResampling(), "Not resampled, delta time is too small: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001238 delta);
Andrew de los Reyesde18f6c2015-10-01 15:57:25 -07001239 return;
1240 } else if (delta > RESAMPLE_MAX_DELTA) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001241 ALOGD_IF(debugResampling(), "Not resampled, delta time is too large: %" PRId64 " ns.",
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001242 delta);
Jeff Brown5912f952013-07-01 19:10:31 -07001243 return;
1244 }
1245 nsecs_t maxPredict = current->eventTime + min(delta / 2, RESAMPLE_MAX_PREDICTION);
1246 if (sampleTime > maxPredict) {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001247 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001248 "Sample time is too far in the future, adjusting prediction "
1249 "from %" PRId64 " to %" PRId64 " ns.",
1250 sampleTime - current->eventTime, maxPredict - current->eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001251 sampleTime = maxPredict;
1252 }
1253 alpha = float(current->eventTime - sampleTime) / delta;
1254 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001255 ALOGD_IF(debugResampling(), "Not resampled, insufficient data.");
Jeff Brown5912f952013-07-01 19:10:31 -07001256 return;
1257 }
1258
Siarhei Vishniakou0ced3cc2017-11-21 15:33:17 -08001259 if (current->eventTime == sampleTime) {
1260 // Prevents having 2 events with identical times and coordinates.
1261 return;
1262 }
1263
Jeff Brown5912f952013-07-01 19:10:31 -07001264 // Resample touch coordinates.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001265 History oldLastResample;
1266 oldLastResample.initializeFrom(touchState.lastResample);
Jeff Brown5912f952013-07-01 19:10:31 -07001267 touchState.lastResample.eventTime = sampleTime;
1268 touchState.lastResample.idBits.clear();
1269 for (size_t i = 0; i < pointerCount; i++) {
1270 uint32_t id = event->getPointerId(i);
1271 touchState.lastResample.idToIndex[id] = i;
1272 touchState.lastResample.idBits.markBit(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001273 if (oldLastResample.hasPointerId(id) && touchState.recentCoordinatesAreIdentical(id)) {
1274 // We maintain the previously resampled value for this pointer (stored in
1275 // oldLastResample) when the coordinates for this pointer haven't changed since then.
1276 // This way we don't introduce artificial jitter when pointers haven't actually moved.
Philip Quinnafb31282022-12-20 18:17:55 -08001277 // The isResampled flag isn't cleared as the values don't reflect what the device is
1278 // actually reporting.
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001279
1280 // We know here that the coordinates for the pointer haven't changed because we
1281 // would've cleared the resampled bit in rewriteMessage if they had. We can't modify
1282 // lastResample in place becasue the mapping from pointer ID to index may have changed.
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001283 touchState.lastResample.pointers[i] = oldLastResample.getPointerById(id);
Siarhei Vishniakou56c9ae12017-11-06 21:16:47 -08001284 continue;
1285 }
1286
Jeff Brown5912f952013-07-01 19:10:31 -07001287 PointerCoords& resampledCoords = touchState.lastResample.pointers[i];
1288 const PointerCoords& currentCoords = current->getPointerById(id);
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001289 resampledCoords = currentCoords;
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001290 if (other->idBits.hasBit(id) && shouldResampleTool(event->getToolType(i))) {
Jeff Brown5912f952013-07-01 19:10:31 -07001291 const PointerCoords& otherCoords = other->getPointerById(id);
Jeff Brown5912f952013-07-01 19:10:31 -07001292 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_X,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001293 lerp(currentCoords.getX(), otherCoords.getX(), alpha));
Jeff Brown5912f952013-07-01 19:10:31 -07001294 resampledCoords.setAxisValue(AMOTION_EVENT_AXIS_Y,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001295 lerp(currentCoords.getY(), otherCoords.getY(), alpha));
Philip Quinnafb31282022-12-20 18:17:55 -08001296 resampledCoords.isResampled = true;
Harry Cutts6c658cc2023-08-02 14:40:40 +00001297 ALOGD_IF(debugResampling(),
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001298 "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f), "
1299 "other (%0.3f, %0.3f), alpha %0.3f",
1300 id, resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1301 currentCoords.getY(), otherCoords.getX(), otherCoords.getY(), alpha);
Jeff Brown5912f952013-07-01 19:10:31 -07001302 } else {
Harry Cutts6c658cc2023-08-02 14:40:40 +00001303 ALOGD_IF(debugResampling(), "[%d] - out (%0.3f, %0.3f), cur (%0.3f, %0.3f)", id,
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001304 resampledCoords.getX(), resampledCoords.getY(), currentCoords.getX(),
1305 currentCoords.getY());
Jeff Brown5912f952013-07-01 19:10:31 -07001306 }
1307 }
1308
1309 event->addSample(sampleTime, touchState.lastResample.pointers);
1310}
1311
Jeff Brown5912f952013-07-01 19:10:31 -07001312status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001313 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1314 "channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",
1315 mChannel->getName().c_str(), seq, toString(handled));
Jeff Brown5912f952013-07-01 19:10:31 -07001316
1317 if (!seq) {
1318 ALOGE("Attempted to send a finished signal with sequence number 0.");
1319 return BAD_VALUE;
1320 }
1321
1322 // Send finished signals for the batch sequence chain first.
1323 size_t seqChainCount = mSeqChains.size();
1324 if (seqChainCount) {
1325 uint32_t currentSeq = seq;
1326 uint32_t chainSeqs[seqChainCount];
1327 size_t chainIndex = 0;
Dan Austin1faef802015-09-22 14:28:07 -07001328 for (size_t i = seqChainCount; i > 0; ) {
1329 i--;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001330 const SeqChain& seqChain = mSeqChains[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001331 if (seqChain.seq == currentSeq) {
1332 currentSeq = seqChain.chain;
1333 chainSeqs[chainIndex++] = currentSeq;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001334 mSeqChains.erase(mSeqChains.begin() + i);
Jeff Brown5912f952013-07-01 19:10:31 -07001335 }
1336 }
1337 status_t status = OK;
Dan Austin1faef802015-09-22 14:28:07 -07001338 while (!status && chainIndex > 0) {
1339 chainIndex--;
Jeff Brown5912f952013-07-01 19:10:31 -07001340 status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);
1341 }
1342 if (status) {
1343 // An error occurred so at least one signal was not sent, reconstruct the chain.
gaoshang9090d4f2017-05-17 14:36:46 +08001344 for (;;) {
Jeff Brown5912f952013-07-01 19:10:31 -07001345 SeqChain seqChain;
1346 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;
1347 seqChain.chain = chainSeqs[chainIndex];
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001348 mSeqChains.push_back(seqChain);
gaoshang9090d4f2017-05-17 14:36:46 +08001349 if (!chainIndex) break;
1350 chainIndex--;
1351 }
Jeff Brown5912f952013-07-01 19:10:31 -07001352 return status;
1353 }
1354 }
1355
1356 // Send finished signal for the last message in the batch.
1357 return sendUnchainedFinishedSignal(seq, handled);
1358}
1359
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001360status_t InputConsumer::sendTimeline(int32_t inputEventId,
1361 std::array<nsecs_t, GraphicsTimeline::SIZE> graphicsTimeline) {
Prabir Pradhan60dd97a2023-02-23 02:23:02 +00001362 ALOGD_IF(DEBUG_TRANSPORT_CONSUMER,
1363 "channel '%s' consumer ~ sendTimeline: inputEventId=%" PRId32
1364 ", gpuCompletedTime=%" PRId64 ", presentTime=%" PRId64,
1365 mChannel->getName().c_str(), inputEventId,
1366 graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME],
1367 graphicsTimeline[GraphicsTimeline::PRESENT_TIME]);
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001368
1369 InputMessage msg;
1370 msg.header.type = InputMessage::Type::TIMELINE;
1371 msg.header.seq = 0;
1372 msg.body.timeline.eventId = inputEventId;
1373 msg.body.timeline.graphicsTimeline = std::move(graphicsTimeline);
1374 return mChannel->sendMessage(&msg);
1375}
1376
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001377nsecs_t InputConsumer::getConsumeTime(uint32_t seq) const {
1378 auto it = mConsumeTimes.find(seq);
1379 // Consume time will be missing if either 'finishInputEvent' is called twice, or if it was
1380 // called for the wrong (synthetic?) input event. Either way, it is a bug that should be fixed.
1381 LOG_ALWAYS_FATAL_IF(it == mConsumeTimes.end(), "Could not find consume time for seq=%" PRIu32,
1382 seq);
1383 return it->second;
1384}
1385
1386void InputConsumer::popConsumeTime(uint32_t seq) {
1387 mConsumeTimes.erase(seq);
1388}
1389
Jeff Brown5912f952013-07-01 19:10:31 -07001390status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {
1391 InputMessage msg;
Siarhei Vishniakou52402772019-10-22 09:32:30 -07001392 msg.header.type = InputMessage::Type::FINISHED;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001393 msg.header.seq = seq;
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001394 msg.body.finished.handled = handled;
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001395 msg.body.finished.consumeTime = getConsumeTime(seq);
1396 status_t result = mChannel->sendMessage(&msg);
1397 if (result == OK) {
1398 // Remove the consume time if the socket write succeeded. We will not need to ack this
1399 // message anymore. If the socket write did not succeed, we will try again and will still
1400 // need consume time.
1401 popConsumeTime(seq);
1402 }
1403 return result;
Jeff Brown5912f952013-07-01 19:10:31 -07001404}
1405
Jeff Brown5912f952013-07-01 19:10:31 -07001406bool InputConsumer::hasPendingBatch() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001407 return !mBatches.empty();
Jeff Brown5912f952013-07-01 19:10:31 -07001408}
1409
Arthur Hungc7812be2020-02-27 22:40:27 +08001410int32_t InputConsumer::getPendingBatchSource() const {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001411 if (mBatches.empty()) {
Arthur Hungc7812be2020-02-27 22:40:27 +08001412 return AINPUT_SOURCE_CLASS_NONE;
1413 }
1414
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001415 const Batch& batch = mBatches[0];
1416 const InputMessage& head = batch.samples[0];
Arthur Hungc7812be2020-02-27 22:40:27 +08001417 return head.body.motion.source;
1418}
1419
Jeff Brown5912f952013-07-01 19:10:31 -07001420ssize_t InputConsumer::findBatch(int32_t deviceId, int32_t source) const {
1421 for (size_t i = 0; i < mBatches.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001422 const Batch& batch = mBatches[i];
1423 const InputMessage& head = batch.samples[0];
Jeff Brown5912f952013-07-01 19:10:31 -07001424 if (head.body.motion.deviceId == deviceId && head.body.motion.source == source) {
1425 return i;
1426 }
1427 }
1428 return -1;
1429}
1430
1431ssize_t InputConsumer::findTouchState(int32_t deviceId, int32_t source) const {
1432 for (size_t i = 0; i < mTouchStates.size(); i++) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001433 const TouchState& touchState = mTouchStates[i];
Jeff Brown5912f952013-07-01 19:10:31 -07001434 if (touchState.deviceId == deviceId && touchState.source == source) {
1435 return i;
1436 }
1437 }
1438 return -1;
1439}
1440
1441void InputConsumer::initializeKeyEvent(KeyEvent* event, const InputMessage* msg) {
Garfield Tan1c7bc862020-01-28 13:24:04 -08001442 event->initialize(msg->body.key.eventId, msg->body.key.deviceId, msg->body.key.source,
Garfield Tanfbe732e2020-01-24 11:26:14 -08001443 msg->body.key.displayId, msg->body.key.hmac, msg->body.key.action,
1444 msg->body.key.flags, msg->body.key.keyCode, msg->body.key.scanCode,
1445 msg->body.key.metaState, msg->body.key.repeatCount, msg->body.key.downTime,
1446 msg->body.key.eventTime);
Jeff Brown5912f952013-07-01 19:10:31 -07001447}
1448
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001449void InputConsumer::initializeFocusEvent(FocusEvent* event, const InputMessage* msg) {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001450 event->initialize(msg->body.focus.eventId, msg->body.focus.hasFocus);
Siarhei Vishniakou7feb2ea2019-11-25 15:11:23 -08001451}
1452
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001453void InputConsumer::initializeCaptureEvent(CaptureEvent* event, const InputMessage* msg) {
Siarhei Vishniakou38b7f7f2021-03-05 01:57:08 +00001454 event->initialize(msg->body.capture.eventId, msg->body.capture.pointerCaptureEnabled);
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001455}
1456
arthurhung7632c332020-12-30 16:58:01 +08001457void InputConsumer::initializeDragEvent(DragEvent* event, const InputMessage* msg) {
1458 event->initialize(msg->body.drag.eventId, msg->body.drag.x, msg->body.drag.y,
1459 msg->body.drag.isExiting);
1460}
1461
Jeff Brown5912f952013-07-01 19:10:31 -07001462void InputConsumer::initializeMotionEvent(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001463 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001464 PointerProperties pointerProperties[pointerCount];
1465 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001466 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001467 pointerProperties[i] = msg->body.motion.pointers[i].properties;
1468 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001469 }
1470
chaviw9eaa22c2020-07-01 16:21:27 -07001471 ui::Transform transform;
1472 transform.set({msg->body.motion.dsdx, msg->body.motion.dtdx, msg->body.motion.tx,
1473 msg->body.motion.dtdy, msg->body.motion.dsdy, msg->body.motion.ty, 0, 0, 1});
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001474 ui::Transform displayTransform;
1475 displayTransform.set({msg->body.motion.dsdxRaw, msg->body.motion.dtdxRaw,
1476 msg->body.motion.txRaw, msg->body.motion.dtdyRaw,
1477 msg->body.motion.dsdyRaw, msg->body.motion.tyRaw, 0, 0, 1});
Garfield Tan1c7bc862020-01-28 13:24:04 -08001478 event->initialize(msg->body.motion.eventId, msg->body.motion.deviceId, msg->body.motion.source,
1479 msg->body.motion.displayId, msg->body.motion.hmac, msg->body.motion.action,
1480 msg->body.motion.actionButton, msg->body.motion.flags,
1481 msg->body.motion.edgeFlags, msg->body.motion.metaState,
chaviw9eaa22c2020-07-01 16:21:27 -07001482 msg->body.motion.buttonState, msg->body.motion.classification, transform,
1483 msg->body.motion.xPrecision, msg->body.motion.yPrecision,
1484 msg->body.motion.xCursorPosition, msg->body.motion.yCursorPosition,
Prabir Pradhanb9b18502021-08-26 12:30:32 -07001485 displayTransform, msg->body.motion.downTime, msg->body.motion.eventTime,
1486 pointerCount, pointerProperties, pointerCoords);
Jeff Brown5912f952013-07-01 19:10:31 -07001487}
1488
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001489void InputConsumer::initializeTouchModeEvent(TouchModeEvent* event, const InputMessage* msg) {
1490 event->initialize(msg->body.touchMode.eventId, msg->body.touchMode.isInTouchMode);
1491}
1492
Jeff Brown5912f952013-07-01 19:10:31 -07001493void InputConsumer::addSample(MotionEvent* event, const InputMessage* msg) {
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001494 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001495 PointerCoords pointerCoords[pointerCount];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001496 for (uint32_t i = 0; i < pointerCount; i++) {
Siarhei Vishniakou73e6d372023-07-06 18:07:21 -07001497 pointerCoords[i] = msg->body.motion.pointers[i].coords;
Jeff Brown5912f952013-07-01 19:10:31 -07001498 }
1499
1500 event->setMetaState(event->getMetaState() | msg->body.motion.metaState);
1501 event->addSample(msg->body.motion.eventTime, pointerCoords);
1502}
1503
1504bool InputConsumer::canAddSample(const Batch& batch, const InputMessage *msg) {
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001505 const InputMessage& head = batch.samples[0];
Narayan Kamathbc6001b2014-05-02 17:53:33 +01001506 uint32_t pointerCount = msg->body.motion.pointerCount;
Jeff Brown5912f952013-07-01 19:10:31 -07001507 if (head.body.motion.pointerCount != pointerCount
1508 || head.body.motion.action != msg->body.motion.action) {
1509 return false;
1510 }
1511 for (size_t i = 0; i < pointerCount; i++) {
1512 if (head.body.motion.pointers[i].properties
1513 != msg->body.motion.pointers[i].properties) {
1514 return false;
1515 }
1516 }
1517 return true;
1518}
1519
1520ssize_t InputConsumer::findSampleNoLaterThan(const Batch& batch, nsecs_t time) {
1521 size_t numSamples = batch.samples.size();
1522 size_t index = 0;
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001523 while (index < numSamples && batch.samples[index].body.motion.eventTime <= time) {
Jeff Brown5912f952013-07-01 19:10:31 -07001524 index += 1;
1525 }
1526 return ssize_t(index) - 1;
1527}
1528
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001529std::string InputConsumer::dump() const {
1530 std::string out;
1531 out = out + "mResampleTouch = " + toString(mResampleTouch) + "\n";
1532 out = out + "mChannel = " + mChannel->getName() + "\n";
1533 out = out + "mMsgDeferred: " + toString(mMsgDeferred) + "\n";
1534 if (mMsgDeferred) {
Dominik Laskowski75788452021-02-09 18:51:25 -08001535 out = out + "mMsg : " + ftl::enum_string(mMsg.header.type) + "\n";
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001536 }
1537 out += "Batches:\n";
1538 for (const Batch& batch : mBatches) {
1539 out += " Batch:\n";
1540 for (const InputMessage& msg : batch.samples) {
1541 out += android::base::StringPrintf(" Message %" PRIu32 ": %s ", msg.header.seq,
Dominik Laskowski75788452021-02-09 18:51:25 -08001542 ftl::enum_string(msg.header.type).c_str());
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001543 switch (msg.header.type) {
1544 case InputMessage::Type::KEY: {
1545 out += android::base::StringPrintf("action=%s keycode=%" PRId32,
1546 KeyEvent::actionToString(
1547 msg.body.key.action),
1548 msg.body.key.keyCode);
1549 break;
1550 }
1551 case InputMessage::Type::MOTION: {
1552 out = out + "action=" + MotionEvent::actionToString(msg.body.motion.action);
1553 for (uint32_t i = 0; i < msg.body.motion.pointerCount; i++) {
1554 const float x = msg.body.motion.pointers[i].coords.getX();
1555 const float y = msg.body.motion.pointers[i].coords.getY();
1556 out += android::base::StringPrintf("\n Pointer %" PRIu32
1557 " : x=%.1f y=%.1f",
1558 i, x, y);
1559 }
1560 break;
1561 }
1562 case InputMessage::Type::FINISHED: {
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001563 out += android::base::StringPrintf("handled=%s, consumeTime=%" PRId64,
1564 toString(msg.body.finished.handled),
1565 msg.body.finished.consumeTime);
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001566 break;
1567 }
1568 case InputMessage::Type::FOCUS: {
Antonio Kantek3cfec7b2021-11-05 18:26:17 -07001569 out += android::base::StringPrintf("hasFocus=%s",
1570 toString(msg.body.focus.hasFocus));
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001571 break;
1572 }
Prabir Pradhan3f37b7b2020-11-10 16:50:18 -08001573 case InputMessage::Type::CAPTURE: {
1574 out += android::base::StringPrintf("hasCapture=%s",
1575 toString(msg.body.capture
1576 .pointerCaptureEnabled));
1577 break;
1578 }
arthurhung7632c332020-12-30 16:58:01 +08001579 case InputMessage::Type::DRAG: {
1580 out += android::base::StringPrintf("x=%.1f y=%.1f, isExiting=%s",
1581 msg.body.drag.x, msg.body.drag.y,
1582 toString(msg.body.drag.isExiting));
1583 break;
1584 }
Siarhei Vishniakouf94ae022021-02-04 01:23:17 +00001585 case InputMessage::Type::TIMELINE: {
1586 const nsecs_t gpuCompletedTime =
1587 msg.body.timeline
1588 .graphicsTimeline[GraphicsTimeline::GPU_COMPLETED_TIME];
1589 const nsecs_t presentTime =
1590 msg.body.timeline.graphicsTimeline[GraphicsTimeline::PRESENT_TIME];
1591 out += android::base::StringPrintf("inputEventId=%" PRId32
1592 ", gpuCompletedTime=%" PRId64
1593 ", presentTime=%" PRId64,
1594 msg.body.timeline.eventId, gpuCompletedTime,
1595 presentTime);
1596 break;
1597 }
Antonio Kantek7cdf8ef2021-07-13 18:04:53 -07001598 case InputMessage::Type::TOUCH_MODE: {
1599 out += android::base::StringPrintf("isInTouchMode=%s",
1600 toString(msg.body.touchMode.isInTouchMode));
1601 break;
1602 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001603 }
1604 out += "\n";
1605 }
1606 }
1607 if (mBatches.empty()) {
1608 out += " <empty>\n";
1609 }
1610 out += "mSeqChains:\n";
1611 for (const SeqChain& chain : mSeqChains) {
1612 out += android::base::StringPrintf(" chain: seq = %" PRIu32 " chain=%" PRIu32, chain.seq,
1613 chain.chain);
1614 }
1615 if (mSeqChains.empty()) {
1616 out += " <empty>\n";
1617 }
Siarhei Vishniakou3531ae72021-02-02 12:12:27 -10001618 out += "mConsumeTimes:\n";
1619 for (const auto& [seq, consumeTime] : mConsumeTimes) {
1620 out += android::base::StringPrintf(" seq = %" PRIu32 " consumeTime = %" PRId64, seq,
1621 consumeTime);
1622 }
1623 if (mConsumeTimes.empty()) {
1624 out += " <empty>\n";
1625 }
Siarhei Vishniakoua64c1592020-06-22 12:02:29 -05001626 return out;
1627}
1628
Jeff Brown5912f952013-07-01 19:10:31 -07001629} // namespace android