JackOutputPlugin.cxx 17.3 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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 "JackOutputPlugin.hxx"
22
#include "OutputAPI.hxx"
23 24 25
#include "ConfigError.hxx"
#include "util/Error.hxx"
#include "util/Domain.hxx"
26
#include "Log.hxx"
27

28 29
#include <assert.h>

30
#include <glib.h>
31 32 33 34
#include <jack/jack.h>
#include <jack/types.h>
#include <jack/ringbuffer.h>

35
#include <stdlib.h>
Max Kellermann's avatar
Max Kellermann committed
36
#include <string.h>
37

38 39 40 41
enum {
	MAX_PORTS = 16,
};

42
static const size_t jack_sample_size = sizeof(jack_default_audio_sample_t);
43

44
struct JackOutput {
45 46
	struct audio_output base;

47 48 49 50 51
	/**
	 * libjack options passed to jack_client_open().
	 */
	jack_options_t options;

52
	const char *name;
53

54 55
	const char *server_name;

56
	/* configuration */
57

58 59 60
	char *source_ports[MAX_PORTS];
	unsigned num_source_ports;

61 62
	char *destination_ports[MAX_PORTS];
	unsigned num_destination_ports;
63

64
	size_t ringbuffer_size;
65

66
	/* the current audio format */
67
	AudioFormat audio_format;
68

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

74
	bool shutdown;
75 76 77 78 79 80

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

82
	bool Initialize(const config_param &param, Error &error_r) {
83 84 85 86 87 88 89
		return ao_base_init(&base, &jack_output_plugin, param,
				    error_r);
	}

	void Deinitialize() {
		ao_base_finish(&base);
	}
90
};
91

92
static constexpr Domain jack_output_domain("jack_output");
93

94 95 96 97 98
/**
 * Determine the number of frames guaranteed to be available on all
 * channels.
 */
static jack_nframes_t
99
mpd_jack_available(const JackOutput *jd)
100 101 102 103 104 105 106 107 108
{
	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
	JackOutput *jd = (JackOutput *) arg;
118

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

122
	if (jd->pause) {
123 124 125 126 127
		/* 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],
128
						     available * jack_sample_size);
129

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

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

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

		return 0;
	}

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

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

159
		jack_ringbuffer_read(jd->ringbuffer[i],
160
				     (char *)out, available * jack_sample_size);
161

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

167 168 169 170
	/* generate silence for the unused source ports */

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

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

185 186 187
	return 0;
}

188 189
static void
mpd_jack_shutdown(void *arg)
190
{
191
	JackOutput *jd = (JackOutput *) arg;
192
	jd->shutdown = true;
193 194
}

195
static void
196
set_audioformat(JackOutput *jd, AudioFormat &audio_format)
197
{
198
	audio_format.sample_rate = jack_get_sample_rate(jd->client);
199

200
	if (jd->num_source_ports == 1)
201 202 203
		audio_format.channels = 1;
	else if (audio_format.channels > jd->num_source_ports)
		audio_format.channels = 2;
204

205 206 207
	if (audio_format.format != SampleFormat::S16 &&
	    audio_format.format != SampleFormat::S24_P32)
		audio_format.format = SampleFormat::S24_P32;
208 209
}

210 211
static void
mpd_jack_error(const char *msg)
212
{
213
	LogError(jack_output_domain, msg);
214 215
}

216
#ifdef HAVE_JACK_SET_INFO_FUNCTION
217 218 219
static void
mpd_jack_info(const char *msg)
{
220
	LogDefault(jack_output_domain, msg);
221
}
222
#endif
223

224 225 226 227
/**
 * Disconnect the JACK client.
 */
static void
228
mpd_jack_disconnect(JackOutput *jd)
229
{
230 231
	assert(jd != nullptr);
	assert(jd->client != nullptr);
232 233 234

	jack_deactivate(jd->client);
	jack_client_close(jd->client);
235
	jd->client = nullptr;
236 237 238 239 240 241 242
}

/**
 * Connect the JACK client and performs some basic setup
 * (e.g. register callbacks).
 */
static bool
243
mpd_jack_connect(JackOutput *jd, Error &error)
244
{
245 246
	jack_status_t status;

247
	assert(jd != nullptr);
248 249 250

	jd->shutdown = false;

251 252
	jd->client = jack_client_open(jd->name, jd->options, &status,
				      jd->server_name);
253
	if (jd->client == nullptr) {
254 255 256
		error.Format(jack_output_domain, status,
			     "Failed to connect to JACK server, status=%d",
			     status);
257 258 259 260 261 262
		return false;
	}

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

263 264 265
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
		jd->ports[i] = jack_port_register(jd->client,
						  jd->source_ports[i],
266 267
						  JACK_DEFAULT_AUDIO_TYPE,
						  JackPortIsOutput, 0);
268
		if (jd->ports[i] == nullptr) {
269 270 271
			error.Format(jack_output_domain,
				     "Cannot register output port \"%s\"",
				     jd->source_ports[i]);
272 273 274 275 276 277 278 279 280 281 282 283 284 285
			mpd_jack_disconnect(jd);
			return false;
		}
	}

	return true;
}

