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/>.
22 #include <alsa/asoundlib.h>
24 #include "AlsaBridge.h"
29 class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
31 djmfix::DJMFix* djmFix;
33 snd_rawmidi_t* output;
34 std::thread receivingThread;
35 std::atomic<bool> stopped{false};
41 ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
42 if (length > 0 && length <= sizeof (buffer)) {
43 // TODO: multiple messages combined together?
44 djmFix->receive(MidiMessage(buffer, buffer + length));
47 std::this_thread::sleep_for(std::chrono::milliseconds(100));
52 AlsaBridgeImpl(djmfix::DJMFix* djmFix, const std::string& deviceName) : djmFix(djmFix) {
53 if (djmFix == nullptr) throw std::invalid_argument("need a djmFix for AlsaBridge");
55 int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), SND_RAWMIDI_NONBLOCK);
56 if (error) throw std::invalid_argument("unable to open ALSA device");
59 djmFix->setMidiSender(this);
62 virtual ~AlsaBridgeImpl() {
63 // TODO: do not use raw/exclusive access to the device
64 snd_rawmidi_close(input);
65 snd_rawmidi_close(output);
66 std::cerr << "~AlsaBridgeImpl()" << std::endl; // TODO: do not mess STDIO
69 virtual void start() override {
71 receivingThread = std::thread(&AlsaBridgeImpl::run, this);
74 virtual void stop() override {
76 receivingThread.join();
80 virtual void send(MidiMessage midiMessage) override {
81 ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
82 std::cerr << "AlsaBridgeImpl::send(): length = " << length << std::endl; // TODO: do not mess STDIO
87 AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName) {
88 return new AlsaBridgeImpl(djmFix, deviceName);