Merge branch 'device' into develop
[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 segmentSize);
51 extern void freeAudioBufferList(AudioBufferList *bufferList);
52 extern CFURLRef getURLFromPath(const char * path);
53
54 aubio_source_apple_audio_t * new_aubio_source_apple_audio(char_t * path, uint_t samplerate, uint_t block_size)
55 {
56   aubio_source_apple_audio_t * s = AUBIO_NEW(aubio_source_apple_audio_t);
57
58   s->path = path;
59   s->block_size = block_size;
60
61   OSStatus err = noErr;
62   UInt32 propSize;
63
64   // open the resource url
65   CFURLRef fileURL = getURLFromPath(path);
66   err = ExtAudioFileOpenURL(fileURL, &s->audioFile);
67   if (err) { AUBIO_ERR("error when trying to access %s, in ExtAudioFileOpenURL, %d\n", s->path, (int)err); goto beach;}
68
69   // create an empty AudioStreamBasicDescription
70   AudioStreamBasicDescription fileFormat;
71   propSize = sizeof(fileFormat);
72   memset(&fileFormat, 0, sizeof(AudioStreamBasicDescription));
73
74   // fill it with the file description
75   err = ExtAudioFileGetProperty(s->audioFile,
76       kExtAudioFileProperty_FileDataFormat, &propSize, &fileFormat);
77   if (err) { AUBIO_ERROR("error in ExtAudioFileGetProperty, %d\n", (int)err); goto beach;}
78
79   if (samplerate == 0) {
80     samplerate = fileFormat.mSampleRate;
81     //AUBIO_DBG("sampling rate set to 0, automagically adjusting to %d\n", samplerate);
82   }
83   s->samplerate = samplerate;
84   s->source_samplerate = fileFormat.mSampleRate;
85   s->channels = fileFormat.mChannelsPerFrame;
86
87   AudioStreamBasicDescription clientFormat;
88   propSize = sizeof(clientFormat);
89   memset(&clientFormat, 0, sizeof(AudioStreamBasicDescription));
90   clientFormat.mFormatID         = kAudioFormatLinearPCM;
91   clientFormat.mSampleRate       = (Float64)(s->samplerate);
92   clientFormat.mFormatFlags      = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
93   clientFormat.mChannelsPerFrame = s->channels;
94   clientFormat.mBitsPerChannel   = sizeof(short) * 8;
95   clientFormat.mFramesPerPacket  = 1;
96   clientFormat.mBytesPerFrame    = clientFormat.mBitsPerChannel * clientFormat.mChannelsPerFrame / 8;
97   clientFormat.mBytesPerPacket   = clientFormat.mFramesPerPacket * clientFormat.mBytesPerFrame;
98   clientFormat.mReserved         = 0;
99
100   // set the client format description
101   err = ExtAudioFileSetProperty(s->audioFile, kExtAudioFileProperty_ClientDataFormat,
102       propSize, &clientFormat);
103   if (err) {
104       AUBIO_ERROR("error in ExtAudioFileSetProperty, %d\n", (int)err);
105 #if 1
106   // print client and format descriptions
107   AUBIO_DBG("Opened %s\n", s->path);
108   AUBIO_DBG("file/client Format.mFormatID:        : %3c%c%c%c / %c%c%c%c\n",
109       (int)RT_BYTE4(fileFormat.mFormatID),   (int)RT_BYTE3(fileFormat.mFormatID),   (int)RT_BYTE2(fileFormat.mFormatID),   (int)RT_BYTE1(fileFormat.mFormatID),
110       (int)RT_BYTE4(clientFormat.mFormatID), (int)RT_BYTE3(clientFormat.mFormatID), (int)RT_BYTE2(clientFormat.mFormatID), (int)RT_BYTE1(clientFormat.mFormatID)
111       );
112
113   AUBIO_DBG("file/client Format.mSampleRate       : %6.0f / %.0f\n",     fileFormat.mSampleRate      ,      clientFormat.mSampleRate);
114   AUBIO_DBG("file/client Format.mFormatFlags      : %6d / %d\n",    (int)fileFormat.mFormatFlags     , (int)clientFormat.mFormatFlags);
115   AUBIO_DBG("file/client Format.mChannelsPerFrame : %6d / %d\n",    (int)fileFormat.mChannelsPerFrame, (int)clientFormat.mChannelsPerFrame);
116   AUBIO_DBG("file/client Format.mBitsPerChannel   : %6d / %d\n",    (int)fileFormat.mBitsPerChannel  , (int)clientFormat.mBitsPerChannel);
117   AUBIO_DBG("file/client Format.mFramesPerPacket  : %6d / %d\n",    (int)fileFormat.mFramesPerPacket , (int)clientFormat.mFramesPerPacket);
118   AUBIO_DBG("file/client Format.mBytesPerFrame    : %6d / %d\n",    (int)fileFormat.mBytesPerFrame   , (int)clientFormat.mBytesPerFrame);
119   AUBIO_DBG("file/client Format.mBytesPerPacket   : %6d / %d\n",    (int)fileFormat.mBytesPerPacket  , (int)clientFormat.mBytesPerPacket);
120   AUBIO_DBG("file/client Format.mReserved         : %6d / %d\n",    (int)fileFormat.mReserved        , (int)clientFormat.mReserved);
121 #endif
122       goto beach;
123   }
124
125   // compute the size of the segments needed to read the input file
126   UInt32 samples = s->block_size * clientFormat.mChannelsPerFrame;
127   Float64 rateRatio = clientFormat.mSampleRate / fileFormat.mSampleRate;
128   uint_t segmentSize= (uint_t)(samples * rateRatio + .5);
129   if (rateRatio < 1.) {
130     segmentSize = (uint_t)(samples / rateRatio + .5);
131   } else if (rateRatio > 1.) {
132     AUBIO_WRN("up-sampling %s from %0.2fHz to %0.2fHz\n", s->path, fileFormat.mSampleRate, clientFormat.mSampleRate);
133   } else {
134     assert ( segmentSize == samples );
135     //AUBIO_DBG("not resampling, segmentSize %d, block_size %d\n", segmentSize, s->block_size);
136   }
137
138   // allocate the AudioBufferList
139   if (createAubioBufferList(&s->bufferList, s->channels, segmentSize)) err = -1;
140
141   return s;
142  
143 beach:
144   AUBIO_FREE(s);
145   return NULL;
146 }
147
148 void aubio_source_apple_audio_do(aubio_source_apple_audio_t *s, fvec_t * read_to, uint_t * read) {
149   UInt32 c, v, loadedPackets = s->block_size;
150   OSStatus err = ExtAudioFileRead(s->audioFile, &loadedPackets, &s->bufferList);
151   if (err) { AUBIO_ERROR("error in ExtAudioFileRead %s %d\n", s->path, (int)err); goto beach;}
152
153   short *data = (short*)s->bufferList.mBuffers[0].mData;
154
155   smpl_t *buf = read_to->data;
156
157   for (v = 0; v < loadedPackets; v++) {
158     buf[v] = 0.;
159     for (c = 0; c < s->channels; c++) {
160       buf[v] += SHORT_TO_FLOAT(data[ v * s->channels + c]);
161     }
162     buf[v] /= (smpl_t)s->channels;
163   }
164   // short read, fill with zeros
165   if (loadedPackets < s->block_size) {
166     for (v = loadedPackets; v < s->block_size; v++) {
167       buf[v] = 0.;
168     }
169   }
170
171   *read = (uint_t)loadedPackets;
172   return;
173 beach:
174   *read = 0;
175   return;
176 }
177
178 void aubio_source_apple_audio_do_multi(aubio_source_apple_audio_t *s, fmat_t * read_to, uint_t * read) {
179   UInt32 c, v, loadedPackets = s->block_size;
180   OSStatus err = ExtAudioFileRead(s->audioFile, &loadedPackets, &s->bufferList);
181   if (err) { AUBIO_ERROR("source_apple_audio: error in ExtAudioFileRead, %d\n", (int)err); goto beach;}
182
183   short *data = (short*)s->bufferList.mBuffers[0].mData;
184
185   smpl_t **buf = read_to->data;
186
187   for (v = 0; v < loadedPackets; v++) {
188     for (c = 0; c < s->channels; c++) {
189       buf[c][v] = SHORT_TO_FLOAT(data[ v * s->channels + c]);
190     }
191   }
192   // short read, fill with zeros
193   if (loadedPackets < s->block_size) {
194     for (v = loadedPackets; v < s->block_size; v++) {
195       for (c = 0; c < s->channels; c++) {
196         buf[c][v] = 0.;
197       }
198     }
199   }
200   *read = (uint_t)loadedPackets;
201   return;
202 beach:
203   *read = 0;
204   return;
205 }
206
207 void del_aubio_source_apple_audio(aubio_source_apple_audio_t * s){
208   OSStatus err = noErr;
209   if (!s || !s->audioFile) { return; }
210   err = ExtAudioFileDispose(s->audioFile);
211   if (err) AUBIO_ERROR("error in ExtAudioFileDispose, %d\n", (int)err);
212   s->audioFile = NULL;
213   freeAudioBufferList(&s->bufferList);
214   AUBIO_FREE(s);
215   return;
216 }
217
218 uint_t aubio_source_apple_audio_seek (aubio_source_apple_audio_t * s, uint_t pos) {
219   SInt64 resampled_pos = (SInt64)ROUND( pos * s->source_samplerate * 1. / s->samplerate );
220   OSStatus err = ExtAudioFileSeek(s->audioFile, resampled_pos);
221   if (err) AUBIO_ERROR("source_apple_audio: error in ExtAudioFileSeek (%d)\n", (int)err);
222   return err;
223 }
224
225 uint_t aubio_source_apple_audio_get_samplerate(aubio_source_apple_audio_t * s) {
226   return s->samplerate;
227 }
228
229 uint_t aubio_source_apple_audio_get_channels(aubio_source_apple_audio_t * s) {
230   return s->channels;
231 }
232
233 #endif /* __APPLE__ */