OpusDecoderPlugin.cxx 13 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * http://www.musicpd.org
 *
 * 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.
 *
 * 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.
 */

#include "OpusDecoderPlugin.h"
21
#include "OggDecoder.hxx"
22
#include "OpusDomain.hxx"
23 24
#include "OpusHead.hxx"
#include "OpusTags.hxx"
25
#include "lib/xiph/OggPacket.hxx"
26
#include "lib/xiph/OggFind.hxx"
27
#include "../DecoderAPI.hxx"
28 29
#include "decoder/Reader.hxx"
#include "input/Reader.hxx"
30
#include "OggCodec.hxx"
31 32
#include "tag/Handler.hxx"
#include "tag/Builder.hxx"
Max Kellermann's avatar
Max Kellermann committed
33
#include "input/InputStream.hxx"
34
#include "util/RuntimeError.hxx"
35
#include "Log.hxx"
36 37 38 39

#include <opus.h>
#include <ogg/ogg.h>

Max Kellermann's avatar
Max Kellermann committed
40
#include <string.h>
41

42 43
namespace {

44
constexpr opus_int32 opus_sample_rate = 48000;
45

46 47 48 49
/**
 * Allocate an output buffer for 16 bit PCM samples big enough to hold
 * a quarter second, larger than 120ms required by libopus.
 */
50
constexpr unsigned opus_output_buffer_frames = opus_sample_rate / 4;
51

52
gcc_pure
53
bool
54
IsOpusHead(const ogg_packet &packet) noexcept
55 56 57 58 59
{
	return packet.bytes >= 8 && memcmp(packet.packet, "OpusHead", 8) == 0;
}

gcc_pure
60
bool
61
IsOpusTags(const ogg_packet &packet) noexcept
62 63 64 65
{
	return packet.bytes >= 8 && memcmp(packet.packet, "OpusTags", 8) == 0;
}

66 67 68 69 70 71 72 73 74 75 76
/**
 * Convert an EBU R128 value to ReplayGain.
 */
constexpr float
EbuR128ToReplayGain(float ebu_r128) noexcept
{
	/* add 5dB to compensate for the different reference levels
	   between ReplayGain (89dB) and EBU R128 (-23 LUFS) */
	return ebu_r128 + 5;
}

77
bool
Rosen Penev's avatar
Rosen Penev committed
78
mpd_opus_init([[maybe_unused]] const ConfigBlock &block)
79
{
80
	LogDebug(opus_domain, opus_get_version_string());
81 82 83 84

	return true;
}

85
class MPDOpusDecoder final : public OggDecoder {
86 87
	OpusDecoder *opus_decoder = nullptr;
	opus_int16 *output_buffer = nullptr;
88

89
	/**
90 91 92
	 * The output gain from the Opus header in dB that should be
	 * applied unconditionally, but is often used specifically for
	 * ReplayGain.  Initialized by OnOggBeginning().
93
	 */
94
	float output_gain;
95

96 97 98 99 100 101 102 103 104 105 106 107
	/**
	 * The pre-skip value from the Opus header.  Initialized by
	 * OnOggBeginning().
	 */
	unsigned pre_skip;

