-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmidiprocess.cpp
92 lines (71 loc) · 2.16 KB
/
midiprocess.cpp
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
#include "midiprocess.hpp"
#include <stdexcept>
#include <cassert>
#include <jack/midiport.h>
midi_packet::midi_packet(bool on, char n, char v)
: type(on?0x90:0x80), note(n), velocity(v)
{}
const size_t MidiProcess::RINGBUF_SIZE = 1024;
MidiProcess::MidiProcess()
: _ringbuf(nullptr), _jclient(nullptr), _port(nullptr)
{}
MidiProcess::MidiProcess(const std::string& name)
: MidiProcess()
{
if(name == "")
throw std::invalid_argument("jack client name cannot be the empty string \"\"");
_jclient = jack_client_open(name.c_str(), JackNullOption, nullptr);
if(!_jclient)
throw std::invalid_argument("Could not connect to jack server.");
_port = jack_port_register(_jclient, "out", JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0);
if(!_port)
throw std::runtime_error("Could not create jack midi output port.");
jack_set_process_callback(_jclient, MidiProcess::jack_process_wrap, this);
_ringbuf = jack_ringbuffer_create(RINGBUF_SIZE);
if(!_ringbuf)
throw std::runtime_error("Unable to create ringbuffer.");
}
bool MidiProcess::activate()
{
int res = -1;
if(_jclient)
res = jack_activate(_jclient);
return (res==0);
}
MidiProcess::~MidiProcess()
{
if(_ringbuf) {
jack_ringbuffer_free(_ringbuf);
_ringbuf=nullptr;
}
_port = nullptr;
if(_jclient) {
jack_deactivate(_jclient);
jack_client_close(_jclient);
_jclient=nullptr;
}
}
bool MidiProcess::enqueue_packet(const midi_packet& packet)
{
size_t wrote = jack_ringbuffer_write(_ringbuf, packet.v, sizeof(packet.v));
return (wrote==sizeof(packet.v));
}
int MidiProcess::jack_process_wrap(jack_nframes_t nframes, void* arg)
{
MidiProcess* mp = static_cast<MidiProcess*>(arg);
assert(mp!=nullptr);
return mp->process(nframes);
}
int MidiProcess::process(jack_nframes_t nframes)
{
void* outBuf = jack_port_get_buffer(_port, nframes);
jack_midi_clear_buffer(outBuf);
size_t numRead = jack_ringbuffer_read_space(_ringbuf)/sizeof(midi_packet);
numRead *= sizeof(midi_packet);
if(numRead > 0) {
jack_midi_data_t* writeBuf = jack_midi_event_reserve(outBuf, 0, numRead);
size_t actRead = jack_ringbuffer_read(_ringbuf, reinterpret_cast<char*>(writeBuf), numRead);
assert(actRead == numRead);
}
return 0;
}