jack_output_plugin.c 17.2 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2011 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * 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.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

20
#include "config.h"
21
#include "jack_output_plugin.h"
22
#include "output_api.h"
23

24 25
#include <assert.h>

26
#include <glib.h>
27 28 29 30
#include <jack/jack.h>
#include <jack/types.h>
#include <jack/ringbuffer.h>

31 32 33 34 35 36
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

Max Kellermann's avatar
Max Kellermann committed
37 38 39
#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN "jack"

40 41 42 43
enum {
	MAX_PORTS = 16,
};

44
static const size_t jack_sample_size = sizeof(jack_default_audio_sample_t);
45

46
struct jack_data {
47 48
	struct audio_output base;

49 50 51 52 53
	/**
	 * libjack options passed to jack_client_open().
	 */
	jack_options_t options;

54
	const char *name;
55

56 57
	const char *server_name;

58
	/* configuration */
59

60 61 62
	char *source_ports[MAX_PORTS];
	unsigned num_source_ports;

63 64
	char *destination_ports[MAX_PORTS];
	unsigned num_destination_ports;
65

66
	size_t ringbuffer_size;
67

68 69
	/* the current audio format */
	struct audio_format audio_format;
70

71
	/* jack library stuff */
72
	jack_port_t *ports[MAX_PORTS];
73
	jack_client_t *client;
74
	jack_ringbuffer_t *ringbuffer[MAX_PORTS];
75

76
	bool shutdown;
77 78 79 80 81 82

	/**
	 * While this flag is set, the "process" callback generates
	 * silence.
	 */
	bool pause;
83
};
84

85 86 87 88 89 90 91 92 93
/**
 * The quark used for GError.domain.
 */
static inline GQuark
jack_output_quark(void)
{
	return g_quark_from_static_string("jack_output");
}

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
/**
 * Determine the number of frames guaranteed to be available on all
 * channels.
 */
static jack_nframes_t
mpd_jack_available(const struct jack_data *jd)
{
	size_t min = jack_ringbuffer_read_space(jd->ringbuffer[0]);

	for (unsigned i = 1; i < jd->audio_format.channels; ++i) {
		size_t current = jack_ringbuffer_read_space(jd->ringbuffer[i]);
		if (current < min)
			min = current;
	}

109
	assert(min % jack_sample_size == 0);
110

111
	return min / jack_sample_size;
112 113
}

114 115
static int
mpd_jack_process(jack_nframes_t nframes, void *arg)
116
{
117
	struct jack_data *jd = (struct jack_data *) arg;
118
	jack_default_audio_sample_t *out;
119

Max Kellermann's avatar
Max Kellermann committed
120
	if (nframes <= 0)
121 122
		return 0;

123
	if (jd->pause) {
124 125 126 127 128
		/* empty the ring buffers */

		const jack_nframes_t available = mpd_jack_available(jd);
		for (unsigned i = 0; i < jd->audio_format.channels; ++i)
			jack_ringbuffer_read_advance(jd->ringbuffer[i],
129
						     available * jack_sample_size);
130

131 132
		/* generate silence while MPD is paused */

133
		for (unsigned i = 0; i < jd->audio_format.channels; ++i) {
134 135 136 137 138 139 140 141 142
			out = jack_port_get_buffer(jd->ports[i], nframes);

			for (jack_nframes_t f = 0; f < nframes; ++f)
				out[f] = 0.0;
		}

		return 0;
	}

143 144 145
	jack_nframes_t available = mpd_jack_available(jd);
	if (available > nframes)
		available = nframes;
146

147
	for (unsigned i = 0; i < jd->audio_format.channels; ++i) {
148
		out = jack_port_get_buffer(jd->ports[i], nframes);
149 150 151 152 153 154 155
		if (out == NULL)
			/* workaround for libjack1 bug: if the server
			   connection fails, the process callback is
			   invoked anyway, but unable to get a
			   buffer */
			continue;

156
		jack_ringbuffer_read(jd->ringbuffer[i],
157
				     (char *)out, available * jack_sample_size);
158

159
		for (jack_nframes_t f = available; f < nframes; ++f)
160
			/* ringbuffer underrun, fill with silence */
161
			out[f] = 0.0;
162 163
	}

164 165 166 167 168
	/* generate silence for the unused source ports */

	for (unsigned i = jd->audio_format.channels;
	     i < jd->num_source_ports; ++i) {
		out = jack_port_get_buffer(jd->ports[i], nframes);
169 170 171 172 173 174
		if (out == NULL)
			/* workaround for libjack1 bug: if the server
			   connection fails, the process callback is
			   invoked anyway, but unable to get a
			   buffer */
			continue;
175 176 177 178 179

		for (jack_nframes_t f = 0; f < nframes; ++f)
			out[f] = 0.0;
	}

180 181 182
	return 0;
}

