filter: Clarify help text of --no-default-filters.
[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 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         assert(b->remaining == 0 || size > 0);
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                         n = powd->from->remaining;
132                         if (n <= 0) {
133                                 n = powd->from->next->remaining;
134                                 if (n <= 0) {
135                                         PARA_INFO_LOG("buffer underrun\n");
136                                         return 0;
137                                 }
138                                 powd->from = powd->from->next;
139                         }
140 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
141                         /*
142                          * we dump what we can. In fact, just the necessary
143                          * should be sufficient
144                          */
145                         if (n > m)
146                                 n = m;
147                         memcpy(dest, powd->from->ptr, n * sizeof(float));
148                         dest += n;
149                         /* remember all done work */
150                         m -= n;
151                         powd->from->ptr += n;
152                         if ((powd->from->remaining -= n) <= 0)
153                                 powd->from = powd->from->next;
154                 }
155         }
156         return 0;
157 }
158
159 #ifdef WORDS_BIGENDIAN /* ppc */
160 #define ENDIAN_FLAGS kLinearPCMFormatFlagIsBigEndian
161 #else
162 #define ENDIAN_FLAGS 0
163 #endif
164
165 static int osx_write_open(struct writer_node *wn)
166 {
167         struct private_osx_write_data *powd = para_calloc(
168                 sizeof(struct private_osx_write_data));
169         ComponentDescription desc;
170         Component comp;
171         AURenderCallbackStruct inputCallback = {osx_callback, powd};
172         AudioStreamBasicDescription format;
173         int ret;
174         struct btr_node *btrn = wn->btrn;
175         struct osx_write_args_info *conf = wn->conf;
176
177         wn->private_data = powd;
178         /* where did that default audio output go? */
179         desc.componentType = kAudioUnitType_Output;
180         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
181         /* NOTE: and if default output isn't Apple? */
182         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
183         desc.componentFlags = 0;
184         desc.componentFlagsMask = 0;
185         ret = -E_DEFAULT_COMP;
186         comp = FindNextComponent(NULL, &desc);
187         if (!comp)
188                 goto e0;
189         ret = -E_OPEN_COMP;
190         if (OpenAComponent(comp, &powd->audio_unit))
191                 goto e0;
192         ret = -E_UNIT_INIT;
193         if (AudioUnitInitialize(powd->audio_unit))
194                 goto e1;
195         powd->play = 0;
196         powd->samplerate = conf->samplerate_arg;
197         powd->channels = conf->channels_arg;
198         if (!conf->samplerate_given) {
199                 int32_t rate;
200                 if (get_btr_samplerate(btrn, &rate) >= 0)
201                         powd->samplerate = rate;
202         }
203         if (!conf->channels_given) {
204                 int32_t ch;
205                 if (get_btr_channels(btrn, &ch) >= 0)
206                         powd->channels = ch;
207         }
208         /*
209          * Choose PCM format. We tell the Output Unit what format we're going
210          * to supply data to it. This is necessary if you're providing data
211          * through an input callback AND you want the DefaultOutputUnit to do
212          * any format conversions necessary from your format to the device's
213          * format.
214          */
215         format.mSampleRate = powd->samplerate;
216         /* The specific encoding type of audio stream */
217         format.mFormatID = kAudioFormatLinearPCM;
218         /* flags specific to each format */
219         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
220                 | kLinearPCMFormatFlagIsPacked
221                 | ENDIAN_FLAGS;
222         format.mChannelsPerFrame = powd->channels;
223         format.mFramesPerPacket = 1;
224         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
225         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
226         /* one of the most constant constants of the whole computer history */
227         format.mBitsPerChannel = sizeof(float) * 8;
228         ret = -E_STREAM_FORMAT;
229         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
230                         kAudioUnitScope_Input, 0, &format,
231                         sizeof(AudioStreamBasicDescription)))
232                 goto e2;
233         init_buffers(wn);
234         ret = -E_ADD_CALLBACK;
235         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
236                         kAudioUnitScope_Input, 0, &inputCallback,
237                         sizeof(inputCallback)) < 0)
238                 goto e3;
239         wn->min_iqs = powd->channels * 2;
240         return 1;
241 e3:
242         destroy_buffers(powd);
243 e2:
244         AudioUnitUninitialize(powd->audio_unit);
245 e1:
246         CloseComponent(powd->audio_unit);
247 e0:
248         return ret;
249 }
250
251 __malloc static void *osx_write_parse_config(const char *options)
252 {
253         struct osx_write_args_info *conf
254                 = para_calloc(sizeof(struct osx_write_args_info));
255         PARA_INFO_LOG("options: %s\n", options);
256         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
257         if (ret)
258                 goto err_out;
259         return conf;
260 err_out:
261         free(conf);
262         return NULL;
263
264 }
265
266 static void osx_free_config(void *conf)
267 {
268         osx_cmdline_parser_free(conf);
269 }
270
271 static void osx_write_close(struct writer_node *wn)
272 {
273         struct private_osx_write_data *powd = wn->private_data;
274
275         PARA_INFO_LOG("closing writer node %p\n", wn);
276         AudioOutputUnitStop(powd->audio_unit);
277         AudioUnitUninitialize(powd->audio_unit);
278         CloseComponent(powd->audio_unit);
279         destroy_buffers(powd);
280         free(powd);
281 }
282
283 static void osx_write_post_select(__a_unused struct sched *s, struct task *t)
284 {
285         struct writer_node *wn = container_of(t, struct writer_node, task);
286         struct private_osx_write_data *powd = wn->private_data;
287         struct btr_node *btrn = wn->btrn;
288         char *data;
289         size_t bytes;
290         int ret = 0;
291
292         while (powd->to->remaining <= 0) {
293                 ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
294                 if (ret <= 0)
295                         break;
296                 btr_merge(btrn, 8192);
297                 bytes = btr_next_buffer(btrn, &data);
298                 //PARA_CRIT_LOG("have: %zu\n", bytes);
299                 fill_buffer(powd->to, (short *)data, bytes / sizeof(short));
300                 btr_consume(btrn, bytes);
301                 if (!powd->play) {
302                         ret = -E_UNIT_START;
303                         if (AudioOutputUnitStart(powd->audio_unit))
304                                 break;
305                         powd->play = 1;
306                 }
307                 powd->to = powd->to->next;
308         }
309         if (ret < 0)
310                 btr_remove_node(btrn);
311         t->error = ret;
312 }
313
314 static void osx_write_pre_select(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 timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
319         unsigned long divisor;
320         size_t numbytes = powd->to->remaining * sizeof(short);
321         int ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
322
323         if (ret < 0)
324                 sched_min_delay(s);
325         if (ret <= 0 || numbytes < wn->min_iqs)
326                 return;
327         divisor = powd->samplerate * wn->min_iqs / numbytes;
328         if (divisor)
329                 tv_divide(divisor, &tmp, &delay);
330         sched_request_timeout(&delay, s);
331 }
332
333 /** the init function of the osx writer */
334 void osx_write_init(struct writer *w)
335 {
336         struct osx_write_args_info dummy;
337
338         osx_cmdline_parser_init(&dummy);
339         w->open = osx_write_open;
340         w->close = osx_write_close;
341         w->pre_select = osx_write_pre_select;
342         w->post_select = osx_write_post_select;
343         w->parse_config = osx_write_parse_config;
344         w->free_config = osx_free_config;
345         w->shutdown = NULL; /* nothing to do */
346         w->help = (struct ggo_help) {
347                 .short_help = osx_write_args_info_help,
348                 .detailed_help = osx_write_args_info_detailed_help
349         };
350         osx_cmdline_parser_free(&dummy);
351 }