AlsaBridge.cpp
author František Kučera <franta-hg@frantovo.cz>
Tue, 15 Apr 2025 22:45:25 +0200
branchv_0
changeset 16 63154f9d24a2
parent 13 334b727f7516
child 18 358a601bfe81
permissions -rw-r--r--
code formatting
     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 	std::string findDeviceName(std::regex cardNamePattern) {
    47 
    48 		std::vector<int> cardNumbers;
    49 
    50 		logger->log(L::INFO, "Looking for available cards:");
    51 
    52 		for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
    53 			char* longName = nullptr;
    54 			snd_card_get_longname(card, &longName);
    55 
    56 			std::stringstream logMessage;
    57 			logMessage << " - card: #" << card << ": '" << longName << "'";
    58 
    59 			if (std::regex_match(longName, cardNamePattern)) {
    60 				cardNumbers.push_back(card);
    61 				logMessage << " [matches]";
    62 			}
    63 
    64 			logger->log(L::INFO, logMessage.str());
    65 
    66 			free(longName);
    67 		}
    68 
    69 		if (cardNumbers.size() == 1) {
    70 			const auto n = std::to_string(cardNumbers[0]);
    71 			logger->log(L::INFO, "Going to fix card #" + n);
    72 			return "hw:" + 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.");
    77 		} else {
    78 			throw std::invalid_argument(
    79 					"Multiple cards with matching name found. "
    80 					"Please provide a name pattern that matches only one card");
    81 		}
    82 	}
    83 
    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;
    88 		return result.str();
    89 	}
    90 
    91 	void run() {
    92 		while (!stopped) {
    93 			{
    94 				std::lock_guard<std::recursive_mutex> lock(midiMutex);
    95 				// TODO: poll
    96 				uint8_t buf[256];
    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));
   101 				}
   102 			}
   103 			std::this_thread::sleep_for(std::chrono::milliseconds(100));
   104 		}
   105 	}
   106 public:
   107 
   108 	AlsaBridgeImpl(
   109 			djmfix::DJMFix* djmFix,
   110 			const std::string& cardNamePattern,
   111 			djmfix::logging::Logger* logger)
   112 	: djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) //
   113 	{
   114 		if (djmFix == nullptr)
   115 			throw std::invalid_argument("Need a djmFix for AlsaBridge.");
   116 
   117 		std::string deviceName = findDeviceName(std::regex(cardNamePattern));
   118 
   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.");
   122 
   123 		djmFix->setMidiSender(this);
   124 	}
   125 
   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()");
   131 	}
   132 
   133 	virtual void start() override {
   134 		djmFix->start();
   135 		receivingThread = std::thread(&AlsaBridgeImpl::run, this);
   136 	}
   137 
   138 	virtual void stop() override {
   139 		stopped = true;
   140 		receivingThread.join();
   141 		djmFix->stop();
   142 	}
   143 
   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));
   150 	}
   151 
   152 };
   153 
   154 AlsaBridge* create(
   155 		djmfix::DJMFix* djmFix,
   156 		const std::string& deviceName,
   157 		djmfix::logging::Logger* logger) //
   158 {
   159 	return new AlsaBridgeImpl(djmFix, deviceName, logger);
   160 }
   161 
   162 }
   163 }