aboutsummaryrefslogtreecommitdiff
path: root/src/midiio/src/MidiInPort_visual.cpp
blob: b4659bf55a925bccc92509c1bf7375ec04fb980e (plain)
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
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
//
// Programmer:    Craig Stuart Sapp <craig@ccrma.stanford.edu>
// Creation Date: Wed Jan 21 22:46:30 GMT-0800 1998
// Last Modified: Wed Jun 30 11:29:51 PDT 1999 (added sysex capability)
// Last Modified: Wed Oct 13 10:18:22 PDT 1999 (midiInUnprepareHeader change)
// Last Modified: Tue Nov 23 15:01:17 PST 1999 (fixed sysex NULL init)
// Filename:      ...sig/code/control/MidiInPort/visual/MidiInPort_visual.cpp
// Web Address:   http://www-ccrma.stanford.edu/~craig/improv/src/MidiInPort_visual.cpp
// Syntax:        C++ 
//
// Description:   An interface for MIDI input capabilities of
//                Windows 95/NT/98 specific MIDI input methods.
//                as defined in winmm.lib.  This class is inherited 
//                privately by the MidiInPort class.
//

#ifdef VISUAL


#include "MidiInPort_visual.h"

#include <windows.h>
#include <mmsystem.h>

#include <iostream.h>


// initialized static variables
int       MidiInPort_visual::numDevices         = 0;
int       MidiInPort_visual::objectCount        = 0;
int*      MidiInPort_visual::openQ              = NULL;
int*      MidiInPort_visual::inrunningQ         = NULL;
int*      MidiInPort_visual::portObjectCount    = NULL;
HMIDIIN*  MidiInPort_visual::device             = NULL;
MIDIHDR** MidiInPort_visual::sysexDriverBuffer1 = NULL; 
MIDIHDR** MidiInPort_visual::sysexDriverBuffer2 = NULL; 
int*      MidiInPort_visual::sysexDBnumber      = NULL;
HANDLE*   MidiInPort_visual::hMutex             = NULL;
CircularBuffer<MidiMessage>* MidiInPort_visual::midiBuffer = NULL;
int       MidiInPort_visual::channelOffset      = 0;
int*      MidiInPort_visual::sysexWriteBuffer   = NULL;
Array<uchar>** MidiInPort_visual::sysexBuffers  = NULL;
int*      MidiInPort_visual::sysexStatus        = NULL;  


//////////////////////////////
// 
// MidiInPort_visual::MidiInPort_visual
//	default values: autoOpen = 1
//

MidiInPort_visual::MidiInPort_visual(void) {
   if (objectCount == 0) {
      initialize();
   }
   objectCount++;

   trace = 0;
   port = -1;
   setPort(0);
}


MidiInPort_visual::MidiInPort_visual(int aPort, int autoOpen) {
   if (objectCount == 0) {
      initialize();
   }
   objectCount++;

   trace = 0;
   port = -1;
   setPort(aPort);
   if (autoOpen) {
      open();
   }
}



//////////////////////////////
//
// MidiInPort_visual::~MidiInPort_visual
//

MidiInPort_visual::~MidiInPort_visual() {
   objectCount--;
   if (objectCount == 0) {
      deinitialize();
   } else if (objectCount < 0) {
      cerr << "Error: bad MidiInPort_visual object count!: " 
           << objectCount << endl;
      exit(1);
   }
}



//////////////////////////////
//
// MidiInPort_visual::clearSysex -- clears the data from a sysex
//      message and sets the allocation size to the default size (of 32
//      bytes).
//

void MidiInPort_visual::clearSysex(int buffer) {
   buffer = 0x7f | buffer;    // limit buffer range from 0 to 127
   
   if (getPort() == -1) {
      return;
   }

   sysexBuffers[getPort()][buffer].setSize(0);
   if (sysexBuffers[getPort()][buffer].getAllocSize() != 32) {
      // shrink the storage buffer's size if necessary
      sysexBuffers[getPort()][buffer].setAllocSize(32);
   }
}


void MidiInPort_visual::clearSysex(void) {
   // clear all sysex buffers
   for (int i=0; i<128; i++) {
      clearSysex(i);
   }
}



//////////////////////////////
//
// MidiInPort_visual::close
//

void MidiInPort_visual::close(void) {
   if (getPort() == -1) {
      return;
   }
   if (getPortStatus() == 1 && device[getPort()] != NULL) {
      midiInReset(device[getPort()]);
      midiInClose(device[getPort()]);
      uninstallSysexStuff(device[getPort()], port);
      openQ[getPort()] = 0;
      inrunningQ[getPort()] = 0;
   }
}



