-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMuPlayer.cpp
More file actions
executable file
·765 lines (658 loc) · 21.1 KB
/
MuPlayer.cpp
File metadata and controls
executable file
·765 lines (658 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
//
// MuPlayer.cpp
// MuMRT
//
// Created by Carlos Eduardo Mello on 2/17/19.
// Copyright © 2019 Carlos Eduardo Mello. All rights reserved.
//
#include "MuPlayer.h"
bool MuPlayer::pause = false;
bool MuPlayer::stop = false;
pthread_mutex_t MuPlayer::sendMIDIlock;
MuPlayer::MuPlayer(void)
{
// initialize all fields of playback pool
// to default values...
for(int i = 0; i < MAX_QUEUES; i++)
{
eqPool[i].buffer.data = NULL;
eqPool[i].buffer.max = 0;
eqPool[i].buffer.max = 0;
eqPool[i].active = false;
eqPool[i].loading = false;
eqPool[i].paused = false;
eqPool[i].next = 0;
eqPool[i].material.Clear();
eqPool[i].queueThread = 0;
eqPool[i].loadingTime = 0;
}
// initialize MIDI objects...
#ifdef MUM_MACOSX
midiClient = 0;
midiOutPort = 0;
midiDest = 0;
#endif
#ifdef MUM_LINUX
// RTMidi
midiout = NULL;
#endif
// clear scheduler thread variable...
schedulerThread = 0;
}
MuPlayer::~MuPlayer(void)
{
Reset();
}
void MuPlayer::CleanPlaybackPool(void)
{
// Clean Playback Pool
for(int i = 0; i < MAX_QUEUES; i++)
{
if(eqPool[i].buffer.data)
delete [] eqPool[i].buffer.data;
eqPool[i].buffer.data = NULL;
eqPool[i].buffer.max = 0;
eqPool[i].buffer.count = 0;
eqPool[i].active = false;
eqPool[i].loading = false;
eqPool[i].paused = false;
eqPool[i].next = 0;
eqPool[i].material.Clear();
if(eqPool[i].queueThread != 0)
{
pthread_cancel(eqPool[i].queueThread);
eqPool[i].queueThread = 0;
}
eqPool[i].loadingTime = 0;
}
}
bool MuPlayer::Init(void)
{
#ifdef MUM_MACOSX
long n,i;
OSStatus err = noErr;
// create Client...
if(midiClient == 0)
{
err = MIDIClientCreate(CFSTR("MuM Playback"), NULL, NULL, &midiClient);
if(err == noErr)
{
// Create Output Port...
err = MIDIOutputPortCreate(midiClient, CFSTR("MuM Output"), &midiOutPort);
if(err == noErr)
{
// List Possible Destinations...
n = MIDIGetNumberOfDestinations();
if(n != 0)
{
CFStringRef name;
char cname[64];
MIDIEndpointRef dest;
// List Possible MIDI Destinations...
for(i = 0; i < n; i++)
{
dest = MIDIGetDestination(i);
if (dest != 0)
{
MIDIObjectGetStringProperty(dest, kMIDIPropertyName, &name);
CFStringGetCString(name, cname, sizeof(cname), 0);
CFRelease(name);
cout << "[Destination " << i << "]: " << cname << endl << endl;
}
}
// Choose a MIDI destination for playback...
midiDest = MIDIGetDestination(0);
if(StartScheduler())
return true;
}
else
{
cout << "No MIDI destinations present!\n" << endl;
}
}
else
{
cout << "Failed to open output port!\n" << endl;
}
}
else
{
cout << "Failed to create MIDI client!\n" << endl;
}
}
else
{
cout << "Client already initialized! (call reset MIDI)\n" << endl;
}
return false;
#endif
#ifdef MUM_LINUX
unsigned int nPorts;
string portName;
// RtMidiOut constructor
try
{
midiout = new RtMidiOut(RtMidiOut::LINUX_ALSA, MUM_CLIENT_NAME);
}
catch( RtMidiError &error )
{
error.printMessage();
exit( EXIT_FAILURE );
}
// Check outputs.
nPorts = midiout->getPortCount();
cout << endl << "Available MIDI ports:" << endl;
for( unsigned int i = 0; i < nPorts; i++ )
{
try
{
portName = midiout->getPortName(i);
}
catch (RtMidiError &error)
{
error.printMessage();
}
cout << "\tport " << i << ": " << portName << endl;
}
selectedPort = 0;
if(selectedPort >= 0)
{
// Connect to available port.
midiout->openPort( selectedPort, MUM_PORT_NAME );
}
else
{
// create a virtual port.
midiout->openVirtualPort(MUM_PORT_NAME);
}
if(StartScheduler())
return true;
return false;
#endif
}
bool MuPlayer::SelectMIDIDestination(int destNumber)
{
#ifdef MUM_MACOSX
if(destNumber >= 0) // FIXED: was 'destNumber > 0' - check if it works...
{
midiDest = MIDIGetDestination(destNumber);
if (midiDest != 0)
{
return true;
}
}
#endif
#ifdef MUM_LINUX
if(destNumber >= 0)
{
midiout->closePort();
midiout->openPort( destNumber, MUM_PORT_NAME );
selectedPort = destNumber;
return true;
}
#endif
return false;
}
string MuPlayer::ListDestinations(void)
{
string list;
#ifdef MUM_MACOSX
long n,i;
// Get number of destinations...
if(midiClient != 0)
{
n = MIDIGetNumberOfDestinations();
if(n != 0)
{
CFStringRef name;
char cname[64];
MIDIEndpointRef dest;
// List Possible MIDI Destinations...
for(i = 0; i < n; i++)
{
dest = MIDIGetDestination(i);
if (dest != 0)
{
MIDIObjectGetStringProperty(dest, kMIDIPropertyName, &name);
CFStringGetCString(name, cname, sizeof(cname), 0);
CFRelease(name);
list += cname;
list += "\n";
}
}
}
}
#endif
#ifdef MUM_LINUX
unsigned int nPorts;
string portName;
// Check outputs.
nPorts = midiout->getPortCount();
for ( unsigned int i = 0; i < nPorts; i++ )
{
try
{
portName = midiout->getPortName(i);
}
catch (RtMidiError &error)
{
error.printMessage();
}
list += portName;
}
#endif
return list;
}
void MuPlayer::Reset(void)
{
// Stop scheduler thread
if(schedulerThread != 0)
{
pthread_cancel(schedulerThread);
schedulerThread = 0;
}
// Release all queue buffers and threads
CleanPlaybackPool();
// Release MIDI components...
#ifdef MUM_MACOSX
midiDest = 0;
midiOutPort = 0;
midiClient = 0;
#endif
#ifdef MUM_LINUX
midiout->closePort();
delete midiout;
#endif
}
bool MuPlayer::Play(MuMaterial & inMat, int mode)
{
int i;
int selectedQueue = -1;
MuNote note;
// First find a usable event queue...
if(mode == PLAYBACK_MODE_NORMAL)
{
// at the end of this loop, if at
// least one queue is available,
// selectedQueue contains its index..
for (i = 0; i < MAX_QUEUES; i++)
{
// if the current queue is not being played or filled,...
if(eqPool[i].active == false && eqPool[i].loading == false)
{
// it can be selected for a new material...
selectedQueue = i;
// mark queue as under construction...
eqPool[i].loading = true;
break;
}
}
// if unused queue is found...
if(selectedQueue >= 0)
{
// start the queue's working thread...
StartQueueThread(inMat,selectedQueue);
}
else
{
// otherwise report failure...
return false;
}
}
return true;
}
bool MuPlayer::SendProgramChange(unsigned char channel, unsigned char pc)
{
MuMIDIBuffer programChange;
programChange.data = new MuMIDIMessage[1];
if(programChange.data)
{
programChange.max = 1;
programChange.count = 1;
programChange.data[0].time = 0.0;
programChange.data[0].status = 0xC0 + channel;
programChange.data[0].data1 = pc;
programChange.data[0].data2 = pc;
if(this->SendEvents(programChange) == false)
return false;
}
else
{
return false;
}
return true;
}
bool MuPlayer::SendEvents(MuMIDIBuffer events)
{
int selectedQueue = -1;
int i;
// at the end of this loop, if at
// least one queue is available,
// selectedQueue contains its index..
for (i = 0; i < MAX_QUEUES; i++)
{
// if the current queue is not being played or filled,...
if(eqPool[i].active == false && eqPool[i].loading == false)
{
// it can be selected for a new material...
selectedQueue = i;
// mark queue as under construction...
eqPool[i].loading = true;
break;
}
}
// if unused queue is found...
if(selectedQueue >= 0)
{
// start the queue thread...
StartQueueThread(events,selectedQueue);
}
else
{
// otherwise report failure...
return false;
}
return true;
}
bool MuPlayer::StartQueueThread(MuMaterial & inMat, int queueIdx)
{
int res;
// make a copy of the input material so the thread can
// work on it safely, as it will be working assynchronously
eqPool[queueIdx].material = inMat;
// Start the thread...
res = pthread_create(&(eqPool[queueIdx].queueThread), NULL, MuPlayer::EnqueueMaterial, (void*)(&eqPool[queueIdx]));
if(res)
{
// if we fail, terminate process...
cout << "THREAD ERROR! - Terminating..." << endl;
exit(EXIT_FAILURE);
}
// if successful...
return true;
}
bool MuPlayer::StartQueueThread(MuMIDIBuffer events, int queueIdx)
{
int res;
// make a copy of the input event buffer so the thread can
// work on it safely, as it will be working assynchronously
eqPool[queueIdx].buffer = events;
// Start the thread...
res = pthread_create(&(eqPool[queueIdx].queueThread), NULL, MuPlayer::EnqueueEvents, (void*)(&eqPool[queueIdx]));
if(res)
{
// if we fail, terminate process...
cout << "THREAD ERROR! - Terminating..." << endl;
exit(EXIT_FAILURE);
}
// if successful...
return true;
}
void * MuPlayer::EnqueueMaterial(void* arg)
{
int numVoices, i;
MuNote note;
unsigned char channel, instrument;
long numNotes,numEvents,nextEvent, j, k;
EventQueue * queue = (EventQueue *)arg;
// get the total number of notes in input material...
numNotes = queue->material.NumberOfNotes();
numVoices = queue->material.NumberOfVoices();
// each note needs two MIDI events (on/off) per note
numEvents = numNotes * 2;
// allocate memory for the note events...
if(numEvents > 0)
{
// Attention! this buffer needs to be released when
// the scheduler is done sending its events...
queue->buffer.data = new MuMIDIMessage[numEvents];
if(queue->buffer.data)
{
// If Allocation worked, extract MIDI events from notes...
queue->buffer.max = numEvents;
nextEvent = 0;
for(i = 0; i < numVoices; i++)
{
channel = queue->material.Channel(i);
channel--; // adjust to zero-based counting
numNotes = queue->material.NumberOfNotes(i);
for (j = 0; j < numNotes; j++)
{
note = queue->material.GetNote(i, j);
queue->buffer.data[nextEvent] = note.MIDIOn();
queue->buffer.data[nextEvent].status += channel;
nextEvent++;
queue->buffer.data[nextEvent] = note.MIDIOff();
queue->buffer.data[nextEvent].status += channel;
nextEvent++;
}
}
// After extracting notes from all voices, nextEvent contains
// the number of events used in the buffer (which should be
// the same as buffer.max, but just in case...)
queue->buffer.count = nextEvent;
// sort events by timestamp...
long n = queue->buffer.count;
for(j = n; j >= 1; j-- )
{
for( k = 0; k < j-1; k++ )
{
if( queue->buffer.data[k].time > queue->buffer.data[k+1].time )
{
// swap messages...
MuMIDIMessage temp;
temp = queue->buffer.data[k];
queue->buffer.data[k] = queue->buffer.data[k+1];
queue->buffer.data[k+1] = temp;
}
}
}
queue->material.Clear();
queue->next = 0;
queue->paused = false;
// IMPORTANT: LOADING TIME
// The following timestamp is registering this moment, after
// the event buffer has been successfully allocated and filled,
// to be the initial time for playback of this queue. All events
// in the queue will be referenced from this point. The amount
// of microseconds retrieved hear will be added to the timestamp
// of every event so the scheduler can compare stamps and decide
// when to send the messages.
queue->loadingTime = ClockStamp();
//cout << "[Loading Time]: " << queue->loadingTime << endl;
// after the queue is set to 'active' the scheduler may
// use it at any moment (even at interrupt time). That's
// why this MUST BE THE LAST ACTION!
queue->active = true;
// after the queue is active we turn off the loading flag...
queue->loading = false;
}
}
// after the work is done we terminate this thread...
pthread_exit(NULL);
}
void * MuPlayer::EnqueueEvents(void* arg)
{
long i, n;
EventQueue * queue = (EventQueue *)arg;
MuMIDIBuffer tempBuff = queue->buffer;
n = queue->buffer.count;
// allocate memory for the events...
if(n > 0)
{
// Attention! this buffer needs to be released when
// the scheduler is done sending its events...
queue->buffer.data = new MuMIDIMessage[n];
// copy MIDI events from input buffer...
if(queue->buffer.data)
{
for(i = 0; i < n; i++)
{
queue->buffer.data[i] = tempBuff.data[i];
}
queue->paused = false;
// IMPORTANT: LOADING TIME
// The following timestamp is registering this moment, after
// the event buffer has been successfully allocated and filled,
// to be the initial time for playback of this queue. All events
// in the queue will be referenced from this point. The amount
// of microseconds retrieved hear will be added to the timestamp
// of every event so the scheduler can compare stamps and decide
// when to send the messages.
queue->loadingTime = ClockStamp();
//cout << "[Loading Time]: " << queue->loadingTime << endl;
// after the queue is set to 'active' the scheduler may
// use it at any moment (even at interrupt time). That's
// why this MUST BE THE LAST ACTION!
queue->active = true;
// after the queue is active we turn off the loading flag...
queue->loading = false;
}
}
// after the work is done we terminate this thread...
pthread_exit(NULL);
}
bool MuPlayer::StartScheduler(void)
{
int res;
res = pthread_create(&schedulerThread, NULL, MuPlayer::ScheduleEvents, (void*)eqPool);
if(res)
{
cout << "THREAD ERROR! - Terminating..." << endl;
exit(EXIT_FAILURE);
}
return true;
}
// FIX FIX FIX: FINISH IMPLEMENTING THIS CAREFULLY!!
// 1) REMEMBER TO RESET EMPTY QUEUES SO THEY CAN BE REUSED
// 2) REMEMBER TO IMPLEMENT GLOBAL PAUSE AND STOP CORRECTLY
// 3) Individual queue pause and stop must be planned better
// for later
void * MuPlayer::ScheduleEvents(void * pl)
{
int i;
MuPlayer * player = (MuPlayer *)pl;
EventQueue * pool = player->eqPool;
// this thread will terminate
// when the Player's stop flag is set...
while (!MuPlayer::stop)
{
// only do work if the player is not paused...
if(!MuPlayer::pause)
{
for(i = 0; i < MAX_QUEUES; i++)
{
// if current queue is active,...
if (pool[i].active == true)
{
// look for its next event...
MuMIDIMessage msg = pool[i].buffer.data[pool[i].next];
long msgTime = (long)(msg.time * ONE_SECOND) + (pool[i].loadingTime);
// get current time from the system
long currTime = ClockStamp();
// if the timestamp on the message is expired...
if( currTime >= msgTime)
{
// schedule it to be sent to destination...
#ifdef MUM_MACOSX
SendMIDIMessage(msg,player->midiOutPort, player->midiDest);
#endif
#ifdef MUM_LINUX
SendMIDIMessage(msg,player->midiout);
#endif
// advance event counter...
pool[i].next += 1;
// if this is the last event in the buffer,
// this queue needs to be reset...
if(pool[i].next >= pool[i].buffer.count)
{
// reset queue
delete [] pool[i].buffer.data;
pool[i].buffer.data = NULL;
pool[i].buffer.count = 0;
pool[i].buffer.max = 0;
pool[i].paused = false;
pool[i].next = 0;
pool[i].queueThread = 0;
pool[i].loadingTime = 0;
// lastly deactivate queue
pool[i].active = false;
pool[i].loading = false;
}
}
}
} // end MAX_QUEUES loop
usleep(10); // idle for a moment...
} // end if(!pause)
else
{
usleep(100); // idle for a moment...
}
} // end infinite loop
pthread_exit(NULL);
}
#ifdef MUM_MACOSX
void MuPlayer::SendMIDIMessage(MuMIDIMessage msg, MIDIPortRef outPort, MIDIEndpointRef dest)
{
//pthread_mutex_lock(&sendMIDIlock);
int byteCount;
Byte msgBuff[MESSAGE_LENGTH];
if((outPort != 0) && (dest != 0))
{
msgBuff[0] = msg.status;
msgBuff[1] = msg.data1;
msgBuff[2] = msg.data2;
// If this is a program change or pitchbend message, send 2 bytes...
if(((msgBuff[0] & 0xF0) == 0xC0) || ((msgBuff[0] & 0xF0) == 0xE0) )
{
byteCount = 2;
}
else // for all other voice messages send three bytes...
{
byteCount = 3;
}
MIDITimeStamp timestamp = 0.0;
Byte buffer[1024]; // storage space for MIDI Packets
MIDIPacketList * packetlist = (MIDIPacketList*)buffer;
MIDIPacket * packet = MIDIPacketListInit(packetlist);
packet = MIDIPacketListAdd( packetlist, sizeof(buffer),
packet, timestamp,
byteCount, msgBuff );
MIDISend(outPort, dest, packetlist);
}
//pthread_mutex_unlock(&sendMIDIlock);
}
#endif
#ifdef MUM_LINUX
void MuPlayer::SendMIDIMessage(MuMIDIMessage msg, RtMidiOut * midiOut)
{
//pthread_mutex_lock(&sendMIDIlock);
int byteCount;
uByte msgBuff[MESSAGE_LENGTH];
if(midiOut != NULL)
{
msgBuff[0] = msg.status;
msgBuff[1] = msg.data1;
msgBuff[2] = msg.data2;
// If this is a program change or pitchbend message, send 2 bytes...
if(((msgBuff[0] & 0xF0) == 0xC0) || ((msgBuff[0] & 0xF0) == 0xE0) )
{
byteCount = 2;
}
else // for all other voice messages send three bytes...
{
byteCount = 3;
}
midiOut->sendMessage( msgBuff, byteCount);
}
//pthread_mutex_unlock(&sendMIDIlock);
}
#endif
void MuPlayer::Pause(bool T_F)
{
pause = T_F;
}
void MuPlayer::Stop(void)
{
stop = true;
}