compress.c: fix serious typo
[paraslash.git] / osx_write.c
1 /*
2  * Copyright (C) 2006-2007 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                 *dest++ = (*source++) / 32768.0;
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                                 return 0;
141                         }
142 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
143                         /*
144                          * we dump what we can. In fact, just the necessary
145                          * should be sufficient
146                          */
147                         if (n > m)
148                                 n = m;
149                         memcpy(dest, powd->from->ptr, n * sizeof(float));
150                         dest += n;
151                         /* remember all done work */
152                         m -= n;
153                         powd->from->ptr += n;
154                         if ((powd->from->remaining -= n) <= 0)
155                                 powd->from = powd->from->next;
156                 }
157         }
158         return 0;
159 }
160
161 static int osx_write_open(struct writer_node *wn)
162 {
163         struct private_osx_write_data *powd = para_calloc(
164                 sizeof(struct private_osx_write_data));
165         ComponentDescription desc;
166         Component comp;
167         AURenderCallbackStruct inputCallback = {osx_callback, powd};
168         AudioStreamBasicDescription format;
169         int ret;
170         struct writer_node_group *wng = wn->wng;
171         struct osx_write_args_info *conf = wn->conf;
172
173         wn->private_data = powd;
174         /* where did that default audio output go? */
175         desc.componentType = kAudioUnitType_Output;
176         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
177         /* NOTE: and if default output isn't Apple? */
178         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
179         desc.componentFlags = 0;
180         desc.componentFlagsMask = 0;
181         ret = -E_DEFAULT_COMP;
182         comp = FindNextComponent(NULL, &desc);
183         if (!comp)
184                 goto e0;
185         ret = -E_OPEN_COMP;
186         if (OpenAComponent(comp, &powd->audio_unit))
187                 goto e0;
188         ret = -E_UNIT_INIT;
189         if (AudioUnitInitialize(powd->audio_unit))
190                 goto e1;
191         powd->play = 0;
192         /* Hmmm, let's choose PCM format */
193         /* We tell the Output Unit what format we're going to supply data to it.
194          * This is necessary if you're providing data through an input callback
195          * AND you want the DefaultOutputUnit to do any format conversions
196          * necessary from your format to the device's format.
197          */
198         if (!conf->samplerate_given && wng->samplerate)
199                 powd->samplerate = *wng->samplerate;
200         else
201                 powd->samplerate = conf->samplerate_arg;
202         format.mSampleRate = powd->samplerate;
203         /* The specific encoding type of audio stream*/
204         format.mFormatID = kAudioFormatLinearPCM;
205         /* flags specific to each format */
206         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
207                 | kLinearPCMFormatFlagIsPacked
208                 | kLinearPCMFormatFlagIsBigEndian;
209         if (!conf->channels_given && wng->channels)
210                 powd->channels = *wng->channels;
211         else
212                 powd->channels = conf->channels_arg;
213         format.mChannelsPerFrame = powd->channels;
214         format.mFramesPerPacket = 1;
215         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
216         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
217         /* one of the most constant constants of the whole computer history */
218         format.mBitsPerChannel = sizeof(float) * 8;
219         ret = -E_STREAM_FORMAT;
220         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
221                         kAudioUnitScope_Input, 0, &format,
222                         sizeof(AudioStreamBasicDescription)))
223                 goto e2;
224         init_buffers(wn);
225         ret = -E_ADD_CALLBACK;
226         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
227                         kAudioUnitScope_Input, 0, &inputCallback,
228                         sizeof(inputCallback)) < 0)
229                 goto e3;
230         return 1;
231 e3:
232         destroy_buffers(powd);
233 e2:
234         AudioUnitUninitialize(powd->audio_unit);
235 e1:
236         CloseComponent(powd->audio_unit);
237 e0:
238         return ret;
239 }
240
241 __malloc static void *osx_write_parse_config(const char *options)
242 {
243         struct osx_write_args_info *conf
244                 = para_calloc(sizeof(struct osx_write_args_info));
245         PARA_INFO_LOG("options: %s\n", options);
246         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
247         if (ret)
248                 goto err_out;
249         return conf;
250 err_out:
251         free(conf);
252         return NULL;
253
254 }
255
256 static void osx_write_close(struct writer_node *wn)
257 {
258         struct private_osx_write_data *powd = wn->private_data;
259
260         PARA_INFO_LOG("closing writer node %p\n", wn);
261         AudioOutputUnitStop(powd->audio_unit);
262         AudioUnitUninitialize(powd->audio_unit);
263         CloseComponent(powd->audio_unit);
264         destroy_buffers(powd);
265         free(powd);
266 }
267
268 static int need_new_buffer(struct writer_node *wn)
269 {
270         struct writer_node_group *wng = wn->wng;
271         struct private_osx_write_data *powd = wn->private_data;
272
273         if (*wng->loaded < sizeof(short))
274                 return 0;
275         if (powd->to->remaining) /* Non empty buffer, must still be playing */
276                 return 0;
277         return 1;
278 }
279
280 static int osx_write_post_select(__a_unused struct sched *s,
281                 struct writer_node *wn)
282 {
283         struct private_osx_write_data *powd = wn->private_data;
284         struct writer_node_group *wng = wn->wng;
285         short *data = (short*)wng->buf;
286
287         if (!need_new_buffer(wn))
288                 return 1;
289         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
290         powd->to = powd->to->next;
291         wn->written = *wng->loaded;
292         if (!powd->play) {
293                 if (AudioOutputUnitStart(powd->audio_unit))
294                         return -E_UNIT_START;
295                 powd->play = 1;
296         }
297         return 1;
298 }
299
300 static int osx_write_pre_select(struct sched *s, __a_unused struct writer_node *wn)
301 {
302         struct private_osx_write_data *powd = wn->private_data;
303         struct writer_node_group *wng = wn->wng;
304         size_t numbytes = powd->to->remaining * sizeof(short);
305         struct timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
306         unsigned long divisor;
307
308         if (!numbytes && *wng->loaded >= sizeof(short))
309                 goto min_delay; /* there's a buffer to fill */
310         if (!numbytes)
311                 return 1;
312         divisor = powd->samplerate * powd->channels * 2 / numbytes;
313         if (divisor)
314                 tv_divide(divisor, &tmp, &delay);
315         if (tv_diff(&s->timeout, &delay, NULL) > 0)
316                 s->timeout = delay;
317 //      PARA_DEBUG_LOG("delay: %lu:%lu\n", (long unsigned) s->timeout.tv_sec,
318 //              (long unsigned) s->timeout.tv_usec);
319         return 1;
320 min_delay:
321         PARA_DEBUG_LOG("%s\n", "minimal delay");
322         s->timeout.tv_sec = 0;
323         s->timeout.tv_usec = 1;
324         return 1;
325 }
326
327 /** the init function of the osx writer */
328 void osx_write_init(struct writer *w)
329 {
330         w->open = osx_write_open;
331         w->close = osx_write_close;
332         w->pre_select = osx_write_pre_select;
333         w->post_select = osx_write_post_select;
334         w->parse_config = osx_write_parse_config;
335         w->shutdown = NULL; /* nothing to do */
336 }