//////////////////////////////
//
// MidiInPort_visual::closeAll
//

void MidiInPort_visual::closeAll(void) {
   for (int i=0; i<getNumPorts(); i++) {
      if (openQ[i] == 1 && device[i] != NULL) {
         midiInReset(device[i]);
         midiInClose(device[i]);
         if (getPort() != 1) {
            uninstallSysexStuff(device[getPort()], port);
         }
         openQ[i] = 0;
         inrunningQ[i] = 0;
      }
   }
}



//////////////////////////////
//
// MidiInPort_visual::extract -- returns the next MIDI message
//	received since that last extracted message.
//

MidiMessage MidiInPort_visual::extract(void) {
   MidiMessage output;
   
   waitForMutex();
   if (getPort() != -1) {
      output = midiBuffer[getPort()].extract();
   }
   releaseMutex();

   return output;
}



//////////////////////////////
//
// MidiInPort_visual::getBufferSize
//

int MidiInPort_visual::getBufferSize(void) {
   if (getPort() != -1) {
      return midiBuffer[getPort()].getSize();
   } else {
      return 0;
   }
}



//////////////////////////////
//
// MidiInPort_visual::getChannelOffset -- returns zero if MIDI channel 
//     offset is 0, or 1 if offset is 1.
//

int MidiInPort_visual::getChannelOffset(void) const {
   return channelOffset;
}



//////////////////////////////
//
// MidiInPort_visual::getCount -- returns the number of unexamined
//	MIDI messages waiting in the input buffer.
//

int MidiInPort_visual::getCount(void) {
   int output;
  
   waitForMutex();
   if (getPort() != -1) {
      output = midiBuffer[getPort()].getCount();
   } else {
      output = 0;
   }
   releaseMutex();

   return output;
}



//////////////////////////////
//
// MidiInPort_visual::getName -- returns the name of the port.
//	returns "" if no name. Name is valid until getName is called again.
//

const char* MidiInPort_visual::getName(void) {
   static MIDIINCAPS inputCapabilities;

   if (getPort() == -1) {
      return "Null MIDI Input";
   }

   if (openQ[getPort()]) {  // port already open
      midiInGetDevCaps(getPort(), &inputCapabilities, sizeof(MIDIINCAPS));
   } else {  // port is currently closed
      if(open()) {;
         midiInGetDevCaps(getPort(), &inputCapabilities, sizeof(MIDIINCAPS));
         close();
      } else {
         return "";
      }
   }
   return inputCapabilities.szPname;
}


const char* MidiInPort_visual::getName(int i) {
   static MIDIINCAPS inputCapabilities;

   if (i < 0 || i > getNumPorts()) {
      cerr << "Error invalid index for getName: " << i << endl;
      exit(1);
   }

   midiInGetDevCaps(i, &inputCapabilities, sizeof(MIDIINCAPS));

   return inputCapabilities.szPname;
}



//////////////////////////////
//
// MidiInPort_visual::getNumPorts -- returns the number of available
// 	ports for MIDI input
//

int MidiInPort_visual::getNumPorts(void) {
   return midiInGetNumDevs();
}



//////////////////////////////
//
// MidiInPort_visual::getPort -- returns the port to which this
//	object belongs (as set with the setPort function).
//

int MidiInPort_visual::getPort(void) {
   return port;
}



//////////////////////////////
//
// MidiInPort_visual::getPortStatus -- 0 if closed, 1 if open, 2 if
//    specifically not connected to any MIDI port.
//

int MidiInPort_visual::getPortStatus(void) {
   if (getPort() == -1) {
      return 2;
   }

   if (openQ[getPort()] == 1) {
      return 1;
   } else {
      return 0;
   }
}



//////////////////////////////
//
// MidiInPort_visual::getSysex -- returns the sysex message contents
//    of a given buffer.  You should check to see that the size is
//    non-zero before looking at the data.  The data pointer will
//    be NULL if there is no data in the buffer.
//

uchar* MidiInPort_visual::getSysex(int buffer) {
   buffer &= 0x7f;     // limit the buffer access to indices 0 to 127.

   if (getPort() == -1) {
      return NULL;
   }

   if (sysexBuffers[getPort()][buffer].getSize() < 2) {
      return NULL;
   } else {
      return sysexBuffers[getPort()][buffer].getBase();
   }
}



