1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package android.media.midi;
18 
19 import android.os.IBinder;
20 import android.os.RemoteException;
21 import android.util.Log;
22 
23 import dalvik.system.CloseGuard;
24 
25 import libcore.io.IoUtils;
26 
27 import java.io.Closeable;
28 import java.io.FileDescriptor;
29 import java.io.FileOutputStream;
30 import java.io.IOException;
31 import java.util.concurrent.atomic.AtomicInteger;
32 
33 /**
34  * This class is used for sending data to a port on a MIDI device
35  */
36 public final class MidiInputPort extends MidiReceiver implements Closeable {
37     private static final String TAG = "MidiInputPort";
38 
39     private IMidiDeviceServer mDeviceServer;
40     private final IBinder mToken;
41     private final int mPortNumber;
42     private FileDescriptor mFileDescriptor;
43     private FileOutputStream mOutputStream;
44 
45     private final CloseGuard mGuard = CloseGuard.get();
46     private boolean mIsClosed;
47     private AtomicInteger mTotalBytes = new AtomicInteger();
48 
49     // buffer to use for sending data out our output stream
50     private final byte[] mBuffer = new byte[MidiPortImpl.MAX_PACKET_SIZE];
51 
MidiInputPort(IMidiDeviceServer server, IBinder token, FileDescriptor fd, int portNumber)52     /* package */ MidiInputPort(IMidiDeviceServer server, IBinder token,
53             FileDescriptor fd, int portNumber) {
54         super(MidiPortImpl.MAX_PACKET_DATA_SIZE);
55 
56         mDeviceServer = server;
57         mToken = token;
58         mFileDescriptor = fd;
59         mPortNumber = portNumber;
60         mOutputStream = new FileOutputStream(fd);
61         mGuard.open("close");
62     }
63 
MidiInputPort(FileDescriptor fd, int portNumber)64     /* package */ MidiInputPort(FileDescriptor fd, int portNumber) {
65         this(null, null, fd, portNumber);
66     }
67 
68     /**
69      * Returns the port number of this port
70      *
71      * @return the port's port number
72      */
getPortNumber()73     public final int getPortNumber() {
74         return mPortNumber;
75     }
76 
77     @Override
onSend(byte[] msg, int offset, int count, long timestamp)78     public void onSend(byte[] msg, int offset, int count, long timestamp) throws IOException {
79         if (offset < 0 || count < 0 || offset + count > msg.length) {
80             throw new IllegalArgumentException("offset or count out of range");
81         }
82         if (count > MidiPortImpl.MAX_PACKET_DATA_SIZE) {
83             throw new IllegalArgumentException("count exceeds max message size");
84         }
85 
86         synchronized (mBuffer) {
87             if (mOutputStream == null) {
88                 throw new IOException("MidiInputPort is closed");
89             }
90             int length = MidiPortImpl.packData(msg, offset, count, timestamp, mBuffer);
91             mOutputStream.write(mBuffer, 0, length);
92             mTotalBytes.addAndGet(length);
93         }
94     }
95 
96     @Override
onFlush()97     public void onFlush() throws IOException {
98         synchronized (mBuffer) {
99             if (mOutputStream == null) {
100                 throw new IOException("MidiInputPort is closed");
101             }
102             int length = MidiPortImpl.packFlush(mBuffer);
103             mOutputStream.write(mBuffer, 0, length);
104         }
105     }
106 
107     // used by MidiDevice.connectInputPort() to connect our socket directly to another device
claimFileDescriptor()108     /* package */ FileDescriptor claimFileDescriptor() {
109         synchronized (mGuard) {
110             FileDescriptor fd;
111             synchronized (mBuffer) {
112                 fd = mFileDescriptor;
113                 if (fd == null) return null;
114                 IoUtils.closeQuietly(mOutputStream);
115                 mFileDescriptor = null;
116                 mOutputStream = null;
117             }
118 
119             // Set mIsClosed = true so we will not call mDeviceServer.closePort() in close().
120             // MidiDevice.MidiConnection.close() will do the cleanup instead.
121             mIsClosed = true;
122             return fd;
123         }
124     }
125 
126     // used by MidiDevice.MidiConnection to close this port after the connection is closed
getToken()127     /* package */ IBinder getToken() {
128         return mToken;
129     }
130 
131     // used by MidiDevice.MidiConnection to close this port after the connection is closed
getDeviceServer()132     /* package */ IMidiDeviceServer getDeviceServer() {
133         return mDeviceServer;
134     }
135 
136     @Override
close()137     public void close() throws IOException {
138         synchronized (mGuard) {
139             if (mIsClosed) return;
140             mGuard.close();
141             synchronized (mBuffer) {
142                 if (mFileDescriptor != null) {
143                     IoUtils.closeQuietly(mFileDescriptor);
144                     mFileDescriptor = null;
145                 }
146                 if (mOutputStream != null) {
147                     mOutputStream.close();
148                     mOutputStream = null;
149                 }
150             }
151             if (mDeviceServer != null) {
152                 try {
153                     mDeviceServer.closePort(mToken);
154                 } catch (RemoteException e) {
155                     Log.e(TAG, "RemoteException in MidiInputPort.close()");
156                 }
157             }
158             mIsClosed = true;
159         }
160     }
161 
162     @Override
finalize()163     protected void finalize() throws Throwable {
164         try {
165             if (mGuard != null) {
166                 mGuard.warnIfOpen();
167             }
168 
169             // not safe to make binder calls from finalize()
170             mDeviceServer = null;
171             close();
172         } finally {
173             super.finalize();
174         }
175     }
176 
177     /**
178      * Pulls total number of bytes and sets to zero. This allows multiple callers.
179      * @hide
180      */
pullTotalBytesCount()181     public int pullTotalBytesCount() {
182         return mTotalBytes.getAndSet(0);
183     }
184 }
185