summaryrefslogtreecommitdiff
path: root/bat/alsa.c
blob: 94f47f422cdfb54aa96c8dfd1a0c8ba2f3e950bb (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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
/*
 * Copyright (C) 2013-2015 Intel Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 */

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdint.h>
#include <pthread.h>
#include <errno.h>

#include <alsa/asoundlib.h>

#include "aconfig.h"
#include "gettext.h"

#include "common.h"
#include "alsa.h"

struct pcm_container {
	snd_pcm_t *handle;
	snd_pcm_uframes_t period_size;
	snd_pcm_uframes_t buffer_size;
	snd_pcm_format_t format;
	unsigned short channels;
	size_t period_bytes;
	size_t sample_bits;
	size_t frame_bits;
	char *buffer;
};

static int set_snd_pcm_params(struct bat *bat, struct pcm_container *sndpcm)
{
	snd_pcm_hw_params_t *params;
	unsigned int buffer_time = 0;
	unsigned int period_time = 0;
	unsigned int rate;
	int err;
	const char *device_name = snd_pcm_name(sndpcm->handle);

	/* Allocate a hardware parameters object. */
	snd_pcm_hw_params_alloca(&params);

	/* Fill it in with default values. */
	err = snd_pcm_hw_params_any(sndpcm->handle, params);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("default params: %s: %s(%d)\n"),
				device_name, snd_strerror(err), err);
		return err;
	}

	/* Set access mode */
	err = snd_pcm_hw_params_set_access(sndpcm->handle, params,
			SND_PCM_ACCESS_RW_INTERLEAVED);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("access type: %s: %s(%d)\n"),
				device_name, snd_strerror(err), err);
		return err;
	}

	/* Set format */
	err = snd_pcm_hw_params_set_format(sndpcm->handle, params, bat->format);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("PCM format: %d %s: %s(%d)\n"),
				bat->format,
				device_name, snd_strerror(err), err);
		return err;
	}

	/* Set channels */
	err = snd_pcm_hw_params_set_channels(sndpcm->handle,
			params, bat->channels);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("channel number: %d %s: %s(%d)\n"),
				bat->channels,
				device_name, snd_strerror(err), err);
		return err;
	}

	/* Set sampling rate */
	rate = bat->rate;
	err = snd_pcm_hw_params_set_rate_near(sndpcm->handle,
			params, &bat->rate,
			0);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("sample rate: %d %s: %s(%d)\n"),
				bat->rate,
				device_name, snd_strerror(err), err);
		return err;
	}
	if ((float) rate * (1 + RATE_RANGE) < bat->rate
			|| (float) rate * (1 - RATE_RANGE) > bat->rate) {
		fprintf(bat->err, _("Invalid parameters: sample rate: "));
		fprintf(bat->err, _("requested %dHz, got %dHz\n"),
				rate, bat->rate);
		return -EINVAL;
	}

	if (snd_pcm_hw_params_get_buffer_time_max(params,
			&buffer_time, 0) < 0) {
		fprintf(bat->err, _("Get parameter from device error: "));
		fprintf(bat->err, _("buffer time: %d %s: %s(%d)\n"),
				buffer_time,
				device_name, snd_strerror(err), err);
		return -EINVAL;
	}

	if (buffer_time > MAX_BUFFERTIME)
		buffer_time = MAX_BUFFERTIME;

	period_time = buffer_time / DIV_BUFFERTIME;

	/* Set buffer time and period time */
	err = snd_pcm_hw_params_set_buffer_time_near(sndpcm->handle, params,
			&buffer_time, 0);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("buffer time: %d %s: %s(%d)\n"),
				buffer_time,
				device_name, snd_strerror(err), err);
		return err;
	}

	err = snd_pcm_hw_params_set_period_time_near(sndpcm->handle, params,
			&period_time, 0);
	if (err < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("period time: %d %s: %s(%d)\n"),
				period_time,
				device_name, snd_strerror(err), err);
		return err;
	}

	/* Write the parameters to the driver */
	if (snd_pcm_hw_params(sndpcm->handle, params) < 0) {
		fprintf(bat->err, _("Set parameter to device error: "));
		fprintf(bat->err, _("hw params: %s: %s(%d)\n"),
				device_name, snd_strerror(err), err);
		return -EINVAL;
	}

	err = snd_pcm_hw_params_get_period_size(params,
			&sndpcm->period_size, 0);
	if (err < 0) {
		fprintf(bat->err, _("Get parameter from device error: "));
		fprintf(bat->err, _("period size: %zd %s: %s(%d)\n"),
				sndpcm->period_size,
				device_name, snd_strerror(err), err);
		return err;
	}

	err = snd_pcm_hw_params_get_buffer_size(params, &sndpcm->buffer_size);
	if (err < 0) {
		fprintf(bat->err, _("Get parameter from device error: "));
		fprintf(bat->err, _("buffer size: %zd %s: %s(%d)\n"),
				sndpcm->buffer_size,
				device_name, snd_strerror(err), err);
		return err;
	}

	if (sndpcm->period_size == sndpcm->buffer_size) {
		fprintf(bat->err, _("Invalid parameters: can't use period "));
		fprintf(bat->err, _("equal to buffer size (%zd)\n"),
				sndpcm->period_size);
		return -EINVAL;
	}

	err = snd_pcm_format_physical_width(bat->format);
	if (err < 0) {
		fprintf(bat->err, _("Invalid parameters: "));
		fprintf(bat->err, _("snd_pcm_format_physical_width: %d\n"),
				err);
		return err;
	}
	sndpcm->sample_bits = err;

	sndpcm->frame_bits = sndpcm->sample_bits * bat->channels;

	/* Calculate the period bytes */
	sndpcm->period_bytes = sndpcm->period_size * sndpcm->frame_bits / 8;
	sndpcm->buffer = (char *) malloc(sndpcm->period_bytes);
	if (sndpcm->buffer == NULL) {
		fprintf(bat->err, _("Not enough memory: size=%zd\n"),
				sndpcm->period_bytes);
		return -ENOMEM;
	}

	return 0;
}