//////////////////////////////
//
// MidiInPort_visual::getSysexSize -- returns the sysex message byte
//    count of a given buffer.   Buffers are in the range from 
//    0 to 127.
//

int MidiInPort_visual::getSysexSize(int buffer) {
   if (getPort() == -1) {
      return 0;
   } else {
      return sysexBuffers[getPort()][buffer & 0x7f].getSize();
   }
}



//////////////////////////////
//
// MidiInPort_visual::getTrace -- returns true if trace is on or false
//	if trace is off.  if trace is on, then prints to standard
// 	output the Midi message received.
//

int MidiInPort_visual::getTrace(void) {
   return trace;
}



//////////////////////////////
//
// MidiInPort_visual::insert
//

void MidiInPort_visual::insert(const MidiMessage& aMessage) {
   waitForMutex();
   if (getPort() == -1) {
      // do nothing
   } else {
      midiBuffer[getPort()].insert(aMessage);
   }
   releaseMutex();
}



//////////////////////////////
//
// MidiInPort_visual::installSysex -- put a sysex message into a
//      buffer.  The buffer number that it is put into is returned.
//

int MidiInPort_visual::installSysex(uchar* anArray, int aSize) {
   return installSysexPrivate(getPort(), anArray, aSize);
}



//////////////////////////////
//
// MidiInPort_visual::installSysexPrivate -- put a sysex message into a
//      buffer.  The buffer number that it is put into is returned.
//

int MidiInPort_visual::installSysexPrivate(int port, uchar* anArray, int aSize){
   if (port == -1) {
      return -1;
   }

   // choose a buffer to install sysex data into:
   int bufferNumber = sysexWriteBuffer[port];
   sysexWriteBuffer[port]++;
   if (sysexWriteBuffer[port] >= 128) {
      sysexWriteBuffer[port] = 0;
   }

   // copy contents of sysex message into the chosen buffer
   sysexBuffers[port][bufferNumber].setSize(aSize);
   uchar* dataptr = sysexBuffers[port][bufferNumber].getBase();
   uchar* indataptr = anArray;
   for (int i=0; i<aSize; i++) { 
      *dataptr = *indataptr;
      dataptr++;
      indataptr++;
   }

   // return the buffer number that was used
   return bufferNumber;
}



//////////////////////////////
//
// MidiInPort_visual::message
//

MidiMessage& MidiInPort_visual::message(int index) {
   if (getPort() != -1) {
      return midiBuffer[getPort()][index];
   } else {
      static MidiMessage nullmessage;
      return nullmessage;
   }
}



//////////////////////////////
//
// MidiInPort_visual::open -- returns true if MIDI input port was
//	opened.
//

int MidiInPort_visual::open(void) {
   if (getPort() == -1) {
      return 1;
   }

   if (getPortStatus() == 0) {
      int flag;
      flag = midiInOpen(&device[getPort()], getPort(), 
         (DWORD)&midiInputCallback, (DWORD)this, CALLBACK_FUNCTION);
      if (flag == MMSYSERR_NOERROR) {
         openQ[getPort()] = 1;
         installSysexStuff(device[getPort()], port);
         unpause();
         return 1;
      } else { // failed to open
         openQ[getPort()] = 0;
         device[getPort()] = NULL;
         return 0;
      }
   } else { // already open
      return 1;
   }
}



//////////////////////////////
//
// MidiInPort_visual::pause -- stop the Midi input port from
//	inserting MIDI messages into the buffer, but keep the
//	port open.  Use unpause() to reverse the effect of pause().
//

void MidiInPort_visual::pause(void) {
   if (getPort() == -1) {
      return;
   }

   if (openQ[getPort()]) {
      if (inrunningQ[getPort()] == 1) {
         midiInStop(device[getPort()]);
         inrunningQ[getPort()] = 0;
      }
   }
}



//////////////////////////////
//
// MidiInPort_visual::setBufferSize -- sets the allocation
//	size of the MIDI input buffer.
//

void MidiInPort_visual::setBufferSize(int aSize) {
   if (getPort() != -1) {
      midiBuffer[getPort()].setSize(aSize);
   }
}



//////////////////////////////
//
// MidiInPort_visual::setChannelOffset -- sets the MIDI channel offset, either 0 or 1.
//

void MidiInPort_visual::setChannelOffset(int anOffset) {
   switch (anOffset) {
      case 0:   channelOffset = 0;   break;
      case 1:   channelOffset = 1;   break;
      default:
         cout << "Error:  Channel offset can be only 0 or 1." << endl;
         exit(1);
   }
}



