summaryrefslogtreecommitdiff
path: root/ao_write.c
blob: ca2b35ad66039c29b1ded457c97155a5b7481b46 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
/* SPDX-License-Identifier: GPL-2.0 */

/** \file ao_write.c Paraslash's libao output plugin. */

#include <pthread.h>
#include <ao/ao.h>
#include <lopsub.h>

#include "write_cmd.lsg.h"
#include "para.h"
#include "fd.h"
#include "string.h"
#include "list.h"
#include "sched.h"
#include "buffer_tree.h"
#include "write.h"
#include "error.h"

struct private_aow_data {
	ao_device *dev;
	int bytes_per_frame;

	pthread_t thread;
	pthread_attr_t attr;
	/* The mutex and the condition variable serialize access to ->btrn */
	pthread_mutex_t mutex;
	pthread_cond_t data_available;
	struct btr_node *thread_btrn;
};

static void aow_close(struct writer_node *wn)
{
	struct private_aow_data *pawd = wn->private_data;

	if (!pawd)
		return;
	assert(!pawd->thread_btrn);
	ao_close(pawd->dev);
	free(pawd);
	wn->private_data = NULL;
	ao_shutdown();
}

static void aow_pre_monitor(struct sched *s, void *context)
{
	struct writer_node *wn = context;
	struct private_aow_data *pawd = wn->private_data;
	int ret;

	if (!pawd) { /* not yet started */
		assert(wn->btrn);
		ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
		if (ret != 0)
			goto min_delay;
		return; /* no data available */
	}
	if (!wn->btrn) { /* EOF */
		if (!pawd->thread_btrn) /* ready to exit */
			goto min_delay;
		/* wait for the play thread to terminate */
		goto timeout;
	}
	pthread_mutex_lock(&pawd->mutex);
	ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
	pthread_mutex_unlock(&pawd->mutex);
	if (ret != 0)
		goto min_delay;
	/*
	 * Even though the node status is zero, we might have data available,
	 * but the output buffer is full. If we don't set a timeout here, we
	 * are woken up only if new data arrives, which might be too late and
	 * result in a buffer underrun in the playing thread. To avoid this we
	 * never sleep longer than the (default) buffer time.
	 */
timeout:
	return sched_request_timeout_ms(20, s);
min_delay:
	sched_min_delay(s);
}

static int aow_set_sample_format(unsigned sample_rate, unsigned channels,
		int sample_format, ao_sample_format *result)
{
	memset(result, 0, sizeof(*result));
	switch (sample_format) {
		case SF_U8:
		case SF_U16_LE:
		case SF_U16_BE:
		case SF_FLOAT_LE:
		case SF_FLOAT_BE:
			return -E_BAD_SAMPLE_FORMAT;
		case SF_S8:
			/* no need to set byte_format */
			result->bits = 8;
			break;
		case SF_S16_LE:
			result->bits = 16;
			result->byte_format = AO_FMT_LITTLE;
			break;
		case SF_S16_BE:
			result->bits = 16;
			result->byte_format = AO_FMT_BIG;
			break;
		default:
			PARA_EMERG_LOG("bug: invalid sample format\n");
			exit(EXIT_FAILURE);
	}
	result->channels = channels;
	result->rate = sample_rate;
	return 1;
}

static int aow_open_device(int id, ao_sample_format *asf, ao_option *options,
		ao_device **result)
{
	const char *msg;
	ao_device *dev = ao_open_live(id, asf, options);

	if (dev) {
		*result = dev;
		return 1;
	}
	switch (errno) {
		case AO_ENODRIVER:
			msg = "No driver corresponds to driver_id";
			break;
		case AO_ENOTLIVE:
			msg = "This driver is not a live output device";
			break;
		case AO_EBADOPTION:
			msg = "A valid option key has an invalid value";
			break;
		case AO_EOPENDEVICE:
			msg = "Cannot open the device";
			break;
		case AO_EFAIL:
			msg = "General libao error";
			break;
		default:
			msg = "Unknown ao error";
			break;
	}
	PARA_ERROR_LOG("%s\n", msg);
	return -E_AO_OPEN_LIVE;
}

