Debian Codegraph @

src/core/midiio_rtmidi.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // file: midiio_rtmidi.cpp
28 // desc: midi io header
29 //
30 // author: Ge Wang ([email protected] | [email protected])
31 // Ananya Misra ([email protected])
32 // date: Summer 2005
33 //-----------------------------------------------------------------------------
34 #include "midiio_rtmidi.h"
35
36 #ifndef __DISABLE_MIDI__
37
38 #include "chuck_errmsg.h"
39 #include "chuck_vm.h"
40 #include <vector>
41 #include <map>
42 #include <fstream>
43
44
45
46
47 //-----------------------------------------------------------------------------
48 // global variables
49 //-----------------------------------------------------------------------------
50 #define MIDI_BUFFER_SIZE 8192
51
52 std::vector<RtMidiIn *> MidiInManager::the_mins;
53 std::vector< std::map< Chuck_VM *, CBufferAdvance * > > MidiInManager::the_bufs;
54 std::vector<RtMidiOut *> MidiOutManager::the_mouts;
55 std::map< Chuck_VM *, CBufferSimple * > MidiInManager::m_event_buffers;
56
57
58
59
60 //-----------------------------------------------------------------------------
61 // name: MidiOut()
62 // desc: constructor
63 //-----------------------------------------------------------------------------
64 MidiOut::MidiOut()
65 {
66 mout = NULL;
67 m_device_num = 0;
68 m_valid = FALSE;
69 m_suppress_output = FALSE;
70 }
71
72
73
74
75 //-----------------------------------------------------------------------------
76 // name: ~MidiOut()
77 // desc: destructor
78 //-----------------------------------------------------------------------------
79 MidiOut::~MidiOut()
80 {
81 if( mout ) this->close();
82 // CK_SAFE_DELETE( mout );
83 }
84
85
86
87
88 //-----------------------------------------------------------------------------
89 // name: send()
90 // desc: send 1 byte midi message
91 //-----------------------------------------------------------------------------
92 t_CKUINT MidiOut::send( t_CKBYTE status )
93 {
94 return this->send( status, 0, 0 );
95 }
96
97
98
99
100 //-----------------------------------------------------------------------------
101 // name: send()
102 // desc: send 2 byte midi message
103 // note: previously, this was sending a 3 byte message with data2 = 0, this was
104 // causing a problem on macOS (only) where rtmidi was sending two program
105 // change messages instead of one. This was fixed by sending a 2 byte
106 // message | 1.5.2.5 (cviejo)
107 //-----------------------------------------------------------------------------
108 t_CKUINT MidiOut::send( t_CKBYTE status, t_CKBYTE data1 )
109 {
110 if( !m_valid ) return 0;
111
112 // clear
113 m_msg.clear();
114 // add
115 m_msg.push_back( status );
116 m_msg.push_back( data1 );
117
118 mout->sendMessage( &m_msg );
119
120 return 2;
121 }
122
123
124
125
126 //-----------------------------------------------------------------------------
127 // name: send()
128 // desc: send 3 byte midi message
129 //-----------------------------------------------------------------------------
130 t_CKUINT MidiOut::send( t_CKBYTE status, t_CKBYTE data1, t_CKBYTE data2 )
131 {
132 if( !m_valid ) return 0;
133
134 // clear
135 m_msg.clear();
136 // add
137 m_msg.push_back( status );
138 m_msg.push_back( data1 );
139 m_msg.push_back( data2 );
140
141 mout->sendMessage( &m_msg );
142
143 return 3;
144 }
145
146
147
148
149 //-----------------------------------------------------------------------------
150 // name: send()
151 // desc: send
152 //-----------------------------------------------------------------------------
153 t_CKUINT MidiOut::send( const MidiMsg * msg )
154 {
155 if( !m_valid ) return 0;
156
157 // clear
158 m_msg.clear();
159 // add
160 m_msg.push_back( msg->data[0] );
161 m_msg.push_back( msg->data[1] );
162 m_msg.push_back( msg->data[2] );
163
164 mout->sendMessage( &m_msg );
165
166 return 3;
167 }
168
169
170
171
172 //-----------------------------------------------------------------------------
173 // name: open
174 // desc: open midi output
175 //-----------------------------------------------------------------------------
176 t_CKBOOL MidiOut::open( t_CKUINT device_num )
177 {
178 // close if already opened
179 if( m_valid )
180 this->close();
181
182 return m_valid = MidiOutManager::open( this, (t_CKINT)device_num );
183 }
184
185
186
187
188 //-----------------------------------------------------------------------------
189 // name: open
190 // desc: open midi output
191 //-----------------------------------------------------------------------------
192 t_CKBOOL MidiOut::open( const std::string & name )
193 {
194 // close if already opened
195 if( m_valid )
196 this->close();
197
198 return m_valid = MidiOutManager::open( this, name );
199 }
200
201
202
203
204 //-----------------------------------------------------------------------------
205 // name: close( )
206 // desc: close midi output
207 //-----------------------------------------------------------------------------
208 t_CKBOOL MidiOut::close( )
209 {
210 if( !m_valid )
211 return FALSE;
212
213 // close
214 // MidiOutManager::close( this );
215
216 m_valid = FALSE;
217
218 return TRUE;
219 }
220
221
222
223
224 //-----------------------------------------------------------------------------
225 // name: noteon()
226 // desc: note on message
227 //-----------------------------------------------------------------------------
228 t_CKUINT MidiOut::noteon( t_CKUINT channel, t_CKUINT note, t_CKUINT velocity )
229 { return this->send( (t_CKBYTE)(MIDI_NOTEON + channel), note, velocity ); }
230
231
232
233
234 //-----------------------------------------------------------------------------
235 // name: noteoff()
236 // desc: note off message
237 //-----------------------------------------------------------------------------
238 t_CKUINT MidiOut::noteoff( t_CKUINT channel, t_CKUINT note, t_CKUINT velocity )
239 { return this->send( (t_CKBYTE)(MIDI_NOTEOFF + channel), note, velocity ); }
240
241
242
243
244 //-----------------------------------------------------------------------------
245 // name: polypress()
246 // desc: polypress message
247 //-----------------------------------------------------------------------------
248 t_CKUINT MidiOut::polypress( t_CKUINT channel, t_CKUINT note, t_CKUINT pressure )
249 { return this->send( (t_CKBYTE)(MIDI_POLYPRESS + channel), note, pressure ); }
250
251
252
253
254 //-----------------------------------------------------------------------------
255 // name: ctrlchange()
256 // desc: ctrl change message
257 //-----------------------------------------------------------------------------
258 t_CKUINT MidiOut::ctrlchange( t_CKUINT channel, t_CKUINT ctrl_num, t_CKUINT ctrl_val )
259 { return this->send( (t_CKBYTE)(MIDI_CTRLCHANGE + channel), ctrl_num, ctrl_val ); }
260
261
262
263
264 //-----------------------------------------------------------------------------
265 // name: progchange()
266 // desc: prog change message
267 //-----------------------------------------------------------------------------
268 t_CKUINT MidiOut::progchange( t_CKUINT channel, t_CKUINT patch )
269 { return this->send( (t_CKBYTE)(MIDI_PROGCHANGE + channel), patch ); }
270
271
272
273
274 //-----------------------------------------------------------------------------
275 // name: chanpress()
276 // desc: chan press
277 //-----------------------------------------------------------------------------
278 t_CKUINT MidiOut::chanpress( t_CKUINT channel, t_CKUINT pressure )
279 { return this->send( (t_CKBYTE)(MIDI_CHANPRESS + channel), pressure ); }
280
281
282
283
284 //-----------------------------------------------------------------------------
285 // name: pitchbend()
286 // desc: pitch bend
287 //-----------------------------------------------------------------------------
288 t_CKUINT MidiOut::pitchbendFine( t_CKUINT channel, t_CKUINT lsb, t_CKUINT msb)
289 { return this->send( (t_CKBYTE)(MIDI_PITCHBEND + channel), lsb, msb ); }
290
291
292
293
294 //-----------------------------------------------------------------------------
295 // name: pitchbend()
296 // desc: pitch bend
297 //-----------------------------------------------------------------------------
298 t_CKUINT MidiOut::pitchbend( t_CKUINT channel, t_CKUINT bend_val )
299 { return this->pitchbendFine( channel, 0, bend_val ); }
300
301
302
303
304 //-----------------------------------------------------------------------------
305 // name: allnotesoff()
306 // desc: allnotesoff
307 // note: allnotesoff and others are channel mode messages, not that commonly
308 // used and very easy to implement with MidiOut::ctrlchange so we're not
309 // exposing them for now.
310 //-----------------------------------------------------------------------------
311 t_CKUINT MidiOut::allnotesoff( t_CKUINT channel )
312 { return this->ctrlchange( channel, 123, 0 ); }
313
314
315
316
317 //-----------------------------------------------------------------------------
318 // name: MidiIn()
319 // desc: constructor
320 //-----------------------------------------------------------------------------
321 MidiIn::MidiIn()
322 {
323 min = NULL;
324 m_device_num = 0;
325 m_valid = FALSE;
326 m_read_index = 0;
327 m_buffer = NULL;
328 m_suppress_output = FALSE;
329 SELF = NULL;
330 }
331
332
333
334
335 //-----------------------------------------------------------------------------
336 // name: ~MidiIn()
337 // desc: destructor
338 //-----------------------------------------------------------------------------
339 MidiIn::~MidiIn( )
340 {
341 this->close();
342 // CK_SAFE_DELETE( min );
343 }
344
345
346
347
348 //-----------------------------------------------------------------------------
349 // name: open()
350 // desc: open
351 //-----------------------------------------------------------------------------
352 t_CKBOOL MidiIn::open( Chuck_VM * vm, t_CKUINT device_num )
353 {
354 // close if already opened
355 if( m_valid )
356 this->close();
357
358 // open
359 return m_valid = MidiInManager::open( this, vm, (t_CKINT)device_num );
360 }
361
362
363
364
365 //-----------------------------------------------------------------------------
366 // name: open()
367 // desc: open
368 //-----------------------------------------------------------------------------
369 t_CKBOOL MidiIn::open( Chuck_VM * vm, const std::string & name )
370 {
371 // close if already opened
372 if( m_valid )
373 this->close();
374
375 // open
376 return m_valid = MidiInManager::open( this, vm, name );
377 }
378
379
380
381
382 MidiInManager::MidiInManager()
383 {
384 the_mins.resize( 1024 );
385 the_bufs.resize( 1024 );
386 }
387
388
389 MidiInManager::~MidiInManager()
390 {
391 // yeah right
392 // vm->destroy_event_buffer( m_event_buffer );
393 }
394
395
396 t_CKBOOL MidiInManager::open( MidiIn * min, Chuck_VM * vm, t_CKINT device_num )
397 {
398 // see if port not already open
399 if( device_num >= (t_CKINT)the_mins.capacity() || !the_mins[device_num] )
400 {
401 if( m_event_buffers.count( vm ) == 0 )
402 {
403 m_event_buffers[vm] = vm->create_event_buffer();
404 }
405
406 // allocate
407 RtMidiIn * rtmin = new RtMidiIn;
408 try {
409 rtmin->openPort( (unsigned int) device_num );
410 // callback, userData. first cast device num to unsigned int, then to void *
411 rtmin->setCallback( cb_midi_input, (void *) ( (t_CKUINT)device_num ) );
412 } catch( RtMidiError & err ) {
413 if( !min->m_suppress_output )
414 {
415 // print it
416 EM_error2( 0, "MidiIn: couldn't open MIDI port %i...", device_num );
417 err.getMessage();
418 // const char * e = err.getMessage().c_str();
419 // EM_error2( 0, "...(%s)", err.getMessage().c_str() );
420 }
421 return FALSE;
422 }
423
424 // clear ignore types | 1.4.1.0 (mariobuoninfante)
425 rtmin->ignoreTypes( false, false, false );
426
427 // resize?
428 if( device_num >= (t_CKINT)the_mins.capacity() )
429 {
430 t_CKINT size = the_mins.capacity() * 2;
431 if( device_num >= size ) size = device_num + 1;
432 the_mins.resize( size );
433 the_bufs.resize( size );
434 }
435
436 // put rtmin in vector for future generations
437 the_mins[device_num] = rtmin;
438 }
439 // if it doesn't exist already, allocate the buffer and put it in the_bufs
440 if( !add_vm( vm, device_num, min->m_suppress_output ) )
441 {
442 return FALSE;
443 }
444
445 // set min
446 min->min = the_mins[device_num];
447 // found
448 min->m_buffer = the_bufs[device_num][vm];
449 // get an index into your (you are min here) own buffer,
450 // and a free ticket to your own workshop
451 min->m_read_index = min->m_buffer->join( (Chuck_Event *)min->SELF );
452 min->m_device_num = (t_CKUINT)device_num;
453
454 // done
455 return TRUE;
456 }
457
458 t_CKBOOL MidiInManager::close(MidiIn * min)
459 {
460 min->m_buffer->resign(min->m_read_index);
461 return true;
462 }
463
464 t_CKBOOL MidiInManager::open( MidiIn * min, Chuck_VM * vm, const std::string & name )
465 {
466 t_CKINT device_num = -1;
467
468 try
469 {
470 RtMidiIn * rtmin = new RtMidiIn;
471
472 t_CKINT count = rtmin->getPortCount();
473 for(t_CKINT i = 0; i < count; i++)
474 {
475 std::string port_name = rtmin->getPortName( (unsigned int) i );
476 if( port_name == name)
477 {
478 device_num = i;
479 break;
480 }
481 }
482
483 if( device_num == -1 )
484 {
485 // search by substring
486 for(t_CKINT i = 0; i < count; i++)
487 {
488 std::string port_name = rtmin->getPortName( (unsigned int) i );
489 if( port_name.find( name ) != std::string::npos )
490 {
491 device_num = i;
492 break;
493 }
494 }
495 }
496 }
497 catch( RtMidiError & err )
498 {
499 if( !min->m_suppress_output )
500 {
501 // print it
502 EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() );
503 err.getMessage();
504 // const char * e = err.getMessage().c_str();
505 // EM_error2( 0, "...(%s)", err.getMessage().c_str() );
506 }
507 return FALSE;
508 }
509
510 if(device_num == -1)
511 {
512 EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() );
513 return FALSE;
514 }
515
516 t_CKBOOL result = open( min, vm, device_num );
517
518 return result;
519 }
520
521
522
523
524 //-----------------------------------------------------------------------------
525 // name: add_vm()
526 // desc: add vm
527 //-----------------------------------------------------------------------------
528 t_CKBOOL MidiInManager::add_vm( Chuck_VM * vm, t_CKINT device_num,
529 t_CKBOOL suppress_output )
530 {
531 if( device_num >= the_bufs.capacity() )
532 {
533 if( !suppress_output )
534 EM_error2( 0, "MidiIn: couldn't allocate CBuffer for unopened port %i...", device_num );
535 return FALSE;
536 }
537
538 if( the_bufs[device_num].count( vm ) > 0
539 && the_bufs[device_num][vm] != NULL )
540 {
541 // already exists: don't need to do anything
542 return TRUE;
543 }
544
545 // allocate the buffer
546 CBufferAdvance * cbuf = new CBufferAdvance;
547 if( !cbuf->initialize( MIDI_BUFFER_SIZE, sizeof(MidiMsg), m_event_buffers[vm] ) )
548 {
549 if( !suppress_output )
550 EM_error2( 0, "MidiIn: couldn't allocate CBuffer for port %i...", device_num );
551 delete cbuf;
552 return FALSE;
553 }
554
555 the_bufs[device_num][vm] = cbuf;
556 return TRUE;
557 }
558
559
560
561
562 //-----------------------------------------------------------------------------
563 // name: cleanup_buffer()
564 // desc: cleanup buffer
565 //-----------------------------------------------------------------------------
566 void MidiInManager::cleanup_buffer( Chuck_VM * vm )
567 {
568 // cleanup all cbufs stored for that vm
569 for( int i = 0; i < the_bufs.size(); i++ )
570 {
571 if( the_bufs[i].count( vm ) > 0 )
572 {
573 CBufferAdvance * cbuf = the_bufs[i][vm];
574 delete cbuf;
575 the_bufs[i].erase( vm );
576 }
577
578 }
579
580 if( m_event_buffers.count( vm ) > 0 )
581 {
582 vm->destroy_event_buffer( m_event_buffers[vm] );
583 m_event_buffers.erase( vm );
584 }
585 }
586
587
588
589
590 //-----------------------------------------------------------------------------
591 // name: close()
592 // desc: close
593 //-----------------------------------------------------------------------------
594 t_CKBOOL MidiIn::close()
595 {
596 if( !m_valid )
597 return FALSE;
598
599 MidiInManager::close(this);
600
601 m_valid = FALSE;
602
603 return TRUE;
604 }
605
606
607
608
609 //-----------------------------------------------------------------------------
610 // name: empty()
611 // desc: is empty?
612 //-----------------------------------------------------------------------------
613 t_CKBOOL MidiIn::empty()
614 {
615 if( !m_valid ) return TRUE;
616 return m_buffer->empty( m_read_index );
617 }
618
619
620
621
622 //-----------------------------------------------------------------------------
623 // name: get()
624 // desc: get message
625 //-----------------------------------------------------------------------------
626 t_CKUINT MidiIn::recv( MidiMsg * msg )
627 {
628 if( !m_valid ) return FALSE;
629 return m_buffer->get( msg, 1, m_read_index );
630 }
631
632
633
634
635 //-----------------------------------------------------------------------------
636 // name: cb_midi_output
637 // desc: call back
638 //-----------------------------------------------------------------------------
639 void MidiInManager::cb_midi_input( double deltatime, std::vector<unsigned char> * msg,
640 void * userData )
641 {
642 // this cb is per-Midi-in AKA per-device number.
643 // it needs to know its device number so it can inform all VMs waiting
644 // on that device number.
645 // --> device num stored in userData
646 t_CKUINT nBytes = (t_CKUINT)msg->size();
647 t_CKUINT device_num = (t_CKUINT)userData;
648 // check if we know the bufs for that device num (we should!)
649 if( device_num >= the_bufs.size() )
650 {
651 EM_error2( 0, "MidiIn: couldn't find buffers for port %i...", device_num );
652 return;
653 }
654 MidiMsg m;
655 if( nBytes >= 1 ) m.data[0] = msg->at(0);
656 if( nBytes >= 2 ) m.data[1] = msg->at(1);
657 if( nBytes >= 3 ) m.data[2] = msg->at(2);
658
659 // put in all the buffers, make sure not active sensing
660 if( m.data[2] != 0xfe )
661 {
662 for( std::map< Chuck_VM *, CBufferAdvance * >::iterator it =
663 the_bufs[device_num].begin(); it != the_bufs[device_num].end(); it++ )
664 {
665 CBufferAdvance * cbuf = it->second;
666 if( cbuf != NULL )
667 {
668 cbuf->put( &m, 1 );
669 }
670 }
671 }
672 }
673
674
675
676
677 //-----------------------------------------------------------------------------
678 // name: probeMidiIn()
679 // desc: ...
680 //-----------------------------------------------------------------------------
681 void probeMidiIn()
682 {
683 RtMidiIn * min = NULL;
684
685 try {
686 min = new RtMidiIn;;
687 } catch( RtMidiError & err ) {
688 EM_error2b( 0, "%s", err.getMessage().c_str() );
689 return;
690 }
691
692 // get num
693 t_CKUINT num = min->getPortCount();
694 EM_print2blue( "------( %i MIDI input%s )------", num, num > 1 ? "s" : "" );
695 EM_reset_msg();
696
697 std::string s;
698 for( t_CKUINT i = 0; i < num; i++ )
699 {
700 try { s = min->getPortName( (unsigned int) i ); }
701 catch( RtMidiError & err )
702 { err.printMessage(); return; }
703 EM_error2b( 0, " [%i] : \"%s\"", i, s.c_str() );
704
705 EM_reset_msg();
706 }
707 }
708
709
710
711
712 //-----------------------------------------------------------------------------
713 // name: probeMidiOut()
714 // desc: ...
715 //-----------------------------------------------------------------------------
716 void probeMidiOut()
717 {
718 RtMidiOut * mout = NULL;
719
720 try {
721 mout = new RtMidiOut;
722 } catch( RtMidiError & err ) {
723 EM_error2b( 0, "%s", err.getMessage().c_str() );
724 return;
725 }
726
727 // get num
728 t_CKUINT num = mout->getPortCount();
729 EM_print2blue( "------( %i MIDI output%s )-----", num, num > 1 ? "s" : "" );
730 std::string s;
731 for( t_CKUINT i = 0; i < num; i++ )
732 {
733 try { s = mout->getPortName( (unsigned int) i ); }
734 catch( RtMidiError & err )
735 { err.printMessage(); return; }
736 EM_error2b( 0, " [%i] : \"%s\"", i, s.c_str() );
737 }
738 }
739
740
741 MidiOutManager::MidiOutManager()
742 {
743 the_mouts.resize( 1024 );
744 }
745
746
747 MidiOutManager::~MidiOutManager()
748 {
749 // yeah right
750 }
751
752
753 t_CKBOOL MidiOutManager::open( MidiOut * mout, t_CKINT device_num )
754 {
755 // see if port not already open
756 if( device_num >= (t_CKINT)the_mouts.capacity() || !the_mouts[device_num] )
757 {
758 // allocate
759 RtMidiOut * rtmout = new RtMidiOut;
760 try {
761 rtmout->openPort( (unsigned int) device_num );
762 } catch( RtMidiError & err ) {
763 if( !mout->m_suppress_output )
764 {
765 // print it
766 EM_error2( 0, "MidiOut: couldn't open MIDI port %i...", device_num );
767 err.getMessage();
768 // const char * e = err.getMessage().c_str();
769 // EM_error2( 0, "...(%s)", err.getMessage().c_str() );
770 }
771 return FALSE;
772 }
773
774 // resize?
775 if( device_num >= (t_CKINT)the_mouts.capacity() )
776 {
777 t_CKINT size = the_mouts.capacity() * 2;
778 if( device_num >= size ) size = device_num + 1;
779 the_mouts.resize( size );
780 }
781
782 // put rtmout in vector for future generations
783 the_mouts[device_num] = rtmout;
784 }
785
786 // found (always) (except when it doesn't get here)
787 mout->mout = the_mouts[device_num];
788 mout->m_device_num = (t_CKUINT)device_num;
789
790 // done
791 return TRUE;
792 }
793
794 t_CKBOOL MidiOutManager::open( MidiOut * mout, const std::string & name )
795 {
796 t_CKINT device_num = -1;
797
798 try
799 {
800 RtMidiOut * rtmout = new RtMidiOut;
801
802 t_CKINT count = rtmout->getPortCount();
803 for(t_CKINT i = 0; i < count; i++)
804 {
805 std::string port_name = rtmout->getPortName( (unsigned int) i );
806 if( port_name == name )
807 {
808 device_num = i;
809 break;
810 }
811 }
812
813 if( device_num == -1 )
814 {
815 // search by substring
816 for(t_CKINT i = 0; i < count; i++)
817 {
818 std::string port_name = rtmout->getPortName( (unsigned int) i );
819 if( port_name.find( name ) != std::string::npos )
820 {
821 device_num = i;
822 break;
823 }
824 }
825 }
826 }
827 catch( RtMidiError & err )
828 {
829 if( !mout->m_suppress_output )
830 {
831 // print it
832 EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() );
833 err.getMessage();
834 // const char * e = err.getMessage().c_str();
835 // EM_error2( 0, "...(%s)", err.getMessage().c_str() );
836 }
837 return FALSE;
838 }
839
840 if(device_num == -1)
841 {
842 EM_error2( 0, "MidiOut: error locating MIDI port named %s", name.c_str() );
843 return FALSE;
844 }
845
846 t_CKBOOL result = open( mout, device_num );
847
848 return result;
849 }
850
851
852 //-----------------------------------------------------------------------------
853 // name: class MidiRW
854 // desc: reads and writes midi messages from file
855 //-----------------------------------------------------------------------------
856
857 static std::map<MidiRW *, MidiRW *> g_rw;
858
859 t_CKBOOL out_detach( );
860 t_CKBOOL midirw_detach( )
861 {
862 std::map<MidiRW *, MidiRW *>::iterator iter;
863 std::vector<MidiRW *> list;
864
865 // log
866 EM_log( CK_LOG_INFO, "detaching MIDI devices..." );
867
868 for( iter = g_rw.begin(); iter != g_rw.end(); iter++ )
869 list.push_back( (*iter).second );
870 for( t_CKUINT i = 0; i < list.size(); i++ )
871 list[i]->close();
872
873 // TODO: release the MidiRW
874 g_rw.clear();
875
876 return out_detach( );
877 }
878
879 MidiRW::MidiRW() { file = NULL; }
880
881 MidiRW::~MidiRW() { this->close(); }
882
883 t_CKBOOL MidiRW::open( const char * filename )
884 {
885 this->close();
886
887 file = fopen( filename, "rb+" );
888 if( file == NULL )
889 {
890 file = fopen( filename, "wb+" );
891 }
892
893 // add to hash
894 g_rw[this] = this;
895
896 return ( file != NULL );
897 }
898
899 t_CKBOOL MidiRW::close()
900 {
901 if( !file ) return FALSE;
902
903 t_CKBOOL value = fclose( file ) == 0;
904
905 // remove from hash
906 std::map<MidiRW *, MidiRW *>::iterator iter;
907 iter = g_rw.find( this );
908 g_rw.erase( iter );
909
910 file = NULL;
911
912 return value;
913 }
914
915 t_CKBOOL MidiRW::read( MidiMsg * msg, t_CKTIME * time )
916 {
917 if( !file )
918 return FALSE;
919
920 // is it open? i don't know...
921
922 t_CKBOOL m, t;
923
924 // wouldn't it be cool if this worked?
925 m = fread( msg, sizeof(MidiMsg), 1, file );
926 t = fread( time, sizeof(t_CKTIME), 1, file );
927
928 return m && t;
929 }
930
931
932 t_CKBOOL MidiRW::write( MidiMsg * msg, t_CKTIME * time )
933 {
934 if( !file )
935 return FALSE;
936
937 t_CKBOOL m, t;
938
939 m = fwrite( msg, sizeof(MidiMsg), 1, file );
940 t = fwrite( time, sizeof(t_CKTIME), 1, file );
941 fflush( file );
942
943 return m && t;
944 }
945
946
947
948
949 //-----------------------------------------------------------------------------
950 // name: class MidiMsgOut
951 // desc: writes midi messages from file
952 //-----------------------------------------------------------------------------
953
954 static std::map<MidiMsgOut *, MidiMsgOut *> g_out;
955
956 t_CKBOOL out_detach( )
957 {
958 std::map<MidiMsgOut *, MidiMsgOut *>::iterator iter;
959 std::vector<MidiMsgOut *> list;
960
961 for( iter = g_out.begin(); iter != g_out.end(); iter++ )
962 list.push_back( (*iter).second );
963 for( t_CKUINT i = 0; i < list.size(); i++ )
964 list[i]->close();
965
966 return TRUE;
967 }
968
969 MidiMsgOut::MidiMsgOut() { file = NULL; }
970
971 MidiMsgOut::~MidiMsgOut() { this->close(); }
972
973 t_CKBOOL MidiMsgOut::open( const char * filename )
974 {
975 this->close();
976
977 file = fopen( filename, "wb" );
978
979 // add to hash
980 g_out[this] = this;
981
982 return ( file != NULL );
983 }
984
985 t_CKBOOL MidiMsgOut::close()
986 {
987 if( !file ) return FALSE;
988
989 t_CKBOOL value = fclose( file ) == 0;
990
991 // remove from hash
992 std::map<MidiMsgOut *, MidiMsgOut *>::iterator iter;
993 iter = g_out.find( this );
994 g_out.erase( iter );
995
996 file = NULL;
997
998 return value;
999 }
1000
1001 t_CKBOOL MidiMsgOut::write( MidiMsg * msg, t_CKTIME * time )
1002 {
1003 if( !file )
1004 return FALSE;
1005
1006 t_CKBOOL m, t;
1007
1008 m = fwrite( msg, sizeof(MidiMsg), 1, file );
1009 t = fwrite( time, sizeof(t_CKTIME), 1, file );
1010 fflush( file );
1011
1012 return m && t;
1013 }
1014
1015
1016
1017
1018 //-----------------------------------------------------------------------------
1019 // name: class MidiMsgIn
1020 // desc: reads midi messages from file
1021 //-----------------------------------------------------------------------------
1022
1023 MidiMsgIn::MidiMsgIn() { file = NULL; }
1024
1025 MidiMsgIn::~MidiMsgIn() { this->close(); }
1026
1027 t_CKBOOL MidiMsgIn::open( const char * filename )
1028 {
1029 this->close();
1030
1031 file = fopen( filename, "rb" );
1032
1033 return ( file != NULL );
1034 }
1035
1036 t_CKBOOL MidiMsgIn::close()
1037 {
1038 if( !file ) return FALSE;
1039
1040 t_CKBOOL value = fclose( file ) == 0;
1041
1042 file = NULL;
1043
1044 return value;
1045 }
1046
1047 t_CKBOOL MidiMsgIn::read( MidiMsg * msg, t_CKTIME * time )
1048 {
1049 if( !file )
1050 return FALSE;
1051
1052 // is it open? i don't know...
1053
1054 t_CKBOOL m, t;
1055
1056 // wouldn't it be cool if this worked?
1057 m = fread( msg, sizeof(MidiMsg), 1, file );
1058 t = fread( time, sizeof(t_CKTIME), 1, file );
1059
1060 return m && t;
1061 }
1062
1063 #else // __DISABLE_MIDI__
1064
1065 MidiOut::MidiOut()
1066 {
1067
1068 }
1069
1070 MidiOut::~MidiOut()
1071 {
1072 }
1073
1074 t_CKBOOL MidiOut::open( t_CKUINT device_num )
1075 {
1076 return TRUE;
1077 }
1078
1079 MidiIn::MidiIn()
1080 {
1081
1082 }
1083
1084 MidiIn::~MidiIn()
1085 {
1086
1087 }
1088
1089 t_CKBOOL MidiIn::open( t_CKUINT device_num )
1090 {
1091 return FALSE;
1092 }
1093
1094 #endif // __DISABLE_MIDI__
1095
1096 //-----------------------------------------------------------------------------
1097 // name: adapted from y-score-reader.cpp
1098 // desc: reads song scores
1099 //
1100 // authors: Ge Wang ([email protected])
1101 // date: Winter 2010
1102 // version: 1.0
1103 //-----------------------------------------------------------------------------
1104 #include <iostream>
1105 #include "midiio_rtmidi.h"
1106 #include "ugen_stk.h"
1107
1108 using namespace stk;
1109 using namespace std;
1110
1111
1112
1113
1114 #pragma mark - MIDI helpers
1115
1116
1117 //-----------------------------------------------------------------------------
1118 // name: isNoteOff()
1119 // desc: ...
1120 //-----------------------------------------------------------------------------
1121 static bool isNoteOff( std::vector<unsigned char> & shuttle )
1122 {
1123 if( shuttle.size() >= 1 && shuttle[0] >> 4 == 0x8 ) // note off event
1124 return true;
1125
1126 if( shuttle.size() >= 3 && shuttle[0] >> 4 == 0x9 && shuttle[2] == 0 ) // note on event with velocity 0
1127 return true;
1128
1129 return false;
1130 }
1131
1132
1133
1134
1135 //-----------------------------------------------------------------------------
1136 // name: isControl()
1137 // desc: ...
1138 //-----------------------------------------------------------------------------
1139 static bool isControl( std::vector<unsigned char> & shuttle )
1140 {
1141 if( shuttle.size() >= 1 && ( shuttle[0] & 0xf0 ) == 0xb0 )
1142 return true;
1143
1144 return false;
1145 }
1146
1147
1148
1149
1150 //-----------------------------------------------------------------------------
1151 // name: isMeta()
1152 // desc: ...
1153 //-----------------------------------------------------------------------------
1154 static bool isMeta( std::vector<unsigned char> & shuttle )
1155 {
1156 if( shuttle.size() >= 1 && shuttle[0] == 0xff )
1157 return true;
1158
1159 return false;
1160 }
1161
1162
1163
1164
1165 //-----------------------------------------------------------------------------
1166 // name: isProgram()
1167 // desc: ...
1168 //-----------------------------------------------------------------------------
1169 static bool isProgram( std::vector<unsigned char> & shuttle )
1170 {
1171 if( shuttle.size() >= 1 && ( shuttle[0] >= 0xC0 && shuttle[0] <= 0xCF ) )
1172 return true;
1173
1174 return false;
1175 }
1176
1177
1178
1179
1180 //-----------------------------------------------------------------------------
1181 // name: MidiScoreReader()
1182 // desc: constructor
1183 //-----------------------------------------------------------------------------
1184 MidiScoreReader::MidiScoreReader()
1185 : m_midiFile(NULL), m_velocity_scale(0.0f), m_numNonZeroTracks(0)
1186 {
1187 }
1188
1189
1190
1191
1192 //-----------------------------------------------------------------------------
1193 // name: ~MidiScoreReader()
1194 // desc: destructor
1195 //-----------------------------------------------------------------------------
1196 MidiScoreReader::~MidiScoreReader()
1197 {
1198 // clean up
1199 cleanup();
1200 }
1201
1202
1203
1204
1205 //-----------------------------------------------------------------------------
1206 // name: cleanup()
1207 // desc: reclaim
1208 //-----------------------------------------------------------------------------
1209 void MidiScoreReader::cleanup()
1210 {
1211 // clean up
1212 if( m_midiFile )
1213 {
1214 // pointer to event
1215 MidiNoteEvent * e = NULL;
1216 MidiNoteEvent * next = NULL;
1217
1218 // clean up the tracks
1219 for( t_CKINT i = 0; i < m_midiFile->getNumberOfTracks(); i++ )
1220 {
1221 // for each track
1222 for( t_CKINT j = 0; j < m_events[i].size(); j++ )
1223 {
1224 // get track
1225 e = m_events[i][j];
1226 // delete simultaneous events
1227 while( e )
1228 {
1229 // get next
1230 next = e->simultaneous;
1231 // delete current
1232 delete e;
1233 // advance
1234 e = next;
1235 }
1236 }
1237
1238 // clear the vectors
1239 m_events[i].clear();
1240 }
1241
1242 // delete midiFile
1243 delete m_midiFile;
1244 m_midiFile = NULL;
1245
1246 // clean the vector
1247 m_events.clear();
1248 m_countMaps.clear();
1249 m_nonZeroTrackIndices.clear();
1250
1251 // clear the queue
1252 while( m_queue.size() > 0 )
1253 m_queue.pop_front();
1254 }
1255 }
1256
1257
1258
1259
1260 //-----------------------------------------------------------------------------
1261 // name: load()
1262 // desc: load a MIDI file
1263 //-----------------------------------------------------------------------------
1264 bool MidiScoreReader::load( const char * path, float velScale )
1265 {
1266 // sanity check
1267 if( m_midiFile ) cleanup();
1268
1269 // open midi file
1270 try
1271 {
1272 m_midiFile = new MidiFileIn( path );
1273 // print a little information about the file.
1274 CK_STDCERR << "[chuck]: MIDI file: " << path << CK_STDENDL;
1275 CK_STDCERR << "[chuck]: | format = " << m_midiFile->getFileFormat() << CK_STDENDL;
1276 CK_STDCERR << "[chuck]: | tracks = " << m_midiFile->getNumberOfTracks() << CK_STDENDL;
1277 CK_STDCERR << "[chuck]: | seconds / ticks = " << m_midiFile->getTickSeconds() << CK_STDENDL;
1278 CK_STDCERR << "[chuck]: | BPM = " << m_midiFile->getBPM() << CK_STDENDL;
1279 }
1280 catch( StkError )
1281 {
1282 // you might want to do something more useful here.
1283 // CK_STDCERR << "[chuck]: error loading MIDI file: " << path << CK_STDENDL;
1284
1285 // 1.4.1.1 (ge) added
1286 // CK_STDCERR << "[chuck]: error text: '" << e.getMessage() << "'" << CK_STDENDL;
1287
1288 // delete
1289 cleanup();
1290
1291 return false;
1292 }
1293
1294 // set velocity scale
1295 m_velocity_scale = velScale;
1296 // reset
1297 m_numNonZeroTracks = 0;
1298 // clear
1299 m_nonZeroTrackIndices.clear();
1300
1301 // allocate element for vector
1302 m_events.resize( m_midiFile->getNumberOfTracks() );
1303 m_lyricEvents.resize( m_midiFile->getNumberOfTracks() );
1304 m_indices.resize( m_midiFile->getNumberOfTracks() );
1305 m_countMaps.resize( m_midiFile->getNumberOfTracks() );
1306 // iterate and set
1307 for( t_CKINT i = 0; i < m_midiFile->getNumberOfTracks(); i++ )
1308 {
1309 // load up the arrays
1310 loadTrack( i, m_events[i], m_lyricEvents[i] );
1311 // log
1312 string name = getTrackName( i );
1313 CK_FPRINTF_STDERR( "[chuck](MIDI file): track-%ld (%s): events: %lu low: %lu high: %lu\n",
1314 i, name.c_str(), m_events[i].size(), getLowestNote( i, NULL ), getHighestNote( i, NULL ) );
1315 // set indice
1316 m_indices[i] = 0;
1317 // add search pointer
1318 m_searchIndices.push_back( 0 );
1319 // count non zero
1320 if( m_events[i].size() )
1321 {
1322 // increment
1323 m_numNonZeroTracks++;
1324 // append
1325 m_nonZeroTrackIndices.push_back( i );
1326 }
1327 }
1328
1329 return true;
1330 }
1331
1332
1333
1334
1335 //-----------------------------------------------------------------------------
1336 // name: getNumTracks()
1337 // desc: get the number of tracks
1338 //-----------------------------------------------------------------------------
1339 t_CKINT MidiScoreReader::getNumTracks() const
1340 {
1341 if( m_midiFile == NULL ) return 0;
1342 return m_midiFile->getNumberOfTracks();
1343 }
1344
1345
1346
1347
1348 //-----------------------------------------------------------------------------
1349 // name: getNumTracksNonZero()
1350 // desc: get number of tracks with more than 0 zero
1351 //-----------------------------------------------------------------------------
1352 t_CKINT MidiScoreReader::getNumTracksNonZero() const
1353 {
1354 if( m_midiFile == NULL ) return 0;
1355 return m_numNonZeroTracks;
1356 }
1357
1358
1359
1360
1361 //-----------------------------------------------------------------------------
1362 // name: getTracksNonZero()
1363 // desc: get a vector of tracks indices that have more than 0 events
1364 //-----------------------------------------------------------------------------
1365 const std::vector<t_CKINT> & MidiScoreReader::getTracksNonZero() const
1366 {
1367 return m_nonZeroTrackIndices;
1368 }
1369
1370
1371
1372
1373 //-----------------------------------------------------------------------------
1374 // name: getBPM()
1375 // desc: get BPM
1376 //-----------------------------------------------------------------------------
1377 double MidiScoreReader::getBPM() const
1378 {
1379 if( m_midiFile == NULL ) return 0;
1380 return m_midiFile->getBPM();
1381 }
1382
1383
1384
1385
1386 //-----------------------------------------------------------------------------
1387 // name: getLowestNote()
1388 // desc: get lowest note for a track
1389 //-----------------------------------------------------------------------------
1390 t_CKINT MidiScoreReader::getLowestNote( t_CKINT track, const MidiNoteEvent * start )
1391 {
1392 int lowestNote = 128;
1393 int startingPoint = 0;
1394
1395 // get the starting point
1396 if( start != NULL )
1397 {
1398 for( int i = 0; i < m_events[track].size(); i++ )
1399 {
1400 if( m_events[track].at(i) == start )
1401 {
1402 startingPoint = i + 1;
1403 break;
1404 }
1405 }
1406 }
1407
1408 for( int i = startingPoint; i < m_events[track].size(); i++ )
1409 {
1410 if( m_events[track].at(i)->data2 < lowestNote )
1411 lowestNote = m_events[track].at(i)->data2;
1412
1413 if( m_events[track].at(i)->phrasemark ) break;
1414 }
1415
1416 return lowestNote < 128 ? lowestNote : 0;
1417 }
1418
1419
1420
1421
1422 //-----------------------------------------------------------------------------
1423 // name: getHighestNote()
1424 // desc: get highest note for a track
1425 //-----------------------------------------------------------------------------
1426 t_CKINT MidiScoreReader::getHighestNote( t_CKINT track, const MidiNoteEvent *start )
1427 {
1428 t_CKINT highestNote = 0;
1429 t_CKINT startingPoint = 0;
1430
1431 // get the starting point
1432 if( start != NULL )
1433 {
1434 for( t_CKINT i = 0; i < m_events[track].size(); i++ )
1435 {
1436 if( m_events[track].at(i) == start )
1437 {
1438 startingPoint = i+1;
1439 break;
1440 }
1441 }
1442 }
1443
1444 for( t_CKINT i = startingPoint; i < m_events[track].size(); i++ )
1445 {
1446 if( m_events[track].at(i)->data2 > highestNote )
1447 highestNote = m_events[track].at(i)->data2;
1448
1449 if( m_events[track].at(i)->phrasemark ) break;
1450 }
1451
1452 return highestNote;
1453 }
1454
1455
1456
1457
1458 //-----------------------------------------------------------------------------
1459 // name: getTopEvent()
1460 // desc: return current (top-level) note event on track
1461 //-----------------------------------------------------------------------------
1462 const MidiNoteEvent * MidiScoreReader::getTopEvent( t_CKINT track, t_CKINT offset )
1463 {
1464 // sanity check
1465 if( !m_midiFile || track >= m_events.size() )
1466 {
1467 CK_STDCERR << "[chuck](MIDI file): cannot access top event data!" << CK_STDENDL;
1468 return NULL;
1469 }
1470
1471 // the new index
1472 t_CKINT index = m_indices[track] + offset;
1473 // check it
1474 if( index < 0 || index >= m_events[track].size() ) return NULL;
1475 // return it
1476 return m_events[track][index];
1477 }
1478
1479
1480
1481
1482 //-----------------------------------------------------------------------------
1483 // name: scanEvent()
1484 // desc: get the next event (respects simultaneous) + move to next
1485 //-----------------------------------------------------------------------------
1486 const MidiNoteEvent * MidiScoreReader::scanEvent( t_CKINT track, bool & isNewSet )
1487 {
1488 const MidiNoteEvent * e = NULL;
1489 isNewSet = false;
1490 // see if there is last event
1491 if( ( e = front() ) )
1492 {
1493 // pop it
1494 dequeue();
1495 // get simulaneous
1496 e = e->simultaneous;
1497 }
1498 // see if still NULL
1499 if( !e )
1500 {
1501 // get current
1502 e = getTopEvent( track );
1503 // set flag
1504 isNewSet = true;
1505 }
1506 // set the next event
1507 enqueue( e );
1508
1509 return e;
1510 }
1511
1512
1513
1514
1515 //-----------------------------------------------------------------------------
1516 // name: seek()
1517 // desc: advance to an event on a track
1518 //-----------------------------------------------------------------------------
1519 bool MidiScoreReader::seek( t_CKINT track, t_CKINT numToAdvance )
1520 {
1521 // sanity check
1522 if( !m_midiFile || track >= m_events.size() )
1523 {
1524 // CK_STDCERR << "[chuck](MIDI file): cannot seek current data!" << CK_STDENDL;
1525 return false;
1526 }
1527
1528 // the next index
1529 t_CKINT index = m_indices[track] + numToAdvance;
1530 // check it
1531 if( index < 0 ) index = 0;
1532 else if( index >= m_events[track].size() ) index = m_events[track].size();
1533 // update
1534 m_indices[track] = index;
1535
1536 // return
1537 if( index >= m_events[track].size() ) return false;
1538 return true;
1539 }
1540
1541
1542
1543
1544 //-----------------------------------------------------------------------------
1545 // name: seekToNoteOn()
1546 // desc: advance to an event on a track
1547 //-----------------------------------------------------------------------------
1548 bool MidiScoreReader::seekToNoteOn( t_CKINT track )
1549 {
1550 // sanity check
1551 if( !m_midiFile || track >= m_events.size() )
1552 {
1553 // CK_STDCERR << "[chuck](MIDI file): cannot seek current data!" << CK_STDENDL;
1554 return false;
1555 }
1556
1557 // event
1558 const MidiNoteEvent * e = NULL;
1559 t_CKINT index = 0;
1560
1561 // go
1562 do {
1563 // the next index
1564 index = m_indices[track] + 1;
1565 // check it
1566 if( index < 0 ) index = 0;
1567 else if( index >= m_events[track].size() ) index = m_events[track].size();
1568 // update
1569 m_indices[track] = index;
1570 // break
1571 if( index >= m_events[track].size() ) break;
1572 // set the e
1573 e = m_events[track][index];
1574 } while( (e->data1 >> 4 != 0x9) || (e->data3 == 0) );
1575
1576 // return
1577 if( index >= m_events[track].size() ) return false;
1578 return true;
1579 }
1580
1581
1582
1583
1584 //-----------------------------------------------------------------------------
1585 // name: rewind()
1586 // desc: go to begining
1587 //-----------------------------------------------------------------------------
1588 void MidiScoreReader::rewind()
1589 {
1590 // sanity check
1591 if( !m_midiFile ) return;
1592
1593 // set all indices to 0
1594 for( t_CKINT i = 0; i < m_midiFile->getNumberOfTracks(); i++ )
1595 {
1596 // clear
1597 m_indices[i] = 0;
1598 m_searchIndices[i] = 0;
1599 }
1600 }
1601
1602
1603
1604
1605 //-----------------------------------------------------------------------------
1606 // name: getEvents()
1607 // desc: get notes in a time window
1608 //-----------------------------------------------------------------------------
1609 void MidiScoreReader::getEvents( t_CKINT track, double startTime, double endTime,
1610 vector<const MidiNoteEvent *> & result,
1611 bool includeSimultaneous )
1612 {
1613 // clear the result
1614 result.clear();
1615
1616 // sanity check
1617 if( !m_midiFile || track >= m_events.size() )
1618 {
1619 // don't alway print this
1620 // CK_STDCERR << "[chuck](MIDI file): cannot read track: " << track << "!" << CK_STDENDL;
1621 return;
1622 }
1623
1624 // get the event
1625 const MidiNoteEvent * searchPtr = getTopEvent( track, m_searchIndices[track] );
1626
1627 // advance the search pointer
1628 while( searchPtr && searchPtr->endTime < startTime )
1629 {
1630 // TODO: this doesn't handle the case where simultaneous note ends later than parent
1631
1632 // increment index
1633 m_searchIndices[track]++;
1634 // get event
1635 searchPtr = getTopEvent( track, m_searchIndices[track] );
1636 }
1637
1638 // check
1639 if( searchPtr == NULL )
1640 return;
1641
1642 // the index
1643 t_CKUINT searchIndex = m_searchIndices[track];
1644
1645 // scan for events within the window
1646 while( searchPtr )
1647 {
1648 // within window - this is some sexy logic, thanks Jieun and Tom
1649 // ge: added the <= for endTime
1650 if( searchPtr->endTime > startTime && searchPtr->startTime <= endTime )
1651 {
1652 // add to vector
1653 result.push_back( searchPtr );
1654 }
1655
1656 // check
1657 if( includeSimultaneous && searchPtr->simultaneous )
1658 {
1659 // move to simultaneous - could have different end time
1660 searchPtr = searchPtr->simultaneous;
1661 }
1662 else // to the next parent (top level event)
1663 {
1664 // advance search index
1665 searchIndex++;
1666 // get event
1667 searchPtr = getTopEvent( track, searchIndex );
1668 }
1669 }
1670 }
1671
1672
1673
1674
1675 //-----------------------------------------------------------------------------
1676 // name: isDone()
1677 // desc: is done
1678 //-----------------------------------------------------------------------------
1679 bool MidiScoreReader::isDone( t_CKINT track, double currTime )
1680 {
1681 // sanity check
1682 if( track < 0 || track >= m_events.size() )
1683 return true;
1684
1685 // number of events on a track
1686 t_CKINT numEvents = m_events[track].size();
1687 // check time against last element
1688 if( numEvents <= 0 )
1689 return true;
1690
1691 return m_events[track][numEvents-1]->endTime < currTime;
1692 }
1693
1694
1695
1696
1697 //-----------------------------------------------------------------------------
1698 // name: applyControl()
1699 // desc: applies control data to an existing event
1700 //-----------------------------------------------------------------------------
1701 bool MidiScoreReader::applyControl( t_CKINT track, t_CKINT data2, t_CKINT data3, MidiNoteEvent * e )
1702 {
1703 // sanity check
1704 if( !e ) return false;
1705 if( data2 < 0 || data2 > 127 ) return false;
1706 if( data3 < 0 || data3 > 127 ) return false;
1707
1708 // flag
1709 bool found = false;
1710
1711 if( data2 == 0x52 )
1712 {
1713 // gliss
1714 e->shouldBend = true;
1715 found = true;
1716 // increment
1717 incrementCount( track, "bend" );
1718 e->bendAmount = (int)data3;
1719 }
1720
1721 if( data2 == 0x53 )
1722 {
1723 // gliss
1724 e->phrasemark = true;
1725 found = true;
1726 // increment
1727 incrementCount( track, "phrasemark" );
1728 }
1729
1730 return found;
1731 }
1732
1733
1734
1735
1736 //-----------------------------------------------------------------------------
1737 // name: loadTrack()
1738 // desc: load a track from file
1739 //-----------------------------------------------------------------------------
1740 bool MidiScoreReader::loadTrack( t_CKINT track, std::vector<MidiNoteEvent *> & data, std::vector<MidiLyricEvent *> & lyricData )
1741 {
1742 // sanity check
1743 if( !m_midiFile || track >= m_events.size() )
1744 {
1745 // error
1746 CK_STDCERR << "[chuck](MIDI file): cannot read track: " << track << "!" << CK_STDENDL;
1747 return false;
1748 }
1749
1750 // clear out the vectors
1751 data.clear();
1752 // clear out active MIDI notes
1753 m_activeNotes.clear();
1754 // a vector to hold the return information
1755 std::vector<unsigned char> shuttle;
1756 // piano event pointers
1757 MidiNoteEvent * e = NULL;
1758 MidiLyricEvent * le = NULL;
1759 // last event
1760 MidiNoteEvent * prev_e = NULL;
1761 MidiLyricEvent * prev_le = NULL;
1762 // parent event
1763 MidiNoteEvent * parent = NULL;
1764
1765 int currentProgram = 27; // program defaults to electric gutiar (27) in case it is not set in the score
1766
1767 // load next on the track
1768 try {
1769 // seconds accum
1770 double secondsAccum = 0;
1771 // loop
1772 while( true )
1773 {
1774 // get the next MIDI event
1775 t_CKUINT ticks = m_midiFile->getNextEvent( &shuttle, (unsigned int)track );
1776
1777 // accumulate time
1778 secondsAccum += ticks * m_midiFile->getTickSeconds();
1779
1780 // MIDI message spec: http://www.srm.com/qtma/davidsmidispec.html
1781
1782 // check size (done?)
1783 if( shuttle.size() == 0 ) break;
1784
1785 if( isNoteOff( shuttle ) )
1786 {
1787 // do note off
1788 handleNoteOff( shuttle[1], secondsAccum );
1789 continue;
1790 }
1791 else if( isControl( shuttle ) )
1792 {
1793 // apply control to previous
1794 applyControl( track, shuttle[1], shuttle[2], prev_e );
1795 continue;
1796 }
1797 else if( isMeta( shuttle ) )
1798 {
1799 // format: http://www.recordingblogs.com/sa/Wiki/tabid/88/Default.aspx?topic=MIDI+meta+messages
1800 // shuttle[1]: message type
1801 // shuttle[2]: number of bytes in custom data part
1802 // shuttle[3]: start of custom data part
1803
1804 switch( shuttle[1] )
1805 {
1806 case 1: // text
1807 {
1808 string text = string( (char *)&shuttle[3] /* name */, shuttle[2] /* length */ );
1809 break;
1810 }
1811 case 3: // track name
1812 {
1813 string name = string( (char *)&shuttle[3] /* name */, shuttle[2] /* length */ );
1814 setTrackName( track, name );
1815 break;
1816 }
1817 case 5: // lyric
1818 {
1819 string lyric = string( (char *)&shuttle[3] /* name */, shuttle[2] /* length */ );
1820
1821 le = new MidiLyricEvent;
1822 le->lyric = lyric;
1823 le->time = le->endTime = secondsAccum;
1824
1825 if( prev_le )
1826 {
1827 prev_le->endTime = secondsAccum;
1828 }
1829
1830 lyricData.push_back( le );
1831
1832 prev_le = le;
1833
1834 break;
1835 }
1836 }
1837 continue;
1838 }
1839
1840 // store a program change in an event
1841 else if( isProgram( shuttle ) )
1842 {
1843 if( shuttle[1] >= 0 )
1844 currentProgram = shuttle[1];
1845 continue;
1846 }
1847
1848 // continue if it's anything but a note on
1849 if( shuttle[0] >> 4 != 0x9 || shuttle[2] == 0 ) continue;
1850
1851 // instantiate
1852 e = new MidiNoteEvent();
1853 // fill
1854 e->data1 = (unsigned short)shuttle[0];
1855 e->data2 = (unsigned short)shuttle[1];
1856 e->data3 = (unsigned short)shuttle[2];
1857 // check
1858 if( (m_velocity_scale > 0) && e->data3 )
1859 {
1860 // scale
1861 e->data3 = e->data3 + m_velocity_scale * (127 - e->data3);
1862 // clamp
1863 if( e->data3 > 127 ) e->data3 = 127;
1864 }
1865
1866 // fill the until next for prev
1867 if( prev_e ) prev_e->untilNext = e->time - prev_e->startTime;
1868 // advance time
1869 e->startTime = e->time = secondsAccum;
1870 // simultaneous
1871 e->simultaneous = NULL;
1872 // store current program
1873 e->programChange = currentProgram;
1874
1875 // simultaneous or in series?
1876 if( prev_e != NULL && e->time == prev_e->time )
1877 {
1878 // sim
1879 prev_e->simultaneous = e;
1880 // point to parent
1881 e->parent = parent;
1882 }
1883 else
1884 {
1885 // increment
1886 incrementCount( track, "note" );
1887 // series
1888 data.push_back( e );
1889 // save as parent
1890 parent = e->parent = e;
1891 }
1892
1893 // add to lookup
1894 handleNoteOn( e, e->data2 );
1895
1896 // update
1897 prev_e = e;
1898 }
1899 }
1900 catch( StkError & )
1901 {
1902 // you might want to do something more useful here.
1903 CK_STDCERR << "[chuck](MIDI file): uh oh, error loading track!" << CK_STDENDL;
1904
1905 // clear out active MIDI notes
1906 m_activeNotes.clear();
1907
1908 return false;
1909 }
1910
1911 // clear out active MIDI notes
1912 m_activeNotes.clear();
1913
1914 return true;
1915 }
1916
1917
1918
1919
1920 //-----------------------------------------------------------------------------
1921 // name: enqueue()
1922 // desc: enqueue a event to remember
1923 //-----------------------------------------------------------------------------
1924 void MidiScoreReader::enqueue( const MidiNoteEvent * event )
1925 {
1926 // TODO: synchronization?
1927 // while( event != NULL )
1928 // {
1929 m_queue.push_back( event );
1930 // event = event->simultaneous;
1931 // }
1932 }
1933
1934
1935
1936
1937 //-----------------------------------------------------------------------------
1938 // name: front()
1939 // desc: get the front event
1940 //-----------------------------------------------------------------------------
1941 const MidiNoteEvent * MidiScoreReader::front() const
1942 {
1943 if( m_queue.size() == 0 ) return NULL;
1944 else return m_queue.front();
1945 }
1946
1947
1948
1949
1950 //-----------------------------------------------------------------------------
1951 // name: dequeue()
1952 // desc: dequeue the event
1953 //-----------------------------------------------------------------------------
1954 void MidiScoreReader::dequeue()
1955 {
1956 if( m_queue.size() > 0 )
1957 m_queue.pop_front();
1958 }
1959
1960
1961
1962
1963 //-----------------------------------------------------------------------------
1964 // name: enqueue_front()
1965 // desc: enqueue to front
1966 //-----------------------------------------------------------------------------
1967 void MidiScoreReader::enqueue_front( const MidiNoteEvent * e )
1968 {
1969 m_queue.push_front( e );
1970 }
1971
1972
1973
1974
1975 //-----------------------------------------------------------------------------
1976 // name: getNumEvents()
1977 // desc: get number of events on a track
1978 //-----------------------------------------------------------------------------
1979 t_CKINT MidiScoreReader::getNumEvents( t_CKINT track ) const
1980 {
1981 // sanity check
1982 if( track < 0 || track >= m_events.size() )
1983 return 0;
1984
1985 // return the number of elements
1986 return m_events[track].size();
1987 }
1988
1989
1990
1991
1992 //-----------------------------------------------------------------------------
1993 // name: getNoteEvents()
1994 // desc: get an entire track's note events
1995 //-----------------------------------------------------------------------------
1996 static vector<MidiNoteEvent *> s_nullNoteVector;
1997 const vector<MidiNoteEvent *> & MidiScoreReader::getNoteEvents( t_CKINT track )
1998 {
1999 // sanity check
2000 if( track < 0 || track >= m_events.size() )
2001 return s_nullNoteVector;
2002
2003 return m_events[track];
2004 }
2005
2006
2007
2008
2009 //-----------------------------------------------------------------------------
2010 // name: getLyricEvents()
2011 // desc: get an entire track's lyric events
2012 //-----------------------------------------------------------------------------
2013 static vector<MidiLyricEvent *> s_nullLyricVector;
2014 const vector<MidiLyricEvent *> & MidiScoreReader::getLyricEvents( t_CKINT track )
2015 {
2016 // sanity check
2017 if( track < 0 || track >= m_lyricEvents.size() )
2018 return s_nullLyricVector;
2019
2020 return m_lyricEvents[track];
2021 }
2022
2023
2024
2025
2026 //-----------------------------------------------------------------------------
2027 // name: getCount()
2028 // desc: return a count associated with key
2029 //-----------------------------------------------------------------------------
2030 t_CKINT MidiScoreReader::getCount( t_CKINT track, const std::string & key )
2031 {
2032 // sanity check
2033 if( track < 0 || track >= m_events.size() ) return 0;
2034 // find
2035 std::map< std::string, t_CKINT >::iterator iter = m_countMaps[track].find( key );
2036 // not found
2037 if( iter == m_countMaps[track].end() ) return 0;
2038 // return value
2039 return iter->second;
2040 }
2041
2042
2043
2044
2045 //-----------------------------------------------------------------------------
2046 // name: incrementCount()
2047 // desc: increment a count associated with key
2048 //-----------------------------------------------------------------------------
2049 void MidiScoreReader::incrementCount( t_CKINT track, const std::string & key )
2050 {
2051 // sanity check
2052 if( track < 0 || track >= m_events.size() ) return;
2053
2054 // find
2055 std::map< std::string, t_CKINT >::iterator iter = m_countMaps[track].find( key );
2056
2057 if( iter == m_countMaps[track].end() )
2058 {
2059 // if not found, add
2060 m_countMaps[track][key] = 1;
2061 }
2062 else
2063 {
2064 // if found, increment
2065 iter->second++;
2066 }
2067 }
2068
2069
2070
2071
2072 //-----------------------------------------------------------------------------
2073 // name: handleNoteOn()
2074 // desc: insert a note on into table
2075 //-----------------------------------------------------------------------------
2076 void MidiScoreReader::handleNoteOn( MidiNoteEvent * e, t_CKINT note )
2077 {
2078 // sanity check
2079 if( !e )
2080 return;
2081
2082 // check to see if occupied
2083 if( m_activeNotes[note] != NULL )
2084 {
2085 // treat as a note-off for the same note
2086 handleNoteOff( note, e->time );
2087 }
2088
2089 // insert
2090 m_activeNotes[note] = e;
2091 }
2092
2093
2094
2095
2096 //-----------------------------------------------------------------------------
2097 // name: handleNoteOff()
2098 // desc: insert a note off into table
2099 //-----------------------------------------------------------------------------
2100 void MidiScoreReader::handleNoteOff( t_CKINT note, double time )
2101 {
2102 // get the piano event
2103 MidiNoteEvent * e = m_activeNotes[note];
2104 // check
2105 if( !e )
2106 return;
2107
2108 // set end time
2109 e->endTime = time;
2110
2111 // set
2112 m_activeNotes[note] = NULL;
2113 }
2114
2115
2116
2117
2118 //-----------------------------------------------------------------------------
2119 // name: setTrackName()
2120 // desc: sets track name
2121 //-----------------------------------------------------------------------------
2122 void MidiScoreReader::setTrackName( t_CKINT track, const std::string & name )
2123 {
2124 // x-map it!
2125 m_trackToName[track] = name;
2126 m_nameToTrack[name] = track;
2127 }
2128
2129
2130
2131
2132 //-----------------------------------------------------------------------------
2133 // name: getTrackName()
2134 // desc: gets track name ("" if not present)
2135 //-----------------------------------------------------------------------------
2136 string MidiScoreReader::getTrackName( t_CKINT track )
2137 {
2138 map<t_CKINT, string>::iterator itr = m_trackToName.find( track );
2139
2140 if( itr == m_trackToName.end() )
2141 return "";
2142
2143 return itr->second;
2144 }
2145
2146
2147
2148
2149 //-----------------------------------------------------------------------------
2150 // name: getTrackForName()
2151 // desc: gets the track with the given name (-1 if not present)
2152 //-----------------------------------------------------------------------------
2153 t_CKINT MidiScoreReader::getTrackForName( const std::string & name )
2154 {
2155 // look up the track index by name
2156 map<string, t_CKINT>::iterator itr = m_nameToTrack.find( name );
2157
2158 // didn't find
2159 if( itr == m_nameToTrack.end() )
2160 return -1;
2161
2162 // make sure the track actually exists
2163 if( itr->second >= m_events.size() )
2164 return -1;
2165
2166 return itr->second;
2167 }