net.c: Fix a fd leak in create_local_socket().
[paraslash.git] / osx_write.c
1 /*
2  * Copyright (C) 2006-2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file osx_write.c paraslash's output plugin for MacOs */
8
9 /*
10  * based on mosx-mpg123, by Guillaume Outters and Steven A. Kortze
11  * <skortze@sourceforge.net>
12  */
13
14 #include <CoreAudio/CoreAudio.h>
15 #include "para.h"
16 #include "fd.h"
17 #include "string.h"
18 #include "list.h"
19 #include "sched.h"
20 #include "write.h"
21 #include "osx_write.cmdline.h"
22 #include "error.h"
23
24
25 #include <CoreAudio/CoreAudio.h>
26 #include <AudioUnit/AudioUnit.h>
27 #include <AudioToolbox/DefaultAudioOutput.h>
28
29 /** describes one input buffer for the osx writer */
30 struct osx_buffer {
31         /** pointer to the beginning of the buffer */
32         float *buffer;
33         /** the size of this buffer */
34         long size;
35         /** current position in the buffer */
36         float *ptr;
37         /** number of floats not yet consuned */
38         long remaining;
39         /** pointer to the next audio buffer */
40         struct osx_buffer *next;
41 };
42
43 /** data specific to the osx writer */
44 struct private_osx_write_data {
45         /** the main control structure for audio data manipulation */
46         AudioUnit audio_unit;
47         /** non-zero if playback has started */
48         char play;
49         /** callback reads audio data from this buffer */
50         struct osx_buffer *from;
51         /** the post_select writes audio data here */
52         struct osx_buffer *to;
53         /** sample rate of the current audio stream */
54         unsigned samplerate;
55         /** number of channels of the current audio stream */
56         unsigned channels;
57 };
58
59 static void destroy_buffers(struct private_osx_write_data *powd)
60 {
61         struct osx_buffer *ptr;
62         struct osx_buffer *ptr2;
63         ptr = powd->to->next;
64         powd->to->next = NULL;
65         while (ptr) {
66                 ptr2 = ptr->next;
67                 free(ptr->buffer);
68                 free(ptr);
69                 ptr = ptr2;
70         }
71 }
72
73 static void init_buffers(struct writer_node *wn)
74 {
75         struct private_osx_write_data *powd = wn->private_data;
76         struct osx_write_args_info *conf = wn->conf;
77         struct osx_buffer **ptrptr;
78         int i;
79
80         ptrptr = &powd->to;
81         for (i = 0; i < conf->numbuffers_arg; i++) {
82                 *ptrptr = malloc(sizeof(struct osx_buffer));
83                 (*ptrptr)->size = 0;
84                 (*ptrptr)->remaining = 0;
85                 (*ptrptr)->buffer = NULL;
86                 ptrptr = &(*ptrptr)->next;
87         }
88         *ptrptr = powd->from = powd->to;
89 }
90
91 static void fill_buffer(struct osx_buffer *b, short *source, long size)
92 {
93         float *dest;
94
95         if (b->remaining) /* Non empty buffer, must still be playing */
96                 return;
97         if (b->size != size) {
98                 b->buffer = para_realloc(b->buffer, size * sizeof(float));
99                 b->size = size;
100         }
101         dest = b->buffer;
102         while (size--)
103                 *dest++ = (*source++) / 32768.0;
104         b->ptr = b->buffer;
105         b->remaining = b->size;
106 }
107
108 static OSStatus osx_callback(void * inClientData,
109         __a_unused AudioUnitRenderActionFlags *inActionFlags,
110         __a_unused const AudioTimeStamp *inTimeStamp,
111         __a_unused  UInt32 inBusNumber,
112         __a_unused UInt32 inNumFrames,
113         AudioBufferList *outOutputData)
114 {
115         long m, n;
116         float *dest;
117         int i;
118         struct private_osx_write_data *powd = inClientData;
119
120 //      PARA_INFO_LOG("%p\n", powd);
121         for (i = 0; i < outOutputData->mNumberBuffers; ++i) {
122                 /* what we have to fill */
123                 m = outOutputData->mBuffers[i].mDataByteSize / sizeof(float);
124                 dest = outOutputData->mBuffers[i].mData;
125                 while (m > 0) {
126                         if ((n = powd->from->remaining) <= 0) {
127                                 PARA_INFO_LOG("%s", "buffer underrun\n");
128                                 return 0;
129                         }
130 //                      PARA_INFO_LOG("buf %p: n = %ld, m= %ld\n", powd->from->buffer, n, m);
131                         /*
132                          * we dump what we can. In fact, just the necessary
133                          * should be sufficient
134                          */
135                         if (n > m)
136                                 n = m;
137                         memcpy(dest, powd->from->ptr, n * sizeof(float));
138                         dest += n;
139                         /* remember all done work */
140                         m -= n;
141                         powd->from->ptr += n;
142                         if ((powd->from->remaining -= n) <= 0)
143                                 powd->from = powd->from->next;
144                 }
145         }
146         return 0;
147 }
148
149 static int osx_write_open(struct writer_node *wn)
150 {
151         struct private_osx_write_data *powd = para_calloc(
152                 sizeof(struct private_osx_write_data));
153         ComponentDescription desc;
154         Component comp;
155         AURenderCallbackStruct inputCallback = {osx_callback, powd};
156         AudioStreamBasicDescription format;
157         int ret;
158         struct writer_node_group *wng = wn->wng;
159         struct osx_write_args_info *conf = wn->conf;
160
161         wn->private_data = powd;
162         /* where did that default audio output go? */
163         desc.componentType = kAudioUnitType_Output;
164         desc.componentSubType = kAudioUnitSubType_DefaultOutput;
165         /* NOTE: and if default output isn't Apple? */
166         desc.componentManufacturer = kAudioUnitManufacturer_Apple;
167         desc.componentFlags = 0;
168         desc.componentFlagsMask = 0;
169         ret = -E_DEFAULT_COMP;
170         comp = FindNextComponent(NULL, &desc);
171         if (!comp)
172                 goto e0;
173         ret = -E_OPEN_COMP;
174         if (OpenAComponent(comp, &powd->audio_unit))
175                 goto e0;
176         ret = -E_UNIT_INIT;
177         if (AudioUnitInitialize(powd->audio_unit))
178                 goto e1;
179         powd->play = 0;
180         /* Hmmm, let's choose PCM format */
181         /* We tell the Output Unit what format we're going to supply data to it.
182          * This is necessary if you're providing data through an input callback
183          * AND you want the DefaultOutputUnit to do any format conversions
184          * necessary from your format to the device's format.
185          */
186         if (!conf->samplerate_given && wng->samplerate)
187                 powd->samplerate = *wng->samplerate;
188         else
189                 powd->samplerate = conf->samplerate_arg;
190         format.mSampleRate = powd->samplerate;
191         /* The specific encoding type of audio stream*/
192         format.mFormatID = kAudioFormatLinearPCM;
193         /* flags specific to each format */
194         format.mFormatFlags = kLinearPCMFormatFlagIsFloat
195                 | kLinearPCMFormatFlagIsPacked
196                 | kLinearPCMFormatFlagIsBigEndian;
197         if (!conf->channels_given && wng->channels)
198                 powd->channels = *wng->channels;
199         else
200                 powd->channels = conf->channels_arg;
201         format.mChannelsPerFrame = powd->channels;
202         format.mFramesPerPacket = 1;
203         format.mBytesPerPacket = format.mChannelsPerFrame * sizeof(float);
204         format.mBytesPerFrame = format.mFramesPerPacket * format.mBytesPerPacket;
205         /* one of the most constant constants of the whole computer history */
206         format.mBitsPerChannel = sizeof(float) * 8;
207         ret = -E_STREAM_FORMAT;
208         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_StreamFormat,
209                         kAudioUnitScope_Input, 0, &format,
210                         sizeof(AudioStreamBasicDescription)))
211                 goto e2;
212         init_buffers(wn);
213         ret = -E_ADD_CALLBACK;
214         if (AudioUnitSetProperty(powd->audio_unit, kAudioUnitProperty_SetRenderCallback,
215                         kAudioUnitScope_Input, 0, &inputCallback,
216                         sizeof(inputCallback)) < 0)
217                 goto e3;
218         return 1;
219 e3:
220         destroy_buffers(powd);
221 e2:
222         AudioUnitUninitialize(powd->audio_unit);
223 e1:
224         CloseComponent(powd->audio_unit);
225 e0:
226         return ret;
227 }
228
229 __malloc static void *osx_write_parse_config(const char *options)
230 {
231         struct osx_write_args_info *conf
232                 = para_calloc(sizeof(struct osx_write_args_info));
233         PARA_INFO_LOG("options: %s\n", options);
234         int ret = osx_cmdline_parser_string(options, conf, "osx_write");
235         if (ret)
236                 goto err_out;
237         return conf;
238 err_out:
239         free(conf);
240         return NULL;
241
242 }
243
244 static void osx_write_close(struct writer_node *wn)
245 {
246         struct private_osx_write_data *powd = wn->private_data;
247
248         PARA_INFO_LOG("closing writer node %p\n", wn);
249         AudioOutputUnitStop(powd->audio_unit);
250         AudioUnitUninitialize(powd->audio_unit);
251         CloseComponent(powd->audio_unit);
252         destroy_buffers(powd);
253         free(powd);
254 }
255
256 static int need_new_buffer(struct writer_node *wn)
257 {
258         struct writer_node_group *wng = wn->wng;
259         struct private_osx_write_data *powd = wn->private_data;
260
261         if (*wng->loaded < sizeof(short))
262                 return 0;
263         if (powd->to->remaining) /* Non empty buffer, must still be playing */
264                 return 0;
265         return 1;
266 }
267
268 static int osx_write_post_select(__a_unused struct sched *s,
269                 struct writer_node *wn)
270 {
271         struct private_osx_write_data *powd = wn->private_data;
272         struct writer_node_group *wng = wn->wng;
273         short *data = (short*)wng->buf;
274
275         if (!need_new_buffer(wn))
276                 return 1;
277         fill_buffer(powd->to, data, *wng->loaded / sizeof(short));
278         powd->to = powd->to->next;
279         wn->written = *wng->loaded;
280         if (!powd->play) {
281                 if (AudioOutputUnitStart(powd->audio_unit))
282                         return -E_UNIT_START;
283                 powd->play = 1;
284         }
285         return 1;
286 }
287
288 static int osx_write_pre_select(struct sched *s, __a_unused struct writer_node *wn)
289 {
290         struct private_osx_write_data *powd = wn->private_data;
291         struct writer_node_group *wng = wn->wng;
292         size_t numbytes = powd->to->remaining * sizeof(short);
293         struct timeval tmp = {.tv_sec = 1, .tv_usec = 0}, delay = tmp;
294         unsigned long divisor;
295
296         if (!numbytes && *wng->loaded >= sizeof(short))
297                 goto min_delay; /* there's a buffer to fill */
298         if (!numbytes)
299                 return 1;
300         divisor = powd->samplerate * powd->channels * 2 / numbytes;
301         if (divisor)
302                 tv_divide(divisor, &tmp, &delay);
303         if (tv_diff(&s->timeout, &delay, NULL) > 0)
304                 s->timeout = delay;
305 //      PARA_DEBUG_LOG("delay: %lu:%lu\n", (long unsigned) s->timeout.tv_sec,
306 //              (long unsigned) s->timeout.tv_usec);
307         return 1;
308 min_delay:
309         PARA_DEBUG_LOG("%s\n", "minimal delay");
310         s->timeout.tv_sec = 0;
311         s->timeout.tv_usec = 1;
312         return 1;
313 }
314
315 /** the init function of the osx writer */
316 void osx_write_init(struct writer *w)
317 {
318         w->open = osx_write_open;
319         w->close = osx_write_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 }