Add UNIT_START errno
[paraslash.git] / osx_writer.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_writer.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;
48
49 struct private_osx_writer_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_writer_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                 if (ptr->buffer)
79                         free(ptr->buffer);
80                 free(ptr);
81                 ptr = ptr2;
82         }
83 }
84
85 static void init_buffers(struct private_osx_writer_data *powd)
86 {
87         int i;
88
89         osx_buffer ** ptrptr;
90         ptrptr = &powd->to;
91         for (i = 0; i < NUMBER_BUFFERS; i++) {
92                 *ptrptr = malloc(sizeof(osx_buffer));
93                 (*ptrptr)->size = 0;
94                 (*ptrptr)->remaining = 0;
95                 (*ptrptr)->buffer = NULL;
96                 ptrptr = &(*ptrptr)->next;
97                 /* This buffer is ready for filling (of course, it is empty!) */
98         }
99         *ptrptr = powd->from = powd->to;
100 }
101
102 static void fill_buffer(osx_buffer *b, short *source, long size)
103 {
104         float *dest;
105
106         if (b->remaining) /* Non empty buffer, must still be playing */
107                 return;
108         PARA_INFO_LOG("%ld\n", size);
109         if (b->size != size) {
110                 /*
111                  * Hey! What's that? Coudn't this buffer size be fixed
112                  * once (well, perhaps we just didn't allocate it yet)
113                  */
114                 if (b->buffer)
115                         free(b->buffer);
116                 b->buffer = malloc(size * sizeof(float));
117                 b->size = size;
118         }
119         dest = b->buffer;
120         while (size--) {
121                 char *tmp = (char *)source;
122                 char c = *tmp;
123                 *tmp = *(tmp + 1);
124                 *(tmp + 1) = c;
125                 /* *dest++ = ((*source++) + 32768) / 65536.0; */
126                 *dest++ = (*source++) / 32768.0;
127         }
128         b->ptr = b->buffer;
129         b->remaining = b->size;
130 }
131
132 static OSStatus osx_callback(void * inClientData,
133         __a_unused AudioUnitRenderActionFlags *inActionFlags,
134         __a_unused const AudioTimeStamp *inTimeStamp,
135         __a_unused  UInt32 inBusNumber,
136         __a_unused UInt32 inNumFrames,
137         AudioBufferList *outOutputData)
138 {
139         long m, n;
140         float *dest;
141         int i;
142         struct private_osx_writer_data *powd = inClientData;
143
144 //      PARA_INFO_LOG("%p\n", powd);
145         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
146                 /* what we have to fill */
147                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
148                 dest = outOutputData->mBuffers[i].mData;
149                 while (m > 0) {
150                         if ((n = powd->from->remaining) <= 0) {
151                                 PARA_INFO_LOG("%s", "buffer underrun\n");
152                                 /* no more bytes in the current read buffer! */
153                                 while ((n = powd->from->remaining) <= 0)
154                                         /* wait for the results */
155                                         usleep(2000);
156                         }
157                         PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
158                         /*
159                          * we dump what we can. In fact, just the necessary
160                          * should be sufficient
161                          */
162                         if (n > m)
163                                 n = m;
164                         memcpy(dest, powd->from->ptr, n * sizeof(float));
165                         dest += n;
166                         /* remember all done work */
167                         m -= n;
168                         powd->from->ptr += n;
169                         if ((powd->from->remaining -= n) <= 0)
170                                 powd->from = powd->from->next;
171                 }
172         }
173         return 0;
174 }
175
176 static int osx_writer_open(struct writer_node *wn)
177 {
178         struct private_osx_writer_data *powd = para_calloc(
179                 sizeof(struct private_osx_writer_data));
180         ComponentDescription desc;
181         Component comp;
182         AURenderCallbackStruct inputCallback = {osx_callback, powd};
183         AudioStreamBasicDescription format;
184         int ret;
185         struct writer_node_group *wng = wn->wng;
186         struct osx_write_args_info *conf = wn->conf;
187
188         wn->private_data = powd;
189         /* where did that default audio output go? */
190         desc.componentType = kAudioUnitType_Output;
191         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
192         /* NOTE: and if default output isn't Apple? */
193         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
194         desc.componentFlags = 0;
195         desc.componentFlagsMask = 0;
196         ret = -E_DEFAULT_COMP;
197         comp = FindNextComponent(NULL, &desc);
198         if (!comp)
199                 goto e0;
200         ret = -E_OPEN_COMP;
201         if (OpenAComponent(comp, &powd->output))
202                 goto e0;
203         ret = -E_UNIT_INIT;
204         if (AudioUnitInitialize(powd->output))
205                 goto e1;
206         powd->size = 0;
207         powd->ptr = NULL;
208         powd->play = 0;
209         /* Hmmm, let's choose PCM format */
210         /* We tell the Output Unit what format we're going to supply data to it.
211          * This is necessary if you're providing data through an input callback
212          * AND you want the DefaultOutputUnit to do any format conversions
213          * necessary from your format to the device's format.
214          */
215         if (!conf->samplerate_given && wng->samplerate)
216                 powd->samplerate = *wng->samplerate;
217         else
218                 powd->samplerate = conf->samplerate_arg;
219         format.mSampleRate = powd->samplerate;
220         /* The specific encoding type of audio stream*/
221         format.mFormatID = kAudioFormatLinearPCM;
222         /* flags specific to each format */
223         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
224                 | kLinearPCMFormatFlagIsPacked
225                 | kLinearPCMFormatFlagIsBigEndian;
226         if (!conf->channels_given && wng->channels)
227                 powd->channels = *wng->channels;
228         else
229                 powd->channels = conf->channels_arg;
230         format.mChannelsPerFrame = powd->channels;
231         format.mFramesPerPacket = 1;
232         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
233         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
234         /* one of the most constant constants of the whole computer history */
235         format.mBitsPerChannel = sizeof(float) * 8;
236         ret = -E_STREAM_FORMAT;
237         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_StreamFormat,
238                         kAudioUnitScope_Input, 0, &format,
239                         sizeof(AudioStreamBasicDescription)))
240                 goto e2;
241         init_buffers(powd);
242         ret = -E_ADD_CALLBACK;
243         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_SetRenderCallback,
244                         kAudioUnitScope_Input, 0, &inputCallback,
245                         sizeof(inputCallback)) < 0)
246                 goto e3;
247         return 1;
248 e3:
249         destroy_buffers(powd);
250 e2:
251         AudioUnitUninitialize(powd->output);
252 e1:
253         CloseComponent(powd->output);
254 e0:
255         return ret;
256 }
257
258 __malloc void *osx_write_parse_config(char *options)
259 {
260         struct osx_write_args_info *conf
261                 = para_calloc(sizeof(struct osx_write_args_info));
262         PARA_INFO_LOG("options: %s\n", options);
263         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
264         if (ret)
265                 goto err_out;
266         return conf;
267 err_out:
268         free(conf);
269         return NULL;
270
271 }
272
273 static void osx_writer_close(struct writer_node *wn)
274 {
275         struct private_osx_writer_data *powd = wn->private_data;
276
277         PARA_INFO_LOG("closing writer node %p\n", wn);
278         AudioOutputUnitStop(powd->output);
279         AudioUnitUninitialize(powd->output);
280         CloseComponent(powd->output);
281         destroy_buffers(powd);
282         free(powd);
283 }
284
285 static int need_new_buffer(struct writer_node *wn)
286 {
287         struct writer_node_group *wng = wn->wng;
288         struct private_osx_writer_data *powd = wn->private_data;
289
290         if (*wng->loaded < sizeof(short))
291                 return 0;
292         if (powd->to->remaining) /* Non empty buffer, must still be playing */
293                 return 0;
294         return 1;
295 }
296
297 static int osx_write_post_select(__a_unused struct sched *s,
298                 struct writer_node *wn)
299 {
300         struct private_osx_writer_data *powd = wn->private_data;
301         struct writer_node_group *wng = wn->wng;
302         short *data = (short*)wng->buf;
303
304         if (!need_new_buffer(wn))
305                 return 1;
306         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
307         powd->to = powd->to->next;
308         wn->written = *wng->loaded;
309         if (!powd->play) {
310                 if (AudioOutputUnitStart(powd->output))
311                         return -E_UNIT_START;
312                 powd->play = 1;
313         }
314         return 1;
315 }
316
317 static int osx_write_pre_select(struct sched *s, __a_unused struct writer_node *wn)
318 {
319         s->timeout.tv_sec = 0;
320         s->timeout.tv_usec = 20;
321         return 1;
322 }
323
324 void osx_writer_init(struct writer *w)
325 {
326         w->open = osx_writer_open;
327         w->close = osx_writer_close;
328         w->pre_select = osx_write_pre_select;
329         w->post_select = osx_write_post_select;
330         w->parse_config = osx_write_parse_config;
331         w->shutdown = NULL; /* nothing to do */
332 }