AlsaBridge.cpp
author František Kučera <franta-hg@frantovo.cz>
Mon, 04 Jan 2021 15:45:12 +0100
branchv_0
changeset 12 15d87fdd6e6c
parent 11 5b351628a377
child 13 334b727f7516
permissions -rw-r--r--
use Logger instead of messing with STDIO directly
     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 <sstream>
    19 #include <stdexcept>
    20 #include <thread>
    21 #include <mutex>
    22 #include <atomic>
    23 #include <regex>
    24 
    25 #include <alsa/asoundlib.h>
    26 
    27 #include "AlsaBridge.h"
    28 #include "Logger.h"
    29 
    30 namespace djmfix {
    31 namespace alsa {
    32 
    33 using L = djmfix::logging::Level;
    34 
    35 class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
    36 private:
    37 	djmfix::DJMFix* djmFix;
    38 	djmfix::logging::Logger* logger;
    39 	snd_rawmidi_t* input;
    40 	snd_rawmidi_t* output;
    41 	std::thread receivingThread;
    42 	std::recursive_mutex midiMutex;
    43 	std::atomic<bool> stopped{false};
    44 
    45 	std::string findDeviceName(std::regex cardNamePattern) {
    46 
    47 		std::vector<int> cardNumbers;
    48 
    49 		logger->log(L::INFO, "Looking for available cards:");
    50 
    51 		for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
    52 			char* longName = nullptr;
    53 			snd_card_get_longname(card, &longName);
    54 
    55 			std::stringstream logMessage;
    56 			logMessage << " - card: #" << card << ": '" << longName << "'";
    57 
    58 			if (std::regex_match(longName, cardNamePattern)) {
    59 				cardNumbers.push_back(card);
    60 				logMessage << " [matches]";
    61 			}
    62 
    63 			logger->log(L::INFO, logMessage.str());
    64 
    65 			free(longName);
    66 		}
    67 
    68 		if (cardNumbers.size() == 1) {
    69 			logger->log(L::INFO, "Going to fix card #" + std::to_string(cardNumbers[0]));
    70 			return "hw:" + std::to_string(cardNumbers[0]);
    71 		} else if (cardNumbers.empty()) {
    72 			throw std::invalid_argument("No card with matching name found. Is the card connected? Maybe try to provide different name pattern.");
    73 		} else {
    74 			throw std::invalid_argument("Multiple cards with matching name found. Please provide a name pattern that matches only one card");
    75 		}
    76 	}
    77 
    78 	void run() {
    79 		while (!stopped) {
    80 			{
    81 				std::lock_guard<std::recursive_mutex> lock(midiMutex);
    82 				// TODO: poll
    83 				uint8_t buffer[256];
    84 				ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
    85 				if (length > 0 && length <= sizeof (buffer)) {
    86 					// TODO: multiple messages combined together?
    87 					djmFix->receive(MidiMessage(buffer, buffer + length));
    88 				}
    89 			}
    90 			std::this_thread::sleep_for(std::chrono::milliseconds(100));
    91 		}
    92 	}
    93 public:
    94 
    95 	AlsaBridgeImpl(djmfix::DJMFix* djmFix, const std::string& cardNamePattern, djmfix::logging::Logger* logger) : djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) {
    96 		if (djmFix == nullptr) throw std::invalid_argument("need a djmFix for AlsaBridge");
    97 
    98 		std::string deviceName = findDeviceName(std::regex(cardNamePattern));
    99 
   100 		int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), SND_RAWMIDI_NONBLOCK);
   101 		if (error) throw std::invalid_argument("unable to open ALSA device");
   102 
   103 
   104 		djmFix->setMidiSender(this);
   105 	}
   106 
   107 	virtual ~AlsaBridgeImpl() {
   108 		// TODO: do not use raw/exclusive access to the MIDI device
   109 		snd_rawmidi_close(input);
   110 		snd_rawmidi_close(output);
   111 		logger->log(L::FINE, "~AlsaBridgeImpl()");
   112 	}
   113 
   114 	virtual void start() override {
   115 		djmFix->start();
   116 		receivingThread = std::thread(&AlsaBridgeImpl::run, this);
   117 	}
   118 
   119 	virtual void stop() override {
   120 		stopped = true;
   121 		receivingThread.join();
   122 		djmFix->stop();
   123 	}
   124 
   125 	virtual void send(MidiMessage midiMessage) override {
   126 		std::lock_guard<std::recursive_mutex> lock(midiMutex);
   127 		ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
   128 		logger->log(L::INFO, "AlsaBridgeImpl::send(): length = " + std::to_string(length));
   129 	}
   130 
   131 };
   132 
   133 AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName, djmfix::logging::Logger* logger) {
   134 	return new AlsaBridgeImpl(djmFix, deviceName, logger);
   135 }
   136 
   137 }
   138 }