Merge pull request #40 from nphilipp/develop--py3k-fixes
[aubio.git] / src / io / sink_apple_audio.c
1 /*
2   Copyright (C) 2012-2014 Paul Brossier <piem@aubio.org>
3
4   This file is part of aubio.
5
6   aubio is free software: you can redistribute it and/or modify
7   it under the terms of the GNU General Public License as published by
8   the Free Software Foundation, either version 3 of the License, or
9   (at your option) any later version.
10
11   aubio is distributed in the hope that it will be useful,
12   but WITHOUT ANY WARRANTY; without even the implied warranty of
13   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14   GNU General Public License for more details.
15
16   You should have received a copy of the GNU General Public License
17   along with aubio.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "config.h"
22
23 #ifdef HAVE_SINK_APPLE_AUDIO
24
25 #include "aubio_priv.h"
26 #include "fvec.h"
27 #include "fmat.h"
28 #include "io/sink_apple_audio.h"
29
30 // CFURLRef, CFURLCreateWithFileSystemPath, ...
31 #include <CoreFoundation/CoreFoundation.h>
32 // ExtAudioFileRef, AudioStreamBasicDescription, AudioBufferList, ...
33 #include <AudioToolbox/AudioToolbox.h>
34
35 #define FLOAT_TO_SHORT(x) (short)(x * 32768)
36
37 extern int createAubioBufferList(AudioBufferList *bufferList, int channels, int segmentSize);
38 extern void freeAudioBufferList(AudioBufferList *bufferList);
39 extern CFURLRef createURLFromPath(const char * path);
40 char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
41
42 uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s);
43
44 #define MAX_SIZE 4096 // the maximum number of frames that can be written at a time
45
46 void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write);
47
48 struct _aubio_sink_apple_audio_t {
49   uint_t samplerate;
50   uint_t channels;
51   char_t *path;
52
53   uint_t max_frames;
54
55   AudioBufferList bufferList;
56   ExtAudioFileRef audioFile;
57   bool async;
58 };
59
60 aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(char_t * uri, uint_t samplerate) {
61   aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
62   s->path = uri;
63   s->max_frames = MAX_SIZE;
64   s->async = false;
65
66   if (uri == NULL) {
67     AUBIO_ERROR("sink_apple_audio: Aborted opening null path\n");
68     goto beach;
69   }
70
71   s->samplerate = 0;
72   s->channels = 0;
73
74   // negative samplerate given, abort
75   if ((sint_t)samplerate < 0) goto beach;
76   // zero samplerate given. do not open yet
77   if ((sint_t)samplerate == 0) return s;
78
79   s->samplerate = samplerate;
80   s->channels = 1;
81
82   if (aubio_sink_apple_audio_open(s) != AUBIO_OK) {
83     // open failed, abort
84     goto beach;
85   }
86
87   return s;
88 beach:
89   AUBIO_FREE(s);
90   return NULL;
91 }
92
93 uint_t aubio_sink_apple_audio_preset_samplerate(aubio_sink_apple_audio_t *s, uint_t samplerate)
94 {
95   if ((sint_t)(samplerate) <= 0) return AUBIO_FAIL;
96   s->samplerate = samplerate;
97   // automatically open when both samplerate and channels have been set
98   if (s->samplerate != 0 && s->channels != 0) {
99     return aubio_sink_apple_audio_open(s);
100   }
101   return AUBIO_OK;
102 }
103
104 uint_t aubio_sink_apple_audio_preset_channels(aubio_sink_apple_audio_t *s, uint_t channels)
105 {
106   if ((sint_t)(channels) <= 0) return AUBIO_FAIL;
107   s->channels = channels;
108   // automatically open when both samplerate and channels have been set
109   if (s->samplerate != 0 && s->channels != 0) {
110     return aubio_sink_apple_audio_open(s);
111   }
112   return AUBIO_OK;
113 }
114
115 uint_t aubio_sink_apple_audio_get_samplerate(aubio_sink_apple_audio_t *s)
116 {
117   return s->samplerate;
118 }
119
120 uint_t aubio_sink_apple_audio_get_channels(aubio_sink_apple_audio_t *s)
121 {
122   return s->channels;
123 }
124
125 uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s) {
126
127   if (s->samplerate == 0 || s->channels == 0) return AUBIO_FAIL;
128
129   AudioStreamBasicDescription clientFormat;
130   memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
131   clientFormat.mFormatID         = kAudioFormatLinearPCM;
132   clientFormat.mSampleRate       = (Float64)(s->samplerate);
133   clientFormat.mFormatFlags      = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
134   clientFormat.mChannelsPerFrame = s->channels;
135   clientFormat.mBitsPerChannel   = sizeof(short) * 8;
136   clientFormat.mFramesPerPacket  = 1;
137   clientFormat.mBytesPerFrame    = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
138   clientFormat.mBytesPerPacket   = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
139   clientFormat.mReserved         = 0;
140
141   AudioFileTypeID fileType = kAudioFileWAVEType;
142   CFURLRef fileURL = createURLFromPath(s->path);
143   bool overwrite = true;
144   OSStatus err = noErr;
145   err = ExtAudioFileCreateWithURL(fileURL, fileType, &clientFormat, NULL,
146      overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
147   CFRelease(fileURL);
148   if (err) {
149     char_t errorstr[20];
150     AUBIO_ERR("sink_apple_audio: error when trying to create %s with "
151         "ExtAudioFileCreateWithURL (%s)\n", s->path,
152         getPrintableOSStatusError(errorstr, err));
153     goto beach;
154   }
155   if (createAubioBufferList(&s->bufferList, s->channels, s->max_frames * s->channels)) {
156     AUBIO_ERR("sink_apple_audio: error when creating buffer list for %s, "
157         "out of memory? \n", s->path);
158     goto beach;
159   }
160   return AUBIO_OK;
161
162 beach:
163   return AUBIO_FAIL;
164 }
165
166 void aubio_sink_apple_audio_do(aubio_sink_apple_audio_t * s, fvec_t * write_data, uint_t write) {
167   UInt32 c, v;
168   short *data = (short*)s->bufferList.mBuffers[0].mData;
169   if (write > s->max_frames) {
170     AUBIO_WRN("sink_apple_audio: trying to write %d frames, max %d\n", write, s->max_frames);
171     write = s->max_frames;
172   }
173   smpl_t *buf = write_data->data;
174
175   if (buf) {
176       for (c = 0; c < s->channels; c++) {
177           for (v = 0; v < write; v++) {
178               data[v * s->channels + c] =
179                   FLOAT_TO_SHORT(buf[ v * s->channels + c]);
180           }
181       }
182   }
183   aubio_sink_apple_audio_write(s, write);
184 }
185
186 void aubio_sink_apple_audio_do_multi(aubio_sink_apple_audio_t * s, fmat_t * write_data, uint_t write) {
187   UInt32 c, v;
188   short *data = (short*)s->bufferList.mBuffers[0].mData;
189   if (write > s->max_frames) {
190     AUBIO_WRN("sink_apple_audio: trying to write %d frames, max %d\n", write, s->max_frames);
191     write = s->max_frames;
192   }
193   smpl_t **buf = write_data->data;
194
195   if (buf) {
196       for (c = 0; c < s->channels; c++) {
197           for (v = 0; v < write; v++) {
198               data[v * s->channels + c] =
199                   FLOAT_TO_SHORT(buf[c][v]);
200           }
201       }
202   }
203   aubio_sink_apple_audio_write(s, write);
204 }
205
206 void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write) {
207   OSStatus err = noErr;
208   if (s->async) {
209     err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
210     if (err) {
211       char_t errorstr[20];
212       if (err == kExtAudioFileError_AsyncWriteBufferOverflow) {
213         sprintf(errorstr,"buffer overflow");
214       } else if (err == kExtAudioFileError_AsyncWriteTooLarge) {
215         sprintf(errorstr,"write too large");
216       } else {
217         // unknown error
218         getPrintableOSStatusError(errorstr, err);
219       }
220       AUBIO_ERROR("sink_apple_audio: error while writing %s "
221                   "in ExtAudioFileWriteAsync (%s)\n", s->path, errorstr);
222     }
223   } else {
224     err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
225     if (err) {
226       char_t errorstr[20];
227       AUBIO_ERROR("sink_apple_audio: error while writing %s "
228           "in ExtAudioFileWrite (%s)\n", s->path,
229           getPrintableOSStatusError(errorstr, err));
230     }
231   }
232 }
233
234 uint_t aubio_sink_apple_audio_close(aubio_sink_apple_audio_t * s) {
235   OSStatus err = noErr;
236   if (!s->audioFile) {
237     return AUBIO_FAIL;
238   }
239   err = ExtAudioFileDispose(s->audioFile);
240   if (err) {
241     char_t errorstr[20];
242     AUBIO_ERROR("sink_apple_audio: error while closing %s "
243         "in ExtAudioFileDispose (%s)\n", s->path,
244         getPrintableOSStatusError(errorstr, err));
245   }
246   s->audioFile = NULL;
247   return err;
248 }
249
250 void del_aubio_sink_apple_audio(aubio_sink_apple_audio_t * s) {
251   if (s->audioFile) aubio_sink_apple_audio_close (s);
252   freeAudioBufferList(&s->bufferList);
253   AUBIO_FREE(s);
254   return;
255 }
256
257 #endif /* HAVE_SINK_APPLE_AUDIO */