Merge branch 'maint'
[paraslash.git] / osx_write.c
1 /*
2  * Copyright (C) 2006-2009 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file osx_write.c paraslash's output plugin for MacOs */
8
9 /*
10  * based on mosx-mpg123, by Guillaume Outters and Steven A. Kortze
11  * <skortze@sourceforge.net>
12  */
13
14 #include <regex.h>
15 #include <sys/types.h>
16 #include <dirent.h>
17 #include <CoreAudio/CoreAudio.h>
18
19 #include "para.h"
20 #include "fd.h"
21 #include "string.h"
22 #include "list.h"
23 #include "sched.h"
24 #include "ggo.h"
25 #include "write.h"
26 #include "osx_write.cmdline.h"
27 #include "error.h"
28
29
30 #include <CoreAudio/CoreAudio.h>
31 #include <AudioUnit/AudioUnit.h>
32 #include <AudioToolbox/DefaultAudioOutput.h>
33
34 /** describes one input buffer for the osx writer */
35 struct osx_buffer {
36         /** pointer to the beginning of the buffer */
37         float *buffer;
38         /** the size of this buffer */
39         long size;
40         /** current position in the buffer */
41         float *ptr;
42         /** number of floats not yet consuned */
43         long remaining;
44         /** pointer to the next audio buffer */
45         struct osx_buffer *next;
46 };
47
48 /** data specific to the osx writer */
49 struct private_osx_write_data {
50         /** the main control structure for audio data manipulation */
51         AudioUnit audio_unit;
52         /** non-zero if playback has started */
53         char play;
54         /** callback reads audio data from this buffer */
55         struct osx_buffer *from;
56         /** the post_select writes audio data here */
57         struct osx_buffer *to;
58         /** sample rate of the current audio stream */
59         unsigned samplerate;
60         /** number of channels of the current audio stream */
61         unsigned channels;
62 };
63
64 static void destroy_buffers(struct private_osx_write_data *powd)
65 {
66         struct osx_buffer *ptr;
67         struct osx_buffer *ptr2;
68         ptr = powd->to->next;
69         powd->to->next = NULL;
70         while (ptr) {
71                 ptr2 = ptr->next;
72                 free(ptr->buffer);
73                 free(ptr);
74                 ptr = ptr2;
75         }
76 }
77
78 static void init_buffers(struct writer_node *wn)
79 {
80         struct private_osx_write_data *powd = wn->private_data;
81         struct osx_write_args_info *conf = wn->conf;
82         struct osx_buffer **ptrptr;
83         int i;
84
85         ptrptr = &powd->to;
86         for (i = 0; i < conf->numbuffers_arg; i++) {
87                 *ptrptr = para_malloc(sizeof(struct osx_buffer));
88                 (*ptrptr)->size = 0;
89                 (*ptrptr)->remaining = 0;
90                 (*ptrptr)->buffer = NULL;
91                 ptrptr = &(*ptrptr)->next;
92         }
93         *ptrptr = powd->from = powd->to;
94 }
95
96 static void fill_buffer(struct osx_buffer *b, short *source, long size)
97 {
98         float *dest;
99
100         if (b->remaining) /* Non empty buffer, must still be playing */
101                 return;
102         if (b->size != size) {
103                 b->buffer = para_realloc(b->buffer, size * sizeof(float));
104                 b->size = size;
105         }
106         dest = b->buffer;
107         while (size--)
108                 *dest++ = (*source++) / 32768.0;
109         b->ptr = b->buffer;
110         b->remaining = b->size;
111 }
112
113 static OSStatus osx_callback(void * inClientData,
114         __a_unused AudioUnitRenderActionFlags *inActionFlags,
115         __a_unused const AudioTimeStamp *inTimeStamp,
116         __a_unused  UInt32 inBusNumber,
117         __a_unused UInt32 inNumFrames,
118         AudioBufferList *outOutputData)
119 {
120         long m, n;
121         float *dest;
122         int i;
123         struct private_osx_write_data *powd = inClientData;
124
125 //      PARA_INFO_LOG("%p\n", powd);
126         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
127                 /* what we have to fill */
128                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
129                 dest = outOutputData->mBuffers[i].mData;
130                 while (m > 0) {
131                         if ((n = powd->from->remaining) <= 0) {
132                                 PARA_INFO_LOG("buffer underrun\n");
133                                 return 0;
134                         }
135 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
136                         /*
137                          * we dump what we can. In fact, just the necessary
138                          * should be sufficient
139                          */
140                         if (n > m)
141                                 n = m;
142                         memcpy(dest, powd->from->ptr, n * sizeof(float));
143                         dest += n;
144                         /* remember all done work */
145                         m -= n;
146                         powd->from->ptr += n;
147                         if ((powd->from->remaining -= n) <= 0)
148                                 powd->from = powd->from->next;
149                 }
150         }
151         return 0;
152 }
153
154 #ifdef WORDS_BIGENDIAN /* ppc */
155 #define ENDIAN_FLAGS kLinearPCMFormatFlagIsBigEndian
156 #else
157 #define ENDIAN_FLAGS 0
158 #endif
159
160 static int osx_write_open(struct writer_node *wn)
161 {
162         struct private_osx_write_data *powd = para_calloc(
163                 sizeof(struct private_osx_write_data));
164         ComponentDescription desc;
165         Component comp;
166         AURenderCallbackStruct inputCallback = {osx_callback, powd};
167         AudioStreamBasicDescription format;
168         int ret;
169         struct writer_node_group *wng = wn->wng;
170         struct osx_write_args_info *conf = wn->conf;
171
172         wn->private_data = powd;
173         /* where did that default audio output go? */
174         desc.componentType = kAudioUnitType_Output;
175         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
176         /* NOTE: and if default output isn't Apple? */
177         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
178         desc.componentFlags = 0;
179         desc.componentFlagsMask = 0;
180         ret = -E_DEFAULT_COMP;
181         comp = FindNextComponent(NULL, &desc);
182         if (!comp)
183                 goto e0;
184         ret = -E_OPEN_COMP;
185         if (OpenAComponent(comp, &powd->audio_unit))
186                 goto e0;
187         ret = -E_UNIT_INIT;
188         if (AudioUnitInitialize(powd->audio_unit))
189                 goto e1;
190         powd->play = 0;
191         /* Hmmm, let's choose PCM format */
192         /* We tell the Output Unit what format we're going to supply data to it.
193          * This is necessary if you're providing data through an input callback
194          * AND you want the DefaultOutputUnit to do any format conversions
195          * necessary from your format to the device's format.
196          */
197         if (!conf->samplerate_given && wng->samplerate)
198                 powd->samplerate = *wng->samplerate;
199         else
200                 powd->samplerate = conf->samplerate_arg;
201         format.mSampleRate = powd->samplerate;
202         /* The specific encoding type of audio stream*/
203         format.mFormatID = kAudioFormatLinearPCM;
204         /* flags specific to each format */
205         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
206                 | kLinearPCMFormatFlagIsPacked
207                 | ENDIAN_FLAGS;
208         if (!conf->channels_given && wng->channels)
209                 powd->channels = *wng->channels;
210         else
211                 powd->channels = conf->channels_arg;
212         format.mChannelsPerFrame = powd->channels;
213         format.mFramesPerPacket = 1;
214         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
215         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
216         /* one of the most constant constants of the whole computer history */
217         format.mBitsPerChannel = sizeof(float) * 8;
218         ret = -E_STREAM_FORMAT;
219         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
220                         kAudioUnitScope_Input, 0, &format,
221                         sizeof(AudioStreamBasicDescription)))
222                 goto e2;
223         init_buffers(wn);
224         ret = -E_ADD_CALLBACK;
225         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
226                         kAudioUnitScope_Input, 0, &inputCallback,
227                         sizeof(inputCallback)) < 0)
228                 goto e3;
229         return 1;
230 e3:
231         destroy_buffers(powd);
232 e2:
233         AudioUnitUninitialize(powd->audio_unit);
234 e1:
235         CloseComponent(powd->audio_unit);
236 e0:
237         return ret;
238 }
239
240 __malloc static void *osx_write_parse_config(const char *options)
241 {
242         struct osx_write_args_info *conf
243                 = para_calloc(sizeof(struct osx_write_args_info));
244         PARA_INFO_LOG("options: %s\n", options);
245         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
246         if (ret)
247                 goto err_out;
248         return conf;
249 err_out:
250         free(conf);
251         return NULL;
252
253 }
254
255 static void osx_write_close(struct writer_node *wn)
256 {
257         struct private_osx_write_data *powd = wn->private_data;
258
259         PARA_INFO_LOG("closing writer node %p\n", wn);
260         AudioOutputUnitStop(powd->audio_unit);
261         AudioUnitUninitialize(powd->audio_unit);
262         CloseComponent(powd->audio_unit);
263         destroy_buffers(powd);
264         free(powd);
265 }
266
267 static int need_new_buffer(struct writer_node *wn)
268 {
269         struct writer_node_group *wng = wn->wng;
270         struct private_osx_write_data *powd = wn->private_data;
271
272         if (*wng->loaded < sizeof(short))
273                 return 0;
274         if (powd->to->remaining) /* Non empty buffer, must still be playing */
275                 return 0;
276         return 1;
277 }
278
279 static int osx_write_post_select(__a_unused struct sched *s,
280                 struct writer_node *wn)
281 {
282         struct private_osx_write_data *powd = wn->private_data;
283         struct writer_node_group *wng = wn->wng;
284         short *data = (short*)*wng->bufp;
285
286         if (!need_new_buffer(wn))
287                 return 1;
288         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
289         powd->to = powd->to->next;
290         wn->written = *wng->loaded;
291         if (!powd->play) {
292                 if (AudioOutputUnitStart(powd->audio_unit))
293                         return -E_UNIT_START;
294                 powd->play = 1;
295         }
296         return 1;
297 }
298
299 static int osx_write_pre_select(struct sched *s, __a_unused struct writer_node *wn)
300 {
301         struct private_osx_write_data *powd = wn->private_data;
302         struct writer_node_group *wng = wn->wng;
303         size_t numbytes = powd->to->remaining * sizeof(short);
304         struct timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
305         unsigned long divisor;
306
307         if (!numbytes && *wng->loaded >= sizeof(short))
308                 goto min_delay; /* there's a buffer to fill */
309         if (!numbytes)
310                 return 1;
311         divisor = powd->samplerate * powd->channels * 2 / numbytes;
312         if (divisor)
313                 tv_divide(divisor, &tmp, &delay);
314         if (tv_diff(&s->timeout, &delay, NULL) > 0)
315                 s->timeout = delay;
316 //      PARA_DEBUG_LOG("delay: %lu:%lu\n", (long unsigned) s->timeout.tv_sec,
317 //              (long unsigned) s->timeout.tv_usec);
318         return 1;
319 min_delay:
320         PARA_DEBUG_LOG("%s\n", "minimal delay");
321         s->timeout.tv_sec = 0;
322         s->timeout.tv_usec = 1;
323         return 1;
324 }
325
326 /** the init function of the osx writer */
327 void osx_write_init(struct writer *w)
328 {
329         w->open = osx_write_open;
330         w->close = osx_write_close;
331         w->pre_select = osx_write_pre_select;
332         w->post_select = osx_write_post_select;
333         w->parse_config = osx_write_parse_config;
334         w->shutdown = NULL; /* nothing to do */
335 }