JackOutputPlugin.cxx 15.3 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 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/Domain.hxx"
24
#include "util/ScopeExit.hxx"
25
#include "util/ConstBuffer.hxx"
26
#include "util/IterableSplitString.hxx"
27
#include "util/RuntimeError.hxx"
28
#include "util/Domain.hxx"
29
#include "Log.hxx"
30

31 32
#include <assert.h>

33 34 35 36
#include <jack/jack.h>
#include <jack/types.h>
#include <jack/ringbuffer.h>

37
#include <unistd.h> /* for usleep() */
38 39
#include <stdlib.h>

40
static constexpr unsigned MAX_PORTS = 16;
41

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

44
struct JackOutput final : AudioOutput {
45 46 47
	/**
	 * libjack options passed to jack_client_open().
	 */
48
	jack_options_t options = JackNullOption;
49

50
	const char *name;
51

52
	const char *const server_name;
53

54
	/* configuration */
55

56
	std::string source_ports[MAX_PORTS];
57 58
	unsigned num_source_ports;

59
	std::string destination_ports[MAX_PORTS];
60
	unsigned num_destination_ports;
61

62
	size_t ringbuffer_size;
63

64
	/* the current audio format */
65
	AudioFormat audio_format;
66

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

72
	bool shutdown;
73 74 75 76 77 78

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

80
	explicit JackOutput(const ConfigBlock &block);
81

82 83 84 85 86 87 88
	/**
	 * Connect the JACK client and performs some basic setup
	 * (e.g. register callbacks).
	 *
	 * Throws #std::runtime_error on error.
	 */
	void Connect();
89 90 91 92

	/**
	 * Disconnect the JACK client.
	 */
93
	void Disconnect() noexcept;
94

95
	void Shutdown() noexcept {
96
		shutdown = true;
97
	}
98

99 100 101 102
	/**
	 * Throws #std::runtime_error on error.
	 */
	void Start();
103
	void Stop() noexcept;
104 105 106 107 108 109

	/**
	 * Determine the number of frames guaranteed to be available
	 * on all channels.
	 */
	gcc_pure
110
	jack_nframes_t GetAvailable() const noexcept;
111 112 113

	void Process(jack_nframes_t nframes);

114 115 116
	/**
	 * @return the number of frames that were written
	 */
117
	size_t WriteSamples(const float *src, size_t n_frames);
118

119 120 121 122 123 124 125 126 127 128 129
	/* virtual methods from class AudioOutput */

	void Enable() override;
	void Disable() noexcept override;

	void Open(AudioFormat &new_audio_format) override;

	void Close() noexcept override {
		Stop();
	}

130
	std::chrono::steady_clock::duration Delay() const noexcept override {
131
		return pause && !shutdown
132 133
			? std::chrono::seconds(1)
			: std::chrono::steady_clock::duration::zero();
134 135
	}

136
	size_t Play(const void *chunk, size_t size) override;
137

138
	bool Pause() override;
139
};
140

141
static constexpr Domain jack_output_domain("jack_output");
142

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
/**
 * Throws #std::runtime_error on error.
 */
static unsigned
parse_port_list(const char *source, std::string dest[])
{
	unsigned n = 0;
	for (auto i : IterableSplitString(source, ',')) {
		if (n >= MAX_PORTS)
			throw std::runtime_error("too many port names");

		dest[n++] = std::string(i.data, i.size);
	}

	if (n == 0)
		throw std::runtime_error("at least one port name expected");

	return n;
}

JackOutput::JackOutput(const ConfigBlock &block)
164
	:AudioOutput(FLAG_ENABLE_DISABLE|FLAG_PAUSE),
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
	 name(block.GetBlockValue("client_name", nullptr)),
	 server_name(block.GetBlockValue("server_name", nullptr))
{
	if (name != nullptr)
		options = jack_options_t(options | JackUseExactName);
	else
		/* if there's a no configured client name, we don't
		   care about the JackUseExactName option */
		name = "Music Player Daemon";

	if (server_name != nullptr)
		options = jack_options_t(options | JackServerName);

	if (!block.GetBlockValue("autostart", false))
		options = jack_options_t(options | JackNoStartServer);

	/* configure the source ports */

	const char *value = block.GetBlockValue("source_ports", "left,right");
	num_source_ports = parse_port_list(value, source_ports);

	/* configure the destination ports */

	value = block.GetBlockValue("destination_ports", nullptr);
	if (value == nullptr) {
		/* compatibility with MPD < 0.16 */
		value = block.GetBlockValue("ports", nullptr);
		if (value != nullptr)
			FormatWarning(jack_output_domain,
				      "deprecated option 'ports' in line %d",
				      block.line);
	}

	if (value != nullptr) {
		num_destination_ports =
			parse_port_list(value, destination_ports);
	} else {
		num_destination_ports = 0;
	}

	if (num_destination_ports > 0 &&
	    num_destination_ports != num_source_ports)
		FormatWarning(jack_output_domain,
			      "number of source ports (%u) mismatches the "
			      "number of destination ports (%u) in line %d",
			      num_source_ports, num_destination_ports,
			      block.line);

213
	ringbuffer_size = block.GetPositiveValue("ringbuffer_size", 32768u);
214 215
}

