Merge branch 'master' into notes
[aubio.git] / src / io / source_apple_audio.c
1 /*
2   Copyright (C) 2012 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_SOURCE_APPLE_AUDIO
24
25 #include "aubio_priv.h"
26 #include "fvec.h"
27 #include "fmat.h"
28 #include "io/source_apple_audio.h"
29
30 // ExtAudioFileRef, AudioStreamBasicDescription, AudioBufferList, ...
31 #include <AudioToolbox/AudioToolbox.h>
32
33 #define RT_BYTE1( a )      ( (a) & 0xff )
34 #define RT_BYTE2( a )      ( ((a) >> 8) & 0xff )
35 #define RT_BYTE3( a )      ( ((a) >> 16) & 0xff )
36 #define RT_BYTE4( a )      ( ((a) >> 24) & 0xff )
37
38 #define SHORT_TO_FLOAT(x) (smpl_t)(x * 3.0517578125e-05)
39
40 struct _aubio_source_apple_audio_t {
41   uint_t channels;
42   uint_t samplerate;          //< requested samplerate
43   uint_t source_samplerate;   //< actual source samplerate
44   uint_t block_size;
45
46   char_t *path;
47
48   ExtAudioFileRef audioFile;
49   AudioBufferList bufferList;
50 };
51
52 extern int createAubioBufferList(AudioBufferList *bufferList, int channels, int max_source_samples);
53 extern void freeAudioBufferList(AudioBufferList *bufferList);
54 extern CFURLRef createURLFromPath(const char * path);
55 char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
56
57 uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, const char_t * path);
58
59 aubio_source_apple_audio_t * new_aubio_source_apple_audio(const char_t * path, uint_t samplerate, uint_t block_size)
60 {
61   aubio_source_apple_audio_t * s = AUBIO_NEW(aubio_source_apple_audio_t);
62
63   if (path == NULL) {
64     AUBIO_ERROR("source_apple_audio: Aborted opening null path\n");
65     goto beach;
66   }
67
68   if ( (sint_t)block_size <= 0 ) {
69     AUBIO_ERROR("source_apple_audio: Can not open %s with null or negative block_size %d\n",
70         path, block_size);
71     goto beach;
72   }
73
74   if ( (sint_t)samplerate < 0 ) {
75     AUBIO_ERROR("source_apple_audio: Can not open %s with negative samplerate %d\n",
76         path, samplerate);
77     goto beach;
78   }
79
80   s->block_size = block_size;
81   s->samplerate = samplerate;
82
83   if ( aubio_source_apple_audio_open ( s, path ) ) {
84     goto beach;
85   }
86   return s;
87
88 beach:
89   AUBIO_FREE(s);
90   return NULL;
91 }
92
93 uint_t aubio_source_apple_audio_open (aubio_source_apple_audio_t *s, const char_t * path)
94 {
95   OSStatus err = noErr;
96   UInt32 propSize;
97
98   if (s->path) AUBIO_FREE(s->path);
99   s->path = AUBIO_ARRAY(char_t, strnlen(path, PATH_MAX) + 1);
100   strncpy(s->path, path, strnlen(path, PATH_MAX) + 1);
101
102   // open the resource url
103   CFURLRef fileURL = createURLFromPath(s->path);
104   err = ExtAudioFileOpenURL(fileURL, &s->audioFile);
105   CFRelease(fileURL);
106   if (err == -43) {
107     AUBIO_ERR("source_apple_audio: Failed opening %s, "
108         "file not found, or no read access\n", s->path);
109     goto beach;
110   } else if (err) {
111     char_t errorstr[20];
112     AUBIO_ERR("source_apple_audio: Failed opening %s, "
113         "error in ExtAudioFileOpenURL (%s)\n", s->path,
114         getPrintableOSStatusError(errorstr, err));
115     goto beach;
116   }
117
118   // create an empty AudioStreamBasicDescription
119   AudioStreamBasicDescription fileFormat;
120   propSize = sizeof(fileFormat);
121   memset(&fileFormat, 0, sizeof(AudioStreamBasicDescription));
122
123   // fill it with the file description
124   err = ExtAudioFileGetProperty(s->audioFile,
125       kExtAudioFileProperty_FileDataFormat, &propSize, &fileFormat);
126   if (err) {
127     char_t errorstr[20];
128     AUBIO_ERROR("source_apple_audio: Failed opening %s, "
129         "error in ExtAudioFileGetProperty (%s)\n", s->path,
130         getPrintableOSStatusError(errorstr, err));
131     goto beach;
132   }
133
134   if (s->samplerate == 0) {
135     s->samplerate = fileFormat.mSampleRate;
136     //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
137   }
138
139   s->source_samplerate = fileFormat.mSampleRate;
140   s->channels = fileFormat.mChannelsPerFrame;
141
142   AudioStreamBasicDescription clientFormat;
143   propSize = sizeof(clientFormat);
144   memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
145   clientFormat.mFormatID         = kAudioFormatLinearPCM;
146   clientFormat.mSampleRate       = (Float64)(s->samplerate);
147   clientFormat.mFormatFlags      = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
148   clientFormat.mChannelsPerFrame = s->channels;
149   clientFormat.mBitsPerChannel   = sizeof(short) * 8;
150   clientFormat.mFramesPerPacket  = 1;
151   clientFormat.mBytesPerFrame    = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
152   clientFormat.mBytesPerPacket   = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
153   clientFormat.mReserved         = 0;
154
155   // set the client format description
156   err = ExtAudioFileSetProperty(s->audioFile, kExtAudioFileProperty_ClientDataFormat,
157       propSize, &clientFormat);
158   if (err) {
159     char_t errorstr[20];
160     AUBIO_ERROR("source_apple_audio: Failed opening %s, "
161         "error in ExtAudioFileSetProperty (%s)\n", s->path,
162         getPrintableOSStatusError(errorstr, err));
163 #if 0
164   // print client and format descriptions
165   AUBIO_DBG("Opened %s\n", s->path);
166   AUBIO_DBG("file/client Format.mFormatID:        : %3c%c%c%c / %c%c%c%c\n",
167       (int)RT_BYTE4(fileFormat.mFormatID),   (int)RT_BYTE3(fileFormat.mFormatID),   (int)RT_BYTE2(fileFormat.mFormatID),   (int)RT_BYTE1(fileFormat.mFormatID),
168       (int)RT_BYTE4(clientFormat.mFormatID), (int)RT_BYTE3(clientFormat.mFormatID), (int)RT_BYTE2(clientFormat.mFormatID), (int)RT_BYTE1(clientFormat.mFormatID)
169       );
170
171   AUBIO_DBG("file/client Format.mSampleRate       : %6.0f / %.0f\n",     fileFormat.mSampleRate      ,      clientFormat.mSampleRate);
172   AUBIO_DBG("file/client Format.mFormatFlags      : %6d / %d\n",    (int)fileFormat.mFormatFlags     , (int)clientFormat.mFormatFlags);
173   AUBIO_DBG("file/client Format.mChannelsPerFrame : %6d / %d\n",    (int)fileFormat.mChannelsPerFrame, (int)clientFormat.mChannelsPerFrame);
174   AUBIO_DBG("file/client Format.mBitsPerChannel   : %6d / %d\n",    (int)fileFormat.mBitsPerChannel  , (int)clientFormat.mBitsPerChannel);
175   AUBIO_DBG("file/client Format.mFramesPerPacket  : %6d / %d\n",    (int)fileFormat.mFramesPerPacket , (int)clientFormat.mFramesPerPacket);
176   AUBIO_DBG("file/client Format.mBytesPerFrame    : %6d / %d\n",    (int)fileFormat.mBytesPerFrame   , (int)clientFormat.mBytesPerFrame);
177   AUBIO_DBG("file/client Format.mBytesPerPacket   : %6d / %d\n",    (int)fileFormat.mBytesPerPacket  , (int)clientFormat.mBytesPerPacket);
178   AUBIO_DBG("file/client Format.mReserved         : %6d / %d\n",    (int)fileFormat.mReserved        , (int)clientFormat.mReserved);
179 #endif
180       goto beach;
181   }
182
183   smpl_t ratio = s->source_samplerate * 1. / s->samplerate;
184   if (ratio < 1.) {
185     AUBIO_WRN("source_apple_audio: up-sampling %s from %0dHz to %0dHz\n",
186         s->path, s->source_samplerate, s->samplerate);
187   }
188
189   // allocate the AudioBufferList
190   freeAudioBufferList(&s->bufferList);
191   if (createAubioBufferList(&s->bufferList, s->channels, s->block_size * s->channels)) {
192     AUBIO_ERR("source_apple_audio: failed creating bufferList\n");
193     goto beach;
194   }
195
196 beach:
197   return err;
198 }
199
200 void aubio_source_apple_audio_do(aubio_source_apple_audio_t *s, fvec_t * read_to, uint_t * read) {
201   UInt32 c, v, loadedPackets = s->block_size;
202   OSStatus err = ExtAudioFileRead(s->audioFile, &loadedPackets, &s->bufferList);
203   if (err) {
204     char_t errorstr[20];
205     AUBIO_ERROR("source_apple_audio: error while reading %s "
206         "with ExtAudioFileRead (%s)\n", s->path,
207         getPrintableOSStatusError(errorstr, err));
208     goto beach;
209   }
210
211   short *data = (short*)s->bufferList.mBuffers[0].mData;
212
213   smpl_t *buf = read_to->data;
214
215   for (v = 0; v < loadedPackets; v++) {
216     buf[v] = 0.;
217     for (c = 0; c < s->channels; c++) {
218       buf[v] += SHORT_TO_FLOAT(data[ v * s->channels + c]);
219     }
220     buf[v] /= (smpl_t)s->channels;
221   }
222   // short read, fill with zeros
223   if (loadedPackets < s->block_size) {
224     for (v = loadedPackets; v < s->block_size; v++) {
225       buf[v] = 0.;
226     }
227   }
228
229   *read = (uint_t)loadedPackets;
230   return;
231 beach:
232   *read = 0;
233   return;
234 }
235
236 void aubio_source_apple_audio_do_multi(aubio_source_apple_audio_t *s, fmat_t * read_to, uint_t * read) {
237   UInt32 c, v, loadedPackets = s->block_size;
238   OSStatus err = ExtAudioFileRead(s->audioFile, &loadedPackets, &s->bufferList);
239   if (err) {
240     char_t errorstr[20];
241     AUBIO_ERROR("source_apple_audio: error while reading %s "
242         "with ExtAudioFileRead (%s)\n", s->path,
243         getPrintableOSStatusError(errorstr, err));
244     goto beach;
245   }
246
247   short *data = (short*)s->bufferList.mBuffers[0].mData;
248
249   smpl_t **buf = read_to->data;
250
251   for (v = 0; v < loadedPackets; v++) {
252     for (c = 0; c < read_to->height; c++) {
253       buf[c][v] = SHORT_TO_FLOAT(data[ v * s->channels + c]);
254     }
255   }
256   // if read_data has more channels than the file
257   if (read_to->height > s->channels) {
258     // copy last channel to all additional channels
259     for (v = 0; v < loadedPackets; v++) {
260       for (c = s->channels; c < read_to->height; c++) {
261         buf[c][v] = SHORT_TO_FLOAT(data[ v * s->channels + (s->channels - 1)]);
262       }
263     }
264   }
265   // short read, fill with zeros
266   if (loadedPackets < s->block_size) {
267     for (v = loadedPackets; v < s->block_size; v++) {
268       for (c = 0; c < read_to->height; c++) {
269         buf[c][v] = 0.;
270       }
271     }
272   }
273   *read = (uint_t)loadedPackets;
274   return;
275 beach:
276   *read = 0;
277   return;
278 }
279
280 uint_t aubio_source_apple_audio_close (aubio_source_apple_audio_t *s)
281 {
282   OSStatus err = noErr;
283   if (!s->audioFile) { return AUBIO_FAIL; }
284   err = ExtAudioFileDispose(s->audioFile);
285   s->audioFile = NULL;
286   if (err) {
287     char_t errorstr[20];
288     AUBIO_ERROR("source_apple_audio: error while closing %s "
289         "in ExtAudioFileDispose (%s)\n", s->path,
290         getPrintableOSStatusError(errorstr, err));
291     return err;
292   }
293   return AUBIO_OK;
294 }
295
296 void del_aubio_source_apple_audio(aubio_source_apple_audio_t * s){
297   aubio_source_apple_audio_close (s);
298   if (s->path) AUBIO_FREE(s->path);
299   freeAudioBufferList(&s->bufferList);
300   AUBIO_FREE(s);
301   return;
302 }
303
304 uint_t aubio_source_apple_audio_seek (aubio_source_apple_audio_t * s, uint_t pos) {
305   OSStatus err = noErr;
306   if ((sint_t)pos < 0) {
307     AUBIO_ERROR("source_apple_audio: error while seeking in %s "
308         "(can not seek at negative position %d)\n",
309         s->path, pos);
310     err = -1;
311     goto beach;
312   }
313   // check if we are not seeking out of the file
314   uint_t fileLengthFrames = aubio_source_apple_audio_get_duration(s);
315   // compute position in the source file, before resampling
316   smpl_t ratio = s->source_samplerate * 1. / s->samplerate;
317   SInt64 resampled_pos = (SInt64)ROUND( pos * ratio );
318   if (resampled_pos > fileLengthFrames) {
319     AUBIO_ERR("source_apple_audio: trying to seek in %s at pos %d, "
320         "but file has only %d frames\n",
321         s->path, pos, (uint_t)(fileLengthFrames / ratio));
322     err = -1;
323     goto beach;
324   }
325   // after a short read, the bufferList size needs to resetted to prepare for a full read
326   AudioBufferList *bufferList = &s->bufferList;
327   bufferList->mBuffers[0].mDataByteSize = s->block_size * s->channels * sizeof (short);
328   // do the actual seek
329   err = ExtAudioFileSeek(s->audioFile, resampled_pos);
330   if (err) {
331     char_t errorstr[20];
332     AUBIO_ERROR("source_apple_audio: error while seeking %s at %d "
333         "in ExtAudioFileSeek (%s)\n", s->path, pos,
334         getPrintableOSStatusError(errorstr, err));
335   }
336 #if 0
337   // check position after seek
338   {
339     SInt64 outFrameOffset = 0;
340     err = ExtAudioFileTell(s->audioFile, &outFrameOffset);
341     if (err) {
342       char_t errorstr[20];
343       AUBIO_ERROR("source_apple_audio: error while seeking %s at %d "
344           "in ExtAudioFileTell (%s)\n", s->path, pos,
345           getPrintableOSStatusError(errorstr, err));
346     }
347     AUBIO_DBG("source_apple_audio: asked seek at %d, tell got %d\n",
348         pos, (uint_t)(outFrameOffset / ratio + .5));
349   }
350 #endif
351 beach:
352   return err;
353 }
354
355 uint_t aubio_source_apple_audio_get_samplerate(const aubio_source_apple_audio_t * s) {
356   return s->samplerate;
357 }
358
359 uint_t aubio_source_apple_audio_get_channels(const aubio_source_apple_audio_t * s) {
360   return s->channels;
361 }
362
363 uint_t aubio_source_apple_audio_get_duration(const aubio_source_apple_audio_t * s) {
364   SInt64 fileLengthFrames = 0;
365   UInt32 propSize = sizeof(fileLengthFrames);
366   OSStatus err = ExtAudioFileGetProperty(s->audioFile,
367       kExtAudioFileProperty_FileLengthFrames, &propSize, &fileLengthFrames);
368   if (err) {
369     char_t errorstr[20];
370     AUBIO_ERROR("source_apple_audio: Failed getting %s duration, "
371         "error in ExtAudioFileGetProperty (%s)\n", s->path,
372         getPrintableOSStatusError(errorstr, err));
373     return err;
374   }
375   return (uint_t)fileLengthFrames;
376 }
377
378 #endif /* HAVE_SOURCE_APPLE_AUDIO */