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