static bool
mpd_jack_test_default_device(void)
{
	return true;
}

286
static unsigned
287
parse_port_list(const char *source, char **dest, Error &error)
288 289 290 291
{
	char **list = g_strsplit(source, ",", 0);
	unsigned n = 0;

292
	for (n = 0; list[n] != nullptr; ++n) {
293
		if (n >= MAX_PORTS) {
294 295
			error.Set(config_domain,
				  "too many port names");
296 297 298 299 300 301 302 303 304
			return 0;
		}

		dest[n] = list[n];
	}

	g_free(list);

	if (n == 0) {
305
		error.Format(config_domain,
306
			     "at least one port name expected");
307 308 309 310 311 312
		return 0;
	}

	return n;
}

313
static struct audio_output *
314
mpd_jack_init(const config_param &param, Error &error)
315
{
316
	JackOutput *jd = new JackOutput();
317

318
	if (!jd->Initialize(param, error)) {
319 320
		delete jd;
		return nullptr;
321 322
	}

323
	const char *value;
324

325 326
	jd->options = JackNullOption;

327
	jd->name = param.GetBlockValue("client_name", nullptr);
328 329
	if (jd->name != nullptr)
		jd->options = jack_options_t(jd->options | JackUseExactName);
330 331 332 333 334
	else
		/* if there's a no configured client name, we don't
		   care about the JackUseExactName option */
		jd->name = "Music Player Daemon";

335
	jd->server_name = param.GetBlockValue("server_name", nullptr);
336 337
	if (jd->server_name != nullptr)
		jd->options = jack_options_t(jd->options | JackServerName);
338

339
	if (!param.GetBlockValue("autostart", false))
340
		jd->options = jack_options_t(jd->options | JackNoStartServer);
341

342 343
	/* configure the source ports */

344
	value = param.GetBlockValue("source_ports", "left,right");
345
	jd->num_source_ports = parse_port_list(value,
346
					       jd->source_ports, error);
347
	if (jd->num_source_ports == 0)
348
		return nullptr;
349 350 351

	/* configure the destination ports */

352
	value = param.GetBlockValue("destination_ports", nullptr);
353
	if (value == nullptr) {
354
		/* compatibility with MPD < 0.16 */
355
		value = param.GetBlockValue("ports", nullptr);
356
		if (value != nullptr)
357 358 359
			FormatWarning(jack_output_domain,
				      "deprecated option 'ports' in line %d",
				      param.line);
360 361
	}

362
	if (value != nullptr) {
363
		jd->num_destination_ports =
364
			parse_port_list(value,
365
					jd->destination_ports, error);
366
		if (jd->num_destination_ports == 0)
367
			return nullptr;
368
	} else {
369
		jd->num_destination_ports = 0;
370 371
	}

372 373
	if (jd->num_destination_ports > 0 &&
	    jd->num_destination_ports != jd->num_source_ports)
374 375 376 377 378
		FormatWarning(jack_output_domain,
			      "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);
379

380
	jd->ringbuffer_size = param.GetBlockValue("ringbuffer_size", 32768u);
381

382
	jack_set_error_function(mpd_jack_error);
383 384

#ifdef HAVE_JACK_SET_INFO_FUNCTION
385
	jack_set_info_function(mpd_jack_info);
386
#endif
387

388
	return &jd->base;
389 390
}

391
static void
392
mpd_jack_finish(struct audio_output *ao)
393
{
394
	JackOutput *jd = (JackOutput *)ao;
395

396 397 398
	for (unsigned i = 0; i < jd->num_source_ports; ++i)
		g_free(jd->source_ports[i]);

399
	for (unsigned i = 0; i < jd->num_destination_ports; ++i)
400
		g_free(jd->destination_ports[i]);
401

402 403
	jd->Deinitialize();
	delete jd;
404 405 406
}

static bool
407
mpd_jack_enable(struct audio_output *ao, Error &error)
408
{
409
	JackOutput *jd = (JackOutput *)ao;
410

411
	for (unsigned i = 0; i < jd->num_source_ports; ++i)
412
		jd->ringbuffer[i] = nullptr;
413

414
	return mpd_jack_connect(jd, error);
415 416 417
}

static void
418
mpd_jack_disable(struct audio_output *ao)
419
{
420
	JackOutput *jd = (JackOutput *)ao;
421

422
	if (jd->client != nullptr)
423 424
		mpd_jack_disconnect(jd);

425
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
426
		if (jd->ringbuffer[i] != nullptr) {
427
			jack_ringbuffer_free(jd->ringbuffer[i]);
428
			jd->ringbuffer[i] = nullptr;
429 430
		}
	}
431 432
}

