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