183 184
static void
mpd_jack_shutdown(void *arg)
185
{
186
	struct jack_data *jd = (struct jack_data *) arg;
187
	jd->shutdown = true;
188 189
}

190 191
static void
set_audioformat(struct jack_data *jd, struct audio_format *audio_format)
192
{
193
	audio_format->sample_rate = jack_get_sample_rate(jd->client);
194

195 196 197
	if (jd->num_source_ports == 1)
		audio_format->channels = 1;
	else if (audio_format->channels > jd->num_source_ports)
198
		audio_format->channels = 2;
199

200 201 202
	if (audio_format->format != SAMPLE_FORMAT_S16 &&
	    audio_format->format != SAMPLE_FORMAT_S24_P32)
		audio_format->format = SAMPLE_FORMAT_S24_P32;
203 204
}

205 206
static void
mpd_jack_error(const char *msg)
207
{
Max Kellermann's avatar
Max Kellermann committed
208
	g_warning("%s", msg);
209 210
}

211
#ifdef HAVE_JACK_SET_INFO_FUNCTION
212 213 214 215 216
static void
mpd_jack_info(const char *msg)
{
	g_message("%s", msg);
}
217
#endif
218

219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
/**
 * Disconnect the JACK client.
 */
static void
mpd_jack_disconnect(struct jack_data *jd)
{
	assert(jd != NULL);
	assert(jd->client != NULL);

	jack_deactivate(jd->client);
	jack_client_close(jd->client);
	jd->client = NULL;
}

/**
 * Connect the JACK client and performs some basic setup
 * (e.g. register callbacks).
 */
static bool
mpd_jack_connect(struct jack_data *jd, GError **error_r)
{
240 241
	jack_status_t status;

242 243 244 245
	assert(jd != NULL);

	jd->shutdown = false;

246 247
	jd->client = jack_client_open(jd->name, jd->options, &status,
				      jd->server_name);
248
	if (jd->client == NULL) {
249
		g_set_error(error_r, jack_output_quark(), 0,
250 251
			    "Failed to connect to JACK server, status=%d",
			    status);
252 253 254 255 256 257
		return false;
	}

	jack_set_process_callback(jd->client, mpd_jack_process, jd);
	jack_on_shutdown(jd->client, mpd_jack_shutdown, jd);

258 259 260
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
		jd->ports[i] = jack_port_register(jd->client,
						  jd->source_ports[i],
261 262 263 264 265
						  JACK_DEFAULT_AUDIO_TYPE,
						  JackPortIsOutput, 0);
		if (jd->ports[i] == NULL) {
			g_set_error(error_r, jack_output_quark(), 0,
				    "Cannot register output port \"%s\"",
266
				    jd->source_ports[i]);
267 268 269 270 271 272 273 274 275 276 277 278 279 280
			mpd_jack_disconnect(jd);
			return false;
		}
	}

	return true;
}

static bool
mpd_jack_test_default_device(void)
{
	return true;
}

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
static unsigned
parse_port_list(int line, const char *source, char **dest, GError **error_r)
{
	char **list = g_strsplit(source, ",", 0);
	unsigned n = 0;

	for (n = 0; list[n] != NULL; ++n) {
		if (n >= MAX_PORTS) {
			g_set_error(error_r, jack_output_quark(), 0,
				    "too many port names in line %d",
				    line);
			return 0;
		}

		dest[n] = list[n];
	}

	g_free(list);

	if (n == 0) {
		g_set_error(error_r, jack_output_quark(), 0,
			    "at least one port name expected in line %d",
			    line);
		return 0;
	}

	return n;
}

