3 * Copyright © 2020 František Kučera (Frantovo.cz, GlobalCode.info)
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, version 3 of the License.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <alsa/asoundlib.h>
25 #include "AlsaBridge.h"
30 class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
32 djmfix::DJMFix* djmFix;
34 snd_rawmidi_t* output;
35 std::thread receivingThread;
36 std::recursive_mutex midiMutex;
37 std::atomic<bool> stopped{false};
42 std::lock_guard<std::recursive_mutex> lock(midiMutex);
45 ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
46 if (length > 0 && length <= sizeof (buffer)) {
47 // TODO: multiple messages combined together?
48 djmFix->receive(MidiMessage(buffer, buffer + length));
51 std::this_thread::sleep_for(std::chrono::milliseconds(100));
56 AlsaBridgeImpl(djmfix::DJMFix* djmFix, const std::string& deviceName) : djmFix(djmFix) {
57 if (djmFix == nullptr) throw std::invalid_argument("need a djmFix for AlsaBridge");
59 int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), SND_RAWMIDI_NONBLOCK);
60 if (error) throw std::invalid_argument("unable to open ALSA device");
63 djmFix->setMidiSender(this);
66 virtual ~AlsaBridgeImpl() {
67 // TODO: do not use raw/exclusive access to the device
68 snd_rawmidi_close(input);
69 snd_rawmidi_close(output);
70 std::cerr << "~AlsaBridgeImpl()" << std::endl; // TODO: do not mess STDIO
73 virtual void start() override {
75 receivingThread = std::thread(&AlsaBridgeImpl::run, this);
78 virtual void stop() override {
80 receivingThread.join();
84 virtual void send(MidiMessage midiMessage) override {
85 std::lock_guard<std::recursive_mutex> lock(midiMutex);
86 ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
87 std::cerr << "AlsaBridgeImpl::send(): length = " << length << std::endl; // TODO: do not mess STDIO
92 AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName) {
93 return new AlsaBridgeImpl(djmFix, deviceName);