c07bbd51e6577152408eda231f5a0e1697b1bbd5
[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         PARA_INFO_LOG("%ld\n", size);
103         if (b->remaining) /* Non empty buffer, must still be playing */
104                 return;
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                         /*
148                          * we dump what we can. In fact, just the necessary
149                          * should be sufficient
150                          */
151                         if (n > m)
152                                 n = m;
153                         memcpy(dest, powd->from->ptr, n * sizeof(float));
154                         dest += n;
155                         /* remember all done work */
156                         m -= n;
157                         powd->from->ptr += n;
158                         if ((powd->from->remaining -= n) <= 0) {
159                                 /* tell that there's a buffer to fill */
160                                 sem_post(powd->semaphore);
161                                 powd->from = powd->from->next;
162                         }
163                 }
164         }
165         return 0;
166 }
167
168 static int osx_writer_open(struct writer_node *wn)
169 {
170         struct private_osx_writer_data *powd = para_calloc(
171                 sizeof(struct private_osx_writer_data));
172         ComponentDescription desc;
173         Component comp;
174         AURenderCallbackStruct inputCallback = {osx_callback, powd};
175         AudioStreamBasicDescription format;
176         char s[10];
177         int m, ret;
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         format.mSampleRate = 44100.0; /* The sample rate of the audio stream */
207         /* The specific encoding type of audio stream*/
208         format.mFormatID = kAudioFormatLinearPCM;
209         /* flags specific to each format */
210         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
211                 | kLinearPCMFormatFlagIsPacked;
212         //      | kLinearPCMFormatFlagIsBigEndian;
213         /*
214          * We produce 2-channel audio. Now if we have a mega-super-hyper card for our
215          * audio, it is its problem to convert it to 8-, 16-, 32- or 1024-channel data.
216          */
217         format.mBytesPerFrame = (format.mFramesPerPacket = 1)
218                 * (format.mBytesPerPacket = (format.mChannelsPerFrame = 2) * sizeof(float));
219         /* one of the most constant constants of the whole computer history */
220         format.mBitsPerChannel = sizeof(float) * 8;
221         ret = -E_STREAM_FORMAT;
222         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_StreamFormat,
223                         kAudioUnitScope_Input, 0, &format,
224                         sizeof(AudioStreamBasicDescription)))
225                 goto e2;
226         /* init the semaphore */
227         strcpy(s, "/mpg123-0000");
228         do {
229                 for (m = 10;; m--)
230                         if( (s[m]++) <= '9')
231                                 break;
232                         else
233                                 s[m] = '0';
234         } while ((powd->semaphore = sem_open(s, O_CREAT | O_EXCL, 0644, 0))
235                 == (sem_t *)SEM_FAILED);
236         init_buffers(powd);
237         ret = -E_ADD_CALLBACK;
238         if (AudioUnitSetProperty(powd->output, kAudioUnitProperty_SetRenderCallback,
239                         kAudioUnitScope_Input, 0, &inputCallback,
240                         sizeof(inputCallback)) < 0)
241                 goto e3;
242         return 0;
243 e3:
244         destroy_buffers(powd);
245 e2:
246         AudioUnitUninitialize(powd->output);
247 e1:
248         CloseComponent(powd->output);
249 e0:
250         return ret;
251 }
252
253 __malloc void *osx_write_parse_config(char *options)
254 {
255         struct osx_write_args_info *conf
256                 = para_calloc(sizeof(struct osx_write_args_info));
257         PARA_INFO_LOG("options: %s\n", options);
258         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
259         if (ret)
260                 goto err_out;
261         return conf;
262 err_out:
263         free(conf);
264         return NULL;
265
266 }
267
268 static void osx_writer_close(struct writer_node *wn)
269 {
270         struct private_osx_writer_data *powd = wn->private_data;
271
272         PARA_INFO_LOG("closing writer node %p\n", wn);
273         AudioOutputUnitStop(powd->output);
274         AudioUnitUninitialize(powd->output);
275         CloseComponent(powd->output);
276         destroy_buffers(powd);
277         sem_close(powd->semaphore);
278         free(powd);
279 }
280
281 static int osx_write_post_select(__a_unused struct sched *s,
282                 struct writer_node *wn)
283 {
284         struct private_osx_writer_data *powd = wn->private_data;
285         struct writer_node_group *wng = wn->wng;
286         short *data = (short*)wng->buf + wn->written;
287
288         if (!*wng->loaded)
289                 return 1;
290         if (powd->to->remaining) /* Non empty buffer, must still be playing */
291                 return 1;
292         fill_buffer(powd->to, data, (*wng->loaded - wn->written) / sizeof(short));
293         powd->to = powd->to->next;
294         wn->written += (*wng->loaded - wn->written);
295         if (!powd->play) {
296                 if (AudioOutputUnitStart(powd->output))
297                         return -1;
298                 powd->play = 1;
299         }
300         return 1;
301 }
302
303 static int osx_write_pre_select(struct sched *s, struct writer_node *wn)
304 {
305         struct writer_node_group *wng = wn->wng;
306         struct private_osx_writer_data *powd = wn->private_data;
307
308 //      if (!*wng->loaded)
309 //              return 1;
310 //      if (powd->to->remaining) /* Non empty buffer, must still be playing */
311 //              return 1;
312         s->timeout.tv_sec = 0;
313         s->timeout.tv_usec = 20;
314         return 1;
315 }
316
317 void osx_writer_init(struct writer *w)
318 {
319         w->open = osx_writer_open;
320         w->close = osx_writer_close;
321         w->pre_select = osx_write_pre_select;
322         w->post_select = osx_write_post_select;
323         w->parse_config = osx_write_parse_config;
324         w->shutdown = NULL; /* nothing to do */
325 }