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