216
inline jack_nframes_t
217
JackOutput::GetAvailable() const noexcept
218
{
219
	size_t min = jack_ringbuffer_read_space(ringbuffer[0]);
220

221 222
	for (unsigned i = 1; i < audio_format.channels; ++i) {
		size_t current = jack_ringbuffer_read_space(ringbuffer[i]);
223 224 225 226
		if (current < min)
			min = current;
	}

227
	assert(min % jack_sample_size == 0);
228

229
	return min / jack_sample_size;
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
/**
 * Call jack_ringbuffer_read_advance() on all buffers in the list.
 */
static void
MultiReadAdvance(ConstBuffer<jack_ringbuffer_t *> buffers,
		 size_t size)
{
	for (auto *i : buffers)
		jack_ringbuffer_read_advance(i, size);
}

/**
 * Write a specific amount of "silence" to the given port.
 */
static void
WriteSilence(jack_port_t &port, jack_nframes_t nframes)
{
	jack_default_audio_sample_t *out =
		(jack_default_audio_sample_t *)
		jack_port_get_buffer(&port, nframes);
	if (out == nullptr)
		/* workaround for libjack1 bug: if the server
		   connection fails, the process callback is invoked
		   anyway, but unable to get a buffer */
			return;

	std::fill_n(out, nframes, 0.0);
}

/**
 * Write a specific amount of "silence" to all ports in the list.
 */
static void
MultiWriteSilence(ConstBuffer<jack_port_t *> ports, jack_nframes_t nframes)
{
	for (auto *i : ports)
		WriteSilence(*i, nframes);
}

/**
 * Copy data from the buffer to the port.  If the buffer underruns,
 * fill with silence.
 */
static void
Copy(jack_port_t &dest, jack_nframes_t nframes,
     jack_ringbuffer_t &src, jack_nframes_t available)
{
	jack_default_audio_sample_t *out =
		(jack_default_audio_sample_t *)
		jack_port_get_buffer(&dest, nframes);
	if (out == nullptr)
		/* workaround for libjack1 bug: if the server
		   connection fails, the process callback is
		   invoked anyway, but unable to get a
		   buffer */
		return;

	/* copy from buffer to port */
	jack_ringbuffer_read(&src, (char *)out,
			     available * jack_sample_size);

	/* ringbuffer underrun, fill with silence */
	std::fill(out + available, out + nframes, 0.0);
}

297 298
inline void
JackOutput::Process(jack_nframes_t nframes)
299
{
Max Kellermann's avatar
Max Kellermann committed
300
	if (nframes <= 0)
301
		return;
302

303
	jack_nframes_t available = GetAvailable();
304

305 306
	const unsigned n_channels = audio_format.channels;

307
	if (pause) {
308 309
		/* empty the ring buffers */

310 311
		MultiReadAdvance({ringbuffer, n_channels},
				 available * jack_sample_size);
312

313 314
		/* generate silence while MPD is paused */

315
		MultiWriteSilence({ports, n_channels}, nframes);
316

317
		return;
318 319
	}

320 321
	if (available > nframes)
		available = nframes;
322

323 324
	for (unsigned i = 0; i < n_channels; ++i)
		Copy(*ports[i], nframes, *ringbuffer[i], available);
325

326 327
	/* generate silence for the unused source ports */

328 329
	MultiWriteSilence({ports + n_channels, num_source_ports - n_channels},
			  nframes);
330 331 332 333 334 335
}

static int
mpd_jack_process(jack_nframes_t nframes, void *arg)
{
	JackOutput &jo = *(JackOutput *) arg;
336

337
	jo.Process(nframes);
338 339 340
	return 0;
}

341 342
static void
mpd_jack_shutdown(void *arg)
343
{
344 345 346
	JackOutput &jo = *(JackOutput *) arg;

	jo.Shutdown();
347 348
}

349
static void
350
set_audioformat(JackOutput *jd, AudioFormat &audio_format)
351
{
352
	audio_format.sample_rate = jack_get_sample_rate(jd->client);
353

354
	if (jd->num_source_ports == 1)
355 356 357
		audio_format.channels = 1;
	else if (audio_format.channels > jd->num_source_ports)
		audio_format.channels = 2;
358

359 360 361 362
	/* JACK uses 32 bit float in the range [-1 .. 1] - just like
	   MPD's SampleFormat::FLOAT*/
	static_assert(jack_sample_size == sizeof(float), "Expected float32");
	audio_format.format = SampleFormat::FLOAT;
363 364
}

365 366
static void
mpd_jack_error(const char *msg)
367
{
368
	LogError(jack_output_domain, msg);
369 370
}

371
#ifdef HAVE_JACK_SET_INFO_FUNCTION
372 373 374
static void
mpd_jack_info(const char *msg)
{
375
	LogDefault(jack_output_domain, msg);
376
}
377
#endif
378

379
void
380
JackOutput::Disconnect() noexcept
381
{
382
	assert(client != nullptr);
383

384 385 386
	jack_deactivate(client);
	jack_client_close(client);
	client = nullptr;
387 388
}

389 390
void
JackOutput::Connect()
391
{
392
	shutdown = false;
393

394
	jack_status_t status;
395
	client = jack_client_open(name, options, &status, server_name);
396 397 398
	if (client == nullptr)
		throw FormatRuntimeError("Failed to connect to JACK server, status=%d",
					 status);
399

400 401
	jack_set_process_callback(client, mpd_jack_process, this);
	jack_on_shutdown(client, mpd_jack_shutdown, this);
402

403 404 405 406 407 408 409
	for (unsigned i = 0; i < num_source_ports; ++i) {
		ports[i] = jack_port_register(client,
					      source_ports[i].c_str(),
					      JACK_DEFAULT_AUDIO_TYPE,
					      JackPortIsOutput, 0);
		if (ports[i] == nullptr) {
			Disconnect();
410 411
			throw FormatRuntimeError("Cannot register output port \"%s\"",
						 source_ports[i].c_str());
412 413 414 415 416 417 418 419 420 421
		}
	}
}

static bool
mpd_jack_test_default_device(void)
{
	return true;
}

422 423
inline void
JackOutput::Enable()
424 425 426 427
{
	for (unsigned i = 0; i < num_source_ports; ++i)
		ringbuffer[i] = nullptr;

428
	Connect();
429 430 431
}

inline void
432
JackOutput::Disable() noexcept
433 434 435 436 437 438 439 440 441 442 443 444
{
	if (client != nullptr)
		Disconnect();

	for (unsigned i = 0; i < num_source_ports; ++i) {
		if (ringbuffer[i] != nullptr) {
			jack_ringbuffer_free(ringbuffer[i]);
			ringbuffer[i] = nullptr;
		}
	}
}

445
static AudioOutput *
446
mpd_jack_init(EventLoop &, const ConfigBlock &block)
447
{
448
	jack_set_error_function(mpd_jack_error);
449 450

#ifdef HAVE_JACK_SET_INFO_FUNCTION
451
	jack_set_info_function(mpd_jack_info);
452
#endif
453

454
	return new JackOutput(block);
455 456
}

457 458 459
/**
 * Stops the playback on the JACK connection.
 */
460
void
461
JackOutput::Stop() noexcept
462
{
463
	if (client == nullptr)
464
		return;
465

466
	if (shutdown)
467
		/* the connection has failed; close it */
468
		Disconnect();
469 470
	else
		/* the connection is alive: just stop playback */
471
		jack_deactivate(client);
472
}
473

474 475
inline void
JackOutput::Start()
476
{
477 478
	assert(client != nullptr);
	assert(audio_format.channels <= num_source_ports);
479

480 481 482 483
	/* 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 */
484 485 486 487
	for (unsigned i = 0; i < num_source_ports; ++i) {
		if (ringbuffer[i] == nullptr)
			ringbuffer[i] =
				jack_ringbuffer_create(ringbuffer_size);
488

489 490
		/* clear the ring buffer to be sure that data from
		   previous playbacks are gone */
491
		jack_ringbuffer_reset(ringbuffer[i]);
492 493
	}

494 495
	if ( jack_activate(client) ) {
		Stop();
496
		throw std::runtime_error("cannot activate client");
497 498
	}

499 500 501
	const char *dports[MAX_PORTS], **jports;
	unsigned num_dports;
	if (num_destination_ports == 0) {
502 503
		/* no output ports were configured - ask libjack for
		   defaults */
504
		jports = jack_get_ports(client, nullptr, nullptr,
505
					JackPortIsPhysical | JackPortIsInput);
506
		if (jports == nullptr) {
507
			Stop();
508
			throw std::runtime_error("no ports found");
509 510
		}

511
		assert(*jports != nullptr);
512

513 514 515
		for (num_dports = 0; num_dports < MAX_PORTS &&
			     jports[num_dports] != nullptr;
		     ++num_dports) {
516 517
			FormatDebug(jack_output_domain,
				    "destination_port[%u] = '%s'\n",
518 519 520
				    num_dports,
				    jports[num_dports]);
			dports[num_dports] = jports[num_dports];
521
		}
522 523 524
	} else {
		/* use the configured output ports */

525 526 527
		num_dports = num_destination_ports;
		for (unsigned i = 0; i < num_dports; ++i)
			dports[i] = destination_ports[i].c_str();
528

529
		jports = nullptr;
530 531
	}

532 533
	AtScopeExit(jports) { free(jports); };

534
	assert(num_dports > 0);
535

536
	const char *duplicate_port = nullptr;
537
	if (audio_format.channels >= 2 && num_dports == 1) {
538 539
		/* mix stereo signal on one speaker */

540 541
		std::fill(dports + num_dports, dports + audio_format.channels,
			  dports[0]);
542
	} else if (num_dports > audio_format.channels) {
543
		if (audio_format.channels == 1 && num_dports >= 2) {
544 545
			/* mono input file: connect the one source
			   channel to the both destination channels */
546 547
			duplicate_port = dports[1];
			num_dports = 1;
548 549
		} else
			/* connect only as many ports as we need */
550
			num_dports = audio_format.channels;
551 552
	}

553
	assert(num_dports <= num_source_ports);
554

555 556 557
	for (unsigned i = 0; i < num_dports; ++i) {
		int ret = jack_connect(client, jack_port_name(ports[i]),
				       dports[i]);
558
		if (ret != 0) {
559
			Stop();
560 561
			throw FormatRuntimeError("Not a valid JACK port: %s",
						 dports[i]);
562
		}
563 564
	}

565
	if (duplicate_port != nullptr) {
566 567 568 569
		/* mono input file: connect the one source channel to
		   the both destination channels */
		int ret;

570
		ret = jack_connect(client, jack_port_name(ports[0]),
571
				   duplicate_port);
572
		if (ret != 0) {
573
			Stop();
574 575
			throw FormatRuntimeError("Not a valid JACK port: %s",
						 duplicate_port);
576 577
		}
	}
578 579
}

580 581
inline void
JackOutput::Open(AudioFormat &new_audio_format)
582
{
583
	pause = false;
584

585 586
	if (client != nullptr && shutdown)
		Disconnect();
587

588 589
	if (client == nullptr)
		Connect();
590

591 592
	set_audioformat(this, new_audio_format);
	audio_format = new_audio_format;
593

594
	Start();
595
}
596

597
inline size_t
598
JackOutput::WriteSamples(const float *src, size_t n_frames)
599
{
600 601
	assert(n_frames > 0);

602
	const unsigned n_channels = audio_format.channels;
603

604 605 606 607 608 609 610 611 612 613
	float *dest[MAX_CHANNELS];
	size_t space = -1;
	for (unsigned i = 0; i < n_channels; ++i) {
		jack_ringbuffer_data_t d[2];
		jack_ringbuffer_get_write_vector(ringbuffer[i], d);

		/* choose the first non-empty writable area */
		const jack_ringbuffer_data_t &e = d[d[0].len == 0];

		if (e.len < space)
614
			/* send data symmetrically */
Max Kellermann's avatar
Max Kellermann committed
615
			space = e.len;
616 617

		dest[i] = (float *)e.buf;
618 619 620 621 622 623 624
	}

	space /= jack_sample_size;
	if (space == 0)
		return 0;

	const size_t result = n_frames = std::min(space, n_frames);
625

626
	while (n_frames-- > 0)
627 628 629 630 631 632 633
		for (unsigned i = 0; i < n_channels; ++i)
			*dest[i]++ = *src++;

	const size_t per_channel_advance = result * jack_sample_size;
	for (unsigned i = 0; i < n_channels; ++i)
		jack_ringbuffer_write_advance(ringbuffer[i],
					      per_channel_advance);
634 635

	return result;
636 637
}

638
inline size_t
639
JackOutput::Play(const void *chunk, size_t size)
640
{
641
	pause = false;
642

643
	const size_t frame_size = audio_format.GetFrameSize();
644
	assert(size % frame_size == 0);
645
	size /= frame_size;
646

647
	while (true) {
648 649 650
		if (shutdown)
			throw std::runtime_error("Refusing to play, because "
						 "there is no client thread");
651

652 653 654 655
		size_t frames_written =
			WriteSamples((const float *)chunk, size);
		if (frames_written > 0)
			return frames_written * frame_size;
656

657 658
		/* XXX do something more intelligent to
		   synchronize */
659
		usleep(1000);
660
	}
661 662
}

663
inline bool
664
JackOutput::Pause()
665
{
666
	if (shutdown)
667 668
		return false;

669
	pause = true;
670 671 672 673

	return true;
}

674
const struct AudioOutputPlugin jack_output_plugin = {
675 676 677 678
	"jack",
	mpd_jack_test_default_device,
	mpd_jack_init,
	nullptr,
679
};