Debian Codegraph @

iOS/Csound iOS Obj-C Examples/csound-iOS/classes/CsoundObj.m

raw
1 /*
2
3 CsoundObj.m:
4
5 Copyright (C) 2014 Steven Yi, Victor Lazzarini, Aurelius Prochazka
6
7 This file is part of Csound for iOS.
8
9 The Csound for iOS Library is free software; you can redistribute it
10 and/or modify it under the terms of the GNU Lesser General Public
11 License as published by the Free Software Foundation; either
12 version 2.1 of the License, or (at your option) any later version.
13
14 Csound is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU Lesser General Public License for more details.
18
19 You should have received a copy of the GNU Lesser General Public
20 License along with Csound; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 02111-1307 USA
23
24 */
25
26 #import <AudioToolbox/AudioConverter.h>
27 #import <AudioToolbox/AudioServices.h>
28 #import <AVFoundation/AVFoundation.h>
29
30 #import "CsoundObj.h"
31 #import "CsoundMIDI.h"
32
33 OSStatus Csound_Render(void *inRefCon,
34 AudioUnitRenderActionFlags *ioActionFlags,
35 const AudioTimeStamp *inTimeStamp,
36 UInt32 dump,
37 UInt32 inNumberFrames,
38 AudioBufferList *ioData);
39 void InterruptionListener(void *inClientData, UInt32 inInterruption);
40
41 @interface CsoundObj() {
42 NSMutableArray *listeners;
43 csdata mCsData;
44 id mMessageListener;
45 }
46
47 - (void)runCsound:(NSString *)csdFilePath;
48 - (void)runCsoundToDisk:(NSArray *)paths;
49
50 @end
51
52 @implementation CsoundObj
53
54 - (id)init
55 {
56 self = [super init];
57 if (self) {
58 mCsData.shouldMute = false;
59 _bindings = [[NSMutableArray alloc] init];
60 listeners = [[NSMutableArray alloc] init];
61 _midiInEnabled = NO;
62 _useAudioInput = NO;
63 }
64
65 return self;
66 }
67
68 // -----------------------------------------------------------------------------
69 # pragma mark - CsoundObj Interface
70 // -----------------------------------------------------------------------------
71
72 - (void)sendScore:(NSString *)score
73 {
74 if (mCsData.cs != NULL) {
75 csoundReadScore(mCsData.cs, (char*)[score cStringUsingEncoding:NSASCIIStringEncoding]);
76 }
77 }
78
79 - (void)play:(NSString *)csdFilePath
80 {
81 mCsData.shouldRecord = false;
82 [self performSelectorInBackground:@selector(runCsound:) withObject:csdFilePath];
83 }
84
85 - (void)updateOrchestra:(NSString *)orchestraString
86 {
87 if (mCsData.cs != NULL) {
88 csoundCompileOrc(mCsData.cs, (char*)[orchestraString cStringUsingEncoding:NSASCIIStringEncoding]);
89 }
90 }
91
92 - (void)stop {
93 mCsData.running = false;
94 }
95
96 - (void)mute {
97 mCsData.shouldMute = true;
98 }
99
100 - (void)unmute {
101 mCsData.shouldMute = false;
102 }
103
104 // -----------------------------------------------------------------------------
105 # pragma mark - Recording
106 // -----------------------------------------------------------------------------
107
108 - (void)record:(NSString *)csdFilePath toURL:(NSURL *)outputURL
109 {
110 mCsData.shouldRecord = true;
111 self.outputURL = outputURL;
112 [self performSelectorInBackground:@selector(runCsound:) withObject:csdFilePath];
113 }
114
115 - (void)record:(NSString *)csdFilePath toFile:(NSString *)outputFile
116 {
117 mCsData.shouldRecord = false;
118
119 [self performSelectorInBackground:@selector(runCsoundToDisk:)
120 withObject:[NSMutableArray arrayWithObjects:csdFilePath, outputFile, nil]];
121 }
122
123 - (void)recordToURL:(NSURL *)outputURL_
124 {
125 // Define format for the audio file.
126 AudioStreamBasicDescription destFormat, clientFormat;
127 memset(&destFormat, 0, sizeof(AudioStreamBasicDescription));
128 memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
129 destFormat.mFormatID = kAudioFormatLinearPCM;
130 destFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger;
131 destFormat.mSampleRate = csoundGetSr(mCsData.cs);
132 destFormat.mChannelsPerFrame = mCsData.nchnls;
133 destFormat.mBytesPerPacket = mCsData.nchnls * 2;
134 destFormat.mBytesPerFrame = mCsData.nchnls * 2;
135 destFormat.mBitsPerChannel = 16;
136 destFormat.mFramesPerPacket = 1;
137
138 // Create the audio file.
139 OSStatus err = noErr;
140 CFURLRef fileURL = (__bridge CFURLRef)outputURL_;
141 err = ExtAudioFileCreateWithURL(fileURL, kAudioFileWAVEType, &destFormat, NULL, kAudioFileFlags_EraseFile, &(mCsData.file));
142 if (err == noErr) {
143 // Get the stream format from the AU...
144 UInt32 propSize = sizeof(AudioStreamBasicDescription);
145 AudioUnitGetProperty(*(mCsData.aunit), kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &clientFormat, &propSize);
146 // ...and set it as the client format for the audio file. The file will use this
147 // format to perform any necessary conversions when asked to read or write.
148 ExtAudioFileSetProperty(mCsData.file, kExtAudioFileProperty_ClientDataFormat, sizeof(clientFormat), &clientFormat);
149 // Warm the file up.
150 ExtAudioFileWriteAsync(mCsData.file, 0, NULL);
151 } else {
152 printf("***Not recording. Error: %d\n", (int)err);
153 err = noErr;
154 }
155
156 mCsData.shouldRecord = true;
157 }
158
159 - (void)stopRecording
160 {
161 mCsData.shouldRecord = false;
162 ExtAudioFileDispose(mCsData.file);
163 }
164
165 // -----------------------------------------------------------------------------
166 # pragma mark - Bindings
167 // -----------------------------------------------------------------------------
168
169 - (void)addBinding:(id<CsoundBinding>)binding
170 {
171 if (binding != nil) {
172 if (mCsData.running) [binding setup:self];
173 [_bindings addObject:binding];
174 }
175 }
176
177 - (void)removeBinding:(id<CsoundBinding>)binding
178 {
179 if (binding != nil && [_bindings containsObject:binding]) {
180 [_bindings removeObject:binding];
181 }
182 }
183
184 - (void)setupBindings
185 {
186 for (int i = 0; i < _bindings.count; i++) {
187 id<CsoundBinding> binding = [_bindings objectAtIndex:i];
188 [binding setup:self];
189 }
190 }
191
192 - (void)cleanupBindings
193 {
194 for (int i = 0; i < _bindings.count; i++) {
195 id<CsoundBinding> binding = [_bindings objectAtIndex:i];
196 if ([binding respondsToSelector:@selector(cleanup)]) {
197 [binding cleanup];
198 }
199 }
200 }
201
202 - (void)updateAllValuesToCsound
203 {
204 for (int i = 0; i < _bindings.count; i++) {
205 id<CsoundBinding> binding = [_bindings objectAtIndex:i];
206 if ([binding respondsToSelector:@selector(updateValuesToCsound)]) {
207 [binding updateValuesToCsound];
208 }
209 }
210 }
211
212 // -----------------------------------------------------------------------------
213 # pragma mark - Listeners and Messages
214 // -----------------------------------------------------------------------------
215
216 - (void)addListener:(id<CsoundObjListener>)listener {
217 [listeners addObject:listener];
218 }
219
220 - (void)notifyListenersOfStartup
221 {
222 for (id<CsoundObjListener> listener in listeners) {
223 if ([listener respondsToSelector:@selector(csoundObjStarted:)]) {
224 [listener csoundObjStarted:self];
225 }
226 }
227 }
228 - (void)notifyListenersOfCompletion
229 {
230 for (id<CsoundObjListener> listener in listeners) {
231 if ([listener respondsToSelector:@selector(csoundObjCompleted:)]) {
232 [listener csoundObjCompleted:self];
233 }
234 }
235 }
236
237 static void messageCallback(CSOUND *cs, int attr, const char *format, va_list valist)
238 {
239 @autoreleasepool {
240 CsoundObj *obj = (__bridge CsoundObj *)(csoundGetHostData(cs));
241 Message info;
242 info.cs = cs;
243 info.attr = attr;
244 info.format = format;
245 va_copy(info.valist,valist);
246 NSValue *infoObj = [NSValue value:&info withObjCType:@encode(Message)];
247 [obj performSelector:@selector(performMessageCallback:) withObject:infoObj];
248 }
249 }
250
251 - (void)setMessageCallback:(SEL)method withListener:(id)listener
252 {
253 self.messageCallbackSelector = method;
254 mMessageListener = listener;
255 }
256
257 - (void)performMessageCallback:(NSValue *)infoObj
258 {
259 #pragma clang diagnostic push
260 #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
261 [mMessageListener performSelector:self.messageCallbackSelector withObject:infoObj];
262 #pragma clang diagnostic pop
263 }
264
265 // -----------------------------------------------------------------------------
266 # pragma mark - Csound Internals / Advanced Methods
267 // -----------------------------------------------------------------------------
268
269 - (CSOUND *)getCsound
270 {
271 if (!mCsData.running) {
272 return NULL;
273 }
274 return mCsData.cs;
275 }
276
277 - (AudioUnit *)getAudioUnit
278 {
279 if (!mCsData.running) {
280 return NULL;
281 }
282 return mCsData.aunit;
283 }
284
285 - (MYFLT *)getInputChannelPtr:(NSString *)channelName channelType:(controlChannelType)channelType
286 {
287 MYFLT *value;
288 csoundGetChannelPtr(mCsData.cs, &value, [channelName cStringUsingEncoding:NSASCIIStringEncoding],
289 channelType | CSOUND_INPUT_CHANNEL);
290 return value;
291 }
292
293 - (MYFLT *)getOutputChannelPtr:(NSString *)channelName channelType:(controlChannelType)channelType
294 {
295 MYFLT *value;
296 csoundGetChannelPtr(mCsData.cs, &value, [channelName cStringUsingEncoding:NSASCIIStringEncoding],
297 channelType | CSOUND_OUTPUT_CHANNEL);
298 return value;
299 }
300
301 - (NSData *)getOutSamples
302 {
303 if (!mCsData.running) {
304 return nil;
305 }
306 CSOUND *csound = [self getCsound];
307 float *spout = csoundGetSpout(csound);
308 int nchnls = csoundGetNchnls(csound);
309 int ksmps = csoundGetKsmps(csound);
310 NSData* data = [NSData dataWithBytes:spout length:(nchnls * ksmps * sizeof(MYFLT))];
311 return data;
312 }
313
314 - (int)getNumChannels
315 {
316 if (!mCsData.running) {
317 return -1;
318 }
319 return csoundGetNchnls(mCsData.cs);
320 }
321
322 - (int)getKsmps
323 {
324 if (!mCsData.running) {
325 return -1;
326 }
327 return csoundGetKsmps(mCsData.cs);
328 }
329
330 #pragma mark Csound Code
331
332 OSStatus Csound_Render(void *inRefCon,
333 AudioUnitRenderActionFlags *ioActionFlags,
334 const AudioTimeStamp *inTimeStamp,
335 UInt32 dump,
336 UInt32 inNumberFrames,
337 AudioBufferList *ioData)
338 {
339 csdata *cdata = (csdata *) inRefCon;
340 int ret = cdata->ret, nchnls = cdata->nchnls;
341 float coef = (float) INT_MAX / csoundGet0dBFS(cdata->cs);
342 CSOUND *cs = cdata->cs;
343
344 int k;
345 int frame;
346 int nsmps = cdata->nsmps;
347 int insmps = nsmps;
348 int ksmps = csoundGetKsmps(cs);
349 MYFLT *spin = csoundGetSpin(cs);
350 MYFLT *spout = csoundGetSpout(cs);
351 SInt32 *buffer;
352
353 AudioUnitRender(*cdata->aunit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
354 NSMutableArray* cache = cdata->valuesCache;
355
356
357 for(frame=0;frame < inNumberFrames;frame++){
358
359 if(cdata->useAudioInput) {
360 for (k = 0; k < nchnls; k++){
361 buffer = (SInt32 *) ioData->mBuffers[k].mData;
362 spin[insmps++] =(1./coef)*buffer[frame];
363 }
364 }
365
366 for (k = 0; k < nchnls; k++) {
367 buffer = (SInt32 *) ioData->mBuffers[k].mData;
368 if (cdata->shouldMute == false) {
369 buffer[frame] = (SInt32) lrintf(spout[nsmps++]*coef) ;
370 } else {
371 buffer[frame] = 0;
372 }
373 }
374
375 if(nsmps == ksmps*nchnls){
376 for (int i = 0; i < cache.count; i++) {
377 id<CsoundBinding> binding = [cache objectAtIndex:i];
378 if ([binding respondsToSelector:@selector(updateValuesToCsound)]) {
379 [binding updateValuesToCsound];
380 }
381 }
382 if(!ret) {
383 ret = csoundPerformKsmps(cdata->cs);
384 } else {
385 cdata->running = false;
386 }
387 for (int i = 0; i < cache.count; i++) {
388 id<CsoundBinding> binding = [cache objectAtIndex:i];
389 if ([binding respondsToSelector:@selector(updateValuesFromCsound)]) {
390 [binding updateValuesFromCsound];
391 }
392 }
393 insmps = nsmps = 0;
394 }
395
396 }
397
398 // Write to file.
399 if (cdata->shouldRecord) {
400 OSStatus err = ExtAudioFileWriteAsync(cdata->file, inNumberFrames, ioData);
401 if (err != noErr) {
402 printf("***Error writing to file: %d\n", (int)err);
403 }
404 }
405
406 cdata->nsmps = nsmps;
407 cdata->ret = ret;
408 return 0;
409 }
410
411 - (void)runCsoundToDisk:(NSArray *)paths
412 {
413 @autoreleasepool {
414
415 CSOUND *cs;
416
417 cs = csoundCreate(NULL);
418
419 const char *argv[4] = { "csound",
420 (char*)[[paths objectAtIndex:0] cStringUsingEncoding:NSASCIIStringEncoding], "-o", (char*)[[paths objectAtIndex:1] cStringUsingEncoding:NSASCIIStringEncoding]};
421 int ret = csoundCompile(cs, 4, argv);
422
423 [self setupBindings];
424 [self notifyListenersOfStartup];
425
426 [self updateAllValuesToCsound];
427
428 if(!ret) {
429 csoundPerform(cs);
430 csoundCleanup(cs);
431 csoundDestroy(cs);
432 }
433
434 [self cleanupBindings];
435 [self notifyListenersOfCompletion];
436 }
437 }
438
439 - (void)runCsound:(NSString *)csdFilePath
440 {
441 @autoreleasepool {
442 CSOUND *cs;
443 NSError* error;
444 BOOL success;
445
446 cs = csoundCreate(NULL);
447 csoundSetHostImplementedAudioIO(cs, 1, 0);
448
449 csoundSetMessageCallback(cs, messageCallback);
450 csoundSetHostData(cs, (__bridge void *)(self));
451
452 if (_midiInEnabled) {
453 [CsoundMIDI setMidiInCallbacks:cs];
454 }
455
456 const char *argv[2] = { "csound", (char*)[csdFilePath cStringUsingEncoding:NSASCIIStringEncoding]};
457 int ret = csoundCompile(cs, 2, argv);
458 mCsData.running = true;
459 mCsData.nsmps = 0;
460
461 if(!ret) {
462
463 mCsData.cs = cs;
464 mCsData.ret = ret;
465 mCsData.nchnls = csoundGetNchnls(cs);
466 mCsData.bufframes = (csoundGetOutputBufferSize(cs))/mCsData.nchnls;
467 mCsData.running = true;
468 mCsData.valuesCache = _bindings;
469 mCsData.useAudioInput = _useAudioInput;
470 AudioStreamBasicDescription format;
471 OSStatus err;
472
473 [self setupBindings];
474
475 /* Audio Session handler */
476 AVAudioSession* session = [AVAudioSession sharedInstance];
477
478 if (_useAudioInput) {
479 success = [session setCategory:AVAudioSessionCategoryPlayAndRecord
480 withOptions:(AVAudioSessionCategoryOptionMixWithOthers |
481 AVAudioSessionCategoryOptionDefaultToSpeaker)
482 error:&error];
483 } else {
484 success = [session setCategory:AVAudioSessionCategoryPlayback
485 withOptions:(AVAudioSessionCategoryOptionMixWithOthers | AVAudioSessionCategoryOptionDefaultToSpeaker)
486 error:&error];
487 }
488
489
490 // success = [session overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:&error];
491
492 Float32 preferredBufferSize = mCsData.bufframes / csoundGetSr(cs);
493 [session setPreferredIOBufferDuration:preferredBufferSize error:&error];
494
495 success = [session setActive:YES error:&error];
496 if(!success) {
497
498 }
499
500 [[NSNotificationCenter defaultCenter] addObserver:self
501 selector:@selector(handleInterruption:)
502 name:AVAudioSessionInterruptionNotification
503 object:session];
504
505 AudioComponentDescription cd = {kAudioUnitType_Output, kAudioUnitSubType_RemoteIO, kAudioUnitManufacturer_Apple, 0, 0};
506 AudioComponent HALOutput = AudioComponentFindNext(NULL, &cd);
507
508 AudioUnit csAUHAL;
509 err = AudioComponentInstanceNew(HALOutput, &csAUHAL);
510
511 if(!err) {
512
513 mCsData.aunit = &csAUHAL;
514 UInt32 enableIO = 1;
515 AudioUnitSetProperty(csAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, 0, &enableIO, sizeof(enableIO));
516 if (_useAudioInput) {
517 AudioUnitSetProperty(csAUHAL, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &enableIO, sizeof(enableIO));
518 }
519
520 if (enableIO) {
521 UInt32 maxFPS;
522 UInt32 outsize;
523 int elem;
524 for(elem = _useAudioInput ? 1 : 0; elem >= 0; elem--){
525 outsize = sizeof(maxFPS);
526 AudioUnitGetProperty(csAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, elem, &maxFPS, &outsize);
527 AudioUnitSetProperty(csAUHAL, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, elem, (UInt32*)&(mCsData.bufframes), sizeof(UInt32));
528 outsize = sizeof(AudioStreamBasicDescription);
529 AudioUnitGetProperty(csAUHAL, kAudioUnitProperty_StreamFormat, (elem ? kAudioUnitScope_Output : kAudioUnitScope_Input), elem, &format, &outsize);
530 format.mSampleRate = csoundGetSr(cs);
531 format.mFormatID = kAudioFormatLinearPCM;
532 format.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kLinearPCMFormatFlagIsNonInterleaved;
533 format.mBytesPerPacket = sizeof(SInt32);
534 format.mFramesPerPacket = 1;
535 format.mBytesPerFrame = sizeof(SInt32);
536 format.mChannelsPerFrame = mCsData.nchnls;
537 format.mBitsPerChannel = sizeof(SInt32)*8;
538 err = AudioUnitSetProperty(csAUHAL, kAudioUnitProperty_StreamFormat, (elem ? kAudioUnitScope_Output : kAudioUnitScope_Input), elem, &format, sizeof(AudioStreamBasicDescription));
539 }
540
541 if (mCsData.shouldRecord) {
542
543 // Define format for the audio file.
544 AudioStreamBasicDescription destFormat, clientFormat;
545 memset(&destFormat, 0, sizeof(AudioStreamBasicDescription));
546 memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
547 destFormat.mFormatID = kAudioFormatLinearPCM;
548 destFormat.mFormatFlags = kLinearPCMFormatFlagIsPacked | kLinearPCMFormatFlagIsSignedInteger;
549 destFormat.mSampleRate = csoundGetSr(cs);
550 destFormat.mChannelsPerFrame = mCsData.nchnls;
551 destFormat.mBytesPerPacket = mCsData.nchnls * 2;
552 destFormat.mBytesPerFrame = mCsData.nchnls * 2;
553 destFormat.mBitsPerChannel = 16;
554 destFormat.mFramesPerPacket = 1;
555
556 // Create the audio file.
557 CFURLRef fileURL = (__bridge CFURLRef)self.outputURL;
558 err = ExtAudioFileCreateWithURL(fileURL, kAudioFileWAVEType, &destFormat, NULL, kAudioFileFlags_EraseFile, &(mCsData.file));
559 if (err == noErr) {
560 // Get the stream format from the AU...
561 UInt32 propSize = sizeof(AudioStreamBasicDescription);
562 AudioUnitGetProperty(csAUHAL, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &clientFormat, &propSize);
563 // ...and set it as the client format for the audio file. The file will use this
564 // format to perform any necessary conversions when asked to read or write.
565 ExtAudioFileSetProperty(mCsData.file, kExtAudioFileProperty_ClientDataFormat, sizeof(clientFormat), &clientFormat);
566 // Warm the file up.
567 ExtAudioFileWriteAsync(mCsData.file, 0, NULL);
568 } else {
569 printf("***Not recording. Error: %d\n", (int)err);
570 err = noErr;
571 }
572 }
573
574 if(!err) {
575 AURenderCallbackStruct output;
576 output.inputProc = Csound_Render;
577 output.inputProcRefCon = &mCsData;
578 AudioUnitSetProperty(csAUHAL, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &output, sizeof(output));
579 AudioUnitInitialize(csAUHAL);
580
581 err = AudioOutputUnitStart(csAUHAL);
582
583 [self notifyListenersOfStartup];
584
585 if(!err) {
586 while (!mCsData.ret && mCsData.running) {
587 [NSThread sleepForTimeInterval:.001];
588 }
589 }
590
591 ExtAudioFileDispose(mCsData.file);
592 mCsData.shouldRecord = false;
593 AudioOutputUnitStop(csAUHAL);
594 /* free(CAInputData); */
595 }
596 AudioUnitUninitialize(csAUHAL);
597 AudioComponentInstanceDispose(csAUHAL);
598 }
599 }
600 csoundDestroy(cs);
601 }
602
603 mCsData.running = false;
604
605 [self cleanupBindings];
606 [self notifyListenersOfCompletion];
607 }
608 }
609
610 - (void)handleInterruption:(NSNotification *)notification
611 {
612 NSDictionary *interuptionDict = notification.userInfo;
613 NSUInteger interuptionType = (NSUInteger)[interuptionDict
614 valueForKey:AVAudioSessionInterruptionTypeKey];
615
616 NSError *error;
617 BOOL success;
618
619 if (mCsData.running) {
620 if (interuptionType == AVAudioSessionInterruptionTypeBegan) {
621 AudioOutputUnitStop(*(mCsData.aunit));
622 } else if (interuptionType == kAudioSessionEndInterruption) {
623 // make sure we are again the active session
624 success = [[AVAudioSession sharedInstance] setActive:YES error:&error];
625 if(success) {
626 AudioOutputUnitStart(*(mCsData.aunit));
627 }
628 }
629 }
630 }
631
632 @end