cfd02e7453b1ccac04eb951e5f42009801806b55
[paraslash.git] / osx_write.c
1 /*
2  * Copyright (C) 2006-2010 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 sample_rate;
61         /** Sample format of the current audio stream */
62         unsigned sample_format;
63         /** number of channels of the current audio stream */
64         unsigned channels;
65 };
66
67 static void destroy_buffers(struct private_osx_write_data *powd)
68 {
69         struct osx_buffer *ptr;
70         struct osx_buffer *ptr2;
71         ptr = powd->to->next;
72         powd->to->next = NULL;
73         while (ptr) {
74                 ptr2 = ptr->next;
75                 free(ptr->buffer);
76                 free(ptr);
77                 ptr = ptr2;
78         }
79 }
80
81 static void init_buffers(struct writer_node *wn)
82 {
83         struct private_osx_write_data *powd = wn->private_data;
84         struct osx_write_args_info *conf = wn->conf;
85         struct osx_buffer **ptrptr;
86         int i;
87
88         ptrptr = &powd->to;
89         for (i = 0; i < conf->numbuffers_arg; i++) {
90                 *ptrptr = para_malloc(sizeof(struct osx_buffer));
91                 (*ptrptr)->size = 0;
92                 (*ptrptr)->remaining = 0;
93                 (*ptrptr)->buffer = NULL;
94                 ptrptr = &(*ptrptr)->next;
95         }
96         *ptrptr = powd->from = powd->to;
97 }
98
99 static void fill_buffer(struct private_osx_write_data *powd, char *data, long bytes)
100 {
101         struct osx_buffer *b = powd->to;
102         float *dest;
103         long samples;
104         enum sample_format sf = powd->sample_format;
105
106         samples = (sf == SF_S8 || sf == SF_U8)? bytes : bytes / 2;
107         assert(b->remaining == 0 || samples > 0);
108         if (b->size != samples) {
109                 b->buffer = para_realloc(b->buffer, samples * sizeof(float));
110                 b->size = samples;
111         }
112         dest = b->buffer;
113         switch (powd->sample_format) {
114         case SF_U8: {
115                 uint8_t *src = (uint8_t *)data;
116                 while (samples--) {
117                         *dest++ = (*src++) / 256.0;
118                 }
119                 break;
120         }
121         case SF_S8: {
122                 int8_t *src = (int8_t *)data;
123                 while (samples--) {
124                         *dest++ = ((*src++) + 128) / 256.0;
125                 }
126                 break;
127         }
128         default: {
129                 short *src = (short *)data;
130                 while (samples--)
131                         *dest++ = (*src++) / 32768.0;
132         }
133         }
134         b->ptr = b->buffer;
135         b->remaining = b->size;
136 }
137
138 static OSStatus osx_callback(void * inClientData,
139         __a_unused AudioUnitRenderActionFlags *inActionFlags,
140         __a_unused const AudioTimeStamp *inTimeStamp,
141         __a_unused  UInt32 inBusNumber,
142         __a_unused UInt32 inNumFrames,
143         AudioBufferList *outOutputData)
144 {
145         long m, n;
146         float *dest;
147         int i;
148         struct private_osx_write_data *powd = inClientData;
149
150 //      PARA_INFO_LOG("%p\n", powd);
151         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
152                 /* what we have to fill */
153                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
154                 dest = outOutputData->mBuffers[i].mData;
155                 while (m > 0) {
156                         n = powd->from->remaining;
157                         if (n <= 0) {
158                                 n = powd->from->next->remaining;
159                                 if (n <= 0) {
160                                         PARA_INFO_LOG("buffer underrun\n");
161                                         return 0;
162                                 }
163                                 powd->from = powd->from->next;
164                         }
165 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
166                         /*
167                          * we dump what we can. In fact, just the necessary
168                          * should be sufficient
169                          */
170                         if (n > m)
171                                 n = m;
172                         memcpy(dest, powd->from->ptr, n * sizeof(float));
173                         dest += n;
174                         /* remember all done work */
175                         m -= n;
176                         powd->from->ptr += n;
177                         if ((powd->from->remaining -= n) <= 0)
178                                 powd->from = powd->from->next;
179                 }
180         }
181         return 0;
182 }
183
184 #ifdef WORDS_BIGENDIAN /* ppc */
185 #define ENDIAN_FLAGS kLinearPCMFormatFlagIsBigEndian
186 #else
187 #define ENDIAN_FLAGS 0
188 #endif
189
190 static int osx_write_open(struct writer_node *wn)
191 {
192         struct private_osx_write_data *powd = para_calloc(sizeof(*powd));
193
194         wn->private_data = powd;
195         init_buffers(wn);
196         return 0;
197 }
198
199 static int core_audio_init(struct writer_node *wn)
200 {
201         struct private_osx_write_data *powd = wn->private_data;
202         ComponentDescription desc;
203         Component comp;
204         AURenderCallbackStruct inputCallback = {osx_callback, powd};
205         AudioStreamBasicDescription format;
206         int ret;
207         struct btr_node *btrn = wn->btrn;
208         int32_t val;
209
210         /* where did that default audio output go? */
211         desc.componentType = kAudioUnitType_Output;
212         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
213         /* NOTE: and if default output isn't Apple? */
214         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
215         desc.componentFlags = 0;
216         desc.componentFlagsMask = 0;
217         ret = -E_DEFAULT_COMP;
218         comp = FindNextComponent(NULL, &desc);
219         if (!comp)
220                 goto e0;
221         ret = -E_OPEN_COMP;
222         if (OpenAComponent(comp, &powd->audio_unit))
223                 goto e0;
224         ret = -E_UNIT_INIT;
225         if (AudioUnitInitialize(powd->audio_unit))
226                 goto e1;
227         powd->play = 0;
228         get_btr_sample_rate(btrn, &val);
229         powd->sample_rate = val;
230         get_btr_channels(btrn, &val);
231         powd->channels = val;
232         get_btr_sample_format(btrn, &val);
233         powd->sample_format = val;
234         /*
235          * Choose PCM format. We tell the Output Unit what format we're going
236          * to supply data to it. This is necessary if you're providing data
237          * through an input callback AND you want the DefaultOutputUnit to do
238          * any format conversions necessary from your format to the device's
239          * format.
240          */
241         format.mFormatID = kAudioFormatLinearPCM;
242         format.mFramesPerPacket = 1;
243         format.mSampleRate = powd->sample_rate;
244         /* flags specific to each format */
245         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
246                 | kLinearPCMFormatFlagIsPacked
247                 | ENDIAN_FLAGS;
248         switch (powd->sample_format) {
249         case SF_S8:
250         case SF_U8:
251                 wn->min_iqs = powd->channels;
252                 break;
253         default:
254                 wn->min_iqs = powd->channels * 2;
255         }
256         format.mBitsPerChannel = 8 * sizeof(float);
257         format.mBytesPerPacket = powd->channels * sizeof(float);
258         format.mBytesPerFrame = format.mBytesPerPacket;
259         format.mChannelsPerFrame = powd->channels;
260
261         ret = -E_STREAM_FORMAT;
262         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
263                         kAudioUnitScope_Input, 0, &format,
264                         sizeof(AudioStreamBasicDescription)))
265                 goto e2;
266         ret = -E_ADD_CALLBACK;
267         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
268                         kAudioUnitScope_Input, 0, &inputCallback,
269                         sizeof(inputCallback)) < 0)
270                 goto e3;
271         return 1;
272 e3:
273         destroy_buffers(powd);
274 e2:
275         AudioUnitUninitialize(powd->audio_unit);
276 e1:
277         CloseComponent(powd->audio_unit);
278 e0:
279         return ret;
280 }
281
282 __malloc static void *osx_write_parse_config(const char *options)
283 {
284         struct osx_write_args_info *conf
285                 = para_calloc(sizeof(struct osx_write_args_info));
286         PARA_INFO_LOG("options: %s\n", options);
287         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
288         if (ret)
289                 goto err_out;
290         return conf;
291 err_out:
292         free(conf);
293         return NULL;
294
295 }
296
297 static void osx_free_config(void *conf)
298 {
299         osx_cmdline_parser_free(conf);
300 }
301
302 static void osx_write_close(struct writer_node *wn)
303 {
304         struct private_osx_write_data *powd = wn->private_data;
305
306         PARA_INFO_LOG("closing writer node %p\n", wn);
307         AudioOutputUnitStop(powd->audio_unit);
308         AudioUnitUninitialize(powd->audio_unit);
309         CloseComponent(powd->audio_unit);
310         destroy_buffers(powd);
311         free(powd);
312 }
313
314 static void osx_write_post_select(__a_unused struct sched *s, struct task *t)
315 {
316         struct writer_node *wn = container_of(t, struct writer_node, task);
317         struct private_osx_write_data *powd = wn->private_data;
318         struct btr_node *btrn = wn->btrn;
319         char *data;
320         size_t bytes;
321         int ret = 0;
322
323         while (powd->to->remaining <= 0) {
324                 ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
325                 if (ret <= 0)
326                         break;
327                 if (powd->sample_rate == 0) {
328                         ret = core_audio_init(wn);
329                         if (ret < 0)
330                                 break;
331                 }
332                 btr_merge(btrn, 8192);
333                 bytes = btr_next_buffer(btrn, &data);
334                 //PARA_CRIT_LOG("have: %zu\n", bytes);
335                 fill_buffer(powd, data, bytes);
336                 btr_consume(btrn, bytes);
337                 if (!powd->play) {
338                         ret = -E_UNIT_START;
339                         if (AudioOutputUnitStart(powd->audio_unit))
340                                 break;
341                         powd->play = 1;
342                 }
343                 powd->to = powd->to->next;
344         }
345         if (ret < 0 && powd->from->remaining <= 0) {
346                 btr_remove_node(btrn);
347                 t->error = ret;
348         }
349 }
350
351 static void osx_write_pre_select(struct sched *s, struct task *t)
352 {
353         struct writer_node *wn = container_of(t, struct writer_node, task);
354         struct private_osx_write_data *powd = wn->private_data;
355         struct timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
356         unsigned long divisor;
357         size_t numbytes = powd->to->remaining * sizeof(short);
358         int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
359
360         if (ret < 0)
361                 sched_min_delay(s);
362         if (ret <= 0 || numbytes < wn->min_iqs)
363                 return;
364         divisor = powd->sample_rate * wn->min_iqs / numbytes;
365         if (divisor)
366                 tv_divide(divisor, &tmp, &delay);
367         sched_request_timeout(&delay, s);
368 }
369
370 /** the init function of the osx writer */
371 void osx_write_init(struct writer *w)
372 {
373         struct osx_write_args_info dummy;
374
375         osx_cmdline_parser_init(&dummy);
376         w->open = osx_write_open;
377         w->close = osx_write_close;
378         w->pre_select = osx_write_pre_select;
379         w->post_select = osx_write_post_select;
380         w->parse_config = osx_write_parse_config;
381         w->free_config = osx_free_config;
382         w->shutdown = NULL; /* nothing to do */
383         w->help = (struct ggo_help) {
384                 .short_help = osx_write_args_info_help,
385                 .detailed_help = osx_write_args_info_detailed_help
386         };
387         osx_cmdline_parser_free(&dummy);
388 }