3 * Copyright © 2025 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/>.
26 #include <alsa/asoundlib.h>
28 #include "AlsaBridge.h"
34 using L = djmfix::logging::Level;
36 class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
38 djmfix::DJMFix* djmFix;
39 djmfix::logging::Logger* logger;
41 snd_rawmidi_t* output;
42 std::thread receivingThread;
43 std::recursive_mutex midiMutex;
44 std::atomic<bool> stopped{false};
46 std::string findDeviceName(std::regex cardNamePattern) {
48 std::vector<int> cardNumbers;
50 logger->log(L::INFO, "Looking for available cards:");
52 for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
53 char* longName = nullptr;
54 snd_card_get_longname(card, &longName);
56 std::stringstream logMessage;
57 logMessage << " - card: #" << card << ": '" << longName << "'";
59 if (std::regex_match(longName, cardNamePattern)) {
60 cardNumbers.push_back(card);
61 logMessage << " [matches]";
64 logger->log(L::INFO, logMessage.str());
69 if (cardNumbers.size() == 1) {
70 const auto n = std::to_string(cardNumbers[0]);
71 logger->log(L::INFO, "Going to fix card #" + n);
73 } else if (cardNumbers.empty()) {
74 throw std::invalid_argument(
75 "No card with matching name found. Is the card connected? "
76 "Maybe try to provide different name pattern.");
78 throw std::invalid_argument(
79 "Multiple cards with matching name found. "
80 "Please provide a name pattern that matches only one card");
84 std::string toString(const MidiMessage& midiMessage) {
85 std::stringstream result;
86 for (uint8_t b : midiMessage)
87 result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
94 std::lock_guard<std::recursive_mutex> lock(midiMutex);
97 ssize_t length = snd_rawmidi_read(input, buf, sizeof (buf));
98 if (length > 0 && length <= sizeof (buf)) {
99 // TODO: multiple messages combined together?
100 djmFix->receive(MidiMessage(buf, buf + length));
103 std::this_thread::sleep_for(std::chrono::milliseconds(100));
109 djmfix::DJMFix* djmFix,
110 const std::string& cardNamePattern,
111 djmfix::logging::Logger* logger)
112 : djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) //
114 if (djmFix == nullptr)
115 throw std::invalid_argument("Need a djmFix for AlsaBridge.");
117 std::string deviceName = findDeviceName(std::regex(cardNamePattern));
119 int mode = SND_RAWMIDI_NONBLOCK;
120 int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), mode);
121 if (error) throw std::invalid_argument("Unable to open ALSA device.");
123 djmFix->setMidiSender(this);
126 virtual ~AlsaBridgeImpl() {
127 // TODO: do not use raw/exclusive access to the MIDI device
128 snd_rawmidi_close(input);
129 snd_rawmidi_close(output);
130 logger->log(L::FINER, "~AlsaBridgeImpl()");
133 virtual void start() override {
135 receivingThread = std::thread(&AlsaBridgeImpl::run, this);
138 virtual void stop() override {
140 receivingThread.join();
144 virtual void send(MidiMessage msg) override {
145 std::lock_guard<std::recursive_mutex> lock(midiMutex);
146 ssize_t length = snd_rawmidi_write(output, msg.data(), msg.size());
147 logger->log(L::FINE, "Sent message:"
148 " length = " + std::to_string(length)
149 + " data = " + toString(msg));
155 djmfix::DJMFix* djmFix,
156 const std::string& deviceName,
157 djmfix::logging::Logger* logger) //
159 return new AlsaBridgeImpl(djmFix, deviceName, logger);