static void aow_show_drivers(void)
{
	int i, j, num_drivers;
	ao_info **driver_list;

	PARA_DEBUG_LOG("libao drivers available on this host:\n");
	PARA_DEBUG_LOG("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");

	driver_list = ao_driver_info_list(&num_drivers);

	for (i = 0; i < num_drivers; i++) {
		ao_info *info = driver_list[i];
		char *keys = NULL, *tmp = NULL;

		if (info->type == AO_TYPE_FILE)
			continue;
		PARA_DEBUG_LOG("name: %s: %s\n", info->short_name, info->name);
		PARA_DEBUG_LOG("priority: %d\n", info->priority);
		for (j = 0; j < info->option_count; j++) {
			tmp = make_message("%s%s%s", keys? keys : "",
				keys? ", " : "",
				info->options[j]);
			free(keys);
			keys = tmp;
		}
		PARA_DEBUG_LOG("keys: %s\n", keys? keys : "[none]");
		free(keys);
		PARA_DEBUG_LOG("comment: %s\n", info->comment?
			info->comment : "[none]");
	}
}

static int aow_init(struct writer_node *wn, unsigned sample_rate,
		unsigned channels, int sample_format)
{
	int id, ret, i;
	ao_option *aoo = NULL;
	ao_sample_format asf;
	ao_info *info;
	const struct lls_opt_result *r;
	unsigned n;
	struct private_aow_data *pawd = alloc(sizeof(*pawd));

	ao_initialize();
	aow_show_drivers();
	if (WRITE_CMD_OPT_GIVEN(AO, DRIVER, wn->lpr)) {
		ret = -E_AO_BAD_DRIVER;
		id = ao_driver_id(WRITE_CMD_OPT_STRING_VAL(AO, DRIVER, wn->lpr));
	} else {
		ret = -E_AO_DEFAULT_DRIVER;
		id = ao_default_driver_id();
	}
	if (id < 0)
		goto fail;
	info = ao_driver_info(id);
	assert(info && info->short_name);
	if (info->type == AO_TYPE_FILE) {
		ret = -E_AO_FILE_NOT_SUPP;
		goto fail;
	}
	PARA_INFO_LOG("using %s driver\n", info->short_name);
	r = WRITE_CMD_OPT_RESULT(AO, AO_OPTION, wn->lpr);
	n = lls_opt_given(r);
	for (i = 0; i < n; i++) {
		char *o = para_strdup(lls_string_val(i, r));
		char *value;

		ret = -E_AO_BAD_OPTION;
		value = strchr(o, ':');
		if (!value) {
			free(o);
			goto fail;
		}
		*value = '\0';
		value++;
		PARA_INFO_LOG("appending option: key=%s, value=%s\n", o, value);
		ret = ao_append_option(&aoo, o, value);
		free(o);
		if (ret == 0) {
			ret = -E_AO_APPEND_OPTION;
			goto fail;
		}
	}
	ret = aow_set_sample_format(sample_rate, channels, sample_format, &asf);
	if (ret < 0)
		goto fail;
	if (sample_format == SF_S8 || sample_format == SF_U8)
		pawd->bytes_per_frame = channels;
	else
		pawd->bytes_per_frame = channels * 2;
	ret = aow_open_device(id, &asf, aoo, &pawd->dev);
	if (ret < 0)
		goto fail;
	PARA_INFO_LOG("successfully opened %s\n", info->short_name);
	wn->private_data = pawd;
	return 1;
fail:
	free(pawd);
	return ret;
}

static void *aow_play(void *priv)
{
	struct writer_node *wn = priv;
	struct private_aow_data *pawd = wn->private_data;
	struct btr_node *btrn = pawd->thread_btrn;
	size_t frames, bytes;
	char *data;
	int ret;

	pthread_mutex_lock(&pawd->mutex);
	for (;;) {
		for (;;) {
			ret = btr_node_status(btrn, wn->min_iqs, BTR_NT_LEAF);
			if (ret < 0)
				goto fail;
			if (ret > 0) {
				btr_merge(btrn, wn->min_iqs);
				bytes = btr_next_buffer(btrn, &data);
				frames = bytes / pawd->bytes_per_frame;
				if (frames > 0)
					break;
				/* eof and less than a single frame available */
				ret = -E_EOF;
				goto fail;
			}
			/*
			 * No data available, go to sleep and wait for the main
			 * thread to wake us up. pthread_cond_wait() unlocks
			 * the mutex while it waits and locks it again upon
			 * return.
			 */
			ret = pthread_cond_wait(&pawd->data_available,
				&pawd->mutex);
			/* pthread_cond_wait() can never fail here */
			assert(ret == 0);
		}
		assert(frames > 0);
		bytes = frames * pawd->bytes_per_frame;
		pthread_mutex_unlock(&pawd->mutex);
		ret = ao_play(pawd->dev, data, bytes);
		pthread_mutex_lock(&pawd->mutex);
		if (ret == 0) { /* failure */
			ret = -E_AO_PLAY;
			goto fail;
		}
		btr_consume(btrn, bytes);
	}
fail:
	btr_remove_node(&pawd->thread_btrn);
	assert(ret < 0);
	PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
	pthread_mutex_unlock(&pawd->mutex);
	pthread_exit(NULL);
}

