rcoremidi 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,15 @@
1
+ #ifndef CLIENT_H
2
+ #define CLIENT_H
3
+
4
+ VALUE client_alloc(VALUE klass);
5
+ VALUE client_init(VALUE self, VALUE name);
6
+ VALUE connect_to(VALUE self, VALUE source);
7
+ VALUE send_packets(int argc, VALUE *argv, VALUE self);
8
+ VALUE start_client(VALUE self);
9
+ VALUE stop_client(VALUE self);
10
+ VALUE client_running(VALUE self);
11
+ VALUE silence_client(VALUE self);
12
+ VALUE dropped_clock_events(VALUE self);
13
+ VALUE dispose_client(VALUE self);
14
+
15
+ #endif
@@ -0,0 +1,9 @@
1
+ require 'mkmf'
2
+
3
+ $CFLAGS << ' -Wall -Wno-unused-parameter'
4
+
5
+ have_framework('CoreMIDI')
6
+ have_framework('CoreFoundation')
7
+ have_framework('CoreAudio')
8
+
9
+ create_makefile('rcoremidi')
@@ -0,0 +1,64 @@
1
+ #include "rcoremidi.h"
2
+ #include <dispatch/dispatch.h>
3
+ #include <pthread.h>
4
+ #include <stdatomic.h>
5
+
6
+ static MIDIClientRef midi_client;
7
+ static bool midi_client_created;
8
+ static OSStatus midi_client_creation_status;
9
+ static dispatch_semaphore_t midi_client_attempted;
10
+ static atomic_bool midi_setup_changed = true;
11
+
12
+ static bool changes_device_list(MIDINotificationMessageID message) {
13
+ return message == kMIDIMsgSetupChanged || message == kMIDIMsgObjectAdded ||
14
+ message == kMIDIMsgObjectRemoved ||
15
+ message == kMIDIMsgPropertyChanged;
16
+ }
17
+
18
+ static void *serve_midi_notifications(void *unused) {
19
+ midi_client_creation_status = MIDIClientCreateWithBlock(
20
+ CFSTR("rcoremidi"), &midi_client, ^(const MIDINotification *message) {
21
+ if (changes_device_list(message->messageID)) {
22
+ atomic_store(&midi_setup_changed, true);
23
+ }
24
+ });
25
+ bool created = midi_client_creation_status == noErr;
26
+ dispatch_semaphore_signal(midi_client_attempted);
27
+ if (created) {
28
+ CFRunLoopRun();
29
+ }
30
+ return NULL;
31
+ }
32
+
33
+ static OSStatus create_client_on_notification_thread(void) {
34
+ static dispatch_once_t once;
35
+ dispatch_once(&once, ^{
36
+ midi_client_attempted = dispatch_semaphore_create(0);
37
+ });
38
+
39
+ pthread_t thread;
40
+ pthread_attr_t attributes;
41
+ pthread_attr_init(&attributes);
42
+ pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
43
+ int started =
44
+ pthread_create(&thread, &attributes, serve_midi_notifications, NULL);
45
+ pthread_attr_destroy(&attributes);
46
+ if (started != 0) {
47
+ return kMIDIUnknownError;
48
+ }
49
+ dispatch_semaphore_wait(midi_client_attempted, DISPATCH_TIME_FOREVER);
50
+ return midi_client_creation_status;
51
+ }
52
+
53
+ MIDIClientRef shared_midi_client(void) {
54
+ if (!midi_client_created) {
55
+ raise_on_midi_error(create_client_on_notification_thread(),
56
+ "Could not create the MIDI client");
57
+ midi_client_created = true;
58
+ }
59
+ return midi_client;
60
+ }
61
+
62
+ bool take_midi_setup_change(void) {
63
+ return atomic_exchange(&midi_setup_changed, false);
64
+ }
@@ -0,0 +1,7 @@
1
+ #ifndef MIDI_CLIENT_H
2
+ #define MIDI_CLIENT_H
3
+
4
+ MIDIClientRef shared_midi_client(void);
5
+ bool take_midi_setup_change(void);
6
+
7
+ #endif
@@ -0,0 +1,207 @@
1
+ #include "rcoremidi.h"
2
+
3
+ static size_t midi_object_memsize(const void *ptr) {
4
+ return sizeof(MIDIObjectRef);
5
+ }
6
+
7
+ const rb_data_type_t midi_object_data_t = {
8
+ "rcoremidi_object",
9
+ {NULL, RUBY_TYPED_DEFAULT_FREE, midi_object_memsize},
10
+ NULL,
11
+ NULL,
12
+ RUBY_TYPED_FREE_IMMEDIATELY};
13
+
14
+ VALUE midi_object_alloc(VALUE klass) {
15
+ MIDIObjectRef *midi_object;
16
+ return TypedData_Make_Struct(klass, MIDIObjectRef, &midi_object_data_t,
17
+ midi_object);
18
+ }
19
+
20
+ MIDIObjectRef *get_midi_data(VALUE rb_midi_object) {
21
+ MIDIObjectRef *midi_object;
22
+ TypedData_Get_Struct(rb_midi_object, MIDIObjectRef, &midi_object_data_t,
23
+ midi_object);
24
+ return midi_object;
25
+ }
26
+
27
+ static VALUE wrap_midi_object(VALUE klass, MIDIObjectRef midi_object) {
28
+ VALUE object = rb_funcall(klass, new_intern, 0);
29
+ *get_midi_data(object) = midi_object;
30
+ return object;
31
+ }
32
+
33
+ static VALUE string_property(MIDIObjectRef midi_object, CFStringRef key) {
34
+ CFStringRef value = NULL;
35
+ if (MIDIObjectGetStringProperty(midi_object, key, &value) != noErr ||
36
+ !value) {
37
+ return Qnil;
38
+ }
39
+ CFIndex capacity = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value),
40
+ kCFStringEncodingUTF8) +
41
+ 1;
42
+ VALUE buffer_owner;
43
+ char *buffer = ALLOCV(buffer_owner, capacity);
44
+ Boolean converted =
45
+ CFStringGetCString(value, buffer, capacity, kCFStringEncodingUTF8);
46
+ CFRelease(value);
47
+ VALUE result = converted ? rb_utf8_str_new_cstr(buffer) : Qnil;
48
+ ALLOCV_END(buffer_owner);
49
+ return result;
50
+ }
51
+
52
+ static bool integer_property(MIDIObjectRef midi_object, CFStringRef key,
53
+ SInt32 *value) {
54
+ return MIDIObjectGetIntegerProperty(midi_object, key, value) == noErr;
55
+ }
56
+
57
+ static void set_string_ivar(VALUE object, const char *ivar,
58
+ MIDIObjectRef midi_object, CFStringRef key) {
59
+ VALUE value = string_property(midi_object, key);
60
+ if (!NIL_P(value)) {
61
+ rb_iv_set(object, ivar, value);
62
+ }
63
+ }
64
+
65
+ static void set_integer_ivar(VALUE object, const char *ivar,
66
+ MIDIObjectRef midi_object, CFStringRef key) {
67
+ SInt32 value;
68
+ if (integer_property(midi_object, key, &value)) {
69
+ rb_iv_set(object, ivar, INT2NUM(value));
70
+ }
71
+ }
72
+
73
+ static void set_boolean_ivar(VALUE object, const char *ivar,
74
+ MIDIObjectRef midi_object, CFStringRef key) {
75
+ SInt32 value;
76
+ if (integer_property(midi_object, key, &value)) {
77
+ rb_iv_set(object, ivar, value ? Qtrue : Qfalse);
78
+ }
79
+ }
80
+
81
+ static void assign_endpoint_properties(VALUE endpoint,
82
+ MIDIEndpointRef midi_endpoint) {
83
+ set_integer_ivar(endpoint, "@uid", midi_endpoint, kMIDIPropertyUniqueID);
84
+ set_string_ivar(endpoint, "@name", midi_endpoint, kMIDIPropertyName);
85
+ }
86
+
87
+ static void assign_entity_properties(VALUE entity, MIDIEntityRef midi_entity) {
88
+ set_integer_ivar(entity, "@uid", midi_entity, kMIDIPropertyUniqueID);
89
+ set_string_ivar(entity, "@name", midi_entity, kMIDIPropertyName);
90
+ set_integer_ivar(entity, "@protocol", midi_entity, kMIDIPropertyProtocolID);
91
+ set_integer_ivar(entity, "@receive_channels", midi_entity,
92
+ kMIDIPropertyReceiveChannels);
93
+ set_boolean_ivar(entity, "@receives_notes", midi_entity,
94
+ kMIDIPropertyReceivesNotes);
95
+ }
96
+
97
+ static void assign_device_properties(VALUE device, MIDIDeviceRef midi_device) {
98
+ set_integer_ivar(device, "@uid", midi_device, kMIDIPropertyUniqueID);
99
+ set_string_ivar(device, "@name", midi_device, kMIDIPropertyName);
100
+ set_string_ivar(device, "@model", midi_device, kMIDIPropertyModel);
101
+ set_string_ivar(device, "@manufacturer", midi_device,
102
+ kMIDIPropertyManufacturer);
103
+ set_string_ivar(device, "@driver", midi_device, kMIDIPropertyDriverOwner);
104
+ set_integer_ivar(device, "@schedule_ahead_micro_seconds", midi_device,
105
+ kMIDIPropertyAdvanceScheduleTimeMuSec);
106
+ set_integer_ivar(device, "@transmit_channels", midi_device,
107
+ kMIDIPropertyTransmitChannels);
108
+ set_integer_ivar(device, "@receives_channels", midi_device,
109
+ kMIDIPropertyReceiveChannels);
110
+ set_boolean_ivar(device, "@supports_general_midi", midi_device,
111
+ kMIDIPropertySupportsGeneralMIDI);
112
+ set_boolean_ivar(device, "@supports_mmc", midi_device,
113
+ kMIDIPropertySupportsMMC);
114
+ set_boolean_ivar(device, "@receives_clock", midi_device,
115
+ kMIDIPropertyReceivesClock);
116
+ set_boolean_ivar(device, "@receives_mtc", midi_device,
117
+ kMIDIPropertyReceivesMTC);
118
+ set_boolean_ivar(device, "@offline", midi_device, kMIDIPropertyOffline);
119
+ set_boolean_ivar(device, "@transmits_mtc", midi_device,
120
+ kMIDIPropertyTransmitsMTC);
121
+ set_boolean_ivar(device, "@transmits_clock", midi_device,
122
+ kMIDIPropertyTransmitsClock);
123
+ }
124
+
125
+ static VALUE build_endpoint(VALUE klass, MIDIEndpointRef midi_endpoint) {
126
+ VALUE endpoint = wrap_midi_object(klass, midi_endpoint);
127
+ assign_endpoint_properties(endpoint, midi_endpoint);
128
+ return endpoint;
129
+ }
130
+
131
+ static VALUE build_entity(VALUE device, MIDIEntityRef midi_entity) {
132
+ VALUE entity = wrap_midi_object(rb_cEntity, midi_entity);
133
+ VALUE endpoints = rb_ary_new();
134
+ rb_iv_set(entity, "@endpoints", endpoints);
135
+ rb_iv_set(entity, "@device", device);
136
+ assign_entity_properties(entity, midi_entity);
137
+
138
+ ItemCount sources = MIDIEntityGetNumberOfSources(midi_entity);
139
+ for (ItemCount i = 0; i < sources; ++i) {
140
+ rb_ary_push(endpoints,
141
+ build_endpoint(rb_cSource, MIDIEntityGetSource(midi_entity, i)));
142
+ }
143
+ ItemCount destinations = MIDIEntityGetNumberOfDestinations(midi_entity);
144
+ for (ItemCount i = 0; i < destinations; ++i) {
145
+ rb_ary_push(endpoints, build_endpoint(rb_cDestination,
146
+ MIDIEntityGetDestination(midi_entity,
147
+ i)));
148
+ }
149
+ return entity;
150
+ }
151
+
152
+ static VALUE build_device(MIDIDeviceRef midi_device) {
153
+ VALUE device = wrap_midi_object(rb_cDevice, midi_device);
154
+ VALUE entities = rb_ary_new();
155
+ rb_iv_set(device, "@entities", entities);
156
+ assign_device_properties(device, midi_device);
157
+
158
+ ItemCount entity_count = MIDIDeviceGetNumberOfEntities(midi_device);
159
+ for (ItemCount i = 0; i < entity_count; ++i) {
160
+ rb_ary_push(entities,
161
+ build_entity(device, MIDIDeviceGetEntity(midi_device, i)));
162
+ }
163
+ return device;
164
+ }
165
+
166
+ VALUE find_by_unique_id(VALUE klass, VALUE uid) {
167
+ MIDIObjectRef midi_object;
168
+ MIDIObjectType midi_object_type;
169
+ OSStatus status = MIDIObjectFindByUniqueID((MIDIUniqueID)NUM2INT(uid),
170
+ &midi_object, &midi_object_type);
171
+ if (status != noErr) {
172
+ rb_raise(rb_eArgError, "MIDI object not found: %d", NUM2INT(uid));
173
+ }
174
+
175
+ switch (midi_object_type) {
176
+ case kMIDIObjectType_Device:
177
+ return build_device(midi_object);
178
+ case kMIDIObjectType_Entity:
179
+ return build_entity(Qnil, midi_object);
180
+ case kMIDIObjectType_Source:
181
+ return build_endpoint(rb_cSource, midi_object);
182
+ case kMIDIObjectType_Destination:
183
+ return build_endpoint(rb_cDestination, midi_object);
184
+ default:
185
+ rb_raise(rb_eArgError, "Unsupported MIDI object type for uid %d",
186
+ NUM2INT(uid));
187
+ }
188
+ }
189
+
190
+ static VALUE build_devices(void) {
191
+ VALUE devices = rb_ary_new();
192
+ ItemCount device_count = MIDIGetNumberOfDevices();
193
+ for (ItemCount i = 0; i < device_count; ++i) {
194
+ rb_ary_push(devices, build_device(MIDIGetDevice(i)));
195
+ }
196
+ return devices;
197
+ }
198
+
199
+ VALUE find_all(VALUE klass) {
200
+ shared_midi_client();
201
+ VALUE devices = rb_cvar_get(klass, devices_intern);
202
+ if (take_midi_setup_change() || RARRAY_LEN(devices) == 0) {
203
+ devices = build_devices();
204
+ rb_cvar_set(klass, devices_intern, devices);
205
+ }
206
+ return devices;
207
+ }
@@ -0,0 +1,9 @@
1
+ #ifndef MIDI_OBJECT_H
2
+ #define MIDI_OBJECT_H
3
+
4
+ VALUE midi_object_alloc(VALUE klass);
5
+ MIDIObjectRef *get_midi_data(VALUE rb_midi_object);
6
+ VALUE find_by_unique_id(VALUE klass, VALUE uid);
7
+ VALUE find_all(VALUE klass);
8
+
9
+ #endif
@@ -0,0 +1,105 @@
1
+ #include "rcoremidi.h"
2
+
3
+ VALUE rb_mRCOREMIDI;
4
+ VALUE rb_cMIDIObject;
5
+ VALUE rb_cDevice;
6
+ VALUE rb_cEntity;
7
+ VALUE rb_cSource;
8
+ VALUE rb_cDestination;
9
+ VALUE rb_cClient;
10
+
11
+ ID new_intern;
12
+ ID devices_intern;
13
+ ID on_intern;
14
+ ID off_intern;
15
+ ID on_timestamp_intern;
16
+ ID off_timestamp_intern;
17
+ ID on_start_intern;
18
+ ID on_tick_intern;
19
+ ID on_stop_intern;
20
+ ID on_continue_intern;
21
+
22
+ void raise_on_midi_error(OSStatus status, const char *message) {
23
+ if (status != noErr) {
24
+ rb_raise(rb_eRuntimeError, "%s (OSStatus %d)", message, (int)status);
25
+ }
26
+ }
27
+
28
+ static VALUE host_time_now(VALUE module) {
29
+ return ULL2NUM(AudioGetCurrentHostTime());
30
+ }
31
+
32
+ static VALUE host_time_to_nanoseconds(VALUE module, VALUE host_time) {
33
+ return ULL2NUM(AudioConvertHostTimeToNanos(NUM2ULL(host_time)));
34
+ }
35
+
36
+ static VALUE host_time_from_nanoseconds(VALUE module, VALUE nanoseconds) {
37
+ return ULL2NUM(AudioConvertNanosToHostTime(NUM2ULL(nanoseconds)));
38
+ }
39
+
40
+ static void init_host_time(void) {
41
+ VALUE host_time = rb_define_module_under(rb_mRCOREMIDI, "HostTime");
42
+ rb_define_singleton_method(host_time, "now", host_time_now, 0);
43
+ rb_define_singleton_method(host_time, "to_nanoseconds",
44
+ host_time_to_nanoseconds, 1);
45
+ rb_define_singleton_method(host_time, "from_nanoseconds",
46
+ host_time_from_nanoseconds, 1);
47
+ }
48
+
49
+ static VALUE define_midi_object_class(const char *name) {
50
+ VALUE klass = rb_define_class_under(rb_mRCOREMIDI, name, rb_cObject);
51
+ rb_define_alloc_func(klass, midi_object_alloc);
52
+ rb_define_attr(klass, "uid", 1, 0);
53
+ return klass;
54
+ }
55
+
56
+ void Init_rcoremidi(void) {
57
+ new_intern = rb_intern("new");
58
+ devices_intern = rb_intern("@@devices");
59
+ on_intern = rb_intern("on");
60
+ off_intern = rb_intern("off");
61
+ on_timestamp_intern = rb_intern("on_timestamp");
62
+ off_timestamp_intern = rb_intern("off_timestamp");
63
+ on_start_intern = rb_intern("on_start");
64
+ on_tick_intern = rb_intern("on_tick");
65
+ on_stop_intern = rb_intern("on_stop");
66
+ on_continue_intern = rb_intern("on_continue");
67
+
68
+ rb_mRCOREMIDI = rb_define_module("RCoreMidi");
69
+ init_host_time();
70
+ init_universal_packet(rb_mRCOREMIDI);
71
+
72
+ rb_cMIDIObject =
73
+ rb_define_class_under(rb_mRCOREMIDI, "MIDIObject", rb_cObject);
74
+ rb_define_singleton_method(rb_cMIDIObject, "find_by_unique_id",
75
+ find_by_unique_id, 1);
76
+
77
+ rb_cDevice = define_midi_object_class("Device");
78
+ rb_cvar_set(rb_cDevice, devices_intern, rb_ary_new());
79
+ rb_define_singleton_method(rb_cDevice, "all", find_all, 0);
80
+ rb_define_attr(rb_cDevice, "name", 1, 0);
81
+ rb_define_attr(rb_cDevice, "driver", 1, 0);
82
+ rb_define_attr(rb_cDevice, "manufacturer", 1, 0);
83
+ rb_define_attr(rb_cDevice, "entities", 1, 0);
84
+
85
+ rb_cEntity = define_midi_object_class("Entity");
86
+ rb_define_attr(rb_cEntity, "name", 1, 0);
87
+ rb_define_attr(rb_cEntity, "endpoints", 1, 0);
88
+
89
+ rb_cSource = define_midi_object_class("Source");
90
+ rb_cDestination = define_midi_object_class("Destination");
91
+
92
+ rb_cClient = rb_define_class_under(rb_mRCOREMIDI, "Client", rb_cObject);
93
+ rb_define_alloc_func(rb_cClient, client_alloc);
94
+ rb_define_method(rb_cClient, "initialize", client_init, 1);
95
+ rb_define_method(rb_cClient, "connect_to", connect_to, 1);
96
+ rb_define_method(rb_cClient, "start", start_client, 0);
97
+ rb_define_method(rb_cClient, "stop", stop_client, 0);
98
+ rb_define_method(rb_cClient, "running?", client_running, 0);
99
+ rb_define_method(rb_cClient, "silence", silence_client, 0);
100
+ rb_define_method(rb_cClient, "dropped_clock_events", dropped_clock_events,
101
+ 0);
102
+ rb_define_method(rb_cClient, "dispose", dispose_client, 0);
103
+ rb_define_method(rb_cClient, "send_packets", send_packets, -1);
104
+ rb_define_attr(rb_cClient, "name", 1, 0);
105
+ }
@@ -0,0 +1,37 @@
1
+ #ifndef RCOREMIDI_H
2
+ #define RCOREMIDI_H
3
+
4
+ #include <CoreAudio/HostTime.h>
5
+ #include <CoreFoundation/CoreFoundation.h>
6
+ #include <CoreMIDI/CoreMIDI.h>
7
+ #include <ruby.h>
8
+ #include <ruby/thread.h>
9
+ #include <stdbool.h>
10
+
11
+ #include "client.h"
12
+ #include "midi_client.h"
13
+ #include "midi_object.h"
14
+ #include "universal_packet.h"
15
+
16
+ extern VALUE rb_cDevice;
17
+ extern VALUE rb_cEntity;
18
+ extern VALUE rb_cSource;
19
+ extern VALUE rb_cDestination;
20
+ extern VALUE rb_cClient;
21
+
22
+ extern ID new_intern;
23
+ extern ID devices_intern;
24
+ extern ID on_intern;
25
+ extern ID off_intern;
26
+ extern ID on_timestamp_intern;
27
+ extern ID off_timestamp_intern;
28
+ extern ID on_start_intern;
29
+ extern ID on_tick_intern;
30
+ extern ID on_stop_intern;
31
+ extern ID on_continue_intern;
32
+
33
+ extern const rb_data_type_t midi_object_data_t;
34
+
35
+ void raise_on_midi_error(OSStatus status, const char *message);
36
+
37
+ #endif
@@ -0,0 +1,190 @@
1
+ #include "rcoremidi.h"
2
+
3
+ enum UniversalMessageType {
4
+ kUniversalSystem = 0x1,
5
+ kUniversalMIDI1ChannelVoice = 0x2,
6
+ kUniversalSysEx7 = 0x3
7
+ };
8
+
9
+ enum SysExChunk {
10
+ kSysExComplete = 0x0,
11
+ kSysExStart = 0x1,
12
+ kSysExContinue = 0x2,
13
+ kSysExEnd = 0x3
14
+ };
15
+
16
+ enum { kSysExBytesPerChunk = 6, kSystemExclusive = 0xF0, kEndOfExclusive = 0xF7 };
17
+
18
+ static const ByteCount kWordsPerMessageType[16] = {1, 1, 1, 2, 2, 4, 1, 1,
19
+ 2, 2, 2, 3, 3, 4, 4, 4};
20
+
21
+ ByteCount universal_message_word_count(UInt32 first_word) {
22
+ return kWordsPerMessageType[first_word >> 28];
23
+ }
24
+
25
+ static int data_byte_count(Byte status) {
26
+ switch (status & 0xF0) {
27
+ case 0x80:
28
+ case 0x90:
29
+ case 0xA0:
30
+ case 0xB0:
31
+ case 0xE0:
32
+ return 2;
33
+ case 0xC0:
34
+ case 0xD0:
35
+ return 1;
36
+ }
37
+ switch (status) {
38
+ case 0xF1:
39
+ case 0xF3:
40
+ return 1;
41
+ case 0xF2:
42
+ return 2;
43
+ case 0xF6:
44
+ case 0xF8:
45
+ case 0xFA:
46
+ case 0xFB:
47
+ case 0xFC:
48
+ case 0xFE:
49
+ case 0xFF:
50
+ return 0;
51
+ }
52
+ return -1;
53
+ }
54
+
55
+ static void ensure_capacity(ByteCount needed) {
56
+ if (needed > kMaxUniversalWordsPerMessage) {
57
+ rb_raise(rb_eArgError, "MIDI message too long for one event");
58
+ }
59
+ }
60
+
61
+ static Byte data_byte(const Byte *bytes, ByteCount index) {
62
+ if (bytes[index] > 0x7F) {
63
+ rb_raise(rb_eArgError, "MIDI data byte out of range: %d", bytes[index]);
64
+ }
65
+ return bytes[index];
66
+ }
67
+
68
+ static ByteCount add_short_message(const Byte *bytes, ByteCount length,
69
+ ByteCount index, UInt32 *words,
70
+ ByteCount word_count) {
71
+ Byte status = bytes[index];
72
+ int data_bytes = data_byte_count(status);
73
+ if (data_bytes < 0) {
74
+ rb_raise(rb_eArgError, "Unsupported MIDI status byte: 0x%02X", status);
75
+ }
76
+ if (index + data_bytes >= length) {
77
+ rb_raise(rb_eArgError, "Incomplete MIDI message for status 0x%02X", status);
78
+ }
79
+ Byte first = data_bytes > 0 ? data_byte(bytes, index + 1) : 0;
80
+ Byte second = data_bytes > 1 ? data_byte(bytes, index + 2) : 0;
81
+ UInt32 type = status >= 0xF0 ? kUniversalSystem : kUniversalMIDI1ChannelVoice;
82
+ ensure_capacity(word_count + 1);
83
+ words[word_count] = (type << 28) | ((UInt32)status << 16) |
84
+ ((UInt32)first << 8) | second;
85
+ return index + 1 + data_bytes;
86
+ }
87
+
88
+ static void add_sysex_chunk(UInt32 *words, ByteCount word_count,
89
+ enum SysExChunk chunk, const Byte *payload,
90
+ ByteCount count) {
91
+ Byte padded[kSysExBytesPerChunk] = {0};
92
+ for (ByteCount i = 0; i < count; ++i) {
93
+ padded[i] = payload[i];
94
+ }
95
+ words[word_count] = ((UInt32)kUniversalSysEx7 << 28) | ((UInt32)chunk << 20) |
96
+ ((UInt32)count << 16) | ((UInt32)padded[0] << 8) |
97
+ padded[1];
98
+ words[word_count + 1] = ((UInt32)padded[2] << 24) |
99
+ ((UInt32)padded[3] << 16) |
100
+ ((UInt32)padded[4] << 8) | padded[5];
101
+ }
102
+
103
+ static enum SysExChunk sysex_chunk_kind(ByteCount offset, ByteCount count,
104
+ ByteCount payload_length) {
105
+ bool first = offset == 0;
106
+ bool last = offset + count >= payload_length;
107
+ if (first && last) {
108
+ return kSysExComplete;
109
+ }
110
+ return first ? kSysExStart : (last ? kSysExEnd : kSysExContinue);
111
+ }
112
+
113
+ static ByteCount add_sysex_message(const Byte *bytes, ByteCount length,
114
+ ByteCount index, UInt32 *words,
115
+ ByteCount *word_count) {
116
+ ByteCount payload_start = index + 1;
117
+ ByteCount end = payload_start;
118
+ while (end < length && bytes[end] != kEndOfExclusive) {
119
+ data_byte(bytes, end);
120
+ ++end;
121
+ }
122
+ if (end == length) {
123
+ rb_raise(rb_eArgError, "System exclusive message is missing 0xF7");
124
+ }
125
+
126
+ ByteCount payload_length = end - payload_start;
127
+ ByteCount offset = 0;
128
+ do {
129
+ ByteCount count = payload_length - offset;
130
+ if (count > kSysExBytesPerChunk) {
131
+ count = kSysExBytesPerChunk;
132
+ }
133
+ ensure_capacity(*word_count + 2);
134
+ add_sysex_chunk(words, *word_count,
135
+ sysex_chunk_kind(offset, count, payload_length),
136
+ bytes + payload_start + offset, count);
137
+ *word_count += 2;
138
+ offset += count;
139
+ } while (offset < payload_length);
140
+ return end + 1;
141
+ }
142
+
143
+ ByteCount universal_words_from_bytes(const Byte *bytes, ByteCount length,
144
+ UInt32 *words) {
145
+ ByteCount word_count = 0;
146
+ ByteCount index = 0;
147
+ while (index < length) {
148
+ if (bytes[index] < 0x80) {
149
+ rb_raise(rb_eArgError, "MIDI message must start with a status byte");
150
+ }
151
+ if (bytes[index] == kSystemExclusive) {
152
+ index = add_sysex_message(bytes, length, index, words, &word_count);
153
+ } else {
154
+ index = add_short_message(bytes, length, index, words, word_count);
155
+ ++word_count;
156
+ }
157
+ }
158
+ return word_count;
159
+ }
160
+
161
+ static VALUE words_for(VALUE module, VALUE message) {
162
+ Check_Type(message, T_ARRAY);
163
+ long length = RARRAY_LEN(message);
164
+ VALUE bytes_owner, words_owner;
165
+ Byte *bytes = ALLOCV_N(Byte, bytes_owner, length ? length : 1);
166
+ for (long i = 0; i < length; ++i) {
167
+ int byte = NUM2INT(rb_ary_entry(message, i));
168
+ if (byte < 0 || byte > 0xFF) {
169
+ rb_raise(rb_eArgError, "MIDI byte out of range: %d", byte);
170
+ }
171
+ bytes[i] = (Byte)byte;
172
+ }
173
+ UInt32 *words =
174
+ ALLOCV_N(UInt32, words_owner, kMaxUniversalWordsPerMessage);
175
+ ByteCount word_count = universal_words_from_bytes(bytes, length, words);
176
+
177
+ VALUE result = rb_ary_new_capa(word_count);
178
+ for (ByteCount i = 0; i < word_count; ++i) {
179
+ rb_ary_push(result, UINT2NUM(words[i]));
180
+ }
181
+ ALLOCV_END(words_owner);
182
+ ALLOCV_END(bytes_owner);
183
+ return result;
184
+ }
185
+
186
+ void init_universal_packet(VALUE rcoremidi_module) {
187
+ VALUE universal_packet =
188
+ rb_define_module_under(rcoremidi_module, "UniversalPacket");
189
+ rb_define_singleton_method(universal_packet, "words_for", words_for, 1);
190
+ }
@@ -0,0 +1,11 @@
1
+ #ifndef UNIVERSAL_PACKET_H
2
+ #define UNIVERSAL_PACKET_H
3
+
4
+ enum { kMaxUniversalWordsPerMessage = 256 };
5
+
6
+ ByteCount universal_words_from_bytes(const Byte *bytes, ByteCount length,
7
+ UInt32 *words);
8
+ ByteCount universal_message_word_count(UInt32 first_word);
9
+ void init_universal_packet(VALUE rcoremidi_module);
10
+
11
+ #endif