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