summaryrefslogtreecommitdiff
path: root/app/src/main/cpp/native-lib.cpp
blob: 3a1811cfb8e286dcb82df7493815ab04817fc8de (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
#include <android/log.h>
#include <sys/eventfd.h>
#include <thread>

#include <jni.h>
#include <rfb/rfb.h>

#define LOG_TAG "RFBServerNative"

#define CLASS_EVENT_CALLBACK "com/javispedro/vndroid/RFBServer$EventCallback"

static void rfb_err(const char *format, ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_ERROR, LOG_TAG, format, args);
    va_end(args);
}

static void rfb_log(const char *format, ...) {
    va_list args;
    va_start(args, format);
    __android_log_vprint(ANDROID_LOG_DEBUG, LOG_TAG, format, args);
    va_end(args);
}

struct Data
{
    jclass cls;
    jfieldID fid;
    jfieldID fid_cb;

    rfbScreenInfoPtr screen;

    std::thread listenThread;
    int listenEventFd;

    std::thread eventThread;
    int eventEventFd;

    jclass cb_cls;
    jobject cb_obj;
    jmethodID cb_ev_ptr;
    jmethodID cb_ev_key;

    std::atomic<bool> pendingPtrEvent;
    int ptrButtonMask, ptrX, ptrY;

    std::atomic<bool> pendingKeyEvent;
    rfbKeySym key;
    bool keyState;
};

static inline Data * getData(JNIEnv *env, jobject instance)
{
    jclass cls = env->GetObjectClass(instance);
    cls = reinterpret_cast<jclass>(env->NewGlobalRef(cls));

    jfieldID fid = env->GetFieldID(cls, "nativeData", "J");

    Data *data = reinterpret_cast<Data*>(env->GetLongField(instance, fid));

    assert(data);

    return data;
}

static inline Data * getData(rfbClientPtr client)
{
    Data *data = reinterpret_cast<Data*>(client->screen->screenData);
    assert(data);
    return data;
}

static void listen_thread_main(Data *data, JavaVM *vm)
{
    rfbScreenInfoPtr screen = data->screen;

    while (rfbIsActive(screen)) {
        int client_fd = -1;
        fd_set listen_fds;  /* temp file descriptor list for select() */
        FD_ZERO(&listen_fds);
        if(screen->listenSock >= 0)
            FD_SET(screen->listenSock, &listen_fds);
        if(screen->listen6Sock >= 0)
            FD_SET(screen->listen6Sock, &listen_fds);

        assert(data->listenEventFd >= 0);
        FD_SET(data->listenEventFd, &listen_fds);

        int max_fd = std::max(screen->maxFd, data->listenEventFd) + 1;

        if (select(max_fd, &listen_fds, NULL, NULL, NULL) == -1) {
            rfb_err("listen_thread_main: error in select");
            return;
        }

        /* there is something on the listening sockets, handle new connections */
        struct sockaddr_storage peer;
        socklen_t len = sizeof (peer);
        if (screen->listenSock >= 0 && FD_ISSET(screen->listenSock, &listen_fds))
            client_fd = accept(screen->listenSock, (struct sockaddr*)&peer, &len);
        else if (screen->listen6Sock >= 0 && FD_ISSET(screen->listen6Sock, &listen_fds))
            client_fd = accept(screen->listen6Sock, (struct sockaddr*)&peer, &len);
        else if (data->listenEventFd >= 0 && FD_ISSET(data->listenEventFd, &listen_fds))
            break;

        rfbClientPtr cl = NULL;
        if(client_fd >= 0)
            cl = rfbNewClient(screen,client_fd);
        if (cl && !cl->onHold )
            rfbStartOnHoldClient(cl);
    }
}

static void event_thread_main(Data *data, JavaVM *vm)
{
    rfbScreenInfoPtr screen = data->screen;

    JNIEnv *env = NULL;
    vm->AttachCurrentThread(&env, 0);
    assert(env);

    eventfd_t value;
    while (rfbIsActive(screen)) {
        if (eventfd_read(data->eventEventFd, &value) != 0)
            break;

        if (data->pendingPtrEvent) {
            env->CallVoidMethod(data->cb_obj, data->cb_ev_ptr, (jint)data->ptrButtonMask, data->ptrX, data->ptrY);
            data->pendingPtrEvent = false;
        }

        if (data->pendingKeyEvent) {
            env->CallVoidMethod(data->cb_obj, data->cb_ev_key, (jint)data->key, (jboolean)data->keyState);
            data->pendingKeyEvent = false;
        }
    }

    vm->DetachCurrentThread();
}

static void ptr_event(int buttonMask, int x, int y, rfbClientPtr cl)
{
    Data *data = getData(cl);

    data->ptrButtonMask = buttonMask;
    data->ptrX = x;
    data->ptrY = y;
    data->pendingPtrEvent = true;

    eventfd_write(data->eventEventFd, 1);

    rfbDefaultPtrAddEvent(buttonMask, x, y, cl);
}

