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