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

/**
 * DJM-Fix
 * Copyright © 2020 František Kučera (Frantovo.cz, GlobalCode.info)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <iostream>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <thread>
#include <mutex>
#include <atomic>
#include <regex>

#include <alsa/asoundlib.h>

#include "AlsaBridge.h"
#include "Logger.h"

namespace djmfix {
namespace alsa {

using L = djmfix::logging::Level;

class AlsaBridgeImpl : public AlsaBridge, private djmfix::MidiSender {
private:
	djmfix::DJMFix* djmFix;
	djmfix::logging::Logger* logger;
	snd_rawmidi_t* input;
	snd_rawmidi_t* output;
	std::thread receivingThread;
	std::recursive_mutex midiMutex;
	std::atomic<bool> stopped{false};

	std::string findDeviceName(std::regex cardNamePattern) {

		std::vector<int> cardNumbers;

		logger->log(L::INFO, "Looking for available cards:");

		for (int card = -1; snd_card_next(&card) == 0 && card >= 0;) {
			char* longName = nullptr;
			snd_card_get_longname(card, &longName);

			std::stringstream logMessage;
			logMessage << " - card: #" << card << ": '" << longName << "'";

			if (std::regex_match(longName, cardNamePattern)) {
				cardNumbers.push_back(card);
				logMessage << " [matches]";
			}

			logger->log(L::INFO, logMessage.str());

			free(longName);
		}

		if (cardNumbers.size() == 1) {
			logger->log(L::INFO, "Going to fix card #" + std::to_string(cardNumbers[0]));
			return "hw:" + std::to_string(cardNumbers[0]);
		} else if (cardNumbers.empty()) {
			throw std::invalid_argument("No card with matching name found. Is the card connected? Maybe try to provide different name pattern.");
		} else {
			throw std::invalid_argument("Multiple cards with matching name found. Please provide a name pattern that matches only one card");
		}
	}

	std::string toString(const MidiMessage& midiMessage) {
		std::stringstream result;
		for (uint8_t b : midiMessage) result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
		return result.str();
	}

	void run() {
		while (!stopped) {
			{
				std::lock_guard<std::recursive_mutex> lock(midiMutex);
				// TODO: poll
				uint8_t buffer[256];
				ssize_t length = snd_rawmidi_read(input, buffer, sizeof (buffer));
				if (length > 0 && length <= sizeof (buffer)) {
					// TODO: multiple messages combined together?
					djmFix->receive(MidiMessage(buffer, buffer + length));
				}
			}
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
		}
	}
public:

	AlsaBridgeImpl(djmfix::DJMFix* djmFix, const std::string& cardNamePattern, djmfix::logging::Logger* logger) : djmFix(djmFix), logger(logger ? logger : djmfix::logging::blackhole()) {
		if (djmFix == nullptr) throw std::invalid_argument("Need a djmFix for AlsaBridge.");

		std::string deviceName = findDeviceName(std::regex(cardNamePattern));

		int error = snd_rawmidi_open(&input, &output, deviceName.c_str(), SND_RAWMIDI_NONBLOCK);
		if (error) throw std::invalid_argument("Unable to open ALSA device.");


		djmFix->setMidiSender(this);
	}

	virtual ~AlsaBridgeImpl() {
		// TODO: do not use raw/exclusive access to the MIDI device
		snd_rawmidi_close(input);
		snd_rawmidi_close(output);
		logger->log(L::FINER, "~AlsaBridgeImpl()");
	}

	virtual void start() override {
		djmFix->start();
		receivingThread = std::thread(&AlsaBridgeImpl::run, this);
	}

	virtual void stop() override {
		stopped = true;
		receivingThread.join();
		djmFix->stop();
	}

	virtual void send(MidiMessage midiMessage) override {
		std::lock_guard<std::recursive_mutex> lock(midiMutex);
		ssize_t length = snd_rawmidi_write(output, midiMessage.data(), midiMessage.size());
		logger->log(L::FINE, "Sent message: length = " + std::to_string(length) + " data = " + toString(midiMessage));
	}

};

AlsaBridge* create(djmfix::DJMFix* djmFix, const std::string& deviceName, djmfix::logging::Logger* logger) {
	return new AlsaBridgeImpl(djmFix, deviceName, logger);
}

}
}