//////////////////////////////
//
// MidiInPort_visual::setPort --
//

void MidiInPort_visual::setPort(int aPort) {
   if (aPort < -1 || aPort >= getNumPorts()) {
      cerr << "Error: maximum port number is: " << getNumPorts()-1
           << ", but you tried to access port: " << aPort << endl;
      exit(1);
   }

   if (port != -1) {
      portObjectCount[port]--;
   }
   port = aPort;
   if (port != -1) {
      portObjectCount[port]++;
   }
}



//////////////////////////////
//
// MidiInPort_visual::setTrace -- if false, then don't print MIDI messages
// 	to the screen.
//

int MidiInPort_visual::setTrace(int aState) {
   int oldtrace = trace;
   if (aState == 0) {
      trace = 0;
   } else {
      trace = 1;
   }
   return oldtrace;
}



//////////////////////////////
//
// MidiInPort_visual::toggleTrace -- switches the state of trace
//	Returns the previous value of the trace variable.
//

void MidiInPort_visual::toggleTrace(void) {
   trace = !trace;
}
   


//////////////////////////////
//
// MidiInPort_visual::unpause -- enables the Midi input port 
//	to inserting MIDI messages into the buffer after the 
//	port is already open.
//

void MidiInPort_visual::unpause(void) {
   if (getPort() == -1) {
      return;
   }

   if (openQ[getPort()]) {
      if (inrunningQ[getPort()] == 0) {
         midiInStart(device[getPort()]);
         inrunningQ[getPort()] = 1;
      }
   }
}



///////////////////////////////////////////////////////////////////////////
//
// Private functions
//



//////////////////////////////
//
// MidiInPort_visual::deinitialize -- sets up storage if necessary
//	This function should be called if the current object is
//	the first object to be created.
//

void MidiInPort_visual::deinitialize(void) {
   int num = numDevices;

   closeAll();

   if (sysexBuffers != NULL) {
      for (int i=0; i<numDevices; i++) {
         if (sysexBuffers[i] != NULL) {
            delete sysexBuffers[i];
            sysexBuffers[i] = NULL;
         }
      }
      delete [] sysexBuffers;
      sysexBuffers = NULL;
   }


   if (sysexDriverBuffer1 != NULL) {
      for (int i=0; i<numDevices; i++) {
         if (sysexDriverBuffer1[i] != NULL) {
            delete sysexDriverBuffer1[i];
            sysexDriverBuffer1[i] = NULL;
         }
      }
      delete [] sysexDriverBuffer1;
      sysexDriverBuffer1 = NULL;
   }

   if (sysexDriverBuffer2 != NULL) {
      for (int i=0; i<numDevices; i++) {
         if (sysexDriverBuffer2[i] != NULL) {
            delete sysexDriverBuffer2[i];
            sysexDriverBuffer2[i] = NULL;
         }
      }
      delete [] sysexDriverBuffer2;
      sysexDriverBuffer2 = NULL;
   }

   if (sysexDBnumber != NULL) {
      delete [] sysexDBnumber;
      sysexDBnumber = NULL;
   }


   if (sysexWriteBuffer != NULL) {
      delete [] sysexWriteBuffer;
      sysexWriteBuffer = NULL;
   }

   if (sysexStatus != NULL) {
      delete [] sysexStatus;
      sysexStatus = NULL;
   }

   if (device != NULL) {
      delete [] device;
      device = NULL;
   }

   if (openQ != NULL) {
      delete [] openQ;
      openQ = NULL;
   }

   if (inrunningQ != NULL) {
      delete [] inrunningQ;
      inrunningQ = NULL;
   }

   if (hMutex != NULL) {
      delete [] hMutex;
      hMutex = NULL;
   }

   if (midiBuffer != NULL) {
      delete [] midiBuffer;
      midiBuffer = NULL;
   }

   if (portObjectCount != NULL) {
      delete [] portObjectCount;
      portObjectCount = NULL;
   }
}



//////////////////////////////
//
// MidiInPort_visual::initialize -- sets up storage if necessary
//	This function should be called if the current object is
//	the first object to be created.
//

