summaryrefslogtreecommitdiff
path: root/app/src/main/java/com/javispedro/vndroid/RFBServer.java
blob: f5af05c6f11cd796bc839451d6c04c51e1f39b83 (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
package com.javispedro.vndroid;

import android.graphics.PixelFormat;
import android.media.Image;
import android.support.annotation.Nullable;
import android.util.EventLog;

import java.nio.ByteBuffer;

public class RFBServer {
    private static final String TAG = RFBServer.class.getSimpleName();

    @Nullable
    private Image lastImage = null;

    @Nullable
    private EventCallback callback = null;

    public class ServerException extends RuntimeException {
        public ServerException(String what) {
            super(what);
        }
    }

    public interface EventCallback {
        void onPointerEvent(int buttonMask, int x, int y);
        void onKeyEvent(int key, boolean state);
    }

    public RFBServer() {
        if (!allocate()) {
            throw new ServerException("failure to allocate()");
        }
    }

    public void start() {
        if (!init()) {
            throw new ServerException("failure to init()");
        }
    }

    public void stop() {
        forgetLastImage();
        shutdown();
    }

    public void finalize() {
        forgetLastImage();
        shutdown();
        deallocate();
    }

    public void setEventCallback(EventCallback c) {
        callback = c;
        set_event_callback(c);
    }

    public void putImage(Image image) {
        Image.Plane[] planes = image.getPlanes();

        if (image.getFormat() != PixelFormat.RGBA_8888) {
            String msg = "Unknown pixel format: " + image.getFormat();
            throw new UnsupportedOperationException(msg);
        }
        if (planes.length != 1) {
            String msg = "Unknown number of planes: " + planes.length;
            throw new UnsupportedOperationException(msg);
        }

        Image.Plane plane = planes[0];

        if (!put_image(image.getWidth(), image.getHeight(), plane.getBuffer(), plane.getPixelStride(), plane.getRowStride())) {
            throw new ServerException("failed to put image");
        }

        forgetLastImage();
        lastImage = image;
    }

    private void forgetLastImage() {
        if (lastImage != null) {
            lastImage.close();
        }
        lastImage = null;
    }

    private long nativeData = 0;

    private native boolean allocate();
    private native void deallocate();

    private native boolean init();
    private native void shutdown();

    private native void set_event_callback(EventCallback c);

    private native boolean put_image(int width, int height, ByteBuffer buffer, int pixel_stride, int row_stride);
}