310 311
static struct audio_output *
mpd_jack_init(const struct config_param *param, GError **error_r)
312
{
313 314 315 316 317 318 319
	struct jack_data *jd = g_new(struct jack_data, 1);

	if (!ao_base_init(&jd->base, &jack_output_plugin, param, error_r)) {
		g_free(jd);
		return NULL;
	}

320
	const char *value;
321

322 323 324 325 326 327 328 329 330 331
	jd->options = JackNullOption;

	jd->name = config_get_block_string(param, "client_name", NULL);
	if (jd->name != NULL)
		jd->options |= JackUseExactName;
	else
		/* if there's a no configured client name, we don't
		   care about the JackUseExactName option */
		jd->name = "Music Player Daemon";

332 333 334 335
	jd->server_name = config_get_block_string(param, "server_name", NULL);
	if (jd->server_name != NULL)
		jd->options |= JackServerName;

336 337
	if (!config_get_block_bool(param, "autostart", false))
		jd->options |= JackNoStartServer;
338

339 340 341 342 343 344 345 346 347 348
	/* configure the source ports */

	value = config_get_block_string(param, "source_ports", "left,right");
	jd->num_source_ports = parse_port_list(param->line, value,
					       jd->source_ports, error_r);
	if (jd->num_source_ports == 0)
		return NULL;

	/* configure the destination ports */

349 350 351 352 353 354 355 356 357
	value = config_get_block_string(param, "destination_ports", NULL);
	if (value == NULL) {
		/* compatibility with MPD < 0.16 */
		value = config_get_block_string(param, "ports", NULL);
		if (value != NULL)
			g_warning("deprecated option 'ports' in line %d",
				  param->line);
	}

358
	if (value != NULL) {
359 360 361 362
		jd->num_destination_ports =
			parse_port_list(param->line, value,
					jd->destination_ports, error_r);
		if (jd->num_destination_ports == 0)
363
			return NULL;
364
	} else {
365
		jd->num_destination_ports = 0;
366 367
	}

368 369 370 371 372 373 374
	if (jd->num_destination_ports > 0 &&
	    jd->num_destination_ports != jd->num_source_ports)
		g_warning("number of source ports (%u) mismatches the "
			  "number of destination ports (%u) in line %d",
			  jd->num_source_ports, jd->num_destination_ports,
			  param->line);

375 376
	jd->ringbuffer_size =
		config_get_block_unsigned(param, "ringbuffer_size", 32768);
377

378
	jack_set_error_function(mpd_jack_error);
379 380

#ifdef HAVE_JACK_SET_INFO_FUNCTION
381
	jack_set_info_function(mpd_jack_info);
382
#endif
383

384
	return &jd->base;
385 386
}

387
static void
388
mpd_jack_finish(struct audio_output *ao)
389
{
390
	struct jack_data *jd = (struct jack_data *)ao;
391

392 393 394
	for (unsigned i = 0; i < jd->num_source_ports; ++i)
		g_free(jd->source_ports[i]);

395
	for (unsigned i = 0; i < jd->num_destination_ports; ++i)
396
		g_free(jd->destination_ports[i]);
397

398
	ao_base_finish(&jd->base);
399 400 401 402
	g_free(jd);
}

static bool
403
mpd_jack_enable(struct audio_output *ao, GError **error_r)
404
{
405
	struct jack_data *jd = (struct jack_data *)ao;
406

407
	for (unsigned i = 0; i < jd->num_source_ports; ++i)
408 409 410 411 412 413
		jd->ringbuffer[i] = NULL;

	return mpd_jack_connect(jd, error_r);
}

static void
414
mpd_jack_disable(struct audio_output *ao)
415
{
416
	struct jack_data *jd = (struct jack_data *)ao;
417

418 419 420
	if (jd->client != NULL)
		mpd_jack_disconnect(jd);

421
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
422 423 424 425 426
		if (jd->ringbuffer[i] != NULL) {
			jack_ringbuffer_free(jd->ringbuffer[i]);
			jd->ringbuffer[i] = NULL;
		}
	}
427 428
}

429 430 431 432 433
/**
 * Stops the playback on the JACK connection.
 */
static void
mpd_jack_stop(struct jack_data *jd)
434
{
435
	assert(jd != NULL);
436

437 438
	if (jd->client == NULL)
		return;
439

440 441 442 443 444 445 446
	if (jd->shutdown)
		/* the connection has failed; close it */
		mpd_jack_disconnect(jd);
	else
		/* the connection is alive: just stop playback */
		jack_deactivate(jd->client);
}
447

448 449 450
static bool
mpd_jack_start(struct jack_data *jd, GError **error_r)
{
451
	const char *destination_ports[MAX_PORTS], **jports;
452
	const char *duplicate_port = NULL;
453
	unsigned num_destination_ports;
454

455
	assert(jd->client != NULL);
456
	assert(jd->audio_format.channels <= jd->num_source_ports);
457

458 459 460 461
	/* allocate the ring buffers on the first open(); these
	   persist until MPD exits.  It's too unsafe to delete them
	   because we can never know when mpd_jack_process() gets
	   called */
462
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
463 464 465
		if (jd->ringbuffer[i] == NULL)
			jd->ringbuffer[i] =
				jack_ringbuffer_create(jd->ringbuffer_size);
466

467 468 469 470 471
		/* clear the ring buffer to be sure that data from
		   previous playbacks are gone */
		jack_ringbuffer_reset(jd->ringbuffer[i]);
	}