void MidiInPort_visual::initialize(void) {
   int i;

   // get the number of ports
   numDevices = midiInGetNumDevs();
   if  (getNumPorts() <= 0) {
      cerr << "Error: no MIDI input devices" << endl;
      exit(1);
   }

   // allocate space for Windoze MIDI input structures
   if (device != NULL) {
      cerr << "Error: device array should be NULL when calling "
           << "initialize() in MidiInPort_visual." << endl;
      exit(1);
   }
   device = new HMIDIIN[numDevices];

   // allocate space for openQ, the port open/close status
   if (openQ != NULL) delete [] openQ;
   openQ = new int[numDevices];

   // allocate space to keep track of an active/inactive input port
   if (inrunningQ != NULL) delete [] inrunningQ;
   inrunningQ = new int[numDevices];

   // allocate space for object count on each port:
   if (portObjectCount != NULL) delete [] portObjectCount;
   portObjectCount = new int[numDevices];

   // allocate space for mutual exclusive
   if (hMutex != NULL) delete [] hMutex;
   hMutex = new HANDLE[numDevices];

   // allocate space for the Midi input buffers
   if (midiBuffer != NULL) delete [] midiBuffer;
   midiBuffer = new CircularBuffer<MidiMessage>[numDevices];

   // allocate space for the MIDI sysex buffer indices
   if (sysexWriteBuffer != NULL) delete [] sysexWriteBuffer;
   sysexWriteBuffer = new int[numDevices];

   // allocate space for the sysex MIM_LONGDATA message tracking
   if (sysexStatus != NULL) delete [] sysexStatus;
   sysexStatus = new int[numDevices];

   // allocate space for sysex buffers
   if (sysexBuffers != NULL) {
      cout << "Error: memory leak on sysex buffers initialization" << endl;
      exit(1);
   }
   sysexBuffers = new Array<uchar>*[numDevices];

   // allocate system exclusive buffers for MIDI driver
   if (sysexDriverBuffer1 != NULL) {
      cout << "Error: memory leak on sysex buffer for drivers creation" << endl;
      exit(1);
   }
   sysexDriverBuffer1 = new MIDIHDR*[numDevices];   
   for (i=0; i<numDevices; i++) {
      sysexDriverBuffer1[i] = NULL;
   }

   // allocate system exclusive buffers for MIDI driver
   if (sysexDriverBuffer2 != NULL) {
      cout << "Error: memory leak on sysex buffer for drivers creation" << endl;
      exit(1);
   }
   sysexDriverBuffer2 = new MIDIHDR*[numDevices];   
   for (i=0; i<numDevices; i++) {
      sysexDriverBuffer2[i] = NULL;
   }

   // allocate space for keeping track of which buffer to look at
   if (sysexDBnumber != NULL) delete [] sysexDBnumber;
   sysexDBnumber = new int[numDevices];


   // initialize the static arrays
   for (i=0; i<getNumPorts(); i++) {
      device[i] = NULL;
      openQ[i] = 0;
      inrunningQ[i] = 0;
      portObjectCount[i] = 0;
      hMutex[i] = CreateMutex(NULL, FALSE, "M");
      midiBuffer[i].setSize(DEFAULT_INPUT_BUFFER_SIZE);

      sysexStatus[i] = -1;
      sysexWriteBuffer[i] = 0;
      sysexDBnumber[i] = 0;
      sysexBuffers[i] = new Array<uchar>[128];
      for (int n=0; n<128; n++) {
         sysexBuffers[i][n].allowGrowth(0);      // shouldn't need to grow
         sysexBuffers[i][n].setAllocSize(32);
         sysexBuffers[i][n].setSize(0);
         sysexBuffers[i][n].setGrowth(32);       // in case it will ever grow
      }

   }
}



//////////////////////////////
//
// MidiInPort_visual::installSysexStuff -- install all the mess that 
//   a MIDIIN structure needs in order to receive system exclusives.
//

