| 1 | /**********************************************************************/ |
| 2 | /*! \class RtMidi |
| 3 | \brief An abstract base class for realtime MIDI input/output. |
| 4 | |
| 5 | This class implements some common functionality for the realtime |
| 6 | MIDI input/output subclasses RtMidiIn and RtMidiOut. |
| 7 | |
| 8 | RtMidi GitHub site: https://github.com/thestk/rtmidi |
| 9 | RtMidi WWW site: http://www.music.mcgill.ca/~gary/rtmidi/ |
| 10 | |
| 11 | RtMidi: realtime MIDI i/o C++ classes |
| 12 | Copyright (c) 2003-2023 Gary P. Scavone |
| 13 | |
| 14 | Permission is hereby granted, free of charge, to any person |
| 15 | obtaining a copy of this software and associated documentation files |
| 16 | (the "Software"), to deal in the Software without restriction, |
| 17 | including without limitation the rights to use, copy, modify, merge, |
| 18 | publish, distribute, sublicense, and/or sell copies of the Software, |
| 19 | and to permit persons to whom the Software is furnished to do so, |
| 20 | subject to the following conditions: |
| 21 | |
| 22 | The above copyright notice and this permission notice shall be |
| 23 | included in all copies or substantial portions of the Software. |
| 24 | |
| 25 | Any person wishing to distribute modifications to the Software is |
| 26 | asked to send the modifications to the original developer so that |
| 27 | they can be incorporated into the canonical version. This is, |
| 28 | however, not a binding provision of this license. |
| 29 | |
| 30 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, |
| 31 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
| 32 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. |
| 33 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR |
| 34 | ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF |
| 35 | CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION |
| 36 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. |
| 37 | */ |
| 38 | /**********************************************************************/ |
| 39 | |
| 40 | #include "rtmidi.h" |
| 41 | #include <sstream> |
| 42 | #if defined(__APPLE__) |
| 43 | #include <TargetConditionals.h> |
| 44 | #endif |
| 45 | |
| 46 | #if (TARGET_OS_IPHONE == 1) |
| 47 | |
| 48 | #define AudioGetCurrentHostTime CAHostTimeBase::GetCurrentTime |
| 49 | #define AudioConvertHostTimeToNanos CAHostTimeBase::ConvertToNanos |
| 50 | |
| 51 | #include <mach/mach_time.h> |
| 52 | class CTime2nsFactor |
| 53 | { |
| 54 | public: |
| 55 | CTime2nsFactor() |
| 56 | { |
| 57 | mach_timebase_info_data_t tinfo; |
| 58 | mach_timebase_info(&tinfo); |
| 59 | Factor = (double)tinfo.numer / tinfo.denom; |
| 60 | } |
| 61 | static double Factor; |
| 62 | }; |
| 63 | double CTime2nsFactor::Factor; |
| 64 | static CTime2nsFactor InitTime2nsFactor; |
| 65 | #undef AudioGetCurrentHostTime |
| 66 | #undef AudioConvertHostTimeToNanos |
| 67 | #define AudioGetCurrentHostTime (uint64_t) mach_absolute_time |
| 68 | #define AudioConvertHostTimeToNanos(t) t *CTime2nsFactor::Factor |
| 69 | #define EndianS32_BtoN(n) n |
| 70 | |
| 71 | #endif |
| 72 | |
| 73 | // Default for Windows is to add an identifier to the port names; this |
| 74 | // flag can be defined (e.g. in your project file) to disable this behaviour. |
| 75 | //#define RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES |
| 76 | |
| 77 | // Default for Windows UWP is to enable a workaround to fix BLE-MIDI IN ports' |
| 78 | // wrong timestamps that occur at least in Windows 10 21H2; |
| 79 | // this flag can be defined (e.g. in your project file) |
| 80 | // to disable this behavior. |
| 81 | //#define RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 82 | |
| 83 | // **************************************************************** // |
| 84 | // |
| 85 | // MidiInApi and MidiOutApi subclass prototypes. |
| 86 | // |
| 87 | // **************************************************************** // |
| 88 | |
| 89 | #if !defined(__LINUX_ALSA__) && !defined(__UNIX_JACK__) && !defined(__MACOSX_CORE__) && !defined(__WINDOWS_MM__) && !defined(__WINDOWS_UWP__) && !defined(TARGET_IPHONE_OS) && !defined(__WEB_MIDI_API__) && !defined(__AMIDI__) |
| 90 | #define __RTMIDI_DUMMY__ |
| 91 | #endif |
| 92 | |
| 93 | #if defined(__MACOSX_CORE__) |
| 94 | #include <CoreMIDI/CoreMIDI.h> |
| 95 | |
| 96 | class MidiInCore: public MidiInApi |
| 97 | { |
| 98 | public: |
| 99 | MidiInCore( const std::string &clientName, unsigned int queueSizeLimit ); |
| 100 | ~MidiInCore( void ); |
| 101 | RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; }; |
| 102 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 103 | void openVirtualPort( const std::string &portName ); |
| 104 | void closePort( void ); |
| 105 | void setClientName( const std::string &clientName ); |
| 106 | void setPortName( const std::string &portName ); |
| 107 | unsigned int getPortCount( void ); |
| 108 | std::string getPortName( unsigned int portNumber ); |
| 109 | |
| 110 | protected: |
| 111 | MIDIClientRef getCoreMidiClientSingleton(const std::string& clientName) throw(); |
| 112 | void initialize( const std::string& clientName ); |
| 113 | }; |
| 114 | |
| 115 | class MidiOutCore: public MidiOutApi |
| 116 | { |
| 117 | public: |
| 118 | MidiOutCore( const std::string &clientName ); |
| 119 | ~MidiOutCore( void ); |
| 120 | RtMidi::Api getCurrentApi( void ) { return RtMidi::MACOSX_CORE; }; |
| 121 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 122 | void openVirtualPort( const std::string &portName ); |
| 123 | void closePort( void ); |
| 124 | void setClientName( const std::string &clientName ); |
| 125 | void setPortName( const std::string &portName ); |
| 126 | unsigned int getPortCount( void ); |
| 127 | std::string getPortName( unsigned int portNumber ); |
| 128 | void sendMessage( const unsigned char *message, size_t size ); |
| 129 | |
| 130 | protected: |
| 131 | MIDIClientRef getCoreMidiClientSingleton(const std::string& clientName) throw(); |
| 132 | void initialize( const std::string& clientName ); |
| 133 | }; |
| 134 | |
| 135 | #endif |
| 136 | |
| 137 | #if defined(__UNIX_JACK__) |
| 138 | |
| 139 | class MidiInJack: public MidiInApi |
| 140 | { |
| 141 | public: |
| 142 | MidiInJack( const std::string &clientName, unsigned int queueSizeLimit ); |
| 143 | ~MidiInJack( void ); |
| 144 | RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; }; |
| 145 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 146 | void openVirtualPort( const std::string &portName ); |
| 147 | void closePort( void ); |
| 148 | void setClientName( const std::string &clientName ); |
| 149 | void setPortName( const std::string &portName); |
| 150 | unsigned int getPortCount( void ); |
| 151 | std::string getPortName( unsigned int portNumber ); |
| 152 | |
| 153 | protected: |
| 154 | std::string clientName; |
| 155 | |
| 156 | void connect( void ); |
| 157 | void initialize( const std::string& clientName ); |
| 158 | }; |
| 159 | |
| 160 | class MidiOutJack: public MidiOutApi |
| 161 | { |
| 162 | public: |
| 163 | MidiOutJack( const std::string &clientName ); |
| 164 | ~MidiOutJack( void ); |
| 165 | RtMidi::Api getCurrentApi( void ) { return RtMidi::UNIX_JACK; }; |
| 166 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 167 | void openVirtualPort( const std::string &portName ); |
| 168 | void closePort( void ); |
| 169 | void setClientName( const std::string &clientName ); |
| 170 | void setPortName( const std::string &portName); |
| 171 | unsigned int getPortCount( void ); |
| 172 | std::string getPortName( unsigned int portNumber ); |
| 173 | void sendMessage( const unsigned char *message, size_t size ); |
| 174 | |
| 175 | protected: |
| 176 | std::string clientName; |
| 177 | |
| 178 | void connect( void ); |
| 179 | void initialize( const std::string& clientName ); |
| 180 | }; |
| 181 | |
| 182 | #endif |
| 183 | |
| 184 | #if defined(__LINUX_ALSA__) |
| 185 | |
| 186 | class MidiInAlsa: public MidiInApi |
| 187 | { |
| 188 | public: |
| 189 | MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit ); |
| 190 | ~MidiInAlsa( void ); |
| 191 | RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; }; |
| 192 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 193 | void openVirtualPort( const std::string &portName ); |
| 194 | void closePort( void ); |
| 195 | void setClientName( const std::string &clientName ); |
| 196 | void setPortName( const std::string &portName); |
| 197 | unsigned int getPortCount( void ); |
| 198 | std::string getPortName( unsigned int portNumber ); |
| 199 | |
| 200 | protected: |
| 201 | void initialize( const std::string& clientName ); |
| 202 | }; |
| 203 | |
| 204 | class MidiOutAlsa: public MidiOutApi |
| 205 | { |
| 206 | public: |
| 207 | MidiOutAlsa( const std::string &clientName ); |
| 208 | ~MidiOutAlsa( void ); |
| 209 | RtMidi::Api getCurrentApi( void ) { return RtMidi::LINUX_ALSA; }; |
| 210 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 211 | void openVirtualPort( const std::string &portName ); |
| 212 | void closePort( void ); |
| 213 | void setClientName( const std::string &clientName ); |
| 214 | void setPortName( const std::string &portName ); |
| 215 | unsigned int getPortCount( void ); |
| 216 | std::string getPortName( unsigned int portNumber ); |
| 217 | void sendMessage( const unsigned char *message, size_t size ); |
| 218 | |
| 219 | protected: |
| 220 | void initialize( const std::string& clientName ); |
| 221 | }; |
| 222 | |
| 223 | #endif |
| 224 | |
| 225 | #if defined(__WINDOWS_MM__) |
| 226 | |
| 227 | class MidiInWinMM: public MidiInApi |
| 228 | { |
| 229 | public: |
| 230 | MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit ); |
| 231 | ~MidiInWinMM( void ); |
| 232 | RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; }; |
| 233 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 234 | void openVirtualPort( const std::string &portName ); |
| 235 | void closePort( void ); |
| 236 | void setClientName( const std::string &clientName ); |
| 237 | void setPortName( const std::string &portName ); |
| 238 | unsigned int getPortCount( void ); |
| 239 | std::string getPortName( unsigned int portNumber ); |
| 240 | |
| 241 | protected: |
| 242 | void initialize( const std::string& clientName ); |
| 243 | }; |
| 244 | |
| 245 | class MidiOutWinMM: public MidiOutApi |
| 246 | { |
| 247 | public: |
| 248 | MidiOutWinMM( const std::string &clientName ); |
| 249 | ~MidiOutWinMM( void ); |
| 250 | RtMidi::Api getCurrentApi( void ) { return RtMidi::WINDOWS_MM; }; |
| 251 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 252 | void openVirtualPort( const std::string &portName ); |
| 253 | void closePort( void ); |
| 254 | void setClientName( const std::string &clientName ); |
| 255 | void setPortName( const std::string &portName ); |
| 256 | unsigned int getPortCount( void ); |
| 257 | std::string getPortName( unsigned int portNumber ); |
| 258 | void sendMessage( const unsigned char *message, size_t size ); |
| 259 | |
| 260 | protected: |
| 261 | void initialize( const std::string& clientName ); |
| 262 | }; |
| 263 | |
| 264 | #endif |
| 265 | |
| 266 | #if defined(__WINDOWS_UWP__) |
| 267 | |
| 268 | class MidiInWinUWP : public MidiInApi |
| 269 | { |
| 270 | public: |
| 271 | MidiInWinUWP(const std::string& clientName, unsigned int queueSizeLimit); |
| 272 | ~MidiInWinUWP(void) override; |
| 273 | RtMidi::Api getCurrentApi(void) override { return RtMidi::WINDOWS_UWP; }; |
| 274 | void openPort(unsigned int portNumber, const std::string& portName) override; |
| 275 | void openVirtualPort(const std::string& portName) override; |
| 276 | void closePort(void) override; |
| 277 | void setClientName(const std::string& clientName) override; |
| 278 | void setPortName(const std::string& portName) override; |
| 279 | unsigned int getPortCount(void) override; |
| 280 | std::string getPortName(unsigned int portNumber) override; |
| 281 | double getMessage(std::vector<unsigned char>* message) override; |
| 282 | |
| 283 | protected: |
| 284 | void initialize(const std::string& clientName) override; |
| 285 | }; |
| 286 | |
| 287 | class MidiOutWinUWP : public MidiOutApi |
| 288 | { |
| 289 | public: |
| 290 | MidiOutWinUWP(const std::string& clientName); |
| 291 | ~MidiOutWinUWP(void) override; |
| 292 | RtMidi::Api getCurrentApi(void) override { return RtMidi::WINDOWS_UWP; }; |
| 293 | void openPort(unsigned int portNumber, const std::string& portName) override; |
| 294 | void openVirtualPort(const std::string& portName) override; |
| 295 | void closePort(void) override; |
| 296 | void setClientName(const std::string& clientName) override; |
| 297 | void setPortName(const std::string& portName) override; |
| 298 | unsigned int getPortCount(void) override; |
| 299 | std::string getPortName(unsigned int portNumber) override; |
| 300 | void sendMessage(const unsigned char* message, size_t size) override; |
| 301 | |
| 302 | protected: |
| 303 | void initialize(const std::string& clientName) override; |
| 304 | }; |
| 305 | |
| 306 | #endif |
| 307 | |
| 308 | #if defined(__WEB_MIDI_API__) |
| 309 | |
| 310 | class MidiInWeb : public MidiInApi |
| 311 | { |
| 312 | std::string client_name{}; |
| 313 | std::string web_midi_id{}; |
| 314 | int open_port_number{-1}; |
| 315 | |
| 316 | public: |
| 317 | MidiInWeb(const std::string &/*clientName*/, unsigned int queueSizeLimit ); |
| 318 | ~MidiInWeb( void ); |
| 319 | RtMidi::Api getCurrentApi( void ) { return RtMidi::WEB_MIDI_API; }; |
| 320 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 321 | void openVirtualPort( const std::string &portName ); |
| 322 | void closePort( void ); |
| 323 | void setClientName( const std::string &clientName ); |
| 324 | void setPortName( const std::string &portName ); |
| 325 | unsigned int getPortCount( void ); |
| 326 | std::string getPortName( unsigned int portNumber ); |
| 327 | |
| 328 | void onMidiMessage( uint8_t* data, double domHishResTimeStamp ); |
| 329 | |
| 330 | protected: |
| 331 | void initialize( const std::string& clientName ); |
| 332 | }; |
| 333 | |
| 334 | class MidiOutWeb: public MidiOutApi |
| 335 | { |
| 336 | std::string client_name{}; |
| 337 | std::string web_midi_id{}; |
| 338 | int open_port_number{-1}; |
| 339 | |
| 340 | public: |
| 341 | MidiOutWeb( const std::string &clientName ); |
| 342 | ~MidiOutWeb( void ); |
| 343 | RtMidi::Api getCurrentApi( void ) { return RtMidi::WEB_MIDI_API; }; |
| 344 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 345 | void openVirtualPort( const std::string &portName ); |
| 346 | void closePort( void ); |
| 347 | void setClientName( const std::string &clientName ); |
| 348 | void setPortName( const std::string &portName ); |
| 349 | unsigned int getPortCount( void ); |
| 350 | std::string getPortName( unsigned int portNumber ); |
| 351 | void sendMessage( const unsigned char *message, size_t size ); |
| 352 | |
| 353 | protected: |
| 354 | void initialize( const std::string& clientName ); |
| 355 | }; |
| 356 | |
| 357 | #endif |
| 358 | |
| 359 | #if defined(__AMIDI__) |
| 360 | |
| 361 | #define LOG_TAG "RtMidi" |
| 362 | #include <amidi/AMidi.h> |
| 363 | #include <android/log.h> |
| 364 | #include <pthread.h> |
| 365 | #include <atomic> |
| 366 | #include <string> |
| 367 | #include <vector> |
| 368 | #include <jni.h> |
| 369 | #include <unistd.h> |
| 370 | |
| 371 | class MidiInAndroid : public MidiInApi |
| 372 | { |
| 373 | public: |
| 374 | MidiInAndroid(const std::string &/*clientName*/, unsigned int queueSizeLimit ); |
| 375 | ~MidiInAndroid( void ); |
| 376 | RtMidi::Api getCurrentApi( void ) { return RtMidi::ANDROID_AMIDI; }; |
| 377 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 378 | void openVirtualPort( const std::string &portName ); |
| 379 | void closePort( void ); |
| 380 | void setClientName( const std::string &clientName ); |
| 381 | void setPortName( const std::string &portName ); |
| 382 | unsigned int getPortCount( void ); |
| 383 | std::string getPortName( unsigned int portNumber ); |
| 384 | |
| 385 | void onMidiMessage( uint8_t* data, double domHishResTimeStamp ); |
| 386 | |
| 387 | void initialize( const std::string& clientName ); |
| 388 | void connect(); |
| 389 | AMidiDevice* receiveDevice = NULL; |
| 390 | AMidiOutputPort* midiOutputPort = NULL; |
| 391 | pthread_t readThread; |
| 392 | std::atomic<bool> reading = ATOMIC_VAR_INIT(false); |
| 393 | static void* pollMidi(void* context); |
| 394 | double lastTime; |
| 395 | }; |
| 396 | |
| 397 | class MidiOutAndroid: public MidiOutApi |
| 398 | { |
| 399 | public: |
| 400 | MidiOutAndroid( const std::string &clientName ); |
| 401 | ~MidiOutAndroid( void ); |
| 402 | RtMidi::Api getCurrentApi( void ) { return RtMidi::ANDROID_AMIDI; }; |
| 403 | void openPort( unsigned int portNumber, const std::string &portName ); |
| 404 | void openVirtualPort( const std::string &portName ); |
| 405 | void closePort( void ); |
| 406 | void setClientName( const std::string &clientName ); |
| 407 | void setPortName( const std::string &portName ); |
| 408 | unsigned int getPortCount( void ); |
| 409 | std::string getPortName( unsigned int portNumber ); |
| 410 | void sendMessage( const unsigned char *message, size_t size ); |
| 411 | |
| 412 | void initialize( const std::string& clientName ); |
| 413 | void connect(); |
| 414 | AMidiDevice* sendDevice = NULL; |
| 415 | AMidiInputPort* midiInputPort = NULL; |
| 416 | }; |
| 417 | |
| 418 | #endif |
| 419 | |
| 420 | #if defined(__RTMIDI_DUMMY__) |
| 421 | |
| 422 | class MidiInDummy: public MidiInApi |
| 423 | { |
| 424 | public: |
| 425 | MidiInDummy( const std::string &/*clientName*/, unsigned int queueSizeLimit ) : MidiInApi( queueSizeLimit ) { errorString_ = "MidiInDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); } |
| 426 | RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; } |
| 427 | void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {} |
| 428 | void openVirtualPort( const std::string &/*portName*/ ) {} |
| 429 | void closePort( void ) {} |
| 430 | void setClientName( const std::string &/*clientName*/ ) {}; |
| 431 | void setPortName( const std::string &/*portName*/ ) {}; |
| 432 | unsigned int getPortCount( void ) { return 0; } |
| 433 | std::string getPortName( unsigned int /*portNumber*/ ) { return ""; } |
| 434 | |
| 435 | protected: |
| 436 | void initialize( const std::string& /*clientName*/ ) {} |
| 437 | }; |
| 438 | |
| 439 | class MidiOutDummy: public MidiOutApi |
| 440 | { |
| 441 | public: |
| 442 | MidiOutDummy( const std::string &/*clientName*/ ) { errorString_ = "MidiOutDummy: This class provides no functionality."; error( RtMidiError::WARNING, errorString_ ); } |
| 443 | RtMidi::Api getCurrentApi( void ) { return RtMidi::RTMIDI_DUMMY; } |
| 444 | void openPort( unsigned int /*portNumber*/, const std::string &/*portName*/ ) {} |
| 445 | void openVirtualPort( const std::string &/*portName*/ ) {} |
| 446 | void closePort( void ) {} |
| 447 | void setClientName( const std::string &/*clientName*/ ) {}; |
| 448 | void setPortName( const std::string &/*portName*/ ) {}; |
| 449 | unsigned int getPortCount( void ) { return 0; } |
| 450 | std::string getPortName( unsigned int /*portNumber*/ ) { return ""; } |
| 451 | void sendMessage( const unsigned char * /*message*/, size_t /*size*/ ) {} |
| 452 | |
| 453 | protected: |
| 454 | void initialize( const std::string& /*clientName*/ ) {} |
| 455 | }; |
| 456 | |
| 457 | #endif |
| 458 | |
| 459 | //*********************************************************************// |
| 460 | // RtMidi Definitions |
| 461 | //*********************************************************************// |
| 462 | |
| 463 | RtMidi :: RtMidi() |
| 464 | : rtapi_(0) |
| 465 | { |
| 466 | } |
| 467 | |
| 468 | RtMidi :: ~RtMidi() |
| 469 | { |
| 470 | delete rtapi_; |
| 471 | rtapi_ = 0; |
| 472 | } |
| 473 | |
| 474 | // (chuck 1.5.5.1 modification): commented out |
| 475 | //RtMidi::RtMidi(RtMidi&& other) noexcept { |
| 476 | // rtapi_ = other.rtapi_; |
| 477 | // other.rtapi_ = nullptr; |
| 478 | //} |
| 479 | |
| 480 | std::string RtMidi :: getVersion( void ) throw() |
| 481 | { |
| 482 | return std::string( RTMIDI_VERSION ); |
| 483 | } |
| 484 | |
| 485 | // Define API names and display names. |
| 486 | // Must be in same order as API enum. |
| 487 | extern "C" { |
| 488 | const char* rtmidi_api_names[][2] = { |
| 489 | { "unspecified" , "Unknown" }, |
| 490 | { "core" , "CoreMidi" }, |
| 491 | { "alsa" , "ALSA" }, |
| 492 | { "jack" , "Jack" }, |
| 493 | { "winmm" , "Windows MultiMedia" }, |
| 494 | { "dummy" , "Dummy" }, |
| 495 | { "web" , "Web MIDI API" }, |
| 496 | { "winuwp" , "Windows UWP" }, |
| 497 | { "amidi" , "Android MIDI API" }, |
| 498 | }; |
| 499 | const unsigned int rtmidi_num_api_names = |
| 500 | sizeof(rtmidi_api_names)/sizeof(rtmidi_api_names[0]); |
| 501 | |
| 502 | // The order here will control the order of RtMidi's API search in |
| 503 | // the constructor. |
| 504 | extern "C" const RtMidi::Api rtmidi_compiled_apis[] = { |
| 505 | #if defined(__MACOSX_CORE__) |
| 506 | RtMidi::MACOSX_CORE, |
| 507 | #endif |
| 508 | #if defined(__LINUX_ALSA__) |
| 509 | RtMidi::LINUX_ALSA, |
| 510 | #endif |
| 511 | #if defined(__UNIX_JACK__) |
| 512 | RtMidi::UNIX_JACK, |
| 513 | #endif |
| 514 | #if defined(__WINDOWS_MM__) |
| 515 | RtMidi::WINDOWS_MM, |
| 516 | #endif |
| 517 | #if defined(__WINDOWS_UWP__) |
| 518 | RtMidi::WINDOWS_UWP, |
| 519 | #endif |
| 520 | #if defined(__WEB_MIDI_API__) |
| 521 | RtMidi::WEB_MIDI_API, |
| 522 | #endif |
| 523 | #if defined(__WEB_MIDI_API__) |
| 524 | RtMidi::WEB_MIDI_API, |
| 525 | #endif |
| 526 | #if defined(__AMIDI__) |
| 527 | RtMidi::ANDROID_AMIDI, |
| 528 | #endif |
| 529 | RtMidi::UNSPECIFIED, |
| 530 | }; |
| 531 | extern "C" const unsigned int rtmidi_num_compiled_apis = |
| 532 | sizeof(rtmidi_compiled_apis)/sizeof(rtmidi_compiled_apis[0])-1; |
| 533 | } |
| 534 | |
| 535 | // This is a compile-time check that rtmidi_num_api_names == RtMidi::NUM_APIS. |
| 536 | // If the build breaks here, check that they match. |
| 537 | template<bool b> class StaticAssert { private: StaticAssert() {} }; |
| 538 | template<> class StaticAssert<true>{ public: StaticAssert() {} }; |
| 539 | class StaticAssertions { StaticAssertions() { |
| 540 | StaticAssert<rtmidi_num_api_names == RtMidi::NUM_APIS>(); |
| 541 | }}; |
| 542 | |
| 543 | void RtMidi :: getCompiledApi( std::vector<RtMidi::Api> &apis ) throw() |
| 544 | { |
| 545 | apis = std::vector<RtMidi::Api>(rtmidi_compiled_apis, |
| 546 | rtmidi_compiled_apis + rtmidi_num_compiled_apis); |
| 547 | } |
| 548 | |
| 549 | std::string RtMidi :: getApiName( RtMidi::Api api ) |
| 550 | { |
| 551 | if (api < RtMidi::UNSPECIFIED || api >= RtMidi::NUM_APIS) |
| 552 | return ""; |
| 553 | return rtmidi_api_names[api][0]; |
| 554 | } |
| 555 | |
| 556 | std::string RtMidi :: getApiDisplayName( RtMidi::Api api ) |
| 557 | { |
| 558 | if (api < RtMidi::UNSPECIFIED || api >= RtMidi::NUM_APIS) |
| 559 | return "Unknown"; |
| 560 | return rtmidi_api_names[api][1]; |
| 561 | } |
| 562 | |
| 563 | RtMidi::Api RtMidi :: getCompiledApiByName( const std::string &name ) |
| 564 | { |
| 565 | unsigned int i=0; |
| 566 | for (i = 0; i < rtmidi_num_compiled_apis; ++i) |
| 567 | if (name == rtmidi_api_names[rtmidi_compiled_apis[i]][0]) |
| 568 | return rtmidi_compiled_apis[i]; |
| 569 | return RtMidi::UNSPECIFIED; |
| 570 | } |
| 571 | |
| 572 | void RtMidi :: setClientName( const std::string &clientName ) |
| 573 | { |
| 574 | rtapi_->setClientName( clientName ); |
| 575 | } |
| 576 | |
| 577 | void RtMidi :: setPortName( const std::string &portName ) |
| 578 | { |
| 579 | rtapi_->setPortName( portName ); |
| 580 | } |
| 581 | |
| 582 | |
| 583 | //*********************************************************************// |
| 584 | // RtMidiIn Definitions |
| 585 | //*********************************************************************// |
| 586 | |
| 587 | void RtMidiIn :: openMidiApi( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit ) |
| 588 | { |
| 589 | delete rtapi_; |
| 590 | rtapi_ = 0; |
| 591 | |
| 592 | #if defined(__UNIX_JACK__) |
| 593 | if ( api == UNIX_JACK ) |
| 594 | rtapi_ = new MidiInJack( clientName, queueSizeLimit ); |
| 595 | #endif |
| 596 | #if defined(__LINUX_ALSA__) |
| 597 | if ( api == LINUX_ALSA ) |
| 598 | rtapi_ = new MidiInAlsa( clientName, queueSizeLimit ); |
| 599 | #endif |
| 600 | #if defined(__WINDOWS_MM__) |
| 601 | if ( api == WINDOWS_MM ) |
| 602 | rtapi_ = new MidiInWinMM( clientName, queueSizeLimit ); |
| 603 | #endif |
| 604 | #if defined(__WINDOWS_UWP__) |
| 605 | if (api == WINDOWS_UWP) |
| 606 | rtapi_ = new MidiInWinUWP(clientName, queueSizeLimit); |
| 607 | #endif |
| 608 | #if defined(__MACOSX_CORE__) |
| 609 | if ( api == MACOSX_CORE ) |
| 610 | rtapi_ = new MidiInCore( clientName, queueSizeLimit ); |
| 611 | #endif |
| 612 | #if defined(__WEB_MIDI_API__) |
| 613 | if ( api == WEB_MIDI_API ) |
| 614 | rtapi_ = new MidiInWeb( clientName, queueSizeLimit ); |
| 615 | #endif |
| 616 | #if defined(__AMIDI__) |
| 617 | if ( api == ANDROID_AMIDI ) |
| 618 | rtapi_ = new MidiInAndroid( clientName, queueSizeLimit ); |
| 619 | #endif |
| 620 | #if defined(__RTMIDI_DUMMY__) |
| 621 | if ( api == RTMIDI_DUMMY ) |
| 622 | rtapi_ = new MidiInDummy( clientName, queueSizeLimit ); |
| 623 | #endif |
| 624 | } |
| 625 | |
| 626 | RTMIDI_DLL_PUBLIC RtMidiIn :: RtMidiIn( RtMidi::Api api, const std::string &clientName, unsigned int queueSizeLimit ) |
| 627 | : RtMidi() |
| 628 | { |
| 629 | if ( api != UNSPECIFIED ) { |
| 630 | // Attempt to open the specified API. |
| 631 | openMidiApi( api, clientName, queueSizeLimit ); |
| 632 | if ( rtapi_ ) return; |
| 633 | |
| 634 | // No compiled support for specified API value. Issue a warning |
| 635 | // and continue as if no API was specified. |
| 636 | std::cerr << "\nRtMidiIn: no compiled support for specified API argument!\n\n" << std::endl; |
| 637 | } |
| 638 | |
| 639 | // Iterate through the compiled APIs and return as soon as we find |
| 640 | // one with at least one port or we reach the end of the list. |
| 641 | std::vector< RtMidi::Api > apis; |
| 642 | getCompiledApi( apis ); |
| 643 | for ( unsigned int i=0; i<apis.size(); i++ ) { |
| 644 | openMidiApi( apis[i], clientName, queueSizeLimit ); |
| 645 | if ( rtapi_ && rtapi_->getPortCount() ) break; |
| 646 | } |
| 647 | |
| 648 | if ( rtapi_ ) return; |
| 649 | |
| 650 | // It should not be possible to get here because the preprocessor |
| 651 | // definition __RTMIDI_DUMMY__ is automatically defined if no |
| 652 | // API-specific definitions are passed to the compiler. But just in |
| 653 | // case something weird happens, we'll throw an error. |
| 654 | std::string errorText = "RtMidiIn: no compiled API support found ... critical error!!"; |
| 655 | throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) ); |
| 656 | } |
| 657 | |
| 658 | RtMidiIn :: ~RtMidiIn() throw() |
| 659 | { |
| 660 | } |
| 661 | |
| 662 | |
| 663 | //*********************************************************************// |
| 664 | // RtMidiOut Definitions |
| 665 | //*********************************************************************// |
| 666 | |
| 667 | void RtMidiOut :: openMidiApi( RtMidi::Api api, const std::string &clientName ) |
| 668 | { |
| 669 | delete rtapi_; |
| 670 | rtapi_ = 0; |
| 671 | |
| 672 | #if defined(__UNIX_JACK__) |
| 673 | if ( api == UNIX_JACK ) |
| 674 | rtapi_ = new MidiOutJack( clientName ); |
| 675 | #endif |
| 676 | #if defined(__LINUX_ALSA__) |
| 677 | if ( api == LINUX_ALSA ) |
| 678 | rtapi_ = new MidiOutAlsa( clientName ); |
| 679 | #endif |
| 680 | #if defined(__WINDOWS_MM__) |
| 681 | if ( api == WINDOWS_MM ) |
| 682 | rtapi_ = new MidiOutWinMM( clientName ); |
| 683 | #endif |
| 684 | #if defined(__WINDOWS_UWP__) |
| 685 | if (api == WINDOWS_UWP) |
| 686 | rtapi_ = new MidiOutWinUWP(clientName); |
| 687 | #endif |
| 688 | #if defined(__MACOSX_CORE__) |
| 689 | if ( api == MACOSX_CORE ) |
| 690 | rtapi_ = new MidiOutCore( clientName ); |
| 691 | #endif |
| 692 | #if defined(__WEB_MIDI_API__) |
| 693 | if ( api == WEB_MIDI_API ) |
| 694 | rtapi_ = new MidiOutWeb( clientName ); |
| 695 | #endif |
| 696 | #if defined(__AMIDI__) |
| 697 | if ( api == ANDROID_AMIDI ) |
| 698 | rtapi_ = new MidiOutAndroid( clientName ); |
| 699 | #endif |
| 700 | #if defined(__RTMIDI_DUMMY__) |
| 701 | if ( api == RTMIDI_DUMMY ) |
| 702 | rtapi_ = new MidiOutDummy( clientName ); |
| 703 | #endif |
| 704 | } |
| 705 | |
| 706 | RTMIDI_DLL_PUBLIC RtMidiOut :: RtMidiOut( RtMidi::Api api, const std::string &clientName) |
| 707 | { |
| 708 | if ( api != UNSPECIFIED ) { |
| 709 | // Attempt to open the specified API. |
| 710 | openMidiApi( api, clientName ); |
| 711 | if ( rtapi_ ) return; |
| 712 | |
| 713 | // No compiled support for specified API value. Issue a warning |
| 714 | // and continue as if no API was specified. |
| 715 | std::cerr << "\nRtMidiOut: no compiled support for specified API argument!\n\n" << std::endl; |
| 716 | } |
| 717 | |
| 718 | // Iterate through the compiled APIs and return as soon as we find |
| 719 | // one with at least one port or we reach the end of the list. |
| 720 | std::vector< RtMidi::Api > apis; |
| 721 | getCompiledApi( apis ); |
| 722 | for ( unsigned int i=0; i<apis.size(); i++ ) { |
| 723 | openMidiApi( apis[i], clientName ); |
| 724 | if ( rtapi_ && rtapi_->getPortCount() ) break; |
| 725 | } |
| 726 | |
| 727 | if ( rtapi_ ) return; |
| 728 | |
| 729 | // It should not be possible to get here because the preprocessor |
| 730 | // definition __RTMIDI_DUMMY__ is automatically defined if no |
| 731 | // API-specific definitions are passed to the compiler. But just in |
| 732 | // case something weird happens, we'll thrown an error. |
| 733 | std::string errorText = "RtMidiOut: no compiled API support found ... critical error!!"; |
| 734 | throw( RtMidiError( errorText, RtMidiError::UNSPECIFIED ) ); |
| 735 | } |
| 736 | |
| 737 | RtMidiOut :: ~RtMidiOut() throw() |
| 738 | { |
| 739 | } |
| 740 | |
| 741 | //*********************************************************************// |
| 742 | // Common MidiApi Definitions |
| 743 | //*********************************************************************// |
| 744 | |
| 745 | MidiApi :: MidiApi( void ) |
| 746 | : apiData_( 0 ), connected_( false ), errorCallback_(0), firstErrorOccurred_(false), errorCallbackUserData_(0) |
| 747 | { |
| 748 | } |
| 749 | |
| 750 | MidiApi :: ~MidiApi( void ) |
| 751 | { |
| 752 | } |
| 753 | |
| 754 | void MidiApi :: setErrorCallback( RtMidiErrorCallback errorCallback, void *userData = 0 ) |
| 755 | { |
| 756 | errorCallback_ = errorCallback; |
| 757 | errorCallbackUserData_ = userData; |
| 758 | } |
| 759 | |
| 760 | void MidiApi :: error( RtMidiError::Type type, std::string errorString ) |
| 761 | { |
| 762 | if ( errorCallback_ ) { |
| 763 | |
| 764 | if ( firstErrorOccurred_ ) |
| 765 | return; |
| 766 | |
| 767 | firstErrorOccurred_ = true; |
| 768 | const std::string errorMessage = errorString; |
| 769 | |
| 770 | errorCallback_( type, errorMessage, errorCallbackUserData_ ); |
| 771 | firstErrorOccurred_ = false; |
| 772 | return; |
| 773 | } |
| 774 | |
| 775 | if ( type == RtMidiError::WARNING ) { |
| 776 | std::cerr << '\n' << errorString << "\n\n"; |
| 777 | } |
| 778 | else if ( type == RtMidiError::DEBUG_WARNING ) { |
| 779 | #if defined(__RTMIDI_DEBUG__) |
| 780 | std::cerr << '\n' << errorString << "\n\n"; |
| 781 | #endif |
| 782 | } |
| 783 | else { |
| 784 | std::cerr << '\n' << errorString << "\n\n"; |
| 785 | throw RtMidiError( errorString, type ); |
| 786 | } |
| 787 | } |
| 788 | |
| 789 | //*********************************************************************// |
| 790 | // Common MidiInApi Definitions |
| 791 | //*********************************************************************// |
| 792 | |
| 793 | MidiInApi :: MidiInApi( unsigned int queueSizeLimit ) |
| 794 | : MidiApi() |
| 795 | { |
| 796 | // Allocate the MIDI queue. |
| 797 | inputData_.queue.ringSize = queueSizeLimit; |
| 798 | if ( inputData_.queue.ringSize > 0 ) |
| 799 | inputData_.queue.ring = new MidiMessage[ inputData_.queue.ringSize ]; |
| 800 | } |
| 801 | |
| 802 | MidiInApi :: ~MidiInApi( void ) |
| 803 | { |
| 804 | // Delete the MIDI queue. |
| 805 | if ( inputData_.queue.ringSize > 0 ) delete [] inputData_.queue.ring; |
| 806 | } |
| 807 | |
| 808 | void MidiInApi :: setCallback( RtMidiIn::RtMidiCallback callback, void *userData ) |
| 809 | { |
| 810 | if ( inputData_.usingCallback ) { |
| 811 | errorString_ = "MidiInApi::setCallback: a callback function is already set!"; |
| 812 | error( RtMidiError::WARNING, errorString_ ); |
| 813 | return; |
| 814 | } |
| 815 | |
| 816 | if ( !callback ) { |
| 817 | errorString_ = "RtMidiIn::setCallback: callback function value is invalid!"; |
| 818 | error( RtMidiError::WARNING, errorString_ ); |
| 819 | return; |
| 820 | } |
| 821 | |
| 822 | inputData_.userCallback = callback; |
| 823 | inputData_.userData = userData; |
| 824 | inputData_.usingCallback = true; |
| 825 | } |
| 826 | |
| 827 | void MidiInApi :: cancelCallback() |
| 828 | { |
| 829 | if ( !inputData_.usingCallback ) { |
| 830 | errorString_ = "RtMidiIn::cancelCallback: no callback function was set!"; |
| 831 | error( RtMidiError::WARNING, errorString_ ); |
| 832 | return; |
| 833 | } |
| 834 | |
| 835 | inputData_.userCallback = 0; |
| 836 | inputData_.userData = 0; |
| 837 | inputData_.usingCallback = false; |
| 838 | } |
| 839 | |
| 840 | void MidiInApi :: ignoreTypes( bool midiSysex, bool midiTime, bool midiSense ) |
| 841 | { |
| 842 | inputData_.ignoreFlags = 0; |
| 843 | if ( midiSysex ) inputData_.ignoreFlags = 0x01; |
| 844 | if ( midiTime ) inputData_.ignoreFlags |= 0x02; |
| 845 | if ( midiSense ) inputData_.ignoreFlags |= 0x04; |
| 846 | } |
| 847 | |
| 848 | double MidiInApi :: getMessage( std::vector<unsigned char> *message ) |
| 849 | { |
| 850 | message->clear(); |
| 851 | |
| 852 | if ( inputData_.usingCallback ) { |
| 853 | errorString_ = "RtMidiIn::getNextMessage: a user callback is currently set for this port."; |
| 854 | error( RtMidiError::WARNING, errorString_ ); |
| 855 | return 0.0; |
| 856 | } |
| 857 | |
| 858 | double timeStamp; |
| 859 | if ( !inputData_.queue.pop( message, &timeStamp ) ) |
| 860 | return 0.0; |
| 861 | |
| 862 | return timeStamp; |
| 863 | } |
| 864 | |
| 865 | void MidiInApi :: setBufferSize( unsigned int size, unsigned int count ) |
| 866 | { |
| 867 | inputData_.bufferSize = size; |
| 868 | inputData_.bufferCount = count; |
| 869 | } |
| 870 | |
| 871 | unsigned int MidiInApi::MidiQueue::size( unsigned int *__back, |
| 872 | unsigned int *__front ) |
| 873 | { |
| 874 | // Access back/front members exactly once and make stack copies for |
| 875 | // size calculation |
| 876 | unsigned int _back = back, _front = front, _size; |
| 877 | if ( _back >= _front ) |
| 878 | _size = _back - _front; |
| 879 | else |
| 880 | _size = ringSize - _front + _back; |
| 881 | |
| 882 | // Return copies of back/front so no new and unsynchronized accesses |
| 883 | // to member variables are needed. |
| 884 | if ( __back ) *__back = _back; |
| 885 | if ( __front ) *__front = _front; |
| 886 | return _size; |
| 887 | } |
| 888 | |
| 889 | // As long as we haven't reached our queue size limit, push the message. |
| 890 | bool MidiInApi::MidiQueue::push( const MidiInApi::MidiMessage& msg ) |
| 891 | { |
| 892 | // Local stack copies of front/back |
| 893 | unsigned int _back, _front, _size; |
| 894 | |
| 895 | // Get back/front indexes exactly once and calculate current size |
| 896 | _size = size( &_back, &_front ); |
| 897 | |
| 898 | if ( _size < ringSize-1 ) |
| 899 | { |
| 900 | ring[_back] = msg; |
| 901 | back = (back+1)%ringSize; |
| 902 | return true; |
| 903 | } |
| 904 | |
| 905 | return false; |
| 906 | } |
| 907 | |
| 908 | bool MidiInApi::MidiQueue::pop( std::vector<unsigned char> *msg, double* timeStamp ) |
| 909 | { |
| 910 | // Local stack copies of front/back |
| 911 | unsigned int _back, _front, _size; |
| 912 | |
| 913 | // Get back/front indexes exactly once and calculate current size |
| 914 | _size = size( &_back, &_front ); |
| 915 | |
| 916 | if ( _size == 0 ) |
| 917 | return false; |
| 918 | |
| 919 | // Copy queued message to the vector pointer argument and then "pop" it. |
| 920 | msg->assign( ring[_front].bytes.begin(), ring[_front].bytes.end() ); |
| 921 | *timeStamp = ring[_front].timeStamp; |
| 922 | |
| 923 | // Update front |
| 924 | front = (front+1)%ringSize; |
| 925 | return true; |
| 926 | } |
| 927 | |
| 928 | //*********************************************************************// |
| 929 | // Common MidiOutApi Definitions |
| 930 | //*********************************************************************// |
| 931 | |
| 932 | MidiOutApi :: MidiOutApi( void ) |
| 933 | : MidiApi() |
| 934 | { |
| 935 | } |
| 936 | |
| 937 | MidiOutApi :: ~MidiOutApi( void ) |
| 938 | { |
| 939 | } |
| 940 | |
| 941 | // *************************************************** // |
| 942 | // |
| 943 | // OS/API-specific methods. |
| 944 | // |
| 945 | // *************************************************** // |
| 946 | |
| 947 | #if defined(__MACOSX_CORE__) |
| 948 | |
| 949 | // The CoreMIDI API is based on the use of a callback function for |
| 950 | // MIDI input. We convert the system specific time stamps to delta |
| 951 | // time values. |
| 952 | |
| 953 | // These are not available on iOS. |
| 954 | #if (TARGET_OS_IPHONE == 0) |
| 955 | #include <CoreAudio/HostTime.h> |
| 956 | #include <CoreServices/CoreServices.h> |
| 957 | #endif |
| 958 | |
| 959 | // A structure to hold variables related to the CoreMIDI API |
| 960 | // implementation. |
| 961 | struct CoreMidiData { |
| 962 | MIDIClientRef client; |
| 963 | MIDIPortRef port; |
| 964 | MIDIEndpointRef endpoint; |
| 965 | MIDIEndpointRef destinationId; |
| 966 | unsigned long long lastTime; |
| 967 | MIDISysexSendRequest sysexreq; |
| 968 | }; |
| 969 | |
| 970 | static MIDIClientRef CoreMidiClientSingleton = 0; |
| 971 | |
| 972 | void RtMidi_setCoreMidiClientSingleton(MIDIClientRef client){ |
| 973 | CoreMidiClientSingleton = client; |
| 974 | } |
| 975 | |
| 976 | void RtMidi_disposeCoreMidiClientSingleton(){ |
| 977 | if (CoreMidiClientSingleton == 0){ |
| 978 | return; |
| 979 | } |
| 980 | MIDIClientDispose( CoreMidiClientSingleton ); |
| 981 | CoreMidiClientSingleton = 0; |
| 982 | } |
| 983 | |
| 984 | //*********************************************************************// |
| 985 | // API: OS-X |
| 986 | // Class Definitions: MidiInCore |
| 987 | //*********************************************************************// |
| 988 | |
| 989 | static void midiInputCallback( const MIDIPacketList *list, void *procRef, void */*srcRef*/ ) |
| 990 | { |
| 991 | MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (procRef); |
| 992 | CoreMidiData *apiData = static_cast<CoreMidiData *> (data->apiData); |
| 993 | |
| 994 | unsigned char status; |
| 995 | unsigned short nBytes, iByte, size; |
| 996 | unsigned long long time; |
| 997 | |
| 998 | bool& continueSysex = data->continueSysex; |
| 999 | MidiInApi::MidiMessage& message = data->message; |
| 1000 | |
| 1001 | const MIDIPacket *packet = &list->packet[0]; |
| 1002 | for ( unsigned int i=0; i<list->numPackets; ++i ) { |
| 1003 | |
| 1004 | // My interpretation of the CoreMIDI documentation: all message |
| 1005 | // types, except sysex, are complete within a packet and there may |
| 1006 | // be several of them in a single packet. Sysex messages can be |
| 1007 | // broken across multiple packets and PacketLists but are bundled |
| 1008 | // alone within each packet (these packets do not contain other |
| 1009 | // message types). If sysex messages are split across multiple |
| 1010 | // MIDIPacketLists, they must be handled by multiple calls to this |
| 1011 | // function. |
| 1012 | |
| 1013 | nBytes = packet->length; |
| 1014 | if ( nBytes == 0 ) { |
| 1015 | packet = MIDIPacketNext( packet ); |
| 1016 | continue; |
| 1017 | } |
| 1018 | |
| 1019 | // Calculate time stamp. |
| 1020 | if ( data->firstMessage ) { |
| 1021 | message.timeStamp = 0.0; |
| 1022 | data->firstMessage = false; |
| 1023 | } |
| 1024 | else { |
| 1025 | time = packet->timeStamp; |
| 1026 | if ( time == 0 ) { // this happens when receiving asynchronous sysex messages |
| 1027 | time = AudioGetCurrentHostTime(); |
| 1028 | } |
| 1029 | time -= apiData->lastTime; |
| 1030 | time = AudioConvertHostTimeToNanos( time ); |
| 1031 | if ( !continueSysex ) |
| 1032 | message.timeStamp = time * 0.000000001; |
| 1033 | } |
| 1034 | |
| 1035 | // Track whether any non-filtered messages were found in this |
| 1036 | // packet for timestamp calculation |
| 1037 | bool foundNonFiltered = false; |
| 1038 | |
| 1039 | iByte = 0; |
| 1040 | if ( continueSysex ) { |
| 1041 | // We have a continuing, segmented sysex message. |
| 1042 | if ( !( data->ignoreFlags & 0x01 ) ) { |
| 1043 | // If we're not ignoring sysex messages, copy the entire packet. |
| 1044 | for ( unsigned int j=0; j<nBytes; ++j ) |
| 1045 | message.bytes.push_back( packet->data[j] ); |
| 1046 | } |
| 1047 | continueSysex = packet->data[nBytes-1] != 0xF7; |
| 1048 | |
| 1049 | if ( !( data->ignoreFlags & 0x01 ) && !continueSysex ) { |
| 1050 | // If not a continuing sysex message, invoke the user callback function or queue the message. |
| 1051 | if ( data->usingCallback ) { |
| 1052 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; |
| 1053 | callback( message.timeStamp, &message.bytes, data->userData ); |
| 1054 | } |
| 1055 | else { |
| 1056 | // As long as we haven't reached our queue size limit, push the message. |
| 1057 | if ( !data->queue.push( message ) ) |
| 1058 | std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; |
| 1059 | } |
| 1060 | message.bytes.clear(); |
| 1061 | } |
| 1062 | } |
| 1063 | else { |
| 1064 | while ( iByte < nBytes ) { |
| 1065 | size = 0; |
| 1066 | // We are expecting that the next byte in the packet is a status byte. |
| 1067 | status = packet->data[iByte]; |
| 1068 | if ( !(status & 0x80) ) break; |
| 1069 | // Determine the number of bytes in the MIDI message. |
| 1070 | if ( status < 0xC0 ) size = 3; |
| 1071 | else if ( status < 0xE0 ) size = 2; |
| 1072 | else if ( status < 0xF0 ) size = 3; |
| 1073 | else if ( status == 0xF0 ) { |
| 1074 | // A MIDI sysex |
| 1075 | if ( data->ignoreFlags & 0x01 ) { |
| 1076 | size = 0; |
| 1077 | iByte = nBytes; |
| 1078 | } |
| 1079 | else size = nBytes - iByte; |
| 1080 | continueSysex = packet->data[nBytes-1] != 0xF7; |
| 1081 | } |
| 1082 | else if ( status == 0xF1 ) { |
| 1083 | // A MIDI time code message |
| 1084 | if ( data->ignoreFlags & 0x02 ) { |
| 1085 | size = 0; |
| 1086 | iByte += 2; |
| 1087 | } |
| 1088 | else size = 2; |
| 1089 | } |
| 1090 | else if ( status == 0xF2 ) size = 3; |
| 1091 | else if ( status == 0xF3 ) size = 2; |
| 1092 | else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) { |
| 1093 | // A MIDI timing tick message and we're ignoring it. |
| 1094 | size = 0; |
| 1095 | iByte += 1; |
| 1096 | } |
| 1097 | else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) { |
| 1098 | // A MIDI active sensing message and we're ignoring it. |
| 1099 | size = 0; |
| 1100 | iByte += 1; |
| 1101 | } |
| 1102 | else size = 1; |
| 1103 | |
| 1104 | // Copy the MIDI data to our vector. |
| 1105 | if ( size ) { |
| 1106 | foundNonFiltered = true; |
| 1107 | message.bytes.assign( &packet->data[iByte], &packet->data[iByte+size] ); |
| 1108 | if ( !continueSysex ) { |
| 1109 | // If not a continuing sysex message, invoke the user callback function or queue the message. |
| 1110 | if ( data->usingCallback ) { |
| 1111 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; |
| 1112 | callback( message.timeStamp, &message.bytes, data->userData ); |
| 1113 | } |
| 1114 | else { |
| 1115 | // As long as we haven't reached our queue size limit, push the message. |
| 1116 | if ( !data->queue.push( message ) ) |
| 1117 | std::cerr << "\nMidiInCore: message queue limit reached!!\n\n"; |
| 1118 | } |
| 1119 | message.bytes.clear(); |
| 1120 | // All subsequent messages within same MIDI packet will have time delta 0 |
| 1121 | message.timeStamp = 0.0; |
| 1122 | } |
| 1123 | iByte += size; |
| 1124 | } |
| 1125 | } |
| 1126 | } |
| 1127 | |
| 1128 | // Save the time of the last non-filtered message |
| 1129 | if ( foundNonFiltered ) { |
| 1130 | apiData->lastTime = packet->timeStamp; |
| 1131 | if ( apiData->lastTime == 0 ) { // this happens when receiving asynchronous sysex messages |
| 1132 | apiData->lastTime = AudioGetCurrentHostTime(); |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | packet = MIDIPacketNext(packet); |
| 1137 | } |
| 1138 | } |
| 1139 | |
| 1140 | MidiInCore :: MidiInCore( const std::string &clientName, unsigned int queueSizeLimit ) |
| 1141 | : MidiInApi( queueSizeLimit ) |
| 1142 | { |
| 1143 | MidiInCore::initialize( clientName ); |
| 1144 | } |
| 1145 | |
| 1146 | MidiInCore :: ~MidiInCore( void ) |
| 1147 | { |
| 1148 | // Close a connection if it exists. |
| 1149 | MidiInCore::closePort(); |
| 1150 | |
| 1151 | // Cleanup. |
| 1152 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1153 | if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); |
| 1154 | delete data; |
| 1155 | } |
| 1156 | |
| 1157 | MIDIClientRef MidiInCore::getCoreMidiClientSingleton(const std::string& clientName) throw() { |
| 1158 | |
| 1159 | if (CoreMidiClientSingleton == 0){ |
| 1160 | // Set up our client. |
| 1161 | MIDIClientRef client; |
| 1162 | |
| 1163 | CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ); |
| 1164 | OSStatus result = MIDIClientCreate(name, NULL, NULL, &client ); |
| 1165 | if ( result != noErr ) { |
| 1166 | std::ostringstream ost; |
| 1167 | ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ")."; |
| 1168 | errorString_ = ost.str(); |
| 1169 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1170 | return 0; |
| 1171 | } |
| 1172 | CFRelease( name ); |
| 1173 | |
| 1174 | CoreMidiClientSingleton = client; |
| 1175 | } |
| 1176 | |
| 1177 | return CoreMidiClientSingleton; |
| 1178 | } |
| 1179 | |
| 1180 | void MidiInCore :: initialize( const std::string& clientName ) |
| 1181 | { |
| 1182 | // Set up our client. |
| 1183 | MIDIClientRef client = getCoreMidiClientSingleton(clientName); |
| 1184 | |
| 1185 | // Save our api-specific connection information. |
| 1186 | CoreMidiData *data = (CoreMidiData *) new CoreMidiData; |
| 1187 | data->client = client; |
| 1188 | data->endpoint = 0; |
| 1189 | apiData_ = (void *) data; |
| 1190 | inputData_.apiData = (void *) data; |
| 1191 | } |
| 1192 | |
| 1193 | void MidiInCore :: openPort( unsigned int portNumber, const std::string &portName ) |
| 1194 | { |
| 1195 | if ( connected_ ) { |
| 1196 | errorString_ = "MidiInCore::openPort: a valid connection already exists!"; |
| 1197 | error( RtMidiError::WARNING, errorString_ ); |
| 1198 | return; |
| 1199 | } |
| 1200 | |
| 1201 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1202 | // (chuck 1.5.5.1 modification): changed `auto` to `long` |
| 1203 | long nSrc = MIDIGetNumberOfSources(); |
| 1204 | if ( nSrc < 1 ) { |
| 1205 | errorString_ = "MidiInCore::openPort: no MIDI input sources found!"; |
| 1206 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 1207 | return; |
| 1208 | } |
| 1209 | |
| 1210 | if ( portNumber >= nSrc ) { |
| 1211 | std::ostringstream ost; |
| 1212 | ost << "MidiInCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 1213 | errorString_ = ost.str(); |
| 1214 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 1215 | return; |
| 1216 | } |
| 1217 | |
| 1218 | MIDIPortRef port; |
| 1219 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1220 | CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); |
| 1221 | OSStatus result = MIDIInputPortCreate( data->client, |
| 1222 | portNameRef, |
| 1223 | midiInputCallback, (void *)&inputData_, &port ); |
| 1224 | CFRelease( portNameRef ); |
| 1225 | |
| 1226 | if ( result != noErr ) { |
| 1227 | errorString_ = "MidiInCore::openPort: error creating OS-X MIDI input port."; |
| 1228 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1229 | return; |
| 1230 | } |
| 1231 | |
| 1232 | // Get the desired input source identifier. |
| 1233 | MIDIEndpointRef endpoint = MIDIGetSource( portNumber ); |
| 1234 | if ( endpoint == 0 ) { |
| 1235 | MIDIPortDispose( port ); |
| 1236 | errorString_ = "MidiInCore::openPort: error getting MIDI input source reference."; |
| 1237 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1238 | return; |
| 1239 | } |
| 1240 | |
| 1241 | // Make the connection. |
| 1242 | result = MIDIPortConnectSource( port, endpoint, NULL ); |
| 1243 | if ( result != noErr ) { |
| 1244 | MIDIPortDispose( port ); |
| 1245 | errorString_ = "MidiInCore::openPort: error connecting OS-X MIDI input port."; |
| 1246 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1247 | return; |
| 1248 | } |
| 1249 | |
| 1250 | // Save our api-specific port information. |
| 1251 | data->port = port; |
| 1252 | |
| 1253 | connected_ = true; |
| 1254 | } |
| 1255 | |
| 1256 | void MidiInCore :: openVirtualPort( const std::string &portName ) |
| 1257 | { |
| 1258 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1259 | |
| 1260 | // Create a virtual MIDI input destination. |
| 1261 | MIDIEndpointRef endpoint; |
| 1262 | CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); |
| 1263 | OSStatus result = MIDIDestinationCreate( data->client, |
| 1264 | portNameRef, |
| 1265 | midiInputCallback, (void *)&inputData_, &endpoint ); |
| 1266 | CFRelease( portNameRef ); |
| 1267 | |
| 1268 | if ( result != noErr ) { |
| 1269 | errorString_ = "MidiInCore::openVirtualPort: error creating virtual OS-X MIDI destination."; |
| 1270 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1271 | return; |
| 1272 | } |
| 1273 | |
| 1274 | // Save our api-specific connection information. |
| 1275 | data->endpoint = endpoint; |
| 1276 | } |
| 1277 | |
| 1278 | void MidiInCore :: closePort( void ) |
| 1279 | { |
| 1280 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1281 | |
| 1282 | if ( data->endpoint ) { |
| 1283 | MIDIEndpointDispose( data->endpoint ); |
| 1284 | data->endpoint = 0; |
| 1285 | } |
| 1286 | |
| 1287 | if ( data->port ) { |
| 1288 | MIDIPortDispose( data->port ); |
| 1289 | data->port = 0; |
| 1290 | } |
| 1291 | |
| 1292 | connected_ = false; |
| 1293 | } |
| 1294 | |
| 1295 | void MidiInCore :: setClientName ( const std::string& ) |
| 1296 | { |
| 1297 | |
| 1298 | errorString_ = "MidiInCore::setClientName: this function is not implemented for the MACOSX_CORE API!"; |
| 1299 | error( RtMidiError::WARNING, errorString_ ); |
| 1300 | |
| 1301 | } |
| 1302 | |
| 1303 | void MidiInCore :: setPortName ( const std::string& ) |
| 1304 | { |
| 1305 | |
| 1306 | errorString_ = "MidiInCore::setPortName: this function is not implemented for the MACOSX_CORE API!"; |
| 1307 | error( RtMidiError::WARNING, errorString_ ); |
| 1308 | |
| 1309 | } |
| 1310 | |
| 1311 | unsigned int MidiInCore :: getPortCount() |
| 1312 | { |
| 1313 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1314 | return static_cast<unsigned int> (MIDIGetNumberOfSources()); |
| 1315 | } |
| 1316 | |
| 1317 | // This function was submitted by Douglas Casey Tucker and apparently |
| 1318 | // derived largely from PortMidi. |
| 1319 | CFStringRef CreateEndpointName( MIDIEndpointRef endpoint, bool isExternal ) |
| 1320 | { |
| 1321 | CFMutableStringRef result = CFStringCreateMutable( NULL, 0 ); |
| 1322 | CFStringRef str; |
| 1323 | |
| 1324 | // Begin with the endpoint's name. |
| 1325 | str = NULL; |
| 1326 | MIDIObjectGetStringProperty( endpoint, kMIDIPropertyName, &str ); |
| 1327 | if ( str != NULL ) { |
| 1328 | CFStringAppend( result, str ); |
| 1329 | CFRelease(str); |
| 1330 | } |
| 1331 | |
| 1332 | // some MIDI devices have a leading space in endpoint name. trim |
| 1333 | CFStringTrim(result, CFSTR(" ")); |
| 1334 | |
| 1335 | MIDIEntityRef entity = 0; |
| 1336 | MIDIEndpointGetEntity( endpoint, &entity ); |
| 1337 | if ( entity == 0 ) |
| 1338 | // probably virtual |
| 1339 | return result; |
| 1340 | |
| 1341 | if ( CFStringGetLength( result ) == 0 ) { |
| 1342 | // endpoint name has zero length -- try the entity |
| 1343 | str = NULL; |
| 1344 | MIDIObjectGetStringProperty( entity, kMIDIPropertyName, &str ); |
| 1345 | if ( str != NULL ) { |
| 1346 | CFStringAppend( result, str ); |
| 1347 | } |
| 1348 | } |
| 1349 | // now consider the device's name |
| 1350 | MIDIDeviceRef device = 0; |
| 1351 | MIDIEntityGetDevice( entity, &device ); |
| 1352 | if ( device == 0 ) |
| 1353 | return result; |
| 1354 | |
| 1355 | str = NULL; |
| 1356 | MIDIObjectGetStringProperty( device, kMIDIPropertyName, &str ); |
| 1357 | if ( CFStringGetLength( result ) == 0 ) { |
| 1358 | CFRelease( result ); |
| 1359 | CFRetain( str ); |
| 1360 | return str; |
| 1361 | } |
| 1362 | if ( str != NULL ) { |
| 1363 | // if an external device has only one entity, throw away |
| 1364 | // the endpoint name and just use the device name |
| 1365 | if ( isExternal && MIDIDeviceGetNumberOfEntities( device ) < 2 ) { |
| 1366 | CFRelease( result ); |
| 1367 | CFRetain( str ); |
| 1368 | return str; |
| 1369 | } else { |
| 1370 | if ( CFStringGetLength( str ) == 0 ) { |
| 1371 | return result; |
| 1372 | } |
| 1373 | // does the entity name already start with the device name? |
| 1374 | // (some drivers do this though they shouldn't) |
| 1375 | // if so, do not prepend |
| 1376 | if ( CFStringCompareWithOptions( result, /* endpoint name */ |
| 1377 | str /* device name */, |
| 1378 | CFRangeMake(0, CFStringGetLength( str ) ), 0 ) != kCFCompareEqualTo ) { |
| 1379 | // prepend the device name to the entity name |
| 1380 | if ( CFStringGetLength( result ) > 0 ) |
| 1381 | CFStringInsert( result, 0, CFSTR(" ") ); |
| 1382 | |
| 1383 | CFStringInsert( result, 0, str ); |
| 1384 | CFRelease(str); |
| 1385 | } |
| 1386 | } |
| 1387 | } |
| 1388 | return result; |
| 1389 | } |
| 1390 | |
| 1391 | // This function was submitted by Douglas Casey Tucker and apparently |
| 1392 | // derived largely from PortMidi. |
| 1393 | static CFStringRef CreateConnectedEndpointName( MIDIEndpointRef endpoint ) |
| 1394 | { |
| 1395 | CFMutableStringRef result = CFStringCreateMutable( NULL, 0 ); |
| 1396 | CFStringRef str; |
| 1397 | OSStatus err; |
| 1398 | int i; |
| 1399 | |
| 1400 | // Does the endpoint have connections? |
| 1401 | CFDataRef connections = NULL; |
| 1402 | size_t nConnected = 0; |
| 1403 | bool anyStrings = false; |
| 1404 | err = MIDIObjectGetDataProperty( endpoint, kMIDIPropertyConnectionUniqueID, &connections ); |
| 1405 | if ( connections != NULL ) { |
| 1406 | // It has connections, follow them |
| 1407 | // Concatenate the names of all connected devices |
| 1408 | nConnected = CFDataGetLength( connections ) / sizeof(MIDIUniqueID); |
| 1409 | if ( nConnected ) { |
| 1410 | const SInt32 *pid = (const SInt32 *)(CFDataGetBytePtr(connections)); |
| 1411 | for ( i=0; i<nConnected; ++i, ++pid ) { |
| 1412 | MIDIUniqueID id = EndianS32_BtoN( *pid ); |
| 1413 | MIDIObjectRef connObject; |
| 1414 | MIDIObjectType connObjectType; |
| 1415 | err = MIDIObjectFindByUniqueID( id, &connObject, &connObjectType ); |
| 1416 | if ( err == noErr ) { |
| 1417 | if ( connObjectType == kMIDIObjectType_ExternalSource || |
| 1418 | connObjectType == kMIDIObjectType_ExternalDestination ) { |
| 1419 | // Connected to an external device's endpoint (10.3 and later). |
| 1420 | str = CreateEndpointName( (MIDIEndpointRef)(connObject), true ); |
| 1421 | } else { |
| 1422 | // Connected to an external device (10.2) (or something else, catch- |
| 1423 | str = NULL; |
| 1424 | MIDIObjectGetStringProperty( connObject, kMIDIPropertyName, &str ); |
| 1425 | if ( str ) CFRetain ( str ); |
| 1426 | } |
| 1427 | if ( str != NULL ) { |
| 1428 | if ( anyStrings ) |
| 1429 | CFStringAppend( result, CFSTR(", ") ); |
| 1430 | else |
| 1431 | anyStrings = true; |
| 1432 | CFStringAppend( result, str ); |
| 1433 | CFRelease( str ); |
| 1434 | } |
| 1435 | } |
| 1436 | } |
| 1437 | } |
| 1438 | CFRelease( connections ); |
| 1439 | } |
| 1440 | if ( anyStrings ) |
| 1441 | return result; |
| 1442 | |
| 1443 | CFRelease( result ); |
| 1444 | |
| 1445 | // Here, either the endpoint had no connections, or we failed to obtain names |
| 1446 | return CreateEndpointName( endpoint, false ); |
| 1447 | } |
| 1448 | |
| 1449 | std::string MidiInCore :: getPortName( unsigned int portNumber ) |
| 1450 | { |
| 1451 | CFStringRef nameRef; |
| 1452 | MIDIEndpointRef portRef; |
| 1453 | char name[128]; |
| 1454 | |
| 1455 | std::string stringName; |
| 1456 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1457 | if ( portNumber >= MIDIGetNumberOfSources() ) { |
| 1458 | std::ostringstream ost; |
| 1459 | ost << "MidiInCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 1460 | errorString_ = ost.str(); |
| 1461 | error( RtMidiError::WARNING, errorString_ ); |
| 1462 | return stringName; |
| 1463 | } |
| 1464 | |
| 1465 | portRef = MIDIGetSource( portNumber ); |
| 1466 | nameRef = CreateConnectedEndpointName( portRef ); |
| 1467 | CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8 ); |
| 1468 | CFRelease( nameRef ); |
| 1469 | |
| 1470 | return stringName = name; |
| 1471 | } |
| 1472 | |
| 1473 | //*********************************************************************// |
| 1474 | // API: OS-X |
| 1475 | // Class Definitions: MidiOutCore |
| 1476 | //*********************************************************************// |
| 1477 | |
| 1478 | MidiOutCore :: MidiOutCore( const std::string &clientName ) |
| 1479 | : MidiOutApi() |
| 1480 | { |
| 1481 | MidiOutCore::initialize( clientName ); |
| 1482 | } |
| 1483 | |
| 1484 | MidiOutCore :: ~MidiOutCore( void ) |
| 1485 | { |
| 1486 | // Close a connection if it exists. |
| 1487 | MidiOutCore::closePort(); |
| 1488 | |
| 1489 | // Cleanup. |
| 1490 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1491 | if ( data->endpoint ) MIDIEndpointDispose( data->endpoint ); |
| 1492 | delete data; |
| 1493 | } |
| 1494 | |
| 1495 | MIDIClientRef MidiOutCore::getCoreMidiClientSingleton(const std::string& clientName) throw() { |
| 1496 | |
| 1497 | if (CoreMidiClientSingleton == 0){ |
| 1498 | // Set up our client. |
| 1499 | MIDIClientRef client; |
| 1500 | |
| 1501 | CFStringRef name = CFStringCreateWithCString( NULL, clientName.c_str(), kCFStringEncodingASCII ); |
| 1502 | OSStatus result = MIDIClientCreate(name, NULL, NULL, &client ); |
| 1503 | if ( result != noErr ) { |
| 1504 | std::ostringstream ost; |
| 1505 | ost << "MidiInCore::initialize: error creating OS-X MIDI client object (" << result << ")."; |
| 1506 | errorString_ = ost.str(); |
| 1507 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1508 | return 0; |
| 1509 | } |
| 1510 | CFRelease( name ); |
| 1511 | |
| 1512 | CoreMidiClientSingleton = client; |
| 1513 | } |
| 1514 | |
| 1515 | return CoreMidiClientSingleton; |
| 1516 | } |
| 1517 | |
| 1518 | void MidiOutCore :: initialize( const std::string& clientName ) |
| 1519 | { |
| 1520 | // Set up our client. |
| 1521 | MIDIClientRef client = getCoreMidiClientSingleton(clientName); |
| 1522 | |
| 1523 | // Save our api-specific connection information. |
| 1524 | CoreMidiData *data = (CoreMidiData *) new CoreMidiData; |
| 1525 | data->client = client; |
| 1526 | data->endpoint = 0; |
| 1527 | apiData_ = (void *) data; |
| 1528 | } |
| 1529 | |
| 1530 | unsigned int MidiOutCore :: getPortCount() |
| 1531 | { |
| 1532 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1533 | return static_cast<unsigned int> (MIDIGetNumberOfDestinations()); |
| 1534 | } |
| 1535 | |
| 1536 | std::string MidiOutCore :: getPortName( unsigned int portNumber ) |
| 1537 | { |
| 1538 | CFStringRef nameRef; |
| 1539 | MIDIEndpointRef portRef; |
| 1540 | char name[128]; |
| 1541 | |
| 1542 | std::string stringName; |
| 1543 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1544 | if ( portNumber >= MIDIGetNumberOfDestinations() ) { |
| 1545 | std::ostringstream ost; |
| 1546 | ost << "MidiOutCore::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 1547 | errorString_ = ost.str(); |
| 1548 | error( RtMidiError::WARNING, errorString_ ); |
| 1549 | return stringName; |
| 1550 | } |
| 1551 | |
| 1552 | portRef = MIDIGetDestination( portNumber ); |
| 1553 | nameRef = CreateConnectedEndpointName(portRef); |
| 1554 | CFStringGetCString( nameRef, name, sizeof(name), kCFStringEncodingUTF8 ); |
| 1555 | CFRelease( nameRef ); |
| 1556 | |
| 1557 | return stringName = name; |
| 1558 | } |
| 1559 | |
| 1560 | void MidiOutCore :: openPort( unsigned int portNumber, const std::string &portName ) |
| 1561 | { |
| 1562 | if ( connected_ ) { |
| 1563 | errorString_ = "MidiOutCore::openPort: a valid connection already exists!"; |
| 1564 | error( RtMidiError::WARNING, errorString_ ); |
| 1565 | return; |
| 1566 | } |
| 1567 | |
| 1568 | CFRunLoopRunInMode( kCFRunLoopDefaultMode, 0, false ); |
| 1569 | // (chuck 1.5.5.1 modification): changed `auto` to `long` |
| 1570 | long nDest = MIDIGetNumberOfDestinations(); |
| 1571 | if (nDest < 1) { |
| 1572 | errorString_ = "MidiOutCore::openPort: no MIDI output destinations found!"; |
| 1573 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 1574 | return; |
| 1575 | } |
| 1576 | |
| 1577 | if ( portNumber >= nDest ) { |
| 1578 | std::ostringstream ost; |
| 1579 | ost << "MidiOutCore::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 1580 | errorString_ = ost.str(); |
| 1581 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 1582 | return; |
| 1583 | } |
| 1584 | |
| 1585 | MIDIPortRef port; |
| 1586 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1587 | CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); |
| 1588 | OSStatus result = MIDIOutputPortCreate( data->client, portNameRef, &port ); |
| 1589 | CFRelease( portNameRef ); |
| 1590 | if ( result != noErr ) { |
| 1591 | errorString_ = "MidiOutCore::openPort: error creating OS-X MIDI output port."; |
| 1592 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1593 | return; |
| 1594 | } |
| 1595 | |
| 1596 | // Get the desired output port identifier. |
| 1597 | MIDIEndpointRef destination = MIDIGetDestination( portNumber ); |
| 1598 | if ( destination == 0 ) { |
| 1599 | MIDIPortDispose( port ); |
| 1600 | errorString_ = "MidiOutCore::openPort: error getting MIDI output destination reference."; |
| 1601 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1602 | return; |
| 1603 | } |
| 1604 | |
| 1605 | // Save our api-specific connection information. |
| 1606 | data->port = port; |
| 1607 | data->destinationId = destination; |
| 1608 | connected_ = true; |
| 1609 | } |
| 1610 | |
| 1611 | void MidiOutCore :: closePort( void ) |
| 1612 | { |
| 1613 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1614 | |
| 1615 | if ( data->endpoint ) { |
| 1616 | MIDIEndpointDispose( data->endpoint ); |
| 1617 | data->endpoint = 0; |
| 1618 | } |
| 1619 | |
| 1620 | if ( data->port ) { |
| 1621 | MIDIPortDispose( data->port ); |
| 1622 | data->port = 0; |
| 1623 | } |
| 1624 | |
| 1625 | connected_ = false; |
| 1626 | } |
| 1627 | |
| 1628 | void MidiOutCore :: setClientName ( const std::string& ) |
| 1629 | { |
| 1630 | |
| 1631 | errorString_ = "MidiOutCore::setClientName: this function is not implemented for the MACOSX_CORE API!"; |
| 1632 | error( RtMidiError::WARNING, errorString_ ); |
| 1633 | |
| 1634 | } |
| 1635 | |
| 1636 | void MidiOutCore :: setPortName ( const std::string& ) |
| 1637 | { |
| 1638 | |
| 1639 | errorString_ = "MidiOutCore::setPortName: this function is not implemented for the MACOSX_CORE API!"; |
| 1640 | error( RtMidiError::WARNING, errorString_ ); |
| 1641 | |
| 1642 | } |
| 1643 | |
| 1644 | void MidiOutCore :: openVirtualPort( const std::string &portName ) |
| 1645 | { |
| 1646 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1647 | |
| 1648 | if ( data->endpoint ) { |
| 1649 | errorString_ = "MidiOutCore::openVirtualPort: a virtual output port already exists!"; |
| 1650 | error( RtMidiError::WARNING, errorString_ ); |
| 1651 | return; |
| 1652 | } |
| 1653 | |
| 1654 | // Create a virtual MIDI output source. |
| 1655 | MIDIEndpointRef endpoint; |
| 1656 | CFStringRef portNameRef = CFStringCreateWithCString( NULL, portName.c_str(), kCFStringEncodingASCII ); |
| 1657 | OSStatus result = MIDISourceCreate( data->client, portNameRef, &endpoint ); |
| 1658 | CFRelease( portNameRef ); |
| 1659 | |
| 1660 | if ( result != noErr ) { |
| 1661 | errorString_ = "MidiOutCore::initialize: error creating OS-X virtual MIDI source."; |
| 1662 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1663 | return; |
| 1664 | } |
| 1665 | |
| 1666 | // Save our api-specific connection information. |
| 1667 | data->endpoint = endpoint; |
| 1668 | } |
| 1669 | |
| 1670 | void MidiOutCore :: sendMessage( const unsigned char *message, size_t size ) |
| 1671 | { |
| 1672 | // We use the MIDISendSysex() function to asynchronously send sysex |
| 1673 | // messages. Otherwise, we use a single CoreMidi MIDIPacket. |
| 1674 | unsigned int nBytes = static_cast<unsigned int> (size); |
| 1675 | if ( nBytes == 0 ) { |
| 1676 | errorString_ = "MidiOutCore::sendMessage: no data in message argument!"; |
| 1677 | error( RtMidiError::WARNING, errorString_ ); |
| 1678 | return; |
| 1679 | } |
| 1680 | |
| 1681 | MIDITimeStamp timeStamp = AudioGetCurrentHostTime(); |
| 1682 | CoreMidiData *data = static_cast<CoreMidiData *> (apiData_); |
| 1683 | OSStatus result; |
| 1684 | |
| 1685 | ByteCount bufsize = nBytes > 65535 ? 65535 : nBytes; |
| 1686 | Byte buffer[bufsize+16]; // pad for other struct members |
| 1687 | ByteCount listSize = sizeof( buffer ); |
| 1688 | MIDIPacketList *packetList = (MIDIPacketList*)buffer; |
| 1689 | |
| 1690 | ByteCount remainingBytes = nBytes; |
| 1691 | while ( remainingBytes ) { |
| 1692 | MIDIPacket *packet = MIDIPacketListInit( packetList ); |
| 1693 | // A MIDIPacketList can only contain a maximum of 64K of data, so if our message is longer, |
| 1694 | // break it up into chunks of 64K or less and send out as a MIDIPacketList with only one |
| 1695 | // MIDIPacket. Here, we reuse the memory allocated above on the stack for all. |
| 1696 | ByteCount bytesForPacket = remainingBytes > 65535 ? 65535 : remainingBytes; |
| 1697 | const Byte* dataStartPtr = (const Byte *) &message[nBytes - remainingBytes]; |
| 1698 | packet = MIDIPacketListAdd( packetList, listSize, packet, timeStamp, bytesForPacket, dataStartPtr ); |
| 1699 | remainingBytes -= bytesForPacket; |
| 1700 | |
| 1701 | if ( !packet ) { |
| 1702 | errorString_ = "MidiOutCore::sendMessage: could not allocate packet list"; |
| 1703 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 1704 | return; |
| 1705 | } |
| 1706 | |
| 1707 | // Send to any destinations that may have connected to us. |
| 1708 | if ( data->endpoint ) { |
| 1709 | result = MIDIReceived( data->endpoint, packetList ); |
| 1710 | if ( result != noErr ) { |
| 1711 | errorString_ = "MidiOutCore::sendMessage: error sending MIDI to virtual destinations."; |
| 1712 | error( RtMidiError::WARNING, errorString_ ); |
| 1713 | } |
| 1714 | } |
| 1715 | |
| 1716 | // And send to an explicit destination port if we're connected. |
| 1717 | if ( connected_ ) { |
| 1718 | result = MIDISend( data->port, data->destinationId, packetList ); |
| 1719 | if ( result != noErr ) { |
| 1720 | errorString_ = "MidiOutCore::sendMessage: error sending MIDI message to port."; |
| 1721 | error( RtMidiError::WARNING, errorString_ ); |
| 1722 | } |
| 1723 | } |
| 1724 | } |
| 1725 | } |
| 1726 | |
| 1727 | #endif // __MACOSX_CORE__ |
| 1728 | |
| 1729 | |
| 1730 | //*********************************************************************// |
| 1731 | // API: LINUX ALSA SEQUENCER |
| 1732 | //*********************************************************************// |
| 1733 | |
| 1734 | // API information found at: |
| 1735 | // - http://www.alsa-project.org/documentation.php#Library |
| 1736 | |
| 1737 | #if defined(__LINUX_ALSA__) |
| 1738 | |
| 1739 | // The ALSA Sequencer API is based on the use of a callback function for |
| 1740 | // MIDI input. |
| 1741 | // |
| 1742 | // Thanks to Pedro Lopez-Cabanillas for help with the ALSA sequencer |
| 1743 | // time stamps and other assorted fixes!!! |
| 1744 | |
| 1745 | // If you don't need timestamping for incoming MIDI events, define the |
| 1746 | // preprocessor definition AVOID_TIMESTAMPING to save resources |
| 1747 | // associated with the ALSA sequencer queues. |
| 1748 | |
| 1749 | #include <pthread.h> |
| 1750 | #include <sys/time.h> |
| 1751 | |
| 1752 | // ALSA header file. |
| 1753 | #include <alsa/asoundlib.h> |
| 1754 | |
| 1755 | // A structure to hold variables related to the ALSA API |
| 1756 | // implementation. |
| 1757 | struct AlsaMidiData { |
| 1758 | snd_seq_t *seq; |
| 1759 | unsigned int portNum; |
| 1760 | int vport; |
| 1761 | snd_seq_port_subscribe_t *subscription; |
| 1762 | snd_midi_event_t *coder; |
| 1763 | unsigned int bufferSize; |
| 1764 | unsigned int requestedBufferSize; |
| 1765 | unsigned char *buffer; |
| 1766 | pthread_t thread; |
| 1767 | pthread_t dummy_thread_id; |
| 1768 | snd_seq_real_time_t lastTime; |
| 1769 | int queue_id; // an input queue is needed to get timestamped events |
| 1770 | int trigger_fds[2]; |
| 1771 | }; |
| 1772 | |
| 1773 | #define PORT_TYPE( pinfo, bits ) ((snd_seq_port_info_get_capability(pinfo) & (bits)) == (bits)) |
| 1774 | |
| 1775 | //*********************************************************************// |
| 1776 | // API: LINUX ALSA |
| 1777 | // Class Definitions: MidiInAlsa |
| 1778 | //*********************************************************************// |
| 1779 | |
| 1780 | static void *alsaMidiHandler( void *ptr ) |
| 1781 | { |
| 1782 | MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (ptr); |
| 1783 | AlsaMidiData *apiData = static_cast<AlsaMidiData *> (data->apiData); |
| 1784 | |
| 1785 | long nBytes; |
| 1786 | double time; |
| 1787 | bool continueSysex = false; |
| 1788 | bool doDecode = false; |
| 1789 | MidiInApi::MidiMessage message; |
| 1790 | int poll_fd_count; |
| 1791 | struct pollfd *poll_fds; |
| 1792 | |
| 1793 | snd_seq_event_t *ev; |
| 1794 | int result; |
| 1795 | result = snd_midi_event_new( 0, &apiData->coder ); |
| 1796 | if ( result < 0 ) { |
| 1797 | data->doInput = false; |
| 1798 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing MIDI event parser!\n\n"; |
| 1799 | return 0; |
| 1800 | } |
| 1801 | unsigned char *buffer = (unsigned char *) malloc( apiData->bufferSize ); |
| 1802 | if ( buffer == NULL ) { |
| 1803 | data->doInput = false; |
| 1804 | snd_midi_event_free( apiData->coder ); |
| 1805 | apiData->coder = 0; |
| 1806 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: error initializing buffer memory!\n\n"; |
| 1807 | return 0; |
| 1808 | } |
| 1809 | snd_midi_event_init( apiData->coder ); |
| 1810 | snd_midi_event_no_status( apiData->coder, 1 ); // suppress running status messages |
| 1811 | |
| 1812 | poll_fd_count = snd_seq_poll_descriptors_count( apiData->seq, POLLIN ) + 1; |
| 1813 | poll_fds = (struct pollfd*)alloca( poll_fd_count * sizeof( struct pollfd )); |
| 1814 | snd_seq_poll_descriptors( apiData->seq, poll_fds + 1, poll_fd_count - 1, POLLIN ); |
| 1815 | poll_fds[0].fd = apiData->trigger_fds[0]; |
| 1816 | poll_fds[0].events = POLLIN; |
| 1817 | |
| 1818 | while ( data->doInput ) { |
| 1819 | |
| 1820 | if ( snd_seq_event_input_pending( apiData->seq, 1 ) == 0 ) { |
| 1821 | // No data pending |
| 1822 | if ( poll( poll_fds, poll_fd_count, -1) >= 0 ) { |
| 1823 | if ( poll_fds[0].revents & POLLIN ) { |
| 1824 | bool dummy; |
| 1825 | int res = read( poll_fds[0].fd, &dummy, sizeof(dummy) ); |
| 1826 | (void) res; |
| 1827 | } |
| 1828 | } |
| 1829 | continue; |
| 1830 | } |
| 1831 | |
| 1832 | // If here, there should be data. |
| 1833 | result = snd_seq_event_input( apiData->seq, &ev ); |
| 1834 | if ( result == -ENOSPC ) { |
| 1835 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: MIDI input buffer overrun!\n\n"; |
| 1836 | continue; |
| 1837 | } |
| 1838 | else if ( result <= 0 ) { |
| 1839 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: unknown MIDI input error!\n"; |
| 1840 | perror("System reports"); |
| 1841 | continue; |
| 1842 | } |
| 1843 | |
| 1844 | // This is a bit weird, but we now have to decode an ALSA MIDI |
| 1845 | // event (back) into MIDI bytes. We'll ignore non-MIDI types. |
| 1846 | if ( !continueSysex ) message.bytes.clear(); |
| 1847 | |
| 1848 | doDecode = false; |
| 1849 | switch ( ev->type ) { |
| 1850 | |
| 1851 | case SND_SEQ_EVENT_PORT_SUBSCRIBED: |
| 1852 | #if defined(__RTMIDI_DEBUG__) |
| 1853 | std::cout << "MidiInAlsa::alsaMidiHandler: port connection made!\n"; |
| 1854 | #endif |
| 1855 | break; |
| 1856 | |
| 1857 | case SND_SEQ_EVENT_PORT_UNSUBSCRIBED: |
| 1858 | #if defined(__RTMIDI_DEBUG__) |
| 1859 | std::cerr << "MidiInAlsa::alsaMidiHandler: port connection has closed!\n"; |
| 1860 | std::cout << "sender = " << (int) ev->data.connect.sender.client << ":" |
| 1861 | << (int) ev->data.connect.sender.port |
| 1862 | << ", dest = " << (int) ev->data.connect.dest.client << ":" |
| 1863 | << (int) ev->data.connect.dest.port |
| 1864 | << std::endl; |
| 1865 | #endif |
| 1866 | break; |
| 1867 | |
| 1868 | case SND_SEQ_EVENT_QFRAME: // MIDI time code |
| 1869 | if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; |
| 1870 | break; |
| 1871 | |
| 1872 | case SND_SEQ_EVENT_TICK: // 0xF9 ... MIDI timing tick |
| 1873 | if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; |
| 1874 | break; |
| 1875 | |
| 1876 | case SND_SEQ_EVENT_CLOCK: // 0xF8 ... MIDI timing (clock) tick |
| 1877 | if ( !( data->ignoreFlags & 0x02 ) ) doDecode = true; |
| 1878 | break; |
| 1879 | |
| 1880 | case SND_SEQ_EVENT_SENSING: // Active sensing |
| 1881 | if ( !( data->ignoreFlags & 0x04 ) ) doDecode = true; |
| 1882 | break; |
| 1883 | |
| 1884 | case SND_SEQ_EVENT_SYSEX: |
| 1885 | if ( (data->ignoreFlags & 0x01) ) break; |
| 1886 | if ( ev->data.ext.len > apiData->bufferSize ) { |
| 1887 | apiData->bufferSize = ev->data.ext.len; |
| 1888 | free( buffer ); |
| 1889 | buffer = (unsigned char *) malloc( apiData->bufferSize ); |
| 1890 | if ( buffer == NULL ) { |
| 1891 | data->doInput = false; |
| 1892 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: error resizing buffer memory!\n\n"; |
| 1893 | break; |
| 1894 | } |
| 1895 | } |
| 1896 | doDecode = true; |
| 1897 | break; |
| 1898 | |
| 1899 | default: |
| 1900 | doDecode = true; |
| 1901 | } |
| 1902 | |
| 1903 | if ( doDecode ) { |
| 1904 | |
| 1905 | nBytes = snd_midi_event_decode( apiData->coder, buffer, apiData->bufferSize, ev ); |
| 1906 | if ( nBytes > 0 ) { |
| 1907 | // The ALSA sequencer has a maximum buffer size for MIDI sysex |
| 1908 | // events of 256 bytes. If a device sends sysex messages larger |
| 1909 | // than this, they are segmented into 256 byte chunks. So, |
| 1910 | // we'll watch for this and concatenate sysex chunks into a |
| 1911 | // single sysex message if necessary. |
| 1912 | if ( !continueSysex ) |
| 1913 | message.bytes.assign( buffer, &buffer[nBytes] ); |
| 1914 | else |
| 1915 | message.bytes.insert( message.bytes.end(), buffer, &buffer[nBytes] ); |
| 1916 | |
| 1917 | continueSysex = ( ( ev->type == SND_SEQ_EVENT_SYSEX ) && ( message.bytes.back() != 0xF7 ) ); |
| 1918 | if ( !continueSysex ) { |
| 1919 | |
| 1920 | // Calculate the time stamp: |
| 1921 | message.timeStamp = 0.0; |
| 1922 | |
| 1923 | // Method 1: Use the system time. |
| 1924 | //(void)gettimeofday(&tv, (struct timezone *)NULL); |
| 1925 | //time = (tv.tv_sec * 1000000) + tv.tv_usec; |
| 1926 | |
| 1927 | // Method 2: Use the ALSA sequencer event time data. |
| 1928 | // (thanks to Pedro Lopez-Cabanillas!). |
| 1929 | |
| 1930 | // Using method from: |
| 1931 | // https://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html |
| 1932 | |
| 1933 | // Perform the carry for the later subtraction by updating y. |
| 1934 | // Temp var y is timespec because computation requires signed types, |
| 1935 | // while snd_seq_real_time_t has unsigned types. |
| 1936 | snd_seq_real_time_t &x( ev->time.time ); |
| 1937 | struct timespec y; |
| 1938 | y.tv_nsec = apiData->lastTime.tv_nsec; |
| 1939 | y.tv_sec = apiData->lastTime.tv_sec; |
| 1940 | if ( x.tv_nsec < y.tv_nsec ) { |
| 1941 | int nsec = (y.tv_nsec - (int)x.tv_nsec) / 1000000000 + 1; |
| 1942 | y.tv_nsec -= 1000000000 * nsec; |
| 1943 | y.tv_sec += nsec; |
| 1944 | } |
| 1945 | if ( x.tv_nsec - y.tv_nsec > 1000000000 ) { |
| 1946 | int nsec = ((int)x.tv_nsec - y.tv_nsec) / 1000000000; |
| 1947 | y.tv_nsec += 1000000000 * nsec; |
| 1948 | y.tv_sec -= nsec; |
| 1949 | } |
| 1950 | |
| 1951 | // Compute the time difference. |
| 1952 | time = (int)x.tv_sec - y.tv_sec + ((int)x.tv_nsec - y.tv_nsec)*1e-9; |
| 1953 | |
| 1954 | apiData->lastTime = ev->time.time; |
| 1955 | |
| 1956 | if ( data->firstMessage == true ) |
| 1957 | data->firstMessage = false; |
| 1958 | else |
| 1959 | message.timeStamp = time; |
| 1960 | } |
| 1961 | else { |
| 1962 | #if defined(__RTMIDI_DEBUG__) |
| 1963 | std::cerr << "\nMidiInAlsa::alsaMidiHandler: event parsing error or not a MIDI event!\n\n"; |
| 1964 | #endif |
| 1965 | } |
| 1966 | } |
| 1967 | } |
| 1968 | |
| 1969 | snd_seq_free_event( ev ); |
| 1970 | if ( message.bytes.size() == 0 || continueSysex ) continue; |
| 1971 | |
| 1972 | if ( data->usingCallback ) { |
| 1973 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; |
| 1974 | callback( message.timeStamp, &message.bytes, data->userData ); |
| 1975 | } |
| 1976 | else { |
| 1977 | // As long as we haven't reached our queue size limit, push the message. |
| 1978 | if ( !data->queue.push( message ) ) |
| 1979 | std::cerr << "\nMidiInAlsa: message queue limit reached!!\n\n"; |
| 1980 | } |
| 1981 | } |
| 1982 | |
| 1983 | if ( buffer ) free( buffer ); |
| 1984 | snd_midi_event_free( apiData->coder ); |
| 1985 | apiData->coder = 0; |
| 1986 | apiData->thread = apiData->dummy_thread_id; |
| 1987 | return 0; |
| 1988 | } |
| 1989 | |
| 1990 | MidiInAlsa :: MidiInAlsa( const std::string &clientName, unsigned int queueSizeLimit ) |
| 1991 | : MidiInApi( queueSizeLimit ) |
| 1992 | { |
| 1993 | MidiInAlsa::initialize( clientName ); |
| 1994 | } |
| 1995 | |
| 1996 | MidiInAlsa :: ~MidiInAlsa() |
| 1997 | { |
| 1998 | // Close a connection if it exists. |
| 1999 | MidiInAlsa::closePort(); |
| 2000 | |
| 2001 | // Shutdown the input thread. |
| 2002 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2003 | if ( inputData_.doInput ) { |
| 2004 | inputData_.doInput = false; |
| 2005 | int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof( inputData_.doInput ) ); |
| 2006 | (void) res; |
| 2007 | if ( !pthread_equal(data->thread, data->dummy_thread_id) ) |
| 2008 | pthread_join( data->thread, NULL ); |
| 2009 | } |
| 2010 | |
| 2011 | // Cleanup. |
| 2012 | close ( data->trigger_fds[0] ); |
| 2013 | close ( data->trigger_fds[1] ); |
| 2014 | if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); |
| 2015 | #ifndef AVOID_TIMESTAMPING |
| 2016 | snd_seq_free_queue( data->seq, data->queue_id ); |
| 2017 | #endif |
| 2018 | snd_seq_close( data->seq ); |
| 2019 | delete data; |
| 2020 | } |
| 2021 | |
| 2022 | void MidiInAlsa :: initialize( const std::string& clientName ) |
| 2023 | { |
| 2024 | // Set up the ALSA sequencer client. |
| 2025 | snd_seq_t *seq; |
| 2026 | int result = snd_seq_open( &seq, "default", SND_SEQ_OPEN_DUPLEX, SND_SEQ_NONBLOCK ); |
| 2027 | if ( result < 0 ) { |
| 2028 | errorString_ = "MidiInAlsa::initialize: error creating ALSA sequencer client object."; |
| 2029 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2030 | return; |
| 2031 | } |
| 2032 | |
| 2033 | // Set client name. |
| 2034 | snd_seq_set_client_name( seq, clientName.c_str() ); |
| 2035 | |
| 2036 | // Save our api-specific connection information. |
| 2037 | AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; |
| 2038 | data->seq = seq; |
| 2039 | data->portNum = -1; |
| 2040 | data->vport = -1; |
| 2041 | data->subscription = 0; |
| 2042 | data->dummy_thread_id = pthread_self(); |
| 2043 | data->thread = data->dummy_thread_id; |
| 2044 | data->trigger_fds[0] = -1; |
| 2045 | data->trigger_fds[1] = -1; |
| 2046 | data->bufferSize = inputData_.bufferSize; |
| 2047 | apiData_ = (void *) data; |
| 2048 | inputData_.apiData = (void *) data; |
| 2049 | |
| 2050 | if ( pipe(data->trigger_fds) == -1 ) { |
| 2051 | errorString_ = "MidiInAlsa::initialize: error creating pipe objects."; |
| 2052 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2053 | return; |
| 2054 | } |
| 2055 | |
| 2056 | // Create the input queue |
| 2057 | #ifndef AVOID_TIMESTAMPING |
| 2058 | data->queue_id = snd_seq_alloc_named_queue( seq, "RtMidi Queue" ); |
| 2059 | // Set arbitrary tempo (mm=100) and resolution (240) |
| 2060 | snd_seq_queue_tempo_t *qtempo; |
| 2061 | snd_seq_queue_tempo_alloca( &qtempo ); |
| 2062 | snd_seq_queue_tempo_set_tempo( qtempo, 600000 ); |
| 2063 | snd_seq_queue_tempo_set_ppq( qtempo, 240 ); |
| 2064 | snd_seq_set_queue_tempo( data->seq, data->queue_id, qtempo ); |
| 2065 | snd_seq_drain_output( data->seq ); |
| 2066 | #endif |
| 2067 | } |
| 2068 | |
| 2069 | // This function is used to count or get the pinfo structure for a given port number. |
| 2070 | unsigned int portInfo( snd_seq_t *seq, snd_seq_port_info_t *pinfo, unsigned int type, int portNumber ) |
| 2071 | { |
| 2072 | snd_seq_client_info_t *cinfo; |
| 2073 | int client; |
| 2074 | int count = 0; |
| 2075 | snd_seq_client_info_alloca( &cinfo ); |
| 2076 | |
| 2077 | snd_seq_client_info_set_client( cinfo, -1 ); |
| 2078 | while ( snd_seq_query_next_client( seq, cinfo ) >= 0 ) { |
| 2079 | client = snd_seq_client_info_get_client( cinfo ); |
| 2080 | if ( client == 0 ) continue; |
| 2081 | // Reset query info |
| 2082 | snd_seq_port_info_set_client( pinfo, client ); |
| 2083 | snd_seq_port_info_set_port( pinfo, -1 ); |
| 2084 | while ( snd_seq_query_next_port( seq, pinfo ) >= 0 ) { |
| 2085 | unsigned int atyp = snd_seq_port_info_get_type( pinfo ); |
| 2086 | if ( ( ( atyp & SND_SEQ_PORT_TYPE_MIDI_GENERIC ) == 0 ) && |
| 2087 | ( ( atyp & SND_SEQ_PORT_TYPE_SYNTH ) == 0 ) && |
| 2088 | ( ( atyp & SND_SEQ_PORT_TYPE_APPLICATION ) == 0 ) ) continue; |
| 2089 | |
| 2090 | unsigned int caps = snd_seq_port_info_get_capability( pinfo ); |
| 2091 | if ( ( ( caps & type ) != type ) || |
| 2092 | ( ( caps & SND_SEQ_PORT_CAP_NO_EXPORT ) != 0 ) ) continue; |
| 2093 | |
| 2094 | if ( count == portNumber ) return 1; |
| 2095 | ++count; |
| 2096 | } |
| 2097 | } |
| 2098 | |
| 2099 | // If a negative portNumber was used, return the port count. |
| 2100 | if ( portNumber < 0 ) return count; |
| 2101 | return 0; |
| 2102 | } |
| 2103 | |
| 2104 | unsigned int MidiInAlsa :: getPortCount() |
| 2105 | { |
| 2106 | snd_seq_port_info_t *pinfo; |
| 2107 | snd_seq_port_info_alloca( &pinfo ); |
| 2108 | |
| 2109 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2110 | return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, -1 ); |
| 2111 | } |
| 2112 | |
| 2113 | std::string MidiInAlsa :: getPortName( unsigned int portNumber ) |
| 2114 | { |
| 2115 | snd_seq_client_info_t *cinfo; |
| 2116 | snd_seq_port_info_t *pinfo; |
| 2117 | snd_seq_client_info_alloca( &cinfo ); |
| 2118 | snd_seq_port_info_alloca( &pinfo ); |
| 2119 | |
| 2120 | std::string stringName; |
| 2121 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2122 | if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) ) { |
| 2123 | int cnum = snd_seq_port_info_get_client( pinfo ); |
| 2124 | snd_seq_get_any_client_info( data->seq, cnum, cinfo ); |
| 2125 | std::ostringstream os; |
| 2126 | os << snd_seq_client_info_get_name( cinfo ); |
| 2127 | os << ":"; |
| 2128 | os << snd_seq_port_info_get_name( pinfo ); |
| 2129 | os << " "; // These lines added to make sure devices are listed |
| 2130 | os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names |
| 2131 | os << ":"; |
| 2132 | os << snd_seq_port_info_get_port( pinfo ); |
| 2133 | stringName = os.str(); |
| 2134 | return stringName; |
| 2135 | } |
| 2136 | |
| 2137 | // If we get here, we didn't find a match. |
| 2138 | errorString_ = "MidiInAlsa::getPortName: error looking for port name!"; |
| 2139 | error( RtMidiError::WARNING, errorString_ ); |
| 2140 | return stringName; |
| 2141 | } |
| 2142 | |
| 2143 | void MidiInAlsa :: openPort( unsigned int portNumber, const std::string &portName ) |
| 2144 | { |
| 2145 | if ( connected_ ) { |
| 2146 | errorString_ = "MidiInAlsa::openPort: a valid connection already exists!"; |
| 2147 | error( RtMidiError::WARNING, errorString_ ); |
| 2148 | return; |
| 2149 | } |
| 2150 | |
| 2151 | unsigned int nSrc = this->getPortCount(); |
| 2152 | if ( nSrc < 1 ) { |
| 2153 | errorString_ = "MidiInAlsa::openPort: no MIDI input sources found!"; |
| 2154 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 2155 | return; |
| 2156 | } |
| 2157 | |
| 2158 | snd_seq_port_info_t *src_pinfo; |
| 2159 | snd_seq_port_info_alloca( &src_pinfo ); |
| 2160 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2161 | if ( portInfo( data->seq, src_pinfo, SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, (int) portNumber ) == 0 ) { |
| 2162 | std::ostringstream ost; |
| 2163 | ost << "MidiInAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 2164 | errorString_ = ost.str(); |
| 2165 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 2166 | return; |
| 2167 | } |
| 2168 | |
| 2169 | snd_seq_addr_t sender, receiver; |
| 2170 | sender.client = snd_seq_port_info_get_client( src_pinfo ); |
| 2171 | sender.port = snd_seq_port_info_get_port( src_pinfo ); |
| 2172 | receiver.client = snd_seq_client_id( data->seq ); |
| 2173 | |
| 2174 | snd_seq_port_info_t *pinfo; |
| 2175 | snd_seq_port_info_alloca( &pinfo ); |
| 2176 | if ( data->vport < 0 ) { |
| 2177 | snd_seq_port_info_set_client( pinfo, 0 ); |
| 2178 | snd_seq_port_info_set_port( pinfo, 0 ); |
| 2179 | snd_seq_port_info_set_capability( pinfo, |
| 2180 | SND_SEQ_PORT_CAP_WRITE | |
| 2181 | SND_SEQ_PORT_CAP_SUBS_WRITE ); |
| 2182 | snd_seq_port_info_set_type( pinfo, |
| 2183 | SND_SEQ_PORT_TYPE_MIDI_GENERIC | |
| 2184 | SND_SEQ_PORT_TYPE_APPLICATION ); |
| 2185 | snd_seq_port_info_set_midi_channels(pinfo, 16); |
| 2186 | #ifndef AVOID_TIMESTAMPING |
| 2187 | snd_seq_port_info_set_timestamping( pinfo, 1 ); |
| 2188 | snd_seq_port_info_set_timestamp_real( pinfo, 1 ); |
| 2189 | snd_seq_port_info_set_timestamp_queue( pinfo, data->queue_id ); |
| 2190 | #endif |
| 2191 | snd_seq_port_info_set_name( pinfo, portName.c_str() ); |
| 2192 | data->vport = snd_seq_create_port( data->seq, pinfo ); |
| 2193 | |
| 2194 | if ( data->vport < 0 ) { |
| 2195 | errorString_ = "MidiInAlsa::openPort: ALSA error creating input port."; |
| 2196 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2197 | return; |
| 2198 | } |
| 2199 | data->vport = snd_seq_port_info_get_port( pinfo ); |
| 2200 | } |
| 2201 | |
| 2202 | receiver.port = data->vport; |
| 2203 | |
| 2204 | if ( !data->subscription ) { |
| 2205 | // Make subscription |
| 2206 | if ( snd_seq_port_subscribe_malloc( &data->subscription ) < 0 ) { |
| 2207 | errorString_ = "MidiInAlsa::openPort: ALSA error allocation port subscription."; |
| 2208 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2209 | return; |
| 2210 | } |
| 2211 | snd_seq_port_subscribe_set_sender( data->subscription, &sender ); |
| 2212 | snd_seq_port_subscribe_set_dest( data->subscription, &receiver ); |
| 2213 | if ( snd_seq_subscribe_port( data->seq, data->subscription ) ) { |
| 2214 | snd_seq_port_subscribe_free( data->subscription ); |
| 2215 | data->subscription = 0; |
| 2216 | errorString_ = "MidiInAlsa::openPort: ALSA error making port connection."; |
| 2217 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2218 | return; |
| 2219 | } |
| 2220 | } |
| 2221 | |
| 2222 | if ( inputData_.doInput == false ) { |
| 2223 | // Start the input queue |
| 2224 | #ifndef AVOID_TIMESTAMPING |
| 2225 | snd_seq_start_queue( data->seq, data->queue_id, NULL ); |
| 2226 | snd_seq_drain_output( data->seq ); |
| 2227 | #endif |
| 2228 | // Start our MIDI input thread. |
| 2229 | pthread_attr_t attr; |
| 2230 | pthread_attr_init( &attr ); |
| 2231 | pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); |
| 2232 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 2233 | |
| 2234 | inputData_.doInput = true; |
| 2235 | int err = pthread_create( &data->thread, &attr, alsaMidiHandler, &inputData_ ); |
| 2236 | pthread_attr_destroy( &attr ); |
| 2237 | if ( err ) { |
| 2238 | snd_seq_unsubscribe_port( data->seq, data->subscription ); |
| 2239 | snd_seq_port_subscribe_free( data->subscription ); |
| 2240 | data->subscription = 0; |
| 2241 | inputData_.doInput = false; |
| 2242 | errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; |
| 2243 | error( RtMidiError::THREAD_ERROR, errorString_ ); |
| 2244 | return; |
| 2245 | } |
| 2246 | } |
| 2247 | |
| 2248 | connected_ = true; |
| 2249 | } |
| 2250 | |
| 2251 | void MidiInAlsa :: openVirtualPort( const std::string &portName ) |
| 2252 | { |
| 2253 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2254 | if ( data->vport < 0 ) { |
| 2255 | snd_seq_port_info_t *pinfo; |
| 2256 | snd_seq_port_info_alloca( &pinfo ); |
| 2257 | snd_seq_port_info_set_capability( pinfo, |
| 2258 | SND_SEQ_PORT_CAP_WRITE | |
| 2259 | SND_SEQ_PORT_CAP_SUBS_WRITE ); |
| 2260 | snd_seq_port_info_set_type( pinfo, |
| 2261 | SND_SEQ_PORT_TYPE_MIDI_GENERIC | |
| 2262 | SND_SEQ_PORT_TYPE_APPLICATION ); |
| 2263 | snd_seq_port_info_set_midi_channels( pinfo, 16 ); |
| 2264 | #ifndef AVOID_TIMESTAMPING |
| 2265 | snd_seq_port_info_set_timestamping( pinfo, 1 ); |
| 2266 | snd_seq_port_info_set_timestamp_real( pinfo, 1 ); |
| 2267 | snd_seq_port_info_set_timestamp_queue( pinfo, data->queue_id ); |
| 2268 | #endif |
| 2269 | snd_seq_port_info_set_name( pinfo, portName.c_str() ); |
| 2270 | data->vport = snd_seq_create_port( data->seq, pinfo ); |
| 2271 | |
| 2272 | if ( data->vport < 0 ) { |
| 2273 | errorString_ = "MidiInAlsa::openVirtualPort: ALSA error creating virtual port."; |
| 2274 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2275 | return; |
| 2276 | } |
| 2277 | data->vport = snd_seq_port_info_get_port( pinfo ); |
| 2278 | } |
| 2279 | |
| 2280 | if ( inputData_.doInput == false ) { |
| 2281 | // Wait for old thread to stop, if still running |
| 2282 | if ( !pthread_equal( data->thread, data->dummy_thread_id ) ) |
| 2283 | pthread_join( data->thread, NULL ); |
| 2284 | |
| 2285 | // Start the input queue |
| 2286 | #ifndef AVOID_TIMESTAMPING |
| 2287 | snd_seq_start_queue( data->seq, data->queue_id, NULL ); |
| 2288 | snd_seq_drain_output( data->seq ); |
| 2289 | #endif |
| 2290 | // Start our MIDI input thread. |
| 2291 | pthread_attr_t attr; |
| 2292 | pthread_attr_init( &attr ); |
| 2293 | pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ); |
| 2294 | pthread_attr_setschedpolicy( &attr, SCHED_OTHER ); |
| 2295 | |
| 2296 | inputData_.doInput = true; |
| 2297 | int err = pthread_create( &data->thread, &attr, alsaMidiHandler, &inputData_ ); |
| 2298 | pthread_attr_destroy( &attr ); |
| 2299 | if ( err ) { |
| 2300 | if ( data->subscription ) { |
| 2301 | snd_seq_unsubscribe_port( data->seq, data->subscription ); |
| 2302 | snd_seq_port_subscribe_free( data->subscription ); |
| 2303 | data->subscription = 0; |
| 2304 | } |
| 2305 | inputData_.doInput = false; |
| 2306 | errorString_ = "MidiInAlsa::openPort: error starting MIDI input thread!"; |
| 2307 | error( RtMidiError::THREAD_ERROR, errorString_ ); |
| 2308 | return; |
| 2309 | } |
| 2310 | } |
| 2311 | } |
| 2312 | |
| 2313 | void MidiInAlsa :: closePort( void ) |
| 2314 | { |
| 2315 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2316 | |
| 2317 | if ( connected_ ) { |
| 2318 | if ( data->subscription ) { |
| 2319 | snd_seq_unsubscribe_port( data->seq, data->subscription ); |
| 2320 | snd_seq_port_subscribe_free( data->subscription ); |
| 2321 | data->subscription = 0; |
| 2322 | } |
| 2323 | // Stop the input queue |
| 2324 | #ifndef AVOID_TIMESTAMPING |
| 2325 | snd_seq_stop_queue( data->seq, data->queue_id, NULL ); |
| 2326 | snd_seq_drain_output( data->seq ); |
| 2327 | #endif |
| 2328 | connected_ = false; |
| 2329 | } |
| 2330 | |
| 2331 | // Stop thread to avoid triggering the callback, while the port is intended to be closed |
| 2332 | if ( inputData_.doInput ) { |
| 2333 | inputData_.doInput = false; |
| 2334 | int res = write( data->trigger_fds[1], &inputData_.doInput, sizeof( inputData_.doInput ) ); |
| 2335 | (void) res; |
| 2336 | if ( !pthread_equal( data->thread, data->dummy_thread_id ) ) |
| 2337 | pthread_join( data->thread, NULL ); |
| 2338 | } |
| 2339 | } |
| 2340 | |
| 2341 | void MidiInAlsa :: setClientName( const std::string &clientName ) |
| 2342 | { |
| 2343 | |
| 2344 | AlsaMidiData *data = static_cast<AlsaMidiData *> ( apiData_ ); |
| 2345 | snd_seq_set_client_name( data->seq, clientName.c_str() ); |
| 2346 | |
| 2347 | } |
| 2348 | |
| 2349 | void MidiInAlsa :: setPortName( const std::string &portName ) |
| 2350 | { |
| 2351 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2352 | snd_seq_port_info_t *pinfo; |
| 2353 | snd_seq_port_info_alloca( &pinfo ); |
| 2354 | snd_seq_get_port_info( data->seq, data->vport, pinfo ); |
| 2355 | snd_seq_port_info_set_name( pinfo, portName.c_str() ); |
| 2356 | snd_seq_set_port_info( data->seq, data->vport, pinfo ); |
| 2357 | } |
| 2358 | |
| 2359 | //*********************************************************************// |
| 2360 | // API: LINUX ALSA |
| 2361 | // Class Definitions: MidiOutAlsa |
| 2362 | //*********************************************************************// |
| 2363 | |
| 2364 | MidiOutAlsa :: MidiOutAlsa( const std::string &clientName ) : MidiOutApi() |
| 2365 | { |
| 2366 | MidiOutAlsa::initialize( clientName ); |
| 2367 | } |
| 2368 | |
| 2369 | MidiOutAlsa :: ~MidiOutAlsa() |
| 2370 | { |
| 2371 | // Close a connection if it exists. |
| 2372 | MidiOutAlsa::closePort(); |
| 2373 | |
| 2374 | // Cleanup. |
| 2375 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2376 | if ( data->vport >= 0 ) snd_seq_delete_port( data->seq, data->vport ); |
| 2377 | if ( data->coder ) snd_midi_event_free( data->coder ); |
| 2378 | if ( data->buffer ) free( data->buffer ); |
| 2379 | snd_seq_close( data->seq ); |
| 2380 | delete data; |
| 2381 | } |
| 2382 | |
| 2383 | void MidiOutAlsa :: initialize( const std::string& clientName ) |
| 2384 | { |
| 2385 | // Set up the ALSA sequencer client. |
| 2386 | snd_seq_t *seq; |
| 2387 | int result1 = snd_seq_open( &seq, "default", SND_SEQ_OPEN_OUTPUT, SND_SEQ_NONBLOCK ); |
| 2388 | if ( result1 < 0 ) { |
| 2389 | errorString_ = "MidiOutAlsa::initialize: error creating ALSA sequencer client object."; |
| 2390 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2391 | return; |
| 2392 | } |
| 2393 | |
| 2394 | // Set client name. |
| 2395 | snd_seq_set_client_name( seq, clientName.c_str() ); |
| 2396 | |
| 2397 | // Save our api-specific connection information. |
| 2398 | AlsaMidiData *data = (AlsaMidiData *) new AlsaMidiData; |
| 2399 | data->seq = seq; |
| 2400 | data->portNum = -1; |
| 2401 | data->vport = -1; |
| 2402 | data->bufferSize = 32; |
| 2403 | data->coder = 0; |
| 2404 | data->buffer = 0; |
| 2405 | int result = snd_midi_event_new( data->bufferSize, &data->coder ); |
| 2406 | if ( result < 0 ) { |
| 2407 | delete data; |
| 2408 | errorString_ = "MidiOutAlsa::initialize: error initializing MIDI event parser!\n\n"; |
| 2409 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2410 | return; |
| 2411 | } |
| 2412 | data->buffer = (unsigned char *) malloc( data->bufferSize ); |
| 2413 | if ( data->buffer == NULL ) { |
| 2414 | delete data; |
| 2415 | errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; |
| 2416 | error( RtMidiError::MEMORY_ERROR, errorString_ ); |
| 2417 | return; |
| 2418 | } |
| 2419 | snd_midi_event_init( data->coder ); |
| 2420 | apiData_ = (void *) data; |
| 2421 | } |
| 2422 | |
| 2423 | unsigned int MidiOutAlsa :: getPortCount() |
| 2424 | { |
| 2425 | snd_seq_port_info_t *pinfo; |
| 2426 | snd_seq_port_info_alloca( &pinfo ); |
| 2427 | |
| 2428 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2429 | return portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, -1 ); |
| 2430 | } |
| 2431 | |
| 2432 | std::string MidiOutAlsa :: getPortName( unsigned int portNumber ) |
| 2433 | { |
| 2434 | snd_seq_client_info_t *cinfo; |
| 2435 | snd_seq_port_info_t *pinfo; |
| 2436 | snd_seq_client_info_alloca( &cinfo ); |
| 2437 | snd_seq_port_info_alloca( &pinfo ); |
| 2438 | |
| 2439 | std::string stringName; |
| 2440 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2441 | if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) ) { |
| 2442 | int cnum = snd_seq_port_info_get_client( pinfo ); |
| 2443 | snd_seq_get_any_client_info( data->seq, cnum, cinfo ); |
| 2444 | std::ostringstream os; |
| 2445 | os << snd_seq_client_info_get_name( cinfo ); |
| 2446 | os << ":"; |
| 2447 | os << snd_seq_port_info_get_name( pinfo ); |
| 2448 | os << " "; // These lines added to make sure devices are listed |
| 2449 | os << snd_seq_port_info_get_client( pinfo ); // with full portnames added to ensure individual device names |
| 2450 | os << ":"; |
| 2451 | os << snd_seq_port_info_get_port( pinfo ); |
| 2452 | stringName = os.str(); |
| 2453 | return stringName; |
| 2454 | } |
| 2455 | |
| 2456 | // If we get here, we didn't find a match. |
| 2457 | errorString_ = "MidiOutAlsa::getPortName: error looking for port name!"; |
| 2458 | error( RtMidiError::WARNING, errorString_ ); |
| 2459 | return stringName; |
| 2460 | } |
| 2461 | |
| 2462 | void MidiOutAlsa :: openPort( unsigned int portNumber, const std::string &portName ) |
| 2463 | { |
| 2464 | if ( connected_ ) { |
| 2465 | errorString_ = "MidiOutAlsa::openPort: a valid connection already exists!"; |
| 2466 | error( RtMidiError::WARNING, errorString_ ); |
| 2467 | return; |
| 2468 | } |
| 2469 | |
| 2470 | unsigned int nSrc = this->getPortCount(); |
| 2471 | if ( nSrc < 1 ) { |
| 2472 | errorString_ = "MidiOutAlsa::openPort: no MIDI output sources found!"; |
| 2473 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 2474 | return; |
| 2475 | } |
| 2476 | |
| 2477 | snd_seq_port_info_t *pinfo; |
| 2478 | snd_seq_port_info_alloca( &pinfo ); |
| 2479 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2480 | if ( portInfo( data->seq, pinfo, SND_SEQ_PORT_CAP_WRITE|SND_SEQ_PORT_CAP_SUBS_WRITE, (int) portNumber ) == 0 ) { |
| 2481 | std::ostringstream ost; |
| 2482 | ost << "MidiOutAlsa::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 2483 | errorString_ = ost.str(); |
| 2484 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 2485 | return; |
| 2486 | } |
| 2487 | |
| 2488 | snd_seq_addr_t sender, receiver; |
| 2489 | receiver.client = snd_seq_port_info_get_client( pinfo ); |
| 2490 | receiver.port = snd_seq_port_info_get_port( pinfo ); |
| 2491 | sender.client = snd_seq_client_id( data->seq ); |
| 2492 | |
| 2493 | if ( data->vport < 0 ) { |
| 2494 | data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), |
| 2495 | SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, |
| 2496 | SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); |
| 2497 | if ( data->vport < 0 ) { |
| 2498 | errorString_ = "MidiOutAlsa::openPort: ALSA error creating output port."; |
| 2499 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2500 | return; |
| 2501 | } |
| 2502 | } |
| 2503 | |
| 2504 | sender.port = data->vport; |
| 2505 | |
| 2506 | // Make subscription |
| 2507 | if ( snd_seq_port_subscribe_malloc( &data->subscription ) < 0 ) { |
| 2508 | snd_seq_port_subscribe_free( data->subscription ); |
| 2509 | errorString_ = "MidiOutAlsa::openPort: error allocating port subscription."; |
| 2510 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2511 | return; |
| 2512 | } |
| 2513 | snd_seq_port_subscribe_set_sender( data->subscription, &sender ); |
| 2514 | snd_seq_port_subscribe_set_dest( data->subscription, &receiver ); |
| 2515 | snd_seq_port_subscribe_set_time_update( data->subscription, 1 ); |
| 2516 | snd_seq_port_subscribe_set_time_real( data->subscription, 1 ); |
| 2517 | if ( snd_seq_subscribe_port( data->seq, data->subscription ) ) { |
| 2518 | snd_seq_port_subscribe_free( data->subscription ); |
| 2519 | errorString_ = "MidiOutAlsa::openPort: ALSA error making port connection."; |
| 2520 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2521 | return; |
| 2522 | } |
| 2523 | |
| 2524 | connected_ = true; |
| 2525 | } |
| 2526 | |
| 2527 | void MidiOutAlsa :: closePort( void ) |
| 2528 | { |
| 2529 | if ( connected_ ) { |
| 2530 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2531 | snd_seq_unsubscribe_port( data->seq, data->subscription ); |
| 2532 | snd_seq_port_subscribe_free( data->subscription ); |
| 2533 | data->subscription = 0; |
| 2534 | connected_ = false; |
| 2535 | } |
| 2536 | } |
| 2537 | |
| 2538 | void MidiOutAlsa :: setClientName( const std::string &clientName ) |
| 2539 | { |
| 2540 | |
| 2541 | AlsaMidiData *data = static_cast<AlsaMidiData *> ( apiData_ ); |
| 2542 | snd_seq_set_client_name( data->seq, clientName.c_str() ); |
| 2543 | |
| 2544 | } |
| 2545 | |
| 2546 | void MidiOutAlsa :: setPortName( const std::string &portName ) |
| 2547 | { |
| 2548 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2549 | snd_seq_port_info_t *pinfo; |
| 2550 | snd_seq_port_info_alloca( &pinfo ); |
| 2551 | snd_seq_get_port_info( data->seq, data->vport, pinfo ); |
| 2552 | snd_seq_port_info_set_name( pinfo, portName.c_str() ); |
| 2553 | snd_seq_set_port_info( data->seq, data->vport, pinfo ); |
| 2554 | } |
| 2555 | |
| 2556 | void MidiOutAlsa :: openVirtualPort( const std::string &portName ) |
| 2557 | { |
| 2558 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2559 | if ( data->vport < 0 ) { |
| 2560 | data->vport = snd_seq_create_simple_port( data->seq, portName.c_str(), |
| 2561 | SND_SEQ_PORT_CAP_READ|SND_SEQ_PORT_CAP_SUBS_READ, |
| 2562 | SND_SEQ_PORT_TYPE_MIDI_GENERIC|SND_SEQ_PORT_TYPE_APPLICATION ); |
| 2563 | |
| 2564 | if ( data->vport < 0 ) { |
| 2565 | errorString_ = "MidiOutAlsa::openVirtualPort: ALSA error creating virtual port."; |
| 2566 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2567 | } |
| 2568 | } |
| 2569 | } |
| 2570 | |
| 2571 | void MidiOutAlsa :: sendMessage( const unsigned char *message, size_t size ) |
| 2572 | { |
| 2573 | long result; |
| 2574 | AlsaMidiData *data = static_cast<AlsaMidiData *> (apiData_); |
| 2575 | unsigned int nBytes = static_cast<unsigned int> (size); |
| 2576 | if ( nBytes > data->bufferSize ) { |
| 2577 | data->bufferSize = nBytes; |
| 2578 | result = snd_midi_event_resize_buffer( data->coder, nBytes ); |
| 2579 | if ( result != 0 ) { |
| 2580 | errorString_ = "MidiOutAlsa::sendMessage: ALSA error resizing MIDI event buffer."; |
| 2581 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2582 | return; |
| 2583 | } |
| 2584 | free (data->buffer); |
| 2585 | data->buffer = (unsigned char *) malloc( data->bufferSize ); |
| 2586 | if ( data->buffer == NULL ) { |
| 2587 | errorString_ = "MidiOutAlsa::initialize: error allocating buffer memory!\n\n"; |
| 2588 | error( RtMidiError::MEMORY_ERROR, errorString_ ); |
| 2589 | return; |
| 2590 | } |
| 2591 | } |
| 2592 | |
| 2593 | for ( unsigned int i=0; i<nBytes; ++i ) data->buffer[i] = message[i]; |
| 2594 | |
| 2595 | unsigned int offset = 0; |
| 2596 | while (offset < nBytes) { |
| 2597 | snd_seq_event_t ev; |
| 2598 | snd_seq_ev_clear( &ev ); |
| 2599 | snd_seq_ev_set_source( &ev, data->vport ); |
| 2600 | snd_seq_ev_set_subs( &ev ); |
| 2601 | snd_seq_ev_set_direct( &ev ); |
| 2602 | result = snd_midi_event_encode( data->coder, data->buffer + offset, |
| 2603 | (long)(nBytes - offset), &ev ); |
| 2604 | if ( result < 0 ) { |
| 2605 | errorString_ = "MidiOutAlsa::sendMessage: event parsing error!"; |
| 2606 | error( RtMidiError::WARNING, errorString_ ); |
| 2607 | return; |
| 2608 | } |
| 2609 | |
| 2610 | if ( ev.type == SND_SEQ_EVENT_NONE ) { |
| 2611 | errorString_ = "MidiOutAlsa::sendMessage: incomplete message!"; |
| 2612 | error( RtMidiError::WARNING, errorString_ ); |
| 2613 | return; |
| 2614 | } |
| 2615 | |
| 2616 | offset += result; |
| 2617 | |
| 2618 | // Send the event. |
| 2619 | result = snd_seq_event_output( data->seq, &ev ); |
| 2620 | if ( result < 0 ) { |
| 2621 | errorString_ = "MidiOutAlsa::sendMessage: error sending MIDI message to port."; |
| 2622 | error( RtMidiError::WARNING, errorString_ ); |
| 2623 | return; |
| 2624 | } |
| 2625 | } |
| 2626 | snd_seq_drain_output( data->seq ); |
| 2627 | } |
| 2628 | |
| 2629 | #endif // __LINUX_ALSA__ |
| 2630 | |
| 2631 | |
| 2632 | //*********************************************************************// |
| 2633 | // API: Windows Multimedia Library (MM) |
| 2634 | //*********************************************************************// |
| 2635 | |
| 2636 | // API information deciphered from: |
| 2637 | // - http://msdn.microsoft.com/library/default.asp?url=/library/en-us/multimed/htm/_win32_midi_reference.asp |
| 2638 | |
| 2639 | // Thanks to Jean-Baptiste Berruchon for the sysex code. |
| 2640 | |
| 2641 | #if defined(__WINDOWS_MM__) |
| 2642 | |
| 2643 | // The Windows MM API is based on the use of a callback function for |
| 2644 | // MIDI input. We convert the system specific time stamps to delta |
| 2645 | // time values. |
| 2646 | |
| 2647 | // Windows MM MIDI header files. |
| 2648 | #include <windows.h> |
| 2649 | #include <mmsystem.h> |
| 2650 | |
| 2651 | // Convert a null-terminated wide string or ANSI-encoded string to UTF-8. |
| 2652 | static std::string ConvertToUTF8(const TCHAR *str) |
| 2653 | { |
| 2654 | std::string u8str; |
| 2655 | const WCHAR *wstr = L""; |
| 2656 | #if defined( UNICODE ) || defined( _UNICODE ) |
| 2657 | wstr = str; |
| 2658 | #else |
| 2659 | // Convert from ANSI encoding to wide string |
| 2660 | int wlength = MultiByteToWideChar( CP_ACP, 0, str, -1, NULL, 0 ); |
| 2661 | std::wstring wstrtemp; |
| 2662 | if ( wlength ) |
| 2663 | { |
| 2664 | wstrtemp.assign( wlength - 1, 0 ); |
| 2665 | MultiByteToWideChar( CP_ACP, 0, str, -1, &wstrtemp[0], wlength ); |
| 2666 | wstr = &wstrtemp[0]; |
| 2667 | } |
| 2668 | #endif |
| 2669 | // Convert from wide string to UTF-8 |
| 2670 | int length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL ); |
| 2671 | if ( length ) |
| 2672 | { |
| 2673 | u8str.assign( length - 1, 0 ); |
| 2674 | length = WideCharToMultiByte( CP_UTF8, 0, wstr, -1, &u8str[0], length, NULL, NULL ); |
| 2675 | } |
| 2676 | return u8str; |
| 2677 | } |
| 2678 | |
| 2679 | // A structure to hold variables related to the CoreMIDI API |
| 2680 | // implementation. |
| 2681 | struct WinMidiData { |
| 2682 | HMIDIIN inHandle; // Handle to Midi Input Device |
| 2683 | HMIDIOUT outHandle; // Handle to Midi Output Device |
| 2684 | DWORD lastTime; |
| 2685 | MidiInApi::MidiMessage message; |
| 2686 | std::vector<LPMIDIHDR> sysexBuffer; |
| 2687 | CRITICAL_SECTION _mutex; // [Patrice] see https://groups.google.com/forum/#!topic/mididev/6OUjHutMpEo |
| 2688 | }; |
| 2689 | |
| 2690 | //*********************************************************************// |
| 2691 | // API: Windows MM |
| 2692 | // Class Definitions: MidiInWinMM |
| 2693 | //*********************************************************************// |
| 2694 | |
| 2695 | static void CALLBACK midiInputCallback( HMIDIIN /*hmin*/, |
| 2696 | UINT inputStatus, |
| 2697 | DWORD_PTR instancePtr, |
| 2698 | DWORD_PTR midiMessage, |
| 2699 | DWORD timestamp ) |
| 2700 | { |
| 2701 | if ( inputStatus != MIM_DATA && inputStatus != MIM_LONGDATA && inputStatus != MIM_LONGERROR ) return; |
| 2702 | |
| 2703 | //MidiInApi::RtMidiInData *data = static_cast<MidiInApi::RtMidiInData *> (instancePtr); |
| 2704 | MidiInApi::RtMidiInData *data = (MidiInApi::RtMidiInData *)instancePtr; |
| 2705 | WinMidiData *apiData = static_cast<WinMidiData *> (data->apiData); |
| 2706 | |
| 2707 | // Calculate time stamp. |
| 2708 | if ( data->firstMessage == true ) { |
| 2709 | apiData->message.timeStamp = 0.0; |
| 2710 | data->firstMessage = false; |
| 2711 | } |
| 2712 | else apiData->message.timeStamp = (double) ( timestamp - apiData->lastTime ) * 0.001; |
| 2713 | |
| 2714 | if ( inputStatus == MIM_DATA ) { // Channel or system message |
| 2715 | |
| 2716 | // Make sure the first byte is a status byte. |
| 2717 | unsigned char status = (unsigned char) (midiMessage & 0x000000FF); |
| 2718 | if ( !(status & 0x80) ) return; |
| 2719 | |
| 2720 | // Determine the number of bytes in the MIDI message. |
| 2721 | unsigned short nBytes = 1; |
| 2722 | if ( status < 0xC0 ) nBytes = 3; |
| 2723 | else if ( status < 0xE0 ) nBytes = 2; |
| 2724 | else if ( status < 0xF0 ) nBytes = 3; |
| 2725 | else if ( status == 0xF1 ) { |
| 2726 | if ( data->ignoreFlags & 0x02 ) return; |
| 2727 | else nBytes = 2; |
| 2728 | } |
| 2729 | else if ( status == 0xF2 ) nBytes = 3; |
| 2730 | else if ( status == 0xF3 ) nBytes = 2; |
| 2731 | else if ( status == 0xF8 && ( data->ignoreFlags & 0x02 ) ) { |
| 2732 | // A MIDI timing tick message and we're ignoring it. |
| 2733 | return; |
| 2734 | } |
| 2735 | else if ( status == 0xFE && ( data->ignoreFlags & 0x04 ) ) { |
| 2736 | // A MIDI active sensing message and we're ignoring it. |
| 2737 | return; |
| 2738 | } |
| 2739 | |
| 2740 | // Copy bytes to our MIDI message. |
| 2741 | unsigned char *ptr = (unsigned char *) &midiMessage; |
| 2742 | for ( int i=0; i<nBytes; ++i ) apiData->message.bytes.push_back( *ptr++ ); |
| 2743 | } |
| 2744 | else { // Sysex message ( MIM_LONGDATA or MIM_LONGERROR ) |
| 2745 | MIDIHDR *sysex = ( MIDIHDR *) midiMessage; |
| 2746 | if ( !( data->ignoreFlags & 0x01 ) && inputStatus != MIM_LONGERROR ) { |
| 2747 | // Sysex message and we're not ignoring it |
| 2748 | for ( int i=0; i<(int)sysex->dwBytesRecorded; ++i ) |
| 2749 | apiData->message.bytes.push_back( sysex->lpData[i] ); |
| 2750 | } |
| 2751 | |
| 2752 | // The WinMM API requires that the sysex buffer be requeued after |
| 2753 | // input of each sysex message. Even if we are ignoring sysex |
| 2754 | // messages, we still need to requeue the buffer in case the user |
| 2755 | // decides to not ignore sysex messages in the future. However, |
| 2756 | // it seems that WinMM calls this function with an empty sysex |
| 2757 | // buffer when an application closes and in this case, we should |
| 2758 | // avoid requeueing it, else the computer suddenly reboots after |
| 2759 | // one or two minutes. |
| 2760 | if ( apiData->sysexBuffer[sysex->dwUser]->dwBytesRecorded > 0 ) { |
| 2761 | //if ( sysex->dwBytesRecorded > 0 ) { |
| 2762 | EnterCriticalSection( &(apiData->_mutex) ); |
| 2763 | MMRESULT result = midiInAddBuffer( apiData->inHandle, apiData->sysexBuffer[sysex->dwUser], sizeof(MIDIHDR) ); |
| 2764 | LeaveCriticalSection( &(apiData->_mutex) ); |
| 2765 | if ( result != MMSYSERR_NOERROR ) |
| 2766 | std::cerr << "\nRtMidiIn::midiInputCallback: error sending sysex to Midi device!!\n\n"; |
| 2767 | |
| 2768 | if ( data->ignoreFlags & 0x01 ) return; |
| 2769 | } |
| 2770 | else return; |
| 2771 | } |
| 2772 | |
| 2773 | // Save the time of the last non-filtered message |
| 2774 | apiData->lastTime = timestamp; |
| 2775 | |
| 2776 | if ( data->usingCallback ) { |
| 2777 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; |
| 2778 | callback( apiData->message.timeStamp, &apiData->message.bytes, data->userData ); |
| 2779 | } |
| 2780 | else { |
| 2781 | // As long as we haven't reached our queue size limit, push the message. |
| 2782 | if ( !data->queue.push( apiData->message ) ) |
| 2783 | std::cerr << "\nMidiInWinMM: message queue limit reached!!\n\n"; |
| 2784 | } |
| 2785 | |
| 2786 | // Clear the vector for the next input message. |
| 2787 | apiData->message.bytes.clear(); |
| 2788 | } |
| 2789 | |
| 2790 | MidiInWinMM :: MidiInWinMM( const std::string &clientName, unsigned int queueSizeLimit ) |
| 2791 | : MidiInApi( queueSizeLimit ) |
| 2792 | { |
| 2793 | MidiInWinMM::initialize( clientName ); |
| 2794 | } |
| 2795 | |
| 2796 | MidiInWinMM :: ~MidiInWinMM() |
| 2797 | { |
| 2798 | // Close a connection if it exists. |
| 2799 | MidiInWinMM::closePort(); |
| 2800 | |
| 2801 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 2802 | DeleteCriticalSection( &(data->_mutex) ); |
| 2803 | |
| 2804 | // Cleanup. |
| 2805 | delete data; |
| 2806 | } |
| 2807 | |
| 2808 | void MidiInWinMM :: initialize( const std::string& /*clientName*/ ) |
| 2809 | { |
| 2810 | // We'll issue a warning here if no devices are available but not |
| 2811 | // throw an error since the user can plugin something later. |
| 2812 | unsigned int nDevices = midiInGetNumDevs(); |
| 2813 | if ( nDevices == 0 ) { |
| 2814 | errorString_ = "MidiInWinMM::initialize: no MIDI input devices currently available."; |
| 2815 | error( RtMidiError::WARNING, errorString_ ); |
| 2816 | } |
| 2817 | |
| 2818 | // Save our api-specific connection information. |
| 2819 | WinMidiData *data = (WinMidiData *) new WinMidiData; |
| 2820 | apiData_ = (void *) data; |
| 2821 | inputData_.apiData = (void *) data; |
| 2822 | data->message.bytes.clear(); // needs to be empty for first input message |
| 2823 | |
| 2824 | if ( !InitializeCriticalSectionAndSpinCount( &(data->_mutex), 0x00000400 ) ) { |
| 2825 | errorString_ = "MidiInWinMM::initialize: InitializeCriticalSectionAndSpinCount failed."; |
| 2826 | error( RtMidiError::WARNING, errorString_ ); |
| 2827 | } |
| 2828 | } |
| 2829 | |
| 2830 | void MidiInWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ ) |
| 2831 | { |
| 2832 | if ( connected_ ) { |
| 2833 | errorString_ = "MidiInWinMM::openPort: a valid connection already exists!"; |
| 2834 | error( RtMidiError::WARNING, errorString_ ); |
| 2835 | return; |
| 2836 | } |
| 2837 | |
| 2838 | unsigned int nDevices = midiInGetNumDevs(); |
| 2839 | if (nDevices == 0) { |
| 2840 | errorString_ = "MidiInWinMM::openPort: no MIDI input sources found!"; |
| 2841 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 2842 | return; |
| 2843 | } |
| 2844 | |
| 2845 | if ( portNumber >= nDevices ) { |
| 2846 | std::ostringstream ost; |
| 2847 | ost << "MidiInWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 2848 | errorString_ = ost.str(); |
| 2849 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 2850 | return; |
| 2851 | } |
| 2852 | |
| 2853 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 2854 | MMRESULT result = midiInOpen( &data->inHandle, |
| 2855 | portNumber, |
| 2856 | (DWORD_PTR)&midiInputCallback, |
| 2857 | (DWORD_PTR)&inputData_, |
| 2858 | CALLBACK_FUNCTION ); |
| 2859 | if ( result != MMSYSERR_NOERROR ) { |
| 2860 | errorString_ = "MidiInWinMM::openPort: error creating Windows MM MIDI input port."; |
| 2861 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2862 | return; |
| 2863 | } |
| 2864 | |
| 2865 | // Allocate and init the sysex buffers. |
| 2866 | data->sysexBuffer.resize( inputData_.bufferCount ); |
| 2867 | for ( unsigned int i=0; i < inputData_.bufferCount; ++i ) { |
| 2868 | data->sysexBuffer[i] = (MIDIHDR*) new char[ sizeof(MIDIHDR) ]; |
| 2869 | data->sysexBuffer[i]->lpData = new char[ inputData_.bufferSize ]; |
| 2870 | data->sysexBuffer[i]->dwBufferLength = inputData_.bufferSize; |
| 2871 | data->sysexBuffer[i]->dwUser = i; // We use the dwUser parameter as buffer indicator |
| 2872 | data->sysexBuffer[i]->dwFlags = 0; |
| 2873 | |
| 2874 | result = midiInPrepareHeader( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); |
| 2875 | if ( result != MMSYSERR_NOERROR ) { |
| 2876 | midiInClose( data->inHandle ); |
| 2877 | data->inHandle = 0; |
| 2878 | errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (PrepareHeader)."; |
| 2879 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2880 | return; |
| 2881 | } |
| 2882 | |
| 2883 | // Register the buffer. |
| 2884 | result = midiInAddBuffer( data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR) ); |
| 2885 | if ( result != MMSYSERR_NOERROR ) { |
| 2886 | midiInClose( data->inHandle ); |
| 2887 | data->inHandle = 0; |
| 2888 | errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port (AddBuffer)."; |
| 2889 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2890 | return; |
| 2891 | } |
| 2892 | } |
| 2893 | |
| 2894 | result = midiInStart( data->inHandle ); |
| 2895 | if ( result != MMSYSERR_NOERROR ) { |
| 2896 | midiInClose( data->inHandle ); |
| 2897 | data->inHandle = 0; |
| 2898 | errorString_ = "MidiInWinMM::openPort: error starting Windows MM MIDI input port."; |
| 2899 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2900 | return; |
| 2901 | } |
| 2902 | |
| 2903 | connected_ = true; |
| 2904 | } |
| 2905 | |
| 2906 | void MidiInWinMM :: openVirtualPort( const std::string &/*portName*/ ) |
| 2907 | { |
| 2908 | // This function cannot be implemented for the Windows MM MIDI API. |
| 2909 | errorString_ = "MidiInWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; |
| 2910 | error( RtMidiError::WARNING, errorString_ ); |
| 2911 | } |
| 2912 | |
| 2913 | void MidiInWinMM :: closePort( void ) |
| 2914 | { |
| 2915 | if ( connected_ ) { |
| 2916 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 2917 | EnterCriticalSection( &(data->_mutex) ); |
| 2918 | midiInReset( data->inHandle ); |
| 2919 | midiInStop( data->inHandle ); |
| 2920 | |
| 2921 | for ( size_t i=0; i < data->sysexBuffer.size(); ++i ) { |
| 2922 | int result = midiInUnprepareHeader(data->inHandle, data->sysexBuffer[i], sizeof(MIDIHDR)); |
| 2923 | delete [] data->sysexBuffer[i]->lpData; |
| 2924 | delete [] data->sysexBuffer[i]; |
| 2925 | if ( result != MMSYSERR_NOERROR ) { |
| 2926 | midiInClose( data->inHandle ); |
| 2927 | data->inHandle = 0; |
| 2928 | errorString_ = "MidiInWinMM::openPort: error closing Windows MM MIDI input port (midiInUnprepareHeader)."; |
| 2929 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 2930 | return; |
| 2931 | } |
| 2932 | } |
| 2933 | |
| 2934 | midiInClose( data->inHandle ); |
| 2935 | data->inHandle = 0; |
| 2936 | connected_ = false; |
| 2937 | LeaveCriticalSection( &(data->_mutex) ); |
| 2938 | } |
| 2939 | } |
| 2940 | |
| 2941 | void MidiInWinMM :: setClientName ( const std::string& ) |
| 2942 | { |
| 2943 | |
| 2944 | errorString_ = "MidiInWinMM::setClientName: this function is not implemented for the WINDOWS_MM API!"; |
| 2945 | error( RtMidiError::WARNING, errorString_ ); |
| 2946 | |
| 2947 | } |
| 2948 | |
| 2949 | void MidiInWinMM :: setPortName ( const std::string& ) |
| 2950 | { |
| 2951 | |
| 2952 | errorString_ = "MidiInWinMM::setPortName: this function is not implemented for the WINDOWS_MM API!"; |
| 2953 | error( RtMidiError::WARNING, errorString_ ); |
| 2954 | |
| 2955 | } |
| 2956 | |
| 2957 | unsigned int MidiInWinMM :: getPortCount() |
| 2958 | { |
| 2959 | return midiInGetNumDevs(); |
| 2960 | } |
| 2961 | |
| 2962 | std::string MidiInWinMM :: getPortName( unsigned int portNumber ) |
| 2963 | { |
| 2964 | std::string stringName; |
| 2965 | unsigned int nDevices = midiInGetNumDevs(); |
| 2966 | if ( portNumber >= nDevices ) { |
| 2967 | std::ostringstream ost; |
| 2968 | ost << "MidiInWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 2969 | errorString_ = ost.str(); |
| 2970 | error( RtMidiError::WARNING, errorString_ ); |
| 2971 | return stringName; |
| 2972 | } |
| 2973 | |
| 2974 | MIDIINCAPS deviceCaps; |
| 2975 | midiInGetDevCaps( portNumber, &deviceCaps, sizeof(MIDIINCAPS)); |
| 2976 | stringName = ConvertToUTF8( deviceCaps.szPname ); |
| 2977 | |
| 2978 | // Next lines added to add the portNumber to the name so that |
| 2979 | // the device's names are sure to be listed with individual names |
| 2980 | // even when they have the same brand name |
| 2981 | #ifndef RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES |
| 2982 | std::ostringstream os; |
| 2983 | os << " "; |
| 2984 | os << portNumber; |
| 2985 | stringName += os.str(); |
| 2986 | #endif |
| 2987 | |
| 2988 | return stringName; |
| 2989 | } |
| 2990 | |
| 2991 | //*********************************************************************// |
| 2992 | // API: Windows MM |
| 2993 | // Class Definitions: MidiOutWinMM |
| 2994 | //*********************************************************************// |
| 2995 | |
| 2996 | MidiOutWinMM :: MidiOutWinMM( const std::string &clientName ) : MidiOutApi() |
| 2997 | { |
| 2998 | MidiOutWinMM::initialize( clientName ); |
| 2999 | } |
| 3000 | |
| 3001 | MidiOutWinMM :: ~MidiOutWinMM() |
| 3002 | { |
| 3003 | // Close a connection if it exists. |
| 3004 | MidiOutWinMM::closePort(); |
| 3005 | |
| 3006 | // Cleanup. |
| 3007 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 3008 | delete data; |
| 3009 | } |
| 3010 | |
| 3011 | void MidiOutWinMM :: initialize( const std::string& /*clientName*/ ) |
| 3012 | { |
| 3013 | // We'll issue a warning here if no devices are available but not |
| 3014 | // throw an error since the user can plug something in later. |
| 3015 | unsigned int nDevices = midiOutGetNumDevs(); |
| 3016 | if ( nDevices == 0 ) { |
| 3017 | errorString_ = "MidiOutWinMM::initialize: no MIDI output devices currently available."; |
| 3018 | error( RtMidiError::WARNING, errorString_ ); |
| 3019 | } |
| 3020 | |
| 3021 | // Save our api-specific connection information. |
| 3022 | WinMidiData *data = (WinMidiData *) new WinMidiData; |
| 3023 | apiData_ = (void *) data; |
| 3024 | } |
| 3025 | |
| 3026 | unsigned int MidiOutWinMM :: getPortCount() |
| 3027 | { |
| 3028 | return midiOutGetNumDevs(); |
| 3029 | } |
| 3030 | |
| 3031 | std::string MidiOutWinMM :: getPortName( unsigned int portNumber ) |
| 3032 | { |
| 3033 | std::string stringName; |
| 3034 | unsigned int nDevices = midiOutGetNumDevs(); |
| 3035 | if ( portNumber >= nDevices ) { |
| 3036 | std::ostringstream ost; |
| 3037 | ost << "MidiOutWinMM::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3038 | errorString_ = ost.str(); |
| 3039 | error( RtMidiError::WARNING, errorString_ ); |
| 3040 | return stringName; |
| 3041 | } |
| 3042 | |
| 3043 | MIDIOUTCAPS deviceCaps; |
| 3044 | midiOutGetDevCaps( portNumber, &deviceCaps, sizeof( MIDIOUTCAPS ) ); |
| 3045 | stringName = ConvertToUTF8( deviceCaps.szPname ); |
| 3046 | |
| 3047 | // Next lines added to add the portNumber to the name so that |
| 3048 | // the device's names are sure to be listed with individual names |
| 3049 | // even when they have the same brand name |
| 3050 | std::ostringstream os; |
| 3051 | #ifndef RTMIDI_DO_NOT_ENSURE_UNIQUE_PORTNAMES |
| 3052 | os << " "; |
| 3053 | os << portNumber; |
| 3054 | stringName += os.str(); |
| 3055 | #endif |
| 3056 | |
| 3057 | return stringName; |
| 3058 | } |
| 3059 | |
| 3060 | void MidiOutWinMM :: openPort( unsigned int portNumber, const std::string &/*portName*/ ) |
| 3061 | { |
| 3062 | if ( connected_ ) { |
| 3063 | errorString_ = "MidiOutWinMM::openPort: a valid connection already exists!"; |
| 3064 | error( RtMidiError::WARNING, errorString_ ); |
| 3065 | return; |
| 3066 | } |
| 3067 | |
| 3068 | unsigned int nDevices = midiOutGetNumDevs(); |
| 3069 | if ( nDevices < 1 ) { |
| 3070 | errorString_ = "MidiOutWinMM::openPort: no MIDI output destinations found!"; |
| 3071 | error( RtMidiError::NO_DEVICES_FOUND, errorString_ ); |
| 3072 | return; |
| 3073 | } |
| 3074 | |
| 3075 | if ( portNumber >= nDevices ) { |
| 3076 | std::ostringstream ost; |
| 3077 | ost << "MidiOutWinMM::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3078 | errorString_ = ost.str(); |
| 3079 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 3080 | return; |
| 3081 | } |
| 3082 | |
| 3083 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 3084 | MMRESULT result = midiOutOpen( &data->outHandle, |
| 3085 | portNumber, |
| 3086 | (DWORD)NULL, |
| 3087 | (DWORD)NULL, |
| 3088 | CALLBACK_NULL ); |
| 3089 | if ( result != MMSYSERR_NOERROR ) { |
| 3090 | errorString_ = "MidiOutWinMM::openPort: error creating Windows MM MIDI output port."; |
| 3091 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 3092 | return; |
| 3093 | } |
| 3094 | |
| 3095 | connected_ = true; |
| 3096 | } |
| 3097 | |
| 3098 | void MidiOutWinMM :: closePort( void ) |
| 3099 | { |
| 3100 | if ( connected_ ) { |
| 3101 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 3102 | // Disabled because midiOutReset triggers 0x7b (if any note was ON) and 0x79 "Reset All |
| 3103 | // Controllers" (to all 16 channels) CC messages which is undesirable (see issue #222) |
| 3104 | // midiOutReset( data->outHandle ); |
| 3105 | |
| 3106 | midiOutClose( data->outHandle ); |
| 3107 | data->outHandle = 0; |
| 3108 | connected_ = false; |
| 3109 | } |
| 3110 | } |
| 3111 | |
| 3112 | void MidiOutWinMM :: setClientName ( const std::string& ) |
| 3113 | { |
| 3114 | |
| 3115 | errorString_ = "MidiOutWinMM::setClientName: this function is not implemented for the WINDOWS_MM API!"; |
| 3116 | error( RtMidiError::WARNING, errorString_ ); |
| 3117 | |
| 3118 | } |
| 3119 | |
| 3120 | void MidiOutWinMM :: setPortName ( const std::string& ) |
| 3121 | { |
| 3122 | |
| 3123 | errorString_ = "MidiOutWinMM::setPortName: this function is not implemented for the WINDOWS_MM API!"; |
| 3124 | error( RtMidiError::WARNING, errorString_ ); |
| 3125 | |
| 3126 | } |
| 3127 | |
| 3128 | void MidiOutWinMM :: openVirtualPort( const std::string &/*portName*/ ) |
| 3129 | { |
| 3130 | // This function cannot be implemented for the Windows MM MIDI API. |
| 3131 | errorString_ = "MidiOutWinMM::openVirtualPort: cannot be implemented in Windows MM MIDI API!"; |
| 3132 | error( RtMidiError::WARNING, errorString_ ); |
| 3133 | } |
| 3134 | |
| 3135 | void MidiOutWinMM :: sendMessage( const unsigned char *message, size_t size ) |
| 3136 | { |
| 3137 | if ( !connected_ ) return; |
| 3138 | |
| 3139 | unsigned int nBytes = static_cast<unsigned int>(size); |
| 3140 | if ( nBytes == 0 ) { |
| 3141 | errorString_ = "MidiOutWinMM::sendMessage: message argument is empty!"; |
| 3142 | error( RtMidiError::WARNING, errorString_ ); |
| 3143 | return; |
| 3144 | } |
| 3145 | |
| 3146 | MMRESULT result; |
| 3147 | WinMidiData *data = static_cast<WinMidiData *> (apiData_); |
| 3148 | if ( nBytes > 3 ) { // Sysex message |
| 3149 | |
| 3150 | // Allocate buffer for sysex data. |
| 3151 | char *buffer = (char *) malloc( nBytes ); |
| 3152 | if ( buffer == NULL ) { |
| 3153 | errorString_ = "MidiOutWinMM::sendMessage: error allocating sysex message memory!"; |
| 3154 | error( RtMidiError::MEMORY_ERROR, errorString_ ); |
| 3155 | return; |
| 3156 | } |
| 3157 | |
| 3158 | // Copy data to buffer. |
| 3159 | for ( unsigned int i=0; i<nBytes; ++i ) buffer[i] = message[i]; |
| 3160 | |
| 3161 | // Create and prepare MIDIHDR structure. |
| 3162 | MIDIHDR sysex{}; |
| 3163 | sysex.lpData = (LPSTR) buffer; |
| 3164 | sysex.dwBufferLength = nBytes; |
| 3165 | sysex.dwFlags = 0; |
| 3166 | result = midiOutPrepareHeader( data->outHandle, &sysex, sizeof( MIDIHDR ) ); |
| 3167 | if ( result != MMSYSERR_NOERROR ) { |
| 3168 | free( buffer ); |
| 3169 | errorString_ = "MidiOutWinMM::sendMessage: error preparing sysex header."; |
| 3170 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 3171 | return; |
| 3172 | } |
| 3173 | |
| 3174 | // Send the message. |
| 3175 | result = midiOutLongMsg( data->outHandle, &sysex, sizeof( MIDIHDR ) ); |
| 3176 | if ( result != MMSYSERR_NOERROR ) { |
| 3177 | free( buffer ); |
| 3178 | errorString_ = "MidiOutWinMM::sendMessage: error sending sysex message."; |
| 3179 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 3180 | return; |
| 3181 | } |
| 3182 | |
| 3183 | // Unprepare the buffer and MIDIHDR. |
| 3184 | while ( MIDIERR_STILLPLAYING == midiOutUnprepareHeader( data->outHandle, &sysex, sizeof ( MIDIHDR ) ) ) Sleep( 1 ); |
| 3185 | free( buffer ); |
| 3186 | } |
| 3187 | else { // Channel or system message. |
| 3188 | |
| 3189 | // Pack MIDI bytes into double word. |
| 3190 | DWORD packet; |
| 3191 | unsigned char *ptr = (unsigned char *) &packet; |
| 3192 | for ( unsigned int i=0; i<nBytes; ++i ) { |
| 3193 | *ptr = message[i]; |
| 3194 | ++ptr; |
| 3195 | } |
| 3196 | |
| 3197 | // Send the message immediately. |
| 3198 | result = midiOutShortMsg( data->outHandle, packet ); |
| 3199 | if ( result != MMSYSERR_NOERROR ) { |
| 3200 | errorString_ = "MidiOutWinMM::sendMessage: error sending MIDI message."; |
| 3201 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 3202 | } |
| 3203 | } |
| 3204 | } |
| 3205 | |
| 3206 | #endif // __WINDOWS_MM__ |
| 3207 | |
| 3208 | |
| 3209 | //*********************************************************************// |
| 3210 | // API: Universal Windows Platform (UWP) |
| 3211 | //*********************************************************************// |
| 3212 | |
| 3213 | // C++/WinRT |
| 3214 | // https://github.com/microsoft/cppwinrt |
| 3215 | // |
| 3216 | // UWP MIDI API |
| 3217 | // https://docs.microsoft.com/en-us/windows/uwp/audio-video-camera/midi |
| 3218 | // |
| 3219 | // Example implementation using UWP MIDI in C++/WinRT |
| 3220 | // https://github.com/trueroad/uwp_midiio |
| 3221 | |
| 3222 | #if defined(__WINDOWS_UWP__) |
| 3223 | |
| 3224 | #include <algorithm> |
| 3225 | #include <chrono> |
| 3226 | #include <regex> |
| 3227 | #include <string_view> |
| 3228 | #include <mutex> |
| 3229 | |
| 3230 | #include <windows.h> |
| 3231 | #include <winrt/base.h> |
| 3232 | #include <winrt/Windows.Foundation.h> |
| 3233 | #include <winrt/Windows.Foundation.Collections.h> |
| 3234 | #include <winrt/Windows.Devices.Enumeration.h> |
| 3235 | #include <winrt/Windows.Devices.Midi.h> |
| 3236 | #include <winrt/Windows.Storage.Streams.h> |
| 3237 | #include <winrt/Windows.Security.Cryptography.h> |
| 3238 | |
| 3239 | using namespace winrt; |
| 3240 | using namespace Windows::Foundation; |
| 3241 | using namespace Windows::Devices::Enumeration; |
| 3242 | using namespace Windows::Devices::Midi; |
| 3243 | using namespace Windows::Storage::Streams; |
| 3244 | using namespace Windows::Security::Cryptography; |
| 3245 | |
| 3246 | // Class for initializing C++/WinRT |
| 3247 | class UWPMidiInit |
| 3248 | { |
| 3249 | public: |
| 3250 | UWPMidiInit() |
| 3251 | { |
| 3252 | winrt::init_apartment(); |
| 3253 | } |
| 3254 | }; |
| 3255 | |
| 3256 | // Class for handling UWP MIDI |
| 3257 | class UWPMidiClass |
| 3258 | { |
| 3259 | public: |
| 3260 | // Structure to store MIDI port name and ID |
| 3261 | struct port |
| 3262 | { |
| 3263 | std::string name; |
| 3264 | std::wstring id; |
| 3265 | std::string hex_id; |
| 3266 | std::string display_name; |
| 3267 | }; |
| 3268 | |
| 3269 | UWPMidiClass(MidiApi& midi_api) : |
| 3270 | midi_api_(midi_api) |
| 3271 | { |
| 3272 | } |
| 3273 | |
| 3274 | ~UWPMidiClass() |
| 3275 | { |
| 3276 | close(); |
| 3277 | } |
| 3278 | |
| 3279 | // Initialize for MIDI IN |
| 3280 | void in_init(MidiInApi::RtMidiInData* input_data) |
| 3281 | { |
| 3282 | input_data_ = input_data; |
| 3283 | |
| 3284 | try |
| 3285 | { |
| 3286 | ports_ = list_ports(MidiInPort::GetDeviceSelector()); |
| 3287 | } |
| 3288 | catch (hresult_error const& ex) |
| 3289 | { |
| 3290 | raise_hresult_error("UWPMidiClass::in_init: ", ex); |
| 3291 | } |
| 3292 | sort_display_name(ports_); |
| 3293 | } |
| 3294 | |
| 3295 | // Initialize for MIDI OUT |
| 3296 | void out_init() |
| 3297 | { |
| 3298 | try |
| 3299 | { |
| 3300 | ports_ = list_ports(MidiOutPort::GetDeviceSelector()); |
| 3301 | fix_display_name(list_ports(MidiInPort::GetDeviceSelector()), ports_); |
| 3302 | } |
| 3303 | catch (hresult_error const& ex) |
| 3304 | { |
| 3305 | raise_hresult_error("UWPMidiClass::out_init: ", ex); |
| 3306 | } |
| 3307 | sort_display_name(ports_); |
| 3308 | } |
| 3309 | |
| 3310 | size_t get_num_ports() |
| 3311 | { |
| 3312 | return ports_.size(); |
| 3313 | } |
| 3314 | |
| 3315 | std::string get_port_name(size_t n) |
| 3316 | { |
| 3317 | return ports_[n].display_name; |
| 3318 | } |
| 3319 | |
| 3320 | bool in_open(size_t port_number); |
| 3321 | bool out_open(size_t port_number); |
| 3322 | void close(); |
| 3323 | |
| 3324 | void midi_in_callback(const MidiInPort&, const MidiMessageReceivedEventArgs& e); |
| 3325 | bool send_buffer(const unsigned char* buff, size_t len); |
| 3326 | |
| 3327 | // Raise RtMidi error for hresult error |
| 3328 | void raise_hresult_error(std::string_view message, hresult_error const& ex) |
| 3329 | { |
| 3330 | std::ostringstream ss; |
| 3331 | ss << message << "exception HRESULT 0x" << std::hex << ex.code() << ", " |
| 3332 | << utf16_to_utf8(static_cast<std::wstring_view>(ex.message())) |
| 3333 | << "\n"; |
| 3334 | midi_api_.error(RtMidiError::DRIVER_ERROR, ss.str()); |
| 3335 | } |
| 3336 | |
| 3337 | // Mutex for MIDI port open/close |
| 3338 | std::mutex mtx_open_close_; |
| 3339 | // Mutex for MIDI IN message queue access |
| 3340 | std::mutex mtx_queue_; |
| 3341 | |
| 3342 | private: |
| 3343 | std::vector<port> list_ports(winrt::hstring device_selector); |
| 3344 | void fix_display_name(const std::vector<port>& in_ports, |
| 3345 | std::vector<port>& out_ports); |
| 3346 | void sort_display_name(std::vector<port>& ports); |
| 3347 | std::string utf16_to_utf8(const std::wstring_view wstr); |
| 3348 | |
| 3349 | template<class MidiPort_T, class IMidiPort_T> |
| 3350 | IMidiPort_T open(size_t port_number); |
| 3351 | |
| 3352 | // MidiApi class |
| 3353 | MidiApi& midi_api_; |
| 3354 | |
| 3355 | // List of MIDI ports |
| 3356 | std::vector<port> ports_; |
| 3357 | // MIDI IN port |
| 3358 | MidiInPort in_port_{ nullptr }; |
| 3359 | // MIDI OUT port |
| 3360 | IMidiOutPort out_port_{ nullptr }; |
| 3361 | // Backup initial MessageReceived event token |
| 3362 | winrt::event_token before_token_; |
| 3363 | // Input data |
| 3364 | MidiInApi::RtMidiInData* input_data_{ nullptr }; |
| 3365 | // Last timestamp |
| 3366 | std::chrono::duration<TimeSpan::rep, TimeSpan::period> last_time_{ 0 }; |
| 3367 | |
| 3368 | // C++/WinRT initializer |
| 3369 | static UWPMidiInit uwp_midi_init_; |
| 3370 | // Regex pattern to extract 8 hex digits from UWP MIDI ID string |
| 3371 | static const std::wregex hex_id_pattern_; |
| 3372 | |
| 3373 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3374 | // QueryPerformanceFrequency |
| 3375 | LONGLONG qpc_freq_{ 0 }; |
| 3376 | // Last QueryPerformanceCounter |
| 3377 | LONGLONG before_qpc_; |
| 3378 | // Weather overflow low occurred or not |
| 3379 | bool b_overflow_low_{ false }; |
| 3380 | |
| 3381 | // BLE-MIDI timestamp periods |
| 3382 | inline constexpr static std::chrono::duration<TimeSpan::rep, TimeSpan::period> ble_midi_period_low_{ std::chrono::milliseconds{128} }; |
| 3383 | inline constexpr static std::chrono::duration<TimeSpan::rep, TimeSpan::period> ble_midi_period_high_{ std::chrono::milliseconds{8192} }; |
| 3384 | // QPC threshold 4096 ms |
| 3385 | inline constexpr static LONGLONG qpc_threshold_{ 4096 }; |
| 3386 | |
| 3387 | // Regex pattern to detect BLE-MIDI IN |
| 3388 | static const std::wregex ble_midi_pattern_; |
| 3389 | #endif |
| 3390 | }; |
| 3391 | |
| 3392 | // C++/WinRT initializer |
| 3393 | UWPMidiInit UWPMidiClass::uwp_midi_init_; |
| 3394 | // Regex pattern to extract 8 hex digits from UWP MIDI ID string |
| 3395 | const std::wregex UWPMidiClass::hex_id_pattern_{ std::wregex(L"#MIDII_([0-9A-F]{8})\\..+#") }; |
| 3396 | |
| 3397 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3398 | const std::wregex UWPMidiClass::ble_midi_pattern_{ std::wregex(L"#MIDII_[0-9A-F]{8}\\.BLE[0-9]{2}#") }; |
| 3399 | #endif |
| 3400 | |
| 3401 | // Find and create a list of UWP MIDI ports |
| 3402 | std::vector<UWPMidiClass::port> UWPMidiClass::list_ports(winrt::hstring device_selector) |
| 3403 | { |
| 3404 | const auto devs{ DeviceInformation::FindAllAsync(device_selector).get() }; |
| 3405 | |
| 3406 | std::vector<port> retval; |
| 3407 | for (const auto& d : devs) |
| 3408 | { |
| 3409 | port p; |
| 3410 | p.name = utf16_to_utf8(d.Name()); |
| 3411 | p.id = d.Id(); |
| 3412 | |
| 3413 | std::wsmatch m; |
| 3414 | if (std::regex_search(p.id, m, hex_id_pattern_)) |
| 3415 | { |
| 3416 | // Ordinary MIDI ports |
| 3417 | // Append hex digits extracted from the UWP MIDI ID string to the port name. |
| 3418 | p.hex_id = utf16_to_utf8(m[1].str()); |
| 3419 | |
| 3420 | std::ostringstream ss; |
| 3421 | ss << p.name |
| 3422 | << " [ " |
| 3423 | << p.hex_id |
| 3424 | << " ]"; |
| 3425 | p.display_name = ss.str(); |
| 3426 | } |
| 3427 | else |
| 3428 | { |
| 3429 | // Microsoft GS Wavetable Synth etc. |
| 3430 | // Unable to extract hex digits from UWP MIDI ID string. |
| 3431 | // Use the device name as the port name. |
| 3432 | p.display_name = p.name; |
| 3433 | } |
| 3434 | |
| 3435 | retval.push_back(p); |
| 3436 | } |
| 3437 | return retval; |
| 3438 | } |
| 3439 | |
| 3440 | // Fix MIDI OUT port names starting with `MIDI` to MIDI IN port names with similar ID strings |
| 3441 | void UWPMidiClass::fix_display_name(const std::vector<port>& in_ports, |
| 3442 | std::vector<port>& out_ports) |
| 3443 | { |
| 3444 | for (auto& outp : out_ports) |
| 3445 | { |
| 3446 | if (outp.hex_id.empty() || |
| 3447 | std::string_view{ outp.name }.substr(0, 4) != "MIDI") |
| 3448 | continue; |
| 3449 | |
| 3450 | for (const auto& inp : in_ports) |
| 3451 | { |
| 3452 | if (outp.hex_id == inp.hex_id) |
| 3453 | { |
| 3454 | outp.display_name = inp.display_name; |
| 3455 | break; |
| 3456 | } |
| 3457 | } |
| 3458 | } |
| 3459 | } |
| 3460 | |
| 3461 | void UWPMidiClass::sort_display_name(std::vector<port>& ports) |
| 3462 | { |
| 3463 | std::sort(ports.begin(), ports.end(), |
| 3464 | [](const auto& lhs, const auto& rhs) |
| 3465 | { |
| 3466 | return lhs.display_name < rhs.display_name; |
| 3467 | }); |
| 3468 | } |
| 3469 | |
| 3470 | std::string UWPMidiClass::utf16_to_utf8(const std::wstring_view wstr) |
| 3471 | { |
| 3472 | auto len{ WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), nullptr, 0, nullptr, nullptr) }; |
| 3473 | std::string u8str(len, '\0'); |
| 3474 | if (len) |
| 3475 | WideCharToMultiByte(CP_UTF8, 0, wstr.data(), static_cast<int>(wstr.size()), u8str.data(), len, nullptr, nullptr); |
| 3476 | return u8str; |
| 3477 | } |
| 3478 | |
| 3479 | // Open MIDI IN/OUT port |
| 3480 | template<class MidiPort_T, class IMidiPort_T> |
| 3481 | IMidiPort_T UWPMidiClass::open(size_t port_number) |
| 3482 | { |
| 3483 | try |
| 3484 | { |
| 3485 | auto async{ MidiPort_T::FromIdAsync(ports_[port_number].id) }; |
| 3486 | // Timeout 3 seconds |
| 3487 | if (async.wait_for(std::chrono::seconds(3)) == AsyncStatus::Completed) |
| 3488 | return async.GetResults(); |
| 3489 | } |
| 3490 | catch (hresult_error const& ex) |
| 3491 | { |
| 3492 | raise_hresult_error("UWPMidiClass::open: ", ex); |
| 3493 | } |
| 3494 | return nullptr; |
| 3495 | } |
| 3496 | |
| 3497 | // Open MIDI IN port |
| 3498 | bool UWPMidiClass::in_open(size_t port_number) |
| 3499 | { |
| 3500 | if (in_port_) |
| 3501 | in_port_.Close(); |
| 3502 | |
| 3503 | in_port_ = open<MidiInPort, MidiInPort>(port_number); |
| 3504 | if (!in_port_) |
| 3505 | return false; |
| 3506 | |
| 3507 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3508 | std::wsmatch m; |
| 3509 | if (std::regex_search(ports_[port_number].id, m, ble_midi_pattern_)) |
| 3510 | { |
| 3511 | // BLE-MIDI IN port |
| 3512 | LARGE_INTEGER li; |
| 3513 | if (::QueryPerformanceFrequency(&li)) |
| 3514 | qpc_freq_ = li.QuadPart; |
| 3515 | } |
| 3516 | #endif |
| 3517 | |
| 3518 | try |
| 3519 | { |
| 3520 | before_token_ = in_port_.MessageReceived({ this, &UWPMidiClass::midi_in_callback }); |
| 3521 | } |
| 3522 | catch (hresult_error const& ex) |
| 3523 | { |
| 3524 | raise_hresult_error("UWPMidiClass::in_open: ", ex); |
| 3525 | } |
| 3526 | |
| 3527 | return true; |
| 3528 | } |
| 3529 | |
| 3530 | // Open MIDI Out port |
| 3531 | bool UWPMidiClass::out_open(size_t port_number) |
| 3532 | { |
| 3533 | if (out_port_) |
| 3534 | out_port_.Close(); |
| 3535 | |
| 3536 | out_port_ = open<MidiOutPort, IMidiOutPort>(port_number); |
| 3537 | if (!out_port_) |
| 3538 | return false; |
| 3539 | |
| 3540 | return true; |
| 3541 | } |
| 3542 | |
| 3543 | // Close MIDI IN/OUT port |
| 3544 | void UWPMidiClass::close() |
| 3545 | { |
| 3546 | if (in_port_) |
| 3547 | { |
| 3548 | if (before_token_) |
| 3549 | in_port_.MessageReceived(before_token_); |
| 3550 | |
| 3551 | in_port_.Close(); |
| 3552 | in_port_ = nullptr; |
| 3553 | } |
| 3554 | if (out_port_) |
| 3555 | { |
| 3556 | out_port_.Close(); |
| 3557 | out_port_ = nullptr; |
| 3558 | } |
| 3559 | } |
| 3560 | |
| 3561 | // MessageReceived event handler |
| 3562 | void UWPMidiClass::midi_in_callback(const MidiInPort&, const MidiMessageReceivedEventArgs& e) |
| 3563 | { |
| 3564 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3565 | LARGE_INTEGER qpc; |
| 3566 | if (qpc_freq_) |
| 3567 | { |
| 3568 | if (!::QueryPerformanceCounter(&qpc)) |
| 3569 | qpc_freq_ = 0; |
| 3570 | } |
| 3571 | #endif |
| 3572 | |
| 3573 | const auto& m{ e.Message() }; |
| 3574 | if (!m) |
| 3575 | return; |
| 3576 | |
| 3577 | MidiInApi::MidiMessage message; |
| 3578 | const std::chrono::duration<TimeSpan::rep, TimeSpan::period> duration{ m.Timestamp() }; |
| 3579 | |
| 3580 | // Calculate time stamp. |
| 3581 | if (input_data_->firstMessage == true) |
| 3582 | { |
| 3583 | message.timeStamp = 0.0; |
| 3584 | input_data_->firstMessage = false; |
| 3585 | last_time_ = duration; |
| 3586 | |
| 3587 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3588 | if (qpc_freq_) |
| 3589 | before_qpc_ = qpc.QuadPart; |
| 3590 | #endif |
| 3591 | } |
| 3592 | else |
| 3593 | { |
| 3594 | auto delta{ duration - last_time_ }; |
| 3595 | |
| 3596 | #ifndef RTMIDI_DO_NOT_ENABLE_WORKAROUND_UWP_WRONG_TIMESTAMPS |
| 3597 | if (qpc_freq_) |
| 3598 | { |
| 3599 | if (b_overflow_low_) |
| 3600 | { |
| 3601 | if (delta >= ble_midi_period_low_) |
| 3602 | { |
| 3603 | // Fix after overflow low |
| 3604 | // https://github.com/trueroad/BLE_MIDI_packet_data_set#page-7-overflow-both |
| 3605 | delta -= ble_midi_period_low_; |
| 3606 | b_overflow_low_ = false; |
| 3607 | } |
| 3608 | } |
| 3609 | else |
| 3610 | { |
| 3611 | if ((ble_midi_period_high_ - ble_midi_period_low_) < delta && delta < ble_midi_period_high_ && |
| 3612 | ((before_qpc_ - qpc.QuadPart) * 1000 / qpc_freq_) < qpc_threshold_) |
| 3613 | { |
| 3614 | // Fix overflow low |
| 3615 | // https://github.com/trueroad/BLE_MIDI_packet_data_set#page-7-overflow-low |
| 3616 | delta = delta - ble_midi_period_high_ + ble_midi_period_low_; |
| 3617 | b_overflow_low_ = true; |
| 3618 | } |
| 3619 | } |
| 3620 | |
| 3621 | before_qpc_ = qpc.QuadPart; |
| 3622 | } |
| 3623 | #endif |
| 3624 | |
| 3625 | const std::chrono::duration<double> sec{ delta }; |
| 3626 | message.timeStamp = sec.count(); |
| 3627 | } |
| 3628 | |
| 3629 | if (((input_data_->ignoreFlags & 0x01) && |
| 3630 | (m.Type() == MidiMessageType::SystemExclusive || m.Type() == MidiMessageType::EndSystemExclusive)) || |
| 3631 | ((input_data_->ignoreFlags & 0x02) && |
| 3632 | (m.Type() == MidiMessageType::MidiTimeCode || m.Type() == MidiMessageType::TimingClock)) || |
| 3633 | ((input_data_->ignoreFlags & 0x04) && |
| 3634 | m.Type() == MidiMessageType::ActiveSensing)) |
| 3635 | { |
| 3636 | return; |
| 3637 | } |
| 3638 | |
| 3639 | const auto& raw_data{ m.RawData() }; |
| 3640 | const size_t len{ raw_data.Length() }; |
| 3641 | |
| 3642 | if (len) |
| 3643 | message.bytes.assign(raw_data.data(), raw_data.data() + len); |
| 3644 | |
| 3645 | last_time_ = duration; |
| 3646 | |
| 3647 | if (input_data_->usingCallback) |
| 3648 | { |
| 3649 | (input_data_->userCallback)(message.timeStamp, &message.bytes, input_data_->userData); |
| 3650 | } |
| 3651 | else |
| 3652 | { |
| 3653 | std::lock_guard<std::mutex> lock(mtx_queue_); |
| 3654 | |
| 3655 | if (!input_data_->queue.push(message)) |
| 3656 | { |
| 3657 | std::cerr << "\nMidiInWinUWP: message queue limit reached!!\n\n"; |
| 3658 | } |
| 3659 | } |
| 3660 | } |
| 3661 | |
| 3662 | // Send MIDI message |
| 3663 | bool UWPMidiClass::send_buffer(const unsigned char* buff, size_t len) |
| 3664 | { |
| 3665 | if (!out_port_) |
| 3666 | return false; |
| 3667 | |
| 3668 | try |
| 3669 | { |
| 3670 | out_port_.SendBuffer(CryptographicBuffer::CreateFromByteArray(array_view(buff, buff + len))); |
| 3671 | } |
| 3672 | catch (hresult_error const& ex) |
| 3673 | { |
| 3674 | raise_hresult_error("UWPMidiClass::send_buffer: ", ex); |
| 3675 | } |
| 3676 | |
| 3677 | return true; |
| 3678 | } |
| 3679 | |
| 3680 | //*********************************************************************// |
| 3681 | // API: Windows UWP |
| 3682 | // Class Definitions: MidiInWinUWP |
| 3683 | //*********************************************************************// |
| 3684 | |
| 3685 | MidiInWinUWP::MidiInWinUWP(const std::string& clientName, unsigned int queueSizeLimit) |
| 3686 | : MidiInApi(queueSizeLimit) |
| 3687 | { |
| 3688 | MidiInWinUWP::initialize(clientName); |
| 3689 | } |
| 3690 | |
| 3691 | MidiInWinUWP :: ~MidiInWinUWP() |
| 3692 | { |
| 3693 | // Close a connection if it exists. |
| 3694 | MidiInWinUWP::closePort(); |
| 3695 | |
| 3696 | // Cleanup. |
| 3697 | UWPMidiClass *data = static_cast<UWPMidiClass*> (apiData_); |
| 3698 | delete data; |
| 3699 | } |
| 3700 | |
| 3701 | void MidiInWinUWP::initialize(const std::string& /*clientName*/) |
| 3702 | { |
| 3703 | // Save our api-specific connection information. |
| 3704 | UWPMidiClass* data{ new UWPMidiClass(*this) }; |
| 3705 | data->in_init(&inputData_); |
| 3706 | apiData_ = static_cast<void*>(data); |
| 3707 | |
| 3708 | // We'll issue a warning here if no devices are available but not |
| 3709 | // throw an error since the user can plugin something later. |
| 3710 | const auto nDevices{ data->get_num_ports() }; |
| 3711 | if (nDevices == 0) |
| 3712 | { |
| 3713 | errorString_ = "MidiInWinUWP::initialize: no MIDI input devices currently available."; |
| 3714 | error(RtMidiError::WARNING, errorString_); |
| 3715 | } |
| 3716 | } |
| 3717 | |
| 3718 | void MidiInWinUWP::openPort(unsigned int portNumber, const std::string&/*portName*/) |
| 3719 | { |
| 3720 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3721 | std::lock_guard<std::mutex> lock(data->mtx_open_close_); |
| 3722 | |
| 3723 | if (connected_) |
| 3724 | { |
| 3725 | errorString_ = "MidiInWinUWP::openPort: a valid connection already exists!"; |
| 3726 | error(RtMidiError::WARNING, errorString_); |
| 3727 | return; |
| 3728 | } |
| 3729 | |
| 3730 | if (data->get_num_ports() == 0) |
| 3731 | { |
| 3732 | errorString_ = "MidiInWinUWP::openPort: no MIDI input sources found!"; |
| 3733 | error(RtMidiError::NO_DEVICES_FOUND, errorString_); |
| 3734 | return; |
| 3735 | } |
| 3736 | |
| 3737 | if (portNumber >= data->get_num_ports()) |
| 3738 | { |
| 3739 | std::ostringstream ost; |
| 3740 | ost << "MidiInWinUWP::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3741 | errorString_ = ost.str(); |
| 3742 | error(RtMidiError::INVALID_PARAMETER, errorString_); |
| 3743 | return; |
| 3744 | } |
| 3745 | |
| 3746 | if (!data->in_open(portNumber)) |
| 3747 | { |
| 3748 | errorString_ = "MidiInWinUWP::openPort: error creating Windows UWP MIDI input port."; |
| 3749 | error(RtMidiError::DRIVER_ERROR, errorString_); |
| 3750 | return; |
| 3751 | } |
| 3752 | |
| 3753 | connected_ = true; |
| 3754 | } |
| 3755 | |
| 3756 | void MidiInWinUWP::openVirtualPort(const std::string&/*portName*/) |
| 3757 | { |
| 3758 | // This function cannot be implemented for the Windows UWP MIDI API. |
| 3759 | errorString_ = "MidiInWinUWP::openVirtualPort: cannot be implemented in Windows UWP MIDI API!"; |
| 3760 | error(RtMidiError::WARNING, errorString_); |
| 3761 | } |
| 3762 | |
| 3763 | void MidiInWinUWP::closePort(void) |
| 3764 | { |
| 3765 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3766 | std::lock_guard<std::mutex> lock(data->mtx_open_close_); |
| 3767 | |
| 3768 | if (connected_) |
| 3769 | { |
| 3770 | data->close(); |
| 3771 | connected_ = false; |
| 3772 | } |
| 3773 | } |
| 3774 | |
| 3775 | void MidiInWinUWP::setClientName(const std::string&) |
| 3776 | { |
| 3777 | errorString_ = "MidiInWinUWP::setClientName: this function is not implemented for the WINDOWS_UWP API!"; |
| 3778 | error(RtMidiError::WARNING, errorString_); |
| 3779 | } |
| 3780 | |
| 3781 | void MidiInWinUWP::setPortName(const std::string&) |
| 3782 | { |
| 3783 | errorString_ = "MidiInWinUWP::setPortName: this function is not implemented for the WINDOWS_UWP API!"; |
| 3784 | error(RtMidiError::WARNING, errorString_); |
| 3785 | } |
| 3786 | |
| 3787 | unsigned int MidiInWinUWP::getPortCount() |
| 3788 | { |
| 3789 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3790 | return static_cast<unsigned int>(data->get_num_ports()); |
| 3791 | } |
| 3792 | |
| 3793 | std::string MidiInWinUWP::getPortName(unsigned int portNumber) |
| 3794 | { |
| 3795 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3796 | |
| 3797 | const auto nDevices{ data->get_num_ports() }; |
| 3798 | if (portNumber >= nDevices) |
| 3799 | { |
| 3800 | std::ostringstream ost; |
| 3801 | ost << "MidiInWinUWP::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3802 | errorString_ = ost.str(); |
| 3803 | error(RtMidiError::WARNING, errorString_); |
| 3804 | return ""; |
| 3805 | } |
| 3806 | |
| 3807 | return data->get_port_name(portNumber); |
| 3808 | } |
| 3809 | |
| 3810 | double MidiInWinUWP::getMessage(std::vector<unsigned char>* message) |
| 3811 | { |
| 3812 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3813 | std::lock_guard<std::mutex> lock(data->mtx_queue_); |
| 3814 | |
| 3815 | return MidiInApi::getMessage(message); |
| 3816 | } |
| 3817 | |
| 3818 | //*********************************************************************// |
| 3819 | // API: Windows UWP |
| 3820 | // Class Definitions: MidiOutWinUWP |
| 3821 | //*********************************************************************// |
| 3822 | |
| 3823 | MidiOutWinUWP::MidiOutWinUWP(const std::string& clientName) : MidiOutApi() |
| 3824 | { |
| 3825 | MidiOutWinUWP::initialize(clientName); |
| 3826 | } |
| 3827 | |
| 3828 | MidiOutWinUWP :: ~MidiOutWinUWP() |
| 3829 | { |
| 3830 | // Close a connection if it exists. |
| 3831 | MidiOutWinUWP::closePort(); |
| 3832 | |
| 3833 | // Cleanup. |
| 3834 | UWPMidiClass* data = static_cast<UWPMidiClass*> (apiData_); |
| 3835 | delete data; |
| 3836 | } |
| 3837 | |
| 3838 | void MidiOutWinUWP::initialize(const std::string& /*clientName*/) |
| 3839 | { |
| 3840 | // Save our api-specific connection information. |
| 3841 | UWPMidiClass* data{ new UWPMidiClass(*this) }; |
| 3842 | data->out_init(); |
| 3843 | apiData_ = static_cast<void*>(data); |
| 3844 | |
| 3845 | // We'll issue a warning here if no devices are available but not |
| 3846 | // throw an error since the user can plug something in later. |
| 3847 | const auto nDevices{ data->get_num_ports() }; |
| 3848 | if (nDevices == 0) |
| 3849 | { |
| 3850 | errorString_ = "MidiOutWinUWP::initialize: no MIDI output devices currently available."; |
| 3851 | error(RtMidiError::WARNING, errorString_); |
| 3852 | } |
| 3853 | } |
| 3854 | |
| 3855 | unsigned int MidiOutWinUWP::getPortCount() |
| 3856 | { |
| 3857 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3858 | return static_cast<unsigned int>(data->get_num_ports()); |
| 3859 | } |
| 3860 | |
| 3861 | std::string MidiOutWinUWP::getPortName(unsigned int portNumber) |
| 3862 | { |
| 3863 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3864 | |
| 3865 | const auto nDevices{ data->get_num_ports() }; |
| 3866 | if (portNumber >= nDevices) |
| 3867 | { |
| 3868 | std::ostringstream ost; |
| 3869 | ost << "MidiOutWinUWP::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3870 | errorString_ = ost.str(); |
| 3871 | error(RtMidiError::WARNING, errorString_); |
| 3872 | return ""; |
| 3873 | } |
| 3874 | |
| 3875 | return data->get_port_name(portNumber); |
| 3876 | } |
| 3877 | |
| 3878 | void MidiOutWinUWP::openPort(unsigned int portNumber, const std::string&/*portName*/) |
| 3879 | { |
| 3880 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3881 | std::lock_guard<std::mutex> lock(data->mtx_open_close_); |
| 3882 | |
| 3883 | if (connected_) |
| 3884 | { |
| 3885 | errorString_ = "MidiOutWinUWP::openPort: a valid connection already exists!"; |
| 3886 | error(RtMidiError::WARNING, errorString_); |
| 3887 | return; |
| 3888 | } |
| 3889 | |
| 3890 | if (data->get_num_ports() == 0) |
| 3891 | { |
| 3892 | errorString_ = "MidiOutWinUWP::openPort: no MIDI output destinations found!"; |
| 3893 | error(RtMidiError::NO_DEVICES_FOUND, errorString_); |
| 3894 | return; |
| 3895 | } |
| 3896 | |
| 3897 | if (portNumber >= data->get_num_ports()) |
| 3898 | { |
| 3899 | std::ostringstream ost; |
| 3900 | ost << "MidiOutWinUWP::openPort: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 3901 | errorString_ = ost.str(); |
| 3902 | error(RtMidiError::INVALID_PARAMETER, errorString_); |
| 3903 | return; |
| 3904 | } |
| 3905 | |
| 3906 | if (!data->out_open(portNumber)) |
| 3907 | { |
| 3908 | errorString_ = "MidiOutWinUWP::openPort: error creating Windows UWP MIDI output port."; |
| 3909 | error(RtMidiError::DRIVER_ERROR, errorString_); |
| 3910 | return; |
| 3911 | } |
| 3912 | |
| 3913 | connected_ = true; |
| 3914 | } |
| 3915 | |
| 3916 | void MidiOutWinUWP::closePort(void) |
| 3917 | { |
| 3918 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3919 | std::lock_guard<std::mutex> lock(data->mtx_open_close_); |
| 3920 | |
| 3921 | if (connected_) |
| 3922 | { |
| 3923 | data->close(); |
| 3924 | connected_ = false; |
| 3925 | } |
| 3926 | } |
| 3927 | |
| 3928 | void MidiOutWinUWP::setClientName(const std::string&) |
| 3929 | { |
| 3930 | errorString_ = "MidiOutWinUWP::setClientName: this function is not implemented for the WINDOWS_UWP API!"; |
| 3931 | error(RtMidiError::WARNING, errorString_); |
| 3932 | } |
| 3933 | |
| 3934 | void MidiOutWinUWP::setPortName(const std::string&) |
| 3935 | { |
| 3936 | errorString_ = "MidiOutWinUWP::setPortName: this function is not implemented for the WINDOWS_UWP API!"; |
| 3937 | error(RtMidiError::WARNING, errorString_); |
| 3938 | } |
| 3939 | |
| 3940 | void MidiOutWinUWP::openVirtualPort(const std::string&/*portName*/) |
| 3941 | { |
| 3942 | // This function cannot be implemented for the Windows UWP MIDI API. |
| 3943 | errorString_ = "MidiOutWinUWP::openVirtualPort: cannot be implemented in Windows UWP MIDI API!"; |
| 3944 | error(RtMidiError::WARNING, errorString_); |
| 3945 | } |
| 3946 | |
| 3947 | void MidiOutWinUWP::sendMessage(const unsigned char* message, size_t size) |
| 3948 | { |
| 3949 | if (!connected_) |
| 3950 | return; |
| 3951 | |
| 3952 | if (size == 0) |
| 3953 | { |
| 3954 | errorString_ = "MidiOutWinUWP::sendMessage: message argument is empty!"; |
| 3955 | error(RtMidiError::WARNING, errorString_); |
| 3956 | return; |
| 3957 | } |
| 3958 | |
| 3959 | UWPMidiClass* data{ static_cast<UWPMidiClass*>(apiData_) }; |
| 3960 | if (!data->send_buffer(message, size)) |
| 3961 | { |
| 3962 | errorString_ = "MidiOutWinUWP::sendMessage: error sending message."; |
| 3963 | error(RtMidiError::DRIVER_ERROR, errorString_); |
| 3964 | } |
| 3965 | } |
| 3966 | |
| 3967 | #endif // __WINDOWS_UWP__ |
| 3968 | |
| 3969 | |
| 3970 | //*********************************************************************// |
| 3971 | // API: UNIX JACK |
| 3972 | // |
| 3973 | // Written primarily by Alexander Svetalkin, with updates for delta |
| 3974 | // time by Gary Scavone, April 2011. |
| 3975 | // |
| 3976 | // *********************************************************************// |
| 3977 | |
| 3978 | #if defined(__UNIX_JACK__) |
| 3979 | |
| 3980 | // JACK header files |
| 3981 | #include <jack/jack.h> |
| 3982 | #include <jack/midiport.h> |
| 3983 | #include <jack/ringbuffer.h> |
| 3984 | #include <pthread.h> |
| 3985 | #include <sched.h> |
| 3986 | #ifdef HAVE_SEMAPHORE |
| 3987 | #include <semaphore.h> |
| 3988 | #endif |
| 3989 | |
| 3990 | #define JACK_RINGBUFFER_SIZE 16384 // Default size for ringbuffer |
| 3991 | |
| 3992 | struct JackMidiData { |
| 3993 | jack_client_t *client; |
| 3994 | jack_port_t *port; |
| 3995 | jack_ringbuffer_t *buff; |
| 3996 | int buffMaxWrite; // actual writable size, usually 1 less than ringbuffer |
| 3997 | jack_time_t lastTime; |
| 3998 | #ifdef HAVE_SEMAPHORE |
| 3999 | sem_t sem_cleanup; |
| 4000 | sem_t sem_needpost; |
| 4001 | #endif |
| 4002 | MidiInApi :: RtMidiInData *rtMidiIn; |
| 4003 | }; |
| 4004 | |
| 4005 | //*********************************************************************// |
| 4006 | // API: JACK |
| 4007 | // Class Definitions: MidiInJack |
| 4008 | //*********************************************************************// |
| 4009 | |
| 4010 | static int jackProcessIn( jack_nframes_t nframes, void *arg ) |
| 4011 | { |
| 4012 | JackMidiData *jData = (JackMidiData *) arg; |
| 4013 | MidiInApi :: RtMidiInData *rtData = jData->rtMidiIn; |
| 4014 | jack_midi_event_t event; |
| 4015 | jack_time_t time; |
| 4016 | |
| 4017 | // Is port created? |
| 4018 | if ( jData->port == NULL ) return 0; |
| 4019 | |
| 4020 | void *buff = jack_port_get_buffer( jData->port, nframes ); |
| 4021 | bool& continueSysex = rtData->continueSysex; |
| 4022 | unsigned char& ignoreFlags = rtData->ignoreFlags; |
| 4023 | |
| 4024 | // We have midi events in buffer |
| 4025 | int evCount = jack_midi_get_event_count( buff ); |
| 4026 | for (int j = 0; j < evCount; j++) { |
| 4027 | MidiInApi::MidiMessage& message = rtData->message; |
| 4028 | jack_midi_event_get( &event, buff, j ); |
| 4029 | |
| 4030 | // Compute the delta time. |
| 4031 | time = jack_get_time(); |
| 4032 | if ( rtData->firstMessage == true ) { |
| 4033 | message.timeStamp = 0.0; |
| 4034 | rtData->firstMessage = false; |
| 4035 | } else |
| 4036 | message.timeStamp = ( time - jData->lastTime ) * 0.000001; |
| 4037 | |
| 4038 | jData->lastTime = time; |
| 4039 | |
| 4040 | if ( !continueSysex ) |
| 4041 | message.bytes.clear(); |
| 4042 | |
| 4043 | if ( !( ( continueSysex || event.buffer[0] == 0xF0 ) && ( ignoreFlags & 0x01 ) ) ) { |
| 4044 | // Unless this is a (possibly continued) SysEx message and we're ignoring SysEx, |
| 4045 | // copy the event buffer into the MIDI message struct. |
| 4046 | for ( unsigned int i = 0; i < event.size; i++ ) |
| 4047 | message.bytes.push_back( event.buffer[i] ); |
| 4048 | } |
| 4049 | |
| 4050 | switch ( event.buffer[0] ) { |
| 4051 | case 0xF0: |
| 4052 | // Start of a SysEx message |
| 4053 | continueSysex = event.buffer[event.size - 1] != 0xF7; |
| 4054 | if ( ignoreFlags & 0x01 ) continue; |
| 4055 | break; |
| 4056 | case 0xF1: |
| 4057 | case 0xF8: |
| 4058 | // MIDI Time Code or Timing Clock message |
| 4059 | if ( ignoreFlags & 0x02 ) continue; |
| 4060 | break; |
| 4061 | case 0xFE: |
| 4062 | // Active Sensing message |
| 4063 | if ( ignoreFlags & 0x04 ) continue; |
| 4064 | break; |
| 4065 | default: |
| 4066 | if ( continueSysex ) { |
| 4067 | // Continuation of a SysEx message |
| 4068 | continueSysex = event.buffer[event.size - 1] != 0xF7; |
| 4069 | if ( ignoreFlags & 0x01 ) continue; |
| 4070 | } |
| 4071 | // All other MIDI messages |
| 4072 | } |
| 4073 | |
| 4074 | if ( !continueSysex ) { |
| 4075 | // If not a continuation of a SysEx message, |
| 4076 | // invoke the user callback function or queue the message. |
| 4077 | if ( rtData->usingCallback ) { |
| 4078 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) rtData->userCallback; |
| 4079 | callback( message.timeStamp, &message.bytes, rtData->userData ); |
| 4080 | } |
| 4081 | else { |
| 4082 | // As long as we haven't reached our queue size limit, push the message. |
| 4083 | if ( !rtData->queue.push( message ) ) |
| 4084 | std::cerr << "\nMidiInJack: message queue limit reached!!\n\n"; |
| 4085 | } |
| 4086 | } |
| 4087 | } |
| 4088 | |
| 4089 | return 0; |
| 4090 | } |
| 4091 | |
| 4092 | MidiInJack :: MidiInJack( const std::string &clientName, unsigned int queueSizeLimit ) |
| 4093 | : MidiInApi( queueSizeLimit ) |
| 4094 | { |
| 4095 | MidiInJack::initialize( clientName ); |
| 4096 | } |
| 4097 | |
| 4098 | void MidiInJack :: initialize( const std::string& clientName ) |
| 4099 | { |
| 4100 | JackMidiData *data = new JackMidiData; |
| 4101 | apiData_ = (void *) data; |
| 4102 | |
| 4103 | data->rtMidiIn = &inputData_; |
| 4104 | data->port = NULL; |
| 4105 | data->client = NULL; |
| 4106 | this->clientName = clientName; |
| 4107 | |
| 4108 | connect(); |
| 4109 | } |
| 4110 | |
| 4111 | void MidiInJack :: connect() |
| 4112 | { |
| 4113 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4114 | if ( data->client ) |
| 4115 | return; |
| 4116 | |
| 4117 | // Initialize JACK client |
| 4118 | if (( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL )) == 0) { |
| 4119 | errorString_ = "MidiInJack::initialize: JACK server not running?"; |
| 4120 | error( RtMidiError::WARNING, errorString_ ); |
| 4121 | return; |
| 4122 | } |
| 4123 | |
| 4124 | jack_set_process_callback( data->client, jackProcessIn, data ); |
| 4125 | jack_activate( data->client ); |
| 4126 | } |
| 4127 | |
| 4128 | MidiInJack :: ~MidiInJack() |
| 4129 | { |
| 4130 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4131 | MidiInJack::closePort(); |
| 4132 | |
| 4133 | if ( data->client ) |
| 4134 | jack_client_close( data->client ); |
| 4135 | delete data; |
| 4136 | } |
| 4137 | |
| 4138 | void MidiInJack :: openPort( unsigned int portNumber, const std::string &portName ) |
| 4139 | { |
| 4140 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4141 | |
| 4142 | connect(); |
| 4143 | |
| 4144 | // Creating new port |
| 4145 | if ( data->port == NULL ) |
| 4146 | data->port = jack_port_register( data->client, portName.c_str(), |
| 4147 | JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); |
| 4148 | |
| 4149 | if ( data->port == NULL ) { |
| 4150 | errorString_ = "MidiInJack::openPort: JACK error creating port"; |
| 4151 | if (portName.size() >= (size_t)jack_port_name_size()) |
| 4152 | errorString_ += " (port name too long?)"; |
| 4153 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 4154 | return; |
| 4155 | } |
| 4156 | |
| 4157 | // Connecting to the output |
| 4158 | std::string name = getPortName( portNumber ); |
| 4159 | jack_connect( data->client, name.c_str(), jack_port_name( data->port ) ); |
| 4160 | |
| 4161 | connected_ = true; |
| 4162 | } |
| 4163 | |
| 4164 | void MidiInJack :: openVirtualPort( const std::string &portName ) |
| 4165 | { |
| 4166 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4167 | |
| 4168 | connect(); |
| 4169 | if ( data->port == NULL ) |
| 4170 | data->port = jack_port_register( data->client, portName.c_str(), |
| 4171 | JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0 ); |
| 4172 | |
| 4173 | if ( data->port == NULL ) { |
| 4174 | errorString_ = "MidiInJack::openVirtualPort: JACK error creating virtual port"; |
| 4175 | if (portName.size() >= (size_t)jack_port_name_size()) |
| 4176 | errorString_ += " (port name too long?)"; |
| 4177 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 4178 | } |
| 4179 | } |
| 4180 | |
| 4181 | unsigned int MidiInJack :: getPortCount() |
| 4182 | { |
| 4183 | int count = 0; |
| 4184 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4185 | connect(); |
| 4186 | if ( !data->client ) |
| 4187 | return 0; |
| 4188 | |
| 4189 | // List of available ports |
| 4190 | const char **ports = jack_get_ports( data->client, NULL, JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); |
| 4191 | |
| 4192 | if ( ports == NULL ) return 0; |
| 4193 | while ( ports[count] != NULL ) |
| 4194 | count++; |
| 4195 | |
| 4196 | free( ports ); |
| 4197 | |
| 4198 | return count; |
| 4199 | } |
| 4200 | |
| 4201 | std::string MidiInJack :: getPortName( unsigned int portNumber ) |
| 4202 | { |
| 4203 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4204 | std::string retStr( "" ); |
| 4205 | |
| 4206 | connect(); |
| 4207 | |
| 4208 | // List of available ports |
| 4209 | const char **ports = jack_get_ports( data->client, NULL, |
| 4210 | JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput ); |
| 4211 | |
| 4212 | // Check port validity |
| 4213 | if ( ports == NULL ) { |
| 4214 | errorString_ = "MidiInJack::getPortName: no ports available!"; |
| 4215 | error( RtMidiError::WARNING, errorString_ ); |
| 4216 | return retStr; |
| 4217 | } |
| 4218 | |
| 4219 | unsigned int i; |
| 4220 | for ( i=0; i<portNumber && ports[i]; i++ ) {} |
| 4221 | if ( i < portNumber || !ports[portNumber] ) { |
| 4222 | std::ostringstream ost; |
| 4223 | ost << "MidiInJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 4224 | errorString_ = ost.str(); |
| 4225 | error( RtMidiError::WARNING, errorString_ ); |
| 4226 | } |
| 4227 | else retStr.assign( ports[portNumber] ); |
| 4228 | |
| 4229 | jack_free( ports ); |
| 4230 | return retStr; |
| 4231 | } |
| 4232 | |
| 4233 | void MidiInJack :: closePort() |
| 4234 | { |
| 4235 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4236 | |
| 4237 | if ( data->port == NULL ) return; |
| 4238 | jack_port_unregister( data->client, data->port ); |
| 4239 | data->port = NULL; |
| 4240 | |
| 4241 | connected_ = false; |
| 4242 | } |
| 4243 | |
| 4244 | void MidiInJack:: setClientName( const std::string& ) |
| 4245 | { |
| 4246 | |
| 4247 | errorString_ = "MidiInJack::setClientName: this function is not implemented for the UNIX_JACK API!"; |
| 4248 | error( RtMidiError::WARNING, errorString_ ); |
| 4249 | |
| 4250 | } |
| 4251 | |
| 4252 | //-------------------------- |
| 4253 | #ifndef JACK_HAS_PORT_RENAME |
| 4254 | // (chuck 1.5.5.1 2025) JACK_HAS_PORT_RENAME appears to not be defined |
| 4255 | // even when jack_port_rename() is present in the header; defining |
| 4256 | // here, assuming jack_port_rename() is present as it has been part of |
| 4257 | // the API since 2015; if a compilation error brought you here, try |
| 4258 | // commenting out the following line: |
| 4259 | #define JACK_HAS_PORT_RENAME |
| 4260 | #endif |
| 4261 | //-------------------------- |
| 4262 | void MidiInJack :: setPortName( const std::string &portName ) |
| 4263 | { |
| 4264 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4265 | #ifdef JACK_HAS_PORT_RENAME |
| 4266 | // if a compiler error brought you, see above comment regarding #define JACK_HAS_PORT_RENAME |
| 4267 | jack_port_rename( data->client, data->port, portName.c_str() ); |
| 4268 | #else |
| 4269 | jack_port_set_name( data->port, portName.c_str() ); |
| 4270 | #endif |
| 4271 | } |
| 4272 | |
| 4273 | //*********************************************************************// |
| 4274 | // API: JACK |
| 4275 | // Class Definitions: MidiOutJack |
| 4276 | //*********************************************************************// |
| 4277 | |
| 4278 | // Jack process callback |
| 4279 | static int jackProcessOut( jack_nframes_t nframes, void *arg ) |
| 4280 | { |
| 4281 | JackMidiData *data = (JackMidiData *) arg; |
| 4282 | jack_midi_data_t *midiData; |
| 4283 | int space; |
| 4284 | |
| 4285 | // Is port created? |
| 4286 | if ( data->port == NULL ) return 0; |
| 4287 | |
| 4288 | void *buff = jack_port_get_buffer( data->port, nframes ); |
| 4289 | jack_midi_clear_buffer( buff ); |
| 4290 | |
| 4291 | while ( jack_ringbuffer_peek( data->buff, (char *) &space, sizeof( space ) ) == sizeof(space) && |
| 4292 | jack_ringbuffer_read_space( data->buff ) >= sizeof(space) + space ) { |
| 4293 | jack_ringbuffer_read_advance( data->buff, sizeof(space) ); |
| 4294 | |
| 4295 | midiData = jack_midi_event_reserve( buff, 0, space ); |
| 4296 | if ( midiData ) |
| 4297 | jack_ringbuffer_read( data->buff, (char *) midiData, (size_t) space ); |
| 4298 | else |
| 4299 | jack_ringbuffer_read_advance( data->buff, (size_t) space ); |
| 4300 | } |
| 4301 | |
| 4302 | #ifdef HAVE_SEMAPHORE |
| 4303 | if ( !sem_trywait( &data->sem_needpost ) ) |
| 4304 | sem_post( &data->sem_cleanup ); |
| 4305 | #endif |
| 4306 | |
| 4307 | return 0; |
| 4308 | } |
| 4309 | |
| 4310 | MidiOutJack :: MidiOutJack( const std::string &clientName ) : MidiOutApi() |
| 4311 | { |
| 4312 | MidiOutJack::initialize( clientName ); |
| 4313 | } |
| 4314 | |
| 4315 | void MidiOutJack :: initialize( const std::string& clientName ) |
| 4316 | { |
| 4317 | JackMidiData *data = new JackMidiData; |
| 4318 | apiData_ = (void *) data; |
| 4319 | |
| 4320 | data->port = NULL; |
| 4321 | data->client = NULL; |
| 4322 | #ifdef HAVE_SEMAPHORE |
| 4323 | sem_init( &data->sem_cleanup, 0, 0 ); |
| 4324 | sem_init( &data->sem_needpost, 0, 0 ); |
| 4325 | #endif |
| 4326 | this->clientName = clientName; |
| 4327 | |
| 4328 | connect(); |
| 4329 | } |
| 4330 | |
| 4331 | void MidiOutJack :: connect() |
| 4332 | { |
| 4333 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4334 | if ( data->client ) |
| 4335 | return; |
| 4336 | |
| 4337 | // Initialize output ringbuffers |
| 4338 | data->buff = jack_ringbuffer_create( JACK_RINGBUFFER_SIZE ); |
| 4339 | data->buffMaxWrite = (int) jack_ringbuffer_write_space( data->buff ); |
| 4340 | |
| 4341 | // Initialize JACK client |
| 4342 | if ( ( data->client = jack_client_open( clientName.c_str(), JackNoStartServer, NULL ) ) == 0 ) { |
| 4343 | errorString_ = "MidiOutJack::initialize: JACK server not running?"; |
| 4344 | error( RtMidiError::WARNING, errorString_ ); |
| 4345 | return; |
| 4346 | } |
| 4347 | |
| 4348 | jack_set_process_callback( data->client, jackProcessOut, data ); |
| 4349 | jack_activate( data->client ); |
| 4350 | } |
| 4351 | |
| 4352 | MidiOutJack :: ~MidiOutJack() |
| 4353 | { |
| 4354 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4355 | MidiOutJack::closePort(); |
| 4356 | |
| 4357 | // Cleanup |
| 4358 | jack_ringbuffer_free( data->buff ); |
| 4359 | if ( data->client ) { |
| 4360 | jack_client_close( data->client ); |
| 4361 | } |
| 4362 | |
| 4363 | #ifdef HAVE_SEMAPHORE |
| 4364 | sem_destroy( &data->sem_cleanup ); |
| 4365 | sem_destroy( &data->sem_needpost ); |
| 4366 | #endif |
| 4367 | |
| 4368 | delete data; |
| 4369 | } |
| 4370 | |
| 4371 | void MidiOutJack :: openPort( unsigned int portNumber, const std::string &portName ) |
| 4372 | { |
| 4373 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4374 | |
| 4375 | connect(); |
| 4376 | |
| 4377 | // Creating new port |
| 4378 | if ( data->port == NULL ) |
| 4379 | data->port = jack_port_register( data->client, portName.c_str(), |
| 4380 | JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); |
| 4381 | |
| 4382 | if ( data->port == NULL ) { |
| 4383 | errorString_ = "MidiOutJack::openPort: JACK error creating port"; |
| 4384 | if (portName.size() >= (size_t)jack_port_name_size()) |
| 4385 | errorString_ += " (port name too long?)"; |
| 4386 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 4387 | return; |
| 4388 | } |
| 4389 | |
| 4390 | // Connecting to the output |
| 4391 | std::string name = getPortName( portNumber ); |
| 4392 | jack_connect( data->client, jack_port_name( data->port ), name.c_str() ); |
| 4393 | |
| 4394 | connected_ = true; |
| 4395 | } |
| 4396 | |
| 4397 | void MidiOutJack :: openVirtualPort( const std::string &portName ) |
| 4398 | { |
| 4399 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4400 | |
| 4401 | connect(); |
| 4402 | if ( data->port == NULL ) |
| 4403 | data->port = jack_port_register( data->client, portName.c_str(), |
| 4404 | JACK_DEFAULT_MIDI_TYPE, JackPortIsOutput, 0 ); |
| 4405 | |
| 4406 | if ( data->port == NULL ) { |
| 4407 | errorString_ = "MidiOutJack::openVirtualPort: JACK error creating virtual port"; |
| 4408 | if (portName.size() >= (size_t)jack_port_name_size()) |
| 4409 | errorString_ += " (port name too long?)"; |
| 4410 | error( RtMidiError::DRIVER_ERROR, errorString_ ); |
| 4411 | } |
| 4412 | } |
| 4413 | |
| 4414 | unsigned int MidiOutJack :: getPortCount() |
| 4415 | { |
| 4416 | int count = 0; |
| 4417 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4418 | connect(); |
| 4419 | if ( !data->client ) |
| 4420 | return 0; |
| 4421 | |
| 4422 | // List of available ports |
| 4423 | const char **ports = jack_get_ports( data->client, NULL, |
| 4424 | JACK_DEFAULT_MIDI_TYPE, JackPortIsInput ); |
| 4425 | |
| 4426 | if ( ports == NULL ) return 0; |
| 4427 | while ( ports[count] != NULL ) |
| 4428 | count++; |
| 4429 | |
| 4430 | free( ports ); |
| 4431 | |
| 4432 | return count; |
| 4433 | } |
| 4434 | |
| 4435 | std::string MidiOutJack :: getPortName( unsigned int portNumber ) |
| 4436 | { |
| 4437 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4438 | std::string retStr(""); |
| 4439 | |
| 4440 | connect(); |
| 4441 | |
| 4442 | // List of available ports |
| 4443 | const char **ports = jack_get_ports( data->client, NULL, |
| 4444 | JACK_DEFAULT_MIDI_TYPE, JackPortIsInput ); |
| 4445 | |
| 4446 | // Check port validity |
| 4447 | if ( ports == NULL ) { |
| 4448 | errorString_ = "MidiOutJack::getPortName: no ports available!"; |
| 4449 | error( RtMidiError::WARNING, errorString_ ); |
| 4450 | return retStr; |
| 4451 | } |
| 4452 | |
| 4453 | if ( ports[portNumber] == NULL ) { |
| 4454 | std::ostringstream ost; |
| 4455 | ost << "MidiOutJack::getPortName: the 'portNumber' argument (" << portNumber << ") is invalid."; |
| 4456 | errorString_ = ost.str(); |
| 4457 | error( RtMidiError::WARNING, errorString_ ); |
| 4458 | } |
| 4459 | else retStr.assign( ports[portNumber] ); |
| 4460 | |
| 4461 | free( ports ); |
| 4462 | return retStr; |
| 4463 | } |
| 4464 | |
| 4465 | void MidiOutJack :: closePort() |
| 4466 | { |
| 4467 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4468 | |
| 4469 | if ( data->port == NULL ) return; |
| 4470 | |
| 4471 | #ifdef HAVE_SEMAPHORE |
| 4472 | struct timespec ts; |
| 4473 | if ( clock_gettime( CLOCK_REALTIME, &ts ) != -1 ) { |
| 4474 | ts.tv_sec += 1; // wait max one second |
| 4475 | sem_post( &data->sem_needpost ); |
| 4476 | sem_timedwait( &data->sem_cleanup, &ts ); |
| 4477 | } |
| 4478 | #endif |
| 4479 | |
| 4480 | jack_port_unregister( data->client, data->port ); |
| 4481 | data->port = NULL; |
| 4482 | |
| 4483 | connected_ = false; |
| 4484 | } |
| 4485 | |
| 4486 | void MidiOutJack:: setClientName( const std::string& ) |
| 4487 | { |
| 4488 | |
| 4489 | errorString_ = "MidiOutJack::setClientName: this function is not implemented for the UNIX_JACK API!"; |
| 4490 | error( RtMidiError::WARNING, errorString_ ); |
| 4491 | |
| 4492 | } |
| 4493 | |
| 4494 | //-------------------------- |
| 4495 | void MidiOutJack :: setPortName( const std::string &portName ) |
| 4496 | { |
| 4497 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4498 | #ifdef JACK_HAS_PORT_RENAME |
| 4499 | // if a compiler error brought you, see above comment regarding #define JACK_HAS_PORT_RENAME |
| 4500 | jack_port_rename( data->client, data->port, portName.c_str() ); |
| 4501 | #else |
| 4502 | jack_port_set_name( data->port, portName.c_str() ); |
| 4503 | #endif |
| 4504 | } |
| 4505 | |
| 4506 | void MidiOutJack :: sendMessage( const unsigned char *message, size_t size ) |
| 4507 | { |
| 4508 | int nBytes = static_cast<int>(size); |
| 4509 | JackMidiData *data = static_cast<JackMidiData *> (apiData_); |
| 4510 | |
| 4511 | if ( size + sizeof(nBytes) > (size_t) data->buffMaxWrite ) |
| 4512 | return; |
| 4513 | |
| 4514 | while ( jack_ringbuffer_write_space(data->buff) < sizeof(nBytes) + size ) |
| 4515 | sched_yield(); |
| 4516 | |
| 4517 | // Write full message to buffer |
| 4518 | jack_ringbuffer_write( data->buff, ( char * ) &nBytes, sizeof( nBytes ) ); |
| 4519 | jack_ringbuffer_write( data->buff, ( const char * ) message, nBytes ); |
| 4520 | } |
| 4521 | |
| 4522 | #endif // __UNIX_JACK__ |
| 4523 | |
| 4524 | //*********************************************************************// |
| 4525 | // API: Web MIDI |
| 4526 | // |
| 4527 | // Written primarily by Atsushi Eno, February 2020. |
| 4528 | // |
| 4529 | // *********************************************************************// |
| 4530 | |
| 4531 | #if defined(__WEB_MIDI_API__) |
| 4532 | |
| 4533 | #include <emscripten.h> |
| 4534 | |
| 4535 | //*********************************************************************// |
| 4536 | // API: WEB MIDI |
| 4537 | // Class Definitions: WebMidiAccessShim |
| 4538 | //*********************************************************************// |
| 4539 | |
| 4540 | class WebMidiAccessShim |
| 4541 | { |
| 4542 | public: |
| 4543 | WebMidiAccessShim(); |
| 4544 | ~WebMidiAccessShim(); |
| 4545 | std::string getPortName( unsigned int portNumber, bool isInput ); |
| 4546 | }; |
| 4547 | |
| 4548 | std::unique_ptr<WebMidiAccessShim> shim{nullptr}; |
| 4549 | |
| 4550 | void ensureShim() |
| 4551 | { |
| 4552 | if ( shim.get() != nullptr ) |
| 4553 | return; |
| 4554 | shim.reset( new WebMidiAccessShim() ); |
| 4555 | } |
| 4556 | |
| 4557 | bool checkWebMidiAvailability() |
| 4558 | { |
| 4559 | ensureShim(); |
| 4560 | |
| 4561 | return MAIN_THREAD_EM_ASM_INT( { |
| 4562 | if ( typeof window._rtmidi_internals_waiting === "undefined" ) { |
| 4563 | console.log ( "Attempted to use Web MIDI API without trying to open it." ); |
| 4564 | return false; |
| 4565 | } |
| 4566 | if ( window._rtmidi_internals_waiting ) { |
| 4567 | console.log ( "Attempted to use Web MIDI API while it is being queried." ); |
| 4568 | return false; |
| 4569 | } |
| 4570 | if ( _rtmidi_internals_midi_access == null ) { |
| 4571 | console.log ( "Attempted to use Web MIDI API while it already turned out to be unavailable." ); |
| 4572 | return false; |
| 4573 | } |
| 4574 | return true; |
| 4575 | } ); |
| 4576 | } |
| 4577 | |
| 4578 | WebMidiAccessShim::WebMidiAccessShim() |
| 4579 | { |
| 4580 | MAIN_THREAD_ASYNC_EM_ASM( { |
| 4581 | if( typeof window._rtmidi_internals_midi_access !== "undefined" ) |
| 4582 | return; |
| 4583 | if( typeof window._rtmidi_internals_waiting !== "undefined" ) { |
| 4584 | console.log( "MIDI Access was requested while another request is in progress." ); |
| 4585 | return; |
| 4586 | } |
| 4587 | |
| 4588 | // define functions |
| 4589 | window._rtmidi_internals_get_port_by_number = function( portNumber, isInput ) { |
| 4590 | var midi = window._rtmidi_internals_midi_access; |
| 4591 | var devices = isInput ? midi.inputs : midi.outputs; |
| 4592 | var i = 0; |
| 4593 | for (var device of devices.values()) { |
| 4594 | if ( i == portNumber ) |
| 4595 | return device; |
| 4596 | i++; |
| 4597 | } |
| 4598 | console.log( "MIDI " + (isInput ? "input" : "output") + " device of portNumber " + portNumber + " is not found."); |
| 4599 | return null; |
| 4600 | }; |
| 4601 | |
| 4602 | window._rtmidi_internals_waiting = true; |
| 4603 | window.navigator.requestMIDIAccess( {"sysex": true} ).then( (midiAccess) => { |
| 4604 | window._rtmidi_internals_midi_access = midiAccess; |
| 4605 | window._rtmidi_internals_latest_message_timestamp = 0.0; |
| 4606 | window._rtmidi_internals_waiting = false; |
| 4607 | if( midiAccess == null ) { |
| 4608 | console.log ( "Could not get access to MIDI API" ); |
| 4609 | } |
| 4610 | } ); |
| 4611 | } ); |
| 4612 | } |
| 4613 | |
| 4614 | WebMidiAccessShim::~WebMidiAccessShim() |
| 4615 | { |
| 4616 | } |
| 4617 | |
| 4618 | std::string WebMidiAccessShim::getPortName( unsigned int portNumber, bool isInput ) |
| 4619 | { |
| 4620 | if( !checkWebMidiAvailability() ) |
| 4621 | return ""; |
| 4622 | char *ret = (char*) MAIN_THREAD_EM_ASM_INT( { |
| 4623 | var port = window._rtmidi_internals_get_port_by_number($0, $1); |
| 4624 | if( port == null) |
| 4625 | return null; |
| 4626 | var length = lengthBytesUTF8(port.name) + 1; |
| 4627 | var ret = _malloc(length); |
| 4628 | stringToUTF8(port.name, ret, length); |
| 4629 | return ret; |
| 4630 | }, portNumber, isInput); |
| 4631 | if (ret == nullptr) |
| 4632 | return ""; |
| 4633 | std::string s = ret; |
| 4634 | free(ret); |
| 4635 | return s; |
| 4636 | } |
| 4637 | |
| 4638 | //*********************************************************************// |
| 4639 | // API: WEB MIDI |
| 4640 | // Class Definitions: MidiInWeb |
| 4641 | //*********************************************************************// |
| 4642 | |
| 4643 | MidiInWeb::MidiInWeb( const std::string &clientName, unsigned int queueSizeLimit ) |
| 4644 | : MidiInApi( queueSizeLimit ) |
| 4645 | { |
| 4646 | initialize( clientName ); |
| 4647 | } |
| 4648 | |
| 4649 | MidiInWeb::~MidiInWeb( void ) |
| 4650 | { |
| 4651 | closePort(); |
| 4652 | } |
| 4653 | |
| 4654 | extern "C" void EMSCRIPTEN_KEEPALIVE rtmidi_onMidiMessageProc( MidiInApi::RtMidiInData* data, uint8_t* inputBytes, int32_t length, double domHighResTimeStamp ) |
| 4655 | { |
| 4656 | auto &message = data->message; |
| 4657 | message.bytes.resize(message.bytes.size() + length); |
| 4658 | memcpy(message.bytes.data(), inputBytes, length); |
| 4659 | // FIXME: handle timestamp |
| 4660 | if ( data->usingCallback ) { |
| 4661 | RtMidiIn::RtMidiCallback callback = (RtMidiIn::RtMidiCallback) data->userCallback; |
| 4662 | callback( message.timeStamp, &message.bytes, data->userData ); |
| 4663 | } |
| 4664 | } |
| 4665 | |
| 4666 | void MidiInWeb::openPort( unsigned int portNumber, const std::string &portName ) |
| 4667 | { |
| 4668 | if( !checkWebMidiAvailability() ) |
| 4669 | return; |
| 4670 | if (open_port_number >= 0) |
| 4671 | return; |
| 4672 | |
| 4673 | MAIN_THREAD_EM_ASM( { |
| 4674 | // In Web MIDI API world, there is no step to open a port, but we have to register the input callback instead. |
| 4675 | var input = window._rtmidi_internals_get_port_by_number($0, true); |
| 4676 | input.onmidimessage = function(e) { |
| 4677 | // In RtMidi world, timestamps are delta time from previous message, while in Web MIDI world |
| 4678 | // timestamps are relative to window creation time (i.e. kind of absolute time with window "epoch" time). |
| 4679 | var rtmidiTimestamp = window._rtmidi_internals_latest_message_timestamp == 0.0 ? 0.0 : e.timeStamp - window._rtmidi_internals_latest_message_timestamp; |
| 4680 | window._rtmidi_internals_latest_message_timestamp = e.timeStamp; |
| 4681 | Module.ccall( 'rtmidi_onMidiMessageProc', 'void', ['number', 'array', 'number', 'number'], [$1, e.data, e.data.length, rtmidiTimestamp] ); |
| 4682 | }; |
| 4683 | }, portNumber, &inputData_ ); |
| 4684 | open_port_number = portNumber; |
| 4685 | connected_ = true; |
| 4686 | } |
| 4687 | |
| 4688 | void MidiInWeb::openVirtualPort( const std::string &portName ) |
| 4689 | { |
| 4690 | |
| 4691 | errorString_ = "MidiInWeb::openVirtualPort: this function is not implemented for the Web MIDI API!"; |
| 4692 | error( RtMidiError::WARNING, errorString_ ); |
| 4693 | |
| 4694 | } |
| 4695 | |
| 4696 | void MidiInWeb::closePort( void ) |
| 4697 | { |
| 4698 | if( open_port_number < 0 ) |
| 4699 | return; |
| 4700 | |
| 4701 | MAIN_THREAD_EM_ASM( { |
| 4702 | var input = _rtmidi_internals_get_port_by_number($0, true); |
| 4703 | if( input == null ) { |
| 4704 | console.log( "Port #" + $0 + " could not be found."); |
| 4705 | return; |
| 4706 | } |
| 4707 | // unregister event handler |
| 4708 | input.onmidimessage = null; |
| 4709 | }, open_port_number ); |
| 4710 | open_port_number = -1; |
| 4711 | connected_ = false; |
| 4712 | } |
| 4713 | |
| 4714 | void MidiInWeb::setClientName( const std::string &clientName ) |
| 4715 | { |
| 4716 | client_name = clientName; |
| 4717 | } |
| 4718 | |
| 4719 | void MidiInWeb::setPortName( const std::string &portName ) |
| 4720 | { |
| 4721 | |
| 4722 | errorString_ = "MidiInWeb::setPortName: this function is not implemented for the Web MIDI API!"; |
| 4723 | error( RtMidiError::WARNING, errorString_ ); |
| 4724 | |
| 4725 | } |
| 4726 | |
| 4727 | unsigned int MidiInWeb::getPortCount( void ) |
| 4728 | { |
| 4729 | if( !checkWebMidiAvailability() ) |
| 4730 | return 0; |
| 4731 | return MAIN_THREAD_EM_ASM_INT( { return _rtmidi_internals_midi_access.inputs.size; } ); |
| 4732 | } |
| 4733 | |
| 4734 | std::string MidiInWeb::getPortName( unsigned int portNumber ) |
| 4735 | { |
| 4736 | if( !checkWebMidiAvailability() ) |
| 4737 | return ""; |
| 4738 | return shim->getPortName( portNumber, true ); |
| 4739 | } |
| 4740 | |
| 4741 | void MidiInWeb::initialize( const std::string& clientName ) |
| 4742 | { |
| 4743 | ensureShim(); |
| 4744 | setClientName( clientName ); |
| 4745 | } |
| 4746 | |
| 4747 | //*********************************************************************// |
| 4748 | // API: WEB MIDI |
| 4749 | // Class Definitions: MidiOutWeb |
| 4750 | //*********************************************************************// |
| 4751 | |
| 4752 | MidiOutWeb::MidiOutWeb( const std::string &clientName ) |
| 4753 | { |
| 4754 | initialize( clientName ); |
| 4755 | } |
| 4756 | |
| 4757 | MidiOutWeb::~MidiOutWeb( void ) |
| 4758 | { |
| 4759 | closePort(); |
| 4760 | } |
| 4761 | |
| 4762 | void MidiOutWeb::openPort( unsigned int portNumber, const std::string &portName ) |
| 4763 | { |
| 4764 | if( !checkWebMidiAvailability() ) |
| 4765 | return; |
| 4766 | if (open_port_number >= 0) |
| 4767 | return; |
| 4768 | // In Web MIDI API world, there is no step to open a port. |
| 4769 | |
| 4770 | open_port_number = portNumber; |
| 4771 | connected_ = true; |
| 4772 | } |
| 4773 | |
| 4774 | void MidiOutWeb::openVirtualPort( const std::string &portName ) |
| 4775 | { |
| 4776 | |
| 4777 | errorString_ = "MidiOutWeb::openVirtualPort: this function is not implemented for the Web MIDI API!"; |
| 4778 | error( RtMidiError::WARNING, errorString_ ); |
| 4779 | |
| 4780 | } |
| 4781 | |
| 4782 | void MidiOutWeb::closePort( void ) |
| 4783 | { |
| 4784 | // there is really nothing to do for output at JS side. |
| 4785 | open_port_number = -1; |
| 4786 | connected_ = false; |
| 4787 | } |
| 4788 | |
| 4789 | void MidiOutWeb::setClientName( const std::string &clientName ) |
| 4790 | { |
| 4791 | client_name = clientName; |
| 4792 | } |
| 4793 | |
| 4794 | void MidiOutWeb::setPortName( const std::string &portName ) |
| 4795 | { |
| 4796 | |
| 4797 | errorString_ = "MidiOutWeb::setPortName: this function is not implemented for the Web MIDI API!"; |
| 4798 | error( RtMidiError::WARNING, errorString_ ); |
| 4799 | |
| 4800 | } |
| 4801 | |
| 4802 | unsigned int MidiOutWeb::getPortCount( void ) |
| 4803 | { |
| 4804 | if( !checkWebMidiAvailability() ) |
| 4805 | return 0; |
| 4806 | return MAIN_THREAD_EM_ASM_INT( { return _rtmidi_internals_midi_access.outputs.size; } ); |
| 4807 | } |
| 4808 | |
| 4809 | std::string MidiOutWeb::getPortName( unsigned int portNumber ) |
| 4810 | { |
| 4811 | if( !checkWebMidiAvailability() ) |
| 4812 | return ""; |
| 4813 | return shim->getPortName( portNumber, false ); |
| 4814 | } |
| 4815 | |
| 4816 | void MidiOutWeb::sendMessage( const unsigned char *message, size_t size ) |
| 4817 | { |
| 4818 | if( open_port_number < 0 ) |
| 4819 | return; |
| 4820 | |
| 4821 | MAIN_THREAD_EM_ASM( { |
| 4822 | var output = _rtmidi_internals_get_port_by_number( $0, false ); |
| 4823 | if( output == null ) { |
| 4824 | console.log( "Port #" + $0 + " could not be found."); |
| 4825 | return; |
| 4826 | } |
| 4827 | var buf = new ArrayBuffer ($2); |
| 4828 | var msg = new Uint8Array( buf ); |
| 4829 | msg.set( new Uint8Array( Module.HEAPU8.buffer.slice( $1, $1 + $2 ) ) ); |
| 4830 | output.send( msg ); |
| 4831 | }, open_port_number, message, size ); |
| 4832 | } |
| 4833 | |
| 4834 | void MidiOutWeb::initialize( const std::string& clientName ) |
| 4835 | { |
| 4836 | if ( shim.get() != nullptr ) |
| 4837 | return; |
| 4838 | shim.reset( new WebMidiAccessShim() ); |
| 4839 | setClientName( clientName ); |
| 4840 | } |
| 4841 | |
| 4842 | #endif // __WEB_MIDI_API__ |
| 4843 | |
| 4844 | |
| 4845 | //*********************************************************************// |
| 4846 | // API: ANDROID AMIDI |
| 4847 | // |
| 4848 | // Written by Yellow Labrador, May 2023. |
| 4849 | // https://github.com/YellowLabrador/rtmidi |
| 4850 | // *********************************************************************// |
| 4851 | |
| 4852 | #if defined(__AMIDI__) |
| 4853 | |
| 4854 | #include <cstdint> |
| 4855 | |
| 4856 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) |
| 4857 | #define LOGW(...) __android_log_print(ANDROID_LOG_WARN, LOG_TAG, __VA_ARGS__) |
| 4858 | #define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__) |
| 4859 | #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) |
| 4860 | |
| 4861 | static std::string androidClientName; |
| 4862 | static std::vector<jobject> androidMidiDevices; |
| 4863 | |
| 4864 | //*********************************************************************// |
| 4865 | // API: Android AMIDI |
| 4866 | // Class Definitions: MidiInAndroid |
| 4867 | //*********************************************************************// |
| 4868 | |
| 4869 | static JNIEnv* androidGetThreadEnv() { |
| 4870 | // Every Android app has only one JVM. Calling JNI_GetCreatedJavaVMs |
| 4871 | // will retrieve the JVM running the app. |
| 4872 | jsize jvmsFound = 0; |
| 4873 | JavaVM jvms[1]; |
| 4874 | JavaVM* pjvms = jvms; |
| 4875 | jint result = JNI_GetCreatedJavaVMs(&pjvms, 1, &jvmsFound); |
| 4876 | |
| 4877 | // Something went terribly wrong, no JVM was found |
| 4878 | if (jvmsFound != 1 || result != JNI_OK) { |
| 4879 | LOGE("No JVM found"); |
| 4880 | return NULL; |
| 4881 | } |
| 4882 | |
| 4883 | // Get the JNIEnv for the current thread |
| 4884 | JNIEnv* env = NULL; |
| 4885 | int rc = pjvms->GetEnv((void**)&env, JNI_VERSION_1_6); |
| 4886 | |
| 4887 | // The current thread was not attached to the JVM. Add it to the JVM |
| 4888 | if (rc == JNI_EDETACHED) { |
| 4889 | pjvms->AttachCurrentThreadAsDaemon(&env, NULL); |
| 4890 | } |
| 4891 | |
| 4892 | // Neither way to retrieve the JNIEnv worked |
| 4893 | if (env == NULL) { |
| 4894 | LOGE("Unable to retrieve JNI environment"); |
| 4895 | } |
| 4896 | |
| 4897 | return env; |
| 4898 | } |
| 4899 | |
| 4900 | static jobject androidGetContext(JNIEnv *env) { |
| 4901 | auto activityThread = env->FindClass("android/app/ActivityThread"); |
| 4902 | auto currentActivityThread = env->GetStaticMethodID(activityThread, "currentActivityThread", "()Landroid/app/ActivityThread;"); |
| 4903 | auto at = env->CallStaticObjectMethod(activityThread, currentActivityThread); |
| 4904 | if (at == NULL) { |
| 4905 | LOGE("Unable to locate the global ActivityThread"); |
| 4906 | return NULL; |
| 4907 | } |
| 4908 | |
| 4909 | auto getApplication = env->GetMethodID(activityThread, "getApplication", "()Landroid/app/Application;"); |
| 4910 | auto context = env->CallObjectMethod(at, getApplication); |
| 4911 | if (context == NULL) { |
| 4912 | LOGE("Application context was NULL"); |
| 4913 | } |
| 4914 | |
| 4915 | return context; |
| 4916 | } |
| 4917 | |
| 4918 | static jobject androidGetMidiManager(JNIEnv *env, jobject context) { |
| 4919 | // MidiManager midiManager = (MidiManager) getSystemService(Context.MIDI_SERVICE); |
| 4920 | auto contextClass = env->FindClass("android/content/Context"); |
| 4921 | auto getServiceMethod = env->GetMethodID(contextClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;"); |
| 4922 | return env->CallObjectMethod(context, getServiceMethod, env->NewStringUTF("midi")); |
| 4923 | } |
| 4924 | |
| 4925 | static void androidRefreshMidiDevices(JNIEnv *env, jobject context, bool isOutput) { |
| 4926 | // Remove all midi devices |
| 4927 | for (jobject jMidiDevice : androidMidiDevices) { |
| 4928 | env->DeleteGlobalRef(jMidiDevice); |
| 4929 | } |
| 4930 | androidMidiDevices.clear(); |
| 4931 | |
| 4932 | auto midiService = androidGetMidiManager(env, context); |
| 4933 | |
| 4934 | // MidiDeviceInfo[] devInfos = mMidiManager.getDevices(); |
| 4935 | auto midiMgrClass = env->FindClass("android/media/midi/MidiManager"); |
| 4936 | auto getDevicesMethod = env->GetMethodID(midiMgrClass, "getDevices", "()[Landroid/media/midi/MidiDeviceInfo;"); |
| 4937 | auto jDevices = (jobjectArray) env->CallObjectMethod(midiService, getDevicesMethod); |
| 4938 | |
| 4939 | auto deviceInfoClass = env->FindClass("android/media/midi/MidiDeviceInfo"); |
| 4940 | auto getInputPortCountMethod = env->GetMethodID(deviceInfoClass, "getInputPortCount", "()I"); |
| 4941 | auto getOutputPortCountMethod = env->GetMethodID(deviceInfoClass, "getOutputPortCount", "()I"); |
| 4942 | |
| 4943 | jsize len = env->GetArrayLength((jarray)jDevices); |
| 4944 | for (int i=0; i<len; i++) { |
| 4945 | auto jDeviceInfo = env->GetObjectArrayElement(jDevices, i); |
| 4946 | |
| 4947 | int numPorts = env->CallIntMethod(jDeviceInfo, isOutput ? getOutputPortCountMethod : getInputPortCountMethod); |
| 4948 | if (numPorts > 0) { |
| 4949 | androidMidiDevices.push_back(env->NewGlobalRef(jDeviceInfo)); |
| 4950 | } |
| 4951 | } |
| 4952 | } |
| 4953 | |
| 4954 | |
| 4955 | extern "C" |
| 4956 | JNIEXPORT void JNICALL |
| 4957 | Java_com_yellowlab_rtmidi_MidiDeviceOpenedListener_midiDeviceOpened(JNIEnv *env, jclass clazz, |
| 4958 | jobject midi_device, jlong targetPtr, jboolean isOutput) { |
| 4959 | if (isOutput) { |
| 4960 | auto midiOut = reinterpret_cast<MidiOutAndroid*>(targetPtr); |
| 4961 | AMidiDevice_fromJava(env, midi_device, &midiOut->sendDevice); |
| 4962 | AMidiInputPort_open(midiOut->sendDevice, 0, &midiOut->midiInputPort); |
| 4963 | } else { |
| 4964 | auto midiIn = reinterpret_cast<MidiInAndroid*>(targetPtr); |
| 4965 | AMidiDevice_fromJava(env, midi_device, &midiIn->receiveDevice); |
| 4966 | AMidiOutputPort_open(midiIn->receiveDevice, 0, &midiIn->midiOutputPort); |
| 4967 | pthread_create(&midiIn->readThread, NULL, MidiInAndroid::pollMidi, midiIn); |
| 4968 | } |
| 4969 | } |
| 4970 | |
| 4971 | static void androidOpenDevice(jobject deviceInfo, void* target, bool isOutput) { |
| 4972 | auto env = androidGetThreadEnv(); |
| 4973 | auto context = androidGetContext(env); |
| 4974 | auto midiMgr = androidGetMidiManager(env, context); |
| 4975 | |
| 4976 | auto looperClass = env->FindClass("android/os/Looper"); |
| 4977 | auto getMyLooperMethod = env->GetStaticMethodID(looperClass, "myLooper", "()Landroid/os/Looper;"); |
| 4978 | auto looperObj = env->CallStaticObjectMethod(looperClass, getMyLooperMethod); |
| 4979 | auto getLooperPrepareMethod = env->GetStaticMethodID(looperClass, "prepare", "()V"); |
| 4980 | auto getLooperQuitMethod = env->GetMethodID(looperClass, "quit", "()V"); |
| 4981 | |
| 4982 | if (!looperObj) |
| 4983 | env->CallStaticVoidMethod(looperClass, getLooperPrepareMethod); |
| 4984 | |
| 4985 | // openDevice(MidiDeviceInfo deviceInfo, OnDeviceOpenedListener listener, Handler handler) |
| 4986 | auto midiMgrClass = env->GetObjectClass(midiMgr); |
| 4987 | auto openDevicesMethod = env->GetMethodID(midiMgrClass, "openDevice", "(Landroid/media/midi/MidiDeviceInfo;Landroid/media/midi/MidiManager$OnDeviceOpenedListener;Landroid/os/Handler;)V"); |
| 4988 | |
| 4989 | auto handlerClass = env->FindClass("android/os/Handler"); |
| 4990 | auto getMainLooperMethod = env->GetStaticMethodID(looperClass, "getMainLooper", "()Landroid/os/Looper;"); |
| 4991 | auto mainLooperObj = env->CallStaticObjectMethod(looperClass, getMainLooperMethod); |
| 4992 | auto handlerCtor = env->GetMethodID(handlerClass, "<init>", "(Landroid/os/Looper;)V"); |
| 4993 | auto handler = env->NewObject(handlerClass, handlerCtor, mainLooperObj); |
| 4994 | |
| 4995 | jclass listenerClass = env->FindClass("com/yellowlab/rtmidi/MidiDeviceOpenedListener"); |
| 4996 | if (!listenerClass) { |
| 4997 | LOGE("Midi listener class not found com.yellowlab.rtmidi.MidiDeviceOpenedListener. Did you forget to add it to your APK?"); |
| 4998 | return; |
| 4999 | } |
| 5000 | |
| 5001 | auto targetPtr = reinterpret_cast<jlong>(target); |
| 5002 | auto listenerCtor = env->GetMethodID(listenerClass, "<init>", "(JZ)V"); |
| 5003 | auto listener = env->NewObject(listenerClass, listenerCtor, targetPtr, isOutput); |
| 5004 | |
| 5005 | env->CallVoidMethod(midiMgr, openDevicesMethod, deviceInfo, listener, handler); |
| 5006 | env->DeleteLocalRef(handler); |
| 5007 | } |
| 5008 | |
| 5009 | static std::string androidPortName(JNIEnv *env, unsigned int portNumber) { |
| 5010 | if (portNumber >= androidMidiDevices.size()) { |
| 5011 | LOGE("androidPortName: Invalid port number"); |
| 5012 | return ""; |
| 5013 | } |
| 5014 | |
| 5015 | // String deviceName = devInfo.getProperties().getString(MidiDeviceInfo.PROPERTY_NAME); |
| 5016 | auto deviceInfoClass = env->FindClass("android/media/midi/MidiDeviceInfo"); |
| 5017 | auto getPropsMethod = env->GetMethodID(deviceInfoClass, "getProperties", "()Landroid/os/Bundle;"); |
| 5018 | auto bundle = env->CallObjectMethod(androidMidiDevices[portNumber], getPropsMethod); |
| 5019 | |
| 5020 | auto bundleClass = env->FindClass("android/os/Bundle"); |
| 5021 | auto getStringMethod = env->GetMethodID(bundleClass, "getString", "(Ljava/lang/String;)Ljava/lang/String;"); |
| 5022 | auto jPortName = (jstring) env->CallObjectMethod(bundle, getStringMethod, env->NewStringUTF("name")); |
| 5023 | |
| 5024 | auto portNameChars = env->GetStringUTFChars(jPortName, NULL); |
| 5025 | auto name = std::string(portNameChars); |
| 5026 | env->ReleaseStringUTFChars(jPortName, portNameChars); |
| 5027 | |
| 5028 | return name; |
| 5029 | } |
| 5030 | |
| 5031 | MidiInAndroid :: MidiInAndroid( const std::string &clientName, unsigned int queueSizeLimit ) |
| 5032 | : MidiInApi( queueSizeLimit ) { |
| 5033 | MidiInAndroid::initialize( clientName ); |
| 5034 | } |
| 5035 | |
| 5036 | void MidiInAndroid :: initialize( const std::string& clientName ) { |
| 5037 | androidClientName = clientName; |
| 5038 | connect(); |
| 5039 | } |
| 5040 | |
| 5041 | void MidiInAndroid :: connect() { |
| 5042 | auto env = androidGetThreadEnv(); |
| 5043 | auto context = androidGetContext(env); |
| 5044 | androidRefreshMidiDevices(env, context, true); |
| 5045 | |
| 5046 | env->DeleteLocalRef(context); |
| 5047 | } |
| 5048 | |
| 5049 | MidiInAndroid :: ~MidiInAndroid() { |
| 5050 | auto env = androidGetThreadEnv(); |
| 5051 | |
| 5052 | // Remove all midi devices |
| 5053 | for (jobject jMidiDevice : androidMidiDevices) { |
| 5054 | env->DeleteGlobalRef(jMidiDevice); |
| 5055 | } |
| 5056 | androidMidiDevices.clear(); |
| 5057 | |
| 5058 | androidClientName = ""; |
| 5059 | } |
| 5060 | |
| 5061 | void MidiInAndroid :: openPort(unsigned int portNumber, const std::string &portName) { |
| 5062 | if (portNumber >= androidMidiDevices.size()) { |
| 5063 | errorString_ = "MidiInAndroid::openPort: Invalid port number"; |
| 5064 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 5065 | |
| 5066 | return; |
| 5067 | } |
| 5068 | |
| 5069 | if (reading) { |
| 5070 | errorString_ = "MidiInAndroid::openPort: A port is already open"; |
| 5071 | error( RtMidiError::INVALID_USE, errorString_ ); |
| 5072 | |
| 5073 | return; |
| 5074 | } |
| 5075 | |
| 5076 | androidOpenDevice(androidMidiDevices[portNumber], this, false); |
| 5077 | } |
| 5078 | |
| 5079 | void MidiInAndroid :: openVirtualPort(const std::string &portName) { |
| 5080 | errorString_ = "MidiInAndroid::openVirtualPort: this function is not implemented for the Android API!"; |
| 5081 | error( RtMidiError::WARNING, errorString_ ); |
| 5082 | } |
| 5083 | |
| 5084 | unsigned int MidiInAndroid :: getPortCount() { |
| 5085 | connect(); |
| 5086 | return androidMidiDevices.size(); |
| 5087 | } |
| 5088 | |
| 5089 | std::string MidiInAndroid :: getPortName(unsigned int portNumber) { |
| 5090 | auto env = androidGetThreadEnv(); |
| 5091 | return androidPortName(env, portNumber); |
| 5092 | } |
| 5093 | |
| 5094 | void MidiInAndroid :: closePort() { |
| 5095 | // Don't try to close a port before it was open |
| 5096 | if (!reading) { |
| 5097 | return; |
| 5098 | } |
| 5099 | |
| 5100 | reading = false; |
| 5101 | pthread_join(readThread, NULL); |
| 5102 | |
| 5103 | AMidiDevice_release(receiveDevice); |
| 5104 | receiveDevice = NULL; |
| 5105 | midiOutputPort = NULL; |
| 5106 | } |
| 5107 | |
| 5108 | void MidiInAndroid:: setClientName(const std::string& clientName) { |
| 5109 | androidClientName = clientName; |
| 5110 | } |
| 5111 | |
| 5112 | void MidiInAndroid :: setPortName(const std::string &portName) { |
| 5113 | errorString_ = "MidiInAndroid::setPortName: this function is not implemented for the Android API!"; |
| 5114 | error( RtMidiError::WARNING, errorString_ ); |
| 5115 | } |
| 5116 | |
| 5117 | void* MidiInAndroid :: pollMidi(void* context) { |
| 5118 | auto self = (MidiInAndroid*) context; |
| 5119 | self->reading = true; |
| 5120 | |
| 5121 | const size_t MAX_BYTES_TO_RECEIVE = 128; |
| 5122 | uint8_t incomingMessage[MAX_BYTES_TO_RECEIVE]; |
| 5123 | |
| 5124 | while (self->reading) { |
| 5125 | // AMidiOutputPort_receive is non-blocking, must poll with some sleep |
| 5126 | usleep(2000); |
| 5127 | auto ignoreFlags = self->inputData_.ignoreFlags; |
| 5128 | bool& continueSysex = self->inputData_.continueSysex; |
| 5129 | |
| 5130 | int32_t opcode; |
| 5131 | size_t numBytesReceived; |
| 5132 | int64_t timestamp; |
| 5133 | ssize_t numMessagesReceived = AMidiOutputPort_receive( |
| 5134 | self->midiOutputPort, &opcode, incomingMessage, MAX_BYTES_TO_RECEIVE, |
| 5135 | &numBytesReceived, ×tamp); |
| 5136 | |
| 5137 | if (numMessagesReceived < 0) { |
| 5138 | self->errorString_ = "MidiInAndroid::pollMidi: error receiving MIDI data"; |
| 5139 | self->error( RtMidiError::SYSTEM_ERROR, self->errorString_ ); |
| 5140 | self->reading = false; |
| 5141 | break; |
| 5142 | } |
| 5143 | |
| 5144 | switch (incomingMessage[0]) { |
| 5145 | case 0xF0: |
| 5146 | // Start of a SysEx message |
| 5147 | continueSysex = incomingMessage[numBytesReceived - 1] != 0xF7; |
| 5148 | if (ignoreFlags & 0x01) continue; |
| 5149 | break; |
| 5150 | case 0xF1: |
| 5151 | case 0xF8: |
| 5152 | // MIDI Time Code or Timing Clock message |
| 5153 | if (ignoreFlags & 0x02) continue; |
| 5154 | break; |
| 5155 | case 0xFE: |
| 5156 | // Active Sensing message |
| 5157 | if (ignoreFlags & 0x04) continue; |
| 5158 | break; |
| 5159 | default: |
| 5160 | if (continueSysex) { |
| 5161 | // Continuation of a SysEx message |
| 5162 | continueSysex = incomingMessage[numBytesReceived - 1] != 0xF7; |
| 5163 | if (ignoreFlags & 0x01) continue; |
| 5164 | } |
| 5165 | // All other MIDI messages |
| 5166 | } |
| 5167 | |
| 5168 | if (numMessagesReceived > 0 && numBytesReceived >= 0) { |
| 5169 | auto message = self->inputData_.message; |
| 5170 | |
| 5171 | if (self->inputData_.firstMessage == true) { |
| 5172 | message.timeStamp = 0.0; |
| 5173 | self->inputData_.firstMessage = false; |
| 5174 | } else { |
| 5175 | message.timeStamp = (timestamp * 0.000001) - self->lastTime; |
| 5176 | } |
| 5177 | self->lastTime = (timestamp * 0.000001); |
| 5178 | |
| 5179 | if (!continueSysex) message.bytes.clear(); |
| 5180 | |
| 5181 | if ( !( ( continueSysex || incomingMessage[0] == 0xF0 ) && ( ignoreFlags & 0x01 ) ) ) { |
| 5182 | // Unless this is a (possibly continued) SysEx message and we're ignoring SysEx, |
| 5183 | // copy the event buffer into the MIDI message struct. |
| 5184 | for (unsigned int i=0; i<numBytesReceived; i++) |
| 5185 | message.bytes.push_back(incomingMessage[i]); |
| 5186 | } |
| 5187 | |
| 5188 | if (!continueSysex) { |
| 5189 | if (self->inputData_.usingCallback) { |
| 5190 | auto callback = (RtMidiIn::RtMidiCallback) self->inputData_.userCallback; |
| 5191 | callback(message.timeStamp, &message.bytes, self->inputData_.userData); |
| 5192 | } else { |
| 5193 | if (!self->inputData_.queue.push(message)) |
| 5194 | std::cerr << "\nMidiInAndroid: message queue limit reached!!\n\n"; |
| 5195 | } |
| 5196 | } |
| 5197 | } |
| 5198 | } |
| 5199 | |
| 5200 | return NULL; |
| 5201 | } |
| 5202 | |
| 5203 | |
| 5204 | //*********************************************************************// |
| 5205 | // API: Android AMIDI |
| 5206 | // Class Definitions: MidiOutAndroid |
| 5207 | //*********************************************************************// |
| 5208 | |
| 5209 | |
| 5210 | MidiOutAndroid :: MidiOutAndroid( const std::string &clientName ) : MidiOutApi() { |
| 5211 | MidiOutAndroid::initialize( clientName ); |
| 5212 | } |
| 5213 | |
| 5214 | void MidiOutAndroid :: initialize( const std::string& clientName ) { |
| 5215 | androidClientName = clientName; |
| 5216 | connect(); |
| 5217 | } |
| 5218 | |
| 5219 | void MidiOutAndroid :: connect() { |
| 5220 | auto env = androidGetThreadEnv(); |
| 5221 | auto context = androidGetContext(env); |
| 5222 | androidRefreshMidiDevices(env, context, false); |
| 5223 | |
| 5224 | env->DeleteLocalRef(context); |
| 5225 | } |
| 5226 | |
| 5227 | MidiOutAndroid :: ~MidiOutAndroid() { |
| 5228 | auto env = androidGetThreadEnv(); |
| 5229 | |
| 5230 | // Remove all midi devices |
| 5231 | for (jobject jMidiDevice : androidMidiDevices) { |
| 5232 | env->DeleteGlobalRef(jMidiDevice); |
| 5233 | } |
| 5234 | androidMidiDevices.clear(); |
| 5235 | |
| 5236 | androidClientName = ""; |
| 5237 | } |
| 5238 | |
| 5239 | void MidiOutAndroid :: openPort( unsigned int portNumber, const std::string &portName ) { |
| 5240 | if (portNumber >= androidMidiDevices.size()) { |
| 5241 | errorString_ = "MidiOutAndroid::openPort: Invalid port number"; |
| 5242 | error( RtMidiError::INVALID_PARAMETER, errorString_ ); |
| 5243 | |
| 5244 | return; |
| 5245 | } |
| 5246 | |
| 5247 | androidOpenDevice(androidMidiDevices[portNumber], this, true); |
| 5248 | } |
| 5249 | |
| 5250 | void MidiOutAndroid :: openVirtualPort( const std::string &portName ) { |
| 5251 | errorString_ = "MidiOutAndroid::openVirtualPort: this function is not implemented for the Android API!"; |
| 5252 | error( RtMidiError::WARNING, errorString_ ); |
| 5253 | } |
| 5254 | |
| 5255 | unsigned int MidiOutAndroid :: getPortCount() { |
| 5256 | connect(); |
| 5257 | return androidMidiDevices.size(); |
| 5258 | } |
| 5259 | |
| 5260 | std::string MidiOutAndroid :: getPortName( unsigned int portNumber ) { |
| 5261 | auto env = androidGetThreadEnv(); |
| 5262 | return androidPortName(env, portNumber); |
| 5263 | } |
| 5264 | |
| 5265 | void MidiOutAndroid :: closePort() { |
| 5266 | AMidiDevice_release(sendDevice); |
| 5267 | sendDevice = NULL; |
| 5268 | midiInputPort = NULL; |
| 5269 | } |
| 5270 | |
| 5271 | void MidiOutAndroid:: setClientName( const std::string& name ) { |
| 5272 | androidClientName = name; |
| 5273 | } |
| 5274 | |
| 5275 | void MidiOutAndroid :: setPortName( const std::string &portName ) { |
| 5276 | errorString_ = "MidiOutAndroid::setPortName: this function is not implemented for the Android API!"; |
| 5277 | error( RtMidiError::WARNING, errorString_ ); |
| 5278 | } |
| 5279 | |
| 5280 | void MidiOutAndroid :: sendMessage( const unsigned char *message, size_t size ) { |
| 5281 | AMidiInputPort_send(midiInputPort, (uint8_t*)message, size); |
| 5282 | } |
| 5283 | |
| 5284 | #endif // __AMIDI__ |