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/>.
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 logger->log(L::INFO, "Going to fix card #" + std::to_string(cardNumbers[0]));
71 return "hw:" + std::to_string(cardNumbers[0]);
72 } else if (cardNumbers.empty()) {
73 throw std::invalid_argument("No card with matching name found. Is the card connected? Maybe try to provide different name pattern.");
75 throw std::invalid_argument("Multiple cards with matching name found. Please provide a name pattern that matches only one card");
79 std::string toString(const MidiMessage& midiMessage) {
80 std::stringstream result;
81 for (uint8_t b : midiMessage) result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
88 std::lock_guard<std::recursive_mutex> lock(midiMutex);
91 ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
92 if (length > 0 && length <= sizeof (buffer)) {
93 // TODO: multiple messages combined together?
94 djmFix->receive(MidiMessage(buffer, buffer + length));
97 std::this_thread::sleep_for(std::chrono::milliseconds(100));
102 AlsaBridgeImpl(djmfix::DJMFix* djmFix, const std::string& cardNamePattern, djmfix::logging::Logger* logger) : djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) {
103 if (djmFix == nullptr) throw std::invalid_argument("Need a djmFix for AlsaBridge.");
105 std::string deviceName = findDeviceName(std::regex(cardNamePattern));
107 int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), SND_RAWMIDI_NONBLOCK);
108 if (error) throw std::invalid_argument("Unable to open ALSA device.");
111 djmFix->setMidiSender(this);
114 virtual ~AlsaBridgeImpl() {
115 // TODO: do not use raw/exclusive access to the MIDI device
116 snd_rawmidi_close(input);
117 snd_rawmidi_close(output);
118 logger->log(L::FINER, "~AlsaBridgeImpl()");
121 virtual void start() override {
123 receivingThread = std::thread(&AlsaBridgeImpl::run, this);
126 virtual void stop() override {
128 receivingThread.join();
132 virtual void send(MidiMessage midiMessage) override {
133 std::lock_guard<std::recursive_mutex> lock(midiMutex);
134 ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
135 logger->log(L::FINE, "Sent message: length = " + std::to_string(length) + " data = " + toString(midiMessage));
140 AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName, djmfix::logging::Logger* logger) {
141 return new AlsaBridgeImpl(djmFix, deviceName, logger);