DJMFix.cpp
author František Kučera <franta-hg@frantovo.cz>
Mon, 04 Jan 2021 15:45:12 +0100
branchv_0
changeset 12 15d87fdd6e6c
parent 8 87dfa7c89294
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 <iomanip>
    20 #include <thread>
    21 #include <mutex>
    22 #include <atomic>
    23 #include <chrono>
    24 #include <stdexcept>
    25 #include <vector>
    26 
    27 #include "DJMFix.h"
    28 
    29 namespace djmfix {
    30 
    31 using L = djmfix::logging::Level;
    32 using Bytes = std::vector<uint8_t>;
    33 
    34 class DJMFixImpl : public DJMFix {
    35 private:
    36 	MidiSender* midiSender;
    37 	djmfix::logging::Logger* logger;
    38 	std::thread keepAliveThread;
    39 	std::recursive_mutex midiMutex;
    40 	std::atomic<bool> running{false};
    41 	std::atomic<bool> stopped{false};
    42 	std::atomic<bool> sendKeepAlive{false};
    43 	Bytes seed2;
    44 
    45 	void run() {
    46 		while (!stopped) {
    47 			logger->log(L::FINE, "DJMFixImpl::run()");
    48 			if (sendKeepAlive) send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x50, 0x01, 0xf7});
    49 			std::this_thread::sleep_for(std::chrono::milliseconds(200));
    50 		}
    51 	}
    52 
    53 	void send(const MidiMessage& midiMessage) {
    54 		std::lock_guard<std::recursive_mutex> lock(midiMutex);
    55 		midiSender->send(midiMessage);
    56 	}
    57 
    58 	std::string toString(const Bytes& midiMessage) {
    59 		std::stringstream result;
    60 		for (uint8_t b : midiMessage) result << std::hex << std::setw(2) << std::setfill('0') << (int) b;
    61 		return result.str();
    62 	}
    63 
    64 	Bytes normalize(const Bytes& data) {
    65 		if (data.size() % 2) throw std::invalid_argument("data before normalization must have even number of bytes");
    66 		Bytes result;
    67 		result.reserve(data.size() / 2);
    68 		for (size_t i = 0; i < data.size() / 2; i++) result.push_back((data[i * 2] & 0x0F) << 4 | (data[i * 2 + 1] & 0x0F));
    69 		return result;
    70 	}
    71 
    72 	Bytes denormalize(const Bytes& data) {
    73 		Bytes result;
    74 		result.reserve(data.size()*2);
    75 		for (size_t i = 0; i < data.size(); i++) {
    76 			result.push_back(data[i] >> 4);
    77 			result.push_back(data[i] & 0x0F);
    78 		}
    79 		return result;
    80 	}
    81 
    82 	uint32_t fnv32hash(const Bytes& buff) {
    83 		uint32_t hash = 0x811c9dc5;
    84 		for (uint8_t b : buff) hash = ((b^hash) * 0x1000193);
    85 		return hash;
    86 	}
    87 
    88 	Bytes toBytes(const uint32_t value) {
    89 		Bytes result;
    90 		result.reserve(4);
    91 		result.push_back(value >> 24);
    92 		result.push_back(value >> 16);
    93 		result.push_back(value >> 8);
    94 		result.push_back(value >> 0);
    95 		return result;
    96 	}
    97 
    98 	bool equals(Bytes a, Bytes b) {
    99 		if (a.size() != b.size()) return false;
   100 		for (size_t i = 0; i < a.size(); i++) if (a[i] != b[i]) return false;
   101 		return true;
   102 	}
   103 
   104 	template<typename T> std::vector<T> concat(const std::vector<T>& a, const std::vector<T>& b, const std::vector<T>& c = {}) {
   105 		std::vector<T> result;
   106 		result.reserve(a.size() + b.size() + c.size());
   107 		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i]);
   108 		for (size_t i = 0; i < b.size(); i++) result.push_back(b[i]);
   109 		for (size_t i = 0; i < c.size(); i++) result.push_back(c[i]);
   110 		return result;
   111 	}
   112 
   113 	template<typename T> std::vector<T> xOR(const std::vector<T>& a, const std::vector<T>& b) {
   114 		if (a.size() != b.size()) throw std::invalid_argument("xor: both must be the same length");
   115 		std::vector<T> result;
   116 		result.reserve(a.size());
   117 		for (size_t i = 0; i < a.size(); i++) result.push_back(a[i] ^ b[i]);
   118 		return result;
   119 	}
   120 
   121 public:
   122 
   123 	DJMFixImpl(djmfix::logging::Logger* logger) : logger(logger ? logger : djmfix::logging::blackhole()) {
   124 	}
   125 
   126 	virtual ~DJMFixImpl() override {
   127 		logger->log(L::FINE, "~DJMFixImpl()");
   128 		if (running) stop();
   129 	}
   130 
   131 	void setMidiSender(MidiSender* midiSender) {
   132 		logger->log(L::FINE, "DJMFixImpl::setMidiSender()");
   133 		this->midiSender = midiSender;
   134 	}
   135 
   136 	virtual void receive(const MidiMessage& midiMessage) override {
   137 		logger->log(L::INFO, "received message: size = " + std::to_string(midiMessage.size()) + " data = " + toString(midiMessage));
   138 		std::lock_guard<std::recursive_mutex> lock(midiMutex);
   139 
   140 
   141 		if (midiMessage.size() == 12 && midiMessage[9] == 0x11) {
   142 			send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x12, 0x2a, 0x01, 0x0b, 0x50, 0x69, 0x6f, 0x6e, 0x65, 0x65, 0x72, 0x44, 0x4a, 0x02, 0x0b, 0x72, 0x65, 0x6b, 0x6f, 0x72, 0x64, 0x62, 0x6f, 0x78, 0x03, 0x12, 0x02, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x03, 0x04, 0x08, 0x00, 0x00, 0x00, 0x00, 0xf7});
   143 		} else if (midiMessage.size() == 54 && midiMessage[9] == 0x13 && midiMessage[33] == 0x04 && midiMessage[43] == 0x03) {
   144 			Bytes hash1(midiMessage.begin() + 35, midiMessage.begin() + 35 + 8);
   145 			seed2 = Bytes(midiMessage.begin() + 45, midiMessage.begin() + 45 + 8);
   146 			hash1 = normalize(hash1);
   147 			seed2 = normalize(seed2);
   148 			logger->log(L::INFO, "got message with hash1 = " + toString(hash1) + " and seed2 = " + toString(seed2));
   149 
   150 			Bytes seed0 = {0x68, 0x01, 0x31, 0xFB};
   151 			Bytes seed1 = {0x29, 0x00, 0x00, 0x00, 0x23, 0x48, 0x00, 0x00};
   152 
   153 			Bytes hash1check = toBytes(fnv32hash(concat(seed1, xOR(seed0, seed2))));
   154 
   155 			if (equals(hash1, hash1check)) {
   156 				logger->log(L::INFO, "hash1 verification: OK");
   157 				Bytes hash2 = toBytes(fnv32hash(concat(seed2, xOR(seed0, seed2))));
   158 				send(concat({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x14, 0x38, 0x01, 0x0b, 0x50, 0x69, 0x6f, 0x6e, 0x65, 0x65, 0x72, 0x44, 0x4a, 0x02, 0x0b, 0x72, 0x65, 0x6b, 0x6f, 0x72, 0x64, 0x62, 0x6f, 0x78, 0x04, 0x0a}, concat(denormalize(hash2),{0x05, 0x16, 0x05, 0x09, 0x0b, 0x05, 0x04, 0x0b, 0x0f, 0x0e, 0x0e, 0x04, 0x04, 0x0a, 0x05, 0x0a, 0x0c, 0x08, 0x0e, 0x04, 0x0c, 0x05, 0xf7})));
   159 			} else {
   160 				std::stringstream logMessage;
   161 				logMessage
   162 						<< "hash1 verification failed: "
   163 						<< " midiMessage = " << toString(midiMessage)
   164 						<< " seed0 = " << toString(seed0)
   165 						<< " seed1 = " << toString(seed1)
   166 						<< " seed2 = " << toString(seed2)
   167 						<< " hash1 = " << toString(hash1)
   168 						<< " hash1check = " << toString(hash1check);
   169 				logger->log(L::SEVERE, logMessage.str());
   170 				// TODO: graceful death
   171 			}
   172 		} else if (midiMessage.size() == 12 && midiMessage[9] == 0x15) {
   173 			sendKeepAlive = true;
   174 		}
   175 
   176 	}
   177 
   178 	void start() override {
   179 		logger->log(L::FINE, "DJMFixImpl::start()");
   180 		if (midiSender == nullptr) throw std::logic_error("need a midiSender when starting DJMFix");
   181 
   182 		// TODO: methods for parsing and constructing messages from parts (TLV)
   183 		send({0xf0, 0x00, 0x40, 0x05, 0x00, 0x00, 0x00, 0x17, 0x00, 0x50, 0x01, 0xf7});
   184 
   185 		keepAliveThread = std::thread(&DJMFixImpl::run, this);
   186 		running = true;
   187 
   188 	}
   189 
   190 	void stop() override {
   191 		stopped = true;
   192 		keepAliveThread.join();
   193 		running = false;
   194 		logger->log(L::FINE, "DJMFixImpl::stop()");
   195 	}
   196 };
   197 
   198 DJMFix* create(djmfix::logging::Logger* logger) {
   199 	return new DJMFixImpl(logger);
   200 }
   201 
   202 }