Merge branch 'master' into my-osx
[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 };
54
55
56 /*
57  * Tried with 3 buffers, but then any little window move is sufficient to
58  * stop the sound (OK, on a G3 400 with a Public Beta. Perhaps now we can
59  * go down to 2 buffers). With 16 buffers we have 1.5 seconds music
60  * buffered (or, if you're pessimistic, 1.5 seconds latency). Note 0
61  * buffers don't work much further than the Bus error.
62  */
63 #define NUMBER_BUFFERS 2
64
65 static void destroy_buffers(struct private_osx_writer_data *powd)
66 {
67         osx_buffer *ptr;
68         osx_buffer *ptr2;
69         ptr = powd->to->next;
70         powd->to->next = NULL;
71         while (ptr) {
72                 ptr2 = ptr->next;
73                 if (ptr->buffer)
74                         free(ptr->buffer);
75                 free(ptr);
76                 ptr = ptr2;
77         }
78 }
79
80 static void init_buffers(struct private_osx_writer_data *powd)
81 {
82         int i;
83
84         osx_buffer ** ptrptr;
85         ptrptr = &powd->to;
86         for (i = 0; i < NUMBER_BUFFERS; i++) {
87                 *ptrptr = malloc(sizeof(osx_buffer));
88                 (*ptrptr)->size = 0;
89                 (*ptrptr)->remaining = 0;
90                 (*ptrptr)->buffer = NULL;
91                 ptrptr = &(*ptrptr)->next;
92                 /* This buffer is ready for filling (of course, it is empty!) */
93                 sem_post(powd->semaphore);
94         }
95         *ptrptr = powd->from = powd->to;
96 }
97
98 static void fill_buffer(osx_buffer *b, short *source, long size)
99 {
100         float *dest;
101
102         if (b->remaining) /* Non empty buffer, must still be playing */
103                 return;
104         PARA_INFO_LOG("%ld\n", size);
105         if (b->size != size) {
106                 /*
107                  * Hey! What's that? Coudn't this buffer size be fixed
108                  * once (well, perhaps we just didn't allocate it yet)
109                  */
110                 if (b->buffer)
111                         free(b->buffer);
112                 b->buffer = malloc(size * sizeof(float));
113                 b->size = size;
114         }
115         dest = b->buffer;
116         while (size--)
117                 /* *dest++ = ((*source++) + 32768) / 65536.0; */
118                 *dest++ = (*source++) / 32768.0;
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_writer_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                                 /* no more bytes in the current read buffer! */
143                                 while ((n = powd->from->remaining) <= 0)
144                                         /* wait for the results */
145                                         usleep(2000);
146                         }
147                         PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
148                         /*
149                          * we dump what we can. In fact, just the necessary
150                          * should be sufficient
151                          */
152                         if (n > m)
153                                 n = m;
154                         memcpy(dest, powd->from->ptr, n * sizeof(float));
155                         dest += n;
156                         /* remember all done work */
157                         m -= n;
158                         powd->from->ptr += n;
159                         if ((powd->from->remaining -= n) <= 0) {
160                                 /* tell that there's a buffer to fill */
161                                 sem_post(powd->semaphore);
162                                 powd->from = powd->from->next;
163                         }
164                 }
165         }
166         return 0;
167 }
168
169 static int osx_writer_open(struct writer_node *wn)
170 {
171         struct private_osx_writer_data *powd = para_calloc(
172                 sizeof(struct private_osx_writer_data));
173         ComponentDescription desc;
174         Component comp;
175         AURenderCallbackStruct inputCallback = {osx_callback, powd};
176         AudioStreamBasicDescription format;
177         char s[10];
178         int m, ret;
179
180         wn->private_data = powd;
181         /* where did that default audio output go? */
182         desc.componentType = kAudioUnitType_Output;
183         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
184         /* NOTE: and if default output isn't Apple? */
185         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
186         desc.componentFlags = 0;
187         desc.componentFlagsMask = 0;
188         ret = -E_DEFAULT_COMP;
189         comp = FindNextComponent(NULL, &desc);
190         if (!comp)
191                 goto e0;
192         ret = -E_OPEN_COMP;
193         if (OpenAComponent(comp, &powd->output))
194                 goto e0;
195         ret = -E_UNIT_INIT;
196         if (AudioUnitInitialize(powd->output))
197                 goto e1;
198         powd->size = 0;
199         powd->ptr = NULL;
200         powd->play = 0;
201         /* Hmmm, let's choose PCM format */
202         /* We tell the Output Unit what format we're going to supply data to it.
203          * This is necessary if you're providing data through an input callback
204          * AND you want the DefaultOutputUnit to do any format conversions
205          * necessary from your format to the device's format.
206          */
207         format.mSampleRate = 44100.0; /* The sample rate of the audio stream */
208         /* The specific encoding type of audio stream*/
209         format.mFormatID = kAudioFormatLinearPCM;
210         /* flags specific to each format */
211         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
212                 | kLinearPCMFormatFlagIsPacked
213                 | kLinearPCMFormatFlagIsBigEndian;
214         /*
215          * We produce 2-channel audio. Now if we have a mega-super-hyper card for our
216          * audio, it is its problem to convert it to 8-, 16-, 32- or 1024-channel data.
217          */
218         format.mBytesPerFrame = (format.mFramesPerPacket = 1)
219                 * (format.mBytesPerPacket = (format.mChannelsPerFrame = 2) * sizeof(float));
220         /* one of the most constant constants of the whole computer history */
221         format.mBitsPerChannel = sizeof(float) * 8;
222         ret = -E_STREAM_FORMAT;
223         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_StreamFormat,
224                         kAudioUnitScope_Input, 0, &format,
225                         sizeof(AudioStreamBasicDescription)))
226                 goto e2;
227         /* init the semaphore */
228         strcpy(s, "/mpg123-0000");
229         do {
230                 for (m = 10;; m--)
231                         if( (s[m]++) <= '9')
232                                 break;
233                         else
234                                 s[m] = '0';
235         } while ((powd->semaphore = sem_open(s, O_CREAT | O_EXCL, 0644, 0))
236                 == (sem_t *)SEM_FAILED);
237         init_buffers(powd);
238         ret = -E_ADD_CALLBACK;
239         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_SetRenderCallback,
240                         kAudioUnitScope_Input, 0, &inputCallback,
241                         sizeof(inputCallback)) < 0)
242                 goto e3;
243         return 0;
244 e3:
245         destroy_buffers(powd);
246 e2:
247         AudioUnitUninitialize(powd->output);
248 e1:
249         CloseComponent(powd->output);
250 e0:
251         return ret;
252 }
253
254 __malloc void *osx_write_parse_config(char *options)
255 {
256         struct osx_write_args_info *conf
257                 = para_calloc(sizeof(struct osx_write_args_info));
258         PARA_INFO_LOG("options: %s\n", options);
259         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
260         if (ret)
261                 goto err_out;
262         return conf;
263 err_out:
264         free(conf);
265         return NULL;
266
267 }
268
269 static void osx_writer_close(struct writer_node *wn)
270 {
271         struct private_osx_writer_data *powd = wn->private_data;
272
273         PARA_INFO_LOG("closing writer node %p\n", wn);
274         AudioOutputUnitStop(powd->output);
275         AudioUnitUninitialize(powd->output);
276         CloseComponent(powd->output);
277         destroy_buffers(powd);
278         sem_close(powd->semaphore);
279         free(powd);
280 }
281
282 static int osx_write_post_select(__a_unused struct sched *s,
283                 struct writer_node *wn)
284 {
285         struct private_osx_writer_data *powd = wn->private_data;
286         struct writer_node_group *wng = wn->wng;
287         short *data = (short*)wng->buf + wn->written;
288
289         if (*wng->loaded <= wn->written)
290                 return 1;
291         if (powd->to->remaining) /* Non empty buffer, must still be playing */
292                 return 1;
293         fill_buffer(powd->to, data, (*wng->loaded - wn->written) / sizeof(short));
294         powd->to = powd->to->next;
295         wn->written += (*wng->loaded - wn->written);
296         if (!powd->play) {
297                 if (AudioOutputUnitStart(powd->output))
298                         return -1;
299                 powd->play = 1;
300         }
301         return 1;
302 }
303
304 static int osx_write_pre_select(struct sched *s, struct writer_node *wn)
305 {
306         struct writer_node_group *wng = wn->wng;
307         struct private_osx_writer_data *powd = wn->private_data;
308
309 //      if (!*wng->loaded)
310 //              return 1;
311 //      if (powd->to->remaining) /* Non empty buffer, must still be playing */
312 //              return 1;
313         s->timeout.tv_sec = 0;
314         s->timeout.tv_usec = 20;
315         return 1;
316 }
317
318 void osx_writer_init(struct writer *w)
319 {
320         w->open = osx_writer_open;
321         w->close = osx_writer_close;
322         w->pre_select = osx_write_pre_select;
323         w->post_select = osx_write_post_select;
324         w->parse_config = osx_write_parse_config;
325         w->shutdown = NULL; /* nothing to do */
326 }