433 434 435 436
/**
 * Stops the playback on the JACK connection.
 */
static void
437
mpd_jack_stop(JackOutput *jd)
438
{
439
	assert(jd != nullptr);
440

441
	if (jd->client == nullptr)
442
		return;
443

444 445 446 447 448 449 450
	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);
}
451

452
static bool
453
mpd_jack_start(JackOutput *jd, Error &error)
454
{
455
	const char *destination_ports[MAX_PORTS], **jports;
456
	const char *duplicate_port = nullptr;
457
	unsigned num_destination_ports;
458

459
	assert(jd->client != nullptr);
460
	assert(jd->audio_format.channels <= jd->num_source_ports);
461

462 463 464 465
	/* 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 */
466
	for (unsigned i = 0; i < jd->num_source_ports; ++i) {
467
		if (jd->ringbuffer[i] == nullptr)
468 469
			jd->ringbuffer[i] =
				jack_ringbuffer_create(jd->ringbuffer_size);
470

471 472 473 474 475
		/* clear the ring buffer to be sure that data from
		   previous playbacks are gone */
		jack_ringbuffer_reset(jd->ringbuffer[i]);
	}

476
	if ( jack_activate(jd->client) ) {
477
		error.Set(jack_output_domain, "cannot activate client");
478
		mpd_jack_stop(jd);
479
		return false;
480 481
	}

482
	if (jd->num_destination_ports == 0) {
483 484
		/* no output ports were configured - ask libjack for
		   defaults */
485
		jports = jack_get_ports(jd->client, nullptr, nullptr,
486
					JackPortIsPhysical | JackPortIsInput);
487
		if (jports == nullptr) {
488
			error.Set(jack_output_domain, "no ports found");
489
			mpd_jack_stop(jd);
490
			return false;
491 492
		}

493
		assert(*jports != nullptr);
494 495 496

		for (num_destination_ports = 0;
		     num_destination_ports < MAX_PORTS &&
497
			     jports[num_destination_ports] != nullptr;
498
		     ++num_destination_ports) {
499 500 501 502
			FormatDebug(jack_output_domain,
				    "destination_port[%u] = '%s'\n",
				    num_destination_ports,
				    jports[num_destination_ports]);
503 504 505
			destination_ports[num_destination_ports] =
				jports[num_destination_ports];
		}
506 507 508
	} else {
		/* use the configured output ports */

509 510 511
		num_destination_ports = jd->num_destination_ports;
		memcpy(destination_ports, jd->destination_ports,
		       num_destination_ports * sizeof(*destination_ports));
512

513
		jports = nullptr;
514 515
	}

516 517
	assert(num_destination_ports > 0);

518
	if (jd->audio_format.channels >= 2 && num_destination_ports == 1) {
519 520
		/* mix stereo signal on one speaker */

521 522 523 524 525 526 527 528 529 530 531 532
		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;
533 534
	}

535
	assert(num_destination_ports <= jd->num_source_ports);
536

537
	for (unsigned i = 0; i < num_destination_ports; ++i) {
538 539 540
		int ret;

		ret = jack_connect(jd->client, jack_port_name(jd->ports[i]),
541
				   destination_ports[i]);
542
		if (ret != 0) {
543 544 545
			error.Format(jack_output_domain,
				     "Not a valid JACK port: %s",
				     destination_ports[i]);
546

547
			if (jports != nullptr)
548 549
				free(jports);

550
			mpd_jack_stop(jd);
551
			return false;
552
		}
553 554
	}

555
	if (duplicate_port != nullptr) {
556 557 558 559 560
		/* 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]),
561
				   duplicate_port);
562
		if (ret != 0) {
563 564 565
			error.Format(jack_output_domain,
				     "Not a valid JACK port: %s",
				     duplicate_port);
566

567
			if (jports != nullptr)
568 569 570 571 572 573 574
				free(jports);

			mpd_jack_stop(jd);
			return false;
		}
	}

575
	if (jports != nullptr)
576 577
		free(jports);

578
	return true;
579 580
}

581
static bool
582
mpd_jack_open(struct audio_output *ao, AudioFormat &audio_format,
583
	      Error &error)
584
{
585
	JackOutput *jd = (JackOutput *)ao;
586

587
	assert(jd != nullptr);
588

589 590
	jd->pause = false;

591
	if (jd->client != nullptr && jd->shutdown)
592 593
		mpd_jack_disconnect(jd);

594
	if (jd->client == nullptr && !mpd_jack_connect(jd, error))
595
		return false;
596

597
	set_audioformat(jd, audio_format);
598
	jd->audio_format = audio_format;
599

600
	if (!mpd_jack_start(jd, error))
601 602
		return false;

603
	return true;
604 605
}

606
static void
607
mpd_jack_close(gcc_unused struct audio_output *ao)
608
{
609
	JackOutput *jd = (JackOutput *)ao;
610

611
	mpd_jack_stop(jd);
612 613
}

614 615 616
static unsigned
mpd_jack_delay(struct audio_output *ao)
{
617
	JackOutput *jd = (JackOutput *)ao;
618 619 620 621 622 623

	return jd->base.pause && jd->pause && !jd->shutdown
		? 1000
		: 0;
}

624 625 626 627 628 629 630
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
631
mpd_jack_write_samples_16(JackOutput *jd, const int16_t *src,
632 633 634
			  unsigned num_samples)
{
	jack_default_audio_sample_t sample;
635
	unsigned i;
636 637

	while (num_samples-- > 0) {
638
		for (i = 0; i < jd->audio_format.channels; ++i) {
639
			sample = sample_16_to_jack(*src++);
640 641
			jack_ringbuffer_write(jd->ringbuffer[i],
					      (const char *)&sample,
642 643
					      sizeof(sample));
		}
644 645 646
	}
}

647 648 649 650 651 652 653
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
654
mpd_jack_write_samples_24(JackOutput *jd, const int32_t *src,
655 656 657
			  unsigned num_samples)
{
	jack_default_audio_sample_t sample;
658
	unsigned i;
659 660

	while (num_samples-- > 0) {
661
		for (i = 0; i < jd->audio_format.channels; ++i) {
662
			sample = sample_24_to_jack(*src++);
663 664
			jack_ringbuffer_write(jd->ringbuffer[i],
					      (const char *)&sample,
665 666
					      sizeof(sample));
		}
667 668 669
	}
}

670
static void
671
mpd_jack_write_samples(JackOutput *jd, const void *src,
672 673
		       unsigned num_samples)
{
674
	switch (jd->audio_format.format) {
675
	case SampleFormat::S16:
676 677 678 679
		mpd_jack_write_samples_16(jd, (const int16_t*)src,
					  num_samples);
		break;

680
	case SampleFormat::S24_P32:
681 682 683 684
		mpd_jack_write_samples_24(jd, (const int32_t*)src,
					  num_samples);
		break;

685 686
	default:
		assert(false);
687
		gcc_unreachable();
688 689 690
	}
}

691
static size_t
692
mpd_jack_play(struct audio_output *ao, const void *chunk, size_t size,
693
	      Error &error)
694
{
695
	JackOutput *jd = (JackOutput *)ao;
696
	const size_t frame_size = jd->audio_format.GetFrameSize();
697
	size_t space = 0, space1;
698

699 700
	jd->pause = false;

701
	assert(size % frame_size == 0);
702
	size /= frame_size;
703

704 705
	while (true) {
		if (jd->shutdown) {
706 707 708
			error.Set(jack_output_domain,
				  "Refusing to play, because "
				  "there is no client thread");
709 710 711
			return 0;
		}

Max Kellermann's avatar
Max Kellermann committed
712
		space = jack_ringbuffer_write_space(jd->ringbuffer[0]);
713 714 715 716 717 718
		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;
		}
719

720
		if (space >= jack_sample_size)
721
			break;
722

723 724 725
		/* XXX do something more intelligent to
		   synchronize */
		g_usleep(1000);
726
	}
Max Kellermann's avatar
Max Kellermann committed
727

728
	space /= jack_sample_size;
729 730 731
	if (space < size)
		size = space;

732
	mpd_jack_write_samples(jd, chunk, size);
733
	return size * frame_size;
734 735
}

736
static bool
737
mpd_jack_pause(struct audio_output *ao)
738
{
739
	JackOutput *jd = (JackOutput *)ao;
740 741 742 743 744 745 746 747 748

	if (jd->shutdown)
		return false;

	jd->pause = true;

	return true;
}

749
const struct audio_output_plugin jack_output_plugin = {
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764
	"jack",
	mpd_jack_test_default_device,
	mpd_jack_init,
	mpd_jack_finish,
	mpd_jack_enable,
	mpd_jack_disable,
	mpd_jack_open,
	mpd_jack_close,
	mpd_jack_delay,
	nullptr,
	mpd_jack_play,
	nullptr,
	nullptr,
	mpd_jack_pause,
	nullptr,
765
};