summaryrefslogtreecommitdiff
path: root/libs/appleutility/CoreAudio/AudioUnits/AUPublic/AUInstrumentBase/AUInstrumentBase.cpp
blob: 1ce8b308b4fddaba75b2d673b5d4cd6e8f74b5c5 (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
/*
     File: AUInstrumentBase.cpp
 Abstract: AUInstrumentBase.h
  Version: 1.1
 
 Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
 Inc. ("Apple") in consideration of your agreement to the following
 terms, and your use, installation, modification or redistribution of
 this Apple software constitutes acceptance of these terms.  If you do
 not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.
 
 In consideration of your agreement to abide by the following terms, and
 subject to these terms, Apple grants you a personal, non-exclusive
 license, under Apple's copyrights in this original Apple software (the
 "Apple Software"), to use, reproduce, modify and redistribute the Apple
 Software, with or without modifications, in source and/or binary forms;
 provided that if you redistribute the Apple Software in its entirety and
 without modifications, you must retain this notice and the following
 text and disclaimers in all such redistributions of the Apple Software.
 Neither the name, trademarks, service marks or logos of Apple Inc. may
 be used to endorse or promote products derived from the Apple Software
 without specific prior written permission from Apple.  Except as
 expressly stated in this notice, no other rights or licenses, express or
 implied, are granted by Apple herein, including but not limited to any
 patent rights that may be infringed by your derivative works or by other
 works in which the Apple Software may be incorporated.
 
 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2014 Apple Inc. All Rights Reserved.
 
*/
#include "AUInstrumentBase.h"
#include "AUMIDIDefs.h"

#if DEBUG
	#define DEBUG_PRINT 0
	#define DEBUG_PRINT_NOTE 0
	#define DEBUG_PRINT_RENDER 0
#endif

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

const UInt32 kEventQueueSize = 1024;

AUInstrumentBase::AUInstrumentBase(
							AudioComponentInstance			inInstance, 
							UInt32							numInputs,
							UInt32							numOutputs,
							UInt32							numGroups,
							UInt32							numParts)
	: MusicDeviceBase(inInstance, numInputs, numOutputs, numGroups), 
	mAbsoluteSampleFrame(0),
	mEventQueue(kEventQueueSize),
	mNumNotes(0),
	mNumActiveNotes(0),
	mMaxActiveNotes(0),
	mNotes(0),
	mNoteSize(0),
	mInitNumPartEls(numParts)
{
#if DEBUG_PRINT
	printf("new AUInstrumentBase\n");
#endif
	mFreeNotes.mState = kNoteState_Free;
	SetWantsRenderThreadID(true);
}
	

AUInstrumentBase::~AUInstrumentBase()
{
#if DEBUG_PRINT
	printf("delete AUInstrumentBase\n");
#endif
}

AUElement *	AUInstrumentBase::CreateElement(AudioUnitScope inScope, AudioUnitElement element)
{
	switch (inScope)
	{
		case kAudioUnitScope_Group:
			return new SynthGroupElement(this, element, new MidiControls);
		case kAudioUnitScope_Part:
			return new SynthPartElement (this, element);
	}
	return MusicDeviceBase::CreateElement(inScope, element);
}

void		AUInstrumentBase::CreateExtendedElements() 
{
	Parts().Initialize(this, kAudioUnitScope_Part, mInitNumPartEls);
}

AUScope *	AUInstrumentBase::GetScopeExtended (AudioUnitScope inScope) 
{
	if (inScope == kAudioUnitScope_Part)
		return &mPartScope;
	return NULL;
}


void		AUInstrumentBase::SetNotes(UInt32 inNumNotes, UInt32 inMaxActiveNotes, SynthNote* inNotes, UInt32 inNoteDataSize)
{
#if DEBUG_PRINT_NOTE
	printf("AUInstrumentBase::SetNotes %d %d %p %d\n", inNumNotes, inMaxActiveNotes, inNotes, inNoteDataSize);
#endif
	mNumNotes = inNumNotes;
	mMaxActiveNotes = inMaxActiveNotes;
	mNoteSize = inNoteDataSize;
	mNotes = inNotes;
	
	for (UInt32 i=0; i<mNumNotes; ++i)
	{
			SynthNote *note = GetNote(i);
			note->Reset();
			mFreeNotes.AddNote(note);
	}
}

UInt32		AUInstrumentBase::CountActiveNotes()
{
	// debugging tool.
	UInt32 sum = 0;
	for (UInt32 i=0; i<mNumNotes; ++i)
	{
		SynthNote *note = GetNote(i);
		if (note->GetState() <= kNoteState_Released) 
			sum++;
	}
	return sum;
}

void		AUInstrumentBase::AddFreeNote(SynthNote* inNote)
{
	// Fast-released notes are already considered inactive and have already decr'd the active count
	if (inNote->GetState() < kNoteState_FastReleased) {
		DecNumActiveNotes();
	}
#if DEBUG_PRINT_NOTE
	else {
			printf("AUInstrumentBase::AddFreeNote: adding fast-released note %p\n", inNote);
	}
	printf("AUInstrumentBase::AddFreeNote (%p)  mNumActiveNotes %lu\n", inNote, mNumActiveNotes);
#endif
	mFreeNotes.AddNote(inNote);
}

OSStatus			AUInstrumentBase::Initialize()
{
/*
TO DO:
	Currently ValidFormat will check and validate that the num channels is not being
	changed if the AU doesn't support the SupportedNumChannels property - which is correct
	
	What needs to happen here is that IFF the AU does support this property, (ie, the AU
	can be configured to have different num channels than its original configuration) then
	the state of the AU at Initialization needs to be validated.
	
	This is work still to be done - see AUEffectBase for the kind of logic that needs to be applied here
*/

	// override to call SetNotes
	
	mNoteIDCounter = 128; // reset this every time we initialise
	mAbsoluteSampleFrame = 0;
	return noErr;
}

void				AUInstrumentBase::Cleanup()
{
	mFreeNotes.Empty();
}


OSStatus			AUInstrumentBase::Reset(			AudioUnitScope 					inScope,
														AudioUnitElement 				inElement)
{
#if DEBUG_PRINT
	printf("AUInstrumentBase::Reset\n");
#endif
	if (inScope == kAudioUnitScope_Global)
	{
		// kill all notes..
		mFreeNotes.Empty();
		for (UInt32 i=0; i<mNumNotes; ++i)
		{
			SynthNote *note = GetNote(i);
			if (note->IsSounding()) 
				note->Kill(0);
			note->ListRemove();
			mFreeNotes.AddNote(note);
		}
		mNumActiveNotes = 0;
		mAbsoluteSampleFrame = 0;

		// empty lists.
		UInt32 numGroups = Groups().GetNumberOfElements();
		for (UInt32 j = 0; j < numGroups; ++j)
		{
			SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j);
			group->Reset();
		}
	}
	return MusicDeviceBase::Reset(inScope, inElement);
}