static int aow_create_thread(struct writer_node *wn)
{
	struct private_aow_data *pawd = wn->private_data;
	int ret;
	const char *msg;

	/* initialize with default attributes */
	msg = "could not init mutex";
	ret = pthread_mutex_init(&pawd->mutex, NULL);
	if (ret < 0)
		goto fail;

	msg = "could not initialize condition variable";
	ret = pthread_cond_init(&pawd->data_available, NULL);
	if (ret < 0)
		goto fail;

	msg = "could not initialize thread attributes";
	ret = pthread_attr_init(&pawd->attr);
	if (ret < 0)
		goto fail;

	/* schedule this thread under the real-time policy SCHED_FIFO */
	msg = "could not set sched policy";
	ret = pthread_attr_setschedpolicy(&pawd->attr, SCHED_FIFO);
	if (ret < 0)
		goto fail;

	msg = "could not set detach state to joinable";
	ret = pthread_attr_setdetachstate(&pawd->attr, PTHREAD_CREATE_JOINABLE);
	if (ret < 0)
		goto fail;

	msg = "could not create thread";
	ret = pthread_create(&pawd->thread, &pawd->attr, aow_play, wn);
	if (ret < 0)
		goto fail;
	return 1;
fail:
	PARA_ERROR_LOG("%s (%s)\n", msg, strerror(ret));
	return -E_AO_PTHREAD;
}

static int aow_post_monitor(__a_unused struct sched *s, void *context)
{
	struct writer_node *wn = context;
	struct private_aow_data *pawd = wn->private_data;
	int ret;

	if (!pawd) {
		int32_t rate, ch, format;
		struct btr_node_description bnd;

		ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
		if (ret < 0)
			goto remove_btrn;
		if (ret == 0)
			return 0;
		ret = get_btr_sample_rate(wn->btrn, &rate);
		if (ret < 0)
			goto remove_btrn;
		ret = get_btr_channels(wn->btrn, &ch);
		if (ret < 0)
			goto remove_btrn;
		ret = get_btr_sample_format(wn->btrn, &format);
		if (ret < 0)
			goto remove_btrn;
		ret = aow_init(wn, rate, ch, format);
		if (ret < 0)
			goto remove_btrn;
		pawd = wn->private_data;

		/* set up thread btr node */
		bnd.name = "ao_thread_btrn";
		bnd.parent = wn->btrn;
		bnd.child = NULL;
		bnd.handler = NULL;
		bnd.context = pawd;
		pawd->thread_btrn = btr_new_node(&bnd);
		wn->private_data = pawd;

		ret = aow_create_thread(wn);
		if (ret < 0)
			goto remove_thread_btrn;
		return 0;
	}
	if (!wn->btrn) {
		if (!pawd->thread_btrn) {
			pthread_join(pawd->thread, NULL);
			return -E_EOF;
		}
		PARA_INFO_LOG("waiting for play thread to terminate\n");
		return 0;
	}
	pthread_mutex_lock(&pawd->mutex);
	ret = btr_node_status(wn->btrn, wn->min_iqs, BTR_NT_LEAF);
	if (ret > 0) {
		btr_pushdown(wn->btrn);
		if (pthread_cond_signal(&pawd->data_available) != 0) {
			ret = -E_AO_PTHREAD;
			PARA_ERROR_LOG("pthread_cond_signal() failed\n");
			goto remove_thread_btrn;
		}
	}
	if (ret >= 0) {
		pthread_mutex_unlock(&pawd->mutex);
		goto out;
	}
	btr_remove_node(&wn->btrn);
	pthread_cond_signal(&pawd->data_available);
	pthread_mutex_unlock(&pawd->mutex);
	return 0;
remove_thread_btrn:
	btr_remove_node(&pawd->thread_btrn);
remove_btrn:
	btr_remove_node(&wn->btrn);
out:
	return ret;
}

/** \cond doxygen_ignore */
struct writer lsg_write_cmd_com_ao_user_data = {
	.close = aow_close,
	.pre_monitor = aow_pre_monitor,
	.post_monitor = aow_post_monitor,
};
/** \endcond */