472
	if ( jack_activate(jd->client) ) {
473
		g_set_error(error_r, jack_output_quark(), 0,
474
			    "cannot activate client");
475
		mpd_jack_stop(jd);
476
		return false;
477 478
	}

479
	if (jd->num_destination_ports == 0) {
480 481 482 483 484
		/* no output ports were configured - ask libjack for
		   defaults */
		jports = jack_get_ports(jd->client, NULL, NULL,
					JackPortIsPhysical | JackPortIsInput);
		if (jports == NULL) {
485
			g_set_error(error_r, jack_output_quark(), 0,
486
				    "no ports found");
487
			mpd_jack_stop(jd);
488
			return false;
489 490
		}

491 492 493 494 495 496 497 498 499 500 501 502
		assert(*jports != NULL);

		for (num_destination_ports = 0;
		     num_destination_ports < MAX_PORTS &&
			     jports[num_destination_ports] != NULL;
		     ++num_destination_ports) {
			g_debug("destination_port[%u] = '%s'\n",
				num_destination_ports,
				jports[num_destination_ports]);
			destination_ports[num_destination_ports] =
				jports[num_destination_ports];
		}
503 504 505
	} else {
		/* use the configured output ports */

506 507 508
		num_destination_ports = jd->num_destination_ports;
		memcpy(destination_ports, jd->destination_ports,
		       num_destination_ports * sizeof(*destination_ports));
509 510

		jports = NULL;
511 512
	}

513 514
	assert(num_destination_ports > 0);

515
	if (jd->audio_format.channels >= 2 && num_destination_ports == 1) {
516 517
		/* mix stereo signal on one speaker */

518 519 520 521 522 523 524 525 526 527 528 529
		while (num_destination_ports < jd->audio_format.channels)
			destination_ports[num_destination_ports++] =
				destination_ports[0];
	} else if (num_destination_ports > jd->audio_format.channels) {
		if (jd->audio_format.channels == 1 && num_destination_ports > 2) {
			/* mono input file: connect the one source
			   channel to the both destination channels */
			duplicate_port = destination_ports[1];
			num_destination_ports = 1;
		} else
			/* connect only as many ports as we need */
			num_destination_ports = jd->audio_format.channels;
530 531
	}

532
	assert(num_destination_ports <= jd->num_source_ports);
533

534
	for (unsigned i = 0; i < num_destination_ports; ++i) {
535 536 537
		int ret;

		ret = jack_connect(jd->client, jack_port_name(jd->ports[i]),
538
				   destination_ports[i]);
539
		if (ret != 0) {
540
			g_set_error(error_r, jack_output_quark(), 0,
541
				    "Not a valid JACK port: %s",
542
				    destination_ports[i]);
543 544 545 546

			if (jports != NULL)
				free(jports);

547
			mpd_jack_stop(jd);
548
			return false;
549
		}
550 551
	}

552
	if (duplicate_port != NULL) {
553 554 555 556 557
		/* mono input file: connect the one source channel to
		   the both destination channels */
		int ret;

		ret = jack_connect(jd->client, jack_port_name(jd->ports[0]),
558
				   duplicate_port);
559 560 561
		if (ret != 0) {
			g_set_error(error_r, jack_output_quark(), 0,
				    "Not a valid JACK port: %s",
562
				    duplicate_port);
563 564 565 566 567 568 569 570 571

			if (jports != NULL)
				free(jports);

			mpd_jack_stop(jd);
			return false;
		}
	}

572 573 574
	if (jports != NULL)
		free(jports);

575
	return true;
576 577
}

578
static bool
579 580
mpd_jack_open(struct audio_output *ao, struct audio_format *audio_format,
	      GError **error_r)
581
{
582
	struct jack_data *jd = (struct jack_data *)ao;
583

584
	assert(jd != NULL);
585

586 587
	jd->pause = false;

588 589 590
	if (jd->client != NULL && jd->shutdown)
		mpd_jack_disconnect(jd);

591
	if (jd->client == NULL && !mpd_jack_connect(jd, error_r))
592
		return false;
593

594
	set_audioformat(jd, audio_format);
595
	jd->audio_format = *audio_format;
596

597 598 599
	if (!mpd_jack_start(jd, error_r))
		return false;

600
	return true;
601 602
}

603
static void
604
mpd_jack_close(G_GNUC_UNUSED struct audio_output *ao)
605
{
606
	struct jack_data *jd = (struct jack_data *)ao;
607

608
	mpd_jack_stop(jd);
609 610
}

