NEWS update
[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
41 /** describes one input buffer for the osx writer */
42 struct osx_buffer {
43         /** pointer to the beginning of the buffer */
44         float *buffer;
45         /** the size of this buffer */
46         long size;
47         /* current position in the buffer */
48         float *ptr;
49         /** number of floats not yet consuned */
50         long remaining;
51         /** pointer to the next audio buffer */
52         struct osx_buffer *next;
53 };
54
55 /** data specific to the osx writer */
56 struct private_osx_write_data {
57         /** the main control structure for audio data manipulation */
58         AudioUnit audio_unit;
59         /** non-zero if playback has started */
60         char play;
61         /** callback reads audio data from this buffer */
62         struct osx_buffer *from;
63         /* the post_select writes audio data here */
64         struct osx_buffer *to;
65         /** sample rate of the current audio stream */
66         unsigned samplerate;
67         /** number of channels of the current audio stream */
68         unsigned channels;
69 };
70
71 static void destroy_buffers(struct private_osx_write_data *powd)
72 {
73         struct osx_buffer *ptr;
74         struct osx_buffer *ptr2;
75         ptr = powd->to->next;
76         powd->to->next = NULL;
77         while (ptr) {
78                 ptr2 = ptr->next;
79                 free(ptr->buffer);
80                 free(ptr);
81                 ptr = ptr2;
82         }
83 }
84
85 static void init_buffers(struct writer_node *wn)
86 {
87         struct private_osx_write_data *powd = wn->private_data;
88         struct osx_write_args_info *conf = wn->conf;
89         struct osx_buffer **ptrptr;
90         int i;
91
92         ptrptr = &powd->to;
93         for (i = 0; i < conf->numbuffers_arg; i++) {
94                 *ptrptr = malloc(sizeof(struct osx_buffer));
95                 (*ptrptr)->size = 0;
96                 (*ptrptr)->remaining = 0;
97                 (*ptrptr)->buffer = NULL;
98                 ptrptr = &(*ptrptr)->next;
99         }
100         *ptrptr = powd->from = powd->to;
101 }
102
103 static void fill_buffer(struct osx_buffer *b, short *source, long size)
104 {
105         float *dest;
106
107         if (b->remaining) /* Non empty buffer, must still be playing */
108                 return;
109         if (b->size != size) {
110                 b->buffer = para_realloc(b->buffer, size * sizeof(float));
111                 b->size = size;
112         }
113         dest = b->buffer;
114         while (size--) {
115                 char *tmp = (char *)source;
116                 char c = *tmp;
117                 *tmp = *(tmp + 1);
118                 *(tmp + 1) = c;
119                 /* *dest++ = ((*source++) + 32768) / 65536.0; */
120                 *dest++ = (*source++) / 32768.0;
121         }
122         b->ptr = b->buffer;
123         b->remaining = b->size;
124 }
125
126 static OSStatus osx_callback(void * inClientData,
127         __a_unused AudioUnitRenderActionFlags *inActionFlags,
128         __a_unused const AudioTimeStamp *inTimeStamp,
129         __a_unused  UInt32 inBusNumber,
130         __a_unused UInt32 inNumFrames,
131         AudioBufferList *outOutputData)
132 {
133         long m, n;
134         float *dest;
135         int i;
136         struct private_osx_write_data *powd = inClientData;
137
138 //      PARA_INFO_LOG("%p\n", powd);
139         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
140                 /* what we have to fill */
141                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
142                 dest = outOutputData->mBuffers[i].mData;
143                 while (m > 0) {
144                         if ((n = powd->from->remaining) <= 0) {
145                                 PARA_INFO_LOG("%s", "buffer underrun\n");
146                                 /* no more bytes in the current read buffer! */
147                                 while ((n = powd->from->remaining) <= 0)
148                                         /* wait for the results */
149                                         usleep(2000);
150                         }
151 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
152                         /*
153                          * we dump what we can. In fact, just the necessary
154                          * should be sufficient
155                          */
156                         if (n > m)
157                                 n = m;
158                         memcpy(dest, powd->from->ptr, n * sizeof(float));
159                         dest += n;
160                         /* remember all done work */
161                         m -= n;
162                         powd->from->ptr += n;
163                         if ((powd->from->remaining -= n) <= 0)
164                                 powd->from = powd->from->next;
165                 }
166         }
167         return 0;
168 }
169
170 static int osx_write_open(struct writer_node *wn)
171 {
172         struct private_osx_write_data *powd = para_calloc(
173                 sizeof(struct private_osx_write_data));
174         ComponentDescription desc;
175         Component comp;
176         AURenderCallbackStruct inputCallback = {osx_callback, powd};
177         AudioStreamBasicDescription format;
178         int ret;
179         struct writer_node_group *wng = wn->wng;
180         struct osx_write_args_info *conf = wn->conf;
181
182         wn->private_data = powd;
183         /* where did that default audio output go? */
184         desc.componentType = kAudioUnitType_Output;
185         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
186         /* NOTE: and if default output isn't Apple? */
187         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
188         desc.componentFlags = 0;
189         desc.componentFlagsMask = 0;
190         ret = -E_DEFAULT_COMP;
191         comp = FindNextComponent(NULL, &desc);
192         if (!comp)
193                 goto e0;
194         ret = -E_OPEN_COMP;
195         if (OpenAComponent(comp, &powd->audio_unit))
196                 goto e0;
197         ret = -E_UNIT_INIT;
198         if (AudioUnitInitialize(powd->audio_unit))
199                 goto e1;
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         if (!conf->samplerate_given && wng->samplerate)
208                 powd->samplerate = *wng->samplerate;
209         else
210                 powd->samplerate = conf->samplerate_arg;
211         format.mSampleRate = powd->samplerate;
212         /* The specific encoding type of audio stream*/
213         format.mFormatID = kAudioFormatLinearPCM;
214         /* flags specific to each format */
215         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
216                 | kLinearPCMFormatFlagIsPacked
217                 | kLinearPCMFormatFlagIsBigEndian;
218         if (!conf->channels_given && wng->channels)
219                 powd->channels = *wng->channels;
220         else
221                 powd->channels = conf->channels_arg;
222         format.mChannelsPerFrame = powd->channels;
223         format.mFramesPerPacket = 1;
224         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
225         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
226         /* one of the most constant constants of the whole computer history */
227         format.mBitsPerChannel = sizeof(float) * 8;
228         ret = -E_STREAM_FORMAT;
229         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
230                         kAudioUnitScope_Input, 0, &format,
231                         sizeof(AudioStreamBasicDescription)))
232                 goto e2;
233         init_buffers(wn);
234         ret = -E_ADD_CALLBACK;
235         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
236                         kAudioUnitScope_Input, 0, &inputCallback,
237                         sizeof(inputCallback)) < 0)
238                 goto e3;
239         return 1;
240 e3:
241         destroy_buffers(powd);
242 e2:
243         AudioUnitUninitialize(powd->audio_unit);
244 e1:
245         CloseComponent(powd->audio_unit);
246 e0:
247         return ret;
248 }
249
250 __malloc void *osx_write_parse_config(char *options)
251 {
252         struct osx_write_args_info *conf
253                 = para_calloc(sizeof(struct osx_write_args_info));
254         PARA_INFO_LOG("options: %s\n", options);
255         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
256         if (ret)
257                 goto err_out;
258         return conf;
259 err_out:
260         free(conf);
261         return NULL;
262
263 }
264
265 static void osx_write_close(struct writer_node *wn)
266 {
267         struct private_osx_write_data *powd = wn->private_data;
268
269         PARA_INFO_LOG("closing writer node %p\n", wn);
270         AudioOutputUnitStop(powd->audio_unit);
271         AudioUnitUninitialize(powd->audio_unit);
272         CloseComponent(powd->audio_unit);
273         destroy_buffers(powd);
274         free(powd);
275 }
276
277 static int need_new_buffer(struct writer_node *wn)
278 {
279         struct writer_node_group *wng = wn->wng;
280         struct private_osx_write_data *powd = wn->private_data;
281
282         if (*wng->loaded < sizeof(short))
283                 return 0;
284         if (powd->to->remaining) /* Non empty buffer, must still be playing */
285                 return 0;
286         return 1;
287 }
288
289 static int osx_write_post_select(__a_unused struct sched *s,
290                 struct writer_node *wn)
291 {
292         struct private_osx_write_data *powd = wn->private_data;
293         struct writer_node_group *wng = wn->wng;
294         short *data = (short*)wng->buf;
295
296         if (!need_new_buffer(wn))
297                 return 1;
298         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
299         powd->to = powd->to->next;
300         wn->written = *wng->loaded;
301         if (!powd->play) {
302                 if (AudioOutputUnitStart(powd->audio_unit))
303                         return -E_UNIT_START;
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         struct private_osx_write_data *powd = wn->private_data;
312         struct writer_node_group *wng = wn->wng;
313         size_t numbytes = powd->to->remaining * sizeof(short);
314         struct timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
315         unsigned long divisor;
316
317         if (!numbytes && *wng->loaded >= sizeof(short))
318                 goto min_delay; /* there's a buffer to fill */
319         if (!numbytes)
320                 return 1;
321         divisor = powd->samplerate * powd->channels * 2 / numbytes;
322         if (divisor)
323                 tv_divide(divisor, &tmp, &delay);
324         if (tv_diff(&s->timeout, &delay, NULL) > 0)
325                 s->timeout = delay;
326 //      PARA_DEBUG_LOG("delay: %lu:%lu\n", (long unsigned) s->timeout.tv_sec,
327 //              (long unsigned) s->timeout.tv_usec);
328         return 1;
329 min_delay:
330         PARA_DEBUG_LOG("%s\n", "minimal delay");
331         s->timeout.tv_sec = 0;
332         s->timeout.tv_usec = 1;
333         return 1;
334 }
335
336 /** the init function of the osx writer */
337 void osx_write_init(struct writer *w)
338 {
339         w->open = osx_write_open;
340         w->close = osx_write_close;
341         w->pre_select = osx_write_pre_select;
342         w->post_select = osx_write_post_select;
343         w->parse_config = osx_write_parse_config;
344         w->shutdown = NULL; /* nothing to do */
345 }