Merge branch 'master' into notes
[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(const char_t * uri, uint_t samplerate) {
61   aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
62   s->max_frames = MAX_SIZE;
63   s->async = false;
64
65   if (uri == NULL) {
66     AUBIO_ERROR("sink_apple_audio: Aborted opening null path\n");
67     goto beach;
68   }
69   if (s->path != NULL) AUBIO_FREE(s->path);
70   s->path = AUBIO_ARRAY(char_t, strnlen(uri, PATH_MAX) + 1);
71   strncpy(s->path, uri, strnlen(uri, PATH_MAX) + 1);
72
73   s->samplerate = 0;
74   s->channels = 0;
75
76   // negative samplerate given, abort
77   if ((sint_t)samplerate < 0) goto beach;
78   // zero samplerate given. do not open yet
79   if ((sint_t)samplerate == 0) return s;
80
81   s->samplerate = samplerate;
82   s->channels = 1;
83
84   if (aubio_sink_apple_audio_open(s) != AUBIO_OK) {
85     // open failed, abort
86     goto beach;
87   }
88
89   return s;
90 beach:
91   AUBIO_FREE(s);
92   return NULL;
93 }
94
95 uint_t aubio_sink_apple_audio_preset_samplerate(aubio_sink_apple_audio_t *s, uint_t samplerate)
96 {
97   if ((sint_t)(samplerate) <= 0) return AUBIO_FAIL;
98   s->samplerate = samplerate;
99   // automatically open when both samplerate and channels have been set
100   if (s->samplerate != 0 && s->channels != 0) {
101     return aubio_sink_apple_audio_open(s);
102   }
103   return AUBIO_OK;
104 }
105
106 uint_t aubio_sink_apple_audio_preset_channels(aubio_sink_apple_audio_t *s, uint_t channels)
107 {
108   if ((sint_t)(channels) <= 0) return AUBIO_FAIL;
109   s->channels = channels;
110   // automatically open when both samplerate and channels have been set
111   if (s->samplerate != 0 && s->channels != 0) {
112     return aubio_sink_apple_audio_open(s);
113   }
114   return AUBIO_OK;
115 }
116
117 uint_t aubio_sink_apple_audio_get_samplerate(const aubio_sink_apple_audio_t *s)
118 {
119   return s->samplerate;
120 }
121
122 uint_t aubio_sink_apple_audio_get_channels(const aubio_sink_apple_audio_t *s)
123 {
124   return s->channels;
125 }
126
127 uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s) {
128
129   if (s->samplerate == 0 || s->channels == 0) return AUBIO_FAIL;
130
131   AudioStreamBasicDescription clientFormat;
132   memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
133   clientFormat.mFormatID         = kAudioFormatLinearPCM;
134   clientFormat.mSampleRate       = (Float64)(s->samplerate);
135   clientFormat.mFormatFlags      = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
136   clientFormat.mChannelsPerFrame = s->channels;
137   clientFormat.mBitsPerChannel   = sizeof(short) * 8;
138   clientFormat.mFramesPerPacket  = 1;
139   clientFormat.mBytesPerFrame    = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
140   clientFormat.mBytesPerPacket   = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
141   clientFormat.mReserved         = 0;
142
143   AudioFileTypeID fileType = kAudioFileWAVEType;
144   CFURLRef fileURL = createURLFromPath(s->path);
145   bool overwrite = true;
146   OSStatus err = noErr;
147   err = ExtAudioFileCreateWithURL(fileURL, fileType, &clientFormat, NULL,
148      overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
149   CFRelease(fileURL);
150   if (err) {
151     char_t errorstr[20];
152     AUBIO_ERR("sink_apple_audio: error when trying to create %s with "
153         "ExtAudioFileCreateWithURL (%s)\n", s->path,
154         getPrintableOSStatusError(errorstr, err));
155     goto beach;
156   }
157   if (createAubioBufferList(&s->bufferList, s->channels, s->max_frames * s->channels)) {
158     AUBIO_ERR("sink_apple_audio: error when creating buffer list for %s, "
159         "out of memory? \n", s->path);
160     goto beach;
161   }
162   return AUBIO_OK;
163
164 beach:
165   return AUBIO_FAIL;
166 }
167
168 void aubio_sink_apple_audio_do(aubio_sink_apple_audio_t * s, fvec_t * write_data, uint_t write) {
169   UInt32 c, v;
170   short *data = (short*)s->bufferList.mBuffers[0].mData;
171   if (write > s->max_frames) {
172     AUBIO_WRN("sink_apple_audio: trying to write %d frames, max %d\n", write, s->max_frames);
173     write = s->max_frames;
174   }
175   smpl_t *buf = write_data->data;
176
177   if (buf) {
178       for (c = 0; c < s->channels; c++) {
179           for (v = 0; v < write; v++) {
180               data[v * s->channels + c] =
181                   FLOAT_TO_SHORT(buf[ v * s->channels + c]);
182           }
183       }
184   }
185   aubio_sink_apple_audio_write(s, write);
186 }
187
188 void aubio_sink_apple_audio_do_multi(aubio_sink_apple_audio_t * s, fmat_t * write_data, uint_t write) {
189   UInt32 c, v;
190   short *data = (short*)s->bufferList.mBuffers[0].mData;
191   if (write > s->max_frames) {
192     AUBIO_WRN("sink_apple_audio: trying to write %d frames, max %d\n", write, s->max_frames);
193     write = s->max_frames;
194   }
195   smpl_t **buf = write_data->data;
196
197   if (buf) {
198       for (c = 0; c < s->channels; c++) {
199           for (v = 0; v < write; v++) {
200               data[v * s->channels + c] =
201                   FLOAT_TO_SHORT(buf[c][v]);
202           }
203       }
204   }
205   aubio_sink_apple_audio_write(s, write);
206 }
207
208 void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write) {
209   OSStatus err = noErr;
210   if (s->async) {
211     err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
212     if (err) {
213       char_t errorstr[20];
214       if (err == kExtAudioFileError_AsyncWriteBufferOverflow) {
215         sprintf(errorstr,"buffer overflow");
216       } else if (err == kExtAudioFileError_AsyncWriteTooLarge) {
217         sprintf(errorstr,"write too large");
218       } else {
219         // unknown error
220         getPrintableOSStatusError(errorstr, err);
221       }
222       AUBIO_ERROR("sink_apple_audio: error while writing %s "
223                   "in ExtAudioFileWriteAsync (%s)\n", s->path, errorstr);
224     }
225   } else {
226     err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
227     if (err) {
228       char_t errorstr[20];
229       AUBIO_ERROR("sink_apple_audio: error while writing %s "
230           "in ExtAudioFileWrite (%s)\n", s->path,
231           getPrintableOSStatusError(errorstr, err));
232     }
233   }
234 }
235
236 uint_t aubio_sink_apple_audio_close(aubio_sink_apple_audio_t * s) {
237   OSStatus err = noErr;
238   if (!s->audioFile) {
239     return AUBIO_FAIL;
240   }
241   err = ExtAudioFileDispose(s->audioFile);
242   if (err) {
243     char_t errorstr[20];
244     AUBIO_ERROR("sink_apple_audio: error while closing %s "
245         "in ExtAudioFileDispose (%s)\n", s->path,
246         getPrintableOSStatusError(errorstr, err));
247   }
248   s->audioFile = NULL;
249   return err;
250 }
251
252 void del_aubio_sink_apple_audio(aubio_sink_apple_audio_t * s) {
253   if (s->audioFile) aubio_sink_apple_audio_close (s);
254   if (s->path) AUBIO_FREE(s->path);
255   freeAudioBufferList(&s->bufferList);
256   AUBIO_FREE(s);
257   return;
258 }
259
260 #endif /* HAVE_SINK_APPLE_AUDIO */