1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "media/midi/usb_midi_device_android.h"
6
7 #include <jni.h>
8 #include <vector>
9
10 #include "base/android/jni_array.h"
11 #include "base/time/time.h"
12 #include "jni/UsbMidiDeviceAndroid_jni.h"
13
14 namespace media {
15
UsbMidiDeviceAndroid(ObjectRef raw_device,UsbMidiDeviceDelegate * delegate)16 UsbMidiDeviceAndroid::UsbMidiDeviceAndroid(ObjectRef raw_device,
17 UsbMidiDeviceDelegate* delegate)
18 : raw_device_(raw_device), delegate_(delegate) {
19 JNIEnv* env = base::android::AttachCurrentThread();
20 Java_UsbMidiDeviceAndroid_registerSelf(
21 env, raw_device_.obj(), reinterpret_cast<jlong>(this));
22 }
23
~UsbMidiDeviceAndroid()24 UsbMidiDeviceAndroid::~UsbMidiDeviceAndroid() {
25 JNIEnv* env = base::android::AttachCurrentThread();
26 Java_UsbMidiDeviceAndroid_close(env, raw_device_.obj());
27 }
28
GetDescriptor()29 std::vector<uint8> UsbMidiDeviceAndroid::GetDescriptor() {
30 JNIEnv* env = base::android::AttachCurrentThread();
31 base::android::ScopedJavaLocalRef<jbyteArray> descriptors =
32 Java_UsbMidiDeviceAndroid_getDescriptors(env, raw_device_.obj());
33
34 std::vector<uint8> ret;
35 base::android::JavaByteArrayToByteVector(env, descriptors.obj(), &ret);
36 return ret;
37 }
38
Send(int endpoint_number,const std::vector<uint8> & data)39 void UsbMidiDeviceAndroid::Send(int endpoint_number,
40 const std::vector<uint8>& data) {
41 JNIEnv* env = base::android::AttachCurrentThread();
42 const uint8* head = data.size() ? &data[0] : NULL;
43 ScopedJavaLocalRef<jbyteArray> data_to_pass =
44 base::android::ToJavaByteArray(env, head, data.size());
45
46 Java_UsbMidiDeviceAndroid_send(
47 env, raw_device_.obj(), endpoint_number, data_to_pass.obj());
48 }
49
OnData(JNIEnv * env,jobject caller,jint endpoint_number,jbyteArray data)50 void UsbMidiDeviceAndroid::OnData(JNIEnv* env,
51 jobject caller,
52 jint endpoint_number,
53 jbyteArray data) {
54 std::vector<uint8> bytes;
55 base::android::JavaByteArrayToByteVector(env, data, &bytes);
56
57 const uint8* head = bytes.size() ? &bytes[0] : NULL;
58 delegate_->ReceiveUsbMidiData(this, endpoint_number, head, bytes.size(),
59 base::TimeTicks::HighResNow());
60 }
61
RegisterUsbMidiDevice(JNIEnv * env)62 bool UsbMidiDeviceAndroid::RegisterUsbMidiDevice(JNIEnv* env) {
63 return RegisterNativesImpl(env);
64 }
65
66 } // namespace media
67