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