aboutsummaryrefslogtreecommitdiffstats
path: root/android/multitouch-port.c
blob: 9a9313cddcdfbc9f88126d2f89cbd6abaa35c385 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "qemu-common.h"
#include "utils/panic.h"
#include "android/hw-events.h"
#include "android/charmap.h"
#include "android/multitouch-screen.h"
#include "android/multitouch-port.h"
#include "android/globals.h"  /* for android_hw */
#include "android/utils/misc.h"
#include "android/utils/jpeg-compress.h"

#define  E(...)    derror(__VA_ARGS__)
#define  W(...)    dwarning(__VA_ARGS__)
#define  D(...)    VERBOSE_PRINT(mtport,__VA_ARGS__)
#define  D_ACTIVE  VERBOSE_CHECK(mtport)

/* Query timeout in milliseconds. */
#define MTSP_QUERY_TIMEOUT       3000
#define MTSP_MAX_MSG             2048
#define MTSP_MAX_EVENT           2048

/* Multi-touch port descriptor. */
struct AndroidMTSPort {
    /* Caller identifier. */
    void*           opaque;
    /* Connected android device. */
    AndroidDevice*  device;
    /* Initialized JPEG compressor instance. */
    AJPEGDesc*      jpeg_compressor;
    /* Connection status: 1 connected, 0 - disconnected. */
    int             is_connected;
    /* Buffer where to receive multitouch messages. */
    char            mts_msg[MTSP_MAX_MSG];
    /* Buffer where to receive multitouch events. */
    char            events[MTSP_MAX_EVENT];
};

/* Destroys and frees the descriptor. */
static void
_mts_port_free(AndroidMTSPort* mtsp)
{
    if (mtsp != NULL) {
        if (mtsp->jpeg_compressor != NULL) {
            jpeg_compressor_destroy(mtsp->jpeg_compressor);
        }
        if (mtsp->device != NULL) {
            android_device_destroy(mtsp->device);
        }
        AFREE(mtsp);
    }
}

/********************************************************************************
 *                          Multi-touch action handlers
 *******************************************************************************/

/*
 * Although there are a lot of similarities in the way the handlers below are
 * implemented, for the sake of tracing / debugging it's better to have a
 * separate handler for each distinctive action.
 */

/* First pointer down event handler. */
static void
_on_action_down(int tracking_id, int x, int y, int pressure)
{
    multitouch_update_pointer(MTES_DEVICE, tracking_id, x, y, pressure);
}

/* Last pointer up event handler. */
static void
_on_action_up(int tracking_id)
{
    multitouch_update_pointer(MTES_DEVICE, tracking_id, 0, 0, 0);
}

/* Pointer down event handler. */
static void
_on_action_pointer_down(int tracking_id, int x, int y, int pressure)
{
    multitouch_update_pointer(MTES_DEVICE, tracking_id, x, y, pressure);
}

/* Pointer up event handler. */
static void
_on_action_pointer_up(int tracking_id)
{
    multitouch_update_pointer(MTES_DEVICE, tracking_id, 0, 0, 0);
}

/* Pointer move event handler. */
static void
_on_action_move(int tracking_id, int x, int y, int pressure)
{
    multitouch_update_pointer(MTES_DEVICE, tracking_id, x, y, pressure);
}

/********************************************************************************
 *                          Multi-touch event handlers
 *******************************************************************************/

/* Handles "pointer move" event. */
static void
_on_move(const char* param)
{
    const char* pid = param;
    D(">>> MOVE: %s", param);
    while (pid && *pid) {
        int pid_val, x, y, pressure = 0;
        if (!get_token_value_int(pid, "pid", &pid_val) &&
            !get_token_value_int(pid, "x", &x) &&
            !get_token_value_int(pid, "y", &y)) {
            get_token_value_int(pid, "pressure", &pressure);
            _on_action_move(pid_val, x, y, pressure);
            pid = strstr(pid + 1, "pid");
        } else {
            break;
        }
    }
}

/* Handles "first pointer down" event. */
static void
_on_down(const char* param)
{
    int pid_val, x, y, pressure = 0;
    D(">>> 1-ST DOWN: %s", param);
    if (!get_token_value_int(param, "pid", &pid_val) &&
        !get_token_value_int(param, "x", &x) &&
        !get_token_value_int(param, "y", &y)) {
        get_token_value_int(param, "pressure", &pressure);
        _on_action_down(pid_val, x, y, pressure);
    } else {
        W("Invalid parameters '%s' for MTS 'down' event", param);
    }
}

/* Handles "last pointer up" event. */
static void
_on_up(const char* param)
{
    int pid_val;
    D(">>> LAST UP: %s", param);
    if (!get_token_value_int(param, "pid", &pid_val)) {
        _on_action_up(pid_val);
    } else {
        W("Invalid parameters '%s' for MTS 'up' event", param);
    }
}

