summaryrefslogtreecommitdiffstats
path: root/core/java/android/midi/MidiDeviceServer.java
blob: 6ce4bf79d17dd89471a6019fdaaa32cb3912b3f1 (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
/*
 * Copyright (C) 2014 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.
 */

package android.midi;

import android.os.ParcelFileDescriptor;
import android.os.RemoteException;
import android.system.OsConstants;
import android.util.Log;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;

/** @hide */
public final class MidiDeviceServer implements Closeable {
    private static final String TAG = "MidiDeviceServer";

    private final IMidiManager mMidiManager;

    // MidiDeviceInfo for the device implemented by this server
    private MidiDeviceInfo mDeviceInfo;
    private int mInputPortCount;
    private int mOutputPortCount;

    // output ports for receiving messages from our clients
    // we can have only one per port number
    private MidiOutputPort[] mInputPortSenders;

    // receivers attached to our input ports
    private ArrayList<MidiReceiver>[] mInputPortReceivers;

    // input ports for sending messages to our clients
    // we can have multiple outputs per port number
    private ArrayList<MidiInputPort>[] mOutputPortReceivers;

    // subclass of MidiInputPort for passing to clients
    // that notifies us when the connection has failed
    private class ServerInputPort extends MidiInputPort {
        ServerInputPort(ParcelFileDescriptor pfd, int portNumber) {
            super(pfd, portNumber);
        }

        @Override
        public void onIOException() {
            synchronized (mOutputPortReceivers) {
                mOutputPortReceivers[getPortNumber()] = null;
            }
        }
    }

    // subclass of MidiOutputPort for passing to clients
    // that notifies us when the connection has failed
    private class ServerOutputPort extends MidiOutputPort {
        ServerOutputPort(ParcelFileDescriptor pfd, int portNumber) {
            super(pfd, portNumber);
        }

        @Override
        public void onIOException() {
            synchronized (mInputPortSenders) {
                mInputPortSenders[getPortNumber()] = null;
            }
        }
    }

    // Binder interface stub for receiving connection requests from clients
    private final IMidiDeviceServer mServer = new IMidiDeviceServer.Stub() {

        @Override
        public ParcelFileDescriptor openInputPort(int portNumber) {
            if (portNumber < 0 || portNumber >= mInputPortCount) {
                Log.e(TAG, "portNumber out of range in openInputPort: " + portNumber);
                return null;
            }

            ParcelFileDescriptor result = null;
            MidiOutputPort newOutputPort = null;

            synchronized (mInputPortSenders) {
                if (mInputPortSenders[portNumber] != null) {
                    Log.d(TAG, "port " + portNumber + " already open");
                    return null;
                }

                try {
                    ParcelFileDescriptor[] pair = ParcelFileDescriptor.createSocketPair(
                                                        OsConstants.SOCK_SEQPACKET);
                    newOutputPort = new ServerOutputPort(pair[0], portNumber);
                    mInputPortSenders[portNumber] = newOutputPort;
                    result =  pair[1];
                } catch (IOException e) {
                    Log.e(TAG, "unable to create ParcelFileDescriptors in openInputPort");
                    return null;
                }

                if (newOutputPort != null) {
                    ArrayList<MidiReceiver> receivers = mInputPortReceivers[portNumber];
                    synchronized (receivers) {
                        for (int i = 0; i < receivers.size(); i++) {
                            newOutputPort.connect(receivers.get(i));
                        }
                    }
                }
            }

            return result;
        }

        @Override
        public ParcelFileDescriptor openOutputPort(int portNumber) {
            if (portNumber < 0 || portNumber >= mOutputPortCount) {
                Log.e(TAG, "portNumber out of range in openOutputPort: " + portNumber);
                return null;
            }
            synchronized (mOutputPortReceivers) {
                try {
                    ParcelFileDescriptor[] pair = ParcelFileDescriptor.createSocketPair(
                                                        OsConstants.SOCK_SEQPACKET);
                    mOutputPortReceivers[portNumber].add(new ServerInputPort(pair[0], portNumber));
                    return pair[1];
                } catch (IOException e) {
                    Log.e(TAG, "unable to create ParcelFileDescriptors in openOutputPort");
                    return null;
                }
            }
        }
    };

    /* package */ MidiDeviceServer(IMidiManager midiManager) {
        mMidiManager = midiManager;
    }

    /* package */ IMidiDeviceServer getBinderInterface() {
        return mServer;
    }

    /* package */ void setDeviceInfo(MidiDeviceInfo deviceInfo) {
        if (mDeviceInfo != null) {
            throw new IllegalStateException("setDeviceInfo should only be called once");
        }
        mDeviceInfo = deviceInfo;
        mInputPortCount = deviceInfo.getInputPortCount();
        mOutputPortCount = deviceInfo.getOutputPortCount();
        mInputPortSenders = new MidiOutputPort[mInputPortCount];

        mInputPortReceivers = new ArrayList[mInputPortCount];
        for (int i = 0; i < mInputPortCount; i++) {
            mInputPortReceivers[i] = new ArrayList<MidiReceiver>();
        }

        mOutputPortReceivers = new ArrayList[mOutputPortCount];
        for (int i = 0; i < mOutputPortCount; i++) {
            mOutputPortReceivers[i] = new ArrayList<MidiInputPort>();
        }
    }

    @Override
    public void close() throws IOException {
        try {
            // FIXME - close input and output ports too?
            mMidiManager.unregisterDeviceServer(mServer);
        } catch (RemoteException e) {
            Log.e(TAG, "RemoteException in unregisterDeviceServer");
        }
    }

    /**
     * Returns a {@link MidiDeviceInfo} object, which describes this device.
     *
     * @return the {@link MidiDeviceInfo} object
     */
    public MidiDeviceInfo getInfo() {
        return mDeviceInfo;
    }

    /**
     * Called to open a {@link MidiSender} to allow receiving MIDI messages
     * on the device's input port for the specified port number.
     *
     * @param portNumber the number of the input port
     * @return the {@link MidiSender}
     */
    public MidiSender openInputPortSender(int portNumber) {
        if (portNumber < 0 || portNumber >= mDeviceInfo.getInputPortCount()) {
            throw new IllegalArgumentException("portNumber " + portNumber + " out of range");
        }
        final int portNumberF = portNumber;
        return new MidiSender() {

            @Override
            public void connect(MidiReceiver receiver) {
                // We always synchronize on mInputPortSenders before receivers if we need to
                // synchronize on both.
                synchronized (mInputPortSenders) {
                    ArrayList<MidiReceiver> receivers = mInputPortReceivers[portNumberF];
                    synchronized (receivers) {
                        receivers.add(receiver);
                        MidiOutputPort outputPort = mInputPortSenders[portNumberF];
                        if (outputPort != null) {
                            outputPort.connect(receiver);
                        }
                    }
                }
            }

            @Override
            public void disconnect(MidiReceiver receiver) {
                // We always synchronize on mInputPortSenders before receivers if we need to
                // synchronize on both.
                synchronized (mInputPortSenders) {
                    ArrayList<MidiReceiver> receivers = mInputPortReceivers[portNumberF];
                    synchronized (receivers) {
                        receivers.remove(receiver);
                        MidiOutputPort outputPort = mInputPortSenders[portNumberF];
                        if (outputPort != null) {
                            outputPort.disconnect(receiver);
                        }
                    }
                }
            }
        };
    }

    /**
     * Called to open a {@link MidiReceiver} to allow sending MIDI messages
     * on the virtual device's output port for the specified port number.
     *
     * @param portNumber the number of the output port
     * @return the {@link MidiReceiver}
     */
    public MidiReceiver openOutputPortReceiver(int portNumber) {
        if (portNumber < 0 || portNumber >= mDeviceInfo.getOutputPortCount()) {
            throw new IllegalArgumentException("portNumber " + portNumber + " out of range");
        }
        final int portNumberF = portNumber;
        return new MidiReceiver() {

            @Override
            public void onPost(byte[] msg, int offset, int count, long timestamp) throws IOException {
                ArrayList<MidiInputPort> receivers = mOutputPortReceivers[portNumberF];
                synchronized (receivers) {
                    for (int i = 0; i < receivers.size(); i++) {
                        // FIXME catch errors and remove dead ones
                        receivers.get(i).onPost(msg, offset, count, timestamp);
                    }
                }
            }
        };
    }
}