id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
24,975
|
opus_encoder.cpp
|
badaix_snapcast/server/encoder/opus_encoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2015 Hannes Ellinger
Copyright (C) 2016-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "opus_encoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
using namespace std;
namespace encoder
{
#define ID_OPUS 0x4F505553
static constexpr opus_int32 const_min_bitrate = 6000;
static constexpr opus_int32 const_max_bitrate = 512000;
static constexpr int min_chunk_size = 10;
static constexpr auto LOG_TAG = "OpusEnc";
namespace
{
template <typename T>
void assign(void* pointer, T val)
{
T* p = (T*)pointer;
*p = val;
}
} // namespace
OpusEncoder::OpusEncoder(const std::string& codecOptions) : Encoder(codecOptions), enc_(nullptr), remainder_max_size_(0)
{
headerChunk_ = make_unique<msg::CodecHeader>("opus");
}
OpusEncoder::~OpusEncoder()
{
if (enc_ != nullptr)
opus_encoder_destroy(enc_);
}
std::string OpusEncoder::getAvailableOptions() const
{
return "BITRATE:[" + cpt::to_string(const_min_bitrate) + " - " + cpt::to_string(const_max_bitrate) + "|MAX|AUTO],COMPLEXITY:[1-10]";
}
std::string OpusEncoder::getDefaultOptions() const
{
return "BITRATE:192000,COMPLEXITY:10";
}
std::string OpusEncoder::name() const
{
return "opus";
}
void OpusEncoder::initEncoder()
{
// Opus is quite restrictive in sample rate and bit depth
// It can handle mono signals, but we will check for stereo
// if ((sampleFormat_.rate() != 48000) || (sampleFormat_.bits() != 16) || (sampleFormat_.channels() != 2))
// throw SnapException("Opus sampleformat must be 48000:16:2");
if (sampleFormat_.channels() != 2)
throw SnapException("Opus requires a stereo signal");
SampleFormat out{48000, 16, 2};
if ((sampleFormat_.rate() != 48000) || (sampleFormat_.bits() != 16))
LOG(INFO, LOG_TAG) << "Resampling input from " << sampleFormat_.toString() << " to " << out.toString() << " as required by Opus\n";
resampler_ = make_unique<Resampler>(sampleFormat_, out);
sampleFormat_ = out;
opus_int32 bitrate = 192000;
opus_int32 complexity = 10;
// parse options: bitrate and complexity
auto options = utils::string::split(codecOptions_, ',');
for (const auto& option : options)
{
auto kv = utils::string::split(option, ':');
if (kv.size() == 2)
{
if (kv.front() == "BITRATE")
{
if (kv.back() == "MAX")
bitrate = OPUS_BITRATE_MAX;
else if (kv.back() == "AUTO")
bitrate = OPUS_AUTO;
else
{
try
{
bitrate = cpt::stoi(kv.back());
if ((bitrate < const_min_bitrate) || (bitrate > const_max_bitrate))
throw SnapException("Opus bitrate must be between " + cpt::to_string(const_min_bitrate) + " and " +
cpt::to_string(const_max_bitrate));
}
catch (const std::invalid_argument&)
{
throw SnapException("Opus error parsing bitrate (must be between " + cpt::to_string(const_min_bitrate) + " and " +
cpt::to_string(const_max_bitrate) + "): " + kv.back());
}
}
}
else if (kv.front() == "COMPLEXITY")
{
try
{
complexity = cpt::stoi(kv.back());
if ((complexity < 1) || (complexity > 10))
throw SnapException("Opus complexity must be between 1 and 10");
}
catch (const std::invalid_argument&)
{
throw SnapException("Opus error parsing complexity (must be between 1 and 10): " + kv.back());
}
}
else
throw SnapException("Opus unknown option: " + kv.front());
}
else
throw SnapException("Opus error parsing options: " + codecOptions_);
}
LOG(INFO, LOG_TAG) << "Init - bitrate: " << bitrate << " bps, complexity: " << complexity << "\n";
int error;
enc_ = opus_encoder_create(sampleFormat_.rate(), sampleFormat_.channels(), OPUS_APPLICATION_RESTRICTED_LOWDELAY, &error);
if (error != 0)
{
throw SnapException("Failed to initialize Opus encoder: " + std::string(opus_strerror(error)));
}
opus_encoder_ctl(enc_, OPUS_SET_BITRATE(bitrate));
opus_encoder_ctl(enc_, OPUS_SET_COMPLEXITY(complexity));
// create some opus pseudo header to let the decoder know about the sample format
headerChunk_->payloadSize = 12;
headerChunk_->payload = static_cast<char*>(realloc(headerChunk_->payload, headerChunk_->payloadSize));
char* payload = headerChunk_->payload;
assign(payload, SWAP_32(ID_OPUS));
assign(payload + 4, SWAP_32(sampleFormat_.rate()));
assign(payload + 8, SWAP_16(sampleFormat_.bits()));
assign(payload + 10, SWAP_16(sampleFormat_.channels()));
remainder_ = std::make_unique<msg::PcmChunk>(sampleFormat_, min_chunk_size);
remainder_max_size_ = remainder_->payloadSize;
remainder_->payloadSize = 0;
}
// Opus encoder can only handle chunk sizes of:
// 5, 10, 20, 40, 60 ms
// 240, 480, 960, 1920, 2880 frames
// We will split the chunk into encodable sizes and store any remaining data in the remainder_ buffer
// and encode the buffer content in the next iteration
void OpusEncoder::encode(const msg::PcmChunk& chunk)
{
// chunk =
// resampler_->resample(std::make_shared<msg::PcmChunk>(chunk)).get();
auto in = std::make_shared<msg::PcmChunk>(chunk);
auto out = resampler_->resample(in); //, std::chrono::milliseconds(20));
if (out == nullptr)
return;
// chunk = out.get();
// LOG(TRACE, LOG_TAG) << "encode " << chunk->duration<std::chrono::milliseconds>().count() << "ms\n";
uint32_t offset = 0;
// check if there is something left from the last call to encode and fill the remainder buffer to
// an encodable size of 10ms (min_chunk_size)
if (remainder_->payloadSize > 0)
{
offset = std::min(static_cast<uint32_t>(remainder_max_size_ - remainder_->payloadSize), out->payloadSize);
memcpy(remainder_->payload + remainder_->payloadSize, out->payload, offset);
// LOG(TRACE, LOG_TAG) << "remainder buffer size: " << remainder_->payloadSize << "/" << remainder_max_size_ << ", appending " << offset << " bytes\n";
remainder_->payloadSize += offset;
if (remainder_->payloadSize < remainder_max_size_)
{
LOG(DEBUG, LOG_TAG) << "not enough data to encode (" << remainder_->payloadSize << " of " << remainder_max_size_ << " bytes)"
<< "\n";
return;
}
encode(out->format, remainder_->payload, remainder_->payloadSize);
remainder_->payloadSize = 0;
}
// encode greedy 60ms, 40ms, 20ms, 10ms chunks
std::vector<size_t> chunk_durations{60, 40, 20, min_chunk_size};
for (const auto duration : chunk_durations)
{
auto ms2bytes = [this](size_t ms) { return (ms * sampleFormat_.msRate() * sampleFormat_.frameSize()); };
uint32_t bytes = ms2bytes(duration);
while (out->payloadSize - offset >= bytes)
{
// LOG(TRACE, LOG_TAG) << "encoding " << duration << "ms (" << bytes << "), offset: " << offset << ", chunk size: " << chunk->payloadSize - offset
// << "\n";
encode(out->format, out->payload + offset, bytes);
offset += bytes;
}
if (out->payloadSize == offset)
break;
}
// something is left (must be less than min_chunk_size (10ms))
if (out->payloadSize > offset)
{
memcpy(remainder_->payload + remainder_->payloadSize, out->payload + offset, out->payloadSize - offset);
remainder_->payloadSize = out->payloadSize - offset;
}
}
void OpusEncoder::encode(const SampleFormat& format, const char* data, size_t size)
{
// void* buffer;
// LOG(INFO, LOG_TAG) << "frames: " << chunk->readFrames(buffer, std::chrono::milliseconds(10)) << "\n";
int samples_per_channel = size / format.frameSize();
if (encoded_.size() < size)
encoded_.resize(size);
opus_int32 len = opus_encode(enc_, (opus_int16*)data, samples_per_channel, encoded_.data(), size);
LOG(TRACE, LOG_TAG) << "Encode " << samples_per_channel << " frames, size " << size << " bytes, encoded: " << len << " bytes" << '\n';
if (len > 0)
{
// copy encoded data to chunk
auto opusChunk = make_shared<msg::PcmChunk>(format, 0);
opusChunk->payloadSize = len;
opusChunk->payload = static_cast<char*>(realloc(opusChunk->payload, opusChunk->payloadSize));
memcpy(opusChunk->payload, encoded_.data(), len);
encoded_callback_(*this, opusChunk, static_cast<double>(samples_per_channel) / sampleFormat_.msRate());
}
else
{
LOG(ERROR, LOG_TAG) << "Failed to encode chunk: " << opus_strerror(len) << ", samples / channel: " << samples_per_channel << ", bytes: " << size
<< '\n';
}
}
} // namespace encoder
| 10,135
|
C++
|
.cpp
| 225
| 37.168889
| 159
| 0.607175
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,976
|
encoder_factory.cpp
|
badaix_snapcast/server/encoder/encoder_factory.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "encoder_factory.hpp"
// local headers
#include "null_encoder.hpp"
#include "pcm_encoder.hpp"
#if defined(HAS_OGG) && defined(HAS_VORBIS) && defined(HAS_VORBIS_ENC)
#include "ogg_encoder.hpp"
#endif
#if defined(HAS_FLAC)
#include "flac_encoder.hpp"
#endif
#if defined(HAS_OPUS)
#include "opus_encoder.hpp"
#endif
#include "common/snap_exception.hpp"
#include "common/utils/string_utils.hpp"
using namespace std;
namespace encoder
{
std::unique_ptr<Encoder> EncoderFactory::createEncoder(const std::string& codecSettings) const
{
std::string codec(codecSettings);
std::string codecOptions;
if (codec.find(':') != std::string::npos)
{
codecOptions = utils::string::trim_copy(codec.substr(codec.find(':') + 1));
codec = utils::string::trim_copy(codec.substr(0, codec.find(':')));
}
if (codec == "pcm")
return std::make_unique<PcmEncoder>(codecOptions);
else if (codec == "null")
return std::make_unique<NullEncoder>(codecOptions);
#if defined(HAS_OGG) && defined(HAS_VORBIS) && defined(HAS_VORBIS_ENC)
else if (codec == "ogg")
return std::make_unique<OggEncoder>(codecOptions);
#endif
#if defined(HAS_FLAC)
else if (codec == "flac")
return std::make_unique<FlacEncoder>(codecOptions);
#endif
#if defined(HAS_OPUS)
else if (codec == "opus")
return std::make_unique<OpusEncoder>(codecOptions);
#endif
throw SnapException("unknown codec: " + codec);
}
} // namespace encoder
| 2,261
|
C++
|
.cpp
| 61
| 33.459016
| 94
| 0.717222
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,977
|
null_encoder.cpp
|
badaix_snapcast/server/encoder/null_encoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "null_encoder.hpp"
// local headers
#include "common/aixlog.hpp"
namespace encoder
{
static constexpr auto LOG_TAG = "NullEnc";
NullEncoder::NullEncoder(const std::string& codecOptions) : Encoder(codecOptions)
{
headerChunk_.reset(new msg::CodecHeader("null"));
}
void NullEncoder::encode(const msg::PcmChunk& chunk)
{
std::ignore = chunk;
}
void NullEncoder::initEncoder()
{
LOG(INFO, LOG_TAG) << "Init\n";
}
std::string NullEncoder::name() const
{
return "null";
}
} // namespace encoder
| 1,303
|
C++
|
.cpp
| 38
| 31.184211
| 81
| 0.744596
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
24,978
|
flac_encoder.cpp
|
badaix_snapcast/server/encoder/flac_encoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "flac_encoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
// 3rd party headers
#include "FLAC/metadata.h"
// standard headers
#include <iostream>
using namespace std;
namespace encoder
{
static constexpr auto LOG_TAG = "FlacEnc";
FlacEncoder::FlacEncoder(const std::string& codecOptions) : Encoder(codecOptions), encoder_(nullptr), pcmBufferSize_(0), encodedSamples_(0), flacChunk_(nullptr)
{
headerChunk_.reset(new msg::CodecHeader("flac"));
pcmBuffer_ = static_cast<FLAC__int32*>(malloc(pcmBufferSize_ * sizeof(FLAC__int32)));
metadata_[0] = nullptr;
metadata_[1] = nullptr;
}
FlacEncoder::~FlacEncoder()
{
if (encoder_ != nullptr)
{
FLAC__stream_encoder_finish(encoder_);
FLAC__metadata_object_delete(metadata_[0]);
FLAC__metadata_object_delete(metadata_[1]);
FLAC__stream_encoder_delete(encoder_);
}
free(pcmBuffer_);
}
std::string FlacEncoder::getAvailableOptions() const
{
return "compression level: [0..8]";
}
std::string FlacEncoder::getDefaultOptions() const
{
return "2";
}
std::string FlacEncoder::name() const
{
return "flac";
}
void FlacEncoder::encode(const msg::PcmChunk& chunk)
{
if (flacChunk_ == nullptr)
flacChunk_ = make_shared<msg::PcmChunk>(chunk.format, 0);
int samples = chunk.getSampleCount();
int frames = chunk.getFrameCount();
// LOG(TRACE, LOG_TAG) << "payload: " << chunk.payloadSize << "\tframes: " << frames << "\tsamples: " << samples
// << "\tduration: " << chunk.duration<chronos::msec>().count() << ", format: " << chunk.format.toString() << "\n";
if (pcmBufferSize_ < samples)
{
pcmBufferSize_ = samples;
pcmBuffer_ = static_cast<FLAC__int32*>(realloc(pcmBuffer_, pcmBufferSize_ * sizeof(FLAC__int32)));
}
auto clip = [](int32_t min, int32_t max, int32_t value) -> int32_t
{
if (value < min)
return min;
if (value > max)
return max;
return value;
};
if (sampleFormat_.sampleSize() == 1)
{
auto* buffer = reinterpret_cast<FLAC__int8*>(chunk.payload);
for (int i = 0; i < samples; i++)
pcmBuffer_[i] = clip(-128, 127, static_cast<FLAC__int32>(buffer[i]));
}
else if (sampleFormat_.sampleSize() == 2)
{
auto* buffer = reinterpret_cast<FLAC__int16*>(chunk.payload);
for (int i = 0; i < samples; i++)
pcmBuffer_[i] = clip(-32768, 32767, static_cast<FLAC__int32>(buffer[i]));
}
else if (sampleFormat_.sampleSize() == 4)
{
auto* buffer = reinterpret_cast<FLAC__int32*>(chunk.payload);
if (sampleFormat_.bits() == 24)
{
for (int i = 0; i < samples; i++)
pcmBuffer_[i] = clip(-8388608, 8388607, buffer[i]);
}
else
{
for (int i = 0; i < samples; i++)
pcmBuffer_[i] = buffer[i];
}
}
FLAC__stream_encoder_process_interleaved(encoder_, pcmBuffer_, frames);
if (encodedSamples_ > 0)
{
double resMs = static_cast<double>(encodedSamples_) / sampleFormat_.msRate();
// LOG(INFO, LOG_TAG) << "encoded: " << chunk->payloadSize << "\tframes: " << encodedSamples_ << "\tres: " << resMs << "\n";
encodedSamples_ = 0;
encoded_callback_(*this, flacChunk_, resMs);
flacChunk_ = make_shared<msg::PcmChunk>(chunk.format, 0);
}
}
FLAC__StreamEncoderWriteStatus FlacEncoder::write_callback(const FLAC__StreamEncoder* /*encoder*/, const FLAC__byte buffer[], size_t bytes, unsigned samples,
unsigned current_frame)
{
// LOG(INFO, LOG_TAG) << "write_callback: " << bytes << ", " << samples << ", " << current_frame << "\n";
if ((current_frame == 0) && (bytes > 0) && (samples == 0))
{
headerChunk_->payload = static_cast<char*>(realloc(headerChunk_->payload, headerChunk_->payloadSize + bytes));
memcpy(headerChunk_->payload + headerChunk_->payloadSize, buffer, bytes);
headerChunk_->payloadSize += bytes;
}
else
{
flacChunk_->payload = static_cast<char*>(realloc(flacChunk_->payload, flacChunk_->payloadSize + bytes));
memcpy(flacChunk_->payload + flacChunk_->payloadSize, buffer, bytes);
flacChunk_->payloadSize += bytes;
encodedSamples_ += samples;
}
return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
}
namespace callback
{
FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder* encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples,
unsigned current_frame, void* client_data)
{
auto* flacEncoder = static_cast<FlacEncoder*>(client_data);
return flacEncoder->write_callback(encoder, buffer, bytes, samples, current_frame);
}
} // namespace callback
void FlacEncoder::initEncoder()
{
int compression_level(2);
try
{
compression_level = cpt::stoi(codecOptions_);
}
catch (...)
{
throw SnapException("Invalid codec option: \"" + codecOptions_ + "\"");
}
if ((compression_level < 0) || (compression_level > 8))
{
throw SnapException("compression level has to be between 0 and 8");
}
LOG(INFO, LOG_TAG) << "Init - compression level: " << compression_level << "\n";
FLAC__bool ok = 1;
FLAC__StreamEncoderInitStatus init_status;
FLAC__StreamMetadata_VorbisComment_Entry entry;
// allocate the encoder
if ((encoder_ = FLAC__stream_encoder_new()) == nullptr)
throw SnapException("error allocating encoder");
ok &= FLAC__stream_encoder_set_verify(encoder_, 1);
// compression levels (0-8):
// https://xiph.org/flac/api/group__flac__stream__encoder.html#gae49cf32f5256cb47eecd33779493ac85
// latency:
// 0-2: 1152 frames, ~26.1224ms
// 3-8: 4096 frames, ~92.8798ms
ok &= FLAC__stream_encoder_set_compression_level(encoder_, compression_level);
ok &= FLAC__stream_encoder_set_channels(encoder_, sampleFormat_.channels());
ok &= FLAC__stream_encoder_set_bits_per_sample(encoder_, sampleFormat_.bits());
ok &= FLAC__stream_encoder_set_sample_rate(encoder_, sampleFormat_.rate());
if (ok == 0)
throw SnapException("error setting up encoder");
// now add some metadata; we'll add some tags and a padding block
if ((metadata_[0] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_VORBIS_COMMENT)) == nullptr ||
(metadata_[1] = FLAC__metadata_object_new(FLAC__METADATA_TYPE_PADDING)) == nullptr ||
// there are many tag (vorbiscomment) functions but these are convenient for this particular use:
(FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "TITLE", "SnapStream") == 0) ||
(FLAC__metadata_object_vorbiscomment_append_comment(metadata_[0], entry, 0) == 0) ||
(FLAC__metadata_object_vorbiscomment_entry_from_name_value_pair(&entry, "VERSION", VERSION) == 0) ||
(FLAC__metadata_object_vorbiscomment_append_comment(metadata_[0], entry, 0) == 0))
throw SnapException("out of memory or tag error");
metadata_[1]->length = 1234; // set the padding length
ok = FLAC__stream_encoder_set_metadata(encoder_, metadata_, 2);
if (ok == 0)
throw SnapException("error setting meta data");
// initialize encoder
init_status = FLAC__stream_encoder_init_stream(encoder_, callback::write_callback, nullptr, nullptr, nullptr, this);
if (init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK)
throw SnapException("ERROR: initializing encoder: " + string(FLAC__StreamEncoderInitStatusString[init_status]));
}
} // namespace encoder
| 8,574
|
C++
|
.cpp
| 196
| 37.658163
| 160
| 0.648308
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,979
|
pcm_encoder.cpp
|
badaix_snapcast/server/encoder/pcm_encoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2021 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "pcm_encoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/endian.hpp"
// standard headers
#include <memory>
namespace encoder
{
static constexpr auto ID_RIFF = 0x46464952;
static constexpr auto ID_WAVE = 0x45564157;
static constexpr auto ID_FMT = 0x20746d66;
static constexpr auto ID_DATA = 0x61746164;
static constexpr auto LOG_TAG = "PcmEnc";
namespace
{
template <typename T>
void assign(void* pointer, T val)
{
T* p = (T*)pointer;
*p = val;
}
} // namespace
PcmEncoder::PcmEncoder(const std::string& codecOptions) : Encoder(codecOptions)
{
headerChunk_.reset(new msg::CodecHeader("pcm"));
}
void PcmEncoder::encode(const msg::PcmChunk& chunk)
{
// copy the chunk into a shared_ptr
auto pcmChunk = std::make_shared<msg::PcmChunk>(chunk);
encoded_callback_(*this, pcmChunk, pcmChunk->durationMs());
}
void PcmEncoder::initEncoder()
{
LOG(INFO, LOG_TAG) << "Init\n";
headerChunk_->payloadSize = 44;
headerChunk_->payload = static_cast<char*>(realloc(headerChunk_->payload, headerChunk_->payloadSize));
char* payload = headerChunk_->payload;
assign(payload, SWAP_32(ID_RIFF));
assign(payload + 4, SWAP_32(36));
assign(payload + 8, SWAP_32(ID_WAVE));
assign(payload + 12, SWAP_32(ID_FMT));
assign(payload + 16, SWAP_32(16));
assign(payload + 20, SWAP_16(1));
assign(payload + 22, SWAP_16(sampleFormat_.channels()));
assign(payload + 24, SWAP_32(sampleFormat_.rate()));
assign(payload + 28, SWAP_32(sampleFormat_.rate() * sampleFormat_.bits() * sampleFormat_.channels() / 8));
assign(payload + 32, SWAP_16(sampleFormat_.channels() * ((sampleFormat_.bits() + 7) / 8)));
assign(payload + 34, SWAP_16(sampleFormat_.bits()));
assign(payload + 36, SWAP_32(ID_DATA));
assign(payload + 40, SWAP_32(0));
}
std::string PcmEncoder::name() const
{
return "pcm";
}
} // namespace encoder
| 2,694
|
C++
|
.cpp
| 72
| 34.138889
| 110
| 0.712913
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
24,980
|
stream.cpp
|
badaix_snapcast/client/stream.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef NOMINMAX
#define NOMINMAX
#endif // NOMINMAX
// prototype/interface header file
#include "stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "time_provider.hpp"
// 3rd party headers
// standard headers
#include <cmath>
#include <cstring>
#include <iostream>
using namespace std;
namespace cs = chronos;
static constexpr auto LOG_TAG = "Stream";
static constexpr auto kCorrectionBegin = 100us;
// #define LOG_LATENCIES
Stream::Stream(const SampleFormat& in_format, const SampleFormat& out_format)
: in_format_(in_format), median_(0), shortMedian_(0), lastUpdate_(0), playedFrames_(0), correctAfterXFrames_(0), bufferMs_(cs::msec(500)), frame_delta_(0),
hard_sync_(true), time_cond_(1s)
{
buffer_.setSize(500);
shortBuffer_.setSize(100);
miniBuffer_.setSize(20);
latencies_.setSize(100);
format_ = in_format_;
if (out_format.isInitialized())
{
format_.setFormat(out_format.rate() != 0 ? out_format.rate() : format_.rate(), out_format.bits() != 0 ? out_format.bits() : format_.bits(),
out_format.channels() != 0 ? out_format.channels() : format_.channels());
}
/*
48000 x
------- = -----
47999,2 x - 1
x = 1,000016667 / (1,000016667 - 1)
*/
// setRealSampleRate(format_.rate());
resampler_ = std::make_unique<Resampler>(in_format_, format_);
}
void Stream::setRealSampleRate(double sampleRate)
{
if (sampleRate == format_.rate())
{
correctAfterXFrames_ = 0;
}
else
{
correctAfterXFrames_ = static_cast<int32_t>(round((format_.rate() / sampleRate) / (format_.rate() / sampleRate - 1.)));
// LOG(TRACE, LOG_TAG) << "Correct after X: " << correctAfterXFrames_ << " (Real rate: " << sampleRate << ", rate: " << format_.rate() << ")\n";
}
}
void Stream::setBufferLen(size_t bufferLenMs)
{
bufferMs_.store(cs::msec(bufferLenMs));
}
void Stream::clearChunks()
{
std::lock_guard<std::mutex> lock(mutex_);
while (!chunks_.empty())
chunks_.pop();
resetBuffers();
}
void Stream::addChunk(unique_ptr<msg::PcmChunk> chunk)
{
// drop chunk if it's too old. Just in case, this shouldn't happen.
auto age = std::chrono::duration_cast<cs::msec>(TimeProvider::serverNow() - chunk->start());
if (age > 5s + bufferMs_.load())
return;
auto resampled = resampler_->resample(std::move(chunk));
if (resampled)
{
std::lock_guard<std::mutex> lock(mutex_);
recent_ = resampled;
chunks_.push(resampled);
std::shared_ptr<msg::PcmChunk> front_;
while (chunks_.front_copy(front_))
{
age = std::chrono::duration_cast<cs::msec>(TimeProvider::serverNow() - front_->start());
if ((age > 5s + bufferMs_.load()) && chunks_.try_pop(front_))
LOG(TRACE, LOG_TAG) << "Oldest chunk too old: " << age.count() << " ms, removing. Chunks in queue left: " << chunks_.size() << "\n";
else
break;
}
}
// LOG(TRACE, LOG_TAG) << "new chunk: " << chunk->durationMs() << " ms, age: " << age.count() << " ms, Chunks: " << chunks_.size() << "\n";
}
bool Stream::waitForChunk(const std::chrono::milliseconds& timeout) const
{
return chunks_.wait_for(timeout);
}
void Stream::getSilentPlayerChunk(void* outputBuffer, uint32_t frames) const
{
memset(outputBuffer, 0, frames * format_.frameSize());
}
cs::time_point_clk Stream::getNextPlayerChunk(void* outputBuffer, uint32_t frames)
{
if (!chunk_ && !chunks_.try_pop(chunk_))
throw SnapException("No chunks available, requested frames: " + cpt::to_string(frames));
cs::time_point_clk tp = chunk_->start();
uint32_t read = 0;
while (read < frames)
{
read += chunk_->readFrames(static_cast<char*>(outputBuffer) + read * format_.frameSize(), frames - read);
if ((read < frames) && chunk_->isEndOfChunk() && !chunks_.try_pop(chunk_))
throw SnapException("Not enough frames available, requested frames: " + cpt::to_string(frames) + ", available: " + cpt::to_string(read));
}
return tp;
}
cs::time_point_clk Stream::getNextPlayerChunk(void* outputBuffer, uint32_t frames, int32_t framesCorrection)
{
if (framesCorrection < 0 && (static_cast<int32_t>(frames) + framesCorrection <= 0))
{
// Avoid underflow in new char[] constructor.
framesCorrection = -static_cast<int32_t>(frames) + 1;
}
if (framesCorrection == 0)
return getNextPlayerChunk(outputBuffer, frames);
frame_delta_ -= framesCorrection;
uint32_t toRead = frames + framesCorrection;
if (toRead * format_.frameSize() > read_buffer_.size())
read_buffer_.resize(toRead * format_.frameSize());
cs::time_point_clk tp = getNextPlayerChunk(read_buffer_.data(), toRead);
const auto max = framesCorrection < 0 ? frames : toRead;
// Divide the buffer into one more slice than frames that need to be dropped.
// We will drop/repeat 0 frames from the first slice, 1 frame from the second, ..., and framesCorrection frames from the last slice.
size_t slices = abs(framesCorrection) + 1;
if (slices > max)
{
// We cannot have more slices than frames, because that would cause
// size = 0 -> pos = 0 -> pos - n < 0 in the loop below
// Overwriting slices effectively corrects less frames than asked for in framesCorrection.
slices = max;
}
// Size of each slice. The last slice may be bigger.
auto size = max / slices;
// LOG(TRACE, LOG_TAG) << "getNextPlayerChunk, frames: " << frames << ", correction: " << framesCorrection << " (" << toRead << "), slices: " << slices
// << "\n";
size_t pos = 0;
for (size_t n = 0; n < slices; ++n)
{
// Adjust size in the last iteration, because the last slice may be bigger
if (n + 1 == slices)
size = max - pos;
if (framesCorrection < 0)
{
// Read one frame less per slice from the input, but write a duplicated frame per slice to the output
// LOG(TRACE, LOG_TAG) << "duplicate - requested: " << frames << ", read: " << toRead << ", slice: " << n << ", size: " << size << ", out pos: " <<
// pos << ", source pos: " << pos - n << "\n";
memcpy(static_cast<char*>(outputBuffer) + pos * format_.frameSize(), read_buffer_.data() + (pos - n) * format_.frameSize(),
size * format_.frameSize());
}
// -- --
// - - - -
// - - - -
// - -- -
// -- --
// - - - -
// - -- - -
// - -- -
// -- --
// - - - -
// - -_ - -
// - -- -
else
{
// Read all input frames, but skip a frame per slice when writing to the output.
// LOG(TRACE, LOG_TAG) << "remove - requested: " << frames << ", read: " << toRead << ", slice: " << n << ", size: " << size << ", out pos: " << pos
// - n << ", source pos: " << pos << "\n";
memcpy(static_cast<char*>(outputBuffer) + (pos - n) * format_.frameSize(), read_buffer_.data() + pos * format_.frameSize(),
size * format_.frameSize());
}
pos += size;
}
return tp;
}
void Stream::updateBuffers(chronos::usec::rep age)
{
buffer_.add(age);
miniBuffer_.add(age);
shortBuffer_.add(age);
}
void Stream::resetBuffers()
{
buffer_.clear();
miniBuffer_.clear();
shortBuffer_.clear();
}
bool Stream::getPlayerChunk(void* outputBuffer, const cs::usec& outputBufferDacTime, uint32_t frames)
{
if (outputBufferDacTime > bufferMs_.load())
{
LOG(INFO, LOG_TAG) << "outputBufferDacTime > bufferMs: " << cs::duration<cs::msec>(outputBufferDacTime) << " > "
<< cs::duration<cs::msec>(bufferMs_.load()) << "\n";
return false;
}
std::lock_guard<std::mutex> lock(mutex_);
time_t now = time(nullptr);
if (!chunk_ && !chunks_.try_pop(chunk_))
{
if (now != lastUpdate_)
{
lastUpdate_ = now;
LOG(INFO, LOG_TAG) << "No chunks available\n";
}
return false;
}
#ifdef LOG_LATENCIES
// calculate the estimated end to end latency
if (recent_)
{
cs::nsec req_chunk_duration = cs::nsec(static_cast<cs::nsec::rep>(frames / format_.nsRate()));
auto youngest = recent_->end() - req_chunk_duration;
cs::msec age = std::chrono::duration_cast<cs::msec>(TimeProvider::serverNow() - youngest + outputBufferDacTime);
latencies_.add(age.count());
}
#endif
/// we have a chunk
/// age = chunk age (server now - rec time: some positive value) - buffer (e.g. 1000ms) + time to DAC
/// age = 0 => play now
/// age < 0 => play in -age => wait for a while, play silence in the meantime
/// age > 0 => too old => throw them away
try
{
if (hard_sync_)
{
cs::nsec req_chunk_duration = cs::nsec(static_cast<cs::nsec::rep>(frames / format_.nsRate()));
cs::usec age = std::chrono::duration_cast<cs::usec>(TimeProvider::serverNow() - chunk_->start()) - bufferMs_.load() + outputBufferDacTime;
// LOG(INFO, LOG_TAG) << "age: " << age.count() / 1000 << ", buffer: " <<
// std::chrono::duration_cast<chrono::milliseconds>(req_chunk_duration).count() << "\n";
if (age < -req_chunk_duration)
{
// the oldest chunk (top of the stream) is too young for the buffer
// e.g. age = -100ms (=> should be played in 100ms)
// but the requested chunk duration is 50ms, so there is not data in this iteration available
getSilentPlayerChunk(outputBuffer, frames);
return true;
}
else
{
if (age.count() > 0)
{
LOG(DEBUG, LOG_TAG) << "age > 0: " << age.count() / 1000 << "ms, dropping old chunks\n";
// age > 0: the top of the stream is too old. We must fast foward.
// delete the current chunk, it's too old. This will avoid an endless loop if there is no chunk in the queue.
chunk_ = nullptr;
while (chunks_.try_pop(chunk_))
{
age = std::chrono::duration_cast<cs::usec>(TimeProvider::serverNow() - chunk_->start()) - bufferMs_.load() + outputBufferDacTime;
LOG(DEBUG, LOG_TAG) << "age: " << age.count() / 1000 << ", requested chunk_duration: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(req_chunk_duration).count()
<< ", duration: " << chunk_->duration<std::chrono::milliseconds>().count() << "\n";
// check if the current chunk's end is older than age => can be player
if ((age.count() > 0) && (age < chunk_->duration<cs::usec>()))
{
// fast forward by "age" to get in sync, i.e. age = 0
chunk_->seek(static_cast<uint32_t>(chunk_->format.nsRate() * std::chrono::duration_cast<cs::nsec>(age).count()));
age = 0s;
}
if (age.count() <= 0)
break;
}
}
if (age.count() <= 0)
{
// the oldest chunk (top of the stream) can be played in this iteration
// e.g. age = -20ms (=> should be played in 20ms)
// and the current chunk duration is 50ms, so we need to play 20ms silence (as we don't have data)
// and can play 30ms of the stream
uint32_t silent_frames = static_cast<uint32_t>(-chunk_->format.nsRate() * std::chrono::duration_cast<cs::nsec>(age).count());
bool result = (silent_frames <= frames);
silent_frames = std::min(silent_frames, frames);
if (silent_frames > 0)
{
LOG(DEBUG, LOG_TAG) << "Silent frames: " << silent_frames << ", frames: " << frames
<< ", age: " << std::chrono::duration_cast<cs::usec>(age).count() / 1000. << "\n";
getSilentPlayerChunk(outputBuffer, silent_frames);
}
getNextPlayerChunk(static_cast<char*>(outputBuffer) + (chunk_->format.frameSize() * silent_frames), frames - silent_frames);
if (result)
{
hard_sync_ = false;
resetBuffers();
}
return true;
}
return false;
}
}
// sample rate correction
// framesCorrection = number of frames to be read more or less to get in-sync
int32_t framesCorrection = 0;
if (correctAfterXFrames_ != 0)
{
playedFrames_ += frames;
if (playedFrames_ >= static_cast<uint32_t>(abs(correctAfterXFrames_)))
{
framesCorrection = static_cast<int32_t>(playedFrames_) / correctAfterXFrames_;
playedFrames_ %= abs(correctAfterXFrames_);
}
}
cs::usec age = std::chrono::duration_cast<cs::usec>(TimeProvider::serverNow() - getNextPlayerChunk(outputBuffer, frames, framesCorrection) -
bufferMs_.load() + outputBufferDacTime);
setRealSampleRate(format_.rate());
// check if we need a hard sync
if (buffer_.full() && (cs::usec(abs(median_)) > cs::msec(2)) && (cs::abs(age) > cs::usec(500)))
{
LOG(INFO, LOG_TAG) << "pBuffer->full() && (abs(median_) > 2): " << median_ << "\n";
hard_sync_ = true;
}
else if (shortBuffer_.full() && (cs::usec(abs(shortMedian_)) > cs::msec(5)) && (cs::abs(age) > cs::usec(500)))
{
LOG(INFO, LOG_TAG) << "pShortBuffer->full() && (abs(shortMedian_) > 5): " << shortMedian_ << "\n";
hard_sync_ = true;
}
else if (miniBuffer_.full() && (cs::usec(abs(miniBuffer_.median())) > cs::msec(50)) && (cs::abs(age) > cs::usec(500)))
{
LOG(INFO, LOG_TAG) << "pMiniBuffer->full() && (abs(pMiniBuffer->mean()) > 50): " << miniBuffer_.median() << "\n";
hard_sync_ = true;
}
else if (cs::abs(age) > 500ms)
{
LOG(INFO, LOG_TAG) << "abs(age > 500): " << cs::abs(age).count() << "\n";
hard_sync_ = true;
}
else if (shortBuffer_.full())
{
// No hard sync needed
// Check if we need a samplerate correction (change playback speed (soft sync))
auto miniMedian = miniBuffer_.median();
if ((cs::usec(shortMedian_) > kCorrectionBegin) && (cs::usec(miniMedian) > cs::usec(50)) && (cs::usec(age) > cs::usec(50)))
{
double rate = (shortMedian_ / 100.) * 0.00005;
rate = 1.0 - std::min(rate, 0.0005);
// LOG(INFO, LOG_TAG) << "Rate: " << rate << "\n";
// we are late (age > 0), this means we are not playing fast enough
// => the real sample rate seems to be lower, we have to drop some frames
setRealSampleRate(format_.rate() * rate); // 0.9999);
}
else if ((cs::usec(shortMedian_) < -kCorrectionBegin) && (cs::usec(miniMedian) < -cs::usec(50)) && (cs::usec(age) < -cs::usec(50)))
{
double rate = (-shortMedian_ / 100.) * 0.00005;
rate = 1.0 + std::min(rate, 0.0005);
// LOG(INFO, LOG_TAG) << "Rate: " << rate << "\n";
// we are early (age > 0), this means we are playing too fast
// => the real sample rate seems to be higher, we have to insert some frames
setRealSampleRate(format_.rate() * rate); // 1.0001);
}
}
updateBuffers(age.count());
// update median_ and shortMedian_ and print sync stats
if (now != lastUpdate_)
{
// log buffer stats
lastUpdate_ = now;
median_ = buffer_.median();
shortMedian_ = shortBuffer_.median();
LOG(DEBUG, "Stats") << "Chunk: " << age.count() / 100 << "\t" << miniBuffer_.median() / 100 << "\t" << shortMedian_ / 100 << "\t" << median_ / 100
<< "\t" << buffer_.size() << "\t" << cs::duration<cs::msec>(outputBufferDacTime) << "\t" << frame_delta_ << "\n";
frame_delta_ = 0;
#ifdef LOG_LATENCIES
// log latencies
std::array<uint8_t, 5> percents = {100, 99, 95, 50, 5};
auto percentiles = latencies_.percentiles(percents);
std::stringstream ss;
for (std::size_t n = 0; n < percents.size(); ++n)
ss << ((n > 0) ? ", " : "") << (int)percents[n] << "%: " << percentiles[n];
LOG(DEBUG, "Latency") << ss.str() << "\n";
#endif
}
return (abs(cs::duration<cs::msec>(age)) < 500);
}
catch (const std::exception& e)
{
LOG(INFO, LOG_TAG) << "Exception: " << e.what() << "\n";
hard_sync_ = true;
return false;
}
}
bool Stream::getPlayerChunkOrSilence(void* outputBuffer, const chronos::usec& outputBufferDacTime, uint32_t frames)
{
bool result = getPlayerChunk(outputBuffer, outputBufferDacTime, frames);
if (!result)
{
LOG(DEBUG, LOG_TAG) << time_cond_ << "Failed to get chunk, returning silence\n";
getSilentPlayerChunk(outputBuffer, frames);
}
return result;
}
| 18,914
|
C++
|
.cpp
| 406
| 36.810345
| 160
| 0.547121
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,981
|
client_connection.cpp
|
badaix_snapcast/client/client_connection.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "client_connection.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/str_compat.hpp"
// 3rd party headers
#include <boost/asio/read.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/write.hpp>
// standard headers
#include <iostream>
using namespace std;
static constexpr auto LOG_TAG = "Connection";
PendingRequest::PendingRequest(const boost::asio::strand<boost::asio::any_io_executor>& strand, uint16_t reqId, const MessageHandler<msg::BaseMessage>& handler)
: id_(reqId), timer_(strand), strand_(strand), handler_(handler)
{
}
PendingRequest::~PendingRequest()
{
handler_ = nullptr;
timer_.cancel();
}
void PendingRequest::setValue(std::unique_ptr<msg::BaseMessage> value)
{
boost::asio::post(strand_,
[this, self = shared_from_this(), val = std::move(value)]() mutable
{
timer_.cancel();
if (handler_)
handler_({}, std::move(val));
});
}
uint16_t PendingRequest::id() const
{
return id_;
}
void PendingRequest::startTimer(const chronos::usec& timeout)
{
timer_.expires_after(timeout);
timer_.async_wait(
[this, self = shared_from_this()](boost::system::error_code ec)
{
if (!handler_)
return;
if (!ec)
{
// !ec => expired => timeout
handler_(boost::asio::error::timed_out, nullptr);
handler_ = nullptr;
}
else if (ec != boost::asio::error::operation_aborted)
{
// ec != aborted => not cancelled (in setValue)
// => should not happen, but who knows => pass the error to the handler
handler_(ec, nullptr);
}
});
}
bool PendingRequest::operator<(const PendingRequest& other) const
{
return (id_ < other.id());
}
ClientConnection::ClientConnection(boost::asio::io_context& io_context, const ClientSettings::Server& server)
: strand_(boost::asio::make_strand(io_context.get_executor())), resolver_(strand_), socket_(strand_), reqId_(1), server_(server)
{
base_msg_size_ = base_message_.getSize();
buffer_.resize(base_msg_size_);
}
ClientConnection::~ClientConnection()
{
disconnect();
}
std::string ClientConnection::getMacAddress()
{
std::string mac =
#ifndef WINDOWS
::getMacAddress(socket_.native_handle());
#else
::getMacAddress(socket_.local_endpoint().address().to_string());
#endif
if (mac.empty())
mac = "00:00:00:00:00:00";
LOG(INFO, LOG_TAG) << "My MAC: \"" << mac << "\", socket: " << socket_.native_handle() << "\n";
return mac;
}
void ClientConnection::connect(const ResultHandler& handler)
{
tcp::resolver::query query(server_.host, cpt::to_string(server_.port), boost::asio::ip::resolver_query_base::numeric_service);
boost::system::error_code ec;
LOG(INFO, LOG_TAG) << "Resolving host IP for: " << server_.host << "\n";
auto iterator = resolver_.resolve(query, ec);
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to resolve host '" << server_.host << "', error: " << ec.message() << "\n";
handler(ec);
return;
}
for (const auto& iter : iterator)
LOG(DEBUG, LOG_TAG) << "Resolved IP: " << iter.endpoint().address().to_string() << "\n";
for (const auto& iter : iterator)
{
LOG(INFO, LOG_TAG) << "Connecting to " << iter.endpoint() << "\n";
socket_.connect(*iterator, ec);
if (!ec || (ec == boost::system::errc::interrupted))
{
// We were successful or interrupted, e.g. by sig int
break;
}
}
if (ec)
LOG(ERROR, LOG_TAG) << "Failed to connect to host '" << server_.host << "', error: " << ec.message() << "\n";
else
LOG(NOTICE, LOG_TAG) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl;
handler(ec);
#if 0
resolver_.async_resolve(query, host_, cpt::to_string(port_), [this, handler](const boost::system::error_code& ec, tcp::resolver::results_type results) {
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to resolve host '" << host_ << "', error: " << ec.message() << "\n";
handler(ec);
return;
}
resolver_.cancel();
socket_.async_connect(*results, [this, handler](const boost::system::error_code& ec) {
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to connect to host '" << host_ << "', error: " << ec.message() << "\n";
handler(ec);
return;
}
LOG(NOTICE, LOG_TAG) << "Connected to " << socket_.remote_endpoint().address().to_string() << endl;
handler(ec);
getNextMessage();
});
});
#endif
}
void ClientConnection::disconnect()
{
LOG(DEBUG, LOG_TAG) << "Disconnecting\n";
if (!socket_.is_open())
{
LOG(DEBUG, LOG_TAG) << "Not connected\n";
return;
}
boost::system::error_code ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
if (ec)
LOG(ERROR, LOG_TAG) << "Error in socket shutdown: " << ec.message() << endl;
socket_.close(ec);
if (ec)
LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << endl;
boost::asio::post(strand_, [this]() { pendingRequests_.clear(); });
LOG(DEBUG, LOG_TAG) << "Disconnected\n";
}
void ClientConnection::sendNext()
{
auto& message = messages_.front();
static boost::asio::streambuf streambuf;
std::ostream stream(&streambuf);
tv t;
message.msg->sent = t;
message.msg->serialize(stream);
auto handler = message.handler;
boost::asio::async_write(socket_, streambuf,
[this, handler](boost::system::error_code ec, std::size_t length)
{
if (ec)
LOG(ERROR, LOG_TAG) << "Failed to send message, error: " << ec.message() << "\n";
else
LOG(TRACE, LOG_TAG) << "Wrote " << length << " bytes to socket\n";
messages_.pop_front();
if (handler)
handler(ec);
if (!messages_.empty())
sendNext();
});
}
void ClientConnection::send(const msg::message_ptr& message, const ResultHandler& handler)
{
boost::asio::post(strand_,
[this, message, handler]()
{
messages_.emplace_back(message, handler);
if (messages_.size() > 1)
{
LOG(DEBUG, LOG_TAG) << "outstanding async_write\n";
return;
}
sendNext();
});
}
void ClientConnection::sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler<msg::BaseMessage>& handler)
{
boost::asio::post(strand_,
[this, message, timeout, handler]()
{
pendingRequests_.erase(
std::remove_if(pendingRequests_.begin(), pendingRequests_.end(), [](std::weak_ptr<PendingRequest> request) { return request.expired(); }),
pendingRequests_.end());
unique_ptr<msg::BaseMessage> response(nullptr);
if (++reqId_ >= 10000)
reqId_ = 1;
message->id = reqId_;
auto request = make_shared<PendingRequest>(strand_, reqId_, handler);
pendingRequests_.push_back(request);
request->startTimer(timeout);
send(message,
[handler](const boost::system::error_code& ec)
{
if (ec)
handler(ec, nullptr);
});
});
}
void ClientConnection::getNextMessage(const MessageHandler<msg::BaseMessage>& handler)
{
boost::asio::async_read(socket_, boost::asio::buffer(buffer_, base_msg_size_),
[this, handler](boost::system::error_code ec, std::size_t length) mutable
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error reading message header of length " << length << ": " << ec.message() << "\n";
if (handler)
handler(ec, nullptr);
return;
}
base_message_.deserialize(buffer_.data());
tv t;
base_message_.received = t;
// LOG(TRACE, LOG_TAG) << "getNextMessage: " << base_message_.type << ", size: " << base_message_.size << ", id: " <<
// base_message_.id << ", refers: " << base_message_.refersTo << "\n";
if (base_message_.type > message_type::kLast)
{
LOG(ERROR, LOG_TAG) << "unknown message type received: " << base_message_.type << ", size: " << base_message_.size << "\n";
if (handler)
handler(boost::asio::error::invalid_argument, nullptr);
return;
}
else if (base_message_.size > msg::max_size)
{
LOG(ERROR, LOG_TAG) << "received message of type " << base_message_.type << " to large: " << base_message_.size << "\n";
if (handler)
handler(boost::asio::error::invalid_argument, nullptr);
return;
}
if (base_message_.size > buffer_.size())
buffer_.resize(base_message_.size);
boost::asio::async_read(socket_, boost::asio::buffer(buffer_, base_message_.size),
[this, handler](boost::system::error_code ec, std::size_t length) mutable
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error reading message body of length " << length << ": " << ec.message() << "\n";
if (handler)
handler(ec, nullptr);
return;
}
auto response = msg::factory::createMessage(base_message_, buffer_.data());
if (!response)
LOG(WARNING, LOG_TAG) << "Failed to deserialize message of type: " << base_message_.type << "\n";
for (auto iter = pendingRequests_.begin(); iter != pendingRequests_.end(); ++iter)
{
auto request = *iter;
if (auto req = request.lock())
{
if (req->id() == base_message_.refersTo)
{
req->setValue(std::move(response));
pendingRequests_.erase(iter);
getNextMessage(handler);
return;
}
}
}
if (handler)
handler(ec, std::move(response));
});
});
}
| 11,337
|
C++
|
.cpp
| 294
| 29.908163
| 160
| 0.564814
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,982
|
snapclient.cpp
|
badaix_snapcast/client/snapclient.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// local headers
#include "common/popl.hpp"
#include "controller.hpp"
#ifdef HAS_ALSA
#include "player/alsa_player.hpp"
#endif
#ifdef HAS_PULSE
#include "player/pulse_player.hpp"
#endif
#ifdef HAS_WASAPI
#include "player/wasapi_player.hpp"
#endif
#include "player/file_player.hpp"
#ifdef HAS_DAEMON
#include "common/daemon.hpp"
#endif
#include "client_settings.hpp"
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/version.hpp"
// 3rd party headers
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/signal_set.hpp>
// standard headers
#include <iostream>
#ifndef WINDOWS
#include <csignal>
#include <sys/resource.h>
#endif
using namespace std;
using namespace popl;
using namespace player;
using namespace std::chrono_literals;
static constexpr auto LOG_TAG = "Snapclient";
PcmDevice getPcmDevice(const std::string& player, const std::string& parameter, const std::string& soundcard)
{
LOG(DEBUG, LOG_TAG) << "Trying to get PCM device for player: " << player << ", parameter: "
<< ", card: " << soundcard << "\n";
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI)
vector<PcmDevice> pcm_devices;
#if defined(HAS_ALSA)
if (player == player::ALSA)
pcm_devices = AlsaPlayer::pcm_list();
#endif
#if defined(HAS_PULSE)
if (player == player::PULSE)
pcm_devices = PulsePlayer::pcm_list(parameter);
#endif
#if defined(HAS_WASAPI)
if (player == player::WASAPI)
pcm_devices = WASAPIPlayer::pcm_list();
#endif
if (player == player::FILE)
return FilePlayer::pcm_list(parameter).front();
try
{
int soundcardIdx = cpt::stoi(soundcard);
for (auto dev : pcm_devices)
if (dev.idx == soundcardIdx)
return dev;
}
catch (...)
{
}
for (auto dev : pcm_devices)
if (dev.name.find(soundcard) != string::npos)
return dev;
#endif
std::ignore = player;
std::ignore = parameter;
PcmDevice pcm_device;
pcm_device.name = soundcard;
return pcm_device;
}
#ifdef WINDOWS
// hack to avoid case destinction in the signal handler
#define SIGHUP SIGINT
const char* strsignal(int sig)
{
switch (sig)
{
case SIGTERM:
return "SIGTERM";
case SIGINT:
return "SIGINT";
case SIGBREAK:
return "SIGBREAK";
case SIGABRT:
return "SIGABRT";
default:
return "Unhandled";
}
}
#endif
int main(int argc, char** argv)
{
#ifdef MACOS
#pragma message "Warning: the macOS support is experimental and might not be maintained"
#endif
int exitcode = EXIT_SUCCESS;
try
{
ClientSettings settings;
string pcm_device(player::DEFAULT_DEVICE);
OptionParser op("Allowed options");
auto helpSwitch = op.add<Switch>("", "help", "produce help message");
auto groffSwitch = op.add<Switch, Attribute::hidden>("", "groff", "produce groff message");
auto versionSwitch = op.add<Switch>("v", "version", "show version number");
op.add<Value<string>>("h", "host", "server hostname or ip address", "", &settings.server.host);
op.add<Value<size_t>>("p", "port", "server port", 1704, &settings.server.port);
op.add<Value<size_t>>("i", "instance", "instance id when running multiple instances on the same host", 1, &settings.instance);
op.add<Value<string>>("", "hostID", "unique host id, default is MAC address", "", &settings.host_id);
// PCM device specific
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI)
auto listSwitch = op.add<Switch>("l", "list", "list PCM devices");
/*auto soundcardValue =*/op.add<Value<string>>("s", "soundcard", "index or name of the pcm device", pcm_device, &pcm_device);
#endif
/*auto latencyValue =*/op.add<Value<int>>("", "latency", "latency of the PCM device", 0, &settings.player.latency);
#ifdef HAS_SOXR
auto sample_format = op.add<Value<string>>("", "sampleformat", "resample audio stream to <rate>:<bits>:<channels>", "");
#endif
auto supported_players = Controller::getSupportedPlayerNames();
string supported_players_str;
for (const auto& supported_player : supported_players)
supported_players_str += (!supported_players_str.empty() ? "|" : "") + supported_player;
op.add<Value<string>>("", "player", supported_players_str + "[:<options>|?]", supported_players.front(), &settings.player.player_name);
// sharing mode
#if defined(HAS_OBOE) || defined(HAS_WASAPI)
auto sharing_mode = op.add<Value<string>>("", "sharingmode", "audio mode to use [shared|exclusive]", "shared");
#endif
// mixer
bool hw_mixer_supported = false;
#if defined(HAS_ALSA)
hw_mixer_supported = true;
#endif
std::shared_ptr<popl::Value<std::string>> mixer_mode;
std::string mixers = "software";
if (hw_mixer_supported)
mixers += "|hardware";
#ifdef SUPPORTS_VOLUME_SCRIPT
mixers += "|script";
#endif
mixer_mode = op.add<Value<string>>("", "mixer", mixers + "|none|?[:<options>]", "software");
// daemon settings
#ifdef HAS_DAEMON
int processPriority(-3);
auto daemonOption = op.add<Implicit<int>>("d", "daemon", "daemonize, optional process priority [-20..19]", processPriority, &processPriority);
auto userValue = op.add<Value<string>>("", "user", "the user[:group] to run snapclient as when daemonized");
#endif
// logging
op.add<Value<string>>("", "logsink", "log sink [null,system,stdout,stderr,file:<filename>]", settings.logging.sink, &settings.logging.sink);
auto logfilterOption = op.add<Value<string>>(
"", "logfilter", "log filter <tag>:<level>[,<tag>:<level>]* with tag = * or <log tag> and level = [trace,debug,info,notice,warning,error,fatal]",
settings.logging.filter);
try
{
op.parse(argc, argv);
}
catch (const std::invalid_argument& e)
{
cerr << "Exception: " << e.what() << std::endl;
cout << "\n" << op << "\n";
exit(EXIT_FAILURE);
}
if (versionSwitch->is_set())
{
cout << "snapclient v" << version::code << (!version::rev().empty() ? (" (rev " + version::rev(8) + ")") : ("")) << "\n"
<< "Copyright (C) 2014-2024 BadAix (snapcast@badaix.de).\n"
<< "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.\n"
<< "This is free software: you are free to change and redistribute it.\n"
<< "There is NO WARRANTY, to the extent permitted by law.\n\n"
<< "Written by Johannes M. Pohl and contributors <https://github.com/badaix/snapcast/graphs/contributors>.\n\n";
exit(EXIT_SUCCESS);
}
settings.player.player_name = utils::string::split_left(settings.player.player_name, ':', settings.player.parameter);
#if defined(HAS_ALSA) || defined(HAS_PULSE) || defined(HAS_WASAPI)
if (listSwitch->is_set())
{
try
{
vector<PcmDevice> pcm_devices;
#if defined(HAS_ALSA)
if (settings.player.player_name == player::ALSA)
pcm_devices = AlsaPlayer::pcm_list();
#endif
#if defined(HAS_PULSE)
if (settings.player.player_name == player::PULSE)
pcm_devices = PulsePlayer::pcm_list(settings.player.parameter);
#endif
#if defined(HAS_WASAPI)
if (settings.player.player_name == player::WASAPI)
pcm_devices = WASAPIPlayer::pcm_list();
#endif
#ifdef WINDOWS
// Set console code page to UTF-8 so console known how to interpret string data
SetConsoleOutputCP(CP_UTF8);
// Enable buffering to prevent VS from chopping up UTF-8 byte sequences
setvbuf(stdout, nullptr, _IOFBF, 1000);
#endif
for (const auto& dev : pcm_devices)
cout << dev.idx << ": " << dev.name << "\n" << dev.description << "\n\n";
if (pcm_devices.empty())
cout << "No PCM device available for audio backend \"" << settings.player.player_name << "\"\n";
}
catch (const std::exception& e)
{
cout << "Failed to get device list: " << e.what() << "\n";
}
exit(EXIT_SUCCESS);
}
#endif
if (helpSwitch->is_set())
{
cout << op << "\n";
exit(EXIT_SUCCESS);
}
if (groffSwitch->is_set())
{
GroffOptionPrinter option_printer(&op);
cout << option_printer.print();
exit(EXIT_SUCCESS);
}
settings.logging.filter = logfilterOption->value();
if (logfilterOption->is_set())
{
for (size_t n = 1; n < logfilterOption->count(); ++n)
settings.logging.filter += "," + logfilterOption->value(n);
}
if (settings.logging.sink.empty())
{
settings.logging.sink = "stdout";
#ifdef HAS_DAEMON
if (daemonOption->is_set())
settings.logging.sink = "system";
#endif
}
AixLog::Filter logfilter;
auto filters = utils::string::split(settings.logging.filter, ',');
for (const auto& filter : filters)
logfilter.add_filter(filter);
string logformat = "%Y-%m-%d %H-%M-%S.#ms [#severity] (#tag_func)";
if (settings.logging.sink.find("file:") != string::npos)
{
string logfile = settings.logging.sink.substr(settings.logging.sink.find(':') + 1);
AixLog::Log::init<AixLog::SinkFile>(logfilter, logfile, logformat);
}
else if (settings.logging.sink == "stdout")
AixLog::Log::init<AixLog::SinkCout>(logfilter, logformat);
else if (settings.logging.sink == "stderr")
AixLog::Log::init<AixLog::SinkCerr>(logfilter, logformat);
else if (settings.logging.sink == "system")
AixLog::Log::init<AixLog::SinkNative>("snapclient", logfilter);
else if (settings.logging.sink == "null")
AixLog::Log::init<AixLog::SinkNull>();
else
throw SnapException("Invalid log sink: " + settings.logging.sink);
#if !defined(HAS_AVAHI) && !defined(HAS_BONJOUR)
if (settings.server.host.empty())
throw SnapException("Snapserver host not configured and mDNS not available, please configure with \"--host\".");
#endif
#ifdef HAS_DAEMON
std::unique_ptr<Daemon> daemon;
if (daemonOption->is_set())
{
string pidFile = "/var/run/snapclient/pid";
if (settings.instance != 1)
pidFile += "." + cpt::to_string(settings.instance);
string user;
string group;
if (userValue->is_set())
{
if (userValue->value().empty())
throw std::invalid_argument("user must not be empty");
vector<string> user_group = utils::string::split(userValue->value(), ':');
user = user_group[0];
if (user_group.size() > 1)
group = user_group[1];
}
daemon = std::make_unique<Daemon>(user, group, pidFile);
processPriority = std::min(std::max(-20, processPriority), 19);
if (processPriority != 0)
setpriority(PRIO_PROCESS, 0, processPriority);
LOG(NOTICE, LOG_TAG) << "daemonizing" << std::endl;
daemon->daemonize();
LOG(NOTICE, LOG_TAG) << "daemon started" << std::endl;
}
#endif
#ifdef HAS_SOXR
if (sample_format->is_set())
{
settings.player.sample_format = SampleFormat(sample_format->value());
if (settings.player.sample_format.channels() != 0)
throw SnapException("sampleformat channels must be * (= same as the source)");
auto bits = settings.player.sample_format.bits();
if ((bits != 0) && (bits != 16) && (bits != 24) && (bits != 32))
throw SnapException("sampleformat bits must be 16, 24, 32, * (= same as the source)");
}
#endif
#if defined(HAS_OBOE) || defined(HAS_WASAPI)
settings.player.sharing_mode = (sharing_mode->value() == "exclusive") ? ClientSettings::SharingMode::exclusive : ClientSettings::SharingMode::shared;
#endif
if (settings.player.parameter == "?")
{
if (settings.player.player_name == player::FILE)
{
cout << "Options are a comma separated list of:\n"
<< " \"filename=<filename>\" - with <filename> = \"stdout\", \"stderr\", \"null\" or a filename\n"
<< " \"mode=[w|a]\" - w: write (discarding the content), a: append (keeping the content)\n";
}
#ifdef HAS_PULSE
else if (settings.player.player_name == player::PULSE)
{
cout << "Options are a comma separated list of:\n"
<< " \"buffer_time=<buffer size [ms]>\" - default 100, min 10\n"
<< " \"server=<PulseAudio server>\" - default not-set: use the default server\n"
<< " \"property=<key>=<value>\" - can be set multiple times, default 'media.role=music'\n";
}
#endif
#ifdef HAS_ALSA
else if (settings.player.player_name == player::ALSA)
{
cout << "Options are a comma separated list of:\n"
<< " \"buffer_time=<total buffer size [ms]>\" - default 80, min 10\n"
<< " \"fragments=<number of buffers>\" - default 4, min 2\n";
}
#endif
else
{
cout << "No options available for \"" << settings.player.player_name << "\n";
}
exit(EXIT_SUCCESS);
}
settings.player.pcm_device = getPcmDevice(settings.player.player_name, settings.player.parameter, pcm_device);
#if defined(HAS_ALSA)
if (settings.player.pcm_device.idx == -1)
{
LOG(ERROR, LOG_TAG) << "PCM device \"" << pcm_device << "\" not found\n";
// exit(EXIT_FAILURE);
}
#endif
string mode = utils::string::split_left(mixer_mode->value(), ':', settings.player.mixer.parameter);
if (mode == "software")
settings.player.mixer.mode = ClientSettings::Mixer::Mode::software;
else if ((mode == "hardware") && hw_mixer_supported)
settings.player.mixer.mode = ClientSettings::Mixer::Mode::hardware;
#ifdef SUPPORTS_VOLUME_SCRIPT
else if (mode == "script")
settings.player.mixer.mode = ClientSettings::Mixer::Mode::script;
#endif
else if (mode == "none")
settings.player.mixer.mode = ClientSettings::Mixer::Mode::none;
else if ((mode == "?") || (mode == "help"))
{
cout << "mixer can be one of 'software', " << (hw_mixer_supported ? "'hardware', " : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
<< "'script', "
#endif
<< "'none'\n"
<< "followed by optional parameters:\n"
<< " * software[:poly[:<exponent>]|exp[:<base>]]\n"
<< (hw_mixer_supported ? " * hardware[:<mixer name>]\n" : "")
#ifdef SUPPORTS_VOLUME_SCRIPT
<< " * script[:<script filename>]"
#endif
<< "\n";
exit(EXIT_SUCCESS);
}
else
throw SnapException("Mixer mode not supported: " + mode);
boost::asio::io_context io_context;
// Construct a signal set registered for process termination.
boost::asio::signal_set signals(io_context, SIGHUP, SIGINT, SIGTERM);
signals.async_wait(
[&](const boost::system::error_code& ec, int signal)
{
if (!ec)
LOG(INFO, LOG_TAG) << "Received signal " << signal << ": " << strsignal(signal) << "\n";
else
LOG(INFO, LOG_TAG) << "Failed to wait for signal, error: " << ec.message() << "\n";
io_context.stop();
});
LOG(INFO, LOG_TAG) << "Version " << version::code << (!version::rev().empty() ? (", revision " + version::rev(8)) : ("")) << "\n";
auto controller = make_shared<Controller>(io_context, settings);
controller->start();
int num_threads = 0;
std::vector<std::thread> threads;
for (int n = 0; n < num_threads; ++n)
threads.emplace_back([&] { io_context.run(); });
io_context.run();
for (auto& t : threads)
t.join();
}
catch (const std::exception& e)
{
LOG(FATAL, LOG_TAG) << "Exception: " << e.what() << std::endl;
exitcode = EXIT_FAILURE;
}
LOG(NOTICE, LOG_TAG) << "Snapclient terminated." << endl;
exit(exitcode);
}
| 17,829
|
C++
|
.cpp
| 415
| 34.231325
| 157
| 0.586352
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,983
|
time_provider.cpp
|
badaix_snapcast/client/time_provider.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "time_provider.hpp"
// local headers
#include "common/aixlog.hpp"
// standard headers
#include <chrono>
static constexpr auto LOG_TAG = "TimeProvider";
TimeProvider::TimeProvider() : diffToServer_(0)
{
diffBuffer_.setSize(200);
}
void TimeProvider::setDiff(const tv& c2s, const tv& s2c)
{
// tv latency = c2s - s2c;
// double diff = (latency.sec * 1000. + latency.usec / 1000.) / 2.;
double diff = (static_cast<double>(c2s.sec) / 2. - static_cast<double>(s2c.sec) / 2.) * 1000. +
(static_cast<double>(c2s.usec) / 2. - static_cast<double>(s2c.usec) / 2.) / 1000.;
setDiffToServer(diff);
}
void TimeProvider::setDiffToServer(double ms)
{
using namespace std::chrono_literals;
auto now = std::chrono::system_clock::now();
static auto lastTimeSync = now;
auto diff = chronos::abs(now - lastTimeSync);
/// clear diffBuffer if last update is older than a minute
if (!diffBuffer_.empty() && (diff > 60s))
{
LOG(INFO, LOG_TAG) << "Last time sync older than a minute. Clearing time buffer\n";
diffToServer_ = static_cast<chronos::usec::rep>(ms * 1000);
diffBuffer_.clear();
}
lastTimeSync = now;
diffBuffer_.add(static_cast<chronos::usec::rep>(ms * 1000));
diffToServer_ = diffBuffer_.median();
// LOG(INFO, LOG_TAG) << "setDiffToServer: " << ms << ", diff: " << diffToServer_ / 1000000 << " s, " << (diffToServer_ / 1000) % 1000 << "." <<
// diffToServer_ % 1000 << " ms\n";
}
/*
long TimeProvider::getPercentileDiffToServer(size_t percentile)
{
return diffBuffer.percentile(percentile);
}
*/
| 2,403
|
C++
|
.cpp
| 58
| 37.241379
| 148
| 0.682403
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
24,984
|
controller.cpp
|
badaix_snapcast/client/controller.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef NOMINMAX
#define NOMINMAX
#endif // NOMINMAX
// prototype/interface header file
#include "controller.hpp"
// local headers
#include "decoder/null_decoder.hpp"
#include "decoder/pcm_decoder.hpp"
#if defined(HAS_OGG) && (defined(HAS_TREMOR) || defined(HAS_VORBIS))
#include "decoder/ogg_decoder.hpp"
#endif
#if defined(HAS_FLAC)
#include "decoder/flac_decoder.hpp"
#endif
#if defined(HAS_OPUS)
#include "decoder/opus_decoder.hpp"
#endif
#ifdef HAS_ALSA
#include "player/alsa_player.hpp"
#endif
#ifdef HAS_PULSE
#include "player/pulse_player.hpp"
#endif
#ifdef HAS_OPENSL
#include "player/opensl_player.hpp"
#endif
#ifdef HAS_OBOE
#include "player/oboe_player.hpp"
#endif
#ifdef HAS_COREAUDIO
#include "player/coreaudio_player.hpp"
#endif
#ifdef HAS_WASAPI
#include "player/wasapi_player.hpp"
#endif
#include "player/file_player.hpp"
#include "browseZeroConf/browse_mdns.hpp"
#include "common/aixlog.hpp"
#include "common/message/client_info.hpp"
#include "common/message/hello.hpp"
#include "common/message/time.hpp"
#include "common/snap_exception.hpp"
#include "time_provider.hpp"
// standard headers
#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
using namespace std;
using namespace player;
static constexpr auto LOG_TAG = "Controller";
static constexpr auto TIME_SYNC_INTERVAL = 1s;
Controller::Controller(boost::asio::io_context& io_context, const ClientSettings& settings) //, std::unique_ptr<MetadataAdapter> meta)
: io_context_(io_context), timer_(io_context), settings_(settings), stream_(nullptr), decoder_(nullptr), player_(nullptr),
serverSettings_(nullptr) // meta_(std::move(meta)),
{
}
template <typename PlayerType>
std::unique_ptr<Player> Controller::createPlayer(ClientSettings::Player& settings, const std::string& player_name)
{
if (settings.player_name.empty() || settings.player_name == player_name)
{
settings.player_name = player_name;
return make_unique<PlayerType>(io_context_, settings, stream_);
}
return nullptr;
}
std::vector<std::string> Controller::getSupportedPlayerNames()
{
std::vector<std::string> result;
#ifdef HAS_ALSA
result.emplace_back(player::ALSA);
#endif
#ifdef HAS_PULSE
result.emplace_back(player::PULSE);
#endif
#ifdef HAS_OBOE
result.emplace_back(player::OBOE);
#endif
#ifdef HAS_OPENSL
result.emplace_back(player::OPENSL);
#endif
#ifdef HAS_COREAUDIO
result.emplace_back(player::COREAUDIO);
#endif
#ifdef HAS_WASAPI
result.emplace_back(player::WASAPI);
#endif
result.emplace_back(player::FILE);
return result;
}
void Controller::getNextMessage()
{
clientConnection_->getNextMessage(
[this](const boost::system::error_code& ec, std::unique_ptr<msg::BaseMessage> response)
{
if (ec)
{
reconnect();
return;
}
if (!response)
{
return getNextMessage();
}
if (response->type == message_type::kWireChunk)
{
if (stream_ && decoder_)
{
// execute on the io_context to do the (costly) decoding on another thread (if more than one thread is used)
// boost::asio::post(io_context_, [this, response = std::move(response)]() mutable {
auto pcmChunk = msg::message_cast<msg::PcmChunk>(std::move(response));
pcmChunk->format = sampleFormat_;
// LOG(TRACE, LOG_TAG) << "chunk: " << pcmChunk->payloadSize << ", sampleFormat: " << sampleFormat_.toString() << "\n";
if (decoder_->decode(pcmChunk.get()))
{
// LOG(TRACE, LOG_TAG) << ", decoded: " << pcmChunk->payloadSize << ", Duration: " << pcmChunk->durationMs() << ", sec: " <<
// pcmChunk->timestamp.sec << ", usec: " << pcmChunk->timestamp.usec / 1000 << ", type: " << pcmChunk->type << "\n";
stream_->addChunk(std::move(pcmChunk));
}
// });
}
}
else if (response->type == message_type::kServerSettings)
{
serverSettings_ = msg::message_cast<msg::ServerSettings>(std::move(response));
LOG(INFO, LOG_TAG) << "ServerSettings - buffer: " << serverSettings_->getBufferMs() << ", latency: " << serverSettings_->getLatency()
<< ", volume: " << serverSettings_->getVolume() << ", muted: " << serverSettings_->isMuted() << "\n";
if (stream_ && player_)
{
player_->setVolume({serverSettings_->getVolume() / 100., serverSettings_->isMuted()});
stream_->setBufferLen(std::max(0, serverSettings_->getBufferMs() - serverSettings_->getLatency() - settings_.player.latency));
}
}
else if (response->type == message_type::kCodecHeader)
{
headerChunk_ = msg::message_cast<msg::CodecHeader>(std::move(response));
decoder_.reset(nullptr);
stream_ = nullptr;
player_.reset(nullptr);
if (headerChunk_->codec == "pcm")
decoder_ = make_unique<decoder::PcmDecoder>();
#if defined(HAS_OGG) && (defined(HAS_TREMOR) || defined(HAS_VORBIS))
else if (headerChunk_->codec == "ogg")
decoder_ = make_unique<decoder::OggDecoder>();
#endif
#if defined(HAS_FLAC)
else if (headerChunk_->codec == "flac")
decoder_ = make_unique<decoder::FlacDecoder>();
#endif
#if defined(HAS_OPUS)
else if (headerChunk_->codec == "opus")
decoder_ = make_unique<decoder::OpusDecoder>();
#endif
else if (headerChunk_->codec == "null")
decoder_ = make_unique<decoder::NullDecoder>();
else
throw SnapException("codec not supported: \"" + headerChunk_->codec + "\"");
sampleFormat_ = decoder_->setHeader(headerChunk_.get());
LOG(INFO, LOG_TAG) << "Codec: " << headerChunk_->codec << ", sampleformat: " << sampleFormat_.toString() << "\n";
stream_ = make_shared<Stream>(sampleFormat_, settings_.player.sample_format);
stream_->setBufferLen(std::max(0, serverSettings_->getBufferMs() - serverSettings_->getLatency() - settings_.player.latency));
#ifdef HAS_ALSA
if (!player_)
player_ = createPlayer<AlsaPlayer>(settings_.player, player::ALSA);
#endif
#ifdef HAS_PULSE
if (!player_)
player_ = createPlayer<PulsePlayer>(settings_.player, player::PULSE);
#endif
#ifdef HAS_OBOE
if (!player_)
player_ = createPlayer<OboePlayer>(settings_.player, player::OBOE);
#endif
#ifdef HAS_OPENSL
if (!player_)
player_ = createPlayer<OpenslPlayer>(settings_.player, player::OPENSL);
#endif
#ifdef HAS_COREAUDIO
if (!player_)
player_ = createPlayer<CoreAudioPlayer>(settings_.player, player::COREAUDIO);
#endif
#ifdef HAS_WASAPI
if (!player_)
player_ = createPlayer<WASAPIPlayer>(settings_.player, player::WASAPI);
#endif
if (!player_ && (settings_.player.player_name == player::FILE))
player_ = createPlayer<FilePlayer>(settings_.player, player::FILE);
if (!player_)
throw SnapException("No audio player support" + (settings_.player.player_name.empty() ? "" : " for: " + settings_.player.player_name));
player_->setVolumeCallback(
[this](const Player::Volume& volume)
{
// Cache the last volume and check if it really changed in the player's volume callback
static Player::Volume last_volume{-1, true};
if (volume != last_volume)
{
last_volume = volume;
auto info = std::make_shared<msg::ClientInfo>();
info->setVolume(static_cast<uint16_t>(volume.volume * 100.));
info->setMuted(volume.mute);
clientConnection_->send(info,
[this](const boost::system::error_code& ec)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to send client info, error: " << ec.message() << "\n";
reconnect();
return;
}
});
}
});
player_->start();
// Don't change the initial hardware mixer volume on the user's device.
// The player class will send the device's volume to the server instead
// if (settings_.player.mixer.mode != ClientSettings::Mixer::Mode::hardware)
// {
player_->setVolume({serverSettings_->getVolume() / 100., serverSettings_->isMuted()});
// }
}
else
{
LOG(WARNING, LOG_TAG) << "Unexpected message received, type: " << response->type << "\n";
}
getNextMessage();
});
}
void Controller::sendTimeSyncMessage(int quick_syncs)
{
auto timeReq = std::make_shared<msg::Time>();
clientConnection_->sendRequest<msg::Time>(timeReq, 2s,
[this, quick_syncs](const boost::system::error_code& ec, const std::unique_ptr<msg::Time>& response) mutable
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Time sync request failed: " << ec.message() << "\n";
reconnect();
return;
}
else
{
TimeProvider::getInstance().setDiff(response->latency, response->received - response->sent);
}
std::chrono::microseconds next = TIME_SYNC_INTERVAL;
if (quick_syncs > 0)
{
if (--quick_syncs == 0)
LOG(INFO, LOG_TAG) << "diff to server [ms]: "
<< static_cast<float>(TimeProvider::getInstance().getDiffToServer<chronos::usec>().count()) / 1000.f << "\n";
next = 100us;
}
timer_.expires_after(next);
timer_.async_wait(
[this, quick_syncs](const boost::system::error_code& ec)
{
if (!ec)
{
sendTimeSyncMessage(quick_syncs);
}
});
});
}
void Controller::browseMdns(const MdnsHandler& handler)
{
#if defined(HAS_AVAHI) || defined(HAS_BONJOUR)
try
{
BrowseZeroConf browser;
mDNSResult avahiResult;
if (browser.browse("_snapcast._tcp", avahiResult, 1000))
{
string host = avahiResult.ip;
uint16_t port = avahiResult.port;
if (avahiResult.ip_version == IPVersion::IPv6)
host += "%" + cpt::to_string(avahiResult.iface_idx);
handler({}, host, port);
return;
}
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << std::endl;
}
timer_.expires_after(500ms);
timer_.async_wait(
[this, handler](const boost::system::error_code& ec)
{
if (!ec)
{
browseMdns(handler);
}
else
{
handler(ec, "", 0);
}
});
#else
handler(boost::asio::error::operation_not_supported, "", 0);
#endif
}
void Controller::start()
{
if (settings_.server.host.empty())
{
browseMdns(
[this](const boost::system::error_code& ec, const std::string& host, uint16_t port)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to browse MDNS, error: " << ec.message() << "\n";
}
else
{
settings_.server.host = host;
settings_.server.port = port;
LOG(INFO, LOG_TAG) << "Found server " << settings_.server.host << ":" << settings_.server.port << "\n";
clientConnection_ = make_unique<ClientConnection>(io_context_, settings_.server);
worker();
}
});
}
else
{
clientConnection_ = make_unique<ClientConnection>(io_context_, settings_.server);
worker();
}
}
// void Controller::stop()
// {
// LOG(DEBUG, LOG_TAG) << "Stopping\n";
// timer_.cancel();
// }
void Controller::reconnect()
{
timer_.cancel();
clientConnection_->disconnect();
player_.reset();
stream_.reset();
decoder_.reset();
timer_.expires_after(1s);
timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (!ec)
{
worker();
}
});
}
void Controller::worker()
{
clientConnection_->connect(
[this](const boost::system::error_code& ec)
{
if (!ec)
{
// LOG(INFO, LOG_TAG) << "Connected!\n";
string macAddress = clientConnection_->getMacAddress();
if (settings_.host_id.empty())
settings_.host_id = ::getHostId(macAddress);
// Say hello to the server
auto hello = std::make_shared<msg::Hello>(macAddress, settings_.host_id, settings_.instance);
clientConnection_->sendRequest<msg::ServerSettings>(
hello, 2s,
[this](const boost::system::error_code& ec, std::unique_ptr<msg::ServerSettings> response) mutable
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Failed to send hello request, error: " << ec.message() << "\n";
reconnect();
return;
}
else
{
serverSettings_ = std::move(response);
LOG(INFO, LOG_TAG) << "ServerSettings - buffer: " << serverSettings_->getBufferMs() << ", latency: " << serverSettings_->getLatency()
<< ", volume: " << serverSettings_->getVolume() << ", muted: " << serverSettings_->isMuted() << "\n";
}
});
// Do initial time sync with the server
sendTimeSyncMessage(50);
// Start receiver loop
getNextMessage();
}
else
{
LOG(ERROR, LOG_TAG) << "Error: " << ec.message() << "\n";
reconnect();
}
});
}
| 15,281
|
C++
|
.cpp
| 406
| 28.401478
| 154
| 0.56699
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,985
|
coreaudio_player.cpp
|
badaix_snapcast/client/player/coreaudio_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2023 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "coreaudio_player.hpp"
// local headers
#include "common/aixlog.hpp"
// 3rd party headers
#include <CoreAudio/CoreAudio.h>
namespace player
{
#define NUM_BUFFERS 2
static constexpr auto LOG_TAG = "CoreAudioPlayer";
// http://stackoverflow.com/questions/4863811/how-to-use-audioqueue-to-play-a-sound-for-mac-osx-in-c
// https://gist.github.com/andormade/1360885
void callback(void* custom_data, AudioQueueRef queue, AudioQueueBufferRef buffer)
{
CoreAudioPlayer* player = static_cast<CoreAudioPlayer*>(custom_data);
player->playerCallback(queue, buffer);
}
CoreAudioPlayer::CoreAudioPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream), ms_(100), pubStream_(stream)
{
}
CoreAudioPlayer::~CoreAudioPlayer()
{
}
/// TODO: experimental. No output device can be configured yet.
std::vector<PcmDevice> CoreAudioPlayer::pcm_list()
{
UInt32 propsize;
AudioObjectPropertyAddress theAddress = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster};
AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize);
int nDevices = propsize / sizeof(AudioDeviceID);
AudioDeviceID* devids = new AudioDeviceID[nDevices];
AudioObjectGetPropertyData(kAudioObjectSystemObject, &theAddress, 0, NULL, &propsize, devids);
std::vector<PcmDevice> result;
for (int i = 0; i < nDevices; ++i)
{
if (devids[i] == kAudioDeviceUnknown)
continue;
UInt32 propSize;
AudioObjectPropertyAddress theAddress = {kAudioDevicePropertyStreamConfiguration, kAudioDevicePropertyScopeOutput, 0};
if (AudioObjectGetPropertyDataSize(devids[i], &theAddress, 0, NULL, &propSize))
continue;
AudioBufferList* buflist = new AudioBufferList[propSize];
if (AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &propSize, buflist))
continue;
int channels = 0;
for (UInt32 i = 0; i < buflist->mNumberBuffers; ++i)
channels += buflist->mBuffers[i].mNumberChannels;
delete[] buflist;
if (channels == 0)
continue;
UInt32 maxlen = 1024;
char buf[1024];
theAddress = {kAudioDevicePropertyDeviceName, kAudioDevicePropertyScopeOutput, 0};
AudioObjectGetPropertyData(devids[i], &theAddress, 0, NULL, &maxlen, buf);
LOG(DEBUG, LOG_TAG) << "device: " << i << ", name: " << buf << ", channels: " << channels << "\n";
result.push_back(PcmDevice(i, buf));
}
delete[] devids;
return result;
}
void CoreAudioPlayer::playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef)
{
/// Estimate the playout delay by checking the number of frames left in the buffer
/// and add ms_ (= complete buffer size). Based on trying.
AudioTimeStamp timestamp;
AudioQueueGetCurrentTime(queue, timeLine_, ×tamp, NULL);
size_t bufferedFrames = (frames_ - ((uint64_t)timestamp.mSampleTime % frames_)) % frames_;
size_t bufferedMs = bufferedFrames * 1000 / pubStream_->getFormat().rate() + (ms_ * (NUM_BUFFERS - 1));
/// 15ms DAC delay. Based on trying.
bufferedMs += 15;
// LOG(INFO, LOG_TAG) << "buffered: " << bufferedFrames << ", ms: " << bufferedMs << ", mSampleTime: " << timestamp.mSampleTime << "\n";
/// TODO: sometimes this bufferedMS or AudioTimeStamp wraps around 1s (i.e. we're 1s out of sync (behind)) and recovers later on
chronos::usec delay(bufferedMs * 1000);
char* buffer = (char*)bufferRef->mAudioData;
if (!pubStream_->getPlayerChunkOrSilence(buffer, delay, frames_))
{
if (chronos::getTickCount() - lastChunkTick > 5000)
{
LOG(NOTICE, LOG_TAG) << "No chunk received for 5000ms. Closing Audio Queue.\n";
uninitAudioQueue(queue);
return;
}
// LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n";
}
else
{
lastChunkTick = chronos::getTickCount();
adjustVolume(buffer, frames_);
}
// OSStatus status =
AudioQueueEnqueueBuffer(queue, bufferRef, 0, NULL);
if (!active_)
{
uninitAudioQueue(queue);
}
}
bool CoreAudioPlayer::needsThread() const
{
return true;
}
void CoreAudioPlayer::worker()
{
while (active_)
{
if (pubStream_->waitForChunk(std::chrono::milliseconds(100)))
{
try
{
initAudioQueue();
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception in worker: " << e.what() << "\n";
chronos::sleep(100);
}
}
chronos::sleep(100);
}
}
void CoreAudioPlayer::initAudioQueue()
{
const SampleFormat& sampleFormat = pubStream_->getFormat();
AudioStreamBasicDescription format;
format.mSampleRate = sampleFormat.rate();
format.mFormatID = kAudioFormatLinearPCM;
format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger; // | kAudioFormatFlagIsPacked;
format.mBitsPerChannel = sampleFormat.bits();
format.mChannelsPerFrame = sampleFormat.channels();
format.mBytesPerFrame = sampleFormat.frameSize();
format.mFramesPerPacket = 1;
format.mBytesPerPacket = format.mBytesPerFrame * format.mFramesPerPacket;
format.mReserved = 0;
AudioQueueRef queue;
AudioQueueNewOutput(&format, callback, this, CFRunLoopGetCurrent(), kCFRunLoopCommonModes, 0, &queue);
AudioQueueCreateTimeline(queue, &timeLine_);
// Apple recommends this as buffer size:
// https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/CoreAudioEssentials/CoreAudioEssentials.html
// static const int maxBufferSize = 0x10000; // limit maximum size to 64K
// static const int minBufferSize = 0x4000; // limit minimum size to 16K
//
// For 100ms @ 48000:16:2 we have 19.2K
// frames: 4800, ms: 100, buffer size: 19200
frames_ = (sampleFormat.rate() * ms_) / 1000;
ms_ = frames_ * 1000 / sampleFormat.rate();
buff_size_ = frames_ * sampleFormat.frameSize();
LOG(INFO, LOG_TAG) << "frames: " << frames_ << ", ms: " << ms_ << ", buffer size: " << buff_size_ << "\n";
AudioQueueBufferRef buffers[NUM_BUFFERS];
for (int i = 0; i < NUM_BUFFERS; i++)
{
AudioQueueAllocateBuffer(queue, buff_size_, &buffers[i]);
buffers[i]->mAudioDataByteSize = buff_size_;
callback(this, queue, buffers[i]);
}
LOG(DEBUG, LOG_TAG) << "CoreAudioPlayer::worker\n";
AudioQueueCreateTimeline(queue, &timeLine_);
AudioQueueStart(queue, NULL);
CFRunLoopRun();
}
void CoreAudioPlayer::uninitAudioQueue(AudioQueueRef queue)
{
AudioQueueStop(queue, false);
AudioQueueDispose(queue, false);
pubStream_->clearChunks();
CFRunLoopStop(CFRunLoopGetCurrent());
}
} // namespace player
| 7,792
|
C++
|
.cpp
| 181
| 37.292818
| 149
| 0.688507
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,986
|
wasapi_player.cpp
|
badaix_snapcast/client/player/wasapi_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "wasapi_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
// 3rd party headers
#include <initguid.h>
#include <mmdeviceapi.h>
// standard headers
#include <audioclient.h>
#include <avrt.h>
#include <comdef.h>
#include <comip.h>
#include <ksmedia.h>
#include <mmdeviceapi.h>
#include <cassert>
using namespace std;
using namespace std::chrono;
using namespace std::chrono_literals;
namespace player
{
static constexpr auto LOG_TAG = "WASAPI";
template <typename T>
struct COMMemDeleter
{
void operator()(T* obj)
{
if (obj != NULL)
{
CoTaskMemFree(obj);
obj = NULL;
}
}
};
template <typename T>
using com_mem_ptr = unique_ptr<T, COMMemDeleter<T>>;
using com_handle = unique_ptr<void, function<BOOL(HANDLE)>>;
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
const IID IID_IAudioClient = __uuidof(IAudioClient);
const IID IID_IAudioRenderClient = __uuidof(IAudioRenderClient);
const IID IID_IAudioClock = __uuidof(IAudioClock);
const IID IID_IAudioEndpointVolume = _uuidof(IAudioEndpointVolume);
_COM_SMARTPTR_TYPEDEF(IMMDevice, __uuidof(IMMDevice));
_COM_SMARTPTR_TYPEDEF(IMMDeviceCollection, __uuidof(IMMDeviceCollection));
_COM_SMARTPTR_TYPEDEF(IMMDeviceEnumerator, __uuidof(IMMDeviceEnumerator));
_COM_SMARTPTR_TYPEDEF(IAudioClient, __uuidof(IAudioClient));
_COM_SMARTPTR_TYPEDEF(IPropertyStore, __uuidof(IPropertyStore));
_COM_SMARTPTR_TYPEDEF(IAudioSessionManager, __uuidof(IAudioSessionManager));
_COM_SMARTPTR_TYPEDEF(IAudioSessionControl, __uuidof(IAudioSessionControl));
#define REFTIMES_PER_SEC 10000000
#define REFTIMES_PER_MILLISEC 10000
EXTERN_C const PROPERTYKEY DECLSPEC_SELECTANY PKEY_Device_FriendlyName = {{0xa45c254e, 0xdf1c, 0x4efd, {0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0}}, 14};
#define CHECK_HR(hres) \
if (FAILED(hres)) \
{ \
stringstream ss; \
ss << "HRESULT fault status: " << hex << (hres) << " line " << dec << __LINE__ << endl; \
LOG(FATAL, LOG_TAG) << ss.str(); \
throw SnapException(ss.str()); \
}
WASAPIPlayer::WASAPIPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream)
{
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
CHECK_HR(hr);
audioEventListener_ = new AudioSessionEventListener();
}
WASAPIPlayer::~WASAPIPlayer()
{
audioEndpointListener_->UnregisterControlChangeNotify(&audioEndpointVolumeCallback_);
WASAPIPlayer::stop();
}
inline PcmDevice convertToDevice(int idx, IMMDevicePtr& device)
{
HRESULT hr;
PcmDevice desc;
LPWSTR id = NULL;
hr = device->GetId(&id);
CHECK_HR(hr);
IPropertyStorePtr properties = nullptr;
hr = device->OpenPropertyStore(STGM_READ, &properties);
PROPVARIANT deviceName;
PropVariantInit(&deviceName);
hr = properties->GetValue(PKEY_Device_FriendlyName, &deviceName);
CHECK_HR(hr);
desc.idx = idx;
// Convert a wide Unicode string to an UTF8 string
auto utf8_encode = [](const std::wstring& wstr)
{
if (wstr.empty())
return std::string();
int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);
std::string strTo(size_needed, 0);
WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);
return strTo;
};
desc.name = utf8_encode(id);
desc.description = utf8_encode(deviceName.pwszVal);
CoTaskMemFree(id);
return desc;
}
vector<PcmDevice> WASAPIPlayer::pcm_list()
{
HRESULT hr;
IMMDeviceCollectionPtr devices = nullptr;
IMMDeviceEnumeratorPtr deviceEnumerator = nullptr;
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (hr != CO_E_ALREADYINITIALIZED)
CHECK_HR(hr);
hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_SERVER, IID_IMMDeviceEnumerator, (void**)&deviceEnumerator);
CHECK_HR(hr);
hr = deviceEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
CHECK_HR(hr);
UINT deviceCount;
devices->GetCount(&deviceCount);
if (deviceCount == 0)
throw SnapException("no valid devices");
vector<PcmDevice> deviceList;
{
IMMDevicePtr defaultDevice = nullptr;
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
CHECK_HR(hr);
auto dev = convertToDevice(0, defaultDevice);
dev.name = DEFAULT_DEVICE;
deviceList.push_back(dev);
}
for (UINT i = 0; i < deviceCount; ++i)
{
IMMDevicePtr device = nullptr;
hr = devices->Item(i, &device);
CHECK_HR(hr);
deviceList.push_back(convertToDevice(i + 1, device));
}
return deviceList;
}
#pragma warning(push)
#pragma warning(disable : 4127)
void WASAPIPlayer::worker()
{
assert(sizeof(char) == sizeof(BYTE));
HRESULT hr;
// Create the format specifier
com_mem_ptr<WAVEFORMATEX> waveformat((WAVEFORMATEX*)(CoTaskMemAlloc(sizeof(WAVEFORMATEX))));
waveformat->wFormatTag = WAVE_FORMAT_PCM;
waveformat->nChannels = stream_->getFormat().channels();
waveformat->nSamplesPerSec = stream_->getFormat().rate();
waveformat->wBitsPerSample = stream_->getFormat().bits();
waveformat->nBlockAlign = waveformat->nChannels * waveformat->wBitsPerSample / 8;
waveformat->nAvgBytesPerSec = waveformat->nSamplesPerSec * waveformat->nBlockAlign;
waveformat->cbSize = 0;
com_mem_ptr<WAVEFORMATEXTENSIBLE> waveformatExtended((WAVEFORMATEXTENSIBLE*)(CoTaskMemAlloc(sizeof(WAVEFORMATEXTENSIBLE))));
waveformatExtended->Format = *waveformat;
waveformatExtended->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
waveformatExtended->Format.cbSize = 22;
waveformatExtended->Samples.wValidBitsPerSample = waveformat->wBitsPerSample;
waveformatExtended->dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT;
waveformatExtended->SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
// Retrieve the device enumerator
IMMDeviceEnumeratorPtr deviceEnumerator = nullptr;
hr = CoCreateInstance(CLSID_MMDeviceEnumerator, NULL, CLSCTX_SERVER, IID_IMMDeviceEnumerator, (void**)&deviceEnumerator);
CHECK_HR(hr);
// Register the default playback device (eRender for playback)
IMMDevicePtr device = nullptr;
if (settings_.pcm_device.idx == 0)
{
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &device);
CHECK_HR(hr);
}
else
{
IMMDeviceCollectionPtr devices = nullptr;
hr = deviceEnumerator->EnumAudioEndpoints(eRender, DEVICE_STATE_ACTIVE, &devices);
CHECK_HR(hr);
devices->Item(settings_.pcm_device.idx - 1, &device);
}
IPropertyStorePtr properties = nullptr;
hr = device->OpenPropertyStore(STGM_READ, &properties);
CHECK_HR(hr);
PROPVARIANT format;
hr = properties->GetValue(PKEY_AudioEngine_DeviceFormat, &format);
CHECK_HR(hr);
PWAVEFORMATEX formatEx = (PWAVEFORMATEX)format.blob.pBlobData;
LOG(INFO, LOG_TAG) << "Device accepts format: " << formatEx->nSamplesPerSec << ":" << formatEx->wBitsPerSample << ":" << formatEx->nChannels << "\n";
// Activate the device
IAudioClientPtr audioClient = nullptr;
hr = device->Activate(IID_IAudioClient, CLSCTX_SERVER, NULL, (void**)&audioClient);
CHECK_HR(hr);
if (settings_.sharing_mode == ClientSettings::SharingMode::exclusive)
{
hr = audioClient->IsFormatSupported(AUDCLNT_SHAREMODE_EXCLUSIVE, &(waveformatExtended->Format), NULL);
CHECK_HR(hr);
}
IAudioSessionManagerPtr sessionManager = nullptr;
// Get the session manager for the endpoint device.
hr = device->Activate(__uuidof(IAudioSessionManager), CLSCTX_INPROC_SERVER, NULL, (void**)&sessionManager);
CHECK_HR(hr);
// Get the control interface for the process-specific audio
// session with session GUID = GUID_NULL. This is the session
// that an audio stream for a DirectSound, DirectShow, waveOut,
// or PlaySound application stream belongs to by default.
IAudioSessionControlPtr control = nullptr;
hr = sessionManager->GetAudioSessionControl(NULL, 0, &control);
CHECK_HR(hr);
// register
hr = control->RegisterAudioSessionNotification(audioEventListener_);
CHECK_HR(hr);
hr = device->Activate(IID_IAudioEndpointVolume, CLSCTX_ALL, NULL, (void**)&audioEndpointListener_);
audioEndpointListener_->RegisterControlChangeNotify((IAudioEndpointVolumeCallback*)&audioEndpointVolumeCallback_);
// Get the device period
REFERENCE_TIME hnsRequestedDuration = REFTIMES_PER_SEC;
hr = audioClient->GetDevicePeriod(NULL, &hnsRequestedDuration);
CHECK_HR(hr);
LOG(INFO, LOG_TAG) << "Initializing WASAPI in " << (settings_.sharing_mode == ClientSettings::SharingMode::shared ? "shared" : "exclusive") << " mode\n";
_AUDCLNT_SHAREMODE share_mode = settings_.sharing_mode == ClientSettings::SharingMode::shared ? AUDCLNT_SHAREMODE_SHARED : AUDCLNT_SHAREMODE_EXCLUSIVE;
DWORD stream_flags = settings_.sharing_mode == ClientSettings::SharingMode::shared
? AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY
: AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
// Initialize the client at minimum latency
hr = audioClient->Initialize(share_mode, stream_flags, hnsRequestedDuration, hnsRequestedDuration, &(waveformatExtended->Format), NULL);
if (hr == AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED)
{
UINT32 alignedBufferSize;
hr = audioClient->GetBufferSize(&alignedBufferSize);
CHECK_HR(hr);
audioClient.Attach(NULL, false);
hnsRequestedDuration = (REFERENCE_TIME)((10000.0 * 1000 / waveformatExtended->Format.nSamplesPerSec * alignedBufferSize) + 0.5);
hr = device->Activate(IID_IAudioClient, CLSCTX_SERVER, NULL, (void**)&audioClient);
CHECK_HR(hr);
hr = audioClient->Initialize(share_mode, stream_flags, hnsRequestedDuration, hnsRequestedDuration, &(waveformatExtended->Format), NULL);
}
CHECK_HR(hr);
// Register an event to refill the buffer
com_handle eventHandle(CreateEvent(NULL, FALSE, FALSE, NULL), &::CloseHandle);
if (eventHandle == NULL)
CHECK_HR(E_FAIL);
hr = audioClient->SetEventHandle(HANDLE(eventHandle.get()));
CHECK_HR(hr);
// Get size of buffer
UINT32 bufferFrameCount;
hr = audioClient->GetBufferSize(&bufferFrameCount);
CHECK_HR(hr);
// Get the rendering service
IAudioRenderClient* renderClient = NULL;
hr = audioClient->GetService(IID_IAudioRenderClient, (void**)&renderClient);
CHECK_HR(hr);
// Grab the clock service
IAudioClock* clock = NULL;
hr = audioClient->GetService(IID_IAudioClock, (void**)&clock);
CHECK_HR(hr);
// Boost our priority
DWORD taskIndex = 0;
com_handle taskHandle(AvSetMmThreadCharacteristics(TEXT("Pro Audio"), &taskIndex), &::AvRevertMmThreadCharacteristics);
if (taskHandle == NULL)
CHECK_HR(E_FAIL);
// And, action!
hr = audioClient->Start();
CHECK_HR(hr);
size_t bufferSize = bufferFrameCount * waveformatExtended->Format.nBlockAlign;
BYTE* buffer;
unique_ptr<char[]> queueBuffer(new char[bufferSize]);
UINT64 position = 0, bufferPosition = 0, frequency;
clock->GetFrequency(&frequency);
while (active_)
{
DWORD returnVal = WaitForSingleObject(eventHandle.get(), 2000);
if (returnVal != WAIT_OBJECT_0)
{
// stop();
LOG(INFO, LOG_TAG) << "Got timeout waiting for audio device callback\n";
CHECK_HR(ERROR_TIMEOUT);
hr = audioClient->Stop();
CHECK_HR(hr);
hr = audioClient->Reset();
CHECK_HR(hr);
while (active_ && !stream_->waitForChunk(std::chrono::milliseconds(100)))
LOG(INFO, LOG_TAG) << "Waiting for chunk\n";
hr = audioClient->Start();
CHECK_HR(hr);
bufferPosition = 0;
break;
}
// Thread was sleeping above, double check that we are still running
if (!active_)
break;
// update our volume from IAudioControl
if (mode_ == ClientSettings::SharingMode::exclusive)
{
volCorrection_ = audioEventListener_->getVolume();
// muteOverride = audioEventListener_->getMuted(); // use this for also applying audio mixer mute state
}
// get audio device volume from IAudioEndpointVolume
// float deviceVolume = audioEndpointVolumeCallback.getVolume(); // system volume (for this audio device)
// bool deviceMuted = audioEndpointVolumeCallback.getMuted(); // system mute (for this audio device)
clock->GetPosition(&position, NULL);
UINT32 padding = 0;
if (settings_.sharing_mode == ClientSettings::SharingMode::shared)
{
hr = audioClient->GetCurrentPadding(&padding);
CHECK_HR(hr);
}
int available = bufferFrameCount - padding;
if (stream_->getPlayerChunk(queueBuffer.get(),
microseconds(((bufferPosition * 1000000) / waveformat->nSamplesPerSec) - ((position * 1000000) / frequency)), available))
{
if (available > 0)
{
adjustVolume(queueBuffer.get(), available);
hr = renderClient->GetBuffer(available, &buffer);
CHECK_HR(hr);
memcpy(buffer, queueBuffer.get(), bufferSize);
hr = renderClient->ReleaseBuffer(available, 0);
CHECK_HR(hr);
bufferPosition += available;
}
}
else
{
LOG(INFO, LOG_TAG) << "Failed to get chunk\n";
hr = audioClient->Stop();
CHECK_HR(hr);
hr = audioClient->Reset();
CHECK_HR(hr);
while (active_ && !stream_->waitForChunk(std::chrono::milliseconds(100)))
LOG(INFO, LOG_TAG) << "Waiting for chunk\n";
hr = audioClient->Start();
CHECK_HR(hr);
bufferPosition = 0;
}
}
}
#pragma warning(pop)
HRESULT STDMETHODCALLTYPE AudioSessionEventListener::QueryInterface(REFIID riid, VOID** ppvInterface)
{
if (IID_IUnknown == riid)
{
AddRef();
*ppvInterface = (IUnknown*)this;
}
else if (__uuidof(IAudioSessionEvents) == riid)
{
AddRef();
*ppvInterface = (IAudioSessionEvents*)this;
}
else
{
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext)
{
std::ignore = EventContext;
volume_ = NewVolume;
muted_ = NewMute;
if (NewMute)
{
LOG(DEBUG, LOG_TAG) << ("MUTE\n");
}
else
{
LOG(DEBUG, LOG_TAG) << "Volume = " << (UINT32)(100 * NewVolume + 0.5) << " percent\n";
}
return S_OK;
}
HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnStateChanged(AudioSessionState NewState)
{
char* pszState = "?????";
switch (NewState)
{
case AudioSessionStateActive:
pszState = "active";
break;
case AudioSessionStateInactive:
pszState = "inactive";
break;
}
LOG(DEBUG, LOG_TAG) << "New session state = " << pszState << "\n";
return S_OK;
}
HRESULT STDMETHODCALLTYPE AudioSessionEventListener::OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason)
{
char* pszReason = "?????";
switch (DisconnectReason)
{
case DisconnectReasonDeviceRemoval:
pszReason = "device removed";
break;
case DisconnectReasonServerShutdown:
pszReason = "server shut down";
break;
case DisconnectReasonFormatChanged:
pszReason = "format changed";
break;
case DisconnectReasonSessionLogoff:
pszReason = "user logged off";
break;
case DisconnectReasonSessionDisconnected:
pszReason = "session disconnected";
break;
case DisconnectReasonExclusiveModeOverride:
pszReason = "exclusive-mode override";
break;
}
LOG(INFO, LOG_TAG) << "Audio session disconnected (reason: " << pszReason << ")";
return S_OK;
}
HRESULT STDMETHODCALLTYPE AudioEndpointVolumeCallback::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify)
{
if (pNotify == NULL)
{
return E_INVALIDARG;
}
if (pNotify->bMuted)
{
LOG(DEBUG, LOG_TAG) << ("MASTER MUTE\n");
}
LOG(DEBUG, LOG_TAG) << "Volume = " << (UINT32)(100 * pNotify->fMasterVolume + 0.5) << " percent\n";
volume_ = pNotify->fMasterVolume;
muted_ = pNotify->bMuted;
return S_OK;
}
} // namespace player
| 18,895
|
C++
|
.cpp
| 438
| 36.550228
| 160
| 0.645119
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,987
|
pulse_player.cpp
|
badaix_snapcast/client/player/pulse_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "pulse_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/logging.hpp"
#include "common/utils/string_utils.hpp"
// 3rd party headers
#include <pulse/proplist.h>
// standard headers
#include <iostream>
using namespace std::chrono_literals;
using namespace std;
namespace player
{
static constexpr std::chrono::milliseconds BUFFER_TIME = 100ms;
static constexpr auto LOG_TAG = "PulsePlayer";
// Example code:
// https://code.qt.io/cgit/qt/qtmultimedia.git/tree/src/plugins/pulseaudio/qaudioinput_pulse.cpp?h=dev
// http://www.videolan.org/developers/vlc/modules/audio_output/pulse.c
// https://www.freedesktop.org/wiki/Software/PulseAudio/Documentation/Developer/Clients/Samples/AsyncPlayback/
vector<PcmDevice> PulsePlayer::pcm_list(const std::string& parameter)
{
auto pa_ml = std::shared_ptr<pa_mainloop>(pa_mainloop_new(), [](pa_mainloop* pa_ml) { pa_mainloop_free(pa_ml); });
pa_mainloop_api* pa_mlapi = pa_mainloop_get_api(pa_ml.get());
auto pa_ctx = std::shared_ptr<pa_context>(pa_context_new(pa_mlapi, "Snapcast"),
[](pa_context* pa_ctx)
{
pa_context_disconnect(pa_ctx);
pa_context_unref(pa_ctx);
});
std::string pa_server;
auto params = utils::string::split_pairs(parameter, ',', '=');
if (params.find("server") != params.end())
pa_server = params["server"];
if (pa_context_connect(pa_ctx.get(), pa_server.empty() ? nullptr : pa_server.c_str(), PA_CONTEXT_NOFLAGS, nullptr) < 0)
throw SnapException("Failed to connect to PulseAudio context, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get()))));
static int pa_ready = 0;
pa_context_set_state_callback(
pa_ctx.get(),
[](pa_context* c, void* userdata)
{
std::ignore = userdata;
pa_context_state_t state = pa_context_get_state(c);
switch (state)
{
case PA_CONTEXT_FAILED:
case PA_CONTEXT_TERMINATED:
pa_ready = 2;
break;
case PA_CONTEXT_READY:
pa_ready = 1;
break;
default:
break;
}
},
nullptr);
// We can't do anything until PA is ready, so just iterate the mainloop
// and continue
auto wait_start = std::chrono::steady_clock::now();
while (pa_ready == 0)
{
auto now = std::chrono::steady_clock::now();
if (now - wait_start > 5s)
throw SnapException("Timeout while waiting for PulseAudio to become ready");
if (pa_mainloop_iterate(pa_ml.get(), 1, nullptr) < 0)
throw SnapException("Error while waiting for PulseAudio to become ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get()))));
this_thread::sleep_for(1ms);
}
if (pa_ready == 2)
throw SnapException("PulseAudio context failed, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get()))));
static std::vector<PcmDevice> devices;
auto* op = pa_context_get_sink_info_list(
pa_ctx.get(),
[](pa_context* ctx, const pa_sink_info* i, int eol, void* userdata) mutable
{
std::ignore = ctx;
std::ignore = userdata;
// auto self = static_cast<PulsePlayer*>(userdata);
// If eol is set to a positive number, you're at the end of the list
if (eol <= 0)
devices.emplace_back(i->index, i->name, i->description);
},
nullptr);
if (op == nullptr)
throw SnapException("PulseAudio get sink info list failed, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx.get()))));
wait_start = std::chrono::steady_clock::now();
while (pa_operation_get_state(op) != PA_OPERATION_DONE)
{
if (pa_operation_get_state(op) == PA_OPERATION_CANCELED)
throw SnapException("PulseAudio operation canceled");
auto now = std::chrono::steady_clock::now();
if (now - wait_start > 2s)
break;
pa_mainloop_iterate(pa_ml.get(), 1, nullptr);
}
int max_idx = -1;
for (const auto& device : devices)
max_idx = std::max(max_idx, device.idx);
devices.emplace(devices.begin(), max_idx + 1, DEFAULT_DEVICE, "Let PulseAudio server choose the device");
return devices;
}
PulsePlayer::PulsePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream), latency_(BUFFER_TIME), pa_ml_(nullptr), pa_ctx_(nullptr), playstream_(nullptr), proplist_(nullptr),
server_(std::nullopt)
{
auto params = utils::string::split_pairs_to_container<std::vector<std::string>>(settings.parameter, ',', '=');
if (params.find("buffer_time") != params.end())
latency_ = std::chrono::milliseconds(std::max(cpt::stoi(params["buffer_time"].front()), 10));
if (params.find("server") != params.end())
server_ = params["server"].front();
properties_[PA_PROP_MEDIA_ROLE] = "music";
properties_[PA_PROP_APPLICATION_ICON_NAME] = "snapcast";
if (params.find("property") != params.end())
{
for (const auto& p : params["property"])
{
std::string value;
std::string key = utils::string::split_left(p, '=', value);
if (!key.empty())
properties_[key] = value;
}
}
for (const auto& property : properties_)
{
if (!property.second.empty())
LOG(INFO, LOG_TAG) << "Setting property \"" << property.first << "\" to \"" << property.second << "\"\n";
}
LOG(INFO, LOG_TAG) << "Using buffer_time: " << latency_.count() / 1000 << " ms, server: " << server_.value_or("default") << "\n";
}
PulsePlayer::~PulsePlayer()
{
LOG(DEBUG, LOG_TAG) << "Destructor\n";
stop();
}
bool PulsePlayer::needsThread() const
{
return true;
}
void PulsePlayer::worker()
{
while (active_)
{
pa_mainloop_run(pa_ml_, nullptr);
// if we are still active, wait for a chunk and attempt to reconnect
while (active_ && !stream_->waitForChunk(100ms))
{
static utils::logging::TimeConditional cond(2s);
LOG(DEBUG, LOG_TAG) << cond << "Waiting for a chunk to become available before reconnecting\n";
}
while (active_)
{
LOG(INFO, LOG_TAG) << "Chunk available, reconnecting to pulse\n";
try
{
connect();
break;
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception while connecting to pulse: " << e.what() << endl;
disconnect();
chronos::sleep(100);
}
}
}
}
void PulsePlayer::setHardwareVolume(const Volume& volume)
{
// if we're not connected to pulse, ignore the hardware volume change as the volume will be set upon reconnect
if (playstream_ == nullptr)
return;
last_change_ = std::chrono::steady_clock::now();
pa_cvolume cvolume;
if (volume.mute)
pa_cvolume_set(&cvolume, stream_->getFormat().channels(), PA_VOLUME_MUTED);
else
pa_cvolume_set(&cvolume, stream_->getFormat().channels(), volume.volume * PA_VOLUME_NORM);
pa_context_set_sink_input_volume(pa_ctx_, pa_stream_get_index(playstream_), &cvolume, nullptr, nullptr);
}
bool PulsePlayer::getHardwareVolume(Volume& volume)
{
// This is called during start to send the initial volume to the server
// Because getting the volume works async, we return false here
// and instead trigger volume notification in pa_context_subscribe
std::ignore = volume;
return false;
}
void PulsePlayer::triggerVolumeUpdate()
{
pa_context_get_sink_input_info(
pa_ctx_, pa_stream_get_index(playstream_),
[](pa_context* ctx, const pa_sink_input_info* info, int eol, void* userdata)
{
std::ignore = ctx;
LOG(DEBUG, LOG_TAG) << "pa_context_get_sink_info_by_index info: " << (info != nullptr) << ", eol: " << eol << "\n";
if (info != nullptr)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->volume_.volume = static_cast<double>(pa_cvolume_avg(&(info->volume))) / static_cast<double>(PA_VOLUME_NORM);
self->volume_.mute = (info->mute != 0);
LOG(DEBUG, LOG_TAG) << "Volume changed: " << self->volume_.volume << ", muted: " << self->volume_.mute << "\n";
auto now = std::chrono::steady_clock::now();
if (now - self->last_change_ < 1s)
{
LOG(DEBUG, LOG_TAG) << "Last volume change by server: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(now - self->last_change_).count()
<< " ms => ignoring volume change\n";
return;
}
self->notifyVolumeChange(self->volume_);
}
},
this);
}
void PulsePlayer::subscribeCallback(pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx)
{
std::ignore = ctx;
LOG(TRACE, LOG_TAG) << "subscribeCallback, event type: " << event_type << ", idx: " << idx << "\n";
unsigned facility = event_type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK;
event_type = static_cast<pa_subscription_event_type_t>(static_cast<int>(event_type) & PA_SUBSCRIPTION_EVENT_TYPE_MASK);
if (facility == PA_SUBSCRIPTION_EVENT_SINK_INPUT)
{
LOG(DEBUG, LOG_TAG) << "event_type: " << event_type << ", facility: " << facility << "\n";
if ((playstream_ != nullptr) && (idx == pa_stream_get_index(playstream_)))
triggerVolumeUpdate();
}
}
void PulsePlayer::underflowCallback(pa_stream* stream)
{
// We increase the latency by 50% if we get 6 underflows and latency is under 2s
// This is very useful for over the network playback that can't handle low latencies
underflows_++;
LOG(INFO, LOG_TAG) << "undeflow #" << underflows_ << ", latency: " << latency_.count() / 1000 << " ms\n";
if (underflows_ >= 6 && latency_ < 500ms)
{
latency_ = (latency_ * 3) / 2;
bufattr_.maxlength = pa_usec_to_bytes(latency_.count(), &pa_ss_);
bufattr_.tlength = pa_usec_to_bytes(latency_.count(), &pa_ss_);
pa_stream_set_buffer_attr(stream, &bufattr_, nullptr, nullptr);
underflows_ = 0;
LOG(INFO, LOG_TAG) << "latency increased to " << latency_.count() / 1000 << " ms\n";
}
}
void PulsePlayer::stateCallback(pa_context* ctx)
{
pa_context_state_t state = pa_context_get_state(ctx);
string str_state = "unknown";
pa_ready_ = 0;
switch (state)
{
// These are just here for reference
case PA_CONTEXT_UNCONNECTED:
str_state = "unconnected";
break;
case PA_CONTEXT_CONNECTING:
str_state = "connecting";
break;
case PA_CONTEXT_AUTHORIZING:
str_state = "authorizing";
break;
case PA_CONTEXT_SETTING_NAME:
str_state = "setting name";
break;
default:
str_state = "unknown";
break;
case PA_CONTEXT_FAILED:
str_state = "failed";
pa_ready_ = 2;
break;
case PA_CONTEXT_TERMINATED:
str_state = "terminated";
pa_ready_ = 2;
break;
case PA_CONTEXT_READY:
str_state = "ready";
pa_ready_ = 1;
break;
}
LOG(DEBUG, LOG_TAG) << "State changed " << state << ": " << str_state << "\n";
}
void PulsePlayer::writeCallback(pa_stream* stream, size_t nbytes)
{
pa_usec_t usec = 0;
int neg = 0;
pa_stream_get_latency(stream, &usec, &neg);
auto numFrames = nbytes / stream_->getFormat().frameSize();
if (buffer_.size() < nbytes)
buffer_.resize(nbytes);
// LOG(TRACE, LOG_TAG) << "writeCallback latency " << usec << " us, frames: " << numFrames << "\n";
if (!stream_->getPlayerChunkOrSilence(buffer_.data(), std::chrono::microseconds(usec), numFrames))
{
// if we haven't got a chunk for a while, it's time to disconnect from pulse so the sound device
// can become idle/suspended.
if (chronos::getTickCount() - last_chunk_tick_ > 5000)
{
LOG(INFO, LOG_TAG) << "No chunk received for 5000ms, disconnecting from pulse.\n";
this->disconnect();
return;
}
// LOG(TRACE, LOG_TAG) << "Failed to get chunk. Playing silence.\n";
}
else
{
last_chunk_tick_ = chronos::getTickCount();
adjustVolume(static_cast<char*>(buffer_.data()), numFrames);
}
pa_stream_write(stream, buffer_.data(), nbytes, nullptr, 0LL, PA_SEEK_RELATIVE);
}
void PulsePlayer::start()
{
LOG(INFO, LOG_TAG) << "Start\n";
this->connect();
Player::start();
}
void PulsePlayer::connect()
{
std::lock_guard<std::mutex> lock(mutex_);
LOG(INFO, LOG_TAG) << "Connecting to pulse\n";
if (settings_.pcm_device.idx == -1)
throw SnapException("Can't open " + settings_.pcm_device.name + ", error: No such device");
const SampleFormat& format = stream_->getFormat();
pa_ss_.rate = format.rate();
pa_ss_.channels = format.channels();
if (format.bits() == 8)
pa_ss_.format = PA_SAMPLE_U8;
else if (format.bits() == 16)
pa_ss_.format = PA_SAMPLE_S16LE;
else if ((format.bits() == 24) && (format.sampleSize() == 3))
pa_ss_.format = PA_SAMPLE_S24LE;
else if ((format.bits() == 24) && (format.sampleSize() == 4))
pa_ss_.format = PA_SAMPLE_S24_32LE;
else if (format.bits() == 32)
pa_ss_.format = PA_SAMPLE_S32LE;
else
throw SnapException("Unsupported sample format \"" + cpt::to_string(format.bits()) + "\"");
// Create a mainloop API and connection to the default server
pa_ready_ = 0;
pa_ml_ = pa_mainloop_new();
pa_mainloop_api* pa_mlapi = pa_mainloop_get_api(pa_ml_);
proplist_ = pa_proplist_new();
for (const auto& property : properties_)
{
if (!property.second.empty())
pa_proplist_sets(proplist_, property.first.c_str(), property.second.c_str());
}
pa_ctx_ = pa_context_new_with_proplist(pa_mlapi, "Snapcast", proplist_);
const char* server = server_.has_value() ? server_.value().c_str() : nullptr;
if (pa_context_connect(pa_ctx_, server, PA_CONTEXT_NOFLAGS, nullptr) < 0)
throw SnapException("Failed to connect to PulseAudio context, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_))));
// This function defines a callback so the server will tell us it's state.
// Our callback will wait for the state to be ready. The callback will
// modify the variable to 1 so we know when we have a connection and it's
// ready.
// If there's an error, the callback will set pa_ready to 2
pa_context_set_state_callback(
pa_ctx_,
[](pa_context* c, void* userdata)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->stateCallback(c);
},
this);
// We can't do anything until PA is ready, so just iterate the mainloop
// and continue
auto wait_start = std::chrono::steady_clock::now();
while (pa_ready_ == 0)
{
auto now = std::chrono::steady_clock::now();
if (now - wait_start > 5s)
throw SnapException("Timeout while waiting for PulseAudio to become ready");
if (pa_mainloop_iterate(pa_ml_, 1, nullptr) < 0)
throw SnapException("Error while waiting for PulseAudio to become ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_))));
this_thread::sleep_for(1ms);
}
if (pa_ready_ == 2)
throw SnapException("PulseAudio is not ready, error: " + std::string(pa_strerror(pa_context_errno(pa_ctx_))));
playstream_ = pa_stream_new(pa_ctx_, "Playback", &pa_ss_, nullptr);
if (playstream_ == nullptr)
throw SnapException("Failed to create PulseAudio stream");
if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware)
{
pa_context_set_subscribe_callback(
pa_ctx_,
[](pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx, void* userdata)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->subscribeCallback(ctx, event_type, idx);
},
this);
const auto mask = static_cast<pa_subscription_mask_t>(PA_SUBSCRIPTION_MASK_SINK_INPUT);
pa_context_subscribe(
pa_ctx_, mask,
[](pa_context* ctx, int success, void* userdata)
{
std::ignore = ctx;
if (success != 0)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->triggerVolumeUpdate();
}
},
this);
}
pa_stream_set_write_callback(
playstream_,
[](pa_stream* stream, size_t length, void* userdata)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->writeCallback(stream, length);
},
this);
pa_stream_set_underflow_callback(
playstream_,
[](pa_stream* stream, void* userdata)
{
auto* self = static_cast<PulsePlayer*>(userdata);
self->underflowCallback(stream);
},
this);
bufattr_.fragsize = pa_usec_to_bytes(latency_.count(), &pa_ss_);
bufattr_.maxlength = pa_usec_to_bytes(latency_.count(), &pa_ss_);
bufattr_.minreq = static_cast<uint32_t>(-1);
bufattr_.prebuf = static_cast<uint32_t>(-1);
bufattr_.tlength = pa_usec_to_bytes(latency_.count(), &pa_ss_);
const char* device = nullptr;
if (settings_.pcm_device.name != DEFAULT_DEVICE)
device = settings_.pcm_device.name.c_str();
int result = pa_stream_connect_playback(
playstream_, device, &bufattr_, static_cast<pa_stream_flags>(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE),
nullptr, nullptr);
if (result < 0)
{
// Old pulse audio servers don't like the ADJUST_LATENCY flag, so retry without that
result = pa_stream_connect_playback(playstream_, device, &bufattr_,
static_cast<pa_stream_flags>(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE), nullptr, nullptr);
}
if (result < 0)
throw SnapException("Failed to connect PulseAudio playback stream");
// we just connected, pretend we got a chunk so we don't immediately disconnect.
last_chunk_tick_ = chronos::getTickCount();
}
void PulsePlayer::stop()
{
LOG(INFO, LOG_TAG) << "Stop\n";
this->disconnect();
Player::stop();
}
void PulsePlayer::disconnect()
{
std::lock_guard<std::mutex> lock(mutex_);
LOG(INFO, LOG_TAG) << "Disconnecting from pulse\n";
if (pa_ml_ != nullptr)
{
pa_mainloop_quit(pa_ml_, 0);
}
if (pa_ctx_ != nullptr)
{
pa_context_disconnect(pa_ctx_);
pa_context_unref(pa_ctx_);
pa_ctx_ = nullptr;
}
if (pa_ml_ != nullptr)
{
pa_mainloop_free(pa_ml_);
pa_ml_ = nullptr;
}
if (playstream_ != nullptr)
{
pa_stream_set_state_callback(playstream_, nullptr, nullptr);
pa_stream_set_read_callback(playstream_, nullptr, nullptr);
pa_stream_set_underflow_callback(playstream_, nullptr, nullptr);
pa_stream_set_overflow_callback(playstream_, nullptr, nullptr);
pa_stream_disconnect(playstream_);
pa_stream_unref(playstream_);
playstream_ = nullptr;
}
if (proplist_ != nullptr)
{
pa_proplist_free(proplist_);
proplist_ = nullptr;
}
}
} // namespace player
| 20,864
|
C++
|
.cpp
| 501
| 33.974052
| 157
| 0.608659
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,988
|
alsa_player.cpp
|
badaix_snapcast/client/player/alsa_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "alsa_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/logging.hpp"
#include "common/utils/string_utils.hpp"
// 3rd party headers
// standard headers
#include <chrono>
using namespace std::chrono_literals;
using namespace std;
namespace player
{
static constexpr std::chrono::milliseconds BUFFER_TIME = 80ms;
static constexpr int PERIODS = 4;
static constexpr int MIN_PERIODS = 3;
#define exp10(x) (exp((x)*log(10)))
static constexpr auto LOG_TAG = "Alsa";
static constexpr auto DEFAULT_MIXER = "PCM";
AlsaPlayer::AlsaPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream), handle_(nullptr), ctl_(nullptr), mixer_(nullptr), elem_(nullptr), sd_(io_context), timer_(io_context)
{
if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware)
{
string tmp;
if (settings_.mixer.parameter.empty())
mixer_name_ = DEFAULT_MIXER;
else
mixer_name_ = utils::string::split_left(settings_.mixer.parameter, ':', tmp);
string card;
// default:CARD=ALSA[,DEV=x] => default
mixer_device_ = utils::string::split_left(settings_.pcm_device.name, ':', card);
if (!card.empty())
{
auto pos = card.find("CARD=");
if (pos != string::npos)
{
card = card.substr(pos + 5);
card = utils::string::split_left(card, ',', tmp);
int card_idx = snd_card_get_index(card.c_str());
if ((card_idx >= 0) && (card_idx < 32))
mixer_device_ = "hw:" + std::to_string(card_idx);
}
}
LOG(DEBUG, LOG_TAG) << "Mixer: " << mixer_name_ << ", device: " << mixer_device_ << "\n";
}
auto params = utils::string::split_pairs(settings.parameter, ',', '=');
if (params.find("buffer_time") != params.end())
buffer_time_ = std::chrono::milliseconds(std::max(cpt::stoi(params["buffer_time"]), 10));
if (params.find("fragments") != params.end())
periods_ = std::max(cpt::stoi(params["fragments"]), 2);
LOG(INFO, LOG_TAG) << "Using " << (buffer_time_.has_value() ? "configured" : "default")
<< " buffer_time: " << buffer_time_.value_or(BUFFER_TIME).count() / 1000 << " ms, " << (periods_.has_value() ? "configured" : "default")
<< " fragments: " << periods_.value_or(PERIODS) << "\n";
}
void AlsaPlayer::setHardwareVolume(const Volume& volume)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (elem_ == nullptr)
return;
last_change_ = std::chrono::steady_clock::now();
try
{
int val = volume.mute ? 0 : 1;
int err = snd_mixer_selem_set_playback_switch_all(elem_, val);
if (err < 0)
LOG(ERROR, LOG_TAG) << "Failed to mute, error: " << snd_strerror(err) << "\n";
long minv, maxv;
if ((err = snd_mixer_selem_get_playback_dB_range(elem_, &minv, &maxv)) == 0)
{
double min_norm = exp10((minv - maxv) / 6000.0);
double vol = volume.volume * (1 - min_norm) + min_norm;
double mixer_volume = 6000.0 * log10(vol) + maxv;
LOG(DEBUG, LOG_TAG) << "Mixer playback dB range [" << minv << ", " << maxv << "], volume: " << vol << ", mixer volume: " << mixer_volume << "\n";
if ((err = snd_mixer_selem_set_playback_dB_all(elem_, mixer_volume, 0)) < 0)
throw SnapException(std::string("Failed to set playback volume, error: ") + snd_strerror(err));
}
else
{
if ((err = snd_mixer_selem_get_playback_volume_range(elem_, &minv, &maxv)) < 0)
throw SnapException(std::string("Failed to get playback volume range, error: ") + snd_strerror(err));
auto mixer_volume = volume.volume * (maxv - minv) + minv;
LOG(DEBUG, LOG_TAG) << "Mixer playback volume range [" << minv << ", " << maxv << "], volume: " << volume.volume
<< ", mixer volume: " << mixer_volume << "\n";
if ((err = snd_mixer_selem_set_playback_volume_all(elem_, mixer_volume)) < 0)
throw SnapException(std::string("Failed to set playback volume, error: ") + snd_strerror(err));
}
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << "\n";
uninitMixer();
}
}
bool AlsaPlayer::getHardwareVolume(Volume& volume)
{
try
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (elem_ == nullptr)
throw SnapException("Mixer not initialized");
long vol;
int err = 0;
while (snd_mixer_handle_events(mixer_) > 0)
this_thread::sleep_for(1us);
long minv, maxv;
if ((err = snd_mixer_selem_get_playback_dB_range(elem_, &minv, &maxv)) == 0)
{
if ((err = snd_mixer_selem_get_playback_dB(elem_, SND_MIXER_SCHN_MONO, &vol)) < 0)
throw SnapException(std::string("Failed to get playback volume, error: ") + snd_strerror(err));
volume.volume = pow(10, (vol - maxv) / 6000.0);
if (minv != SND_CTL_TLV_DB_GAIN_MUTE)
{
double min_norm = pow(10, (minv - maxv) / 6000.0);
volume.volume = (volume.volume - min_norm) / (1 - min_norm);
}
}
else
{
if ((err = snd_mixer_selem_get_playback_volume_range(elem_, &minv, &maxv)) < 0)
throw SnapException(std::string("Failed to get playback volume range, error: ") + snd_strerror(err));
if ((err = snd_mixer_selem_get_playback_volume(elem_, SND_MIXER_SCHN_MONO, &vol)) < 0)
throw SnapException(std::string("Failed to get playback volume, error: ") + snd_strerror(err));
vol -= minv;
maxv = maxv - minv;
volume.volume = static_cast<double>(vol) / static_cast<double>(maxv);
}
int val;
if ((err = snd_mixer_selem_get_playback_switch(elem_, SND_MIXER_SCHN_MONO, &val)) < 0)
throw SnapException(std::string("Failed to get mute state, error: ") + snd_strerror(err));
volume.mute = (val == 0);
LOG(DEBUG, LOG_TAG) << "Get volume, mixer volume range [" << minv << ", " << maxv << "], volume: " << volume.volume << ", muted: " << volume.mute
<< "\n";
snd_mixer_handle_events(mixer_);
return true;
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << "\n";
return false;
}
}
void AlsaPlayer::waitForEvent()
{
sd_.async_wait(boost::asio::posix::stream_descriptor::wait_read,
[this](const boost::system::error_code& ec)
{
if (ec)
{
// TODO: fd is "Bad" after unplugging/plugging USB DAC, i.e. after init/uninit/init cycle
LOG(DEBUG, LOG_TAG) << "waitForEvent error: " << ec.message() << "\n";
return;
}
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (ctl_ == nullptr)
return;
unsigned short revents;
snd_ctl_poll_descriptors_revents(ctl_, fd_.get(), 1, &revents);
if (((revents & POLLIN) != 0) || (revents == 0))
{
snd_ctl_event_t* event;
snd_ctl_event_alloca(&event);
if (((snd_ctl_read(ctl_, event) >= 0) && (snd_ctl_event_get_type(event) == SND_CTL_EVENT_ELEM)) || (revents == 0))
{
auto now = std::chrono::steady_clock::now();
if (now - last_change_ < 1s)
{
LOG(DEBUG, LOG_TAG) << "Last volume change by server: " << std::chrono::duration_cast<std::chrono::milliseconds>(now - last_change_).count()
<< " ms => ignoring volume change\n";
waitForEvent();
return;
}
// Sometimes the old volume is reported by getHardwareVolume after this event has been raised.
// As workaround we defer getting the volume by 20ms.
timer_.cancel();
timer_.expires_after(20ms);
timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (!ec)
{
if (getHardwareVolume(volume_))
{
LOG(DEBUG, LOG_TAG) << "Volume changed: " << volume_.volume << ", muted: " << volume_.mute << "\n";
notifyVolumeChange(volume_);
}
}
});
}
}
waitForEvent();
});
}
void AlsaPlayer::initMixer()
{
if (settings_.mixer.mode != ClientSettings::Mixer::Mode::hardware)
return;
LOG(DEBUG, LOG_TAG) << "initMixer\n";
std::lock_guard<std::recursive_mutex> lock(mutex_);
int err;
if ((err = snd_ctl_open(&ctl_, mixer_device_.c_str(), SND_CTL_READONLY)) < 0)
throw SnapException("Can't open control for " + mixer_device_ + ", error: " + snd_strerror(err));
if ((err = snd_ctl_subscribe_events(ctl_, 1)) < 0)
throw SnapException("Can't subscribe for events for " + mixer_device_ + ", error: " + snd_strerror(err));
fd_ = std::unique_ptr<pollfd, std::function<void(pollfd*)>>(new pollfd(),
[](pollfd* p)
{
close(p->fd);
delete p;
});
err = snd_ctl_poll_descriptors(ctl_, fd_.get(), 1);
LOG(DEBUG, LOG_TAG) << "Filled " << err << " poll descriptors, poll descriptor count: " << snd_ctl_poll_descriptors_count(ctl_) << ", fd: " << fd_->fd
<< "\n";
snd_mixer_selem_id_t* sid;
snd_mixer_selem_id_alloca(&sid);
int mix_index = 0;
// sets simple-mixer index and name
snd_mixer_selem_id_set_index(sid, mix_index);
snd_mixer_selem_id_set_name(sid, mixer_name_.c_str());
if ((err = snd_mixer_open(&mixer_, 0)) < 0)
throw SnapException(std::string("Failed to open mixer, error: ") + snd_strerror(err));
if ((err = snd_mixer_attach(mixer_, mixer_device_.c_str())) < 0)
throw SnapException("Failed to attach mixer to " + mixer_device_ + ", error: " + snd_strerror(err));
if ((err = snd_mixer_selem_register(mixer_, nullptr, nullptr)) < 0)
throw SnapException(std::string("Failed to register selem, error: ") + snd_strerror(err));
if ((err = snd_mixer_load(mixer_)) < 0)
throw SnapException(std::string("Failed to load mixer, error: ") + snd_strerror(err));
elem_ = snd_mixer_find_selem(mixer_, sid);
if (elem_ == nullptr)
throw SnapException("Failed to find mixer: " + mixer_name_);
sd_ = boost::asio::posix::stream_descriptor(io_context_, fd_->fd);
waitForEvent();
}
void AlsaPlayer::initAlsa()
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
const SampleFormat& format = stream_->getFormat();
uint32_t rate = format.rate();
int channels = format.channels();
int err;
// Open the PCM device in playback mode
if ((err = snd_pcm_open(&handle_, settings_.pcm_device.name.c_str(), SND_PCM_STREAM_PLAYBACK, 0)) < 0)
throw SnapException("Can't open " + settings_.pcm_device.name + ", error: " + snd_strerror(err), err);
// struct snd_pcm_playback_info_t pinfo;
// if ((pcm = snd_pcm_playback_info( pcm_handle, &pinfo)) < 0)
// fprintf(stderr, "Error: playback info error: %s\n", snd_strerror(err));
// printf("buffer: '%d'\n", pinfo.buffer_size);
// Allocate parameters object and fill it with default values
snd_pcm_hw_params_t* params;
snd_pcm_hw_params_alloca(¶ms);
if ((err = snd_pcm_hw_params_any(handle_, params)) < 0)
throw SnapException("Can't fill params: " + string(snd_strerror(err)));
snd_output_t* output;
if (snd_output_buffer_open(&output) == 0)
{
if (snd_pcm_hw_params_dump(params, output) == 0)
{
char* str;
size_t len = snd_output_buffer_string(output, &str);
LOG(DEBUG, LOG_TAG) << std::string(str, len) << "\n";
}
snd_output_close(output);
}
// Set parameters
if ((err = snd_pcm_hw_params_set_access(handle_, params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
throw SnapException("Can't set interleaved mode: " + string(snd_strerror(err)));
snd_pcm_format_t snd_pcm_format;
if (format.bits() == 8)
snd_pcm_format = SND_PCM_FORMAT_S8;
else if (format.bits() == 16)
snd_pcm_format = SND_PCM_FORMAT_S16_LE;
else if ((format.bits() == 24) && (format.sampleSize() == 4))
snd_pcm_format = SND_PCM_FORMAT_S24_LE;
else if (format.bits() == 32)
snd_pcm_format = SND_PCM_FORMAT_S32_LE;
else
throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits()));
err = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format);
if (err == -EINVAL)
{
if (snd_pcm_format == SND_PCM_FORMAT_S24_LE)
{
snd_pcm_format = SND_PCM_FORMAT_S32_LE;
volCorrection_ = 256;
}
if (snd_pcm_format == SND_PCM_FORMAT_S8)
{
snd_pcm_format = SND_PCM_FORMAT_U8;
}
}
err = snd_pcm_hw_params_set_format(handle_, params, snd_pcm_format);
if (err < 0)
{
stringstream ss;
ss << "Can't set format: " << string(snd_strerror(err)) << ", supported: ";
for (int format = 0; format <= static_cast<int>(SND_PCM_FORMAT_LAST); format++)
{
auto snd_pcm_format = static_cast<snd_pcm_format_t>(format);
if (snd_pcm_hw_params_test_format(handle_, params, snd_pcm_format) == 0)
ss << snd_pcm_format_name(snd_pcm_format) << " ";
}
throw SnapException(ss.str());
}
if ((err = snd_pcm_hw_params_set_channels(handle_, params, channels)) < 0)
throw SnapException("Can't set channel count: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params_set_rate_near(handle_, params, &rate, nullptr)) < 0)
throw SnapException("Can't set rate: " + string(snd_strerror(err)));
if (rate != format.rate())
LOG(WARNING, LOG_TAG) << "Could not set sample rate to " << format.rate() << " Hz, using: " << rate << " Hz\n";
uint32_t period_time = buffer_time_.value_or(BUFFER_TIME).count() / periods_.value_or(PERIODS);
uint32_t max_period_time = period_time;
if ((err = snd_pcm_hw_params_get_period_time_max(params, &max_period_time, nullptr)) < 0)
{
LOG(ERROR, LOG_TAG) << "Can't get max period time: " << snd_strerror(err) << "\n";
}
else
{
if (period_time > max_period_time)
{
LOG(INFO, LOG_TAG) << "Period time too large, changing from " << period_time << " to " << max_period_time << "\n";
period_time = max_period_time;
}
}
uint32_t min_period_time = period_time;
if ((err = snd_pcm_hw_params_get_period_time_min(params, &min_period_time, nullptr)) < 0)
{
LOG(ERROR, LOG_TAG) << "Can't get min period time: " << snd_strerror(err) << "\n";
}
else
{
if (period_time < min_period_time)
{
LOG(INFO, LOG_TAG) << "Period time too small, changing from " << period_time << " to " << min_period_time << "\n";
period_time = min_period_time;
}
}
if ((err = snd_pcm_hw_params_set_period_time_near(handle_, params, &period_time, nullptr)) < 0)
throw SnapException("Can't set period time: " + string(snd_strerror(err)));
uint32_t buffer_time = buffer_time_.value_or(BUFFER_TIME).count();
uint32_t periods = periods_.value_or(MIN_PERIODS);
if (buffer_time < period_time * periods)
{
LOG(INFO, LOG_TAG) << "Buffer time smaller than " << periods << " * periods: " << buffer_time << " us < " << period_time * periods
<< " us, raising buffer time\n";
buffer_time = period_time * periods;
}
if ((err = snd_pcm_hw_params_set_buffer_time_near(handle_, params, &buffer_time, nullptr)) < 0)
throw SnapException("Can't set buffer time to " + cpt::to_string(buffer_time) + " us : " + string(snd_strerror(err)));
// unsigned int periods = periods_;
// if ((err = snd_pcm_hw_params_set_periods_near(handle_, params, &periods, 0)) < 0)
// throw SnapException("Can't set periods: " + string(snd_strerror(err)));
// Write parameters
if ((err = snd_pcm_hw_params(handle_, params)) < 0)
throw SnapException("Can't set hardware parameters: " + string(snd_strerror(err)));
// Resume information
// uint32_t periods;
if (snd_pcm_hw_params_get_periods(params, &periods, nullptr) < 0)
periods = round(static_cast<double>(buffer_time) / static_cast<double>(period_time));
snd_pcm_hw_params_get_period_size(params, &frames_, nullptr);
LOG(INFO, LOG_TAG) << "PCM name: " << snd_pcm_name(handle_) << ", sample rate: " << rate << " Hz, channels: " << channels
<< ", buffer time: " << buffer_time << " us, periods: " << periods << ", period time: " << period_time
<< " us, period frames: " << frames_ << "\n";
// Allocate buffer to hold single period
snd_pcm_sw_params_t* swparams;
snd_pcm_sw_params_alloca(&swparams);
snd_pcm_sw_params_current(handle_, swparams);
snd_pcm_sw_params_set_avail_min(handle_, swparams, frames_);
snd_pcm_sw_params_set_start_threshold(handle_, swparams, frames_);
// snd_pcm_sw_params_set_stop_threshold(pcm_handle, swparams, frames_);
snd_pcm_sw_params(handle_, swparams);
if (snd_pcm_state(handle_) == SND_PCM_STATE_PREPARED)
{
if ((err = snd_pcm_start(handle_)) < 0)
LOG(DEBUG, LOG_TAG) << "Failed to start PCM: " << snd_strerror(err) << "\n";
}
if (ctl_ == nullptr)
initMixer();
}
void AlsaPlayer::uninitAlsa(bool uninit_mixer)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (uninit_mixer)
uninitMixer();
if (handle_ != nullptr)
{
snd_pcm_drop(handle_);
snd_pcm_close(handle_);
handle_ = nullptr;
}
}
void AlsaPlayer::uninitMixer()
{
if (settings_.mixer.mode != ClientSettings::Mixer::Mode::hardware)
return;
LOG(DEBUG, LOG_TAG) << "uninitMixer\n";
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (sd_.is_open())
{
boost::system::error_code ec;
sd_.cancel(ec);
}
if (ctl_ != nullptr)
{
snd_ctl_close(ctl_);
ctl_ = nullptr;
}
if (mixer_ != nullptr)
{
snd_mixer_close(mixer_);
mixer_ = nullptr;
}
fd_ = nullptr;
elem_ = nullptr;
}
void AlsaPlayer::start()
{
try
{
initAlsa();
}
catch (const SnapException& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << ", code: " << e.code() << "\n";
// Accept "Device or ressource busy", the worker loop will retry
if (e.code() != -EBUSY)
throw;
}
Player::start();
}
AlsaPlayer::~AlsaPlayer()
{
stop();
}
void AlsaPlayer::stop()
{
Player::stop();
uninitAlsa(true);
}
bool AlsaPlayer::needsThread() const
{
return true;
}
bool AlsaPlayer::getAvailDelay(snd_pcm_sframes_t& avail, snd_pcm_sframes_t& delay)
{
int result = snd_pcm_avail_delay(handle_, &avail, &delay);
if (result < 0)
{
LOG(WARNING, LOG_TAG) << "snd_pcm_avail_delay failed: " << snd_strerror(result) << " (" << result << "), avail: " << avail << ", delay: " << delay
<< ", using snd_pcm_avail amd snd_pcm_delay.\n";
this_thread::sleep_for(1ms);
avail = snd_pcm_avail(handle_);
result = snd_pcm_delay(handle_, &delay);
if ((result < 0) || (delay < 0))
{
LOG(WARNING, LOG_TAG) << "snd_pcm_delay failed: " << snd_strerror(result) << " (" << result << "), avail: " << avail << ", delay: " << delay
<< "\n";
return false;
}
// LOG(DEBUG, LOG_TAG) << "snd_pcm_delay: " << delay << ", snd_pcm_avail: " << avail << "\n";
}
if (avail < 0)
{
LOG(DEBUG, LOG_TAG) << "snd_pcm_avail failed: " << snd_strerror(avail) << " (" << avail << "), using " << frames_ << "\n";
avail = frames_;
}
return true;
}
void AlsaPlayer::worker()
{
snd_pcm_sframes_t pcm;
snd_pcm_sframes_t framesDelay;
snd_pcm_sframes_t framesAvail;
long lastChunkTick = chronos::getTickCount();
const SampleFormat& format = stream_->getFormat();
while (active_)
{
if (handle_ == nullptr)
{
try
{
initAlsa();
// set the hardware volume. It might have changed when we were not initialized
if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware)
setHardwareVolume(volume_);
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception in initAlsa: " << e.what() << endl;
chronos::sleep(100);
}
if (handle_ == nullptr)
continue;
}
int wait_result = snd_pcm_wait(handle_, 100);
if (wait_result == -EPIPE)
{
LOG(ERROR, LOG_TAG) << "XRUN while waiting for PCM: " << snd_strerror(wait_result) << "\n";
snd_pcm_prepare(handle_);
}
else if (wait_result < 0)
{
LOG(ERROR, LOG_TAG) << "ERROR. Can't wait for PCM to become ready: " << snd_strerror(wait_result) << "\n";
uninitAlsa(true);
continue;
}
else if (wait_result == 0)
{
continue;
}
if (!getAvailDelay(framesAvail, framesDelay))
{
this_thread::sleep_for(10ms);
snd_pcm_prepare(handle_);
continue;
}
// if (framesAvail < static_cast<snd_pcm_sframes_t>(frames_))
// {
// this_thread::sleep_for(5ms);
// continue;
// }
if (framesAvail == 0)
{
auto frame_time = std::chrono::microseconds(static_cast<int>(frames_ / format.usRate()));
std::chrono::microseconds wait = std::min(frame_time / 2, std::chrono::microseconds(10ms));
LOG(DEBUG, LOG_TAG) << "No frames available, waiting for " << wait.count() << " us\n";
this_thread::sleep_for(wait);
continue;
}
// LOG(TRACE, LOG_TAG) << "res: " << result << ", framesAvail: " << framesAvail << ", delay: " << framesDelay << ", frames: " << frames_ << "\n";
chronos::usec delay(static_cast<chronos::usec::rep>(1000 * static_cast<double>(framesDelay) / format.msRate()));
// LOG(TRACE, LOG_TAG) << "delay: " << framesDelay << ", delay[ms]: " << delay.count() / 1000 << ", avail: " << framesAvail << "\n";
if (buffer_.size() < static_cast<size_t>(framesAvail * format.frameSize()))
{
LOG(DEBUG, LOG_TAG) << "Resizing buffer from " << buffer_.size() << " to " << framesAvail * format.frameSize() << "\n";
buffer_.resize(framesAvail * format.frameSize());
}
if (stream_->getPlayerChunk(buffer_.data(), delay, framesAvail))
{
lastChunkTick = chronos::getTickCount();
adjustVolume(buffer_.data(), framesAvail);
if ((pcm = snd_pcm_writei(handle_, buffer_.data(), framesAvail)) == -EPIPE)
{
LOG(ERROR, LOG_TAG) << "XRUN while writing to PCM: " << snd_strerror(pcm) << "\n";
snd_pcm_prepare(handle_);
}
else if (pcm < 0)
{
LOG(ERROR, LOG_TAG) << "ERROR. Can't write to PCM device: " << snd_strerror(pcm) << "\n";
uninitAlsa(true);
}
}
else
{
LOG(INFO, LOG_TAG) << "Failed to get chunk\n";
while (active_ && !stream_->waitForChunk(100ms))
{
// Log "Waiting for chunk" only every second second
static utils::logging::TimeConditional cond(2s);
LOG(DEBUG, LOG_TAG) << cond << "Waiting for chunk\n";
if ((handle_ != nullptr) && (chronos::getTickCount() - lastChunkTick > 5000))
{
LOG(NOTICE, LOG_TAG) << "No chunk received for 5000ms. Closing ALSA.\n";
uninitAlsa(false);
stream_->clearChunks();
}
}
}
}
}
vector<PcmDevice> AlsaPlayer::pcm_list()
{
void **hints, **n;
char *name, *descr, *io;
vector<PcmDevice> result;
PcmDevice pcmDevice;
if (snd_device_name_hint(-1, "pcm", &hints) < 0)
return result;
n = hints;
size_t idx(0);
while (*n != nullptr)
{
name = snd_device_name_get_hint(*n, "NAME");
descr = snd_device_name_get_hint(*n, "DESC");
io = snd_device_name_get_hint(*n, "IOID");
if (io != nullptr && strcmp(io, "Output") != 0)
goto __end;
pcmDevice.name = name;
if (descr == nullptr)
{
pcmDevice.description = "";
}
else
{
pcmDevice.description = descr;
}
pcmDevice.idx = idx++;
result.push_back(pcmDevice);
__end:
if (name != nullptr)
free(name);
if (descr != nullptr)
free(descr);
if (io != nullptr)
free(io);
n++;
}
snd_device_name_free_hint(hints);
return result;
}
} // namespace player
| 26,928
|
C++
|
.cpp
| 626
| 33.976038
| 160
| 0.555789
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,989
|
opensl_player.cpp
|
badaix_snapcast/client/player/opensl_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "opensl_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
namespace player
{
static constexpr auto LOG_TAG = "OpenSlPlayer";
static constexpr auto kPhaseInit = "Init";
static constexpr auto kPhaseStart = "Start";
static constexpr auto kPhaseStop = "Stop";
// http://stackoverflow.com/questions/35730050/android-with-nexus-6-how-to-avoid-decreased-opensl-audio-thread-priority-rela?rq=1
// source: https://github.com/hrydgard/native/blob/master/android/native-audio-so.cpp
// https://android.googlesource.com/platform/development/+/c21a505/ndk/platforms/android-9/samples/native-audio/jni/native-audio-jni.c
// This callback handler is called every time a buffer finishes playing.
// The documentation available is very unclear about how to best manage buffers.
// I've chosen to this approach: Instantly enqueue a buffer that was rendered to the last time,
// and then render the next. Hopefully it's okay to spend time in this callback after having enqueued.
static void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void* context)
{
OpenslPlayer* player = static_cast<OpenslPlayer*>(context);
player->playerCallback(bq);
}
OpenslPlayer::OpenslPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream), engineObject(nullptr), engineEngine(nullptr), outputMixObject(nullptr), bqPlayerObject(nullptr),
bqPlayerPlay(nullptr), bqPlayerBufferQueue(nullptr), bqPlayerVolume(nullptr), curBuffer(0), ms_(50), buff_size(0), pubStream_(stream)
{
initOpensl();
}
OpenslPlayer::~OpenslPlayer()
{
uninitOpensl();
}
void OpenslPlayer::playerCallback(SLAndroidSimpleBufferQueueItf bq)
{
if (bq != bqPlayerBufferQueue)
{
LOG(ERROR, LOG_TAG) << "Wrong bq!\n";
return;
}
if (!active_)
return;
chronos::usec delay(ms_ * 1000);
if (!pubStream_->getPlayerChunkOrSilence(buffer[curBuffer], delay, frames_))
{
// LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n";
}
else
{
adjustVolume(buffer[curBuffer], frames_);
}
while (active_)
{
SLresult result = (*bq)->Enqueue(bq, buffer[curBuffer], buff_size);
if (result == SL_RESULT_BUFFER_INSUFFICIENT)
chronos::sleep(1);
else
break;
}
curBuffer ^= 1; // Switch buffer
}
std::string OpenslPlayer::resultToString(SLresult result) const
{
switch (result)
{
case SL_RESULT_SUCCESS:
return "SL_RESULT_SUCCESS";
case SL_RESULT_PRECONDITIONS_VIOLATED:
return "SL_RESULT_PRECONDITIONS_VIOLATED";
case SL_RESULT_PARAMETER_INVALID:
return "SL_RESULT_PARAMETER_INVALID";
case SL_RESULT_MEMORY_FAILURE:
return "SL_RESULT_MEMORY_FAILURE";
case SL_RESULT_RESOURCE_ERROR:
return "SL_RESULT_RESOURCE_ERROR";
case SL_RESULT_RESOURCE_LOST:
return "SL_RESULT_RESOURCE_LOST";
case SL_RESULT_IO_ERROR:
return "SL_RESULT_IO_ERROR";
case SL_RESULT_BUFFER_INSUFFICIENT:
return "SL_RESULT_BUFFER_INSUFFICIENT";
case SL_RESULT_CONTENT_CORRUPTED:
return "SL_RESULT_CONTENT_CORRUPTED";
case SL_RESULT_CONTENT_UNSUPPORTED:
return "SL_RESULT_CONTENT_UNSUPPORTED";
case SL_RESULT_CONTENT_NOT_FOUND:
return "SL_RESULT_CONTENT_NOT_FOUND";
case SL_RESULT_PERMISSION_DENIED:
return "SL_RESULT_PERMISSION_DENIED";
case SL_RESULT_FEATURE_UNSUPPORTED:
return "SL_RESULT_FEATURE_UNSUPPORTED";
case SL_RESULT_INTERNAL_ERROR:
return "SL_RESULT_INTERNAL_ERROR";
case SL_RESULT_UNKNOWN_ERROR:
return "SL_RESULT_UNKNOWN_ERROR";
case SL_RESULT_OPERATION_ABORTED:
return "SL_RESULT_OPERATION_ABORTED";
case SL_RESULT_CONTROL_LOST:
return "SL_RESULT_CONTROL_LOST";
default:
return "UNKNOWN";
}
}
bool OpenslPlayer::needsThread() const
{
return false;
}
void OpenslPlayer::throwUnsuccess(const std::string& phase, const std::string& what, SLresult result)
{
if (SL_RESULT_SUCCESS == result)
return;
stringstream ss;
ss << phase << " failed, operation: " << what << ", result: " << resultToString(result) << "(" << result << ")";
throw SnapException(ss.str());
}
void OpenslPlayer::initOpensl()
{
if (active_)
return;
LOG(INFO, LOG_TAG) << "Init start\n";
const SampleFormat& format = stream_->getFormat();
frames_ = format.rate() / (1000 / ms_); // * format.channels(); // 1920; // 48000 * 2 / 50 // => 50ms
buff_size = frames_ * format.frameSize() /* 2 -> sample size */;
LOG(INFO, LOG_TAG) << "frames: " << frames_ << ", channels: " << format.channels() << ", rate: " << format.rate() << ", buff: " << buff_size << "\n";
SLresult result;
// create engine
SLEngineOption engineOption[] = {{(SLuint32)SL_ENGINEOPTION_THREADSAFE, (SLuint32)SL_BOOLEAN_TRUE}};
result = slCreateEngine(&engineObject, 1, engineOption, 0, nullptr, nullptr);
throwUnsuccess(kPhaseInit, "slCreateEngine", result);
result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
throwUnsuccess(kPhaseInit, "EngineObject::Realize", result);
result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
throwUnsuccess(kPhaseInit, "EngineObject::GetInterface", result);
result = (*engineEngine)->CreateOutputMix(engineEngine, &outputMixObject, 0, 0, 0);
throwUnsuccess(kPhaseInit, "EngineEngine::CreateOutputMix", result);
result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE);
throwUnsuccess(kPhaseInit, "OutputMixObject::Realize", result);
SLuint32 samplesPerSec = SL_SAMPLINGRATE_48;
switch (format.rate())
{
case 8000:
samplesPerSec = SL_SAMPLINGRATE_8;
break;
case 11025:
samplesPerSec = SL_SAMPLINGRATE_11_025;
break;
case 16000:
samplesPerSec = SL_SAMPLINGRATE_16;
break;
case 22050:
samplesPerSec = SL_SAMPLINGRATE_22_05;
break;
case 24000:
samplesPerSec = SL_SAMPLINGRATE_24;
break;
case 32000:
samplesPerSec = SL_SAMPLINGRATE_32;
break;
case 44100:
samplesPerSec = SL_SAMPLINGRATE_44_1;
break;
case 48000:
samplesPerSec = SL_SAMPLINGRATE_48;
break;
case 64000:
samplesPerSec = SL_SAMPLINGRATE_64;
break;
case 88200:
samplesPerSec = SL_SAMPLINGRATE_88_2;
break;
case 96000:
samplesPerSec = SL_SAMPLINGRATE_96;
break;
case 192000:
samplesPerSec = SL_SAMPLINGRATE_192;
break;
default:
throw SnapException("Sample rate not supported");
}
SLuint32 bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
SLuint32 containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
switch (format.bits())
{
case 8:
bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_8;
containerSize = SL_PCMSAMPLEFORMAT_FIXED_8;
break;
case 16:
bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_16;
containerSize = SL_PCMSAMPLEFORMAT_FIXED_16;
break;
case 24:
bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_24;
containerSize = SL_PCMSAMPLEFORMAT_FIXED_32;
break;
case 32:
bitsPerSample = SL_PCMSAMPLEFORMAT_FIXED_32;
containerSize = SL_PCMSAMPLEFORMAT_FIXED_32;
break;
default:
throw SnapException("Unsupported sample format: " + cpt::to_string(format.bits()));
}
SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2};
SLDataFormat_PCM format_pcm = {
SL_DATAFORMAT_PCM, format.channels(), samplesPerSec, bitsPerSample, containerSize, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT,
SL_BYTEORDER_LITTLEENDIAN};
SLDataSource audioSrc = {&loc_bufq, &format_pcm};
// configure audio sink
SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject};
SLDataSink audioSnk = {&loc_outmix, nullptr};
// create audio player
const SLInterfaceID ids[3] = {SL_IID_ANDROIDCONFIGURATION, SL_IID_PLAY, SL_IID_BUFFERQUEUE}; //, SL_IID_VOLUME};
const SLboolean req[3] = {SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE, SL_BOOLEAN_TRUE}; //, SL_BOOLEAN_TRUE};
result = (*engineEngine)->CreateAudioPlayer(engineEngine, &bqPlayerObject, &audioSrc, &audioSnk, 3, ids, req);
throwUnsuccess(kPhaseInit, "Engine::CreateAudioPlayer", result);
SLAndroidConfigurationItf playerConfig;
result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_ANDROIDCONFIGURATION, &playerConfig);
throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result);
SLint32 streamType = SL_ANDROID_STREAM_MEDIA;
//// SLint32 streamType = SL_ANDROID_STREAM_VOICE;
result = (*playerConfig)->SetConfiguration(playerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32));
throwUnsuccess(kPhaseInit, "PlayerConfig::SetConfiguration", result);
// Set the performance mode.
SLuint32 performanceMode = SL_ANDROID_PERFORMANCE_NONE;
result = (*playerConfig)->SetConfiguration(playerConfig, SL_ANDROID_KEY_PERFORMANCE_MODE, &performanceMode, sizeof(performanceMode));
result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE);
throwUnsuccess(kPhaseInit, "PlayerObject::Realize", result);
result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay);
throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result);
result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue);
throwUnsuccess(kPhaseInit, "PlayerObject::GetInterface", result);
result = (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this);
throwUnsuccess(kPhaseInit, "PlayerBufferQueue::RegisterCallback", result);
// result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_VOLUME, &bqPlayerVolume);
// throwUnsuccess("PlayerObject::GetInterface", result);
result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PAUSED);
throwUnsuccess(kPhaseInit, "PlayerPlay::SetPlayState", result);
// Render and enqueue a first buffer. (or should we just play the buffer empty?)
curBuffer = 0;
buffer[0] = new char[buff_size];
buffer[1] = new char[buff_size];
active_ = true;
memset(buffer[curBuffer], 0, buff_size);
result = (*bqPlayerBufferQueue)->Enqueue(bqPlayerBufferQueue, buffer[curBuffer], sizeof(buffer[curBuffer]));
throwUnsuccess(kPhaseInit, "PlayerBufferQueue::Enqueue", result);
curBuffer ^= 1;
LOG(INFO, LOG_TAG) << "Init done\n";
}
void OpenslPlayer::uninitOpensl()
{
// if (!active_)
// return;
LOG(INFO, LOG_TAG) << "uninitOpensl\n";
SLresult result;
LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - stopping playback\n";
if (bqPlayerPlay != nullptr)
{
result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED);
if (SL_RESULT_SUCCESS != result)
LOG(ERROR, LOG_TAG) << "SetPlayState failed\n";
}
LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting player object\n";
if (bqPlayerObject != nullptr)
{
(*bqPlayerObject)->Destroy(bqPlayerObject);
bqPlayerObject = nullptr;
bqPlayerPlay = nullptr;
bqPlayerBufferQueue = nullptr;
bqPlayerVolume = nullptr;
}
LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting mix object\n";
if (outputMixObject != nullptr)
{
(*outputMixObject)->Destroy(outputMixObject);
outputMixObject = nullptr;
}
LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - deleting engine object\n";
if (engineObject != nullptr)
{
(*engineObject)->Destroy(engineObject);
engineObject = nullptr;
engineEngine = nullptr;
}
delete[] buffer[0];
buffer[0] = nullptr;
delete[] buffer[1];
buffer[1] = nullptr;
LOG(INFO, LOG_TAG) << "OpenSLWrap_Shutdown - finished\n";
active_ = false;
}
void OpenslPlayer::start()
{
SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING);
throwUnsuccess(kPhaseStart, "PlayerPlay::SetPlayState", result);
}
void OpenslPlayer::stop()
{
SLresult result = (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED);
(*bqPlayerBufferQueue)->Clear(bqPlayerBufferQueue);
throwUnsuccess(kPhaseStop, "PlayerPlay::SetPlayState", result);
}
} // namespace player
| 13,919
|
C++
|
.cpp
| 321
| 36.657321
| 153
| 0.680834
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,990
|
player.cpp
|
badaix_snapcast/client/player/player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
// 3rd party headers
#ifdef SUPPORTS_VOLUME_SCRIPT
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunused-result"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wmissing-braces"
#pragma GCC diagnostic ignored "-Wnarrowing"
#pragma GCC diagnostic ignored "-Wc++11-narrowing"
#include <boost/process/args.hpp>
#include <boost/process/async.hpp>
#include <boost/process/child.hpp>
#include <boost/process/exe.hpp>
#pragma GCC diagnostic pop
#endif
// standard headers
#include <cmath>
#include <iostream>
#include <memory>
#include <optional>
using namespace std;
namespace player
{
static constexpr auto LOG_TAG = "Player";
Player::Player(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: io_context_(io_context), active_(false), stream_(stream), settings_(settings), volCorrection_(1.0)
{
string sharing_mode;
switch (settings_.sharing_mode)
{
case ClientSettings::SharingMode::unspecified:
sharing_mode = "unspecified";
break;
case ClientSettings::SharingMode::exclusive:
sharing_mode = "exclusive";
break;
case ClientSettings::SharingMode::shared:
sharing_mode = "shared";
break;
}
auto not_empty = [](const std::string& value) -> std::string
{
if (!value.empty())
return value;
else
return "<none>";
};
LOG(INFO, LOG_TAG) << "Player name: " << not_empty(settings_.player_name) << ", device: " << not_empty(settings_.pcm_device.name)
<< ", description: " << not_empty(settings_.pcm_device.description) << ", idx: " << settings_.pcm_device.idx
<< ", sharing mode: " << sharing_mode << ", parameters: " << not_empty(settings.parameter) << "\n";
string mixer;
switch (settings_.mixer.mode)
{
case ClientSettings::Mixer::Mode::hardware:
mixer = "hardware";
break;
case ClientSettings::Mixer::Mode::software:
mixer = "software";
break;
case ClientSettings::Mixer::Mode::script:
mixer = "script";
break;
case ClientSettings::Mixer::Mode::none:
mixer = "none";
break;
}
LOG(INFO, LOG_TAG) << "Mixer mode: " << mixer << ", parameters: " << not_empty(settings_.mixer.parameter) << "\n";
LOG(INFO, LOG_TAG) << "Sampleformat: " << (settings_.sample_format.isInitialized() ? settings_.sample_format.toString() : stream->getFormat().toString())
<< ", stream: " << stream->getFormat().toString() << "\n";
}
Player::~Player()
{
stop();
}
void Player::start()
{
active_ = true;
if (needsThread())
playerThread_ = thread(&Player::worker, this);
// If hardware mixer is used, send the initial volume to the server, because this is
// the volume that is configured by the user on his local device, so we shouldn't change it
// on client start up
// if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware)
// {
// if (getHardwareVolume(volume_, muted_))
// {
// LOG(DEBUG, LOG_TAG) << "Volume: " << volume_ << ", muted: " << muted_ << "\n";
// notifyVolumeChange(volume_, muted_);
// }
// }
}
void Player::stop()
{
if (active_)
{
active_ = false;
if (playerThread_.joinable())
playerThread_.join();
}
}
void Player::worker()
{
}
void Player::setHardwareVolume(const Volume& volume)
{
std::ignore = volume;
throw SnapException("Failed to set hardware mixer volume: not supported");
}
bool Player::getHardwareVolume(Volume& volume)
{
std::ignore = volume;
throw SnapException("Failed to get hardware mixer volume: not supported");
}
void Player::adjustVolume(char* buffer, size_t frames)
{
std::lock_guard<std::mutex> lock(mutex_);
double volume = volCorrection_;
// apply volume changes only for software mixer
// for any other mixer, we might still have to apply the volCorrection_
if (settings_.mixer.mode == ClientSettings::Mixer::Mode::software)
{
volume = volume_.mute ? 0. : volume_.volume;
volume *= volCorrection_;
}
if (volume != 1.0)
{
const SampleFormat& sampleFormat = stream_->getFormat();
if (sampleFormat.sampleSize() == 1)
adjustVolume<int8_t>(buffer, frames * sampleFormat.channels(), volume);
else if (sampleFormat.sampleSize() == 2)
adjustVolume<int16_t>(buffer, frames * sampleFormat.channels(), volume);
else if (sampleFormat.sampleSize() == 4)
adjustVolume<int32_t>(buffer, frames * sampleFormat.channels(), volume);
}
}
// https://cgit.freedesktop.org/pulseaudio/pulseaudio/tree/src/pulse/volume.c#n260
// http://www.robotplanet.dk/audio/audio_gui_design/
// https://lists.linuxaudio.org/pipermail/linux-audio-dev/2009-May/thread.html#22198
void Player::setVolume_poly(double volume, double exp)
{
volume_.volume = std::pow(volume, exp);
LOG(DEBUG, LOG_TAG) << "setVolume poly with exp " << exp << ": " << volume << " => " << volume_.volume << "\n";
}
// http://stackoverflow.com/questions/1165026/what-algorithms-could-i-use-for-audio-volume-level
void Player::setVolume_exp(double volume, double base)
{
// double base = M_E;
// double base = 10.;
volume_.volume = (pow(base, volume) - 1) / (base - 1);
LOG(DEBUG, LOG_TAG) << "setVolume exp with base " << base << ": " << volume << " => " << volume_.volume << "\n";
}
void Player::setVolume(const Volume& volume)
{
std::lock_guard<std::mutex> lock(mutex_);
volume_ = volume;
if (settings_.mixer.mode == ClientSettings::Mixer::Mode::hardware)
{
setHardwareVolume(volume);
}
else if (settings_.mixer.mode == ClientSettings::Mixer::Mode::software)
{
string param;
string mode = utils::string::split_left(settings_.mixer.parameter, ':', param);
double dparam = -1.;
if (!param.empty())
{
try
{
dparam = cpt::stod(param);
if (dparam < 0)
throw SnapException("must be a positive number");
}
catch (const std::exception& e)
{
throw SnapException("Invalid mixer param: " + param + ", error: " + string(e.what()));
}
}
if (mode == "poly")
setVolume_poly(volume.volume, (dparam < 0) ? 3. : dparam);
else
setVolume_exp(volume.volume, (dparam < 0) ? 10. : dparam);
}
else if (settings_.mixer.mode == ClientSettings::Mixer::Mode::script)
{
#ifdef SUPPORTS_VOLUME_SCRIPT
static std::optional<Volume> pending_volume_change;
static boost::process::child mixer_script_process;
if (mixer_script_process.running())
{
pending_volume_change = volume;
LOG(DEBUG, LOG_TAG) << "Volume mixer script still running, deferring this volume change\n";
}
else
{
try
{
namespace bp = boost::process;
mixer_script_process = bp::child(bp::exe = settings_.mixer.parameter,
bp::args = {"--volume", cpt::to_string(volume.volume), "--mute", volume.mute ? "true" : "false"},
bp::on_exit(
[&](int ret_val, std::error_code ec)
{
std::unique_lock<std::mutex> lock(mutex_);
LOG(DEBUG, LOG_TAG) << "Error code: " << ec.message() << ", i: " << ret_val << "\n";
if (pending_volume_change.has_value())
{
Volume v = pending_volume_change.value();
pending_volume_change = std::nullopt;
lock.unlock();
setVolume(v);
}
}),
io_context_);
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Failed to run script '" + settings_.mixer.parameter + "', error: " << e.what() << "\n";
pending_volume_change = std::nullopt;
}
}
#else
LOG(ERROR, LOG_TAG) << "Mixer mode 'script' not supported\n";
#endif
}
}
} // namespace player
| 9,686
|
C++
|
.cpp
| 247
| 31.105263
| 157
| 0.593172
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,991
|
file_player.cpp
|
badaix_snapcast/client/player/file_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "file_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
// 3rd party headers
// standard headers
using namespace std;
namespace player
{
static constexpr auto LOG_TAG = "FilePlayer";
static constexpr auto kDefaultBuffer = 50ms;
static constexpr auto kDescription = "Raw PCM file output";
std::vector<PcmDevice> FilePlayer::pcm_list(const std::string& parameter)
{
auto params = utils::string::split_pairs(parameter, ',', '=');
string filename;
if (params.find("filename") != params.end())
filename = params["filename"];
if (filename.empty())
filename = "stdout";
return {PcmDevice{0, filename, kDescription}};
}
FilePlayer::FilePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream), timer_(io_context), file_(nullptr)
{
auto params = utils::string::split_pairs(settings.parameter, ',', '=');
string filename;
if (params.find("filename") != params.end())
filename = params["filename"];
if (filename.empty() || (filename == "stdout"))
{
file_.reset(stdout, [](auto p) { std::ignore = p; });
}
else if (filename == "stderr")
{
file_.reset(stderr, [](auto p) { std::ignore = p; });
}
else if (filename != "null")
{
std::string mode = "w";
if (params.find("mode") != params.end())
mode = params["mode"];
if ((mode != "w") && (mode != "a"))
throw SnapException("Mode must be w (write) or a (append)");
mode += "b";
file_.reset(fopen(filename.c_str(), mode.c_str()), [](auto p) { fclose(p); });
if (!file_)
throw SnapException("Error opening file: '" + filename + "', error: " + cpt::to_string(errno));
}
}
FilePlayer::~FilePlayer()
{
LOG(DEBUG, LOG_TAG) << "Destructor\n";
stop();
}
bool FilePlayer::needsThread() const
{
return false;
}
void FilePlayer::requestAudio()
{
auto numFrames = static_cast<uint32_t>(stream_->getFormat().msRate() * kDefaultBuffer.count());
auto needed = numFrames * stream_->getFormat().frameSize();
if (buffer_.size() < needed)
buffer_.resize(needed);
if (!stream_->getPlayerChunkOrSilence(buffer_.data(), 10ms, numFrames))
{
// LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n";
}
else
{
adjustVolume(static_cast<char*>(buffer_.data()), numFrames);
}
if (file_)
{
fwrite(buffer_.data(), 1, needed, file_.get());
fflush(file_.get());
}
loop();
}
void FilePlayer::loop()
{
next_request_ += kDefaultBuffer;
auto now = std::chrono::steady_clock::now();
if (next_request_ < now)
next_request_ = now + 1ms;
timer_.expires_at(next_request_);
timer_.async_wait(
[this](boost::system::error_code ec)
{
if (ec)
return;
requestAudio();
});
}
void FilePlayer::start()
{
next_request_ = std::chrono::steady_clock::now();
loop();
}
void FilePlayer::stop()
{
LOG(INFO, LOG_TAG) << "Stop\n";
timer_.cancel();
}
} // namespace player
| 4,081
|
C++
|
.cpp
| 123
| 28.333333
| 131
| 0.642038
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,992
|
oboe_player.cpp
|
badaix_snapcast/client/player/oboe_player.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "oboe_player.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/str_compat.hpp"
// 3rd party headers
// standard headers
#include <cstring>
#include <iostream>
using namespace std;
namespace player
{
static constexpr auto LOG_TAG = "OboePlayer";
static constexpr double kDefaultLatency = 50;
OboePlayer::OboePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream)
: Player(io_context, settings, stream)
{
LOG(DEBUG, LOG_TAG) << "Contructor\n";
LOG(INFO, LOG_TAG) << "Init start\n";
char* env = getenv("SAMPLE_RATE");
if (env)
oboe::DefaultStreamValues::SampleRate = cpt::stoi(env, oboe::DefaultStreamValues::SampleRate);
env = getenv("FRAMES_PER_BUFFER");
if (env)
oboe::DefaultStreamValues::FramesPerBurst = cpt::stoi(env, oboe::DefaultStreamValues::FramesPerBurst);
LOG(INFO, LOG_TAG) << "DefaultStreamValues::SampleRate: " << oboe::DefaultStreamValues::SampleRate
<< ", DefaultStreamValues::FramesPerBurst: " << oboe::DefaultStreamValues::FramesPerBurst << "\n";
auto result = openStream();
LOG(INFO, LOG_TAG) << "BufferSizeInFrames: " << out_stream_->getBufferSizeInFrames() << ", FramesPerBurst: " << out_stream_->getFramesPerBurst() << "\n";
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error building AudioStream: " << oboe::convertToText(result) << "\n";
LOG(INFO, LOG_TAG) << "Init done\n";
}
OboePlayer::~OboePlayer()
{
LOG(DEBUG, LOG_TAG) << "Destructor\n";
stop();
auto result = out_stream_->stop(std::chrono::nanoseconds(100ms).count());
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error in AudioStream::stop: " << oboe::convertToText(result) << "\n";
result = out_stream_->close();
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error in AudioStream::stop: " << oboe::convertToText(result) << "\n";
}
oboe::Result OboePlayer::openStream()
{
oboe::SharingMode sharing_mode = oboe::SharingMode::Shared;
if (settings_.sharing_mode == ClientSettings::SharingMode::exclusive)
sharing_mode = oboe::SharingMode::Exclusive;
oboe::AudioFormat audio_format;
switch (stream_->getFormat().bits())
{
case 32:
audio_format = oboe::AudioFormat::I32;
break;
case 24:
audio_format = oboe::AudioFormat::I24;
break;
case 16:
default:
audio_format = oboe::AudioFormat::I16;
break;
}
// The builder set methods can be chained for convenience.
oboe::AudioStreamBuilder builder;
auto result = builder.setSharingMode(sharing_mode)
->setPerformanceMode(oboe::PerformanceMode::None)
->setChannelCount(stream_->getFormat().channels())
->setSampleRate(stream_->getFormat().rate())
->setFormat(audio_format)
->setDataCallback(this)
->setErrorCallback(this)
->setDirection(oboe::Direction::Output)
//->setFramesPerCallback((8 * stream->getFormat().rate) / 1000)
//->setFramesPerCallback(2 * oboe::DefaultStreamValues::FramesPerBurst)
//->setFramesPerCallback(960) // 2*192)
->openStream(out_stream_);
LOG(INFO, LOG_TAG) << "Hardware sample rate: " << out_stream_->getHardwareSampleRate()
<< ", hardware format: " << oboe::convertToText(out_stream_->getHardwareFormat()) << "\n";
if (out_stream_->getAudioApi() == oboe::AudioApi::AAudio)
{
LOG(INFO, LOG_TAG) << "AudioApi: AAudio\n";
latency_tuner_ = nullptr;
}
else
{
LOG(INFO, LOG_TAG) << "AudioApi: OpenSL\n";
out_stream_->setBufferSizeInFrames(4 * out_stream_->getFramesPerBurst());
}
return result;
}
bool OboePlayer::needsThread() const
{
return false;
}
double OboePlayer::getCurrentOutputLatencyMillis() const
{
// Get the time that a known audio frame was presented for playing
auto result = out_stream_->getTimestamp(CLOCK_MONOTONIC);
double outputLatencyMillis = kDefaultLatency;
const int64_t kNanosPerMillisecond = 1000000;
if (result == oboe::Result::OK)
{
oboe::FrameTimestamp playedFrame = result.value();
// Get the write index for the next audio frame
int64_t writeIndex = out_stream_->getFramesWritten();
// Calculate the number of frames between our known frame and the write index
int64_t frameIndexDelta = writeIndex - playedFrame.position;
// Calculate the time which the next frame will be presented
int64_t frameTimeDelta = (frameIndexDelta * oboe::kNanosPerSecond) / (out_stream_->getSampleRate());
int64_t nextFramePresentationTime = playedFrame.timestamp + frameTimeDelta;
// Assume that the next frame will be written at the current time
using namespace std::chrono;
int64_t nextFrameWriteTime = duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count();
// Calculate the latency
outputLatencyMillis = static_cast<double>(nextFramePresentationTime - nextFrameWriteTime) / kNanosPerMillisecond;
}
else
{
// LOG(ERROR, LOG_TAG) << "Error calculating latency: " << oboe::convertToText(result.error()) << "\n";
}
return outputLatencyMillis;
}
oboe::DataCallbackResult OboePlayer::onAudioReady(oboe::AudioStream* /*oboeStream*/, void* audioData, int32_t numFrames)
{
if (latency_tuner_)
latency_tuner_->tune();
double output_latency = getCurrentOutputLatencyMillis();
// LOG(INFO, LOG_TAG) << "getCurrentOutputLatencyMillis: " << output_latency << ", frames: " << numFrames << "\n";
chronos::usec delay(static_cast<int>(output_latency * 1000.));
void* buffer = audioData;
if (stream_->getFormat().bits() == 24)
{
// Oboe expects 24 bit audio in 3 bytes, while Snapcast stores 24 bit in 4 bytes.
// Data must be converted before passing it to Oboe, but first we need to adabt the buffer size
size_t needed = stream_->getFormat().frameSize() * numFrames;
if (audio_data_.size() < needed)
{
LOG(INFO, LOG_TAG) << "Resizing audio buffer to " << numFrames << " frames, (" << needed << ") bytes\n";
audio_data_.resize(needed);
}
buffer = audio_data_.data();
}
if (!stream_->getPlayerChunkOrSilence(buffer, delay, numFrames))
{
// LOG(INFO, LOG_TAG) << "Failed to get chunk. Playing silence.\n";
}
else
{
adjustVolume(static_cast<char*>(buffer), numFrames);
if (stream_->getFormat().bits() == 24)
{
// Copy the 24 bit, 4 bytes data into Oboes 24 bit, 3 bytes buffer
for (size_t n = 0; n < static_cast<size_t>(numFrames) * stream_->getFormat().channels(); ++n)
memcpy(static_cast<char*>(audioData) + 3 * n, audio_data_.data() + 4 * n, 3);
}
}
return oboe::DataCallbackResult::Continue;
}
void OboePlayer::onErrorBeforeClose(oboe::AudioStream* oboeStream, oboe::Result error)
{
std::ignore = oboeStream;
LOG(INFO, LOG_TAG) << "onErrorBeforeClose: " << oboe::convertToText(error) << "\n";
stop();
}
void OboePlayer::onErrorAfterClose(oboe::AudioStream* oboeStream, oboe::Result error)
{
// Tech Note: Disconnected Streams and Plugin Issues
// https://github.com/google/oboe/blob/master/docs/notes/disconnect.md
std::ignore = oboeStream;
LOG(INFO, LOG_TAG) << "onErrorAfterClose: " << oboe::convertToText(error) << "\n";
auto result = openStream();
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error building AudioStream: " << oboe::convertToText(result) << "\n";
start();
}
void OboePlayer::start()
{
// Typically, start the stream after querying some stream information, as well as some input from the user
LOG(INFO, LOG_TAG) << "Start\n";
auto result = out_stream_->requestStart();
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error in requestStart: " << oboe::convertToText(result) << "\n";
}
void OboePlayer::stop()
{
LOG(INFO, LOG_TAG) << "Stop\n";
auto result = out_stream_->requestStop();
if (result != oboe::Result::OK)
LOG(ERROR, LOG_TAG) << "Error in requestStop: " << oboe::convertToText(result) << "\n";
}
} // namespace player
| 9,351
|
C++
|
.cpp
| 206
| 38.650485
| 157
| 0.650736
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,993
|
browse_avahi.cpp
|
badaix_snapcast/client/browseZeroConf/browse_avahi.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "browse_avahi.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
// standard headers
#include <cassert>
#include <iostream>
static AvahiSimplePoll* simple_poll = nullptr;
static constexpr auto LOG_TAG = "Avahi";
BrowseAvahi::BrowseAvahi() : client_(nullptr), sb_(nullptr)
{
}
BrowseAvahi::~BrowseAvahi()
{
cleanUp();
}
void BrowseAvahi::cleanUp()
{
if (sb_ != nullptr)
avahi_service_browser_free(sb_);
sb_ = nullptr;
if (client_ != nullptr)
avahi_client_free(client_);
client_ = nullptr;
if (simple_poll != nullptr)
avahi_simple_poll_free(simple_poll);
simple_poll = nullptr;
}
void BrowseAvahi::resolve_callback(AvahiServiceResolver* r, AVAHI_GCC_UNUSED AvahiIfIndex interface, AVAHI_GCC_UNUSED AvahiProtocol protocol,
AvahiResolverEvent event, const char* name, const char* type, const char* domain, const char* host_name,
const AvahiAddress* address, uint16_t port, AvahiStringList* txt, AvahiLookupResultFlags flags,
AVAHI_GCC_UNUSED void* userdata)
{
auto* browseAvahi = static_cast<BrowseAvahi*>(userdata);
assert(r);
/* Called whenever a service has been resolved successfully or timed out */
switch (event)
{
case AVAHI_RESOLVER_FAILURE:
LOG(ERROR, LOG_TAG) << "(Resolver) Failed to resolve service '" << name << "' of type '" << type << "' in domain '" << domain
<< "': " << avahi_strerror(avahi_client_errno(avahi_service_resolver_get_client(r))) << "\n";
break;
case AVAHI_RESOLVER_FOUND:
{
char a[AVAHI_ADDRESS_STR_MAX], *t;
LOG(INFO, LOG_TAG) << "Service '" << name << "' of type '" << type << "' in domain '" << domain << "':\n";
avahi_address_snprint(a, sizeof(a), address);
browseAvahi->result_.host = host_name;
browseAvahi->result_.ip = a;
browseAvahi->result_.port = port;
// protocol seems to be unreliable (0 for IPv4 and for IPv6)
browseAvahi->result_.ip_version = (browseAvahi->result_.ip.find(':') == std::string::npos) ? (IPVersion::IPv4) : (IPVersion::IPv6);
browseAvahi->result_.valid = true;
browseAvahi->result_.iface_idx = interface;
t = avahi_string_list_to_string(txt);
LOG(INFO, LOG_TAG) << "\t" << host_name << ":" << port << " (" << a << ")\n";
LOG(DEBUG, LOG_TAG) << "\tTXT=" << t << "\n";
LOG(DEBUG, LOG_TAG) << "\tProto=" << static_cast<int>(protocol) << "\n";
LOG(DEBUG, LOG_TAG) << "\tcookie is " << avahi_string_list_get_service_cookie(txt) << "\n";
LOG(DEBUG, LOG_TAG) << "\tis_local: " << !((flags & AVAHI_LOOKUP_RESULT_LOCAL) == 0) << "\n";
LOG(DEBUG, LOG_TAG) << "\tour_own: " << !((flags & AVAHI_LOOKUP_RESULT_OUR_OWN) == 0) << "\n";
LOG(DEBUG, LOG_TAG) << "\twide_area: " << !((flags & AVAHI_LOOKUP_RESULT_WIDE_AREA) == 0) << "\n";
LOG(DEBUG, LOG_TAG) << "\tmulticast: " << !((flags & AVAHI_LOOKUP_RESULT_MULTICAST) == 0) << "\n";
LOG(DEBUG, LOG_TAG) << "\tcached: " << !((flags & AVAHI_LOOKUP_RESULT_CACHED) == 0) << "\n";
avahi_free(t);
}
}
avahi_service_resolver_free(r);
}
void BrowseAvahi::browse_callback(AvahiServiceBrowser* b, AvahiIfIndex interface, AvahiProtocol protocol, AvahiBrowserEvent event, const char* name,
const char* type, const char* domain, AVAHI_GCC_UNUSED AvahiLookupResultFlags flags, void* userdata)
{
// AvahiClient* client = (AvahiClient*)userdata;
auto* browseAvahi = static_cast<BrowseAvahi*>(userdata);
assert(b);
/* Called whenever a new services becomes available on the LAN or is removed from the LAN */
switch (event)
{
case AVAHI_BROWSER_FAILURE:
LOG(ERROR, LOG_TAG) << "(Browser) " << avahi_strerror(avahi_client_errno(avahi_service_browser_get_client(b))) << "\n";
avahi_simple_poll_quit(simple_poll);
return;
case AVAHI_BROWSER_NEW:
LOG(INFO, LOG_TAG) << "(Browser) NEW: service '" << name << "' of type '" << type << "' in domain '" << domain << "'\n";
/* We ignore the returned resolver object. In the callback
function we free it. If the server is terminated before
the callback function is called the server will free
the resolver for us. */
if ((avahi_service_resolver_new(browseAvahi->client_, interface, protocol, name, type, domain, AVAHI_PROTO_UNSPEC, static_cast<AvahiLookupFlags>(0),
resolve_callback, userdata)) == nullptr)
LOG(ERROR, LOG_TAG) << "Failed to resolve service '" << name << "': " << avahi_strerror(avahi_client_errno(browseAvahi->client_)) << "\n";
break;
case AVAHI_BROWSER_REMOVE:
LOG(INFO, LOG_TAG) << "(Browser) REMOVE: service '" << name << "' of type '" << type << "' in domain '" << domain << "'\n";
break;
case AVAHI_BROWSER_ALL_FOR_NOW:
case AVAHI_BROWSER_CACHE_EXHAUSTED:
LOG(INFO, LOG_TAG) << "(Browser) " << (event == AVAHI_BROWSER_CACHE_EXHAUSTED ? "CACHE_EXHAUSTED" : "ALL_FOR_NOW") << "\n";
break;
}
}
void BrowseAvahi::client_callback(AvahiClient* c, AvahiClientState state, AVAHI_GCC_UNUSED void* userdata)
{
assert(c);
/* Called whenever the client or server state changes */
// BrowseAvahi* browseAvahi = static_cast<BrowseAvahi*>(userdata);
if (state == AVAHI_CLIENT_FAILURE)
{
LOG(ERROR, LOG_TAG) << "Server connection failure: " << avahi_strerror(avahi_client_errno(c)) << "\n";
avahi_simple_poll_quit(simple_poll);
}
}
bool BrowseAvahi::browse(const std::string& serviceName, mDNSResult& result, int timeout)
{
try
{
/* Allocate main loop object */
if ((simple_poll = avahi_simple_poll_new()) == nullptr)
throw SnapException("BrowseAvahi - Failed to create simple poll object");
/* Allocate a new client */
int error;
if ((client_ = avahi_client_new(avahi_simple_poll_get(simple_poll), static_cast<AvahiClientFlags>(0), client_callback, this, &error)) == nullptr)
throw SnapException("BrowseAvahi - Failed to create client: " + std::string(avahi_strerror(error)));
/* Create the service browser */
if ((sb_ = avahi_service_browser_new(client_, AVAHI_IF_UNSPEC, AVAHI_PROTO_INET, serviceName.c_str(), nullptr, static_cast<AvahiLookupFlags>(0),
browse_callback, this)) == nullptr)
throw SnapException("BrowseAvahi - Failed to create service browser: " + std::string(avahi_strerror(avahi_client_errno(client_))));
result_.valid = false;
while (timeout > 0)
{
avahi_simple_poll_iterate(simple_poll, 100);
timeout -= 100;
if (result_.valid)
{
result = result_;
cleanUp();
return true;
}
}
cleanUp();
return false;
}
catch (...)
{
cleanUp();
throw;
}
}
| 8,191
|
C++
|
.cpp
| 163
| 41.079755
| 160
| 0.602055
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,994
|
browse_bonjour.cpp
|
badaix_snapcast/client/browseZeroConf/browse_bonjour.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "browse_bonjour.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
// standard headers
#include <deque>
#include <iostream>
#ifdef WINDOWS
#include <WinSock2.h>
#include <Ws2tcpip.h>
#else
#include <netdb.h>
#include <sys/socket.h>
#endif
using namespace std;
static constexpr auto LOG_TAG = "Bonjour";
struct DNSServiceRefDeleter
{
void operator()(DNSServiceRef* ref)
{
DNSServiceRefDeallocate(*ref);
delete ref;
}
};
using DNSServiceHandle = std::unique_ptr<DNSServiceRef, DNSServiceRefDeleter>;
string BonjourGetError(DNSServiceErrorType error)
{
switch (error)
{
case kDNSServiceErr_NoError:
return "NoError";
default:
case kDNSServiceErr_Unknown:
return "Unknown";
case kDNSServiceErr_NoSuchName:
return "NoSuchName";
case kDNSServiceErr_NoMemory:
return "NoMemory";
case kDNSServiceErr_BadParam:
return "BadParam";
case kDNSServiceErr_BadReference:
return "BadReference";
case kDNSServiceErr_BadState:
return "BadState";
case kDNSServiceErr_BadFlags:
return "BadFlags";
case kDNSServiceErr_Unsupported:
return "Unsupported";
case kDNSServiceErr_NotInitialized:
return "NotInitialized";
case kDNSServiceErr_AlreadyRegistered:
return "AlreadyRegistered";
case kDNSServiceErr_NameConflict:
return "NameConflict";
case kDNSServiceErr_Invalid:
return "Invalid";
case kDNSServiceErr_Firewall:
return "Firewall";
case kDNSServiceErr_Incompatible:
return "Incompatible";
case kDNSServiceErr_BadInterfaceIndex:
return "BadInterfaceIndex";
case kDNSServiceErr_Refused:
return "Refused";
case kDNSServiceErr_NoSuchRecord:
return "NoSuchRecord";
case kDNSServiceErr_NoAuth:
return "NoAuth";
case kDNSServiceErr_NoSuchKey:
return "NoSuchKey";
case kDNSServiceErr_NATTraversal:
return "NATTraversal";
case kDNSServiceErr_DoubleNAT:
return "DoubleNAT";
case kDNSServiceErr_BadTime:
return "BadTime";
case kDNSServiceErr_BadSig:
return "BadSig";
case kDNSServiceErr_BadKey:
return "BadKey";
case kDNSServiceErr_Transient:
return "Transient";
case kDNSServiceErr_ServiceNotRunning:
return "ServiceNotRunning";
case kDNSServiceErr_NATPortMappingUnsupported:
return "NATPortMappingUnsupported";
case kDNSServiceErr_NATPortMappingDisabled:
return "NATPortMappingDisabled";
case kDNSServiceErr_NoRouter:
return "NoRouter";
case kDNSServiceErr_PollingMode:
return "PollingMode";
case kDNSServiceErr_Timeout:
return "Timeout";
}
}
struct mDNSReply
{
string name, regtype, domain;
};
struct mDNSResolve
{
string fullName;
uint16_t port;
};
#define CHECKED(err) \
if ((err) != kDNSServiceErr_NoError) \
throw SnapException(BonjourGetError(err) + ":" + to_string(__LINE__));
void runService(const DNSServiceHandle& service)
{
if (!*service)
return;
auto socket = DNSServiceRefSockFD(*service);
fd_set set;
FD_ZERO(&set);
FD_SET(socket, &set);
timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 500000;
while (select(FD_SETSIZE, &set, NULL, NULL, &timeout))
{
CHECKED(DNSServiceProcessResult(*service));
timeout.tv_sec = 0;
timeout.tv_usec = 500000;
}
}
bool BrowseBonjour::browse(const string& serviceName, mDNSResult& result, int /*timeout*/)
{
result.valid = false;
// Discover
deque<mDNSReply> replyCollection;
{
DNSServiceHandle service(new DNSServiceRef(NULL));
CHECKED(DNSServiceBrowse(
service.get(), 0, 0, serviceName.c_str(), "local.",
[](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t /*interfaceIndex*/, DNSServiceErrorType errorCode, const char* serviceName,
const char* regtype, const char* replyDomain, void* context)
{
auto replyCollection = static_cast<deque<mDNSReply>*>(context);
CHECKED(errorCode);
replyCollection->push_back(mDNSReply{string(serviceName), string(regtype), string(replyDomain)});
},
&replyCollection));
runService(service);
}
// Resolve
deque<mDNSResolve> resolveCollection;
{
DNSServiceHandle service(new DNSServiceRef(NULL));
for (auto& reply : replyCollection)
CHECKED(DNSServiceResolve(
service.get(), 0, 0, reply.name.c_str(), reply.regtype.c_str(), reply.domain.c_str(),
[](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t /*interfaceIndex*/, DNSServiceErrorType errorCode, const char* /*fullName*/,
const char* hosttarget, uint16_t port, uint16_t /*txtLen*/, const unsigned char* /*txtRecord*/, void* context)
{
auto resultCollection = static_cast<deque<mDNSResolve>*>(context);
CHECKED(errorCode);
resultCollection->push_back(mDNSResolve{string(hosttarget), ntohs(port)});
},
&resolveCollection));
runService(service);
}
// DNS/mDNS Resolve
deque<mDNSResult> resultCollection(resolveCollection.size(), mDNSResult{});
{
DNSServiceHandle service(new DNSServiceRef(NULL));
unsigned i = 0;
for (auto& resolve : resolveCollection)
{
resultCollection[i].port = resolve.port;
CHECKED(DNSServiceGetAddrInfo(
service.get(), kDNSServiceFlagsLongLivedQuery, 0, kDNSServiceProtocol_IPv4, resolve.fullName.c_str(),
[](DNSServiceRef /*service*/, DNSServiceFlags /*flags*/, uint32_t interfaceIndex, DNSServiceErrorType /*errorCode*/, const char* hostname,
const sockaddr* address, uint32_t /*ttl*/, void* context)
{
auto result = static_cast<mDNSResult*>(context);
result->host = string(hostname);
result->ip_version = (address->sa_family == AF_INET) ? (IPVersion::IPv4) : (IPVersion::IPv6);
result->iface_idx = static_cast<int>(interfaceIndex);
char hostIP[NI_MAXHOST];
char hostService[NI_MAXSERV];
if (getnameinfo(address, sizeof(*address), hostIP, sizeof(hostIP), hostService, sizeof(hostService), NI_NUMERICHOST | NI_NUMERICSERV) == 0)
result->ip = string(hostIP);
else
return;
result->valid = true;
},
&resultCollection[i++]));
}
runService(service);
}
resultCollection.erase(std::remove_if(resultCollection.begin(), resultCollection.end(), [](const mDNSResult& res) { return res.ip.empty(); }),
resultCollection.end());
if (resultCollection.empty())
return false;
if (resultCollection.size() > 1)
LOG(NOTICE, LOG_TAG) << "Multiple servers found. Using first" << endl;
result = resultCollection.front();
return true;
}
#undef CHECKED
| 8,600
|
C++
|
.cpp
| 216
| 30.990741
| 160
| 0.61974
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,995
|
ogg_decoder.cpp
|
badaix_snapcast/client/decoder/ogg_decoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "ogg_decoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/endian.hpp"
#include "common/snap_exception.hpp"
// 3rd party headers
// standard headers
#ifndef HAS_TREMOR
#include <cmath> // floor
#endif
#include <cstdint>
#include <cstring>
using namespace std;
static constexpr auto LOG_TAG = "OggDecoder";
namespace decoder
{
OggDecoder::OggDecoder() : Decoder()
{
ogg_sync_init(&oy); /* Now we can read pages */
}
OggDecoder::~OggDecoder()
{
std::lock_guard<std::mutex> lock(mutex_);
vorbis_block_clear(&vb);
vorbis_dsp_clear(&vd);
ogg_stream_clear(&os);
vorbis_comment_clear(&vc);
vorbis_info_clear(&vi); /* must be called last */
ogg_sync_clear(&oy);
}
bool OggDecoder::decode(msg::PcmChunk* chunk)
{
std::lock_guard<std::mutex> lock(mutex_);
/* grab some data at the head of the stream. We want the first page
(which is guaranteed to be small and only contain the Vorbis
stream initial header) We need the first page to get the stream
serialno. */
int size = chunk->payloadSize;
char* buffer = ogg_sync_buffer(&oy, size);
memcpy(buffer, chunk->payload, size);
ogg_sync_wrote(&oy, size);
chunk->payloadSize = 0;
/* The rest is just a straight decode loop until end of stream */
// while(!eos){
while (true)
{
int result = ogg_sync_pageout(&oy, &og);
if (result == 0)
break; /* need more data */
if (result < 0)
{
/* missing or corrupt data at this page position */
LOG(ERROR, LOG_TAG) << "Corrupt or missing data in bitstream; continuing...\n";
continue;
}
ogg_stream_pagein(&os, &og); /* can safely ignore errors at this point */
while (true)
{
result = ogg_stream_packetout(&os, &op);
if (result == 0)
break; /* need more data */
if (result < 0)
continue; /* missing or corrupt data at this page position */
/* no reason to complain; already complained above */
/* we have a packet. Decode it */
#ifdef HAS_TREMOR
ogg_int32_t** pcm;
#else
float** pcm;
#endif
int samples;
if (vorbis_synthesis(&vb, &op) == 0) /* test for success! */
vorbis_synthesis_blockin(&vd, &vb);
/*
**pcm is a multichannel float vector. In stereo, for
example, pcm[0] is left, and pcm[1] is right. samples is
the size of each channel. Convert the float values
(-1.<=range<=1.) to whatever PCM format and write it out */
while ((samples = vorbis_synthesis_pcmout(&vd, &pcm)) > 0)
{
uint32_t bytes = sampleFormat_.sampleSize() * vi.channels * samples;
chunk->payload = static_cast<char*>(realloc(chunk->payload, chunk->payloadSize + bytes));
for (int channel = 0; channel < vi.channels; ++channel)
{
if (sampleFormat_.sampleSize() == 1)
{
auto* chunkBuffer = reinterpret_cast<int8_t*>(chunk->payload + chunk->payloadSize);
for (int i = 0; i < samples; i++)
{
int8_t& val = chunkBuffer[sampleFormat_.channels() * i + channel];
#ifdef HAS_TREMOR
val = clip<int8_t>(pcm[channel][i], INT8_MIN, INT8_MAX);
#else
val = clip<int8_t>(floor(pcm[channel][i] * 127.f + .5f), INT8_MIN, INT8_MAX);
#endif
}
}
else if (sampleFormat_.sampleSize() == 2)
{
auto* chunkBuffer = reinterpret_cast<int16_t*>(chunk->payload + chunk->payloadSize);
for (int i = 0; i < samples; i++)
{
int16_t& val = chunkBuffer[sampleFormat_.channels() * i + channel];
#ifdef HAS_TREMOR
val = SWAP_16(clip<int16_t>(pcm[channel][i] >> 9, INT16_MIN, INT16_MAX));
#else
val = SWAP_16(clip<int16_t>(floor(pcm[channel][i] * 32767.f + .5f), INT16_MIN, INT16_MAX));
#endif
}
}
else if (sampleFormat_.sampleSize() == 4)
{
auto* chunkBuffer = reinterpret_cast<int32_t*>(chunk->payload + chunk->payloadSize);
for (int i = 0; i < samples; i++)
{
int32_t& val = chunkBuffer[sampleFormat_.channels() * i + channel];
#ifdef HAS_TREMOR
val = SWAP_32(clip<int32_t>(pcm[channel][i] << 7, INT32_MIN, INT32_MAX));
#else
val = SWAP_32(clip<int32_t>(floor(pcm[channel][i] * 2147483647.f + .5f), INT32_MIN, INT32_MAX));
#endif
}
}
}
chunk->payloadSize += bytes;
vorbis_synthesis_read(&vd, samples);
}
}
}
return true;
}
SampleFormat OggDecoder::setHeader(msg::CodecHeader* chunk)
{
int size = chunk->payloadSize;
char* buffer = ogg_sync_buffer(&oy, size);
memcpy(buffer, chunk->payload, size);
ogg_sync_wrote(&oy, size);
if (ogg_sync_pageout(&oy, &og) != 1)
throw SnapException("Input does not appear to be an Ogg bitstream");
ogg_stream_init(&os, ogg_page_serialno(&og));
vorbis_info_init(&vi);
vorbis_comment_init(&vc);
if (ogg_stream_pagein(&os, &og) < 0)
throw SnapException("Error reading first page of Ogg bitstream data");
if (ogg_stream_packetout(&os, &op) != 1)
throw SnapException("Error reading initial header packet");
if (vorbis_synthesis_headerin(&vi, &vc, &op) < 0)
throw SnapException("This Ogg bitstream does not contain Vorbis audio data");
int i(0);
while (i < 2)
{
while (i < 2)
{
int result = ogg_sync_pageout(&oy, &og);
if (result == 0)
break; /* Need more data */
/* Don't complain about missing or corrupt data yet. We'll
catch it at the packet output phase */
if (result == 1)
{
ogg_stream_pagein(&os, &og); /* we can ignore any errors here as they'll also become apparent at packetout */
while (i < 2)
{
result = ogg_stream_packetout(&os, &op);
if (result == 0)
break;
/// Uh oh; data at some point was corrupted or missing!
/// We can't tolerate that in a header. Die. */
if (result < 0)
throw SnapException("Corrupt secondary header. Exiting.");
result = vorbis_synthesis_headerin(&vi, &vc, &op);
if (result < 0)
throw SnapException("Corrupt secondary header. Exiting.");
i++;
}
}
}
}
/// OK, got and parsed all three headers. Initialize the Vorbis packet->PCM decoder.
if (vorbis_synthesis_init(&vd, &vi) == 0)
vorbis_block_init(&vd, &vb);
/// central decode state
/// local state for most of the decode so multiple block decodes can proceed
/// in parallel. We could init multiple vorbis_block structures for vd here
sampleFormat_.setFormat(vi.rate, 16, static_cast<uint16_t>(vi.channels));
/* Throw the comments plus a few lines about the bitstream we're decoding */
char** ptr = vc.user_comments;
while (*ptr != nullptr)
{
std::string comment(*ptr);
if (comment.find("SAMPLE_FORMAT=") == 0)
sampleFormat_.setFormat(comment.substr(comment.find('=') + 1));
LOG(INFO, LOG_TAG) << "comment: " << comment << "\n";
;
++ptr;
}
LOG(INFO, LOG_TAG) << "Encoded by: " << vc.vendor << "\n";
return sampleFormat_;
}
} // namespace decoder
| 9,005
|
C++
|
.cpp
| 215
| 31.274419
| 125
| 0.553778
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,996
|
opus_decoder.cpp
|
badaix_snapcast/client/decoder/opus_decoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2015 Hannes Ellinger
Copyright (C) 2016-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "opus_decoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
namespace decoder
{
#define ID_OPUS 0x4F505553
/// int: Number of samples per channel in the input signal.
/// This must be an Opus frame size for the encoder's sampling rate. For example, at 48 kHz the
/// permitted values are 120, 240, 480, 960, 1920, and 2880.
/// Passing in a duration of less than 10 ms (480 samples at 48 kHz) will prevent the encoder from using the LPC or hybrid modes.
static constexpr int const_max_frame_size = 2880;
static constexpr auto LOG_TAG = "OpusDecoder";
OpusDecoder::OpusDecoder() : Decoder(), dec_(nullptr)
{
pcm_.resize(120);
}
OpusDecoder::~OpusDecoder()
{
if (dec_ != nullptr)
opus_decoder_destroy(dec_);
}
bool OpusDecoder::decode(msg::PcmChunk* chunk)
{
int decoded_frames = 0;
while ((decoded_frames = opus_decode(dec_, reinterpret_cast<unsigned char*>(chunk->payload), chunk->payloadSize, pcm_.data(),
static_cast<int>(pcm_.size()) / sample_format_.channels(), 0)) == OPUS_BUFFER_TOO_SMALL)
{
if (pcm_.size() < const_max_frame_size * sample_format_.channels())
{
pcm_.resize(pcm_.size() * 2);
LOG(DEBUG, LOG_TAG) << "OPUS encoding buffer too small, resizing to " << pcm_.size() / sample_format_.channels() << " samples per channel\n";
}
else
break;
}
if (decoded_frames < 0)
{
LOG(ERROR, LOG_TAG) << "Failed to decode chunk: " << opus_strerror(decoded_frames) << ", IN size: " << chunk->payloadSize
<< ", OUT size: " << pcm_.size() << '\n';
return false;
}
else
{
LOG(TRACE, LOG_TAG) << "Decode chunk: " << decoded_frames << " frames, size: " << chunk->payloadSize
<< " bytes, decoded: " << decoded_frames * sample_format_.frameSize() << " bytes\n";
// copy encoded data to chunk
chunk->payloadSize = decoded_frames * sample_format_.frameSize(); // decoded_frames * sample_format_.channels() * sizeof(opus_int16);
chunk->payload = static_cast<char*>(realloc(chunk->payload, chunk->payloadSize));
memcpy(chunk->payload, reinterpret_cast<char*>(pcm_.data()), chunk->payloadSize);
return true;
}
}
SampleFormat OpusDecoder::setHeader(msg::CodecHeader* chunk)
{
// decode the opus pseudo header
if (chunk->payloadSize < 12)
throw SnapException("OPUS header too small");
// decode the "opus id" magic number, this is our constant part that must match
uint32_t id_opus;
memcpy(&id_opus, chunk->payload, sizeof(id_opus));
if (SWAP_32(id_opus) != ID_OPUS)
throw SnapException("Not an Opus pseudo header");
// decode the sampleformat
uint32_t rate;
memcpy(&rate, chunk->payload + 4, sizeof(rate));
uint16_t bits;
memcpy(&bits, chunk->payload + 8, sizeof(bits));
uint16_t channels;
memcpy(&channels, chunk->payload + 10, sizeof(channels));
sample_format_.setFormat(SWAP_32(rate), SWAP_16(bits), SWAP_16(channels));
LOG(DEBUG, LOG_TAG) << "Opus sampleformat: " << sample_format_.toString() << "\n";
// create the decoder
int error;
dec_ = opus_decoder_create(sample_format_.rate(), sample_format_.channels(), &error);
if (error != 0)
throw SnapException("Failed to initialize Opus decoder: " + std::string(opus_strerror(error)));
return sample_format_;
}
} // namespace decoder
| 4,351
|
C++
|
.cpp
| 96
| 39.458333
| 153
| 0.659967
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,998
|
null_decoder.cpp
|
badaix_snapcast/client/decoder/null_decoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "null_decoder.hpp"
// local headers
// 3rd party headers
// standard headers
namespace decoder
{
NullDecoder::NullDecoder() : Decoder()
{
}
bool NullDecoder::decode(msg::PcmChunk* /*chunk*/)
{
return true;
}
SampleFormat NullDecoder::setHeader(msg::CodecHeader* chunk)
{
std::ignore = chunk;
return {48000, 16, 2};
}
} // namespace decoder
| 1,148
|
C++
|
.cpp
| 34
| 30.558824
| 73
| 0.744313
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,999
|
flac_decoder.cpp
|
badaix_snapcast/client/decoder/flac_decoder.cpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
// prototype/interface header file
#include "flac_decoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/endian.hpp"
#include "common/snap_exception.hpp"
// standard headers
#include <cstring>
#include <iostream>
using namespace std;
static constexpr auto LOG_TAG = "FlacDecoder";
namespace decoder
{
namespace callback
{
FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder* decoder, FLAC__byte buffer[], size_t* bytes, void* client_data);
FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder* decoder, const FLAC__Frame* frame, const FLAC__int32* const buffer[],
void* client_data);
void metadata_callback(const FLAC__StreamDecoder* decoder, const FLAC__StreamMetadata* metadata, void* client_data);
void error_callback(const FLAC__StreamDecoder* decoder, FLAC__StreamDecoderErrorStatus status, void* client_data);
} // namespace callback
namespace
{
msg::CodecHeader* flacHeader = nullptr;
msg::PcmChunk* flacChunk = nullptr;
msg::PcmChunk* pcmChunk = nullptr;
SampleFormat sampleFormat;
FLAC__StreamDecoder* decoder = nullptr;
} // namespace
FlacDecoder::FlacDecoder() : Decoder(), lastError_(nullptr)
{
flacChunk = new msg::PcmChunk();
}
FlacDecoder::~FlacDecoder()
{
std::lock_guard<std::mutex> lock(mutex_);
FLAC__stream_decoder_delete(decoder);
delete flacChunk;
}
bool FlacDecoder::decode(msg::PcmChunk* chunk)
{
std::lock_guard<std::mutex> lock(mutex_);
cacheInfo_.reset();
pcmChunk = chunk;
flacChunk->payload = static_cast<char*>(realloc(flacChunk->payload, chunk->payloadSize));
memcpy(flacChunk->payload, chunk->payload, chunk->payloadSize);
flacChunk->payloadSize = chunk->payloadSize;
pcmChunk->payload = static_cast<char*>(realloc(pcmChunk->payload, 0));
pcmChunk->payloadSize = 0;
while (flacChunk->payloadSize > 0)
{
if (FLAC__stream_decoder_process_single(decoder) == 0)
{
return false;
}
if (lastError_)
{
LOG(ERROR, LOG_TAG) << "FLAC decode error: " << FLAC__StreamDecoderErrorStatusString[*lastError_] << "\n";
lastError_ = nullptr;
return false;
}
}
if ((cacheInfo_.cachedBlocks_ > 0) && (cacheInfo_.sampleRate_ != 0))
{
double diffMs = static_cast<double>(cacheInfo_.cachedBlocks_) / (static_cast<double>(cacheInfo_.sampleRate_) / 1000.);
auto us = static_cast<uint64_t>(diffMs * 1000.);
tv diff(static_cast<int32_t>(us / 1000000), static_cast<int32_t>(us % 1000000));
LOG(TRACE, LOG_TAG) << "Cached: " << cacheInfo_.cachedBlocks_ << ", " << diffMs << "ms, " << diff.sec << "s, " << diff.usec << "us\n";
chunk->timestamp = chunk->timestamp - diff;
}
return true;
}
SampleFormat FlacDecoder::setHeader(msg::CodecHeader* chunk)
{
flacHeader = chunk;
FLAC__StreamDecoderInitStatus init_status;
if ((decoder = FLAC__stream_decoder_new()) == nullptr)
throw SnapException("ERROR: allocating decoder");
// (void)FLAC__stream_decoder_set_md5_checking(decoder, true);
init_status = FLAC__stream_decoder_init_stream(decoder, callback::read_callback, nullptr, nullptr, nullptr, nullptr, callback::write_callback,
callback::metadata_callback, callback::error_callback, this);
if (init_status != FLAC__STREAM_DECODER_INIT_STATUS_OK)
throw SnapException("ERROR: initializing decoder: " + string(FLAC__StreamDecoderInitStatusString[init_status]));
FLAC__stream_decoder_process_until_end_of_metadata(decoder);
if (sampleFormat.rate() == 0)
throw SnapException("Sample format not found");
return sampleFormat;
}
namespace callback
{
FLAC__StreamDecoderReadStatus read_callback(const FLAC__StreamDecoder* /*decoder*/, FLAC__byte buffer[], size_t* bytes, void* client_data)
{
if (flacHeader != nullptr)
{
*bytes = flacHeader->payloadSize;
memcpy(buffer, flacHeader->payload, *bytes);
flacHeader = nullptr;
}
else if (flacChunk != nullptr)
{
// cerr << "read_callback: " << *bytes << ", avail: " << flacChunk->payloadSize << "\n";
static_cast<FlacDecoder*>(client_data)->cacheInfo_.isCachedChunk_ = false;
if (*bytes > flacChunk->payloadSize)
*bytes = flacChunk->payloadSize;
// if (*bytes == 0)
// return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
memcpy(buffer, flacChunk->payload, *bytes);
memmove(flacChunk->payload, flacChunk->payload + *bytes, flacChunk->payloadSize - *bytes);
flacChunk->payloadSize = flacChunk->payloadSize - static_cast<uint32_t>(*bytes);
flacChunk->payload = static_cast<char*>(realloc(flacChunk->payload, flacChunk->payloadSize));
}
return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
}
FLAC__StreamDecoderWriteStatus write_callback(const FLAC__StreamDecoder* /*decoder*/, const FLAC__Frame* frame, const FLAC__int32* const buffer[],
void* client_data)
{
if (pcmChunk != nullptr)
{
size_t bytes = frame->header.blocksize * sampleFormat.frameSize();
auto* flacDecoder = static_cast<FlacDecoder*>(client_data);
if (flacDecoder->cacheInfo_.isCachedChunk_)
flacDecoder->cacheInfo_.cachedBlocks_ += frame->header.blocksize;
pcmChunk->payload = static_cast<char*>(realloc(pcmChunk->payload, pcmChunk->payloadSize + bytes));
for (size_t channel = 0; channel < sampleFormat.channels(); ++channel)
{
if (buffer[channel] == nullptr)
{
LOG(ERROR, LOG_TAG) << "ERROR: buffer[" << channel << "] is NULL\n";
return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
}
if (sampleFormat.sampleSize() == 1)
{
auto* chunkBuffer = reinterpret_cast<int8_t*>(pcmChunk->payload + pcmChunk->payloadSize);
for (size_t i = 0; i < frame->header.blocksize; i++)
chunkBuffer[sampleFormat.channels() * i + channel] = static_cast<int8_t>(buffer[channel][i]);
}
else if (sampleFormat.sampleSize() == 2)
{
auto* chunkBuffer = reinterpret_cast<int16_t*>(pcmChunk->payload + pcmChunk->payloadSize);
for (size_t i = 0; i < frame->header.blocksize; i++)
chunkBuffer[sampleFormat.channels() * i + channel] = SWAP_16((int16_t)(buffer[channel][i]));
}
else if (sampleFormat.sampleSize() == 4)
{
auto* chunkBuffer = reinterpret_cast<int32_t*>(pcmChunk->payload + pcmChunk->payloadSize);
for (size_t i = 0; i < frame->header.blocksize; i++)
chunkBuffer[sampleFormat.channels() * i + channel] = SWAP_32((int32_t)(buffer[channel][i]));
}
}
pcmChunk->payloadSize += static_cast<uint32_t>(bytes);
}
return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
}
void metadata_callback(const FLAC__StreamDecoder* /*decoder*/, const FLAC__StreamMetadata* metadata, void* client_data)
{
/* print some stats */
if (metadata->type == FLAC__METADATA_TYPE_STREAMINFO)
{
static_cast<FlacDecoder*>(client_data)->cacheInfo_.sampleRate_ = metadata->data.stream_info.sample_rate;
sampleFormat.setFormat(metadata->data.stream_info.sample_rate, static_cast<uint16_t>(metadata->data.stream_info.bits_per_sample),
static_cast<uint16_t>(metadata->data.stream_info.channels));
}
}
void error_callback(const FLAC__StreamDecoder* /*decoder*/, FLAC__StreamDecoderErrorStatus status, void* client_data)
{
LOG(ERROR, LOG_TAG) << "Got error callback: " << FLAC__StreamDecoderErrorStatusString[status] << "\n";
static_cast<FlacDecoder*>(client_data)->lastError_ = std::make_unique<FLAC__StreamDecoderErrorStatus>(status);
}
} // namespace callback
} // namespace decoder
| 8,803
|
C++
|
.cpp
| 184
| 40.668478
| 146
| 0.660371
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,000
|
version.hpp
|
badaix_snapcast/common/version.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <string>
namespace version
{
#ifdef REVISION
static constexpr auto revision = REVISION;
#else
static constexpr auto revision = "";
#endif
#ifdef VERSION
static constexpr auto code = VERSION;
#else
static constexpr auto code = "";
#endif
static std::string rev(std::size_t len = 0)
{
if (len == 0)
{
return revision;
}
return std::string(revision).substr(0, len);
}
} // namespace version
| 1,203
|
C++
|
.h
| 38
| 28.447368
| 73
| 0.738075
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,001
|
endian.hpp
|
badaix_snapcast/common/endian.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <cstdint>
#ifdef IS_BIG_ENDIAN
#define SWAP_16(x) (__builtin_bswap16(x))
#define SWAP_32(x) (__builtin_bswap32(x))
#define SWAP_64(x) (__builtin_bswap64(x))
#else
#define SWAP_16(x) x
#define SWAP_32(x) x
#define SWAP_64(x) x
#endif
namespace endian
{
template <typename T>
T swap(const T&);
template <>
inline int8_t swap(const int8_t& val)
{
return val;
}
template <>
inline int16_t swap(const int16_t& val)
{
return SWAP_16(val);
}
template <>
inline int32_t swap(const int32_t& val)
{
return SWAP_32(val);
}
template <>
inline int64_t swap(const int64_t& val)
{
return SWAP_64(val);
}
} // namespace endian
| 1,418
|
C++
|
.h
| 51
| 25.313725
| 73
| 0.732103
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,002
|
utils.hpp
|
badaix_snapcast/common/utils.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/utils/string_utils.hpp"
// standard headers
#include <cstring>
#include <fstream>
#include <iomanip>
#include <memory>
#ifndef WINDOWS
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/utsname.h>
#include <unistd.h>
#endif
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#if !defined(WINDOWS) && !defined(FREEBSD)
#include <sys/sysinfo.h>
#endif
#ifdef MACOS
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/IOTypes.h>
#include <ifaddrs.h>
#include <net/if_dl.h>
#endif
#ifdef ANDROID
#include <sys/system_properties.h>
#endif
#ifdef WINDOWS
#include <chrono>
#include <direct.h>
#include <iphlpapi.h>
#include <versionhelpers.h>
#include <windows.h>
#include <winsock2.h>
#endif
namespace strutils = utils::string;
#ifndef WINDOWS
static std::string execGetOutput(const std::string& cmd)
{
std::shared_ptr<::FILE> pipe(popen((cmd + " 2> /dev/null").c_str(), "r"),
[](::FILE* stream)
{
if (stream != nullptr)
pclose(stream);
});
if (!pipe)
return "";
char buffer[1024];
std::string result;
while (feof(pipe.get()) == 0)
{
if (fgets(buffer, 1024, pipe.get()) != nullptr)
result += buffer;
}
return strutils::trim(result);
}
#endif
#ifdef ANDROID
static std::string getProp(const std::string& key, const std::string& def = "")
{
std::string result(def);
char cresult[PROP_VALUE_MAX + 1];
if (__system_property_get(key.c_str(), cresult) > 0)
result = cresult;
return result;
}
#endif
static std::string getOS()
{
static std::string os;
if (!os.empty())
return os;
#ifdef ANDROID
os = strutils::trim_copy("Android " + getProp("ro.build.version.release"));
#elif WINDOWS
if (/*IsWindows10OrGreater()*/ FALSE)
os = "Windows 10";
else if (IsWindows8Point1OrGreater())
os = "Windows 8.1";
else if (IsWindows8OrGreater())
os = "Windows 8";
else if (IsWindows7SP1OrGreater())
os = "Windows 7 SP1";
else if (IsWindows7OrGreater())
os = "Windows 7";
else if (IsWindowsVistaSP2OrGreater())
os = "Windows Vista SP2";
else if (IsWindowsVistaSP1OrGreater())
os = "Windows Vista SP1";
else if (IsWindowsVistaOrGreater())
os = "Windows Vista";
else if (IsWindowsXPSP3OrGreater())
os = "Windows XP SP3";
else if (IsWindowsXPSP2OrGreater())
os = "Windows XP SP2";
else if (IsWindowsXPSP1OrGreater())
os = "Windows XP SP1";
else if (IsWindowsXPOrGreater())
os = "Windows XP";
else
os = "Unknown Windows";
#else
os = execGetOutput("lsb_release -d");
if ((os.find(':') != std::string::npos) && (os.find("lsb_release") == std::string::npos))
os = strutils::trim_copy(os.substr(os.find(':') + 1));
#endif
#ifndef WINDOWS
if (os.empty())
{
os = strutils::trim_copy(execGetOutput("grep /etc/os-release /etc/openwrt_release -e PRETTY_NAME -e DISTRIB_DESCRIPTION"));
if (os.find('=') != std::string::npos)
{
os = strutils::trim_copy(os.substr(os.find('=') + 1));
os.erase(std::remove(os.begin(), os.end(), '"'), os.end());
os.erase(std::remove(os.begin(), os.end(), '\''), os.end());
}
}
if (os.empty())
{
utsname u;
uname(&u);
os = u.sysname;
}
#endif
strutils::trim(os);
return os;
}
static std::string getHostName()
{
#ifdef ANDROID
std::string result = getProp("net.hostname");
if (!result.empty())
return result;
result = getProp("ro.product.model");
if (!result.empty())
return result;
#endif
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
return hostname;
}
static std::string getArch()
{
std::string arch;
#ifdef ANDROID
arch = getProp("ro.product.cpu.abi");
if (!arch.empty())
return arch;
#endif
#ifndef WINDOWS
arch = execGetOutput("arch");
if (arch.empty())
arch = execGetOutput("uname -i");
if (arch.empty() || (arch == "unknown"))
arch = execGetOutput("uname -m");
#else
SYSTEM_INFO sysInfo;
GetSystemInfo(&sysInfo);
switch (sysInfo.wProcessorArchitecture)
{
case PROCESSOR_ARCHITECTURE_AMD64:
arch = "amd64";
break;
case PROCESSOR_ARCHITECTURE_ARM:
arch = "arm";
break;
case PROCESSOR_ARCHITECTURE_IA64:
arch = "ia64";
break;
case PROCESSOR_ARCHITECTURE_INTEL:
arch = "intel";
break;
default:
case PROCESSOR_ARCHITECTURE_UNKNOWN:
arch = "unknown";
break;
}
#endif
return strutils::trim_copy(arch);
}
// Seems not to be used
// static std::chrono::seconds uptime()
// {
// #ifndef WINDOWS
// #ifndef FREEBSD
// struct sysinfo info;
// sysinfo(&info);
// return std::chrono::seconds(info.uptime);
// #else
// std::string uptime = execGetOutput("sysctl kern.boottime");
// if ((uptime.find(" sec = ") != std::string::npos) && (uptime.find(",") != std::string::npos))
// {
// uptime = strutils::trim_copy(uptime.substr(uptime.find(" sec = ") + 7));
// uptime.resize(uptime.find(","));
// timeval now;
// gettimeofday(&now, NULL);
// try
// {
// return std::chrono::seconds(now.tv_sec - cpt::stoul(uptime));
// }
// catch (...)
// {
// }
// }
// return 0s;
// #endif
// #else
// return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::milliseconds(GetTickCount()));
// #endif
// }
/// http://stackoverflow.com/questions/2174768/generating-random-uuids-in-linux
static std::string generateUUID()
{
static bool initialized(false);
if (!initialized)
{
std::srand(static_cast<unsigned int>(std::time(nullptr)));
initialized = true;
}
std::stringstream ss;
ss << std::setfill('0') << std::hex << std::setw(4) << (std::rand() % 0xffff) << std::setw(4) << (std::rand() % 0xffff) << "-" << std::setw(4)
<< (std::rand() % 0xffff) << "-" << std::setw(4) << (std::rand() % 0xffff) << "-" << std::setw(4) << (std::rand() % 0xffff) << "-" << std::setw(4)
<< (std::rand() % 0xffff) << std::setw(4) << (std::rand() % 0xffff) << std::setw(4) << (std::rand() % 0xffff);
return ss.str();
}
#ifndef WINDOWS
/// https://gist.github.com/OrangeTide/909204
static std::string getMacAddress(int sock)
{
struct ifreq ifr;
struct ifconf ifc;
char buf[16384];
int success = 0;
if (sock < 0)
return "";
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifc) != 0)
return "";
struct ifreq* it = ifc.ifc_req;
for (int i = 0; i < ifc.ifc_len;)
{
/// some systems have ifr_addr.sa_len and adjust the length that way, but not mine. weird */
#ifdef FREEBSD
size_t len = IFNAMSIZ + it->ifr_addr.sa_len;
#else
size_t len = sizeof(*it);
#endif
strcpy(ifr.ifr_name, it->ifr_name);
if (ioctl(sock, SIOCGIFFLAGS, &ifr) == 0)
{
if (!(ifr.ifr_flags & IFF_LOOPBACK)) // don't count loopback
{
#ifdef MACOS
/// Dirty Mac version
struct ifaddrs *ifap, *ifaptr;
unsigned char* ptr;
if (getifaddrs(&ifap) == 0)
{
for (ifaptr = ifap; ifaptr != NULL; ifaptr = ifaptr->ifa_next)
{
// std::cout << ifaptr->ifa_name << ", " << ifreq->ifr_name << "\n";
if (strcmp(ifaptr->ifa_name, it->ifr_name) != 0)
continue;
if (ifaptr->ifa_addr->sa_family == AF_LINK)
{
ptr = (unsigned char*)LLADDR((struct sockaddr_dl*)ifaptr->ifa_addr);
char mac[19];
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr + 1), *(ptr + 2), *(ptr + 3), *(ptr + 4), *(ptr + 5));
if (strcmp(mac, "00:00:00:00:00:00") == 0)
continue;
freeifaddrs(ifap);
return mac;
}
}
freeifaddrs(ifap);
}
#endif
#ifdef FREEBSD
if (ioctl(sock, SIOCGIFMAC, &ifr) == 0)
#else
if (ioctl(sock, SIOCGIFHWADDR, &ifr) == 0)
#endif
{
success = 1;
break;
}
else
{
std::stringstream ss;
ss << "/sys/class/net/" << ifr.ifr_name << "/address";
std::ifstream infile(ss.str().c_str());
std::string line;
if (infile.good() && std::getline(infile, line))
{
strutils::trim(line);
if ((line.size() == 17) && (line[2] == ':'))
return line;
}
}
}
}
else
{ /* handle error */
}
it = (struct ifreq*)((char*)it + len);
i += len;
}
if (!success)
return "";
char mac[19];
#ifndef FREEBSD
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char)ifr.ifr_hwaddr.sa_data[0], (unsigned char)ifr.ifr_hwaddr.sa_data[1],
(unsigned char)ifr.ifr_hwaddr.sa_data[2], (unsigned char)ifr.ifr_hwaddr.sa_data[3], (unsigned char)ifr.ifr_hwaddr.sa_data[4],
(unsigned char)ifr.ifr_hwaddr.sa_data[5]);
#else
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", (unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[0], (unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[1],
(unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[2], (unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[3],
(unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[4], (unsigned char)ifr.ifr_ifru.ifru_addr.sa_data[5]);
#endif
return mac;
}
#else
static std::string getMacAddress(const std::string& address)
{
IP_ADAPTER_INFO* first;
IP_ADAPTER_INFO* pos;
ULONG bufferLength = sizeof(IP_ADAPTER_INFO);
first = (IP_ADAPTER_INFO*)malloc(bufferLength);
if (GetAdaptersInfo(first, &bufferLength) == ERROR_BUFFER_OVERFLOW)
{
free(first);
first = (IP_ADAPTER_INFO*)malloc(bufferLength);
}
char mac[19];
if (GetAdaptersInfo(first, &bufferLength) == NO_ERROR)
for (pos = first; pos != NULL; pos = pos->Next)
{
IP_ADDR_STRING* firstAddr = &pos->IpAddressList;
IP_ADDR_STRING* posAddr;
for (posAddr = firstAddr; posAddr != NULL; posAddr = posAddr->Next)
if (_stricmp(posAddr->IpAddress.String, address.c_str()) == 0)
{
sprintf(mac, "%02x:%02x:%02x:%02x:%02x:%02x", pos->Address[0], pos->Address[1], pos->Address[2], pos->Address[3], pos->Address[4],
pos->Address[5]);
free(first);
return mac;
}
}
else
free(first);
return mac;
}
#endif
static std::string getHostId(const std::string& defaultId = "")
{
std::string result = strutils::trim_copy(defaultId);
if (!result.empty() // default provided
&& (result != "00:00:00:00:00:00") // default mac returned by getMaxAddress if it fails
&& (result != "02:00:00:00:00:00") // the Android API will return "02:00:00:00:00:00" for WifiInfo.getMacAddress()
&& (result != "ac:de:48:00:11:22") // iBridge interface on new MacBook Pro (later 2016)
)
return result;
#ifdef MACOS
/// https://stackoverflow.com/questions/933460/unique-hardware-id-in-mac-os-x
/// About this Mac, Hardware-UUID
char buf[64];
io_registry_entry_t ioRegistryRoot = IORegistryEntryFromPath(kIOMasterPortDefault, "IOService:/");
CFStringRef uuidCf = (CFStringRef)IORegistryEntryCreateCFProperty(ioRegistryRoot, CFSTR(kIOPlatformUUIDKey), kCFAllocatorDefault, 0);
IOObjectRelease(ioRegistryRoot);
if (CFStringGetCString(uuidCf, buf, 64, kCFStringEncodingMacRoman))
result = buf;
CFRelease(uuidCf);
#elif ANDROID
result = getProp("ro.serialno");
#endif
//#else
// // on embedded platforms it's
// // - either not there
// // - or not unique, or changes during boot
// // - or changes during boot
// std::ifstream infile("/var/lib/dbus/machine-id");
// if (infile.good())
// std::getline(infile, result);
//#endif
strutils::trim(result);
if (!result.empty())
return result;
/// The host name should be unique enough in a LAN
return getHostName();
}
| 13,848
|
C++
|
.h
| 410
| 26.67561
| 153
| 0.570767
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,003
|
daemon.hpp
|
badaix_snapcast/common/daemon.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <string>
class Daemon
{
public:
Daemon(const std::string& user, const std::string& group, const std::string& pidfile);
virtual ~Daemon();
void daemonize();
private:
int pidFilehandle_;
std::string user_;
std::string group_;
std::string pidfile_;
};
| 1,066
|
C++
|
.h
| 29
| 32.793103
| 90
| 0.731256
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,004
|
time_defs.hpp
|
badaix_snapcast/common/time_defs.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <chrono>
#include <thread>
#ifdef MACOS
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#ifndef WINDOWS
#include <sys/time.h>
#else
#include <Windows.h>
#include <stdint.h>
#include <winsock2.h>
#endif
namespace chronos
{
using clk =
#ifndef WINDOWS
std::chrono::steady_clock;
#else
std::chrono::system_clock;
#endif
using time_point_clk = std::chrono::time_point<clk>;
using sec = std::chrono::seconds;
using msec = std::chrono::milliseconds;
using usec = std::chrono::microseconds;
using nsec = std::chrono::nanoseconds;
template <class Clock>
inline static void timeofday(struct timeval* tv)
{
auto now = Clock::now();
auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
tv->tv_sec = static_cast<long>(microsecs.count() / 1000000);
tv->tv_usec = static_cast<long>(microsecs.count() % 1000000);
}
#ifdef WINDOWS
// Implementation from http://stackoverflow.com/a/26085827/2510022
inline static int gettimeofday(struct timeval* tp, struct timezone* tzp)
{
std::ignore = tzp;
// Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);
SYSTEMTIME system_time;
FILETIME file_time;
uint64_t time;
GetSystemTime(&system_time);
SystemTimeToFileTime(&system_time, &file_time);
time = ((uint64_t)file_time.dwLowDateTime);
time += ((uint64_t)file_time.dwHighDateTime) << 32;
tp->tv_sec = (long)((time - EPOCH) / 10000000L);
tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
return 0;
}
#endif
inline static void steadytimeofday(struct timeval* tv)
{
#ifndef WINDOWS
timeofday<clk>(tv);
#else
gettimeofday(tv, NULL);
#endif
}
inline static void systemtimeofday(struct timeval* tv)
{
timeofday<std::chrono::system_clock>(tv);
}
template <class ToDuration>
inline ToDuration diff(const timeval& tv1, const timeval& tv2)
{
auto sec = tv1.tv_sec - tv2.tv_sec;
auto usec = tv1.tv_usec - tv2.tv_usec;
while (usec < 0)
{
sec -= 1;
usec += 1000000;
}
return std::chrono::duration_cast<ToDuration>(std::chrono::seconds(sec) + std::chrono::microseconds(usec));
}
inline static long getTickCount()
{
#if defined(MACOS)
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
return mts.tv_sec * 1000 + mts.tv_nsec / 1000000;
#elif defined(WINDOWS)
return getTickCount();
#else
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
return now.tv_sec * 1000 + now.tv_nsec / 1000000;
#endif
}
template <class Rep, class Period>
inline std::chrono::duration<Rep, Period> abs(std::chrono::duration<Rep, Period> d)
{
Rep x = d.count();
return std::chrono::duration<Rep, Period>(x >= 0 ? x : -x);
}
template <class ToDuration, class Rep, class Period>
inline int64_t duration(std::chrono::duration<Rep, Period> d)
{
return std::chrono::duration_cast<ToDuration>(d).count();
}
/// some sleep functions. Just for convenience.
template <class Rep, class Period>
inline void sleep(const std::chrono::duration<Rep, Period>& sleep_duration)
{
std::this_thread::sleep_for(sleep_duration);
}
inline void sleep(const int32_t& milliseconds)
{
if (milliseconds < 0)
return;
sleep(msec(milliseconds));
}
inline void usleep(const int32_t& microseconds)
{
if (microseconds < 0)
return;
sleep(usec(microseconds));
}
} // namespace chronos
| 4,409
|
C++
|
.h
| 140
| 28.442857
| 111
| 0.718323
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,005
|
error_code.hpp
|
badaix_snapcast/common/error_code.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <optional>
#include <string>
#include <system_error>
namespace snapcast
{
struct ErrorCode : public std::error_code
{
ErrorCode() : std::error_code(), detail_(std::nullopt)
{
}
ErrorCode(const std::error_code& code) : std::error_code(code), detail_(std::nullopt)
{
}
ErrorCode(const std::error_code& code, std::string detail) : std::error_code(code), detail_(std::move(detail))
{
}
std::string detailed_message() const
{
if (detail_.has_value())
return message() + ": " + *detail_;
return message();
}
private:
std::optional<std::string> detail_;
};
} // namespace snapcast
| 1,447
|
C++
|
.h
| 42
| 30.071429
| 114
| 0.695183
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,006
|
queue.hpp
|
badaix_snapcast/common/queue.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <atomic>
#include <condition_variable>
#include <deque>
#include <mutex>
template <typename T>
class Queue
{
public:
T pop()
{
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty())
cond_.wait(mlock);
// std::lock_guard<std::mutex> lock(mutex_);
auto val = queue_.front();
queue_.pop_front();
return val;
}
void abort_wait()
{
{
std::lock_guard<std::mutex> mlock(mutex_);
abort_ = true;
}
cond_.notify_one();
}
bool wait_for(const std::chrono::microseconds& timeout) const
{
std::unique_lock<std::mutex> mlock(mutex_);
abort_ = false;
if (!cond_.wait_for(mlock, timeout, [this] { return (!queue_.empty() || abort_); }))
return false;
return !queue_.empty() && !abort_;
}
bool try_pop(T& item, const std::chrono::microseconds& timeout = std::chrono::microseconds(0))
{
std::unique_lock<std::mutex> mlock(mutex_);
abort_ = false;
if (timeout.count() > 0)
{
if (!cond_.wait_for(mlock, timeout, [this] { return (!queue_.empty() || abort_); }))
return false;
}
if (queue_.empty() || abort_)
return false;
item = std::move(queue_.front());
queue_.pop_front();
return true;
}
void pop(T& item)
{
std::unique_lock<std::mutex> mlock(mutex_);
while (queue_.empty())
cond_.wait(mlock);
item = queue_.front();
queue_.pop_front();
}
void push_front(const T& item)
{
{
std::lock_guard<std::mutex> mlock(mutex_);
queue_.push_front(item);
}
cond_.notify_one();
}
bool back_copy(T& copy)
{
std::lock_guard<std::mutex> mlock(mutex_);
if (queue_.empty())
return false;
copy = queue_.back();
return true;
}
bool front_copy(T& copy)
{
std::lock_guard<std::mutex> mlock(mutex_);
if (queue_.empty())
return false;
copy = queue_.front();
return true;
}
void push_front(T&& item)
{
{
std::lock_guard<std::mutex> mlock(mutex_);
queue_.push_front(std::move(item));
}
cond_.notify_one();
}
void push(const T& item)
{
{
std::lock_guard<std::mutex> mlock(mutex_);
queue_.push_back(item);
}
cond_.notify_one();
}
void push(T&& item)
{
{
std::lock_guard<std::mutex> mlock(mutex_);
queue_.push_back(std::move(item));
}
cond_.notify_one();
}
size_t size() const
{
std::lock_guard<std::mutex> mlock(mutex_);
return queue_.size();
}
bool empty() const
{
return (size() == 0);
}
Queue() = default;
Queue(const Queue&) = delete; // disable copying
Queue& operator=(const Queue&) = delete; // disable assignment
private:
std::deque<T> queue_;
mutable std::atomic<bool> abort_;
mutable std::mutex mutex_;
mutable std::condition_variable cond_;
};
| 4,033
|
C++
|
.h
| 139
| 21.748201
| 98
| 0.562193
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,007
|
snap_exception.hpp
|
badaix_snapcast/common/snap_exception.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <exception>
#include <string>
// text_exception uses a dynamically-allocated internal c-string for what():
class SnapException : public std::exception
{
std::string text_;
int error_code_;
public:
SnapException(const char* text, int error_code = 0) : text_(text), error_code_(error_code)
{
}
SnapException(const std::string& text, int error_code = 0) : SnapException(text.c_str(), error_code)
{
}
~SnapException() throw() override = default;
int code() const noexcept
{
return error_code_;
}
const char* what() const noexcept override
{
return text_.c_str();
}
};
| 1,430
|
C++
|
.h
| 40
| 31.375
| 104
| 0.707759
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,009
|
sample_format.hpp
|
badaix_snapcast/common/sample_format.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <cstdint>
#include <string>
/**
* sample and frame as defined in alsa:
* http://www.alsa-project.org/main/index.php/FramesPeriods
* Say we want to work with a stereo, 16-bit, 44.1 KHz stream, one-way (meaning, either in playback or in capture direction). Then we have:
* 'stereo' = number of channels: 2
* 1 analog sample is represented with 16 bits = 2 bytes
* 1 frame represents 1 analog sample from all channels; here we have 2 channels, and so:
* 1 frame = (num_channels) * (1 sample in bytes) = (2 channels) * (2 bytes (16 bits) per sample) = 4 bytes (32 bits)
* To sustain 2x 44.1 KHz analog rate - the system must be capable of data transfer rate, in Bytes/sec:
* Bps_rate = (num_channels) * (1 sample in bytes) * (analog_rate) = (1 frame) * (analog_rate) = ( 2 channels ) * (2 bytes/sample) * (44100 samples/sec) =
* 2*2*44100 = 176400 Bytes/sec (link to formula img)
*/
class SampleFormat
{
public:
SampleFormat();
SampleFormat(const std::string& format);
SampleFormat(uint32_t rate, uint16_t bits, uint16_t channels);
std::string toString() const;
void setFormat(const std::string& format);
void setFormat(uint32_t rate, uint16_t bits, uint16_t channels);
bool isInitialized() const
{
return ((rate_ != 0) || (bits_ != 0) || (channels_ != 0));
}
uint32_t rate() const
{
return rate_;
}
uint16_t bits() const
{
return bits_;
}
uint16_t channels() const
{
return channels_;
}
// size in [bytes] of a single mono sample, e.g. 2 bytes (= 16 bits)
uint16_t sampleSize() const
{
return sample_size_;
}
// size in [bytes] of a frame (sum of sample sizes = #channel*sampleSize), e.g. 4 bytes (= 2 channel * 16 bit)
uint16_t frameSize() const
{
return frame_size_;
}
inline double msRate() const
{
return (double)rate_ / 1000.;
}
inline double usRate() const
{
return (double)rate_ / 1000000.;
}
inline double nsRate() const
{
return (double)rate_ / 1000000000.;
}
private:
uint16_t sample_size_;
uint16_t frame_size_;
uint32_t rate_;
uint16_t bits_;
uint16_t channels_;
};
| 3,016
|
C++
|
.h
| 84
| 31.214286
| 154
| 0.66701
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,011
|
str_compat.hpp
|
badaix_snapcast/common/str_compat.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <clocale>
#include <string>
#ifdef NO_CPP11_STRING
#include <cerrno>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <stdexcept>
#endif
namespace cpt
{
static struct lconv* localeconv()
{
#ifdef NO_CPP11_STRING
static struct lconv result;
result.decimal_point = nullptr;
result.thousands_sep = nullptr;
return &result;
#else
return std::localeconv();
#endif
}
template <typename T>
static std::string to_string(const T& t)
{
#ifdef NO_CPP11_STRING
std::stringstream ss;
ss << t;
return ss.str();
#else
return std::to_string(t);
#endif
}
static long stoul(const std::string& str)
{
#ifdef NO_CPP11_STRING
errno = 0;
char* temp;
long val = strtol(str.c_str(), &temp, 10);
if (temp == str.c_str() || *temp != '\0')
throw std::invalid_argument("stoi");
if (((val == LONG_MIN) || (val == LONG_MAX)) && (errno == ERANGE))
throw std::out_of_range("stoi");
return val;
#else
return std::stoul(str);
#endif
}
static int stoi(const std::string& str)
{
#ifdef NO_CPP11_STRING
return cpt::stoul(str);
#else
return std::stoi(str);
#endif
}
static int stoi(const std::string& str, int def)
{
try
{
return cpt::stoi(str);
}
catch (...)
{
return def;
}
}
static double stod(const std::string& str)
{
#ifdef NO_CPP11_STRING
errno = 0;
char* temp;
double val = strtod(str.c_str(), &temp);
if (temp == str.c_str() || *temp != '\0')
throw std::invalid_argument("stod");
if ((val == HUGE_VAL) && (errno == ERANGE))
throw std::out_of_range("stod");
return val;
#else
return std::stod(str.c_str());
#endif
}
static long double strtold(const char* str, char** endptr)
{
#ifdef NO_CPP11_STRING
std::ignore = endptr;
return cpt::stod(str);
#else
return std::strtold(str, endptr);
#endif
}
static float strtof(const char* str, char** endptr)
{
#ifdef NO_CPP11_STRING
std::ignore = endptr;
return (float)cpt::stod(str);
#else
return std::strtof(str, endptr);
#endif
}
} // namespace cpt
| 2,885
|
C++
|
.h
| 118
| 21.245763
| 73
| 0.676118
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,012
|
resampler.hpp
|
badaix_snapcast/common/resampler.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/pcm_chunk.hpp"
#include "common/sample_format.hpp"
// 3rd party headers
#ifdef HAS_SOXR
#include <soxr.h>
#endif
// standard headers
#include <vector>
class Resampler
{
public:
Resampler(const SampleFormat& in_format, const SampleFormat& out_format);
virtual ~Resampler();
// std::shared_ptr<msg::PcmChunk> resample(std::shared_ptr<msg::PcmChunk> chunk, chronos::usec duration);
std::shared_ptr<msg::PcmChunk> resample(std::shared_ptr<msg::PcmChunk> chunk);
std::shared_ptr<msg::PcmChunk> resample(const msg::PcmChunk& chunk);
bool resamplingNeeded() const;
private:
std::vector<char> resample_buffer_;
// std::unique_ptr<msg::PcmChunk> resampled_chunk_;
SampleFormat in_format_;
SampleFormat out_format_;
#ifdef HAS_SOXR
soxr_t soxr_{nullptr};
#endif
};
| 1,603
|
C++
|
.h
| 42
| 34.690476
| 109
| 0.741123
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,013
|
pcm_chunk.hpp
|
badaix_snapcast/common/message/pcm_chunk.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef MESSAGE_PCM_CHUNK_HPP
#define MESSAGE_PCM_CHUNK_HPP
// local headers
#include "common/sample_format.hpp"
#include "message.hpp"
#include "wire_chunk.hpp"
// standard headers
#include <chrono>
namespace msg
{
/**
* Piece of PCM data with SampleFormat information
* Has information about "when" recorded (start) and duration
* frames can be read with "readFrames", which will also change the start time
*/
class PcmChunk : public WireChunk
{
public:
PcmChunk(const SampleFormat& sampleFormat, uint32_t ms)
: WireChunk((sampleFormat.rate() * ms / 1000) * sampleFormat.frameSize()), format(sampleFormat), idx_(0)
{
}
PcmChunk() : WireChunk(), idx_(0)
{
}
~PcmChunk() override = default;
#if 0
template <class Rep, class Period>
int readFrames(void* outputBuffer, const std::chrono::duration<Rep, Period>& duration)
{
auto us = std::chrono::microseconds(duration).count();
auto frames = (us * 48000) / std::micro::den;
// return readFrames(outputBuffer, (us * 48000) / std::micro::den);
return frames;
}
#endif
// std::unique_ptr<PcmChunk> consume(uint32_t frameCount)
// {
// auto result = std::make_unique<PcmChunk>(format, 0);
// if (frameCount * format.frameSize() > payloadSize)
// frameCount = payloadSize / format.frameSize();
// result->payload = payload;
// result->payloadSize = frameCount * format.frameSize();
// payloadSize -= result->payloadSize;
// payload = (char*)realloc(payload + result->payloadSize, payloadSize);
// // payload += result->payloadSize;
// return result;
// }
int readFrames(void* outputBuffer, uint32_t frameCount)
{
// logd << "read: " << frameCount << ", total: " << (wireChunk->length / format.frameSize()) << ", idx: " << idx;// << std::endl;
int result = frameCount;
if (idx_ + frameCount > (payloadSize / format.frameSize()))
result = (payloadSize / format.frameSize()) - idx_;
// logd << ", from: " << format.frameSize()*idx << ", to: " << format.frameSize()*idx + format.frameSize()*result;
if (outputBuffer != nullptr)
memcpy((char*)outputBuffer, (char*)(payload) + format.frameSize() * idx_, format.frameSize() * result);
idx_ += result;
// logd << ", new idx: " << idx << ", result: " << result << ", wireChunk->length: " << wireChunk->length << ", format.frameSize(): " <<
// format.frameSize() << "\n";
return result;
}
int seek(int frames)
{
if ((frames < 0) && (-frames > static_cast<int>(idx_)))
frames = -static_cast<int>(idx_);
idx_ += frames;
if (idx_ > getFrameCount())
idx_ = getFrameCount();
return idx_;
}
chronos::time_point_clk start() const override
{
return chronos::time_point_clk(chronos::sec(timestamp.sec) + chronos::usec(timestamp.usec) +
chronos::usec(static_cast<chronos::usec::rep>(1000000. * ((double)idx_ / (double)format.rate()))));
}
inline chronos::time_point_clk end() const
{
return start() + durationLeft<chronos::usec>();
}
template <typename T>
inline T duration() const
{
return std::chrono::duration_cast<T>(chronos::nsec(static_cast<chronos::nsec::rep>(1000000 * getFrameCount() / format.msRate())));
}
// void append(const PcmChunk& chunk)
// {
// auto newSize = payloadSize + chunk.payloadSize;
// payload = (char*)realloc(payload, newSize);
// memcpy(payload + payloadSize, chunk.payload, chunk.payloadSize);
// payloadSize = newSize;
// }
void setFrameCount(int frameCount)
{
auto newSize = format.frameSize() * frameCount;
payload = static_cast<char*>(realloc(payload, newSize));
payloadSize = newSize;
}
double durationMs() const
{
return static_cast<double>(getFrameCount()) / format.msRate();
}
template <typename T>
inline T durationLeft() const
{
return std::chrono::duration_cast<T>(chronos::nsec(static_cast<chronos::nsec::rep>(1000000 * (getFrameCount() - idx_) / format.msRate())));
}
inline bool isEndOfChunk() const
{
return idx_ >= getFrameCount();
}
inline uint32_t getFrameCount() const
{
return (payloadSize / format.frameSize());
}
inline uint32_t getSampleCount() const
{
return (payloadSize / format.sampleSize());
}
SampleFormat format;
private:
uint32_t idx_ = 0;
};
} // namespace msg
#endif
| 5,421
|
C++
|
.h
| 139
| 33.172662
| 147
| 0.631238
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,014
|
message.hpp
|
badaix_snapcast/common/message/message.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/endian.hpp"
#include "common/time_defs.hpp"
// standard headers
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <streambuf>
#ifndef WINDOWS
#include <sys/time.h>
#endif
#include <memory>
/*
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT>
{
public:
vectorwrapbuf(std::vector<CharT> &vec)
{
this->setg(vec.data(), vec.data(), vec.data() + vec.size());
}
};
*/
struct membuf : public std::basic_streambuf<char>
{
membuf(char* begin, char* end)
{
this->setg(begin, begin, end);
}
};
enum class message_type : uint16_t
{
kBase = 0,
kCodecHeader = 1,
kWireChunk = 2,
kServerSettings = 3,
kTime = 4,
kHello = 5,
// kStreamTags = 6,
kClientInfo = 7,
kFirst = kBase,
kLast = kClientInfo
};
static std::ostream& operator<<(std::ostream& os, const message_type& msg_type)
{
switch (msg_type)
{
case message_type::kBase:
os << "Base";
break;
case message_type::kCodecHeader:
os << "CodecHeader";
break;
case message_type::kWireChunk:
os << "WireChunk";
break;
case message_type::kServerSettings:
os << "ServerSettings";
break;
case message_type::kTime:
os << "Time";
break;
case message_type::kHello:
os << "Hello";
break;
case message_type::kClientInfo:
os << "ClientInfo";
break;
default:
os << "Unknown";
}
return os;
}
struct tv
{
tv()
{
timeval t;
chronos::steadytimeofday(&t);
sec = t.tv_sec;
usec = t.tv_usec;
}
tv(timeval tv) : sec(tv.tv_sec), usec(tv.tv_usec){};
tv(int32_t _sec, int32_t _usec) : sec(_sec), usec(_usec){};
int32_t sec;
int32_t usec;
tv operator+(const tv& other) const
{
tv result(*this);
result.sec += other.sec;
result.usec += other.usec;
if (result.usec > 1000000)
{
result.sec += result.usec / 1000000;
result.usec %= 1000000;
}
return result;
}
tv operator-(const tv& other) const
{
tv result(*this);
result.sec -= other.sec;
result.usec -= other.usec;
while (result.usec < 0)
{
result.sec -= 1;
result.usec += 1000000;
}
return result;
}
};
namespace msg
{
const size_t max_size = 1000000;
struct BaseMessage;
using message_ptr = std::shared_ptr<msg::BaseMessage>;
struct BaseMessage
{
BaseMessage() : BaseMessage(message_type::kBase)
{
}
BaseMessage(message_type type_) : type(type_), id(0), refersTo(0), size(0)
{
}
virtual ~BaseMessage() = default;
virtual void read(std::istream& stream)
{
readVal(stream, type);
readVal(stream, id);
readVal(stream, refersTo);
readVal(stream, sent.sec);
readVal(stream, sent.usec);
readVal(stream, received.sec);
readVal(stream, received.usec);
readVal(stream, size);
}
void deserialize(char* payload)
{
membuf databuf(payload, payload + BaseMessage::getSize());
std::istream is(&databuf);
read(is);
}
void deserialize(const BaseMessage& baseMessage, char* payload)
{
type = baseMessage.type;
id = baseMessage.id;
refersTo = baseMessage.refersTo;
sent = baseMessage.sent;
received = baseMessage.received;
size = baseMessage.size;
membuf databuf(payload, payload + size);
std::istream is(&databuf);
read(is);
}
virtual void serialize(std::ostream& stream) const
{
writeVal(stream, type);
writeVal(stream, id);
writeVal(stream, refersTo);
writeVal(stream, sent.sec);
writeVal(stream, sent.usec);
writeVal(stream, received.sec);
writeVal(stream, received.usec);
size = getSize();
writeVal(stream, size);
doserialize(stream);
}
virtual uint32_t getSize() const
{
return 3 * sizeof(uint16_t) + 2 * sizeof(tv) + sizeof(uint32_t);
};
message_type type;
mutable uint16_t id;
uint16_t refersTo;
tv received;
mutable tv sent;
mutable uint32_t size;
protected:
void writeVal(std::ostream& stream, const bool& val) const
{
char c = val ? 1 : 0;
writeVal(stream, c);
}
void writeVal(std::ostream& stream, const char& val) const
{
stream.write(reinterpret_cast<const char*>(&val), sizeof(char));
}
void writeVal(std::ostream& stream, const uint16_t& val) const
{
uint16_t v = SWAP_16(val);
stream.write(reinterpret_cast<const char*>(&v), sizeof(uint16_t));
}
void writeVal(std::ostream& stream, const message_type& val) const
{
uint16_t v = SWAP_16(static_cast<uint16_t>(val));
stream.write(reinterpret_cast<const char*>(&v), sizeof(uint16_t));
}
void writeVal(std::ostream& stream, const int16_t& val) const
{
uint16_t v = SWAP_16(val);
stream.write(reinterpret_cast<const char*>(&v), sizeof(int16_t));
}
void writeVal(std::ostream& stream, const uint32_t& val) const
{
uint32_t v = SWAP_32(val);
stream.write(reinterpret_cast<const char*>(&v), sizeof(uint32_t));
}
void writeVal(std::ostream& stream, const int32_t& val) const
{
uint32_t v = SWAP_32(val);
stream.write(reinterpret_cast<const char*>(&v), sizeof(int32_t));
}
void writeVal(std::ostream& stream, const char* payload, const uint32_t& size) const
{
writeVal(stream, size);
stream.write(payload, size);
}
void writeVal(std::ostream& stream, const std::string& val) const
{
auto len = static_cast<uint32_t>(val.size());
writeVal(stream, val.c_str(), len);
}
void readVal(std::istream& stream, bool& val) const
{
char c;
readVal(stream, c);
val = (c != 0);
}
void readVal(std::istream& stream, char& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(char));
}
void readVal(std::istream& stream, uint16_t& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(uint16_t));
// cppcheck-suppress selfAssignment
val = SWAP_16(val);
}
void readVal(std::istream& stream, message_type& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(uint16_t));
val = static_cast<message_type>(SWAP_16(static_cast<uint16_t>(val)));
}
void readVal(std::istream& stream, int16_t& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(int16_t));
// cppcheck-suppress selfAssignment
val = SWAP_16(val);
}
void readVal(std::istream& stream, uint32_t& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(uint32_t));
// cppcheck-suppress selfAssignment
val = SWAP_32(val);
}
void readVal(std::istream& stream, int32_t& val) const
{
stream.read(reinterpret_cast<char*>(&val), sizeof(int32_t));
// cppcheck-suppress selfAssignment
val = SWAP_32(val);
}
void readVal(std::istream& stream, char** payload, uint32_t& size) const
{
readVal(stream, size);
*payload = (char*)realloc(*payload, size);
stream.read(*payload, size);
}
void readVal(std::istream& stream, std::string& val) const
{
uint32_t len;
readVal(stream, len);
val.resize(len);
stream.read(&val[0], len);
}
virtual void doserialize(std::ostream& /*stream*/) const {};
};
} // namespace msg
| 8,743
|
C++
|
.h
| 292
| 23.393836
| 88
| 0.607691
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,016
|
json_message.hpp
|
badaix_snapcast/common/message/json_message.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef MESSAGE_JSON_HPP
#define MESSAGE_JSON_HPP
// local headers
#include "common/json.hpp"
#include "message.hpp"
using json = nlohmann::json;
namespace msg
{
class JsonMessage : public BaseMessage
{
public:
JsonMessage(message_type msgType) : BaseMessage(msgType)
{
}
~JsonMessage() override = default;
void read(std::istream& stream) override
{
std::string s;
readVal(stream, s);
msg = json::parse(s);
}
uint32_t getSize() const override
{
return static_cast<uint32_t>(sizeof(uint32_t) + msg.dump().size());
}
json msg;
protected:
void doserialize(std::ostream& stream) const override
{
writeVal(stream, msg.dump());
}
template <typename T>
T get(const std::string& what, const T& def) const
{
try
{
if (!msg.count(what))
return def;
return msg[what].get<T>();
}
catch (...)
{
return def;
}
}
};
} // namespace msg
#endif
| 1,795
|
C++
|
.h
| 62
| 23.451613
| 75
| 0.656359
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,017
|
client_info.hpp
|
badaix_snapcast/common/message/client_info.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef MESSAGE_CLIENT_INFO_HPP
#define MESSAGE_CLIENT_INFO_HPP
// local headers
#include "json_message.hpp"
namespace msg
{
/// Client information sent from client to server
/// Might also be used for sync stats and latency estimations
class ClientInfo : public JsonMessage
{
public:
ClientInfo() : JsonMessage(message_type::kClientInfo)
{
setVolume(100);
setMuted(false);
}
~ClientInfo() override = default;
uint16_t getVolume()
{
return get("volume", static_cast<uint16_t>(100));
}
bool isMuted()
{
return get("muted", false);
}
void setVolume(uint16_t volume)
{
msg["volume"] = volume;
}
void setMuted(bool muted)
{
msg["muted"] = muted;
}
};
} // namespace msg
#endif
| 1,537
|
C++
|
.h
| 50
| 26.24
| 73
| 0.69837
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,020
|
codec_header.hpp
|
badaix_snapcast/common/message/codec_header.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef MESSAGE_CODEC_HEADER_HPP
#define MESSAGE_CODEC_HEADER_HPP
// local headers
#include "message.hpp"
namespace msg
{
/**
* Codec dependend header of encoded data stream
*/
class CodecHeader : public BaseMessage
{
public:
CodecHeader(const std::string& codecName = "", uint32_t size = 0)
: BaseMessage(message_type::kCodecHeader), payloadSize(size), payload(nullptr), codec(codecName)
{
if (size > 0)
payload = (char*)malloc(size * sizeof(char));
}
~CodecHeader() override
{
free(payload);
}
void read(std::istream& stream) override
{
readVal(stream, codec);
readVal(stream, &payload, payloadSize);
}
uint32_t getSize() const override
{
return static_cast<uint32_t>(sizeof(uint32_t) + codec.size() + sizeof(uint32_t) + payloadSize);
}
uint32_t payloadSize;
char* payload;
std::string codec;
protected:
void doserialize(std::ostream& stream) const override
{
writeVal(stream, codec);
writeVal(stream, payload, payloadSize);
}
};
} // namespace msg
#endif
| 1,859
|
C++
|
.h
| 57
| 27.894737
| 104
| 0.696309
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,021
|
factory.hpp
|
badaix_snapcast/common/message/factory.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "client_info.hpp"
#include "codec_header.hpp"
#include "hello.hpp"
#include "pcm_chunk.hpp"
#include "server_settings.hpp"
#include "time.hpp"
namespace msg
{
template <typename ToType>
static std::unique_ptr<ToType> message_cast(std::unique_ptr<msg::BaseMessage> message)
{
ToType* tmp = dynamic_cast<ToType*>(message.get());
std::unique_ptr<ToType> result;
if (tmp != nullptr)
{
message.release();
result.reset(tmp);
return result;
}
return nullptr;
}
namespace factory
{
template <typename T>
static std::unique_ptr<T> createMessage(const BaseMessage& base_message, char* buffer)
{
std::unique_ptr<T> result = std::make_unique<T>();
if (!result)
return nullptr;
result->deserialize(base_message, buffer);
return result;
}
static std::unique_ptr<BaseMessage> createMessage(const BaseMessage& base_message, char* buffer)
{
std::unique_ptr<BaseMessage> result;
switch (base_message.type)
{
case message_type::kCodecHeader:
return createMessage<CodecHeader>(base_message, buffer);
case message_type::kHello:
return createMessage<Hello>(base_message, buffer);
case message_type::kServerSettings:
return createMessage<ServerSettings>(base_message, buffer);
case message_type::kTime:
return createMessage<Time>(base_message, buffer);
case message_type::kWireChunk:
// this is kind of cheated to safe the convertion from WireChunk to PcmChunk
// the user of the factory must be aware that a PcmChunk will be created
return createMessage<PcmChunk>(base_message, buffer);
case message_type::kClientInfo:
return createMessage<ClientInfo>(base_message, buffer);
default:
return nullptr;
}
}
} // namespace factory
} // namespace msg
| 2,665
|
C++
|
.h
| 73
| 31.219178
| 96
| 0.703373
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,023
|
file_utils.hpp
|
badaix_snapcast/common/utils/file_utils.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2021 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef FILE_UTILS_HPP
#define FILE_UTILS_HPP
// local headers
#include "string_utils.hpp"
// 3rd party headers
// standard headers
#ifndef WINDOWS
#include <grp.h>
#include <pwd.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <filesystem>
#include <fstream>
#include <stdexcept>
#include <vector>
namespace utils
{
namespace file
{
static bool exists(const std::string& filename)
{
return std::filesystem::exists(filename);
}
#ifndef WINDOWS
static void do_chown(const std::string& file_path, const std::string& user_name, const std::string& group_name)
{
if (user_name.empty() && group_name.empty())
return;
if (!utils::file::exists(file_path))
return;
uid_t uid = -1;
gid_t gid = -1;
if (!user_name.empty())
{
struct passwd* pwd = getpwnam(user_name.c_str());
if (pwd == nullptr)
throw std::runtime_error("Failed to get uid");
uid = pwd->pw_uid;
}
if (!group_name.empty())
{
struct group* grp = getgrnam(group_name.c_str());
if (grp == nullptr)
throw std::runtime_error("Failed to get gid");
gid = grp->gr_gid;
}
if (chown(file_path.c_str(), uid, gid) == -1)
throw std::runtime_error("chown failed");
}
static int mkdirRecursive(const char* path, mode_t mode)
{
std::vector<std::string> pathes = utils::string::split(path, '/');
std::stringstream ss;
int res = 0;
for (const auto& p : pathes)
{
if (p.empty())
continue;
ss << "/" << p;
res = mkdir(ss.str().c_str(), mode);
if ((res != 0) && (errno != EEXIST))
return res;
}
return res;
}
#endif
} // namespace file
} // namespace utils
#endif
| 2,496
|
C++
|
.h
| 84
| 25.166667
| 111
| 0.653138
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,024
|
string_utils.hpp
|
badaix_snapcast/common/utils/string_utils.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2021 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef STRING_UTILS_HPP
#define STRING_UTILS_HPP
#include <algorithm>
#include <map>
#include <sstream>
#include <stdio.h>
#include <string>
#include <vector>
#ifdef WINDOWS
#include <cctype>
#endif
namespace utils
{
namespace string
{
// trim from start
static inline std::string& ltrim(std::string& s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) { return !std::isspace(ch); }));
return s;
}
// trim from end
static inline std::string& rtrim(std::string& s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), [](int ch) { return !std::isspace(ch); }).base(), s.end());
return s;
}
// trim from both ends
static inline std::string& trim(std::string& s)
{
return ltrim(rtrim(s));
}
// trim from start
static inline std::string ltrim_copy(const std::string& s)
{
std::string str(s);
return ltrim(str);
}
// trim from end
static inline std::string rtrim_copy(const std::string& s)
{
std::string str(s);
return rtrim(str);
}
// trim from both ends
static inline std::string trim_copy(const std::string& s)
{
std::string str(s);
return trim(str);
}
// decode %xx to char
static std::string uriDecode(const std::string& src)
{
std::string ret;
char ch;
for (size_t i = 0; i < src.length(); i++)
{
if (int(src[i]) == 37)
{
unsigned int ii;
sscanf(src.substr(i + 1, 2).c_str(), "%x", &ii);
ch = static_cast<char>(ii);
ret += ch;
i += 2;
}
else
{
ret += src[i];
}
}
return (ret);
}
static void split_left(const std::string& s, char delim, std::string& left, std::string& right)
{
auto pos = s.find(delim);
if (pos != std::string::npos)
{
left = s.substr(0, pos);
right = s.substr(pos + 1);
}
else
{
left = s;
right = "";
}
}
static std::string split_left(const std::string& s, char delim, std::string& right)
{
std::string left;
split_left(s, delim, left, right);
return left;
}
static std::vector<std::string>& split(const std::string& s, char delim, std::vector<std::string>& elems)
{
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim))
{
elems.push_back(item);
}
return elems;
}
static std::vector<std::string> split(const std::string& s, char delim)
{
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
template <typename T>
static std::map<std::string, T> split_pairs_to_container(const std::string& s, char pair_delim, char key_value_delim)
{
std::map<std::string, T> result;
auto keyValueList = split(s, pair_delim);
for (auto& kv : keyValueList)
{
auto pos = kv.find(key_value_delim);
if (pos != std::string::npos)
{
std::string key = trim_copy(kv.substr(0, pos));
std::string value = trim_copy(kv.substr(pos + 1));
result[key].push_back(std::move(value));
}
}
return result;
}
static std::map<std::string, std::string> split_pairs(const std::string& s, char pair_delim, char key_value_delim)
{
std::map<std::string, std::string> result;
auto pairs = split_pairs_to_container<std::vector<std::string>>(s, pair_delim, key_value_delim);
for (auto& pair : pairs)
result[pair.first] = *pair.second.begin();
return result;
}
static inline std::string& tolower(std::string& s)
{
std::transform(s.begin(), s.end(), s.begin(), [](unsigned char c) { return static_cast<char>(std::tolower(c)); });
return s;
}
static inline std::string tolower_copy(const std::string& s)
{
std::string str(s);
return tolower(str);
}
} // namespace string
} // namespace utils
#endif
| 4,526
|
C++
|
.h
| 160
| 24.0625
| 118
| 0.640055
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
25,025
|
logging.hpp
|
badaix_snapcast/common/utils/logging.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2021 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef LOGGING_UTILS_HPP
#define LOGGING_UTILS_HPP
#include "common/aixlog.hpp"
#include <chrono>
namespace utils
{
namespace logging
{
using namespace std::chrono_literals;
/// Log Conditional to limit log frequency
struct TimeConditional : public AixLog::Conditional
{
/// c'tor
/// @param interval duration that must be passed since the last log line
TimeConditional(const std::chrono::milliseconds& interval) : interval_(interval)
{
reset();
}
/// return true for the next check
void reset()
{
last_time_ = std::chrono::steady_clock::now() - interval_ - 1s;
}
/// Change log interval
/// @param interval duration that must be passed since the last log line
void setInterval(const std::chrono::milliseconds& interval)
{
interval_ = interval;
}
/// check if the interval is passed
/// @return true if interval passed since the last log
bool is_true() const override
{
auto now = std::chrono::steady_clock::now();
if (now > last_time_ + interval_)
{
last_time_ = now;
return true;
}
return false;
}
private:
/// log interval
std::chrono::milliseconds interval_;
/// last log time
mutable std::chrono::steady_clock::time_point last_time_;
};
} // namespace logging
} // namespace utils
#endif
| 2,126
|
C++
|
.h
| 64
| 28.421875
| 84
| 0.687836
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
25,026
|
control_session_ws.hpp
|
badaix_snapcast/server/control_session_ws.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "control_session.hpp"
// 3rd party headers
#include <boost/asio/strand.hpp>
#pragma GCC diagnostic push
#if defined(__clang__)
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wdeprecated-copy-with-user-provided-copy"
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
#include <boost/beast/core.hpp>
#pragma GCC diagnostic pop
#include <boost/beast/websocket.hpp>
// standard headers
#include <deque>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
/// Endpoint for a connected control client.
/**
* Endpoint for a connected control client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the ControlMessageReceiver callback
*/
class ControlSessionWebsocket : public ControlSession
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket);
~ControlSessionWebsocket() override;
void start() override;
void stop() override;
/// Sends a message to the client (asynchronous)
void sendAsync(const std::string& message) override;
protected:
// Websocket methods
void on_read_ws(beast::error_code ec, std::size_t bytes_transferred);
void do_read_ws();
void send_next();
websocket::stream<beast::tcp_stream> ws_;
protected:
beast::flat_buffer buffer_;
boost::asio::strand<boost::asio::any_io_executor> strand_;
std::deque<std::string> messages_;
};
| 2,518
|
C++
|
.h
| 61
| 38.180328
| 109
| 0.754199
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,027
|
stream_session.hpp
|
badaix_snapcast/server/stream_session.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/message.hpp"
#include "streamreader/stream_manager.hpp"
// 3rd party headers
#include <boost/asio/any_io_executor.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/asio/strand.hpp>
// standard headers
#include <deque>
#include <memory>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
class StreamSession;
/// Interface: callback for a received message.
class StreamMessageReceiver
{
public:
virtual void onMessageReceived(StreamSession* connection, const msg::BaseMessage& baseMessage, char* buffer) = 0;
virtual void onDisconnect(StreamSession* connection) = 0;
};
// A reference-counted non-modifiable buffer class.
class shared_const_buffer
{
struct Message
{
std::vector<char> data;
bool is_pcm_chunk;
message_type type;
chronos::time_point_clk rec_time;
};
public:
shared_const_buffer(msg::BaseMessage& message) : on_air(false)
{
tv t;
message.sent = t;
const msg::PcmChunk* pcm_chunk = dynamic_cast<const msg::PcmChunk*>(&message);
message_ = std::make_shared<Message>();
message_->type = message.type;
message_->is_pcm_chunk = (pcm_chunk != nullptr);
if (message_->is_pcm_chunk)
message_->rec_time = pcm_chunk->start();
std::ostringstream oss;
message.serialize(oss);
std::string s = oss.str();
message_->data = std::vector<char>(s.begin(), s.end());
buffer_ = boost::asio::buffer(message_->data);
}
// Implement the ConstBufferSequence requirements.
using value_type = boost::asio::const_buffer;
using const_iterator = const boost::asio::const_buffer*;
const boost::asio::const_buffer* begin() const
{
return &buffer_;
}
const boost::asio::const_buffer* end() const
{
return &buffer_ + 1;
}
const Message& message() const
{
return *message_;
}
bool on_air;
private:
std::shared_ptr<Message> message_;
boost::asio::const_buffer buffer_;
};
using WriteHandler = std::function<void(boost::system::error_code ec, std::size_t length)>;
/// Endpoint for a connected client.
/**
* Endpoint for a connected client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the StreamMessageReceiver callback
*/
class StreamSession : public std::enable_shared_from_this<StreamSession>
{
public:
/// ctor. Received message from the client are passed to StreamMessageReceiver
StreamSession(const boost::asio::any_io_executor& executor, StreamMessageReceiver* receiver);
virtual ~StreamSession() = default;
virtual std::string getIP() = 0;
virtual void start() = 0;
virtual void stop() = 0;
void setMessageReceiver(StreamMessageReceiver* receiver)
{
messageReceiver_ = receiver;
}
protected:
virtual void sendAsync(const shared_const_buffer& buffer, const WriteHandler& handler) = 0;
public:
/// Sends a message to the client (asynchronous)
void send(msg::message_ptr message);
/// Sends a message to the client (asynchronous)
void send(shared_const_buffer const_buf);
/// Max playout latency. No need to send PCM data that is older than bufferMs
void setBufferMs(size_t bufferMs);
std::string clientId;
void setPcmStream(streamreader::PcmStreamPtr pcmStream);
const streamreader::PcmStreamPtr pcmStream() const;
protected:
void send_next();
msg::BaseMessage baseMessage_;
std::vector<char> buffer_;
size_t base_msg_size_;
StreamMessageReceiver* messageReceiver_;
size_t bufferMs_;
streamreader::PcmStreamPtr pcmStream_;
boost::asio::strand<boost::asio::any_io_executor> strand_;
std::deque<shared_const_buffer> messages_;
mutable std::mutex mutex_;
};
| 4,639
|
C++
|
.h
| 128
| 31.585938
| 117
| 0.705475
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,028
|
stream_server.hpp
|
badaix_snapcast/server/stream_server.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/message.hpp"
#include "common/queue.hpp"
#include "control_server.hpp"
#include "server_settings.hpp"
#include "stream_session.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <memory>
#include <mutex>
#include <vector>
using namespace streamreader;
using boost::asio::ip::tcp;
using acceptor_ptr = std::unique_ptr<tcp::acceptor>;
using session_ptr = std::shared_ptr<StreamSession>;
/// Forwars PCM data to the connected clients
/**
* Reads PCM data from several StreamSessions
* Accepts and holds client connections (StreamSession)
* Receives (via the StreamMessageReceiver interface) and answers messages from the clients
* Forwards PCM data to the clients
*/
class StreamServer : public StreamMessageReceiver
{
public:
StreamServer(boost::asio::io_context& io_context, const ServerSettings& serverSettings, StreamMessageReceiver* messageReceiver = nullptr);
virtual ~StreamServer();
void start();
void stop();
/// Send a message to all connceted clients
// void send(const msg::BaseMessage* message);
void addSession(std::shared_ptr<StreamSession> session);
void onChunkEncoded(const PcmStream* pcmStream, bool isDefaultStream, std::shared_ptr<msg::PcmChunk> chunk, double duration);
session_ptr getStreamSession(const std::string& clientId) const;
session_ptr getStreamSession(StreamSession* session) const;
private:
void startAccept();
void handleAccept(tcp::socket socket);
void cleanup();
/// Implementation of StreamMessageReceiver
void onMessageReceived(StreamSession* streamSession, const msg::BaseMessage& baseMessage, char* buffer) override;
void onDisconnect(StreamSession* streamSession) override;
mutable std::recursive_mutex sessionsMutex_;
std::vector<std::weak_ptr<StreamSession>> sessions_;
boost::asio::io_context& io_context_;
std::vector<acceptor_ptr> acceptor_;
boost::asio::steady_timer config_timer_;
ServerSettings settings_;
Queue<std::shared_ptr<msg::BaseMessage>> messages_;
StreamMessageReceiver* messageReceiver_;
};
| 2,944
|
C++
|
.h
| 68
| 39.794118
| 142
| 0.763222
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,029
|
stream_session_ws.hpp
|
badaix_snapcast/server/stream_session_ws.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "stream_session.hpp"
// 3rd party headers
#include <boost/asio/strand.hpp>
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wunknown-warning-option"
#pragma GCC diagnostic ignored "-Wdeprecated-copy-with-user-provided-copy"
#pragma GCC diagnostic ignored "-Wdeprecated-copy"
#endif
#include <boost/beast/core.hpp>
#pragma GCC diagnostic pop
#include <boost/beast/websocket.hpp>
// standard headers
namespace beast = boost::beast; // from <boost/beast.hpp>
// namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
/// Endpoint for a connected control client.
/**
* Endpoint for a connected control client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the ControlMessageReceiver callback
*/
class StreamSessionWebsocket : public StreamSession
{
public:
/// ctor. Received message from the client are passed to StreamMessageReceiver
StreamSessionWebsocket(StreamMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket);
~StreamSessionWebsocket() override;
void start() override;
void stop() override;
std::string getIP() override;
protected:
// Websocket methods
void sendAsync(const shared_const_buffer& buffer, const WriteHandler& handler) override;
void on_read_ws(beast::error_code ec, std::size_t bytes_transferred);
void do_read_ws();
websocket::stream<beast::tcp_stream> ws_;
protected:
beast::flat_buffer buffer_;
};
| 2,367
|
C++
|
.h
| 56
| 39.214286
| 107
| 0.756969
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,030
|
stream_session_tcp.hpp
|
badaix_snapcast/server/stream_session_tcp.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "stream_session.hpp"
// 3rd party headers
#include <boost/asio/ip/tcp.hpp>
// standard headers
using boost::asio::ip::tcp;
/// Endpoint for a connected client.
/**
* Endpoint for a connected client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the StreamMessageReceiver callback
*/
class StreamSessionTcp : public StreamSession
{
public:
/// ctor. Received message from the client are passed to StreamMessageReceiver
StreamSessionTcp(StreamMessageReceiver* receiver, tcp::socket&& socket);
~StreamSessionTcp() override;
void start() override;
void stop() override;
std::string getIP() override;
protected:
void read_next();
void sendAsync(const shared_const_buffer& buffer, const WriteHandler& handler) override;
private:
tcp::socket socket_;
};
| 1,638
|
C++
|
.h
| 42
| 35.595238
| 92
| 0.753001
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,031
|
server.hpp
|
badaix_snapcast/server/server.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/message.hpp"
#include "common/queue.hpp"
#include "control_server.hpp"
#include "jsonrpcpp.hpp"
#include "server_settings.hpp"
#include "stream_server.hpp"
#include "stream_session.hpp"
#include "streamreader/stream_manager.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <memory>
using namespace streamreader;
using boost::asio::ip::tcp;
using acceptor_ptr = std::unique_ptr<tcp::acceptor>;
using session_ptr = std::shared_ptr<StreamSession>;
/**
* Receives and routes PcmStreams
* Processes ControlSession messages
*/
class Server : public StreamMessageReceiver, public ControlMessageReceiver, public PcmStream::Listener
{
public:
// TODO: revise handler names
using OnResponse = std::function<void(jsonrpcpp::entity_ptr response, jsonrpcpp::notification_ptr notification)>;
Server(boost::asio::io_context& io_context, const ServerSettings& serverSettings);
virtual ~Server();
void start();
void stop();
private:
/// Implementation of StreamMessageReceiver
void onMessageReceived(StreamSession* streamSession, const msg::BaseMessage& baseMessage, char* buffer) override;
void onDisconnect(StreamSession* streamSession) override;
/// Implementation of ControllMessageReceiver
void onMessageReceived(std::shared_ptr<ControlSession> controlSession, const std::string& message, const ResponseHander& response_handler) override;
void onNewSession(std::shared_ptr<ControlSession> session) override
{
std::ignore = session;
};
void onNewSession(std::shared_ptr<StreamSession> session) override;
/// Implementation of PcmStream::Listener
void onPropertiesChanged(const PcmStream* pcmStream, const Properties& properties) override;
void onStateChanged(const PcmStream* pcmStream, ReaderState state) override;
void onChunkRead(const PcmStream* pcmStream, const msg::PcmChunk& chunk) override;
void onChunkEncoded(const PcmStream* pcmStream, std::shared_ptr<msg::PcmChunk> chunk, double duration) override;
void onResync(const PcmStream* pcmStream, double ms) override;
private:
void processRequest(const jsonrpcpp::request_ptr request, const OnResponse& on_response) const;
/// Save the server state deferred to prevent blocking and lower disk io
/// @param deferred the delay after the last call to saveConfig
void saveConfig(const std::chrono::milliseconds& deferred = std::chrono::seconds(2));
boost::asio::io_context& io_context_;
boost::asio::steady_timer config_timer_;
ServerSettings settings_;
Queue<std::shared_ptr<msg::BaseMessage>> messages_;
std::unique_ptr<ControlServer> controlServer_;
std::unique_ptr<StreamServer> streamServer_;
std::unique_ptr<StreamManager> streamManager_;
};
| 3,623
|
C++
|
.h
| 76
| 43.934211
| 152
| 0.766307
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,032
|
control_server.hpp
|
badaix_snapcast/server/control_server.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "control_session.hpp"
#include "server_settings.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/ip/tcp.hpp>
// standard headers
#include <memory>
#include <mutex>
#include <vector>
using boost::asio::ip::tcp;
using acceptor_ptr = std::unique_ptr<tcp::acceptor>;
/// Telnet like remote control
/**
* Telnet like remote control
*/
class ControlServer : public ControlMessageReceiver
{
public:
ControlServer(boost::asio::io_context& io_context, const ServerSettings::Tcp& tcp_settings, const ServerSettings::Http& http_settings,
ControlMessageReceiver* controlMessageReceiver = nullptr);
virtual ~ControlServer();
void start();
void stop();
/// Send a message to all connected clients
void send(const std::string& message, const ControlSession* excludeSession = nullptr);
private:
void startAccept();
template <typename SessionType, typename... Args>
void handleAccept(tcp::socket socket, Args&&... args);
void cleanup();
/// Implementation of ControlMessageReceiver
void onMessageReceived(std::shared_ptr<ControlSession> session, const std::string& message, const ResponseHander& response_handler) override;
void onNewSession(std::shared_ptr<ControlSession> session) override;
void onNewSession(std::shared_ptr<StreamSession> session) override;
mutable std::recursive_mutex session_mutex_;
std::vector<std::weak_ptr<ControlSession>> sessions_;
std::vector<acceptor_ptr> acceptor_tcp_;
std::vector<acceptor_ptr> acceptor_http_;
boost::asio::io_context& io_context_;
ServerSettings::Tcp tcp_settings_;
ServerSettings::Http http_settings_;
ControlMessageReceiver* controlMessageReceiver_;
};
| 2,525
|
C++
|
.h
| 59
| 38.847458
| 145
| 0.748366
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,033
|
image_cache.hpp
|
badaix_snapcast/server/image_cache.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// 3rd party headers
#include <boost/algorithm/hex.hpp>
#include <boost/uuid/detail/md5.hpp>
// standard headers
#include <map>
#include <mutex>
#include <optional>
#include <string>
class ImageCache
{
public:
ImageCache() = default;
virtual ~ImageCache() = default;
std::string setImage(const std::string& key, std::string image, const std::string& extension)
{
if (image.empty())
{
clear(key);
return "";
}
using boost::uuids::detail::md5;
md5 hash;
md5::digest_type digest;
hash.process_bytes(key.data(), key.size());
hash.process_bytes(image.data(), image.size());
hash.get_digest(digest);
std::string filename;
const auto intDigest = reinterpret_cast<const int*>(&digest);
boost::algorithm::hex_lower(intDigest, intDigest + (sizeof(md5::digest_type) / sizeof(int)), std::back_inserter(filename));
auto ext = extension;
if (ext.find('.') == 0)
ext = ext.substr(1);
filename += "." + ext;
std::lock_guard<std::mutex> lock(mutex_);
key_to_url_[key] = filename;
url_to_data_[filename] = std::move(image);
return filename;
};
void clear(const std::string& key)
{
std::lock_guard<std::mutex> lock(mutex_);
auto iter = key_to_url_.find(key);
if (iter != key_to_url_.end())
{
auto url = *iter;
auto url_iter = url_to_data_.find(url.second);
if (url_iter != url_to_data_.end())
url_to_data_.erase(url_iter);
key_to_url_.erase(iter);
}
}
std::optional<std::string> getImage(const std::string& url)
{
std::lock_guard<std::mutex> lock(mutex_);
auto iter = url_to_data_.find(url);
if (iter == url_to_data_.end())
return std::nullopt;
else
return iter->second;
}
private:
std::map<std::string, std::string> key_to_url_;
std::map<std::string, std::string> url_to_data_;
std::mutex mutex_;
};
| 2,850
|
C++
|
.h
| 80
| 28.8
| 131
| 0.619739
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,034
|
server_settings.hpp
|
badaix_snapcast/server/server_settings.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "image_cache.hpp"
// standard headers
#include <string>
#include <vector>
struct ServerSettings
{
struct Server
{
int threads{-1};
std::string pid_file{"/var/run/snapserver/pid"};
std::string user{"snapserver"};
std::string group{""};
std::string data_dir{""};
};
struct Http
{
bool enabled{true};
size_t port{1780};
std::vector<std::string> bind_to_address{{"0.0.0.0"}};
std::string doc_root{""};
std::string host{"<hostname>"};
inline static ImageCache image_cache;
};
struct Tcp
{
bool enabled{true};
size_t port{1705};
std::vector<std::string> bind_to_address{{"0.0.0.0"}};
};
struct Stream
{
size_t port{1704};
std::vector<std::string> sources;
std::string codec{"flac"};
int32_t bufferMs{1000};
std::string sampleFormat{"48000:16:2"};
size_t streamChunkMs{20};
bool sendAudioToMutedClients{false};
std::vector<std::string> bind_to_address{{"0.0.0.0"}};
};
struct StreamingClient
{
uint16_t initialVolume{100};
};
struct Logging
{
std::string sink{""};
std::string filter{"*:info"};
};
Server server;
Http http;
Tcp tcp;
Stream stream;
StreamingClient streamingclient;
Logging logging;
};
| 2,181
|
C++
|
.h
| 72
| 24.305556
| 73
| 0.640401
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,035
|
control_session_tcp.hpp
|
badaix_snapcast/server/control_session_tcp.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "control_session.hpp"
// 3rd party headers
#include <boost/asio/any_io_executor.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/strand.hpp>
#include <boost/asio/streambuf.hpp>
// standard headers
#include <deque>
using boost::asio::ip::tcp;
/// Endpoint for a connected control client.
/**
* Endpoint for a connected control client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the ControlMessageReceiver callback
*/
class ControlSessionTcp : public ControlSession
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSessionTcp(ControlMessageReceiver* receiver, tcp::socket&& socket);
~ControlSessionTcp() override;
void start() override;
void stop() override;
/// Sends a message to the client (asynchronous)
void sendAsync(const std::string& message) override;
protected:
void do_read();
void send_next();
tcp::socket socket_;
boost::asio::streambuf streambuf_;
boost::asio::strand<boost::asio::any_io_executor> strand_;
std::deque<std::string> messages_;
};
| 1,925
|
C++
|
.h
| 49
| 35.897959
| 86
| 0.747182
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,036
|
control_session.hpp
|
badaix_snapcast/server/control_session.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
// 3rd party headers
// standard headers
#include <functional>
#include <memory>
#include <string>
class ControlSession;
class StreamSession;
/// Interface: callback for a received message.
class ControlMessageReceiver
{
public:
using ResponseHander = std::function<void(const std::string& response)>;
// TODO: rename, error handling
virtual void onMessageReceived(std::shared_ptr<ControlSession> session, const std::string& message, const ResponseHander& response_handler) = 0;
virtual void onNewSession(std::shared_ptr<ControlSession> session) = 0;
virtual void onNewSession(std::shared_ptr<StreamSession> session) = 0;
};
/// Endpoint for a connected control client.
/**
* Endpoint for a connected control client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the ControlMessageReceiver callback
*/
class ControlSession : public std::enable_shared_from_this<ControlSession>
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSession(ControlMessageReceiver* receiver) : message_receiver_(receiver)
{
}
virtual ~ControlSession() = default;
virtual void start() = 0;
virtual void stop() = 0;
/// Sends a message to the client (asynchronous)
virtual void sendAsync(const std::string& message) = 0;
protected:
ControlMessageReceiver* message_receiver_;
};
| 2,207
|
C++
|
.h
| 54
| 37.537037
| 148
| 0.756896
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,037
|
config.hpp
|
badaix_snapcast/server/config.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/json.hpp"
#include "common/utils.hpp"
#include "common/utils/string_utils.hpp"
// standard headers
#include <memory>
#include <mutex>
#include <string>
#include <sys/time.h>
#include <vector>
namespace strutils = utils::string;
using json = nlohmann::json;
struct ClientInfo;
struct Group;
using ClientInfoPtr = std::shared_ptr<ClientInfo>;
using GroupPtr = std::shared_ptr<Group>;
template <typename T>
T jGet(const json& j, const std::string& what, const T& def)
{
try
{
if (!j.count(what))
return def;
return j[what].get<T>();
}
catch (...)
{
return def;
}
}
struct Volume
{
Volume(uint16_t _percent = 100, bool _muted = false) : percent(_percent), muted(_muted)
{
}
void fromJson(const json& j)
{
percent = jGet<uint16_t>(j, "percent", percent);
muted = jGet<bool>(j, "muted", muted);
}
json toJson()
{
json j;
j["percent"] = percent;
j["muted"] = muted;
return j;
}
uint16_t percent;
bool muted;
};
struct Host
{
Host() : name(""), mac(""), os(""), arch(""), ip("")
{
}
void update()
{
name = getHostName();
os = getOS();
arch = getArch();
}
void fromJson(const json& j)
{
name = strutils::trim_copy(jGet<std::string>(j, "name", ""));
mac = strutils::trim_copy(jGet<std::string>(j, "mac", ""));
os = strutils::trim_copy(jGet<std::string>(j, "os", ""));
arch = strutils::trim_copy(jGet<std::string>(j, "arch", ""));
ip = strutils::trim_copy(jGet<std::string>(j, "ip", ""));
}
json toJson()
{
json j;
j["name"] = name;
j["mac"] = mac;
j["os"] = os;
j["arch"] = arch;
j["ip"] = ip;
return j;
}
std::string name;
std::string mac;
std::string os;
std::string arch;
std::string ip;
};
struct ClientConfig
{
ClientConfig() : name(""), volume(100), latency(0), instance(1)
{
}
void fromJson(const json& j)
{
name = strutils::trim_copy(jGet<std::string>(j, "name", ""));
volume.fromJson(j["volume"]);
latency = jGet<int32_t>(j, "latency", 0);
instance = jGet<size_t>(j, "instance", 1);
}
json toJson()
{
json j;
j["name"] = strutils::trim_copy(name);
j["volume"] = volume.toJson();
j["latency"] = latency;
j["instance"] = instance;
return j;
}
std::string name;
Volume volume;
int32_t latency;
size_t instance;
};
struct Snapcast
{
Snapcast(const std::string& _name = "", const std::string& _version = "") : name(_name), version(_version), protocolVersion(1)
{
}
virtual ~Snapcast() = default;
virtual void fromJson(const json& j)
{
name = strutils::trim_copy(jGet<std::string>(j, "name", ""));
version = strutils::trim_copy(jGet<std::string>(j, "version", ""));
protocolVersion = jGet<int>(j, "protocolVersion", 1);
}
virtual json toJson()
{
json j;
j["name"] = strutils::trim_copy(name);
j["version"] = strutils::trim_copy(version);
j["protocolVersion"] = protocolVersion;
return j;
}
std::string name;
std::string version;
int protocolVersion;
};
struct Snapclient : public Snapcast
{
Snapclient(const std::string& _name = "", const std::string& _version = "") : Snapcast(_name, _version)
{
}
};
struct Snapserver : public Snapcast
{
Snapserver(const std::string& _name = "", const std::string& _version = "") : Snapcast(_name, _version), controlProtocolVersion(1)
{
}
void fromJson(const json& j) override
{
Snapcast::fromJson(j);
controlProtocolVersion = jGet<int>(j, "controlProtocolVersion", 1);
}
json toJson() override
{
json j = Snapcast::toJson();
j["controlProtocolVersion"] = controlProtocolVersion;
return j;
}
int controlProtocolVersion;
};
struct ClientInfo
{
ClientInfo(const std::string& _clientId = "") : id(_clientId), connected(false)
{
lastSeen.tv_sec = 0;
lastSeen.tv_usec = 0;
}
void fromJson(const json& j)
{
host.fromJson(j["host"]);
id = jGet<std::string>(j, "id", host.mac);
snapclient.fromJson(j["snapclient"]);
config.fromJson(j["config"]);
lastSeen.tv_sec = jGet<int32_t>(j["lastSeen"], "sec", 0);
lastSeen.tv_usec = jGet<int32_t>(j["lastSeen"], "usec", 0);
connected = jGet<bool>(j, "connected", true);
}
json toJson()
{
json j;
j["id"] = id;
j["host"] = host.toJson();
j["snapclient"] = snapclient.toJson();
j["config"] = config.toJson();
j["lastSeen"]["sec"] = lastSeen.tv_sec;
j["lastSeen"]["usec"] = lastSeen.tv_usec;
j["connected"] = connected;
return j;
}
std::string id;
Host host;
Snapclient snapclient;
ClientConfig config;
timeval lastSeen;
bool connected;
};
struct Group
{
Group(const ClientInfoPtr client = nullptr) : muted(false)
{
if (client)
id = client->id;
id = generateUUID();
}
void fromJson(const json& j)
{
name = strutils::trim_copy(jGet<std::string>(j, "name", ""));
id = strutils::trim_copy(jGet<std::string>(j, "id", ""));
streamId = strutils::trim_copy(jGet<std::string>(j, "stream_id", ""));
muted = jGet<bool>(j, "muted", false);
clients.clear();
if (j.count("clients"))
{
for (const auto& jClient : j["clients"])
{
ClientInfoPtr client = std::make_shared<ClientInfo>();
client->fromJson(jClient);
client->connected = false;
addClient(client);
}
}
}
json toJson()
{
json j;
j["name"] = strutils::trim_copy(name);
j["id"] = strutils::trim_copy(id);
j["stream_id"] = strutils::trim_copy(streamId);
j["muted"] = muted;
json jClients = json::array();
for (const auto& client : clients)
jClients.push_back(client->toJson());
j["clients"] = jClients;
return j;
}
ClientInfoPtr removeClient(const std::string& clientId)
{
for (auto iter = clients.begin(); iter != clients.end(); ++iter)
{
if ((*iter)->id == clientId)
{
clients.erase(iter);
return (*iter);
}
}
return nullptr;
}
ClientInfoPtr removeClient(ClientInfoPtr client)
{
if (!client)
return nullptr;
return removeClient(client->id);
}
ClientInfoPtr getClient(const std::string& clientId)
{
for (const auto& client : clients)
{
if (client->id == clientId)
return client;
}
return nullptr;
}
void addClient(ClientInfoPtr client)
{
if (!client)
return;
for (const auto& c : clients)
{
if (c->id == client->id)
return;
}
clients.push_back(client);
/* sort(clients.begin(), clients.end(),
[](const ClientInfoPtr a, const ClientInfoPtr b) -> bool
{
return a.name > b.name;
});
*/
}
bool empty() const
{
return clients.empty();
}
std::string name;
std::string id;
std::string streamId;
bool muted;
std::vector<ClientInfoPtr> clients;
};
class Config
{
public:
static Config& instance()
{
static Config instance_;
return instance_;
}
ClientInfoPtr getClientInfo(const std::string& clientId) const;
GroupPtr addClientInfo(const std::string& clientId);
GroupPtr addClientInfo(ClientInfoPtr client);
void remove(ClientInfoPtr client);
void remove(GroupPtr group, bool force = false);
// GroupPtr removeFromGroup(const std::string& groupId, const std::string& clientId);
// GroupPtr setGroupForClient(const std::string& groupId, const std::string& clientId);
GroupPtr getGroupFromClient(const std::string& clientId);
GroupPtr getGroupFromClient(ClientInfoPtr client);
GroupPtr getGroup(const std::string& groupId) const;
json getGroups() const;
json getServerStatus(const json& streams) const;
void save();
void init(const std::string& root_directory = "", const std::string& user = "", const std::string& group = "");
std::vector<GroupPtr> groups;
std::mutex& getMutex();
private:
Config() = default;
~Config();
mutable std::recursive_mutex mutex_;
std::mutex client_mutex_;
std::string filename_;
};
| 9,774
|
C++
|
.h
| 334
| 22.461078
| 134
| 0.579329
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,039
|
control_session_http.hpp
|
badaix_snapcast/server/control_session_http.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "control_session.hpp"
#include "server_settings.hpp"
// 3rd party headers
#include <boost/beast/core.hpp>
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#include <boost/beast/websocket.hpp>
#pragma GCC diagnostic pop
#else
#include <boost/beast/websocket.hpp>
#endif
// standard headers
#include <deque>
using boost::asio::ip::tcp;
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
/// Endpoint for a connected control client.
/**
* Endpoint for a connected control client.
* Messages are sent to the client with the "send" method.
* Received messages from the client are passed to the ControlMessageReceiver callback
*/
class ControlSessionHttp : public ControlSession
{
public:
/// ctor. Received message from the client are passed to ControlMessageReceiver
ControlSessionHttp(ControlMessageReceiver* receiver, tcp::socket&& socket, const ServerSettings::Http& settings);
~ControlSessionHttp() override;
void start() override;
void stop() override;
/// Sends a message to the client (asynchronous)
void sendAsync(const std::string& message) override;
protected:
// HTTP methods
void on_read(beast::error_code ec, std::size_t bytes_transferred);
void on_write(beast::error_code ec, std::size_t bytes, bool close);
template <class Body, class Allocator, class Send>
void handle_request(http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send);
http::request<http::string_body> req_;
protected:
tcp::socket socket_;
beast::flat_buffer buffer_;
ServerSettings::Http settings_;
std::deque<std::string> messages_;
};
| 2,545
|
C++
|
.h
| 62
| 37.822581
| 117
| 0.74645
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,040
|
librespot_stream.hpp
|
badaix_snapcast/server/streamreader/librespot_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "process_stream.hpp"
namespace streamreader
{
/// Starts librespot and reads PCM data from stdout
/**
* Starts librespot, reads PCM data from stdout, and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
* usage:
* snapserver -s "spotify:///librespot?name=Spotify&username=<my username>&password=<my password>[&devicename=Snapcast][&bitrate=320][&volume=<volume in
* percent>][&cache=<cache dir>]"
*/
class LibrespotStream : public ProcessStream
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
LibrespotStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
protected:
bool killall_;
void onStderrMsg(const std::string& line) override;
void initExeAndPath(const std::string& filename) override;
};
} // namespace streamreader
| 1,718
|
C++
|
.h
| 39
| 40.846154
| 154
| 0.755995
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,041
|
pipe_stream.hpp
|
badaix_snapcast/server/streamreader/pipe_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "asio_stream.hpp"
namespace streamreader
{
using boost::asio::posix::stream_descriptor;
/// Reads and decodes PCM data from a named pipe
/**
* Reads PCM from a named pipe and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class PipeStream : public AsioStream<stream_descriptor>
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
PipeStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
protected:
void connect() override;
};
} // namespace streamreader
| 1,438
|
C++
|
.h
| 35
| 37.914286
| 140
| 0.758447
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,042
|
stream_manager.hpp
|
badaix_snapcast/server/streamreader/stream_manager.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "pcm_stream.hpp"
#include "server_settings.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
// standard headers
#include <memory>
#include <string>
#include <vector>
namespace streamreader
{
using PcmStreamPtr = std::shared_ptr<PcmStream>;
class StreamManager
{
public:
StreamManager(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& settings);
PcmStreamPtr addStream(const std::string& uri);
PcmStreamPtr addStream(StreamUri& streamUri);
void removeStream(const std::string& name);
void start();
void stop();
const std::vector<PcmStreamPtr>& getStreams();
const PcmStreamPtr getDefaultStream();
const PcmStreamPtr getStream(const std::string& id);
json toJson() const;
private:
std::vector<PcmStreamPtr> streams_;
PcmStream::Listener* pcmListener_;
ServerSettings settings_;
boost::asio::io_context& io_context_;
};
} // namespace streamreader
| 1,741
|
C++
|
.h
| 47
| 33.531915
| 114
| 0.750595
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,043
|
meta_stream.hpp
|
badaix_snapcast/server/streamreader/meta_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/resampler.hpp"
#include "pcm_stream.hpp"
// standard headers
#include <memory>
namespace streamreader
{
// Mixing digital audio:
// https://www.vttoth.com/CMS/technical-notes/?view=article&id=68
/// Reads and decodes PCM data
/**
* Reads PCM and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class MetaStream : public PcmStream, public PcmStream::Listener
{
public:
/// ctor. Encoded PCM data is passed to the PcmStream::Listener
MetaStream(PcmStream::Listener* pcmListener, const std::vector<std::shared_ptr<PcmStream>>& streams, boost::asio::io_context& ioc,
const ServerSettings& server_settings, const StreamUri& uri);
virtual ~MetaStream();
void start() override;
void stop() override;
// Setter for properties
void setShuffle(bool shuffle, ResultHandler handler) override;
void setLoopStatus(LoopStatus status, ResultHandler handler) override;
void setVolume(uint16_t volume, ResultHandler handler) override;
void setMute(bool mute, ResultHandler handler) override;
void setRate(float rate, ResultHandler handler) override;
// Control commands
void setPosition(std::chrono::milliseconds position, ResultHandler handler) override;
void seek(std::chrono::milliseconds offset, ResultHandler handler) override;
void next(ResultHandler handler) override;
void previous(ResultHandler handler) override;
void pause(ResultHandler handler) override;
void playPause(ResultHandler handler) override;
void stop(ResultHandler handler) override;
void play(ResultHandler handler) override;
protected:
/// Implementation of PcmStream::Listener
void onPropertiesChanged(const PcmStream* pcmStream, const Properties& properties) override;
void onStateChanged(const PcmStream* pcmStream, ReaderState state) override;
void onChunkRead(const PcmStream* pcmStream, const msg::PcmChunk& chunk) override;
void onChunkEncoded(const PcmStream* pcmStream, std::shared_ptr<msg::PcmChunk> chunk, double duration) override;
void onResync(const PcmStream* pcmStream, double ms) override;
protected:
std::vector<std::shared_ptr<PcmStream>> streams_;
std::recursive_mutex active_mutex_;
std::shared_ptr<PcmStream> active_stream_;
std::unique_ptr<Resampler> resampler_;
bool first_read_;
std::chrono::time_point<std::chrono::steady_clock> next_tick_;
};
} // namespace streamreader
| 3,287
|
C++
|
.h
| 70
| 42.942857
| 134
| 0.7607
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,045
|
pcm_stream.hpp
|
badaix_snapcast/server/streamreader/pcm_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/error_code.hpp"
#include "common/json.hpp"
#include "common/message/codec_header.hpp"
#include "common/sample_format.hpp"
#include "encoder/encoder.hpp"
#include "jsonrpcpp.hpp"
#include "properties.hpp"
#include "server_settings.hpp"
#include "stream_control.hpp"
#include "stream_uri.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/read_until.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <atomic>
#include <mutex>
#include <string>
#include <vector>
using json = nlohmann::json;
namespace streamreader
{
class PcmStream;
enum class ReaderState
{
kUnknown = 0,
kIdle = 1,
kPlaying = 2,
kDisabled = 3
};
static std::string to_string(const ReaderState& reader_state)
{
switch (reader_state)
{
case ReaderState::kIdle:
return "idle";
case ReaderState::kPlaying:
return "playing";
case ReaderState::kDisabled:
return "disabled";
case ReaderState::kUnknown:
default:
return "unknown";
}
}
static std::ostream& operator<<(std::ostream& os, const ReaderState& reader_state)
{
os << to_string(reader_state);
return os;
}
static constexpr auto kUriCodec = "codec";
static constexpr auto kUriName = "name";
static constexpr auto kUriSampleFormat = "sampleformat";
static constexpr auto kUriChunkMs = "chunk_ms";
static constexpr auto kControlScript = "controlscript";
static constexpr auto kControlScriptParams = "controlscriptparams";
/// Reads and decodes PCM data
/**
* Reads PCM and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class PcmStream
{
public:
/// Callback interface for users of PcmStream
/**
* Users of PcmStream should implement this to get the data
*/
class Listener
{
public:
virtual void onPropertiesChanged(const PcmStream* pcmStream, const Properties& properties) = 0;
virtual void onStateChanged(const PcmStream* pcmStream, ReaderState state) = 0;
virtual void onChunkRead(const PcmStream* pcmStream, const msg::PcmChunk& chunk) = 0;
virtual void onChunkEncoded(const PcmStream* pcmStream, std::shared_ptr<msg::PcmChunk> chunk, double duration) = 0;
virtual void onResync(const PcmStream* pcmStream, double ms) = 0;
};
using ResultHandler = std::function<void(const snapcast::ErrorCode& ec)>;
/// ctor. Encoded PCM data is passed to the PcmStream::Listener
PcmStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
virtual ~PcmStream();
virtual void start();
virtual void stop();
virtual std::shared_ptr<msg::CodecHeader> getHeader();
virtual const StreamUri& getUri() const;
virtual const std::string& getName() const;
virtual const std::string& getId() const;
virtual const SampleFormat& getSampleFormat() const;
virtual std::string getCodec() const;
const Properties& getProperties() const;
// Setter for properties
virtual void setShuffle(bool shuffle, ResultHandler handler);
virtual void setLoopStatus(LoopStatus status, ResultHandler handler);
virtual void setVolume(uint16_t volume, ResultHandler handler);
virtual void setMute(bool mute, ResultHandler handler);
virtual void setRate(float rate, ResultHandler handler);
// Control commands
virtual void setPosition(std::chrono::milliseconds position, ResultHandler handler);
virtual void seek(std::chrono::milliseconds offset, ResultHandler handler);
virtual void next(ResultHandler handler);
virtual void previous(ResultHandler handler);
virtual void pause(ResultHandler handler);
virtual void playPause(ResultHandler handler);
virtual void stop(ResultHandler handler);
virtual void play(ResultHandler handler);
virtual ReaderState getState() const;
virtual json toJson() const;
void addListener(PcmStream::Listener* pcmListener);
protected:
std::atomic<bool> active_;
/// check if the volume of the \p chunk is below the silence threshold
bool isSilent(const msg::PcmChunk& chunk) const;
void setState(ReaderState newState);
void chunkRead(const msg::PcmChunk& chunk);
void resync(const std::chrono::nanoseconds& duration);
void chunkEncoded(const encoder::Encoder& encoder, std::shared_ptr<msg::PcmChunk> chunk, double duration);
void setProperties(const Properties& properties);
void pollProperties();
// script callbacks
/// Request received from control script
void onControlRequest(const jsonrpcpp::Request& request);
/// Notification received from control script
void onControlNotification(const jsonrpcpp::Notification& notification);
/// Log message received from control script via stderr
void onControlLog(std::string line);
/// Send request to stream control script
void sendRequest(const std::string& method, const jsonrpcpp::Parameter& params, ResultHandler handler);
boost::asio::strand<boost::asio::any_io_executor> strand_;
std::chrono::time_point<std::chrono::steady_clock> tvEncodedChunk_;
std::vector<PcmStream::Listener*> pcmListeners_;
StreamUri uri_;
SampleFormat sampleFormat_;
size_t chunk_ms_;
std::unique_ptr<encoder::Encoder> encoder_;
std::string name_;
std::atomic<ReaderState> state_;
Properties properties_;
ServerSettings server_settings_;
std::unique_ptr<StreamControl> stream_ctrl_;
std::atomic<int> req_id_;
boost::asio::steady_timer property_timer_;
mutable std::recursive_mutex mutex_;
/// If a chunk's max amplitude is below the threshold, it is considered silent
int32_t silence_threshold_ = 0;
/// Current chunk
std::unique_ptr<msg::PcmChunk> chunk_;
/// Silent chunk (all 0), for fast silence detection (memcmp)
std::vector<char> silent_chunk_;
};
} // namespace streamreader
| 6,829
|
C++
|
.h
| 167
| 36.461078
| 139
| 0.73561
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,046
|
jack_stream.hpp
|
badaix_snapcast/server/streamreader/jack_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
Copyright (C) 2024 Marcus Weseloh <marcus@weseloh.cc>
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "pcm_stream.hpp"
#include <server/server_settings.hpp>
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/steady_timer.hpp>
#include <jack/jack.h>
namespace streamreader
{
/// Reads and decodes PCM data from a Jack server
/**
* Reads PCM from a Jack server and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class JackStream : public PcmStream
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
JackStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
void start() override;
void stop() override;
protected:
bool openJackConnection();
void closeJackConnection();
bool createJackPorts();
void tryConnect();
int readJackBuffers(jack_nframes_t nframes);
void onJackPortRegistration(jack_port_id_t port_id, int registered);
void onJackShutdown();
void autoConnectPorts();
std::string serverName_;
jack_client_t* client_;
std::vector<jack_port_t*> ports_;
SampleFormat jackSampleFormat_;
std::string autoConnectRegex_;
bool doAutoConnect_ = false;
int autoConnectSkip_;
std::function<void(char*, jack_default_audio_sample_t*, unsigned long, unsigned long)> interleave_func_;
boost::asio::steady_timer read_timer_;
std::chrono::microseconds silence_;
/// send silent chunks to clients
bool send_silence_;
/// silence duration before switching the stream to idle
std::chrono::milliseconds idle_threshold_;
/// first read after idle => reset chunk timestamp
bool first_;
};
} // namespace streamreader
| 2,608
|
C++
|
.h
| 66
| 35.636364
| 140
| 0.740476
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,047
|
stream_control.hpp
|
badaix_snapcast/server/streamreader/stream_control.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "jsonrpcpp.hpp"
#include "server_settings.hpp"
// 3rd party headers
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpragmas"
#pragma GCC diagnostic ignored "-Wunused-result"
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wmissing-braces"
#pragma GCC diagnostic ignored "-Wnarrowing"
#pragma GCC diagnostic ignored "-Wc++11-narrowing"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if !defined(__clang__)
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
#endif
#include <boost/process.hpp>
#pragma GCC diagnostic pop
#include <boost/asio/any_io_executor.hpp>
// standard headers
#include <map>
#include <string>
namespace bp = boost::process;
using json = nlohmann::json;
namespace streamreader
{
class StreamControl
{
public:
using OnRequest = std::function<void(const jsonrpcpp::Request& response)>;
using OnNotification = std::function<void(const jsonrpcpp::Notification& response)>;
using OnResponse = std::function<void(const jsonrpcpp::Response& response)>;
using OnLog = std::function<void(std::string message)>;
StreamControl(const boost::asio::any_io_executor& executor);
virtual ~StreamControl() = default;
void start(const std::string& stream_id, const ServerSettings& server_setttings, const OnNotification& notification_handler,
const OnRequest& request_handler, const OnLog& log_handler);
void command(const jsonrpcpp::Request& request, const OnResponse& response_handler);
protected:
virtual void doCommand(const jsonrpcpp::Request& request) = 0;
virtual void doStart(const std::string& stream_id, const ServerSettings& server_setttings) = 0;
void onReceive(const std::string& json);
void onLog(std::string message);
boost::asio::any_io_executor executor_;
private:
OnRequest request_handler_;
OnNotification notification_handler_;
OnLog log_handler_;
std::map<jsonrpcpp::Id, OnResponse> request_callbacks_;
};
class ScriptStreamControl : public StreamControl
{
public:
ScriptStreamControl(const boost::asio::any_io_executor& executor, const std::string& script, const std::string& params);
virtual ~ScriptStreamControl() = default;
protected:
/// Send a message to stdin of the process
void doCommand(const jsonrpcpp::Request& request) override;
void doStart(const std::string& stream_id, const ServerSettings& server_setttings) override;
void stderrReadLine();
void stdoutReadLine();
bp::child process_;
bp::pipe pipe_stdout_;
bp::pipe pipe_stderr_;
std::unique_ptr<boost::asio::posix::stream_descriptor> stream_stdout_;
std::unique_ptr<boost::asio::posix::stream_descriptor> stream_stderr_;
boost::asio::streambuf streambuf_stdout_;
boost::asio::streambuf streambuf_stderr_;
std::string script_;
std::string params_;
bp::opstream in_;
};
} // namespace streamreader
| 3,711
|
C++
|
.h
| 87
| 39.022989
| 128
| 0.754035
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,048
|
file_stream.hpp
|
badaix_snapcast/server/streamreader/file_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "asio_stream.hpp"
namespace streamreader
{
using boost::asio::posix::stream_descriptor;
/// Reads and decodes PCM data from a file
/**
* Reads PCM from a file and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class FileStream : public AsioStream<stream_descriptor>
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
FileStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
protected:
void connect() override;
};
} // namespace streamreader
| 1,425
|
C++
|
.h
| 35
| 37.571429
| 140
| 0.757796
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,049
|
airplay_stream.hpp
|
badaix_snapcast/server/streamreader/airplay_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "process_stream.hpp"
// 3rd party headers
// Expat is used in metadata parsing from Shairport-sync.
// Without HAS_EXPAT defined no parsing will occur.
#ifdef HAS_EXPAT
#include <expat.h>
#endif
namespace streamreader
{
class TageEntry
{
public:
TageEntry() : isBase64(false), length(0)
{
}
std::string code;
std::string type;
std::string data;
bool isBase64;
int length;
};
/// Starts shairport-sync and reads PCM data from stdout
/**
* Starts librespot, reads PCM data from stdout, and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
* usage:
* snapserver -s "airplay:///shairport-sync?name=Airplay[&devicename=Snapcast][&port=5000]"
*/
class AirplayStream : public ProcessStream
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
AirplayStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
~AirplayStream() override;
protected:
#ifdef HAS_EXPAT
XML_Parser parser_;
std::unique_ptr<TageEntry> entry_;
std::string buf_;
/// set whenever metadata_ has changed
Metadata meta_;
bool metadata_dirty_;
#endif
void pipeReadLine();
#ifdef HAS_EXPAT
int parse(const std::string& line);
void createParser();
void push();
template <typename T>
void setMetaData(std::optional<T>& meta_value, const T& value);
#endif
void setParamsAndPipePathFromPort();
void connect() override;
void disconnect() override;
void onStderrMsg(const std::string& line) override;
void initExeAndPath(const std::string& filename) override;
size_t port_;
std::string pipePath_;
std::string params_wo_port_;
std::unique_ptr<boost::asio::posix::stream_descriptor> pipe_fd_;
boost::asio::steady_timer pipe_open_timer_;
boost::asio::streambuf streambuf_pipe_;
#ifdef HAS_EXPAT
static void XMLCALL element_start(void* userdata, const char* element_name, const char** attr);
static void XMLCALL element_end(void* userdata, const char* element_name);
static void XMLCALL data(void* userdata, const char* content, int length);
#endif
private:
AixLog::Severity read_logseverity_{AixLog::Severity::info};
};
} // namespace streamreader
| 3,126
|
C++
|
.h
| 88
| 31.943182
| 143
| 0.734173
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,050
|
alsa_stream.hpp
|
badaix_snapcast/server/streamreader/alsa_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "pcm_stream.hpp"
// 3rd party headers
#include <alsa/asoundlib.h>
#include <boost/asio/io_context.hpp>
#include <boost/asio/steady_timer.hpp>
namespace streamreader
{
/// Reads and decodes PCM data from an alsa audio device device
/**
* Reads PCM from an alsa audio device device and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class AlsaStream : public PcmStream
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
AlsaStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
void start() override;
void stop() override;
protected:
void do_read();
void initAlsa();
void uninitAlsa();
snd_pcm_t* handle_;
bool first_;
std::chrono::time_point<std::chrono::steady_clock> nextTick_;
boost::asio::steady_timer read_timer_;
std::string device_;
std::chrono::microseconds silence_;
std::string lastException_;
/// send silent chunks to clients
bool send_silence_;
/// silence duration before switching the stream to idle
std::chrono::milliseconds idle_threshold_;
};
} // namespace streamreader
| 2,037
|
C++
|
.h
| 53
| 34.773585
| 140
| 0.738688
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,051
|
properties.hpp
|
badaix_snapcast/server/streamreader/properties.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/json.hpp"
#include "metadata.hpp"
// standard headers
#include <optional>
#include <string>
using json = nlohmann::json;
enum class PlaybackStatus
{
kPlaying = 0,
kPaused = 1,
kStopped = 2,
kUnknown = 3
};
enum class LoopStatus
{
kNone = 0,
kTrack = 1,
kPlaylist = 2,
kUnknown = 3
};
static std::string to_string(PlaybackStatus playback_status)
{
switch (playback_status)
{
case PlaybackStatus::kPlaying:
return "playing";
case PlaybackStatus::kPaused:
return "paused";
case PlaybackStatus::kStopped:
return "stopped";
default:
return "unknown";
}
}
static std::ostream& operator<<(std::ostream& os, PlaybackStatus playback_status)
{
os << to_string(playback_status);
return os;
}
static PlaybackStatus playback_status_from_string(std::string& status)
{
if (status == "playing")
return PlaybackStatus::kPlaying;
else if (status == "paused")
return PlaybackStatus::kPaused;
else if (status == "stopped")
return PlaybackStatus::kStopped;
else
return PlaybackStatus::kUnknown;
}
static std::istream& operator>>(std::istream& is, PlaybackStatus& playback_status)
{
std::string status;
playback_status = PlaybackStatus::kUnknown;
if (is >> status)
playback_status = playback_status_from_string(status);
else
playback_status = PlaybackStatus::kUnknown;
return is;
}
static std::string to_string(LoopStatus loop_status)
{
switch (loop_status)
{
case LoopStatus::kNone:
return "none";
case LoopStatus::kTrack:
return "track";
case LoopStatus::kPlaylist:
return "playlist";
default:
return "unknown";
}
}
static std::ostream& operator<<(std::ostream& os, LoopStatus loop_status)
{
os << to_string(loop_status);
return os;
}
static LoopStatus loop_status_from_string(std::string& status)
{
if (status == "none")
return LoopStatus::kNone;
else if (status == "track")
return LoopStatus::kTrack;
else if (status == "playlist")
return LoopStatus::kPlaylist;
else
return LoopStatus::kUnknown;
}
static std::istream& operator>>(std::istream& is, LoopStatus& loop_status)
{
std::string status;
if (is >> status)
loop_status = loop_status_from_string(status);
else
loop_status = LoopStatus::kUnknown;
return is;
}
class Properties
{
public:
Properties() = default;
Properties(const json& j);
/// Meta data
std::optional<Metadata> metadata;
/// https://www.musicpd.org/doc/html/protocol.html#tags
/// The current playback status
std::optional<PlaybackStatus> playback_status;
/// The current loop / repeat status
std::optional<LoopStatus> loop_status;
/// The current playback rate
std::optional<float> rate;
/// A value of false indicates that playback is progressing linearly through a playlist, while true means playback is progressing through a playlist in some
/// other order.
std::optional<bool> shuffle;
/// The volume level between 0-100
std::optional<int> volume;
/// The current mute state
std::optional<bool> mute;
/// The current track position in seconds
std::optional<float> position;
/// The minimum value which the Rate property can take. Clients should not attempt to set the Rate property below this value
std::optional<float> minimum_rate;
/// The maximum value which the Rate property can take. Clients should not attempt to set the Rate property above this value
std::optional<float> maximum_rate;
/// Whether the client can call the next method on this interface and expect the current track to change
bool can_go_next = false;
/// Whether the client can call the previous method on this interface and expect the current track to change
bool can_go_previous = false;
/// Whether playback can be started using "play" or "playPause"
bool can_play = false;
/// Whether playback can be paused using "pause" or "playPause"
bool can_pause = false;
/// Whether the client can control the playback position using "seek" and "setPosition". This may be different for different tracks
bool can_seek = false;
/// Whether the media player may be controlled over this interface
bool can_control = false;
json toJson() const;
void fromJson(const json& j);
bool operator==(const Properties& other) const;
};
| 5,365
|
C++
|
.h
| 158
| 28.949367
| 160
| 0.692114
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,052
|
watchdog.hpp
|
badaix_snapcast/server/streamreader/watchdog.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// 3rd party headers
#include <boost/asio/any_io_executor.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
namespace streamreader
{
class Watchdog;
class WatchdogListener
{
public:
virtual void onTimeout(const Watchdog& watchdog, std::chrono::milliseconds ms) = 0;
};
/// Watchdog
class Watchdog
{
public:
Watchdog(const boost::asio::any_io_executor& executor, WatchdogListener* listener = nullptr);
virtual ~Watchdog();
void start(const std::chrono::milliseconds& timeout);
void stop();
void trigger();
private:
boost::asio::steady_timer timer_;
WatchdogListener* listener_;
std::chrono::milliseconds timeout_ms_;
};
} // namespace streamreader
| 1,464
|
C++
|
.h
| 42
| 31.452381
| 97
| 0.748754
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,053
|
metadata.hpp
|
badaix_snapcast/server/streamreader/metadata.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/json.hpp"
// standard headers
#include <optional>
#include <string>
using json = nlohmann::json;
class Metadata
{
public:
struct ArtData
{
std::string data;
std::string extension;
bool operator==(const ArtData& other) const
{
return ((other.data == data) && (other.extension == extension));
}
bool operator!=(const ArtData& other) const
{
return !(other == *this);
}
};
Metadata() = default;
Metadata(const json& j);
/// https://www.musicpd.org/doc/html/protocol.html#tags
/// the duration of the song
std::optional<float> duration;
/// the artist name. Its meaning is not well-defined; see “composer” and “performer” for more specific tags.
std::optional<std::vector<std::string>> artist;
/// same as artist, but for sorting. This usually omits prefixes such as “The”.
std::optional<std::vector<std::string>> artist_sort;
/// the album name.
std::optional<std::string> album;
/// same as album, but for sorting.
std::optional<std::string> album_sort;
/// on multi-artist albums, this is the artist name which shall be used for the whole album. The exact meaning of this tag is not well-defined.
std::optional<std::vector<std::string>> album_artist;
/// same as albumartist, but for sorting.
std::optional<std::vector<std::string>> album_artist_sort;
/// a name for this song. This is not the song title. The exact meaning of this tag is not well-defined. It is often used by badly configured internet radio
/// stations with broken tags to squeeze both the artist name and the song title in one tag.
std::optional<std::string> name;
/// the song’s release date. This is usually a 4-digit year.
std::optional<std::string> date;
/// the song’s original release date.
std::optional<std::string> original_date;
/// the artist who performed the song.
std::optional<std::string> performer;
/// the conductor who conducted the song.
std::optional<std::string> conductor;
/// “a work is a distinct intellectual or artistic creation, which can be expressed in the form of one or more audio recordings”
std::optional<std::string> work;
/// “used if the sound belongs to a larger category of sounds/music” (from the IDv2.4.0 TIT1 description).
std::optional<std::string> grouping;
/// the name of the label or publisher.
std::optional<std::string> label;
/// the artist id in the MusicBrainz database.
std::optional<std::string> musicbrainz_artist_id;
/// the album id in the MusicBrainz database.
std::optional<std::string> musicbrainz_album_id;
/// the album artist id in the MusicBrainz database.
std::optional<std::string> musicbrainz_album_artist_id;
/// the track id in the MusicBrainz database.
std::optional<std::string> musicbrainz_track_id;
/// the release track id in the MusicBrainz database.
std::optional<std::string> musicbrainz_release_track_id;
/// the work id in the MusicBrainz database.
std::optional<std::string> musicbrainz_work_id;
/// https://www.freedesktop.org/wiki/Specifications/mpris-spec/metadata/
/// A unique identity for this track within the context of an MPRIS object (eg: tracklist).
std::optional<std::string> track_id;
/// URI: The location of an image representing the track or album. Clients should not assume this will continue to exist when the media player stops giving
/// out the URL
std::optional<std::string> art_url;
/// Base64 encoded data of an image representing the track or album
std::optional<ArtData> art_data;
/// The track lyrics
std::optional<std::string> lyrics;
/// The speed of the music, in beats per minute
std::optional<uint16_t> bpm;
/// Float: An automatically-generated rating, based on things such as how often it has been played. This should be in the range 0.0 to 1.0
std::optional<float> auto_rating;
/// A (list of) freeform comment(s)
std::optional<std::vector<std::string>> comment;
/// The composer(s) of the track
std::optional<std::vector<std::string>> composer;
/// Date/Time: When the track was created. Usually only the year component will be useful
std::optional<std::string> content_created;
/// Integer: The disc number on the album that this track is from
std::optional<uint16_t> disc_number;
/// Date/Time: When the track was first played
std::optional<std::string> first_used;
/// List of Strings: The genre(s) of the track
std::optional<std::vector<std::string>> genre;
/// Date/Time: When the track was last played
std::optional<std::string> last_used;
/// List of Strings: The lyricist(s) of the track
std::optional<std::vector<std::string>> lyricist;
/// String: The track title
std::optional<std::string> title;
/// Integer: The track number on the album disc
std::optional<uint16_t> track_number;
/// URI: The location of the media file.
std::optional<std::string> url;
/// Integer: The number of times the track has been played.
std::optional<uint16_t> use_count;
/// Float: A user-specified rating. This should be in the range 0.0 to 1.0.
std::optional<float> user_rating;
/// Spotify artist id
std::optional<std::string> spotify_artist_id;
/// Spotify track id
std::optional<std::string> spotify_track_id;
json toJson() const;
void fromJson(const json& j);
bool operator==(const Metadata& other) const;
};
| 6,388
|
C++
|
.h
| 131
| 43.480916
| 160
| 0.697072
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,054
|
asio_stream.hpp
|
badaix_snapcast/server/streamreader/asio_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/aixlog.hpp"
#include "common/str_compat.hpp"
#include "pcm_stream.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
namespace streamreader
{
using namespace std::chrono_literals;
template <typename ReadStream>
class AsioStream : public PcmStream
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
AsioStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
void start() override;
void stop() override;
protected:
virtual void connect() = 0;
virtual void disconnect();
virtual void on_connect();
virtual void do_read();
/// Start a timer that will change the stream state to idle after \p duration
void check_state(const std::chrono::steady_clock::duration& duration);
/// Use Timer \p timer to call \p handler after \p duration
template <typename Timer, typename Rep, typename Period>
void wait(Timer& timer, const std::chrono::duration<Rep, Period>& duration, std::function<void()> handler);
/// Cache last exception to avoid repeated error logging
std::string lastException_;
timeval tv_chunk_;
bool first_;
std::chrono::time_point<std::chrono::steady_clock> nextTick_;
uint32_t buffer_ms_;
boost::asio::steady_timer read_timer_;
boost::asio::steady_timer state_timer_;
std::unique_ptr<ReadStream> stream_;
/// duration of the current silence period
std::chrono::microseconds silence_{0ms};
/// silence duration before switching the stream to idle
std::chrono::milliseconds idle_threshold_;
};
template <typename ReadStream>
template <typename Timer, typename Rep, typename Period>
void AsioStream<ReadStream>::wait(Timer& timer, const std::chrono::duration<Rep, Period>& duration, std::function<void()> handler)
{
timer.expires_after(duration);
timer.async_wait(
[handler = std::move(handler)](const boost::system::error_code& ec)
{
if (ec)
{
LOG(ERROR, "AsioStream") << "Error during async wait: " << ec.message() << "\n";
}
else
{
handler();
}
});
}
template <typename ReadStream>
AsioStream<ReadStream>::AsioStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: PcmStream(pcmListener, ioc, server_settings, uri), read_timer_(strand_), state_timer_(strand_)
{
LOG(DEBUG, "AsioStream") << "Chunk duration: " << chunk_->durationMs() << " ms, frames: " << chunk_->getFrameCount() << ", size: " << chunk_->payloadSize
<< "\n";
idle_threshold_ = std::chrono::milliseconds(std::max(cpt::stoi(uri_.getQuery("idle_threshold", "100")), 10));
buffer_ms_ = 50;
try
{
buffer_ms_ = cpt::stoi(uri_.getQuery("buffer_ms", cpt::to_string(buffer_ms_)));
}
catch (...)
{
}
}
template <typename ReadStream>
void AsioStream<ReadStream>::check_state(const std::chrono::steady_clock::duration& duration)
{
state_timer_.expires_after(duration);
state_timer_.async_wait(
[this, duration](const boost::system::error_code& ec)
{
if (!ec)
{
LOG(INFO, "AsioStream") << "No data since " << std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()
<< " ms, switching to idle\n";
setState(ReaderState::kIdle);
}
});
}
template <typename ReadStream>
void AsioStream<ReadStream>::start()
{
PcmStream::start();
connect();
}
template <typename ReadStream>
void AsioStream<ReadStream>::stop()
{
read_timer_.cancel();
disconnect();
PcmStream::stop();
}
template <typename ReadStream>
void AsioStream<ReadStream>::disconnect()
{
if (stream_ && stream_->is_open())
stream_->close();
setState(ReaderState::kIdle);
}
template <typename ReadStream>
void AsioStream<ReadStream>::on_connect()
{
first_ = true;
tvEncodedChunk_ = std::chrono::steady_clock::now();
do_read();
}
template <typename ReadStream>
void AsioStream<ReadStream>::do_read()
{
// Reset the silence timer
check_state(idle_threshold_ + std::chrono::milliseconds(chunk_ms_));
boost::asio::async_read(*stream_, boost::asio::buffer(chunk_->payload, chunk_->payloadSize),
[this](boost::system::error_code ec, std::size_t length) mutable
{
state_timer_.cancel();
if (ec)
{
if (lastException_ != ec.message())
{
LOG(ERROR, "AsioStream") << "Error reading message: " << ec.message() << ", length: " << length << ", ec: " << ec << "\n";
lastException_ = ec.message();
}
disconnect();
wait(read_timer_, 100ms, [this] { connect(); });
return;
}
lastException_.clear();
if (isSilent(*chunk_))
{
silence_ += chunk_->duration<std::chrono::microseconds>();
if (silence_ >= idle_threshold_)
{
setState(ReaderState::kIdle);
// Avoid overflow
silence_ = idle_threshold_;
}
}
else
{
silence_ = 0ms;
setState(ReaderState::kPlaying);
}
// LOG(DEBUG, "AsioStream") << "Read: " << length << " bytes\n";
// First read after connect. Set the initial read timestamp
// the timestamp will be incremented after encoding,
// since we do not know how much the encoder actually encoded
// if (!first_)
// {
// auto now = std::chrono::steady_clock::now();
// auto stream2systime_diff = now - tvEncodedChunk_;
// if (stream2systime_diff > chronos::sec(5) + chronos::msec(chunk_ms_))
// {
// LOG(WARNING, "AsioStream") << "Stream and system time out of sync: "
// << std::chrono::duration_cast<std::chrono::microseconds>(stream2systime_diff).count() / 1000.
// << " ms, resetting stream time.\n";
// first_ = true;
// }
// }
if (first_)
{
first_ = false;
tvEncodedChunk_ = std::chrono::steady_clock::now() - chunk_->duration<std::chrono::nanoseconds>();
nextTick_ = std::chrono::steady_clock::now();
}
chunkRead(*chunk_);
nextTick_ += chunk_->duration<std::chrono::nanoseconds>();
auto currentTick = std::chrono::steady_clock::now();
// Synchronize read to chunk_ms_
if (nextTick_ >= currentTick)
{
read_timer_.expires_after(nextTick_ - currentTick);
read_timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (ec)
{
LOG(ERROR, "AsioStream") << "Error during async wait: " << ec.message() << "\n";
}
else
{
do_read();
}
});
return;
}
// Read took longer, wait for the buffer to fill up
else
{
resync(std::chrono::duration_cast<std::chrono::nanoseconds>(currentTick - nextTick_));
first_ = true;
do_read();
}
});
}
} // namespace streamreader
| 8,430
|
C++
|
.h
| 224
| 30.178571
| 159
| 0.599804
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,055
|
stream_uri.hpp
|
badaix_snapcast/server/streamreader/stream_uri.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2020 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/json.hpp"
// standard headers
#include <map>
#include <string>
using json = nlohmann::json;
namespace streamreader
{
// scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
struct StreamUri
{
StreamUri(const std::string& uri);
std::string uri;
std::string scheme;
/* struct Authority
{
std::string username;
std::string password;
std::string host;
size_t port;
};
Authority authority;
*/
std::string host;
std::string path;
std::map<std::string, std::string> query;
std::string fragment;
std::string id() const;
json toJson() const;
std::string getQuery(const std::string& key, const std::string& def = "") const;
void parse(const std::string& streamUri);
std::string toString() const;
};
} // namespace streamreader
| 1,699
|
C++
|
.h
| 49
| 28.897959
| 84
| 0.669927
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,056
|
process_stream.hpp
|
badaix_snapcast/server/streamreader/process_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "asio_stream.hpp"
#include "watchdog.hpp"
// standard headers
#include <memory>
#include <string>
namespace bp = boost::process;
namespace streamreader
{
using boost::asio::posix::stream_descriptor;
/// Starts an external process and reads and PCM data from stdout
/**
* Starts an external process, reads PCM data from stdout, and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class ProcessStream : public AsioStream<stream_descriptor>, public WatchdogListener
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
ProcessStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
~ProcessStream() override = default;
protected:
void connect() override;
void disconnect() override;
std::string exe_;
std::string path_;
std::string params_;
bp::pipe pipe_stdout_;
bp::pipe pipe_stderr_;
bp::child process_;
bool logStderr_;
boost::asio::streambuf streambuf_stderr_;
std::unique_ptr<stream_descriptor> stream_stderr_;
// void worker() override;
virtual void stderrReadLine();
virtual void onStderrMsg(const std::string& line);
virtual void initExeAndPath(const std::string& filename);
std::string findExe(const std::string& filename) const;
size_t wd_timeout_sec_;
std::unique_ptr<Watchdog> watchdog_;
void onTimeout(const Watchdog& watchdog, std::chrono::milliseconds ms) override;
};
} // namespace streamreader
| 2,373
|
C++
|
.h
| 59
| 36.508475
| 143
| 0.744551
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,057
|
tcp_stream.hpp
|
badaix_snapcast/server/streamreader/tcp_stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "asio_stream.hpp"
// 3rd party headers
#include <boost/asio/ip/tcp.hpp>
using boost::asio::ip::tcp;
namespace streamreader
{
/// Reads and decodes PCM data from a named pipe
/**
* Reads PCM from a named pipe and passes the data to an encoder.
* Implements EncoderListener to get the encoded data.
* Data is passed to the PcmStream::Listener
*/
class TcpStream : public AsioStream<tcp::socket>
{
public:
/// ctor. Encoded PCM data is passed to the PipeListener
TcpStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri);
protected:
void connect() override;
void disconnect() override;
std::unique_ptr<tcp::acceptor> acceptor_;
std::string host_;
size_t port_;
bool is_server_;
boost::asio::steady_timer reconnect_timer_;
};
} // namespace streamreader
| 1,655
|
C++
|
.h
| 43
| 35.162791
| 139
| 0.74375
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,058
|
control_error.hpp
|
badaix_snapcast/server/streamreader/control_error.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2023 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// standard headers
#include <system_error>
// https://www.boost.org/doc/libs/develop/libs/outcome/doc/html/motivation/plug_error_code.html
// https://akrzemi1.wordpress.com/examples/error_code-example/
// https://breese.github.io/2017/05/12/customizing-error-codes.html
// http://blog.think-async.com/2010/04/system-error-support-in-c0x-part-5.html
enum class ControlErrc
{
success = 0,
// Stream can not be controlled
can_not_control = 1,
// Stream property can_go_next is false
can_go_next_is_false = 2,
// Stream property can_go_previous is false
can_go_previous_is_false = 3,
// Stream property can_play is false
can_play_is_false = 4,
// Stream property can_pause is false
can_pause_is_false = 5,
// Stream property can_seek is false
can_seek_is_false = 6,
// Stream property can_control is false
can_control_is_false = 7,
// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
parse_error = -32700,
// The JSON sent is not a valid Request object.
invalid_request = -32600,
// The method does not exist / is not available.
method_not_found = -32601,
// Invalid method parameter(s).
invalid_params = -32602,
// Internal JSON-RPC error.
internal_error = -32603
};
namespace snapcast::error::control
{
const std::error_category& category();
}
namespace std
{
template <>
struct is_error_code_enum<ControlErrc> : public std::true_type
{
};
} // namespace std
std::error_code make_error_code(ControlErrc);
| 2,325
|
C++
|
.h
| 61
| 34.393443
| 108
| 0.723508
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,059
|
publish_bonjour.hpp
|
badaix_snapcast/server/publishZeroConf/publish_bonjour.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
class PublishBonjour;
// local headers
#include "publish_mdns.hpp"
// 3rd party headers
#include <dns_sd.h>
// standard headers
#include <string>
#include <thread>
class PublishBonjour : public PublishmDNS
{
public:
PublishBonjour(const std::string& serviceName, boost::asio::io_context& ioc);
virtual ~PublishBonjour();
virtual void publish(const std::vector<mDNSService>& services);
private:
std::thread pollThread_;
void worker();
std::atomic<bool> active_;
std::vector<DNSServiceRef> clients;
};
| 1,289
|
C++
|
.h
| 35
| 33.342857
| 81
| 0.747385
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,060
|
publish_mdns.hpp
|
badaix_snapcast/server/publishZeroConf/publish_mdns.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// 3rd party headers
#include <boost/asio/io_context.hpp>
// standard headers
#include <string>
#include <vector>
struct mDNSService
{
mDNSService(const std::string& name, size_t port) : name_(name), port_(port)
{
}
std::string name_;
size_t port_;
};
class PublishmDNS
{
public:
PublishmDNS(const std::string& serviceName, boost::asio::io_context& ioc) : serviceName_(serviceName), io_context_(ioc)
{
}
virtual ~PublishmDNS() = default;
virtual void publish(const std::vector<mDNSService>& services) = 0;
protected:
std::string serviceName_;
boost::asio::io_context& io_context_;
};
#if defined(HAS_AVAHI)
#include "publish_avahi.hpp"
using PublishZeroConf = PublishAvahi;
#elif defined(HAS_BONJOUR)
#include "publish_bonjour.hpp"
using PublishZeroConf = PublishBonjour;
#endif
| 1,593
|
C++
|
.h
| 47
| 30.510638
| 123
| 0.737255
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,061
|
publish_avahi.hpp
|
badaix_snapcast/server/publishZeroConf/publish_avahi.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
// 3rd party headers
#include <avahi-client/client.h>
#include <avahi-client/publish.h>
#include <avahi-common/alternative.h>
#include <avahi-common/error.h>
#include <avahi-common/malloc.h>
#include <avahi-common/simple-watch.h>
#include <avahi-common/timeval.h>
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <string>
#include <vector>
class PublishAvahi;
#include "publish_mdns.hpp"
class PublishAvahi : public PublishmDNS
{
public:
PublishAvahi(const std::string& serviceName, boost::asio::io_context& ioc);
~PublishAvahi() override;
void publish(const std::vector<mDNSService>& services) override;
private:
static void entry_group_callback(AvahiEntryGroup* g, AvahiEntryGroupState state, AVAHI_GCC_UNUSED void* userdata);
static void client_callback(AvahiClient* c, AvahiClientState state, AVAHI_GCC_UNUSED void* userdata);
void create_services(AvahiClient* c);
void poll();
AvahiClient* client_;
std::vector<mDNSService> services_;
boost::asio::steady_timer timer_;
};
| 1,816
|
C++
|
.h
| 45
| 37.111111
| 118
| 0.759386
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,062
|
pcm_encoder.hpp
|
badaix_snapcast/server/encoder/pcm_encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2020 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "encoder.hpp"
namespace encoder
{
class PcmEncoder : public Encoder
{
public:
PcmEncoder(const std::string& codecOptions = "");
void encode(const msg::PcmChunk& chunk) override;
std::string name() const override;
protected:
void initEncoder() override;
};
} // namespace encoder
| 1,081
|
C++
|
.h
| 29
| 33.724138
| 73
| 0.746641
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,063
|
opus_encoder.hpp
|
badaix_snapcast/server/encoder/opus_encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2015 Hannes Ellinger
Copyright (C) 2016-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/resampler.hpp"
#include "encoder.hpp"
// 3rd party headers
#ifdef MACOS
#include <opus.h>
#else
#include <opus/opus.h>
#endif
namespace encoder
{
class OpusEncoder : public Encoder
{
public:
OpusEncoder(const std::string& codecOptions = "");
~OpusEncoder() override;
void encode(const msg::PcmChunk& chunk) override;
std::string getAvailableOptions() const override;
std::string getDefaultOptions() const override;
std::string name() const override;
protected:
void encode(const SampleFormat& format, const char* data, size_t size);
void initEncoder() override;
::OpusEncoder* enc_;
std::vector<unsigned char> encoded_;
std::unique_ptr<msg::PcmChunk> remainder_;
size_t remainder_max_size_;
std::unique_ptr<Resampler> resampler_;
};
} // namespace encoder
| 1,644
|
C++
|
.h
| 46
| 32.217391
| 75
| 0.740227
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,064
|
null_encoder.hpp
|
badaix_snapcast/server/encoder/null_encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "encoder.hpp"
namespace encoder
{
/// Null Encoder class
/**
* Dummy encoder that will not encode any PcmChunk and thus will also never call
* "Encoder::encoded_callback_", i.e. the "OnEncodedCallback" to report any encoded data
* to the listener.
* Typically used as input stream for a MetaStream, which will do it's own encoding.
* Streams that use the null encoder cannot be listened to directly, nor they are visible
* on the RPC interface.
*/
class NullEncoder : public Encoder
{
public:
NullEncoder(const std::string& codecOptions = "");
void encode(const msg::PcmChunk& chunk) override;
std::string name() const override;
protected:
void initEncoder() override;
};
} // namespace encoder
| 1,504
|
C++
|
.h
| 38
| 36.447368
| 89
| 0.75
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,065
|
flac_encoder.hpp
|
badaix_snapcast/server/encoder/flac_encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "encoder.hpp"
// 3rd party headers
#include "FLAC/stream_encoder.h"
// standard headers
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
namespace encoder
{
class FlacEncoder : public Encoder
{
public:
FlacEncoder(const std::string& codecOptions = "");
~FlacEncoder() override;
void encode(const msg::PcmChunk& chunk) override;
std::string getAvailableOptions() const override;
std::string getDefaultOptions() const override;
std::string name() const override;
FLAC__StreamEncoderWriteStatus write_callback(const FLAC__StreamEncoder* encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples,
unsigned current_frame);
protected:
void initEncoder() override;
FLAC__StreamEncoder* encoder_;
FLAC__StreamMetadata* metadata_[2];
FLAC__int32* pcmBuffer_;
int pcmBufferSize_;
size_t encodedSamples_;
std::shared_ptr<msg::PcmChunk> flacChunk_;
};
} // namespace encoder
| 1,779
|
C++
|
.h
| 46
| 34
| 144
| 0.72468
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,066
|
ogg_encoder.hpp
|
badaix_snapcast/server/encoder/ogg_encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "encoder.hpp"
// 3rd party headers
#include <ogg/ogg.h>
#include <vorbis/vorbisenc.h>
namespace encoder
{
class OggEncoder : public Encoder
{
public:
OggEncoder(const std::string& codecOptions = "");
~OggEncoder() override;
void encode(const msg::PcmChunk& chunk) override;
std::string getAvailableOptions() const override;
std::string getDefaultOptions() const override;
std::string name() const override;
protected:
void initEncoder() override;
private:
ogg_stream_state os_; /// take physical pages, weld into a logical stream of packets
ogg_page og_; /// one Ogg bitstream page. Vorbis packets are inside
ogg_packet op_; /// one raw packet of data for decode
vorbis_info vi_; /// struct that stores all the static vorbis bitstream settings
vorbis_comment vc_; /// struct that stores all the user comments
vorbis_dsp_state vd_; /// central working state for the packet->PCM decoder
vorbis_block vb_; /// local working space for packet->PCM decode
ogg_int64_t lastGranulepos_;
};
} // namespace encoder
| 1,879
|
C++
|
.h
| 44
| 38.886364
| 88
| 0.729522
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,067
|
encoder_factory.hpp
|
badaix_snapcast/server/encoder/encoder_factory.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "encoder.hpp"
// standard headers
#include <memory>
#include <string>
namespace encoder
{
class EncoderFactory
{
public:
// EncoderFactory(const std::string& codecSettings);
std::unique_ptr<Encoder> createEncoder(const std::string& codecSettings) const;
};
} // namespace encoder
| 1,074
|
C++
|
.h
| 29
| 33.758621
| 83
| 0.755556
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,068
|
encoder.hpp
|
badaix_snapcast/server/encoder/encoder.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/codec_header.hpp"
#include "common/message/pcm_chunk.hpp"
#include "common/sample_format.hpp"
// standard headers
#include <functional>
#include <memory>
#include <string>
namespace encoder
{
/// Abstract Encoder class
/**
* Stream encoder. PCM chunks are fed into the encoder.
* As soon as a frame is encoded, the encoded data is passed to the EncoderListener
*/
class Encoder
{
public:
using OnEncodedCallback = std::function<void(const Encoder&, std::shared_ptr<msg::PcmChunk>, double)>;
/// ctor. Codec options (E.g. compression level) are passed as string and are codec dependend
Encoder(const std::string& codecOptions = "") : headerChunk_(nullptr), codecOptions_(codecOptions)
{
}
virtual ~Encoder() = default;
/// The listener will receive the encoded stream
virtual void init(OnEncodedCallback callback, const SampleFormat& format)
{
if (codecOptions_ == "")
codecOptions_ = getDefaultOptions();
encoded_callback_ = callback;
sampleFormat_ = format;
initEncoder();
}
/// Here the work is done. Encoded data is passed to the EncoderListener.
virtual void encode(const msg::PcmChunk& chunk) = 0;
virtual std::string name() const = 0;
virtual std::string getAvailableOptions() const
{
return "No codec options supported";
}
virtual std::string getDefaultOptions() const
{
return "";
}
/// Header information needed to decode the data
virtual std::shared_ptr<msg::CodecHeader> getHeader() const
{
return headerChunk_;
}
protected:
virtual void initEncoder() = 0;
SampleFormat sampleFormat_;
std::shared_ptr<msg::CodecHeader> headerChunk_;
std::string codecOptions_;
OnEncodedCallback encoded_callback_;
};
} // namespace encoder
| 2,629
|
C++
|
.h
| 72
| 32.027778
| 106
| 0.714624
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,069
|
controller.hpp
|
badaix_snapcast/client/controller.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "client_connection.hpp"
#include "client_settings.hpp"
#include "common/message/server_settings.hpp"
#include "decoder/decoder.hpp"
#include "player/player.hpp"
#include "stream.hpp"
// 3rd party headers
// standard headers
using namespace std::chrono_literals;
/// Forwards PCM data to the audio player
/**
* Sets up a connection to the server (using ClientConnection)
* Sets up the audio decoder and player.
* Decodes audio (message_type::kWireChunk) and feeds PCM to the audio stream buffer
* Does timesync with the server
*/
class Controller
{
public:
Controller(boost::asio::io_context& io_context, const ClientSettings& settings); //, std::unique_ptr<MetadataAdapter> meta);
void start();
// void stop();
static std::vector<std::string> getSupportedPlayerNames();
private:
using MdnsHandler = std::function<void(const boost::system::error_code& ec, const std::string& host, uint16_t port)>;
void worker();
void reconnect();
void browseMdns(const MdnsHandler& handler);
template <typename PlayerType>
std::unique_ptr<player::Player> createPlayer(ClientSettings::Player& settings, const std::string& player_name);
void getNextMessage();
void sendTimeSyncMessage(int quick_syncs);
boost::asio::io_context& io_context_;
boost::asio::steady_timer timer_;
ClientSettings settings_;
SampleFormat sampleFormat_;
std::unique_ptr<ClientConnection> clientConnection_;
std::shared_ptr<Stream> stream_;
std::unique_ptr<decoder::Decoder> decoder_;
std::unique_ptr<player::Player> player_;
// std::unique_ptr<MetadataAdapter> meta_;
std::unique_ptr<msg::ServerSettings> serverSettings_;
std::unique_ptr<msg::CodecHeader> headerChunk_;
};
| 2,516
|
C++
|
.h
| 60
| 38.283333
| 128
| 0.743243
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,070
|
stream.hpp
|
badaix_snapcast/client/stream.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/message/pcm_chunk.hpp"
#include "common/queue.hpp"
#include "common/resampler.hpp"
#include "common/sample_format.hpp"
#include "common/utils/logging.hpp"
#include "double_buffer.hpp"
// 3rd party headers
#ifdef HAS_SOXR
#include <soxr.h>
#endif
// standard headers
#include <atomic>
#include <memory>
/// Time synchronized audio stream
/**
* Queue with PCM data.
* Returns "online" server-time-synchronized PCM data
*/
class Stream
{
public:
Stream(const SampleFormat& in_format, const SampleFormat& out_format);
virtual ~Stream() = default;
/// Adds PCM data to the queue
void addChunk(std::unique_ptr<msg::PcmChunk> chunk);
void clearChunks();
/// Get PCM data, which will be played out in "outputBufferDacTime" time
/// frame = (num_channels) * (1 sample in bytes) = (2 channels) * (2 bytes (16 bits) per sample) = 4 bytes (32 bits)
/// @param[out] outputBuffer the buffer to be filled with PCM data
/// @param outputBufferDacTime the duration until the PCM chunk will be audible
/// @param frames the number of requested frames to be copied into outputBuffer
/// @return true if a chunk was available and successfully copied to outputBuffer
bool getPlayerChunk(void* outputBuffer, const chronos::usec& outputBufferDacTime, uint32_t frames);
/// Try to get a player chunk and fill the buffer with silence if it fails
/// @sa getPlayerChunk
/// @return true if a chunk was available and successfully copied to outputBuffer, else false and outputBuffer is filled with silence
bool getPlayerChunkOrSilence(void* outputBuffer, const chronos::usec& outputBufferDacTime, uint32_t frames);
/// "Server buffer": playout latency, e.g. 1000ms
void setBufferLen(size_t bufferLenMs);
const SampleFormat& getFormat() const
{
return format_;
}
bool waitForChunk(const std::chrono::milliseconds& timeout) const;
private:
/// Request an audio chunk from the front of the stream.
/// @param outputBuffer will be filled with the chunk
/// @param frames the number of requested frames
/// @return the timepoint when this chunk should be audible
chronos::time_point_clk getNextPlayerChunk(void* outputBuffer, uint32_t frames);
/// Request an audio chunk from the front of the stream with a tempo adaption
/// @param outputBuffer will be filled with the chunk
/// @param frames the number of requested frames
/// @param framesCorrection number of frames that should be added or removed.
/// The function will allways return "frames" frames, but will fit "frames + framesCorrection" frames into "frames"
/// so if frames is 100 and framesCorrection is 2, 102 frames will be read from the stream and 2 frames will be removed.
/// This makes us "fast-forward" by 2 frames, or if framesCorrection is -3, 97 frames will be read from the stream and
/// filled with 3 frames (simply by dublication), this makes us effectively slower
/// @return the timepoint when this chunk should be audible
chronos::time_point_clk getNextPlayerChunk(void* outputBuffer, uint32_t frames, int32_t framesCorrection);
/// Request a silent audio chunk
/// @param outputBuffer will be filled with the chunk
/// @param frames the number of requested frames
void getSilentPlayerChunk(void* outputBuffer, uint32_t frames) const;
void updateBuffers(chronos::usec::rep age);
void resetBuffers();
void setRealSampleRate(double sampleRate);
SampleFormat format_;
SampleFormat in_format_;
Queue<std::shared_ptr<msg::PcmChunk>> chunks_;
DoubleBuffer<chronos::usec::rep> miniBuffer_;
DoubleBuffer<chronos::usec::rep> shortBuffer_;
DoubleBuffer<chronos::usec::rep> buffer_;
/// current chunk (oldest, to be played)
std::shared_ptr<msg::PcmChunk> chunk_;
/// most recent chunk (newly queued)
std::shared_ptr<msg::PcmChunk> recent_;
DoubleBuffer<chronos::msec::rep> latencies_;
chronos::usec::rep median_;
chronos::usec::rep shortMedian_;
time_t lastUpdate_;
uint32_t playedFrames_;
int32_t correctAfterXFrames_;
std::atomic<chronos::msec> bufferMs_;
std::unique_ptr<Resampler> resampler_;
std::vector<char> resample_buffer_;
std::vector<char> read_buffer_;
int frame_delta_;
// int64_t next_us_;
mutable std::mutex mutex_;
bool hard_sync_;
/// Log "failed to get chunk" only once per second
utils::logging::TimeConditional time_cond_;
};
| 5,313
|
C++
|
.h
| 110
| 43.963636
| 137
| 0.725797
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,072
|
client_settings.hpp
|
badaix_snapcast/client/client_settings.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/sample_format.hpp"
#include "player/pcm_device.hpp"
// standard headers
#include <string>
struct ClientSettings
{
enum class SharingMode
{
unspecified,
exclusive,
shared
};
struct Mixer
{
enum class Mode
{
hardware,
software,
script,
none
};
Mode mode{Mode::software};
std::string parameter{""};
};
struct Server
{
std::string host{""};
size_t port{1704};
};
struct Player
{
std::string player_name{""};
std::string parameter{""};
int latency{0};
player::PcmDevice pcm_device;
SampleFormat sample_format;
SharingMode sharing_mode{SharingMode::unspecified};
Mixer mixer;
};
struct Logging
{
std::string sink{""};
std::string filter{"*:info"};
};
size_t instance{1};
std::string host_id;
Server server;
Player player;
Logging logging;
};
| 1,816
|
C++
|
.h
| 66
| 21.30303
| 73
| 0.639562
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,073
|
client_connection.hpp
|
badaix_snapcast/client/client_connection.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "client_settings.hpp"
#include "common/message/factory.hpp"
#include "common/message/message.hpp"
#include "common/time_defs.hpp"
// 3rd party headers
#include <boost/asio/any_io_executor.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/asio/strand.hpp>
// standard headers
#include <deque>
#include <memory>
#include <string>
using boost::asio::ip::tcp;
class ClientConnection;
template <typename Message>
using MessageHandler = std::function<void(const boost::system::error_code&, std::unique_ptr<Message>)>;
/// Used to synchronize server requests (wait for server response)
class PendingRequest : public std::enable_shared_from_this<PendingRequest>
{
public:
PendingRequest(const boost::asio::strand<boost::asio::any_io_executor>& strand, uint16_t reqId, const MessageHandler<msg::BaseMessage>& handler);
virtual ~PendingRequest();
/// Set the response for the pending request and passes it to the handler
/// @param value the response message
void setValue(std::unique_ptr<msg::BaseMessage> value);
/// @return the id of the request
uint16_t id() const;
/// Start the timer for the request
/// @param timeout the timeout to wait for the reception of the response
void startTimer(const chronos::usec& timeout);
/// Needed to put the requests in a container
bool operator<(const PendingRequest& other) const;
private:
uint16_t id_;
boost::asio::steady_timer timer_;
boost::asio::strand<boost::asio::any_io_executor> strand_;
MessageHandler<msg::BaseMessage> handler_;
};
/// Endpoint of the server connection
/**
* Server connection endpoint.
* Messages are sent to the server with the "send" method (async).
* Messages are sent sync to server with the sendReq method.
*/
class ClientConnection
{
public:
using ResultHandler = std::function<void(const boost::system::error_code&)>;
/// c'tor
ClientConnection(boost::asio::io_context& io_context, const ClientSettings::Server& server);
/// d'tor
virtual ~ClientConnection();
/// async connect
/// @param handler async result handler
void connect(const ResultHandler& handler);
/// disconnect the socket
void disconnect();
/// async send a message
/// @param message the message
/// @param handler the result handler
void send(const msg::message_ptr& message, const ResultHandler& handler);
/// Send request to the server and wait for answer
/// @param message the message
/// @param timeout the send timeout
/// @param handler async result handler with the response message or error
void sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler<msg::BaseMessage>& handler);
/// @sa sendRequest with templated response message
template <typename Message>
void sendRequest(const msg::message_ptr& message, const chronos::usec& timeout, const MessageHandler<Message>& handler)
{
sendRequest(message, timeout,
[handler](const boost::system::error_code& ec, std::unique_ptr<msg::BaseMessage> response)
{
if (ec)
handler(ec, nullptr);
else if (auto casted_response = msg::message_cast<Message>(std::move(response)))
handler(ec, std::move(casted_response));
else
handler(boost::system::errc::make_error_code(boost::system::errc::bad_message), nullptr);
});
}
std::string getMacAddress();
/// async get the next message
/// @param handler the next received message or error
void getNextMessage(const MessageHandler<msg::BaseMessage>& handler);
protected:
void sendNext();
msg::BaseMessage base_message_;
std::vector<char> buffer_;
size_t base_msg_size_;
boost::asio::strand<boost::asio::any_io_executor> strand_;
tcp::resolver resolver_;
tcp::socket socket_;
std::vector<std::weak_ptr<PendingRequest>> pendingRequests_;
uint16_t reqId_;
ClientSettings::Server server_;
struct PendingMessage
{
PendingMessage(const msg::message_ptr& msg, ResultHandler handler) : msg(msg), handler(handler)
{
}
msg::message_ptr msg;
ResultHandler handler;
};
std::deque<PendingMessage> messages_;
};
| 5,132
|
C++
|
.h
| 123
| 36.691057
| 149
| 0.70866
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,074
|
metadata.hpp
|
badaix_snapcast/client/metadata.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "common/json.hpp"
// standard headers
#include <iostream>
// Prefix used in output
#define METADATA std::string("metadata")
/*
* Implement a generic metadata output handler
*/
using json = nlohmann::json;
/*
* Base class, prints to stdout
*/
class MetadataAdapter
{
public:
MetadataAdapter()
{
reset();
}
virtual ~MetadataAdapter() = default;
void reset()
{
msg_ = json{};
}
std::string serialize()
{
return METADATA + ":" + msg_.dump();
}
void tag(const std::string& name, const std::string& value)
{
msg_[name] = value;
}
std::string operator[](const std::string& key)
{
try
{
return msg_[key];
}
catch (std::domain_error&)
{
return std::string();
}
}
virtual int push()
{
std::cout << serialize() << "\n";
return 0;
}
int push(const json& jtag)
{
msg_ = jtag;
return push();
}
protected:
json msg_;
};
/*
* Send metadata to stderr as json
*/
class MetaStderrAdapter : public MetadataAdapter
{
public:
using MetadataAdapter::push;
int push() override
{
std::cerr << serialize() << "\n";
return 0;
}
};
| 2,066
|
C++
|
.h
| 85
| 19.376471
| 73
| 0.63284
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,076
|
alsa_player.hpp
|
badaix_snapcast/client/player/alsa_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "player.hpp"
// 3rd party headers
#include <alsa/asoundlib.h>
#include <boost/asio/posix/stream_descriptor.hpp>
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <chrono>
#include <optional>
#include <vector>
namespace player
{
static constexpr auto ALSA = "alsa";
/// Audio Player
/**
* Audio player implementation using Alsa
*/
class AlsaPlayer : public Player
{
public:
AlsaPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
~AlsaPlayer() override;
void start() override;
void stop() override;
/// List the system's audio output devices
static std::vector<PcmDevice> pcm_list();
protected:
void worker() override;
bool needsThread() const override;
private:
/// initialize alsa and the mixer (if neccessary)
void initAlsa();
/// free alsa and optionally the mixer
/// @param uninit_mixer free the mixer
void uninitAlsa(bool uninit_mixer);
bool getAvailDelay(snd_pcm_sframes_t& avail, snd_pcm_sframes_t& delay);
void initMixer();
void uninitMixer();
bool getHardwareVolume(Volume& volume) override;
void setHardwareVolume(const Volume& volume) override;
void waitForEvent();
snd_pcm_t* handle_;
snd_ctl_t* ctl_;
snd_mixer_t* mixer_;
snd_mixer_elem_t* elem_;
std::string mixer_name_;
std::string mixer_device_;
std::unique_ptr<pollfd, std::function<void(pollfd*)>> fd_;
std::vector<char> buffer_;
snd_pcm_uframes_t frames_;
boost::asio::posix::stream_descriptor sd_;
std::chrono::time_point<std::chrono::steady_clock> last_change_;
std::recursive_mutex mutex_;
boost::asio::steady_timer timer_;
std::optional<std::chrono::microseconds> buffer_time_;
std::optional<uint32_t> periods_;
};
} // namespace player
| 2,631
|
C++
|
.h
| 73
| 32.178082
| 124
| 0.722682
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,077
|
file_player.hpp
|
badaix_snapcast/client/player/file_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef FILE_PLAYER_HPP
#define FILE_PLAYER_HPP
// local headers
#include "player.hpp"
// 3rd party headers
#include <boost/asio/steady_timer.hpp>
// standard headers
#include <cstdio>
#include <memory>
namespace player
{
static constexpr auto FILE = "file";
/// File Player
/// Used for testing and doesn't even write the received audio to file at the moment,
/// but just discards it
class FilePlayer : public Player
{
public:
FilePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~FilePlayer();
void start() override;
void stop() override;
/// List the dummy file PCM device
static std::vector<PcmDevice> pcm_list(const std::string& parameter);
protected:
void requestAudio();
void loop();
bool needsThread() const override;
boost::asio::steady_timer timer_;
std::vector<char> buffer_;
std::chrono::time_point<std::chrono::steady_clock> next_request_;
std::shared_ptr<::FILE> file_;
};
} // namespace player
#endif
| 1,797
|
C++
|
.h
| 49
| 33.326531
| 124
| 0.736295
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,078
|
wasapi_player.hpp
|
badaix_snapcast/client/player/wasapi_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef WASAPI_PLAYER_HPP
#define WASAPI_PLAYER_HPP
#pragma warning(push)
#pragma warning(disable : 4100)
// local headers
#include "player.hpp"
// 3rd party headers
#include <audiopolicy.h>
#include <endpointvolume.h>
namespace player
{
class AudioSessionEventListener : public IAudioSessionEvents
{
LONG _cRef;
float volume_ = 1.f;
bool muted_ = false;
public:
AudioSessionEventListener() : _cRef(1)
{
}
float getVolume()
{
return volume_;
}
bool getMuted()
{
return muted_;
}
~AudioSessionEventListener()
{
}
// IUnknown methods -- AddRef, Release, and QueryInterface
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef)
{
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID** ppvInterface);
// Notification methods for audio session events
HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPCWSTR NewIconPath, LPCGUID EventContext)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext);
HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext)
{
return S_OK;
}
HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState);
HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason);
};
class AudioEndpointVolumeCallback : public IAudioEndpointVolumeCallback
{
LONG _cRef;
float volume_ = 1.f;
bool muted_ = false;
public:
AudioEndpointVolumeCallback() : _cRef(1)
{
}
~AudioEndpointVolumeCallback()
{
}
float getVolume()
{
return volume_;
}
bool getMuted()
{
return muted_;
}
// IUnknown methods -- AddRef, Release, and QueryInterface
ULONG STDMETHODCALLTYPE AddRef()
{
return InterlockedIncrement(&_cRef);
}
ULONG STDMETHODCALLTYPE Release()
{
ULONG ulRef = InterlockedDecrement(&_cRef);
if (0 == ulRef)
{
delete this;
}
return ulRef;
}
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID** ppvInterface)
{
if (IID_IUnknown == riid)
{
AddRef();
*ppvInterface = (IUnknown*)this;
}
else if (__uuidof(IAudioEndpointVolumeCallback) == riid)
{
AddRef();
*ppvInterface = (IAudioEndpointVolumeCallback*)this;
}
else
{
*ppvInterface = NULL;
return E_NOINTERFACE;
}
return S_OK;
}
// Callback method for endpoint-volume-change notifications.
HRESULT STDMETHODCALLTYPE OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify);
};
static constexpr auto WASAPI = "wasapi";
class WASAPIPlayer : public Player
{
public:
WASAPIPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~WASAPIPlayer();
static std::vector<PcmDevice> pcm_list();
protected:
virtual void worker();
virtual bool needsThread() const override
{
return true;
}
private:
AudioSessionEventListener* audioEventListener_;
IAudioEndpointVolume* audioEndpointListener_;
AudioEndpointVolumeCallback audioEndpointVolumeCallback_;
ClientSettings::SharingMode mode_;
};
#pragma warning(pop)
} // namespace player
#endif
| 4,748
|
C++
|
.h
| 159
| 24.157233
| 147
| 0.693019
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
25,079
|
pcm_device.hpp
|
badaix_snapcast/client/player/pcm_device.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2020 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef PCM_DEVICE_HPP
#define PCM_DEVICE_HPP
#include <string>
namespace player
{
static constexpr char DEFAULT_DEVICE[] = "default";
struct PcmDevice
{
PcmDevice() : idx(-1), name(DEFAULT_DEVICE){};
PcmDevice(int idx, const std::string& name, const std::string& description = "") : idx(idx), name(name), description(description){};
int idx;
std::string name;
std::string description;
};
} // namespace player
#endif
| 1,187
|
C++
|
.h
| 30
| 35.9
| 136
| 0.734498
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
25,080
|
coreaudio_player.hpp
|
badaix_snapcast/client/player/coreaudio_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef CORE_AUDIO_PLAYER_HPP
#define CORE_AUDIO_PLAYER_HPP
// local headers
#include "player.hpp"
// 3rd party headers
#include <AudioToolbox/AudioQueue.h>
#include <CoreAudio/CoreAudioTypes.h>
#include <CoreFoundation/CFRunLoop.h>
namespace player
{
static constexpr auto COREAUDIO = "coreaudio";
/// Audio Player
/**
* Audio player implementation using CoreAudio
*
* Warning:
*
* !! This player is experimental and might not be maintained !!
*
*/
class CoreAudioPlayer : public Player
{
public:
CoreAudioPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~CoreAudioPlayer();
void playerCallback(AudioQueueRef queue, AudioQueueBufferRef bufferRef);
static std::vector<PcmDevice> pcm_list();
protected:
void worker() override;
bool needsThread() const override;
void initAudioQueue();
void uninitAudioQueue(AudioQueueRef queue);
AudioQueueTimelineRef timeLine_;
size_t ms_;
size_t frames_;
size_t buff_size_;
std::shared_ptr<Stream> pubStream_;
long lastChunkTick;
};
} // namespace player
#endif
| 1,889
|
C++
|
.h
| 55
| 31.036364
| 129
| 0.752475
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,081
|
pulse_player.hpp
|
badaix_snapcast/client/player/pulse_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "player.hpp"
// 3rd party headers
#include <pulse/pulseaudio.h>
// standard headers
#include <atomic>
#include <cstdio>
#include <memory>
#include <optional>
namespace player
{
static constexpr auto PULSE = "pulse";
/// File Player
/// Used for testing and doesn't even write the received audio to file at the moment,
/// but just discards it
class PulsePlayer : public Player
{
public:
PulsePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~PulsePlayer();
void start() override;
void stop() override;
/// List the system's audio output devices
static std::vector<PcmDevice> pcm_list(const std::string& parameter);
protected:
bool needsThread() const override;
void worker() override;
void connect();
void disconnect();
bool getHardwareVolume(Volume& volume) override;
void setHardwareVolume(const Volume& volume) override;
void triggerVolumeUpdate();
void underflowCallback(pa_stream* stream);
void stateCallback(pa_context* ctx);
void writeCallback(pa_stream* stream, size_t nbytes);
void subscribeCallback(pa_context* ctx, pa_subscription_event_type_t event_type, uint32_t idx);
std::vector<char> buffer_;
std::chrono::microseconds latency_;
int underflows_ = 0;
std::atomic<int> pa_ready_;
long last_chunk_tick_;
pa_buffer_attr bufattr_;
pa_sample_spec pa_ss_;
pa_mainloop* pa_ml_;
pa_context* pa_ctx_;
pa_stream* playstream_;
pa_proplist* proplist_;
std::optional<std::string> server_;
std::map<std::string, std::string> properties_;
// cache of the last volume change
std::chrono::time_point<std::chrono::steady_clock> last_change_;
};
} // namespace player
| 2,568
|
C++
|
.h
| 68
| 33.823529
| 125
| 0.728595
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,082
|
player.hpp
|
badaix_snapcast/client/player/player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "client_settings.hpp"
#include "common/endian.hpp"
#include "stream.hpp"
// 3rd party headers
#include <boost/asio/io_context.hpp>
// standard headers
#include <atomic>
#include <functional>
#include <mutex>
#include <thread>
#if !defined(WINDOWS)
#define SUPPORTS_VOLUME_SCRIPT
#endif
namespace player
{
/// Audio Player
/**
* Abstract audio player implementation
*/
class Player
{
public:
struct Volume
{
double volume{1.0};
bool mute{false};
};
using volume_callback = std::function<void(const Volume& volume)>;
Player(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~Player();
/// Set audio volume in range [0..1]
/// @param volume the volume on range [0..1], muted or not
virtual void setVolume(const Volume& volume);
/// Called on start, before the first audio sample is sent or any other function is called.
/// In case of hardware mixer, it will call getVolume and notify the server about the current volume
virtual void start();
/// Called on stop
virtual void stop();
/// Sets the hardware volume change callback
void setVolumeCallback(const volume_callback& callback)
{
onVolumeChanged_ = callback;
}
protected:
/// will be run in a thread if needsThread is true
virtual void worker();
/// @return true if the worker function should be started in a thread
virtual bool needsThread() const = 0;
/// get the hardware mixer volume
/// @param[out] volume the volume on range [0..1], muted or not
/// @return success or not
virtual bool getHardwareVolume(Volume& volume);
/// set the hardware mixer volume
/// @param volume the volume on range [0..1], muted or not
/// @param muted muted or not
virtual void setHardwareVolume(const Volume& volume);
void setVolume_poly(double volume, double exp);
void setVolume_exp(double volume, double base);
void adjustVolume(char* buffer, size_t frames);
/// Notify the server about hardware volume changes
/// @param volume the volume in range [0..1]
/// @param muted if muted or not
void notifyVolumeChange(const Volume& volume) const
{
if (onVolumeChanged_)
onVolumeChanged_(volume);
}
boost::asio::io_context& io_context_;
std::atomic<bool> active_;
std::shared_ptr<Stream> stream_;
std::thread playerThread_;
ClientSettings::Player settings_;
Player::Volume volume_;
double volCorrection_;
volume_callback onVolumeChanged_;
mutable std::mutex mutex_;
private:
template <typename T>
void adjustVolume(char* buffer, size_t count, double volume)
{
T* bufferT = (T*)buffer;
for (size_t n = 0; n < count; ++n)
bufferT[n] = endian::swap<T>(static_cast<T>(endian::swap<T>(bufferT[n]) * volume));
}
};
inline bool operator==(const Player::Volume& lhs, const Player::Volume& rhs)
{
return ((lhs.volume == rhs.volume) && (lhs.mute == rhs.mute));
}
inline bool operator!=(const Player::Volume& lhs, const Player::Volume& rhs)
{
return !(lhs == rhs);
}
} // namespace player
| 3,974
|
C++
|
.h
| 110
| 31.818182
| 120
| 0.69828
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
25,083
|
opensl_player.hpp
|
badaix_snapcast/client/player/opensl_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2022 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#ifndef OPEN_SL_PLAYER_HPP
#define OPEN_SL_PLAYER_HPP
// local headers
#include "player.hpp"
// 3rd party headers
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
// standard headers
#include <string>
namespace player
{
static constexpr auto OPENSL = "opensl";
typedef int (*AndroidAudioCallback)(short* buffer, int num_samples);
/// OpenSL Audio Player
/**
* Player implementation for OpenSL (e.g. Android)
*/
class OpenslPlayer : public Player
{
public:
OpenslPlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
virtual ~OpenslPlayer();
void start() override;
void stop() override;
void playerCallback(SLAndroidSimpleBufferQueueItf bq);
protected:
void initOpensl();
void uninitOpensl();
bool needsThread() const override;
void throwUnsuccess(const std::string& phase, const std::string& what, SLresult result);
std::string resultToString(SLresult result) const;
// engine interfaces
SLObjectItf engineObject;
SLEngineItf engineEngine;
SLObjectItf outputMixObject;
// buffer queue player interfaces
SLObjectItf bqPlayerObject;
SLPlayItf bqPlayerPlay;
SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue;
SLVolumeItf bqPlayerVolume;
// Double buffering.
int curBuffer;
char* buffer[2];
size_t ms_;
size_t frames_;
size_t buff_size;
std::shared_ptr<Stream> pubStream_;
};
} // namespace player
#endif
| 2,243
|
C++
|
.h
| 64
| 31.28125
| 126
| 0.749072
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,084
|
oboe_player.hpp
|
badaix_snapcast/client/player/oboe_player.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
// local headers
#include "player.hpp"
// 3rd party headers
#include <oboe/LatencyTuner.h>
#include <oboe/Oboe.h>
// standard headers
#include <vector>
namespace player
{
static constexpr auto OBOE = "oboe";
/// Android Oboe Audio Player
/**
* Player implementation for Android Oboe
*/
class OboePlayer : public Player, public oboe::AudioStreamDataCallback, public oboe::AudioStreamErrorCallback
{
public:
/// c'tor
OboePlayer(boost::asio::io_context& io_context, const ClientSettings::Player& settings, std::shared_ptr<Stream> stream);
/// d'tor
virtual ~OboePlayer();
void start() override;
void stop() override;
protected:
/// AudioStreamDataCallback::onAudioReady override
oboe::DataCallbackResult onAudioReady(oboe::AudioStream* oboeStream, void* audioData, int32_t numFrames) override;
/// AudioStreamErrorCallback::onErrorBeforeClose override
void onErrorBeforeClose(oboe::AudioStream* oboeStream, oboe::Result error) override;
/// AudioStreamErrorCallback::onErrorAfterClose override
void onErrorAfterClose(oboe::AudioStream* oboeStream, oboe::Result error) override;
protected:
/// Open the oboe stream
oboe::Result openStream();
/// Get current audio playout delay
double getCurrentOutputLatencyMillis() const;
bool needsThread() const override;
/// The oboe output stream
std::shared_ptr<oboe::AudioStream> out_stream_;
/// Latency tuner to optimize the latency
std::unique_ptr<oboe::LatencyTuner> latency_tuner_;
/// Audio data buffer used for chaning the bit depth
std::vector<char> audio_data_;
};
} // namespace player
| 2,396
|
C++
|
.h
| 59
| 36.898305
| 124
| 0.750755
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
25,086
|
browse_bonjour.hpp
|
badaix_snapcast/client/browseZeroConf/browse_bonjour.hpp
|
/***
This file is part of snapcast
Copyright (C) 2014-2024 Johannes Pohl
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 3 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, see <http://www.gnu.org/licenses/>.
***/
#pragma once
class BrowseBonjour;
// local headers
#include "browse_mdns.hpp"
// 3rd party headers
#include <dns_sd.h>
class BrowseBonjour : public BrowsemDNS
{
public:
bool browse(const std::string& serviceName, mDNSResult& result, int timeout) override;
};
| 1,009
|
C++
|
.h
| 25
| 36.92
| 90
| 0.755897
|
badaix/snapcast
| 6,105
| 452
| 82
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.