	/**
	 * The number of decoded samples which shall be skipped.  At
	 * the beginning of the file, this gets set to #pre_skip (by
	 * OnOggBeginning()), and may also be set while seeking.
	 */
	unsigned skip;
108

109 110 111 112 113 114
	/**
	 * If non-zero, then a previous Opus stream has been found
	 * already with this number of channels.  If opus_decoder is
	 * nullptr, then its end-of-stream packet has been found
	 * already.
	 */
115
	unsigned previous_channels = 0;
116

117 118
	size_t frame_size;

119 120 121 122 123 124 125
	/**
	 * The granulepos of the next sample to be submitted to
	 * DecoderClient::SubmitData().  Negative if unkown.
	 * Initialized by OnOggBeginning().
	 */
	ogg_int64_t granulepos;

126 127 128 129 130 131 132 133
	/**
	 * Was DecoderClient::SubmitReplayGain() called?  We need to
	 * keep track of this, because it will usually be called by
	 * HandleTags(), but if there is no OpusTags packet, we need
	 * to submit our #output_gain value from the OpusHead.
	 */
	bool submitted_replay_gain = false;

134
public:
135 136
	explicit MPDOpusDecoder(DecoderReader &reader)
		:OggDecoder(reader) {}
137

138 139
	~MPDOpusDecoder();

140
	/**
141
	 * Has DecoderClient::Ready() been called yet?
142
	 */
143
	[[nodiscard]] bool IsInitialized() const {
144 145 146
		return previous_channels != 0;
	}

147
	bool Seek(uint64_t where_frame);
148 149

private:
150 151 152 153 154 155 156
	void AddGranulepos(ogg_int64_t n) noexcept {
		assert(n >= 0);

		if (granulepos >= 0)
			granulepos += n;
	}

157 158 159 160 161 162 163 164
	void HandleTags(const ogg_packet &packet);
	void HandleAudio(const ogg_packet &packet);

protected:
	/* virtual methods from class OggVisitor */
	void OnOggBeginning(const ogg_packet &packet) override;
	void OnOggPacket(const ogg_packet &packet) override;
	void OnOggEnd() override;
165 166 167 168
};

MPDOpusDecoder::~MPDOpusDecoder()
{
169
	delete[] output_buffer;
170 171 172

	if (opus_decoder != nullptr)
		opus_decoder_destroy(opus_decoder);
173 174
}

175 176
void
MPDOpusDecoder::OnOggPacket(const ogg_packet &packet)
177
{
178
	if (IsOpusTags(packet))
179 180 181
		HandleTags(packet);
	else
		HandleAudio(packet);
182 183
}

184 185
void
MPDOpusDecoder::OnOggBeginning(const ogg_packet &packet)
186 187 188
{
	assert(packet.b_o_s);

189 190
	if (opus_decoder != nullptr || !IsOpusHead(packet))
		throw std::runtime_error("BOS packet must be OpusHead");
191 192

	unsigned channels;
193 194
	signed output_gain_i;
	if (!ScanOpusHeader(packet.packet, packet.bytes, channels, output_gain_i, pre_skip) ||
195 196
	    !audio_valid_channel_count(channels))
		throw std::runtime_error("Malformed BOS packet");
197

198 199 200
	/* convert Q7.8 fixed-point to float */
	output_gain = float(output_gain_i) / 256.0f;

201
	granulepos = 0;
202 203
	skip = pre_skip;

204
	assert(opus_decoder == nullptr);
205
	assert(IsInitialized() == (output_buffer != nullptr));
206

207 208 209
	if (IsInitialized() && channels != previous_channels)
		throw FormatRuntimeError("Next stream has different channels (%u -> %u)",
					 previous_channels, channels);
210 211 212 213 214 215 216

	/* TODO: parse attributes from the OpusHead (sample rate,
	   channels, ...) */

	int opus_error;
	opus_decoder = opus_decoder_create(opus_sample_rate, channels,
					   &opus_error);
217 218 219
	if (opus_decoder == nullptr)
		throw FormatRuntimeError("libopus error: %s",
					 opus_strerror(opus_error));
220

221
	if (IsInitialized()) {
222 223 224
		/* decoder was already initialized by the previous
		   stream; skip the rest of this method */
		LogDebug(opus_domain, "Found another stream");
225
		return;
226 227
	}

228
	const auto eos_granulepos = UpdateEndGranulePos();
229 230 231 232
	const auto duration = eos_granulepos >= 0
		? SignedSongTime::FromScale<uint64_t>(eos_granulepos,
						      opus_sample_rate)
		: SignedSongTime::Negative();
233

234
	previous_channels = channels;
235 236
	const AudioFormat audio_format(opus_sample_rate,
				       SampleFormat::S16, channels);
237
	client.Ready(audio_format, eos_granulepos > 0, duration);
238
	frame_size = audio_format.GetFrameSize();
239

240 241 242 243 244 245
	if (output_buffer == nullptr)
		/* note: if we ever support changing the channel count
		   in chained streams, we need to reallocate this
		   buffer instead of keeping it */
		output_buffer = new opus_int16[opus_output_buffer_frames
					       * audio_format.channels];
246

247
	auto cmd = client.GetCommand();
248 249
	if (cmd != DecoderCommand::NONE)
		throw cmd;
250 251
}

252 253
void
MPDOpusDecoder::OnOggEnd()
254
{
255
	if (!IsSeekable() && IsInitialized()) {
256 257 258 259 260 261
		/* allow chaining of (unseekable) streams */
		assert(opus_decoder != nullptr);
		assert(output_buffer != nullptr);

		opus_decoder_destroy(opus_decoder);
		opus_decoder = nullptr;
262 263
	} else
		throw StopDecoder();
264 265
}

266
inline void
267 268
MPDOpusDecoder::HandleTags(const ogg_packet &packet)
{
269
	ReplayGainInfo rgi;
270
	rgi.Clear();
271

272
	TagBuilder tag_builder;
273
	AddTagHandler h(tag_builder);
274

275 276 277
	if (!ScanOpusTags(packet.packet, packet.bytes, &rgi, h))
		return;

278 279 280 281 282 283 284 285 286 287
	if (rgi.IsDefined()) {
		/* submit all valid EBU R128 values with output_gain
		   applied */
		if (rgi.track.IsDefined())
			rgi.track.gain += EbuR128ToReplayGain(output_gain);
		if (rgi.album.IsDefined())
			rgi.album.gain += EbuR128ToReplayGain(output_gain);
		client.SubmitReplayGain(&rgi);
		submitted_replay_gain = true;
	}
288

289
	if (!tag_builder.empty()) {
290
		Tag tag = tag_builder.Commit();
291
		auto cmd = client.SubmitTag(input_stream, std::move(tag));
292 293 294
		if (cmd != DecoderCommand::NONE)
			throw cmd;
	}
295 296
}

297
inline void
298 299 300 301
MPDOpusDecoder::HandleAudio(const ogg_packet &packet)
{
	assert(opus_decoder != nullptr);

302 303 304 305 306 307 308 309 310 311 312 313
	if (!submitted_replay_gain) {
		/* if we didn't see an OpusTags packet with EBU R128
		   values, we still need to apply the output gain
		   value from the OpusHead packet; submit it as "track
		   gain" value */
		ReplayGainInfo rgi;
		rgi.Clear();
		rgi.track.gain = EbuR128ToReplayGain(output_gain);
		client.SubmitReplayGain(&rgi);
		submitted_replay_gain = true;
	}

314 315 316
	int nframes = opus_decode(opus_decoder,
				  (const unsigned char*)packet.packet,
				  packet.bytes,
317
				  output_buffer, opus_output_buffer_frames,
318
				  0);
319 320 321 322 323
	if (gcc_unlikely(nframes <= 0)) {
		if (nframes < 0)
			throw FormatRuntimeError("libopus error: %s",
						 opus_strerror(nframes));
		else
324
			return;
325
	}
326

327 328 329
	/* apply the "skip" value */
	if (skip >= (unsigned)nframes) {
		skip -= nframes;
330
		AddGranulepos(nframes);
331
		return;
332
	}
333

334 335 336
	const opus_int16 *data = output_buffer;
	data += skip * previous_channels;
	nframes -= skip;
337
	AddGranulepos(skip);
338 339
	skip = 0;

340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
	if (packet.e_o_s && packet.granulepos > 0 && granulepos >= 0) {
		/* End Trimming (RFC7845 4.4): "The page with the 'end
		   of stream' flag set MAY have a granule position
		   that indicates the page contains less audio data
		   than would normally be returned by decoding up
		   through the final packet.  This is used to end the
		   stream somewhere other than an even frame
		   boundary. [...] The remaining samples are
		   discarded. */
		ogg_int64_t remaining = packet.granulepos - granulepos;
		if (remaining <= 0)
			return;

		if (remaining < nframes)
			nframes = remaining;
355
	}
356

357 358 359 360 361 362 363 364
	/* submit decoded samples to the DecoderClient */
	const size_t nbytes = nframes * frame_size;
	auto cmd = client.SubmitData(input_stream,
				     data, nbytes,
				     0);
	if (cmd != DecoderCommand::NONE)
		throw cmd;

365 366 367
	if (packet.granulepos > 0) {
		granulepos = packet.granulepos;
		client.SubmitTimestamp(FloatDuration(granulepos - pre_skip)
368
				       / opus_sample_rate);
369 370
	} else
		AddGranulepos(nframes);
371 372
}

373
bool
374
MPDOpusDecoder::Seek(uint64_t where_frame)
375
{
376
	assert(IsSeekable());
377 378
	assert(input_stream.IsSeekable());
	assert(input_stream.KnownSize());
379

380
	const ogg_int64_t where_granulepos(where_frame);
381

382 383 384 385 386
	/* we don't know the exact granulepos after seeking, so let's
	   set it to -1 - it will be set after the next packet which
	   declares its granulepos */
	granulepos = -1;

387 388
	try {
		SeekGranulePos(where_granulepos);
389 390 391 392 393 394

		/* since all frame numbers are offset by the file's
		   pre-skip value, we need to apply it here as well;
		   we could just seek to "where_frame+pre_skip" as
		   well, but I think by decoding those samples and
		   discard them, we're safer */
395
		skip = pre_skip;
396
		return true;
397
	} catch (...) {
398 399
		return false;
	}
400 401
}

402
void
403
mpd_opus_stream_decode(DecoderClient &client,
404
		       InputStream &input_stream)
405
{
406
	if (ogg_codec_detect(&client, input_stream) != OGG_CODEC_OPUS)
407 408 409 410
		return;

	/* rewind the stream, because ogg_codec_detect() has
	   moved it */
411 412
	try {
		input_stream.LockRewind();
413
	} catch (...) {
414
	}
415

416
	DecoderReader reader(client, input_stream);
417

418
	MPDOpusDecoder d(reader);
419

420
	while (true) {
421 422
		try {
			d.Visit();
423
			break;
424 425
		} catch (DecoderCommand cmd) {
			if (cmd == DecoderCommand::SEEK) {
426 427
				if (d.Seek(client.GetSeekFrame()))
					client.CommandFinished();
428
				else
429
					client.SeekError();
430 431 432
			} else if (cmd != DecoderCommand::NONE)
				break;
		}
433 434 435
	}
}

436
bool
437
ReadAndParseOpusHead(OggSyncState &sync, OggStreamState &stream,
438
		     unsigned &channels, signed &output_gain, unsigned &pre_skip)
439 440 441
{
	ogg_packet packet;

442 443
	return OggReadPacket(sync, stream, packet) && packet.b_o_s &&
		IsOpusHead(packet) &&
444
		ScanOpusHeader(packet.packet, packet.bytes, channels,
445
			       output_gain, pre_skip) &&
446 447
		audio_valid_channel_count(channels);
}
448

449
bool
450
ReadAndVisitOpusTags(OggSyncState &sync, OggStreamState &stream,
451
		     TagHandler &handler)
452 453
{
	ogg_packet packet;
454

455 456 457 458
	return OggReadPacket(sync, stream, packet) &&
		IsOpusTags(packet) &&
		ScanOpusTags(packet.packet, packet.bytes,
			     nullptr,
459
			     handler);
460
}
461

462
void
463
VisitOpusDuration(InputStream &is, OggSyncState &sync, OggStreamState &stream,
464
		  ogg_int64_t pre_skip, TagHandler &handler)
465 466
{
	ogg_packet packet;
467

468 469
	if (OggSeekFindEOS(sync, stream, packet, is) &&
	    packet.granulepos >= pre_skip) {
470 471 472
		const auto duration =
			SongTime::FromScale<uint64_t>(packet.granulepos,
						      opus_sample_rate);
473
		handler.OnDuration(duration);
474
	}
475
}
476

477
static bool
478
mpd_opus_scan_stream(InputStream &is, TagHandler &handler)
479 480 481 482 483 484 485 486 487 488
{
	InputStreamReader reader(is);
	OggSyncState oy(reader);

	ogg_page first_page;
	if (!oy.ExpectPage(first_page))
		return false;

	OggStreamState os(first_page);

489
	unsigned channels, pre_skip;
490 491
	signed output_gain;
	if (!ReadAndParseOpusHead(oy, os, channels, output_gain, pre_skip) ||
492
	    !ReadAndVisitOpusTags(oy, os, handler))
493 494
		return false;

495 496 497
	handler.OnAudioFormat(AudioFormat(opus_sample_rate,
					  SampleFormat::S16, channels));

498
	VisitOpusDuration(is, oy, os, pre_skip, handler);
499
	return true;
500 501
}

502
const char *const opus_suffixes[] = {
503 504 505 506 507 508
	"opus",
	"ogg",
	"oga",
	nullptr
};

509
const char *const opus_mime_types[] = {
510 511 512 513 514 515 516
	/* the official MIME type (RFC 5334) */
	"audio/ogg",

	/* deprecated (RFC 5334) */
	"application/ogg",

	/* deprecated; from an early draft */
517 518 519 520
	"audio/opus",
	nullptr
};

521 522
} /* anonymous namespace */

523 524 525 526 527
constexpr DecoderPlugin opus_decoder_plugin =
	DecoderPlugin("opus", mpd_opus_stream_decode, mpd_opus_scan_stream)
	.WithInit(mpd_opus_init)
	.WithSuffixes(opus_suffixes)
	.WithMimeTypes(opus_mime_types);