static int write_to_pcm(const struct pcm_container *sndpcm,
		int frames, struct bat *bat)
{
	int err;
	int offset = 0;
	int remain = frames;

	while (remain > 0) {
		err = snd_pcm_writei(sndpcm->handle, sndpcm->buffer + offset,
				remain);
		if (err == -EAGAIN || (err >= 0 && err < frames)) {
			snd_pcm_wait(sndpcm->handle, 500);
		} else if (err == -EPIPE) {
			fprintf(bat->err, _("Underrun: %s(%d)\n"),
					snd_strerror(err), err);
			snd_pcm_prepare(sndpcm->handle);
		} else if (err < 0) {
			fprintf(bat->err, _("Write PCM device error: %s(%d)\n"),
					snd_strerror(err), err);
			return err;
		}

		if (err > 0) {
			remain -= err;
			offset += err * sndpcm->frame_bits / 8;
		}
	}

	return 0;
}

static int write_to_pcm_loop(struct pcm_container *sndpcm, struct bat *bat)
{
	int err = 0;
	int bytes = sndpcm->period_bytes; /* playback buffer size */
	int frames = bytes * 8 / sndpcm->frame_bits; /* frame count */
	FILE *fp = NULL;
	int bytes_total = 0;

	if (bat->debugplay) {
		fp = fopen(bat->debugplay, "wb");
		err = -errno;
		if (fp == NULL) {
			fprintf(bat->err, _("Cannot open file: %s %d\n"),
					bat->debugplay, err);
			return err;
		}
		/* leave space for wav header */
		if (fseek(fp, sizeof(struct wav_container), SEEK_SET) != 0) {
			err = -errno;
			fclose(fp);
			return err;
		}
	}

	while (1) {
		err = generate_input_data(bat, sndpcm->buffer, bytes, frames);
		if (err != 0)
			break;

		if (bat->debugplay) {
			if (fwrite(sndpcm->buffer, 1, bytes, fp) != bytes) {
				err = -EIO;
				break;
			}
			bytes_total += bytes;
		}

		bat->periods_played++;
		if (bat->period_is_limited
				&& bat->periods_played >= bat->periods_total)
			break;

		err = write_to_pcm(sndpcm, frames, bat);
		if (err != 0)
			break;
	}

	if (bat->debugplay) {
		update_wav_header(bat, fp, bytes_total);
		fclose(fp);
	}

	snd_pcm_drain(sndpcm->handle);

	return err;
}

/**
 * Play
 */
void *playback_alsa(struct bat *bat)
{
	int err = 0;
	struct pcm_container sndpcm;

	fprintf(bat->log, _("Entering playback thread (ALSA).\n"));

	retval_play = 0;
	memset(&sndpcm, 0, sizeof(sndpcm));

	err = snd_pcm_open(&sndpcm.handle, bat->playback.device,
			SND_PCM_STREAM_PLAYBACK, 0);
	if (err != 0) {
		fprintf(bat->err, _("Cannot open PCM playback device: "));
		fprintf(bat->err, _("%s(%d)\n"), snd_strerror(err), err);
		retval_play = err;
		goto exit1;
	}

	err = set_snd_pcm_params(bat, &sndpcm);
	if (err != 0) {
		retval_play = err;
		goto exit2;
	}

	if (bat->playback.file == NULL) {
		fprintf(bat->log, _("Playing generated audio sine wave"));
		bat->sinus_duration == 0 ?
			fprintf(bat->log, _(" endlessly\n")) :
			fprintf(bat->log, _("\n"));
	} else {
		fprintf(bat->log, _("Playing input audio file: %s\n"),
				bat->playback.file);
		bat->fp = fopen(bat->playback.file, "rb");
		err = -errno;
		if (bat->fp == NULL) {
			fprintf(bat->err, _("Cannot open file: %s %d\n"),
					bat->playback.file, err);
			retval_play = err;
			goto exit3;
		}
		/* Skip header */
		err = read_wav_header(bat, bat->playback.file, bat->fp, true);
		if (err != 0) {
			retval_play = err;
			goto exit4;
		}
	}

	err = write_to_pcm_loop(&sndpcm, bat);
	if (err < 0) {
		retval_play = err;
		goto exit4;
	}

exit4:
	if (bat->playback.file)
		fclose(bat->fp);
exit3:
	free(sndpcm.buffer);
exit2:
	snd_pcm_close(sndpcm.handle);
exit1:
	pthread_exit(&retval_play);
}