static void key_event(rfbBool down, rfbKeySym keySym, rfbClientPtr cl)
{
    Data *data = getData(cl);

    // TODO This misses keys...

    data->key = keySym;
    data->keyState = down;
    data->pendingKeyEvent = true;

    eventfd_write(data->eventEventFd, 1);
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_javispedro_vndroid_RFBServer_allocate(JNIEnv *env, jobject instance)
{
    jclass cls = env->GetObjectClass(instance);
    cls = reinterpret_cast<jclass>(env->NewGlobalRef(cls));

    jfieldID fid = env->GetFieldID(cls, "nativeData", "J");

    assert(fid);
    assert(env->GetLongField(instance, fid) == 0);

    rfb_log("starting server");

    rfbErr = rfb_err;
    rfbLog = rfb_log;

    Data *data = new Data();
    assert(data);

    data->cls = cls;
    data->fid = fid;
    data->fid_cb = env->GetFieldID(cls, "callback", "L" CLASS_EVENT_CALLBACK ";");
    assert(data->fid_cb);

    jclass cb_cls = env->FindClass(CLASS_EVENT_CALLBACK);
    assert(cb_cls);
    data->cb_cls = cb_cls = reinterpret_cast<jclass>(env->NewGlobalRef(cb_cls));
    data->cb_obj = 0;
    data->cb_ev_ptr = env->GetMethodID(cb_cls, "onPointerEvent", "(III)V");
    assert(data->cb_ev_ptr);
    data->cb_ev_key = env->GetMethodID(cb_cls, "onKeyEvent", "(IZ)V");
    assert(data->cb_ev_key);

    data->screen = 0;
    data->listenEventFd = -1;
    data->eventEventFd = -1;

    env->SetLongField(instance, fid, reinterpret_cast<jlong>(data));

    return JNI_TRUE;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_javispedro_vndroid_RFBServer_deallocate(JNIEnv *env, jobject instance)
{
    Data *data = getData(env, instance);

    assert(data->screen == 0);

    env->SetLongField(instance, data->fid, 0);
    env->DeleteGlobalRef(data->cb_cls);
    if (data->cb_obj) env->DeleteGlobalRef(data->cb_obj);
    env->DeleteGlobalRef(data->cls);

    data->cb_cls = 0;
    data->cb_obj = 0;
    data->cls = 0;

    delete data;
}


extern "C"
JNIEXPORT jboolean JNICALL
Java_com_javispedro_vndroid_RFBServer_init(JNIEnv *env, jobject instance)
{
    Data *data = getData(env, instance);

    if (data->screen) {
        rfb_err("server already initialized");
        return JNI_FALSE;
    }

    JavaVM *vm = NULL;
    env->GetJavaVM(&vm);

    rfb_log("allocating rfb screen");
    data->screen = rfbGetScreen(NULL, NULL, 0, 0, 0, 0, 0);
    rfbInitServer(data->screen);

    data->screen->screenData = data;
    data->screen->ptrAddEvent = ptr_event;
    data->screen->kbdAddEvent = key_event;

    rfb_log("starting listen thread");
    data->screen->backgroundLoop = TRUE;
    data->listenEventFd = eventfd(0, EFD_CLOEXEC);
    if (data->listenEventFd == -1) {
        rfbLogPerror("eventfd");
        return FALSE;
    }
    data->listenThread = std::thread(listen_thread_main, data, vm);

    rfb_log("starting event thread");
    data->eventThread = std::thread(event_thread_main, data, vm);
    data->eventEventFd = eventfd(0, EFD_CLOEXEC);
    if (data->eventEventFd == -1) {
        rfbLogPerror("eventfd");
        return FALSE;
    }

    return JNI_TRUE;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_javispedro_vndroid_RFBServer_shutdown(JNIEnv *env, jobject instance)
{
    Data *data = getData(env, instance);

    if (!data->screen) {
        return; // Nothing to do
    }

    rfb_log("shutting down rfb screen");
    rfbShutdownServer(data->screen, TRUE);

    rfb_log("waiting for listen thread");
    if (data->listenThread.joinable()) {
        assert(data->listenEventFd != -1);
        eventfd_write(data->listenEventFd, 1);
        data->listenThread.join();
    }
    close(data->listenEventFd);
    data->listenEventFd = -1;

    rfb_log("waiting for event thread");
    if (data->eventThread.joinable()) {
        assert(data->eventEventFd != -1);
        eventfd_write(data->eventEventFd, 1);
        data->eventThread.join();
    }
    close(data->eventEventFd);
    data->eventEventFd = -1;

    rfb_log("freeing up resources");
    rfbScreenCleanup(data->screen);
    data->screen = 0;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_javispedro_vndroid_RFBServer_set_1event_1callback(JNIEnv *env, jobject instance,
                                                           jobject callback) {
    Data *data = getData(env, instance);

    if (data->cb_obj) {
        env->DeleteGlobalRef(data->cb_obj);
    }

    if (callback) {
        data->cb_obj = env->NewGlobalRef(callback);
    } else {
        data->cb_obj = 0;
    }
}

extern "C"
JNIEXPORT jboolean JNICALL
Java_com_javispedro_vndroid_RFBServer_put_1image(JNIEnv *env, jobject instance, jint width,
                                                 jint height, jobject buffer, jint pixel_stride,
                                                 jint row_stride) {
    Data *data = getData(env, instance);
    if (!data->screen) {
        rfb_err("no screen");
        return JNI_FALSE;
    }

    const int bitsPerSample = 8;
    const int samplesPerPixel = 3;
    const int bytesPerPixel = pixel_stride;
    const int bitsPerPixel = 8 * bytesPerPixel;
    const int bytesPerRow = row_stride;

    bool size_change = data->screen->width != width || data->screen->height != height;
    bool format_change = data->screen->bitsPerPixel != bitsPerPixel or data->screen->paddedWidthInBytes != bytesPerRow;

    char * fb = reinterpret_cast<char *>(env->GetDirectBufferAddress(buffer));

    if (size_change || format_change) {
        rfb_log("size or format changed");

        rfbNewFramebuffer(data->screen, fb, width, height, bitsPerSample, samplesPerPixel,
                          bytesPerPixel, bytesPerRow);
    } else {
        data->screen->frameBuffer = fb;
        rfbMarkRectAsModified(data->screen, 0, 0, width, height);
    }

    return JNI_TRUE;
}