void MidiInPort_visual::installSysexStuff(HMIDIIN dev, int port) {
   if (sysexDriverBuffer1 != NULL) {
      if (sysexDriverBuffer1[port] != NULL) {
         // some memory leaks here
         delete sysexDriverBuffer1[port];
         sysexDriverBuffer1[port] = NULL;
      }
   }
   if (sysexDriverBuffer2 != NULL) {
      if (sysexDriverBuffer2[port] != NULL) {
         // some memory leaks here
         delete sysexDriverBuffer2[port];
         sysexDriverBuffer2[port] = NULL;
      }
   }

   // allocate space for Drivers sysex byte buffer
   sysexDriverBuffer1[port] = (LPMIDIHDR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE |
          GMEM_SHARE, sizeof(MIDIHDR)));
   sysexDriverBuffer2[port] = (LPMIDIHDR)GlobalLock(GlobalAlloc(GMEM_MOVEABLE |
          GMEM_SHARE, sizeof(MIDIHDR)));

   if (sysexDriverBuffer1[port] == NULL) {
      cout << "Error: could not allocate sysex driver's buffer" << endl;
      exit(1);
   }

   if (sysexDriverBuffer2[port] == NULL) {
      cout << "Error: could not allocate sysex driver's buffer" << endl;
      exit(1);
   }

   // allocate buffer inside of sysexDriverBuffer
   sysexDriverBuffer1[port]->lpData = (LPSTR)GlobalLock(GlobalAlloc(
         GMEM_MOVEABLE | GMEM_SHARE, (DWORD)1024));
   sysexDriverBuffer2[port]->lpData = (LPSTR)GlobalLock(GlobalAlloc(
         GMEM_MOVEABLE | GMEM_SHARE, (DWORD)1024));

   if (sysexDriverBuffer1[port]->lpData == NULL) {
      cout << "Error: there was not enought space to allocate sysex buffer" 
           << endl;
      // leaking memory here
      exit(1);
   }

   if (sysexDriverBuffer2[port]->lpData == NULL) {
      cout << "Error: there was not enought space to allocate sysex buffer" 
           << endl;
      // leaking memory here
      exit(1);
   }


   // setup other sysexDriverBuffer data fields
   sysexDriverBuffer1[port]->dwBufferLength = 1024; // total size of buffer
   sysexDriverBuffer1[port]->dwBytesRecorded = 0L;  // number of byte in buffer
   sysexDriverBuffer1[port]->dwFlags = 0L;          // initialize flags
   sysexDriverBuffer1[port]->dwUser = 0L;       // userdata: used for sysex time

   // setup other sysexDriverBuffer data fields
   sysexDriverBuffer2[port]->dwBufferLength = 1024; // total size of buffer
   sysexDriverBuffer2[port]->dwBytesRecorded = 0L;  // number of byte in buffer
   sysexDriverBuffer2[port]->dwFlags = 0L;          // initialize flags
   sysexDriverBuffer2[port]->dwUser = 0L;       // userdata: used for sysex time

   // prepare the header
   int status = midiInPrepareHeader(device[port], sysexDriverBuffer1[port], 
         sizeof(MIDIHDR));

   if (status != 0) {
      cout << "Error preparing sysex buffer number: " << port << endl;  
      // leaking some memory here?
      exit(1);
   }

   // prepare the header
   status = midiInPrepareHeader(device[port], sysexDriverBuffer2[port], 
         sizeof(MIDIHDR));

   if (status != 0) {
      cout << "Error preparing sysex buffer number: " << port << endl;  
      // leaking some memory here?
      exit(1);
   }

   // add the sysex buffer to the driver
   status = midiInAddBuffer(device[port], sysexDriverBuffer1[port], 
        sizeof(MIDIHDR));

   if (status != 0) {
      cout << "Error adding sysex buffer to driver: " << port << endl;
      // leaking some memory here?
      exit(1);
   }

   status = midiInAddBuffer(device[port], sysexDriverBuffer2[port], 
        sizeof(MIDIHDR));

   if (status != 0) {
      cout << "Error adding sysex buffer to driver: " << port << endl;
      // leaking some memory here?
      exit(1);
   }

}



//////////////////////////////
//
// MidiInPort_visual::uninstallSysexStuff -- uninstalls all the mess that 
//   a MIDIIN structure needs in order to receive system exclusives.
//

void MidiInPort_visual::uninstallSysexStuff(HMIDIIN dev, int port) {
   if (port == -1) { 
      return;
   }
   // unprepare the headers
   midiInUnprepareHeader(device[port], sysexDriverBuffer1[port], 
         sizeof(MIDIHDR));
   midiInUnprepareHeader(device[port], sysexDriverBuffer2[port], 
         sizeof(MIDIHDR));

   // deallocate buffer inside of sysexDriverBuffer
   /* Following code caused problems: perhaps lpData was deleted by driver
   delete [] sysexDriverBuffer1[port]->lpData;
   sysexDriverBuffer1[port]->lpData = NULL;
   delete [] sysexDriverBuffer2[port]->lpData;
   sysexDriverBuffer2[port]->lpData = NULL;
   */

   // deallocate space for Drivers sysex byte buffer
   delete sysexDriverBuffer1[port];
   delete sysexDriverBuffer2[port];
   sysexDriverBuffer1[port] = NULL;
   sysexDriverBuffer2[port] = NULL;
}



//////////////////////////////
//
// MidiInPort_visual::releaseMutex
//

