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