/* Handles "next pointer down" event. */
static void
_on_pdown(const char* param)
{
    int pid_val, x, y, pressure = 0;
    D(">>> DOWN: %s", param);
    if (!get_token_value_int(param, "pid", &pid_val) &&
        !get_token_value_int(param, "x", &x) &&
        !get_token_value_int(param, "y", &y)) {
        get_token_value_int(param, "pressure", &pressure);
        _on_action_pointer_down(pid_val, x, y, pressure);
    } else {
        W("Invalid parameters '%s' for MTS 'pointer down' event", param);
    }
}

/* Handles "next pointer up" event. */
static void
_on_pup(const char* param)
{
    int pid_val;
    D(">>> UP: %s", param);
    if (!get_token_value_int(param, "pid", &pid_val)) {
        _on_action_pointer_up(pid_val);
    } else {
        W("Invalid parameters '%s' for MTS 'up' event", param);
    }
}

/********************************************************************************
 *                      Device communication callbacks
 *******************************************************************************/

/* Main event handler.
 * This routine is invoked when an event message has been received from the
 * device.
 */
static void
_on_event_received(void* opaque, AndroidDevice* ad, char* msg, int msgsize)
{
    char* action;
    int res;
    AndroidMTSPort* mtsp = (AndroidMTSPort*)opaque;

    if (errno) {
        D("Multi-touch notification has failed: %s", strerror(errno));
        return;
    }

    /* Dispatch the event to an appropriate handler. */
    res = get_token_value_alloc(msg, "action", &action);
    if (!res) {
        const char* param = strchr(msg, ' ');
        if (param) {
            param++;
        }
        if (!strcmp(action, "move")) {
            _on_move(param);
        } else if (!strcmp(action, "down")) {
            _on_down(param);
        } else if (!strcmp(action, "up")) {
            _on_up(param);
        } else if (!strcmp(action, "pdown")) {
            _on_pdown(param);
        } else if (!strcmp(action, "pup")) {
            _on_pup(param);
        } else {
            D("Unknown multi-touch event action '%s'", action);
        }
        free(action);
    }

    /* Listen to the next event. */
    android_device_listen(ad, mtsp->events, sizeof(mtsp->events),
                          _on_event_received);
}

/* A callback that is invoked when android device is connected (i.e. both,
 * command and event channels have been established).
 * Param:
 *  opaque - AndroidMTSPort instance.
 *  ad - Android device used by this port.
 *  failure - Connections status.
 */
static void
_on_device_connected(void* opaque, AndroidDevice* ad, int failure)
{
    if (!failure) {
        AndroidMTSPort* mtsp = (AndroidMTSPort*)opaque;
        mtsp->is_connected = 1;
        D("Multi-touch emulation has started");
        android_device_listen(mtsp->device, mtsp->events, sizeof(mtsp->events),
                              _on_event_received);
        mts_port_start(mtsp);
    }
}

/* Invoked when an I/O failure occurs on a socket.
 * Note that this callback will not be invoked on connection failures.
 * Param:
 *  opaque - AndroidMTSPort instance.
 *  ad - Android device instance
 *  ads - Connection socket where failure has occured.
 *  failure - Contains 'errno' indicating the reason for failure.
 */
static void
_on_io_failure(void* opaque, AndroidDevice* ad, int failure)
{
    AndroidMTSPort* mtsp = (AndroidMTSPort*)opaque;
    E("Multi-touch port got disconnected: %s", strerror(failure));
    mtsp->is_connected = 0;
    android_device_disconnect(ad);

    /* Try to reconnect again. */
    android_device_connect_async(ad, _on_device_connected);
}

/********************************************************************************
 *                          MTS port API
 *******************************************************************************/

AndroidMTSPort*
mts_port_create(void* opaque)
{
    AndroidMTSPort* mtsp;
    int res;

    ANEW0(mtsp);
    mtsp->opaque = opaque;
    mtsp->is_connected = 0;

    /* Initialize default MTS descriptor. */
    multitouch_init(mtsp);

    /* Create JPEG compressor. Put "$BLOB:%09d\0" + MTFrameHeader header in front
     * of the compressed data. this way we will have entire query ready to be
     * transmitted to the device. */
    mtsp->jpeg_compressor = jpeg_compressor_create(16 + sizeof(MTFrameHeader), 4096);

    mtsp->device = android_device_init(mtsp, AD_MULTITOUCH_PORT, _on_io_failure);
    if (mtsp->device == NULL) {
        _mts_port_free(mtsp);
        return NULL;
    }

    res = android_device_connect_async(mtsp->device, _on_device_connected);
    if (res != 0) {
        mts_port_destroy(mtsp);
        return NULL;
    }

    return mtsp;
}

void
mts_port_destroy(AndroidMTSPort* mtsp)
{
    _mts_port_free(mtsp);
}

int
mts_port_is_connected(AndroidMTSPort* mtsp)
{
    return mtsp->is_connected;
}