static int read_from_pcm(struct pcm_container *sndpcm,
		int frames, struct bat *bat)
{
	int err = 0;
	int offset = 0;
	int remain = frames;

	while (remain > 0) {
		err = snd_pcm_readi(sndpcm->handle,
				sndpcm->buffer + offset, remain);
		if (err == -EAGAIN || (err >= 0 && err < remain)) {
			snd_pcm_wait(sndpcm->handle, 500);
		} else if (err == -EPIPE) {
			snd_pcm_prepare(sndpcm->handle);
			fprintf(bat->err, _("Overrun: %s(%d)\n"),
					snd_strerror(err), err);
		} else if (err < 0) {
			fprintf(bat->err, _("Read PCM device error: %s(%d)\n"),
					snd_strerror(err), err);
			return err;
		}

		if (err > 0) {
			remain -= err;
			offset += err * sndpcm->frame_bits / 8;
		}
	}

	return 0;
}

static int read_from_pcm_loop(struct pcm_container *sndpcm, struct bat *bat)
{
	int err = 0;
	FILE *fp = NULL;
	int size, frames;
	int bytes_read = 0;
	int bytes_count = bat->frames * bat->frame_size;
	int remain = bytes_count;

	remove(bat->capture.file);
	fp = fopen(bat->capture.file, "wb");
	err = -errno;
	if (fp == NULL) {
		fprintf(bat->err, _("Cannot open file: %s %d\n"),
				bat->capture.file, err);
		return err;
	}
	/* leave space for file header */
	if (fseek(fp, sizeof(struct wav_container), SEEK_SET) != 0) {
		err = -errno;
		fclose(fp);
		return err;
	}

	while (remain > 0) {
		size = (remain <= sndpcm->period_bytes) ?
			remain : sndpcm->period_bytes;
		frames = size * 8 / sndpcm->frame_bits;

		/* read a chunk from pcm device */
		err = read_from_pcm(sndpcm, frames, bat);
		if (err != 0)
			break;

		/* write the chunk to file */
		if (fwrite(sndpcm->buffer, 1, size, fp) != size) {
			err = -EIO;
			break;
		}

		bytes_read += size;
		remain -= size;
		bat->periods_played++;

		if (bat->period_is_limited
				&& bat->periods_played >= bat->periods_total)
			break;
	}

	update_wav_header(bat, fp, bytes_read);

	fclose(fp);
	return err;
}

static void pcm_cleanup(void *p)
{
	snd_pcm_close(p);
}

/**
 * Record
 */
void *record_alsa(struct bat *bat)
{
	int err = 0;
	struct pcm_container sndpcm;

	pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);

	fprintf(bat->log, _("Entering capture thread (ALSA).\n"));

	retval_record = 0;
	memset(&sndpcm, 0, sizeof(sndpcm));

	err = snd_pcm_open(&sndpcm.handle, bat->capture.device,
			SND_PCM_STREAM_CAPTURE, 0);
	if (err != 0) {
		fprintf(bat->err, _("Cannot open PCM capture device: "));
		fprintf(bat->err, _("%s(%d)\n"), snd_strerror(err), err);
		retval_record = err;
		goto exit1;
	}

	err = set_snd_pcm_params(bat, &sndpcm);
	if (err != 0) {
		retval_record = err;
		goto exit2;
	}

	pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
	pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
	pthread_cleanup_push(pcm_cleanup, sndpcm.handle);
	pthread_cleanup_push(free, sndpcm.buffer);

	fprintf(bat->log, _("Recording ...\n"));
	err = read_from_pcm_loop(&sndpcm, bat);
	if (err != 0) {
		retval_record = err;
		goto exit3;
	}

	/* Normally we will never reach this part of code (unless error in
	 * previous call) (before exit3) as this thread will be cancelled
	 * by end of play thread. Except in single line mode. */
	pthread_cleanup_pop(0);
	pthread_cleanup_pop(0);

	snd_pcm_drain(sndpcm.handle);
	pthread_exit(&retval_record);

exit3:
	free(sndpcm.buffer);
exit2:
	snd_pcm_close(sndpcm.handle);
exit1:
	pthread_exit(&retval_record);
}