source: src/io/sink_apple_audio.c @ 99365e9

feature/autosinkfeature/cnnfeature/crepefix/ffmpeg5
Last change on this file since 99365e9 was 99365e9, checked in by Paul Brossier <piem@piem.org>, 6 years ago

[io] sink_apple_audio uses software-based encoding on ios

  • Property mode set to 100644
File size: 12.2 KB
Line 
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
34extern int createAudioBufferList(AudioBufferList *bufferList, int channels, int segmentSize);
35extern void freeAudioBufferList(AudioBufferList *bufferList);
36extern CFURLRef createURLFromPath(const char * path);
37char_t *getPrintableOSStatusError(char_t *str, OSStatus error);
38
39uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s);
40
41uint_t aubio_str_extension_matches(const char_t *ext,
42    const char_t *pattern);
43const char_t *aubio_str_get_extension(const char_t *filename);
44
45#define MAX_SIZE 4096 // the maximum number of frames that can be written at a time
46
47void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write);
48
49struct _aubio_sink_apple_audio_t {
50  uint_t samplerate;
51  uint_t channels;
52  char_t *path;
53
54  uint_t max_frames;
55
56  AudioBufferList bufferList;
57  ExtAudioFileRef audioFile;
58  bool async;
59  AudioFileTypeID fileType;
60};
61
62aubio_sink_apple_audio_t * new_aubio_sink_apple_audio(const char_t * uri, uint_t samplerate) {
63  aubio_sink_apple_audio_t * s = AUBIO_NEW(aubio_sink_apple_audio_t);
64  s->max_frames = MAX_SIZE;
65  s->async = false;
66
67  if ( (uri == NULL) || (strnlen(uri, PATH_MAX) < 1) ) {
68    AUBIO_ERROR("sink_apple_audio: Aborted opening null path\n");
69    goto beach;
70  }
71
72  s->path = AUBIO_ARRAY(char_t, strnlen(uri, PATH_MAX) + 1);
73  strncpy(s->path, uri, strnlen(uri, PATH_MAX) + 1);
74
75  s->samplerate = 0;
76  s->channels = 0;
77
78  aubio_sink_apple_audio_preset_format(s, aubio_str_get_extension(uri));
79
80  // zero samplerate given. do not open yet
81  if ((sint_t)samplerate == 0) {
82    return s;
83  }
84
85  // invalid samplerate given, abort
86  if (aubio_io_validate_samplerate("sink_apple_audio", s->path, samplerate)) {
87    goto beach;
88  }
89
90  s->samplerate = samplerate;
91  s->channels = 1;
92
93  if (aubio_sink_apple_audio_open(s) != AUBIO_OK) {
94    // open failed, abort
95    goto beach;
96  }
97
98  return s;
99beach:
100  del_aubio_sink_apple_audio(s);
101  return NULL;
102}
103
104uint_t aubio_sink_apple_audio_preset_samplerate(aubio_sink_apple_audio_t *s, uint_t samplerate)
105{
106  if (aubio_io_validate_samplerate("sink_apple_audio", s->path, samplerate)) {
107    return AUBIO_FAIL;
108  }
109  s->samplerate = samplerate;
110  // automatically open when both samplerate and channels have been set
111  if (/* s->samplerate != 0 && */ s->channels != 0) {
112    return aubio_sink_apple_audio_open(s);
113  }
114  return AUBIO_OK;
115}
116
117uint_t aubio_sink_apple_audio_preset_channels(aubio_sink_apple_audio_t *s, uint_t channels)
118{
119  if (aubio_io_validate_channels("sink_apple_audio", s->path, channels)) {
120    return AUBIO_FAIL;
121  }
122  s->channels = channels;
123  // automatically open when both samplerate and channels have been set
124  if (s->samplerate != 0 /* && s->channels != 0 */) {
125    return aubio_sink_apple_audio_open(s);
126  }
127  return AUBIO_OK;
128}
129
130uint_t aubio_sink_apple_audio_preset_format(aubio_sink_apple_audio_t *s,
131    const char_t *fmt)
132{
133  if (aubio_str_extension_matches(fmt, "wav")) {
134    s->fileType = kAudioFileWAVEType;
135  } else if (aubio_str_extension_matches(fmt, "m4a")
136      || aubio_str_extension_matches(fmt, "mp4") ) {
137    // use alac for "mp4" and "m4a"
138    s->fileType = kAudioFileM4AType;
139  } else if (aubio_str_extension_matches(fmt, "aac") ) {
140    // only use lossy codec for "aac"
141    s->fileType = kAudioFileMPEG4Type;
142  } else if (aubio_str_extension_matches(fmt, "aiff") ) {
143    // only use lossy codec for "aac"
144    s->fileType = kAudioFileAIFFType;
145  } else {
146    AUBIO_WRN("sink_apple_audio: could not guess format for %s,"
147       " using default (wav)\n", s->path);
148    s->fileType = kAudioFileWAVEType;
149    return AUBIO_FAIL;
150  }
151  return AUBIO_OK;
152}
153
154static void aubio_sink_apple_audio_set_client_format(aubio_sink_apple_audio_t* s,
155    AudioStreamBasicDescription *clientFormat)
156{
157  memset(clientFormat, 0, sizeof(AudioStreamBasicDescription));
158  // always set samplerate and channels first
159  clientFormat->mSampleRate       = (Float64)(s->samplerate);
160  clientFormat->mChannelsPerFrame = s->channels;
161
162  switch (s->fileType) {
163    case kAudioFileM4AType:
164      clientFormat->mFormatID         = kAudioFormatAppleLossless;
165      break;
166    case kAudioFileMPEG4Type:
167      clientFormat->mFormatID         = kAudioFormatMPEG4AAC;
168      clientFormat->mFormatFlags      = kMPEG4Object_AAC_Main;
169      clientFormat->mFormatFlags     |= kAppleLosslessFormatFlag_16BitSourceData;
170      clientFormat->mFramesPerPacket  = 1024;
171      break;
172    case kAudioFileWAVEType:
173      clientFormat->mFormatID         = kAudioFormatLinearPCM;
174      clientFormat->mFormatFlags      = kAudioFormatFlagIsSignedInteger;
175      clientFormat->mFormatFlags     |= kAudioFormatFlagIsPacked;
176      clientFormat->mBitsPerChannel   = sizeof(short) * 8;
177      clientFormat->mFramesPerPacket  = 1;
178      clientFormat->mBytesPerFrame    = clientFormat->mBitsPerChannel * clientFormat->mChannelsPerFrame / 8;
179      clientFormat->mBytesPerPacket   = clientFormat->mFramesPerPacket * clientFormat->mBytesPerFrame;
180      break;
181    case kAudioFileAIFFType:
182      clientFormat->mFormatID         = kAudioFormatLinearPCM;
183      clientFormat->mFormatFlags      = kAudioFormatFlagIsSignedInteger;
184      clientFormat->mFormatFlags     |= kAudioFormatFlagIsPacked;
185      clientFormat->mFormatFlags     |= kAudioFormatFlagIsBigEndian;
186      clientFormat->mBitsPerChannel   = sizeof(short) * 8;
187      clientFormat->mFramesPerPacket  = 1;
188      clientFormat->mBytesPerFrame    = clientFormat->mBitsPerChannel * clientFormat->mChannelsPerFrame / 8;
189      clientFormat->mBytesPerPacket   = clientFormat->mFramesPerPacket * clientFormat->mBytesPerFrame;
190      break;
191    default:
192      break;
193  }
194}
195
196uint_t aubio_sink_apple_audio_get_samplerate(const aubio_sink_apple_audio_t *s)
197{
198  return s->samplerate;
199}
200
201uint_t aubio_sink_apple_audio_get_channels(const aubio_sink_apple_audio_t *s)
202{
203  return s->channels;
204}
205
206uint_t aubio_sink_apple_audio_open(aubio_sink_apple_audio_t *s) {
207
208  if (s->samplerate == 0 || s->channels == 0) return AUBIO_FAIL;
209
210  CFURLRef fileURL = createURLFromPath(s->path);
211  bool overwrite = true;
212
213  // set the in-memory format
214  AudioStreamBasicDescription inputFormat;
215  memset(&inputFormat, 0, sizeof(AudioStreamBasicDescription));
216  inputFormat.mFormatID         = kAudioFormatLinearPCM;
217  inputFormat.mSampleRate       = (Float64)(s->samplerate);
218  inputFormat.mFormatFlags      = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked;
219  inputFormat.mChannelsPerFrame = s->channels;
220  inputFormat.mBitsPerChannel   = sizeof(smpl_t) * 8;
221  inputFormat.mFramesPerPacket  = 1;
222  inputFormat.mBytesPerFrame    = inputFormat.mBitsPerChannel * inputFormat.mChannelsPerFrame / 8;
223  inputFormat.mBytesPerPacket   = inputFormat.mFramesPerPacket * inputFormat.mBytesPerFrame;
224
225  // get the in-file format
226  AudioStreamBasicDescription clientFormat;
227  aubio_sink_apple_audio_set_client_format(s, &clientFormat);
228
229  OSStatus err = noErr;
230  err = ExtAudioFileCreateWithURL(fileURL, s->fileType, &clientFormat, NULL,
231     overwrite ? kAudioFileFlags_EraseFile : 0, &s->audioFile);
232  CFRelease(fileURL);
233  if (err) {
234    char_t errorstr[20];
235    AUBIO_ERR("sink_apple_audio: error when trying to create %s with "
236        "ExtAudioFileCreateWithURL (%s)\n", s->path,
237        getPrintableOSStatusError(errorstr, err));
238    goto beach;
239  }
240
241#if defined(kAppleSoftwareAudioCodecManufacturer)
242  // on iOS, set software based encoding before setting clientDataFormat
243  UInt32 codecManf = kAppleSoftwareAudioCodecManufacturer;
244  err = ExtAudioFileSetProperty(s->audioFile,
245      kExtAudioFileProperty_CodecManufacturer,
246      sizeof(UInt32), &codecManf);
247  if (err) {
248    char_t errorstr[20];
249    AUBIO_ERR("sink_apple_audio: error when trying to set sofware codec on %s "
250        "(%s)\n", s->path, getPrintableOSStatusError(errorstr, err));
251    goto beach;
252  }
253#endif
254
255  err = ExtAudioFileSetProperty(s->audioFile,
256      kExtAudioFileProperty_ClientDataFormat,
257      sizeof(AudioStreamBasicDescription), &inputFormat);
258  if (err) {
259    char_t errorstr[20];
260    AUBIO_ERR("sink_apple_audio: error when trying to set output format on %s "
261        "(%s)\n", s->path, getPrintableOSStatusError(errorstr, err));
262    goto beach;
263  }
264
265  if (createAudioBufferList(&s->bufferList, s->channels, s->max_frames * s->channels)) {
266    AUBIO_ERR("sink_apple_audio: error when creating buffer list for %s, "
267        "out of memory? \n", s->path);
268    goto beach;
269  }
270  return AUBIO_OK;
271
272beach:
273  return AUBIO_FAIL;
274}
275
276void aubio_sink_apple_audio_do(aubio_sink_apple_audio_t * s, fvec_t * write_data, uint_t write) {
277  UInt32 c, v;
278  smpl_t *data = (smpl_t*)s->bufferList.mBuffers[0].mData;
279  uint_t length = aubio_sink_validate_input_length("sink_apple_audio", s->path,
280      s->max_frames, write_data->length, write);
281
282  for (c = 0; c < s->channels; c++) {
283    for (v = 0; v < length; v++) {
284      data[v * s->channels + c] = write_data->data[v];
285    }
286  }
287
288  aubio_sink_apple_audio_write(s, length);
289}
290
291void aubio_sink_apple_audio_do_multi(aubio_sink_apple_audio_t * s, fmat_t * write_data, uint_t write) {
292  UInt32 c, v;
293  smpl_t *data = (smpl_t*)s->bufferList.mBuffers[0].mData;
294  uint_t channels = aubio_sink_validate_input_channels("sink_apple_audio",
295      s->path, s->channels, write_data->height);
296  uint_t length = aubio_sink_validate_input_length("sink_apple_audio", s->path,
297      s->max_frames, write_data->length, write);
298
299  for (c = 0; c < channels; c++) {
300    for (v = 0; v < length; v++) {
301      data[v * s->channels + c] = write_data->data[c][v];
302    }
303  }
304
305  aubio_sink_apple_audio_write(s, length);
306}
307
308void aubio_sink_apple_audio_write(aubio_sink_apple_audio_t *s, uint_t write) {
309  OSStatus err = noErr;
310  // set mDataByteSize to match the number of frames to be written
311  // see https://www.mail-archive.com/coreaudio-api@lists.apple.com/msg01109.html
312  s->bufferList.mBuffers[0].mDataByteSize = write * s->channels
313    * sizeof(smpl_t);
314  if (s->async) {
315    err = ExtAudioFileWriteAsync(s->audioFile, write, &s->bufferList);
316    if (err) {
317      char_t errorstr[20];
318      if (err == kExtAudioFileError_AsyncWriteBufferOverflow) {
319        sprintf(errorstr,"buffer overflow");
320      } else if (err == kExtAudioFileError_AsyncWriteTooLarge) {
321        sprintf(errorstr,"write too large");
322      } else {
323        // unknown error
324        getPrintableOSStatusError(errorstr, err);
325      }
326      AUBIO_ERROR("sink_apple_audio: error while writing %s "
327                  "in ExtAudioFileWriteAsync (%s)\n", s->path, errorstr);
328    }
329  } else {
330    err = ExtAudioFileWrite(s->audioFile, write, &s->bufferList);
331    if (err) {
332      char_t errorstr[20];
333      AUBIO_ERROR("sink_apple_audio: error while writing %s "
334          "in ExtAudioFileWrite (%s)\n", s->path,
335          getPrintableOSStatusError(errorstr, err));
336    }
337  }
338}
339
340uint_t aubio_sink_apple_audio_close(aubio_sink_apple_audio_t * s) {
341  OSStatus err = noErr;
342  if (!s->audioFile) {
343    return AUBIO_FAIL;
344  }
345  err = ExtAudioFileDispose(s->audioFile);
346  if (err) {
347    char_t errorstr[20];
348    AUBIO_ERROR("sink_apple_audio: error while closing %s "
349        "in ExtAudioFileDispose (%s)\n", s->path,
350        getPrintableOSStatusError(errorstr, err));
351  }
352  s->audioFile = NULL;
353  return err;
354}
355
356void del_aubio_sink_apple_audio(aubio_sink_apple_audio_t * s) {
357  AUBIO_ASSERT(s);
358  if (s->audioFile)
359    aubio_sink_apple_audio_close (s);
360  if (s->path)
361    AUBIO_FREE(s->path);
362  freeAudioBufferList(&s->bufferList);
363  AUBIO_FREE(s);
364}
365
366#endif /* HAVE_SINK_APPLE_AUDIO */
Note: See TracBrowser for help on using the repository browser.