c4a97e4b5ae9c0f2575f8239bb79c43dab45a8f7
[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 #include <CoreAudio/CoreAudio.h>
22 #include "para.h"
23 #include "fd.h"
24 #include "string.h"
25 #include "list.h"
26 #include "sched.h"
27 #include "write.h"
28 #include "osx_write.cmdline.h"
29 #include "error.h"
30
31
32 #include <CoreAudio/CoreAudio.h>
33 #include <AudioUnit/AudioUnit.h>
34 #include <AudioToolbox/DefaultAudioOutput.h>
35 #include <semaphore.h>
36 struct osx_buffer {
37         float *buffer;
38         long size;
39         float *ptr; /* Where in the buffer are we? */
40         long remaining;
41         struct osx_buffer *next;
42 };
43 typedef struct osx_buffer osx_buffer;
44
45 struct private_osx_writer_data {
46         long size;
47         short *ptr;
48         AudioUnit output;
49         char play;
50         sem_t *semaphore;
51         osx_buffer *from; /* Current buffers */
52         osx_buffer *to;
53         unsigned samplerate;
54 };
55
56
57 /*
58  * Tried with 3 buffers, but then any little window move is sufficient to
59  * stop the sound (OK, on a G3 400 with a Public Beta. Perhaps now we can
60  * go down to 2 buffers). With 16 buffers we have 1.5 seconds music
61  * buffered (or, if you're pessimistic, 1.5 seconds latency). Note 0
62  * buffers don't work much further than the Bus error.
63  */
64 #define NUMBER_BUFFERS 2
65
66 static void destroy_buffers(struct private_osx_writer_data *powd)
67 {
68         osx_buffer *ptr;
69         osx_buffer *ptr2;
70         ptr = powd->to->next;
71         powd->to->next = NULL;
72         while (ptr) {
73                 ptr2 = ptr->next;
74                 if (ptr->buffer)
75                         free(ptr->buffer);
76                 free(ptr);
77                 ptr = ptr2;
78         }
79 }
80
81 static void init_buffers(struct private_osx_writer_data *powd)
82 {
83         int i;
84
85         osx_buffer ** ptrptr;
86         ptrptr = &powd->to;
87         for (i = 0; i < NUMBER_BUFFERS; i++) {
88                 *ptrptr = malloc(sizeof(osx_buffer));
89                 (*ptrptr)->size = 0;
90                 (*ptrptr)->remaining = 0;
91                 (*ptrptr)->buffer = NULL;
92                 ptrptr = &(*ptrptr)->next;
93                 /* This buffer is ready for filling (of course, it is empty!) */
94                 sem_post(powd->semaphore);
95         }
96         *ptrptr = powd->from = powd->to;
97 }
98
99 static void fill_buffer(osx_buffer *b, short *source, long size)
100 {
101         float *dest;
102
103         if (b->remaining) /* Non empty buffer, must still be playing */
104                 return;
105         PARA_INFO_LOG("%ld\n", size);
106         if (b->size != size) {
107                 /*
108                  * Hey! What's that? Coudn't this buffer size be fixed
109                  * once (well, perhaps we just didn't allocate it yet)
110                  */
111                 if (b->buffer)
112                         free(b->buffer);
113                 b->buffer = malloc(size * sizeof(float));
114                 b->size = size;
115         }
116         dest = b->buffer;
117         while (size--) {
118                 char *tmp = (char *)source;
119                 char c = *tmp;
120                 *tmp = *(tmp + 1);
121                 *(tmp + 1) = c;
122                 /* *dest++ = ((*source++) + 32768) / 65536.0; */
123                 *dest++ = (*source++) / 32768.0;
124         }
125         b->ptr = b->buffer;
126         b->remaining = b->size;
127 }
128
129 static OSStatus osx_callback(void * inClientData,
130         __a_unused AudioUnitRenderActionFlags *inActionFlags,
131         __a_unused const AudioTimeStamp *inTimeStamp,
132         __a_unused  UInt32 inBusNumber,
133         __a_unused UInt32 inNumFrames,
134         AudioBufferList *outOutputData)
135 {
136         long m, n;
137         float *dest;
138         int i;
139         struct private_osx_writer_data *powd = inClientData;
140
141 //      PARA_INFO_LOG("%p\n", powd);
142         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
143                 /* what we have to fill */
144                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
145                 dest = outOutputData->mBuffers[i].mData;
146                 while (m > 0) {
147                         if ((n = powd->from->remaining) <= 0) {
148                                 /* no more bytes in the current read buffer! */
149                                 while ((n = powd->from->remaining) <= 0)
150                                         /* wait for the results */
151                                         usleep(2000);
152                         }
153                         PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
154                         /*
155                          * we dump what we can. In fact, just the necessary
156                          * should be sufficient
157                          */
158                         if (n > m)
159                                 n = m;
160                         memcpy(dest, powd->from->ptr, n * sizeof(float));
161                         dest += n;
162                         /* remember all done work */
163                         m -= n;
164                         powd->from->ptr += n;
165                         if ((powd->from->remaining -= n) <= 0) {
166                                 /* tell that there's a buffer to fill */
167                                 sem_post(powd->semaphore);
168                                 powd->from = powd->from->next;
169                         }
170                 }
171         }
172         return 0;
173 }
174
175 static int osx_writer_open(struct writer_node *wn)
176 {
177         struct private_osx_writer_data *powd = para_calloc(
178                 sizeof(struct private_osx_writer_data));
179         ComponentDescription desc;
180         Component comp;
181         AURenderCallbackStruct inputCallback = {osx_callback, powd};
182         AudioStreamBasicDescription format;
183         char s[10];
184         int m, 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         /*
227          * We produce 2-channel audio. Now if we have a mega-super-hyper card for our
228          * audio, it is its problem to convert it to 8-, 16-, 32- or 1024-channel data.
229          */
230         format.mFramesPerPacket = 1;
231         format.mChannelsPerFrame = 2;
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 the semaphore */
242         strcpy(s, "/mpg123-0000");
243         do {
244                 for (m = 10;; m--)
245                         if( (s[m]++) <= '9')
246                                 break;
247                         else
248                                 s[m] = '0';
249         } while ((powd->semaphore = sem_open(s, O_CREAT | O_EXCL, 0644, 0))
250                 == (sem_t *)SEM_FAILED);
251         init_buffers(powd);
252         ret = -E_ADD_CALLBACK;
253         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_SetRenderCallback,
254                         kAudioUnitScope_Input, 0, &inputCallback,
255                         sizeof(inputCallback)) < 0)
256                 goto e3;
257         return 1;
258 e3:
259         destroy_buffers(powd);
260 e2:
261         AudioUnitUninitialize(powd->output);
262 e1:
263         CloseComponent(powd->output);
264 e0:
265         return ret;
266 }
267
268 __malloc void *osx_write_parse_config(char *options)
269 {
270         struct osx_write_args_info *conf
271                 = para_calloc(sizeof(struct osx_write_args_info));
272         PARA_INFO_LOG("options: %s\n", options);
273         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
274         if (ret)
275                 goto err_out;
276         return conf;
277 err_out:
278         free(conf);
279         return NULL;
280
281 }
282
283 static void osx_writer_close(struct writer_node *wn)
284 {
285         struct private_osx_writer_data *powd = wn->private_data;
286
287         PARA_INFO_LOG("closing writer node %p\n", wn);
288         AudioOutputUnitStop(powd->output);
289         AudioUnitUninitialize(powd->output);
290         CloseComponent(powd->output);
291         destroy_buffers(powd);
292         sem_close(powd->semaphore);
293         free(powd);
294 }
295
296 static int need_new_buffer(struct writer_node *wn)
297 {
298         struct writer_node_group *wng = wn->wng;
299         struct private_osx_writer_data *powd = wn->private_data;
300
301         if (*wng->loaded < sizeof(short))
302                 return 0;
303         if (powd->to->remaining) /* Non empty buffer, must still be playing */
304                 return 0;
305         return 1;
306 }
307
308 static int osx_write_post_select(__a_unused struct sched *s,
309                 struct writer_node *wn)
310 {
311         struct private_osx_writer_data *powd = wn->private_data;
312         struct writer_node_group *wng = wn->wng;
313         short *data = (short*)wng->buf;
314
315         if (!need_new_buffer(wn))
316                 return 1;
317         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
318         powd->to = powd->to->next;
319         wn->written = *wng->loaded;
320         if (!powd->play) {
321                 if (AudioOutputUnitStart(powd->output))
322                         return -1;
323                 powd->play = 1;
324         }
325         return 1;
326 }
327
328 static int osx_write_pre_select(struct sched *s, __a_unused struct writer_node *wn)
329 {
330         s->timeout.tv_sec = 0;
331         s->timeout.tv_usec = 20;
332         return 1;
333 }
334
335 void osx_writer_init(struct writer *w)
336 {
337         w->open = osx_writer_open;
338         w->close = osx_writer_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 }