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,810
|
blocklist_menu.hpp
|
wwmm_easyeffects/include/blocklist_menu.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkpopover.h>
#include "application.hpp"
#include "pipeline_type.hpp"
namespace ui::blocklist_menu {
G_BEGIN_DECLS
#define EE_TYPE_BLOCKLIST_MENU (blocklist_menu_get_type())
G_DECLARE_FINAL_TYPE(BlocklistMenu, blocklist_menu, EE, BLOCKLIST_MENU, GtkPopover)
G_END_DECLS
auto create() -> BlocklistMenu*;
void setup(BlocklistMenu* self, app::Application* application, PipelineType pipeline_type);
} // namespace ui::blocklist_menu
| 1,290
|
C++
|
.h
| 33
| 37.272727
| 91
| 0.764234
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,811
|
pitch.hpp
|
wwmm_easyeffects/include/pitch.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <STTypes.h>
#include <deque>
#include <span>
#include <string>
#include <vector>
#include "SoundTouch.h"
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Pitch : public PluginBase {
public:
Pitch(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Pitch(const Pitch&) = delete;
auto operator=(const Pitch&) -> Pitch& = delete;
Pitch(const Pitch&&) = delete;
auto operator=(const Pitch&&) -> Pitch& = delete;
~Pitch() override;
enum class Mode { speed, quality, consistency };
enum class Formant { shifted, preserved };
enum class Transients { crisp, mixed, smooth };
enum class Detector { compound, percussive, soft };
enum class Phase { laminar, independent };
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
private:
bool soundtouch_ready = false;
bool notify_latency = false;
uint latency_n_frames = 0U;
std::vector<float> data_L, data_R, data;
std::deque<float> deque_out_L, deque_out_R;
soundtouch::SoundTouch* snd_touch = nullptr;
bool anti_alias = false;
bool quick_seek = false;
int sequence_length_ms = 40;
int seek_window_ms = 15;
int overlap_length_ms = 8;
double semitones = 0.0;
double tempo_difference = 0.0;
double rate_difference = 0.0;
void set_semitones();
void set_sequence_length();
void set_seek_window();
void set_overlap_length();
void set_quick_seek();
void set_anti_alias();
void set_tempo_difference();
void set_rate_difference();
void init_soundtouch();
};
| 2,579
|
C++
|
.h
| 75
| 30.906667
| 73
| 0.70418
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,812
|
application_ui.hpp
|
wwmm_easyeffects/include/application_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <gio/gio.h>
#include <glib-object.h>
#include <glibconfig.h>
namespace ui::application_window {
G_BEGIN_DECLS
#define EE_TYPE_APPLICATION_WINDOW (application_window_get_type())
G_DECLARE_FINAL_TYPE(ApplicationWindow, application_window, EE, APP_WINDOW, AdwApplicationWindow)
G_END_DECLS
auto create(GApplication* gapp) -> ApplicationWindow*;
} // namespace ui::application_window
| 1,186
|
C++
|
.h
| 30
| 37.666667
| 97
| 0.765475
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,813
|
crossfeed_ui.hpp
|
wwmm_easyeffects/include/crossfeed_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "crossfeed.hpp"
namespace ui::crossfeed_box {
G_BEGIN_DECLS
#define EE_TYPE_CROSSFEED_BOX (crossfeed_box_get_type())
G_DECLARE_FINAL_TYPE(CrossfeedBox, crossfeed_box, EE, CROSSFEED_BOX, GtkBox)
G_END_DECLS
auto create() -> CrossfeedBox*;
void setup(CrossfeedBox* self, std::shared_ptr<Crossfeed> crossfeed, const std::string& schema_path);
} // namespace ui::crossfeed_box
| 1,289
|
C++
|
.h
| 34
| 36.117647
| 101
| 0.75743
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,814
|
compressor_preset.hpp
|
wwmm_easyeffects/include/compressor_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class CompressorPreset : public PluginPresetBase {
public:
explicit CompressorPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,107
|
C++
|
.h
| 29
| 36.137931
| 74
| 0.757689
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,815
|
autogain_preset.hpp
|
wwmm_easyeffects/include/autogain_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class AutoGainPreset : public PluginPresetBase {
public:
explicit AutoGainPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,103
|
C++
|
.h
| 29
| 36
| 73
| 0.756782
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,816
|
test_signals.hpp
|
wwmm_easyeffects/include/test_signals.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <pipewire/context.h>
#include <pipewire/filter.h>
#include <pipewire/proxy.h>
#include <spa/utils/hook.h>
#include <sys/types.h>
#include <random>
#include <vector>
#include "pipe_manager.hpp"
enum class TestSignalType { sine_wave, gaussian, pink };
class TestSignals {
public:
TestSignals(PipeManager* pipe_manager);
TestSignals(const TestSignals&) = delete;
auto operator=(const TestSignals&) -> TestSignals& = delete;
TestSignals(const TestSignals&&) = delete;
auto operator=(const TestSignals&&) -> TestSignals& = delete;
virtual ~TestSignals();
struct data;
struct port {
struct data* data;
};
struct data {
struct port* out_left = nullptr;
struct port* out_right = nullptr;
TestSignals* ts = nullptr;
};
pw_filter* filter = nullptr;
pw_filter_state state = PW_FILTER_STATE_UNCONNECTED;
uint n_samples = 0U;
uint rate = 0U;
bool create_left_channel = true;
bool create_right_channel = true;
bool can_get_node_id = false;
float sine_phase = 0.0F;
float sine_frequency = 1000.0F;
TestSignalType signal_type = TestSignalType::sine_wave;
void set_state(const bool& state);
void set_frequency(const float& value);
[[nodiscard]] auto get_node_id() const -> uint;
void set_active(const bool& state) const;
void set_signal_type(const TestSignalType& value);
auto white_noise() -> float;
private:
PipeManager* pm = nullptr;
spa_hook listener{};
data pf_data = {};
uint node_id = 0U;
std::vector<pw_proxy*> list_proxies;
std::random_device rd{};
std::mt19937 random_generator;
std::normal_distribution<float> normal_distribution{0.0F, 0.3F};
};
| 2,435
|
C++
|
.h
| 71
| 31.366197
| 73
| 0.729846
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,817
|
presets_menu.hpp
|
wwmm_easyeffects/include/presets_menu.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkpopover.h>
#include "application.hpp"
#include "preset_type.hpp"
namespace ui::presets_menu {
G_BEGIN_DECLS
#define EE_TYPE_PRESETS_MENU (presets_menu_get_type())
G_DECLARE_FINAL_TYPE(PresetsMenu, presets_menu, EE, PRESETS_MENU, GtkPopover)
G_END_DECLS
auto create() -> PresetsMenu*;
void setup(PresetsMenu* self, app::Application* application, PresetType preset_type);
} // namespace ui::presets_menu
| 1,266
|
C++
|
.h
| 33
| 36.545455
| 85
| 0.759608
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,818
|
reverb.hpp
|
wwmm_easyeffects/include/reverb.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <span>
#include <string>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Reverb : public PluginBase {
public:
Reverb(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Reverb(const Reverb&) = delete;
auto operator=(const Reverb&) -> Reverb& = delete;
Reverb(const Reverb&&) = delete;
auto operator=(const Reverb&&) -> Reverb& = delete;
~Reverb() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
private:
};
| 1,552
|
C++
|
.h
| 43
| 32.186047
| 73
| 0.698402
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,819
|
loudness_ui.hpp
|
wwmm_easyeffects/include/loudness_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "loudness.hpp"
namespace ui::loudness_box {
G_BEGIN_DECLS
#define EE_TYPE_LOUDNESS_BOX (loudness_box_get_type())
G_DECLARE_FINAL_TYPE(LoudnessBox, loudness_box, EE, LOUDNESS_BOX, GtkBox)
G_END_DECLS
auto create() -> LoudnessBox*;
void setup(LoudnessBox* self, std::shared_ptr<Loudness> loudness, const std::string& schema_path);
} // namespace ui::loudness_box
| 1,277
|
C++
|
.h
| 34
| 35.764706
| 98
| 0.755069
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,820
|
exciter.hpp
|
wwmm_easyeffects/include/exciter.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <sigc++/signal.h>
#include <span>
#include <string>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Exciter : public PluginBase {
public:
Exciter(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Exciter(const Exciter&) = delete;
auto operator=(const Exciter&) -> Exciter& = delete;
Exciter(const Exciter&&) = delete;
auto operator=(const Exciter&&) -> Exciter& = delete;
~Exciter() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
sigc::signal<void(const double)> harmonics;
double harmonics_port_value = 0.0;
private:
};
| 1,679
|
C++
|
.h
| 46
| 32.565217
| 73
| 0.700739
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,821
|
deesser_ui.hpp
|
wwmm_easyeffects/include/deesser_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "deesser.hpp"
namespace ui::deesser_box {
G_BEGIN_DECLS
#define EE_TYPE_DEESSER_BOX (deesser_box_get_type())
G_DECLARE_FINAL_TYPE(DeesserBox, deesser_box, EE, DEESSER_BOX, GtkBox)
G_END_DECLS
auto create() -> DeesserBox*;
void setup(DeesserBox* self, std::shared_ptr<Deesser> deesser, const std::string& schema_path);
} // namespace ui::deesser_box
| 1,265
|
C++
|
.h
| 34
| 35.411765
| 95
| 0.752662
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,822
|
rnnoise.hpp
|
wwmm_easyeffects/include/rnnoise.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <sigc++/signal.h>
#include <sys/types.h>
#include <algorithm>
#include <climits>
#include <cstddef>
#include <memory>
#include <span>
#include <string>
#include <vector>
#include "pipe_manager.hpp"
#ifdef ENABLE_RNNOISE
#include <rnnoise.h>
#endif
#include <deque>
#include "plugin_base.hpp"
#include "resampler.hpp"
class RNNoise : public PluginBase {
public:
RNNoise(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
RNNoise(const RNNoise&) = delete;
auto operator=(const RNNoise&) -> RNNoise& = delete;
RNNoise(const RNNoise&&) = delete;
auto operator=(const RNNoise&&) -> RNNoise& = delete;
~RNNoise() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
void init_release();
auto search_model_path(const std::string& name) -> std::string;
#ifndef ENABLE_RNNOISE
bool package_installed = false;
#endif
const std::string rnnn_ext = ".rnnn";
bool standard_model = true;
sigc::signal<void(const bool load_error)> model_changed;
private:
std::string local_dir_rnnoise;
std::vector<std::string> system_data_dir_rnnoise;
bool resample = false;
bool notify_latency = false;
bool rnnoise_ready = false;
bool resampler_ready = false;
bool enable_vad = false;
uint blocksize = 480U;
uint rnnoise_rate = 48000U;
uint latency_n_frames = 0U;
float vad_thres = 0.95F;
float wet_ratio = 1.0F;
uint release = 2U;
const float inv_short_max = 1.0F / (SHRT_MAX + 1.0F);
std::deque<float> deque_out_L, deque_out_R;
std::vector<float> data_L, data_R, data_tmp;
std::vector<float> resampled_data_L, resampled_data_R;
std::unique_ptr<Resampler> resampler_inL, resampler_outL;
std::unique_ptr<Resampler> resampler_inR, resampler_outR;
#ifdef ENABLE_RNNOISE
RNNModel* model = nullptr;
DenoiseState *state_left = nullptr, *state_right = nullptr;
float vad_prob_left, vad_prob_right;
int vad_grace_left, vad_grace_right;
auto get_model_from_name() -> RNNModel*;
void free_rnnoise();
template <typename T1, typename T2>
void remove_noise(const T1& left_in, const T1& right_in, T2& out_L, T2& out_R) {
for (const auto& v : left_in) {
data_L.push_back(v);
if (data_L.size() == blocksize) {
if (state_left != nullptr) {
std::ranges::for_each(data_L, [](auto& v) { v *= static_cast<float>(SHRT_MAX + 1); });
data_tmp = data_L;
vad_prob_left = rnnoise_process_frame(state_left, data_L.data(), data_L.data());
if (enable_vad) {
if (vad_prob_left >= vad_thres) {
vad_grace_left = release;
}
if (vad_grace_left >= 0) {
--vad_grace_left;
for (size_t i = 0U; i < data_L.size(); i++) {
data_L[i] = data_L[i] * wet_ratio + data_tmp[i] * (1.0F - wet_ratio);
data_L[i] *= inv_short_max;
}
} else {
std::ranges::for_each(data_L, [&](auto& v) { v = 0.0F; });
}
} else {
for (size_t i = 0U; i < data_L.size(); i++) {
data_L[i] = data_L[i] * wet_ratio + data_tmp[i] * (1.0F - wet_ratio);
data_L[i] *= inv_short_max;
}
}
}
for (const auto& v : data_L) {
out_L.push_back(v);
}
data_L.resize(0U);
}
}
for (const auto& v : right_in) {
data_R.push_back(v);
if (data_R.size() == blocksize) {
if (state_right != nullptr) {
std::ranges::for_each(data_R, [](auto& v) { v *= static_cast<float>(SHRT_MAX + 1); });
data_tmp = data_R;
vad_prob_right = rnnoise_process_frame(state_right, data_R.data(), data_R.data());
if (enable_vad) {
if (vad_prob_right >= vad_thres) {
vad_grace_right = release;
}
if (vad_grace_right >= 0) {
--vad_grace_right;
for (size_t i = 0U; i < data_R.size(); i++) {
data_R[i] = data_R[i] * wet_ratio + data_tmp[i] * (1.0F - wet_ratio);
data_R[i] *= inv_short_max;
}
} else {
std::ranges::for_each(data_R, [&](auto& v) { v = 0.0F; });
}
} else {
for (size_t i = 0U; i < data_R.size(); i++) {
data_R[i] = data_R[i] * wet_ratio + data_tmp[i] * (1.0F - wet_ratio);
data_R[i] *= inv_short_max;
}
}
}
for (const auto& v : data_R) {
out_R.push_back(v);
}
data_R.resize(0U);
}
}
}
#endif
};
| 5,699
|
C++
|
.h
| 159
| 28.930818
| 96
| 0.586339
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,823
|
maximizer_ui.hpp
|
wwmm_easyeffects/include/maximizer_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "maximizer.hpp"
namespace ui::maximizer_box {
G_BEGIN_DECLS
#define EE_TYPE_MAXIMIZER_BOX (maximizer_box_get_type())
G_DECLARE_FINAL_TYPE(MaximizerBox, maximizer_box, EE, MAXIMIZER_BOX, GtkBox)
G_END_DECLS
auto create() -> MaximizerBox*;
void setup(MaximizerBox* self, std::shared_ptr<Maximizer> maximizer, const std::string& schema_path);
} // namespace ui::maximizer_box
| 1,289
|
C++
|
.h
| 34
| 36.117647
| 101
| 0.75743
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,824
|
filter_preset.hpp
|
wwmm_easyeffects/include/filter_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class FilterPreset : public PluginPresetBase {
public:
explicit FilterPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,099
|
C++
|
.h
| 29
| 35.862069
| 73
| 0.755869
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,825
|
presets_autoloading_holder.hpp
|
wwmm_easyeffects/include/presets_autoloading_holder.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <glib-object.h>
#include <glibconfig.h>
#include <string>
namespace ui::holders {
G_BEGIN_DECLS
#define EE_TYPE_PRESETS_AUTOLOADING_HOLDER (presets_autoloading_holder_get_type())
G_DECLARE_FINAL_TYPE(PresetsAutoloadingHolder, presets_autoloading_holder, EE, PRESETS_AUTOLOADING_HOLDER, GObject)
G_END_DECLS
struct PresetsAutoLoadingData {
public:
std::string device, device_description, device_profile, preset_name;
};
struct _PresetsAutoloadingHolder {
GObject parent_instance;
PresetsAutoLoadingData* data;
};
auto create(const std::string& device,
const std::string& device_description,
const std::string& device_profile,
const std::string& preset_name) -> PresetsAutoloadingHolder*;
} // namespace ui::holders
| 1,544
|
C++
|
.h
| 40
| 35.825
| 115
| 0.757535
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,826
|
multiband_gate_preset.hpp
|
wwmm_easyeffects/include/multiband_gate_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <sys/types.h>
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
#include "tags_multiband_gate.hpp"
class MultibandGatePreset : public PluginPresetBase {
public:
explicit MultibandGatePreset(PresetType preset_type, const int& index = 0);
private:
static constexpr uint n_bands = tags::multiband_gate::n_bands;
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,237
|
C++
|
.h
| 32
| 36.625
| 77
| 0.758966
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,827
|
crystalizer_preset.hpp
|
wwmm_easyeffects/include/crystalizer_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class CrystalizerPreset : public PluginPresetBase {
public:
explicit CrystalizerPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,109
|
C++
|
.h
| 29
| 36.206897
| 75
| 0.75814
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,828
|
rnnoise_ui.hpp
|
wwmm_easyeffects/include/rnnoise_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "application.hpp"
#include "rnnoise.hpp"
namespace ui::rnnoise_box {
G_BEGIN_DECLS
#define EE_TYPE_RNNOISE_BOX (rnnoise_box_get_type())
G_DECLARE_FINAL_TYPE(RNNoiseBox, rnnoise_box, EE, RNNOISE_BOX, GtkBox)
G_END_DECLS
auto create() -> RNNoiseBox*;
void setup(RNNoiseBox* self,
std::shared_ptr<RNNoise> rnnoise,
const std::string& schema_path,
app::Application* application);
} // namespace ui::rnnoise_box
| 1,356
|
C++
|
.h
| 38
| 33.105263
| 73
| 0.737768
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,829
|
limiter_ui.hpp
|
wwmm_easyeffects/include/limiter_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "limiter.hpp"
#include "pipe_manager.hpp"
namespace ui::limiter_box {
G_BEGIN_DECLS
#define EE_TYPE_LIMITER_BOX (limiter_box_get_type())
G_DECLARE_FINAL_TYPE(LimiterBox, limiter_box, EE, LIMITER_BOX, GtkBox)
G_END_DECLS
auto create() -> LimiterBox*;
void setup(LimiterBox* self, std::shared_ptr<Limiter> limiter, const std::string& schema_path, PipeManager* pm);
} // namespace ui::limiter_box
| 1,310
|
C++
|
.h
| 35
| 35.657143
| 112
| 0.75336
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,830
|
stereo_tools_preset.hpp
|
wwmm_easyeffects/include/stereo_tools_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class StereoToolsPreset : public PluginPresetBase {
public:
explicit StereoToolsPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,109
|
C++
|
.h
| 29
| 36.206897
| 75
| 0.75814
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,831
|
multiband_gate.hpp
|
wwmm_easyeffects/include/multiband_gate.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <gio/gio.h>
#include <glib-object.h>
#include <glib.h>
#include <pipewire/proxy.h>
#include <sigc++/signal.h>
#include <sys/types.h>
#include <array>
#include <cstddef>
#include <span>
#include <string>
#include <utility>
#include <vector>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
#include "tags_multiband_gate.hpp"
class MultibandGate : public PluginBase {
public:
MultibandGate(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
MultibandGate(const MultibandGate&) = delete;
auto operator=(const MultibandGate&) -> MultibandGate& = delete;
MultibandGate(const MultibandGate&&) = delete;
auto operator=(const MultibandGate&&) -> MultibandGate& = delete;
~MultibandGate() override;
static constexpr uint n_bands = tags::multiband_gate::n_bands;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out,
std::span<float>& probe_left,
std::span<float>& probe_right) override;
auto get_latency_seconds() -> float override;
void update_probe_links() override;
sigc::signal<void(const std::array<float, n_bands>)> reduction, envelope, curve, frequency_range;
float latency_port_value = 0.0F;
std::array<float, n_bands> frequency_range_end_port_array = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
std::array<float, n_bands> envelope_port_array = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
std::array<float, n_bands> curve_port_array = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
std::array<float, n_bands> reduction_port_array = {0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F};
private:
uint latency_n_frames = 0U;
std::vector<pw_proxy*> list_proxies;
void update_sidechain_links(const std::string& key);
template <size_t n>
constexpr void bind_band() {
using namespace tags::multiband_gate;
using namespace std::string_literals;
if (n > 0U) {
lv2_wrapper->bind_key_bool<cbe[n], band_enable[n]>(settings);
lv2_wrapper->bind_key_double<sf[n], band_split_frequency[n]>(settings);
}
lv2_wrapper->bind_key_bool<ce[n], band_gate_enable[n]>(settings);
lv2_wrapper->bind_key_bool<bs[n], band_solo[n]>(settings);
lv2_wrapper->bind_key_bool<bm[n], band_mute[n]>(settings);
lv2_wrapper->bind_key_bool<gh[n], band_hysteresis[n]>(settings);
lv2_wrapper->bind_key_bool<sce[n], band_external_sidechain[n]>(settings);
lv2_wrapper->bind_key_bool<sclc[n], band_lowcut_filter[n]>(settings);
lv2_wrapper->bind_key_bool<schc[n], band_highcut_filter[n]>(settings);
lv2_wrapper->bind_key_enum<sscs[n], band_stereo_split_source[n]>(settings);
lv2_wrapper->bind_key_enum<scs[n], band_sidechain_source[n]>(settings);
lv2_wrapper->bind_key_enum<scm[n], band_sidechain_mode[n]>(settings);
lv2_wrapper->bind_key_double<at[n], band_attack_time[n]>(settings);
lv2_wrapper->bind_key_double<rt[n], band_release_time[n]>(settings);
lv2_wrapper->bind_key_double<sclf[n], band_lowcut_filter_frequency[n]>(settings);
lv2_wrapper->bind_key_double<schf[n], band_highcut_filter_frequency[n]>(settings);
lv2_wrapper->bind_key_double<sla[n], band_sidechain_lookahead[n]>(settings);
lv2_wrapper->bind_key_double<scr[n], band_sidechain_reactivity[n]>(settings);
lv2_wrapper->bind_key_double_db<ht[n], band_hysteresis_threshold[n]>(settings);
lv2_wrapper->bind_key_double_db<hz[n], band_hysteresis_zone[n]>(settings);
lv2_wrapper->bind_key_double_db<gt[n], band_curve_threshold[n]>(settings);
lv2_wrapper->bind_key_double_db<gz[n], band_curve_zone[n]>(settings);
lv2_wrapper->bind_key_double_db<gr[n], band_reduction[n]>(settings);
lv2_wrapper->bind_key_double_db<mk[n], band_makeup[n]>(settings);
lv2_wrapper->bind_key_double_db<scp[n], band_sidechain_preamp[n]>(settings);
gconnections.push_back(g_signal_connect(settings, ("changed::"s + band_external_sidechain[n].data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<MultibandGate*>(user_data);
self->update_sidechain_links(key);
}),
this));
}
template <size_t... Ns>
constexpr void bind_bands(std::index_sequence<Ns...> /*unused*/) {
(bind_band<Ns>(), ...);
}
};
| 5,478
|
C++
|
.h
| 109
| 43.880734
| 113
| 0.661366
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,832
|
convolver_preset.hpp
|
wwmm_easyeffects/include/convolver_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class ConvolverPreset : public PluginPresetBase {
public:
explicit ConvolverPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,105
|
C++
|
.h
| 29
| 36.068966
| 73
| 0.757236
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,833
|
echo_canceller_ui.hpp
|
wwmm_easyeffects/include/echo_canceller_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "echo_canceller.hpp"
namespace ui::echo_canceller_box {
G_BEGIN_DECLS
#define EE_TYPE_ECHO_CANCELLER_BOX (echo_canceller_box_get_type())
G_DECLARE_FINAL_TYPE(EchoCancellerBox, echo_canceller_box, EE, ECHO_CANCELLER_BOX, GtkBox)
G_END_DECLS
auto create() -> EchoCancellerBox*;
void setup(EchoCancellerBox* self, std::shared_ptr<EchoCanceller> echo_canceller, const std::string& schema_path);
} // namespace ui::echo_canceller_box
| 1,345
|
C++
|
.h
| 34
| 37.764706
| 114
| 0.761722
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,834
|
crystalizer.hpp
|
wwmm_easyeffects/include/crystalizer.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <sys/types.h>
#include <algorithm>
#include <array>
#include <deque>
#include <memory>
#include <span>
#include <string>
#include <vector>
#include "fir_filter_base.hpp"
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Crystalizer : public PluginBase {
public:
Crystalizer(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Crystalizer(const Crystalizer&) = delete;
auto operator=(const Crystalizer&) -> Crystalizer& = delete;
Crystalizer(const Crystalizer&&) = delete;
auto operator=(const Crystalizer&&) -> Crystalizer& = delete;
~Crystalizer() override;
auto get_latency() const -> float;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
private:
bool n_samples_is_power_of_2 = true;
bool filters_are_ready = false;
bool notify_latency = false;
bool do_first_rotation = true;
uint blocksize = 512U;
uint latency_n_frames = 0U;
static constexpr uint nbands = 13U;
std::vector<float> data_L;
std::vector<float> data_R;
std::array<bool, nbands> band_mute;
std::array<bool, nbands> band_bypass;
std::array<float, nbands + 1U> frequencies;
std::array<float, nbands> band_intensity;
std::array<float, nbands> band_last_L;
std::array<float, nbands> band_last_R;
std::array<float, nbands> band_next_L;
std::array<float, nbands> band_next_R;
std::array<std::vector<float>, nbands> band_data_L;
std::array<std::vector<float>, nbands> band_data_R;
std::array<std::vector<float>, nbands> band_gain;
std::array<std::vector<float>, nbands> band_second_derivative_L;
std::array<std::vector<float>, nbands> band_second_derivative_R;
std::array<std::unique_ptr<FirFilterBase>, nbands> filters;
std::deque<float> deque_out_L, deque_out_R;
void bind_band(const int& n);
template <typename T1>
void enhance_peaks(T1& data_left, T1& data_right) {
for (uint n = 0U; n < nbands; n++) {
std::copy(data_left.begin(), data_left.end(), band_data_L.at(n).begin());
std::copy(data_right.begin(), data_right.end(), band_data_R.at(n).begin());
filters.at(n)->process(band_data_L.at(n), band_data_R.at(n));
/*
Later we will need to calculate the second derivative of each band. This
is done through the central difference method. In order to calculate
the derivative at the last elements of the array we have to know the first
element of the next buffer. As we do not have this information the only
way to do this calculation is delaying the signal by 1 sample.
*/
// last (R,L) becomes the first
std::rotate(band_data_L.at(n).rbegin(), band_data_L.at(n).rbegin() + 1, band_data_L.at(n).rend());
std::rotate(band_data_R.at(n).rbegin(), band_data_R.at(n).rbegin() + 1, band_data_R.at(n).rend());
if (do_first_rotation) {
/*
band_data was rotated. Its first values are the last ones from the original array. we have to save them for
the next round.
*/
band_next_L.at(n) = band_data_L.at(n)[0];
band_next_R.at(n) = band_data_R.at(n)[0];
band_last_L.at(n) = 0.0F;
band_last_R.at(n) = 0.0F;
band_data_L.at(n)[0] = 0.0F;
band_data_R.at(n)[0] = 0.0F;
do_first_rotation = false;
} else {
/*
band_data was rotated. Its first values are the last ones from the original array. we have to save them for
the next round.
*/
const float L = band_data_L.at(n)[0];
const float R = band_data_R.at(n)[0];
band_data_L.at(n)[0] = band_next_L.at(n);
band_data_R.at(n)[0] = band_next_R.at(n);
band_next_L.at(n) = L;
band_next_R.at(n) = R;
}
}
for (uint n = 0U; n < nbands; n++) {
// Calculating the second derivative
if (!band_bypass.at(n)) {
for (uint m = 0U; m < blocksize; m++) {
const float L = band_data_L.at(n)[m];
const float R = band_data_R.at(n)[m];
if (m > 0U && m < blocksize - 1U) {
const float& L_lower = band_data_L.at(n)[m - 1U];
const float& R_lower = band_data_R.at(n)[m - 1U];
const float& L_upper = band_data_L.at(n)[m + 1U];
const float& R_upper = band_data_R.at(n)[m + 1U];
band_second_derivative_L.at(n)[m] = L_upper - 2.0F * L + L_lower;
band_second_derivative_R.at(n)[m] = R_upper - 2.0F * R + R_lower;
} else if (m == 0U) {
const float& L_lower = band_last_L.at(n);
const float& R_lower = band_last_R.at(n);
const float& L_upper = band_data_L.at(n)[m + 1U];
const float& R_upper = band_data_R.at(n)[m + 1U];
band_second_derivative_L.at(n)[m] = L_upper - 2.0F * L + L_lower;
band_second_derivative_R.at(n)[m] = R_upper - 2.0F * R + R_lower;
} else if (m == blocksize - 1U) {
const float& L_upper = band_next_L.at(n);
const float& R_upper = band_next_R.at(n);
const float& L_lower = band_data_L.at(n)[m - 1U];
const float& R_lower = band_data_R.at(n)[m - 1U];
band_second_derivative_L.at(n)[m] = L_upper - 2.0F * L + L_lower;
band_second_derivative_R.at(n)[m] = R_upper - 2.0F * R + R_lower;
}
}
// peak enhancing using second derivative
for (uint m = 0U; m < blocksize; m++) {
const float L = band_data_L.at(n)[m];
const float R = band_data_R.at(n)[m];
const float& d2L = band_second_derivative_L.at(n)[m];
const float& d2R = band_second_derivative_R.at(n)[m];
band_data_L.at(n)[m] = L - band_intensity.at(n) * d2L;
band_data_R.at(n)[m] = R - band_intensity.at(n) * d2R;
if (m == blocksize - 1U) {
band_last_L.at(n) = L;
band_last_R.at(n) = R;
}
}
} else {
band_last_L.at(n) = band_data_L.at(n)[blocksize - 1U];
band_last_R.at(n) = band_data_R.at(n)[blocksize - 1U];
}
}
// add bands
for (uint m = 0U; m < blocksize; m++) {
data_left[m] = 0.0F;
data_right[m] = 0.0F;
for (uint n = 0U; n < nbands; n++) {
if (!band_mute.at(n)) {
data_left[m] += band_data_L.at(n)[m];
data_right[m] += band_data_R.at(n)[m];
}
}
}
}
};
| 7,466
|
C++
|
.h
| 176
| 35.346591
| 117
| 0.60011
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,835
|
loudness.hpp
|
wwmm_easyeffects/include/loudness.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <sys/types.h>
#include <span>
#include <string>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Loudness : public PluginBase {
public:
Loudness(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Loudness(const Loudness&) = delete;
auto operator=(const Loudness&) -> Loudness& = delete;
Loudness(const Loudness&&) = delete;
auto operator=(const Loudness&&) -> Loudness& = delete;
~Loudness() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
private:
uint latency_n_frames = 0U;
};
| 1,635
|
C++
|
.h
| 45
| 32.333333
| 73
| 0.699305
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,836
|
speex_ui.hpp
|
wwmm_easyeffects/include/speex_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "application.hpp"
#include "speex.hpp"
namespace ui::speex_box {
G_BEGIN_DECLS
#define EE_TYPE_SPEEX_BOX (speex_box_get_type())
G_DECLARE_FINAL_TYPE(SpeexBox, speex_box, EE, SPEEX_BOX, GtkBox)
G_END_DECLS
auto create() -> SpeexBox*;
void setup(SpeexBox* self, std::shared_ptr<Speex> speex, const std::string& schema_path, app::Application* application);
} // namespace ui::speex_box
| 1,299
|
C++
|
.h
| 35
| 35.342857
| 120
| 0.750399
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,837
|
rnnoise_preset.hpp
|
wwmm_easyeffects/include/rnnoise_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class RNNoisePreset : public PluginPresetBase {
public:
explicit RNNoisePreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,101
|
C++
|
.h
| 29
| 35.931034
| 73
| 0.756326
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,838
|
bass_enhancer_ui.hpp
|
wwmm_easyeffects/include/bass_enhancer_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "bass_enhancer.hpp"
namespace ui::bass_enhancer_box {
G_BEGIN_DECLS
#define EE_TYPE_BASS_ENHANCER_BOX (bass_enhancer_box_get_type())
G_DECLARE_FINAL_TYPE(BassEnhancerBox, bass_enhancer_box, EE, BASS_ENHANCER_BOX, GtkBox)
G_END_DECLS
auto create() -> BassEnhancerBox*;
void setup(BassEnhancerBox* self, std::shared_ptr<BassEnhancer> bass_enhancer, const std::string& schema_path);
} // namespace ui::bass_enhancer_box
| 1,333
|
C++
|
.h
| 34
| 37.411765
| 111
| 0.759503
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,839
|
stream_output_effects.hpp
|
wwmm_easyeffects/include/stream_output_effects.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "effects_base.hpp"
#include "pipe_manager.hpp"
#include "pipe_objects.hpp"
class StreamOutputEffects : public EffectsBase {
public:
StreamOutputEffects(PipeManager* pipe_manager);
StreamOutputEffects(const StreamOutputEffects&) = delete;
auto operator=(const StreamOutputEffects&) -> StreamOutputEffects& = delete;
StreamOutputEffects(const StreamOutputEffects&&) = delete;
auto operator=(const StreamOutputEffects&&) -> StreamOutputEffects& = delete;
~StreamOutputEffects() override;
void set_bypass(const bool& state);
private:
bool bypass = false;
void connect_filters(const bool& bypass = false);
void disconnect_filters();
auto apps_want_to_play() -> bool;
void on_app_added(NodeInfo node_info);
};
| 1,514
|
C++
|
.h
| 38
| 37.473684
| 79
| 0.761418
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,840
|
gate_preset.hpp
|
wwmm_easyeffects/include/gate_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class GatePreset : public PluginPresetBase {
public:
explicit GatePreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,095
|
C++
|
.h
| 29
| 35.724138
| 73
| 0.754948
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,841
|
plugins_box.hpp
|
wwmm_easyeffects/include/plugins_box.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtk.h>
#include "application.hpp"
#include "pipeline_type.hpp"
namespace ui::plugins_box {
G_BEGIN_DECLS
#define EE_TYPE_PLUGINS_BOX (plugins_box_get_type())
G_DECLARE_FINAL_TYPE(PluginsBox, plugins_box, EE, PLUGINS_BOX, GtkBox)
G_END_DECLS
auto create() -> PluginsBox*;
void setup(PluginsBox* self, app::Application* application, PipelineType pipeline_type);
} // namespace ui::plugins_box
| 1,231
|
C++
|
.h
| 32
| 36.625
| 88
| 0.756939
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,842
|
ladspa_wrapper.hpp
|
wwmm_easyeffects/include/ladspa_wrapper.hpp
|
/*
* Copyright © 2023 Torge Matthies
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <dlfcn.h>
#include <gio/gio.h>
#include <glib-object.h>
#include <glib.h>
#include <ladspa.h>
#include <sys/types.h>
#include <cmath>
#include <limits>
#include <span>
#include <string>
#include <tuple>
#include <unordered_map>
#include "string_literal_wrapper.hpp"
#include "util.hpp"
namespace ladspa {
using namespace std::string_literals;
class LadspaWrapper {
public:
LadspaWrapper(const std::string& plugin_filename, const std::string& plugin_label);
LadspaWrapper(const LadspaWrapper&) = delete;
auto operator=(const LadspaWrapper&) -> LadspaWrapper& = delete;
LadspaWrapper(const LadspaWrapper&&) = delete;
auto operator=(const LadspaWrapper&&) -> LadspaWrapper& = delete;
virtual ~LadspaWrapper();
auto create_instance(uint rate) -> bool;
void connect_data_ports(const std::span<const float>& left_in,
const std::span<const float>& right_in,
const std::span<float>& left_out,
const std::span<float>& right_out);
void connect_data_ports(const std::span<const float>& left_in,
const std::span<const float>& right_in,
const std::span<float>& left_out,
const std::span<float>& right_out,
const std::span<const float>& probe_left,
const std::span<const float>& probe_right);
void activate();
void deactivate();
void run() const;
[[nodiscard]] auto get_control_port_count() const -> uint;
[[nodiscard]] auto get_control_port_name(uint index) const -> std::string;
[[nodiscard]] auto is_control_port_output(uint index) const -> bool;
[[nodiscard]] auto get_control_port_range(uint index) const -> std::tuple<float, float>;
[[nodiscard]] auto get_control_port_default(uint index) const -> float;
[[nodiscard]] auto get_control_port_value(uint index) const -> float;
[[nodiscard]] auto get_control_port_value(const std::string& symbol) const -> float;
auto set_control_port_value_clamp(uint index, float value) -> float;
auto set_control_port_value_clamp(const std::string& symbol, float value) -> float;
[[nodiscard]] auto found_plugin() const -> bool { return found; }
[[nodiscard]] auto has_instance() const -> bool { return instance != nullptr; }
[[nodiscard]] auto get_rate() const -> uint { return rate; }
using genum = gint;
template <typename T>
void load_from_gsettings(GSettings* settings, const char* gkey, const char* port_name) {
float value = 0.0F;
if constexpr (std::is_same_v<T, double>) {
value = static_cast<float>(g_settings_get_double(settings, gkey));
} else if constexpr (std::is_same_v<T, int>) {
value = static_cast<float>(g_settings_get_int(settings, gkey));
} else if constexpr (std::is_same_v<T, bool>) {
value = static_cast<float>(g_settings_get_boolean(settings, gkey));
} else if constexpr (std::is_same_v<T, genum>) {
value = static_cast<float>(g_settings_get_enum(settings, gkey));
}
auto actual_value = set_control_port_value_clamp(port_name, value);
if (actual_value != value && !(std::isnan(actual_value) && std::isnan(value))) {
if constexpr (std::is_same_v<T, double>) {
g_settings_set_double(settings, gkey, static_cast<double>(actual_value));
} else if constexpr (std::is_same_v<T, int>) {
g_settings_set_int(settings, gkey, static_cast<int>(actual_value));
} else if constexpr (std::is_same_v<T, bool>) {
g_settings_set_boolean(settings, gkey, static_cast<gboolean>(actual_value));
} else if constexpr (std::is_same_v<T, genum>) {
g_settings_set_enum(settings, gkey, static_cast<genum>(actual_value));
}
}
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper>
void bind_key_bool(GSettings* settings) {
load_from_gsettings<bool>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
g_signal_connect(settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
self->load_from_gsettings<bool>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
}),
this);
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper>
void bind_key_enum(GSettings* settings) {
load_from_gsettings<genum>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
g_signal_connect(settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
self->load_from_gsettings<genum>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
}),
this);
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper>
void bind_key_int(GSettings* settings) {
load_from_gsettings<int>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
g_signal_connect(settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
self->load_from_gsettings<int>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
}),
this);
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper>
void bind_key_double(GSettings* settings) {
load_from_gsettings<double>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
g_signal_connect(settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
self->load_from_gsettings<double>(settings, gkey_wrapper.msg.data(), key_wrapper.msg.data());
}),
this);
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper, bool lower_bound = true>
void bind_key_double_db_exponential(GSettings* settings) {
const auto db_v = static_cast<float>(g_settings_get_double(settings, gkey_wrapper.msg.data()));
const auto clamped =
(!lower_bound && db_v <= util::minimum_db_level) ? -std::numeric_limits<float>::infinity() : db_v;
const auto new_v = set_control_port_value_clamp(key_wrapper.msg.data(), clamped);
// Update gsettings if the new value is valid and clamped/different from the original
if (new_v != clamped && !(std::isnan(new_v) && std::isnan(clamped))) {
g_settings_set_double(settings, gkey_wrapper.msg.data(), static_cast<gdouble>(new_v));
}
g_signal_connect(settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
const auto db_v = static_cast<float>(g_settings_get_double(settings, gkey_wrapper.msg.data()));
const auto clamped = (!lower_bound && db_v <= util::minimum_db_level)
? -std::numeric_limits<float>::infinity()
: db_v;
const auto new_v = self->set_control_port_value_clamp(key_wrapper.msg.data(), clamped);
// Update gsettings if the new value is valid and clamped/different from the original
if (new_v != clamped && !(std::isnan(new_v) && std::isnan(clamped)))
g_settings_set_double(settings, gkey_wrapper.msg.data(), static_cast<gdouble>(new_v));
}),
this);
}
template <StringLiteralWrapper key_wrapper, StringLiteralWrapper gkey_wrapper, bool lower_bound = true>
void bind_key_double_db(GSettings* settings) {
const auto db_v = static_cast<float>(g_settings_get_double(settings, gkey_wrapper.msg.data()));
const auto clamped_v = (!lower_bound && db_v <= util::minimum_db_level) ? 0.0F : util::db_to_linear(db_v);
const auto new_v = set_control_port_value_clamp(key_wrapper.msg.data(), clamped_v);
// Update gsettings if the new value is valid and clamped/different from the original
if (new_v != clamped_v && !(std::isnan(new_v) && std::isnan(clamped_v))) {
g_settings_set_double(settings, gkey_wrapper.msg.data(), static_cast<gdouble>(util::linear_to_db(new_v)));
}
g_signal_connect(
settings, ("changed::"s + gkey_wrapper.msg.data()).c_str(),
G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) {
auto* self = static_cast<LadspaWrapper*>(user_data);
const auto db_v = static_cast<float>(g_settings_get_double(settings, gkey_wrapper.msg.data()));
const auto clamped_v = (!lower_bound && db_v <= util::minimum_db_level) ? 0.0F : util::db_to_linear(db_v);
const auto new_v = self->set_control_port_value_clamp(key_wrapper.msg.data(), clamped_v);
// Update gsettings if the new value is valid and clamped/different from the original
if (new_v != clamped_v && !(std::isnan(new_v) && std::isnan(clamped_v)))
g_settings_set_double(settings, gkey_wrapper.msg.data(), static_cast<gdouble>(util::linear_to_db(new_v)));
}),
this);
}
uint n_samples = 0U;
private:
std::string plugin_name;
void* dl_handle = nullptr;
const LADSPA_Descriptor* descriptor = nullptr;
LADSPA_Handle instance = nullptr;
static constexpr unsigned long null_ul = (unsigned long)-1L;
bool found = false;
bool active = false;
uint rate = 0U;
LADSPA_Data* control_ports = nullptr;
bool* control_ports_initialized = nullptr;
std::unordered_map<std::string, unsigned long> map_cp_name_to_idx = std::unordered_map<std::string, unsigned long>();
};
} // namespace ladspa
| 11,090
|
C++
|
.h
| 196
| 47.964286
| 119
| 0.642303
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,843
|
echo_canceller.hpp
|
wwmm_easyeffects/include/echo_canceller.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <speex/speex_echo.h>
#include <climits>
#include <span>
#include <string>
#include <vector>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
#include <speex/speex_preprocess.h>
#include <speex/speexdsp_config_types.h>
#include <sys/types.h>
class EchoCanceller : public PluginBase {
public:
EchoCanceller(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
EchoCanceller(const EchoCanceller&) = delete;
auto operator=(const EchoCanceller&) -> EchoCanceller& = delete;
EchoCanceller(const EchoCanceller&&) = delete;
auto operator=(const EchoCanceller&&) -> EchoCanceller& = delete;
~EchoCanceller() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out,
std::span<float>& probe_left,
std::span<float>& probe_right) override;
auto get_latency_seconds() -> float override;
private:
bool notify_latency = false;
bool ready = false;
uint filter_length_ms = 100U;
uint latency_n_frames = 0U;
int residual_echo_suppression = -10;
int near_end_suppression = -10;
const float inv_short_max = 1.0F / (SHRT_MAX + 1.0F);
std::vector<spx_int16_t> data_L;
std::vector<spx_int16_t> data_R;
std::vector<spx_int16_t> probe_mono;
std::vector<spx_int16_t> filtered_L;
std::vector<spx_int16_t> filtered_R;
SpeexEchoState* echo_state_L = nullptr;
SpeexEchoState* echo_state_R = nullptr;
SpeexPreprocessState *state_left = nullptr, *state_right = nullptr;
void free_speex();
void init_speex();
};
| 2,551
|
C++
|
.h
| 68
| 33.191176
| 73
| 0.69923
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,844
|
tags_schema.hpp
|
wwmm_easyeffects/include/tags_schema.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
namespace tags::schema {
inline constexpr auto id_input = "com.github.wwmm.easyeffects.streaminputs";
inline constexpr auto id_output = "com.github.wwmm.easyeffects.streamoutputs";
} // namespace tags::schema
namespace tags::schema::autogain {
inline constexpr auto id = "com.github.wwmm.easyeffects.autogain";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/autogain/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/autogain/";
} // namespace tags::schema::autogain
namespace tags::schema::bass_enhancer {
inline constexpr auto id = "com.github.wwmm.easyeffects.bassenhancer";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/bassenhancer/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/bassenhancer/";
} // namespace tags::schema::bass_enhancer
namespace tags::schema::bass_loudness {
inline constexpr auto id = "com.github.wwmm.easyeffects.bassloudness";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/bassloudness/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/bassloudness/";
} // namespace tags::schema::bass_loudness
namespace tags::schema::compressor {
inline constexpr auto id = "com.github.wwmm.easyeffects.compressor";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/compressor/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/compressor/";
} // namespace tags::schema::compressor
namespace tags::schema::convolver {
inline constexpr auto id = "com.github.wwmm.easyeffects.convolver";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/convolver/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/convolver/";
} // namespace tags::schema::convolver
namespace tags::schema::crossfeed {
inline constexpr auto id = "com.github.wwmm.easyeffects.crossfeed";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/crossfeed/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/crossfeed/";
} // namespace tags::schema::crossfeed
namespace tags::schema::crystalizer {
inline constexpr auto id = "com.github.wwmm.easyeffects.crystalizer";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/crystalizer/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/crystalizer/";
} // namespace tags::schema::crystalizer
namespace tags::schema::deepfilternet {
inline constexpr auto id = "com.github.wwmm.easyeffects.deepfilternet";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/deepfilternet/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/deepfilternet/";
} // namespace tags::schema::deepfilternet
namespace tags::schema::deesser {
inline constexpr auto id = "com.github.wwmm.easyeffects.deesser";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/deesser/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/deesser/";
} // namespace tags::schema::deesser
namespace tags::schema::delay {
inline constexpr auto id = "com.github.wwmm.easyeffects.delay";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/delay/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/delay/";
} // namespace tags::schema::delay
namespace tags::schema::echo_canceller {
inline constexpr auto id = "com.github.wwmm.easyeffects.echocanceller";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/echocanceller/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/echocanceller/";
} // namespace tags::schema::echo_canceller
namespace tags::schema::equalizer {
inline constexpr auto id = "com.github.wwmm.easyeffects.equalizer";
inline constexpr auto channel_id = "com.github.wwmm.easyeffects.equalizer.channel";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/equalizer/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/equalizer/";
} // namespace tags::schema::equalizer
namespace tags::schema::exciter {
inline constexpr auto id = "com.github.wwmm.easyeffects.exciter";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/exciter/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/exciter/";
} // namespace tags::schema::exciter
namespace tags::schema::expander {
inline constexpr auto id = "com.github.wwmm.easyeffects.expander";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/expander/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/expander/";
} // namespace tags::schema::expander
namespace tags::schema::filter {
inline constexpr auto id = "com.github.wwmm.easyeffects.filter";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/filter/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/filter/";
} // namespace tags::schema::filter
namespace tags::schema::gate {
inline constexpr auto id = "com.github.wwmm.easyeffects.gate";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/gate/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/gate/";
} // namespace tags::schema::gate
namespace tags::schema::level_meter {
inline constexpr auto id = "com.github.wwmm.easyeffects.levelmeter";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/levelmeter/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/levelmeter/";
} // namespace tags::schema::level_meter
namespace tags::schema::limiter {
inline constexpr auto id = "com.github.wwmm.easyeffects.limiter";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/limiter/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/limiter/";
} // namespace tags::schema::limiter
namespace tags::schema::loudness {
inline constexpr auto id = "com.github.wwmm.easyeffects.loudness";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/loudness/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/loudness/";
} // namespace tags::schema::loudness
namespace tags::schema::maximizer {
inline constexpr auto id = "com.github.wwmm.easyeffects.maximizer";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/maximizer/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/maximizer/";
} // namespace tags::schema::maximizer
namespace tags::schema::multiband_compressor {
inline constexpr auto id = "com.github.wwmm.easyeffects.multibandcompressor";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/multibandcompressor/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/multibandcompressor/";
} // namespace tags::schema::multiband_compressor
namespace tags::schema::multiband_gate {
inline constexpr auto id = "com.github.wwmm.easyeffects.multibandgate";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/multibandgate/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/multibandgate/";
} // namespace tags::schema::multiband_gate
namespace tags::schema::output_level {
inline constexpr auto id = "com.github.wwmm.easyeffects.outputlevel";
} // namespace tags::schema::output_level
namespace tags::schema::pitch {
inline constexpr auto id = "com.github.wwmm.easyeffects.pitch";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/pitch/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/pitch/";
} // namespace tags::schema::pitch
namespace tags::schema::reverb {
inline constexpr auto id = "com.github.wwmm.easyeffects.reverb";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/reverb/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/reverb/";
} // namespace tags::schema::reverb
namespace tags::schema::rnnoise {
inline constexpr auto id = "com.github.wwmm.easyeffects.rnnoise";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/rnnoise/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/rnnoise/";
} // namespace tags::schema::rnnoise
namespace tags::schema::speex {
inline constexpr auto id = "com.github.wwmm.easyeffects.speex";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/speex/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/speex/";
} // namespace tags::schema::speex
namespace tags::schema::stereo_tools {
inline constexpr auto id = "com.github.wwmm.easyeffects.stereotools";
inline constexpr auto input_path = "/com/github/wwmm/easyeffects/streaminputs/stereotools/";
inline constexpr auto output_path = "/com/github/wwmm/easyeffects/streamoutputs/stereotools/";
} // namespace tags::schema::stereo_tools
namespace tags::schema::spectrum {
inline constexpr auto id = "com.github.wwmm.easyeffects.spectrum";
} // namespace tags::schema::spectrum
| 10,370
|
C++
|
.h
| 165
| 60.854545
| 102
| 0.793398
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,845
|
exciter_ui.hpp
|
wwmm_easyeffects/include/exciter_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "exciter.hpp"
namespace ui::exciter_box {
G_BEGIN_DECLS
#define EE_TYPE_EXCITER_BOX (exciter_box_get_type())
G_DECLARE_FINAL_TYPE(ExciterBox, exciter_box, EE, EXCITER_BOX, GtkBox)
G_END_DECLS
auto create() -> ExciterBox*;
void setup(ExciterBox* self, std::shared_ptr<Exciter> exciter, const std::string& schema_path);
} // namespace ui::exciter_box
| 1,265
|
C++
|
.h
| 34
| 35.411765
| 95
| 0.752662
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,846
|
level_meter.hpp
|
wwmm_easyeffects/include/level_meter.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <ebur128.h>
#include <sigc++/signal.h>
#include <sys/types.h>
#include <span>
#include <string>
#include <thread>
#include <vector>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class LevelMeter : public PluginBase {
public:
LevelMeter(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
LevelMeter(const LevelMeter&) = delete;
auto operator=(const LevelMeter&) -> LevelMeter& = delete;
LevelMeter(const LevelMeter&&) = delete;
auto operator=(const LevelMeter&&) -> LevelMeter& = delete;
~LevelMeter() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
void reset_history();
sigc::signal<void(const double, // momentary
const double, // shortterm
const double, // integrated
const double, // relative
const double, // range
const double, // true_peak_R
const double // true_peak_R
)>
results; // range
private:
bool ebur128_ready = false;
uint old_rate = 0U;
double momentary = 0.0;
double shortterm = 0.0;
double global = 0.0;
double relative = 0.0;
double range = 0.0;
double true_peak_L = 0.0;
double true_peak_R = 0.0;
std::vector<float> data;
ebur128_state* ebur_state = nullptr;
std::vector<std::thread> mythreads;
auto init_ebur128() -> bool;
};
| 2,501
|
C++
|
.h
| 71
| 29.633803
| 73
| 0.655758
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,847
|
exciter_preset.hpp
|
wwmm_easyeffects/include/exciter_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class ExciterPreset : public PluginPresetBase {
public:
explicit ExciterPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,101
|
C++
|
.h
| 29
| 35.931034
| 73
| 0.756326
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,848
|
chart.hpp
|
wwmm_easyeffects/include/chart.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <gdk/gdk.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkshortcut.h>
#include <string>
#include <vector>
namespace ui::chart {
G_BEGIN_DECLS
#define EE_TYPE_CHART (chart_get_type())
G_DECLARE_FINAL_TYPE(Chart, chart, EE, CHART, GtkWidget)
G_END_DECLS
enum class ChartType { bar, line, dots };
enum class ChartScale { linear, logarithmic };
void set_chart_type(Chart* self, const ChartType& value);
void set_chart_scale(Chart* self, const ChartScale& value);
void set_x_data(Chart* self, const std::vector<double>& x);
void set_y_data(Chart* self, const std::vector<double>& y);
void set_background_color(Chart* self, GdkRGBA color);
void set_color(Chart* self, GdkRGBA color);
void set_axis_labels_color(Chart* self, GdkRGBA color);
void set_line_width(Chart* self, const float& value);
void set_draw_bar_border(Chart* self, const bool& v);
void set_rounded_corners(Chart* self, const bool& v);
void set_fill_bars(Chart* self, const bool& v);
void set_n_x_decimals(Chart* self, const int& v);
void set_n_y_decimals(Chart* self, const int& v);
void set_x_unit(Chart* self, const std::string& value);
void set_y_unit(Chart* self, const std::string& value);
void set_margin(Chart* self, const float& v);
auto get_is_visible(Chart* self) -> bool;
void set_dynamic_y_scale(Chart* self, const bool& v);
auto create() -> Chart*;
} // namespace ui::chart
| 2,194
|
C++
|
.h
| 53
| 39.528302
| 73
| 0.744792
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,849
|
pipe_objects.hpp
|
wwmm_easyeffects/include/pipe_objects.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <pipewire/link.h>
#include <pipewire/node.h>
#include <pipewire/proxy.h>
#include <spa/param/param.h>
#include <spa/utils/defs.h>
#include <sys/types.h>
#include <cstdint>
#include <string>
struct NodeInfo {
pw_proxy* proxy = nullptr;
uint id = SPA_ID_INVALID;
uint device_id = SPA_ID_INVALID;
uint64_t serial = SPA_ID_INVALID;
std::string name;
std::string description;
std::string media_class;
std::string media_role;
std::string app_name;
std::string app_process_id;
std::string app_process_binary;
std::string app_icon_name;
std::string media_icon_name;
std::string device_icon_name;
std::string media_name;
std::string format;
std::string application_id;
int priority = -1;
pw_node_state state = PW_NODE_STATE_IDLE;
bool mute = false;
bool connected = false;
int n_input_ports = 0;
int n_output_ports = 0;
int rate = 1; // used as divisor to calculate latency, so do not initialize it as 0
uint n_volume_channels = 0U;
float latency = 0.0F;
float volume = 0.0F;
};
struct LinkInfo {
std::string path;
uint id = SPA_ID_INVALID;
uint input_node_id = 0U;
uint input_port_id = 0U;
uint output_node_id = 0U;
uint output_port_id = 0U;
uint64_t serial = SPA_ID_INVALID;
bool passive = false; // does not cause the graph to be runnable
pw_link_state state = PW_LINK_STATE_UNLINKED;
};
struct PortInfo {
std::string path;
std::string format_dsp;
std::string audio_channel;
std::string name;
std::string direction;
bool physical = false;
bool terminal = false;
bool monitor = false;
uint id = SPA_ID_INVALID;
uint node_id = 0U;
uint port_id = 0U;
uint64_t serial = SPA_ID_INVALID;
};
struct ModuleInfo {
uint id;
uint64_t serial = SPA_ID_INVALID;
std::string name;
std::string description;
std::string filename;
};
struct ClientInfo {
uint id;
uint64_t serial = SPA_ID_INVALID;
std::string name;
std::string access;
std::string api;
};
struct DeviceInfo {
uint id;
uint64_t serial = SPA_ID_INVALID;
std::string name;
std::string description;
std::string nick;
std::string media_class;
std::string api;
std::string input_route_name;
std::string output_route_name;
std::string bus_id;
std::string bus_path;
spa_param_availability input_route_available;
spa_param_availability output_route_available;
};
| 3,188
|
C++
|
.h
| 110
| 25.872727
| 86
| 0.723128
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,850
|
convolver_menu_impulses.hpp
|
wwmm_easyeffects/include/convolver_menu_impulses.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkpopover.h>
#include <sndfile.hh>
#include <string>
#include "application.hpp"
namespace ui::convolver_menu_impulses {
G_BEGIN_DECLS
#define EE_TYPE_CONVOLVER_MENU_IMPULSES (convolver_menu_impulses_get_type())
G_DECLARE_FINAL_TYPE(ConvolverMenuImpulses, convolver_menu_impulses, EE, CONVOLVER_MENU_IMPULSES, GtkPopover)
G_END_DECLS
auto create() -> ConvolverMenuImpulses*;
void setup(ConvolverMenuImpulses* self,
const std::string& schema_path,
app::Application* application,
std::shared_ptr<Convolver> convolver);
void append_to_string_list(ConvolverMenuImpulses* self, const std::string& irs_filename);
void remove_from_string_list(ConvolverMenuImpulses* self, const std::string& irs_filename);
} // namespace ui::convolver_menu_impulses
| 1,638
|
C++
|
.h
| 39
| 39.410256
| 109
| 0.761185
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,851
|
libportal.hpp
|
wwmm_easyeffects/include/libportal.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <gtk/gtk.h>
#include "libportal-gtk4/portal-gtk4.h"
#include "libportal/portal.h"
namespace libportal {
void init(GtkSwitch* g_enable_autostart, GtkSwitch* g_shutdown_on_window_close);
} // namespace libportal
| 990
|
C++
|
.h
| 25
| 37.76
| 80
| 0.756504
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,852
|
stereo_tools_ui.hpp
|
wwmm_easyeffects/include/stereo_tools_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "stereo_tools.hpp"
namespace ui::stereo_tools_box {
G_BEGIN_DECLS
#define EE_TYPE_STEREO_TOOLS_BOX (stereo_tools_box_get_type())
G_DECLARE_FINAL_TYPE(StereoToolsBox, stereo_tools_box, EE, STEREO_TOOLS_BOX, GtkBox)
G_END_DECLS
auto create() -> StereoToolsBox*;
void setup(StereoToolsBox* self, std::shared_ptr<StereoTools> stereo_tools, const std::string& schema_path);
} // namespace ui::stereo_tools_box
| 1,321
|
C++
|
.h
| 34
| 37.058824
| 108
| 0.757244
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,853
|
reverb_ui.hpp
|
wwmm_easyeffects/include/reverb_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "reverb.hpp"
namespace ui::reverb_box {
G_BEGIN_DECLS
#define EE_TYPE_REVERB_BOX (reverb_box_get_type())
G_DECLARE_FINAL_TYPE(ReverbBox, reverb_box, EE, REVERB_BOX, GtkBox)
G_END_DECLS
auto create() -> ReverbBox*;
void setup(ReverbBox* self, std::shared_ptr<Reverb> reverb, const std::string& schema_path);
} // namespace ui::reverb_box
| 1,253
|
C++
|
.h
| 34
| 35.058824
| 92
| 0.750207
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,854
|
expander_preset.hpp
|
wwmm_easyeffects/include/expander_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class ExpanderPreset : public PluginPresetBase {
public:
explicit ExpanderPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,103
|
C++
|
.h
| 29
| 36
| 73
| 0.756782
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,855
|
deepfilternet_ui.hpp
|
wwmm_easyeffects/include/deepfilternet_ui.hpp
|
/*
* Copyright © 2023 Torge Matthies
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "deepfilternet.hpp"
namespace ui::deepfilternet_box {
G_BEGIN_DECLS
#define EE_TYPE_DEEPFILTERNET_BOX (deepfilternet_box_get_type())
G_DECLARE_FINAL_TYPE(DeepFilterNetBox, deepfilternet_box, EE, DEEPFILTERNET_BOX, GtkBox)
G_END_DECLS
auto create() -> DeepFilterNetBox*;
void setup(DeepFilterNetBox* self, std::shared_ptr<DeepFilterNet> deepfilternet, const std::string& schema_path);
} // namespace ui::deepfilternet_box
| 1,328
|
C++
|
.h
| 34
| 37.264706
| 113
| 0.765576
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,856
|
fir_filter_highpass.hpp
|
wwmm_easyeffects/include/fir_filter_highpass.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include "fir_filter_base.hpp"
class FirFilterHighpass : public FirFilterBase {
public:
FirFilterHighpass(std::string tag);
FirFilterHighpass(const FirFilterHighpass&) = delete;
auto operator=(const FirFilterHighpass&) -> FirFilterHighpass& = delete;
FirFilterHighpass(const FirFilterHighpass&&) = delete;
auto operator=(const FirFilterHighpass&&) -> FirFilterHighpass& = delete;
~FirFilterHighpass() override;
void setup() override;
};
| 1,240
|
C++
|
.h
| 31
| 37.83871
| 75
| 0.760996
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,857
|
deepfilternet_preset.hpp
|
wwmm_easyeffects/include/deepfilternet_preset.hpp
|
/*
* Copyright © 2023 Torge Matthies
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class DeepFilterNetPreset : public PluginPresetBase {
public:
explicit DeepFilterNetPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,104
|
C++
|
.h
| 29
| 36.034483
| 77
| 0.757944
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,858
|
preset_type.hpp
|
wwmm_easyeffects/include/preset_type.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
enum class PresetType { input, output };
| 809
|
C++
|
.h
| 20
| 38.5
| 73
| 0.748412
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,859
|
multiband_compressor_ui.hpp
|
wwmm_easyeffects/include/multiband_compressor_ui.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <adwaita.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <memory>
#include <string>
#include "multiband_compressor.hpp"
#include "pipe_manager.hpp"
namespace ui::multiband_compressor_box {
G_BEGIN_DECLS
#define EE_TYPE_MULTIBAND_COMPRESSOR_BOX (multiband_compressor_box_get_type())
G_DECLARE_FINAL_TYPE(MultibandCompressorBox, multiband_compressor_box, EE, MULTIBAND_COMPRESSOR_BOX, GtkBox)
G_END_DECLS
auto create() -> MultibandCompressorBox*;
void setup(MultibandCompressorBox* self,
std::shared_ptr<MultibandCompressor> multiband_compressor,
const std::string& schema_path,
PipeManager* pm);
} // namespace ui::multiband_compressor_box
| 1,495
|
C++
|
.h
| 38
| 36.763158
| 108
| 0.75812
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,860
|
output_level.hpp
|
wwmm_easyeffects/include/output_level.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <span>
#include <string>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class OutputLevel : public PluginBase {
public:
OutputLevel(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
OutputLevel(const OutputLevel&) = delete;
auto operator=(const OutputLevel&) -> OutputLevel& = delete;
OutputLevel(const OutputLevel&&) = delete;
auto operator=(const OutputLevel&&) -> OutputLevel& = delete;
~OutputLevel() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
};
| 1,616
|
C++
|
.h
| 42
| 34.071429
| 73
| 0.699617
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,861
|
app_info.hpp
|
wwmm_easyeffects/include/app_info.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <STTypes.h>
#include <adwaita.h>
#include <fmt/core.h>
#include <gio/gio.h>
#include <glib-object.h>
#include <glibconfig.h>
#include <gtk/gtkbox.h>
#include <gtk/gtkicontheme.h>
#include <unordered_map>
#include "application.hpp"
#include "pipe_objects.hpp"
namespace ui::app_info {
G_BEGIN_DECLS
#define EE_TYPE_APP_INFO (app_info_get_type())
G_DECLARE_FINAL_TYPE(AppInfo, app_info, EE, APP_INFO, GtkBox)
G_END_DECLS
auto create() -> AppInfo*;
void setup(AppInfo* self,
app::Application* application,
GSettings* settings,
GtkIconTheme* icon_theme,
std::unordered_map<uint, bool>& enabled_app_list);
void update(AppInfo* self, NodeInfo node_info);
} // namespace ui::app_info
| 1,508
|
C++
|
.h
| 43
| 32.395349
| 73
| 0.731774
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,862
|
resampler.hpp
|
wwmm_easyeffects/include/resampler.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <samplerate.h>
#include <cmath>
#include <vector>
class Resampler {
public:
Resampler(const int& input_rate, const int& output_rate);
Resampler(const Resampler&) = delete;
auto operator=(const Resampler&) -> Resampler& = delete;
Resampler(const Resampler&&) = delete;
auto operator=(const Resampler&&) -> Resampler& = delete;
~Resampler();
template <typename T>
auto process(const T& input, const bool& end_of_input) -> const std::vector<float>& {
output.resize(std::ceil(1.5 * resample_ratio * input.size()));
// The number of frames of data pointed to by data_in
src_data.input_frames = input.size();
// A pointer to the input data samples
src_data.data_in = input.data();
// Maximum number of frames pointed to by data_out
src_data.output_frames = static_cast<long>(output.size());
// A pointer to the output data samples
src_data.data_out = output.data();
// Equal to output_sample_rate / input_sample_rate
src_data.src_ratio = resample_ratio;
// Equal to 0 if more input data is available and 1 otherwise
src_data.end_of_input = static_cast<int>(end_of_input);
src_process(src_state, &src_data);
output.resize(src_data.output_frames_gen);
return output;
}
private:
double resample_ratio = 1.0;
SRC_STATE* src_state = nullptr;
SRC_DATA src_data{};
std::vector<float> output;
};
| 2,166
|
C++
|
.h
| 55
| 36.090909
| 87
| 0.715377
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
24,863
|
speex.hpp
|
wwmm_easyeffects/include/speex.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <speex/speex_preprocess.h>
#include <speex/speexdsp_config_types.h>
#include <sys/types.h>
#include <climits>
#include <span>
#include <string>
#include <vector>
#include "pipe_manager.hpp"
#include "plugin_base.hpp"
class Speex : public PluginBase {
public:
Speex(const std::string& tag,
const std::string& schema,
const std::string& schema_path,
PipeManager* pipe_manager,
PipelineType pipe_type);
Speex(const Speex&) = delete;
auto operator=(const Speex&) -> Speex& = delete;
Speex(const Speex&&) = delete;
auto operator=(const Speex&&) -> Speex& = delete;
~Speex() override;
void setup() override;
void process(std::span<float>& left_in,
std::span<float>& right_in,
std::span<float>& left_out,
std::span<float>& right_out) override;
auto get_latency_seconds() -> float override;
private:
bool speex_ready = false;
int enable_denoise = 0, noise_suppression = -15, enable_agc = 0, enable_vad = 0, vad_probability_start = 95,
vad_probability_continue = 90, enable_dereverb = 0;
uint latency_n_frames = 0U;
const float inv_short_max = 1.0F / (SHRT_MAX + 1);
std::vector<spx_int16_t> data_L, data_R;
SpeexPreprocessState *state_left = nullptr, *state_right = nullptr;
void free_speex();
};
| 2,094
|
C++
|
.h
| 56
| 33.767857
| 110
| 0.701728
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,864
|
deesser_preset.hpp
|
wwmm_easyeffects/include/deesser_preset.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <nlohmann/json_fwd.hpp>
#include "plugin_preset_base.hpp"
#include "preset_type.hpp"
class DeesserPreset : public PluginPresetBase {
public:
explicit DeesserPreset(PresetType preset_type, const int& index = 0);
private:
void save(nlohmann::json& json) override;
void load(const nlohmann::json& json) override;
};
| 1,101
|
C++
|
.h
| 29
| 35.931034
| 73
| 0.756326
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,865
|
util.hpp
|
wwmm_easyeffects/include/util.hpp
|
/*
* Copyright © 2017-2024 Wellington Wallace
*
* This file is part of Easy Effects.
*
* Easy Effects 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.
*
* Easy Effects 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 Easy Effects. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <gdk/gdk.h>
#include <gio/gio.h>
#include <gio/gsettingsschema.h>
#include <glib-object.h>
#include <glib.h>
#include <sys/types.h>
#include <array>
#include <charconv>
#include <cmath>
#include <cstdlib>
#include <filesystem>
#include <functional>
#include <limits>
#include <source_location>
#include <string>
#include <system_error>
#include <type_traits>
#include <utility>
#include <vector>
namespace util {
// Minimum dB level reported here has to be used in gsettings and spinbuttons
// as minimal values for controls that replicates the -infinity state (linear 0).
constexpr float minimum_db_level = -100.0F;
constexpr double minimum_db_d_level = -100.0;
constexpr float minimum_linear_level = 0.00001F;
constexpr double minimum_linear_d_level = 0.00001;
using source_location = std::source_location;
void debug(const std::string& s, source_location location = source_location::current());
void error(const std::string& s, source_location location = source_location::current());
void critical(const std::string& s, source_location location = source_location::current());
void warning(const std::string& s, source_location location = source_location::current());
void info(const std::string& s, source_location location = source_location::current());
auto normalize(const double& x, const double& max, const double& min = 1.0) -> double;
auto linear_to_db(const float& amp) -> float;
auto linear_to_db(const double& amp) -> double;
auto db_to_linear(const float& db) -> float;
auto db_to_linear(const double& db) -> double;
auto db20_gain_to_linear(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto linear_gain_to_db20(const GValue* value, const GVariantType* expected_type, gpointer user_data) -> GVariant*;
auto db10_gain_to_linear(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto double_to_float(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto db20_gain_to_linear_double(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto linear_double_gain_to_db20(const GValue* value, const GVariantType* expected_type, gpointer user_data)
-> GVariant*;
auto double_x10_to_int(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto ms_to_ns(GValue* value, GVariant* variant, gpointer user_data) -> gboolean;
auto remove_filename_extension(const std::string& basename) -> std::string;
void print_thread_id();
auto gchar_array_to_vector(gchar** gchar_array, bool free_data = true) -> std::vector<std::string>;
auto make_gchar_pointer_vector(const std::vector<std::string>& input) -> std::vector<const gchar*>;
auto gsettings_get_color(GSettings* settings, const char* key) -> GdkRGBA;
auto gsettings_get_string(GSettings* settings, const char* key) -> std::string;
auto gsettings_get_range(GSettings* settings, const char* key) -> std::pair<std::string, std::string>;
auto add_new_blocklist_entry(GSettings* settings, const std::string& name) -> bool;
void remove_blocklist_entry(GSettings* settings, const std::string& name);
void idle_add(
std::function<void()> cb,
std::function<void()> cleanup_cb = []() {});
auto get_files_name(const std::filesystem::path& dir_path, const std::string& ext) -> std::vector<std::string>;
void reset_all_keys_except(GSettings* settings,
const std::vector<std::string>& blocklist = std::vector<std::string>(),
bool delay = false);
auto str_contains(const std::string& haystack, const std::string& needle) -> bool;
auto compare_versions(const std::string& v0, const std::string& v1) -> int;
void str_trim_start(std::string& str);
void str_trim_end(std::string& str);
void str_trim(std::string& str);
auto search_filename(const std::filesystem::path& path,
const std::string& filename,
std::string& full_path_result,
const uint& top_scan_level = std::numeric_limits<uint>::max()) -> bool;
template <typename T>
void print_type(T v) {
warning(typeid(v).name());
}
template <typename T>
auto str_to_num(const std::string& str, T& num) -> bool {
// This is a more robust implementation of `std::from_chars`
// so that we don't have to do every time with `std::from_chars_result` structure.
// We don't care of error types, so a simple bool is returned on success/fail.
// A left trim is performed on strings so that the conversion could success
// even if there are leading whitespaces and/or the plus sign.
auto first_char = str.find_first_not_of(" +\n\r\t\v\f");
if (first_char == std::string::npos) {
return false;
}
#ifndef ENABLE_LIBCPP_WORKAROUNDS
const auto result = std::from_chars(str.data() + first_char, str.data() + str.size(), num);
return (result.ec == std::errc());
#else
if constexpr (std::is_floating_point_v<T>) {
char* endp = nullptr;
/* we're asking for C locale which is preallocated, so no alloc here */
auto loc = newlocale(LC_ALL_MASK, "C", nullptr);
if constexpr (std::is_same_v<T, float>) {
num = strtof_l(str.data() + first_char, &endp, loc);
} else {
num = strtod_l(str.data() + first_char, &endp, loc);
}
/* we gotta "free" it anyway */
freelocale(loc);
return (endp && !*endp && (endp != (str.data() + first_char)));
} else {
const auto result = std::from_chars(str.data() + first_char, str.data() + str.size(), num);
return (result.ec == std::errc());
}
#endif
}
template <typename T>
auto to_string(const T& num, const std::string def = "0") -> std::string {
// This is used to replace `std::to_string` as a locale independent
// number conversion using `std::to_chars`.
// An additional string parameter could be eventually provided with a
// default value to return in case the conversion fails.
// Max buffer length:
// number of base-10 digits that can be represented by the type T without change +
// number of base-10 digits that are necessary to uniquely represent all distinct
// values of the type T (meaningful only for real numbers) +
// room for other characters such as "+-e,."
const size_t max = std::numeric_limits<T>::digits10 + std::numeric_limits<T>::max_digits10 + 10U;
std::array<char, max> buffer;
const auto p_init = buffer.data();
const auto result = std::to_chars(p_init, p_init + max, num);
return (result.ec == std::errc()) ? std::string(p_init, result.ptr - p_init) : def;
}
template <class T>
concept Number = std::is_integral_v<T> || std::is_floating_point_v<T>;
template <Number T>
auto logspace(const T& start, const T& stop, const uint& npoints) -> std::vector<T> {
std::vector<T> output;
if (stop <= start || npoints < 2) {
return output;
}
auto log10_start = std::log10(start);
auto log10_stop = std::log10(stop);
const T delta = (log10_stop - log10_start) / static_cast<T>(npoints - 1);
output.push_back(start);
T v = log10_start;
while (output.size() < npoints - 1) {
v += delta;
if constexpr (std::is_same_v<T, float>) {
output.push_back(std::pow(10.0F, v));
} else {
output.push_back(std::pow(10.0, v));
}
}
output.push_back(stop);
return output;
}
template <Number T>
auto linspace(const T& start, const T& stop, const uint& npoints) -> std::vector<T> {
std::vector<T> output;
if (stop <= start || npoints < 2) {
return output;
}
const T delta = (stop - start) / static_cast<T>(npoints - 1);
output.push_back(start);
T v = start;
while (output.size() < npoints - 1) {
v += delta;
output.push_back(v);
}
output.push_back(stop);
return output;
}
// The following is not used and it was made only for reference. May be removed in the future.
template <Number T>
auto gsettings_key_check_number_range(GSettings* settings, const char* key, const T& v) -> bool {
GSettingsSchema* schema = nullptr;
GVariant* g_value = nullptr;
// Get GSettingsSchema
g_object_get(settings, "settings-schema", &schema, nullptr);
auto* schema_key = g_settings_schema_get_key(schema, key);
// Get GVariant
if constexpr (std::is_same_v<T, double>) {
g_value = g_variant_new_double(v);
} else if constexpr (std::is_same_v<T, int>) {
g_value = g_variant_new_int32(v);
}
if (g_value == nullptr) {
return false;
}
const auto is_in_range = g_settings_schema_key_range_check(schema_key, g_value);
g_variant_unref(g_value);
g_settings_schema_unref(schema);
return is_in_range != 0;
}
} // namespace util
| 9,306
|
C++
|
.h
| 207
| 41.657005
| 114
| 0.700499
|
wwmm/easyeffects
| 6,414
| 268
| 211
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,890
|
SessionDataSource.h
|
BlueMatthew_WechatExporter/WechatExporter/SessionDataSource.h
|
//
// SessionDataSource.h
// WechatExporter
//
// Created by Matthew on 2021/2/1.
// Copyright © 2021 Matthew. All rights reserved.
//
#ifndef SessionDataSource_h
#define SessionDataSource_h
#import <Cocoa/Cocoa.h>
#include <vector>
#include <set>
#include <utility>
#import "WechatObjects.h"
@interface SessionItem : NSObject
@property (assign) NSInteger orgIndex;
@property (assign) NSInteger userIndex;
@property (assign) BOOL checked;
@property (strong) NSString *sessionUsrName;
@property (strong) NSString *displayName;
@property (assign) NSInteger recordCount;
@property (strong) NSString *userDisplayName;
@property (strong) NSString *usrName;
// @property (assign) NSInteger userPointer;
// @property (assign) NSInteger sessionPointer;
// - (NSComparisonResult)orgIndexCompare:(SessionItem *)sessionItem:(BOOL)ascending;
- (NSComparisonResult)displayNameCompare:(SessionItem *)sessionItem ascending:(BOOL)ascending;
- (NSComparisonResult)recordCountCompare:(SessionItem *)sessionItem ascending:(BOOL)ascending;
- (NSComparisonResult)userIndexCompare:(SessionItem *)sessionItem ascending:(BOOL)ascending;
@end
@interface SessionDataSource : NSObject<NSTableViewDataSource>
- (void)loadData:(const std::vector<std::pair<Friend, std::vector<Session>>> *)usersAndSessions withAllUsers:(BOOL)allUsers indexOfSelectedUser:(NSInteger)indexOfSelectedUser;
- (void)getSelectedUserAndSessions:(std::map<std::string, std::map<std::string, void *>>&)usersAndSessions;
- (void)bindCellView:(NSTableCellView *)cellView atRow:(NSInteger)row andColumnId:(NSString *)identifier;
- (NSControlStateValue)updateCheckStateAtRow:(NSInteger)row;
- (void)checkAllSessions:(BOOL)checked;
@end
#endif /* SessionDataSource_h */
| 1,728
|
C++
|
.h
| 38
| 44.131579
| 175
| 0.806202
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,892
|
AppConfiguration.h
|
BlueMatthew_WechatExporter/WechatExporter/AppConfiguration.h
|
//
// AppConfiguration.h
// WechatExporter
//
// Created by Matthew on 2021/3/18.
// Copyright © 2021 Matthew. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef NS_ENUM(NSInteger, OUTPUT_FORMAT)
{
OUTPUT_FORMAT_HTML = 0,
OUTPUT_FORMAT_TEXT,
OUTPUT_FORMAT_PDF,
OUTPUT_FORMAT_LAST
};
@interface AppConfiguration : NSObject
+ (void)setDescOrder:(BOOL)descOrder;
+ (BOOL)getDescOrder;
+ (BOOL)IsPdfSupported;
+ (NSInteger)getOutputFormat;
+ (BOOL)isHtmlMode;
+ (BOOL)isTextMode;
+ (BOOL)isPdfMode;
+ (void)setOutputFormat:(NSInteger)outputFormat;
+ (void)setSavingInSession:(BOOL)savingInSession;
+ (BOOL)getSavingInSession;
+ (void)setAsyncLoading:(BOOL)asyncLoading;
+ (BOOL)getAsyncLoading;
+ (void)setIncrementalExporting:(BOOL)incrementalExp;
+ (BOOL)getIncrementalExporting;
+ (void)setLastOutputDir:(NSString *)outputDir;
+ (NSString *)getLastOrDefaultOutputDir;
+ (NSString *)getDefaultOutputDir;
+ (void)setLastBackupDir:(NSString *)backupDir;
+ (NSString *)getLastBackupDir;
+ (NSString *)getDefaultBackupDir:(BOOL)checkExistence; // YES
+ (NSInteger)getLastCheckUpdateTime;
+ (void)setLastCheckUpdateTime;
+ (void)setLastCheckUpdateTime:(NSInteger)lastCheckUpdateTime;
+ (void)setCheckingUpdateDisabled:(BOOL)disabled;
+ (BOOL)isCheckingUpdateDisabled;
+ (void)setLoadingDataOnScroll; // YES
+ (void)setLoadingDataOnScroll:(BOOL)loadingDataOnScroll;
+ (BOOL)getLoadingDataOnScroll;
+ (void)setSupportingFilter:(BOOL)supportingFilter;
+ (BOOL)getSupportingFilter;
@end
NS_ASSUME_NONNULL_END
| 1,577
|
C++
|
.h
| 49
| 30.469388
| 62
| 0.799205
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,893
|
ViewController.h
|
BlueMatthew_WechatExporter/WechatExporter/ViewController.h
|
//
// ViewController.h
// WechatExporter
//
// Created by Matthew on 2020/9/29.
// Copyright © 2020 Matthew. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface ViewController : NSViewController
@property (weak) IBOutlet NSTextField *lblITunes;
@property (weak) IBOutlet NSButton *btnExport;
@property (weak) IBOutlet NSButton *btnCancel;
@property (weak) IBOutlet NSButton *btnQuit;
@property (weak) IBOutlet NSTextField *txtboxOutput;
@property (weak) IBOutlet NSPopUpButton *popupBackup;
@property (weak) IBOutlet NSPopUpButton *popupUsers;
@property (weak) IBOutlet NSButton *btnToggleAll;
@property (weak) IBOutlet NSScrollView *sclSessions;
@property (weak) IBOutlet NSTableView *tblSessions;
@property (weak) IBOutlet NSButton *btnBackup;
@property (weak) IBOutlet NSButton *btnOutput;
@property (weak) IBOutlet NSProgressIndicator *progressBar;
@property (weak) IBOutlet NSScrollView *sclViewLogs;
@property (unsafe_unretained) IBOutlet NSTextView *txtViewLogs;
- (void)writeLog:(NSString *)log;
- (void)onStart;
- (void)onComplete:(BOOL)cancelled;
@end
| 1,083
|
C++
|
.h
| 28
| 37.357143
| 63
| 0.799235
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,894
|
HttpHelper.h
|
BlueMatthew_WechatExporter/WechatExporter/HttpHelper.h
|
//
// HttpHelper.h
// WechatExporter
//
// Created by Matthew on 2021/3/9.
// Copyright © 2021 Matthew. All rights reserved.
//
#ifndef HttpHelper_h
#define HttpHelper_h
#import <Foundation/Foundation.h>
@interface HttpHelper : NSObject
+ (NSString *)standardUserAgent;
@end
#endif /* HttpHelper_h */
| 312
|
C++
|
.h
| 14
| 20.857143
| 51
| 0.75
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,896
|
PdfConverterImpl.h
|
BlueMatthew_WechatExporter/WechatExporter/PdfConverterImpl.h
|
//
// PdfConverterImpl.h
// WechatExporter
//
// Created by Matthew on 2021/4/22.
// Copyright © 2021 Matthew. All rights reserved.
//
#include "PdfConverter.h"
#import <Cocoa/Cocoa.h>
#include "FileSystem.h"
#include "Utils.h"
#ifndef PdfConverterImpl_h
#define PdfConverterImpl_h
class PdfConverterImpl : public PdfConverter
{
public:
PdfConverterImpl(const char *outputDir) : m_pdfSupported(false)
{
if (detectChromeInstalled())
{
m_pdfSupported = true;
m_param = @[@"--headless", @"--disable-extensions", @"--disable-gpu", @"--print-to-pdf-no-header"];
// m_param = "--headless --disable-extensions --disable-gpu --print-to-pdf=\"%%DEST%%\" --print-to-pdf-no-header \"file://%%SRC%%\"";
}
else if (detectEdgeInstalled())
{
m_pdfSupported = true;
// m_param = @[@"--headless", @"--disable-extensions", @"--disable-gpu", @"--print-to-pdf-no-header"];
m_param = @[@"--headless", @"--print-to-pdf-no-header"];
}
if (NULL != outputDir)
{
initShellFile(outputDir);
}
}
bool isPdfSupported() const
{
return m_pdfSupported;
}
~PdfConverterImpl()
{
}
void executeCommand()
{
NSString *shellPathString = [NSString stringWithUTF8String:m_shellPath.c_str()];
if (![[NSFileManager defaultManager] fileExistsAtPath:shellPathString])
{
return;
}
NSURL *terminalUrl = [[NSWorkspace sharedWorkspace] URLForApplicationWithBundleIdentifier:@"com.apple.Terminal"];
if (nil == terminalUrl)
{
return;
}
[[NSWorkspace sharedWorkspace] openFile:shellPathString withApplication:terminalUrl.path];
}
void setWorkDir(NSString* workDir)
{
m_workDir = [NSString stringWithString:workDir];
}
bool makeUserDirectory(const std::string& dirName)
{
// std::string command = replaceAll(dirName, " ", "\\ ");
std::string command = NEW_LINE + "[ -d \"pdf/" + dirName + "\" ] || mkdir \"pdf/" + dirName + "\"" + NEW_LINE;
appendFile(m_shellPath, reinterpret_cast<const unsigned char *>(command.c_str()), command.size());
return true;
}
bool convert(const std::string& htmlPath, const std::string& pdfPath)
{
if (!m_pdfSupported)
{
return false;
}
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithUTF8String:htmlPath.c_str()]];
std::string command = "chrome ";
command += "--headless --disable-gpu --disable-extensions --print-to-pdf-no-header --print-to-pdf=\"";
command += pdfPath;
command += "\" \"";
command += [[url absoluteString] UTF8String];
command += "\" >/dev/null 2>&1" + NEW_LINE;
command += "echo \"" + pdfPath.substr(m_output.size()) + "\"" + NEW_LINE;
appendFile(m_shellPath, reinterpret_cast<const unsigned char *>(command.c_str()), command.size());
return true;
/*
std::string command = [m_assemblyPath UTF8String];
command += " ";
NSString *src = [NSString stringWithUTF8String:htmlPath.c_str()];
NSString *dest = [NSString stringWithUTF8String:pdfPath.c_str()];
NSURL *url = [NSURL fileURLWithPath:src];
NSMutableArray *params = [NSMutableArray arrayWithArray:m_param];
[params addObject:[NSString stringWithFormat:@"--print-to-pdf=\"%@\"", dest]];
[params addObject:[url absoluteString]];
NSString* args = [params componentsJoinedByString:@" "];
NSString* arg1 = [NSString stringWithFormat:@"--print-to-pdf=\"%@\"", dest];
command += [args UTF8String];
// system(command.c_str());
execlp([m_assemblyPath UTF8String], [m_assemblyPath UTF8String], "--headless", "--print-to-pdf-no-header", [arg1 UTF8String], [[url absoluteString] UTF8String], NULL);
*/
/*
// std::string param = m_param;
// replaceAll(param, "%%SRC%%", htmlPath);
// replaceAll(param, "%%DEST%%", pdfPath);
NSTask *task = [[NSTask alloc] init];
task.launchPath = m_assemblyPath;
task.arguments = params;
task.currentDirectoryPath = m_workDir;
// task.standardOutput = pipe;
NSPipe *pipe = [NSPipe pipe];
NSFileHandle *file = pipe.fileHandleForReading;
task.standardOutput = pipe;
[task launch];
NSData *data = [file readDataToEndOfFile];
[file closeFile];
// [[outputPipe fileHandleForReading] readToEndOfFileInBackgroundAndNotify];
[task waitUntilExit];
int status = [task terminationStatus];
return status == 0;
*/
}
protected:
bool detectChromeInstalled()
{
NSString *appPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.google.Chrome"];
if (nil != appPath)
{
appPath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/Google Chrome"];
if ([[NSFileManager defaultManager] fileExistsAtPath:appPath])
{
m_assemblyPath = [NSString stringWithString:appPath];
return true;
}
}
return false;
}
bool detectEdgeInstalled()
{
NSString *appPath = [[NSWorkspace sharedWorkspace] absolutePathForAppBundleWithIdentifier:@"com.microsoft.edgemac"];
if (nil != appPath)
{
appPath = [appPath stringByAppendingPathComponent:@"Contents/MacOS/Microsoft Edge"];
if ([[NSFileManager defaultManager] fileExistsAtPath:appPath])
{
m_assemblyPath = [NSString stringWithString:appPath];
return true;
}
}
return false;
}
void initShellFile(const char *outputDir)
{
m_output = outputDir;
if (!endsWith(m_output, "/"))
{
m_output += "/";
}
m_shellPath = combinePath(m_output, "pdf.sh");
deleteFile(m_shellPath);
std::string aliasCmd = [m_assemblyPath UTF8String];
replaceAll(aliasCmd, " ", "\\ ");
aliasCmd = "#/bin/sh" + NEW_LINE + NEW_LINE + "alias chrome=\"" + aliasCmd + "\"" + NEW_LINE + NEW_LINE;
std::string output = m_output;
// replaceAll(output, " ", "\\ ");
aliasCmd += "cd \"" + output + "\"" + NEW_LINE;
aliasCmd += "[ -d pdf ] || mkdir pdf" + NEW_LINE;
NSDictionary<NSFileAttributeKey, id> *attributes = @{NSFilePosixPermissions : [NSNumber numberWithShort:0777]};
NSData *contents = [NSData dataWithBytes:aliasCmd.c_str() length:aliasCmd.size()];
NSString *shellPath = [NSString stringWithUTF8String:m_shellPath.c_str()];
[[NSFileManager defaultManager] createFileAtPath:shellPath contents:contents attributes:attributes];
// appendFile(m_shellPath, reinterpret_cast<const unsigned char *>(aliasCmd.c_str()), aliasCmd.size());
}
private:
bool m_pdfSupported;
NSString *m_assemblyPath;
NSArray *m_param;
std::string m_output;
std::string m_shellPath;
NSString *m_workDir;
const std::string NEW_LINE = "\n";
};
#endif /* PdfConverterImpl_h */
| 7,571
|
C++
|
.h
| 180
| 32.522222
| 175
| 0.609725
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,897
|
AppDelegate.h
|
BlueMatthew_WechatExporter/WechatExporter/AppDelegate.h
|
//
// AppDelegate.h
// WechatExporter
//
// Created by Matthew on 2020/9/29.
// Copyright © 2020 Matthew. All rights reserved.
//
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
- (IBAction)fileMenuItemClick:(NSMenuItem *)sender;
- (IBAction)formatMenuItemClick:(NSMenuItem *)sender;
- (IBAction)optionsMenuItemClick:(NSMenuItem *)sender;
@end
| 387
|
C++
|
.h
| 13
| 28.461538
| 57
| 0.772973
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,928
|
Core.h
|
BlueMatthew_WechatExporter/vcproject/Core.h
|
#pragma once
#include "..\WechatExporter\core\FileSystem.h"
#include "..\WechatExporter\core\Logger.h"
#include "..\WechatExporter\core\PdfConverter.h"
#include "..\WechatExporter\core\Exporter.h"
#include "..\WechatExporter\core\Updater.h"
| 242
|
C++
|
.h
| 6
| 39.166667
| 48
| 0.778723
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,929
|
ViewHelper.h
|
BlueMatthew_WechatExporter/vcproject/ViewHelper.h
|
#pragma once
#define MB_TIMEDOUT 32000
int MessageBoxTimeoutA(IN HWND hWnd, IN LPCSTR lpText,
IN LPCSTR lpCaption, IN UINT uType,
IN WORD wLanguageId, IN DWORD dwMilliseconds);
int MessageBoxTimeoutW(IN HWND hWnd, IN LPCWSTR lpText,
IN LPCWSTR lpCaption, IN UINT uType,
IN WORD wLanguageId, IN DWORD dwMilliseconds);
#ifdef UNICODE
#define MessageBoxTimeout MessageBoxTimeoutW
#else
#define MessageBoxTimeout MessageBoxTimeoutA
#endif
int MsgBox(HWND hWnd, UINT uStrId, UINT uType = MB_OK);
int MsgBox(HWND hWnd, const CString& text, UINT uType = MB_OK);
void SetComboBoxCurSel(HWND hWnd, CComboBox &cbm, int nCurSel);
void CheckAllItems(CListViewCtrl& listViewCtrl, BOOL fChecked);
void SetHeaderCheckState(CListViewCtrl& listViewCtrl, BOOL fChecked);
BOOL SetHeaderCheckState(CListViewCtrl& listViewCtrl);
| 836
|
C++
|
.h
| 19
| 41.526316
| 70
| 0.809113
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,934
|
resource.h
|
BlueMatthew_WechatExporter/vcproject/resource.h
|
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by WechatExporter.rc
//
#define IDD_ABOUTBOX 100
#define IDR_MAINFRAME 128
#define IDD_WECHATEXPORTER_FORM 129
#define IDS_SEL_BACKUP_DIR 129
#define IDS_SEL_OUTPUT_DIR 130
#define IDS_CANCEL_PROMPT 131
#define IDS_STATIC_BACKUP 132
#define IDS_SESSION_IDX 133
#define IDS_SESSION_NAME 134
#define IDS_SESSION_COUNT 135
#define IDS_ALL_USERS 136
#define IDS_SESSION_USER 137
#define IDS_ITUNES_VERSION 138
#define IDS_ITUNES_NOT_INSTALLED 139
#define IDS_ENC_BKP_NOT_SUPPORTED 140
#define IDS_FAILED_TO_LOAD_BKP 141
#define IDS_INVALID_OUTPUT_DIR 142
#define IDS_TOOLTIP_LOGS 143
#define IDS_NEW_VERSION 144
#define IDS_SESSION_NUMBER 145
#define IDS_SESSION_STATUS 146
#define IDS_SESSION_DONE 147
#define IDS_SESSION_PROGRESS 148
#define IDS_SESSION_CANCELLED 149
#define IDS_SHOW_LOGS 150
#define IDS_HIDE_LOGS 151
#define IDS_VERSIONS 152
#define IDS_NO_PREV_EXP 153
#define IDS_PREV_EXP_FOUND 154
#define IDS_DELETED_SESSION 155
#define IDS_EXPORTING_MSGS 156
#define IDS_DOWNLOADING_EMOJI 157
#define IDC_BACKUP 1000
#define IDC_CHOOSE_BKP 1001
#define IDC_OUTPUT 1002
#define IDC_CHOOSE_OUTPUT 1003
#define IDC_LOGS 1004
#define IDC_EXPORT 1005
#define IDC_PROGRESS 1006
#define IDC_CANCEL 1007
#define IDC_STATIC_BACKUP 1010
#define IDC_VERSION 1011
#define IDC_USERS 1012
#define IDC_CLOSE 1013
#define IDC_SESSIONS 1014
#define IDC_GRP_LOGS 1015
#define IDC_GRP_USR_CHAT 1016
#define IDC_SESS_PROGRESS 1017
#define IDC_CHECK1 1018
#define IDC_SHOW_LOGS 1018
#define IDC_PROGRESS_TEXT 1019
#define IDC_VERSIONS 1020
#define ID_FILE_CHK_UPDATE 32775
#define ID_FORMAT_HTML 32776
#define ID_FORMAT_TEXT 32777
#define ID_FORMAT_PDF 32778
#define ID_OPT_DESC_ORDER 32779
#define ID_OPT_SAVING_IN_SESSION 32780
#define ID_OPT_DL_EMOJI 32781
#define ID_OPT_ASYNC_LOADING 32782
#define ID_OPT_LM_ONSCROLL 32783
#define ID_OPT_FILTER 32784
#define ID_OPT_INCREMENTALEXP 32785
#define ID_HELP_HOMEPAGE 32786
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 204
#define _APS_NEXT_COMMAND_VALUE 32787
#define _APS_NEXT_CONTROL_VALUE 1021
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 3,339
|
C++
|
.h
| 78
| 40.730769
| 48
| 0.544226
|
BlueMatthew/WechatExporter
| 6,161
| 559
| 99
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
24,939
|
test_main.cpp
|
badaix_snapcast/test/test_main.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/>.
***/
#define CATCH_CONFIG_MAIN
// prototype/interface header file
#include "catch.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/utils/string_utils.hpp"
#include "server/streamreader/control_error.hpp"
#include "server/streamreader/properties.hpp"
#include "server/streamreader/stream_uri.hpp"
// 3rd party headers
// standard headers
#include <regex>
using namespace std;
TEST_CASE("String utils")
{
using namespace utils::string;
REQUIRE(ltrim_copy(" test") == "test");
}
TEST_CASE("Uri")
{
AixLog::Log::init<AixLog::SinkCout>(AixLog::Severity::debug);
using namespace streamreader;
StreamUri uri("pipe:///tmp/snapfifo?name=default&codec=flac");
REQUIRE(uri.scheme == "pipe");
REQUIRE(uri.path == "/tmp/snapfifo");
REQUIRE(uri.host.empty());
// uri = StreamUri("scheme:[//host[:port]][/]path[?query=none][#fragment]");
// Test with all fields
uri = StreamUri("scheme://host:port/path?query=none&key=value#fragment");
REQUIRE(uri.scheme == "scheme");
REQUIRE(uri.host == "host:port");
REQUIRE(uri.path == "/path");
REQUIRE(uri.query["query"] == "none");
REQUIRE(uri.query["key"] == "value");
REQUIRE(uri.fragment == "fragment");
// Test with all fields, url encoded
// "%21%23%24%25%26%27%28%29%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D"
// "!#$%&'()*+,/:;=?@[]"
uri = StreamUri("scheme%26://%26host%3f:port/pa%2Bth?%21%23%24%25%26%27%28%29=%2A%2B%2C%2F%3A%3B%3D%3F%40%5B%5D&key%2525=value#fragment%3f%21%3F");
REQUIRE(uri.scheme == "scheme&");
REQUIRE(uri.host == "&host?:port");
REQUIRE(uri.path == "/pa+th");
REQUIRE(uri.query["!#$%&'()"] == "*+,/:;=?@[]");
REQUIRE(uri.query["key%25"] == "value");
REQUIRE(uri.fragment == "fragment?!?");
// No host
uri = StreamUri("scheme:///path?query=none#fragment");
REQUIRE(uri.scheme == "scheme");
REQUIRE(uri.path == "/path");
REQUIRE(uri.query["query"] == "none");
REQUIRE(uri.fragment == "fragment");
// No host, no query
uri = StreamUri("scheme:///path#fragment");
REQUIRE(uri.scheme == "scheme");
REQUIRE(uri.path == "/path");
REQUIRE(uri.query.empty());
REQUIRE(uri.fragment == "fragment");
// No host, no fragment
uri = StreamUri("scheme:///path?query=none");
REQUIRE(uri.scheme == "scheme");
REQUIRE(uri.path == "/path");
REQUIRE(uri.query["query"] == "none");
REQUIRE(uri.fragment.empty());
// just schema and path
uri = StreamUri("scheme:///path");
REQUIRE(uri.scheme == "scheme");
REQUIRE(uri.path == "/path");
REQUIRE(uri.query.empty());
REQUIRE(uri.fragment.empty());
// Issue #850
uri = StreamUri("spotify:///librespot?name=Spotify&username=EMAIL&password=string%26with%26ampersands&devicename=Snapcast&bitrate=320&killall=false");
REQUIRE(uri.scheme == "spotify");
REQUIRE(uri.host.empty());
REQUIRE(uri.path == "/librespot");
REQUIRE(uri.query["name"] == "Spotify");
REQUIRE(uri.query["username"] == "EMAIL");
REQUIRE(uri.query["password"] == "string&with&ersands");
REQUIRE(uri.query["devicename"] == "Snapcast");
REQUIRE(uri.query["bitrate"] == "320");
REQUIRE(uri.query["killall"] == "false");
}
TEST_CASE("Metadata")
{
auto in_json = json::parse(R"(
{
"album": "Memories...Do Not Open",
"albumArtist": [
"The Chainsmokers"
],
"albumArtistSort": [
"Chainsmokers, The"
],
"artist": [
"The Chainsmokers & Coldplay"
],
"artistSort": [
"Chainsmokers, The & Coldplay"
],
"contentCreated": "2017-04-07",
"discNumber": 1,
"duration": 247.0,
"url": "The Chainsmokers - Memories...Do Not Open (2017)/05 - Something Just Like This.mp3",
"genre": [
"Dance/Electronic"
],
"label": "Columbia/Disruptor Records",
"musicbrainzAlbumArtistId": "91a81925-92f9-4fc9-b897-93cf01226282",
"musicbrainzAlbumId": "a9ff33d7-c5a1-4e15-83f7-f669ff96c196",
"musicbrainzArtistId": "91a81925-92f9-4fc9-b897-93cf01226282/cc197bad-dc9c-440d-a5b5-d52ba2e14234",
"musicbrainzReleaseTrackId": "8ccd52a8-de1d-48ce-acf9-b382a7296cfe",
"musicbrainzTrackId": "6fdd95d6-9837-4d95-91f4-b123d0696a2a",
"originalDate": "2017",
"title": "Something Just Like This",
"trackNumber": 5
}
)");
// std::cout << in_json.dump(4) << "\n";
Metadata meta(in_json);
REQUIRE(meta.album.has_value());
REQUIRE(meta.album.value() == "Memories...Do Not Open");
REQUIRE(meta.genre.has_value());
REQUIRE(meta.genre->size() == 1);
REQUIRE(meta.genre.value().front() == "Dance/Electronic");
auto out_json = meta.toJson();
// std::cout << out_json.dump(4) << "\n";
REQUIRE(in_json == out_json);
}
TEST_CASE("Properties")
{
std::stringstream ss;
ss << PlaybackStatus::kPlaying;
REQUIRE(ss.str() == "playing");
PlaybackStatus playback_status;
ss >> playback_status;
REQUIRE(playback_status == PlaybackStatus::kPlaying);
REQUIRE(to_string(PlaybackStatus::kPaused) == "paused");
auto in_json = json::parse(R"(
{
"canControl": false,
"canGoNext": false,
"canGoPrevious": false,
"canPause": false,
"canPlay": false,
"canSeek": false,
"playbackStatus": "playing",
"loopStatus": "track",
"shuffle": false,
"volume": 42,
"mute": false,
"position": 23.0
}
)");
// std::cout << in_json.dump(4) << "\n";
Properties properties(in_json);
std::cout << properties.toJson().dump(4) << "\n";
REQUIRE(properties.loop_status.has_value());
auto out_json = properties.toJson();
// std::cout << out_json.dump(4) << "\n";
REQUIRE(in_json == out_json);
in_json = json::parse(R"(
{
"canControl": true,
"canGoNext": true,
"canGoPrevious": true,
"canPause": true,
"canPlay": true,
"canSeek": true,
"volume": 42
}
)");
// std::cout << in_json.dump(4) << "\n";
properties.fromJson(in_json);
// std::cout << properties.toJson().dump(4) << "\n";
REQUIRE(!properties.loop_status.has_value());
out_json = properties.toJson();
// std::cout << out_json.dump(4) << "\n";
REQUIRE(in_json == out_json);
}
TEST_CASE("Librespot")
{
std::string line = "[2021-06-04T07:20:47Z INFO librespot_playback::player] <Tunnel> (310573 ms) loaded";
smatch m;
static regex re_track_loaded(R"( <(.*)> \((.*) ms\) loaded)");
// Parse the patched version
if (std::regex_search(line, m, re_track_loaded))
{
REQUIRE(m.size() == 3);
REQUIRE(m[1] == "Tunnel");
REQUIRE(m[2] == "310573");
}
REQUIRE(m.size() == 3);
static regex re_log_line(R"(\[(\S+)(\s+)(\bTRACE\b|\bDEBUG\b|\bINFO\b|\bWARN\b|\bERROR\b)(\s+)(.*)\] (.*))");
// Parse the patched version
REQUIRE(std::regex_search(line, m, re_log_line));
REQUIRE(m.size() == 7);
REQUIRE(m[1] == "2021-06-04T07:20:47Z");
REQUIRE(m[2] == " ");
REQUIRE(m[3] == "INFO");
REQUIRE(m[4] == " ");
REQUIRE(m[5] == "librespot_playback::player");
REQUIRE(m[6] == "<Tunnel> (310573 ms) loaded");
for (const auto& match : m)
std::cerr << "Match: '" << match << "'\n";
}
TEST_CASE("Librespot2")
{
std::string line = "[2021-06-04T07:20:47Z INFO librespot_playback::player] <Tunnel> (310573 ms) loaded";
size_t n = 0;
size_t title_pos = 0;
size_t ms_pos = 0;
if (((title_pos = line.find("<")) != std::string::npos) && ((n = line.find(">", title_pos)) != std::string::npos) &&
((ms_pos = line.find("(", n)) != std::string::npos) && ((n = line.find("ms) loaded", ms_pos)) != std::string::npos))
{
title_pos += 1;
std::string title = line.substr(title_pos, line.find(">", title_pos) - title_pos);
REQUIRE(title == "Tunnel");
ms_pos += 1;
std::string ms = line.substr(ms_pos, n - ms_pos - 1);
REQUIRE(ms == "310573");
}
line = "[2021-06-04T07:20:47Z INFO librespot_playback::player] metadata:{\"ARTIST\":\"artist\",\"TITLE\":\"title\"}";
n = 0;
if (((n = line.find("metadata:")) != std::string::npos))
{
std::string meta = line.substr(n + 9);
REQUIRE(meta == "{\"ARTIST\":\"artist\",\"TITLE\":\"title\"}");
json j = json::parse(meta);
std::string artist = j["ARTIST"].get<std::string>();
REQUIRE(artist == "artist");
std::string title = j["TITLE"].get<std::string>();
REQUIRE(title == title);
}
}
// TEST_CASE("Librespot2")
// {
// std::vector<std::string>
// loglines =
// {R"xx([2022-06-27T20:44:48Z INFO librespot] librespot 0.4.1 c8897dd332 (Built on 2022-05-24, Build ID: 1653416940, Profile: release))xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] Command line argument(s):)xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] -n "libre")xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] -b "160")xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] -v)xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] --backend "pipe")xx",
// R"xx([2022-06-27T20:44:48Z TRACE librespot] --device "/dev/null")xx",
// R"xx([2022-06-27T20:44:48Z DEBUG librespot_discovery::server] Zeroconf server listening on 0.0.0.0:46693)xx",
// R"xx([2022-06-27T20:44:59Z DEBUG librespot_discovery::server] POST "/" {})xx",
// R"xx([2022-06-27T20:44:59Z INFO librespot_core::session] Connecting to AP "ap-gae2.spotify.com:4070")xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_core::session] Authenticated as "REDACTED" !)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_core::session] new Session[0])xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_playback::mixer::softmixer] Mixing with softvol and volume control: Log(60.0))xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] new Spirc[0])xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] canonical_username: REDACTED)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot::component] new MercuryManager)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::player] new Player[0])xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::mixer::mappings] Input volume 58958 mapped to: 49.99%)xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_playback::convert] Converting with ditherer: tpdf)xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_playback::audio_backend::pipe] Using pipe sink with format: S16)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::player] command=AddEventSender)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::player] command=VolumeSet(58958))xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_core::session] Session[0] strong=3 weak=2)xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_core::session] Country: "NZ")xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_core::mercury] subscribed uri=hm://remote/user/REDACTED/ count=0)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] kMessageTypeNotify "REDACTED’s MacBook Air" 77fff453997b1fd01bfe33e60acca5b91948f3df
// 652808319 1656362700156 kPlayStatusStop)xx", R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] kMessageTypeNotify "REDACTED"
// 73d40aa67ebaebab0f887eae39a3dca1a29a68f0 652808319 1656362700156 kPlayStatusStop)xx", R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc]
// kMessageTypeLoad "REDACTED MacBook Air" 77fff453997b1fd01bfe33e60acca5b91948f3df 652808631 1656362700156 kPlayStatusPause)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] State: context_uri: "spotify:playlist:6C0FrjLUZZ99ovwSXwt0DE" index: 10 position_ms:
// 126126 status: kPlayStatusPause position_measured_at: 1656362700511 context_description: "" shuffle: false repeat: false playing_from_fallback:
// true row: 0 playing_track_index: 10 track {gid: "\315i\201.\177BC\316\223\302h!|\203\264\024"} track {gid:
// "y\336[{\220\237C\022\210\300\032_\246\276Eu"} track {gid: "\323.H^\265\265A\313\265\'\205\220\272*\341\030"} track {gid:
// ")\224E\314)\357GX\201\277\311l\277\364`$"} track {gid: "\310#\223\310\254\376H\026\214\3600\r\201\000R\313"} track {gid:
// "\223\227#\3447\354M\322\234\222\355\242Kpq)"} track {gid: "\326\326\235\t\320\244K<\231\336\032V\240d%\031"} track {gid:
// "\007\204\252o\022\303N\200\214\377\221\310EW7\230"} track {gid: "\327\307\336\265koLt\2507a9\364\306}j"} track {gid:
// ")\221-\034\316`J\303\241\362\020\335\221\034:\320"} track {gid: "M\332\300\341\260\264M\340\216\237[\3313<\221 "} track {gid:
// "\202q\273\177i\352J.\212\222\335\303\002a!z"} track {gid: ",\356\372\\\215D@j\203\366\022\021&\336\237\000"} track {gid:
// "<\031\235{\305\320O-\264a\331=\273\236\365\220"} track {gid: "\316[\002\222\3704J*\2157V\336\344\266\351\314"} track {gid:
// "1+\360\n;\212Nb\235%\2476xL\257\265"} track {gid: "j\207K\250f<L\337\241|C\3376w-\203"} track {gid: "\361$p\035\221\377H
// \216\216-\265\000\211f)"} track {gid: "\\N9h\211.Jz\236\013`\202\033\230i\313"} track {gid: ".\036\211\302\247\234C\336\252\353>\034\306RcH"}
// track {gid: ";wr\260\264\234E>\207\200\301n9\261\022w"} track {gid: "\010\226\300\377BDD\377\215\030\376\013j\311\262*"} track {gid:
// "\377\272\345m\324\232N\321\203\253I\016I\321H\315"} track {gid: "\313\336\321<c\350N\005\265\037\354b\330w\240&"} track {gid:
// "z\024_I\213\335O\002\264kiu\331\317\n\375"} track {gid: "%/\230z\337JK+\2027\253\021\300b\370\214"} track {gid: "\016\257\036\312\364\336H
// \252\216\376%\343\2778|"} track {gid: "\013\323\303Y\261\002J\330\236\272zT\017\230\200\004"} track {gid:
// "NN~u\246\177M\273\224T\335y\312&m\027"} track {gid: "mq\000\314&\267M\226\222[\350(\230\321\211\315"} track {gid:
// "\344\361\314\222\371\023J~\275\345M@M\0214\000"})xx", R"xx([2022-06-27T20:45:00Z DEBUG librespot_connect::spirc] Frame has 31 tracks)xx",
// R"xx([2022-06-27T20:45:00Z TRACE librespot_connect::spirc] Sending status to server: [kPlayStatusPause])xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::player] command=SetAutoNormaliseAsAlbum(false))xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_playback::player] command=Load(SpotifyId { id: REDACTED, audio_type: Track }, false, 126126))xx",
// R"xx([2022-06-27T20:45:00Z TRACE librespot_connect::spirc] Sending status to server: [kPlayStatusPause])xx",
// R"xx([2022-06-27T20:45:00Z INFO librespot_playback::player] Loading <Flip Reset> with Spotify URI <spotify:track:2mUnxSunvs3Clvtpq3FtGo>)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot_audio::fetch] Downloading file REDACTED)xx",
// R"xx([2022-06-27T20:45:00Z DEBUG librespot::component] new ChannelManager)xx",
// R"xx([2022-06-27T20:45:01Z DEBUG librespot::component] new AudioKeyManager)xx",
// R"xx([2022-06-27T20:45:03Z INFO librespot_playback::player] <Flip Reset> (187661 ms) loaded)xx",
// R"xx([2022-06-27T20:45:03Z TRACE librespot_connect::spirc] Sending status to server: [kPlayStatusPause])xx",
// R"xx([2022-06-27T20:45:03Z TRACE librespot_connect::spirc] ==> kPlayStatusPause)xx",
// R"xx([2022-06-30T15:25:37Z DEBUG librespot_connect::spirc] State: context_uri: "spotify:show:4bGWMQA1ANGTgcysDo14aX" index: 10 position_ms:
// 3130170 status: kPlayStatusPause position_measured_at: 1656602737490 context_description: "" shuffle: false repeat: false playing_from_fallback:
// true row: 0 playing_track_index: 10 track {uri: "spotify:episode:7luHEaQvEf2GA241SqaoIg"} track {uri: "spotify:episode:29LOC9vr1vWakVpWBwuF7n"}
// track {uri: "spotify:episode:2MS5phBmztGepq6yft07XA"} track {uri: "spotify:episode:1kqqpitr713tPbjzPhCCbf"} track {uri:
// "spotify:episode:59PP5P8bF17KnzueM9DUH5"} track {uri: "spotify:episode:4nxFKKH8UPXrYUhbD2G0Db"} track {uri:
// "spotify:episode:4CU6IsMhkflwdQcXyXPxrs"} track {uri: "spotify:episode:0VfUuKQWnttO6XsffakAnF"} track {uri:
// "spotify:episode:5ZNj0vDZJOYTHRpaCJExCl"} track {uri: "spotify:episode:3SV9ap9wMxpDKHaeEv0kuc"} track {uri:
// "spotify:episode:7oe8eW41Vrh2xJAUOQRsvF"})xx"};
// auto onStderrMsg = [](const std::string& line)
// {
// std::string LOG_TAG = "xxx";
// smatch m;
// static regex re_log_line(R"(\[(\S+)(\s+)(\bTRACE\b|\bDEBUG\b|\bINFO\b|\bWARN\b|\bERROR\b)(\s+)(.*)\] (.*))");
// if (regex_search(line, m, re_log_line) && (m.size() == 7))
// {
// const std::string& level = m[3];
// const std::string& source = m[5];
// const std::string& message = m[6];
// AixLog::Severity severity = AixLog::Severity::info;
// if (level == "TRACE")
// severity = AixLog::Severity::trace;
// else if (level == "DEBUG")
// severity = AixLog::Severity::debug;
// else if (level == "INFO")
// severity = AixLog::Severity::info;
// else if (level == "WARN")
// severity = AixLog::Severity::warning;
// else if (level == "ERROR")
// severity = AixLog::Severity::error;
// LOG(severity, source) << message << "\n";
// }
// else
// LOG(INFO, LOG_TAG) << line << "\n";
// // Librespot patch:
// // info!("metadata:{{\"ARTIST\":\"{}\",\"TITLE\":\"{}\"}}", artist.name, track.name);
// // non patched:
// // [2021-06-04T07:20:47Z INFO librespot_playback::player] <Tunnel> (310573 ms) loaded
// // info!("Track \"{}\" loaded", track.name);
// // std::cerr << line << "\n";
// static regex re_patched("metadata:(.*)");
// static regex re_track_loaded(R"( <(.*)> \((.*) ms\) loaded)");
// // Parse the patched version
// if (regex_search(line, m, re_patched))
// {
// // Patched version
// LOG(INFO, LOG_TAG) << "metadata: <" << m[1] << ">\n";
// json j = json::parse(m[1].str());
// Metadata meta;
// meta.artist = std::vector<std::string>{j["ARTIST"].get<std::string>()};
// meta.title = j["TITLE"].get<std::string>();
// // meta.art_data = {SPOTIFY_LOGO, "svg"};
// Properties properties;
// properties.metadata = std::move(meta);
// // setProperties(properties);
// }
// else if (regex_search(line, m, re_track_loaded))
// {
// LOG(INFO, LOG_TAG) << "metadata: <" << m[1] << ">\n";
// Metadata meta;
// meta.title = string(m[1]);
// meta.duration = cpt::stod(m[2]) / 1000.;
// // meta.art_data = {SPOTIFY_LOGO, "svg"};
// Properties properties;
// properties.metadata = std::move(meta);
// // setProperties(properties);
// }
// };
// for (const auto& line : loglines)
// {
// onStderrMsg(line);
// }
// REQUIRE(true);
// }
TEST_CASE("Error")
{
std::error_code ec = ControlErrc::can_not_control;
REQUIRE(ec);
REQUIRE(ec == ControlErrc::can_not_control);
REQUIRE(ec != ControlErrc::success);
std::cout << ec << std::endl;
ec = make_error_code(ControlErrc::can_not_control);
REQUIRE(ec.category() == snapcast::error::control::category());
std::cout << "Category: " << ec.category().name() << ", " << ec.message() << std::endl;
}
| 20,814
|
C++
|
.cpp
| 393
| 49.422392
| 161
| 0.609712
|
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,940
|
daemon.cpp
|
badaix_snapcast/common/daemon.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 "daemon.hpp"
// local headers
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/file_utils.hpp"
// standard headers
#include <cstdlib>
#include <cstring>
#include <fcntl.h>
#include <grp.h>
#include <pwd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <syslog.h>
#include <unistd.h>
Daemon::Daemon(const std::string& user, const std::string& group, const std::string& pidfile)
: pidFilehandle_(-1), user_(user), group_(group), pidfile_(pidfile)
{
if (pidfile.empty() || pidfile.find('/') == std::string::npos)
throw SnapException("invalid pid file \"" + pidfile + "\"");
}
Daemon::~Daemon()
{
if (pidFilehandle_ != -1)
close(pidFilehandle_);
}
void Daemon::daemonize()
{
std::string pidfileDir(pidfile_.substr(0, pidfile_.find_last_of('/')));
utils::file::mkdirRecursive(pidfileDir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
/// Ensure only one copy
pidFilehandle_ = open(pidfile_.c_str(), O_RDWR | O_CREAT, 0644);
if (pidFilehandle_ == -1)
{
/// Couldn't open lock file
throw SnapException("Could not open PID lock file \"" + pidfile_ + "\"");
}
auto user_uid = static_cast<uid_t>(-1);
auto user_gid = static_cast<gid_t>(-1);
// std::string user_name;
// #ifdef FREEBSD
// bool had_group = false;
// #endif
if (!user_.empty())
{
struct passwd* pwd = getpwnam(user_.c_str());
if (pwd == nullptr)
throw SnapException("no such user \"" + user_ + "\"");
user_uid = pwd->pw_uid;
user_gid = pwd->pw_gid;
// user_name = strdup(user_.c_str());
/// this is needed by libs such as arts
setenv("HOME", pwd->pw_dir, 1);
}
if (!group_.empty())
{
struct group* grp = getgrnam(group_.c_str());
if (grp == nullptr)
throw SnapException("no such group \"" + group_ + "\"");
user_gid = grp->gr_gid;
// #ifdef FREEBSD
// had_group = true;
// #endif
}
if (chown(pidfile_.c_str(), user_uid, user_gid) == -1)
{
/// Couldn't open lock file
throw SnapException("Could not chown PID lock file \"" + pidfile_ + "\"");
}
/// set gid
if (user_gid != static_cast<gid_t>(-1) && user_gid != getgid() && setgid(user_gid) == -1)
throw SnapException("Failed to set group " + cpt::to_string(static_cast<int>(user_gid)));
// #if defined(FREEBSD) && !defined(MACOS)
// #ifdef FREEBSD
/// init supplementary groups
/// (must be done before we change our uid)
/// no need to set the new user's supplementary groups if we are already this user
// if (!had_group && user_uid != getuid() && initgroups(user_name, user_gid) == -1)
// throw SnapException("Failed to set supplementary groups of user \"" + user + "\"");
// #endif
/// set uid
if (user_uid != static_cast<uid_t>(-1) && user_uid != getuid() && setuid(user_uid) == -1)
throw SnapException("Failed to set user " + user_);
/// Our process ID and Session ID
pid_t pid, sid;
/// Fork off the parent process
pid = fork();
if (pid < 0)
exit(EXIT_FAILURE);
/// If we got a good PID, then we can exit the parent process.
if (pid > 0)
exit(EXIT_SUCCESS);
/// Change the file mode mask
umask(0);
/// Open any logs here
/// Create a new SID for the child process
sid = setsid();
if (sid < 0)
{
/// Log the failure
exit(EXIT_FAILURE);
}
/// Change the current working directory
if ((chdir("/")) < 0)
{
/// Log the failure
exit(EXIT_FAILURE);
}
/// Try to lock file
if (lockf(pidFilehandle_, F_TLOCK, 0) == -1)
throw SnapException("Could not lock PID lock file \"" + pidfile_ + "\". Is the daemon already running?");
char str[10];
/// Get and format PID
sprintf(str, "%d\n", getpid());
/// write pid to lockfile
if (write(pidFilehandle_, str, strlen(str)) != static_cast<int>(strlen(str)))
throw SnapException("Could not write PID to lock file \"" + pidfile_ + "\"");
/// Close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
}
| 5,090
|
C++
|
.cpp
| 137
| 31.759124
| 113
| 0.615885
|
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,941
|
sample_format.cpp
|
badaix_snapcast/common/sample_format.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 "sample_format.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
// standard headers
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;
SampleFormat::SampleFormat()
{
setFormat(0, 0, 0);
}
SampleFormat::SampleFormat(const std::string& format)
{
setFormat(format);
}
SampleFormat::SampleFormat(uint32_t sampleRate, uint16_t bitsPerSample, uint16_t channels)
{
setFormat(sampleRate, bitsPerSample, channels);
}
string SampleFormat::toString() const
{
stringstream ss;
ss << rate_ << ":" << bits_ << ":" << channels_;
return ss.str();
}
void SampleFormat::setFormat(const std::string& format)
{
std::vector<std::string> strs;
strs = utils::string::split(format, ':');
if (strs.size() == 3)
setFormat(strs[0] == "*" ? 0 : cpt::stoul(strs[0]), strs[1] == "*" ? 0 : static_cast<uint16_t>(cpt::stoul(strs[1])),
strs[2] == "*" ? 0 : static_cast<uint16_t>(cpt::stoul(strs[2])));
else
throw SnapException("sampleformat must be <rate>:<bits>:<channels>");
}
void SampleFormat::setFormat(uint32_t rate, uint16_t bits, uint16_t channels)
{
// needs something like:
// 24_4 = 3 bytes, padded to 4
// 32 = 4 bytes
rate_ = rate;
bits_ = bits;
channels_ = channels;
sample_size_ = bits / 8;
if (bits_ == 24)
sample_size_ = 4;
frame_size_ = channels_ * sample_size_;
// LOG(DEBUG) << "SampleFormat: " << rate << ":" << bits << ":" << channels << "\n";
}
| 2,334
|
C++
|
.cpp
| 66
| 31.484848
| 124
| 0.673932
|
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,942
|
resampler.cpp
|
badaix_snapcast/common/resampler.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 "resampler.hpp"
// local headers
#include "common/aixlog.hpp"
// standard headers
#include <cmath>
using namespace std;
static constexpr auto LOG_TAG = "Resampler";
Resampler::Resampler(const SampleFormat& in_format, const SampleFormat& out_format) : in_format_(in_format), out_format_(out_format)
{
#ifdef HAS_SOXR
if ((out_format_.rate() != in_format_.rate()) || (out_format_.bits() != in_format_.bits()))
{
LOG(INFO, LOG_TAG) << "Resampling from " << in_format_.toString() << " to " << out_format_.toString() << "\n";
soxr_error_t error;
soxr_datatype_t in_type = SOXR_INT16_I;
soxr_datatype_t out_type = SOXR_INT16_I;
if (in_format_.sampleSize() > 2)
in_type = SOXR_INT32_I;
if (out_format_.sampleSize() > 2)
out_type = SOXR_INT32_I;
soxr_io_spec_t iospec = soxr_io_spec(in_type, out_type);
// HQ should be fine: http://sox.sourceforge.net/Docs/FAQ
soxr_quality_spec_t q_spec = soxr_quality_spec(SOXR_HQ, 0);
soxr_ = soxr_create(static_cast<double>(in_format_.rate()), static_cast<double>(out_format_.rate()), in_format_.channels(), &error, &iospec, &q_spec,
nullptr);
if (error != nullptr)
{
LOG(ERROR, LOG_TAG) << "Error soxr_create: " << error << "\n";
soxr_ = nullptr;
}
// initialize the buffer with 20ms (~latency of the reampler)
resample_buffer_.resize(out_format_.frameSize() * static_cast<uint16_t>(ceil(out_format_.msRate() * 20)));
}
#else
LOG(WARNING, LOG_TAG) << "Soxr not available, resampling not supported\n";
if ((out_format_.rate() != in_format_.rate()) || (out_format_.bits() != in_format_.bits()))
{
throw SnapException("Resampling requested, but not supported");
}
#endif
// resampled_chunk_ = std::make_unique<msg::PcmChunk>(out_format_, 0);
}
bool Resampler::resamplingNeeded() const
{
#ifdef HAS_SOXR
return soxr_ != nullptr;
#else
return false;
#endif
}
// std::shared_ptr<msg::PcmChunk> Resampler::resample(std::shared_ptr<msg::PcmChunk> chunk, chronos::usec duration)
// {
// auto resampled_chunk = resample(chunk);
// if (!resampled_chunk)
// return nullptr;
// std::cerr << "1\n";
// resampled_chunk_->append(*resampled_chunk);
// std::cerr << "2\n";
// while (resampled_chunk_->duration<chronos::usec>() >= duration)
// {
// LOG(DEBUG, LOG_TAG) << "resampled duration: " << resampled_chunk_->durationMs() << ", consuming: " << out_format_.usRate() * duration.count() <<
// "\n";
// auto chunk = resampled_chunk_->consume(out_format_.usRate() * duration.count());
// LOG(DEBUG, LOG_TAG) << "consumed: " << chunk->durationMs() << ", resampled duration: " << resampled_chunk_->durationMs() << "\n";
// return chunk;
// }
// // resampled_chunks_.push_back(resampled_chunk);
// // chronos::usec avail;
// // for (const auto& chunk: resampled_chunks_)
// // {
// // avail += chunk->durationLeft<chronos::usec>();
// // if (avail >= duration)
// // {
// // }
// // }
// }
std::shared_ptr<msg::PcmChunk> Resampler::resample(const msg::PcmChunk& chunk)
{
#ifndef HAS_SOXR
return std::make_shared<msg::PcmChunk>(chunk);
#else
if (!resamplingNeeded())
{
return std::make_shared<msg::PcmChunk>(chunk);
}
else
{
if (in_format_.bits() == 24)
{
// sox expects 32 bit input, shift 8 bits left
auto* frames = reinterpret_cast<int32_t*>(chunk.payload);
for (size_t n = 0; n < chunk.getSampleCount(); ++n)
frames[n] = frames[n] << 8;
}
size_t idone;
size_t odone;
auto resample_buffer_framesize = resample_buffer_.size() / out_format_.frameSize();
const auto* error = soxr_process(soxr_, chunk.payload, chunk.getFrameCount(), &idone, resample_buffer_.data(), resample_buffer_framesize, &odone);
if (error != nullptr)
{
LOG(ERROR, LOG_TAG) << "Error soxr_process: " << error << "\n";
}
else
{
LOG(TRACE, LOG_TAG) << "Resample idone: " << idone << "/" << chunk.getFrameCount() << ", odone: " << odone << "/"
<< resample_buffer_.size() / out_format_.frameSize() << ", delay: " << soxr_delay(soxr_) << "\n";
// some data has been resampled (odone frames) and some is still in the pipe (soxr_delay frames)
if (odone > 0)
{
// get the resampled ts from the input ts
auto input_end_ts = chunk.start() + chunk.duration<std::chrono::microseconds>();
double resampled_ms = (odone + soxr_delay(soxr_)) / out_format_.msRate();
auto resampled_start = input_end_ts - std::chrono::microseconds(static_cast<int>(resampled_ms * 1000.));
auto resampled_chunk = std::make_shared<msg::PcmChunk>(out_format_, 0);
auto us = chrono::duration_cast<chrono::microseconds>(resampled_start.time_since_epoch()).count();
resampled_chunk->timestamp.sec = static_cast<int32_t>(us / 1000000);
resampled_chunk->timestamp.usec = static_cast<int32_t>(us % 1000000);
// copy from the resample_buffer to the resampled chunk
resampled_chunk->payloadSize = static_cast<uint32_t>(odone * out_format_.frameSize());
resampled_chunk->payload = static_cast<char*>(realloc(resampled_chunk->payload, resampled_chunk->payloadSize));
memcpy(resampled_chunk->payload, resample_buffer_.data(), resampled_chunk->payloadSize);
if (out_format_.bits() == 24)
{
// sox has quantized to 32 bit, shift 8 bits right
auto* frames = reinterpret_cast<int32_t*>(resampled_chunk->payload);
for (size_t n = 0; n < resampled_chunk->getSampleCount(); ++n)
{
// +128 to round to the nearest so that quantisation steps are distributed evenly
frames[n] = (frames[n] + 128) >> 8;
if (frames[n] > 0x7fffffff)
frames[n] = 0x7fffffff;
}
}
// check if the resample_buffer is large enough, or if soxr was using all available space
if (odone == resample_buffer_framesize)
{
// buffer for resampled data too small, add space for 5ms
resample_buffer_.resize(resample_buffer_.size() + out_format_.frameSize() * static_cast<uint16_t>(ceil(out_format_.msRate() * 5)));
LOG(DEBUG, LOG_TAG) << "Resample buffer completely filled, adding space for 5ms; new buffer size: " << resample_buffer_.size()
<< " bytes\n";
}
// //LOG(TRACE, LOG_TAG) << "ts: " << out->timestamp.sec << "s, " << out->timestamp.usec/1000.f << " ms, duration: " << odone / format_.msRate()
// << "\n";
// int64_t next_us = us + static_cast<int64_t>(odone / format_.msRate() * 1000);
// LOG(TRACE, LOG_TAG) << "ts: " << us << ", next: " << next_us << ", diff: " << next_us_ - us << "\n";
// next_us_ = next_us;
return resampled_chunk;
}
}
}
return nullptr;
#endif
}
shared_ptr<msg::PcmChunk> Resampler::resample(shared_ptr<msg::PcmChunk> chunk)
{
#ifndef HAS_SOXR
return chunk;
#else
if (!resamplingNeeded())
{
return chunk;
}
else
{
return resample(*chunk);
}
#endif
}
Resampler::~Resampler()
{
#ifdef HAS_SOXR
if (soxr_ != nullptr)
soxr_delete(soxr_);
#endif
}
| 8,699
|
C++
|
.cpp
| 190
| 37.531579
| 160
| 0.579314
|
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,943
|
snapserver.cpp
|
badaix_snapcast/server/snapserver.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"
#ifdef HAS_DAEMON
#include "common/daemon.hpp"
#endif
#include "common/snap_exception.hpp"
#include "common/utils/string_utils.hpp"
#include "common/version.hpp"
#include "encoder/encoder_factory.hpp"
#include "server.hpp"
#include "server_settings.hpp"
#if defined(HAS_AVAHI) || defined(HAS_BONJOUR)
#include "publishZeroConf/publish_mdns.hpp"
#endif
#include "common/aixlog.hpp"
#include "config.hpp"
// 3rd party headers
#include <boost/asio/ip/host_name.hpp>
// standard headers
#include <chrono>
#include <memory>
#include <sys/resource.h>
using namespace std;
using namespace popl;
static constexpr auto LOG_TAG = "Snapserver";
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
{
ServerSettings settings;
std::string pcmSource = "pipe:///tmp/snapfifo?name=default";
std::string config_file = "/etc/snapserver.conf";
OptionParser op("Allowed options");
auto helpSwitch = op.add<Switch>("h", "help", "Produce help message, use -hh to show options from config file");
auto groffSwitch = op.add<Switch, Attribute::hidden>("", "groff", "produce groff message");
auto versionSwitch = op.add<Switch>("v", "version", "Show version number");
#ifdef HAS_DAEMON
int processPriority(0);
auto daemonOption = op.add<Implicit<int>>("d", "daemon", "Daemonize\noptional process priority [-20..19]", 0, &processPriority);
#endif
op.add<Value<string>>("c", "config", "path to the configuration file", config_file, &config_file);
OptionParser conf("Overridable config file options");
// server settings
conf.add<Value<int>>("", "server.threads", "number of server threads", settings.server.threads, &settings.server.threads);
conf.add<Value<string>>("", "server.pidfile", "pid file when running as daemon", settings.server.pid_file, &settings.server.pid_file);
conf.add<Value<string>>("", "server.user", "the user to run as when daemonized", settings.server.user, &settings.server.user);
conf.add<Implicit<string>>("", "server.group", "the group to run as when daemonized", settings.server.group, &settings.server.group);
conf.add<Implicit<string>>("", "server.datadir", "directory where persistent data is stored", settings.server.data_dir, &settings.server.data_dir);
// HTTP RPC settings
conf.add<Value<bool>>("", "http.enabled", "enable HTTP Json RPC (HTTP POST and websockets)", settings.http.enabled, &settings.http.enabled);
conf.add<Value<size_t>>("", "http.port", "which port the server should listen on", settings.http.port, &settings.http.port);
auto http_bind_to_address = conf.add<Value<string>>("", "http.bind_to_address", "address for the server to listen on",
settings.http.bind_to_address.front(), &settings.http.bind_to_address[0]);
conf.add<Implicit<string>>("", "http.doc_root", "serve a website from the doc_root location", settings.http.doc_root, &settings.http.doc_root);
conf.add<Value<string>>("", "http.host", "Hostname or IP under which clients can reach this host", settings.http.host, &settings.http.host);
// TCP RPC settings
conf.add<Value<bool>>("", "tcp.enabled", "enable TCP Json RPC)", settings.tcp.enabled, &settings.tcp.enabled);
conf.add<Value<size_t>>("", "tcp.port", "which port the server should listen on", settings.tcp.port, &settings.tcp.port);
auto tcp_bind_to_address = conf.add<Value<string>>("", "tcp.bind_to_address", "address for the server to listen on",
settings.tcp.bind_to_address.front(), &settings.tcp.bind_to_address[0]);
// stream settings
auto stream_bind_to_address = conf.add<Value<string>>("", "stream.bind_to_address", "address for the server to listen on",
settings.stream.bind_to_address.front(), &settings.stream.bind_to_address[0]);
conf.add<Value<size_t>>("", "stream.port", "which port the server should listen on", settings.stream.port, &settings.stream.port);
// deprecated: stream.stream, use stream.source instead
auto streamValue = conf.add<Value<string>>("", "stream.stream", "Deprecated: use stream.source", pcmSource, &pcmSource);
auto sourceValue = conf.add<Value<string>>(
"", "stream.source", "URI of the PCM input stream.\nFormat: TYPE://host/path?name=NAME\n[&codec=CODEC]\n[&sampleformat=SAMPLEFORMAT]", pcmSource,
&pcmSource);
conf.add<Value<string>>("", "stream.sampleformat", "Default sample format", settings.stream.sampleFormat, &settings.stream.sampleFormat);
conf.add<Value<string>>("", "stream.codec", "Default transport codec\n(flac|ogg|opus|pcm)[:options]\nType codec:? to get codec specific options",
settings.stream.codec, &settings.stream.codec);
// deprecated: stream_buffer, use chunk_ms instead
conf.add<Value<size_t>>("", "stream.stream_buffer", "Default stream read chunk size [ms], deprecated, use stream.chunk_ms instead",
settings.stream.streamChunkMs, &settings.stream.streamChunkMs);
conf.add<Value<size_t>>("", "stream.chunk_ms", "Default stream read chunk size [ms]", settings.stream.streamChunkMs, &settings.stream.streamChunkMs);
conf.add<Value<int>>("", "stream.buffer", "Buffer [ms]", settings.stream.bufferMs, &settings.stream.bufferMs);
conf.add<Value<bool>>("", "stream.send_to_muted", "Send audio to muted clients", settings.stream.sendAudioToMutedClients,
&settings.stream.sendAudioToMutedClients);
// streaming_client options
conf.add<Value<uint16_t>>("", "streaming_client.initial_volume", "Volume [percent] assigned to new streaming clients",
settings.streamingclient.initialVolume, &settings.streamingclient.initialVolume);
// logging settings
conf.add<Value<string>>("", "logging.sink", "log sink [null,system,stdout,stderr,file:<filename>]", settings.logging.sink, &settings.logging.sink);
auto logfilterOption = conf.add<Value<string>>(
"", "logging.filter",
"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);
conf.parse(config_file);
conf.parse(argc, argv);
if (tcp_bind_to_address->is_set())
{
settings.tcp.bind_to_address.clear();
for (size_t n = 0; n < tcp_bind_to_address->count(); ++n)
settings.tcp.bind_to_address.push_back(tcp_bind_to_address->value(n));
}
if (http_bind_to_address->is_set())
{
settings.http.bind_to_address.clear();
for (size_t n = 0; n < http_bind_to_address->count(); ++n)
settings.http.bind_to_address.push_back(http_bind_to_address->value(n));
}
if (stream_bind_to_address->is_set())
{
settings.stream.bind_to_address.clear();
for (size_t n = 0; n < stream_bind_to_address->count(); ++n)
settings.stream.bind_to_address.push_back(stream_bind_to_address->value(n));
}
}
catch (const std::invalid_argument& e)
{
cerr << "Exception: " << e.what() << std::endl;
cout << "\n" << op << "\n";
exit(EXIT_FAILURE);
}
if (versionSwitch->is_set())
{
cout << "snapserver 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);
}
if (helpSwitch->is_set())
{
cout << op << "\n";
if (helpSwitch->count() > 1)
cout << conf << "\n";
exit(EXIT_SUCCESS);
}
if (groffSwitch->is_set())
{
GroffOptionPrinter option_printer(&op);
cout << option_printer.print();
exit(EXIT_SUCCESS);
}
if (settings.stream.codec.find(":?") != string::npos)
{
encoder::EncoderFactory encoderFactory;
std::unique_ptr<encoder::Encoder> encoder(encoderFactory.createEncoder(settings.stream.codec));
if (encoder)
{
cout << "Options for codec \"" << encoder->name() << "\":\n"
<< " " << encoder->getAvailableOptions() << "\n"
<< " Default: \"" << encoder->getDefaultOptions() << "\"\n";
}
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>("snapserver", logfilter);
else if (settings.logging.sink == "null")
AixLog::Log::init<AixLog::SinkNull>();
else
throw SnapException("Invalid log sink: " + settings.logging.sink);
LOG(INFO, LOG_TAG) << "Version " << version::code << (!version::rev().empty() ? (", revision " + version::rev(8)) : ("")) << "\n";
if (!streamValue->is_set() && !sourceValue->is_set())
settings.stream.sources.push_back(sourceValue->value());
for (size_t n = 0; n < streamValue->count(); ++n)
{
LOG(INFO, LOG_TAG) << "Adding stream: " << streamValue->value(n) << "\n";
settings.stream.sources.push_back(streamValue->value(n));
}
for (size_t n = 0; n < sourceValue->count(); ++n)
{
LOG(INFO, LOG_TAG) << "Adding source: " << sourceValue->value(n) << "\n";
settings.stream.sources.push_back(sourceValue->value(n));
}
#ifdef HAS_DAEMON
std::unique_ptr<Daemon> daemon;
if (daemonOption->is_set())
{
if (settings.server.user.empty())
throw std::invalid_argument("user must not be empty");
if (settings.server.data_dir.empty())
settings.server.data_dir = "/var/lib/snapserver";
Config::instance().init(settings.server.data_dir, settings.server.user, settings.server.group);
daemon = std::make_unique<Daemon>(settings.server.user, settings.server.group, settings.server.pid_file);
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;
}
else
Config::instance().init(settings.server.data_dir);
#else
Config::instance().init(settings.server.data_dir);
#endif
boost::asio::io_context io_context;
#if defined(HAS_AVAHI) || defined(HAS_BONJOUR)
auto publishZeroConfg = std::make_unique<PublishZeroConf>("Snapcast", io_context);
vector<mDNSService> dns_services;
dns_services.emplace_back("_snapcast._tcp", settings.stream.port);
dns_services.emplace_back("_snapcast-stream._tcp", settings.stream.port);
if (settings.tcp.enabled)
{
dns_services.emplace_back("_snapcast-jsonrpc._tcp", settings.tcp.port);
dns_services.emplace_back("_snapcast-tcp._tcp", settings.tcp.port);
}
if (settings.http.enabled)
{
dns_services.emplace_back("_snapcast-http._tcp", settings.http.port);
}
publishZeroConfg->publish(dns_services);
#endif
if (settings.http.enabled)
{
if ((settings.http.host == "<hostname>") || settings.http.host.empty())
{
settings.http.host = boost::asio::ip::host_name();
LOG(INFO, LOG_TAG) << "Using HTTP host name: " << settings.http.host << "\n";
}
}
if (settings.stream.streamChunkMs < 10)
{
LOG(WARNING, LOG_TAG) << "Stream read chunk size is less than 10ms, changing to 10ms\n";
settings.stream.streamChunkMs = 10;
}
static constexpr chrono::milliseconds MIN_BUFFER_DURATION = 20ms;
if (settings.stream.bufferMs < MIN_BUFFER_DURATION.count())
{
LOG(WARNING, LOG_TAG) << "Buffer is less than " << MIN_BUFFER_DURATION.count() << "ms, changing to " << MIN_BUFFER_DURATION.count() << "ms\n";
settings.stream.bufferMs = MIN_BUFFER_DURATION.count();
}
auto server = std::make_unique<Server>(io_context, settings);
server->start();
if (settings.server.threads < 0)
settings.server.threads = std::max(2, std::min(4, static_cast<int>(std::thread::hardware_concurrency())));
LOG(INFO, LOG_TAG) << "Number of threads: " << settings.server.threads << ", hw threads: " << std::thread::hardware_concurrency() << "\n";
// Construct a signal set registered for process termination.
boost::asio::signal_set signals(io_context, SIGHUP, SIGINT, SIGTERM);
signals.async_wait(
[&io_context](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();
});
std::vector<std::thread> threads;
for (int n = 0; n < settings.server.threads; ++n)
threads.emplace_back([&] { io_context.run(); });
io_context.run();
for (auto& t : threads)
t.join();
LOG(INFO, LOG_TAG) << "Stopping streamServer" << endl;
server->stop();
LOG(INFO, LOG_TAG) << "done" << endl;
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << std::endl;
exitcode = EXIT_FAILURE;
}
Config::instance().save();
LOG(NOTICE, LOG_TAG) << "Snapserver terminated." << endl;
exit(exitcode);
}
| 17,004
|
C++
|
.cpp
| 311
| 44.29582
| 157
| 0.602595
|
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,944
|
stream_session_tcp.cpp
|
badaix_snapcast/server/stream_session_tcp.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 "stream_session_tcp.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
using namespace streamreader;
static constexpr auto LOG_TAG = "StreamSessionTCP";
StreamSessionTcp::StreamSessionTcp(StreamMessageReceiver* receiver, tcp::socket&& socket)
: StreamSession(socket.get_executor(), receiver), socket_(std::move(socket))
{
}
StreamSessionTcp::~StreamSessionTcp()
{
LOG(DEBUG, LOG_TAG) << "~StreamSessionTcp\n";
stop();
}
void StreamSessionTcp::start()
{
read_next();
}
void StreamSessionTcp::stop()
{
LOG(DEBUG, LOG_TAG) << "stop\n";
if (socket_.is_open())
{
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() << "\n";
socket_.close(ec);
if (ec)
LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << "\n";
LOG(DEBUG, LOG_TAG) << "stopped\n";
}
}
std::string StreamSessionTcp::getIP()
{
try
{
return socket_.remote_endpoint().address().to_string();
}
catch (...)
{
return "0.0.0.0";
}
}
void StreamSessionTcp::read_next()
{
boost::asio::async_read(socket_, boost::asio::buffer(buffer_, base_msg_size_),
[this, self = shared_from_this()](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";
messageReceiver_->onDisconnect(this);
return;
}
baseMessage_.deserialize(buffer_.data());
LOG(DEBUG, LOG_TAG) << "getNextMessage: " << baseMessage_.type << ", size: " << baseMessage_.size << ", id: " << baseMessage_.id
<< ", refers: " << baseMessage_.refersTo << "\n";
if (baseMessage_.type > message_type::kLast)
{
LOG(ERROR, LOG_TAG) << "unknown message type received: " << baseMessage_.type << ", size: " << baseMessage_.size << "\n";
messageReceiver_->onDisconnect(this);
return;
}
else if (baseMessage_.size > msg::max_size)
{
LOG(ERROR, LOG_TAG) << "received message of type " << baseMessage_.type << " to large: " << baseMessage_.size << "\n";
messageReceiver_->onDisconnect(this);
return;
}
if (baseMessage_.size > buffer_.size())
buffer_.resize(baseMessage_.size);
boost::asio::async_read(socket_, boost::asio::buffer(buffer_, baseMessage_.size),
[this, self](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";
messageReceiver_->onDisconnect(this);
return;
}
tv t;
baseMessage_.received = t;
if (messageReceiver_ != nullptr)
messageReceiver_->onMessageReceived(this, baseMessage_, buffer_.data());
read_next();
});
});
}
void StreamSessionTcp::sendAsync(const shared_const_buffer& buffer, const WriteHandler& handler)
{
boost::asio::async_write(socket_, buffer,
[self = shared_from_this(), buffer, handler](boost::system::error_code ec, std::size_t length) { handler(ec, length); });
}
| 4,513
|
C++
|
.cpp
| 114
| 31.666667
| 150
| 0.598032
|
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,945
|
control_session_http.cpp
|
badaix_snapcast/server/control_session_http.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 "control_session_http.hpp"
// standard headers
#include <iostream>
// 3rd party headers
#include <boost/beast/http/buffer_body.hpp>
#include <boost/beast/http/file_body.hpp>
// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"
#include "common/utils/file_utils.hpp"
#include "control_session_ws.hpp"
#include "stream_session_ws.hpp"
using namespace std;
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
static constexpr auto LOG_TAG = "ControlSessionHTTP";
static constexpr const char* HTTP_SERVER_NAME = "Snapcast";
static constexpr const char* UNCONFIGURED =
"<html><head><title>Snapcast Default Page</title></head>"
"<body>"
" <h1>Snapcast Default Page</h1>"
" <p>"
" This is the default welcome page used to test the correct operation of the Snapcast built-in webserver."
" </p>"
" <p>"
" This webserver is a websocket endpoint for control clients (ws://<i>host</i>:1780/jsonrpc) and streaming clients"
" (ws://<i>host</i>:1780/stream), but it can also host simple web pages. To serve a web page, you must configure the"
" document root in the snapserver configuration file <b>snapserver.conf</b>, usually located in"
" <b>/etc/snapserver.conf</b>"
" </p>"
" <p>"
" The Snapserver installation should include a copy of <a href=\"https://github.com/badaix/snapweb\">Snapweb</a>,"
" located in <b>/usr/share/snapserver/snapweb/</b><br>"
" To activate it, please configure the <b>doc_root</b> as follows, and restart Snapserver to activate the changes:"
" </p>"
" <pre>"
"# HTTP RPC #####################################\n"
"#\n"
"[http]\n"
"\n"
"...\n"
"\n"
"# serve a website from the doc_root location\n"
"doc_root = /usr/share/snapserver/snapweb/\n"
"\n"
"#\n"
"################################################</pre>"
"</body>"
"</html>";
namespace
{
// Return a reasonable mime type based on the extension of a file.
boost::beast::string_view mime_type(boost::beast::string_view path)
{
using boost::beast::iequals;
auto const ext = [&path]
{
auto const pos = path.rfind(".");
if (pos == boost::beast::string_view::npos)
return boost::beast::string_view{};
return path.substr(pos);
}();
if (iequals(ext, ".htm"))
return "text/html";
if (iequals(ext, ".html"))
return "text/html";
if (iequals(ext, ".php"))
return "text/html";
if (iequals(ext, ".css"))
return "text/css";
if (iequals(ext, ".txt"))
return "text/plain";
if (iequals(ext, ".js"))
return "application/javascript";
if (iequals(ext, ".json"))
return "application/json";
if (iequals(ext, ".xml"))
return "application/xml";
if (iequals(ext, ".swf"))
return "application/x-shockwave-flash";
if (iequals(ext, ".flv"))
return "video/x-flv";
if (iequals(ext, ".png"))
return "image/png";
if (iequals(ext, ".jpe"))
return "image/jpeg";
if (iequals(ext, ".jpeg"))
return "image/jpeg";
if (iequals(ext, ".jpg"))
return "image/jpeg";
if (iequals(ext, ".gif"))
return "image/gif";
if (iequals(ext, ".bmp"))
return "image/bmp";
if (iequals(ext, ".ico"))
return "image/vnd.microsoft.icon";
if (iequals(ext, ".tiff"))
return "image/tiff";
if (iequals(ext, ".tif"))
return "image/tiff";
if (iequals(ext, ".svg"))
return "image/svg+xml";
if (iequals(ext, ".svgz"))
return "image/svg+xml";
return "application/text";
}
// Append an HTTP rel-path to a local filesystem path.
// The returned path is normalized for the platform.
std::string path_cat(boost::beast::string_view base, boost::beast::string_view path)
{
if (base.empty())
return std::string(path);
std::string result = std::string(base);
char constexpr path_separator = '/';
if (result.back() == path_separator)
result.resize(result.size() - 1);
result.append(path.data(), path.size());
return result;
}
} // namespace
ControlSessionHttp::ControlSessionHttp(ControlMessageReceiver* receiver, tcp::socket&& socket, const ServerSettings::Http& settings)
: ControlSession(receiver), socket_(std::move(socket)), settings_(settings)
{
LOG(DEBUG, LOG_TAG) << "ControlSessionHttp, Local IP: " << socket_.local_endpoint().address().to_string() << "\n";
}
ControlSessionHttp::~ControlSessionHttp()
{
LOG(DEBUG, LOG_TAG) << "ControlSessionHttp::~ControlSessionHttp()\n";
stop();
}
void ControlSessionHttp::start()
{
http::async_read(socket_, buffer_, req_, [this, self = shared_from_this()](boost::system::error_code ec, std::size_t bytes) { on_read(ec, bytes); });
}
// This function produces an HTTP response for the given
// request. The type of the response object depends on the
// contents of the request, so the interface requires the
// caller to pass a generic lambda for receiving the response.
template <class Body, class Allocator, class Send>
void ControlSessionHttp::handle_request(http::request<Body, http::basic_fields<Allocator>>&& req, Send&& send)
{
// Returns a bad request response
auto const bad_request = [&req](boost::beast::string_view why)
{
http::response<http::string_body> res{http::status::bad_request, req.version()};
// TODO: Server: Snapcast/VERSION
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = std::string(why);
res.prepare_payload();
return res;
};
// Returns a not found response
auto const not_found = [&req](boost::beast::string_view target)
{
http::response<http::string_body> res{http::status::not_found, req.version()};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "The resource '" + std::string(target) + "' was not found.";
res.prepare_payload();
return res;
};
// Returns a configuration help
auto const unconfigured = [&req]()
{
http::response<http::string_body> res{http::status::ok, req.version()};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = UNCONFIGURED;
res.prepare_payload();
return res;
};
// Returns a server error response
auto const server_error = [&req](boost::beast::string_view what)
{
http::response<http::string_body> res{http::status::internal_server_error, req.version()};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "An error occurred: '" + std::string(what) + "'";
res.prepare_payload();
return res;
};
// Make sure we can handle the method
if ((req.method() != http::verb::get) && (req.method() != http::verb::head) && (req.method() != http::verb::post))
return send(bad_request("Unknown HTTP-method"));
// handle json rpc requests
if (req.method() == http::verb::post)
{
if (req.target() != "/jsonrpc")
return send(bad_request("Illegal request-target"));
std::string request = req.body();
return message_receiver_->onMessageReceived(shared_from_this(), request,
[req = std::move(req), send = std::move(send)](const std::string& response)
{
http::response<http::string_body> res{http::status::ok, req.version()};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, "application/json");
res.keep_alive(req.keep_alive());
res.body() = response;
res.prepare_payload();
return send(std::move(res));
});
}
// Request path must be absolute and not contain "..".
auto target = req.target();
if (target.empty() || target[0] != '/' || target.find("..") != beast::string_view::npos)
return send(bad_request("Illegal request-target"));
static const string image_cache_target = "/__image_cache?name=";
auto pos = target.find(image_cache_target);
if (pos != std::string::npos)
{
pos += image_cache_target.size();
target = target.substr(pos);
auto image = settings_.image_cache.getImage(std::string(target));
LOG(DEBUG, LOG_TAG) << "image cache: " << target << ", found: " << image.has_value() << "\n";
if (image.has_value())
{
http::response<http::buffer_body> res{http::status::ok, req.version()};
res.body().data = image.value().data();
const auto size = image.value().size();
res.body().size = size;
res.body().more = false;
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, mime_type(target));
res.content_length(size);
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
return send(not_found(req.target()));
}
// Build the path to the requested file
std::string path = path_cat(settings_.doc_root, target);
if (req.target().back() == '/')
path.append("index.html");
if (settings_.doc_root.empty())
{
static constexpr auto default_page = "/usr/share/snapserver/index.html";
if (utils::file::exists(default_page))
path = default_page;
else
return send(unconfigured());
}
LOG(DEBUG, LOG_TAG) << "path: " << path << "\n";
// Attempt to open the file
beast::error_code ec;
http::file_body::value_type body;
body.open(path.c_str(), beast::file_mode::scan, ec);
// Handle the case where the file doesn't exist
if (ec == boost::system::errc::no_such_file_or_directory)
return send(not_found(req.target()));
// Handle an unknown error
if (ec)
return send(server_error(ec.message()));
// Cache the size since we need it after the move
auto const size = body.size();
// Respond to HEAD request
if (req.method() == http::verb::head)
{
http::response<http::empty_body> res{http::status::ok, req.version()};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
// Respond to GET request
http::response<http::file_body> res{std::piecewise_construct, std::make_tuple(std::move(body)), std::make_tuple(http::status::ok, req.version())};
res.set(http::field::server, HTTP_SERVER_NAME);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
void ControlSessionHttp::on_read(beast::error_code ec, std::size_t bytes_transferred)
{
// This means they closed the connection
if (ec == http::error::end_of_stream)
{
socket_.shutdown(tcp::socket::shutdown_send, ec);
return;
}
// Handle the error, if any
if (ec)
{
LOG(ERROR, LOG_TAG) << "ControlSessionHttp::on_read error: " << ec.message() << "\n";
return;
}
LOG(DEBUG, LOG_TAG) << "read: " << bytes_transferred << ", method: " << req_.method_string() << ", content type: " << req_[beast::http::field::content_type]
<< ", target: " << req_.target() << ", body: " << req_.body() << "\n";
// See if it is a WebSocket Upgrade
if (websocket::is_upgrade(req_))
{
LOG(DEBUG, LOG_TAG) << "websocket upgrade, target: " << req_.target() << "\n";
if (req_.target() == "/jsonrpc")
{
// Create a WebSocket session by transferring the socket
// std::make_shared<websocket_session>(std::move(socket_), state_)->run(std::move(req_));
auto ws = std::make_shared<websocket::stream<beast::tcp_stream>>(std::move(socket_));
ws->async_accept(req_,
[this, ws, self = shared_from_this()](beast::error_code ec)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error during WebSocket handshake (control): " << ec.message() << "\n";
}
else
{
auto ws_session = make_shared<ControlSessionWebsocket>(message_receiver_, std::move(*ws));
message_receiver_->onNewSession(std::move(ws_session));
}
});
}
else if (req_.target() == "/stream")
{
// Create a WebSocket session by transferring the socket
// std::make_shared<websocket_session>(std::move(socket_), state_)->run(std::move(req_));
auto ws = std::make_shared<websocket::stream<beast::tcp_stream>>(std::move(socket_));
ws->async_accept(req_,
[this, ws, self = shared_from_this()](beast::error_code ec)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error during WebSocket handshake (stream): " << ec.message() << "\n";
}
else
{
auto ws_session = make_shared<StreamSessionWebsocket>(nullptr, std::move(*ws));
message_receiver_->onNewSession(std::move(ws_session));
}
});
}
return;
}
// Send the response
handle_request(std::move(req_),
[this](auto&& response)
{
// The lifetime of the message has to extend
// for the duration of the async operation so
// we use a shared_ptr to manage it.
using response_type = typename std::decay<decltype(response)>::type;
auto sp = std::make_shared<response_type>(std::forward<decltype(response)>(response));
// Write the response
http::async_write(this->socket_, *sp,
[this, self = this->shared_from_this(), sp](beast::error_code ec, std::size_t bytes) { this->on_write(ec, bytes, sp->need_eof()); });
});
}
void ControlSessionHttp::on_write(beast::error_code ec, std::size_t bytes, bool close)
{
std::ignore = bytes;
// Handle the error, if any
if (ec)
{
LOG(ERROR, LOG_TAG) << "ControlSessionHttp::on_write, error: " << ec.message() << "\n";
return;
}
if (close)
{
// This means we should close the connection, usually because
// the response indicated the "Connection: close" semantic.
socket_.shutdown(tcp::socket::shutdown_send, ec);
return;
}
// Clear contents of the request message,
// otherwise the read behavior is undefined.
req_ = {};
// Read another request
http::async_read(socket_, buffer_, req_, [this, self = shared_from_this()](beast::error_code ec, std::size_t bytes) { on_read(ec, bytes); });
}
void ControlSessionHttp::stop()
{
}
void ControlSessionHttp::sendAsync(const std::string& /*message*/)
{
}
| 16,432
|
C++
|
.cpp
| 393
| 34.29771
| 160
| 0.598174
|
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,946
|
control_session_tcp.cpp
|
badaix_snapcast/server/control_session_tcp.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 "control_session_tcp.hpp"
// 3rd party headers
#include <boost/asio/read_until.hpp>
#include <boost/asio/write.hpp>
// local headers
#include "common/aixlog.hpp"
using namespace std;
static constexpr auto LOG_TAG = "ControlSessionTCP";
// https://stackoverflow.com/questions/7754695/boost-asio-async-write-how-to-not-interleaving-async-write-calls/7756894
ControlSessionTcp::ControlSessionTcp(ControlMessageReceiver* receiver, tcp::socket&& socket)
: ControlSession(receiver), socket_(std::move(socket)), strand_(boost::asio::make_strand(socket_.get_executor()))
{
}
ControlSessionTcp::~ControlSessionTcp()
{
LOG(DEBUG, LOG_TAG) << "ControlSessionTcp::~ControlSessionTcp()\n";
stop();
}
void ControlSessionTcp::do_read()
{
const std::string delimiter = "\n";
boost::asio::async_read_until(socket_, streambuf_, delimiter,
[this, self = shared_from_this(), delimiter](const std::error_code& ec, std::size_t bytes_transferred)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while reading from control socket: " << ec.message() << "\n";
return;
}
// Extract up to the first delimiter.
std::string line{buffers_begin(streambuf_.data()), buffers_begin(streambuf_.data()) + bytes_transferred - delimiter.length()};
if (!line.empty())
{
if (line.back() == '\r')
line.resize(line.size() - 1);
// LOG(DEBUG, LOG_TAG) << "received: " << line << "\n";
if ((message_receiver_ != nullptr) && !line.empty())
{
message_receiver_->onMessageReceived(shared_from_this(), line,
[this](const std::string& response)
{
if (!response.empty())
sendAsync(response);
});
}
}
streambuf_.consume(bytes_transferred);
do_read();
});
}
void ControlSessionTcp::start()
{
do_read();
}
void ControlSessionTcp::stop()
{
LOG(DEBUG, LOG_TAG) << "ControlSession::stop\n";
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() << "\n";
socket_.close(ec);
if (ec)
LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << "\n";
LOG(DEBUG, LOG_TAG) << "ControlSession ControlSession stopped\n";
}
void ControlSessionTcp::sendAsync(const std::string& message)
{
boost::asio::post(strand_,
[this, self = shared_from_this(), message]()
{
messages_.emplace_back(message + "\r\n");
if (messages_.size() > 1)
{
LOG(DEBUG, LOG_TAG) << "TCP session outstanding async_writes: " << messages_.size() << "\n";
return;
}
send_next();
});
}
void ControlSessionTcp::send_next()
{
boost::asio::async_write(socket_, boost::asio::buffer(messages_.front()),
[this, self = shared_from_this()](std::error_code ec, std::size_t length)
{
messages_.pop_front();
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while writing to control socket: " << ec.message() << "\n";
}
else
{
LOG(TRACE, LOG_TAG) << "Wrote " << length << " bytes to control socket\n";
}
if (!messages_.empty())
send_next();
});
}
| 4,439
|
C++
|
.cpp
| 113
| 30.699115
| 136
| 0.587073
|
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,947
|
config.cpp
|
badaix_snapcast/server/config.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 "config.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/file_utils.hpp"
// standard headers
#include <cerrno>
#include <fcntl.h>
#include <fstream>
#include <sys/stat.h>
#include <sys/types.h>
using namespace std;
Config::~Config()
{
save();
}
void Config::init(const std::string& root_directory, const std::string& user, const std::string& group)
{
string dir;
if (!root_directory.empty())
dir = root_directory;
else if (getenv("HOME") == nullptr)
dir = "/var/lib/snapserver/";
else
dir = string(getenv("HOME")) + "/.config/snapserver/";
if (!dir.empty() && (dir.back() != '/'))
dir += "/";
// if (dir.find("/var/lib/snapserver") == string::npos)
// dir += ".config/snapserver/";
int status = utils::file::mkdirRecursive(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if ((status != 0) && (errno != EEXIST))
throw SnapException("failed to create settings directory: \"" + dir + "\": " + cpt::to_string(errno));
filename_ = dir + "server.json";
LOG(NOTICE) << "Settings file: \"" << filename_ << "\"\n";
int fd;
if ((fd = open(filename_.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
{
if (errno == EACCES)
throw std::runtime_error("failed to open file \"" + filename_ + "\", permission denied (error " + cpt::to_string(errno) + ")");
else
throw std::runtime_error("failed to open file \"" + filename_ + "\", error " + cpt::to_string(errno));
}
close(fd);
if (!user.empty() && !group.empty())
{
try
{
utils::file::do_chown(dir, user, group);
utils::file::do_chown(filename_, user, group);
}
catch (const std::exception& e)
{
LOG(ERROR) << "Exception in chown: " << e.what() << "\n";
}
}
try
{
ifstream ifs(filename_, std::ifstream::in);
if (ifs.good() && (ifs.peek() != std::ifstream::traits_type::eof()))
{
json j;
ifs >> j;
if (j.count("ConfigVersion") != 0u)
{
json jGroups = j["Groups"];
for (const auto& jGroup : jGroups)
{
GroupPtr group = make_shared<Group>();
group->fromJson(jGroup);
// if (client->id.empty() || getClientInfo(client->id))
// continue;
groups.push_back(group);
}
}
}
}
catch (const std::exception& e)
{
LOG(ERROR) << "Error reading config: " << e.what() << "\n";
}
}
void Config::save()
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (filename_.empty())
init();
std::ofstream ofs(filename_.c_str(), std::ofstream::out | std::ofstream::trunc);
json clients = {{"ConfigVersion", 2}, {"Groups", getGroups()}};
// ofs << std::setw(4) << clients;
ofs << clients;
ofs.close();
}
ClientInfoPtr Config::getClientInfo(const std::string& clientId) const
{
if (clientId.empty())
return nullptr;
std::lock_guard<std::recursive_mutex> lock(mutex_);
for (const auto& group : groups)
{
for (auto client : group->clients)
{
if (client->id == clientId)
return client;
}
}
return nullptr;
}
GroupPtr Config::addClientInfo(ClientInfoPtr client)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
GroupPtr group = getGroupFromClient(client);
if (!group)
{
group = std::make_shared<Group>();
group->addClient(client);
groups.push_back(group);
}
return group;
}
GroupPtr Config::addClientInfo(const std::string& clientId)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
ClientInfoPtr client = getClientInfo(clientId);
if (!client)
client = make_shared<ClientInfo>(clientId);
return addClientInfo(client);
}
GroupPtr Config::getGroup(const std::string& groupId) const
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
for (const auto& group : groups)
{
if (group->id == groupId)
return group;
}
return nullptr;
}
GroupPtr Config::getGroupFromClient(const std::string& clientId)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
for (const auto& group : groups)
{
for (const auto& c : group->clients)
{
if (c->id == clientId)
return group;
}
}
return nullptr;
}
GroupPtr Config::getGroupFromClient(ClientInfoPtr client)
{
return getGroupFromClient(client->id);
}
json Config::getServerStatus(const json& streams) const
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
Host host;
host.update();
// TODO: Set MAC and IP
Snapserver snapserver("Snapserver", VERSION);
json serverStatus = {{"server",
{{"host", host.toJson()}, // getHostName()},
{"snapserver", snapserver.toJson()}}},
{"groups", getGroups()},
{"streams", streams}};
return serverStatus;
}
json Config::getGroups() const
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
json result = json::array();
for (const auto& group : groups)
result.push_back(group->toJson());
return result;
}
void Config::remove(ClientInfoPtr client)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
auto group = getGroupFromClient(client);
if (!group)
return;
group->removeClient(client);
if (group->empty())
remove(group);
}
void Config::remove(GroupPtr group, bool force)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (!group)
return;
if (group->empty() || force)
groups.erase(std::remove(groups.begin(), groups.end(), group), groups.end());
}
std::mutex& Config::getMutex()
{
return client_mutex_;
}
/*
GroupPtr Config::removeFromGroup(const std::string& groupId, const std::string& clientId)
{
GroupPtr group = getGroup(groupId);
if (!group || (group->id != groupId))
return group;
auto client = getClientInfo(clientId);
if (client)
group->clients.erase(std::remove(group->clients.begin(), group->clients.end(), client), group->clients.end());
addClientInfo(clientId);
return group;
}
GroupPtr Config::setGroupForClient(const std::string& groupId, const std::string& clientId)
{
GroupPtr oldGroup = getGroupFromClient(clientId);
if (oldGroup && (oldGroup->id == groupId))
return oldGroup;
GroupPtr newGroup = getGroup(groupId);
if (!newGroup)
return nullptr;
auto client = getClientInfo(clientId);
if (!client)
return nullptr;
if (oldGroup)
removeFromGroup(oldGroup->id, clientId);
newGroup->addClient(client);
return newGroup;
}
*/
| 7,984
|
C++
|
.cpp
| 243
| 26.156379
| 139
| 0.600286
|
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,948
|
control_session_ws.cpp
|
badaix_snapcast/server/control_session_ws.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 "control_session_ws.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
static constexpr auto LOG_TAG = "ControlSessionWS";
ControlSessionWebsocket::ControlSessionWebsocket(ControlMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket)
: ControlSession(receiver), ws_(std::move(socket)), strand_(boost::asio::make_strand(ws_.get_executor()))
{
LOG(DEBUG, LOG_TAG) << "ControlSessionWebsocket\n";
}
ControlSessionWebsocket::~ControlSessionWebsocket()
{
LOG(DEBUG, LOG_TAG) << "ControlSessionWebsocket::~ControlSessionWebsocket()\n";
stop();
}
void ControlSessionWebsocket::start()
{
// Read a message
do_read_ws();
}
void ControlSessionWebsocket::stop()
{
// if (ws_.is_open())
// {
// boost::beast::error_code ec;
// ws_.close(beast::websocket::close_code::normal, ec);
// if (ec)
// LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << "\n";
// }
}
void ControlSessionWebsocket::sendAsync(const std::string& message)
{
boost::asio::post(strand_,
[this, self = shared_from_this(), msg = message]()
{
messages_.push_back(std::move(msg));
if (messages_.size() > 1)
{
LOG(DEBUG, LOG_TAG) << "HTTP session outstanding async_writes: " << messages_.size() << "\n";
return;
}
send_next();
});
}
void ControlSessionWebsocket::send_next()
{
const std::string& message = messages_.front();
ws_.async_write(boost::asio::buffer(message),
[this, self = shared_from_this()](std::error_code ec, std::size_t length)
{
messages_.pop_front();
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while writing to web socket: " << ec.message() << "\n";
}
else
{
LOG(TRACE, LOG_TAG) << "Wrote " << length << " bytes to web socket\n";
}
if (!messages_.empty())
send_next();
});
}
void ControlSessionWebsocket::do_read_ws()
{
// Read a message into our buffer
ws_.async_read(buffer_, [this, self = shared_from_this()](beast::error_code ec, std::size_t bytes_transferred) { on_read_ws(ec, bytes_transferred); });
}
void ControlSessionWebsocket::on_read_ws(beast::error_code ec, std::size_t bytes_transferred)
{
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if (ec == websocket::error::closed)
return;
if (ec)
{
LOG(ERROR, LOG_TAG) << "ControlSessionWebsocket::on_read_ws error: " << ec.message() << "\n";
return;
}
std::string line{boost::beast::buffers_to_string(buffer_.data())};
if (!line.empty())
{
// LOG(DEBUG, LOG_TAG) << "received: " << line << "\n";
if ((message_receiver_ != nullptr) && !line.empty())
{
message_receiver_->onMessageReceived(shared_from_this(), line,
[this](const std::string& response)
{
if (!response.empty())
{
sendAsync(response);
}
});
}
}
buffer_.consume(bytes_transferred);
do_read_ws();
}
| 4,233
|
C++
|
.cpp
| 117
| 29.213675
| 155
| 0.607877
|
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,949
|
stream_server.cpp
|
badaix_snapcast/server/stream_server.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 "stream_server.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/message/client_info.hpp"
#include "common/message/hello.hpp"
#include "common/message/time.hpp"
#include "config.hpp"
#include "stream_session_tcp.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
using namespace streamreader;
using json = nlohmann::json;
static constexpr auto LOG_TAG = "StreamServer";
StreamServer::StreamServer(boost::asio::io_context& io_context, const ServerSettings& serverSettings, StreamMessageReceiver* messageReceiver)
: io_context_(io_context), config_timer_(io_context), settings_(serverSettings), messageReceiver_(messageReceiver)
{
}
StreamServer::~StreamServer() = default;
void StreamServer::cleanup()
{
auto new_end = std::remove_if(sessions_.begin(), sessions_.end(), [](std::weak_ptr<StreamSession> session) { return session.expired(); });
auto count = distance(new_end, sessions_.end());
if (count > 0)
{
LOG(INFO, LOG_TAG) << "Removing " << count << " inactive session(s), active sessions: " << sessions_.size() - count << "\n";
sessions_.erase(new_end, sessions_.end());
}
}
void StreamServer::addSession(std::shared_ptr<StreamSession> session)
{
session->setMessageReceiver(this);
session->setBufferMs(settings_.stream.bufferMs);
session->start();
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
sessions_.emplace_back(std::move(session));
cleanup();
}
void StreamServer::onChunkEncoded(const PcmStream* pcmStream, bool isDefaultStream, std::shared_ptr<msg::PcmChunk> chunk, double /*duration*/)
{
// LOG(TRACE, LOG_TAG) << "onChunkRead (" << pcmStream->getName() << "): " << duration << "ms\n";
shared_const_buffer buffer(*chunk);
// make a copy of the sessions to avoid that a session get's deleted
std::vector<std::shared_ptr<StreamSession>> sessions;
{
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
for (const auto& session : sessions_)
if (auto s = session.lock())
sessions.push_back(s);
}
for (const auto& session : sessions)
{
if (!settings_.stream.sendAudioToMutedClients)
{
std::lock_guard<std::mutex> lock(Config::instance().getMutex());
GroupPtr group = Config::instance().getGroupFromClient(session->clientId);
if (group)
{
if (group->muted)
{
continue;
}
else
{
ClientInfoPtr client = group->getClient(session->clientId);
if (client && client->config.volume.muted)
continue;
}
}
}
if (!session->pcmStream() && isDefaultStream) //->getName() == "default")
session->send(buffer);
else if (session->pcmStream().get() == pcmStream)
session->send(buffer);
}
}
void StreamServer::onMessageReceived(StreamSession* streamSession, const msg::BaseMessage& baseMessage, char* buffer)
{
try
{
if (messageReceiver_ != nullptr)
messageReceiver_->onMessageReceived(streamSession, baseMessage, buffer);
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Server::onMessageReceived exception: " << e.what() << ", message type: " << baseMessage.type << "\n";
auto session = getStreamSession(streamSession);
session->stop();
}
}
void StreamServer::onDisconnect(StreamSession* streamSession)
{
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
session_ptr session = getStreamSession(streamSession);
if (session == nullptr)
return;
LOG(INFO, LOG_TAG) << "onDisconnect: " << session->clientId << "\n";
LOG(DEBUG, LOG_TAG) << "sessions: " << sessions_.size() << "\n";
sessions_.erase(std::remove_if(sessions_.begin(), sessions_.end(),
[streamSession](std::weak_ptr<StreamSession> session)
{
auto s = session.lock();
return s.get() == streamSession;
}),
sessions_.end());
LOG(DEBUG, LOG_TAG) << "sessions: " << sessions_.size() << "\n";
if (messageReceiver_ != nullptr)
messageReceiver_->onDisconnect(streamSession);
cleanup();
}
session_ptr StreamServer::getStreamSession(StreamSession* streamSession) const
{
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
for (const auto& session : sessions_)
{
if (auto s = session.lock())
if (s.get() == streamSession)
return s;
}
return nullptr;
}
session_ptr StreamServer::getStreamSession(const std::string& clientId) const
{
// LOG(INFO, LOG_TAG) << "getStreamSession: " << mac << "\n";
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
for (const auto& session : sessions_)
{
if (auto s = session.lock())
if (s->clientId == clientId)
return s;
}
return nullptr;
}
void StreamServer::startAccept()
{
auto accept_handler = [this](error_code ec, tcp::socket socket)
{
if (!ec)
handleAccept(std::move(socket));
else
LOG(ERROR, LOG_TAG) << "Error while accepting socket connection: " << ec.message() << "\n";
};
for (auto& acceptor : acceptor_)
acceptor->async_accept(accept_handler);
}
void StreamServer::handleAccept(tcp::socket socket)
{
try
{
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
/// experimental: turn on tcp::no_delay
socket.set_option(tcp::no_delay(true));
LOG(NOTICE, LOG_TAG) << "StreamServer::NewConnection: " << socket.remote_endpoint().address().to_string() << endl;
shared_ptr<StreamSession> session = make_shared<StreamSessionTcp>(this, std::move(socket));
addSession(session);
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception in StreamServer::handleAccept: " << e.what() << endl;
}
startAccept();
}
void StreamServer::start()
{
for (const auto& address : settings_.stream.bind_to_address)
{
try
{
LOG(INFO, LOG_TAG) << "Creating stream acceptor for address: " << address << ", port: " << settings_.stream.port << "\n";
acceptor_.emplace_back(make_unique<tcp::acceptor>(boost::asio::make_strand(io_context_.get_executor()),
tcp::endpoint(boost::asio::ip::address::from_string(address), settings_.stream.port)));
}
catch (const boost::system::system_error& e)
{
LOG(ERROR, LOG_TAG) << "error creating TCP acceptor: " << e.what() << ", code: " << e.code() << "\n";
}
}
startAccept();
}
void StreamServer::stop()
{
for (auto& acceptor : acceptor_)
acceptor->cancel();
acceptor_.clear();
std::lock_guard<std::recursive_mutex> mlock(sessionsMutex_);
cleanup();
for (const auto& s : sessions_)
{
if (auto session = s.lock())
session->stop();
}
}
| 8,239
|
C++
|
.cpp
| 212
| 31.716981
| 149
| 0.624436
|
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,950
|
control_server.cpp
|
badaix_snapcast/server/control_server.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 "control_server.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/json.hpp"
#include "control_session_http.hpp"
#include "control_session_tcp.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
using json = nlohmann::json;
static constexpr auto LOG_TAG = "ControlServer";
ControlServer::ControlServer(boost::asio::io_context& io_context, const ServerSettings::Tcp& tcp_settings, const ServerSettings::Http& http_settings,
ControlMessageReceiver* controlMessageReceiver)
: io_context_(io_context), tcp_settings_(tcp_settings), http_settings_(http_settings), controlMessageReceiver_(controlMessageReceiver)
{
}
ControlServer::~ControlServer()
{
stop();
}
void ControlServer::cleanup()
{
auto new_end = std::remove_if(sessions_.begin(), sessions_.end(), [](const std::weak_ptr<ControlSession>& session) { return session.expired(); });
auto count = distance(new_end, sessions_.end());
if (count > 0)
{
LOG(INFO, LOG_TAG) << "Removing " << count << " inactive session(s), active sessions: " << sessions_.size() - count << "\n";
sessions_.erase(new_end, sessions_.end());
}
}
void ControlServer::send(const std::string& message, const ControlSession* excludeSession)
{
std::lock_guard<std::recursive_mutex> mlock(session_mutex_);
for (const auto& s : sessions_)
{
if (auto session = s.lock())
{
if (session.get() != excludeSession)
session->sendAsync(message);
}
}
cleanup();
}
void ControlServer::onMessageReceived(std::shared_ptr<ControlSession> session, const std::string& message, const ResponseHander& response_handler)
{
// LOG(DEBUG, LOG_TAG) << "received: \"" << message << "\"\n";
if (controlMessageReceiver_ != nullptr)
controlMessageReceiver_->onMessageReceived(std::move(session), message, response_handler);
}
void ControlServer::onNewSession(shared_ptr<ControlSession> session)
{
std::lock_guard<std::recursive_mutex> mlock(session_mutex_);
session->start();
sessions_.emplace_back(std::move(session));
cleanup();
}
void ControlServer::onNewSession(std::shared_ptr<StreamSession> session)
{
if (controlMessageReceiver_ != nullptr)
controlMessageReceiver_->onNewSession(std::move(session));
}
void ControlServer::startAccept()
{
auto accept_handler_tcp = [this](error_code ec, tcp::socket socket)
{
if (!ec)
handleAccept<ControlSessionTcp>(std::move(socket));
else
LOG(ERROR, LOG_TAG) << "Error while accepting socket connection: " << ec.message() << "\n";
};
auto accept_handler_http = [this](error_code ec, tcp::socket socket)
{
if (!ec)
handleAccept<ControlSessionHttp>(std::move(socket), http_settings_);
else
LOG(ERROR, LOG_TAG) << "Error while accepting socket connection: " << ec.message() << "\n";
};
for (auto& acceptor : acceptor_tcp_)
acceptor->async_accept(accept_handler_tcp);
for (auto& acceptor : acceptor_http_)
acceptor->async_accept(accept_handler_http);
}
template <typename SessionType, typename... Args>
void ControlServer::handleAccept(tcp::socket socket, Args&&... args)
{
try
{
struct timeval tv;
tv.tv_sec = 5;
tv.tv_usec = 0;
setsockopt(socket.native_handle(), SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(socket.native_handle(), SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
// socket->set_option(boost::asio::ip::tcp::no_delay(false));
LOG(NOTICE, LOG_TAG) << "ControlServer::NewConnection: " << socket.remote_endpoint().address().to_string() << endl;
shared_ptr<SessionType> session = make_shared<SessionType>(this, std::move(socket), std::forward<Args>(args)...);
onNewSession(std::move(session));
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception in ControlServer::handleAccept: " << e.what() << endl;
}
startAccept();
}
void ControlServer::start()
{
if (tcp_settings_.enabled)
{
for (const auto& address : tcp_settings_.bind_to_address)
{
try
{
LOG(INFO, LOG_TAG) << "Creating TCP acceptor for address: " << address << ", port: " << tcp_settings_.port << "\n";
acceptor_tcp_.emplace_back(make_unique<tcp::acceptor>(boost::asio::make_strand(io_context_.get_executor()),
tcp::endpoint(boost::asio::ip::address::from_string(address), tcp_settings_.port)));
}
catch (const boost::system::system_error& e)
{
LOG(ERROR, LOG_TAG) << "error creating TCP acceptor: " << e.what() << ", code: " << e.code() << "\n";
}
}
}
if (http_settings_.enabled)
{
for (const auto& address : http_settings_.bind_to_address)
{
try
{
LOG(INFO, LOG_TAG) << "Creating HTTP acceptor for address: " << address << ", port: " << http_settings_.port << "\n";
acceptor_http_.emplace_back(make_unique<tcp::acceptor>(boost::asio::make_strand(io_context_.get_executor()),
tcp::endpoint(boost::asio::ip::address::from_string(address), http_settings_.port)));
}
catch (const boost::system::system_error& e)
{
LOG(ERROR, LOG_TAG) << "error creating HTTP acceptor: " << e.what() << ", code: " << e.code() << "\n";
}
}
}
startAccept();
}
void ControlServer::stop()
{
for (auto& acceptor : acceptor_tcp_)
acceptor->cancel();
for (auto& acceptor : acceptor_http_)
acceptor->cancel();
acceptor_tcp_.clear();
acceptor_http_.clear();
std::lock_guard<std::recursive_mutex> mlock(session_mutex_);
cleanup();
for (const auto& s : sessions_)
{
if (auto session = s.lock())
session->stop();
}
}
| 6,936
|
C++
|
.cpp
| 171
| 33.467836
| 156
| 0.627361
|
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,951
|
stream_session_ws.cpp
|
badaix_snapcast/server/stream_session_ws.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 "stream_session_ws.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/message/pcm_chunk.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
static constexpr auto LOG_TAG = "StreamSessionWS";
StreamSessionWebsocket::StreamSessionWebsocket(StreamMessageReceiver* receiver, websocket::stream<beast::tcp_stream>&& socket)
: StreamSession(socket.get_executor(), receiver), ws_(std::move(socket))
{
LOG(DEBUG, LOG_TAG) << "StreamSessionWS\n";
}
StreamSessionWebsocket::~StreamSessionWebsocket()
{
LOG(DEBUG, LOG_TAG) << "~StreamSessionWS\n";
stop();
}
void StreamSessionWebsocket::start()
{
// Read a message
LOG(DEBUG, LOG_TAG) << "start\n";
ws_.binary(true);
do_read_ws();
}
void StreamSessionWebsocket::stop()
{
if (ws_.is_open())
{
boost::beast::error_code ec;
ws_.close(beast::websocket::close_code::normal, ec);
if (ec)
LOG(ERROR, LOG_TAG) << "Error in socket close: " << ec.message() << "\n";
}
}
std::string StreamSessionWebsocket::getIP()
{
try
{
return ws_.next_layer().socket().remote_endpoint().address().to_string();
}
catch (...)
{
return "0.0.0.0";
}
}
void StreamSessionWebsocket::sendAsync(const shared_const_buffer& buffer, const WriteHandler& handler)
{
LOG(TRACE, LOG_TAG) << "sendAsync: " << buffer.message().type << "\n";
ws_.async_write(buffer, [self = shared_from_this(), buffer, handler](boost::system::error_code ec, std::size_t length) { handler(ec, length); });
}
void StreamSessionWebsocket::do_read_ws()
{
// Read a message into our buffer
ws_.async_read(buffer_, [this, self = shared_from_this()](beast::error_code ec, std::size_t bytes_transferred) { on_read_ws(ec, bytes_transferred); });
}
void StreamSessionWebsocket::on_read_ws(beast::error_code ec, std::size_t bytes_transferred)
{
LOG(DEBUG, LOG_TAG) << "on_read_ws, ec: " << ec << ", bytes_transferred: " << bytes_transferred << "\n";
boost::ignore_unused(bytes_transferred);
// This indicates that the session was closed
if (ec == websocket::error::closed)
{
messageReceiver_->onDisconnect(this);
return;
}
if (ec)
{
LOG(ERROR, LOG_TAG) << "ControlSessionWebsocket::on_read_ws error: " << ec.message() << "\n";
messageReceiver_->onDisconnect(this);
return;
}
auto* data = boost::asio::buffer_cast<char*>(buffer_.data());
baseMessage_.deserialize(data);
LOG(DEBUG, LOG_TAG) << "getNextMessage: " << baseMessage_.type << ", size: " << baseMessage_.size << ", id: " << baseMessage_.id
<< ", refers: " << baseMessage_.refersTo << "\n";
tv t;
baseMessage_.received = t;
if (messageReceiver_ != nullptr)
messageReceiver_->onMessageReceived(this, baseMessage_, data + base_msg_size_);
buffer_.consume(bytes_transferred);
do_read_ws();
}
| 3,753
|
C++
|
.cpp
| 99
| 33.333333
| 155
| 0.671909
|
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,952
|
server.cpp
|
badaix_snapcast/server/server.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 "server.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/message/client_info.hpp"
#include "common/message/hello.hpp"
#include "common/message/server_settings.hpp"
#include "common/message/time.hpp"
#include "config.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
using namespace streamreader;
using json = nlohmann::json;
static constexpr auto LOG_TAG = "Server";
Server::Server(boost::asio::io_context& io_context, const ServerSettings& serverSettings)
: io_context_(io_context), config_timer_(io_context), settings_(serverSettings)
{
}
Server::~Server() = default;
void Server::onNewSession(std::shared_ptr<StreamSession> session)
{
LOG(DEBUG, LOG_TAG) << "onNewSession\n";
streamServer_->addSession(std::move(session));
}
void Server::onPropertiesChanged(const PcmStream* pcmStream, const Properties& properties)
{
LOG(DEBUG, LOG_TAG) << "Properties changed, stream: " << pcmStream->getName() << ", properties: " << properties.toJson().dump(3) << "\n";
// Send properties to all connected control clients
json notification =
jsonrpcpp::Notification("Stream.OnProperties", jsonrpcpp::Parameter("id", pcmStream->getId(), "properties", properties.toJson())).to_json();
controlServer_->send(notification.dump(), nullptr);
}
void Server::onStateChanged(const PcmStream* pcmStream, ReaderState state)
{
// clang-format off
// Notification: {"jsonrpc":"2.0","method":"Stream.OnUpdate","params":{"id":"stream 1","stream":{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}}}}
// clang-format on
LOG(INFO, LOG_TAG) << "onStateChanged (" << pcmStream->getName() << "): " << state << "\n";
// LOG(INFO, LOG_TAG) << pcmStream->toJson().dump(4);
json notification = jsonrpcpp::Notification("Stream.OnUpdate", jsonrpcpp::Parameter("id", pcmStream->getId(), "stream", pcmStream->toJson())).to_json();
controlServer_->send(notification.dump(), nullptr);
// cout << "Notification: " << notification.dump() << "\n";
}
void Server::onChunkRead(const PcmStream* pcmStream, const msg::PcmChunk& chunk)
{
std::ignore = pcmStream;
std::ignore = chunk;
}
void Server::onChunkEncoded(const PcmStream* pcmStream, std::shared_ptr<msg::PcmChunk> chunk, double duration)
{
streamServer_->onChunkEncoded(pcmStream, pcmStream == streamManager_->getDefaultStream().get(), chunk, duration);
}
void Server::onResync(const PcmStream* pcmStream, double ms)
{
LOG(INFO, LOG_TAG) << "onResync (" << pcmStream->getName() << "): " << ms << " ms\n";
}
void Server::onDisconnect(StreamSession* streamSession)
{
// notify controllers if not yet done
ClientInfoPtr clientInfo = Config::instance().getClientInfo(streamSession->clientId);
if (!clientInfo || !clientInfo->connected)
return;
clientInfo->connected = false;
chronos::systemtimeofday(&clientInfo->lastSeen);
saveConfig();
if (controlServer_ != nullptr)
{
// Check if there is no session of this client left
// Can happen in case of ungraceful disconnect/reconnect or
// in case of a duplicate client id
if (streamServer_->getStreamSession(clientInfo->id) == nullptr)
{
// clang-format off
// Notification:
// {"jsonrpc":"2.0","method":"Client.OnDisconnect","params":{"client":{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":81}},"connected":false,"host":{"arch":"x86_64","ip":"192.168.0.54","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025523,"usec":814067},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},"id":"00:21:6a:7d:74:fc"}}
// clang-format on
json notification =
jsonrpcpp::Notification("Client.OnDisconnect", jsonrpcpp::Parameter("id", clientInfo->id, "client", clientInfo->toJson())).to_json();
controlServer_->send(notification.dump());
// cout << "Notification: " << notification.dump() << "\n";
}
}
}
void Server::processRequest(const jsonrpcpp::request_ptr request, const OnResponse& on_response) const
{
jsonrpcpp::entity_ptr response;
jsonrpcpp::notification_ptr notification;
try
{
// LOG(INFO, LOG_TAG) << "Server::processRequest method: " << request->method << ", " << "id: " << request->id() << "\n";
Json result;
if (request->method().find("Client.") == 0)
{
ClientInfoPtr clientInfo = Config::instance().getClientInfo(request->params().get<std::string>("id"));
if (clientInfo == nullptr)
throw jsonrpcpp::InternalErrorException("Client not found", request->id());
if (request->method() == "Client.GetStatus")
{
// clang-format off
// Request: {"id":8,"jsonrpc":"2.0","method":"Client.GetStatus","params":{"id":"00:21:6a:7d:74:fc"}}
// Response: {"id":8,"jsonrpc":"2.0","result":{"client":{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":74}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488026416,"usec":135973},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}}}
// clang-format on
result["client"] = clientInfo->toJson();
}
else if (request->method() == "Client.SetVolume")
{
// clang-format off
// Request: {"id":8,"jsonrpc":"2.0","method":"Client.SetVolume","params":{"id":"00:21:6a:7d:74:fc","volume":{"muted":false,"percent":74}}}
// Response: {"id":8,"jsonrpc":"2.0","result":{"volume":{"muted":false,"percent":74}}}
// Notification: {"jsonrpc":"2.0","method":"Client.OnVolumeChanged","params":{"id":"00:21:6a:7d:74:fc","volume":{"muted":false,"percent":74}}}
// clang-format on
clientInfo->config.volume.fromJson(request->params().get("volume"));
result["volume"] = clientInfo->config.volume.toJson();
notification = std::make_shared<jsonrpcpp::Notification>(
"Client.OnVolumeChanged", jsonrpcpp::Parameter("id", clientInfo->id, "volume", clientInfo->config.volume.toJson()));
}
else if (request->method() == "Client.SetLatency")
{
// clang-format off
// Request: {"id":7,"jsonrpc":"2.0","method":"Client.SetLatency","params":{"id":"00:21:6a:7d:74:fc#2","latency":10}}
// Response: {"id":7,"jsonrpc":"2.0","result":{"latency":10}}
// Notification: {"jsonrpc":"2.0","method":"Client.OnLatencyChanged","params":{"id":"00:21:6a:7d:74:fc#2","latency":10}}
// clang-format on
int latency = request->params().get("latency");
if (latency < -10000)
latency = -10000;
else if (latency > settings_.stream.bufferMs)
latency = settings_.stream.bufferMs;
clientInfo->config.latency = latency; //, -10000, settings_.stream.bufferMs);
result["latency"] = clientInfo->config.latency;
notification = std::make_shared<jsonrpcpp::Notification>("Client.OnLatencyChanged",
jsonrpcpp::Parameter("id", clientInfo->id, "latency", clientInfo->config.latency));
}
else if (request->method() == "Client.SetName")
{
// clang-format off
// Request: {"id":6,"jsonrpc":"2.0","method":"Client.SetName","params":{"id":"00:21:6a:7d:74:fc#2","name":"Laptop"}}
// Response: {"id":6,"jsonrpc":"2.0","result":{"name":"Laptop"}}
// Notification: {"jsonrpc":"2.0","method":"Client.OnNameChanged","params":{"id":"00:21:6a:7d:74:fc#2","name":"Laptop"}}
// clang-format on
clientInfo->config.name = request->params().get<std::string>("name");
result["name"] = clientInfo->config.name;
notification = std::make_shared<jsonrpcpp::Notification>("Client.OnNameChanged",
jsonrpcpp::Parameter("id", clientInfo->id, "name", clientInfo->config.name));
}
else
throw jsonrpcpp::MethodNotFoundException(request->id());
if (request->method().find("Client.Set") == 0)
{
/// Update client
session_ptr session = streamServer_->getStreamSession(clientInfo->id);
if (session != nullptr)
{
auto serverSettings = make_shared<msg::ServerSettings>();
serverSettings->setBufferMs(settings_.stream.bufferMs);
serverSettings->setVolume(clientInfo->config.volume.percent);
GroupPtr group = Config::instance().getGroupFromClient(clientInfo);
serverSettings->setMuted(clientInfo->config.volume.muted || group->muted);
serverSettings->setLatency(clientInfo->config.latency);
session->send(serverSettings);
}
}
}
else if (request->method().find("Group.") == 0)
{
GroupPtr group = Config::instance().getGroup(request->params().get<std::string>("id"));
if (group == nullptr)
throw jsonrpcpp::InternalErrorException("Group not found", request->id());
if (request->method() == "Group.GetStatus")
{
// clang-format off
// Request: {"id":5,"jsonrpc":"2.0","method":"Group.GetStatus","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1"}}
// Response: {"id":5,"jsonrpc":"2.0","result":{"group":{"clients":[{"config":{"instance":2,"latency":10,"name":"Laptop","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488026485,"usec":644997},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":74}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488026481,"usec":223747},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":true,"name":"","stream_id":"stream 1"}}}
// clang-format on
result["group"] = group->toJson();
}
else if (request->method() == "Group.SetName")
{
// clang-format off
// Request: {"id":6,"jsonrpc":"2.0","method":"Group.SetName","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","name":"Laptop"}}
// Response: {"id":6,"jsonrpc":"2.0","result":{"name":"MediaPlayer"}}
// Notification: {"jsonrpc":"2.0","method":"Group.OnNameChanged","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","MediaPlayer":"Laptop"}}
// clang-format on
group->name = request->params().get<std::string>("name");
result["name"] = group->name;
notification = std::make_shared<jsonrpcpp::Notification>("Group.OnNameChanged", jsonrpcpp::Parameter("id", group->id, "name", group->name));
}
else if (request->method() == "Group.SetMute")
{
// clang-format off
// Request: {"id":5,"jsonrpc":"2.0","method":"Group.SetMute","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","mute":true}}
// Response: {"id":5,"jsonrpc":"2.0","result":{"mute":true}}
// Notification: {"jsonrpc":"2.0","method":"Group.OnMute","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","mute":true}}
// clang-format on
bool muted = request->params().get<bool>("mute");
group->muted = muted;
/// Update clients
for (const auto& client : group->clients)
{
session_ptr session = streamServer_->getStreamSession(client->id);
if (session != nullptr)
{
auto serverSettings = make_shared<msg::ServerSettings>();
serverSettings->setBufferMs(settings_.stream.bufferMs);
serverSettings->setVolume(client->config.volume.percent);
GroupPtr group = Config::instance().getGroupFromClient(client);
serverSettings->setMuted(client->config.volume.muted || group->muted);
serverSettings->setLatency(client->config.latency);
session->send(serverSettings);
}
}
result["mute"] = group->muted;
notification = std::make_shared<jsonrpcpp::Notification>("Group.OnMute", jsonrpcpp::Parameter("id", group->id, "mute", group->muted));
}
else if (request->method() == "Group.SetStream")
{
// clang-format off
// Request: {"id":4,"jsonrpc":"2.0","method":"Group.SetStream","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","stream_id":"stream 1"}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"stream_id":"stream 1"}}
// Notification: {"jsonrpc":"2.0","method":"Group.OnStreamChanged","params":{"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","stream_id":"stream 1"}}
// clang-format on
string streamId = request->params().get<std::string>("stream_id");
PcmStreamPtr stream = streamManager_->getStream(streamId);
if (stream == nullptr)
throw jsonrpcpp::InternalErrorException("Stream not found", request->id());
group->streamId = streamId;
// Update clients
for (const auto& client : group->clients)
{
session_ptr session = streamServer_->getStreamSession(client->id);
if (session && (session->pcmStream() != stream))
{
// session->send(stream->getMeta());
session->send(stream->getHeader());
session->setPcmStream(stream);
}
}
// Notify others
result["stream_id"] = group->streamId;
notification =
std::make_shared<jsonrpcpp::Notification>("Group.OnStreamChanged", jsonrpcpp::Parameter("id", group->id, "stream_id", group->streamId));
}
else if (request->method() == "Group.SetClients")
{
// clang-format off
// Request: {"id":3,"jsonrpc":"2.0","method":"Group.SetClients","params":{"clients":["00:21:6a:7d:74:fc#2","00:21:6a:7d:74:fc"],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1"}}
// Response: {"id":3,"jsonrpc":"2.0","result":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025901,"usec":864472},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":100}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025905,"usec":45238},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// Notification: {"jsonrpc":"2.0","method":"Server.OnUpdate","params":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025901,"usec":864472},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":100}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025905,"usec":45238},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// clang-format on
vector<string> clients = request->params().get("clients");
// Remove clients from group
for (auto iter = group->clients.begin(); iter != group->clients.end();)
{
auto client = *iter;
if (find(clients.begin(), clients.end(), client->id) != clients.end())
{
++iter;
continue;
}
iter = group->clients.erase(iter);
GroupPtr newGroup = Config::instance().addClientInfo(client);
newGroup->streamId = group->streamId;
}
// Add clients to group
PcmStreamPtr stream = streamManager_->getStream(group->streamId);
for (const auto& clientId : clients)
{
ClientInfoPtr client = Config::instance().getClientInfo(clientId);
if (!client)
continue;
GroupPtr oldGroup = Config::instance().getGroupFromClient(client);
if (oldGroup && (oldGroup->id == group->id))
continue;
if (oldGroup)
{
oldGroup->removeClient(client);
Config::instance().remove(oldGroup);
}
group->addClient(client);
// assign new stream
session_ptr session = streamServer_->getStreamSession(client->id);
if (session && stream && (session->pcmStream() != stream))
{
// session->send(stream->getMeta());
session->send(stream->getHeader());
session->setPcmStream(stream);
}
}
if (group->empty())
Config::instance().remove(group);
json server = Config::instance().getServerStatus(streamManager_->toJson());
result["server"] = server;
// Notify others: since at least two groups are affected, send a complete server update
notification = std::make_shared<jsonrpcpp::Notification>("Server.OnUpdate", jsonrpcpp::Parameter("server", server));
}
else
throw jsonrpcpp::MethodNotFoundException(request->id());
}
else if (request->method().find("Server.") == 0)
{
if (request->method().find("Server.GetRPCVersion") == 0)
{
// Request: {"id":8,"jsonrpc":"2.0","method":"Server.GetRPCVersion"}
// Response: {"id":8,"jsonrpc":"2.0","result":{"major":2,"minor":0,"patch":0}}
// <major>: backwards incompatible change
result["major"] = 2;
// <minor>: feature addition to the API
result["minor"] = 0;
// <patch>: bugfix release
result["patch"] = 0;
}
else if (request->method() == "Server.GetStatus")
{
// clang-format off
// Request: {"id":1,"jsonrpc":"2.0","method":"Server.GetStatus"}
// Response: {"id":1,"jsonrpc":"2.0","result":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025696,"usec":578142},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":81}},"connected":true,"host":{"arch":"x86_64","ip":"192.168.0.54","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025696,"usec":611255},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// clang-format on
result["server"] = Config::instance().getServerStatus(streamManager_->toJson());
}
else if (request->method() == "Server.DeleteClient")
{
// clang-format off
// Request: {"id":2,"jsonrpc":"2.0","method":"Server.DeleteClient","params":{"id":"00:21:6a:7d:74:fc"}}
// Response: {"id":2,"jsonrpc":"2.0","result":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025751,"usec":654777},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// Notification: {"jsonrpc":"2.0","method":"Server.OnUpdate","params":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025751,"usec":654777},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// clang-format on
ClientInfoPtr clientInfo = Config::instance().getClientInfo(request->params().get<std::string>("id"));
if (clientInfo == nullptr)
throw jsonrpcpp::InternalErrorException("Client not found", request->id());
Config::instance().remove(clientInfo);
json server = Config::instance().getServerStatus(streamManager_->toJson());
result["server"] = server;
/// Notify others
notification = std::make_shared<jsonrpcpp::Notification>("Server.OnUpdate", jsonrpcpp::Parameter("server", server));
}
else
throw jsonrpcpp::MethodNotFoundException(request->id());
}
else if (request->method().find("Stream.") == 0)
{
// if (request->method().find("Stream.SetMeta") == 0)
// {
// clang-format off
// Request: {"id":4,"jsonrpc":"2.0","method":"Stream.SetMeta","params":{"id":"Spotify", "metadata": {"album": "some album", "artist": "some artist", "track": "some track"...}}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"id":"Spotify"}}
// clang-format on
// LOG(INFO, LOG_TAG) << "Stream.SetMeta id: " << request->params().get<std::string>("id") << ", meta: " << request->params().get("metadata") <<
// "\n";
// // Find stream
// string streamId = request->params().get<std::string>("id");
// PcmStreamPtr stream = streamManager_->getStream(streamId);
// if (stream == nullptr)
// throw jsonrpcpp::InternalErrorException("Stream not found", request->id());
// // Set metadata from request
// stream->setMetadata(request->params().get("metadata"));
// // Setup response
// result["id"] = streamId;
// }
if (request->method().find("Stream.Control") == 0)
{
// clang-format off
// Request: {"id":4,"jsonrpc":"2.0","method":"Stream.Control","params":{"id":"Spotify", "command": "next", params: {}}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"id":"Spotify"}}
//
// Request: {"id":4,"jsonrpc":"2.0","method":"Stream.Control","params":{"id":"Spotify", "command": "seek", "param": "60000"}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"id":"Spotify"}}
// clang-format on
LOG(INFO, LOG_TAG) << "Stream.Control id: " << request->params().get<std::string>("id") << ", command: " << request->params().get("command")
<< ", params: " << (request->params().has("params") ? request->params().get("params") : "") << "\n";
// Find stream
string streamId = request->params().get<std::string>("id");
PcmStreamPtr stream = streamManager_->getStream(streamId);
if (stream == nullptr)
throw jsonrpcpp::InternalErrorException("Stream not found", request->id());
if (!request->params().has("command"))
throw jsonrpcpp::InvalidParamsException("Parameter 'commmand' is missing", request->id());
auto command = request->params().get<string>("command");
auto handle_response = [request, on_response, command](const snapcast::ErrorCode& ec)
{
auto log_level = AixLog::Severity::debug;
if (ec)
log_level = AixLog::Severity::error;
LOG(log_level, LOG_TAG) << "Response to '" << command << "': " << ec << ", message: " << ec.detailed_message() << ", msg: " << ec.message()
<< ", category: " << ec.category().name() << "\n";
std::shared_ptr<jsonrpcpp::Response> response;
if (ec)
response = make_shared<jsonrpcpp::Response>(request->id(), jsonrpcpp::Error(ec.detailed_message(), ec.value()));
else
response = make_shared<jsonrpcpp::Response>(request->id(), "ok");
// LOG(DEBUG, LOG_TAG) << response->to_json().dump() << "\n";
on_response(response, nullptr);
};
if (command == "setPosition")
{
if (!request->params().has("params") || !request->params().get("params").contains("position"))
throw jsonrpcpp::InvalidParamsException("setPosition requires parameter 'position'");
auto seconds = request->params().get("params")["position"].get<float>();
stream->setPosition(std::chrono::milliseconds(static_cast<int>(seconds * 1000)),
[handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "seek")
{
if (!request->params().has("params") || !request->params().get("params").contains("offset"))
throw jsonrpcpp::InvalidParamsException("Seek requires parameter 'offset'");
auto offset = request->params().get("params")["offset"].get<float>();
stream->seek(std::chrono::milliseconds(static_cast<int>(offset * 1000)),
[handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "next")
{
stream->next([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "previous")
{
stream->previous([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "pause")
{
stream->pause([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "playPause")
{
stream->playPause([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "stop")
{
stream->stop([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (command == "play")
{
stream->play([handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else
throw jsonrpcpp::InvalidParamsException("Command '" + command + "' not supported", request->id());
return;
}
else if (request->method().find("Stream.SetProperty") == 0)
{
LOG(INFO, LOG_TAG) << "Stream.SetProperty id: " << request->params().get<std::string>("id")
<< ", property: " << request->params().get("property") << ", value: " << request->params().get("value") << "\n";
// Find stream
string streamId = request->params().get<std::string>("id");
PcmStreamPtr stream = streamManager_->getStream(streamId);
if (stream == nullptr)
throw jsonrpcpp::InternalErrorException("Stream not found", request->id());
if (!request->params().has("property"))
throw jsonrpcpp::InvalidParamsException("Parameter 'property' is missing", request->id());
if (!request->params().has("value"))
throw jsonrpcpp::InvalidParamsException("Parameter 'value' is missing", request->id());
auto name = request->params().get<string>("property");
auto value = request->params().get("value");
LOG(INFO, LOG_TAG) << "Stream '" << streamId << "' set property: " << name << " = " << value << "\n";
auto handle_response = [request, on_response](const snapcast::ErrorCode& ec)
{
LOG(ERROR, LOG_TAG) << "SetShuffle: " << ec << ", message: " << ec.detailed_message() << ", msg: " << ec.message()
<< ", category: " << ec.category().name() << "\n";
std::shared_ptr<jsonrpcpp::Response> response;
if (ec)
response = make_shared<jsonrpcpp::Response>(request->id(), jsonrpcpp::Error(ec.detailed_message(), ec.value()));
else
response = make_shared<jsonrpcpp::Response>(request->id(), "ok");
on_response(response, nullptr);
};
if (name == "loopStatus")
{
auto val = value.get<std::string>();
LoopStatus loop_status = loop_status_from_string(val);
if (loop_status == LoopStatus::kUnknown)
throw jsonrpcpp::InvalidParamsException("Value for loopStatus must be one of 'none', 'track', 'playlist'", request->id());
stream->setLoopStatus(loop_status, [handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (name == "shuffle")
{
if (!value.is_boolean())
throw jsonrpcpp::InvalidParamsException("Value for shuffle must be bool", request->id());
stream->setShuffle(value.get<bool>(), [handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (name == "volume")
{
if (!value.is_number_integer())
throw jsonrpcpp::InvalidParamsException("Value for volume must be an int", request->id());
stream->setVolume(value.get<int16_t>(), [handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (name == "mute")
{
if (!value.is_boolean())
throw jsonrpcpp::InvalidParamsException("Value for mute must be bool", request->id());
stream->setMute(value.get<bool>(), [handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else if (name == "rate")
{
if (!value.is_number_float())
throw jsonrpcpp::InvalidParamsException("Value for rate must be float", request->id());
stream->setRate(value.get<float>(), [handle_response](const snapcast::ErrorCode& ec) { handle_response(ec); });
}
else
throw jsonrpcpp::InvalidParamsException("Property '" + name + "' not supported", request->id());
return;
}
else if (request->method() == "Stream.AddStream")
{
// clang-format off
// Request: {"id":4,"jsonrpc":"2.0","method":"Stream.AddStream","params":{"streamUri":"uri"}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"id":"Spotify"}}
// clang-format on
LOG(INFO, LOG_TAG) << "Stream.AddStream(" << request->params().get("streamUri") << ")"
<< "\n";
// Find stream
string streamUri = request->params().get("streamUri");
PcmStreamPtr stream = streamManager_->addStream(streamUri);
if (stream == nullptr)
throw jsonrpcpp::InternalErrorException("Stream not created", request->id());
stream->start(); // We start the stream, otherwise it would be silent
// Setup response
result["id"] = stream->getId();
}
else if (request->method() == "Stream.RemoveStream")
{
// clang-format off
// Request: {"id":4,"jsonrpc":"2.0","method":"Stream.RemoveStream","params":{"id":"Spotify"}}
// Response: {"id":4,"jsonrpc":"2.0","result":{"id":"Spotify"}}
// clang-format on
LOG(INFO, LOG_TAG) << "Stream.RemoveStream(" << request->params().get("id") << ")"
<< "\n";
// Find stream
string streamId = request->params().get("id");
streamManager_->removeStream(streamId);
// Setup response
result["id"] = streamId;
}
else
throw jsonrpcpp::MethodNotFoundException(request->id());
}
else
throw jsonrpcpp::MethodNotFoundException(request->id());
response = std::make_shared<jsonrpcpp::Response>(*request, result);
}
catch (const jsonrpcpp::RequestException& e)
{
LOG(ERROR, LOG_TAG) << "Server::onMessageReceived JsonRequestException: " << e.to_json().dump() << ", message: " << request->to_json().dump() << "\n";
response = std::make_shared<jsonrpcpp::RequestException>(e);
}
catch (const exception& e)
{
LOG(ERROR, LOG_TAG) << "Server::onMessageReceived exception: " << e.what() << ", message: " << request->to_json().dump() << "\n";
response = std::make_shared<jsonrpcpp::InternalErrorException>(e.what(), request->id());
}
on_response(std::move(response), std::move(notification));
}
void Server::onMessageReceived(std::shared_ptr<ControlSession> controlSession, const std::string& message, const ResponseHander& response_handler)
{
// LOG(DEBUG, LOG_TAG) << "onMessageReceived: " << message << "\n";
std::lock_guard<std::mutex> lock(Config::instance().getMutex());
jsonrpcpp::entity_ptr entity(nullptr);
try
{
entity = jsonrpcpp::Parser::do_parse(message);
if (!entity)
return response_handler("");
}
catch (const jsonrpcpp::ParseErrorException& e)
{
return response_handler(e.to_json().dump());
}
catch (const std::exception& e)
{
return response_handler(jsonrpcpp::ParseErrorException(e.what()).to_json().dump());
}
jsonrpcpp::entity_ptr response(nullptr);
jsonrpcpp::notification_ptr notification(nullptr);
if (entity->is_request())
{
jsonrpcpp::request_ptr request = dynamic_pointer_cast<jsonrpcpp::Request>(entity);
processRequest(request,
[this, controlSession, response_handler](jsonrpcpp::entity_ptr response, jsonrpcpp::notification_ptr notification)
{
saveConfig();
////cout << "Request: " << request->to_json().dump() << "\n";
if (notification)
{
////cout << "Notification: " << notification->to_json().dump() << "\n";
controlServer_->send(notification->to_json().dump(), controlSession.get());
}
if (response)
{
////cout << "Response: " << response->to_json().dump() << "\n";
return response_handler(response->to_json().dump());
}
return response_handler("");
});
}
else if (entity->is_batch())
{
/// Attention: this will only work as long as the response handler in processRequest is called synchronously. One way to do this is to remove the outer
/// loop and to call the next processRequest with
/// This is true for volume changes, which is the only batch request, but not for Control commands!
jsonrpcpp::batch_ptr batch = dynamic_pointer_cast<jsonrpcpp::Batch>(entity);
////cout << "Batch: " << batch->to_json().dump() << "\n";
jsonrpcpp::Batch responseBatch;
jsonrpcpp::Batch notificationBatch;
for (const auto& batch_entity : batch->entities)
{
if (batch_entity->is_request())
{
jsonrpcpp::request_ptr request = dynamic_pointer_cast<jsonrpcpp::Request>(batch_entity);
processRequest(request,
[controlSession, response_handler, &responseBatch, ¬ificationBatch](jsonrpcpp::entity_ptr response,
jsonrpcpp::notification_ptr notification)
{
if (response != nullptr)
responseBatch.add_ptr(response);
if (notification != nullptr)
notificationBatch.add_ptr(notification);
});
}
}
saveConfig();
if (!notificationBatch.entities.empty())
controlServer_->send(notificationBatch.to_json().dump(), controlSession.get());
if (!responseBatch.entities.empty())
return response_handler(responseBatch.to_json().dump());
return response_handler("");
}
return response_handler("");
}
void Server::onMessageReceived(StreamSession* streamSession, const msg::BaseMessage& baseMessage, char* buffer)
{
LOG(DEBUG, LOG_TAG) << "onMessageReceived: " << baseMessage.type << ", size: " << baseMessage.size << ", id: " << baseMessage.id
<< ", refers: " << baseMessage.refersTo << ", sent: " << baseMessage.sent.sec << "," << baseMessage.sent.usec
<< ", recv: " << baseMessage.received.sec << "," << baseMessage.received.usec << "\n";
std::lock_guard<std::mutex> lock(Config::instance().getMutex());
if (baseMessage.type == message_type::kTime)
{
auto timeMsg = make_shared<msg::Time>();
timeMsg->deserialize(baseMessage, buffer);
timeMsg->refersTo = timeMsg->id;
timeMsg->latency = timeMsg->received - timeMsg->sent;
// LOG(INFO, LOG_TAG) << "Latency sec: " << timeMsg.latency.sec << ", usec: " << timeMsg.latency.usec << ", refers to: " << timeMsg.refersTo <<
// "\n";
streamSession->send(timeMsg);
// refresh streamSession state
ClientInfoPtr client = Config::instance().getClientInfo(streamSession->clientId);
if (client != nullptr)
{
chronos::systemtimeofday(&client->lastSeen);
client->connected = true;
}
}
else if (baseMessage.type == message_type::kClientInfo)
{
ClientInfoPtr clientInfo = Config::instance().getClientInfo(streamSession->clientId);
if (clientInfo == nullptr)
{
LOG(ERROR, LOG_TAG) << "client not found: " << streamSession->clientId << "\n";
return;
}
msg::ClientInfo infoMsg;
infoMsg.deserialize(baseMessage, buffer);
clientInfo->config.volume.percent = infoMsg.getVolume();
clientInfo->config.volume.muted = infoMsg.isMuted();
jsonrpcpp::notification_ptr notification = make_shared<jsonrpcpp::Notification>(
"Client.OnVolumeChanged", jsonrpcpp::Parameter("id", streamSession->clientId, "volume", clientInfo->config.volume.toJson()));
controlServer_->send(notification->to_json().dump());
}
else if (baseMessage.type == message_type::kHello)
{
msg::Hello helloMsg;
helloMsg.deserialize(baseMessage, buffer);
streamSession->clientId = helloMsg.getUniqueId();
LOG(INFO, LOG_TAG) << "Hello from " << streamSession->clientId << ", host: " << helloMsg.getHostName() << ", v" << helloMsg.getVersion()
<< ", ClientName: " << helloMsg.getClientName() << ", OS: " << helloMsg.getOS() << ", Arch: " << helloMsg.getArch()
<< ", Protocol version: " << helloMsg.getProtocolVersion() << "\n";
bool newGroup(false);
GroupPtr group = Config::instance().getGroupFromClient(streamSession->clientId);
if (group == nullptr)
{
group = Config::instance().addClientInfo(streamSession->clientId);
newGroup = true;
}
ClientInfoPtr client = group->getClient(streamSession->clientId);
if (newGroup)
{
client->config.volume.percent = settings_.streamingclient.initialVolume;
}
LOG(DEBUG, LOG_TAG) << "Sending ServerSettings to " << streamSession->clientId << "\n";
auto serverSettings = make_shared<msg::ServerSettings>();
serverSettings->setVolume(client->config.volume.percent);
serverSettings->setMuted(client->config.volume.muted || group->muted);
serverSettings->setLatency(client->config.latency);
serverSettings->setBufferMs(settings_.stream.bufferMs);
serverSettings->refersTo = helloMsg.id;
streamSession->send(serverSettings);
client->host.mac = helloMsg.getMacAddress();
client->host.ip = streamSession->getIP();
client->host.name = helloMsg.getHostName();
client->host.os = helloMsg.getOS();
client->host.arch = helloMsg.getArch();
client->snapclient.version = helloMsg.getVersion();
client->snapclient.name = helloMsg.getClientName();
client->snapclient.protocolVersion = helloMsg.getProtocolVersion();
client->config.instance = helloMsg.getInstance();
client->connected = true;
chronos::systemtimeofday(&client->lastSeen);
// Assign and update stream
PcmStreamPtr stream = streamManager_->getStream(group->streamId);
if (!stream)
{
stream = streamManager_->getDefaultStream();
group->streamId = stream->getId();
}
LOG(DEBUG, LOG_TAG) << "Group: " << group->id << ", stream: " << group->streamId << "\n";
saveConfig();
// LOG(DEBUG, LOG_TAG) << "Sending meta data to " << streamSession->clientId << "\n";
// streamSession->send(stream->getMeta());
streamSession->setPcmStream(stream);
auto headerChunk = stream->getHeader();
LOG(DEBUG, LOG_TAG) << "Sending codec header to " << streamSession->clientId << "\n";
streamSession->send(headerChunk);
if (newGroup)
{
// clang-format off
// Notification: {"jsonrpc":"2.0","method":"Server.OnUpdate","params":{"server":{"groups":[{"clients":[{"config":{"instance":2,"latency":6,"name":"123 456","volume":{"muted":false,"percent":48}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc#2","lastSeen":{"sec":1488025796,"usec":714671},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"4dcc4e3b-c699-a04b-7f0c-8260d23c43e1","muted":false,"name":"","stream_id":"stream 2"},{"clients":[{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":100}},"connected":true,"host":{"arch":"x86_64","ip":"127.0.0.1","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025798,"usec":728305},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}}],"id":"c5da8f7a-f377-1e51-8266-c5cc61099b71","muted":false,"name":"","stream_id":"stream 1"}],"server":{"host":{"arch":"x86_64","ip":"","mac":"","name":"T400","os":"Linux Mint 17.3 Rosa"},"snapserver":{"controlProtocolVersion":1,"name":"Snapserver","protocolVersion":1,"version":"0.10.0"}},"streams":[{"id":"stream 1","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 1","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 1","scheme":"pipe"}},{"id":"stream 2","status":"idle","uri":{"fragment":"","host":"","path":"/tmp/snapfifo","query":{"chunk_ms":"20","codec":"flac","name":"stream 2","sampleformat":"48000:16:2"},"raw":"pipe:///tmp/snapfifo?name=stream 2","scheme":"pipe"}}]}}}
// clang-format on
json server = Config::instance().getServerStatus(streamManager_->toJson());
json notification = jsonrpcpp::Notification("Server.OnUpdate", jsonrpcpp::Parameter("server", server)).to_json();
controlServer_->send(notification.dump());
}
else
{
// clang-format off
// Notification: {"jsonrpc":"2.0","method":"Client.OnConnect","params":{"client":{"config":{"instance":1,"latency":0,"name":"","volume":{"muted":false,"percent":81}},"connected":true,"host":{"arch":"x86_64","ip":"192.168.0.54","mac":"00:21:6a:7d:74:fc","name":"T400","os":"Linux Mint 17.3 Rosa"},"id":"00:21:6a:7d:74:fc","lastSeen":{"sec":1488025524,"usec":876332},"snapclient":{"name":"Snapclient","protocolVersion":2,"version":"0.10.0"}},"id":"00:21:6a:7d:74:fc"}}
// clang-format on
json notification = jsonrpcpp::Notification("Client.OnConnect", jsonrpcpp::Parameter("id", client->id, "client", client->toJson())).to_json();
controlServer_->send(notification.dump());
// cout << "Notification: " << notification.dump() << "\n";
}
// cout << Config::instance().getServerStatus(streamManager_->toJson()).dump(4) << "\n";
// cout << group->toJson().dump(4) << "\n";
}
}
void Server::saveConfig(const std::chrono::milliseconds& deferred)
{
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
config_timer_.cancel();
config_timer_.expires_after(deferred);
config_timer_.async_wait(
[](const boost::system::error_code& ec)
{
if (!ec)
{
LOG(DEBUG, LOG_TAG) << "Saving config\n";
Config::instance().save();
}
});
}
void Server::start()
{
try
{
controlServer_ = std::make_unique<ControlServer>(io_context_, settings_.tcp, settings_.http, this);
streamServer_ = std::make_unique<StreamServer>(io_context_, settings_, this);
streamManager_ = std::make_unique<StreamManager>(this, io_context_, settings_);
// Add normal sources first
for (const auto& sourceUri : settings_.stream.sources)
{
StreamUri streamUri(sourceUri);
if (streamUri.scheme == "meta")
continue;
PcmStreamPtr stream = streamManager_->addStream(streamUri);
if (stream)
LOG(INFO, LOG_TAG) << "Stream: " << stream->getUri().toJson() << "\n";
}
// Add meta sources second
for (const auto& sourceUri : settings_.stream.sources)
{
StreamUri streamUri(sourceUri);
if (streamUri.scheme != "meta")
continue;
PcmStreamPtr stream = streamManager_->addStream(streamUri);
if (stream)
LOG(INFO, LOG_TAG) << "Stream: " << stream->getUri().toJson() << "\n";
}
streamManager_->start();
controlServer_->start();
streamServer_->start();
}
catch (const std::exception& e)
{
LOG(NOTICE, LOG_TAG) << "Server::start: " << e.what() << endl;
stop();
throw;
}
}
void Server::stop()
{
if (streamManager_)
{
streamManager_->stop();
streamManager_ = nullptr;
}
if (controlServer_)
{
controlServer_->stop();
controlServer_ = nullptr;
}
if (streamServer_)
{
streamServer_->stop();
streamServer_ = nullptr;
}
}
| 55,405
|
C++
|
.cpp
| 828
| 53.292271
| 1,716
| 0.558872
|
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,953
|
stream_session.cpp
|
badaix_snapcast/server/stream_session.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 "stream_session.hpp"
// local headers
#include "common/aixlog.hpp"
// 3rd party headers
// standard headers
#include <iostream>
using namespace std;
using namespace streamreader;
static constexpr auto LOG_TAG = "StreamSession";
StreamSession::StreamSession(const boost::asio::any_io_executor& executor, StreamMessageReceiver* receiver)
: messageReceiver_(receiver), pcmStream_(nullptr), strand_(boost::asio::make_strand(executor))
{
base_msg_size_ = baseMessage_.getSize();
buffer_.resize(base_msg_size_);
}
void StreamSession::setPcmStream(PcmStreamPtr pcmStream)
{
std::lock_guard<std::mutex> lock(mutex_);
pcmStream_ = pcmStream;
}
const PcmStreamPtr StreamSession::pcmStream() const
{
std::lock_guard<std::mutex> lock(mutex_);
return pcmStream_;
}
void StreamSession::send_next()
{
auto& buffer = messages_.front();
buffer.on_air = true;
boost::asio::post(strand_,
[this, self = shared_from_this(), buffer]()
{
sendAsync(buffer,
[this](boost::system::error_code ec, std::size_t length)
{
messages_.pop_front();
if (ec)
{
LOG(ERROR, LOG_TAG) << "StreamSession write error (msg length: " << length << "): " << ec.message() << "\n";
messageReceiver_->onDisconnect(this);
return;
}
if (!messages_.empty())
send_next();
});
});
}
void StreamSession::send(shared_const_buffer const_buf)
{
boost::asio::post(strand_,
[this, self = shared_from_this(), const_buf]()
{
// delete PCM chunks that are older than the overall buffer duration
messages_.erase(std::remove_if(messages_.begin(), messages_.end(),
[this](const shared_const_buffer& buffer)
{
const auto& msg = buffer.message();
if (!msg.is_pcm_chunk || buffer.on_air)
return false;
auto age = chronos::clk::now() - msg.rec_time;
return (age > std::chrono::milliseconds(bufferMs_) + 100ms);
}),
messages_.end());
messages_.push_back(const_buf);
if (messages_.size() > 1)
{
LOG(TRACE, LOG_TAG) << "outstanding async_write\n";
return;
}
send_next();
});
}
void StreamSession::send(msg::message_ptr message)
{
if (!message)
return;
// TODO: better set the timestamp in send_next for more accurate time sync
send(shared_const_buffer(*message));
}
void StreamSession::setBufferMs(size_t bufferMs)
{
bufferMs_ = bufferMs;
}
| 3,586
|
C++
|
.cpp
| 98
| 28.602041
| 124
| 0.612829
|
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,954
|
tcp_stream.cpp
|
badaix_snapcast/server/streamreader/tcp_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/>.
***/
// prototype/interface header file
#include "tcp_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
#include "encoder/encoder_factory.hpp"
// 3rd party headers
// standard headers
#include <cerrno>
#include <memory>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "TcpStream";
TcpStream::TcpStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: AsioStream<tcp::socket>(pcmListener, ioc, server_settings, uri), reconnect_timer_(ioc)
{
host_ = uri_.host;
auto host_port = utils::string::split(host_, ':');
port_ = 4953;
if (host_port.size() == 2)
{
host_ = host_port[0];
port_ = cpt::stoi(host_port[1], port_);
}
auto mode = uri_.getQuery("mode", "server");
if (mode == "server")
is_server_ = true;
else if (mode == "client")
is_server_ = false;
else
throw SnapException("mode must be 'client' or 'server'");
port_ = cpt::stoi(uri_.getQuery("port", cpt::to_string(port_)), port_);
LOG(INFO, LOG_TAG) << "TcpStream host: " << host_ << ", port: " << port_ << ", is server: " << is_server_ << "\n";
if (is_server_)
acceptor_ = make_unique<tcp::acceptor>(strand_, tcp::endpoint(boost::asio::ip::address::from_string(host_), port_));
}
void TcpStream::connect()
{
if (!active_)
return;
if (is_server_)
{
acceptor_->async_accept(
[this](boost::system::error_code ec, tcp::socket socket)
{
if (!ec)
{
LOG(DEBUG, LOG_TAG) << "New client connection\n";
stream_ = make_unique<tcp::socket>(std::move(socket));
on_connect();
}
else
{
LOG(ERROR, LOG_TAG) << "Accept failed: " << ec.message() << "\n";
}
});
}
else
{
stream_ = make_unique<tcp::socket>(strand_);
boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host_), port_);
stream_->async_connect(endpoint,
[this](const boost::system::error_code& ec)
{
if (!ec)
{
LOG(DEBUG, LOG_TAG) << "Connected\n";
on_connect();
}
else
{
LOG(DEBUG, LOG_TAG) << "Connect failed: " << ec.message() << "\n";
wait(reconnect_timer_, 1s, [this] { connect(); });
}
});
}
}
void TcpStream::disconnect()
{
reconnect_timer_.cancel();
if (acceptor_)
acceptor_->cancel();
AsioStream<tcp::socket>::disconnect();
}
} // namespace streamreader
| 3,635
|
C++
|
.cpp
| 102
| 28.401961
| 145
| 0.594133
|
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,955
|
alsa_stream.cpp
|
badaix_snapcast/server/streamreader/alsa_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/>.
***/
// prototype/interface header file
#include "alsa_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
// 3rd party headers
#include <boost/asio/post.hpp>
// standard headers
#include <cerrno>
#include <memory>
using namespace std;
using namespace std::chrono_literals;
namespace streamreader
{
static constexpr auto LOG_TAG = "AlsaStream";
static constexpr auto kResyncTolerance = 50ms;
// https://superuser.com/questions/597227/linux-arecord-capture-sound-card-output-rather-than-microphone-input
// https://wiki.ubuntuusers.de/.asoundrc/
// https://alsa.opensrc.org/Dsnoop#The_dsnoop_howto
// https://linuxconfig.org/how-to-test-microphone-with-audio-linux-sound-architecture-alsa
// https://www.alsa-project.org/alsa-doc/alsa-lib/_2test_2latency_8c-example.html#a30
namespace
{
template <typename Rep, typename Period>
void wait(boost::asio::steady_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, LOG_TAG) << "Error during async wait: " << ec.message() << "\n";
}
else
{
handler();
}
});
}
} // namespace
AlsaStream::AlsaStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: PcmStream(pcmListener, ioc, server_settings, uri), handle_(nullptr), read_timer_(strand_), silence_(0ms)
{
device_ = uri_.getQuery("device", "hw:0");
send_silence_ = (uri_.getQuery("send_silence", "false") == "true");
idle_threshold_ = std::chrono::milliseconds(std::max(cpt::stoi(uri_.getQuery("idle_threshold", "100")), 10));
}
void AlsaStream::start()
{
LOG(DEBUG, LOG_TAG) << "Start, sampleformat: " << sampleFormat_.toString() << "\n";
initAlsa();
first_ = true;
tvEncodedChunk_ = std::chrono::steady_clock::now();
PcmStream::start();
// wait(read_timer_, std::chrono::milliseconds(chunk_ms_), [this] { do_read(); });
boost::asio::post(strand_, [this] { do_read(); });
}
void AlsaStream::stop()
{
PcmStream::stop();
uninitAlsa();
}
void AlsaStream::initAlsa()
{
int err;
unsigned int rate = sampleFormat_.rate();
snd_pcm_format_t snd_pcm_format;
if (sampleFormat_.bits() == 8)
snd_pcm_format = SND_PCM_FORMAT_S8;
else if (sampleFormat_.bits() == 16)
snd_pcm_format = SND_PCM_FORMAT_S16_LE;
else if ((sampleFormat_.bits() == 24) && (sampleFormat_.sampleSize() == 4))
snd_pcm_format = SND_PCM_FORMAT_S24_LE;
else if (sampleFormat_.bits() == 32)
snd_pcm_format = SND_PCM_FORMAT_S32_LE;
else
throw SnapException("Unsupported sample format: " + cpt::to_string(sampleFormat_.bits()));
if ((err = snd_pcm_open(&handle_, device_.c_str(), SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK)) < 0) // SND_PCM_NONBLOCK
throw SnapException("Can't open device '" + device_ + "', error: " + snd_strerror(err));
snd_pcm_hw_params_t* hw_params;
if ((err = snd_pcm_hw_params_malloc(&hw_params)) < 0)
throw SnapException("Can't allocate hardware parameter structure: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params_any(handle_, hw_params)) < 0)
throw SnapException("Can't fill params: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params_set_access(handle_, hw_params, SND_PCM_ACCESS_RW_INTERLEAVED)) < 0)
throw SnapException("Can't set interleaved mode: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params_set_format(handle_, hw_params, snd_pcm_format)) < 0)
throw SnapException("Can't set sample format: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params_set_rate_near(handle_, hw_params, &rate, nullptr)) < 0)
throw SnapException("Can't set rate: " + string(snd_strerror(err)));
if (rate != sampleFormat_.rate())
{
LOG(WARNING, LOG_TAG) << "Rate is not accurate (requested: " << sampleFormat_.rate() << ", got: " << rate << "), using: " << rate << "\n";
sampleFormat_.setFormat(rate, sampleFormat_.bits(), sampleFormat_.channels());
}
if ((err = snd_pcm_hw_params_set_channels(handle_, hw_params, sampleFormat_.channels())) < 0)
throw SnapException("Can't set channel count: " + string(snd_strerror(err)));
if ((err = snd_pcm_hw_params(handle_, hw_params)) < 0)
throw SnapException("Can't set hardware parameters: " + string(snd_strerror(err)));
#if 0 // Period size test code
// snd_pcm_uframes_t period_size;
// if ((err = snd_pcm_hw_params_get_period_size(hw_params, &period_size, nullptr)) < 0)
// LOG(ERROR, LOG_TAG) << "Can't get min period size: " << snd_strerror(err) << "\n";
// else
// LOG(INFO, LOG_TAG) << "Period size: " << period_size << ", " << double(period_size) / double(sampleFormat_.rate()) * 1000. << " ms\n";
// period_size = sampleFormat_.msRate() * chunk_ms_;
// if ((err = snd_pcm_hw_params_set_period_size_near(handle_, hw_params, &period_size, 0)) < 0)
// LOG(ERROR, LOG_TAG) << "Can't set period size: " << snd_strerror(err) << "\n";
// else
// LOG(INFO, LOG_TAG) << "Period size: " << period_size << ", " << double(period_size) / double(sampleFormat_.rate()) * 1000. << " ms\n";
// chunk_ = std::make_unique<msg::PcmChunk>(sampleFormat_, 2*period_size, false);
// LOG(INFO, LOG_TAG) << "Chunk duration: " << chunk_->duration<std::chrono::milliseconds>().count() << "\n";
#endif
snd_pcm_hw_params_free(hw_params);
if ((err = snd_pcm_prepare(handle_)) < 0)
throw SnapException("Can't prepare audio interface for use: " + string(snd_strerror(err)));
if (snd_pcm_state(handle_) == SND_PCM_STATE_PREPARED)
{
if ((err = snd_pcm_start(handle_)) < 0)
throw SnapException("Failed to start PCM: " + string(snd_strerror(err)));
}
}
void AlsaStream::uninitAlsa()
{
if (handle_ != nullptr)
{
snd_pcm_close(handle_);
handle_ = nullptr;
}
}
void AlsaStream::do_read()
{
try
{
if (first_)
{
LOG(TRACE, LOG_TAG) << "First read, initializing nextTick to now\n";
nextTick_ = std::chrono::steady_clock::now();
}
auto avail = snd_pcm_avail(handle_);
if (avail >= 0)
{
#if 0 // Some debug code
static long max_avail = 0;
if (avail > max_avail)
{
max_avail = avail;
LOG(INFO, LOG_TAG) << "Max Available: " << avail << ", " << double(avail) / double(sampleFormat_.rate()) * 1000. << " ms\n";
}
static utils::logging::TimeConditional cond(1s);
LOG(INFO, LOG_TAG) << cond << "Available: " << avail << ", " << double(avail) / double(sampleFormat_.rate()) * 1000. << " ms, max: " << double(max_avail) / double(sampleFormat_.rate()) * 1000. << " ms\n";
#endif
// check if enough data is available to read from alsa
if ((static_cast<int32_t>(chunk_->getFrameCount()) > avail))
{
// Calculate when there will be enough data available, add half chunk duration tolerance and try later
auto available = std::chrono::milliseconds(static_cast<size_t>(double(avail) / double(sampleFormat_.rate()) * 1000.));
auto missing = chunk_->duration<std::chrono::milliseconds>() - available;
LOG(INFO, LOG_TAG) << "Not enough data available: " << available.count() << " ms, missing: " << missing.count()
<< " ms, needed: " << chunk_->duration<std::chrono::milliseconds>().count() << " ms\n";
missing += chunk_->duration<std::chrono::milliseconds>() / 2;
resync(missing);
first_ = true;
wait(read_timer_, missing, [this] { do_read(); });
return;
}
// check if there is too much data available, i.e. if we are far behind
else if (avail > static_cast<int32_t>(3 * chunk_->getFrameCount()))
{
// Fast forward, by reading and dropping audio frames
// const auto newAvail = static_cast<int32_t>(chunk_->getFrameCount() + static_cast<uint32_t>(chunk_->format.msRate() * 20));
const auto newAvail = 1.5 * chunk_->getFrameCount();
LOG(INFO, LOG_TAG) << "Too many frames available, fast forwarding from " << avail << " frames ("
<< double(avail) / double(sampleFormat_.rate()) * 1000. << " ms) to " << newAvail << " frames ("
<< double(newAvail) / double(sampleFormat_.rate()) * 1000. << " ms)\n";
do
{
int count = snd_pcm_readi(handle_, chunk_->payload, std::min(chunk_->getFrameCount(), static_cast<uint32_t>(avail - newAvail)));
if (count <= 0)
{
// some read error happened, just break here, this will be handled properly later in the read loop
break;
}
avail -= count;
LOG(DEBUG, LOG_TAG) << "Read " << count << " frames (" << double(count) / double(sampleFormat_.rate()) * 1000.
<< " ms), available: " << avail << " frames (" << double(avail) / double(sampleFormat_.rate()) * 1000. << " ms)\n";
} while (avail > newAvail);
first_ = true;
}
}
int toRead = chunk_->payloadSize;
auto duration = chunk_->duration<std::chrono::nanoseconds>();
int len = 0;
do
{
snd_pcm_sframes_t count = snd_pcm_readi(handle_, chunk_->payload + len, (toRead - len) / chunk_->format.frameSize());
if (count == -EAGAIN)
{
LOG(INFO, LOG_TAG) << "No data availabale, playing silence.\n";
// no data available, fill with silence
memset(chunk_->payload + len, 0, toRead - len);
break;
}
else if (count == 0)
{
throw SnapException("end of file");
}
else if (count < 0)
{
// ESTRPIPE
LOG(ERROR, LOG_TAG) << "Error reading PCM data: " << snd_strerror(count) << " (code: " << count << ")\n";
first_ = true;
uninitAlsa();
initAlsa();
continue;
}
else
{
// LOG(TRACE, LOG_TAG) << "count: " << count << ", len: " << len << ", toRead: " << toRead << "\n";
len += count * chunk_->format.frameSize();
}
} while (len < toRead);
if (isSilent(*chunk_))
{
silence_ += chunk_->duration<std::chrono::microseconds>();
if (silence_ > idle_threshold_)
{
setState(ReaderState::kIdle);
}
}
else
{
silence_ = 0ms;
if ((state_ == ReaderState::kIdle) && !send_silence_)
first_ = true;
setState(ReaderState::kPlaying);
}
// LOG(DEBUG, LOG_TAG) << "Received " << len << "/" << toRead << " bytes\n";
if (first_)
{
first_ = false;
// initialize the stream's base timestamp to now minus the chunk's duration
tvEncodedChunk_ = std::chrono::steady_clock::now() - duration;
}
if ((state_ == ReaderState::kPlaying) || ((state_ == ReaderState::kIdle) && send_silence_))
{
chunkRead(*chunk_);
}
nextTick_ += duration;
auto currentTick = std::chrono::steady_clock::now();
auto next_read = nextTick_ - currentTick;
if (next_read >= 0ms)
{
// LOG(DEBUG, LOG_TAG) << "Next read: " << std::chrono::duration_cast<std::chrono::milliseconds>(next_read).count() << "\n";
// synchronize reads to an interval of chunk_ms_
wait(read_timer_, next_read, [this] { do_read(); });
return;
}
else if (next_read >= -kResyncTolerance)
{
LOG(INFO, LOG_TAG) << "next read < 0 (" << getName() << "): " << std::chrono::duration_cast<std::chrono::microseconds>(next_read).count() / 1000.
<< " ms\n ";
boost::asio::post(strand_, [this] { do_read(); });
}
else
{
// reading chunk_ms_ took longer than chunk_ms_
resync(-next_read);
first_ = true;
boost::asio::post(strand_, [this] { do_read(); });
}
lastException_ = "";
}
catch (const std::exception& e)
{
if (lastException_ != e.what())
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << std::endl;
lastException_ = e.what();
}
first_ = true;
uninitAlsa();
initAlsa();
wait(read_timer_, 100ms, [this] { do_read(); });
}
}
} // namespace streamreader
| 14,121
|
C++
|
.cpp
| 303
| 37.422442
| 216
| 0.566282
|
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,956
|
watchdog.cpp
|
badaix_snapcast/server/streamreader/watchdog.cpp
|
/***
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/>.
***/
// prototype/interface header file
#include "watchdog.hpp"
// local headers
#include "common/aixlog.hpp"
// 3rd party headers
// standard headers
#include <chrono>
static constexpr auto LOG_TAG = "Watchdog";
using namespace std;
namespace streamreader
{
Watchdog::Watchdog(const boost::asio::any_io_executor& executor, WatchdogListener* listener) : timer_(executor), listener_(listener)
{
}
Watchdog::~Watchdog()
{
stop();
}
void Watchdog::start(const std::chrono::milliseconds& timeout)
{
LOG(INFO, LOG_TAG) << "Starting watchdog, timeout: " << std::chrono::duration_cast<std::chrono::seconds>(timeout).count() << "s\n";
timeout_ms_ = timeout;
trigger();
}
void Watchdog::stop()
{
timer_.cancel();
}
void Watchdog::trigger()
{
timer_.cancel();
timer_.expires_after(timeout_ms_);
timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (!ec)
{
LOG(INFO, LOG_TAG) << "Timed out: " << std::chrono::duration_cast<std::chrono::seconds>(timeout_ms_).count() << "s\n";
listener_->onTimeout(*this, timeout_ms_);
}
});
}
} // namespace streamreader
| 1,912
|
C++
|
.cpp
| 57
| 29.561404
| 135
| 0.695581
|
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,957
|
jack_stream.cpp
|
badaix_snapcast/server/streamreader/jack_stream.cpp
|
/***
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/>.
***/
// prototype/interface header file
#include "jack_stream.hpp"
#include <jack/jack.h>
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
// standard headers
#include <memory>
using namespace std;
using namespace std::chrono_literals;
namespace streamreader
{
static constexpr auto LOG_TAG = "JackStream";
void float_to_s32(char* dst, jack_default_audio_sample_t* src, unsigned long nsamples, unsigned long dst_skip)
{
while (nsamples--)
{
// float to S32 conversion
double clipped = fmin(1.0f, fmax((double)(*src), -1.0f));
double scaled = clipped * 2147483647.0;
*(int32_t*)dst = lrint(scaled);
dst += dst_skip;
src++;
}
}
void float_to_s24(char* dst, jack_default_audio_sample_t* src, unsigned long nsamples, unsigned long dst_skip)
{
int32_t tmp;
while (nsamples--)
{
// float to S24 conversion
if (*src <= -1.0f)
{
tmp = -8388607;
}
else if (*src >= 1.0f)
{
tmp = 8388607;
}
else
{
tmp = lrintf(*src * 8388607.0);
}
#if __BYTE_ORDER == __LITTLE_ENDIAN
memcpy(dst, &tmp, 3);
#elif __BYTE_ORDER == __BIG_ENDIAN
memcpy(dst, (char*)&tmp + 1, 3);
#endif
dst += dst_skip;
src++;
}
}
void float_to_s16(char* dst, jack_default_audio_sample_t* src, unsigned long nsamples, unsigned long dst_skip)
{
while (nsamples--)
{
// float to S16 conversion
if (*src <= -1.0f)
{
*((int16_t*)dst) = -32767;
}
else if (*src >= 1.0f)
{
*((int16_t*)dst) = 32767;
}
else
{
*((int16_t*)dst) = lrintf(*src * 32767.0);
}
dst += dst_skip;
src++;
}
}
namespace
{
template <typename Rep, typename Period>
void wait(boost::asio::steady_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, LOG_TAG) << "Error during async wait: " << ec.message() << "\n";
}
else
{
handler();
}
});
}
} // namespace
JackStream::JackStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: PcmStream(pcmListener, ioc, server_settings, uri), read_timer_(strand_), silence_(0ms), first_(true)
{
serverName_ = uri_.getQuery("server_name", "default");
send_silence_ = (uri_.getQuery("send_silence", "false") == "true");
idle_threshold_ = std::chrono::milliseconds(std::max(cpt::stoi(uri_.getQuery("idle_threshold", "100")), 10));
doAutoConnect_ = (uri_.query.find("autoconnect") != uri_.query.end());
autoConnectRegex_ = uri_.getQuery("autoconnect", "");
autoConnectSkip_ = cpt::stoi(uri_.getQuery("autoconnect_skip", "0"));
switch (sampleFormat_.bits())
{
case 16:
interleave_func_ = float_to_s16;
break;
case 24:
interleave_func_ = float_to_s24;
break;
case 32:
interleave_func_ = float_to_s32;
break;
default:
throw SnapException("JackStreams only support 16, 24 and 32 bit sample formats");
}
jack_set_error_function([](const char* msg) { LOG(ERROR, LOG_TAG) << "Jack Error: " << msg << "\n"; });
jack_set_info_function([](const char* msg) { LOG(DEBUG, LOG_TAG) << msg << "\n"; });
}
void JackStream::start()
{
LOG(TRACE, LOG_TAG) << "JackStream::start()\n";
// Need to start immediately, otherwise client will fail
// due to a zero-length pcm header message
first_ = true;
tvEncodedChunk_ = std::chrono::steady_clock::now();
PcmStream::start();
boost::asio::post(strand_, [this] { tryConnect(); });
}
void JackStream::stop()
{
LOG(TRACE, LOG_TAG) << "JackStream::stop()\n";
PcmStream::stop();
closeJackConnection();
}
/**
* Try to connect to the jack server. If it fails, wait
* a little bit and try again.
*/
void JackStream::tryConnect()
{
try
{
if (!openJackConnection())
{
LOG(WARNING, LOG_TAG) << "Jack connection failed, trying again in 5 seconds\n";
wait(read_timer_, 5s, [this] { tryConnect(); });
return;
}
if (!createJackPorts())
{
LOG(ERROR, LOG_TAG) << "Failed to create Jack ports, trying again in 5 seconds\n";
closeJackConnection();
wait(read_timer_, 5s, [this] { tryConnect(); });
return;
}
if (doAutoConnect_)
{
autoConnectPorts();
}
}
catch (exception& e)
{
LOG(ERROR, LOG_TAG) << "Error during Jack connection: " << e.what() << "\n";
stop();
}
}
bool JackStream::openJackConnection()
{
char* serverName = serverName_.data();
jack_options_t options = (jack_options_t)(JackNoStartServer | JackServerName);
client_ = jack_client_open(name_.c_str(), options, nullptr, serverName);
if (client_ == nullptr)
{
return false;
}
LOG(INFO, LOG_TAG) << "Connected Jack client " << jack_get_client_name(client_) << "\n";
jack_nframes_t jack_sample_rate = jack_get_sample_rate(client_);
if (jack_sample_rate != sampleFormat_.rate())
{
throw SnapException("Jack streams must match the sample rate of the Jack server. "
"The server sample rate is " +
cpt::to_string(jack_sample_rate) + ".");
}
jack_set_process_callback(
client_, [](jack_nframes_t nframes, void* arg) { return static_cast<JackStream*>(arg)->readJackBuffers(nframes); }, this);
jack_on_shutdown(
client_, [](void* arg) { static_cast<JackStream*>(arg)->onJackShutdown(); }, this);
jack_set_port_registration_callback(
client_, [](jack_port_id_t port_id, int registered, void* arg) { return static_cast<JackStream*>(arg)->onJackPortRegistration(port_id, registered); },
this);
int err = jack_activate(client_);
if (err)
{
LOG(ERROR, LOG_TAG) << "Failed to activate Jack client " << name_ << ": " << err << "\n";
closeJackConnection();
return false;
}
return true;
}
bool JackStream::createJackPorts()
{
if (ports_.size() > 0)
{
throw SnapException("Jack ports already created!");
}
int channelCount = sampleFormat_.channels();
ports_.reserve(channelCount);
// Register input ports
for (int i = 0; i < channelCount; ++i)
{
std::string portName = "input_" + std::to_string(i);
jack_port_t* port = jack_port_register(client_, portName.c_str(), JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0);
if (port == nullptr)
{
LOG(ERROR, LOG_TAG) << name_ << ": failed to register port " << portName << "\n";
return false;
}
ports_.push_back(port);
}
return true;
}
/**
* Reads the Jack port buffers, interlaces and converts the samples
* to the stream format and adds the resulting data to the
* ringbuffer, along with the jack timing information.
*/
int JackStream::readJackBuffers(jack_nframes_t nframes)
{
int bytes_per_frame = sampleFormat_.sampleSize();
int num_channels = sampleFormat_.channels();
int payload_skip = bytes_per_frame * num_channels;
// resize chunk payload buffer to match the Jack buffer size, if required
if (chunk_->getFrameCount() != nframes)
{
LOG(TRACE, LOG_TAG) << "Resizing chunk to " << nframes << " frames\n";
chunk_->setFrameCount(nframes);
silent_chunk_ = std::vector<char>(chunk_->payloadSize, 0);
}
int connectedPorts = 0;
for (size_t i = 0; i < ports_.size(); i++)
{
int payload_offset = bytes_per_frame * i;
jack_port_t* port = ports_[i];
if (jack_port_connected(port))
{
connectedPorts++;
}
jack_default_audio_sample_t* buf = static_cast<jack_default_audio_sample_t*>(jack_port_get_buffer(port, nframes));
if (buf == nullptr)
{
LOG(ERROR, LOG_TAG) << "Unable to get Jack port buffer!\n";
return -1;
}
interleave_func_(chunk_->payload + payload_offset, buf, nframes, payload_skip);
}
if (connectedPorts == 0 || isSilent(*chunk_))
{
silence_ += chunk_->duration<std::chrono::microseconds>();
if (silence_ > idle_threshold_)
{
setState(ReaderState::kIdle);
first_ = true;
}
}
else
{
silence_ = 0ms;
setState(ReaderState::kPlaying);
if (first_)
{
first_ = false;
tvEncodedChunk_ = std::chrono::steady_clock::now() - chunk_->duration<chrono::nanoseconds>();
}
}
if ((state_ == ReaderState::kPlaying) || ((state_ == ReaderState::kIdle) && send_silence_))
{
chunkRead(*chunk_);
}
return 0;
}
void JackStream::closeJackConnection()
{
if (client_ == nullptr)
{
return;
}
LOG(INFO, LOG_TAG) << "Closing Jack connection for " << name_ << "\n";
ports_.clear();
jack_client_close(client_);
client_ = nullptr;
}
void JackStream::onJackPortRegistration(jack_port_id_t port_id, int registered)
{
if (!doAutoConnect_ || !registered)
{
return;
}
jack_port_t* port = jack_port_by_id(client_, port_id);
if (port == nullptr)
{
return;
}
if (jack_port_is_mine(client_, port))
{
return;
}
boost::asio::post(strand_, [this] { autoConnectPorts(); });
}
void JackStream::autoConnectPorts()
{
const char** portNames = jack_get_ports(client_, autoConnectRegex_.c_str(), nullptr, JackPortIsOutput);
if (portNames == nullptr)
{
return;
}
size_t portIdx = 0;
int nameIdx = 0;
while (portIdx < ports_.size() && portNames[nameIdx] != nullptr)
{
if (nameIdx < autoConnectSkip_)
{
nameIdx++;
continue;
}
if (!jack_port_connected_to(ports_[portIdx], portNames[nameIdx]))
{
const char* localPortName = jack_port_name(ports_[portIdx]);
int err = jack_connect(client_, portNames[nameIdx], localPortName);
if (err != 0)
{
LOG(ERROR, LOG_TAG) << "Unable to autoconnect " << localPortName << " to " << portNames[nameIdx] << "(Error: " << err << ")\n";
}
}
portIdx++;
nameIdx++;
}
jack_free(portNames);
}
void JackStream::onJackShutdown()
{
LOG(ERROR, LOG_TAG) << "Jack has shut down, trying to connect again!\n";
ports_.clear();
client_ = nullptr;
wait(read_timer_, 1000ms, [this] { tryConnect(); });
}
} // namespace streamreader
| 11,928
|
C++
|
.cpp
| 363
| 26.280992
| 158
| 0.595195
|
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,958
|
process_stream.cpp
|
badaix_snapcast/server/streamreader/process_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/>.
***/
// prototype/interface header file
#include "process_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/utils.hpp"
#include "common/utils/file_utils.hpp"
// standard headers
#include <cstdio>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "ProcessStream";
ProcessStream::ProcessStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: AsioStream<stream_descriptor>(pcmListener, ioc, server_settings, uri)
{
params_ = uri_.getQuery("params");
wd_timeout_sec_ = cpt::stoul(uri_.getQuery("wd_timeout", "0"));
LOG(DEBUG, LOG_TAG) << "Watchdog timeout: " << wd_timeout_sec_ << "\n";
logStderr_ = (uri_.getQuery("log_stderr", "false") == "true");
}
std::string ProcessStream::findExe(const std::string& filename) const
{
/// check if filename exists
if (utils::file::exists(filename))
return filename;
std::string exe = filename;
if (exe.find('/') != string::npos)
exe = exe.substr(exe.find_last_of('/') + 1);
/// check with "which"
string which = execGetOutput("which " + exe);
if (!which.empty())
return which;
/// check in the same path as this binary
char buff[PATH_MAX];
char szTmp[32];
sprintf(szTmp, "/proc/%d/exe", getpid());
ssize_t len = readlink(szTmp, buff, sizeof(buff) - 1);
if (len != -1)
{
buff[len] = '\0';
return string(buff) + "/" + exe;
}
return "";
}
void ProcessStream::initExeAndPath(const std::string& filename)
{
path_ = "";
exe_ = findExe(filename);
if (exe_.find('/') != string::npos)
{
path_ = exe_.substr(0, exe_.find_last_of('/') + 1);
exe_ = exe_.substr(exe_.find_last_of('/') + 1);
}
if (!utils::file::exists(path_ + exe_))
throw SnapException("file not found: \"" + filename + "\"");
}
void ProcessStream::connect()
{
if (!active_)
return;
initExeAndPath(uri_.path);
LOG(DEBUG, LOG_TAG) << "Launching: '" << path_ + exe_ << "', with params: '" << params_ << "', in path: '" << path_ << "'\n";
pipe_stdout_ = bp::pipe();
// could use bp::async_pipe, but this is broken in boost 1.72:
// https://github.com/boostorg/process/issues/116
pipe_stderr_ = bp::pipe();
// stdout pipe should not block
int flags = fcntl(pipe_stdout_.native_source(), F_GETFL, 0);
fcntl(pipe_stdout_.native_source(), F_SETFL, flags | O_NONBLOCK);
process_ = bp::child(path_ + exe_ + " " + params_, bp::std_out > pipe_stdout_, bp::std_err > pipe_stderr_, bp::start_dir = path_);
stream_ = make_unique<stream_descriptor>(strand_, pipe_stdout_.native_source());
stream_stderr_ = make_unique<stream_descriptor>(strand_, pipe_stderr_.native_source());
on_connect();
if (wd_timeout_sec_ > 0)
{
watchdog_ = make_unique<Watchdog>(strand_, this);
watchdog_->start(std::chrono::seconds(wd_timeout_sec_));
}
else
{
watchdog_ = nullptr;
}
stderrReadLine();
}
void ProcessStream::disconnect()
{
if (process_.running())
::kill(-process_.native_handle(), SIGINT);
AsioStream<stream_descriptor>::disconnect();
}
void ProcessStream::onStderrMsg(const std::string& line)
{
if (logStderr_)
{
LOG(INFO, LOG_TAG) << "(" << getName() << ") " << line << "\n";
}
}
void ProcessStream::stderrReadLine()
{
const std::string delimiter = "\n";
boost::asio::async_read_until(*stream_stderr_, streambuf_stderr_, delimiter,
[this, delimiter](const std::error_code& ec, std::size_t bytes_transferred)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while reading from stderr: " << ec.message() << "\n";
return;
}
if (watchdog_)
watchdog_->trigger();
// Extract up to the first delimiter.
std::string line{buffers_begin(streambuf_stderr_.data()), buffers_begin(streambuf_stderr_.data()) + bytes_transferred - delimiter.length()};
if (!line.empty())
{
if (line.back() == '\r')
line.resize(line.size() - 1);
onStderrMsg(line);
}
streambuf_stderr_.consume(bytes_transferred);
stderrReadLine();
});
}
void ProcessStream::onTimeout(const Watchdog& /*watchdog*/, std::chrono::milliseconds ms)
{
LOG(ERROR, LOG_TAG) << "Watchdog timeout: " << ms.count() / 1000 << "s\n";
if (process_)
::kill(-process_.native_handle(), SIGINT);
}
} // namespace streamreader
| 5,438
|
C++
|
.cpp
| 144
| 32.118056
| 153
| 0.626213
|
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,959
|
file_stream.cpp
|
badaix_snapcast/server/streamreader/file_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/>.
***/
// prototype/interface header file
#include "file_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "encoder/encoder_factory.hpp"
// 3rd party headers
// standard headers
#include <filesystem>
#include <memory>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "FileStream";
FileStream::FileStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: AsioStream<stream_descriptor>(pcmListener, ioc, server_settings, uri)
{
struct stat buffer;
if (stat(uri_.path.c_str(), &buffer) != 0)
{
throw SnapException("Failed to open PCM file: \"" + uri_.path + "\"");
}
else if ((buffer.st_mode & S_IFMT) != S_IFREG)
{
throw SnapException("Not a regular file: \"" + uri_.path + "\"");
}
Properties properties;
Metadata meta;
meta.title = std::filesystem::path(uri_.path).filename().replace_extension("");
properties.metadata = meta;
setProperties(properties);
}
void FileStream::connect()
{
LOG(DEBUG, LOG_TAG) << "connect\n";
int fd = open(uri_.path.c_str(), O_RDONLY | O_NONBLOCK);
stream_ = std::make_unique<boost::asio::posix::stream_descriptor>(strand_, fd);
on_connect();
}
} // namespace streamreader
| 2,093
|
C++
|
.cpp
| 54
| 35
| 147
| 0.714144
|
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,960
|
airplay_stream.cpp
|
badaix_snapcast/server/streamreader/airplay_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/>.
***/
// prototype/interface header file
#include "airplay_stream.hpp"
// local headers
#include "base64.h"
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/utils/file_utils.hpp"
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "AirplayStream";
namespace
{
string hex2str(const string& input)
{
using byte = unsigned char;
unsigned long x = strtoul(input.c_str(), nullptr, 16);
byte a[] = {byte(x >> 24), byte(x >> 16), byte(x >> 8), byte(x), 0};
return string(reinterpret_cast<char*>(a));
}
} // namespace
/*
* Expat is used in metadata parsing from Shairport-sync.
* Without HAS_EXPAT defined no parsing will occur.
*/
AirplayStream::AirplayStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: ProcessStream(pcmListener, ioc, server_settings, uri), port_(5000), pipe_open_timer_(ioc)
{
logStderr_ = true;
string devicename = uri_.getQuery("devicename", "Snapcast");
string password = uri_.getQuery("password", "");
params_wo_port_ = "\"--name=" + devicename + "\" --output=stdout --get-coverart";
if (!password.empty())
params_wo_port_ += " --password \"" + password + "\"";
if (!params_.empty())
params_wo_port_ += " " + params_;
port_ = cpt::stoul(uri_.getQuery("port", "5000"));
setParamsAndPipePathFromPort();
#ifdef HAS_EXPAT
createParser();
metadata_dirty_ = false;
#else
LOG(INFO, LOG_TAG) << "Metadata support not enabled (HAS_EXPAT not defined)"
<< "\n";
#endif
}
AirplayStream::~AirplayStream()
{
#ifdef HAS_EXPAT
parse(string("</metatags>"));
XML_ParserFree(parser_);
#endif
}
#ifdef HAS_EXPAT
int AirplayStream::parse(const string& line)
{
enum XML_Status result;
if ((result = XML_Parse(parser_, line.c_str(), line.length(), 0)) == XML_STATUS_ERROR)
{
XML_ParserFree(parser_);
createParser();
}
return result;
}
void AirplayStream::createParser()
{
parser_ = XML_ParserCreate("UTF-8");
XML_SetElementHandler(parser_, element_start, element_end);
XML_SetCharacterDataHandler(parser_, data);
XML_SetUserData(parser_, this);
// Make an outer element to keep parsing going
parse(string("<metatags>"));
}
void AirplayStream::push()
{
// The metadata we collect consists of two parts:
// (1) ALBUM, ARTIST, TITLE
// (2) COVER
//
// This stems from the Airplay protocol, which treats cover art differently from the rest of the metadata.
//
// The process for (1) is as follows:
// - The ssnc->mdst message is sent ("metadata start")
// - core->asal|asar|minm messages are sent
// - The ssnc->mden message is sent ("metadata end")
// This process can repeat multiple times *for the same song*, with *the same metadata*.
//
// The process for (2) is as follows:
// - The ssnc->pcst message is sent ("picture start")
// - The ssnc->PICT message is sent (picture contents)
// - The ssnc->pcen message is sent ("picture end")
// If no cover art is available, the PICT message's data has a length of 0 *or* none of the messages are sent.
//
// Here is an example from an older iPad:
//
// User plays song without cover art
// - empty cover art message (2)
// - empty cover art message (2)
// - metadata message (1)
// - metadata message (1)
// - metadata message (1)
// User selects next song without cover art
// - metadata message (1)
// - metadata message (1)
// User selects next song with cover art
// - metadata message (1)
// - metadata message (1)
// - cover art message (2)
// - metadata message (1)
// User selects next song with cover art
// - metadata message (1)
// - metadata message (1)
// - empty cover art message (2) (!)
// - metadata message (1)
// - cover art message (2)
//
// As can be seen, the order of metadata (1) and cover (2) messages is non-deterministic.
// That is why we call setMetadata() on both end of message (1) and (2).
string data = entry_->data;
// Do not base64 decode cover art
const bool is_cover = entry_->type == "ssnc" && entry_->code == "PICT";
if (!is_cover && entry_->isBase64 && entry_->length > 0)
data = base64_decode(data);
if (is_cover)
{
setMetaData(meta_.art_data, Metadata::ArtData{data, "jpg"});
// LOG(INFO, LOG_TAG) << "Metadata type: " << entry_->type << " code: " << entry_->code << " data length: " << data.length() << "\n";
}
else
{
// LOG(INFO, LOG_TAG) << "Metadata type: " << entry_->type << " code: " << entry_->code << " data: " << data << "\n";
}
if (entry_->type == "core" && entry_->code == "asal")
setMetaData(meta_.album, data);
else if (entry_->type == "core" && entry_->code == "asar")
setMetaData(meta_.artist, {data});
else if (entry_->type == "core" && entry_->code == "minm")
setMetaData(meta_.title, data);
// mden = metadata end, pcen == picture end
if (metadata_dirty_ && entry_->type == "ssnc" && (entry_->code == "mden" || entry_->code == "pcen"))
{
Properties properties;
properties.metadata = meta_;
setProperties(properties);
metadata_dirty_ = false;
}
}
template <typename T>
void AirplayStream::setMetaData(std::optional<T>& meta_value, const T& value)
{
// Only overwrite metadata and set metadata_dirty_ if the metadata has changed.
// This avoids multiple unnecessary transmissions of the same metadata.
if (!meta_value.has_value() || (meta_value.value() != value))
{
meta_value = value;
metadata_dirty_ = true;
}
}
#endif
void AirplayStream::setParamsAndPipePathFromPort()
{
pipePath_ = "/tmp/shairmeta." + cpt::to_string(getpid()) + "." + cpt::to_string(port_);
params_ = params_wo_port_ + " \"--metadata-pipename=" + pipePath_ + "\" --port=" + cpt::to_string(port_);
}
void AirplayStream::connect()
{
ProcessStream::connect();
pipeReadLine();
}
void AirplayStream::disconnect()
{
ProcessStream::disconnect();
// Shairpot-sync created but does not remove the pipe
if (utils::file::exists(pipePath_) && (remove(pipePath_.c_str()) != 0))
LOG(INFO, LOG_TAG) << "Failed to remove metadata pipe \"" << pipePath_ << "\": " << errno << "\n";
}
void AirplayStream::pipeReadLine()
{
if (!pipe_fd_ || !pipe_fd_->is_open())
{
try
{
int fd = open(pipePath_.c_str(), O_RDONLY | O_NONBLOCK);
pipe_fd_ = std::make_unique<boost::asio::posix::stream_descriptor>(strand_, fd);
LOG(INFO, LOG_TAG) << "Metadata pipe opened: " << pipePath_ << "\n";
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Error opening metadata pipe, retrying in 500ms. Error: " << e.what() << "\n";
pipe_fd_ = nullptr;
wait(pipe_open_timer_, 500ms, [this] { pipeReadLine(); });
return;
}
}
const std::string delimiter = "\n";
boost::asio::async_read_until(*pipe_fd_, streambuf_pipe_, delimiter,
[this, delimiter](const std::error_code& ec, std::size_t bytes_transferred)
{
if (ec)
{
if ((ec.value() == boost::asio::error::eof) || (ec.value() == boost::asio::error::bad_descriptor))
{
// For some reason, EOF is returned until the first metadata is written to the pipe.
// If shairport-sync has not finished setting up the pipe, bad file descriptor is returned.
static constexpr auto retry_ms = 2500ms;
LOG(read_logseverity_, LOG_TAG) << "Waiting for metadata, retrying in " << retry_ms.count() << "ms\n";
read_logseverity_ = AixLog::Severity::debug;
wait(pipe_open_timer_, retry_ms, [this] { pipeReadLine(); });
}
else
{
LOG(ERROR, LOG_TAG) << "Error while reading from metadata pipe: " << ec.message() << "\n";
}
return;
}
read_logseverity_ = AixLog::Severity::info;
// Extract up to the first delimiter.
std::string line{buffers_begin(streambuf_pipe_.data()), buffers_begin(streambuf_pipe_.data()) + bytes_transferred - delimiter.length()};
if (!line.empty())
{
if (line.back() == '\r')
line.resize(line.size() - 1);
#ifdef HAS_EXPAT
parse(line);
#endif
}
streambuf_pipe_.consume(bytes_transferred);
pipeReadLine();
});
}
void AirplayStream::initExeAndPath(const string& filename)
{
path_ = "";
exe_ = findExe(filename);
if (!utils::file::exists(exe_) || (exe_ == "/"))
{
exe_ = findExe("shairport-sync");
if (!utils::file::exists(exe_))
throw SnapException("shairport-sync not found");
}
if (exe_.find('/') != string::npos)
{
path_ = exe_.substr(0, exe_.find_last_of('/') + 1);
exe_ = exe_.substr(exe_.find_last_of('/') + 1);
}
}
void AirplayStream::onStderrMsg(const std::string& line)
{
if (line.empty())
return;
LOG(INFO, LOG_TAG) << "(" << getName() << ") " << line << "\n";
if (line.find("Is another instance of Shairport Sync running on this device") != string::npos)
{
LOG(ERROR, LOG_TAG) << "It seems there is another Shairport Sync runnig on port " << port_ << ", switching to port " << port_ + 1 << "\n";
++port_;
setParamsAndPipePathFromPort();
}
else if (line.find("Invalid audio output specified") != string::npos)
{
LOG(ERROR, LOG_TAG) << "shairport sync compiled without stdout audio backend\n";
LOG(ERROR, LOG_TAG) << "build with: \"./configure --with-stdout --with-avahi --with-ssl=openssl --with-metadata\"\n";
}
}
#ifdef HAS_EXPAT
void XMLCALL AirplayStream::element_start(void* userdata, const char* element_name, const char** attr)
{
auto* self = static_cast<AirplayStream*>(userdata);
string name(element_name);
self->buf_.assign("");
if (name == "item")
self->entry_.reset(new TageEntry);
for (int i = 0; attr[i] != nullptr; i += 2)
{
string name(attr[i]);
string value(attr[i + 1]);
if (name == "encoding")
self->entry_->isBase64 = (value == "base64"); // Quick & dirty..
}
}
void XMLCALL AirplayStream::element_end(void* userdata, const char* element_name)
{
auto* self = static_cast<AirplayStream*>(userdata);
string name(element_name);
if (name == "code")
self->entry_->code.assign(hex2str(self->buf_));
else if (name == "type")
self->entry_->type.assign(hex2str(self->buf_));
else if (name == "length")
self->entry_->length = strtoul(self->buf_.c_str(), nullptr, 10);
else if (name == "data")
self->entry_->data = self->buf_;
else if (name == "item")
self->push();
else if (name == "metatags")
;
else
cout << "Unknown tag <" << name << ">\n";
}
void XMLCALL AirplayStream::data(void* userdata, const char* content, int length)
{
auto* self = static_cast<AirplayStream*>(userdata);
string value(content, static_cast<size_t>(length));
self->buf_.append(value);
}
#endif
} // namespace streamreader
| 12,274
|
C++
|
.cpp
| 320
| 32.49375
| 153
| 0.611345
|
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,961
|
stream_uri.cpp
|
badaix_snapcast/server/streamreader/stream_uri.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_uri.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/utils/string_utils.hpp"
using namespace std;
namespace strutils = utils::string;
namespace streamreader
{
StreamUri::StreamUri(const std::string& uri)
{
parse(uri);
}
void StreamUri::parse(const std::string& streamUri)
{
// https://en.wikipedia.org/wiki/Uniform_Resource_Identifier
// scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
// would be more elegant with regex. Not yet supported on my dev machine's gcc 4.8 :(
LOG(DEBUG) << "StreamUri: " << streamUri << "\n";
size_t pos;
uri = strutils::trim_copy(streamUri);
while (!uri.empty() && ((uri[0] == '\'') || (uri[0] == '"')))
uri = uri.substr(1);
while (!uri.empty() && ((uri[uri.length() - 1] == '\'') || (uri[uri.length() - 1] == '"')))
uri = uri.substr(0, this->uri.length() - 1);
// string decodedUri = strutils::uriDecode(uri);
// LOG(DEBUG) << "StreamUri decoded: " << decodedUri << "\n";
string tmp(uri);
pos = tmp.find(':');
if (pos == string::npos)
throw invalid_argument("missing ':'");
scheme = strutils::uriDecode(strutils::trim_copy(tmp.substr(0, pos)));
tmp = tmp.substr(pos + 1);
LOG(TRACE) << "scheme: '" << scheme << "', tmp: '" << tmp << "'\n";
if (tmp.find("//") != 0)
throw invalid_argument("missing host separator: '//'");
tmp = tmp.substr(2);
pos = tmp.find('/');
if (pos == string::npos)
{
pos = tmp.find('?');
if (pos == string::npos)
pos = tmp.length();
}
host = strutils::uriDecode(strutils::trim_copy(tmp.substr(0, pos)));
tmp = tmp.substr(pos);
path = tmp;
pos = std::min(path.find('?'), path.find('#'));
path = strutils::uriDecode(strutils::trim_copy(path.substr(0, pos)));
LOG(TRACE) << "host: '" << host << "', tmp: '" << tmp << "', path: '" << path << "'\n";
string queryStr;
pos = tmp.find('?');
if (pos != string::npos)
{
tmp = tmp.substr(pos + 1);
queryStr = tmp;
LOG(TRACE) << "path: '" << path << "', tmp: '" << tmp << "', query: '" << queryStr << "'\n";
}
pos = tmp.find('#');
if (pos != string::npos)
{
queryStr = tmp.substr(0, pos);
tmp = tmp.substr(pos + 1);
fragment = strutils::uriDecode(strutils::trim_copy(tmp));
LOG(TRACE) << "query: '" << queryStr << "', fragment: '" << fragment << "', tmp: '" << tmp << "'\n";
}
vector<string> keyValueList = strutils::split(queryStr, '&');
for (auto& kv : keyValueList)
{
pos = kv.find('=');
if (pos != string::npos)
{
string key = strutils::uriDecode(strutils::trim_copy(kv.substr(0, pos)));
string value = strutils::uriDecode(strutils::trim_copy(kv.substr(pos + 1)));
query[key] = value;
}
}
LOG(DEBUG) << "StreamUri.toString: " << toString() << "\n";
}
std::string StreamUri::toString() const
{
// scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
stringstream ss;
ss << scheme << "://" << host << "/" + path;
if (!query.empty())
{
ss << "?";
auto iter = query.begin();
while (true)
{
ss << iter->first << "=" << iter->second;
if (++iter == query.end())
break;
ss << "&";
}
}
if (!fragment.empty())
ss << "#" << fragment;
return ss.str();
}
json StreamUri::toJson() const
{
json j = {{"raw", toString()}, {"scheme", scheme}, {"host", host}, {"path", path}, {"fragment", fragment}, {"query", query}};
return j;
}
std::string StreamUri::getQuery(const std::string& key, const std::string& def) const
{
auto iter = query.find(key);
if (iter != query.end())
return iter->second;
return def;
}
} // namespace streamreader
| 4,748
|
C++
|
.cpp
| 130
| 30.969231
| 129
| 0.579956
|
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,963
|
stream_manager.cpp
|
badaix_snapcast/server/streamreader/stream_manager.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 "stream_manager.hpp"
// local headers
#include "airplay_stream.hpp"
#ifdef HAS_ALSA
#include "alsa_stream.hpp"
#endif
#ifdef HAS_JACK
#include "jack_stream.hpp"
#endif
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "file_stream.hpp"
#include "librespot_stream.hpp"
#include "meta_stream.hpp"
#include "pipe_stream.hpp"
#include "process_stream.hpp"
#include "tcp_stream.hpp"
// 3rd party headers
// standard headers
using namespace std;
namespace streamreader
{
StreamManager::StreamManager(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& settings)
// const std::string& defaultSampleFormat, const std::string& defaultCodec, size_t defaultChunkBufferMs)
: pcmListener_(pcmListener), settings_(settings), io_context_(ioc)
{
}
PcmStreamPtr StreamManager::addStream(const std::string& uri)
{
StreamUri streamUri(uri);
return addStream(streamUri);
}
PcmStreamPtr StreamManager::addStream(StreamUri& streamUri)
{
if (streamUri.query.find(kUriSampleFormat) == streamUri.query.end())
streamUri.query[kUriSampleFormat] = settings_.stream.sampleFormat;
if (streamUri.query.find(kUriCodec) == streamUri.query.end())
streamUri.query[kUriCodec] = settings_.stream.codec;
if (streamUri.query.find(kUriChunkMs) == streamUri.query.end())
streamUri.query[kUriChunkMs] = cpt::to_string(settings_.stream.streamChunkMs);
// LOG(DEBUG) << "\nURI: " << streamUri.uri << "\nscheme: " << streamUri.scheme << "\nhost: "
// << streamUri.host << "\npath: " << streamUri.path << "\nfragment: " << streamUri.fragment << "\n";
// for (auto kv: streamUri.query)
// LOG(DEBUG) << "key: '" << kv.first << "' value: '" << kv.second << "'\n";
PcmStreamPtr stream(nullptr);
PcmStream::Listener* listener = pcmListener_;
if ((streamUri.query[kUriCodec] == "null") && (streamUri.scheme != "meta"))
{
// Streams with null codec are "invisible" and will not report any updates to the listener.
// If the stream is used as input for a Meta stream, then the meta stream will add himself
// as another listener to the stream, so that updates are indirect reported through it.
listener = nullptr;
}
if (streamUri.scheme == "pipe")
{
stream = make_shared<PipeStream>(listener, io_context_, settings_, streamUri);
}
else if (streamUri.scheme == "file")
{
stream = make_shared<FileStream>(listener, io_context_, settings_, streamUri);
}
else if (streamUri.scheme == "process")
{
stream = make_shared<ProcessStream>(listener, io_context_, settings_, streamUri);
}
#ifdef HAS_ALSA
else if (streamUri.scheme == "alsa")
{
stream = make_shared<AlsaStream>(listener, io_context_, settings_, streamUri);
}
#endif
#ifdef HAS_JACK
else if (streamUri.scheme == "jack")
{
stream = make_shared<JackStream>(listener, io_context_, settings_, streamUri);
}
#endif
else if ((streamUri.scheme == "spotify") || (streamUri.scheme == "librespot"))
{
// Overwrite sample format here instead of inside the constructor, to make sure
// that all constructors of all parent classes also use the overwritten sample
// format.
streamUri.query[kUriSampleFormat] = "44100:16:2";
stream = make_shared<LibrespotStream>(listener, io_context_, settings_, streamUri);
}
else if (streamUri.scheme == "airplay")
{
// Overwrite sample format here instead of inside the constructor, to make sure
// that all constructors of all parent classes also use the overwritten sample
// format.
streamUri.query[kUriSampleFormat] = "44100:16:2";
stream = make_shared<AirplayStream>(listener, io_context_, settings_, streamUri);
}
else if (streamUri.scheme == "tcp")
{
stream = make_shared<TcpStream>(listener, io_context_, settings_, streamUri);
}
else if (streamUri.scheme == "meta")
{
stream = make_shared<MetaStream>(listener, streams_, io_context_, settings_, streamUri);
}
else
{
throw SnapException("Unknown stream type: " + streamUri.scheme);
}
if (stream)
{
for (const auto& s : streams_)
{
if (s->getName() == stream->getName())
throw SnapException("Stream with name \"" + stream->getName() + "\" already exists");
}
streams_.push_back(stream);
}
return stream;
}
void StreamManager::removeStream(const std::string& name)
{
auto iter = std::find_if(streams_.begin(), streams_.end(), [&name](const PcmStreamPtr& stream) { return stream->getName() == name; });
if (iter != streams_.end())
{
(*iter)->stop();
streams_.erase(iter);
}
}
const std::vector<PcmStreamPtr>& StreamManager::getStreams()
{
return streams_;
}
const PcmStreamPtr StreamManager::getDefaultStream()
{
if (streams_.empty())
return nullptr;
for (const auto& stream : streams_)
{
if (stream->getCodec() != "null")
return stream;
}
return nullptr;
}
const PcmStreamPtr StreamManager::getStream(const std::string& id)
{
for (auto stream : streams_)
{
if (stream->getId() == id)
return stream;
}
return nullptr;
}
void StreamManager::start()
{
// Start meta streams first
for (const auto& stream : streams_)
if (stream->getUri().scheme == "meta")
stream->start();
// Start normal streams second
for (const auto& stream : streams_)
if (stream->getUri().scheme != "meta")
stream->start();
}
void StreamManager::stop()
{
// Stop normal streams first
for (const auto& stream : streams_)
if (stream && (stream->getUri().scheme != "meta"))
stream->stop();
// Stop meta streams second
for (const auto& stream : streams_)
if (stream && (stream->getUri().scheme == "meta"))
stream->stop();
}
json StreamManager::toJson() const
{
json result = json::array();
for (const auto& stream : streams_)
{
// A stream with "null" codec will only serve as input for a meta stream, i.e. is not a "stand alone" stream
if (stream->getCodec() != "null")
result.push_back(stream->toJson());
}
return result;
}
} // namespace streamreader
| 7,222
|
C++
|
.cpp
| 198
| 31.29798
| 138
| 0.662563
|
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,964
|
properties.cpp
|
badaix_snapcast/server/streamreader/properties.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 "properties.hpp"
// local headers
#include "common/aixlog.hpp"
// standard headers
#include <set>
static constexpr auto LOG_TAG = "Properties";
namespace
{
template <typename T>
void readTag(const json& j, const std::string& tag, std::optional<T>& dest)
{
try
{
if (!j.contains(tag))
dest = std::nullopt;
else
dest = j[tag].get<T>();
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "failed to read tag: '" << tag << "': " << e.what() << '\n';
}
}
template <typename T>
void readTag(const json& j, const std::string& tag, T& dest, const T& def)
{
std::optional<T> val;
readTag(j, tag, val);
if (val.has_value())
dest = val.value();
else
dest = def;
}
template <typename T>
void addTag(json& j, const std::string& tag, const T& source)
{
try
{
j[tag] = source;
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "failed to add tag: '" << tag << "': " << e.what() << '\n';
}
}
template <typename T>
void addTag(json& j, const std::string& tag, const std::optional<T>& source)
{
if (!source.has_value())
{
if (j.contains(tag))
j.erase(tag);
}
else
addTag(j, tag, source.value());
}
} // namespace
Properties::Properties(const json& j)
{
fromJson(j);
}
json Properties::toJson() const
{
json j;
if (playback_status.has_value())
addTag(j, "playbackStatus", std::optional<std::string>(to_string(playback_status.value())));
if (loop_status.has_value())
addTag(j, "loopStatus", std::optional<std::string>(to_string(loop_status.value())));
addTag(j, "rate", rate);
addTag(j, "shuffle", shuffle);
addTag(j, "volume", volume);
addTag(j, "mute", mute);
addTag(j, "position", position);
addTag(j, "minimumRate", minimum_rate);
addTag(j, "maximumRate", maximum_rate);
addTag(j, "canGoNext", can_go_next);
addTag(j, "canGoPrevious", can_go_previous);
addTag(j, "canPlay", can_play);
addTag(j, "canPause", can_pause);
addTag(j, "canSeek", can_seek);
addTag(j, "canControl", can_control);
if (metadata.has_value())
addTag(j, "metadata", metadata->toJson());
return j;
}
void Properties::fromJson(const json& j)
{
static std::set<std::string> rw_props = {"loopStatus", "shuffle", "volume", "mute", "rate"};
static std::set<std::string> ro_props = {"playbackStatus", "loopStatus", "shuffle", "volume", "mute", "position", "minimumRate", "maximumRate",
"canGoNext", "canGoPrevious", "canPlay", "canPause", "canSeek", "canControl", "metadata"};
for (const auto& element : j.items())
{
bool is_rw = (rw_props.find(element.key()) != rw_props.end());
bool is_ro = (ro_props.find(element.key()) != ro_props.end());
if (!is_rw && !is_ro)
LOG(WARNING, LOG_TAG) << "Property not supoorted: " << element.key() << "\n";
}
std::optional<std::string> opt;
readTag(j, "playbackStatus", opt);
if (opt.has_value())
playback_status = playback_status_from_string(opt.value());
else
playback_status = std::nullopt;
readTag(j, "loopStatus", opt);
if (opt.has_value())
loop_status = loop_status_from_string(opt.value());
else
loop_status = std::nullopt;
readTag(j, "rate", rate);
readTag(j, "shuffle", shuffle);
readTag(j, "volume", volume);
readTag(j, "mute", mute);
readTag(j, "position", position);
readTag(j, "minimumRate", minimum_rate);
readTag(j, "maximumRate", maximum_rate);
readTag(j, "canGoNext", can_go_next, false);
readTag(j, "canGoPrevious", can_go_previous, false);
readTag(j, "canPlay", can_play, false);
readTag(j, "canPause", can_pause, false);
readTag(j, "canSeek", can_seek, false);
readTag(j, "canControl", can_control, false);
if (j.contains("metadata"))
{
Metadata m;
m.fromJson(j["metadata"]);
metadata = m;
}
else
metadata = std::nullopt;
}
bool Properties::operator==(const Properties& other) const
{
// expensive, but not called ofetn and less typing
return (toJson() == other.toJson());
// clang-format off
// return (playback_status == other.playback_status &&
// loop_status == other.loop_status &&
// rate == other.rate &&
// shuffle == other.shuffle &&
// volume == other.volume &&
// position == other.position &&
// minimum_rate == other.minimum_rate &&
// maximum_rate == other.maximum_rate &&
// can_go_next == other.can_go_next &&
// can_go_previous == other.can_go_previous &&
// can_play == other.can_play &&
// can_pause == other.can_pause &&
// can_seek == other.can_seek &&
// can_control == other.can_control);
// clang-format on
}
| 5,854
|
C++
|
.cpp
| 166
| 29.759036
| 157
| 0.601059
|
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,965
|
control_error.cpp
|
badaix_snapcast/server/streamreader/control_error.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 "control_error.hpp"
namespace snapcast::error::control
{
namespace detail
{
struct category : public std::error_category
{
public:
const char* name() const noexcept override;
std::string message(int value) const override;
};
const char* category::name() const noexcept
{
return "control";
}
std::string category::message(int value) const
{
switch (static_cast<ControlErrc>(value))
{
case ControlErrc::success:
return "Success";
case ControlErrc::can_not_control:
return "Stream can not be controlled";
case ControlErrc::can_go_next_is_false:
return "Stream property canGoNext is false";
case ControlErrc::can_go_previous_is_false:
return "Stream property canGoPrevious is false";
case ControlErrc::can_play_is_false:
return "Stream property canPlay is false";
case ControlErrc::can_pause_is_false:
return "Stream property canPause is false";
case ControlErrc::can_seek_is_false:
return "Stream property canSeek is false";
case ControlErrc::can_control_is_false:
return "Stream property canControl is false";
case ControlErrc::parse_error:
return "Parse error";
case ControlErrc::invalid_request:
return "Invalid request";
case ControlErrc::method_not_found:
return "Method not found";
case ControlErrc::invalid_params:
return "Invalid params";
case ControlErrc::internal_error:
return "Internal error";
default:
return "Unknown";
}
}
} // namespace detail
const std::error_category& category()
{
// The category singleton
static detail::category instance;
return instance;
}
} // namespace snapcast::error::control
std::error_code make_error_code(ControlErrc errc)
{
// Create an error_code with the original mpg123 error value
// and the mpg123 error category.
return std::error_code(static_cast<int>(errc), snapcast::error::control::category());
}
| 2,874
|
C++
|
.cpp
| 78
| 30.833333
| 89
| 0.691118
|
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,966
|
metadata.cpp
|
badaix_snapcast/server/streamreader/metadata.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 "metadata.hpp"
// local headers
#include "common/aixlog.hpp"
// standard headers
#include <set>
static constexpr auto LOG_TAG = "Metadata";
namespace
{
template <typename T>
void readTag(const json& j, const std::string& tag, std::optional<T>& dest)
{
try
{
if (!j.contains(tag))
dest = std::nullopt;
else
dest = j[tag].get<T>();
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "failed to read tag: '" << tag << "': " << e.what() << '\n';
}
}
template <typename T>
void addTag(json& j, const std::string& tag, const std::optional<T>& source)
{
try
{
if (!source.has_value())
{
if (j.contains(tag))
j.erase(tag);
}
else
j[tag] = source.value();
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "failed to add tag: '" << tag << "': " << e.what() << '\n';
}
}
} // namespace
Metadata::Metadata(const json& j)
{
fromJson(j);
}
json Metadata::toJson() const
{
json j(json::object());
addTag(j, "trackId", track_id);
addTag(j, "duration", duration);
addTag(j, "artist", artist);
addTag(j, "artistSort", artist_sort);
addTag(j, "album", album);
addTag(j, "albumSort", album_sort);
addTag(j, "albumArtist", album_artist);
addTag(j, "albumArtistSort", album_artist_sort);
addTag(j, "name", name);
addTag(j, "date", date);
addTag(j, "originalDate", original_date);
addTag(j, "performer", performer);
addTag(j, "conductor", conductor);
addTag(j, "work", work);
addTag(j, "grouping", grouping);
addTag(j, "label", label);
addTag(j, "musicbrainzArtistId", musicbrainz_artist_id);
addTag(j, "musicbrainzAlbumId", musicbrainz_album_id);
addTag(j, "musicbrainzAlbumArtistId", musicbrainz_album_artist_id);
addTag(j, "musicbrainzTrackId", musicbrainz_track_id);
addTag(j, "musicbrainzReleaseTrackId", musicbrainz_release_track_id);
addTag(j, "musicbrainzWorkId", musicbrainz_work_id);
addTag(j, "lyrics", lyrics);
addTag(j, "bpm", bpm);
addTag(j, "autoRating", auto_rating);
addTag(j, "comment", comment);
addTag(j, "composer", composer);
addTag(j, "contentCreated", content_created);
addTag(j, "discNumber", disc_number);
addTag(j, "firstUsed", first_used);
addTag(j, "genre", genre);
addTag(j, "lastUsed", last_used);
addTag(j, "lyricist", lyricist);
addTag(j, "title", title);
addTag(j, "trackNumber", track_number);
addTag(j, "url", url);
addTag(j, "artUrl", art_url);
if (art_data.has_value())
{
j["artData"] = {{"data", art_data->data}, {"extension", art_data->extension}};
}
addTag(j, "useCount", use_count);
addTag(j, "userRating", user_rating);
addTag(j, "spotifyArtistId", spotify_artist_id);
addTag(j, "spotifyTrackId", spotify_track_id);
return j;
}
void Metadata::fromJson(const json& j)
{
static std::set<std::string> supported_tags = {"trackId",
"duration",
"artist",
"artistSort",
"album",
"albumSort",
"albumArtist",
"albumArtistSort",
"name",
"date",
"originalDate",
"performer",
"conductor",
"work",
"grouping",
"label",
"musicbrainzArtistId",
"musicbrainzAlbumId",
"musicbrainzAlbumArtistId",
"musicbrainzTrackId",
"musicbrainzReleaseTrackId",
"musicbrainzWorkId",
"lyrics",
"bpm",
"autoRating",
"comment",
"composer",
"contentCreated",
"discNumber",
"firstUsed",
"genre",
"lastUsed",
"lyricist",
"title",
"trackNumber",
"url",
"artUrl",
"artData",
"useCount",
"userRating",
"spotifyArtistId",
"spotifyTrackId"};
for (const auto& element : j.items())
{
if (supported_tags.find(element.key()) == supported_tags.end())
LOG(WARNING, LOG_TAG) << "Tag not supoorted: " << element.key() << "\n";
}
readTag(j, "trackId", track_id);
readTag(j, "duration", duration);
readTag(j, "artist", artist);
readTag(j, "artistSort", artist_sort);
readTag(j, "album", album);
readTag(j, "albumSort", album_sort);
readTag(j, "albumArtist", album_artist);
readTag(j, "albumArtistSort", album_artist_sort);
readTag(j, "name", name);
readTag(j, "date", date);
readTag(j, "originalDate", original_date);
readTag(j, "performer", performer);
readTag(j, "conductor", conductor);
readTag(j, "work", work);
readTag(j, "grouping", grouping);
readTag(j, "label", label);
readTag(j, "musicbrainzArtistId", musicbrainz_artist_id);
readTag(j, "musicbrainzAlbumId", musicbrainz_album_id);
readTag(j, "musicbrainzAlbumArtistId", musicbrainz_album_artist_id);
readTag(j, "musicbrainzTrackId", musicbrainz_track_id);
readTag(j, "musicbrainzReleaseTrackId", musicbrainz_release_track_id);
readTag(j, "musicbrainzWorkId", musicbrainz_work_id);
readTag(j, "lyrics", lyrics);
readTag(j, "bpm", bpm);
readTag(j, "autoRating", auto_rating);
readTag(j, "comment", comment);
readTag(j, "composer", composer);
readTag(j, "contentCreated", content_created);
readTag(j, "discNumber", disc_number);
readTag(j, "firstUsed", first_used);
readTag(j, "genre", genre);
readTag(j, "lastUsed", last_used);
readTag(j, "lyricist", lyricist);
readTag(j, "title", title);
readTag(j, "trackNumber", track_number);
readTag(j, "url", url);
readTag(j, "artUrl", art_url);
art_data = std::nullopt;
if (j.contains("artData") && j["artData"].contains("data") && j["artData"].contains("extension"))
{
art_data = ArtData{j["artData"]["data"].get<std::string>(), j["artData"]["extension"].get<std::string>()};
}
readTag(j, "useCount", use_count);
readTag(j, "userRating", user_rating);
readTag(j, "spotifyArtistId", spotify_artist_id);
readTag(j, "spotifyTrackId", spotify_track_id);
}
bool Metadata::operator==(const Metadata& other) const
{
// expensive, but not called often and less typing
return (toJson() == other.toJson());
}
| 8,881
|
C++
|
.cpp
| 212
| 27.858491
| 114
| 0.496936
|
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,967
|
librespot_stream.cpp
|
badaix_snapcast/server/streamreader/librespot_stream.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 "librespot_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/utils.hpp"
#include "common/utils/file_utils.hpp"
#include "common/utils/string_utils.hpp"
// standard headers
#include <exception>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "LibrespotStream";
// https://commons.wikimedia.org/wiki/File:Spotify_logo_without_text.svg
static constexpr auto SPOTIFY_LOGO = "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxz"
"dmcgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiBoZWlnaHQ9IjE2OHB4IiB3aWR0"
"aD0iMTY4cHgiIHZlcnNpb249IjEuMSIgdmlld0JveD0iMCAwIDE2OCAxNjgiPgogPHBhdGggZmls"
"bD0iIzFFRDc2MCIgZD0ibTgzLjk5NiAwLjI3N2MtNDYuMjQ5IDAtODMuNzQzIDM3LjQ5My04My43"
"NDMgODMuNzQyIDAgNDYuMjUxIDM3LjQ5NCA4My43NDEgODMuNzQzIDgzLjc0MSA0Ni4yNTQgMCA4"
"My43NDQtMzcuNDkgODMuNzQ0LTgzLjc0MSAwLTQ2LjI0Ni0zNy40OS04My43MzgtODMuNzQ1LTgz"
"LjczOGwwLjAwMS0wLjAwNHptMzguNDA0IDEyMC43OGMtMS41IDIuNDYtNC43MiAzLjI0LTcuMTgg"
"MS43My0xOS42NjItMTIuMDEtNDQuNDE0LTE0LjczLTczLjU2NC04LjA3LTIuODA5IDAuNjQtNS42"
"MDktMS4xMi02LjI0OS0zLjkzLTAuNjQzLTIuODEgMS4xMS01LjYxIDMuOTI2LTYuMjUgMzEuOS03"
"LjI5MSA1OS4yNjMtNC4xNSA4MS4zMzcgOS4zNCAyLjQ2IDEuNTEgMy4yNCA0LjcyIDEuNzMgNy4x"
"OHptMTAuMjUtMjIuODA1Yy0xLjg5IDMuMDc1LTUuOTEgNC4wNDUtOC45OCAyLjE1NS0yMi41MS0x"
"My44MzktNTYuODIzLTE3Ljg0Ni04My40NDgtOS43NjQtMy40NTMgMS4wNDMtNy4xLTAuOTAzLTgu"
"MTQ4LTQuMzUtMS4wNC0zLjQ1MyAwLjkwNy03LjA5MyA0LjM1NC04LjE0MyAzMC40MTMtOS4yMjgg"
"NjguMjIyLTQuNzU4IDk0LjA3MiAxMS4xMjcgMy4wNyAxLjg5IDQuMDQgNS45MSAyLjE1IDguOTc2"
"di0wLjAwMXptMC44OC0yMy43NDRjLTI2Ljk5LTE2LjAzMS03MS41Mi0xNy41MDUtOTcuMjg5LTku"
"Njg0LTQuMTM4IDEuMjU1LTguNTE0LTEuMDgxLTkuNzY4LTUuMjE5LTEuMjU0LTQuMTQgMS4wOC04"
"LjUxMyA1LjIyMS05Ljc3MSAyOS41ODEtOC45OCA3OC43NTYtNy4yNDUgMTA5LjgzIDExLjIwMiAz"
"LjczIDIuMjA5IDQuOTUgNy4wMTYgMi43NCAxMC43MzMtMi4yIDMuNzIyLTcuMDIgNC45NDktMTAu"
"NzMgMi43Mzl6Ii8+Cjwvc3ZnPgo=";
LibrespotStream::LibrespotStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: ProcessStream(pcmListener, ioc, server_settings, uri)
{
wd_timeout_sec_ = cpt::stoul(uri_.getQuery("wd_timeout", "7800")); ///< 130min
string username = uri_.getQuery("username", "");
string password = uri_.getQuery("password", "");
string cache = uri_.getQuery("cache", "");
bool disable_audio_cache = (uri_.getQuery("disable_audio_cache", "false") == "true");
string volume = uri_.getQuery("volume", "100");
string bitrate = uri_.getQuery("bitrate", "320");
string devicename = uri_.getQuery("devicename", "Snapcast");
string onevent = uri_.getQuery("onevent", "");
bool normalize = (uri_.getQuery("normalize", "false") == "true");
bool autoplay = (uri_.getQuery("autoplay", "false") == "true");
killall_ = (uri_.getQuery("killall", "false") == "true");
if (username.empty() != password.empty())
throw SnapException(R"(missing parameter "username" or "password" (must provide both, or neither))");
if (!params_.empty())
params_ += " ";
params_ += "--name \"" + devicename + "\"";
if (!username.empty() && !password.empty())
params_ += " --username \"" + username + "\" --password \"" + password + "\"";
params_ += " --bitrate " + bitrate + " --backend pipe";
if (!cache.empty())
params_ += " --cache \"" + cache + "\"";
if (disable_audio_cache)
params_ += " --disable-audio-cache";
if (!volume.empty())
params_ += " --initial-volume " + volume;
if (!onevent.empty())
params_ += " --onevent \"" + onevent + "\"";
if (normalize)
params_ += " --enable-volume-normalisation";
if (autoplay)
params_ += " --autoplay on";
params_ += " --verbose";
if (uri_.query.find("username") != uri_.query.end())
uri_.query["username"] = "xxx";
if (uri_.query.find("password") != uri_.query.end())
uri_.query["password"] = "xxx";
// LOG(INFO, LOG_TAG) << "params: " << params << "\n";
}
void LibrespotStream::initExeAndPath(const std::string& filename)
{
path_ = "";
exe_ = findExe(filename);
if (!utils::file::exists(exe_) || (exe_ == "/"))
{
exe_ = findExe("librespot");
if (!utils::file::exists(exe_))
throw SnapException("librespot not found");
}
if (exe_.find('/') != string::npos)
{
path_ = exe_.substr(0, exe_.find_last_of('/') + 1);
exe_ = exe_.substr(exe_.find_last_of('/') + 1);
}
if (killall_)
{
/// kill if it's already running
execGetOutput("killall " + exe_);
}
}
void LibrespotStream::onStderrMsg(const std::string& line)
{
try
{
// Watch stderr for 'Loading track' messages and set the stream metadata
// For more than track name check: https://github.com/plietar/librespot/issues/154
/// Watch will kill librespot if there was no message received for 130min
// 2021-05-09 09-25-48.651 [Info] (LibrespotStream) (Spotify) [2021-05-09T07:25:48Z DEBUG librespot_playback::player] command=Load(SpotifyId
// 2021-05-09 09-25-48.651 [Info] (LibrespotStream) (Spotify) [2021-05-09T07:25:48Z TRACE librespot_connect::spirc] Sending status to server
// 2021-05-09 09-25-48.746 [Info] (LibrespotStream) (Spotify) [2021-05-09T07:25:48Z WARN librespot_connect::spirc] No autoplay_uri found
// 2021-05-09 09-25-48.747 [Info] (LibrespotStream) (Spotify) [2021-05-09T07:25:48Z ERROR librespot_connect::spirc] AutoplayError: MercuryError
// 2021-05-09 09-25-48.750 [Info] (LibrespotStream) (Spotify) [2021-05-09T07:25:48Z INFO librespot_playback::player] Loading <Big Gangsta>
// Parse log level, source and message from the log line
// Format: [2021-05-09T08:31:08Z DEBUG librespot_playback::player] new Player[0]
// std::cerr << "Librespot: " << line << "\n";
std::string message = line;
utils::string::split_left(message, ' ', message);
std::string level = utils::string::trim_copy(utils::string::split_left(message, ' ', message));
std::string source = utils::string::trim_copy(utils::string::split_left(message, ']', message));
utils::string::trim(message);
bool parsed = true;
AixLog::Severity severity = AixLog::Severity::info;
if (level == "TRACE")
severity = AixLog::Severity::trace;
else if (level == "DEBUG")
severity = AixLog::Severity::debug;
else if (level == "INFO")
severity = AixLog::Severity::info;
else if (level == "WARN")
severity = AixLog::Severity::warning;
else if (level == "ERROR")
severity = AixLog::Severity::error;
else
parsed = false;
if (parsed)
{
LOG(severity, source) << message << "\n";
// std::cerr << "Parsed: " << "Severity: " << severity << ", source: " << source << ", msg: " << message << "\n";
}
else
{
return;
// LOG(INFO, LOG_TAG) << "(" << getName() << ") " << line << "\n";
}
// [2021-06-04T07:20:47Z INFO librespot_playback::player] <Tunnel> (310573 ms) loaded
// info!("Track \"{}\" loaded", track.name);
size_t title_pos = 0;
size_t ms_pos = 0;
size_t n = 0;
if (((title_pos = line.find("<")) != std::string::npos) && ((n = line.find(">", title_pos)) != std::string::npos) &&
((ms_pos = line.find("(", n)) != std::string::npos) && ((n = line.find("ms) loaded", ms_pos)) != std::string::npos))
{
title_pos += 1;
std::string title = line.substr(title_pos, line.find(">", title_pos) - title_pos);
LOG(INFO, LOG_TAG) << "metadata: <" << title << ">\n";
ms_pos += 1;
std::string ms = line.substr(ms_pos, n - ms_pos - 1);
Metadata meta;
meta.title = title;
meta.duration = cpt::stod(ms) / 1000.;
meta.art_data = {SPOTIFY_LOGO, "svg"};
Properties properties;
properties.metadata = std::move(meta);
setProperties(properties);
}
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Exception: " << e.what() << std::endl;
}
}
} // namespace streamreader
| 9,854
|
C++
|
.cpp
| 183
| 43.781421
| 157
| 0.616884
|
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,968
|
pcm_stream.cpp
|
badaix_snapcast/server/streamreader/pcm_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/>.
***/
// prototype/interface header file
#include "pcm_stream.hpp"
// local headers
#include "base64.h"
#include "common/aixlog.hpp"
#include "common/error_code.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
#include "control_error.hpp"
#include "encoder/encoder_factory.hpp"
// 3rd party headers
#include <boost/asio/ip/host_name.hpp>
// standard headers
#include <memory>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "PcmStream";
PcmStream::PcmStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: active_(false), strand_(boost::asio::make_strand(ioc.get_executor())), pcmListeners_{pcmListener}, uri_(uri), chunk_ms_(20), state_(ReaderState::kIdle),
server_settings_(server_settings), req_id_(0), property_timer_(strand_)
{
encoder::EncoderFactory encoderFactory;
if (uri_.query.find(kUriCodec) == uri_.query.end())
throw SnapException("Stream URI must have a codec");
encoder_ = encoderFactory.createEncoder(uri_.query[kUriCodec]);
if (uri_.query.find(kUriName) == uri_.query.end())
throw SnapException("Stream URI must have a name");
name_ = uri_.query[kUriName];
if (uri_.query.find(kUriSampleFormat) == uri_.query.end())
throw SnapException("Stream URI must have a sampleformat");
sampleFormat_ = SampleFormat(uri_.query[kUriSampleFormat]);
chunk_ = std::make_unique<msg::PcmChunk>(sampleFormat_, chunk_ms_);
silent_chunk_ = std::vector<char>(chunk_->payloadSize, 0);
LOG(DEBUG, LOG_TAG) << "Chunk duration: " << chunk_->durationMs() << " ms, frames: " << chunk_->getFrameCount() << ", size: " << chunk_->payloadSize
<< "\n";
LOG(INFO, LOG_TAG) << "PcmStream: " << name_ << ", sampleFormat: " << sampleFormat_.toString() << "\n";
if (uri_.query.find(kControlScript) != uri_.query.end())
{
std::string params;
if (uri_.query.find(kControlScriptParams) != uri_.query.end())
params = uri_.query[kControlScriptParams];
stream_ctrl_ = std::make_unique<ScriptStreamControl>(strand_, uri_.query[kControlScript], params);
}
if (uri_.query.find(kUriChunkMs) != uri_.query.end())
chunk_ms_ = cpt::stoul(uri_.query[kUriChunkMs]);
double silence_threshold_percent = 0.;
try
{
silence_threshold_percent = cpt::stod(uri_.getQuery("silence_threshold_percent", "0"));
}
catch (...)
{
}
int32_t max_amplitude = std::pow(2, sampleFormat_.bits() - 1) - 1;
silence_threshold_ = max_amplitude * (silence_threshold_percent / 100.);
LOG(DEBUG, LOG_TAG) << "Silence threshold percent: " << silence_threshold_percent << ", silence threshold amplitude: " << silence_threshold_ << "\n";
}
PcmStream::~PcmStream()
{
stop();
property_timer_.cancel();
}
std::shared_ptr<msg::CodecHeader> PcmStream::getHeader()
{
return encoder_->getHeader();
}
const StreamUri& PcmStream::getUri() const
{
return uri_;
}
const std::string& PcmStream::getName() const
{
return name_;
}
const std::string& PcmStream::getId() const
{
return getName();
}
const SampleFormat& PcmStream::getSampleFormat() const
{
return sampleFormat_;
}
std::string PcmStream::getCodec() const
{
return encoder_->name();
}
void PcmStream::onControlRequest(const jsonrpcpp::Request& request)
{
LOG(INFO, LOG_TAG) << "Request: " << request.method() << ", id: " << request.id() << ", params: " << request.params().to_json() << "\n";
}
void PcmStream::pollProperties()
{
property_timer_.expires_after(10s);
property_timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (!ec)
{
stream_ctrl_->command({++req_id_, "Plugin.Stream.Player.GetProperties"},
[this](const jsonrpcpp::Response& response)
{
LOG(INFO, LOG_TAG) << "Response for Plugin.Stream.Player.GetProperties: " << response.to_json() << "\n";
if (response.error().code() == 0)
setProperties(response.result());
});
pollProperties();
}
});
}
void PcmStream::onControlNotification(const jsonrpcpp::Notification& notification)
{
try
{
LOG(DEBUG, LOG_TAG) << "Notification method: " << notification.method() << ", params: " << notification.params().to_json() << "\n";
if (notification.method() == "Plugin.Stream.Player.Properties")
{
LOG(DEBUG, LOG_TAG) << "Received properties notification\n";
setProperties(notification.params().to_json());
}
else if (notification.method() == "Plugin.Stream.Ready")
{
LOG(DEBUG, LOG_TAG) << "Plugin is ready\n";
stream_ctrl_->command({++req_id_, "Plugin.Stream.Player.GetProperties"},
[this](const jsonrpcpp::Response& response)
{
LOG(INFO, LOG_TAG) << "Response for Plugin.Stream.Player.GetProperties: " << response.to_json() << "\n";
if (response.error().code() == 0)
setProperties(response.result());
});
// TODO: Add capabilities or settings?
// {"jsonrpc": "2.0", "method": "Plugin.Stream.Ready", "params": {"pollProperties": 10, "responseTimeout": 5}}
// pollProperties();
}
else if (notification.method() == "Plugin.Stream.Log")
{
std::string severity = notification.params().get("severity");
std::string message = notification.params().get("message");
LOG(INFO, LOG_TAG) << "Plugin log - severity: " << severity << ", message: " << message << "\n";
}
else
LOG(WARNING, LOG_TAG) << "Received unknown notification method: '" << notification.method() << "'\n";
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Error while receiving notification: " << e.what() << '\n';
}
}
void PcmStream::onControlLog(std::string line)
{
if (line.back() == '\r')
line.resize(line.size() - 1);
if (line.empty())
return;
auto tmp = utils::string::tolower_copy(line);
AixLog::Severity severity = AixLog::Severity::info;
if (tmp.find(" trace") != string::npos)
severity = AixLog::Severity::trace;
else if (tmp.find(" debug") != string::npos)
severity = AixLog::Severity::debug;
else if (tmp.find(" info") != string::npos)
severity = AixLog::Severity::info;
else if (tmp.find(" warning") != string::npos)
severity = AixLog::Severity::warning;
else if (tmp.find(" error") != string::npos)
severity = AixLog::Severity::error;
else if ((tmp.find(" fatal") != string::npos) || (tmp.find(" critical") != string::npos))
severity = AixLog::Severity::fatal;
LOG(severity, LOG_TAG) << "Stream: " << getId() << ", message: " << line << "\n";
}
void PcmStream::start()
{
LOG(DEBUG, LOG_TAG) << "Start: " << name_ << ", type: " << uri_.scheme << ", sampleformat: " << sampleFormat_.toString() << ", codec: " << getCodec()
<< "\n";
encoder_->init([this](const encoder::Encoder& encoder, std::shared_ptr<msg::PcmChunk> chunk, double duration) { chunkEncoded(encoder, chunk, duration); },
sampleFormat_);
if (stream_ctrl_)
{
stream_ctrl_->start(
getId(), server_settings_, [this](const jsonrpcpp::Notification& notification) { onControlNotification(notification); },
[this](const jsonrpcpp::Request& request) { onControlRequest(request); }, [this](std::string message) { onControlLog(std::move(message)); });
}
active_ = true;
}
void PcmStream::stop()
{
active_ = false;
setState(ReaderState::kIdle);
}
bool PcmStream::isSilent(const msg::PcmChunk& chunk) const
{
if (silence_threshold_ == 0)
return (std::memcmp(chunk.payload, silent_chunk_.data(), silent_chunk_.size()) == 0);
if (sampleFormat_.sampleSize() == 1)
{
auto payload = chunk.getPayload<int8_t>();
for (size_t n = 0; n < payload.second; ++n)
{
if (abs(payload.first[n]) > silence_threshold_)
return false;
}
}
else if (sampleFormat_.sampleSize() == 2)
{
auto payload = chunk.getPayload<int16_t>();
for (size_t n = 0; n < payload.second; ++n)
{
if (abs(payload.first[n]) > silence_threshold_)
return false;
}
}
else if (sampleFormat_.sampleSize() == 4)
{
auto payload = chunk.getPayload<int32_t>();
for (size_t n = 0; n < payload.second; ++n)
{
if (abs(payload.first[n]) > silence_threshold_)
return false;
}
}
return true;
}
ReaderState PcmStream::getState() const
{
return state_;
}
void PcmStream::setState(ReaderState newState)
{
if (newState != state_)
{
LOG(INFO, LOG_TAG) << "State changed: " << name_ << ", state: " << state_ << " => " << newState << "\n";
state_ = newState;
for (auto* listener : pcmListeners_)
{
if (listener != nullptr)
listener->onStateChanged(this, newState);
}
}
}
void PcmStream::chunkEncoded(const encoder::Encoder& encoder, std::shared_ptr<msg::PcmChunk> chunk, double duration)
{
std::ignore = encoder;
// LOG(TRACE, LOG_TAG) << "onChunkEncoded: " << getName() << ", duration: " << duration
// << " ms, compression ratio: " << 100 - ceil(100 * (chunk->durationMs() / duration)) << "%\n";
if (duration <= 0)
return;
// absolute start timestamp is the tvEncodedChunk_
auto microsecs = std::chrono::duration_cast<std::chrono::microseconds>(tvEncodedChunk_.time_since_epoch()).count();
chunk->timestamp.sec = microsecs / 1000000;
chunk->timestamp.usec = microsecs % 1000000;
// update tvEncodedChunk_ to the next chunk start by adding the current chunk duration
tvEncodedChunk_ += std::chrono::nanoseconds(static_cast<std::chrono::nanoseconds::rep>(duration * 1000000));
for (auto* listener : pcmListeners_)
{
if (listener != nullptr)
listener->onChunkEncoded(this, chunk, duration);
}
}
void PcmStream::chunkRead(const msg::PcmChunk& chunk)
{
for (auto* listener : pcmListeners_)
{
if (listener != nullptr)
listener->onChunkRead(this, chunk);
}
encoder_->encode(chunk);
}
void PcmStream::resync(const std::chrono::nanoseconds& duration)
{
for (auto* listener : pcmListeners_)
{
if (listener != nullptr)
listener->onResync(this, duration.count() / 1000000.);
}
}
json PcmStream::toJson() const
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
json j = {
{"uri", uri_.toJson()},
{"id", getId()},
{"status", to_string(state_)},
};
j["properties"] = properties_.toJson();
return j;
}
void PcmStream::addListener(PcmStream::Listener* pcmListener)
{
pcmListeners_.push_back(pcmListener);
}
const Properties& PcmStream::getProperties() const
{
// std::lock_guard<std::recursive_mutex> lock(mutex_);
return properties_;
}
void PcmStream::setShuffle(bool shuffle, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setShuffle: " << shuffle << "\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.SetProperty", {"shuffle", shuffle}, std::move(handler));
}
void PcmStream::setLoopStatus(LoopStatus status, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setLoopStatus: " << status << "\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.SetProperty", {"loopStatus", to_string(status)}, std::move(handler));
}
void PcmStream::setVolume(uint16_t volume, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setVolume: " << volume << "\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.SetProperty", {"volume", volume}, std::move(handler));
}
void PcmStream::setMute(bool mute, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setMute: " << mute << "\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.SetProperty", {"mute", mute}, std::move(handler));
}
void PcmStream::setRate(float rate, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setRate: " << rate << "\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.SetProperty", {"rate", rate}, std::move(handler));
}
void PcmStream::setPosition(std::chrono::milliseconds position, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "setPosition\n";
if (!properties_.can_seek)
return handler({ControlErrc::can_seek_is_false});
json params;
params["command"] = "setPosition";
json j;
j["position"] = position.count() / 1000.f;
params["params"] = j;
sendRequest("Plugin.Stream.Player.Control", params, std::move(handler));
}
void PcmStream::seek(std::chrono::milliseconds offset, ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "seek\n";
if (!properties_.can_seek)
return handler({ControlErrc::can_seek_is_false});
json params;
params["command"] = "seek";
json j;
j["offset"] = offset.count() / 1000.f;
params["params"] = j;
sendRequest("Plugin.Stream.Player.Control", params, std::move(handler));
}
void PcmStream::next(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "next\n";
if (!properties_.can_go_next)
return handler({ControlErrc::can_go_next_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "next"}, std::move(handler));
}
void PcmStream::previous(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "previous\n";
if (!properties_.can_go_previous)
return handler({ControlErrc::can_go_previous_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "previous"}, std::move(handler));
}
void PcmStream::pause(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "pause\n";
if (!properties_.can_pause)
return handler({ControlErrc::can_pause_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "pause"}, std::move(handler));
}
void PcmStream::playPause(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "playPause\n";
if (!properties_.can_pause)
return handler({ControlErrc::can_play_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "playPause"}, std::move(handler));
}
void PcmStream::stop(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "stop\n";
if (!properties_.can_control)
return handler({ControlErrc::can_control_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "stop"}, std::move(handler));
}
void PcmStream::play(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "play\n";
if (!properties_.can_play)
return handler({ControlErrc::can_play_is_false});
sendRequest("Plugin.Stream.Player.Control", {"command", "play"}, std::move(handler));
}
void PcmStream::sendRequest(const std::string& method, const jsonrpcpp::Parameter& params, ResultHandler handler)
{
if (!stream_ctrl_)
return handler({ControlErrc::can_not_control});
jsonrpcpp::Request req(++req_id_, method, params);
stream_ctrl_->command(req,
[handler](const jsonrpcpp::Response& response)
{
if (response.error().code() != 0)
handler({static_cast<ControlErrc>(response.error().code()), response.error().data()});
else
handler({ControlErrc::success});
});
}
void PcmStream::setProperties(const Properties& properties)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
Properties props = properties;
// Missing metadata means the data didn't change, so
// enrich the new properites with old metadata
if (!props.metadata.has_value() && properties_.metadata.has_value())
props.metadata = properties_.metadata;
// If the cover image is availbale as raw data, cache it on the HTTP Server to make it also available via HTTP
if (props.metadata.has_value() && props.metadata->art_data.has_value() && !props.metadata->art_url.has_value())
{
auto data = base64_decode(props.metadata->art_data->data);
auto md5 = ServerSettings::Http::image_cache.setImage(getName(), std::move(data), props.metadata->art_data->extension);
std::stringstream url;
url << "http://" << server_settings_.http.host << ":" << server_settings_.http.port << "/__image_cache?name=" << md5;
props.metadata->art_url = url.str();
}
else if (!props.metadata.has_value() || !props.metadata->art_data.has_value())
{
ServerSettings::Http::image_cache.clear(getName());
}
if (props == properties_)
{
LOG(DEBUG, LOG_TAG) << "setProperties: Properties did not change\n";
return;
}
properties_ = std::move(props);
LOG(DEBUG, LOG_TAG) << "setProperties, stream: " << getId() << ", properties: " << properties_.toJson() << "\n";
// Trigger a stream update
for (auto* listener : pcmListeners_)
{
if (listener != nullptr)
listener->onPropertiesChanged(this, properties_);
}
}
} // namespace streamreader
| 18,599
|
C++
|
.cpp
| 461
| 34.305857
| 158
| 0.634402
|
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,969
|
stream_control.cpp
|
badaix_snapcast/server/streamreader/stream_control.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 "stream_control.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/utils/file_utils.hpp"
// 3rd party headers
#include <boost/asio/read_until.hpp>
// standard headers
#include <memory>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "Script";
StreamControl::StreamControl(const boost::asio::any_io_executor& executor) : executor_(executor)
{
}
void StreamControl::start(const std::string& stream_id, const ServerSettings& server_setttings, const OnNotification& notification_handler,
const OnRequest& request_handler, const OnLog& log_handler)
{
notification_handler_ = notification_handler;
request_handler_ = request_handler;
log_handler_ = log_handler;
doStart(stream_id, server_setttings);
}
void StreamControl::command(const jsonrpcpp::Request& request, const OnResponse& response_handler)
{
// use strand to serialize commands sent from different threads
boost::asio::post(executor_,
[this, request, response_handler]()
{
if (response_handler)
request_callbacks_[request.id()] = response_handler;
doCommand(request);
});
}
void StreamControl::onReceive(const std::string& json)
{
jsonrpcpp::entity_ptr entity(nullptr);
try
{
entity = jsonrpcpp::Parser::do_parse(json);
if (!entity)
{
LOG(ERROR, LOG_TAG) << "Failed to parse message\n";
}
else if (entity->is_notification())
{
jsonrpcpp::notification_ptr notification = dynamic_pointer_cast<jsonrpcpp::Notification>(entity);
notification_handler_(*notification);
}
else if (entity->is_request())
{
jsonrpcpp::request_ptr request = dynamic_pointer_cast<jsonrpcpp::Request>(entity);
request_handler_(*request);
}
else if (entity->is_response())
{
jsonrpcpp::response_ptr response = dynamic_pointer_cast<jsonrpcpp::Response>(entity);
LOG(INFO, LOG_TAG) << "Response: " << response->to_json() << ", id: " << response->id() << "\n";
// TODO: call request_callbacks_ on timeout with error
auto iter = request_callbacks_.find(response->id());
if (iter != request_callbacks_.end())
{
iter->second(*response);
request_callbacks_.erase(iter);
}
else
{
LOG(WARNING, LOG_TAG) << "No request found for response with id: " << response->id() << "\n";
}
}
else
{
LOG(WARNING, LOG_TAG) << "Not handling message: " << json << "\n";
}
}
catch (const jsonrpcpp::ParseErrorException& e)
{
LOG(ERROR, LOG_TAG) << "Failed to parse message: " << e.what() << "\n";
}
catch (const std::exception& e)
{
LOG(ERROR, LOG_TAG) << "Failed to parse message: " << e.what() << "\n";
}
}
void StreamControl::onLog(std::string message)
{
log_handler_(std::move(message));
}
ScriptStreamControl::ScriptStreamControl(const boost::asio::any_io_executor& executor, const std::string& script, const std::string& params)
: StreamControl(executor), script_(script), params_(params)
{
namespace fs = utils::file;
if (!fs::exists(script_))
{
std::string plugin_path = "/usr/share/snapserver/plug-ins/";
if (fs::exists(plugin_path + script_))
script_ = plugin_path + script_;
else
throw SnapException("Control script not found: \"" + script_ + "\"");
}
}
void ScriptStreamControl::doStart(const std::string& stream_id, const ServerSettings& server_setttings)
{
pipe_stderr_ = bp::pipe();
pipe_stdout_ = bp::pipe();
stringstream params;
params << " " << params_;
params << " \"--stream=" + stream_id + "\"";
if (server_setttings.http.enabled)
{
params << " --snapcast-port=" << server_setttings.http.port;
params << " --snapcast-host=" << server_setttings.http.host;
}
LOG(DEBUG, LOG_TAG) << "Starting control script: '" << script_ << "', params: '" << params.str() << "'\n";
try
{
process_ = bp::child(
script_ + params.str(), bp::std_out > pipe_stdout_, bp::std_err > pipe_stderr_, bp::std_in < in_,
bp::on_exit =
[](int exit, const std::error_code& ec_in)
{
auto severity = AixLog::Severity::debug;
if (exit != 0)
severity = AixLog::Severity::error;
LOG(severity, LOG_TAG) << "Exit code: " << exit << ", message: " << ec_in.message() << "\n";
});
}
catch (const std::exception& e)
{
throw SnapException("Failed to start control script: '" + script_ + "', exception: " + e.what());
}
stream_stdout_ = make_unique<boost::asio::posix::stream_descriptor>(executor_, pipe_stdout_.native_source());
stream_stderr_ = make_unique<boost::asio::posix::stream_descriptor>(executor_, pipe_stderr_.native_source());
stdoutReadLine();
stderrReadLine();
}
void ScriptStreamControl::doCommand(const jsonrpcpp::Request& request)
{
std::string msg = request.to_json().dump() + "\n";
LOG(INFO, LOG_TAG) << "Sending request: " << msg;
in_.write(msg.data(), msg.size());
in_.flush();
}
void ScriptStreamControl::stderrReadLine()
{
const std::string delimiter = "\n";
boost::asio::async_read_until(*stream_stderr_, streambuf_stderr_, delimiter,
[this, delimiter](const std::error_code& ec, std::size_t bytes_transferred)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while reading from stderr: " << ec.message() << "\n";
return;
}
// Extract up to the first delimiter.
std::string line{buffers_begin(streambuf_stderr_.data()), buffers_begin(streambuf_stderr_.data()) + bytes_transferred - delimiter.length()};
onLog(std::move(line));
streambuf_stderr_.consume(bytes_transferred);
stderrReadLine();
});
}
void ScriptStreamControl::stdoutReadLine()
{
const std::string delimiter = "\n";
boost::asio::async_read_until(*stream_stdout_, streambuf_stdout_, delimiter,
[this, delimiter](const std::error_code& ec, std::size_t bytes_transferred)
{
if (ec)
{
LOG(ERROR, LOG_TAG) << "Error while reading from stdout: " << ec.message() << "\n";
return;
}
// Extract up to the first delimiter.
std::string line{buffers_begin(streambuf_stdout_.data()), buffers_begin(streambuf_stdout_.data()) + bytes_transferred - delimiter.length()};
onReceive(line);
streambuf_stdout_.consume(bytes_transferred);
stdoutReadLine();
});
}
} // namespace streamreader
| 7,829
|
C++
|
.cpp
| 196
| 32.362245
| 148
| 0.612597
|
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,970
|
meta_stream.cpp
|
badaix_snapcast/server/streamreader/meta_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/>.
***/
// prototype/interface header file
#include "meta_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/utils/string_utils.hpp"
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "MetaStream";
// static constexpr auto kResyncTolerance = 50ms;
MetaStream::MetaStream(PcmStream::Listener* pcmListener, const std::vector<std::shared_ptr<PcmStream>>& streams, boost::asio::io_context& ioc,
const ServerSettings& server_settings, const StreamUri& uri)
: PcmStream(pcmListener, ioc, server_settings, uri), first_read_(true)
{
auto path_components = utils::string::split(uri.path, '/');
for (const auto& component : path_components)
{
if (component.empty())
continue;
bool found = false;
for (const auto& stream : streams)
{
if (stream->getName() == component)
{
streams_.push_back(stream);
stream->addListener(this);
found = true;
break;
}
}
if (!found)
throw SnapException("Unknown stream: \"" + component + "\"");
}
if (streams_.empty())
throw SnapException("Meta stream '" + getName() + "' must contain at least one stream");
active_stream_ = streams_.front();
resampler_ = make_unique<Resampler>(active_stream_->getSampleFormat(), sampleFormat_);
}
MetaStream::~MetaStream()
{
stop();
}
void MetaStream::start()
{
LOG(DEBUG, LOG_TAG) << "Start, sampleformat: " << sampleFormat_.toString() << "\n";
PcmStream::start();
}
void MetaStream::stop()
{
active_ = false;
}
void MetaStream::onPropertiesChanged(const PcmStream* pcmStream, const Properties& properties)
{
LOG(DEBUG, LOG_TAG) << "onPropertiesChanged: " << pcmStream->getName() << "\n";
// std::lock_guard<std::recursive_mutex> lock(mutex_);
if (pcmStream != active_stream_.get())
return;
setProperties(properties);
}
void MetaStream::onStateChanged(const PcmStream* pcmStream, ReaderState state)
{
LOG(DEBUG, LOG_TAG) << "onStateChanged: " << pcmStream->getName() << ", state: " << state << "\n";
std::lock_guard<std::recursive_mutex> lock(active_mutex_);
// Should a pause keep the stream active? E.g. Spotify can only pause, so it would never get inactive
// if (active_stream_->getProperties().playback_status == PlaybackStatus::kPaused)
// return;
auto switch_stream = [this](std::shared_ptr<PcmStream> new_stream)
{
if (new_stream == active_stream_)
return;
LOG(INFO, LOG_TAG) << "Stream: " << name_ << ", switching active stream: " << (active_stream_ ? active_stream_->getName() : "<null>") << " => "
<< new_stream->getName() << "\n";
active_stream_ = new_stream;
setProperties(active_stream_->getProperties());
resampler_ = make_unique<Resampler>(active_stream_->getSampleFormat(), sampleFormat_);
};
for (const auto& stream : streams_)
{
if (stream->getState() == ReaderState::kPlaying)
{
if (state_ != ReaderState::kPlaying) // || (active_stream_ != stream))
first_read_ = true;
if (active_stream_ != stream)
{
switch_stream(stream);
}
setState(ReaderState::kPlaying);
return;
}
}
switch_stream(streams_.front());
setState(ReaderState::kIdle);
}
void MetaStream::onChunkRead(const PcmStream* pcmStream, const msg::PcmChunk& chunk)
{
// LOG(TRACE, LOG_TAG) << "onChunkRead: " << pcmStream->getName() << ", duration: " << chunk.durationMs() << "\n";
// std::lock_guard<std::recursive_mutex> lock(mutex_);
std::lock_guard<std::recursive_mutex> lock(active_mutex_);
if (pcmStream != active_stream_.get())
return;
// active_stream_->sampleFormat_
// sampleFormat_
if (first_read_)
{
first_read_ = false;
LOG(INFO, LOG_TAG) << "first read, updating timestamp\n";
tvEncodedChunk_ = std::chrono::steady_clock::now() - chunk.duration<std::chrono::nanoseconds>();
next_tick_ = std::chrono::steady_clock::now();
}
next_tick_ += chunk.duration<std::chrono::nanoseconds>();
auto currentTick = std::chrono::steady_clock::now();
auto next_read = next_tick_ - currentTick;
// Read took longer, wait for the buffer to fill up
if (next_read < 0ms)
{
// if (next_read >= -kResyncTolerance)
// {
// LOG(INFO, LOG_TAG) << "next read < 0 (" << getName() << "): " << std::chrono::duration_cast<std::chrono::microseconds>(next_read).count() / 1000.
// << " ms\n";
// }
// else
// {
resync(-next_read);
first_read_ = true;
// }
}
if (resampler_ && resampler_->resamplingNeeded())
{
auto resampled_chunk = resampler_->resample(chunk);
if (resampled_chunk)
chunkRead(*resampled_chunk);
}
else
chunkRead(chunk);
}
void MetaStream::onChunkEncoded(const PcmStream* pcmStream, std::shared_ptr<msg::PcmChunk> chunk, double duration)
{
std::ignore = pcmStream;
std::ignore = chunk;
std::ignore = duration;
// LOG(TRACE, LOG_TAG) << "onChunkEncoded: " << pcmStream->getName() << ", duration: " << duration << "\n";
// chunkEncoded(*encoder_, chunk, duration);
}
void MetaStream::onResync(const PcmStream* pcmStream, double ms)
{
LOG(DEBUG, LOG_TAG) << "onResync: " << pcmStream->getName() << ", duration: " << ms << " ms\n";
// std::lock_guard<std::recursive_mutex> lock(mutex_);
if (pcmStream != active_stream_.get())
return;
resync(std::chrono::nanoseconds(static_cast<int64_t>(ms * 1000000)));
}
// Setter for properties
void MetaStream::setShuffle(bool shuffle, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setShuffle(shuffle, std::move(handler));
}
void MetaStream::setLoopStatus(LoopStatus status, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setLoopStatus(status, std::move(handler));
}
void MetaStream::setVolume(uint16_t volume, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setVolume(volume, std::move(handler));
}
void MetaStream::setMute(bool mute, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setMute(mute, std::move(handler));
}
void MetaStream::setRate(float rate, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setRate(rate, std::move(handler));
}
// Control commands
void MetaStream::setPosition(std::chrono::milliseconds position, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->setPosition(position, std::move(handler));
}
void MetaStream::seek(std::chrono::milliseconds offset, ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->seek(offset, std::move(handler));
}
void MetaStream::next(ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->next(std::move(handler));
}
void MetaStream::previous(ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->previous(std::move(handler));
}
void MetaStream::pause(ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->pause(std::move(handler));
}
void MetaStream::playPause(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "PlayPause\n";
std::lock_guard<std::recursive_mutex> lock(mutex_);
if (active_stream_->getState() == ReaderState::kIdle)
play(handler);
else
active_stream_->playPause(std::move(handler));
}
void MetaStream::stop(ResultHandler handler)
{
std::lock_guard<std::recursive_mutex> lock(mutex_);
active_stream_->stop(std::move(handler));
}
void MetaStream::play(ResultHandler handler)
{
LOG(DEBUG, LOG_TAG) << "Play\n";
std::lock_guard<std::recursive_mutex> lock(mutex_);
if ((active_stream_->getProperties().can_play) && (active_stream_->getProperties().playback_status != PlaybackStatus::kPlaying))
return active_stream_->play(std::move(handler));
for (const auto& stream : streams_)
{
if ((stream->getState() == ReaderState::kIdle) && (stream->getProperties().can_play))
{
return stream->play(std::move(handler));
}
}
// call play on the active stream to get the handler called
active_stream_->play(std::move(handler));
}
} // namespace streamreader
| 9,622
|
C++
|
.cpp
| 249
| 33.148594
| 160
| 0.651095
|
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,971
|
pipe_stream.cpp
|
badaix_snapcast/server/streamreader/pipe_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/>.
***/
// prototype/interface header file
#include "pipe_stream.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
// standard headers
#include <cerrno>
#include <memory>
using namespace std;
namespace streamreader
{
static constexpr auto LOG_TAG = "PipeStream";
PipeStream::PipeStream(PcmStream::Listener* pcmListener, boost::asio::io_context& ioc, const ServerSettings& server_settings, const StreamUri& uri)
: AsioStream<stream_descriptor>(pcmListener, ioc, server_settings, uri)
{
umask(0);
string mode = uri_.getQuery("mode", "create");
LOG(INFO, LOG_TAG) << "PipeStream mode: " << mode << "\n";
if ((mode != "read") && (mode != "create"))
throw SnapException(R"(create mode for fifo must be "read" or "create")");
if (mode == "create")
{
if ((mkfifo(uri_.path.c_str(), 0666) != 0) && (errno != EEXIST))
throw SnapException("failed to make fifo \"" + uri_.path + "\": " + cpt::to_string(errno));
}
}
void PipeStream::connect()
{
int fd = open(uri_.path.c_str(), O_RDONLY | O_NONBLOCK);
if (fd < 0)
throw SnapException("failed to open fifo \"" + uri_.path + "\": " + cpt::to_string(errno));
int pipe_size = -1;
#if !defined(MACOS) && !defined(FREEBSD)
pipe_size = fcntl(fd, F_GETPIPE_SZ);
#endif
LOG(TRACE, LOG_TAG) << "Stream: " << name_ << ", connect to pipe: " << uri_.path << ", fd: " << fd << ", pipe size: " << pipe_size << "\n";
stream_ = std::make_unique<boost::asio::posix::stream_descriptor>(strand_, fd);
on_connect();
}
} // namespace streamreader
| 2,378
|
C++
|
.cpp
| 55
| 39.290909
| 147
| 0.674187
|
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,972
|
publish_bonjour.cpp
|
badaix_snapcast/server/publishZeroConf/publish_bonjour.cpp
|
/***
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/>.
***/
// prototype/interface header file
#include "publish_bonjour.hpp"
// local headers
#include "common/aixlog.hpp"
// 3rd party headers
// standard headers
#include <cstdlib>
static constexpr auto LOG_TAG = "Bonjour";
typedef union
{
unsigned char b[2];
unsigned short NotAnInteger;
} Opaque16;
PublishBonjour::PublishBonjour(const std::string& serviceName, boost::asio::io_context& ioc) : PublishmDNS(serviceName, ioc), active_(false)
{
/// dns-sd -R Snapcast _snapcast._tcp local 1704
/// dns-sd -R Snapcast _snapcast-jsonrpc._tcp local 1705
}
PublishBonjour::~PublishBonjour()
{
active_ = false;
pollThread_.join();
for (auto client : clients)
{
if (client)
DNSServiceRefDeallocate(client);
}
}
void PublishBonjour::worker()
{
// int dns_sd_fd = client ? DNSServiceRefSockFD(client) : -1;
// 1. Set up the fd_set as usual here.
// This example client has no file descriptors of its own,
// but a real application would call FD_SET to add them to the set here
fd_set readfds;
FD_ZERO(&readfds);
std::vector<int> dns_sd_fds;
int nfds = -1;
for (size_t n = 0; n < clients.size(); ++n)
{
int dns_sd_fd = DNSServiceRefSockFD(clients[n]);
dns_sd_fds.push_back(dns_sd_fd);
if (nfds < dns_sd_fd)
nfds = dns_sd_fd;
// 2. Add the fd for our client(s) to the fd_set
FD_SET(dns_sd_fd, &readfds);
}
++nfds;
// 3. Set up the timeout.
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 100 * 1000;
active_ = true;
while (active_)
{
FD_ZERO(&readfds);
for (size_t n = 0; n < dns_sd_fds.size(); ++n)
FD_SET(dns_sd_fds[n], &readfds);
int result = select(nfds, &readfds, (fd_set*)NULL, (fd_set*)NULL, &tv);
if (result > 0)
{
for (size_t n = 0; n < dns_sd_fds.size(); ++n)
{
if (clients[n] && FD_ISSET(dns_sd_fds[n], &readfds))
{
DNSServiceErrorType err = DNSServiceProcessResult(clients[n]);
if (err)
{
LOG(ERROR, LOG_TAG) << "DNSServiceProcessResult returned " << err << "\n";
active_ = false;
}
}
}
}
// else if (result == 0)
// myTimerCallBack();
else if (result < 0)
{
LOG(ERROR, LOG_TAG) << "select() returned " << result << " errno " << errno << " " << strerror(errno) << "\n";
if (errno != EINTR)
active_ = false;
}
}
}
static void DNSSD_API reg_reply(DNSServiceRef sdref, const DNSServiceFlags flags, DNSServiceErrorType errorCode, const char* name, const char* regtype,
const char* domain, void* context)
{
(void)sdref; // Unused
(void)flags; // Unused
PublishBonjour* publishBonjour = (PublishBonjour*)context;
(void)publishBonjour; // unused
LOG(INFO, LOG_TAG) << "Got a reply for service " << name << "." << regtype << domain << "\n";
if (errorCode == kDNSServiceErr_NoError)
{
if (flags & kDNSServiceFlagsAdd)
LOG(INFO, LOG_TAG) << "Name now registered and active\n";
else
LOG(INFO, LOG_TAG) << "Name registration removed\n";
}
else if (errorCode == kDNSServiceErr_NameConflict)
{
/// TODO: Error handling
LOG(INFO, LOG_TAG) << "Name in use, please choose another\n";
exit(-1);
}
else
LOG(INFO, LOG_TAG) << "Error " << errorCode << "\n";
if (!(flags & kDNSServiceFlagsMoreComing))
fflush(stdout);
}
void PublishBonjour::publish(const std::vector<mDNSService>& services)
{
for (auto service : services)
{
DNSServiceFlags flags = 0;
Opaque16 registerPort = {{static_cast<unsigned char>(service.port_ >> 8), static_cast<unsigned char>(service.port_ & 0xFF)}};
DNSServiceRef client = NULL;
// DNSServiceRegister(&client, flags, kDNSServiceInterfaceIndexAny, serviceName_.c_str(), service.name_.c_str(), NULL, NULL, registerPort.NotAnInteger,
// service.txt_.size(), service.txt_.empty()?NULL:service.txt_.c_str(), reg_reply, this);
DNSServiceRegister(&client, flags, kDNSServiceInterfaceIndexAny, serviceName_.c_str(), service.name_.c_str(), NULL, NULL, registerPort.NotAnInteger, 0,
NULL, reg_reply, this);
clients.push_back(client);
}
pollThread_ = std::thread(&PublishBonjour::worker, this);
}
| 5,361
|
C++
|
.cpp
| 139
| 31.223022
| 159
| 0.609709
|
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,973
|
publish_avahi.cpp
|
badaix_snapcast/server/publishZeroConf/publish_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 "publish_avahi.hpp"
// local headers
#include "common/aixlog.hpp"
// 3rd party headers
// standard headers
static constexpr auto LOG_TAG = "Avahi";
static AvahiEntryGroup* group;
static AvahiSimplePoll* simple_poll;
static char* name;
PublishAvahi::PublishAvahi(const std::string& serviceName, boost::asio::io_context& ioc) : PublishmDNS(serviceName, ioc), client_(nullptr), timer_(ioc)
{
group = nullptr;
simple_poll = nullptr;
name = avahi_strdup(serviceName_.c_str());
}
void PublishAvahi::publish(const std::vector<mDNSService>& services)
{
services_ = services;
/// Allocate main loop object
if ((simple_poll = avahi_simple_poll_new()) == nullptr)
{
/// TODO: error handling
LOG(ERROR, LOG_TAG) << "Failed to create simple poll object.\n";
}
/// Allocate a new client
int error;
client_ = avahi_client_new(avahi_simple_poll_get(simple_poll), AVAHI_CLIENT_IGNORE_USER_CONFIG, client_callback, this, &error);
/// Check wether creating the client object succeeded
if (client_ == nullptr)
{
LOG(ERROR, LOG_TAG) << "Failed to create client: " << avahi_strerror(error) << "\n";
}
poll();
}
void PublishAvahi::poll()
{
timer_.expires_after(std::chrono::milliseconds(50));
timer_.async_wait(
[this](const boost::system::error_code& ec)
{
if (!ec && (avahi_simple_poll_iterate(simple_poll, 0) == 0))
poll();
});
}
PublishAvahi::~PublishAvahi()
{
timer_.cancel();
if (client_ != nullptr)
avahi_client_free(client_);
if (simple_poll != nullptr)
avahi_simple_poll_free(simple_poll);
avahi_free(name);
}
void PublishAvahi::entry_group_callback(AvahiEntryGroup* g, AvahiEntryGroupState state, AVAHI_GCC_UNUSED void* userdata)
{
assert(g == group || group == nullptr);
group = g;
/// Called whenever the entry group state changes
switch (state)
{
case AVAHI_ENTRY_GROUP_ESTABLISHED:
/// The entry group has been established successfully
LOG(INFO, LOG_TAG) << "Service '" << name << "' successfully established.\n";
break;
case AVAHI_ENTRY_GROUP_COLLISION:
{
char* n;
/// A service name collision with a remote service happened. Let's pick a new name
n = avahi_alternative_service_name(name);
avahi_free(name);
name = n;
LOG(NOTICE, LOG_TAG) << "Service name collision, renaming service to '" << name << "'\n";
/// And recreate the services
static_cast<PublishAvahi*>(userdata)->create_services(avahi_entry_group_get_client(g));
break;
}
case AVAHI_ENTRY_GROUP_FAILURE:
LOG(ERROR, LOG_TAG) << "Entry group failure: " << avahi_strerror(avahi_client_errno(avahi_entry_group_get_client(g))) << "\n";
/// Some kind of failure happened while we were registering our services
avahi_simple_poll_quit(simple_poll);
break;
case AVAHI_ENTRY_GROUP_UNCOMMITED:
case AVAHI_ENTRY_GROUP_REGISTERING:;
}
}
void PublishAvahi::create_services(AvahiClient* c)
{
assert(c);
char* n;
/// If this is the first time we're called, let's create a new entry group if necessary
if (group == nullptr)
{
if ((group = avahi_entry_group_new(c, entry_group_callback, this)) == nullptr)
{
LOG(ERROR, LOG_TAG) << "avahi_entry_group_new() failed: " << avahi_strerror(avahi_client_errno(c)) << "\n";
goto fail;
}
}
/// If the group is empty (either because it was just created, or because it was reset previously, add our entries.
int ret;
if (avahi_entry_group_is_empty(group) != 0)
{
LOG(INFO, LOG_TAG) << "Adding service '" << name << "'\n";
/// We will now add two services and one subtype to the entry group
for (const auto& service : services_)
{
if ((ret = avahi_entry_group_add_service(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, AvahiPublishFlags(0), name, service.name_.c_str(), nullptr,
nullptr, service.port_, static_cast<char*>(nullptr))) < 0)
{
if (ret == AVAHI_ERR_COLLISION)
goto collision;
LOG(ERROR, LOG_TAG) << "Failed to add " << service.name_ << " service: " << avahi_strerror(ret) << "\n";
goto fail;
}
}
/// Add an additional (hypothetic) subtype
/* if ((ret = avahi_entry_group_add_service_subtype(group, AVAHI_IF_UNSPEC, AVAHI_PROTO_UNSPEC, AvahiPublishFlags(0), name,
"_printer._tcp",
NULL, "_magic._sub._printer._tcp") < 0))
{
fprintf(stderr, "Failed to add subtype _magic._sub._printer._tcp: %s\n", avahi_strerror(ret));
goto fail;
}
*/
/// Tell the server to register the service
if ((ret = avahi_entry_group_commit(group)) < 0)
{
LOG(ERROR, LOG_TAG) << "Failed to commit entry group: " << avahi_strerror(ret) << "\n";
goto fail;
}
}
return;
collision:
/// A service name collision with a local service happened. Let's pick a new name
n = avahi_alternative_service_name(name);
avahi_free(name);
name = n;
LOG(INFO, LOG_TAG) << "Service name collision, renaming service to '" << name << "'\n";
avahi_entry_group_reset(group);
create_services(c);
return;
fail:
avahi_simple_poll_quit(simple_poll);
}
void PublishAvahi::client_callback(AvahiClient* c, AvahiClientState state, AVAHI_GCC_UNUSED void* userdata)
{
assert(c);
/// Called whenever the client or server state changes
switch (state)
{
case AVAHI_CLIENT_S_RUNNING:
/// The server has startup successfully and registered its host name on the network, so it's time to create our services
static_cast<PublishAvahi*>(userdata)->create_services(c);
break;
case AVAHI_CLIENT_FAILURE:
LOG(ERROR, LOG_TAG) << "Client failure: " << avahi_strerror(avahi_client_errno(c)) << "\n";
avahi_simple_poll_quit(simple_poll);
break;
case AVAHI_CLIENT_S_COLLISION:
/// Let's drop our registered services. When the server is back
/// in AVAHI_SERVER_RUNNING state we will register them again with the new host name.
case AVAHI_CLIENT_S_REGISTERING:
/// The server records are now being established. This might be caused by a host name change. We need to wait
/// for our own records to register until the host name is properly esatblished.
if (group != nullptr)
avahi_entry_group_reset(group);
break;
case AVAHI_CLIENT_CONNECTING:;
}
}
| 7,796
|
C++
|
.cpp
| 185
| 34.054054
| 156
| 0.621772
|
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,974
|
ogg_encoder.cpp
|
badaix_snapcast/server/encoder/ogg_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 "ogg_encoder.hpp"
// local headers
#include "common/aixlog.hpp"
#include "common/snap_exception.hpp"
#include "common/str_compat.hpp"
#include "common/utils/string_utils.hpp"
// standard headers
#include <cstring>
#include <iostream>
using namespace std;
namespace encoder
{
static constexpr auto LOG_TAG = "OggEnc";
OggEncoder::OggEncoder(const std::string& codecOptions) : Encoder(codecOptions), lastGranulepos_(0)
{
}
OggEncoder::~OggEncoder()
{
ogg_stream_clear(&os_);
vorbis_block_clear(&vb_);
vorbis_dsp_clear(&vd_);
vorbis_comment_clear(&vc_);
vorbis_info_clear(&vi_);
}
std::string OggEncoder::getAvailableOptions() const
{
return "VBR:[-0.1 - 1.0]";
}
std::string OggEncoder::getDefaultOptions() const
{
return "VBR:0.9";
}
std::string OggEncoder::name() const
{
return "ogg";
}
void OggEncoder::encode(const msg::PcmChunk& chunk)
{
double res = 0;
// LOG(TRACE, LOG_TAG) << "payload: " << chunk->payloadSize << "\tframes: " << chunk->getFrameCount() << "\tduration: " <<
// chunk->duration<chronos::msec>().count()
// << "\n";
int frames = chunk.getFrameCount();
float** buffer = vorbis_analysis_buffer(&vd_, frames);
/* uninterleave samples */
for (size_t channel = 0; channel < sampleFormat_.channels(); ++channel)
{
if (sampleFormat_.sampleSize() == 1)
{
auto* chunkBuffer = reinterpret_cast<int8_t*>(chunk.payload);
for (int i = 0; i < frames; i++)
buffer[channel][i] = chunkBuffer[sampleFormat_.channels() * i + channel] / 128.f;
}
else if (sampleFormat_.sampleSize() == 2)
{
auto* chunkBuffer = reinterpret_cast<int16_t*>(chunk.payload);
for (int i = 0; i < frames; i++)
buffer[channel][i] = chunkBuffer[sampleFormat_.channels() * i + channel] / 32768.f;
}
else if (sampleFormat_.sampleSize() == 4)
{
auto* chunkBuffer = reinterpret_cast<int32_t*>(chunk.payload);
for (int i = 0; i < frames; i++)
buffer[channel][i] = chunkBuffer[sampleFormat_.channels() * i + channel] / 2147483648.f;
}
}
/* tell the library how much we actually submitted */
vorbis_analysis_wrote(&vd_, frames);
auto oggChunk = make_shared<msg::PcmChunk>(chunk.format, 0);
/* vorbis does some data preanalysis, then divvies up blocks for
more involved (potentially parallel) processing. Get a single
block for encoding now */
size_t pos = 0;
while (vorbis_analysis_blockout(&vd_, &vb_) == 1)
{
/* analysis, assume we want to use bitrate management */
vorbis_analysis(&vb_, nullptr);
vorbis_bitrate_addblock(&vb_);
while (vorbis_bitrate_flushpacket(&vd_, &op_) != 0)
{
/* weld the packet into the bitstream */
ogg_stream_packetin(&os_, &op_);
/* write out pages (if any) */
while (true)
{
int result = ogg_stream_flush(&os_, &og_);
if (result == 0)
break;
res = os_.granulepos - lastGranulepos_;
size_t nextLen = pos + og_.header_len + og_.body_len;
// make chunk larger
if (oggChunk->payloadSize < nextLen)
oggChunk->payload = static_cast<char*>(realloc(oggChunk->payload, nextLen));
memcpy(oggChunk->payload + pos, og_.header, og_.header_len);
pos += og_.header_len;
memcpy(oggChunk->payload + pos, og_.body, og_.body_len);
pos += og_.body_len;
if (ogg_page_eos(&og_) != 0)
break;
}
}
}
if (res > 0)
{
res /= sampleFormat_.msRate();
// LOG(INFO, LOG_TAG) << "res: " << res << "\n";
lastGranulepos_ = os_.granulepos;
// make oggChunk smaller
oggChunk->payload = static_cast<char*>(realloc(oggChunk->payload, pos));
oggChunk->payloadSize = pos;
encoded_callback_(*this, oggChunk, res);
}
}
void OggEncoder::initEncoder()
{
if (codecOptions_.find(':') == string::npos)
throw SnapException("Invalid codec options: \"" + codecOptions_ + "\"");
string mode = utils::string::trim_copy(codecOptions_.substr(0, codecOptions_.find(':')));
if (mode != "VBR")
throw SnapException("Unsupported codec mode: \"" + mode + R"(". Available: "VBR")");
string qual = utils::string::trim_copy(codecOptions_.substr(codecOptions_.find(':') + 1));
double quality = 1.0;
try
{
quality = cpt::stod(qual);
}
catch (...)
{
throw SnapException("Invalid codec option: \"" + codecOptions_ + "\"");
}
if ((quality < -0.1) || (quality > 1.0))
{
throw SnapException("compression level has to be between -0.1 and 1.0");
}
LOG(INFO, LOG_TAG) << "Init - quality: " << quality << "\n";
/********** Encode setup ************/
vorbis_info_init(&vi_);
/* choose an encoding mode. A few possibilities commented out, one
actually used: */
/*********************************************************************
Encoding using a VBR quality mode. The usable range is -.1
(lowest quality, smallest file) to 1. (highest quality, largest file).
Example quality mode .4: 44kHz stereo coupled, roughly 128kbps VBR
ret = vorbis_encode_init_vbr(&vi,2,44100,.4);
---------------------------------------------------------------------
Encoding using an average bitrate mode (ABR).
example: 44kHz stereo coupled, average 128kbps VBR
ret = vorbis_encode_init(&vi,2,44100,-1,128000,-1);
---------------------------------------------------------------------
Encode using a quality mode, but select that quality mode by asking for
an approximate bitrate. This is not ABR, it is true VBR, but selected
using the bitrate interface, and then turning bitrate management off:
ret = ( vorbis_encode_setup_managed(&vi,2,44100,-1,128000,-1) ||
vorbis_encode_ctl(&vi,OV_ECTL_RATEMANAGE2_SET,NULL) ||
vorbis_encode_setup_init(&vi));
*********************************************************************/
int ret = vorbis_encode_init_vbr(&vi_, sampleFormat_.channels(), sampleFormat_.rate(), quality);
/* do not continue if setup failed; this can happen if we ask for a
mode that libVorbis does not support (eg, too low a bitrate, etc,
will return 'OV_EIMPL') */
if (ret != 0)
throw SnapException("failed to init encoder");
/* add a comment */
vorbis_comment_init(&vc_);
vorbis_comment_add_tag(&vc_, "TITLE", "SnapStream");
vorbis_comment_add_tag(&vc_, "VERSION", VERSION);
vorbis_comment_add_tag(&vc_, "SAMPLE_FORMAT", sampleFormat_.toString().c_str());
/* set up the analysis state and auxiliary encoding storage */
vorbis_analysis_init(&vd_, &vi_);
vorbis_block_init(&vd_, &vb_);
/* set up our packet->stream encoder */
/* pick a random serial number; that way we can more likely build
chained streams just by concatenation */
srand(time(nullptr));
ogg_stream_init(&os_, rand());
/* Vorbis streams begin with three headers; the initial header (with
most of the codec setup parameters) which is mandated by the Ogg
bitstream spec. The second header holds any comment fields. The
third header holds the bitstream codebook. We merely need to
make the headers, then pass them to libvorbis one at a time;
libvorbis handles the additional Ogg bitstream constraints */
ogg_packet header;
ogg_packet header_comm;
ogg_packet header_code;
vorbis_analysis_headerout(&vd_, &vc_, &header, &header_comm, &header_code);
ogg_stream_packetin(&os_, &header);
ogg_stream_packetin(&os_, &header_comm);
ogg_stream_packetin(&os_, &header_code);
/* This ensures the actual
* audio data will start on a new page, as per spec
*/
size_t pos(0);
headerChunk_.reset(new msg::CodecHeader("ogg"));
while (true)
{
int result = ogg_stream_flush(&os_, &og_);
if (result == 0)
break;
headerChunk_->payloadSize += og_.header_len + og_.body_len;
headerChunk_->payload = static_cast<char*>(realloc(headerChunk_->payload, headerChunk_->payloadSize));
LOG(DEBUG, LOG_TAG) << "HeadLen: " << og_.header_len << ", bodyLen: " << og_.body_len << ", result: " << result << "\n";
memcpy(headerChunk_->payload + pos, og_.header, og_.header_len);
pos += og_.header_len;
memcpy(headerChunk_->payload + pos, og_.body, og_.body_len);
pos += og_.body_len;
}
}
} // namespace encoder
| 9,587
|
C++
|
.cpp
| 223
| 36.170404
| 128
| 0.604921
|
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.