AlsaBridge.cpp
author František Kučera <franta-hg@frantovo.cz>
Sun, 01 Jun 2025 13:18:10 +0200
branchv_0
changeset 20 a08e30243b95
parent 18 358a601bfe81
permissions -rw-r--r--
Added tag v0.1 for changeset 334b727f7516
     1 /**
     2  * DJM-Fix
     3  * Copyright © 2025 František Kučera (Frantovo.cz, GlobalCode.info)
     4  *
     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.
     8  *
     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.
    13  *
    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/>.
    16  */
    17 #include <iostream>
    18 #include <iomanip>
    19 #include <sstream>
    20 #include <stdexcept>
    21 #include <thread>
    22 #include <mutex>
    23 #include <atomic>
    24 #include <regex>
    25 
    26 #include <alsa/asoundlib.h>
    27 
    28 #include "AlsaBridge.h"
    29 #include "Logger.h"
    30 
    31 namespace djmfix {
    32 namespace alsa {
    33 
    34 using L = djmfix::logging::Level;
    35 
    36 class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
    37 private:
    38 	djmfix::DJMFix* djmFix;
    39 	djmfix::logging::Logger* logger;
    40 	snd_rawmidi_t* input;
    41 	snd_rawmidi_t* output;
    42 	std::thread receivingThread;
    43 	std::recursive_mutex midiMutex;
    44 	std::atomic<bool> stopped{false};
    45 
    46 	struct FoundDevice {
    47 		std::string id;
    48 		std::string name;
    49 	};
    50 
    51 	FoundDevice findDeviceName(std::regex cardNamePattern) {
    52 		std::vector<int> cardNumbers;
    53 		std::vector<std::string> cardNames;
    54 
    55 		logger->log(L::INFO, "Looking for available cards:");
    56 
    57 		for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
    58 			char* longName = nullptr;
    59 			snd_card_get_longname(card, &longName);
    60 
    61 			std::stringstream logMessage;
    62 			logMessage << " - card: #" << card << ": '" << longName << "'";
    63 
    64 			if (std::regex_match(longName, cardNamePattern)) {
    65 				cardNumbers.push_back(card);
    66 				cardNames.push_back(longName);
    67 				logMessage << " [matches]";
    68 			}
    69 
    70 			logger->log(L::INFO, logMessage.str());
    71 
    72 			free(longName);
    73 		}
    74 
    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.");
    83 		} else {
    84 			throw std::invalid_argument(
    85 					"Multiple cards with matching name found. "
    86 					"Please provide a name pattern that matches only one card");
    87 		}
    88 	}
    89 
    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;
    94 		return result.str();
    95 	}
    96 
    97 	void run() {
    98 		MidiMessage msg;
    99 		while (!stopped) {
   100 			{
   101 				std::lock_guard<std::recursive_mutex> lock(midiMutex);
   102 				// TODO: poll
   103 				uint8_t buf[256];
   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++) {
   109 						uint8_t b = buf[i];
   110 						if (b == MIDI_CMD_COMMON_SYSEX) {
   111 							// start of MIDI SysEx message
   112 							msg.clear();
   113 							msg.push_back(b);
   114 						} else if (b == MIDI_CMD_COMMON_SYSEX_END) {
   115 							// end of MIDI SysEx message
   116 							msg.push_back(b);
   117 							djmFix->receive(msg);
   118 							msg.clear();
   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
   125 							msg.clear();
   126 							logger->log(L::FINER, "unknown message ignored");
   127 						} else {
   128 							// message data
   129 							msg.push_back(b);
   130 						}
   131 					}
   132 				}
   133 			}
   134 			std::this_thread::sleep_for(std::chrono::milliseconds(100));
   135 		}
   136 	}
   137 public:
   138 
   139 	AlsaBridgeImpl(
   140 			djmfix::DJMFix* djmFix,
   141 			const std::string& cardNamePattern,
   142 			djmfix::logging::Logger* logger)
   143 	: djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) //
   144 	{
   145 		if (djmFix == nullptr)
   146 			throw std::invalid_argument("Need a djmFix for AlsaBridge.");
   147 
   148 		FoundDevice found = findDeviceName(std::regex(cardNamePattern));
   149 
   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.");
   153 
   154 		djmFix->setDeviceName(found.name);
   155 		djmFix->setMidiSender(this);
   156 	}
   157 
   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()");
   163 	}
   164 
   165 	virtual void start() override {
   166 		djmFix->start();
   167 		receivingThread = std::thread(&AlsaBridgeImpl::run, this);
   168 	}
   169 
   170 	virtual void stop() override {
   171 		stopped = true;
   172 		receivingThread.join();
   173 		djmFix->stop();
   174 	}
   175 
   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));
   182 	}
   183 
   184 };
   185 
   186 AlsaBridge* create(
   187 		djmfix::DJMFix* djmFix,
   188 		const std::string& deviceName,
   189 		djmfix::logging::Logger* logger) //
   190 {
   191 	return new AlsaBridgeImpl(djmFix, deviceName, logger);
   192 }
   193 
   194 }
   195 }