upd sender: Don't send FEC EOF from command handler context.
[paraslash.git] / ao_write.c
1 /* Copyright (C) 2011 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file ao_write.c Paraslash's libao output plugin. */
4
5 #include <pthread.h>
6 #include <ao/ao.h>
7 #include <regex.h>
8 #include <lopsub.h>
9
10 #include "write_cmd.lsg.h"
11 #include "para.h"
12 #include "fd.h"
13 #include "string.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "buffer_tree.h"
17 #include "write.h"
18 #include "error.h"
19
20 struct private_aow_data {
21         ao_device *dev;
22         int bytes_per_frame;
23
24         pthread_t thread;
25         pthread_attr_t attr;
26         /* The mutex and the condition variable serialize access to ->btrn */
27         pthread_mutex_t mutex;
28         pthread_cond_t data_available;
29         struct btr_node *thread_btrn;
30 };
31
32 static void aow_close(struct writer_node *wn)
33 {
34         struct private_aow_data *pawd = wn->private_data;
35
36         if (!pawd)
37                 return;
38         assert(!pawd->thread_btrn);
39         ao_close(pawd->dev);
40         free(pawd);
41         wn->private_data = NULL;
42         ao_shutdown();
43 }
44
45 static void aow_pre_select(struct sched *s, void *context)
46 {
47         struct writer_node *wn = context;
48         struct private_aow_data *pawd = wn->private_data;
49         int ret;
50
51         if (!pawd) { /* not yet started */
52                 assert(wn->btrn);
53                 ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
54                 if (ret != 0)
55                         goto min_delay;
56                 return; /* no data available */
57         }
58         if (!wn->btrn) { /* EOF */
59                 if (!pawd->thread_btrn) /* ready to exit */
60                         goto min_delay;
61                 /* wait for the play thread to terminate */
62                 goto timeout;
63         }
64         pthread_mutex_lock(&pawd->mutex);
65         ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
66         pthread_mutex_unlock(&pawd->mutex);
67         if (ret != 0)
68                 goto min_delay;
69         /*
70          * Even though the node status is zero, we might have data available,
71          * but the output buffer is full. If we don't set a timeout here, we
72          * are woken up only if new data arrives, which might be too late and
73          * result in a buffer underrun in the playing thread. To avoid this we
74          * never sleep longer than the (default) buffer time.
75          */
76 timeout:
77         return sched_request_timeout_ms(20, s);
78 min_delay:
79         sched_min_delay(s);
80 }
81
82 static int aow_set_sample_format(unsigned sample_rate, unsigned channels,
83                 int sample_format, ao_sample_format *result)
84 {
85         memset(result, 0, sizeof(*result));
86         switch (sample_format) {
87                 case SF_U8:
88                 case SF_U16_LE:
89                 case SF_U16_BE:
90                         return -E_BAD_SAMPLE_FORMAT;
91                 case SF_S8:
92                         /* no need to set byte_format */
93                         result->bits = 8;
94                         break;
95                 case SF_S16_LE:
96                         result->bits = 16;
97                         result->byte_format = AO_FMT_LITTLE;
98                         break;
99                 case SF_S16_BE:
100                         result->bits = 16;
101                         result->byte_format = AO_FMT_BIG;
102                         break;
103                 default:
104                         PARA_EMERG_LOG("bug: invalid sample format\n");
105                         exit(EXIT_FAILURE);
106         }
107         result->channels = channels;
108         result->rate = sample_rate;
109         return 1;
110 }
111
112 static int aow_open_device(int id, ao_sample_format *asf, ao_option *options,
113                 ao_device **result)
114 {
115         const char *msg;
116         ao_device *dev = ao_open_live(id, asf, options);
117
118         if (dev) {
119                 *result = dev;
120                 return 1;
121         }
122         switch (errno) {
123                 case AO_ENODRIVER:
124                         msg = "No driver corresponds to driver_id";
125                         break;
126                 case AO_ENOTLIVE:
127                         msg = "This driver is not a live output device";
128                         break;
129                 case AO_EBADOPTION:
130                         msg = "A valid option key has an invalid value";
131                         break;
132                 case AO_EOPENDEVICE:
133                         msg = "Cannot open the device";
134                         break;
135                 case AO_EFAIL:
136                         msg = "General libao error";
137                         break;
138                 default:
139                         msg = "Unknown ao error";
140                         break;
141         }
142         PARA_ERROR_LOG("%s\n", msg);
143         return -E_AO_OPEN_LIVE;
144 }
145
146 static void aow_show_drivers(void)
147 {
148         int i, j, num_drivers;
149         ao_info **driver_list;
150
151         PARA_DEBUG_LOG("libao drivers available on this host:\n");
152         PARA_DEBUG_LOG("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
153
154         driver_list = ao_driver_info_list(&num_drivers);
155
156         for (i = 0; i < num_drivers; i++) {
157                 ao_info *info = driver_list[i];
158                 char *keys = NULL, *tmp = NULL;
159
160                 if (info->type == AO_TYPE_FILE)
161                         continue;
162                 PARA_DEBUG_LOG("name: %s: %s\n", info->short_name, info->name);
163                 PARA_DEBUG_LOG("priority: %d\n", info->priority);
164                 for (j = 0; j < info->option_count; j++) {
165                         tmp = make_message("%s%s%s", keys? keys : "",
166                                 keys? ", " : "",
167                                 info->options[j]);
168                         free(keys);
169                         keys = tmp;
170                 }
171                 PARA_DEBUG_LOG("keys: %s\n", keys? keys : "[none]");
172                 free(keys);
173                 PARA_DEBUG_LOG("comment: %s\n", info->comment?
174                         info->comment : "[none]");
175         }
176 }
177
178 static int aow_init(struct writer_node *wn, unsigned sample_rate,
179                 unsigned channels, int sample_format)
180 {
181         int id, ret, i;
182         ao_option *aoo = NULL;
183         ao_sample_format asf;
184         ao_info *info;
185         const struct lls_opt_result *r;
186         unsigned n;
187         struct private_aow_data *pawd = para_malloc(sizeof(*pawd));
188
189         ao_initialize();
190         aow_show_drivers();
191         if (WRITE_CMD_OPT_GIVEN(AO, DRIVER, wn->lpr)) {
192                 ret = -E_AO_BAD_DRIVER;
193                 id = ao_driver_id(WRITE_CMD_OPT_STRING_VAL(AO, DRIVER, wn->lpr));
194         } else {
195                 ret = -E_AO_DEFAULT_DRIVER;
196                 id = ao_default_driver_id();
197         }
198         if (id < 0)
199                 goto fail;
200         info = ao_driver_info(id);
201         assert(info && info->short_name);
202         if (info->type == AO_TYPE_FILE) {
203                 ret = -E_AO_FILE_NOT_SUPP;
204                 goto fail;
205         }
206         PARA_INFO_LOG("using %s driver\n", info->short_name);
207         r = WRITE_CMD_OPT_RESULT(AO, AO_OPTION, wn->lpr);
208         n = lls_opt_given(r);
209         for (i = 0; i < n; i++) {
210                 char *o = para_strdup(lls_string_val(i, r));
211                 char *value;
212
213                 ret = -E_AO_BAD_OPTION;
214                 value = strchr(o, ':');
215                 if (!value) {
216                         free(o);
217                         goto fail;
218                 }
219                 *value = '\0';
220                 value++;
221                 PARA_INFO_LOG("appending option: key=%s, value=%s\n", o, value);
222                 ret = ao_append_option(&aoo, o, value);
223                 free(o);
224                 if (ret == 0) {
225                         ret = -E_AO_APPEND_OPTION;
226                         goto fail;
227                 }
228         }
229         ret = aow_set_sample_format(sample_rate, channels, sample_format, &asf);
230         if (ret < 0)
231                 goto fail;
232         if (sample_format == SF_S8 || sample_format == SF_U8)
233                 pawd->bytes_per_frame = channels;
234         else
235                 pawd->bytes_per_frame = channels * 2;
236         ret = aow_open_device(id, &asf, aoo, &pawd->dev);
237         if (ret < 0)
238                 goto fail;
239         PARA_INFO_LOG("successfully opened %s\n", info->short_name);
240         wn->private_data = pawd;
241         return 1;
242 fail:
243         free(pawd);
244         return ret;
245 }
246
247 static void *aow_play(void *priv)
248 {
249         struct writer_node *wn = priv;
250         struct private_aow_data *pawd = wn->private_data;
251         struct btr_node *btrn = pawd->thread_btrn;
252         size_t frames, bytes;
253         char *data;
254         int ret;
255
256         pthread_mutex_lock(&pawd->mutex);
257         for (;;) {
258                 for (;;) {
259                         ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
260                         if (ret < 0)
261                                 goto fail;
262                         if (ret > 0) {
263                                 btr_merge(btrn, wn->min_iqs);
264                                 bytes = btr_next_buffer(btrn, &data);
265                                 frames = bytes / pawd->bytes_per_frame;
266                                 if (frames > 0)
267                                         break;
268                                 /* eof and less than a single frame available */
269                                 ret = -E_WRITE_COMMON_EOF;
270                                 goto fail;
271                         }
272                         /*
273                          * No data available, go to sleep and wait for the main
274                          * thread to wake us up. pthread_cond_wait() unlocks
275                          * the mutex while it waits and locks it again upon
276                          * return.
277                          */
278                         ret = pthread_cond_wait(&pawd->data_available,
279                                 &pawd->mutex);
280                         /* pthread_cond_wait() can never fail here */
281                         assert(ret == 0);
282                 }
283                 assert(frames > 0);
284                 bytes = frames * pawd->bytes_per_frame;
285                 pthread_mutex_unlock(&pawd->mutex);
286                 ret = ao_play(pawd->dev, data, bytes);
287                 pthread_mutex_lock(&pawd->mutex);
288                 if (ret == 0) { /* failure */
289                         ret = -E_AO_PLAY;
290                         goto fail;
291                 }
292                 btr_consume(btrn, bytes);
293         }
294 fail:
295         btr_remove_node(&pawd->thread_btrn);
296         assert(ret < 0);
297         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
298         pthread_mutex_unlock(&pawd->mutex);
299         pthread_exit(NULL);
300 }
301
302 static int aow_create_thread(struct writer_node *wn)
303 {
304         struct private_aow_data *pawd = wn->private_data;
305         int ret;
306         const char *msg;
307
308         /* initialize with default attributes */
309         msg = "could not init mutex";
310         ret = pthread_mutex_init(&pawd->mutex, NULL);
311         if (ret < 0)
312                 goto fail;
313
314         msg = "could not initialize condition variable";
315         ret = pthread_cond_init(&pawd->data_available, NULL);
316         if (ret < 0)
317                 goto fail;
318
319         msg = "could not initialize thread attributes";
320         ret = pthread_attr_init(&pawd->attr);
321         if (ret < 0)
322                 goto fail;
323
324         /* schedule this thread under the real-time policy SCHED_FIFO */
325         msg = "could not set sched policy";
326         ret = pthread_attr_setschedpolicy(&pawd->attr, SCHED_FIFO);
327         if (ret < 0)
328                 goto fail;
329
330         msg = "could not set detach state to joinable";
331         ret = pthread_attr_setdetachstate(&pawd->attr, PTHREAD_CREATE_JOINABLE);
332         if (ret < 0)
333                 goto fail;
334
335         msg = "could not create thread";
336         ret = pthread_create(&pawd->thread, &pawd->attr, aow_play, wn);
337         if (ret < 0)
338                 goto fail;
339         return 1;
340 fail:
341         PARA_ERROR_LOG("%s (%s)\n", msg, strerror(ret));
342         return -E_AO_PTHREAD;
343 }
344
345 static int aow_post_select(__a_unused struct sched *s, void *context)
346 {
347         struct writer_node *wn = context;
348         struct private_aow_data *pawd = wn->private_data;
349         int ret;
350
351         if (!pawd) {
352                 int32_t rate, ch, format;
353                 struct btr_node_description bnd;
354
355                 ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
356                 if (ret < 0)
357                         goto remove_btrn;
358                 if (ret == 0)
359                         return 0;
360                 get_btr_sample_rate(wn->btrn, &rate);
361                 get_btr_channels(wn->btrn, &ch);
362                 get_btr_sample_format(wn->btrn, &format);
363                 ret = aow_init(wn, rate, ch, format);
364                 if (ret < 0)
365                         goto remove_btrn;
366                 pawd = wn->private_data;
367
368                 /* set up thread btr node */
369                 bnd.name = "ao_thread_btrn";
370                 bnd.parent = wn->btrn;
371                 bnd.child = NULL;
372                 bnd.handler = NULL;
373                 bnd.context = pawd;
374                 pawd->thread_btrn = btr_new_node(&bnd);
375                 wn->private_data = pawd;
376
377                 ret = aow_create_thread(wn);
378                 if (ret < 0)
379                         goto remove_thread_btrn;
380                 return 0;
381         }
382         if (!wn->btrn) {
383                 if (!pawd->thread_btrn) {
384                         pthread_join(pawd->thread, NULL);
385                         return -E_AO_EOF;
386                 }
387                 PARA_INFO_LOG("waiting for play thread to terminate\n");
388                 return 0;
389         }
390         pthread_mutex_lock(&pawd->mutex);
391         ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
392         if (ret > 0) {
393                 btr_pushdown(wn->btrn);
394                 if (pthread_cond_signal(&pawd->data_available) != 0) {
395                         ret = -E_AO_PTHREAD;
396                         PARA_ERROR_LOG("pthread_cond_signal() failed\n");
397                         goto remove_thread_btrn;
398                 }
399         }
400         if (ret >= 0) {
401                 pthread_mutex_unlock(&pawd->mutex);
402                 goto out;
403         }
404         btr_remove_node(&wn->btrn);
405         pthread_cond_signal(&pawd->data_available);
406         pthread_mutex_unlock(&pawd->mutex);
407         return 0;
408 remove_thread_btrn:
409         btr_remove_node(&pawd->thread_btrn);
410 remove_btrn:
411         btr_remove_node(&wn->btrn);
412 out:
413         return ret;
414 }
415
416 struct writer lsg_write_cmd_com_ao_user_data = {
417         .close = aow_close,
418         .pre_select = aow_pre_select,
419         .post_select = aow_post_select,
420 };
421