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.
- checksums.yaml +7 -0
- data/README.md +129 -0
- data/ext/rcoremidi/client.c +579 -0
- data/ext/rcoremidi/client.h +15 -0
- data/ext/rcoremidi/extconf.rb +9 -0
- data/ext/rcoremidi/midi_client.c +64 -0
- data/ext/rcoremidi/midi_client.h +7 -0
- data/ext/rcoremidi/midi_object.c +207 -0
- data/ext/rcoremidi/midi_object.h +9 -0
- data/ext/rcoremidi/rcoremidi.c +105 -0
- data/ext/rcoremidi/rcoremidi.h +37 -0
- data/ext/rcoremidi/universal_packet.c +190 -0
- data/ext/rcoremidi/universal_packet.h +11 -0
- data/lib/rcoremidi/client.rb +58 -0
- data/lib/rcoremidi/destination.rb +26 -0
- data/lib/rcoremidi/device.rb +13 -0
- data/lib/rcoremidi/entity.rb +21 -0
- data/lib/rcoremidi/source.rb +4 -0
- data/lib/rcoremidi/version.rb +3 -0
- data/lib/rcoremidi.rb +7 -0
- metadata +132 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 06ffb555ac55f2cfda68e6f9750ae91067884f73a820e7f7395c2e1b1a3ba002
|
|
4
|
+
data.tar.gz: 2a20cf56e3d7bbc9f61b34a2c468d275b00e37f2e99fdeef1fb254f4374777ca
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: a70466d1109d19bd5f464b7e0a5e914a65a2a67afdf38b743856c29b24a3f69586fb3c56e4cbbb98fb7a0f4925c29b26f5573d90530b52b50f88133a9252d9ce
|
|
7
|
+
data.tar.gz: 63c7380a5344ed5ebc3ca2484a13eef5a00a986fa97e2f8a099328f6ce80c85d6ffe0b33ae4605ca39ffe080a3b0a0b392bf7f4d714bf804c39966efa0ded235
|
data/README.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
# rcoremidi
|
|
2
|
+
|
|
3
|
+
Ruby bindings for the macOS [CoreMIDI](https://developer.apple.com/documentation/coremidi) framework, written as a C extension.
|
|
4
|
+
|
|
5
|
+
rcoremidi lists MIDI devices and their endpoints, follows an external MIDI clock (Start, Clock, Stop, Continue, Song Position) by calling hooks on a `RCoreMidi::Client` subclass, and sends timestamped notes through CoreMIDI's host-time scheduler. It is only a driver: it has no notion of bars, tempo or patterns.
|
|
6
|
+
|
|
7
|
+
For live coding music on top of it, see [archaeopteryx](https://github.com/StupidCodeFactory/archaeopteryx).
|
|
8
|
+
|
|
9
|
+
## Requirements
|
|
10
|
+
|
|
11
|
+
- macOS 11 or later (the extension links CoreMIDI, CoreAudio and CoreFoundation and uses the Universal MIDI Packet API)
|
|
12
|
+
- Ruby 3.2 or later
|
|
13
|
+
- Xcode command line tools, to compile the extension
|
|
14
|
+
|
|
15
|
+
It does not build on Linux or Windows.
|
|
16
|
+
|
|
17
|
+
## Install
|
|
18
|
+
|
|
19
|
+
```sh
|
|
20
|
+
gem install rcoremidi
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
or in a Gemfile:
|
|
24
|
+
|
|
25
|
+
```ruby
|
|
26
|
+
gem 'rcoremidi'
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
From a checkout, `bundle install && bundle exec rake compile` builds the extension into `lib/`.
|
|
30
|
+
|
|
31
|
+
## Listing devices
|
|
32
|
+
|
|
33
|
+
```ruby
|
|
34
|
+
require 'rcoremidi'
|
|
35
|
+
|
|
36
|
+
RCoreMidi::Device.all.each do |device|
|
|
37
|
+
puts device.name
|
|
38
|
+
device.entities.each do |entity|
|
|
39
|
+
puts " #{entity.name}: #{entity.sources.size} in, #{entity.destinations.size} out"
|
|
40
|
+
end
|
|
41
|
+
end
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`Device.all` is rebuilt after any CoreMIDI setup change. Each `Entity` has `endpoints`, split into `sources` (MIDI in) and `destinations` (MIDI out). `RCoreMidi::Destination.named('Port 1')` finds a destination by name across all devices, and raises if none or several match.
|
|
45
|
+
|
|
46
|
+
## Following a clock and sending notes
|
|
47
|
+
|
|
48
|
+
Subclass `RCoreMidi::Client` and override the hooks you need. The C extension calls them on the thread that called `start`:
|
|
49
|
+
|
|
50
|
+
- `on_start(host_time)` on MIDI Start; the next clock is tick 0
|
|
51
|
+
- `on_tick(tick, host_time)` on every MIDI Clock, 24 per quarter note (`Client::TICKS_PER_QUARTER`)
|
|
52
|
+
- `on_stop` and `on_continue`
|
|
53
|
+
|
|
54
|
+
All four are no-ops by default.
|
|
55
|
+
|
|
56
|
+
`send_packets(destination, notes, base_host_time = now)` schedules notes. Each note responds to `on`, `on_timestamp`, `off` and `off_timestamp`; `RCoreMidi::Client::TimedNote` is a Struct with exactly those members. `on` and `off` are MIDI 1.0 bytes, and the timestamps are nanoseconds after `base_host_time`.
|
|
57
|
+
|
|
58
|
+
```ruby
|
|
59
|
+
require 'rcoremidi'
|
|
60
|
+
|
|
61
|
+
class Metronome < RCoreMidi::Client
|
|
62
|
+
CLICK = 37
|
|
63
|
+
CLICK_LENGTH = 50_000_000 # nanoseconds
|
|
64
|
+
|
|
65
|
+
def on_tick(tick, host_time)
|
|
66
|
+
return unless (tick % TICKS_PER_QUARTER).zero?
|
|
67
|
+
|
|
68
|
+
note = TimedNote.new([0x99, CLICK, 100], 0, [0x89, CLICK, 0], CLICK_LENGTH)
|
|
69
|
+
send_packets(midi_out, [note], host_time)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def on_stop
|
|
73
|
+
silence
|
|
74
|
+
end
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
iac = RCoreMidi::Device.all.detect { |device| device.name == 'IAC Driver' }
|
|
78
|
+
bus = iac.entities.first
|
|
79
|
+
|
|
80
|
+
metronome = Metronome.new('metronome')
|
|
81
|
+
metronome.midi_in = bus.sources.first
|
|
82
|
+
metronome.midi_out = bus.destinations.first
|
|
83
|
+
metronome.connect!
|
|
84
|
+
|
|
85
|
+
begin
|
|
86
|
+
metronome.start # blocks until stop or Ctrl-C; other Ruby threads keep running
|
|
87
|
+
ensure
|
|
88
|
+
metronome.dispose
|
|
89
|
+
end
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Other driver methods: `stop`, `running?`, `silence` (unschedule pending packets and send All Notes Off on all channels of every destination it has sent to), `dropped_clock_events` and `dispose`. `RCoreMidi::HostTime.now`, `.to_nanoseconds` and `.from_nanoseconds` convert CoreMIDI host times.
|
|
93
|
+
|
|
94
|
+
See [MIDI_FLOW_DIAGRAM.md](MIDI_FLOW_DIAGRAM.md) for how clock events reach Ruby and [C_EXTENSION_CODE_REVIEW.md](C_EXTENSION_CODE_REVIEW.md) for notes on the extension's design.
|
|
95
|
+
|
|
96
|
+
## Development
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
bundle install
|
|
100
|
+
bundle exec rake compile
|
|
101
|
+
bundle exec rspec
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The extension specs expect the IAC Driver to be enabled in Audio MIDI Setup. `spec/rcoremidi/client_spec.rb` runs without the compiled extension.
|
|
105
|
+
|
|
106
|
+
## License
|
|
107
|
+
|
|
108
|
+
The MIT License
|
|
109
|
+
|
|
110
|
+
Copyright (c) 2010 Yann Marquet
|
|
111
|
+
|
|
112
|
+
Permission is hereby granted, free of charge, to any person obtaining
|
|
113
|
+
a copy of this software and associated documentation files (the
|
|
114
|
+
'Software'), to deal in the Software without restriction, including
|
|
115
|
+
without limitation the rights to use, copy, modify, merge, publish,
|
|
116
|
+
distribute, sublicense, and/or sell copies of the Software, and to
|
|
117
|
+
permit persons to whom the Software is furnished to do so, subject to
|
|
118
|
+
the following conditions:
|
|
119
|
+
|
|
120
|
+
The above copyright notice and this permission notice shall be
|
|
121
|
+
included in all copies or substantial portions of the Software.
|
|
122
|
+
|
|
123
|
+
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
|
|
124
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
|
125
|
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
|
126
|
+
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
|
127
|
+
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
|
|
128
|
+
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
|
129
|
+
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
#include "rcoremidi.h"
|
|
2
|
+
#include <dispatch/dispatch.h>
|
|
3
|
+
#include <mach/mach_time.h>
|
|
4
|
+
#include <stdatomic.h>
|
|
5
|
+
#include <stdlib.h>
|
|
6
|
+
|
|
7
|
+
enum ClockEventKind {
|
|
8
|
+
kClockStart = 1,
|
|
9
|
+
kClockTick,
|
|
10
|
+
kClockStop,
|
|
11
|
+
kClockContinue
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
enum MidiStatus {
|
|
15
|
+
kMIDISongPositionPointer = 0xF2,
|
|
16
|
+
kMIDITimingClock = 0xF8,
|
|
17
|
+
kMIDIStart = 0xFA,
|
|
18
|
+
kMIDIContinue = 0xFB,
|
|
19
|
+
kMIDIStop = 0xFC,
|
|
20
|
+
kMIDIControlChange = 0xB0,
|
|
21
|
+
kMIDIAllSoundOff = 120,
|
|
22
|
+
kMIDIAllNotesOff = 123
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
enum {
|
|
26
|
+
kClockQueueCapacity = 1024,
|
|
27
|
+
kMaxMIDIMessageLength = 256,
|
|
28
|
+
kMIDIChannels = 16,
|
|
29
|
+
kMaxRememberedDestinations = 16,
|
|
30
|
+
kUniversalSystemMessage = 0x1,
|
|
31
|
+
kUniversalMIDI1ChannelVoice = 0x2
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
static const ByteCount kEventListCapacity = 65536;
|
|
35
|
+
static const int64_t kTicksPerSixteenth = 6;
|
|
36
|
+
static const int64_t kClockWaitNanoseconds = 100 * NSEC_PER_MSEC;
|
|
37
|
+
static const int64_t kClockInputReleaseDelay = NSEC_PER_SEC;
|
|
38
|
+
static const long long kMaxScheduleAheadNanoseconds = 3600LL * NSEC_PER_SEC;
|
|
39
|
+
|
|
40
|
+
typedef struct ClockEvent {
|
|
41
|
+
int kind;
|
|
42
|
+
int64_t tick;
|
|
43
|
+
MIDITimeStamp host_time;
|
|
44
|
+
} ClockEvent;
|
|
45
|
+
|
|
46
|
+
typedef struct ClockInput {
|
|
47
|
+
ClockEvent events[kClockQueueCapacity];
|
|
48
|
+
_Atomic uint64_t head;
|
|
49
|
+
_Atomic uint64_t tail;
|
|
50
|
+
_Atomic uint64_t dropped;
|
|
51
|
+
atomic_bool listening;
|
|
52
|
+
atomic_int receiving;
|
|
53
|
+
int64_t tick;
|
|
54
|
+
dispatch_semaphore_t signal;
|
|
55
|
+
} ClockInput;
|
|
56
|
+
|
|
57
|
+
typedef struct RCoremidiNode {
|
|
58
|
+
MIDIPortRef in;
|
|
59
|
+
MIDIPortRef out;
|
|
60
|
+
bool ports_created;
|
|
61
|
+
bool disposed;
|
|
62
|
+
bool running;
|
|
63
|
+
atomic_bool stop_requested;
|
|
64
|
+
MIDIEndpointRef destinations[kMaxRememberedDestinations];
|
|
65
|
+
int destination_count;
|
|
66
|
+
ClockInput *clock;
|
|
67
|
+
} RCoremidiNode;
|
|
68
|
+
|
|
69
|
+
enum ReleaseOrder { kReleaseFirst = 0, kAttackAfterRelease = 1 };
|
|
70
|
+
|
|
71
|
+
typedef struct ScheduledMessage {
|
|
72
|
+
MIDITimeStamp timestamp;
|
|
73
|
+
enum ReleaseOrder release_order;
|
|
74
|
+
long position;
|
|
75
|
+
ByteCount word_count;
|
|
76
|
+
UInt32 words[kMaxUniversalWordsPerMessage];
|
|
77
|
+
} ScheduledMessage;
|
|
78
|
+
|
|
79
|
+
static ClockInput *create_clock_input(void) {
|
|
80
|
+
ClockInput *input = calloc(1, sizeof *input);
|
|
81
|
+
if (!input) {
|
|
82
|
+
return NULL;
|
|
83
|
+
}
|
|
84
|
+
input->signal = dispatch_semaphore_create(0);
|
|
85
|
+
if (!input->signal) {
|
|
86
|
+
free(input);
|
|
87
|
+
return NULL;
|
|
88
|
+
}
|
|
89
|
+
return input;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
static void schedule_clock_input_release(ClockInput *input);
|
|
93
|
+
|
|
94
|
+
static void free_clock_input_when_idle(void *ptr) {
|
|
95
|
+
ClockInput *input = ptr;
|
|
96
|
+
if (atomic_load(&input->receiving) > 0) {
|
|
97
|
+
schedule_clock_input_release(input);
|
|
98
|
+
return;
|
|
99
|
+
}
|
|
100
|
+
dispatch_release(input->signal);
|
|
101
|
+
free(input);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
static void schedule_clock_input_release(ClockInput *input) {
|
|
105
|
+
dispatch_after_f(dispatch_time(DISPATCH_TIME_NOW, kClockInputReleaseDelay),
|
|
106
|
+
dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), input,
|
|
107
|
+
free_clock_input_when_idle);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
static bool push_clock_event(ClockInput *input, ClockEvent event) {
|
|
111
|
+
uint64_t tail = atomic_load_explicit(&input->tail, memory_order_relaxed);
|
|
112
|
+
uint64_t head = atomic_load_explicit(&input->head, memory_order_acquire);
|
|
113
|
+
if (tail - head == kClockQueueCapacity) {
|
|
114
|
+
atomic_fetch_add_explicit(&input->dropped, 1, memory_order_relaxed);
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
input->events[tail % kClockQueueCapacity] = event;
|
|
118
|
+
atomic_store_explicit(&input->tail, tail + 1, memory_order_release);
|
|
119
|
+
return true;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
static bool pop_clock_event(ClockInput *input, ClockEvent *event) {
|
|
123
|
+
uint64_t head = atomic_load_explicit(&input->head, memory_order_relaxed);
|
|
124
|
+
uint64_t tail = atomic_load_explicit(&input->tail, memory_order_acquire);
|
|
125
|
+
if (head == tail) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
*event = input->events[head % kClockQueueCapacity];
|
|
129
|
+
atomic_store_explicit(&input->head, head + 1, memory_order_release);
|
|
130
|
+
return true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
static bool clock_queue_empty(ClockInput *input) {
|
|
134
|
+
return atomic_load_explicit(&input->head, memory_order_relaxed) ==
|
|
135
|
+
atomic_load_explicit(&input->tail, memory_order_acquire);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
static void discard_clock_events(ClockInput *input) {
|
|
139
|
+
ClockEvent ignored;
|
|
140
|
+
while (pop_clock_event(input, &ignored)) {
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
static void enqueue_clock_event(ClockInput *input, int kind,
|
|
145
|
+
MIDITimeStamp host_time) {
|
|
146
|
+
if (!atomic_load_explicit(&input->listening, memory_order_acquire)) {
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
ClockEvent event = {.kind = kind, .tick = input->tick, .host_time = host_time};
|
|
150
|
+
if (push_clock_event(input, event)) {
|
|
151
|
+
dispatch_semaphore_signal(input->signal);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
static void handle_system_message(ClockInput *input, UInt32 word,
|
|
156
|
+
MIDITimeStamp host_time) {
|
|
157
|
+
switch ((word >> 16) & 0xFF) {
|
|
158
|
+
case kMIDIStart:
|
|
159
|
+
input->tick = -1;
|
|
160
|
+
enqueue_clock_event(input, kClockStart, host_time);
|
|
161
|
+
break;
|
|
162
|
+
case kMIDITimingClock:
|
|
163
|
+
input->tick++;
|
|
164
|
+
enqueue_clock_event(input, kClockTick, host_time);
|
|
165
|
+
break;
|
|
166
|
+
case kMIDIContinue:
|
|
167
|
+
enqueue_clock_event(input, kClockContinue, host_time);
|
|
168
|
+
break;
|
|
169
|
+
case kMIDIStop:
|
|
170
|
+
enqueue_clock_event(input, kClockStop, host_time);
|
|
171
|
+
break;
|
|
172
|
+
case kMIDISongPositionPointer: {
|
|
173
|
+
int64_t sixteenths = ((word >> 8) & 0x7F) | ((word & 0x7F) << 7);
|
|
174
|
+
input->tick = sixteenths * kTicksPerSixteenth - 1;
|
|
175
|
+
break;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
static void receive_clock(ClockInput *input, const MIDIEventList *event_list) {
|
|
181
|
+
const MIDIEventPacket *packet = &event_list->packet[0];
|
|
182
|
+
for (UInt32 p = 0; p < event_list->numPackets; ++p) {
|
|
183
|
+
MIDITimeStamp host_time =
|
|
184
|
+
packet->timeStamp ? packet->timeStamp : mach_absolute_time();
|
|
185
|
+
UInt32 w = 0;
|
|
186
|
+
while (w < packet->wordCount) {
|
|
187
|
+
UInt32 word = packet->words[w];
|
|
188
|
+
if ((word >> 28) == kUniversalSystemMessage) {
|
|
189
|
+
handle_system_message(input, word, host_time);
|
|
190
|
+
}
|
|
191
|
+
w += universal_message_word_count(word);
|
|
192
|
+
}
|
|
193
|
+
packet = MIDIEventPacketNext(packet);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
static UInt32 control_change_word(int channel, Byte controller) {
|
|
198
|
+
return ((UInt32)kUniversalMIDI1ChannelVoice << 28) |
|
|
199
|
+
((UInt32)(kMIDIControlChange | channel) << 16) |
|
|
200
|
+
((UInt32)controller << 8);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
static void send_words_now(MIDIPortRef port, MIDIEndpointRef destination,
|
|
204
|
+
const UInt32 *words, ByteCount word_count) {
|
|
205
|
+
Byte buffer[sizeof(MIDIEventList) + 64 * sizeof(UInt32)];
|
|
206
|
+
MIDIEventList *event_list = (MIDIEventList *)buffer;
|
|
207
|
+
MIDIEventPacket *packet = MIDIEventListInit(event_list, kMIDIProtocol_1_0);
|
|
208
|
+
for (ByteCount i = 0; i < word_count && packet; ++i) {
|
|
209
|
+
packet =
|
|
210
|
+
MIDIEventListAdd(event_list, sizeof buffer, packet, 0, 1, &words[i]);
|
|
211
|
+
}
|
|
212
|
+
MIDISendEventList(port, destination, event_list);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
static void silence_destination(MIDIPortRef port, MIDIEndpointRef destination) {
|
|
216
|
+
MIDIFlushOutput(destination);
|
|
217
|
+
UInt32 words[kMIDIChannels * 2];
|
|
218
|
+
for (int channel = 0; channel < kMIDIChannels; ++channel) {
|
|
219
|
+
words[channel * 2] = control_change_word(channel, kMIDIAllSoundOff);
|
|
220
|
+
words[channel * 2 + 1] = control_change_word(channel, kMIDIAllNotesOff);
|
|
221
|
+
}
|
|
222
|
+
send_words_now(port, destination, words, kMIDIChannels * 2);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
static void silence_destinations(RCoremidiNode *node) {
|
|
226
|
+
if (!node->ports_created || node->disposed) {
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
for (int i = 0; i < node->destination_count; ++i) {
|
|
230
|
+
silence_destination(node->out, node->destinations[i]);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
static void remember_destination(RCoremidiNode *node,
|
|
235
|
+
MIDIEndpointRef destination) {
|
|
236
|
+
for (int i = 0; i < node->destination_count; ++i) {
|
|
237
|
+
if (node->destinations[i] == destination) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (node->destination_count < kMaxRememberedDestinations) {
|
|
242
|
+
node->destinations[node->destination_count++] = destination;
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
static void dispose_ports(RCoremidiNode *node) {
|
|
247
|
+
if (!node->ports_created || node->disposed) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
atomic_store_explicit(&node->clock->listening, false, memory_order_release);
|
|
251
|
+
silence_destinations(node);
|
|
252
|
+
MIDIPortDispose(node->in);
|
|
253
|
+
MIDIPortDispose(node->out);
|
|
254
|
+
node->disposed = true;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
static void midi_node_free(void *ptr) {
|
|
258
|
+
RCoremidiNode *node = ptr;
|
|
259
|
+
dispose_ports(node);
|
|
260
|
+
if (node->clock) {
|
|
261
|
+
schedule_clock_input_release(node->clock);
|
|
262
|
+
}
|
|
263
|
+
ruby_xfree(node);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
static size_t midi_node_memsize(const void *ptr) {
|
|
267
|
+
return sizeof(RCoremidiNode) + sizeof(ClockInput);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
static const rb_data_type_t midi_node_data_t = {
|
|
271
|
+
"rcoremidi_client",
|
|
272
|
+
{NULL, midi_node_free, midi_node_memsize},
|
|
273
|
+
NULL,
|
|
274
|
+
NULL,
|
|
275
|
+
RUBY_TYPED_FREE_IMMEDIATELY};
|
|
276
|
+
|
|
277
|
+
static RCoremidiNode *client_node(VALUE self) {
|
|
278
|
+
RCoremidiNode *node;
|
|
279
|
+
TypedData_Get_Struct(self, RCoremidiNode, &midi_node_data_t, node);
|
|
280
|
+
return node;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
static RCoremidiNode *usable_client_node(VALUE self) {
|
|
284
|
+
RCoremidiNode *node = client_node(self);
|
|
285
|
+
if (!node->ports_created || node->disposed) {
|
|
286
|
+
rb_raise(rb_eRuntimeError, "MIDI client is not available (disposed?)");
|
|
287
|
+
}
|
|
288
|
+
return node;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
VALUE client_alloc(VALUE klass) {
|
|
292
|
+
RCoremidiNode *node;
|
|
293
|
+
VALUE self =
|
|
294
|
+
TypedData_Make_Struct(klass, RCoremidiNode, &midi_node_data_t, node);
|
|
295
|
+
node->clock = create_clock_input();
|
|
296
|
+
return self;
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
static void wake_clock_waiter(void *ptr) {
|
|
300
|
+
RCoremidiNode *node = ptr;
|
|
301
|
+
dispatch_semaphore_signal(node->clock->signal);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
static void *wait_for_clock_events(void *ptr) {
|
|
305
|
+
RCoremidiNode *node = ptr;
|
|
306
|
+
if (clock_queue_empty(node->clock) && !atomic_load(&node->stop_requested)) {
|
|
307
|
+
dispatch_semaphore_wait(
|
|
308
|
+
node->clock->signal,
|
|
309
|
+
dispatch_time(DISPATCH_TIME_NOW, kClockWaitNanoseconds));
|
|
310
|
+
}
|
|
311
|
+
return NULL;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
static void call_optional_handler(VALUE self, ID handler) {
|
|
315
|
+
if (rb_respond_to(self, handler)) {
|
|
316
|
+
rb_funcall(self, handler, 0);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
static void deliver_clock_event(VALUE self, const ClockEvent *event) {
|
|
321
|
+
VALUE host_time = ULL2NUM(event->host_time);
|
|
322
|
+
switch (event->kind) {
|
|
323
|
+
case kClockStart:
|
|
324
|
+
rb_funcall(self, on_start_intern, 1, host_time);
|
|
325
|
+
break;
|
|
326
|
+
case kClockTick:
|
|
327
|
+
rb_funcall(self, on_tick_intern, 2, LL2NUM(event->tick), host_time);
|
|
328
|
+
break;
|
|
329
|
+
case kClockStop:
|
|
330
|
+
call_optional_handler(self, on_stop_intern);
|
|
331
|
+
break;
|
|
332
|
+
case kClockContinue:
|
|
333
|
+
call_optional_handler(self, on_continue_intern);
|
|
334
|
+
break;
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
static void deliver_clock_events(VALUE self, RCoremidiNode *node) {
|
|
339
|
+
ClockEvent event;
|
|
340
|
+
while (!atomic_load(&node->stop_requested) &&
|
|
341
|
+
pop_clock_event(node->clock, &event)) {
|
|
342
|
+
deliver_clock_event(self, &event);
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
static VALUE run_clock(VALUE self) {
|
|
347
|
+
RCoremidiNode *node = client_node(self);
|
|
348
|
+
while (!atomic_load(&node->stop_requested)) {
|
|
349
|
+
rb_thread_call_without_gvl2(wait_for_clock_events, node, wake_clock_waiter,
|
|
350
|
+
node);
|
|
351
|
+
deliver_clock_events(self, node);
|
|
352
|
+
rb_thread_check_ints();
|
|
353
|
+
}
|
|
354
|
+
return Qnil;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
static VALUE finish_clock(VALUE self) {
|
|
358
|
+
RCoremidiNode *node = client_node(self);
|
|
359
|
+
atomic_store_explicit(&node->clock->listening, false, memory_order_release);
|
|
360
|
+
node->running = false;
|
|
361
|
+
return Qnil;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
VALUE start_client(VALUE self) {
|
|
365
|
+
RCoremidiNode *node = usable_client_node(self);
|
|
366
|
+
if (node->running) {
|
|
367
|
+
rb_raise(rb_eRuntimeError, "MIDI clock already started");
|
|
368
|
+
}
|
|
369
|
+
node->running = true;
|
|
370
|
+
atomic_store(&node->stop_requested, false);
|
|
371
|
+
discard_clock_events(node->clock);
|
|
372
|
+
atomic_store_explicit(&node->clock->listening, true, memory_order_release);
|
|
373
|
+
return rb_ensure(run_clock, self, finish_clock, self);
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
VALUE stop_client(VALUE self) {
|
|
377
|
+
RCoremidiNode *node = client_node(self);
|
|
378
|
+
atomic_store(&node->stop_requested, true);
|
|
379
|
+
if (node->clock) {
|
|
380
|
+
dispatch_semaphore_signal(node->clock->signal);
|
|
381
|
+
}
|
|
382
|
+
return Qnil;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
VALUE client_running(VALUE self) {
|
|
386
|
+
RCoremidiNode *node = client_node(self);
|
|
387
|
+
return node->clock && atomic_load_explicit(&node->clock->listening,
|
|
388
|
+
memory_order_acquire)
|
|
389
|
+
? Qtrue
|
|
390
|
+
: Qfalse;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
VALUE silence_client(VALUE self) {
|
|
394
|
+
silence_destinations(usable_client_node(self));
|
|
395
|
+
return Qnil;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
VALUE dropped_clock_events(VALUE self) {
|
|
399
|
+
RCoremidiNode *node = client_node(self);
|
|
400
|
+
return ULL2NUM(node->clock ? atomic_load(&node->clock->dropped) : 0);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
VALUE connect_to(VALUE self, VALUE source) {
|
|
404
|
+
RCoremidiNode *node = usable_client_node(self);
|
|
405
|
+
raise_on_midi_error(
|
|
406
|
+
MIDIPortConnectSource(node->in, *get_midi_data(source), NULL),
|
|
407
|
+
"Could not connect the input port to the MIDI source");
|
|
408
|
+
rb_iv_set(self, "@source", source);
|
|
409
|
+
return Qtrue;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
static Byte midi_byte(VALUE value) {
|
|
413
|
+
int byte = NUM2INT(value);
|
|
414
|
+
if (byte < 0 || byte > 0xFF) {
|
|
415
|
+
rb_raise(rb_eArgError, "MIDI byte out of range: %d", byte);
|
|
416
|
+
}
|
|
417
|
+
return (Byte)byte;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
static ByteCount universal_words_for(VALUE message, UInt32 *words) {
|
|
421
|
+
Check_Type(message, T_ARRAY);
|
|
422
|
+
long length = RARRAY_LEN(message);
|
|
423
|
+
if (length == 0 || length > kMaxMIDIMessageLength) {
|
|
424
|
+
rb_raise(rb_eArgError, "MIDI message too long or empty: %ld bytes (max %d)",
|
|
425
|
+
length, kMaxMIDIMessageLength);
|
|
426
|
+
}
|
|
427
|
+
Byte bytes[kMaxMIDIMessageLength];
|
|
428
|
+
for (long i = 0; i < length; ++i) {
|
|
429
|
+
bytes[i] = midi_byte(rb_ary_entry(message, i));
|
|
430
|
+
}
|
|
431
|
+
return universal_words_from_bytes(bytes, (ByteCount)length, words);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
static UInt64 schedule_offset_in_nanoseconds(VALUE nanoseconds) {
|
|
435
|
+
long long offset = NUM2LL(nanoseconds);
|
|
436
|
+
if (offset < 0 || offset > kMaxScheduleAheadNanoseconds) {
|
|
437
|
+
rb_raise(rb_eArgError, "MIDI timestamp out of range: %lld ns", offset);
|
|
438
|
+
}
|
|
439
|
+
return (UInt64)offset;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
static void schedule_message(ScheduledMessage *scheduled, long position,
|
|
443
|
+
enum ReleaseOrder release_order, VALUE message,
|
|
444
|
+
VALUE nanoseconds, UInt64 base_host_time) {
|
|
445
|
+
scheduled->position = position;
|
|
446
|
+
scheduled->release_order = release_order;
|
|
447
|
+
scheduled->word_count = universal_words_for(message, scheduled->words);
|
|
448
|
+
scheduled->timestamp =
|
|
449
|
+
base_host_time +
|
|
450
|
+
AudioConvertNanosToHostTime(schedule_offset_in_nanoseconds(nanoseconds));
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
static int compare_schedule(const void *a, const void *b) {
|
|
454
|
+
const ScheduledMessage *left = a;
|
|
455
|
+
const ScheduledMessage *right = b;
|
|
456
|
+
if (left->timestamp != right->timestamp) {
|
|
457
|
+
return left->timestamp < right->timestamp ? -1 : 1;
|
|
458
|
+
}
|
|
459
|
+
if (left->release_order != right->release_order) {
|
|
460
|
+
return left->release_order < right->release_order ? -1 : 1;
|
|
461
|
+
}
|
|
462
|
+
return (left->position > right->position) -
|
|
463
|
+
(left->position < right->position);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
static MIDIEventPacket *add_scheduled_message(MIDIEventList *event_list,
|
|
467
|
+
MIDIEventPacket *packet,
|
|
468
|
+
const ScheduledMessage *message) {
|
|
469
|
+
ByteCount w = 0;
|
|
470
|
+
while (w < message->word_count) {
|
|
471
|
+
ByteCount size = universal_message_word_count(message->words[w]);
|
|
472
|
+
packet = MIDIEventListAdd(event_list, kEventListCapacity, packet,
|
|
473
|
+
message->timestamp, size, &message->words[w]);
|
|
474
|
+
if (!packet) {
|
|
475
|
+
rb_raise(rb_eArgError, "Too many MIDI events for one event list");
|
|
476
|
+
}
|
|
477
|
+
w += size;
|
|
478
|
+
}
|
|
479
|
+
return packet;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
static void fill_event_list(MIDIEventList *event_list,
|
|
483
|
+
const ScheduledMessage *messages, long count) {
|
|
484
|
+
MIDIEventPacket *packet = MIDIEventListInit(event_list, kMIDIProtocol_1_0);
|
|
485
|
+
for (long i = 0; i < count; ++i) {
|
|
486
|
+
packet = add_scheduled_message(event_list, packet, &messages[i]);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
VALUE send_packets(int argc, VALUE *argv, VALUE self) {
|
|
491
|
+
VALUE destination, events, base_host_time;
|
|
492
|
+
rb_scan_args(argc, argv, "21", &destination, &events, &base_host_time);
|
|
493
|
+
RCoremidiNode *node = usable_client_node(self);
|
|
494
|
+
MIDIEndpointRef endpoint = *get_midi_data(destination);
|
|
495
|
+
Check_Type(events, T_ARRAY);
|
|
496
|
+
UInt64 base = NIL_P(base_host_time) ? AudioGetCurrentHostTime()
|
|
497
|
+
: NUM2ULL(base_host_time);
|
|
498
|
+
|
|
499
|
+
long event_count = RARRAY_LEN(events);
|
|
500
|
+
long message_count = event_count * 2;
|
|
501
|
+
VALUE messages_owner, event_list_owner;
|
|
502
|
+
ScheduledMessage *messages = ALLOCV_N(ScheduledMessage, messages_owner,
|
|
503
|
+
message_count ? message_count : 1);
|
|
504
|
+
for (long i = 0; i < event_count; ++i) {
|
|
505
|
+
VALUE event = rb_ary_entry(events, i);
|
|
506
|
+
schedule_message(&messages[2 * i], 2 * i, kAttackAfterRelease,
|
|
507
|
+
rb_funcall(event, on_intern, 0),
|
|
508
|
+
rb_funcall(event, on_timestamp_intern, 0), base);
|
|
509
|
+
schedule_message(&messages[2 * i + 1], 2 * i + 1, kReleaseFirst,
|
|
510
|
+
rb_funcall(event, off_intern, 0),
|
|
511
|
+
rb_funcall(event, off_timestamp_intern, 0), base);
|
|
512
|
+
}
|
|
513
|
+
mergesort(messages, message_count, sizeof *messages, compare_schedule);
|
|
514
|
+
|
|
515
|
+
MIDIEventList *event_list = ALLOCV(event_list_owner, kEventListCapacity);
|
|
516
|
+
fill_event_list(event_list, messages, message_count);
|
|
517
|
+
OSStatus status = MIDISendEventList(node->out, endpoint, event_list);
|
|
518
|
+
remember_destination(node, endpoint);
|
|
519
|
+
|
|
520
|
+
ALLOCV_END(event_list_owner);
|
|
521
|
+
ALLOCV_END(messages_owner);
|
|
522
|
+
raise_on_midi_error(status, "Could not send MIDI events");
|
|
523
|
+
return Qnil;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
static CFStringRef cf_string_from_ruby(VALUE string) {
|
|
527
|
+
CFStringRef cf_string = CFStringCreateWithCString(
|
|
528
|
+
NULL, StringValueCStr(string), kCFStringEncodingUTF8);
|
|
529
|
+
if (!cf_string) {
|
|
530
|
+
rb_raise(rb_eArgError, "MIDI client name must be valid UTF-8");
|
|
531
|
+
}
|
|
532
|
+
return cf_string;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
static OSStatus create_input_port(MIDIClientRef client, CFStringRef name,
|
|
536
|
+
ClockInput *input, MIDIPortRef *port) {
|
|
537
|
+
return MIDIInputPortCreateWithProtocol(
|
|
538
|
+
client, name, kMIDIProtocol_1_0, port,
|
|
539
|
+
^(const MIDIEventList *event_list, void *source_ref) {
|
|
540
|
+
atomic_fetch_add(&input->receiving, 1);
|
|
541
|
+
receive_clock(input, event_list);
|
|
542
|
+
atomic_fetch_sub(&input->receiving, 1);
|
|
543
|
+
});
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
static void create_ports(RCoremidiNode *node, MIDIClientRef client,
|
|
547
|
+
CFStringRef name) {
|
|
548
|
+
OSStatus status = create_input_port(client, name, node->clock, &node->in);
|
|
549
|
+
if (status == noErr) {
|
|
550
|
+
status = MIDIOutputPortCreate(client, name, &node->out);
|
|
551
|
+
if (status != noErr) {
|
|
552
|
+
MIDIPortDispose(node->in);
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
CFRelease(name);
|
|
556
|
+
raise_on_midi_error(status, "Could not create the MIDI ports");
|
|
557
|
+
node->ports_created = true;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
VALUE client_init(VALUE self, VALUE name) {
|
|
561
|
+
RCoremidiNode *node = client_node(self);
|
|
562
|
+
if (node->ports_created) {
|
|
563
|
+
rb_raise(rb_eRuntimeError, "MIDI client already initialized");
|
|
564
|
+
}
|
|
565
|
+
if (!node->clock) {
|
|
566
|
+
rb_raise(rb_eNoMemError, "Could not allocate the MIDI clock input");
|
|
567
|
+
}
|
|
568
|
+
MIDIClientRef client = shared_midi_client();
|
|
569
|
+
create_ports(node, client, cf_string_from_ruby(name));
|
|
570
|
+
rb_iv_set(self, "@name", name);
|
|
571
|
+
return self;
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
VALUE dispose_client(VALUE self) {
|
|
575
|
+
RCoremidiNode *node = client_node(self);
|
|
576
|
+
stop_client(self);
|
|
577
|
+
dispose_ports(node);
|
|
578
|
+
return self;
|
|
579
|
+
}
|