int
mts_port_start(AndroidMTSPort* mtsp)
{
    char qresp[MTSP_MAX_MSG];
    char query[256];
    AndroidHwConfig* config = android_hw;

    /* Query the device to start capturing multi-touch events, also providing
     * the device with width / height of the emulator's screen. This is required
     * so device can properly adjust multi-touch event coordinates, and display
     * emulator's framebuffer. */
    snprintf(query, sizeof(query), "start:%dx%d",
             config->hw_lcd_width, config->hw_lcd_height);
    int res = android_device_query(mtsp->device, query, qresp, sizeof(qresp),
                                   MTSP_QUERY_TIMEOUT);
    if (!res) {
        /* By protocol device should reply with its view dimensions. */
        if (*qresp) {
            int width, height;
            if (sscanf(qresp, "%dx%d", &width, &height) == 2) {
                multitouch_set_device_screen_size(width, height);
                D("Multi-touch emulation has started. Device dims: %dx%d",
                  width, height);
            } else {
                E("Unexpected reply to MTS 'start' query: %s", qresp);
                android_device_query(mtsp->device, "stop", qresp, sizeof(qresp),
                                     MTSP_QUERY_TIMEOUT);
                res = -1;
            }
        } else {
            E("MTS protocol error: no reply to query 'start'");
            android_device_query(mtsp->device, "stop", qresp, sizeof(qresp),
                                 MTSP_QUERY_TIMEOUT);
            res = -1;
        }
    } else {
        if (errno) {
            D("Query 'start' failed on I/O: %s", strerror(errno));
        } else {
            D("Query 'start' failed on device: %s", qresp);
        }
    }
    return res;
}

int
mts_port_stop(AndroidMTSPort* mtsp)
{
    char qresp[MTSP_MAX_MSG];
    const int res =
        android_device_query(mtsp->device, "stop", qresp, sizeof(qresp),
                             MTSP_QUERY_TIMEOUT);
    if (res) {
        if (errno) {
            D("Query 'stop' failed on I/O: %s", strerror(errno));
        } else {
            D("Query 'stop' failed on device: %s", qresp);
        }
    }

    return res;
}

/********************************************************************************
 *                       Handling framebuffer updates
 *******************************************************************************/

/* Compresses a framebuffer region into JPEG image.
 * Param:
 *  mtsp - Multi-touch port descriptor with initialized JPEG compressor.
 *  fmt Descriptor for framebuffer region to compress.
 *  fb Beginning of the framebuffer.
 *  jpeg_quality JPEG compression quality. A number from 1 to 100. Note that
 *      value 10 provides pretty decent image for the purpose of multi-touch
 *      emulation.
 */
static void
_fb_compress(const AndroidMTSPort* mtsp,
             const MTFrameHeader* fmt,
             const uint8_t* fb,
             int jpeg_quality,
             int ydir)
{
    jpeg_compressor_compress_fb(mtsp->jpeg_compressor, fmt->x, fmt->y, fmt->w,
                                fmt->h, fmt->disp_height, fmt->bpp, fmt->bpl,
                                fb, jpeg_quality, ydir);
}

int
mts_port_send_frame(AndroidMTSPort* mtsp,
                    MTFrameHeader* fmt,
                    const uint8_t* fb,
                    async_send_cb cb,
                    void* cb_opaque,
                    int ydir)
{
    char* query;
    int blob_size, off;

    /* Make sure that port is connected. */
    if (!mts_port_is_connected(mtsp)) {
        return -1;
    }

    /* Compress framebuffer region. 10% quality seems to be sufficient. */
    fmt->format = MTFB_JPEG;
    _fb_compress(mtsp, fmt, fb, 10, ydir);

    /* Total size of the blob: header + JPEG image. */
    blob_size = sizeof(MTFrameHeader) +
                jpeg_compressor_get_jpeg_size(mtsp->jpeg_compressor);

    /* Query starts at the beginning of the buffer allocated by the compressor's
     * destination manager. */
    query = (char*)jpeg_compressor_get_buffer(mtsp->jpeg_compressor);

    /* Build the $BLOB query to transfer to the device. */
    snprintf(query, jpeg_compressor_get_header_size(mtsp->jpeg_compressor),
             "$BLOB:%09d", blob_size);
    off = strlen(query) + 1;

    /* Copy framebuffer update header to the query. */
    memcpy(query + off, fmt, sizeof(MTFrameHeader));

    /* Zeroing the rectangle in the update header we indicate that it contains
     * no updates. */
    fmt->x = fmt->y = fmt->w = fmt->h = 0;

    /* Initiate asynchronous transfer of the updated framebuffer rectangle. */
    if (android_device_send_async(mtsp->device, query, off + blob_size, 0, cb, cb_opaque)) {
        D("Unable to send query '%s': %s", query, strerror(errno));
        return -1;
    }

    return 0;
}