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};
51 FoundDevice findDeviceName(std::regex cardNamePattern) {
52 std::vector<int> cardNumbers;
53 std::vector<std::string> cardNames;
55 logger->log(L::INFO, "Looking for available cards:");
57 for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
58 char* longName = nullptr;
59 snd_card_get_longname(card, &longName);
61 std::stringstream logMessage;
62 logMessage << " - card: #" << card << ": '" << longName << "'";
64 if (std::regex_match(longName, cardNamePattern)) {
65 cardNumbers.push_back(card);
66 cardNames.push_back(longName);
67 logMessage << " [matches]";
70 logger->log(L::INFO, logMessage.str());
75 if (cardNumbers.size() == 1) {
76 const auto n = std::to_string(cardNumbers[0]);
77 logger->log(L::INFO, "Going to fix card #" + n);
78 return {"hw:" + n, cardNames[0]};
79 } else if (cardNumbers.empty()) {
80 throw std::invalid_argument(
81 "No card with matching name found. Is the card connected? "
82 "Maybe try to provide different name pattern.");
84 throw std::invalid_argument(
85 "Multiple cards with matching name found. "
86 "Please provide a name pattern that matches only one card");
90 std::string toString(const MidiMessage& midiMessage) {
91 std::stringstream result;
92 for (uint8_t b : midiMessage)
93 result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
101 std::lock_guard<std::recursive_mutex> lock(midiMutex);
104 ssize_t length = snd_rawmidi_read(input, buf, sizeof (buf));
105 if (length > 0 && length <= sizeof (buf)) {
106 // Parse MIDI messages and ignore/skip unwanted data.
107 // Needed for DJM-V10 that sends annoying amounts of 0xF8.
108 for (int i = 0; i < length; i++) {
110 if (b == MIDI_CMD_COMMON_SYSEX) {
111 // start of MIDI SysEx message
114 } else if (b == MIDI_CMD_COMMON_SYSEX_END) {
115 // end of MIDI SysEx message
117 djmFix->receive(msg);
119 } else if (b == MIDI_CMD_COMMON_CLOCK) {
120 logger->log(L::FINEST, "timing clock ignored");
121 } else if (b == MIDI_CMD_COMMON_SENSING) {
122 logger->log(L::FINEST, "active sensing ignored");
123 } else if (b & 0x80) {
124 // unknown status, drop previous data
126 logger->log(L::FINER, "unknown message ignored");
134 std::this_thread::sleep_for(std::chrono::milliseconds(100));
140 djmfix::DJMFix* djmFix,
141 const std::string& cardNamePattern,
142 djmfix::logging::Logger* logger)
143 : djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) //
145 if (djmFix == nullptr)
146 throw std::invalid_argument("Need a djmFix for AlsaBridge.");
148 FoundDevice found = findDeviceName(std::regex(cardNamePattern));
150 int mode = SND_RAWMIDI_NONBLOCK;
151 int error = snd_rawmidi_open(&input, &output, found.id.c_str(), mode);
152 if (error) throw std::invalid_argument("Unable to open ALSA device.");
154 djmFix->setDeviceName(found.name);
155 djmFix->setMidiSender(this);
158 virtual ~AlsaBridgeImpl() {
159 // TODO: do not use raw/exclusive access to the MIDI device
160 snd_rawmidi_close(input);
161 snd_rawmidi_close(output);
162 logger->log(L::FINER, "~AlsaBridgeImpl()");
165 virtual void start() override {
167 receivingThread = std::thread(&AlsaBridgeImpl::run, this);
170 virtual void stop() override {
172 receivingThread.join();
176 virtual void send(MidiMessage msg) override {
177 std::lock_guard<std::recursive_mutex> lock(midiMutex);
178 ssize_t length = snd_rawmidi_write(output, msg.data(), msg.size());
179 logger->log(L::FINE, "Sent message:"
180 " length = " + std::to_string(length)
181 + " data = " + toString(msg));
187 djmfix::DJMFix* djmFix,
188 const std::string& deviceName,
189 djmfix::logging::Logger* logger) //
191 return new AlsaBridgeImpl(djmFix, deviceName, logger);