JackOutputPlugin.cxx 17.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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
#include "config/ConfigError.hxx"
24 25
#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
	AudioOutput base;
46

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 83 84
	JackOutput()
		:base(jack_output_plugin) {}

85
	bool Initialize(const config_param &param, Error &error_r) {
86
		return base.Configure(param, error_r);
87
	}
88
};
89

90
static constexpr Domain jack_output_domain("jack_output");
91

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

107
	assert(min % jack_sample_size == 0);
108

109
	return min / jack_sample_size;
110 111
}

112 113
static int
mpd_jack_process(jack_nframes_t nframes, void *arg)
114
{
115
	JackOutput *jd = (JackOutput *) arg;
116

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

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

128 129
		/* generate silence while MPD is paused */

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

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

		return 0;
	}

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

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

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

160
		for (jack_nframes_t f = available; f < nframes; ++f)
161
			/* ringbuffer underrun, fill with silence */
162
			out[f] = 0.0;
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) {
169 170 171 172
		jack_default_audio_sample_t *out =
			(jack_default_audio_sample_t *)
			jack_port_get_buffer(jd->ports[i], nframes);
		if (out == nullptr)
173 174 175 176 177
			/* workaround for libjack1 bug: if the server
			   connection fails, the process callback is
			   invoked anyway, but unable to get a
			   buffer */
			continue;
178 179 180 181 182

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

183 184 185
	return 0;
}

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

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

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

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

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

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

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

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

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

245
	assert(jd != nullptr);
246 247 248

	jd->shutdown = false;

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

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

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

	return true;
}

static bool
mpd_jack_test_default_device(void)
{
	return true;
}

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

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

		dest[n] = list[n];
	}

	g_free(list);

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

	return n;
}

311
static AudioOutput *
312
mpd_jack_init(const config_param &param, Error &error)
313
{
314
	JackOutput *jd = new JackOutput();
315

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

321
	const char *value;
322

323 324
	jd->options = JackNullOption;

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

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

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

340 341
	/* configure the source ports */

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

	/* configure the destination ports */

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

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

370 371
	if (jd->num_destination_ports > 0 &&
	    jd->num_destination_ports != jd->num_source_ports)
372 373 374 375 376
		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);
377

378
	jd->ringbuffer_size = param.GetBlockValue("ringbuffer_size", 32768u);
379

380
	jack_set_error_function(mpd_jack_error);
381 382

#ifdef HAVE_JACK_SET_INFO_FUNCTION
383
	jack_set_info_function(mpd_jack_info);
384
#endif
385

386
	return &jd->base;
387 388
}

389
static void
390
mpd_jack_finish(AudioOutput *ao)
391
{
392
	JackOutput *jd = (JackOutput *)ao;
393

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

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

400
	delete jd;
401 402 403
}

static bool
404
mpd_jack_enable(AudioOutput *ao, Error &error)
405
{
406
	JackOutput *jd = (JackOutput *)ao;
407

408
	for (unsigned i = 0; i < jd->num_source_ports; ++i)
409
		jd->ringbuffer[i] = nullptr;
410

411
	return mpd_jack_connect(jd, error);
412 413 414
}

static void
415
mpd_jack_disable(AudioOutput *ao)
416
{
417
	JackOutput *jd = (JackOutput *)ao;
418

419
	if (jd->client != nullptr)
420 421
		mpd_jack_disconnect(jd);

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

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

438
	if (jd->client == nullptr)
439
		return;
440

441 442 443 444 445 446 447
	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);
}
448

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

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

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

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

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

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

490
		assert(*jports != nullptr);
491 492 493

		for (num_destination_ports = 0;
		     num_destination_ports < MAX_PORTS &&
494
			     jports[num_destination_ports] != nullptr;
495
		     ++num_destination_ports) {
496 497 498 499
			FormatDebug(jack_output_domain,
				    "destination_port[%u] = '%s'\n",
				    num_destination_ports,
				    jports[num_destination_ports]);
500 501 502
			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 = nullptr;
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 541 542
			error.Format(jack_output_domain,
				     "Not a valid JACK port: %s",
				     destination_ports[i]);
543

544
			if (jports != nullptr)
545 546
				free(jports);

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

552
	if (duplicate_port != nullptr) {
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
		if (ret != 0) {
560 561 562
			error.Format(jack_output_domain,
				     "Not a valid JACK port: %s",
				     duplicate_port);
563

564
			if (jports != nullptr)
565 566 567 568 569 570 571
				free(jports);

			mpd_jack_stop(jd);
			return false;
		}
	}

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

575
	return true;
576 577
}

578
static bool
579
mpd_jack_open(AudioOutput *ao, AudioFormat &audio_format,
580
	      Error &error)
581
{
582
	JackOutput *jd = (JackOutput *)ao;
583

584
	assert(jd != nullptr);
585

586 587
	jd->pause = false;

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

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

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

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

600
	return true;
601 602
}

603
static void
604
mpd_jack_close(gcc_unused AudioOutput *ao)
605
{
606
	JackOutput *jd = (JackOutput *)ao;
607

608
	mpd_jack_stop(jd);
609 610
}

611
static unsigned
612
mpd_jack_delay(AudioOutput *ao)
613
{
614
	JackOutput *jd = (JackOutput *)ao;
615 616 617 618 619 620

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

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

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

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

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

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

677
	case SampleFormat::S24_P32:
678 679 680 681
		mpd_jack_write_samples_24(jd, (const int32_t*)src,
					  num_samples);
		break;

682 683
	default:
		assert(false);
684
		gcc_unreachable();
685 686 687
	}
}

688
static size_t
689
mpd_jack_play(AudioOutput *ao, const void *chunk, size_t size,
690
	      Error &error)
691
{
692
	JackOutput *jd = (JackOutput *)ao;
693
	const size_t frame_size = jd->audio_format.GetFrameSize();
694
	size_t space = 0, space1;
695

696 697
	jd->pause = false;

698
	assert(size % frame_size == 0);
699
	size /= frame_size;
700

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

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

717
		if (space >= jack_sample_size)
718
			break;
719

720 721 722
		/* XXX do something more intelligent to
		   synchronize */
		g_usleep(1000);
723
	}
Max Kellermann's avatar
Max Kellermann committed
724

725
	space /= jack_sample_size;
726 727 728
	if (space < size)
		size = space;

729
	mpd_jack_write_samples(jd, chunk, size);
730
	return size * frame_size;
731 732
}

733
static bool
734
mpd_jack_pause(AudioOutput *ao)
735
{
736
	JackOutput *jd = (JackOutput *)ao;
737 738 739 740 741 742 743 744 745

	if (jd->shutdown)
		return false;

	jd->pause = true;

	return true;
}

746
const struct AudioOutputPlugin jack_output_plugin = {
747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
	"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,
762
};