/
Instrument.m
executable file
·1589 lines (1210 loc) · 50.5 KB
/
Instrument.m
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
//
// TrackInstrument.m
// Hexatone
//
// Created by Glenn Barnett on 1/5/09.
// Copyright 2009 Impresario Digital. All rights reserved.
//
#import "Instrument.h"
#import "Sample.h"
#import "IDAudioUtils.h"
#import "Tuning.h"
#import "Scale.h"
#import "Patch.h"
#import "HexaphoneAppDelegate.h"
#import "ScaleManager.h"
#import "PatchManager.h"
#import "PatchViewController.h"
#import "GLVectorOverlayView.h"
#import <AudioToolbox/AudioToolbox.h>
#define kNumBytesPerPacket 2
@implementation Instrument;
@synthesize touchView;
@synthesize keysArePlaying;
@synthesize keysAreStarting;
@synthesize keysAreStopping;
@synthesize interfaceKeysPlaying;
@synthesize recordedKeysPlaying;
@synthesize keysToIndicate;
@synthesize tuning;
@synthesize patchId;
@synthesize scaleId;
//@synthesize externalSpeakerWasUsed;
// basement flooded! will came over to help!
void interruptionListenerCallback (
void *inUserData,
UInt32 interruptionState
) {
//GSB: from speakhere
// This callback, being outside the implementation block, needs a reference
// to the AudioViewController object. You provide this reference when
// initializing the audio session (see the call to AudioSessionInitialize).
// AudioViewController *controller = (AudioViewController *) inUserData;
//NSLog (@"Instrument: interruptionListenerCallback");
// if (interruptionState == kAudioSessionBeginInterruption) {
//
// NSLog (@"Interrupted. Stopping playback or recording.");
//
//// if (controller.audioPlayer) {
//// // if currently playing, pause
//// [controller pausePlayback];
//// controller.interruptedOnPlayback = YES;
//// }
//
// } else if ((interruptionState == kAudioSessionEndInterruption) && controller.interruptedOnPlayback) {
// // if the interruption was removed, and the app had been playing, resume playback
// [controller resumePlayback];
// controller.interruptedOnPlayback = NO;
// }
}
// Audio session callback function for responding to audio route changes. This
// callback behaves as follows when a headset gets plugged in or unplugged:
//
// If playing back: pauses playback and displays an alert that allows the user
// to resume playback
//
// If recording: stops recording and displays an alert that notifies the
// user that recording has stopped.
BOOL isHeadphonePluggedIn() {
CFStringRef newAudioRoute;
UInt32 propertySize = sizeof (CFStringRef);
AudioSessionGetProperty (
kAudioSessionProperty_AudioRoute,
&propertySize,
&newAudioRoute
);
if(newAudioRoute == nil) {
return 0;
}
BOOL isHeadphonePluggedIn = kCFCompareEqualTo == CFStringCompare (
newAudioRoute,
(CFStringRef) @"Headphone",
0
);
return isHeadphonePluggedIn;
}
void audioRouteChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
const void *inPropertyValue
) {
// NSLog (@"Instrument: audioRouteChangeListenerCallback");
// ensure that this callback was invoked for the correct property change
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
// This callback, being outside the implementation block, needs a reference
// to the AudioViewController object. You provide this reference when
// registering this callback (see the call to AudioSessionAddPropertyListener).
// AudioViewController *controller = (AudioViewController *) inUserData;
// A change in audio session category counts as an "audio route change." Because
// this sample sets the audio session category only when beginning playback
// or recording, it should not pause or stop for that. To avoid inappropriate
// pausing or stopping, this callback queries the "reason" for the route change
// and branches accordingly.
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef =
CFDictionaryGetValue (
routeChangeDictionary,
CFSTR (kAudioSession_AudioRouteChangeKey_Reason)
);
SInt32 routeChangeReason;
CFNumberGetValue (
routeChangeReasonRef,
kCFNumberSInt32Type,
&routeChangeReason
);
if (routeChangeReason != kAudioSessionRouteChangeReason_CategoryChange) {
//
// CFStringRef newAudioRoute;
// UInt32 propertySize = sizeof (CFStringRef);
//
// AudioSessionGetProperty (
// kAudioSessionProperty_AudioRoute,
// &propertySize,
// &newAudioRoute
// );
//
//
// CFComparisonResult newDeviceIsHeadphone = CFStringCompare (
// newAudioRoute,
// (CFStringRef) @"Headphone",
// 0
// );
//
// if (newDeviceIsHeadphone == kCFCompareEqualTo) {
// if(isHeadphonePluggedIn() == 1) {
// externalSpeakerWasUsed = YES;
//
//// UIAlertView *routeChangeAlertView;
//// routeChangeAlertView = [[UIAlertView alloc] initWithTitle: @"Playback Paused"
//// message: @"Audio output was changed"
//// delegate: self
//// cancelButtonTitle: @"Stop"
//// otherButtonTitles: @"Play", nil];
//// [routeChangeAlertView show];
// // release takes place in alertView:clickedButtonAtIndex: method
//
// } else {
// NSLog(@"audio route switched to something else");
// //NSLog (@"New audio route is not Headphone, but: %@.", newAudioRoute);
// } // end if (newDeviceIsSpeaker == kCFCompareEqualTo)
//
} else {
// NSLog (@"Audio category change.");
}
}
// 20100809 lowpass2
-(void) setFilterRez:(float)sliderPercent {
resonance = sliderPercent * 4.0f;
if(resonance < 0.05f && [UIAccelerometer sharedAccelerometer].delegate != nil) {
NSLog(@"I.adjustFilterRez: disabling accelerometer");
[[UIAccelerometer sharedAccelerometer] setDelegate:nil];
} else if(resonance >= 0.05f && [UIAccelerometer sharedAccelerometer].delegate == nil) {
NSLog(@"I.adjustFilterRez: re-enabling accelerometer");
[[UIAccelerometer sharedAccelerometer] setDelegate:appDelegate];
}
}
// 20100809 /lowpass2
-(id) init {
// NSLog(@"Instrument: -init");
[super init];
in1 = in2 = in3 = in4 = out1 = out2 = out3 = out4 = 0.0f;
// externalSpeakerWasUsed = isHeadphonePluggedIn();
instrumentVolume = 1.0;
touchExpansionPixels = 8;
volumePedalModifier = 1.0;
volumePedalMinimum = 1.0;
appDelegate = (HexaphoneAppDelegate*) [[UIApplication sharedApplication] delegate];
keysArePlaying = 0;
keysAreStarting = 0;
keysAreStopping = 0;
interfaceKeysPlaying = 0;
recordedKeysPlaying = 0;
_keysData = [[NSMutableData alloc] init];
// Audio Session: (for both OpenAL and RemoteIO/AudioUnits):
//audio session init - so we can get notifications when user
// returns from phone call or alarm. taken from SpeakHere app.
AudioSessionInitialize (
NULL,
NULL,
interruptionListenerCallback,
self
);
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// this works - allows ipod in background - http://stackoverflow.com/questions/1090871/implementing-ipod-playback
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
UInt32 shouldDuck = false;
AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck, sizeof(shouldDuck), &shouldDuck);
AudioSessionSetActive(true);
//GSB post-MX: going back to openAL
[self initRemoteIO];
return self;
}
//#define kFadeSteps 256
//#define kFadeStepsFloat 256.0f
#define kFadeSteps 256
#define kFadeStepsFloat 256.0f
#define kFadeThresholdNeg -10
#define kFadeThresholdPos 10
#define kFadeThresholdFloatNeg -0.0001
#define kFadeThresholdFloatPos 0.0001
#define kFadeMultiplierExponent 2.0f
// peak at 1.3/1.4
float waveshape_distort( float in ) {
if(in <= -1.25f) {
return -0.984375;
} else if(in >= 1.25f) {
return 0.984375;
} else {
return 1.1f * in - 0.2f * in * in * in;
}
}
float waveshape_distort_01( float in ) {
return 1.5f * in - 0.5f * in * in * in;
}
// audiounit playback callback
// fresh conversion to floats GSB 20100407 midnight
#define kCutoffThrottle 0.04f
static OSStatus playbackCallback(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData) {
// Keys: ioData contains buffers (may be more than one!)
// Fill them up as much as you can. Remember to set the size value in each buffer to match how
// much data is in the buffer.
// NSLog(@" PBCB: inNumberFrames=%d", inNumberFrames); //512
// NSLog(@" PBCB: ioData->mBuffers[0].mDataByteSize=%d", ioData->mBuffers[0].mDataByteSize); //512
Instrument *instrument =(Instrument*)inRefCon;
AudioBufferList *_mSampleBufferList = instrument->_mSampleBufferList;
// initialize to 0
memset(ioData->mBuffers[0].mData, 0, ioData->mBuffers[0].mDataByteSize);
// cast buffer to SInt16 for arithmatic
SInt16 *deviceBuffer = (SInt16*) ioData->mBuffers[0].mData;
UInt32 framesToRead = inNumberFrames; // 512
// prepare float buffer
float *floatDeviceBuffer = malloc(sizeof(float) * inNumberFrames);
memset(floatDeviceBuffer, 0.0f, sizeof(float) * inNumberFrames);
// count how many notes are playing (for clip prevention)
UInt8 numKeysPlaying = 0;
for(volatile UInt8 checkedBit = 0; checkedBit < 31; checkedBit++) {
if(((instrument->keysAreStarting | instrument->keysArePlaying) >> checkedBit) & 1 == 1) {
numKeysPlaying++;
}
}
for(volatile UInt8 checkedBit = 0; checkedBit < 31; checkedBit++) {
// only bother with keys that are active:
if(((instrument->keysAreStarting | instrument->keysAreStopping | instrument->keysArePlaying) >> checkedBit) & 1 == 1) {
SInt16 *sampleBuffer = (SInt16*) _mSampleBufferList->mBuffers[checkedBit].mData;
UInt32 remainingFramesToFill = framesToRead;
UInt32 deviceBufferCursor = 0;
UInt32 sampleBufferSizeFrames = _mSampleBufferList->mBuffers[checkedBit].mDataByteSize/2;
volatile UInt32 sampleBufferCursor = instrument->_mSampleBufferCursors[checkedBit];
UInt32 fadeInFraction = kFadeSteps; // out of 256
UInt32 fadeOutFraction = 0; // out of 256
if((instrument->keysAreStarting >> checkedBit) & 1 == 1) {
// KEYS THAT ARE STARTING
// we need to fade them in to avoid pop
fadeInFraction = 0; // set to 0, will be incremented until 256
// zero out keysAreStarting[checkedBit] since we've "claimed" the fadein
instrument->keysAreStarting = instrument->keysAreStarting & (0xFFFFFFFF ^ 1<<checkedBit);
while(remainingFramesToFill > (sampleBufferSizeFrames - sampleBufferCursor)) {
// we can put the whole (remaining) sample in
for(int i=0; i<sampleBufferSizeFrames-sampleBufferCursor; i++) {
float rawValue = (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
float fadedValue = 0.0f;
float fadeMultiplier = ((float) ++fadeInFraction / kFadeStepsFloat);
if(fadeInFraction < kFadeSteps) {
fadedValue = rawValue * fadeMultiplier;
} else {
fadedValue = rawValue;
}
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += fadedValue;
//********************************** wave mixed in
}
deviceBufferCursor += (sampleBufferSizeFrames - sampleBufferCursor);
remainingFramesToFill -= (sampleBufferSizeFrames - sampleBufferCursor);
sampleBufferCursor = 0;
}
if(remainingFramesToFill > 0) {
// we have more bytes to fill, but can't fit our sample in.
// put in as much as we can, and save the position so we can
// resume on the next callback.
for(int i=0; i<remainingFramesToFill; i++) {
UInt32 debugBufferOffset = sampleBufferCursor+i;
BOOL bufferOverflow;
UInt32 debugSampleBufferSizeFrames = sampleBufferSizeFrames;
if(debugBufferOffset >= debugSampleBufferSizeFrames) {
bufferOverflow = YES;
} else {
bufferOverflow = NO;
}
float rawValue = (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
float fadedValue = 0.0f;
float fadeMultiplier = ((float) ++fadeInFraction / kFadeStepsFloat);
if(fadeInFraction < kFadeSteps) {
fadedValue = rawValue * fadeMultiplier;
} else {
fadedValue = rawValue;
}
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += fadedValue;
//********************************** wave mixed in
}
if(remainingFramesToFill == sampleBufferSizeFrames) {
sampleBufferCursor = 0; // it just fit!
} else {
sampleBufferCursor += remainingFramesToFill;
}
instrument->_mSampleBufferCursors[checkedBit] = sampleBufferCursor;
remainingFramesToFill = 0;
}
} else if((instrument->keysAreStopping >> checkedBit) & 1 == 1) {
// sample[checkedBit] should be faded out
fadeOutFraction = kFadeSteps; // set to 256, will be decremented until 0
// zero out keysAreStopping[checkedBit] since we've "claimed" the fadein
instrument->keysAreStopping = instrument->keysAreStopping & (0xFFFFFFFF ^ 1<<checkedBit);
BOOL noteHasStopped = false;
while(remainingFramesToFill > (sampleBufferSizeFrames - sampleBufferCursor) && !noteHasStopped) {
// we can put the whole (remaining) sample in
for(int i=0; i<sampleBufferSizeFrames-sampleBufferCursor && !noteHasStopped; i++) {
float rawValue = (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
float fadedValue = 0.0f;
float fadeMultiplier = powf(((float) --fadeOutFraction / kFadeStepsFloat), kFadeMultiplierExponent);
if(fadeOutFraction > 0) {
fadedValue = rawValue * fadeMultiplier;
} else {
fadedValue = 0.0f;
noteHasStopped = YES;
sampleBufferCursor = 0;
}
if(kFadeThresholdFloatNeg < fadedValue && fadedValue < kFadeThresholdFloatPos) {
// close enough
fadedValue = 0.0f;
noteHasStopped = YES;
sampleBufferCursor = 0;
}
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += fadedValue;
//********************************** wave mixed in
}
deviceBufferCursor += (sampleBufferSizeFrames - sampleBufferCursor);
remainingFramesToFill -= (sampleBufferSizeFrames - sampleBufferCursor);
sampleBufferCursor = 0;
}
if(remainingFramesToFill > 0 && !noteHasStopped) {
// we have more bytes to fill, but can't fit our sample in.
// put in as much as we can, and save the position so we can
// resume on the next callback.
for(int i=0; i<remainingFramesToFill && !noteHasStopped; i++) {
float rawValue = (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
float fadedValue = 0.0f;
float fadeMultiplier = powf(((float) --fadeOutFraction / kFadeStepsFloat), kFadeMultiplierExponent);
if(fadeOutFraction > 0) {
fadedValue = rawValue * fadeMultiplier;
} else {
fadedValue = 0.0f;
noteHasStopped = YES;
sampleBufferCursor = 0;
}
if(kFadeThresholdFloatNeg < fadedValue && fadedValue < kFadeThresholdFloatPos) {
// close enough
fadedValue = 0.0f;
noteHasStopped = YES;
sampleBufferCursor = 0;
}
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += fadedValue;
//********************************** wave mixed in
}
if(remainingFramesToFill == sampleBufferSizeFrames) {
sampleBufferCursor = 0; // it just fit!
} else {
sampleBufferCursor += remainingFramesToFill;
}
instrument->_mSampleBufferCursors[checkedBit] = sampleBufferCursor;
remainingFramesToFill = 0;
}
} else {
while(remainingFramesToFill > (sampleBufferSizeFrames - sampleBufferCursor)) {
// we can put the whole (remaining) sample[checkedBit] in
for(int i=0; i<sampleBufferSizeFrames-sampleBufferCursor; i++) {
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
//********************************** wave mixed in
}
deviceBufferCursor += (sampleBufferSizeFrames - sampleBufferCursor);
remainingFramesToFill -= (sampleBufferSizeFrames - sampleBufferCursor);
sampleBufferCursor = 0;
}
if(remainingFramesToFill > 0) {
// we have more bytes to fill, but can't fit our sample in.
// put in as much as we can, and save the position so we can
// resume on the next callback.
for(int i=0; i<remainingFramesToFill; i++) {
//********************************** wave mixed in
floatDeviceBuffer[deviceBufferCursor+i] += (float) sampleBuffer[sampleBufferCursor+i] / 32767.0f;
//********************************** wave mixed in
}
if(remainingFramesToFill == sampleBufferSizeFrames) {
sampleBufferCursor = 0; // it just fit!
} else {
sampleBufferCursor += remainingFramesToFill;
}
instrument->_mSampleBufferCursors[checkedBit] = sampleBufferCursor;
remainingFramesToFill = 0;
}
}
}
}
// WAVE IS RENDERED AT THIS POINT - rest is post-processing
// throttle the filter_cutoff
if(fabs(instrument->target_filter_cutoff - instrument->filter_cutoff) > kCutoffThrottle) {
if(instrument->target_filter_cutoff < instrument->filter_cutoff) {
instrument->filter_cutoff -= kCutoffThrottle;
} else {
instrument->filter_cutoff += kCutoffThrottle;
}
} else {
instrument->filter_cutoff = instrument->target_filter_cutoff;
}
//TODO POSTLAUNCH: GSB - iterate over deviceBuffer[], scaling the whole thing down to 32766
for(int i=0; i<framesToRead; i++) {
float waveIn = floatDeviceBuffer[i];
float waveVolumeAdjusted = waveIn * instrument->instrumentVolume;
//float waveLowPassPost = waveVolumeAdjusted;
//GSB 20100809 lowpass2 http://musicdsp.org/showArchiveComment.php?ArchiveID=26
float waveLowPassPost;
if(instrument->resonance >= 0.05f) {
float input = waveVolumeAdjusted;
float f = instrument->filter_cutoff * 1.16;
float fb = instrument->resonance * (1.0 - 0.15 * f * f);
input -= instrument->out4 * fb;
input *= 0.35013 * (f*f)*(f*f);
instrument->out1 = input + 0.3 * instrument->in1 + (1 - f) * instrument->out1; // Pole 1
instrument->in1 = input;
instrument->out2 = instrument->out1 + 0.3 * instrument->in2 + (1 - f) * instrument->out2; // Pole 2
instrument->in2 = instrument->out1;
instrument->out3 = instrument->out2 + 0.3 * instrument->in3 + (1 - f) * instrument->out3; // Pole 3
instrument->in3 = instrument->out2;
instrument->out4 = instrument->out3 + 0.3 * instrument->in4 + (1 - f) * instrument->out4; // Pole 4
instrument->in4 = instrument->out3;
waveLowPassPost = instrument->out4;
} else { // rez is 0.0, bypass
waveLowPassPost = waveVolumeAdjusted;
}
//GSB 20100809 /lowpass2
float wavePedalAdjusted = waveLowPassPost * instrument->volumePedalModifier;
// if(waveVolumeAdjusted > peak) {
// peak = waveVolumeAdjusted;
// newPeakLogged = NO;
// }
//
// if(!newPeakLogged && [NSDate timeIntervalSinceReferenceDate] - lastPeakLog > 0.05) {
// newPeakLogged = YES;
// lastPeakLog = [NSDate timeIntervalSinceReferenceDate];
//// NSLog(@"peak: %.2f", peak);
// }
float compressPost = waveshape_distort(wavePedalAdjusted);
deviceBuffer[i] = (SInt16) (compressPost * 32767);
}
//GSB 20100815 v1.2 wave recording
// initialize wavOutAudioFile elsewhere
if(instrument->wavOutAudioFile != nil) {
// prepare inBuffer (contains mAudioDataByteSize and mAudioDate)
AudioStreamPacketDescription* inPacketDescs = nil; // this will probably choke
AudioStreamPacketDescription foo; // if we must use this, here's a pass:
foo.mStartOffset = 0l;
foo.mVariableFramesInPacket = 0;
foo.mDataByteSize = kNumBytesPerPacket; // 2
// Apple: "For all uncompressed formats, this function equates packets with frames."
// http://developer.apple.com/mac/library/documentation/MusicAudio/Reference/AudioFileConvertRef/Reference/reference.html#//apple_ref/c/func/AudioFileWritePackets
UInt32 inNumberPackets = inNumberFrames;
OSStatus status = AudioFileWritePackets(instrument->wavOutAudioFile,
false,
inNumberFrames * kNumBytesPerPacket,
inPacketDescs,
instrument->wavOutCurrentPacket,
&inNumberPackets,
deviceBuffer);
if(status == 0)
{
instrument->wavOutCurrentPacket += inNumberPackets;
}
}
//GSB 20100815 /v1.2 wave recording
//free(clipProofDeviceBuffer);
free(floatDeviceBuffer);
return noErr;
}
#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
-(void) startRecordWavOut {
NSLog(@"I: startRecordWavOut: BEGIN");
wavOutCurrentPacket = 0;
NSURL *audioFileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/hexaphone-export.wav", DOCUMENTS_FOLDER]];
//TODO audioFormat
// from web:
// AudioStreamBasicDescription audioFormat;
// audioFormat.mFormatID = kAudioFormatLinearPCM;
// audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger
// | kAudioFormatFlagsNativeEndian
// | kLinearPCMFormatFlagIsNonInterleaved
// | (24 << kLinearPCMFormatFlagsSampleFractionShift);
// audioFormat.mSampleRate = 44100;
// audioFormat.mBitsPerChannel = 32;
// audioFormat.mChannelsPerFrame = 1;
// audioFormat.mFramesPerPacket = 1;
// audioFormat.mBytesPerFrame = (audioFormat.mBitsPerChannel / 8);
// audioFormat.mBytesPerPacket = audioFormat.mBytesPerFrame * audioFormat.mFramesPerPacket;
// from audiounit init:
AudioStreamBasicDescription audioFormat;
audioFormat.mSampleRate= 44100.00;
audioFormat.mFormatID= kAudioFormatLinearPCM;
audioFormat.mFormatFlags= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
audioFormat.mFramesPerPacket= 1;
audioFormat.mChannelsPerFrame= 1;
audioFormat.mBitsPerChannel= 16;
audioFormat.mBytesPerPacket= 2;
audioFormat.mBytesPerFrame= 2;
OSStatus status = AudioFileCreateWithURL (
(CFURLRef) audioFileURL,
kAudioFileWAVEType,
&audioFormat,
kAudioFileFlags_EraseFile,
&wavOutAudioFile
);
if(status != 0) {
NSLog(@"I: startRecordWavOut: error status: %d", status);
}
}
-(void) stopRecordWavOut {
NSLog(@"I: stopRecordWavOut: BEGIN");
OSStatus status = AudioFileClose(wavOutAudioFile);
if(status != 0) {
NSLog(@"I: stopRecordWavOut: error status: %d", status);
}
wavOutAudioFile = nil;
}
-(void) initRemoteIO {
// NSLog(@"Instrument: initRemoteIO");
OSStatus status;
// Describe audio component
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_RemoteIO;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
// Get component
AudioComponent inputComponent = AudioComponentFindNext(NULL, &desc);
// Get audio units
status = AudioComponentInstanceNew(inputComponent, &_audioUnit);
// DISABLE IO for recording
UInt32 enableInputFlag = 0;
status = AudioUnitSetProperty(_audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Input,
kInputBus,
&enableInputFlag,
sizeof(enableInputFlag));
// Enable IO for playback
UInt32 enableOutputFlag = 1;
status = AudioUnitSetProperty(_audioUnit,
kAudioOutputUnitProperty_EnableIO,
kAudioUnitScope_Output,
kOutputBus,
&enableOutputFlag,
sizeof(enableOutputFlag));
// Describe format
AudioStreamBasicDescription audioFormat;
audioFormat.mSampleRate= 44100.00;
audioFormat.mFormatID= kAudioFormatLinearPCM;
audioFormat.mFormatFlags= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
audioFormat.mFramesPerPacket= 1;
audioFormat.mChannelsPerFrame= 1;
audioFormat.mBitsPerChannel= 16;
audioFormat.mBytesPerPacket= 2;
audioFormat.mBytesPerFrame= 2;
AudioUnitSetProperty(_audioUnit, kAudioUnitProperty_StreamFormat,
kAudioUnitScope_Input, kOutputBus, &audioFormat, sizeof(audioFormat));
// Apply format (for output)
//GSB: disabling as per alex
// status = AudioUnitSetProperty(_audioUnit,
// kAudioUnitProperty_StreamFormat,
// kAudioUnitScope_Output,
// kInputBus,
// &audioFormat,
// sizeof(audioFormat));
// [self checkStatus:status];
// //GSB: for lower latency / smaller buffer size: https://devforums.apple.com/message/16446#16446
// Float32 preferredBufferSize = 0.005;
// AudioSessionSetProperty(kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof(preferredBufferSize), &preferredBufferSize);
//GSB: no need to do for input
// status = AudioUnitSetProperty(_audioUnit,
// kAudioUnitProperty_StreamFormat,
// kAudioUnitScope_Input,
// kOutputBus,
// &audioFormat,
// sizeof(audioFormat));
// [self checkStatus:status];
//GSB: adding:
AURenderCallbackStruct callbackStruct;
callbackStruct.inputProc = playbackCallback;
callbackStruct.inputProcRefCon = self;
status = AudioUnitSetProperty(_audioUnit,
kAudioUnitProperty_SetRenderCallback,
kAudioUnitScope_Global,
kOutputBus,
&callbackStruct,
sizeof(callbackStruct));
//GSB: no recorder config needed - but should set this for output, no?
// from pastie: http://pastie.org/pastes/219616
// UInt32 shouldAllocateBuffer = 1;
// AudioUnitSetProperty(instance, kAudioUnitProperty_ShouldAllocateBuffer, kAudioUnitScope_Global, 1, &shouldAllocateBuffer, sizeof(shouldAllocateBuffer));
// // Disable buffer allocation for the recorder
// UInt32 shouldAllocateBuffer = 0;
// status = AudioUnitSetProperty(_audioUnit,
// kAudioUnitProperty_ShouldAllocateBuffer,
// kAudioUnitScope_Output,
// kInputBus,
// &shouldAllocateBuffer,
// sizeof(shouldAllocateBuffer));
//GSB: need to set the following callback (from pastie)?
// err = AudioUnitSetProperty(instance, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callback_struct, sizeof(callback_struct));
//calculate number of buffers from channels
//malloc buffer lists
// UInt32 nchannels = 1;
// //http://lists.apple.com/archives/coreaudio-api/2005/Nov/msg00252.html
// _mSampleBufferList = (AudioBufferList *)malloc(offsetof(AudioBufferList, mBuffers) + nchannels * sizeof(AudioBuffer));
// _mSampleBufferList->mNumberBuffers = 1;
//
//
// //TODO: for each note
//
// AudioFileID fileID = [IDAudioUtils openAudioFile:[[NSBundle mainBundle] pathForResource:@"Organ838-C4-LEI16" ofType:@"caf"]];
// //AudioFileID fileID = [IDAudioUtils openAudioFile:[[NSBundle mainBundle] pathForResource:@"Sick_IIe_C3dub" ofType:@"caf"]];
// //AudioFileID fileID = [IDAudioUtils openAudioFile:[[NSBundle mainBundle] pathForResource:@"Sick_IIe_Gb1" ofType:@"caf"]];
// UInt32 fileSize = [IDAudioUtils audioFileSize:fileID];
//
//// unsigned char * outData = malloc(fileSize);
//// // get the bytes from the file and put them into the data buffer
//// status = AudioFileReadBytes(fileID, false, 0, &fileSize, outData);
//
//
// //GSB: AudioFileReadPackets, from MT's blog
// SInt64 position = 0;
// UInt32 numPackets = fileSize / kNumBytesPerPacket;
// UInt32 numBytesRead;
// SInt16 *fileBuffer = malloc(fileSize);
// status = AudioFileReadPackets(fileID, NO, &numBytesRead, NULL, position, &numPackets, fileBuffer);
// [IDAudioUtils closeAudioFile:fileID];
// UInt32 numFramesRead = numBytesRead / 2;
//
//// for ( int i=0; i<numBytesRead / 2; i++ ) {
//// NSLog(@"fileBuffer: %d", (SInt16) fileBuffer[i]);
//// }
//
//
//
// UInt32 sourceFrameCount = numBytesRead / 2;
// for ( int i=0; i<sourceFrameCount; i++ ) {
// NSLog(@"sourceBuffer: %d", (SInt16) fileBuffer[i]);
// }
//
//
// float halfStepAdj = 5.0f; //float freq_mult = pow(2,halfstep_adj/12.0f); // 2^(h/12)
// Float32 frequencyMultiplier = pow(2,halfStepAdj/12.0f); // 2^(h/12)
// NSLog(@"frequencyMultiplier = %f", frequencyMultiplier);
// UInt32 destFrameCount = floor(sourceFrameCount / frequencyMultiplier);
//
// SInt16 *transposedBuffer = [self createTransposedBufferFrom:fileBuffer sourceFrameCount:numFramesRead destFrameCount:destFrameCount];
// for ( int i=0; i<destFrameCount; i++ ) {
// NSLog(@"transposedBuffer: %d", (SInt16) transposedBuffer[i]);
// }
//
//
//
//
// _mSampleBufferList->mBuffers[0].mData = transposedBuffer;
// _mSampleBufferList->mBuffers[0].mDataByteSize = destFrameCount * 2;
// _mSampleBufferList->mBuffers[0].mNumberChannels = 1;
//
// for ( int i=0; i<_mSampleBufferList->mBuffers[0].mDataByteSize / 2; i++ ) {
// NSLog(@"_mSampleBufferList->mBuffers[0].mData[+%3d]: %d", i, *((SInt16*)_mSampleBufferList->mBuffers[0].mData + i));
// }
[self clearRIO];
// Initialise
status = AudioUnitInitialize(_audioUnit);
// // fire it up!
// status = AudioOutputUnitStart(_audioUnit);
// NSLog(@"AudioOutputUnitStart: got status %d", status);
// AudioStreamBasicDescription remoteIODeviceFormat;
// UInt32 size = sizeof(AudioStreamBasicDescription);
// AudioUnitGetProperty(_audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &remoteIODeviceFormat, &size);
// //GSB: this yielded
// // mSampleRate 44100
// // mFormatId 1819304813
// // mFormatFlags 12
// // mBytesPerPacket 2
// // mFramesPerPacket 1
// // mBytesPerFrame 2
// // mChannelsPerFrame 1
// // mBitsPerChannel 16
// // mReserved 0
// NSLog(@"remoteIODeviceFormat.mSampleRate: %f", remoteIODeviceFormat.mSampleRate);
// NSLog(@"remoteIODeviceFormat.mFormatID: %d", remoteIODeviceFormat.mFormatID);
// NSLog(@"remoteIODeviceFormat.mFormatFlags: %x", remoteIODeviceFormat.mFormatFlags);
// NSLog(@"remoteIODeviceFormat.mFramesPerPacket: %d", remoteIODeviceFormat.mFramesPerPacket);
// NSLog(@"remoteIODeviceFormat.mChannelsPerFrame: %d", remoteIODeviceFormat.mChannelsPerFrame);
// NSLog(@"remoteIODeviceFormat.mBitsPerChannel: %d", remoteIODeviceFormat.mBitsPerChannel);
// NSLog(@"remoteIODeviceFormat.mBytesPerPacket: %d", remoteIODeviceFormat.mBytesPerPacket);
// NSLog(@"remoteIODeviceFormat.mBytesPerFrame: %d", remoteIODeviceFormat.mBytesPerFrame);
}
#define kBytesPerFrame 2
-(SInt16*) createTransposedBufferFrom:(SInt16*)sourceBuffer sourceFrameCount:(UInt32)sourceFrameCount destFrameCount:(UInt32)destFrameCount {
//NSLog(@"Instrument: -createTransposedBuffer...: sf:%d df:%d ", sourceFrameCount, destFrameCount);
// // half step up: 1.05946;
// // half step down: .94387
Float32 frequencyMultiplier = (Float32) sourceFrameCount / (Float32) destFrameCount;
//NSLog(@"Instrument: -createTransposedBuffer...: frequencyMultiplier = %f", frequencyMultiplier);
// for ( int i=0; i<sourceFrameCount; i++ ) {
// NSLog(@"sourceBuffer: %d", (SInt16) sourceBuffer[i]);
// }
SInt16 *destBuffer = malloc(destFrameCount * kBytesPerFrame);
Float32 idxTarget; // the extrapolated, floating-point index for the target value
UInt16 idxPrevNeighbor, idxNextNeighbor; // the indicies of the two "nearest neighbors" to the target value
Float32 nextNeighborBias; // to what degree we should weight one neighbor over the other (out of 100%)
Float32 prevNeighborBias; // 100% - nextNeighborBias; included for readability - could just divide by next for a performance improvement
// for each desired frame for the destination buffer:
for(int idxDest=0; idxDest<destFrameCount; idxDest++) {
idxTarget = idxDest * frequencyMultiplier;
idxPrevNeighbor = floor(idxTarget);
idxNextNeighbor = ceil(idxTarget);
if(idxNextNeighbor >= sourceFrameCount) {
// loop around - don't overflow!
idxNextNeighbor = 0;
}
// if target index is [4.78], use [4] (prev) with a 22% weighting, and [5] (next) with a 78% weighting
nextNeighborBias = idxTarget - idxPrevNeighbor;
prevNeighborBias = 1.0 - nextNeighborBias;
Float32 interpolatedValue = sourceBuffer[idxPrevNeighbor] * prevNeighborBias
+ sourceBuffer[idxNextNeighbor] * nextNeighborBias;
destBuffer[idxDest] = round(interpolatedValue); // convert to int, store
}
// for ( int i=0; i<destFrameCount; i++ ) {
// NSLog(@"destBuffer: %d", (SInt16) destBuffer[i]);
// }
return destBuffer;
}
//-(Key*) getKey:(UInt32) keyNumber {
// Key** keysArray = (Key**)[_keysData bytes];
//
// Key** keyPtr = keysArray + keyNumber;
//
// return *keyPtr;
//
//}