void		AUInstrumentBase::PerformEvents(const AudioTimeStamp& inTimeStamp)
{
#if DEBUG_PRINT_RENDER
	printf("AUInstrumentBase::PerformEvents\n");
#endif
	SynthEvent *event;
	SynthGroupElement *group;
	
	while ((event = mEventQueue.ReadItem()) != NULL)
	{
#if DEBUG_PRINT_RENDER
		printf("event %08X %d\n", event, event->GetEventType());
#endif
		switch(event->GetEventType())
		{
			case SynthEvent::kEventType_NoteOn :
				RealTimeStartNote(GetElForGroupID (event->GetGroupID()), event->GetNoteID(),
									event->GetOffsetSampleFrame(), *event->GetParams());
				break;
			case SynthEvent::kEventType_NoteOff :
				RealTimeStopNote(event->GetGroupID(), event->GetNoteID(),
					event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_SustainOn :
				group = GetElForGroupID (event->GetGroupID());
				group->SustainOn(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_SustainOff :
				group = GetElForGroupID (event->GetGroupID());
				group->SustainOff(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_SostenutoOn :
				group = GetElForGroupID (event->GetGroupID());
				group->SostenutoOn(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_SostenutoOff :
				group = GetElForGroupID (event->GetGroupID());
				group->SostenutoOff(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_AllNotesOff :
				group = GetElForGroupID (event->GetGroupID());
				group->AllNotesOff(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_AllSoundOff :
				group = GetElForGroupID (event->GetGroupID());
				group->AllSoundOff(event->GetOffsetSampleFrame());
				break;
			case SynthEvent::kEventType_ResetAllControllers :
				group = GetElForGroupID (event->GetGroupID());
				group->ResetAllControllers(event->GetOffsetSampleFrame());
				break;
		}
		
		mEventQueue.AdvanceReadPtr();
	}
}

														
OSStatus			AUInstrumentBase::Render(   AudioUnitRenderActionFlags &	ioActionFlags,
												const AudioTimeStamp &			inTimeStamp,
												UInt32							inNumberFrames)
{
	PerformEvents(inTimeStamp);

	AUScope &outputs = Outputs();
	UInt32 numOutputs = outputs.GetNumberOfElements();
	for (UInt32 j = 0; j < numOutputs; ++j)
	{
		GetOutput(j)->PrepareBuffer(inNumberFrames);	// AUBase::DoRenderBus() only does this for the first output element
		AudioBufferList& bufferList = GetOutput(j)->GetBufferList();
		for (UInt32 k = 0; k < bufferList.mNumberBuffers; ++k)
		{
			memset(bufferList.mBuffers[k].mData, 0, bufferList.mBuffers[k].mDataByteSize);
		}
	}
	UInt32 numGroups = Groups().GetNumberOfElements();
	for (UInt32 j = 0; j < numGroups; ++j)
	{
		SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j);
		OSStatus err = group->Render((SInt64)inTimeStamp.mSampleTime, inNumberFrames, outputs);
		if (err) return err;
	}
	mAbsoluteSampleFrame += inNumberFrames;
	return noErr;
}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//	AUInstrumentBase::ValidFormat
//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
bool				AUInstrumentBase::ValidFormat(	AudioUnitScope					inScope,
													AudioUnitElement				inElement,
													const CAStreamBasicDescription  & inNewFormat)
{	
		// if the AU supports this, then we should just let this go through to the Init call
	if (SupportedNumChannels (NULL)) 
		return MusicDeviceBase::ValidFormat(inScope, inElement, inNewFormat);

	bool isGood = MusicDeviceBase::ValidFormat (inScope, inElement, inNewFormat);
	if (!isGood) return false;
	
		// if we get to here, then the basic criteria is that the
		// num channels cannot change on an existing bus
	AUIOElement *el = GetIOElement (inScope, inElement);
	return (el->GetStreamFormat().NumberChannels() == inNewFormat.NumberChannels()); 
}


bool				AUInstrumentBase::StreamFormatWritable(	AudioUnitScope					scope,
															AudioUnitElement				element)
{
	return IsInitialized() ? false : true;
}

OSStatus			AUInstrumentBase::RealTimeStartNote(	SynthGroupElement 			*inGroup,
															NoteInstanceID 				inNoteInstanceID, 
															UInt32 						inOffsetSampleFrame, 
															const MusicDeviceNoteParams &inParams)
{
	return noErr;
}

SynthPartElement *	AUInstrumentBase::GetPartElement (AudioUnitElement inPartElement)
{
	AUScope & parts = Parts();
	unsigned int numEls = parts.GetNumberOfElements();
	for (unsigned int i = 0; i < numEls; ++i) {
		SynthPartElement* el = reinterpret_cast<SynthPartElement*>(parts.GetElement(i));
		if (el->GetIndex() == inPartElement) {
			return el;
		}
	}
	return NULL;
}

SynthGroupElement *	AUInstrumentBase::GetElForGroupID (MusicDeviceGroupID	inGroupID)
{
	AUScope & groups = Groups();
	unsigned int numEls = groups.GetNumberOfElements();
	SynthGroupElement* unassignedEl = NULL;
	
	for (unsigned int i = 0; i < numEls; ++i) {
		SynthGroupElement* el = reinterpret_cast<SynthGroupElement*>(groups.GetElement(i));
		if (el->GroupID() == inGroupID) 
			return el;
		if (el->GroupID() == SynthGroupElement::kUnassignedGroup) {
			unassignedEl = el;
			break; // we fill this up from the start of the group scope vector
		}
	}
	if (unassignedEl) {
		unassignedEl->SetGroupID(inGroupID);
		return unassignedEl;
	}
	throw static_cast<OSStatus>(kAudioUnitErr_InvalidElement);
}

OSStatus			AUInstrumentBase::RealTimeStopNote(
												MusicDeviceGroupID 			inGroupID, 
												NoteInstanceID 				inNoteInstanceID, 
												UInt32 						inOffsetSampleFrame)
{
#if DEBUG_PRINT
	printf("AUInstrumentBase::RealTimeStopNote ch %d id %d\n", inGroupID, inNoteInstanceID);
#endif
	
	SynthGroupElement *gp = (inGroupID == kMusicNoteEvent_Unused
								? GetElForNoteID (inNoteInstanceID)
								: GetElForGroupID(inGroupID));
	if (gp)
	{
		gp->NoteOff (inNoteInstanceID, inOffsetSampleFrame);
	}
	
	return noErr;
}

SynthGroupElement *	AUInstrumentBase::GetElForNoteID (NoteInstanceID inNoteID)
{
#if DEBUG_PRINT
	printf("GetElForNoteID id %u\n", inNoteID);
#endif
	AUScope & groups = Groups();
	unsigned int numEls = groups.GetNumberOfElements();
	
	for (unsigned int i = 0; i < numEls; ++i) {
		SynthGroupElement* el = reinterpret_cast<SynthGroupElement*>(groups.GetElement(i));
		if (el->GetNote(inNoteID) != NULL)	// searches for any note state
			return el;
	}
	throw static_cast<OSStatus>(kAudioUnitErr_InvalidElement);
}

OSStatus			AUInstrumentBase::StartNote(	MusicDeviceInstrumentID 	inInstrument, 
													MusicDeviceGroupID 			inGroupID, 
													NoteInstanceID *			outNoteInstanceID, 
													UInt32 						inOffsetSampleFrame, 
													const MusicDeviceNoteParams &inParams)
{
	OSStatus err = noErr;
	
	NoteInstanceID noteID; 
	if (outNoteInstanceID) {
		noteID = NextNoteID();
		*outNoteInstanceID = noteID;
	} else
		noteID = (UInt32)inParams.mPitch;
	
#if DEBUG_PRINT
	printf("AUInstrumentBase::StartNote ch %u, key %u, offset %u\n", inGroupID, (unsigned) inParams.mPitch, inOffsetSampleFrame);
#endif

	if (InRenderThread ())
	{		
		err = RealTimeStartNote(
					GetElForGroupID(inGroupID),
					noteID,
					inOffsetSampleFrame,
					inParams);
	}
	else
	{
		SynthEvent *event = mEventQueue.WriteItem();
		if (!event) return -1; // queue full

		event->Set(
			SynthEvent::kEventType_NoteOn,
			inGroupID,
			noteID,
			inOffsetSampleFrame,
			&inParams
		);
		
		mEventQueue.AdvanceWritePtr();
	}
	return err;
}

OSStatus			AUInstrumentBase::StopNote( MusicDeviceGroupID 			inGroupID, 
												NoteInstanceID 				inNoteInstanceID, 
												UInt32 						inOffsetSampleFrame)
{
#if DEBUG_PRINT
	printf("AUInstrumentBase::StopNote ch %u, id %u, offset %u\n", (unsigned)inGroupID, (unsigned)inNoteInstanceID, inOffsetSampleFrame);
#endif
	OSStatus err = noErr;

	if (InRenderThread ())
	{		
		err = RealTimeStopNote(
			inGroupID,
			inNoteInstanceID,
			inOffsetSampleFrame);
	}
	else
	{
		SynthEvent *event = mEventQueue.WriteItem();
		if (!event) return -1; // queue full

		event->Set(
			SynthEvent::kEventType_NoteOff,
			inGroupID,
			inNoteInstanceID,
			inOffsetSampleFrame,
			NULL
		);
		
		mEventQueue.AdvanceWritePtr();
	}
	return err;
}

OSStatus	AUInstrumentBase::SendPedalEvent(MusicDeviceGroupID inGroupID, UInt32 inEventType, UInt32 inOffsetSampleFrame)
{
	
	if (InRenderThread ())
	{
		SynthGroupElement *group = GetElForGroupID(inGroupID);
		if (!group)
			return kAudioUnitErr_InvalidElement;
		
		switch (inEventType)
		{
			case SynthEvent::kEventType_SustainOn :
				group->SustainOn(inOffsetSampleFrame);
				break;
			case SynthEvent::kEventType_SustainOff :
				group->SustainOff(inOffsetSampleFrame);
				break;
			case SynthEvent::kEventType_SostenutoOn :
				group->SostenutoOn(inOffsetSampleFrame);
				break;
			case SynthEvent::kEventType_SostenutoOff :
				group->SostenutoOff(inOffsetSampleFrame);
				break;
			case SynthEvent::kEventType_AllNotesOff :
				group->AllNotesOff(inOffsetSampleFrame);
				mNumActiveNotes = CountActiveNotes();
				break;
			case SynthEvent::kEventType_AllSoundOff :
				group->AllSoundOff(inOffsetSampleFrame);
				mNumActiveNotes = CountActiveNotes();
				break;
			case SynthEvent::kEventType_ResetAllControllers :
				group->ResetAllControllers(inOffsetSampleFrame);
				break;
		}
	}
	else
	{
		SynthEvent *event = mEventQueue.WriteItem();
		if (!event) return -1; // queue full

		event->Set(inEventType, inGroupID, 0, 0, NULL);
		
		mEventQueue.AdvanceWritePtr();
	}
	return noErr;
}

OSStatus	AUInstrumentBase::HandleControlChange(	UInt8 	inChannel,
													UInt8 	inController,
													UInt8 	inValue,
													UInt32	inStartFrame)
{
#if DEBUG_PRINT
	printf("AUInstrumentBase::HandleControlChange ch %u ctlr: %u val: %u frm: %u\n", inChannel, inController, inValue, inStartFrame);
#endif
	SynthGroupElement *gp = GetElForGroupID(inChannel);
	if (gp)
	{
		gp->ChannelMessage(inController, inValue);
	}
	else
		return kAudioUnitErr_InvalidElement;
	switch (inController)
	{
		case kMidiController_Sustain :
			if (inValue >= 64)
				SendPedalEvent(inChannel, SynthEvent::kEventType_SustainOn, inStartFrame);
			else
				SendPedalEvent(inChannel, SynthEvent::kEventType_SustainOff, inStartFrame);
			break;
		case kMidiController_Sostenuto :
			if (inValue >= 64)
				SendPedalEvent(inChannel, SynthEvent::kEventType_SostenutoOn, inStartFrame);
			else
				SendPedalEvent(inChannel, SynthEvent::kEventType_SostenutoOff, inStartFrame);
			break;
        case kMidiController_OmniModeOff:
        case kMidiController_OmniModeOn:
        case kMidiController_MonoModeOn:
        case kMidiController_MonoModeOff:
            HandleAllSoundOff(inChannel);
            break;
	}
	return noErr;
}
												
OSStatus	AUInstrumentBase::HandlePitchWheel(		UInt8 	inChannel,
													UInt8 	inPitch1,	// LSB
													UInt8 	inPitch2,	// MSB
													UInt32	inStartFrame)
{
	SynthGroupElement *gp = GetElForGroupID(inChannel);
	if (gp)
	{
		gp->ChannelMessage(kMidiMessage_PitchWheel, (inPitch2 << 7) | inPitch1);
		return noErr;
	}
	else
		return kAudioUnitErr_InvalidElement;
}

												
OSStatus	AUInstrumentBase::HandleChannelPressure(UInt8 	inChannel,
													UInt8 	inValue,
													UInt32	inStartFrame)
{
	SynthGroupElement *gp = GetElForGroupID(inChannel);
	if (gp)
	{
		gp->ChannelMessage(kMidiMessage_ChannelPressure, inValue);
		return noErr;
	}
	else
		return kAudioUnitErr_InvalidElement;
}


OSStatus	AUInstrumentBase::HandleProgramChange(	UInt8 	inChannel,
													UInt8 	inValue)
{
#if DEBUG_PRINT
	printf("AUInstrumentBase::HandleProgramChange %u %u\n", inChannel, inValue);
#endif
	SynthGroupElement *gp = GetElForGroupID(inChannel);
	if (gp)
	{
		gp->ChannelMessage(kMidiMessage_ProgramChange, inValue);
		return noErr;
	}
	else
		return kAudioUnitErr_InvalidElement;
}


OSStatus	AUInstrumentBase::HandlePolyPressure(	UInt8 	inChannel,
													UInt8 	inKey,
													UInt8	inValue,
													UInt32	inStartFrame)
{
	SynthGroupElement *gp = GetElForGroupID(inChannel);
	if (gp)
	{
		// Combine key and value into single argument.  UGLY!
		gp->ChannelMessage(kMidiMessage_PolyPressure, (inKey << 7) | inValue);
		return noErr;
	}
	else
		return kAudioUnitErr_InvalidElement;
}


OSStatus	AUInstrumentBase::HandleResetAllControllers(	UInt8 	inChannel)
{
	return SendPedalEvent (inChannel, SynthEvent::kEventType_ResetAllControllers, 0);
}

	
OSStatus	AUInstrumentBase::HandleAllNotesOff(			UInt8 	inChannel)
{
	return SendPedalEvent (inChannel, SynthEvent::kEventType_AllNotesOff, 0);
}

	
OSStatus	AUInstrumentBase::HandleAllSoundOff(			UInt8 	inChannel)
{
	return SendPedalEvent (inChannel, SynthEvent::kEventType_AllSoundOff, 0);
}

SynthNote*  AUInstrumentBase::GetAFreeNote(UInt32 inFrame)
{
#if DEBUG_PRINT_NOTE
	printf("AUInstrumentBase::GetAFreeNote:  %lu available\n", mFreeNotes.Length());
#endif
	SynthNote *note = mFreeNotes.mHead;
	if (note)
	{
		mFreeNotes.RemoveNote(note);
		return note;
	}
	
	return VoiceStealing(inFrame, true);
}

SynthNote*  AUInstrumentBase::VoiceStealing(UInt32 inFrame, bool inKillIt)
{

#if DEBUG_PRINT_NOTE
	printf("AUInstrumentBase::VoiceStealing\n");
#endif
	// free list was empty so we need to kill a note.
	UInt32 startState = inKillIt ? kNoteState_FastReleased : kNoteState_Released;
	for (UInt32 i = startState; i <= startState; --i)
	{
#if DEBUG_PRINT_NOTE
		printf(" checking state %d...\n", i);
#endif
		UInt32 numGroups = Groups().GetNumberOfElements();
		for (UInt32 j = 0; j < numGroups; ++j)
		{
			SynthGroupElement *group = (SynthGroupElement*)Groups().GetElement(j);
#if DEBUG_PRINT_NOTE
			printf("\tsteal group %d   size %d\n", j, group->mNoteList[i].Length());
#endif
			if (group->mNoteList[i].NotEmpty()) {
#if DEBUG_PRINT_NOTE
				printf("\t-- not empty\n");
#endif
				SynthNote *note = group->mNoteList[i].FindMostQuietNote();
				if (inKillIt) {
#if DEBUG_PRINT_NOTE
					printf("\t--=== KILL ===---\n");
#endif
					note->Kill(inFrame);
					group->mNoteList[i].RemoveNote(note);
					if (i != kNoteState_FastReleased)
						DecNumActiveNotes();
					return note;
				} else {
#if DEBUG_PRINT_NOTE
					printf("\t--=== FAST RELEASE ===---\n");
#endif
					group->mNoteList[i].RemoveNote(note);
					note->FastRelease(inFrame);
					group->mNoteList[kNoteState_FastReleased].AddNote(note);
					DecNumActiveNotes(); // kNoteState_FastReleased counts as inactive for voice stealing purposes.
					return NULL;
				}
			}
		}
	}
#if DEBUG_PRINT_NOTE
	printf("no notes to steal????\n");
#endif
	return NULL; // It should be impossible to get here. It means there were no notes to kill in any state. 
}

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

AUMonotimbralInstrumentBase::AUMonotimbralInstrumentBase(
							AudioComponentInstance			inInstance, 
							UInt32							numInputs,
							UInt32							numOutputs,
							UInt32							numGroups,
							UInt32							numParts)
	: AUInstrumentBase(inInstance, numInputs, numOutputs, numGroups, numParts)
{
}

OSStatus			AUMonotimbralInstrumentBase::RealTimeStartNote(	
															SynthGroupElement 			*inGroup, 
															NoteInstanceID 				inNoteInstanceID, 
															UInt32 						inOffsetSampleFrame, 
															const MusicDeviceNoteParams &inParams)
{
#if DEBUG_PRINT_RENDER
	printf("AUMonotimbralInstrumentBase::RealTimeStartNote %d\n", inNoteInstanceID);
#endif

	if (NumActiveNotes() + 1 > MaxActiveNotes()) 
	{
		VoiceStealing(inOffsetSampleFrame, false);
	}
	SynthNote *note = GetAFreeNote(inOffsetSampleFrame);
	if (!note) return -1;
	
	SynthPartElement *part = GetPartElement (0);	// Only one part for monotimbral
	
	IncNumActiveNotes();
	inGroup->NoteOn(note, part, inNoteInstanceID, inOffsetSampleFrame, inParams);
	
	return noErr;
}

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


OSStatus			AUMultitimbralInstrumentBase::GetPropertyInfo(AudioUnitPropertyID	inID,
												AudioUnitScope				inScope,
												AudioUnitElement			inElement,
												UInt32 &					outDataSize,
												Boolean &					outWritable)
{
	OSStatus result = noErr;
	
	switch (inID) 
	{
#if !TARGET_OS_IPHONE
		case kMusicDeviceProperty_PartGroup:
			if (inScope != kAudioUnitScope_Part) return kAudioUnitErr_InvalidScope;
			outDataSize = sizeof(UInt32);
			outWritable = true;
			break;
#endif
		default:
			result = AUInstrumentBase::GetPropertyInfo (inID, inScope, inElement, outDataSize, outWritable);
	}
	return result;
}

OSStatus			AUMultitimbralInstrumentBase::GetProperty(	AudioUnitPropertyID 	inID,
												AudioUnitScope 				inScope,
												AudioUnitElement		 	inElement,
												void *						outData)
{
	OSStatus result = noErr;

	switch (inID) 
	{
#if !TARGET_OS_IPHONE
		case kMusicDeviceProperty_PartGroup:
			if (inScope != kAudioUnitScope_Group) return kAudioUnitErr_InvalidScope;
			// ??
			return -1; //unimpl
			break;
#endif
		default:
			result = AUInstrumentBase::GetProperty (inID, inScope, inElement, outData);
	}
	
	return result;
}



OSStatus			AUMultitimbralInstrumentBase::SetProperty(  AudioUnitPropertyID 			inID,
																AudioUnitScope 					inScope,
																AudioUnitElement 				inElement,
																const void *					inData,
																UInt32 							inDataSize)
{
	OSStatus result = noErr;

	switch (inID) 
	{
#if !TARGET_OS_IPHONE
		case kMusicDeviceProperty_PartGroup:
			if (inScope != kAudioUnitScope_Group) return kAudioUnitErr_InvalidScope;
			// ??
			return -1; //unimpl
			break;
#endif
		default:
			result = MusicDeviceBase::SetProperty (inID, inScope, inElement, inData, inDataSize);
	}
	
	return result;
}

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