AlsaBridge.cpp
author František Kučera <franta-hg@frantovo.cz>
Mon, 04 Jan 2021 17:11:57 +0100
branchv_0
changeset 13 334b727f7516
parent 12 15d87fdd6e6c
permissions -rw-r--r--
improved logging and error messages
     1 /**
     2  * DJM-Fix
     3  * Copyright © 2020 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 			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.");
    74 		} else {
    75 			throw std::invalid_argument("Multiple cards with matching name found. Please provide a name pattern that matches only one card");
    76 		}
    77 	}
    78 
    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;
    82 		return result.str();
    83 	}
    84 
    85 	void run() {
    86 		while (!stopped) {
    87 			{
    88 				std::lock_guard<std::recursive_mutex> lock(midiMutex);
    89 				// TODO: poll
    90 				uint8_t buffer[256];
    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));
    95 				}
    96 			}
    97 			std::this_thread::sleep_for(std::chrono::milliseconds(100));
    98 		}
    99 	}
   100 public:
   101 
   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.");
   104 
   105 		std::string deviceName = findDeviceName(std::regex(cardNamePattern));
   106 
   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.");
   109 
   110 
   111 		djmFix->setMidiSender(this);
   112 	}
   113 
   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()");
   119 	}
   120 
   121 	virtual void start() override {
   122 		djmFix->start();
   123 		receivingThread = std::thread(&AlsaBridgeImpl::run, this);
   124 	}
   125 
   126 	virtual void stop() override {
   127 		stopped = true;
   128 		receivingThread.join();
   129 		djmFix->stop();
   130 	}
   131 
   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));
   136 	}
   137 
   138 };
   139 
   140 AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName, djmfix::logging::Logger* logger) {
   141 	return new AlsaBridgeImpl(djmFix, deviceName, logger);
   142 }
   143 
   144 }
   145 }