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