[io] sink_apple_audio to use native format conversion
[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 "aubio_priv.h"
22
23 #ifdef HAVE_SINK_APPLE_AUDIO
24 #include "fvec.h"
25 #include "fmat.h"
26 #include "io/sink_apple_audio.h"
27 #include "io/ioutils.h"
28
29 // CFURLRef, CFURLCreateWithFileSystemPath, ...
30 #include <CoreFoundation/CoreFoundation.h>
31 // ExtAudioFileRef, AudioStreamBasicDescription, AudioBufferList, ...
32 #include <AudioToolbox/AudioToolbox.h>
33
34 extern int createAudioBufferList(AudioBufferList *bufferList, int channels, int segmentSize);
35 extern void freeAudioBufferList(AudioBufferList *bufferList);
36 extern CFURLRef createURLFromPath(const char * path);
37 char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
38
39 uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s);
40
41 #define MAX_SIZE 4096 // the maximum number of frames that can be written at a time
42
43 void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write);
44
45 struct _aubio_sink_apple_audio_t {
46   uint_t samplerate;
47   uint_t channels;
48   char_t *path;
49
50   uint_t max_frames;
51
52   AudioBufferList bufferList;
53   ExtAudioFileRef audioFile;
54   bool async;
55 };
56
57 aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(const char_t * uri, uint_t samplerate) {
58   aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
59   s->max_frames = MAX_SIZE;
60   s->async = false;
61
62   if ( (uri == NULL) || (strnlen(uri, PATH_MAX) < 1) ) {
63     AUBIO_ERROR("sink_apple_audio: Aborted opening null path\n");
64     goto beach;
65   }
66
67   s->path = AUBIO_ARRAY(char_t, strnlen(uri, PATH_MAX) + 1);
68   strncpy(s->path, uri, strnlen(uri, PATH_MAX) + 1);
69
70   s->samplerate = 0;
71   s->channels = 0;
72
73   // zero samplerate given. do not open yet
74   if ((sint_t)samplerate == 0) {
75     return s;
76   }
77
78   // invalid samplerate given, abort
79   if (aubio_io_validate_samplerate("sink_apple_audio", s->path, samplerate)) {
80     goto beach;
81   }
82
83   s->samplerate = samplerate;
84   s->channels = 1;
85
86   if (aubio_sink_apple_audio_open(s) != AUBIO_OK) {
87     // open failed, abort
88     goto beach;
89   }
90
91   return s;
92 beach:
93   del_aubio_sink_apple_audio(s);
94   return NULL;
95 }
96
97 uint_t aubio_sink_apple_audio_preset_samplerate(aubio_sink_apple_audio_t *s, uint_t samplerate)
98 {
99   if (aubio_io_validate_samplerate("sink_apple_audio", s->path, samplerate)) {
100     return AUBIO_FAIL;
101   }
102   s->samplerate = samplerate;
103   // automatically open when both samplerate and channels have been set
104   if (/* s->samplerate != 0 && */ s->channels != 0) {
105     return aubio_sink_apple_audio_open(s);
106   }
107   return AUBIO_OK;
108 }
109
110 uint_t aubio_sink_apple_audio_preset_channels(aubio_sink_apple_audio_t *s, uint_t channels)
111 {
112   if (aubio_io_validate_channels("sink_apple_audio", s->path, channels)) {
113     return AUBIO_FAIL;
114   }
115   s->channels = channels;
116   // automatically open when both samplerate and channels have been set
117   if (s->samplerate != 0 /* && s->channels != 0 */) {
118     return aubio_sink_apple_audio_open(s);
119   }
120   return AUBIO_OK;
121 }
122
123 uint_t aubio_sink_apple_audio_get_samplerate(const aubio_sink_apple_audio_t *s)
124 {
125   return s->samplerate;
126 }
127
128 uint_t aubio_sink_apple_audio_get_channels(const aubio_sink_apple_audio_t *s)
129 {
130   return s->channels;
131 }
132
133 uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s) {
134
135   if (s->samplerate == 0 || s->channels == 0) return AUBIO_FAIL;
136
137   AudioStreamBasicDescription clientFormat;
138   memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
139   clientFormat.mFormatID         = kAudioFormatLinearPCM;
140   clientFormat.mSampleRate       = (Float64)(s->samplerate);
141   clientFormat.mFormatFlags      = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
142   clientFormat.mChannelsPerFrame = s->channels;
143   clientFormat.mBitsPerChannel   = sizeof(short) * 8;
144   clientFormat.mFramesPerPacket  = 1;
145   clientFormat.mBytesPerFrame    = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
146   clientFormat.mBytesPerPacket   = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
147   clientFormat.mReserved         = 0;
148
149   AudioFileTypeID fileType = kAudioFileWAVEType;
150   CFURLRef fileURL = createURLFromPath(s->path);
151   bool overwrite = true;
152
153   // set the in-memory format
154   AudioStreamBasicDescription inputFormat;
155   memset(&inputFormat, 0, sizeof(AudioStreamBasicDescription));
156   inputFormat.mFormatID         = kAudioFormatLinearPCM;
157   inputFormat.mSampleRate       = (Float64)(s->samplerate);
158   inputFormat.mFormatFlags      = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked;
159   inputFormat.mChannelsPerFrame = s->channels;
160   inputFormat.mBitsPerChannel   = sizeof(smpl_t) * 8;
161   inputFormat.mFramesPerPacket  = 1;
162   inputFormat.mBytesPerFrame    = inputFormat.mBitsPerChannel * inputFormat.mChannelsPerFrame / 8;
163   inputFormat.mBytesPerPacket   = inputFormat.mFramesPerPacket * inputFormat.mBytesPerFrame;
164   OSStatus err = noErr;
165   err = ExtAudioFileCreateWithURL(fileURL, fileType, &clientFormat, NULL,
166      overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
167   CFRelease(fileURL);
168   if (err) {
169     char_t errorstr[20];
170     AUBIO_ERR("sink_apple_audio: error when trying to create %s with "
171         "ExtAudioFileCreateWithURL (%s)\n", s->path,
172         getPrintableOSStatusError(errorstr, err));
173     goto beach;
174   }
175
176   err = ExtAudioFileSetProperty(s->audioFile,
177       kExtAudioFileProperty_ClientDataFormat,
178       sizeof(AudioStreamBasicDescription), &inputFormat);
179   if (err) {
180     char_t errorstr[20];
181     AUBIO_ERR("sink_apple_audio: error when trying to set output format on %s "
182         "(%s)\n", s->path, getPrintableOSStatusError(errorstr, err));
183     goto beach;
184   }
185
186   if (createAudioBufferList(&s->bufferList, s->channels, s->max_frames * s->channels)) {
187     AUBIO_ERR("sink_apple_audio: error when creating buffer list for %s, "
188         "out of memory? \n", s->path);
189     goto beach;
190   }
191   return AUBIO_OK;
192
193 beach:
194   return AUBIO_FAIL;
195 }
196
197 void aubio_sink_apple_audio_do(aubio_sink_apple_audio_t * s, fvec_t * write_data, uint_t write) {
198   UInt32 c, v;
199   smpl_t *data = (smpl_t*)s->bufferList.mBuffers[0].mData;
200   uint_t length = aubio_sink_validate_input_length("sink_apple_audio", s->path,
201       s->max_frames, write_data->length, write);
202
203   for (c = 0; c < s->channels; c++) {
204     for (v = 0; v < length; v++) {
205       data[v * s->channels + c] = write_data->data[v];
206     }
207   }
208
209   aubio_sink_apple_audio_write(s, length);
210 }
211
212 void aubio_sink_apple_audio_do_multi(aubio_sink_apple_audio_t * s, fmat_t * write_data, uint_t write) {
213   UInt32 c, v;
214   smpl_t *data = (smpl_t*)s->bufferList.mBuffers[0].mData;
215   uint_t channels = aubio_sink_validate_input_channels("sink_apple_audio",
216       s->path, s->channels, write_data->height);
217   uint_t length = aubio_sink_validate_input_length("sink_apple_audio", s->path,
218       s->max_frames, write_data->length, write);
219
220   for (c = 0; c < channels; c++) {
221     for (v = 0; v < length; v++) {
222       data[v * s->channels + c] = write_data->data[c][v];
223     }
224   }
225
226   aubio_sink_apple_audio_write(s, length);
227 }
228
229 void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write) {
230   OSStatus err = noErr;
231   // set mDataByteSize to match the number of frames to be written
232   // see https://www.mail-archive.com/coreaudio-api@lists.apple.com/msg01109.html
233   s->bufferList.mBuffers[0].mDataByteSize = write * s->channels
234     * sizeof(smpl_t);
235   if (s->async) {
236     err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
237     if (err) {
238       char_t errorstr[20];
239       if (err == kExtAudioFileError_AsyncWriteBufferOverflow) {
240         sprintf(errorstr,"buffer overflow");
241       } else if (err == kExtAudioFileError_AsyncWriteTooLarge) {
242         sprintf(errorstr,"write too large");
243       } else {
244         // unknown error
245         getPrintableOSStatusError(errorstr, err);
246       }
247       AUBIO_ERROR("sink_apple_audio: error while writing %s "
248                   "in ExtAudioFileWriteAsync (%s)\n", s->path, errorstr);
249     }
250   } else {
251     err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
252     if (err) {
253       char_t errorstr[20];
254       AUBIO_ERROR("sink_apple_audio: error while writing %s "
255           "in ExtAudioFileWrite (%s)\n", s->path,
256           getPrintableOSStatusError(errorstr, err));
257     }
258   }
259 }
260
261 uint_t aubio_sink_apple_audio_close(aubio_sink_apple_audio_t * s) {
262   OSStatus err = noErr;
263   if (!s->audioFile) {
264     return AUBIO_FAIL;
265   }
266   err = ExtAudioFileDispose(s->audioFile);
267   if (err) {
268     char_t errorstr[20];
269     AUBIO_ERROR("sink_apple_audio: error while closing %s "
270         "in ExtAudioFileDispose (%s)\n", s->path,
271         getPrintableOSStatusError(errorstr, err));
272   }
273   s->audioFile = NULL;
274   return err;
275 }
276
277 void del_aubio_sink_apple_audio(aubio_sink_apple_audio_t * s) {
278   AUBIO_ASSERT(s);
279   if (s->audioFile)
280     aubio_sink_apple_audio_close (s);
281   if (s->path)
282     AUBIO_FREE(s->path);
283   freeAudioBufferList(&s->bufferList);
284   AUBIO_FREE(s);
285 }
286
287 #endif /* HAVE_SINK_APPLE_AUDIO */