611 612 613 614 615 616 617 618 619 620 621
static inline jack_default_audio_sample_t
sample_16_to_jack(int16_t sample)
{
	return sample / (jack_default_audio_sample_t)(1 << (16 - 1));
}

static void
mpd_jack_write_samples_16(struct jack_data *jd, const int16_t *src,
			  unsigned num_samples)
{
	jack_default_audio_sample_t sample;
622
	unsigned i;
623 624

	while (num_samples-- > 0) {
625
		for (i = 0; i < jd->audio_format.channels; ++i) {
626
			sample = sample_16_to_jack(*src++);
627
			jack_ringbuffer_write(jd->ringbuffer[i], (void*)&sample,
628 629
					      sizeof(sample));
		}
630 631 632
	}
}

633 634 635 636 637 638 639 640 641 642 643
static inline jack_default_audio_sample_t
sample_24_to_jack(int32_t sample)
{
	return sample / (jack_default_audio_sample_t)(1 << (24 - 1));
}

static void
mpd_jack_write_samples_24(struct jack_data *jd, const int32_t *src,
			  unsigned num_samples)
{
	jack_default_audio_sample_t sample;
644
	unsigned i;
645 646

	while (num_samples-- > 0) {
647
		for (i = 0; i < jd->audio_format.channels; ++i) {
648
			sample = sample_24_to_jack(*src++);
649
			jack_ringbuffer_write(jd->ringbuffer[i], (void*)&sample,
650 651
					      sizeof(sample));
		}
652 653 654
	}
}

655 656 657 658
static void
mpd_jack_write_samples(struct jack_data *jd, const void *src,
		       unsigned num_samples)
{
659 660
	switch (jd->audio_format.format) {
	case SAMPLE_FORMAT_S16:
661 662 663 664
		mpd_jack_write_samples_16(jd, (const int16_t*)src,
					  num_samples);
		break;

665
	case SAMPLE_FORMAT_S24_P32:
666 667 668 669
		mpd_jack_write_samples_24(jd, (const int32_t*)src,
					  num_samples);
		break;

670 671 672 673 674
	default:
		assert(false);
	}
}

675
static size_t
676 677
mpd_jack_play(struct audio_output *ao, const void *chunk, size_t size,
	      GError **error_r)
678
{
679
	struct jack_data *jd = (struct jack_data *)ao;
680
	const size_t frame_size = audio_format_frame_size(&jd->audio_format);
681
	size_t space = 0, space1;
682

683 684
	jd->pause = false;

685
	assert(size % frame_size == 0);
686
	size /= frame_size;
687

688 689
	while (true) {
		if (jd->shutdown) {
690
			g_set_error(error_r, jack_output_quark(), 0,
691 692 693 694 695
				    "Refusing to play, because "
				    "there is no client thread");
			return 0;
		}

Max Kellermann's avatar
Max Kellermann committed
696
		space = jack_ringbuffer_write_space(jd->ringbuffer[0]);
697 698 699 700 701 702
		for (unsigned i = 1; i < jd->audio_format.channels; ++i) {
			space1 = jack_ringbuffer_write_space(jd->ringbuffer[i]);
			if (space > space1)
				/* send data symmetrically */
				space = space1;
		}
703

704
		if (space >= jack_sample_size)
705
			break;
706

707 708 709
		/* XXX do something more intelligent to
		   synchronize */
		g_usleep(1000);
710
	}
Max Kellermann's avatar
Max Kellermann committed
711

712
	space /= jack_sample_size;
713 714 715
	if (space < size)
		size = space;

716
	mpd_jack_write_samples(jd, chunk, size);
717
	return size * frame_size;
718 719
}

720
static bool
721
mpd_jack_pause(struct audio_output *ao)
722
{
723
	struct jack_data *jd = (struct jack_data *)ao;
724 725 726 727 728 729 730 731 732 733 734 735 736

	if (jd->shutdown)
		return false;

	jd->pause = true;

	/* due to a MPD API limitation, we have to sleep a little bit
	   here, to avoid hogging the CPU */
	g_usleep(50000);

	return true;
}

737
const struct audio_output_plugin jack_output_plugin = {
738
	.name = "jack",
739 740 741
	.test_default_device = mpd_jack_test_default_device,
	.init = mpd_jack_init,
	.finish = mpd_jack_finish,
742 743
	.enable = mpd_jack_enable,
	.disable = mpd_jack_disable,
744 745
	.open = mpd_jack_open,
	.play = mpd_jack_play,
746
	.pause = mpd_jack_pause,
747
	.close = mpd_jack_close,
748
};