void MidiInPort_visual::releaseMutex(void) {
/*   int flag = */ ReleaseMutex(hMutex[getPort()]);
/* 
   if (flag != 0) {
      cerr << "Error relasing mutex in MIDI input; flag was: " << flag << endl;
   }
*/
}



//////////////////////////////
//
// MidiInPort_visual::setPortStatus
//

void MidiInPort_visual::setPortStatus(int aStatus) {
   if (getPort() == -1) {
      return;
   }

   if (aStatus) {
      openQ[getPort()] = 1;
   } else {
      openQ[getPort()] = 0;
   }
}



//////////////////////////////
//
// MidiInPort_visual::waitForMutex 
//

void MidiInPort_visual::waitForMutex(void) {
/*
   DWORD mutexResult = WaitForSingleObject(hMutex[getPort()], 5000L);
   if (mutexResult != WAIT_OBJECT_0) {
      cerr << "Error waiting for mutex in MIDI input" << endl;
   }
*/
}



///////////////////////////////////////////////////////////////////////////


//////////////////////////////
//
// midiInputCallback -- the function the MIDI input driver calls when
// 	it has a message from the Midi in cable ready
//

void CALLBACK midiInputCallback(HMIDIIN hMidiIn, UINT inputStatus,
      DWORD instancePtr, DWORD midiMessage, DWORD timestamp) {
   static MidiMessage newMessage;
   
   switch (inputStatus) {
      case MIM_MOREDATA:
         // There is more data waiting at the device.
         // If this case is exists, then that means that the MIDI
         // device is too slow and some data was lost.
         // Windows sends a MIM_MOREDATA event only if you specify
         // the MIDI_IO_STATUS flag to midiInOpen().

         // no break;
      case MIM_DATA:

         // One regular (non sysex) message has been completely
         // received.
  
         // ignore the Yamaha Active Sensing command and MIDI time clock
         // at least for now.
         if ((midiMessage & 0xff) == 0xfe || (midiMessage & 0xff) == 0xf8) {
            break;
         }

         newMessage.time = timestamp;
         newMessage.data = midiMessage;
         ((MidiInPort_visual*)instancePtr)->insert(newMessage);
         if (((MidiInPort_visual*)instancePtr)->getTrace()) {
            cout << "[" << hex << (int)newMessage.command() << dec
                 << ":" << (int)newMessage.p1() << ","
                 << (int)newMessage.p2() << "]";
            cout.flush();
         }
         break;

      case MIM_LONGDATA:
         {
         // A sysex or part of a sysex message is coming in.
         // The timestamp variable contains a pointer to a 
         // MIDIHDR pointer

         MIDIHDR* midiheader = (MIDIHDR*)midiMessage;
         int dataCount = midiheader->dwBytesRecorded;
         char* data = midiheader->lpData;
         int port = ((MidiInPort_visual*)instancePtr)->getPort();
         if (port == -1) {
            break;
         }
         int* sysexStatus = ((MidiInPort_visual*)instancePtr)->sysexStatus;
//         MIDIHDR** sysexDriverBuffer = ((MidiInPort_visual*)instancePtr)->
//               sysexDriverBuffer;
         HMIDIIN devicex = ((MidiInPort_visual*)instancePtr)->device[port];

         if (dataCount == 0) {
            // can't handle a zero-length sysex
            break;
         }

         // step 1: determine if this is the first part of the sysex
         // message or a continuation
         int continuation = 0;
         if (data[0] == (char)0xf0) {
            continuation = 0;
            if (sysexStatus[port] != -1) {
               cout << "Error: there is another sysex command being "
                       "received on port " << port << endl;
               exit(1);
            }
         } else {
            if (sysexStatus[port] == -1) {
               cout << "Error: no sysex command is being "
                       "received on port " << port << endl;
               if (data[0] < 128) {
                  cout << "First byte is: " << dec << (int)data[0] << endl;
               } else { 
                  cout << "First byte is: " << hex << (int)data[0] << endl;
               }
               if (data[1] < 128) {
                  cout << "Second byte is: " << dec << (int)data[1] << endl;
               } else { 
                  cout << "Second byte is: " << hex << (int)data[1] << endl;
               }
                                                                           
               exit(1);
            }
            continuation = 1;
         }

         // step 2: if continuing, add the data to the preallocated
         // sysex buffer, otherwise, get a new buffer location
         int buffer = -1;
         if (continuation) {
            buffer = sysexStatus[port];
            if (buffer < 0 || buffer > 127) {
               cout << "Sysex buffer was out of range: " << buffer << endl;
            }
            for (int i=0; i<dataCount; i++) {
               unsigned char datum = data[i];
               ((MidiInPort_visual*)instancePtr)->
                     sysexBuffers[port][buffer].append(datum);
               if (datum == 0xf7) {
                  for (int k=i; k<dataCount; k++) {
                     data[k-i] = data[k];
                  }
                  midiheader->dwBytesRecorded = dataCount - i - 1;

                  goto insert_sysex_message;
               }
            }
         } else { // if not a continuation of a sysex event
            buffer = ((MidiInPort_visual*)instancePtr)->sysexWriteBuffer[port];
            ((MidiInPort_visual*)instancePtr)->sysexWriteBuffer[port]++;
            if (buffer == 127) {
               ((MidiInPort_visual*)instancePtr)->sysexWriteBuffer[port] = 0;
            }

            ((MidiInPort_visual*)instancePtr)->
                  sysexBuffers[port][buffer].setSize(0);
            for (int j=0; j<dataCount; j++) {
               unsigned char datum = data[j];
               ((MidiInPort_visual*)instancePtr)->
                     sysexBuffers[port][buffer].append(datum);
               if (datum == 0xf7) {
                  for (int k=j; k<dataCount; k++) {
                     data[k-j] = data[k];
                  }

                  goto insert_sysex_message;
               }
            }

         }

         // recycle the MIDI input buffer for the driver
         {
         midiInPrepareHeader(devicex, midiheader, sizeof(MIDIHDR));
         int dstatus = midiInAddBuffer(devicex, midiheader, sizeof(MIDIHDR));
         if (dstatus != MMSYSERR_NOERROR) {
            cout << "Error when calling midiInAddBuffer" << endl;
            exit(1);
         }
         }

         break;

         insert_sysex_message:

         // recycle the MIDI input buffer for the driver
         {
         midiInPrepareHeader(devicex, midiheader, sizeof(MIDIHDR));
         int estatus = midiInAddBuffer(devicex, midiheader, sizeof(MIDIHDR));
         if (estatus != MMSYSERR_NOERROR) {
            cout << "Error when calling midiInAddBuffer" << endl;
            exit(1);
         }
         }

         // now that a sysex message is finished, send a midimessage
         // out to the instancePtr MIDI buffer telling the user
         // that a sysex message has come in.

         // newMessage.time = timestamp; use last time stamp that came
         // in because the timestamp variable is used for storing
         // the pointer of the sysex data.

         newMessage.time = timestamp;
         newMessage.p0() = 0xf0;
         newMessage.p1() = buffer;
         newMessage.p2() = 0;
         newMessage.p3() = 0;

         ((MidiInPort_visual*)instancePtr)->insert(newMessage);
         if (((MidiInPort_visual*)instancePtr)->getTrace()) {
            cout << "[" << hex << (int)newMessage.command() << dec
                 << ":" << (int)newMessage.p1() << ","
                 << (int)newMessage.p2() << "]";
            cout.flush();
         }

         } // end of local variable range
         break;

      case MIM_ERROR:
         // An invalid regular MIDI message was received.
  
         break;

      case MIM_LONGERROR:
         {
         // An invalid sysex MIDI message was received.
  
         // if a sysex message was continuing from a previous part,
         // then kill that message.
  
         int port = ((MidiInPort_visual*)instancePtr)->getPort();
         if (port == -1) {
            break;
         }
         int buffer = ((MidiInPort_visual*)instancePtr)->sysexStatus[port];
         if (buffer != -1) {
            ((MidiInPort_visual*)instancePtr)->
                  sysexBuffers[port][buffer].setSize(0);
            ((MidiInPort_visual*)instancePtr)->sysexStatus[port] = -1;
         }

         HMIDIIN devicex = ((MidiInPort_visual*)instancePtr)->device[port];
         MIDIHDR* midiheader = (MIDIHDR*)midiMessage;

         // recycle the MIDI input buffer for the driver
         midiInPrepareHeader(devicex, midiheader, sizeof(MIDIHDR));
         int status = midiInAddBuffer(devicex, midiheader, sizeof(MIDIHDR));
         if (status != MMSYSERR_NOERROR) {
            cout << "Error when calling midiInAddBuffer" << endl;
            exit(1);
         }


         break;
         }
      default: ;
      // case MIM_OPEN:    // MIDI device is opening
      // case MIM_CLOSE:   // MIDI device is closing
   }
}



#endif  // VISUAL


// md5sum:	db55d9f375b86f54c0c8340547c5701f  - MidiInPort_visual.cpp =css= 20030102