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