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,610
loudness.cpp
wwmm_easyeffects/src/loudness.cpp
/* * 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/>. */ #include "loudness.hpp" #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Loudness::Loudness(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::loudness, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/loud_comp_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/loud_comp_stereo is not installed"); } lv2_wrapper->bind_key_enum<"std", "std">(settings); lv2_wrapper->bind_key_enum<"fft", "fft">(settings); lv2_wrapper->bind_key_double<"volume", "volume">(settings); lv2_wrapper->bind_key_bool<"hclip", "clipping">(settings); lv2_wrapper->bind_key_double<"hcrange", "clipping-range">(settings); setup_input_output_gain(); } Loudness::~Loudness() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Loudness::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Loudness::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto Loudness::get_latency_seconds() -> float { return latency_value; }
3,891
C++
.cpp
111
29.792793
101
0.643372
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,611
echo_canceller_ui.cpp
wwmm_easyeffects/src/echo_canceller_ui.cpp
/* * 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/>. */ #include "echo_canceller_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "echo_canceller.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::echo_canceller_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<EchoCanceller> echo_canceller; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _EchoCancellerBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *filter_length, *residual_echo_suppression, *near_end_suppression; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(EchoCancellerBox, echo_canceller_box, GTK_TYPE_BOX) void on_reset(EchoCancellerBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(EchoCancellerBox* self, std::shared_ptr<EchoCanceller> echo_canceller, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->echo_canceller = echo_canceller; self->settings = g_settings_new_with_path(tags::schema::echo_canceller::id, schema_path.c_str()); echo_canceller->set_post_messages(true); self->data->connections.push_back(echo_canceller->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(echo_canceller->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->echo_canceller->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain", "filter-length", "residual-echo-suppression", "near-end-suppression">(self->settings, self->input_gain, self->output_gain, self->filter_length, self->residual_echo_suppression, self->near_end_suppression); } void dispose(GObject* object) { auto* self = EE_ECHO_CANCELLER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(echo_canceller_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_ECHO_CANCELLER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(echo_canceller_box_parent_class)->finalize(object); } void echo_canceller_box_class_init(EchoCancellerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::echo_canceller_ui); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, input_gain); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, output_gain); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, filter_length); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, residual_echo_suppression); gtk_widget_class_bind_template_child(widget_class, EchoCancellerBox, near_end_suppression); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void echo_canceller_box_init(EchoCancellerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"ms">(self->filter_length); prepare_spinbuttons<"dB">(self->residual_echo_suppression, self->near_end_suppression); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> EchoCancellerBox* { return static_cast<EchoCancellerBox*>(g_object_new(EE_TYPE_ECHO_CANCELLER_BOX, nullptr)); } } // namespace ui::echo_canceller_box
7,033
C++
.cpp
152
41.585526
115
0.716923
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,612
filter_preset.cpp
wwmm_easyeffects/src/filter_preset.cpp
/* * 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/>. */ #include "filter_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" FilterPreset::FilterPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::filter::id, tags::schema::filter::input_path, tags::schema::filter::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::filter).append("#").append(util::to_string(index)); } void FilterPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["frequency"] = g_settings_get_double(settings, "frequency"); json[section][instance_name]["width"] = g_settings_get_double(settings, "width"); json[section][instance_name]["gain"] = g_settings_get_double(settings, "gain"); json[section][instance_name]["quality"] = g_settings_get_double(settings, "quality"); json[section][instance_name]["balance"] = g_settings_get_double(settings, "balance"); json[section][instance_name]["type"] = util::gsettings_get_string(settings, "type"); json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["equal-mode"] = util::gsettings_get_string(settings, "equal-mode"); json[section][instance_name]["slope"] = util::gsettings_get_string(settings, "slope"); } void FilterPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "frequency", "frequency"); update_key<double>(json.at(section).at(instance_name), settings, "width", "width"); update_key<double>(json.at(section).at(instance_name), settings, "gain", "gain"); update_key<double>(json.at(section).at(instance_name), settings, "quality", "quality"); update_key<double>(json.at(section).at(instance_name), settings, "balance", "balance"); update_key<gchar*>(json.at(section).at(instance_name), settings, "type", "type"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<gchar*>(json.at(section).at(instance_name), settings, "equal-mode", "equal-mode"); update_key<gchar*>(json.at(section).at(instance_name), settings, "slope", "slope"); }
3,675
C++
.cpp
63
54.333333
98
0.709147
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,613
compressor_ui.cpp
wwmm_easyeffects/src/compressor_ui.cpp
/* * 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/>. */ #include "compressor_ui.hpp" #include <STTypes.h> #include <fmt/core.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "compressor.hpp" #include "node_info_holder.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::compressor_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Compressor> compressor; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _CompressorBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkLabel *gain_label, *sidechain_label, *curve_label, *envelope_label; GtkSpinButton *attack, *release, *release_threshold, *threshold, *knee, *ratio, *makeup, *dry, *wet, *boost_threshold, *boost_amount, *preamp, *reactivity, *lookahead, *hpf_freq, *lpf_freq; GtkToggleButton *listen, *show_native_ui; GtkCheckButton* stereo_split; GtkDropDown *compression_mode, *sidechain_type, *sidechain_mode, *sidechain_source, *stereo_split_source, *lpf_mode, *hpf_mode, *dropdown_input_devices; GListStore* input_devices_model; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(CompressorBox, compressor_box, GTK_TYPE_BOX) void on_reset(CompressorBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(CompressorBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->compressor->show_native_ui(); } else { self->data->compressor->close_native_ui(); } } auto set_device_sensitive(CompressorBox* self, const guint selected_id) -> gboolean { // Sensitive on External Device selected return (selected_id == 2U) ? 1 : 0; } auto set_boost_threshold_sensitive(CompressorBox* self, const guint selected_id) -> gboolean { switch (selected_id) { case 0U: // Downward case 2U: // Boosting return 0; default: break; } return 1; } auto set_boost_amount_sensitive(CompressorBox* self, const guint selected_id) -> gboolean { switch (selected_id) { case 0U: // Downward case 1U: // Upward return 0; default: break; } return 1; } void setup_dropdown_input_device(CompressorBox* self) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(self->input_devices_model)); g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, CompressorBox* self) { if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->settings, "sidechain-input-device", holder->info->name.c_str()); } }), self); gtk_drop_down_set_model(self->dropdown_input_devices, G_LIST_MODEL(self->input_devices_model)); g_object_unref(selection); } void setup(CompressorBox* self, std::shared_ptr<Compressor> compressor, const std::string& schema_path, PipeManager* pm) { self->data->compressor = compressor; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::compressor::id, schema_path.c_str()); compressor->set_post_messages(true); setup_dropdown_input_device(self); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source || node.media_role == tags::pipewire::media_role::dsp) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); } } self->data->connections.push_back(compressor->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(compressor->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(compressor->reduction.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->gain_label)) { return; } gtk_label_set_text(self->gain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(compressor->envelope.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->envelope_label)) { return; } gtk_label_set_text(self->envelope_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(compressor->sidechain.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->sidechain_label)) { return; } gtk_label_set_text(self->sidechain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(compressor->curve.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->curve_label)) { return; } gtk_label_set_text(self->curve_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->compressor->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "dry", gtk_spin_button_get_adjustment(self->dry), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet", gtk_spin_button_get_adjustment(self->wet), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "attack", gtk_spin_button_get_adjustment(self->attack), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "knee", gtk_spin_button_get_adjustment(self->knee), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "makeup", gtk_spin_button_get_adjustment(self->makeup), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "ratio", gtk_spin_button_get_adjustment(self->ratio), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release", gtk_spin_button_get_adjustment(self->release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "threshold", gtk_spin_button_get_adjustment(self->threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-preamp", gtk_spin_button_get_adjustment(self->preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-reactivity", gtk_spin_button_get_adjustment(self->reactivity), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-lookahead", gtk_spin_button_get_adjustment(self->lookahead), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release-threshold", gtk_spin_button_get_adjustment(self->release_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "boost-threshold", gtk_spin_button_get_adjustment(self->boost_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "boost-amount", gtk_spin_button_get_adjustment(self->boost_amount), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hpf-frequency", gtk_spin_button_get_adjustment(self->hpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "lpf-frequency", gtk_spin_button_get_adjustment(self->lpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-listen", self->listen, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "stereo-split", self->stereo_split, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "mode", self->compression_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-type", self->sidechain_type); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-mode", self->sidechain_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-source", self->sidechain_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "stereo-split-source", self->stereo_split_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "hpf-mode", self->hpf_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "lpf-mode", self->lpf_mode); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); // bind source dropdowns sensitive property to split-stereo gsettings boolean g_settings_bind(self->settings, "stereo-split", self->sidechain_source, "sensitive", static_cast<GSettingsBindFlags>(G_SETTINGS_BIND_DEFAULT | G_SETTINGS_BIND_INVERT_BOOLEAN)); g_settings_bind(self->settings, "stereo-split", self->stereo_split_source, "sensitive", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_COMPRESSOR_BOX(object); self->data->compressor->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(compressor_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_COMPRESSOR_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(compressor_box_parent_class)->finalize(object); } void compressor_box_class_init(CompressorBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::compressor_ui); gtk_widget_class_bind_template_child(widget_class, CompressorBox, input_gain); gtk_widget_class_bind_template_child(widget_class, CompressorBox, output_gain); gtk_widget_class_bind_template_child(widget_class, CompressorBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, CompressorBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, CompressorBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, CompressorBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, CompressorBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, CompressorBox, gain_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, sidechain_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, curve_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, envelope_label); gtk_widget_class_bind_template_child(widget_class, CompressorBox, attack); gtk_widget_class_bind_template_child(widget_class, CompressorBox, release); gtk_widget_class_bind_template_child(widget_class, CompressorBox, release_threshold); gtk_widget_class_bind_template_child(widget_class, CompressorBox, threshold); gtk_widget_class_bind_template_child(widget_class, CompressorBox, knee); gtk_widget_class_bind_template_child(widget_class, CompressorBox, ratio); gtk_widget_class_bind_template_child(widget_class, CompressorBox, makeup); gtk_widget_class_bind_template_child(widget_class, CompressorBox, dry); gtk_widget_class_bind_template_child(widget_class, CompressorBox, wet); gtk_widget_class_bind_template_child(widget_class, CompressorBox, boost_threshold); gtk_widget_class_bind_template_child(widget_class, CompressorBox, boost_amount); gtk_widget_class_bind_template_child(widget_class, CompressorBox, preamp); gtk_widget_class_bind_template_child(widget_class, CompressorBox, reactivity); gtk_widget_class_bind_template_child(widget_class, CompressorBox, lookahead); gtk_widget_class_bind_template_child(widget_class, CompressorBox, hpf_freq); gtk_widget_class_bind_template_child(widget_class, CompressorBox, lpf_freq); gtk_widget_class_bind_template_child(widget_class, CompressorBox, compression_mode); gtk_widget_class_bind_template_child(widget_class, CompressorBox, sidechain_type); gtk_widget_class_bind_template_child(widget_class, CompressorBox, sidechain_mode); gtk_widget_class_bind_template_child(widget_class, CompressorBox, sidechain_source); gtk_widget_class_bind_template_child(widget_class, CompressorBox, stereo_split_source); gtk_widget_class_bind_template_child(widget_class, CompressorBox, stereo_split); gtk_widget_class_bind_template_child(widget_class, CompressorBox, lpf_mode); gtk_widget_class_bind_template_child(widget_class, CompressorBox, hpf_mode); gtk_widget_class_bind_template_child(widget_class, CompressorBox, listen); gtk_widget_class_bind_template_child(widget_class, CompressorBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, CompressorBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); gtk_widget_class_bind_template_callback(widget_class, set_device_sensitive); gtk_widget_class_bind_template_callback(widget_class, set_boost_threshold_sensitive); gtk_widget_class_bind_template_callback(widget_class, set_boost_amount_sensitive); } void compressor_box_init(CompressorBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); prepare_spinbuttons<"dB">(self->threshold, self->boost_threshold, self->boost_amount, self->knee, self->makeup, self->preamp); prepare_spinbuttons<"Hz">(self->hpf_freq, self->lpf_freq); prepare_spinbuttons<"ms">(self->attack, self->release, self->lookahead, self->reactivity); prepare_spinbuttons<"">(self->ratio); prepare_scales<"dB">(self->input_gain, self->output_gain); // The following spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->release_threshold, self->dry, self->wet); } auto create() -> CompressorBox* { return static_cast<CompressorBox*>(g_object_new(EE_TYPE_COMPRESSOR_BOX, nullptr)); } } // namespace ui::compressor_box
19,587
C++
.cpp
388
44.675258
120
0.693357
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,614
exciter_preset.cpp
wwmm_easyeffects/src/exciter_preset.cpp
/* * 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/>. */ #include "exciter_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" ExciterPreset::ExciterPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::exciter::id, tags::schema::exciter::input_path, tags::schema::exciter::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::exciter).append("#").append(util::to_string(index)); } void ExciterPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["amount"] = g_settings_get_double(settings, "amount"); json[section][instance_name]["harmonics"] = g_settings_get_double(settings, "harmonics"); json[section][instance_name]["scope"] = g_settings_get_double(settings, "scope"); json[section][instance_name]["ceil"] = g_settings_get_double(settings, "ceil"); json[section][instance_name]["blend"] = g_settings_get_double(settings, "blend"); json[section][instance_name]["ceil-active"] = g_settings_get_boolean(settings, "ceil-active") != 0; } void ExciterPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "amount", "amount"); update_key<double>(json.at(section).at(instance_name), settings, "harmonics", "harmonics"); update_key<double>(json.at(section).at(instance_name), settings, "scope", "scope"); update_key<double>(json.at(section).at(instance_name), settings, "ceil", "ceil"); update_key<double>(json.at(section).at(instance_name), settings, "blend", "blend"); update_key<bool>(json.at(section).at(instance_name), settings, "ceil-active", "ceil-active"); }
3,134
C++
.cpp
56
51.910714
101
0.709941
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,615
bass_loudness_preset.cpp
wwmm_easyeffects/src/bass_loudness_preset.cpp
/* * 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/>. */ #include "bass_loudness_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" BassLoudnessPreset::BassLoudnessPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::bass_loudness::id, tags::schema::bass_loudness::input_path, tags::schema::bass_loudness::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::bass_loudness).append("#").append(util::to_string(index)); } void BassLoudnessPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["loudness"] = g_settings_get_double(settings, "loudness"); json[section][instance_name]["output"] = g_settings_get_double(settings, "output"); json[section][instance_name]["link"] = g_settings_get_double(settings, "link"); } void BassLoudnessPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "loudness", "loudness"); update_key<double>(json.at(section).at(instance_name), settings, "output", "output"); update_key<double>(json.at(section).at(instance_name), settings, "link", "link"); }
2,636
C++
.cpp
50
48.66
100
0.713453
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,616
bass_loudness.cpp
wwmm_easyeffects/src/bass_loudness.cpp
/* * 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/>. */ #include "bass_loudness.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" BassLoudness::BassLoudness(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::bass_loudness, tags::plugin_package::mda, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://drobilla.net/plugins/mda/Loudness"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://drobilla.net/plugins/mda/Loudness is not installed"); } lv2_wrapper->bind_key_double_db<"loudness", "loudness">(settings); lv2_wrapper->bind_key_double_db<"output", "output">(settings); lv2_wrapper->bind_key_double_db<"link", "link">(settings); setup_input_output_gain(); } BassLoudness::~BassLoudness() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void BassLoudness::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void BassLoudness::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto BassLoudness::get_latency_seconds() -> float { return 0.0F; }
3,259
C++
.cpp
92
29.630435
94
0.641132
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,617
preferences_spectrum.cpp
wwmm_easyeffects/src/preferences_spectrum.cpp
/* * 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/>. */ #include "preferences_spectrum.hpp" #include <adwaita.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <vector> #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::preferences::spectrum { struct Data { public: ~Data() { util::debug("data struct destroyed"); } std::vector<gulong> gconnections; }; struct _PreferencesSpectrum { AdwPreferencesPage parent_instance; GtkSwitch *show, *fill, *show_bar_border, *rounded_corners, *dynamic_y_scale; GtkColorDialogButton *color_button, *axis_color_button; GtkDropDown* type; GtkSpinButton *n_points, *height, *line_width, *minimum_frequency, *maximum_frequency, *avsync_delay; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PreferencesSpectrum, preferences_spectrum, ADW_TYPE_PREFERENCES_PAGE) void on_spectrum_color_set(GtkColorDialogButton* button, GParamSpec* pspec, PreferencesSpectrum* self) { auto* rgba = gtk_color_dialog_button_get_rgba(button); g_settings_set(self->settings, "color", "(dddd)", rgba->red, rgba->green, rgba->blue, rgba->alpha); } void on_spectrum_axis_color_set(GtkColorDialogButton* button, GParamSpec* pspec, PreferencesSpectrum* self) { auto* rgba = gtk_color_dialog_button_get_rgba(button); g_settings_set(self->settings, "color-axis-labels", "(dddd)", rgba->red, rgba->green, rgba->blue, rgba->alpha); } void dispose(GObject* object) { auto* self = EE_PREFERENCES_SPECTRUM(object); for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(preferences_spectrum_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_PREFERENCES_SPECTRUM(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(preferences_spectrum_parent_class)->finalize(object); } void preferences_spectrum_class_init(PreferencesSpectrumClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::preferences_spectrum_ui); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, show); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, type); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, fill); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, n_points); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, line_width); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, height); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, show_bar_border); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, rounded_corners); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, dynamic_y_scale); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, color_button); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, axis_color_button); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, minimum_frequency); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, maximum_frequency); gtk_widget_class_bind_template_child(widget_class, PreferencesSpectrum, avsync_delay); gtk_widget_class_bind_template_callback(widget_class, on_spectrum_color_set); gtk_widget_class_bind_template_callback(widget_class, on_spectrum_axis_color_set); } void preferences_spectrum_init(PreferencesSpectrum* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->settings = g_settings_new(tags::schema::spectrum::id); // initializing some widgets auto color = util::gsettings_get_color(self->settings, "color"); gtk_color_dialog_button_set_rgba(self->color_button, &color); color = util::gsettings_get_color(self->settings, "color-axis-labels"); gtk_color_dialog_button_set_rgba(self->axis_color_button, &color); // connecting some widgets signals prepare_spinbuttons<"px">(self->height, self->line_width); g_signal_connect(self->minimum_frequency, "output", G_CALLBACK(+[](GtkSpinButton* button, gpointer user_data) { return parse_spinbutton_output(button, "Hz"); }), nullptr); g_signal_connect(self->minimum_frequency, "input", G_CALLBACK(+[](GtkSpinButton* button, gdouble* new_value, PreferencesSpectrum* self) { const auto parse_result = parse_spinbutton_input(button, new_value); if (parse_result != GTK_INPUT_ERROR) { const auto max_freq = static_cast<double>(g_settings_get_int(self->settings, "maximum-frequency")); if (const auto valid_min_freq = max_freq - 100.0; *new_value > valid_min_freq) { *new_value = valid_min_freq; } } return parse_result; }), self); g_signal_connect(self->maximum_frequency, "output", G_CALLBACK(+[](GtkSpinButton* button, gpointer user_data) { return parse_spinbutton_output(button, "Hz"); }), nullptr); g_signal_connect(self->maximum_frequency, "input", G_CALLBACK(+[](GtkSpinButton* button, gdouble* new_value, PreferencesSpectrum* self) { const auto parse_result = parse_spinbutton_input(button, new_value); if (parse_result != GTK_INPUT_ERROR) { const auto min_freq = static_cast<double>(g_settings_get_int(self->settings, "minimum-frequency")); if (const auto valid_max_freq = min_freq + 100.0; *new_value < valid_max_freq) { *new_value = valid_max_freq; } } return parse_result; }), self); // spectrum section gsettings bindings gsettings_bind_widgets<"show", "fill", "rounded-corners", "show-bar-border", "dynamic-y-scale", "n-points", "height", "line-width", "minimum-frequency", "maximum-frequency", "avsync-delay">( self->settings, self->show, self->fill, self->rounded_corners, self->show_bar_border, self->dynamic_y_scale, self->n_points, self->height, self->line_width, self->minimum_frequency, self->maximum_frequency, self->avsync_delay); ui::gsettings_bind_enum_to_combo_widget(self->settings, "type", self->type); // Spectrum gsettings signals connections self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::color", G_CALLBACK(+[](GSettings* settings, char* key, PreferencesSpectrum* self) { auto color = util::gsettings_get_color(settings, key); gtk_color_dialog_button_set_rgba(self->color_button, &color); }), self)); self->data->gconnections.push_back( g_signal_connect(self->settings, "changed::color-axis-labels", G_CALLBACK(+[](GSettings* settings, char* key, PreferencesSpectrum* self) { auto color = util::gsettings_get_color(settings, key); gtk_color_dialog_button_set_rgba(self->axis_color_button, &color); }), self)); } auto create() -> PreferencesSpectrum* { return static_cast<PreferencesSpectrum*>(g_object_new(EE_TYPE_PREFERENCES_SPECTRUM, nullptr)); } } // namespace ui::preferences::spectrum
8,768
C++
.cpp
165
45.757576
124
0.684734
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,618
pipe_manager.cpp
wwmm_easyeffects/src/pipe_manager.cpp
/* * 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/>. */ #include "pipe_manager.hpp" #include <glib.h> #include <pipewire/client.h> #include <pipewire/context.h> #include <pipewire/core.h> #include <pipewire/device.h> #include <pipewire/extensions/metadata.h> #include <pipewire/keys.h> #include <pipewire/link.h> #include <pipewire/module.h> #include <pipewire/node.h> #include <pipewire/pipewire.h> #include <pipewire/port.h> #include <pipewire/properties.h> #include <pipewire/proxy.h> #include <pipewire/thread-loop.h> #include <pipewire/version.h> #include <spa/monitor/device.h> #include <spa/param/audio/raw-types.h> #include <spa/param/audio/raw.h> #include <spa/param/format.h> #include <spa/param/param.h> #include <spa/param/props.h> #include <spa/param/route.h> #include <spa/pod/builder.h> #include <spa/pod/iter.h> #include <spa/pod/parser.h> #include <spa/pod/pod.h> #include <spa/pod/vararg.h> #include <spa/utils/defs.h> #include <spa/utils/dict.h> #include <spa/utils/hook.h> #include <spa/utils/json.h> #include <spa/utils/keys.h> #include <spa/utils/result.h> #include <spa/utils/type.h> #include <sys/types.h> #include <algorithm> #include <array> #include <cerrno> #include <chrono> #include <cstdint> #include <cstring> #include <ctime> #include <span> #include <stdexcept> #include <string> #include <thread> #include <vector> #include "pipe_objects.hpp" #include "tags_app.hpp" #include "tags_pipewire.hpp" #include "util.hpp" namespace { struct node_data { pw_proxy* proxy = nullptr; spa_hook proxy_listener{}; spa_hook object_listener{}; PipeManager* pm = nullptr; NodeInfo* nd_info{}; }; struct proxy_data { pw_proxy* proxy = nullptr; spa_hook proxy_listener{}; spa_hook object_listener{}; PipeManager* pm = nullptr; uint id = SPA_ID_INVALID; uint64_t serial = SPA_ID_INVALID; }; template <typename T> auto spa_dict_get_string(const spa_dict* props, const char* key, T& str) -> bool { // If we will use string views in the future, this template could be useful. if (const auto* s = spa_dict_lookup(props, key)) { str = s; return true; } return false; } template <typename T> auto spa_dict_get_num(const spa_dict* props, const char* key, T& num) -> bool { if (const auto* n = spa_dict_lookup(props, key)) { return util::str_to_num(std::string(n), num); } return false; } auto spa_dict_get_bool(const spa_dict* props, const char* key, bool& b) -> bool { // Returning bool is for conversion success state. // The bool value is assigned to reference parameter. if (const auto* v = spa_dict_lookup(props, key)) { b = (g_strcmp0(v, "true") == 0); return true; } return false; } void on_removed_proxy(void* data) { auto* const pd = static_cast<proxy_data*>(data); // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) if (pd->object_listener.link.next != nullptr || pd->object_listener.link.prev != nullptr) { spa_hook_remove(&pd->object_listener); } pw_proxy_destroy(pd->proxy); } auto link_info_from_props(const spa_dict* props) -> LinkInfo { LinkInfo info; spa_dict_get_num(props, PW_KEY_LINK_ID, info.id); spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, info.serial); spa_dict_get_string(props, PW_KEY_OBJECT_PATH, info.path); spa_dict_get_num(props, PW_KEY_LINK_INPUT_NODE, info.input_node_id); spa_dict_get_num(props, PW_KEY_LINK_INPUT_PORT, info.input_port_id); spa_dict_get_num(props, PW_KEY_LINK_OUTPUT_NODE, info.output_node_id); spa_dict_get_num(props, PW_KEY_LINK_OUTPUT_PORT, info.output_port_id); spa_dict_get_bool(props, PW_KEY_LINK_PASSIVE, info.passive); return info; } auto port_info_from_props(const spa_dict* props) -> PortInfo { PortInfo info; spa_dict_get_num(props, PW_KEY_PORT_ID, info.port_id); spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, info.serial); spa_dict_get_string(props, PW_KEY_PORT_NAME, info.name); spa_dict_get_num(props, PW_KEY_NODE_ID, info.node_id); spa_dict_get_string(props, PW_KEY_PORT_DIRECTION, info.direction); spa_dict_get_string(props, PW_KEY_AUDIO_CHANNEL, info.audio_channel); spa_dict_get_string(props, PW_KEY_AUDIO_FORMAT, info.format_dsp); spa_dict_get_bool(props, PW_KEY_PORT_PHYSICAL, info.physical); spa_dict_get_bool(props, PW_KEY_PORT_TERMINAL, info.terminal); spa_dict_get_bool(props, PW_KEY_PORT_MONITOR, info.monitor); return info; } void on_removed_node_proxy(void* data) { auto* const nd = static_cast<node_data*>(data); spa_hook_remove(&nd->object_listener); pw_proxy_destroy(nd->proxy); } void on_destroy_node_proxy(void* data) { auto* const nd = static_cast<node_data*>(data); auto* const pm = nd->pm; auto node_it = pm->node_map.find(nd->nd_info->serial); if (node_it == pm->node_map.end()) { return; } nd->nd_info->proxy = nullptr; node_it->second.proxy = nullptr; spa_hook_remove(&nd->proxy_listener); pm->node_map.erase(node_it); if (!PipeManager::exiting) { if (nd->nd_info->media_class == tags::pipewire::media_class::source) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->source_removed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::sink) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->sink_removed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::output_stream) { const auto serial = nd->nd_info->serial; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_output_removed.emit(serial); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::input_stream) { const auto serial = nd->nd_info->serial; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_input_removed.emit(serial); }); } } util::debug(nd->nd_info->media_class + " " + util::to_string(nd->nd_info->id) + " " + nd->nd_info->name + " has been removed"); delete nd->nd_info; } void on_node_info(void* object, const struct pw_node_info* info) { if (PipeManager::exiting) { return; } auto* const nd = static_cast<node_data*>(object); auto* const pm = nd->pm; // Check if the node is inside our map auto node_it = pm->node_map.find(nd->nd_info->serial); if (node_it == pm->node_map.end()) { return; } // Check if the node has to be removed bool remove_node = false; // Exclude blocklisted App id. // To be checked here because PW_KEY_APP_ID is not set in on_registry_global. if (const auto* app_id = spa_dict_lookup(info->props, PW_KEY_APP_ID)) { if (std::ranges::find(pm->blocklist_app_id, app_id) != pm->blocklist_app_id.end()) { remove_node = true; } } // Exclude capture streams. // Even PW_KEY_STREAM_CAPTURE_SINK is not set in on_registry_global. // Useful to exclude OBS recording streams. if (g_strcmp0(spa_dict_lookup(info->props, PW_KEY_STREAM_CAPTURE_SINK), "true") == 0 && PipeManager::exclude_monitor_stream) { remove_node = true; } bool ignore_input_stream = false; bool ignore_output_stream = false; if (nd->nd_info->media_class == tags::pipewire::media_class::input_stream && !pm->input_device.name.empty()) { if (const auto* target_object = spa_dict_lookup(info->props, PW_KEY_TARGET_OBJECT)) { /* target.object can a name or serial number: https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/master/src/pipewire/keys.h#L334 */ uint64_t serial = SPA_ID_INVALID; if (util::str_to_num(target_object, serial)) { if (serial != SPA_ID_INVALID && (serial != pm->input_device.serial && serial != pm->ee_source_node.serial)) { ignore_input_stream = true; } } else if (target_object != pm->input_device.name && target_object != pm->ee_source_node.name) { ignore_input_stream = true; } if (ignore_input_stream) { util::debug("The input stream " + nd->nd_info->name + " does not have as target the same mic used as EE input: " + pm->input_device.name + "\n The user wants it to record from device " + target_object + ". We will ignore this stream."); remove_node = true; } } } if (nd->nd_info->media_class == tags::pipewire::media_class::output_stream && !pm->output_device.name.empty()) { if (const auto* target_object = spa_dict_lookup(info->props, PW_KEY_TARGET_OBJECT)) { /* target.object can a name or serial number: https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/master/src/pipewire/keys.h#L334 */ uint64_t serial = SPA_ID_INVALID; if (util::str_to_num(target_object, serial)) { if (serial != SPA_ID_INVALID && (serial != pm->output_device.serial && serial != pm->ee_sink_node.serial)) { ignore_output_stream = true; } } else if (target_object != pm->output_device.name && target_object != pm->ee_sink_node.name) { ignore_output_stream = true; } if (ignore_output_stream) { util::debug("The output stream " + nd->nd_info->name + " does not have as target the same output device used as EE: " + pm->output_device.name + "\n The user wants it to play to device " + target_object + ". We will ignore this stream."); remove_node = true; } } } if (remove_node) { nd->nd_info->proxy = nullptr; node_it->second.proxy = nullptr; spa_hook_remove(&nd->proxy_listener); pm->node_map.erase(node_it); if (nd->nd_info->media_class == tags::pipewire::media_class::source) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->source_removed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::sink) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->sink_removed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::output_stream) { const auto serial = nd->nd_info->serial; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_output_removed.emit(serial); pm->disconnect_stream(nd->nd_info->id); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::input_stream) { const auto serial = nd->nd_info->serial; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_input_removed.emit(serial); pm->disconnect_stream(nd->nd_info->id); }); } util::debug(nd->nd_info->media_class + " " + util::to_string(nd->nd_info->id) + " " + nd->nd_info->name + " has been removed"); return; } // Chech for node info updates auto app_info_ui_changed = false; if (info->state != nd->nd_info->state) { nd->nd_info->state = info->state; app_info_ui_changed = true; } nd->nd_info->n_input_ports = static_cast<int>(info->n_input_ports); nd->nd_info->n_output_ports = static_cast<int>(info->n_output_ports); spa_dict_get_num(info->props, PW_KEY_PRIORITY_SESSION, nd->nd_info->priority); if (const auto* app_id = spa_dict_lookup(info->props, PW_KEY_APP_ID)) { if (app_id != nd->nd_info->application_id) { nd->nd_info->application_id = app_id; } } // spa_dict_get_string(props, PW_KEY_APP_PROCESS_BINARY, app_process_binary); if (const auto* app_name = spa_dict_lookup(info->props, PW_KEY_APP_NAME)) { if (app_name != nd->nd_info->app_name) { nd->nd_info->app_name = app_name; app_info_ui_changed = true; } } if (const auto* app_process_id = spa_dict_lookup(info->props, PW_KEY_APP_PROCESS_ID)) { if (app_process_id != nd->nd_info->app_process_id) { nd->nd_info->app_process_id = app_process_id; app_info_ui_changed = true; } } if (const auto* app_process_binary = spa_dict_lookup(info->props, PW_KEY_APP_PROCESS_BINARY)) { if (app_process_binary != nd->nd_info->app_process_binary) { nd->nd_info->app_process_binary = app_process_binary; app_info_ui_changed = true; } } if (const auto* app_icon_name = spa_dict_lookup(info->props, PW_KEY_APP_ICON_NAME)) { if (app_icon_name != nd->nd_info->app_icon_name) { nd->nd_info->app_icon_name = app_icon_name; app_info_ui_changed = true; } } if (const auto* media_icon_name = spa_dict_lookup(info->props, PW_KEY_MEDIA_ICON_NAME)) { if (media_icon_name != nd->nd_info->media_icon_name) { nd->nd_info->media_icon_name = media_icon_name; app_info_ui_changed = true; } } spa_dict_get_string(info->props, PW_KEY_DEVICE_ICON_NAME, nd->nd_info->device_icon_name); if (const auto* media_name = spa_dict_lookup(info->props, PW_KEY_MEDIA_NAME)) { if (media_name != nd->nd_info->media_name) { nd->nd_info->media_name = media_name; app_info_ui_changed = true; } } if (const auto* node_latency = spa_dict_lookup(info->props, PW_KEY_NODE_LATENCY)) { const auto str = std::string(node_latency); const auto delimiter_pos = str.find('/'); int rate = 1; if (util::str_to_num(str.substr(delimiter_pos + 1U), rate)) { if (rate != nd->nd_info->rate) { nd->nd_info->rate = rate; app_info_ui_changed = true; } } float pw_lat = 0.0F; if (util::str_to_num(str.substr(0U, delimiter_pos), pw_lat)) { if (auto latency = (pw_lat / static_cast<float>(nd->nd_info->rate)); latency != nd->nd_info->latency) { nd->nd_info->latency = latency; app_info_ui_changed = true; } } } spa_dict_get_num(info->props, PW_KEY_DEVICE_ID, nd->nd_info->device_id); if ((info->change_mask & PW_NODE_CHANGE_MASK_PARAMS) != 0U) { auto params = std::span(info->params, info->n_params); for (auto param : params) { if ((param.flags & SPA_PARAM_INFO_READ) == 0U) { continue; } if (const auto id = param.id; id == SPA_PARAM_Props || id == SPA_PARAM_EnumFormat || id == SPA_PARAM_Format) { pw_node_enum_params((struct pw_node*)nd->proxy, 0, id, 0, -1, nullptr); } } } // update NodeInfo inside map node_it->second = *nd->nd_info; // sometimes PipeWire destroys the pointer before signal_idle is called, // therefore we make a copy if (nd->nd_info->connected != pm->stream_is_connected(info->id, nd->nd_info->media_class)) { nd->nd_info->connected = !nd->nd_info->connected; app_info_ui_changed = true; } if (app_info_ui_changed) { const auto nd_info_copy = *nd->nd_info; if (nd->nd_info->media_class == tags::pipewire::media_class::output_stream) { util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_output_changed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::input_stream) { util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->stream_input_changed.emit(nd_info_copy); }); } } if (nd->nd_info->media_class == tags::pipewire::media_class::source) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->source_changed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::sink) { const auto nd_info_copy = *nd->nd_info; util::idle_add([=]() { if (PipeManager::exiting) { return; } pm->sink_changed.emit(nd_info_copy); }); } // const struct spa_dict_item* item = nullptr; // spa_dict_for_each(item, info->props) printf("\t\t%s: \"%s\"\n", item->key, item->value); } void on_node_event_param(void* object, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod* param) { if (PipeManager::exiting) { return; } auto* const nd = static_cast<node_data*>(object); auto* const pm = nd->pm; if (param == nullptr) { return; } spa_pod_prop* pod_prop = nullptr; auto* obj = (spa_pod_object*)param; const auto serial = nd->nd_info->serial; auto notify = false; SPA_POD_OBJECT_FOREACH(obj, pod_prop) { switch (pod_prop->key) { case SPA_FORMAT_AUDIO_format: { uint format = 0U; if (spa_pod_get_id(&pod_prop->value, &format) != 0) { break; } auto node_it = pm->node_map.find(serial); if (node_it == pm->node_map.end()) { break; } std::string format_str = "unknown"; for (const auto type_info : std::to_array(spa_type_audio_format)) { if (format == type_info.type) { if (type_info.name != nullptr) { std::string long_name = type_info.name; format_str = long_name.substr(long_name.rfind(':') + 1U); } } } if (format_str != nd->nd_info->format) { node_it->second.format = format_str; nd->nd_info->format = format_str; notify = true; } break; } case SPA_FORMAT_AUDIO_rate: { int rate = 1; if (spa_pod_get_int(&pod_prop->value, &rate) != 0) { break; } if (rate == nd->nd_info->rate) { break; } if (auto node_it = pm->node_map.find(serial); node_it != pm->node_map.end()) { node_it->second.rate = rate; nd->nd_info->rate = rate; notify = true; } break; } case SPA_PROP_mute: { auto v = false; if (spa_pod_get_bool(&pod_prop->value, &v) != 0) { break; } if (v == nd->nd_info->mute) { break; } if (auto node_it = pm->node_map.find(serial); node_it != pm->node_map.end()) { node_it->second.mute = v; nd->nd_info->mute = v; notify = true; } break; } case SPA_PROP_channelVolumes: { auto node_it = pm->node_map.find(serial); if (node_it == pm->node_map.end()) { break; } std::array<float, SPA_AUDIO_MAX_CHANNELS> volumes{}; const auto n_volumes = spa_pod_copy_array(&pod_prop->value, SPA_TYPE_Float, volumes.data(), SPA_AUDIO_MAX_CHANNELS); float max = 0.0F; for (uint i = 0U; i < n_volumes; i++) { max = std::max(volumes.at(i), max); } if (n_volumes != nd->nd_info->n_volume_channels || max != nd->nd_info->volume) { node_it->second.n_volume_channels = n_volumes; node_it->second.volume = max; nd->nd_info->n_volume_channels = n_volumes; nd->nd_info->volume = max; notify = true; } break; } default: break; } } if (notify) { // sometimes PipeWire destroys the pointer before signal_idle is called, // therefore we make a copy if (nd->nd_info->media_class == tags::pipewire::media_class::output_stream) { const auto nd_info_copy = *nd->nd_info; util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->stream_output_changed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::input_stream) { const auto nd_info_copy = *nd->nd_info; util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->stream_input_changed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::virtual_source) { const auto nd_info_copy = *nd->nd_info; if (nd_info_copy.serial == pm->ee_source_node.serial) { pm->ee_source_node = nd_info_copy; } util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->source_changed.emit(nd_info_copy); }); } else if (nd->nd_info->media_class == tags::pipewire::media_class::sink) { const auto nd_info_copy = *nd->nd_info; if (nd_info_copy.serial == pm->ee_sink_node.serial) { pm->ee_sink_node = nd_info_copy; } util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->sink_changed.emit(nd_info_copy); }); } } } void on_link_info(void* object, const struct pw_link_info* info) { auto* const ld = static_cast<proxy_data*>(object); auto* const pm = ld->pm; LinkInfo link_copy; for (auto& l : ld->pm->list_links) { if (l.serial == ld->serial) { l.state = info->state; link_copy = l; util::idle_add([pm, link_copy] { if (PipeManager::exiting) { return; } pm->link_changed.emit(link_copy); }); // util::warning(pw_link_state_as_string(l.state)); break; } } // const struct spa_dict_item* item = nullptr; // spa_dict_for_each(item, info->props) printf("\t\t%s: \"%s\"\n", item->key, item->value); } void on_destroy_link_proxy(void* data) { auto* const ld = static_cast<proxy_data*>(data); spa_hook_remove(&ld->proxy_listener); ld->pm->list_links.erase(std::remove_if(ld->pm->list_links.begin(), ld->pm->list_links.end(), [=](const auto& n) { return n.serial == ld->serial; }), ld->pm->list_links.end()); } void on_destroy_port_proxy(void* data) { auto* const pd = static_cast<proxy_data*>(data); spa_hook_remove(&pd->proxy_listener); pd->pm->list_ports.erase(std::remove_if(pd->pm->list_ports.begin(), pd->pm->list_ports.end(), [=](const auto& n) { return n.serial == pd->serial; }), pd->pm->list_ports.end()); } void on_module_info(void* object, const struct pw_module_info* info) { auto* const md = static_cast<proxy_data*>(object); for (auto& module : md->pm->list_modules) { if (module.id == info->id) { if (info->filename != nullptr) { module.filename = info->filename; } spa_dict_get_string(info->props, PW_KEY_MODULE_DESCRIPTION, module.description); break; } } } void on_destroy_module_proxy(void* data) { auto* const md = static_cast<proxy_data*>(data); spa_hook_remove(&md->proxy_listener); md->pm->list_modules.erase(std::remove_if(md->pm->list_modules.begin(), md->pm->list_modules.end(), [=](const auto& n) { return n.id == md->id; }), md->pm->list_modules.end()); } void on_client_info(void* object, const struct pw_client_info* info) { auto* const cd = static_cast<proxy_data*>(object); for (auto& client : cd->pm->list_clients) { if (client.id == info->id) { spa_dict_get_string(info->props, PW_KEY_APP_NAME, client.name); spa_dict_get_string(info->props, PW_KEY_ACCESS, client.access); spa_dict_get_string(info->props, PW_KEY_CLIENT_API, client.api); break; } } } void on_destroy_client_proxy(void* data) { auto* const cd = static_cast<proxy_data*>(data); spa_hook_remove(&cd->proxy_listener); cd->pm->list_clients.erase(std::remove_if(cd->pm->list_clients.begin(), cd->pm->list_clients.end(), [=](const auto& n) { return n.serial == cd->serial; }), cd->pm->list_clients.end()); } void on_device_info(void* object, const struct pw_device_info* info) { auto* const dd = static_cast<proxy_data*>(object); for (auto& device : dd->pm->list_devices) { if (device.id != info->id) { continue; } spa_dict_get_string(info->props, PW_KEY_DEVICE_NAME, device.name); spa_dict_get_string(info->props, PW_KEY_DEVICE_NICK, device.nick); spa_dict_get_string(info->props, PW_KEY_DEVICE_DESCRIPTION, device.description); spa_dict_get_string(info->props, PW_KEY_DEVICE_API, device.api); if (spa_dict_get_string(info->props, SPA_KEY_DEVICE_BUS_ID, device.bus_id)) { std::ranges::replace(device.bus_id, ':', '_'); std::ranges::replace(device.bus_id, '+', '_'); } if (spa_dict_get_string(info->props, PW_KEY_DEVICE_BUS_PATH, device.bus_path)) { std::ranges::replace(device.bus_path, ':', '_'); std::ranges::replace(device.bus_path, '+', '_'); } /* For some reason bluez5 devices do not define bus-path or bus-id. So as a workaround we set SPA_KEY_API_BLUEZ5_ADDRESS as bus_path */ if (device.api == "bluez5") { if (spa_dict_get_string(info->props, SPA_KEY_API_BLUEZ5_ADDRESS, device.bus_path)) { std::replace(device.bus_path.begin(), device.bus_path.end(), ':', '_'); } } if ((info->change_mask & PW_DEVICE_CHANGE_MASK_PARAMS) != 0U) { auto params = std::span(info->params, info->n_params); for (auto param : params) { if ((param.flags & SPA_PARAM_INFO_READ) == 0U) { continue; } if (const auto id = param.id; id == SPA_PARAM_Route) { pw_device_enum_params((struct pw_device*)dd->proxy, 0, id, 0, -1, nullptr); } } } break; } } void on_device_event_param(void* object, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod* param) { if (id != SPA_PARAM_Route) { return; } auto* const dd = static_cast<proxy_data*>(object); const char* name = nullptr; enum spa_direction direction {}; enum spa_param_availability available {}; if (spa_pod_parse_object(param, SPA_TYPE_OBJECT_ParamRoute, nullptr, SPA_PARAM_ROUTE_direction, SPA_POD_Id(&direction), SPA_PARAM_ROUTE_name, SPA_POD_String(&name), SPA_PARAM_ROUTE_available, SPA_POD_Id(&available)) < 0) { return; } if (name == nullptr) { return; } for (auto& device : dd->pm->list_devices) { if (device.id != dd->id) { continue; } auto* const pm = dd->pm; if (direction == SPA_DIRECTION_INPUT) { if (name != device.input_route_name || available != device.input_route_available) { device.input_route_name = name; device.input_route_available = available; util::idle_add([pm, device] { if (PipeManager::exiting) { return; } pm->device_input_route_changed.emit(device); }); } } else if (direction == SPA_DIRECTION_OUTPUT) { if (name != device.output_route_name || available != device.output_route_available) { device.output_route_name = name; device.output_route_available = available; util::idle_add([pm, device] { if (PipeManager::exiting) { return; } pm->device_output_route_changed.emit(device); }); } } break; } } void on_destroy_device_proxy(void* data) { auto* const dd = static_cast<proxy_data*>(data); spa_hook_remove(&dd->proxy_listener); dd->pm->list_devices.erase(std::remove_if(dd->pm->list_devices.begin(), dd->pm->list_devices.end(), [=](const auto& n) { return n.id == dd->id; }), dd->pm->list_devices.end()); } auto on_metadata_property(void* data, uint32_t id, const char* key, const char* type, const char* value) -> int { auto* const pm = static_cast<PipeManager*>(data); const std::string str_key = (key != nullptr) ? key : ""; const std::string str_type = (type != nullptr) ? type : ""; const std::string str_value = (value != nullptr) ? value : ""; util::debug("new metadata property: " + util::to_string(id) + ", " + str_key + ", " + str_type + ", " + str_value); if (str_value.empty()) { return 0; } if (str_key == "default.audio.sink") { std::array<char, 1024U> v{}; PipeManager::json_object_find(str_value.c_str(), "name", v.data(), v.size() * sizeof(char)); if (g_strcmp0(v.data(), tags::pipewire::ee_sink_name) == 0) { return 0; } pm->default_output_device_name = v.data(); util::idle_add([pm] { if (PipeManager::exiting) { return; } pm->new_default_sink_name.emit(pm->default_output_device_name); }); } if (str_key == "default.audio.source") { std::array<char, 1024U> v{}; PipeManager::json_object_find(str_value.c_str(), "name", v.data(), v.size() * sizeof(char)); if (g_strcmp0(v.data(), tags::pipewire::ee_source_name) == 0) { return 0; } pm->default_input_device_name = v.data(); util::idle_add([pm] { if (PipeManager::exiting) { return; } pm->new_default_source_name.emit(pm->default_input_device_name); }); } return 0; } const struct pw_metadata_events metadata_events = {PW_VERSION_METADATA_EVENTS, on_metadata_property}; const struct pw_proxy_events link_proxy_events = {.destroy = on_destroy_link_proxy, .bound = nullptr, .removed = on_removed_proxy, .done = nullptr, .error = nullptr}; const struct pw_proxy_events port_proxy_events = {.destroy = on_destroy_port_proxy, .bound = nullptr, .removed = on_removed_proxy, .done = nullptr, .error = nullptr}; const struct pw_proxy_events module_proxy_events = {.destroy = on_destroy_module_proxy, .bound = nullptr, .removed = on_removed_proxy, .done = nullptr, .error = nullptr}; const struct pw_proxy_events client_proxy_events = {.destroy = on_destroy_client_proxy, .bound = nullptr, .removed = on_removed_proxy, .done = nullptr, .error = nullptr}; const struct pw_proxy_events device_proxy_events = {.destroy = on_destroy_device_proxy, .bound = nullptr, .removed = on_removed_proxy, .done = nullptr, .error = nullptr}; const struct pw_proxy_events node_proxy_events = {.destroy = on_destroy_node_proxy, .bound = nullptr, .removed = on_removed_node_proxy, .done = nullptr, .error = nullptr}; const struct pw_node_events node_events = {.info = on_node_info, .param = on_node_event_param}; const struct pw_link_events link_events = { .info = on_link_info, }; const struct pw_module_events module_events = { .info = on_module_info, }; const struct pw_client_events client_events = { .info = on_client_info, }; const struct pw_device_events device_events = {.info = on_device_info, .param = on_device_event_param}; void on_registry_global(void* data, uint32_t id, uint32_t permissions, const char* type, uint32_t version, const struct spa_dict* props) { if (id == SPA_ID_INVALID) { // If PipeWire send us a wrong id, we don't have issues return; } auto* const pm = static_cast<PipeManager*>(data); if (g_strcmp0(type, PW_TYPE_INTERFACE_Node) == 0) { bool is_ee_filter = false; if (const auto* key_media_role = spa_dict_lookup(props, PW_KEY_MEDIA_ROLE)) { // Exclude blocklisted media roles if (std::ranges::find(pm->blocklist_media_role, std::string(key_media_role)) != pm->blocklist_media_role.end()) { return; } if (g_strcmp0(key_media_role, "DSP") == 0) { if (const auto* key_media_category = spa_dict_lookup(props, PW_KEY_MEDIA_CATEGORY)) { if (g_strcmp0(key_media_category, "Filter") == 0) { if (const auto* key_node_name = spa_dict_lookup(props, PW_KEY_NODE_NAME)) { if (std::string node_name(key_node_name); node_name.size() > 3U) { if (node_name.starts_with("ee_")) { is_ee_filter = true; } } } } } } } std::string media_class; std::string media_role; if (const auto* key_media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS)) { media_class = key_media_class; } if (const auto* key_media_role = spa_dict_lookup(props, PW_KEY_MEDIA_ROLE)) { media_role = key_media_role; } constexpr auto class_array = std::to_array({tags::pipewire::media_class::output_stream, tags::pipewire::media_class::input_stream, tags::pipewire::media_class::sink, tags::pipewire::media_class::source, tags::pipewire::media_class::virtual_source}); if (!is_ee_filter && !std::any_of(class_array.begin(), class_array.end(), [&](const auto& str) { return str == media_class; })) { return; } std::string node_name; spa_dict_get_string(props, PW_KEY_NODE_NAME, node_name); // At least for now I do not think there is a point in showing the spectrum adn the output level filters in menus if (util::str_contains(node_name, "output_level") || util::str_contains(node_name, "spectrum")) { return; } // Exclude blocklisted node names if (std::ranges::find(PipeManager::blocklist_node_name, node_name) != PipeManager::blocklist_node_name.end()) { return; } uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while retrieving the object serial. The node cannot be handled by Easy Effects."); return; } // New node can be added into the node map auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_NODE, sizeof(node_data))); auto* nd = static_cast<node_data*>(pw_proxy_get_user_data(proxy)); nd->proxy = proxy; nd->pm = pm; nd->nd_info = new NodeInfo(); nd->nd_info->proxy = proxy; nd->nd_info->serial = serial; nd->nd_info->id = id; nd->nd_info->media_class = media_class; nd->nd_info->media_role = media_role; nd->nd_info->name = node_name; spa_dict_get_string(props, PW_KEY_NODE_DESCRIPTION, nd->nd_info->description); spa_dict_get_num(props, PW_KEY_PRIORITY_SESSION, nd->nd_info->priority); spa_dict_get_num(props, PW_KEY_DEVICE_ID, nd->nd_info->device_id); const auto [node_it, success] = pm->node_map.insert({serial, *nd->nd_info}); if (!success) { util::warning("Cannot insert node " + util::to_string(id) + " " + node_name + " into the node map because there's already an existing serial " + util::to_string(serial)); return; } pw_node_add_listener(proxy, &nd->object_listener, &node_events, nd); pw_proxy_add_listener(proxy, &nd->proxy_listener, &node_proxy_events, nd); // sometimes PipeWire destroys the pointer before signal_idle is called, // therefore we make a copy of NodeInfo const auto nd_info_copy = *nd->nd_info; if (media_class == tags::pipewire::media_class::source && node_name != tags::pipewire::ee_source_name) { util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->source_added.emit(nd_info_copy); }); } else if (media_class == tags::pipewire::media_class::sink && node_name != tags::pipewire::ee_sink_name) { util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->sink_added.emit(nd_info_copy); }); } else if (media_class == tags::pipewire::media_class::output_stream) { util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->stream_output_added.emit(nd_info_copy); }); } else if (media_class == tags::pipewire::media_class::input_stream) { util::idle_add([pm, nd_info_copy] { if (PipeManager::exiting) { return; } pm->stream_input_added.emit(nd_info_copy); }); } // We will have debug info about our filters later if (!is_ee_filter) { util::debug(media_class + " " + util::to_string(id) + " " + nd->nd_info->name + " with serial " + util::to_string(serial) + " has been added"); } return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Link) == 0) { uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while retrieving the object serial. This link cannot be handled by Easy Effects."); return; } auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_LINK, sizeof(proxy_data))); auto* const pd = static_cast<proxy_data*>(pw_proxy_get_user_data(proxy)); pd->proxy = proxy; pd->pm = pm; pd->id = id; pd->serial = serial; pw_link_add_listener(proxy, &pd->object_listener, &link_events, pd); pw_proxy_add_listener(proxy, &pd->proxy_listener, &link_proxy_events, pd); auto link_info = link_info_from_props(props); link_info.id = id; link_info.serial = serial; pm->list_links.push_back(link_info); try { const auto input_node = pm->node_map_at_id(link_info.input_node_id); const auto output_node = pm->node_map_at_id(link_info.output_node_id); util::debug(output_node.name + " port " + util::to_string(link_info.output_port_id) + " is connected to " + input_node.name + " port " + util::to_string(link_info.input_port_id)); } catch (std::out_of_range& e) { util::debug(e.what()); } return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Port) == 0) { uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while retrieving the object serial. This port cannot be handled by Easy Effects."); return; } auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_PORT, sizeof(proxy_data))); auto* const pd = static_cast<proxy_data*>(pw_proxy_get_user_data(proxy)); pd->proxy = proxy; pd->pm = pm; pd->id = id; pd->serial = serial; pw_proxy_add_listener(proxy, &pd->proxy_listener, &port_proxy_events, pd); auto port_info = port_info_from_props(props); port_info.id = id; port_info.serial = serial; // std::cout << port_info.name << "\t" << port_info.audio_channel << "\t" << port_info.direction << "\t" // << port_info.format_dsp << "\t" << port_info.port_id << "\t" << port_info.node_id << std::endl; pm->list_ports.push_back(port_info); return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Module) == 0) { uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while retrieving the object serial. This module cannot be handled by Easy Effects."); return; } auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_MODULE, sizeof(proxy_data))); auto* const pd = static_cast<proxy_data*>(pw_proxy_get_user_data(proxy)); pd->proxy = proxy; pd->pm = pm; pd->id = id; pd->serial = serial; pw_module_add_listener(proxy, &pd->object_listener, &module_events, pd); pw_proxy_add_listener(proxy, &pd->proxy_listener, &module_proxy_events, pd); ModuleInfo m_info{.id = id, .serial = serial}; spa_dict_get_string(props, PW_KEY_MODULE_NAME, m_info.name); pm->list_modules.push_back(m_info); return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Client) == 0) { uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while retrieving the object serial. This client cannot be handled by Easy Effects."); return; } auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_CLIENT, sizeof(proxy_data))); auto* const pd = static_cast<proxy_data*>(pw_proxy_get_user_data(proxy)); pd->proxy = proxy; pd->pm = pm; pd->id = id; pd->serial = serial; pw_client_add_listener(proxy, &pd->object_listener, &client_events, pd); pw_proxy_add_listener(proxy, &pd->proxy_listener, &client_proxy_events, pd); ClientInfo c_info{.id = id, .serial = serial}; pm->list_clients.push_back(c_info); return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Metadata) == 0) { if (const auto* name = spa_dict_lookup(props, PW_KEY_METADATA_NAME)) { using namespace std::string_literals; util::debug("found metadata: "s + name); if (g_strcmp0(name, "default") == 0) { if (pm->metadata != nullptr) { util::debug("A new default metadata is available. We will use it"); spa_hook_remove(&pm->metadata_listener); } pm->metadata = static_cast<pw_metadata*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_METADATA, 0)); if (pm->metadata != nullptr) { pw_metadata_add_listener(pm->metadata, &pm->metadata_listener, &metadata_events, pm); } else { util::warning("pw_registry_bind returned a null metadata object"); } } } return; } if (g_strcmp0(type, PW_TYPE_INTERFACE_Device) == 0) { if (const auto* key_media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS)) { const std::string media_class = key_media_class; if (media_class == tags::pipewire::media_class::device) { uint64_t serial = 0U; if (!spa_dict_get_num(props, PW_KEY_OBJECT_SERIAL, serial)) { util::warning( "An error occurred while converting the object serial. This device cannot be handled by Easy Effects."); return; } auto* proxy = static_cast<pw_proxy*>(pw_registry_bind(pm->registry, id, type, PW_VERSION_DEVICE, sizeof(proxy_data))); auto* const pd = static_cast<proxy_data*>(pw_proxy_get_user_data(proxy)); pd->proxy = proxy; pd->pm = pm; pd->id = id; pd->serial = serial; pw_device_add_listener(proxy, &pd->object_listener, &device_events, pd); pw_proxy_add_listener(proxy, &pd->proxy_listener, &device_proxy_events, pd); DeviceInfo d_info{.id = id, .serial = serial, .media_class = media_class}; pm->list_devices.push_back(d_info); } } return; } } void on_core_error(void* data, uint32_t id, int seq, int res, const char* message) { auto* const pm = static_cast<PipeManager*>(data); using namespace std::string_literals; if (id == PW_ID_CORE) { util::warning("Remote error res: "s + spa_strerror(res)); util::warning("Remote error message: "s + message); pw_thread_loop_signal(pm->thread_loop, false); } } void on_core_info(void* data, const struct pw_core_info* info) { using namespace std::string_literals; auto* const pm = static_cast<PipeManager*>(data); pm->core_name = info->name; pm->version = info->version; spa_dict_get_string(info->props, "default.clock.rate", pm->default_clock_rate); spa_dict_get_string(info->props, "default.clock.min-quantum", pm->default_min_quantum); spa_dict_get_string(info->props, "default.clock.max-quantum", pm->default_max_quantum); spa_dict_get_string(info->props, "default.clock.quantum", pm->default_quantum); util::debug("core version: "s + info->version); util::debug("core name: "s + info->name); } void on_core_done(void* data, uint32_t id, int seq) { auto* const pm = static_cast<PipeManager*>(data); if (id == PW_ID_CORE) { pw_thread_loop_signal(pm->thread_loop, false); } } const struct pw_core_events core_events = {.version = PW_VERSION_CORE_EVENTS, .info = on_core_info, .done = on_core_done, .error = on_core_error}; const struct pw_registry_events registry_events = { .global = on_registry_global, }; } // namespace PipeManager::PipeManager() : header_version(pw_get_headers_version()), library_version(pw_get_library_version()) { pw_init(nullptr, nullptr); spa_zero(core_listener); spa_zero(registry_listener); util::debug("compiled with PipeWire: " + header_version); util::debug("linked to PipeWire: " + library_version); // this needs to occur after pw_init(), so putting it before pw_init() in the initializer breaks this // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer) thread_loop = pw_thread_loop_new("ee-pipewire-thread", nullptr); // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) if (thread_loop == nullptr) { util::error("could not create PipeWire loop"); } if (pw_thread_loop_start(thread_loop) != 0) { util::error("could not start the loop"); } lock(); pw_properties* props_context = pw_properties_new(nullptr, nullptr); pw_properties_set(props_context, PW_KEY_CONFIG_NAME, "client-rt.conf"); pw_properties_set(props_context, PW_KEY_MEDIA_TYPE, "Audio"); pw_properties_set(props_context, PW_KEY_MEDIA_CATEGORY, "Manager"); pw_properties_set(props_context, PW_KEY_MEDIA_ROLE, "Music"); context = pw_context_new(pw_thread_loop_get_loop(thread_loop), props_context, 0); if (context == nullptr) { util::error("could not create PipeWire context"); } core = pw_context_connect(context, nullptr, 0); if (core == nullptr) { util::error("context connection failed"); } registry = pw_core_get_registry(core, PW_VERSION_REGISTRY, 0); if (registry == nullptr) { util::error("could not get the registry"); } pw_registry_add_listener(registry, &registry_listener, &registry_events, this); pw_core_add_listener(core, &core_listener, &core_events, this); // loading Easy Effects sink pw_properties* props_sink = pw_properties_new(nullptr, nullptr); pw_properties_set(props_sink, PW_KEY_APP_ID, tags::app::id); pw_properties_set(props_sink, PW_KEY_NODE_NAME, tags::pipewire::ee_sink_name); pw_properties_set(props_sink, PW_KEY_NODE_DESCRIPTION, "Easy Effects Sink"); pw_properties_set(props_sink, PW_KEY_NODE_VIRTUAL, "true"); pw_properties_set(props_sink, PW_KEY_NODE_PASSIVE, "out"); pw_properties_set(props_sink, "factory.name", "support.null-audio-sink"); pw_properties_set(props_sink, PW_KEY_MEDIA_CLASS, tags::pipewire::media_class::sink); pw_properties_set(props_sink, "audio.position", "FL,FR"); pw_properties_set(props_sink, "monitor.channel-volumes", "false"); pw_properties_set(props_sink, "monitor.passthrough", "true"); pw_properties_set(props_sink, "priority.session", "0"); proxy_stream_output_sink = static_cast<pw_proxy*>( pw_core_create_object(core, "adapter", PW_TYPE_INTERFACE_Node, PW_VERSION_NODE, &props_sink->dict, 0)); pw_properties_free(props_sink); // loading our source pw_properties* props_source = pw_properties_new(nullptr, nullptr); pw_properties_set(props_source, PW_KEY_APP_ID, tags::app::id); pw_properties_set(props_source, PW_KEY_NODE_NAME, tags::pipewire::ee_source_name); pw_properties_set(props_source, PW_KEY_NODE_DESCRIPTION, "Easy Effects Source"); pw_properties_set(props_source, PW_KEY_NODE_VIRTUAL, "true"); pw_properties_set(props_source, "factory.name", "support.null-audio-sink"); pw_properties_set(props_source, PW_KEY_MEDIA_CLASS, tags::pipewire::media_class::virtual_source); pw_properties_set(props_source, "audio.position", "FL,FR"); pw_properties_set(props_source, "monitor.channel-volumes", "false"); pw_properties_set(props_source, "monitor.passthrough", "true"); pw_properties_set(props_source, "priority.session", "0"); proxy_stream_input_source = static_cast<pw_proxy*>( pw_core_create_object(core, "adapter", PW_TYPE_INTERFACE_Node, PW_VERSION_NODE, &props_source->dict, 0)); pw_properties_free(props_source); sync_wait_unlock(); using namespace std::string_literals; do { std::this_thread::sleep_for(std::chrono::milliseconds(1)); for (const auto& [serial, node] : node_map) { if (ee_sink_node.name.empty() && node.name == tags::pipewire::ee_sink_name) { ee_sink_node = node; util::debug(tags::pipewire::ee_sink_name + " node successfully retrieved with id "s + util::to_string(node.id) + " and serial " + util::to_string(node.serial)); } else if (ee_source_node.name.empty() && node.name == tags::pipewire::ee_source_name) { ee_source_node = node; util::debug(tags::pipewire::ee_source_name + " node successfully retrieved with id "s + util::to_string(node.id) + " and serial " + util::to_string(node.serial)); } } } while (ee_sink_node.id == SPA_ID_INVALID || ee_source_node.id == SPA_ID_INVALID); } PipeManager::~PipeManager() { exiting = true; lock(); spa_hook_remove(&registry_listener); spa_hook_remove(&core_listener); spa_hook_remove(&metadata_listener); if (metadata != nullptr) { pw_proxy_destroy((struct pw_proxy*)metadata); } pw_proxy_destroy(proxy_stream_output_sink); pw_proxy_destroy(proxy_stream_input_source); util::debug("Destroying PipeWire registry..."); pw_proxy_destroy((struct pw_proxy*)registry); util::debug("Disconnecting PipeWire core..."); pw_core_disconnect(core); unlock(); util::debug("Stopping PipeWire's loop..."); pw_thread_loop_stop(thread_loop); util::debug("Destroying PipeWire's context..."); pw_context_destroy(context); util::debug("Destroying PipeWire's loop..."); pw_thread_loop_destroy(thread_loop); } auto PipeManager::node_map_at_id(const uint& id) -> NodeInfo& { // Helper method to access easily a node by id, same functionality as map.at() for (auto& [serial, node] : node_map) { if (node.id == id) { return node; } } throw std::out_of_range("No node with id " + util::to_string(id) + " in our node_map"); } auto PipeManager::stream_is_connected(const uint& id, const std::string& media_class) -> bool { if (media_class == tags::pipewire::media_class::output_stream) { for (const auto& link : list_links) { if (link.output_node_id == id && link.input_node_id == ee_sink_node.id) { return true; } } } else if (media_class == tags::pipewire::media_class::input_stream) { for (const auto& link : list_links) { if (link.output_node_id == ee_source_node.id && link.input_node_id == id) { return true; } } } return false; } void PipeManager::connect_stream_output(const uint& id) const { set_metadata_target_node(id, ee_sink_node.id, ee_sink_node.serial); } void PipeManager::connect_stream_input(const uint& id) const { set_metadata_target_node(id, ee_source_node.id, ee_source_node.serial); } void PipeManager::set_metadata_target_node(const uint& origin_id, const uint& target_id, const uint64_t& target_serial) const { if (metadata == nullptr) { return; } lock(); // target.node for backward compatibility with old PW session managers pw_metadata_set_property(metadata, origin_id, "target.node", "Spa:Id", util::to_string(target_id).c_str()); pw_metadata_set_property(metadata, origin_id, "target.object", "Spa:Id", util::to_string(target_serial).c_str()); sync_wait_unlock(); } void PipeManager::disconnect_stream(const uint& stream_id) const { if (metadata == nullptr) { return; } lock(); // target.node for backward compatibility with old PW session managers pw_metadata_set_property(metadata, stream_id, "target.node", nullptr, nullptr); pw_metadata_set_property(metadata, stream_id, "target.object", nullptr, nullptr); sync_wait_unlock(); } void PipeManager::set_node_volume(pw_proxy* proxy, const uint& n_vol_ch, const float& value) const { std::array<float, SPA_AUDIO_MAX_CHANNELS> volumes{}; std::ranges::fill(volumes, 0.0F); std::fill_n(volumes.begin(), n_vol_ch, value); std::array<char, 1024U> buffer{}; auto builder = SPA_POD_BUILDER_INIT(buffer.data(), sizeof(buffer)); lock(); pw_node_set_param( (struct pw_node*)proxy, SPA_PARAM_Props, 0, (spa_pod*)spa_pod_builder_add_object(&builder, SPA_TYPE_OBJECT_Props, SPA_PARAM_Props, SPA_PROP_channelVolumes, SPA_POD_Array(sizeof(float), SPA_TYPE_Float, n_vol_ch, volumes.data()))); sync_wait_unlock(); } void PipeManager::set_node_mute(pw_proxy* proxy, const bool& state) const { std::array<char, 1024U> buffer{}; auto builder = SPA_POD_BUILDER_INIT(buffer.data(), sizeof(buffer)); lock(); pw_node_set_param((pw_node*)proxy, SPA_PARAM_Props, 0, (spa_pod*)spa_pod_builder_add_object(&builder, SPA_TYPE_OBJECT_Props, SPA_PARAM_Props, SPA_PROP_mute, SPA_POD_Bool(state))); sync_wait_unlock(); } auto PipeManager::count_node_ports(const uint& node_id) -> uint { uint count = 0U; for (const auto& port : list_ports) { if (port.node_id == node_id) { count++; } } return count; } auto PipeManager::link_nodes(const uint& output_node_id, const uint& input_node_id, const bool& probe_link, const bool& link_passive) -> std::vector<pw_proxy*> { std::vector<pw_proxy*> list; std::vector<PortInfo> list_output_ports; std::vector<PortInfo> list_input_ports; auto use_audio_channel = true; for (const auto& port : list_ports) { if (port.node_id == output_node_id && port.direction == "out") { list_output_ports.push_back(port); if (!probe_link) { if (port.audio_channel != "FL" && port.audio_channel != "FR") { use_audio_channel = false; } } } if (port.node_id == input_node_id && port.direction == "in") { if (!probe_link) { list_input_ports.push_back(port); if (port.audio_channel != "FL" && port.audio_channel != "FR") { use_audio_channel = false; } } else { if (port.audio_channel == "PROBE_FL" || port.audio_channel == "PROBE_FR") { list_input_ports.push_back(port); } } } } if (list_input_ports.empty()) { util::debug("node " + util::to_string(input_node_id) + " has no input ports yet. Aborting the link"); return list; } if (list_output_ports.empty()) { util::debug("node " + util::to_string(output_node_id) + " has no output ports yet. Aborting the link"); return list; } for (const auto& outp : list_output_ports) { for (const auto& inp : list_input_ports) { bool ports_match = false; if (!probe_link) { if (use_audio_channel) { ports_match = outp.audio_channel == inp.audio_channel; } else { ports_match = outp.port_id == inp.port_id; } } else { if (outp.audio_channel == "FL" && inp.audio_channel == "PROBE_FL") { ports_match = true; } if (outp.audio_channel == "FR" && inp.audio_channel == "PROBE_FR") { ports_match = true; } } if (ports_match) { pw_properties* props = pw_properties_new(nullptr, nullptr); pw_properties_set(props, PW_KEY_LINK_PASSIVE, (link_passive) ? "true" : "false"); pw_properties_set(props, PW_KEY_OBJECT_LINGER, "false"); pw_properties_set(props, PW_KEY_LINK_OUTPUT_NODE, util::to_string(output_node_id).c_str()); pw_properties_set(props, PW_KEY_LINK_OUTPUT_PORT, util::to_string(outp.id).c_str()); pw_properties_set(props, PW_KEY_LINK_INPUT_NODE, util::to_string(input_node_id).c_str()); pw_properties_set(props, PW_KEY_LINK_INPUT_PORT, util::to_string(inp.id).c_str()); lock(); auto* proxy = static_cast<pw_proxy*>( pw_core_create_object(core, "link-factory", PW_TYPE_INTERFACE_Link, PW_VERSION_LINK, &props->dict, 0)); pw_properties_free(props); if (proxy == nullptr) { util::warning("failed to link the node " + util::to_string(output_node_id) + " to " + util::to_string(input_node_id)); unlock(); return list; } sync_wait_unlock(); list.push_back(proxy); } } } return list; } void PipeManager::lock() const { pw_thread_loop_lock(thread_loop); } void PipeManager::unlock() const { pw_thread_loop_unlock(thread_loop); } void PipeManager::sync_wait_unlock() const { pw_core_sync(core, PW_ID_CORE, 0); pw_thread_loop_wait(thread_loop); pw_thread_loop_unlock(thread_loop); } auto PipeManager::wait_full() const -> int { timespec abstime; pw_thread_loop_get_time(thread_loop, &abstime, 30 * SPA_NSEC_PER_SEC); return pw_thread_loop_timed_wait_full(thread_loop, &abstime); } void PipeManager::destroy_object(const int& id) const { lock(); pw_registry_destroy(registry, id); sync_wait_unlock(); } void PipeManager::destroy_links(const std::vector<pw_proxy*>& list) const { for (auto* proxy : list) { if (proxy != nullptr) { lock(); pw_proxy_destroy(proxy); sync_wait_unlock(); } } } /* Function inspired by code present in PipeWire's sources: https://gitlab.freedesktop.org/pipewire/pipewire/-/blob/master/spa/include/spa/utils/json.h#L350 */ auto PipeManager::json_object_find(const char* obj, const char* key, char* value, const size_t& len) -> int { const char* v = nullptr; std::array<spa_json, 2U> sjson{}; std::array<char, 128U> res{}; spa_json_init(sjson.data(), obj, strlen(obj)); if (spa_json_enter_object(sjson.data(), sjson.data() + 1) <= 0) { return -EINVAL; } while (spa_json_get_string(sjson.data() + 1, res.data(), res.size() * sizeof(char) - 1) > 0) { if (g_strcmp0(res.data(), key) == 0) { if (spa_json_get_string(sjson.data() + 1, value, static_cast<int>(len)) <= 0) { continue; } return 0; } if (spa_json_next(sjson.data() + 1, &v) <= 0) { break; } } return -ENOENT; }
60,586
C++
.cpp
1,467
34.078391
120
0.608716
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,619
application.cpp
wwmm_easyeffects/src/application.cpp
/* * 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/>. */ #include "application.hpp" #include <adwaita.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <spa/param/param.h> #include <spa/utils/defs.h> #include <array> #include <cstdlib> #include <iostream> #include <ostream> #include <string> #include <thread> #include "application_ui.hpp" #include "config.h" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "preferences_window.hpp" #include "preset_type.hpp" #include "presets_manager.hpp" #include "stream_input_effects.hpp" #include "stream_output_effects.hpp" #include "tags_app.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "util.hpp" namespace app { using namespace std::string_literals; // NOLINTNEXTLINE G_DEFINE_TYPE(Application, application, ADW_TYPE_APPLICATION) void hide_all_windows(GApplication* app) { auto* list = gtk_application_get_windows(GTK_APPLICATION(app)); while (list != nullptr) { auto* window = list->data; auto* next = list->next; gtk_window_destroy(GTK_WINDOW(window)); list = next; } } void update_bypass_state(Application* self) { const auto state = g_settings_get_boolean(self->settings, "bypass"); self->soe->set_bypass(state != 0); self->sie->set_bypass(state != 0); util::info(((state) != 0 ? "enabling" : "disabling") + " global bypass"s); } void on_startup(GApplication* gapp) { G_APPLICATION_CLASS(application_parent_class)->startup(gapp); auto* self = EE_APP(gapp); self->data = new Data(); self->sie_settings = g_settings_new(tags::schema::id_input); self->soe_settings = g_settings_new(tags::schema::id_output); self->pm = new PipeManager(); self->soe = new StreamOutputEffects(self->pm); self->sie = new StreamInputEffects(self->pm); if (self->settings == nullptr) { self->settings = g_settings_new(tags::app::id); } if (self->presets_manager == nullptr) { self->presets_manager = new PresetsManager(); } PipeManager::exclude_monitor_stream = g_settings_get_boolean(self->settings, "exclude-monitor-streams") != 0; self->data->connections.push_back(self->pm->new_default_sink_name.connect([=](const std::string name) { util::debug("new default output device: " + name); if (g_settings_get_boolean(self->soe_settings, "use-default-output-device") != 0) { g_settings_set_string(self->soe_settings, "output-device", name.c_str()); } })); self->data->connections.push_back(self->pm->new_default_source_name.connect([=](const std::string name) { util::debug("new default input device: " + name); if (g_settings_get_boolean(self->sie_settings, "use-default-input-device") != 0) { g_settings_set_string(self->sie_settings, "input-device", name.c_str()); } })); self->data->connections.push_back(self->pm->device_input_route_changed.connect([=](const DeviceInfo device) { if (device.input_route_available == SPA_PARAM_AVAILABILITY_no) { return; } util::debug("input autoloading: device \"" + device.name + "\" has changed its input route to \"" + device.input_route_name + "\""); const auto name = util::gsettings_get_string(self->sie_settings, "input-device"); for (const auto& [serial, node] : self->pm->node_map) { if (node.media_class == tags::pipewire::media_class::source && node.device_id == device.id && node.name == name) { util::debug("input autoloading: target node \"" + name + "\" matches the input device name"); self->presets_manager->autoload(PresetType::input, node.name, device.input_route_name); return; } else { util::debug("input autoloading: skip \"" + node.name + "\" candidate since it does not match \"" + name + "\" input device"); } } util::debug("input autoloading: no target nodes match the input device name \"" + name + "\""); })); self->data->connections.push_back(self->pm->device_output_route_changed.connect([=](const DeviceInfo device) { if (device.output_route_available == SPA_PARAM_AVAILABILITY_no) { return; } util::debug("output autoloading: device \"" + device.name + "\" has changed its output route to \"" + device.output_route_name + "\""); const auto name = util::gsettings_get_string(self->soe_settings, "output-device"); for (const auto& [serial, node] : self->pm->node_map) { if (node.media_class == tags::pipewire::media_class::sink && node.device_id == device.id && node.name == name) { util::debug("output autoloading: target node \"" + name + "\" matches the output device name"); self->presets_manager->autoload(PresetType::output, node.name, device.output_route_name); return; } else { util::debug("output autoloading: skip \"" + node.name + "\" candidate since it does not match \"" + name + "\" output device"); } } util::debug("output autoloading: no target nodes match the output device name \"" + name + "\""); })); self->data->gconnections_soe.push_back(g_signal_connect( self->soe_settings, "changed::output-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Application*>(user_data); const auto name = util::gsettings_get_string(settings, key); if (name.empty()) { return; } for (const auto& device : self->pm->list_devices) { if (util::str_contains(name, device.bus_path) || util::str_contains(name, device.bus_id)) { self->presets_manager->autoload(PresetType::output, name, device.output_route_name); return; } } }), self)); self->data->gconnections_sie.push_back(g_signal_connect( self->sie_settings, "changed::input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Application*>(user_data); const auto name = util::gsettings_get_string(settings, key); if (name.empty()) { return; } for (const auto& device : self->pm->list_devices) { if (util::str_contains(name, device.bus_path) || util::str_contains(name, device.bus_id)) { self->presets_manager->autoload(PresetType::input, name, device.input_route_name); return; } } }), self)); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::bypass", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Application*>(user_data); update_bypass_state(self); }), self)); self->data->gconnections.push_back( g_signal_connect(self->settings, "changed::exclude-monitor-streams", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { PipeManager::exclude_monitor_stream = g_settings_get_boolean(settings, key) != 0; }), self)); update_bypass_state(self); if ((g_application_get_flags(gapp) & G_APPLICATION_IS_SERVICE) != 0) { g_application_hold(gapp); } // Debug check PipeWire minimum version const auto comparison_result = util::compare_versions(self->pm->version, tags::app::minimum_pw_version); switch (comparison_result) { case 1: case 0: // Supported version. Nothing to show... break; case -1: util::warning("PipeWire version " + self->pm->version + " is lower than " + tags::app::minimum_pw_version + " minimum supported."); break; default: util::debug("Cannot check the current PipeWire version against the minimum supported."); break; } } void application_class_init(ApplicationClass* klass) { auto* application_class = G_APPLICATION_CLASS(klass); application_class->handle_local_options = [](GApplication* gapp, GVariantDict* options) { if (options == nullptr) { return -1; } auto* self = EE_APP(gapp); if (self->settings == nullptr) { self->settings = g_settings_new(tags::app::id); } if (self->presets_manager == nullptr) { self->presets_manager = new PresetsManager(); } if (g_variant_dict_contains(options, "version") != 0) { std::cout << "easyeffects version: " << std::string(VERSION) << '\n'; return EXIT_SUCCESS; } if (g_variant_dict_contains(options, "presets") != 0) { std::string list; for (const auto& name : self->presets_manager->get_local_presets_name(PresetType::output)) { list += name + ","; } std::cout << _("Output Presets") + ": "s + list << '\n'; list = ""; for (const auto& name : self->presets_manager->get_local_presets_name(PresetType::input)) { list += name + ","; } std::cout << _("Input Presets") + ": "s + list << '\n'; return EXIT_SUCCESS; } if (g_variant_dict_contains(options, "bypass") != 0) { if (int bypass_arg = 2; g_variant_dict_lookup(options, "bypass", "i", &bypass_arg)) { if (bypass_arg == 3) { std::cout << g_settings_get_boolean(self->settings, "bypass") << '\n'; return EXIT_SUCCESS; } } } return -1; }; application_class->startup = on_startup; application_class->command_line = [](GApplication* gapp, GApplicationCommandLine* cmdline) { auto* self = EE_APP(gapp); GVariantDict* options = g_application_command_line_get_options_dict(cmdline); if (g_variant_dict_contains(options, "quit") != 0) { hide_all_windows(gapp); g_application_quit(G_APPLICATION(gapp)); return EXIT_SUCCESS; } if (g_variant_dict_contains(options, "load-preset") != 0) { const char* name = nullptr; if (g_variant_dict_lookup(options, "load-preset", "&s", &name) != 0) { if (self->presets_manager->preset_file_exists(PresetType::input, name)) { self->presets_manager->load_local_preset_file(PresetType::input, name); return EXIT_SUCCESS; } if (self->presets_manager->preset_file_exists(PresetType::output, name)) { self->presets_manager->load_local_preset_file(PresetType::output, name); return EXIT_SUCCESS; } } } if (g_variant_dict_contains(options, "reset") != 0) { util::reset_all_keys_except(self->settings); self->soe->reset_settings(); self->sie->reset_settings(); util::info("All settings were reset"); return EXIT_SUCCESS; } if (g_variant_dict_contains(options, "hide-window") != 0) { hide_all_windows(gapp); util::info("Hiding the window..."); return EXIT_SUCCESS; } if (g_variant_dict_contains(options, "bypass") != 0) { if (int bypass_arg = 2; g_variant_dict_lookup(options, "bypass", "i", &bypass_arg)) { if (bypass_arg == 1) { g_settings_set_boolean(self->settings, "bypass", 1); } else if (bypass_arg == 2) { g_settings_set_boolean(self->settings, "bypass", 0); } return EXIT_SUCCESS; } } g_application_activate(gapp); return G_APPLICATION_CLASS(application_parent_class)->command_line(gapp, cmdline); }; application_class->activate = [](GApplication* gapp) { if (gtk_application_get_active_window(GTK_APPLICATION(gapp)) == nullptr) { G_APPLICATION_CLASS(application_parent_class)->activate(gapp); auto* window = ui::application_window::create(gapp); gtk_window_present(GTK_WINDOW(window)); } }; application_class->shutdown = [](GApplication* gapp) { G_APPLICATION_CLASS(application_parent_class)->shutdown(gapp); auto* self = EE_APP(gapp); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } for (auto& handler_id : self->data->gconnections_sie) { g_signal_handler_disconnect(self->sie_settings, handler_id); } for (auto& handler_id : self->data->gconnections_soe) { g_signal_handler_disconnect(self->soe_settings, handler_id); } self->data->connections.clear(); self->data->gconnections_sie.clear(); self->data->gconnections_soe.clear(); g_object_unref(self->settings); g_object_unref(self->sie_settings); g_object_unref(self->soe_settings); PipeManager::exiting = true; delete self->data; delete self->presets_manager; delete self->sie; delete self->soe; delete self->pm; self->data = nullptr; self->presets_manager = nullptr; self->sie = nullptr; self->soe = nullptr; self->pm = nullptr; util::debug("Shutting down..."); }; } void application_init(Application* self) { std::array<GActionEntry, 8> entries{}; entries[0] = {"quit", [](GSimpleAction* action, GVariant* parameter, gpointer app) { util::debug("The user pressed <Ctrl>Q or executed a similar action. Our process will exit."); g_application_quit(G_APPLICATION(app)); }, nullptr, nullptr, nullptr}; entries[1] = {"help", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { /* It isn't secure to call std::system but it is the only way to make our help to be shown for KDE users. */ if (g_strcmp0(std::getenv("XDG_SESSION_DESKTOP"), "KDE") == 0 || g_strcmp0(std::getenv("XDG_CURRENT_DESKTOP"), "KDE") == 0) { std::thread t([]() { return std::system("yelp help:easyeffects"); }); t.detach(); return; } auto* parent = gtk_application_get_active_window(GTK_APPLICATION(gapp)); auto* launcher = gtk_uri_launcher_new("help:easyeffects"); gtk_uri_launcher_launch(launcher, parent, nullptr, nullptr, nullptr); g_object_unref(launcher); }, nullptr, nullptr, nullptr}; entries[2] = { "about", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { std::array<const char*, 4> developers = {"Wellington Wallace <wellingtonwallace@gmail.com>", "Giusy Digital <kurmikon@libero.it>", "Vincent Chernin", nullptr}; std::array<const char*, 3> documenters = {"Wellington Wallace <wellingtonwallace@gmail.com>", "Giusy Digital <kurmikon@libero.it>", nullptr}; adw_show_about_dialog(GTK_WIDGET(gtk_application_get_active_window(GTK_APPLICATION(gapp))), "application-name", APP_NAME, "version", VERSION, "developer-name", "Wellington Wallace", "developers", developers.data(), "application-icon", IS_DEVEL_BUILD ? std::string(tags::app::id).append(".Devel").c_str() : tags::app::id, "copyright", "Copyright © 2017–2022 Easy Effects Contributors", "license-type", GTK_LICENSE_GPL_3_0, "website", "https://github.com/wwmm/easyeffects", "debug-info", std::string("Commit: ").append(COMMIT_DESC).c_str(), "translator-credits", _("Weblate https://hosted.weblate.org/projects/easyeffects/"), "documenters", documenters.data(), "issue-url", "https://github.com/wwmm/easyeffects/issues", nullptr); }, nullptr, nullptr, nullptr}; entries[3] = {"fullscreen", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { auto* self = EE_APP(gapp); auto state = g_settings_get_boolean(self->settings, "window-fullscreen") != 0; if (state) { gtk_window_unfullscreen(GTK_WINDOW(gtk_application_get_active_window(GTK_APPLICATION(gapp)))); g_settings_set_boolean(self->settings, "window-fullscreen", 0); } else { gtk_window_fullscreen(GTK_WINDOW(gtk_application_get_active_window(GTK_APPLICATION(gapp)))); g_settings_set_boolean(self->settings, "window-fullscreen", 1); } }, nullptr, nullptr, nullptr}; entries[4] = {"preferences", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { auto* preferences = ui::preferences::window::create(); adw_dialog_present(ADW_DIALOG(preferences), GTK_WIDGET(gtk_application_get_active_window(GTK_APPLICATION(gapp)))); }, nullptr, nullptr, nullptr}; entries[5] = {"reset", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { auto* self = EE_APP(gapp); util::reset_all_keys_except(self->settings); self->soe->reset_settings(); self->sie->reset_settings(); }, nullptr, nullptr, nullptr}; entries[6] = {"shortcuts", [](GSimpleAction* action, GVariant* parameter, gpointer gapp) { auto* builder = gtk_builder_new_from_resource(tags::resources::shortcuts_ui); auto* window = GTK_SHORTCUTS_WINDOW(gtk_builder_get_object(builder, "window")); gtk_window_set_transient_for(GTK_WINDOW(window), GTK_WINDOW(gtk_application_get_active_window(GTK_APPLICATION(gapp)))); gtk_window_present(GTK_WINDOW(window)); g_object_unref(builder); }, nullptr, nullptr, nullptr}; entries[7] = {"hide_windows", [](GSimpleAction* action, GVariant* parameter, gpointer app) { util::debug("The user pressed <Ctrl>W or executed a similar action. Hiding our window."); hide_all_windows(G_APPLICATION(app)); }, nullptr, nullptr, nullptr}; g_action_map_add_action_entries(G_ACTION_MAP(self), entries.data(), entries.size(), self); std::array<const char*, 2> quit_accels = {"<Ctrl>Q", nullptr}; std::array<const char*, 2> hide_windows_accels = {"<Ctrl>W", nullptr}; std::array<const char*, 2> help_accels = {"F1", nullptr}; std::array<const char*, 2> fullscreen_accels = {"F11", nullptr}; gtk_application_set_accels_for_action(GTK_APPLICATION(self), "app.quit", quit_accels.data()); gtk_application_set_accels_for_action(GTK_APPLICATION(self), "app.hide_windows", hide_windows_accels.data()); gtk_application_set_accels_for_action(GTK_APPLICATION(self), "app.help", help_accels.data()); gtk_application_set_accels_for_action(GTK_APPLICATION(self), "app.fullscreen", fullscreen_accels.data()); } auto application_new() -> GApplication* { g_set_application_name("Easy Effects"); auto* app = g_object_new(EE_TYPE_APPLICATION, "application-id", IS_DEVEL_BUILD ? std::string(tags::app::id).append(".Devel").c_str() : tags::app::id, "flags", G_APPLICATION_HANDLES_COMMAND_LINE, nullptr); g_application_add_main_option(G_APPLICATION(app), "quit", 'q', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, _("Quit Easy Effects. Useful when running in service mode."), nullptr); g_application_add_main_option(G_APPLICATION(app), "version", 'v', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, _("Print the easyeffects version"), nullptr); g_application_add_main_option(G_APPLICATION(app), "reset", 'r', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, _("Reset Easy Effects."), nullptr); g_application_add_main_option(G_APPLICATION(app), "hide-window", 'w', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, _("Hide the Window."), nullptr); g_application_add_main_option(G_APPLICATION(app), "bypass", 'b', G_OPTION_FLAG_NONE, G_OPTION_ARG_INT, _("Global bypass. 1 to enable, 2 to disable and 3 to get status"), nullptr); g_application_add_main_option(G_APPLICATION(app), "presets", 'p', G_OPTION_FLAG_NONE, G_OPTION_ARG_NONE, _("Show available presets."), nullptr); g_application_add_main_option(G_APPLICATION(app), "load-preset", 'l', G_OPTION_FLAG_NONE, G_OPTION_ARG_STRING, _("Load a preset. Example: easyeffects -l music"), nullptr); return G_APPLICATION(app); } } // namespace app
21,728
C++
.cpp
443
40.117381
120
0.614503
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,620
fir_filter_lowpass.cpp
wwmm_easyeffects/src/fir_filter_lowpass.cpp
/* * 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/>. */ #include "fir_filter_lowpass.hpp" #include <string> #include <utility> #include "fir_filter_base.hpp" FirFilterLowpass::FirFilterLowpass(std::string tag) : FirFilterBase(std::move(tag)) {} FirFilterLowpass::~FirFilterLowpass() = default; void FirFilterLowpass::setup() { kernel = create_lowpass_kernel(max_frequency, transition_band); delay = 0.5F * static_cast<float>(kernel.size() - 1U) / static_cast<float>(rate); setup_zita(); }
1,198
C++
.cpp
29
39.310345
86
0.748065
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,621
pipe_manager_box.cpp
wwmm_easyeffects/src/pipe_manager_box.cpp
/* * 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/>. */ #include "pipe_manager_box.hpp" #include <fmt/format.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtkexpression.h> #include <gtk/gtknoselection.h> #include <gtk/gtkshortcut.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <nlohmann/json_fwd.hpp> #include <string> #include <vector> #include "application.hpp" #include "client_info_holder.hpp" #include "module_info_holder.hpp" #include "node_info_holder.hpp" #include "pipe_objects.hpp" #include "preset_type.hpp" #include "presets_autoloading_holder.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "test_signals.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::pipe_manager_box { using namespace std::string_literals; struct Data { public: ~Data() { util::debug("data struct destroyed"); } app::Application* application; std::unique_ptr<TestSignals> ts; std::vector<sigc::connection> connections; std::vector<gulong> gconnections_sie, gconnections_soe; }; struct _PipeManagerBox { GtkBox parent_instance; GtkSwitch *use_default_input, *use_default_output, *enable_test_signal; GtkDropDown *dropdown_input_devices, *dropdown_output_devices, *dropdown_autoloading_output_devices, *dropdown_autoloading_input_devices, *dropdown_autoloading_output_presets, *dropdown_autoloading_input_presets; GtkListView *listview_modules, *listview_clients, *listview_autoloading_output, *listview_autoloading_input; GtkButton *autoloading_add_input_profile, *autoloading_add_output_profile; GtkLabel *header_version, *library_version, *core_version, *quantum, *max_quantum, *min_quantum, *server_rate; GtkSpinButton* spinbutton_test_signal_frequency; GListStore *input_devices_model, *output_devices_model, *modules_model, *clients_model, *autoloading_input_model, *autoloading_output_model, *autoloading_input_devices_model, *autoloading_output_devices_model; GtkStringList *input_presets_string_list, *output_presets_string_list; GSettings *sie_settings, *soe_settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PipeManagerBox, pipe_manager_box, GTK_TYPE_BOX) void on_enable_test_signal(PipeManagerBox* self, gboolean state, GtkSwitch* btn) { self->data->ts->set_state(state != 0); } void on_checkbutton_channel_left(PipeManagerBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { self->data->ts->create_left_channel = true; self->data->ts->create_right_channel = false; } } void on_checkbutton_channel_right(PipeManagerBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { self->data->ts->create_left_channel = false; self->data->ts->create_right_channel = true; } } void on_checkbutton_channel_both(PipeManagerBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { self->data->ts->create_left_channel = true; self->data->ts->create_right_channel = true; } } void on_checkbutton_signal_sine(PipeManagerBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { self->data->ts->signal_type = TestSignalType::sine_wave; self->data->ts->sine_phase = 0.0F; } } void on_checkbutton_signal_gaussian(PipeManagerBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { self->data->ts->signal_type = TestSignalType::gaussian; } } void on_autoloading_add_input_profile(PipeManagerBox* self, GtkButton* btn) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>( gtk_drop_down_get_selected_item(self->dropdown_autoloading_input_devices)); if (holder == nullptr) { return; } std::string device_profile; for (const auto& device : self->data->application->pm->list_devices) { if (device.id == holder->info->device_id) { device_profile = device.input_route_name; break; } } // first we remove any autoloading profile associated to the target device so that our ui is updated for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->autoloading_input_model)); n++) { auto* item = static_cast<ui::holders::PresetsAutoloadingHolder*>( g_list_model_get_item(G_LIST_MODEL(self->autoloading_input_model), n)); if (holder->info->name == item->data->device && device_profile == item->data->device_profile) { self->data->application->presets_manager->remove_autoload(PresetType::input, item->data->preset_name, item->data->device, item->data->device_profile); g_object_unref(item); break; } g_object_unref(item); } auto* selected_preset = gtk_drop_down_get_selected_item(self->dropdown_autoloading_input_presets); if (selected_preset == nullptr) { return; } const auto* preset_name = gtk_string_object_get_string(GTK_STRING_OBJECT(selected_preset)); self->data->application->presets_manager->add_autoload(PresetType::input, preset_name, holder->info->name, holder->info->description, device_profile); } void on_autoloading_add_output_profile(PipeManagerBox* self, GtkButton* btn) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>( gtk_drop_down_get_selected_item(self->dropdown_autoloading_output_devices)); if (holder == nullptr) { return; } std::string device_profile; for (const auto& device : self->data->application->pm->list_devices) { if (device.id == holder->info->device_id) { device_profile = device.output_route_name; break; } } // first we remove any autoloading profile associated to the target device so that our ui is updated for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->autoloading_output_model)); n++) { auto* item = static_cast<ui::holders::PresetsAutoloadingHolder*>( g_list_model_get_item(G_LIST_MODEL(self->autoloading_output_model), n)); if (holder->info->name == item->data->device && device_profile == item->data->device_profile) { self->data->application->presets_manager->remove_autoload(PresetType::output, item->data->preset_name, item->data->device, item->data->device_profile); g_object_unref(item); break; } g_object_unref(item); } auto* selected_preset = gtk_drop_down_get_selected_item(self->dropdown_autoloading_output_presets); if (selected_preset == nullptr) { return; } const auto* preset_name = gtk_string_object_get_string(GTK_STRING_OBJECT(selected_preset)); self->data->application->presets_manager->add_autoload(PresetType::output, preset_name, holder->info->name, holder->info->description, device_profile); } void update_modules_info(PipeManagerBox* self) { std::vector<ui::holders::ModuleInfoHolder*> values; for (const auto& info : self->data->application->pm->list_modules) { values.push_back(ui::holders::create(info)); } g_list_store_splice(self->modules_model, 0, g_list_model_get_n_items(G_LIST_MODEL(self->modules_model)), (gpointer*)(values.data()), values.size()); for (auto* holder : values) { g_object_unref(holder); } } void update_clients_info(PipeManagerBox* self) { std::vector<ui::holders::ClientInfoHolder*> values; for (const auto& info : self->data->application->pm->list_clients) { values.push_back(ui::holders::create(info)); } g_list_store_splice(self->clients_model, 0, g_list_model_get_n_items(G_LIST_MODEL(self->clients_model)), (gpointer*)(values.data()), values.size()); for (auto* holder : values) { g_object_unref(holder); } } void on_stack_visible_child_changed(PipeManagerBox* self, GParamSpec* pspec, GtkWidget* stack) { if (const auto* const name = gtk_stack_get_visible_child_name(GTK_STACK(stack)); g_strcmp0(name, "page_modules") == 0) { update_modules_info(self); } else if (g_strcmp0(name, "page_clients") == 0) { update_clients_info(self); } } void setup_listview_modules(PipeManagerBox* self) { auto* selection = gtk_no_selection_new(G_LIST_MODEL(self->modules_model)); gtk_list_view_set_model(self->listview_modules, GTK_SELECTION_MODEL(selection)); g_object_unref(selection); } void setup_listview_clients(PipeManagerBox* self) { auto* selection = gtk_no_selection_new(G_LIST_MODEL(self->clients_model)); gtk_list_view_set_model(self->listview_clients, GTK_SELECTION_MODEL(selection)); g_object_unref(selection); } template <PresetType preset_type> void setup_listview_autoloading(PipeManagerBox* self) { GListStore* model = nullptr; GtkListView* listview = nullptr; if constexpr (preset_type == PresetType::output) { model = self->autoloading_output_model; listview = self->listview_autoloading_output; } else if constexpr (preset_type == PresetType::input) { model = self->autoloading_input_model; listview = self->listview_autoloading_input; } auto* factory = gtk_signal_list_item_factory_new(); // setting the factory callbacks g_signal_connect( factory, "setup", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PipeManagerBox* self) { auto builder = gtk_builder_new_from_resource(tags::resources::autoload_row_ui); auto* top_box = gtk_builder_get_object(builder, "top_box"); g_object_set_data(G_OBJECT(item), "device", gtk_builder_get_object(builder, "device")); g_object_set_data(G_OBJECT(item), "device_description", gtk_builder_get_object(builder, "device_description")); g_object_set_data(G_OBJECT(item), "device_profile", gtk_builder_get_object(builder, "device_profile")); g_object_set_data(G_OBJECT(item), "preset_name", gtk_builder_get_object(builder, "preset_name")); auto* remove = gtk_builder_get_object(builder, "remove"); g_object_set_data(G_OBJECT(item), "remove", remove); gtk_list_item_set_activatable(item, 0); gtk_list_item_set_child(item, GTK_WIDGET(top_box)); g_object_unref(builder); g_signal_connect( remove, "clicked", G_CALLBACK(+[](GtkButton* btn, PipeManagerBox* self) { if (auto* holder = static_cast<ui::holders::PresetsAutoloadingHolder*>(g_object_get_data(G_OBJECT(btn), "holder")); holder != nullptr) { self->data->application->presets_manager->remove_autoload( preset_type, holder->data->preset_name, holder->data->device, holder->data->device_profile); } }), self); }), self); g_signal_connect( factory, "bind", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PipeManagerBox* self) { auto* device = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "device")); auto* device_description = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "device_description")); auto* device_profile = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "device_profile")); auto* preset_name = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "preset_name")); auto* remove = static_cast<GtkButton*>(g_object_get_data(G_OBJECT(item), "remove")); auto* holder = static_cast<ui::holders::PresetsAutoloadingHolder*>(gtk_list_item_get_item(item)); g_object_set_data(G_OBJECT(remove), "holder", holder); gtk_label_set_text(device, holder->data->device.c_str()); gtk_label_set_text(device_description, holder->data->device_description.c_str()); gtk_label_set_text(device_profile, holder->data->device_profile.c_str()); gtk_label_set_text(preset_name, holder->data->preset_name.c_str()); gtk_accessible_update_property(GTK_ACCESSIBLE(remove), GTK_ACCESSIBLE_PROPERTY_LABEL, (_("Remove Autoloading Preset") + " "s + holder->data->preset_name).c_str(), -1); }), self); gtk_list_view_set_factory(listview, factory); g_object_unref(factory); // setting the model const auto profiles = self->data->application->presets_manager->get_autoload_profiles(preset_type); for (const auto& json : profiles) { const auto device = json.value("device", ""); const auto device_description = json.value("device-description", ""); const auto device_profile = json.value("device-profile", ""); const auto preset_name = json.value("preset-name", ""); auto* holder = ui::holders::create(device, device_description, device_profile, preset_name); g_list_store_append(model, holder); g_object_unref(holder); } auto* selection = gtk_no_selection_new(G_LIST_MODEL(model)); gtk_list_view_set_model(listview, GTK_SELECTION_MODEL(selection)); g_object_unref(selection); } template <PresetType preset_type> void setup_dropdown_presets(PipeManagerBox* self) { GtkDropDown* dropdown = nullptr; GtkStringList* string_list = nullptr; if constexpr (preset_type == PresetType::output) { dropdown = self->dropdown_autoloading_output_presets; string_list = self->output_presets_string_list; } else if constexpr (preset_type == PresetType::input) { dropdown = self->dropdown_autoloading_input_presets; string_list = self->input_presets_string_list; } for (const auto& name : self->data->application->presets_manager->get_local_presets_name(preset_type)) { gtk_string_list_append(string_list, name.c_str()); } // sorter auto* sorter = gtk_string_sorter_new(gtk_property_expression_new(GTK_TYPE_STRING_OBJECT, nullptr, "string")); auto* sorter_model = gtk_sort_list_model_new(G_LIST_MODEL(string_list), GTK_SORTER(sorter)); // setting the dropdown model auto* selection = gtk_single_selection_new(G_LIST_MODEL(sorter_model)); gtk_drop_down_set_model(dropdown, G_LIST_MODEL(selection)); g_object_unref(selection); } void setup_dropdown_devices(PipeManagerBox* self, GtkDropDown* dropdown, GListStore* model) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(model)); gtk_drop_down_set_model(dropdown, G_LIST_MODEL(model)); g_object_unref(selection); } void setup(PipeManagerBox* self, app::Application* application) { self->data->application = application; auto* pm = application->pm; self->data->ts = std::make_unique<TestSignals>(pm); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::sink) { auto* holder = ui::holders::create(node); g_list_store_append(self->output_devices_model, holder); g_list_store_append(self->autoloading_output_devices_model, holder); g_object_unref(holder); } else if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_list_store_append(self->autoloading_input_devices_model, holder); g_object_unref(holder); } } int rate = 0; util::str_to_num(std::string(pm->default_clock_rate), rate); gtk_label_set_text(self->header_version, pm->header_version.c_str()); gtk_label_set_text(self->library_version, pm->library_version.c_str()); gtk_label_set_text(self->core_version, pm->version.c_str()); gtk_label_set_text(self->server_rate, fmt::format(ui::get_user_locale(), "{0:Ld} Hz", rate).c_str()); gtk_label_set_text(self->min_quantum, pm->default_min_quantum.c_str()); gtk_label_set_text(self->max_quantum, pm->default_max_quantum.c_str()); gtk_label_set_text(self->quantum, pm->default_quantum.c_str()); setup_listview_modules(self); setup_listview_clients(self); setup_listview_autoloading<PresetType::input>(self); setup_listview_autoloading<PresetType::output>(self); setup_dropdown_devices(self, self->dropdown_input_devices, self->input_devices_model); setup_dropdown_devices(self, self->dropdown_output_devices, self->output_devices_model); setup_dropdown_devices(self, self->dropdown_autoloading_input_devices, self->autoloading_input_devices_model); setup_dropdown_devices(self, self->dropdown_autoloading_output_devices, self->autoloading_output_devices_model); setup_dropdown_presets<PresetType::input>(self); setup_dropdown_presets<PresetType::output>(self); /* This connection is being done here after initializing the dropdowns to avoid unnecessary emittions while EE is initializing */ g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, PipeManagerBox* self) { if (gtk_switch_get_state(self->use_default_input) != 0) { return; } if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->sie_settings, "input-device", holder->info->name.c_str()); } }), self); g_signal_connect(self->dropdown_output_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, PipeManagerBox* self) { if (gtk_switch_get_state(self->use_default_output) != 0) { return; } if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->soe_settings, "output-device", holder->info->name.c_str()); } }), self); // initializing the custom device selection dropdowns to the previoulsly used device { auto* holder_selected = static_cast<ui::holders::NodeInfoHolder*>(gtk_drop_down_get_selected_item(self->dropdown_input_devices)); if (holder_selected != nullptr) { const auto input_device_name = util::gsettings_get_string(self->sie_settings, "input-device"); if (holder_selected->info->name != input_device_name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* item = static_cast<ui::holders::NodeInfoHolder*>( g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (item->info->name == input_device_name) { gtk_drop_down_set_selected(self->dropdown_input_devices, n); g_object_unref(item); break; } g_object_unref(item); } } } } { auto* holder_selected = static_cast<ui::holders::NodeInfoHolder*>(gtk_drop_down_get_selected_item(self->dropdown_output_devices)); if (holder_selected != nullptr) { const auto output_device_name = util::gsettings_get_string(self->soe_settings, "output-device"); if (holder_selected->info->name != output_device_name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_devices_model)); n++) { auto* item = static_cast<ui::holders::NodeInfoHolder*>( g_list_model_get_item(G_LIST_MODEL(self->output_devices_model), n)); if (item->info->name == output_device_name) { gtk_drop_down_set_selected(self->dropdown_output_devices, n); g_object_unref(item); break; } g_object_unref(item); } } } } // signals related to device insertion/removal self->data->connections.push_back(pm->sink_added.connect([=](const NodeInfo& info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->output_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->output_devices_model, holder); g_list_store_append(self->autoloading_output_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->sink_removed.connect([=](const NodeInfo& info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->output_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->output_devices_model, n); g_list_store_remove(self->autoloading_output_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo& info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_list_store_append(self->autoloading_input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo& info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_list_store_remove(self->autoloading_input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); // updating the devices dropdown when the default device is changed self->data->connections.push_back(pm->new_default_sink_name.connect([=](const std::string new_default_device_name) { if (gtk_switch_get_state(self->use_default_output) != 1) { return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->output_devices_model), n)); if (holder->info->name == new_default_device_name) { g_object_unref(holder); gtk_drop_down_set_selected(self->dropdown_output_devices, n); return; } g_object_unref(holder); } })); self->data->connections.push_back(pm->new_default_source_name.connect([=](const std::string new_default_device_name) { if (gtk_switch_get_state(self->use_default_input) != 1) { return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->name == new_default_device_name) { g_object_unref(holder); gtk_drop_down_set_selected(self->dropdown_input_devices, n); return; } g_object_unref(holder); } })); // signals related to presets creation/destruction self->data->connections.push_back( application->presets_manager->user_output_preset_created.connect([=](const std::string& preset_name) { if (preset_name.empty()) { util::warning("can't retrieve information about the preset file"); return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_presets_string_list)); n++) { if (gtk_string_list_get_string(self->output_presets_string_list, n) == preset_name) { return; } } gtk_string_list_append(self->output_presets_string_list, preset_name.c_str()); })); self->data->connections.push_back( application->presets_manager->user_output_preset_removed.connect([=](const std::string& preset_name) { if (preset_name.empty()) { util::warning("can't retrieve information about the preset file"); return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_presets_string_list)); n++) { if (gtk_string_list_get_string(self->output_presets_string_list, n) == preset_name) { gtk_string_list_remove(self->output_presets_string_list, n); return; } } })); self->data->connections.push_back( application->presets_manager->user_input_preset_created.connect([=](const std::string& preset_name) { if (preset_name.empty()) { util::warning("can't retrieve information about the preset file"); return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_presets_string_list)); n++) { if (gtk_string_list_get_string(self->input_presets_string_list, n) == preset_name) { return; } } gtk_string_list_append(self->input_presets_string_list, preset_name.c_str()); })); self->data->connections.push_back( application->presets_manager->user_input_preset_removed.connect([=](const std::string& preset_name) { if (preset_name.empty()) { util::warning("can't retrieve information about the preset file"); return; } for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_presets_string_list)); n++) { if (gtk_string_list_get_string(self->input_presets_string_list, n) == preset_name) { gtk_string_list_remove(self->input_presets_string_list, n); return; } } })); // signals related to autoload profiles self->data->connections.push_back(application->presets_manager->autoload_input_profiles_changed.connect( [=](const std::vector<nlohmann::json>& profiles) { std::vector<ui::holders::PresetsAutoloadingHolder*> list; for (const auto& json : profiles) { const auto device = json.value("device", ""); const auto device_description = json.value("device-description", ""); const auto device_profile = json.value("device-profile", ""); const auto preset_name = json.value("preset-name", ""); list.push_back(ui::holders::create(device, device_description, device_profile, preset_name)); } g_list_store_splice(self->autoloading_input_model, 0, g_list_model_get_n_items(G_LIST_MODEL(self->autoloading_input_model)), (gpointer*)(list.data()), list.size()); for (auto* holder : list) { g_object_unref(holder); } })); self->data->connections.push_back(application->presets_manager->autoload_output_profiles_changed.connect( [=](const std::vector<nlohmann::json>& profiles) { std::vector<ui::holders::PresetsAutoloadingHolder*> list; for (const auto& json : profiles) { const auto device = json.value("device", ""); const auto device_description = json.value("device-description", ""); const auto device_profile = json.value("device-profile", ""); const auto preset_name = json.value("preset-name", ""); list.push_back(ui::holders::create(device, device_description, device_profile, preset_name)); } g_list_store_splice(self->autoloading_output_model, 0, g_list_model_get_n_items(G_LIST_MODEL(self->autoloading_output_model)), (gpointer*)(list.data()), list.size()); for (auto* holder : list) { g_object_unref(holder); } })); } void dispose(GObject* object) { auto* self = EE_PIPE_MANAGER_BOX(object); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections_sie) { g_signal_handler_disconnect(self->sie_settings, handler_id); } for (auto& handler_id : self->data->gconnections_soe) { g_signal_handler_disconnect(self->soe_settings, handler_id); } self->data->connections.clear(); self->data->gconnections_sie.clear(); self->data->gconnections_soe.clear(); g_object_unref(self->sie_settings); g_object_unref(self->soe_settings); util::debug("disposed"); G_OBJECT_CLASS(pipe_manager_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_PIPE_MANAGER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(pipe_manager_box_parent_class)->finalize(object); } void pipe_manager_box_class_init(PipeManagerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::pipe_manager_box_ui); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, use_default_input); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, use_default_output); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, enable_test_signal); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_output_devices); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_autoloading_input_devices); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_autoloading_output_devices); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_autoloading_input_presets); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, dropdown_autoloading_output_presets); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, listview_modules); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, listview_clients); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, listview_autoloading_input); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, listview_autoloading_output); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, autoloading_add_input_profile); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, autoloading_add_output_profile); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, header_version); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, library_version); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, core_version); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, quantum); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, max_quantum); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, min_quantum); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, server_rate); gtk_widget_class_bind_template_child(widget_class, PipeManagerBox, spinbutton_test_signal_frequency); gtk_widget_class_bind_template_callback(widget_class, on_enable_test_signal); gtk_widget_class_bind_template_callback(widget_class, on_checkbutton_channel_left); gtk_widget_class_bind_template_callback(widget_class, on_checkbutton_channel_right); gtk_widget_class_bind_template_callback(widget_class, on_checkbutton_channel_both); gtk_widget_class_bind_template_callback(widget_class, on_checkbutton_signal_sine); gtk_widget_class_bind_template_callback(widget_class, on_checkbutton_signal_gaussian); gtk_widget_class_bind_template_callback(widget_class, on_stack_visible_child_changed); gtk_widget_class_bind_template_callback(widget_class, on_autoloading_add_input_profile); gtk_widget_class_bind_template_callback(widget_class, on_autoloading_add_output_profile); } void pipe_manager_box_init(PipeManagerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_presets_string_list = gtk_string_list_new(nullptr); self->output_presets_string_list = gtk_string_list_new(nullptr); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); self->output_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); self->modules_model = g_list_store_new(ui::holders::module_info_holder_get_type()); self->clients_model = g_list_store_new(ui::holders::client_info_holder_get_type()); self->autoloading_input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); self->autoloading_output_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); self->autoloading_input_model = g_list_store_new(ui::holders::presets_autoloading_holder_get_type()); self->autoloading_output_model = g_list_store_new(ui::holders::presets_autoloading_holder_get_type()); self->sie_settings = g_settings_new(tags::schema::id_input); self->soe_settings = g_settings_new(tags::schema::id_output); prepare_spinbuttons<"Hz">(self->spinbutton_test_signal_frequency); g_settings_bind(self->sie_settings, "use-default-input-device", self->use_default_input, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->soe_settings, "use-default-output-device", self->use_default_output, "active", G_SETTINGS_BIND_DEFAULT); g_signal_connect(self->spinbutton_test_signal_frequency, "value-changed", G_CALLBACK(+[](GtkSpinButton* btn, PipeManagerBox* self) { self->data->ts->set_frequency(static_cast<float>(gtk_spin_button_get_value(btn))); }), self); g_signal_connect( self->use_default_input, "notify::active", G_CALLBACK(+[](GtkSwitch* btn, GParamSpec* pspec, PipeManagerBox* self) { if (gtk_switch_get_active(btn) != 0) { g_settings_set_string(self->sie_settings, "input-device", self->data->application->pm->default_input_device_name.c_str()); auto* holder = static_cast<ui::holders::NodeInfoHolder*>(gtk_drop_down_get_selected_item(self->dropdown_input_devices)); if (holder == nullptr) { return; } if (holder->info->name != self->data->application->pm->default_input_device_name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* item = static_cast<ui::holders::NodeInfoHolder*>( g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (item->info->name == self->data->application->pm->default_input_device_name) { gtk_drop_down_set_selected(self->dropdown_input_devices, n); g_object_unref(item); break; } g_object_unref(item); } } } }), self); g_signal_connect( self->use_default_output, "notify::active", G_CALLBACK(+[](GtkSwitch* btn, GParamSpec* pspec, PipeManagerBox* self) { if (gtk_switch_get_active(btn) != 0) { g_settings_set_string(self->soe_settings, "output-device", self->data->application->pm->default_output_device_name.c_str()); auto* holder = static_cast<ui::holders::NodeInfoHolder*>(gtk_drop_down_get_selected_item(self->dropdown_output_devices)); if (holder == nullptr) { return; } if (holder->info->name != self->data->application->pm->default_output_device_name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->output_devices_model)); n++) { auto* item = static_cast<ui::holders::NodeInfoHolder*>( g_list_model_get_item(G_LIST_MODEL(self->output_devices_model), n)); if (item->info->name == self->data->application->pm->default_output_device_name) { gtk_drop_down_set_selected(self->dropdown_output_devices, n); g_object_unref(item); break; } g_object_unref(item); } } } }), self); } auto create() -> PipeManagerBox* { return static_cast<PipeManagerBox*>(g_object_new(EE_TYPE_PIPE_MANAGER_BOX, nullptr)); } } // namespace ui::pipe_manager_box
38,256
C++
.cpp
739
44.638701
120
0.671204
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,622
app_info.cpp
wwmm_easyeffects/src/app_info.cpp
/* * 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/>. */ #include "app_info.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <fmt/format.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkbox.h> #include <gtk/gtkcheckbutton.h> #include <gtk/gtkicontheme.h> #include <gtk/gtkimage.h> #include <gtk/gtklabel.h> #include <gtk/gtkspinbutton.h> #include <gtk/gtktogglebutton.h> #include <pipewire/node.h> #include <algorithm> #include <array> #include <cctype> #include <cmath> #include <filesystem> #include <string> #include <string_view> #include <unordered_map> #include <utility> #include "application.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_app.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::app_info { using namespace std::string_literals; struct Data { public: ~Data() { util::debug("data struct destroyed"); } app::Application* application; NodeInfo info; gulong handler_id_enable, handler_id_volume, handler_id_mute, handler_id_blocklist; std::unordered_map<uint, bool>* enabled_app_list; }; struct _AppInfo { GtkBox parent_instance; GtkImage* app_icon; GtkLabel *app_name, *media_name, *format, *rate, *channels, *latency, *state; GtkToggleButton* mute; GtkSpinButton* volume; GtkCheckButton *blocklist, *enable; GtkIconTheme* icon_theme; GSettings *settings, *app_settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(AppInfo, app_info, GTK_TYPE_BOX) auto node_state_to_char_pointer(const pw_node_state& state) -> const char* { switch (state) { case PW_NODE_STATE_RUNNING: return _("Running"); case PW_NODE_STATE_SUSPENDED: return _("Suspended"); case PW_NODE_STATE_IDLE: return _("Idle"); case PW_NODE_STATE_CREATING: return _("Creating"); case PW_NODE_STATE_ERROR: return _("Error"); default: return _("Unknown"); } } auto app_is_blocklisted(AppInfo* self, const std::string& name) -> bool { const auto list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "blocklist")); return std::ranges::find(list, name) != list.end(); } auto get_app_icon_name(const NodeInfo& node_info) -> std::string { // map to handle cases where PipeWire does not set icon name string or app name equal to icon name. constexpr auto icon_map = std::to_array<std::pair<const char*, const char*>>({{"chromium-browser", "chromium"}, {"firefox", "firefox"}, {"nightly", "firefox-nightly"}, {"obs", "com.obsproject.Studio"}}); std::string icon_name; if (!node_info.app_icon_name.empty()) { icon_name = node_info.app_icon_name; } else if (!node_info.media_icon_name.empty()) { icon_name = node_info.media_icon_name; } else if (!node_info.name.empty()) { const std::string prefix = "alsa_playback."; if (node_info.name.substr(0, prefix.size()) == prefix) { icon_name = node_info.name.substr(prefix.size()); } else { icon_name = node_info.name; } // get lowercase name so if it changes in the future, we have a chance to pick the same index std::transform(icon_name.begin(), icon_name.end(), icon_name.begin(), [](unsigned char c) { return std::tolower(c); }); } for (const auto& [key, value] : icon_map) { if (key == icon_name) { return value; } } return icon_name; } auto icon_available(AppInfo* self, const std::string& icon_name) -> bool { if (gtk_icon_theme_has_icon(self->icon_theme, icon_name.c_str()) != 0) { return true; } // The icon object can't lookup icons in pixmaps directories, so we check their existence there also. constexpr auto pixmaps_dirs = std::to_array({"/usr/share/pixmaps", "/usr/local/share/pixmaps"}); for (const auto& dir : pixmaps_dirs) { try { for (std::filesystem::directory_iterator it{dir}; it != std::filesystem::directory_iterator{}; ++it) { if (std::filesystem::is_regular_file(it->status())) { if (it->path().stem().string() == icon_name) { util::debug(icon_name + " icon name not included in the icon theme, but found in " + dir); return true; } } } } catch (...) { util::debug("cannot lookup application icon " + icon_name + " in " + dir); } } return false; } void connect_stream(AppInfo* self, const uint& id, const std::string& media_class) { if (media_class == tags::pipewire::media_class::output_stream) { self->data->application->pm->connect_stream_output(id); } else if (media_class == tags::pipewire::media_class::input_stream) { self->data->application->pm->connect_stream_input(id); } } void disconnect_stream(AppInfo* self, const uint& id, const std::string& media_class) { if (media_class == tags::pipewire::media_class::output_stream || media_class == tags::pipewire::media_class::input_stream) { self->data->application->pm->disconnect_stream(id); } } void on_enable(GtkCheckButton* btn, AppInfo* self) { auto is_enabled = gtk_check_button_get_active(btn) != 0; auto is_blocklisted = app_is_blocklisted(self, self->data->info.name); if (!is_blocklisted) { (is_enabled) ? connect_stream(self, self->data->info.id, self->data->info.media_class) : disconnect_stream(self, self->data->info.id, self->data->info.media_class); self->data->enabled_app_list->insert_or_assign(self->data->info.id, is_enabled); } } void on_volume_changed(GtkSpinButton* sbtn, AppInfo* self) { auto vol = static_cast<float>(gtk_spin_button_get_value(sbtn)) / 100.0F; if (g_settings_get_boolean(self->app_settings, "use-cubic-volumes") != 0) { vol = vol * vol * vol; } if (self->data->info.proxy != nullptr) { self->data->application->pm->set_node_volume(self->data->info.proxy, self->data->info.n_volume_channels, vol); } } void on_mute(GtkToggleButton* btn, AppInfo* self) { const auto state = gtk_toggle_button_get_active(btn); if (state != 0) { gtk_button_set_icon_name(GTK_BUTTON(btn), "audio-volume-muted-symbolic"); } else { gtk_button_set_icon_name(GTK_BUTTON(btn), "audio-volume-high-symbolic"); } if (self->data->info.proxy != nullptr) { self->data->application->pm->set_node_mute(self->data->info.proxy, state != 0); } } void on_blocklist(GtkCheckButton* btn, AppInfo* self) { const auto is_blocklisted = gtk_check_button_get_active(btn); std::string app_tag = self->data->info.application_id; if (app_tag.empty()) { app_tag = self->data->info.name; } if (is_blocklisted != 0) { self->data->enabled_app_list->insert_or_assign(self->data->info.id, gtk_check_button_get_active(self->enable)); util::add_new_blocklist_entry(self->settings, app_tag); } else { util::remove_blocklist_entry(self->settings, app_tag); } } void update(AppInfo* self, const NodeInfo node_info) { if (node_info.state == PW_NODE_STATE_CREATING) { // PW_NODE_STATE_CREATING is useless and does not give any meaningful info, therefore skip it return; } self->data->info = node_info; std::string app_name = node_info.app_name; auto isspace = [](std::string_view a) { return std::ranges::all_of(a, [](auto c) { return std::isspace(c); }); }; if (app_name.empty() || isspace(app_name)) { app_name = node_info.name; } if (app_name.empty() || isspace(app_name)) { app_name = node_info.app_process_binary; } if (app_name.empty() || isspace(app_name)) { app_name = node_info.app_process_binary; } if (app_name.empty()) { app_name = _("Undefined Name - Process ID "); app_name.append(node_info.app_process_id); } gtk_label_set_text(self->app_name, app_name.c_str()); gtk_label_set_text(self->media_name, node_info.media_name.c_str()); gtk_label_set_text(self->format, node_info.format.c_str()); gtk_label_set_text( self->rate, fmt::format(ui::get_user_locale(), "{0:.1Lf} kHz", static_cast<float>(node_info.rate) / 1000.0F).c_str()); gtk_label_set_text(self->channels, fmt::format("{0:d} {1}", node_info.n_volume_channels, _("channels")).c_str()); gtk_label_set_text(self->latency, fmt::format("{0:.0f} ms", 1000.0F * node_info.latency).c_str()); gtk_label_set_text(self->state, node_state_to_char_pointer(node_info.state)); // updating the enable toggle button g_signal_handler_block(self->enable, self->data->handler_id_enable); const auto is_enabled = self->data->application->pm->stream_is_connected(node_info.id, node_info.media_class); const auto is_blocklisted = app_is_blocklisted(self, node_info.name); gtk_widget_set_sensitive(GTK_WIDGET(self->enable), static_cast<gboolean>(is_enabled || !is_blocklisted)); gtk_check_button_set_active(self->enable, static_cast<gboolean>(is_enabled)); g_signal_handler_unblock(self->enable, self->data->handler_id_enable); // updating the volume g_signal_handler_block(self->volume, self->data->handler_id_volume); if (g_settings_get_boolean(self->app_settings, "use-cubic-volumes") != 0) { gtk_spin_button_set_value(self->volume, 100.0 * std::cbrt(static_cast<double>(node_info.volume))); } else { gtk_spin_button_set_value(self->volume, 100.0 * static_cast<double>(node_info.volume)); } g_signal_handler_unblock(self->volume, self->data->handler_id_volume); // updating the mute button state g_signal_handler_block(self->mute, self->data->handler_id_mute); if (node_info.mute) { gtk_button_set_icon_name(GTK_BUTTON(self->mute), "audio-volume-muted-symbolic"); } else { gtk_button_set_icon_name(GTK_BUTTON(self->mute), "audio-volume-high-symbolic"); } gtk_toggle_button_set_active(self->mute, static_cast<gboolean>(node_info.mute)); g_signal_handler_unblock(self->mute, self->data->handler_id_mute); // set the icon name if (const auto default_app_icon = "ee-applications-multimedia-symbolic"s; self->icon_theme == nullptr) { gtk_image_set_from_icon_name(self->app_icon, default_app_icon.c_str()); } else if (const auto icon_name = get_app_icon_name(node_info); icon_name.empty()) { gtk_image_set_from_icon_name(self->app_icon, default_app_icon.c_str()); } else if (!icon_available(self, icon_name)) { gtk_image_set_from_icon_name(self->app_icon, default_app_icon.c_str()); } else { gtk_image_set_from_icon_name(self->app_icon, icon_name.c_str()); } // updating the blocklist button state g_signal_handler_block(self->blocklist, self->data->handler_id_blocklist); gtk_check_button_set_active(self->blocklist, static_cast<gboolean>(is_blocklisted)); g_signal_handler_unblock(self->blocklist, self->data->handler_id_blocklist); // save app "enabled state" only the first time when it is not present in the enabled_app_list map if (self->data->enabled_app_list->find(node_info.id) == self->data->enabled_app_list->end()) { self->data->enabled_app_list->insert({node_info.id, is_enabled}); } } void setup(AppInfo* self, app::Application* application, GSettings* settings, GtkIconTheme* icon_theme, std::unordered_map<uint, bool>& enabled_app_list) { self->data->application = application; self->settings = settings; self->icon_theme = icon_theme; self->data->enabled_app_list = &enabled_app_list; } void dispose(GObject* object) { auto* self = EE_APP_INFO(object); g_object_unref(self->app_settings); util::debug(self->data->info.name + " disposed"); G_OBJECT_CLASS(app_info_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_APP_INFO(object); util::debug(self->data->info.name + " finalized"); delete self->data; G_OBJECT_CLASS(app_info_parent_class)->finalize(object); } void app_info_class_init(AppInfoClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::app_info_ui); gtk_widget_class_bind_template_child(widget_class, AppInfo, enable); gtk_widget_class_bind_template_child(widget_class, AppInfo, app_icon); gtk_widget_class_bind_template_child(widget_class, AppInfo, app_name); gtk_widget_class_bind_template_child(widget_class, AppInfo, media_name); gtk_widget_class_bind_template_child(widget_class, AppInfo, format); gtk_widget_class_bind_template_child(widget_class, AppInfo, rate); gtk_widget_class_bind_template_child(widget_class, AppInfo, channels); gtk_widget_class_bind_template_child(widget_class, AppInfo, latency); gtk_widget_class_bind_template_child(widget_class, AppInfo, state); gtk_widget_class_bind_template_child(widget_class, AppInfo, volume); gtk_widget_class_bind_template_child(widget_class, AppInfo, mute); gtk_widget_class_bind_template_child(widget_class, AppInfo, blocklist); } void app_info_init(AppInfo* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->app_settings = g_settings_new(tags::app::id); prepare_spinbuttons<"%">(self->volume); self->data->handler_id_enable = g_signal_connect(self->enable, "toggled", G_CALLBACK(on_enable), self); self->data->handler_id_volume = g_signal_connect(self->volume, "value-changed", G_CALLBACK(on_volume_changed), self); self->data->handler_id_mute = g_signal_connect(self->mute, "toggled", G_CALLBACK(on_mute), self); self->data->handler_id_blocklist = g_signal_connect(self->blocklist, "toggled", G_CALLBACK(on_blocklist), self); } auto create() -> AppInfo* { return static_cast<AppInfo*>(g_object_new(EE_TYPE_APP_INFO, nullptr)); } } // namespace ui::app_info
14,765
C++
.cpp
331
40.293051
119
0.686344
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,623
effects_box.cpp
wwmm_easyeffects/src/effects_box.cpp
/* * 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/>. */ #include "effects_box.hpp" #include <STTypes.h> #include <adwaita.h> #include <fmt/core.h> #include <fmt/format.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gobject/gobject.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gtk/gtk.h> #include <gtk/gtkshortcut.h> #include <sigc++/connection.h> #include <algorithm> #include <cstddef> #include <vector> #include "application.hpp" #include "apps_box.hpp" #include "blocklist_menu.hpp" #include "chart.hpp" #include "effects_base.hpp" #include "pipeline_type.hpp" #include "plugins_box.hpp" #include "tags_app.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace { bool schedule_signal_idle = false; } namespace ui::effects_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } app::Application* application; EffectsBase* effects_base; PipelineType pipeline_type; uint spectrum_rate, spectrum_n_bands; float global_output_level_left, global_output_level_right, pipeline_latency_ms; std::vector<double> spectrum_mag, spectrum_x_axis, spectrum_freqs; std::vector<sigc::connection> connections; std::vector<gulong> gconnections_spectrum; }; struct _EffectsBox { GtkBox parent_instance; AdwViewStack* stack; AdwViewStackPage *apps_box_page, *plugins_box_page; GtkLabel *device_state, *latency_status, *label_global_output_level_left, *label_global_output_level_right; GtkToggleButton* toggle_listen_mic; GtkMenuButton* menubutton_blocklist; GtkImage* saturation_icon; GtkIconTheme* icon_theme; ui::chart::Chart* spectrum_chart; ui::apps_box::AppsBox* appsBox; ui::plugins_box::PluginsBox* pluginsBox; ui::blocklist_menu::BlocklistMenu* blocklist_menu; GSettings *settings_spectrum, *app_settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(EffectsBox, effects_box, GTK_TYPE_BOX) void init_spectrum_frequency_axis(EffectsBox* self) { self->data->spectrum_freqs.resize(self->data->spectrum_n_bands); for (uint n = 0U; n < self->data->spectrum_n_bands; n++) { self->data->spectrum_freqs[n] = 0.5F * static_cast<float>(self->data->spectrum_rate) * static_cast<float>(n) / static_cast<float>(self->data->spectrum_n_bands); } if (!self->data->spectrum_freqs.empty()) { const auto min_freq = static_cast<float>(g_settings_get_int(self->settings_spectrum, "minimum-frequency")); const auto max_freq = static_cast<float>(g_settings_get_int(self->settings_spectrum, "maximum-frequency")); if (min_freq > (max_freq - 100.0F)) { return; } auto log_x_axis = util::logspace(min_freq, max_freq, g_settings_get_int(self->settings_spectrum, "n-points")); self->data->spectrum_x_axis.resize(log_x_axis.size()); self->data->spectrum_mag.resize(log_x_axis.size()); std::copy(log_x_axis.begin(), log_x_axis.end(), self->data->spectrum_x_axis.begin()); ui::chart::set_x_data(self->spectrum_chart, self->data->spectrum_x_axis); } } void setup_spectrum(EffectsBox* self) { self->data->spectrum_rate = 0U; self->data->spectrum_n_bands = 0U; ui::chart::set_color(self->spectrum_chart, util::gsettings_get_color(self->settings_spectrum, "color")); ui::chart::set_axis_labels_color(self->spectrum_chart, util::gsettings_get_color(self->settings_spectrum, "color-axis-labels")); ui::chart::set_fill_bars(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, "fill") != 0); ui::chart::set_dynamic_y_scale(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, "dynamic-y-scale") != 0); ui::chart::set_rounded_corners(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, "rounded-corners") != 0); ui::chart::set_draw_bar_border(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, "show-bar-border") != 0); ui::chart::set_line_width(self->spectrum_chart, static_cast<float>(g_settings_get_double(self->settings_spectrum, "line-width"))); ui::chart::set_chart_scale(self->spectrum_chart, ui::chart::ChartScale::logarithmic); ui::chart::set_x_unit(self->spectrum_chart, "Hz"); ui::chart::set_y_unit(self->spectrum_chart, "dB"); ui::chart::set_n_x_decimals(self->spectrum_chart, 0); ui::chart::set_n_y_decimals(self->spectrum_chart, 1); ui::chart::set_margin(self->spectrum_chart, 0.0F); gtk_widget_set_size_request(GTK_WIDGET(self->spectrum_chart), -1, g_settings_get_int(self->settings_spectrum, "height")); auto chart_type = util::gsettings_get_string(self->settings_spectrum, "type"); if (chart_type == "Bars") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::bar); } else if (chart_type == "Lines") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::line); } else if (chart_type == "Dots") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::dots); } g_settings_bind(self->settings_spectrum, "show", self->spectrum_chart, "visible", G_SETTINGS_BIND_GET); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::color", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_color(self->spectrum_chart, util::gsettings_get_color(self->settings_spectrum, key)); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::color-axis-labels", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_axis_labels_color(self->spectrum_chart, util::gsettings_get_color(self->settings_spectrum, key)); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::fill", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_fill_bars(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, key) != 0); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::dynamic-y-scale", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_dynamic_y_scale(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, key) != 0); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::rounded-corners", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_rounded_corners(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, key) != 0); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::show-bar-border", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_draw_bar_border(self->spectrum_chart, g_settings_get_boolean(self->settings_spectrum, key) != 0); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::line-width", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { ui::chart::set_line_width(self->spectrum_chart, static_cast<float>(g_settings_get_double(self->settings_spectrum, key))); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::height", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { gtk_widget_set_size_request(GTK_WIDGET(self->spectrum_chart), -1, g_settings_get_int(self->settings_spectrum, key)); }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::type", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { auto chart_type = util::gsettings_get_string(self->settings_spectrum, key); if (chart_type == "Bars") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::bar); } else if (chart_type == "Lines") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::line); } else if (chart_type == "Dots") { ui::chart::set_chart_type(self->spectrum_chart, chart::ChartType::dots); } }), self)); self->data->gconnections_spectrum.push_back(g_signal_connect( self->settings_spectrum, "changed::n-points", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { g_object_ref(self); util::idle_add([=]() { init_spectrum_frequency_axis(self); }, [=]() { g_object_unref(self); }); }), self)); self->data->gconnections_spectrum.push_back( g_signal_connect(self->settings_spectrum, "changed::minimum-frequency", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { g_object_ref(self); util::idle_add([=]() { init_spectrum_frequency_axis(self); }, [=]() { g_object_unref(self); }); }), self)); self->data->gconnections_spectrum.push_back( g_signal_connect(self->settings_spectrum, "changed::maximum-frequency", G_CALLBACK(+[](GSettings* settings, char* key, EffectsBox* self) { g_object_ref(self); util::idle_add([=]() { init_spectrum_frequency_axis(self); }, [=]() { g_object_unref(self); }); }), self)); } void stack_visible_child_changed(EffectsBox* self, GParamSpec* pspec, GtkWidget* stack) { const auto* name = adw_view_stack_get_visible_child_name(ADW_VIEW_STACK(stack)); gtk_widget_set_visible(GTK_WIDGET(self->menubutton_blocklist), (g_strcmp0(name, "apps") == 0) ? 1 : 0); if (self->data->pipeline_type == PipelineType::input) { gtk_widget_set_visible(GTK_WIDGET(self->toggle_listen_mic), (g_strcmp0(name, "plugins") == 0) ? 1 : 0); } } void on_listen_mic_toggled(EffectsBox* self, GtkToggleButton* button) { self->data->application->sie->set_listen_to_mic(gtk_toggle_button_get_active(button) != 0); } static gboolean spectrum_data_update(GtkWidget* widget, GdkFrameClock* frame_clock, EffectsBox* self) { if (!ui::chart::get_is_visible(self->spectrum_chart)) { return G_SOURCE_CONTINUE; } if (!schedule_signal_idle) { return G_SOURCE_CONTINUE; } auto [rate, n_bands, magnitudes] = self->data->effects_base->spectrum->compute_magnitudes(); // No new data available, no redraw required. if (rate == 0 || n_bands == 0) { return G_SOURCE_CONTINUE; } if (self->data->spectrum_rate != rate || self->data->spectrum_n_bands != n_bands) { self->data->spectrum_rate = rate; self->data->spectrum_n_bands = n_bands; init_spectrum_frequency_axis(self); } auto* acc = gsl_interp_accel_alloc(); auto* spline = gsl_spline_alloc(gsl_interp_steffen, n_bands); gsl_spline_init(spline, self->data->spectrum_freqs.data(), magnitudes, n_bands); for (size_t n = 0; n < self->data->spectrum_x_axis.size(); n++) { self->data->spectrum_mag[n] = static_cast<float>(gsl_spline_eval(spline, self->data->spectrum_x_axis[n], acc)); } gsl_spline_free(spline); gsl_interp_accel_free(acc); std::ranges::for_each(self->data->spectrum_mag, [](auto& v) { v = 10.0F * std::log10(v); if (!std::isinf(v)) { v = (v > util::minimum_db_level) ? v : util::minimum_db_level; } else { v = util::minimum_db_level; } }); ui::chart::set_y_data(self->spectrum_chart, self->data->spectrum_mag); return G_SOURCE_CONTINUE; } void setup(EffectsBox* self, app::Application* application, PipelineType pipeline_type, GtkIconTheme* icon_theme) { self->data->application = application; self->data->pipeline_type = pipeline_type; self->icon_theme = icon_theme; switch (pipeline_type) { case PipelineType::input: { self->data->effects_base = static_cast<EffectsBase*>(self->data->application->sie); self->apps_box_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->appsBox), "apps", _("Recorders")); adw_view_stack_page_set_icon_name(self->apps_box_page, "media-record-symbolic"); auto set_device_state_label = [=]() { auto source_rate = static_cast<float>(application->pm->ee_source_node.rate) * 0.001F; gtk_label_set_text(self->device_state, fmt::format(ui::get_user_locale(), "{0:.1Lf} kHz", source_rate).c_str()); }; set_device_state_label(); self->data->connections.push_back(application->pm->source_changed.connect([=](const auto nd_info) { if (nd_info.id == application->pm->ee_source_node.id) { set_device_state_label(); } })); break; } case PipelineType::output: { self->data->effects_base = static_cast<EffectsBase*>(self->data->application->soe); self->apps_box_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->appsBox), "apps", _("Players")); adw_view_stack_page_set_icon_name(self->apps_box_page, "multimedia-player-symbolic"); auto set_device_state_label = [=]() { auto sink_rate = static_cast<float>(application->pm->ee_sink_node.rate) * 0.001F; gtk_label_set_text(self->device_state, fmt::format(ui::get_user_locale(), "{0:.1Lf} kHz", sink_rate).c_str()); }; set_device_state_label(); self->data->connections.push_back(application->pm->sink_changed.connect([=](const auto nd_info) { if (nd_info.id == application->pm->ee_sink_node.id) { set_device_state_label(); } })); break; } } self->plugins_box_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->pluginsBox), "plugins", _("Effects")); adw_view_stack_page_set_icon_name(self->plugins_box_page, "emblem-music-symbolic"); // setting up the boxes we added to the stack ui::apps_box::setup(self->appsBox, application, pipeline_type, icon_theme); ui::plugins_box::setup(self->pluginsBox, application, pipeline_type); ui::blocklist_menu::setup(self->blocklist_menu, application, pipeline_type); // output level self->data->connections.push_back( self->data->effects_base->output_level->output_level.connect([=](const float left, const float right) { self->data->global_output_level_left = left; self->data->global_output_level_right = right; if (!schedule_signal_idle) { return; } g_idle_add((GSourceFunc) + [](EffectsBox* self) { if (!schedule_signal_idle) { return G_SOURCE_REMOVE; } gtk_label_set_text(self->label_global_output_level_left, fmt::format("{0:.0f}", self->data->global_output_level_left).c_str()); gtk_label_set_text(self->label_global_output_level_right, fmt::format("{0:.0f}", self->data->global_output_level_right).c_str()); gtk_widget_set_opacity( GTK_WIDGET(self->saturation_icon), (self->data->global_output_level_left > 0.0 || self->data->global_output_level_right > 0.0) ? 1.0 : 0.0); return G_SOURCE_REMOVE; }, self); })); // spectrum array gtk_widget_add_tick_callback(GTK_WIDGET(self->spectrum_chart), (GtkTickCallback)spectrum_data_update, self, NULL); // As we are showing the window we want the filters to send notifications about level meters, etc self->data->effects_base->spectrum->bypass = g_settings_get_boolean(self->settings_spectrum, "show") == 0; self->data->effects_base->output_level->set_post_messages(true); // pipeline latency gtk_label_set_text( self->latency_status, fmt::format(ui::get_user_locale(), " {0:.1Lf} ms", self->data->effects_base->get_pipeline_latency()).c_str()); self->data->connections.push_back(self->data->effects_base->pipeline_latency.connect([=](const float& v) { self->data->pipeline_latency_ms = v; if (!schedule_signal_idle) { return; } g_idle_add( (GSourceFunc) + [](EffectsBox* self) { if (!schedule_signal_idle) { return G_SOURCE_REMOVE; } gtk_label_set_text( self->latency_status, fmt::format(ui::get_user_locale(), " {0:.1Lf} ms", self->data->pipeline_latency_ms).c_str()); return G_SOURCE_REMOVE; }, self); })); } void realize(GtkWidget* widget) { schedule_signal_idle = true; GTK_WIDGET_CLASS(effects_box_parent_class)->realize(widget); } void unroot(GtkWidget* widget) { schedule_signal_idle = false; GTK_WIDGET_CLASS(effects_box_parent_class)->unroot(widget); } void dispose(GObject* object) { auto* self = EE_EFFECTS_BOX(object); schedule_signal_idle = false; self->data->effects_base->spectrum->bypass = true; for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections_spectrum) { g_signal_handler_disconnect(self->settings_spectrum, handler_id); } self->data->connections.clear(); self->data->gconnections_spectrum.clear(); g_object_unref(self->app_settings); g_object_unref(self->settings_spectrum); util::debug("disposed"); G_OBJECT_CLASS(effects_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_EFFECTS_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(effects_box_parent_class)->finalize(object); } void effects_box_class_init(EffectsBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; widget_class->realize = realize; widget_class->unroot = unroot; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::effects_box_ui); gtk_widget_class_bind_template_child(widget_class, EffectsBox, stack); gtk_widget_class_bind_template_child(widget_class, EffectsBox, device_state); gtk_widget_class_bind_template_child(widget_class, EffectsBox, latency_status); gtk_widget_class_bind_template_child(widget_class, EffectsBox, label_global_output_level_left); gtk_widget_class_bind_template_child(widget_class, EffectsBox, label_global_output_level_right); gtk_widget_class_bind_template_child(widget_class, EffectsBox, toggle_listen_mic); gtk_widget_class_bind_template_child(widget_class, EffectsBox, menubutton_blocklist); gtk_widget_class_bind_template_child(widget_class, EffectsBox, saturation_icon); gtk_widget_class_bind_template_callback(widget_class, stack_visible_child_changed); gtk_widget_class_bind_template_callback(widget_class, on_listen_mic_toggled); } void effects_box_init(EffectsBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); schedule_signal_idle = false; self->app_settings = g_settings_new(tags::app::id); self->settings_spectrum = g_settings_new(tags::schema::spectrum::id); self->spectrum_chart = ui::chart::create(); self->appsBox = ui::apps_box::create(); self->pluginsBox = ui::plugins_box::create(); self->blocklist_menu = ui::blocklist_menu::create(); gtk_menu_button_set_popover(self->menubutton_blocklist, GTK_WIDGET(self->blocklist_menu)); setup_spectrum(self); gtk_box_insert_child_after(GTK_BOX(self), GTK_WIDGET(self->spectrum_chart), nullptr); g_signal_connect(GTK_WIDGET(self->spectrum_chart), "show", G_CALLBACK(+[](GtkWidget* widget, EffectsBox* self) { self->data->effects_base->spectrum->bypass = false; }), self); g_signal_connect(GTK_WIDGET(self->spectrum_chart), "hide", G_CALLBACK(+[](GtkWidget* widget, EffectsBox* self) { self->data->effects_base->spectrum->bypass = true; }), self); } auto create() -> EffectsBox* { return static_cast<EffectsBox*>(g_object_new(EE_TYPE_EFFECTS_BOX, nullptr)); } } // namespace ui::effects_box
21,611
C++
.cpp
436
42.594037
120
0.655673
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,624
level_meter_preset.cpp
wwmm_easyeffects/src/level_meter_preset.cpp
/* * 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/>. */ #include "level_meter_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" LevelMeterPreset::LevelMeterPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::level_meter::id, tags::schema::level_meter::input_path, tags::schema::level_meter::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::level_meter).append("#").append(util::to_string(index)); } void LevelMeterPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; } void LevelMeterPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); }
1,702
C++
.cpp
40
38.475
98
0.708082
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,625
multiband_gate_band_box.cpp
wwmm_easyeffects/src/multiband_gate_band_box.cpp
/* * 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/>. */ #include "multiband_gate_band_box.hpp" #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <vector> #include "tags_multiband_gate.hpp" #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::multiband_gate_band_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } int index; std::vector<gulong> gconnections; }; struct _MultibandGateBandBox { GtkBox parent_instance; GtkToggleButton *bypass, *mute, *solo, *external_sidechain, *hysteresis; GtkLabel *end_label, *gain_label, *envelope_label, *curve_label; GtkSpinButton *split_frequency, *lowcut_filter_frequency, *highcut_filter_frequency, *attack_time, *release_time, *hysteresis_threshold, *hysteresis_zone, *curve_threshold, *curve_zone, *reduction, *makeup, *sidechain_preamp, *sidechain_reactivity, *sidechain_lookahead; GtkCheckButton *lowcut_filter, *highcut_filter; GtkDropDown *sidechain_mode, *sidechain_source, *stereo_split_source; GtkBox* split_frequency_box; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(MultibandGateBandBox, multiband_gate_band_box, GTK_TYPE_BOX) void set_end_label(MultibandGateBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->end_label)) { return; } gtk_label_set_text(self->end_label, fmt::format("{0:.0f}", value).c_str()); } void set_envelope_label(MultibandGateBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->envelope_label)) { return; } gtk_label_set_text(self->envelope_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void set_curve_label(MultibandGateBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->curve_label)) { return; } gtk_label_set_text(self->curve_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void set_gain_label(MultibandGateBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->gain_label)) { return; } gtk_label_set_text(self->gain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void setup(MultibandGateBandBox* self, GSettings* settings, int index) { self->data->index = index; self->settings = settings; using namespace tags::multiband_gate; if (index > 0) { g_settings_bind(settings, band_split_frequency[index].data(), gtk_spin_button_get_adjustment(self->split_frequency), "value", G_SETTINGS_BIND_DEFAULT); } else { // removing split frequency from band 0 for (auto* child = gtk_widget_get_last_child(GTK_WIDGET(self->split_frequency_box)); child != nullptr; child = gtk_widget_get_last_child(GTK_WIDGET(self->split_frequency_box))) { gtk_box_remove(self->split_frequency_box, child); } auto* label = gtk_label_new("0 Hz"); gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_CENTER); gtk_box_append(self->split_frequency_box, GTK_WIDGET(label)); } g_settings_bind(self->settings, band_gate_enable[index].data(), self->bypass, "active", G_SETTINGS_BIND_INVERT_BOOLEAN); g_settings_bind(self->settings, band_mute[index].data(), self->mute, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_solo[index].data(), self->solo, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_lowcut_filter[index].data(), self->lowcut_filter, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_highcut_filter[index].data(), self->highcut_filter, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_external_sidechain[index].data(), self->external_sidechain, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_sidechain_mode[index].data(), self->sidechain_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_sidechain_source[index].data(), self->sidechain_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_stereo_split_source[index].data(), self->stereo_split_source); g_settings_bind(settings, band_lowcut_filter_frequency[index].data(), gtk_spin_button_get_adjustment(self->lowcut_filter_frequency), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_highcut_filter_frequency[index].data(), gtk_spin_button_get_adjustment(self->highcut_filter_frequency), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_attack_time[index].data(), gtk_spin_button_get_adjustment(self->attack_time), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_release_time[index].data(), gtk_spin_button_get_adjustment(self->release_time), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_hysteresis[index].data(), self->hysteresis, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_hysteresis_threshold[index].data(), gtk_spin_button_get_adjustment(self->hysteresis_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_hysteresis_zone[index].data(), gtk_spin_button_get_adjustment(self->hysteresis_zone), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_curve_threshold[index].data(), gtk_spin_button_get_adjustment(self->curve_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_curve_zone[index].data(), gtk_spin_button_get_adjustment(self->curve_zone), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_reduction[index].data(), gtk_spin_button_get_adjustment(self->reduction), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_makeup[index].data(), gtk_spin_button_get_adjustment(self->makeup), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_preamp[index].data(), gtk_spin_button_get_adjustment(self->sidechain_preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_reactivity[index].data(), gtk_spin_button_get_adjustment(self->sidechain_reactivity), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_lookahead[index].data(), gtk_spin_button_get_adjustment(self->sidechain_lookahead), "value", G_SETTINGS_BIND_DEFAULT); // bind source dropdowns sensitive property to split-stereo gsettings boolean g_settings_bind(self->settings, "stereo-split", self->sidechain_source, "sensitive", static_cast<GSettingsBindFlags>(G_SETTINGS_BIND_DEFAULT | G_SETTINGS_BIND_INVERT_BOOLEAN)); g_settings_bind(self->settings, "stereo-split", self->stereo_split_source, "sensitive", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_MULTIBAND_GATE_BAND_BOX(object); for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->gconnections.clear(); util::debug("index: " + util::to_string(self->data->index) + " disposed"); G_OBJECT_CLASS(multiband_gate_band_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_MULTIBAND_GATE_BAND_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(multiband_gate_band_box_parent_class)->finalize(object); } void multiband_gate_band_box_class_init(MultibandGateBandBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::multiband_gate_band_ui); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, bypass); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, mute); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, solo); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, external_sidechain); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, end_label); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, gain_label); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, envelope_label); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, curve_label); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, split_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, split_frequency_box); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, lowcut_filter); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, highcut_filter); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, lowcut_filter_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, highcut_filter_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, attack_time); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, release_time); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, hysteresis); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, hysteresis_threshold); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, hysteresis_zone); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, curve_threshold); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, curve_zone); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, reduction); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, makeup); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, sidechain_preamp); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, sidechain_reactivity); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, sidechain_lookahead); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, sidechain_mode); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, sidechain_source); gtk_widget_class_bind_template_child(widget_class, MultibandGateBandBox, stereo_split_source); } void multiband_gate_band_box_init(MultibandGateBandBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"Hz">(self->lowcut_filter_frequency, self->highcut_filter_frequency, self->split_frequency); prepare_spinbuttons<"ms">(self->attack_time, self->release_time, self->sidechain_reactivity, self->sidechain_lookahead); prepare_spinbuttons<"dB">(self->hysteresis_threshold, self->hysteresis_zone, self->curve_threshold, self->curve_zone, self->reduction, self->makeup, self->sidechain_preamp); } auto create() -> MultibandGateBandBox* { return static_cast<MultibandGateBandBox*>(g_object_new(EE_TYPE_MULTIBAND_GATE_BAND_BOX, nullptr)); } } // namespace ui::multiband_gate_band_box
12,425
C++
.cpp
217
52.299539
120
0.732272
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,626
stereo_tools_preset.cpp
wwmm_easyeffects/src/stereo_tools_preset.cpp
/* * 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/>. */ #include "stereo_tools_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" StereoToolsPreset::StereoToolsPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::stereo_tools::id, tags::schema::stereo_tools::input_path, tags::schema::stereo_tools::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::stereo_tools).append("#").append(util::to_string(index)); } void StereoToolsPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["balance-in"] = g_settings_get_double(settings, "balance-in"); json[section][instance_name]["balance-out"] = g_settings_get_double(settings, "balance-out"); json[section][instance_name]["softclip"] = g_settings_get_boolean(settings, "softclip") != 0; json[section][instance_name]["mutel"] = g_settings_get_boolean(settings, "mutel") != 0; json[section][instance_name]["muter"] = g_settings_get_boolean(settings, "muter") != 0; json[section][instance_name]["phasel"] = g_settings_get_boolean(settings, "phasel") != 0; json[section][instance_name]["phaser"] = g_settings_get_boolean(settings, "phaser") != 0; json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["side-level"] = g_settings_get_double(settings, "slev"); json[section][instance_name]["side-balance"] = g_settings_get_double(settings, "sbal"); json[section][instance_name]["middle-level"] = g_settings_get_double(settings, "mlev"); json[section][instance_name]["middle-panorama"] = g_settings_get_double(settings, "mpan"); json[section][instance_name]["stereo-base"] = g_settings_get_double(settings, "stereo-base"); json[section][instance_name]["delay"] = g_settings_get_double(settings, "delay"); json[section][instance_name]["sc-level"] = g_settings_get_double(settings, "sc-level"); json[section][instance_name]["stereo-phase"] = g_settings_get_double(settings, "stereo-phase"); } void StereoToolsPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "balance-in", "balance-in"); update_key<double>(json.at(section).at(instance_name), settings, "balance-out", "balance-out"); update_key<bool>(json.at(section).at(instance_name), settings, "softclip", "softclip"); update_key<bool>(json.at(section).at(instance_name), settings, "mutel", "mutel"); update_key<bool>(json.at(section).at(instance_name), settings, "muter", "muter"); update_key<bool>(json.at(section).at(instance_name), settings, "phasel", "phasel"); update_key<bool>(json.at(section).at(instance_name), settings, "phaser", "phaser"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<double>(json.at(section).at(instance_name), settings, "slev", "side-level"); update_key<double>(json.at(section).at(instance_name), settings, "sbal", "side-balance"); update_key<double>(json.at(section).at(instance_name), settings, "mlev", "middle-level"); update_key<double>(json.at(section).at(instance_name), settings, "mpan", "middle-panorama"); update_key<double>(json.at(section).at(instance_name), settings, "stereo-base", "stereo-base"); update_key<double>(json.at(section).at(instance_name), settings, "delay", "delay"); update_key<double>(json.at(section).at(instance_name), settings, "sc-level", "sc-level"); update_key<double>(json.at(section).at(instance_name), settings, "stereo-phase", "stereo-phase"); }
5,068
C++
.cpp
77
61.818182
99
0.711371
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,627
gate.cpp
wwmm_easyeffects/src/gate.cpp
/* * 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/>. */ #include "gate.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Gate::Gate(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::gate, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_gate_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_gate_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Gate*>(user_data); self->update_sidechain_links(key); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Gate*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"sci", "sidechain-input">(settings); lv2_wrapper->bind_key_enum<"scm", "sidechain-mode">(settings); lv2_wrapper->bind_key_enum<"scs", "sidechain-source">(settings); lv2_wrapper->bind_key_enum<"sscs", "stereo-split-source">(settings); lv2_wrapper->bind_key_enum<"shpm", "hpf-mode">(settings); lv2_wrapper->bind_key_enum<"slpm", "lpf-mode">(settings); lv2_wrapper->bind_key_bool<"ssplit", "stereo-split">(settings); lv2_wrapper->bind_key_bool<"scl", "sidechain-listen">(settings); lv2_wrapper->bind_key_double<"at", "attack">(settings); lv2_wrapper->bind_key_double<"rt", "release">(settings); lv2_wrapper->bind_key_double<"scr", "sidechain-reactivity">(settings); lv2_wrapper->bind_key_double<"sla", "sidechain-lookahead">(settings); lv2_wrapper->bind_key_double<"shpf", "hpf-frequency">(settings); lv2_wrapper->bind_key_double<"slpf", "lpf-frequency">(settings); lv2_wrapper->bind_key_double_db<"gt", "curve-threshold">(settings); lv2_wrapper->bind_key_double_db<"gz", "curve-zone">(settings); lv2_wrapper->bind_key_bool<"gh", "hysteresis">(settings); lv2_wrapper->bind_key_double_db<"ht", "hysteresis-threshold">(settings); lv2_wrapper->bind_key_double_db<"hz", "hysteresis-zone">(settings); lv2_wrapper->bind_key_double_db<"gr", "reduction">(settings); lv2_wrapper->bind_key_double_db<"mk", "makeup">(settings); lv2_wrapper->bind_key_double_db<"scp", "sidechain-preamp">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"cdr", "dry", false>(settings); lv2_wrapper->bind_key_double_db<"cwt", "wet", false>(settings); setup_input_output_gain(); } Gate::~Gate() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Gate::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Gate::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { attack_zone_start_port_value = lv2_wrapper->get_control_port_value("gzs"); attack_threshold_port_value = lv2_wrapper->get_control_port_value("gt"); release_zone_start_port_value = lv2_wrapper->get_control_port_value("hts"); release_threshold_port_value = lv2_wrapper->get_control_port_value("hzs"); reduction_port_value = 0.5F * (lv2_wrapper->get_control_port_value("rlm_l") + lv2_wrapper->get_control_port_value("rlm_r")); sidechain_port_value = 0.5F * (lv2_wrapper->get_control_port_value("slm_l") + lv2_wrapper->get_control_port_value("slm_r")); curve_port_value = 0.5F * (lv2_wrapper->get_control_port_value("clm_l") + lv2_wrapper->get_control_port_value("clm_r")); envelope_port_value = 0.5F * (lv2_wrapper->get_control_port_value("elm_l") + lv2_wrapper->get_control_port_value("elm_r")); attack_zone_start.emit(attack_zone_start_port_value); attack_threshold.emit(attack_threshold_port_value); release_zone_start.emit(release_zone_start_port_value); release_threshold.emit(release_threshold_port_value); reduction.emit(reduction_port_value); sidechain.emit(sidechain_port_value); curve.emit(curve_port_value); envelope.emit(envelope_port_value); notify(); } } } void Gate::update_sidechain_links(const std::string& key) { if (util::gsettings_get_string(settings, "sidechain-input") != "External") { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void Gate::update_probe_links() { update_sidechain_links(""); } auto Gate::get_latency_seconds() -> float { return this->latency_value; }
8,364
C++
.cpp
193
36.170984
111
0.632469
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,628
reverb.cpp
wwmm_easyeffects/src/reverb.cpp
/* * 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/>. */ #include "reverb.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Reverb::Reverb(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::reverb, tags::plugin_package::calf, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://calf.sourceforge.net/plugins/Reverb"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://calf.sourceforge.net/plugins/Reverb is not installed"); } lv2_wrapper->bind_key_double<"decay_time", "decay-time">(settings); lv2_wrapper->bind_key_double<"hf_damp", "hf-damp">(settings); lv2_wrapper->bind_key_double<"diffusion", "diffusion">(settings); lv2_wrapper->bind_key_double<"predelay", "predelay">(settings); lv2_wrapper->bind_key_double<"bass_cut", "bass-cut">(settings); lv2_wrapper->bind_key_double<"treble_cut", "treble-cut">(settings); lv2_wrapper->bind_key_enum<"room_size", "room-size">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"amount", "amount", false>(settings); lv2_wrapper->bind_key_double_db<"dry", "dry", false>(settings); setup_input_output_gain(); } Reverb::~Reverb() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Reverb::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Reverb::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto Reverb::get_latency_seconds() -> float { return 0.0F; }
3,605
C++
.cpp
99
31.424242
96
0.657085
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,629
reverb_ui.cpp
wwmm_easyeffects/src/reverb_ui.cpp
/* * 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/>. */ #include "reverb_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "reverb.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::reverb_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Reverb> reverb; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _ReverbBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkDropDown* room_size; GtkSpinButton *predelay, *decay_time, *diffusion, *dry, *wet, *hf_damp, *bass_cut, *treble_cut; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(ReverbBox, reverb_box, GTK_TYPE_BOX) void on_reset(ReverbBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_preset_room(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 0.445945); g_settings_set_double(self->settings, "hf-damp", 5508.46); g_settings_set_enum(self->settings, "room-size", 4); g_settings_set_double(self->settings, "diffusion", 0.54); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.469761)); g_settings_set_double(self->settings, "dry", util::linear_to_db(1.0)); g_settings_set_double(self->settings, "predelay", 25.0); g_settings_set_double(self->settings, "bass-cut", 257.65); g_settings_set_double(self->settings, "treble-cut", 20000.0); } void on_preset_empty_walls(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 0.505687); g_settings_set_double(self->settings, "hf-damp", 3971.64); g_settings_set_enum(self->settings, "room-size", 4); g_settings_set_double(self->settings, "diffusion", 0.17); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.198884)); g_settings_set_double(self->settings, "dry", util::linear_to_db(1.0)); g_settings_set_double(self->settings, "predelay", 13.0); g_settings_set_double(self->settings, "bass-cut", 240.453); g_settings_set_double(self->settings, "treble-cut", 3303.47); } void on_preset_ambience(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 1.10354); g_settings_set_double(self->settings, "hf-damp", 2182.58); g_settings_set_enum(self->settings, "room-size", 4); g_settings_set_double(self->settings, "diffusion", 0.69); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.291183)); g_settings_set_double(self->settings, "dry", util::linear_to_db(1.0)); g_settings_set_double(self->settings, "predelay", 6.5); g_settings_set_double(self->settings, "bass-cut", 514.079); g_settings_set_double(self->settings, "treble-cut", 4064.15); } void on_preset_large_empty_hall(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 2.00689); g_settings_set_double(self->settings, "hf-damp", 20000.0); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.366022)); g_settings_reset(self->settings, "room-size"); g_settings_reset(self->settings, "diffusion"); g_settings_reset(self->settings, "dry"); g_settings_reset(self->settings, "predelay"); g_settings_reset(self->settings, "bass-cut"); g_settings_reset(self->settings, "treble-cut"); } void on_preset_disco(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 1.0); g_settings_set_double(self->settings, "hf-damp", 3396.49); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.269807)); g_settings_reset(self->settings, "room-size"); g_settings_reset(self->settings, "diffusion"); g_settings_reset(self->settings, "dry"); g_settings_reset(self->settings, "predelay"); g_settings_reset(self->settings, "bass-cut"); g_settings_reset(self->settings, "treble-cut"); } void on_preset_large_occupied_hall(ReverbBox* self, GtkButton* btn) { g_settings_set_double(self->settings, "decay-time", 1.45397); g_settings_set_double(self->settings, "hf-damp", 9795.58); g_settings_set_double(self->settings, "amount", util::linear_to_db(0.184284)); g_settings_reset(self->settings, "room-size"); g_settings_reset(self->settings, "diffusion"); g_settings_reset(self->settings, "dry"); g_settings_reset(self->settings, "predelay"); g_settings_reset(self->settings, "bass-cut"); g_settings_reset(self->settings, "treble-cut"); } void setup(ReverbBox* self, std::shared_ptr<Reverb> reverb, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->reverb = reverb; self->settings = g_settings_new_with_path(tags::schema::reverb::id, schema_path.c_str()); reverb->set_post_messages(true); self->data->connections.push_back(reverb->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(reverb->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->reverb->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "amount", gtk_spin_button_get_adjustment(self->wet), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "predelay", gtk_spin_button_get_adjustment(self->predelay), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "decay-time", gtk_spin_button_get_adjustment(self->decay_time), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "diffusion", gtk_spin_button_get_adjustment(self->diffusion), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "dry", gtk_spin_button_get_adjustment(self->dry), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hf-damp", gtk_spin_button_get_adjustment(self->hf_damp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "bass-cut", gtk_spin_button_get_adjustment(self->bass_cut), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "treble-cut", gtk_spin_button_get_adjustment(self->treble_cut), "value", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "room-size", self->room_size); } void dispose(GObject* object) { auto* self = EE_REVERB_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(reverb_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_REVERB_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(reverb_box_parent_class)->finalize(object); } void reverb_box_class_init(ReverbBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::reverb_ui); gtk_widget_class_bind_template_child(widget_class, ReverbBox, input_gain); gtk_widget_class_bind_template_child(widget_class, ReverbBox, output_gain); gtk_widget_class_bind_template_child(widget_class, ReverbBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, ReverbBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, ReverbBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, ReverbBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, ReverbBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, ReverbBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, ReverbBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, ReverbBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, ReverbBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, ReverbBox, room_size); gtk_widget_class_bind_template_child(widget_class, ReverbBox, predelay); gtk_widget_class_bind_template_child(widget_class, ReverbBox, decay_time); gtk_widget_class_bind_template_child(widget_class, ReverbBox, diffusion); gtk_widget_class_bind_template_child(widget_class, ReverbBox, dry); gtk_widget_class_bind_template_child(widget_class, ReverbBox, wet); gtk_widget_class_bind_template_child(widget_class, ReverbBox, hf_damp); gtk_widget_class_bind_template_child(widget_class, ReverbBox, bass_cut); gtk_widget_class_bind_template_child(widget_class, ReverbBox, treble_cut); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_preset_room); gtk_widget_class_bind_template_callback(widget_class, on_preset_empty_walls); gtk_widget_class_bind_template_callback(widget_class, on_preset_ambience); gtk_widget_class_bind_template_callback(widget_class, on_preset_large_empty_hall); gtk_widget_class_bind_template_callback(widget_class, on_preset_disco); gtk_widget_class_bind_template_callback(widget_class, on_preset_large_occupied_hall); } void reverb_box_init(ReverbBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"Hz">(self->hf_damp, self->bass_cut, self->treble_cut); prepare_spinbuttons<"s">(self->decay_time); prepare_spinbuttons<"ms">(self->predelay); prepare_spinbuttons<"">(self->diffusion); // These spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->wet, self->dry); } auto create() -> ReverbBox* { return static_cast<ReverbBox*>(g_object_new(EE_TYPE_REVERB_BOX, nullptr)); } } // namespace ui::reverb_box
12,346
C++
.cpp
247
46.064777
118
0.715652
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,630
util.cpp
wwmm_easyeffects/src/util.cpp
/* * 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/>. */ #include "util.hpp" #include <gdk/gdk.h> #include <gio/gio.h> #include <gio/gsettingsschema.h> #include <glib-object.h> #include <glib.h> #include <glib/gvariant.h> #include <glib/gvarianttype.h> #include <glibconfig.h> #include <sys/types.h> #include <algorithm> #include <array> #include <cmath> #include <cstring> #include <filesystem> #include <functional> #include <iostream> #include <ostream> #include <regex> #include <sstream> #include <string> #include <thread> #include <utility> #include <vector> namespace util { auto prepare_debug_message(const std::string& message, source_location location) -> std::string { auto file_path = std::filesystem::path{location.file_name()}; std::ostringstream msg_stream; msg_stream << "\t" << file_path.filename().string() << ":" << to_string(location.line()) << "\t" << message; return msg_stream.str(); } void debug(const std::string& s, source_location location) { g_debug(prepare_debug_message(s, location).c_str(), "%s"); } void error(const std::string& s, source_location location) { g_error(prepare_debug_message(s, location).c_str(), "%s"); } void critical(const std::string& s, source_location location) { g_critical(prepare_debug_message(s, location).c_str(), "%s"); } void warning(const std::string& s, source_location location) { g_warning(prepare_debug_message(s, location).c_str(), "%s"); } void info(const std::string& s, source_location location) { g_info(prepare_debug_message(s, location).c_str(), "%s"); } void print_thread_id() { std::cout << "thread id: " << std::this_thread::get_id() << '\n'; } auto normalize(const double& x, const double& max, const double& min) -> double { // Mainly used for gating level bar in gate effects return (x - min) / (max - min); } auto linear_to_db(const float& amp) -> float { if (amp >= minimum_linear_level) { return 20.0F * std::log10(amp); } return minimum_db_level; } auto linear_to_db(const double& amp) -> double { if (amp >= minimum_linear_d_level) { return 20.0 * std::log10(amp); } return minimum_db_d_level; } auto db_to_linear(const float& db) -> float { return std::exp((db / 20.0F) * std::log(10.0F)); } auto db_to_linear(const double& db) -> double { return std::exp((db / 20.0) * std::log(10.0)); } auto db20_gain_to_linear(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { const gfloat v_linear = std::pow(10.0F, static_cast<float>(g_variant_get_double(variant)) / 20.0F); g_value_set_float(value, v_linear); return 1; } auto linear_gain_to_db20(const GValue* value, const GVariantType* expected_type, gpointer user_data) -> GVariant* { const gdouble v_db = 20.0 * std::log10(static_cast<double>(g_value_get_float(value))); return g_variant_new_double(v_db); } auto db10_gain_to_linear(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { const gfloat v_linear = std::pow(10.0F, static_cast<float>(g_variant_get_double(variant)) / 10.0F); g_value_set_float(value, v_linear); return 1; } auto double_to_float(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { g_value_set_float(value, static_cast<gfloat>(g_variant_get_double(variant))); return 1; } auto db20_gain_to_linear_double(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { const gdouble v_linear = std::pow(10.0, g_variant_get_double(variant) / 20.0); g_value_set_double(value, v_linear); return 1; } auto linear_double_gain_to_db20(const GValue* value, const GVariantType* expected_type, gpointer user_data) -> GVariant* { const gdouble v_db = 20.0 * std::log10(g_value_get_double(value)); return g_variant_new_double(v_db); } auto double_x10_to_int(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { g_value_set_int(value, static_cast<gint>(g_variant_get_double(variant) * 10.0)); return 1; } auto ms_to_ns(GValue* value, GVariant* variant, gpointer user_data) -> gboolean { g_value_set_uint64(value, static_cast<guint64>(g_variant_get_double(variant) * 1000000.0)); return 1; } auto remove_filename_extension(const std::string& basename) -> std::string { return basename.substr(0U, basename.find_last_of('.')); } auto gchar_array_to_vector(gchar** gchar_array, const bool free_data) -> std::vector<std::string> { std::vector<std::string> output; if (gchar_array != nullptr) { for (int n = 0; gchar_array[n] != nullptr; n++) { output.emplace_back(gchar_array[n]); } } if (free_data) { g_strfreev(gchar_array); } return output; } auto make_gchar_pointer_vector(const std::vector<std::string>& input) -> std::vector<const gchar*> { std::vector<const gchar*> output; output.reserve(input.size()); for (const auto& v : input) { output.push_back(v.c_str()); } output.push_back(nullptr); // char* arrays passed to g_settings_set_strv must have a null pointer as the last element return output; } auto gsettings_get_color(GSettings* settings, const char* key) -> GdkRGBA { GdkRGBA rgba; std::array<double, 4> color{}; g_settings_get(settings, key, "(dddd)", color.data(), &color[1], &color[2], &color[3]); rgba.red = static_cast<float>(color[0]); rgba.green = static_cast<float>(color[1]); rgba.blue = static_cast<float>(color[2]); rgba.alpha = static_cast<float>(color[3]); return rgba; } auto gsettings_get_string(GSettings* settings, const char* key) -> std::string { auto* s = g_settings_get_string(settings, key); std::string output = s; g_free(s); return output; } // The following is not used and it was made only for reference. May be removed in the future. // GIO recommends to not use g_settings_schema_key_get_range in "normal programs". auto gsettings_get_range(GSettings* settings, const char* key) -> std::pair<std::string, std::string> { GSettingsSchema* schema = nullptr; const gchar* type = nullptr; GVariant* detail = nullptr; std::string min_v; std::string max_v; g_object_get(settings, "settings-schema", &schema, nullptr); auto* schema_key = g_settings_schema_get_key(schema, key); auto* range = g_settings_schema_key_get_range(schema_key); g_variant_get(range, "(&sv)", &type, &detail); if (strcmp(type, "range") == 0) { GVariant* min = nullptr; GVariant* max = nullptr; gchar* smin = nullptr; gchar* smax = nullptr; g_variant_get(detail, "(**)", &min, &max); smin = g_variant_print(min, 0); smax = g_variant_print(max, 0); min_v = smin; max_v = smax; g_variant_unref(min); g_variant_unref(max); g_free(smin); g_free(smax); } g_variant_unref(detail); g_variant_unref(range); g_settings_schema_key_unref(schema_key); g_settings_schema_unref(schema); return {min_v, max_v}; } auto add_new_blocklist_entry(GSettings* settings, const std::string& name) -> bool { if (name.empty()) { return false; } auto list = util::gchar_array_to_vector(g_settings_get_strv(settings, "blocklist")); if (std::any_of(list.cbegin(), list.cend(), [&](const auto& str) { return str == name; })) { util::debug("entry already present in the list"); return false; } list.push_back(name); g_settings_set_strv(settings, "blocklist", util::make_gchar_pointer_vector(list).data()); util::debug("new entry has been added to the blocklist"); return true; } void remove_blocklist_entry(GSettings* settings, const std::string& name) { auto list = util::gchar_array_to_vector(g_settings_get_strv(settings, "blocklist")); list.erase(std::remove_if(list.begin(), list.end(), [=](const auto& a) { return a == name; }), list.end()); g_settings_set_strv(settings, "blocklist", util::make_gchar_pointer_vector(list).data()); util::debug("an entry has been removed from the blocklist"); } void idle_add(std::function<void()> cb, std::function<void()> cleanup_cb) { struct Data { std::function<void()> cb, cleanup_cp; }; auto* d = new Data(); d->cb = std::move(cb); d->cleanup_cp = std::move(cleanup_cb); g_idle_add((GSourceFunc) + [](Data* d) { if (d == nullptr) { return G_SOURCE_REMOVE; } if (d->cb == nullptr) { return G_SOURCE_REMOVE; } d->cb(); d->cleanup_cp(); delete d; return G_SOURCE_REMOVE; }, d); } auto get_files_name(const std::filesystem::path& dir_path, const std::string& ext) -> std::vector<std::string> { std::vector<std::string> names; for (std::filesystem::directory_iterator it{dir_path}; it != std::filesystem::directory_iterator{}; ++it) { if (std::filesystem::is_regular_file(it->status())) { if (it->path().extension() == ext) { names.push_back(it->path().stem().string()); } } } return names; } void reset_all_keys_except(GSettings* settings, const std::vector<std::string>& blocklist, bool delay) { GSettingsSchema* schema = nullptr; g_object_get(settings, "settings-schema", &schema, nullptr); gchar** keys = g_settings_schema_list_keys(schema); /* For some reason the delayed mode breaks the binding between gsettings and the plugins. Until We figure out the reasons delayed mode will be disabled. */ // Gsettings should have a maximum of 256 delayed changes in delay mode (see issue #2215). // If surpassed, the whole application crashes (it happens on the Equalizer). // Anyway we set the maximum at the half (128) for satefy reasons. uint keys_changed = 0U; uint max_changes = 128U; if (delay) { g_settings_delay(settings); } for (int i = 0; keys[i] != nullptr; i++) { if (std::ranges::find(blocklist, keys[i]) != blocklist.end()) { continue; } g_settings_reset(settings, keys[i]); keys_changed++; if (delay && keys_changed >= max_changes) { g_settings_apply(settings); keys_changed = 0U; } } if (delay && keys_changed > 0U) { g_settings_apply(settings); } g_settings_schema_unref(schema); g_strfreev(keys); } auto str_contains(const std::string& haystack, const std::string& needle) -> bool { // This helper indicates if the needle is contained in the haystack string, // but the empty needle will NOT return true. // Instead .find method of C++ string class returns a size_type different // than std::string::npos when the needle is empty indicating that an empty // string IS CONTAINED in the haystack. That's pointless, so here is this helper. if (needle.empty()) { return false; } return (haystack.find(needle) != std::string::npos); } void str_trim_start(std::string& str) { // This util removes whitespaces such as simple space " ", new line "\n", // carriage return "\r", tab "\t", vertical tab "\v" and form feed "\f" // at the start of the given string. // No copy involved, the input string is just modified if needed. str.erase(0U, str.find_first_not_of(" \n\r\t\v\f")); } void str_trim_end(std::string& str) { // Same as above, but at the end of the given string. str.erase(str.find_last_not_of(" \n\r\t\v\f") + 1U); } void str_trim(std::string& str) { // Trim both sides of the given string. See above. str_trim_end(str); str_trim_start(str); } auto search_filename(const std::filesystem::path& path, const std::string& filename, std::string& full_path_result, const uint& top_scan_level) -> bool { // Recursive util to search a filename from an origin full path directory. // The search is performed in subdirectories and it's stopped at a specified // sublevel (top_scan_level = 1 searches only in the path). if (!std::filesystem::exists(path) || !std::filesystem::is_directory(path)) { return false; } const auto fn = path / filename; // Get the file in this directory, if exists. if (std::filesystem::exists(fn) && std::filesystem::is_regular_file(fn)) { // File found, abort the search. full_path_result = fn.c_str(); return true; } // The file is not in this directory, search in subdirectories. const auto scan_level = top_scan_level - 1U; if (scan_level == 0U) { return false; } auto it = std::filesystem::directory_iterator{path}; try { while (it != std::filesystem::directory_iterator{}) { if (std::filesystem::is_directory(it->status())) { if (const auto p = it->path(); !p.empty()) { // Continue the search in the subfolder. const auto found = search_filename(p, filename, full_path_result, scan_level); if (found) { return true; } } } ++it; } } catch (const std::exception& e) { util::warning(e.what()); return false; } return false; } auto compare_versions(const std::string& v0, const std::string& v1) -> int { /* This is an util to compare two strings as semver, mainly used to compare two Pipewire versions. The format should adhere to what is defined at `https://semver.org/`. The additional extension label, if present, is ignored and fortunately we don't need to look at it since Pipewire does not use it. Given two version strings v0 and v1, this util returns an integer: - 0 if the versions are equal; - 1 if v0 is higher than v1; - -1 if v0 is lower than v1; - Whichever other number if the comparison fails (i.e. giving one or both strings not respecting the semver format). */ struct SemVer { int major = -1; int minor = -1; int patch = -1; }; static const auto re_semver = std::regex(R"(^(\d+)\.?(\d+)?\.?(\d+)?)"); std::array<SemVer, 2> sv{}; std::array<std::string, 2> v{v0, v1}; // SemVer struct initialization. Loop the given strings. for (int v_idx = 0; v_idx < 2; v_idx++) { // For both strings, execute the regular expression search, // then loop through the submatches. std::smatch match; if (!std::regex_search(v[v_idx], match, re_semver)) { // The given string is not a semver: the comparison failed. return 9; } // Submatches lookup for (int sub_idx = 0, size = match.size(); sub_idx < size; sub_idx++) { // Fill the structure converting the string to an integer. switch (sub_idx) { case 1: // major str_to_num(match[sub_idx].str(), sv[v_idx].major); break; case 2: // minor str_to_num(match[sub_idx].str(), sv[v_idx].minor); break; case 3: // patch str_to_num(match[sub_idx].str(), sv[v_idx].patch); break; default: // sub_idx = 0: the first group which is the entire match we don't need. break; } } } // Now that we are sure to have two valid semver, let's compare each part. if (sv[0].major < sv[1].major) { return -1; } else if (sv[0].major > sv[1].major) { return 1; } if (sv[0].minor < sv[1].minor) { return -1; } else if (sv[0].minor > sv[1].minor) { return 1; } if (sv[0].patch < sv[1].patch) { return -1; } else if (sv[0].patch > sv[1].patch) { return 1; } return 0; } } // namespace util
16,050
C++
.cpp
421
33.817102
120
0.660943
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,631
loudness_preset.cpp
wwmm_easyeffects/src/loudness_preset.cpp
/* * 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/>. */ #include "loudness_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" LoudnessPreset::LoudnessPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::loudness::id, tags::schema::loudness::input_path, tags::schema::loudness::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::loudness).append("#").append(util::to_string(index)); } void LoudnessPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["fft"] = util::gsettings_get_string(settings, "fft"); json[section][instance_name]["std"] = util::gsettings_get_string(settings, "std"); json[section][instance_name]["volume"] = g_settings_get_double(settings, "volume"); json[section][instance_name]["clipping"] = g_settings_get_boolean(settings, "clipping") != 0; json[section][instance_name]["clipping-range"] = g_settings_get_double(settings, "clipping-range"); } void LoudnessPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<gchar*>(json.at(section).at(instance_name), settings, "fft", "fft"); update_key<gchar*>(json.at(section).at(instance_name), settings, "std", "std"); update_key<double>(json.at(section).at(instance_name), settings, "volume", "volume"); update_key<bool>(json.at(section).at(instance_name), settings, "clipping", "clipping"); update_key<double>(json.at(section).at(instance_name), settings, "clipping-range", "clipping-range"); }
2,995
C++
.cpp
55
50.454545
103
0.71013
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,632
speex_preset.cpp
wwmm_easyeffects/src/speex_preset.cpp
/* * 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/>. */ #include "speex_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" SpeexPreset::SpeexPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::speex::id, tags::schema::speex::input_path, tags::schema::speex::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::speex).append("#").append(util::to_string(index)); } void SpeexPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["enable-denoise"] = g_settings_get_boolean(settings, "enable-denoise") != 0; json[section][instance_name]["noise-suppression"] = g_settings_get_int(settings, "noise-suppression"); json[section][instance_name]["enable-agc"] = g_settings_get_boolean(settings, "enable-agc") != 0; json[section][instance_name]["vad"]["enable"] = g_settings_get_boolean(settings, "enable-vad") != 0; json[section][instance_name]["vad"]["probability-start"] = g_settings_get_int(settings, "vad-probability-start"); json[section][instance_name]["vad"]["probability-continue"] = g_settings_get_int(settings, "vad-probability-continue"); json[section][instance_name]["enable-dereverb"] = g_settings_get_boolean(settings, "enable-dereverb") != 0; } void SpeexPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<bool>(json.at(section).at(instance_name), settings, "enable-denoise", "enable-denoise"); update_key<int>(json.at(section).at(instance_name), settings, "noise-suppression", "noise-suppression"); update_key<bool>(json.at(section).at(instance_name), settings, "enable-agc", "enable-agc"); update_key<bool>(json.at(section).at(instance_name).at("vad"), settings, "enable-vad", "enable"); update_key<int>(json.at(section).at(instance_name).at("vad"), settings, "vad-probability-start", "probability-start"); update_key<int>(json.at(section).at(instance_name).at("vad"), settings, "vad-probability-continue", "probability-continue"); update_key<bool>(json.at(section).at(instance_name), settings, "enable-dereverb", "enable-dereverb"); }
3,597
C++
.cpp
60
55.6
120
0.708962
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,633
limiter_ui.cpp
wwmm_easyeffects/src/limiter_ui.cpp
/* * 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/>. */ #include "limiter_ui.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "limiter.hpp" #include "node_info_holder.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::limiter_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Limiter> limiter; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _LimiterBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkDropDown *mode, *oversampling, *dither; GtkDropDown* dropdown_input_devices; GtkLabel *gain_left, *gain_right, *sidechain_left, *sidechain_right; GtkSpinButton *sc_preamp, *lookahead, *attack, *release, *threshold, *stereo_link, *alr_attack, *alr_release, *alr_knee; GtkCheckButton* gain_boost; GtkToggleButton *alr, *external_sidechain, *show_native_ui; GListStore* input_devices_model; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(LimiterBox, limiter_box, GTK_TYPE_BOX) void on_reset(LimiterBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(LimiterBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->limiter->show_native_ui(); } else { self->data->limiter->close_native_ui(); } } void setup_dropdown_input_device(LimiterBox* self) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(self->input_devices_model)); g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, LimiterBox* self) { if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->settings, "sidechain-input-device", holder->info->name.c_str()); } }), self); gtk_drop_down_set_model(self->dropdown_input_devices, G_LIST_MODEL(self->input_devices_model)); g_object_unref(selection); } void setup(LimiterBox* self, std::shared_ptr<Limiter> limiter, const std::string& schema_path, PipeManager* pm) { self->data->limiter = limiter; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::limiter::id, schema_path.c_str()); limiter->set_post_messages(true); setup_dropdown_input_device(self); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source || node.media_role == tags::pipewire::media_role::dsp) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); } } self->data->connections.push_back(limiter->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(limiter->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(limiter->gain_left.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->gain_left)) { return; } gtk_label_set_text(self->gain_left, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(limiter->gain_right.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->gain_right)) { return; } gtk_label_set_text(self->gain_right, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(limiter->sidechain_left.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->sidechain_left)) { return; } gtk_label_set_text(self->sidechain_left, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(limiter->sidechain_right.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->sidechain_right)) { return; } gtk_label_set_text(self->sidechain_right, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->limiter->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "sidechain-preamp", gtk_spin_button_get_adjustment(self->sc_preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "lookahead", gtk_spin_button_get_adjustment(self->lookahead), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "attack", gtk_spin_button_get_adjustment(self->attack), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release", gtk_spin_button_get_adjustment(self->release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "threshold", gtk_spin_button_get_adjustment(self->threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "stereo-link", gtk_spin_button_get_adjustment(self->stereo_link), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "alr-attack", gtk_spin_button_get_adjustment(self->alr_attack), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "alr-release", gtk_spin_button_get_adjustment(self->alr_release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "alr-knee", gtk_spin_button_get_adjustment(self->alr_knee), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "gain-boost", self->gain_boost, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "external-sidechain", self->external_sidechain, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "alr", self->alr, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "mode", self->mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "oversampling", self->oversampling); ui::gsettings_bind_enum_to_combo_widget(self->settings, "dithering", self->dither); } void dispose(GObject* object) { auto* self = EE_LIMITER_BOX(object); self->data->limiter->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(limiter_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_LIMITER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(limiter_box_parent_class)->finalize(object); } void limiter_box_class_init(LimiterBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::limiter_ui); gtk_widget_class_bind_template_child(widget_class, LimiterBox, input_gain); gtk_widget_class_bind_template_child(widget_class, LimiterBox, output_gain); gtk_widget_class_bind_template_child(widget_class, LimiterBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, LimiterBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, LimiterBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, LimiterBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, LimiterBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, LimiterBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, LimiterBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, LimiterBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, LimiterBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, LimiterBox, mode); gtk_widget_class_bind_template_child(widget_class, LimiterBox, oversampling); gtk_widget_class_bind_template_child(widget_class, LimiterBox, dither); gtk_widget_class_bind_template_child(widget_class, LimiterBox, sc_preamp); gtk_widget_class_bind_template_child(widget_class, LimiterBox, lookahead); gtk_widget_class_bind_template_child(widget_class, LimiterBox, attack); gtk_widget_class_bind_template_child(widget_class, LimiterBox, release); gtk_widget_class_bind_template_child(widget_class, LimiterBox, threshold); gtk_widget_class_bind_template_child(widget_class, LimiterBox, stereo_link); gtk_widget_class_bind_template_child(widget_class, LimiterBox, alr_attack); gtk_widget_class_bind_template_child(widget_class, LimiterBox, alr_release); gtk_widget_class_bind_template_child(widget_class, LimiterBox, alr_knee); gtk_widget_class_bind_template_child(widget_class, LimiterBox, alr); gtk_widget_class_bind_template_child(widget_class, LimiterBox, external_sidechain); gtk_widget_class_bind_template_child(widget_class, LimiterBox, gain_boost); gtk_widget_class_bind_template_child(widget_class, LimiterBox, gain_left); gtk_widget_class_bind_template_child(widget_class, LimiterBox, gain_right); gtk_widget_class_bind_template_child(widget_class, LimiterBox, sidechain_left); gtk_widget_class_bind_template_child(widget_class, LimiterBox, sidechain_right); gtk_widget_class_bind_template_child(widget_class, LimiterBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, LimiterBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); } void limiter_box_init(LimiterBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"dB">(self->sc_preamp, self->threshold, self->alr_knee); prepare_spinbuttons<"ms">(self->lookahead, self->attack, self->release, self->alr_attack, self->alr_release); prepare_spinbuttons<"%">(self->stereo_link); } auto create() -> LimiterBox* { return static_cast<LimiterBox*>(g_object_new(EE_TYPE_LIMITER_BOX, nullptr)); } } // namespace ui::limiter_box
15,571
C++
.cpp
327
41.825688
119
0.680971
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,634
crystalizer_ui.cpp
wwmm_easyeffects/src/crystalizer_ui.cpp
/* * 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/>. */ #include "crystalizer_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkbox.h> #include <gtk/gtkbutton.h> #include <gtk/gtklabel.h> #include <gtk/gtklevelbar.h> #include <gtk/gtkscale.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "crystalizer.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::crystalizer_box { constexpr uint nbands = 13U; struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Crystalizer> crystalizer; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _CrystalizerBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label; GtkBox* bands_box; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(CrystalizerBox, crystalizer_box, GTK_TYPE_BOX) void on_reset(CrystalizerBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void build_bands(CrystalizerBox* self) { for (uint n = 0U; n < nbands; n++) { auto builder = gtk_builder_new_from_resource(tags::resources::crystalizer_band_ui); auto* band_box = GTK_BOX(gtk_builder_get_object(builder, "band_box")); auto* band_label = GTK_LABEL(gtk_builder_get_object(builder, "band_label")); auto* band_intensity = GTK_SCALE(gtk_builder_get_object(builder, "band_intensity")); auto* band_bypass = GTK_TOGGLE_BUTTON(gtk_builder_get_object(builder, "band_bypass")); auto* band_mute = GTK_TOGGLE_BUTTON(gtk_builder_get_object(builder, "band_mute")); prepare_scales<"">(band_intensity); const auto bandn = "band" + util::to_string(n); // connections g_settings_bind(self->settings, ("intensity-" + bandn).c_str(), gtk_range_get_adjustment(GTK_RANGE(band_intensity)), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, ("mute-" + bandn).c_str(), band_mute, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, ("bypass-" + bandn).c_str(), band_bypass, "active", G_SETTINGS_BIND_DEFAULT); switch (n) { case 0U: gtk_label_set_text(band_label, "250 Hz"); break; case 1U: gtk_label_set_text(band_label, "750 Hz"); break; case 2U: gtk_label_set_text(band_label, "1.5 kHz"); break; case 3U: gtk_label_set_text(band_label, "2.5 kHz"); break; case 4U: gtk_label_set_text(band_label, "3.5 kHz"); break; case 5U: gtk_label_set_text(band_label, "4.5 kHz"); break; case 6U: gtk_label_set_text(band_label, "5.5 kHz"); break; case 7U: gtk_label_set_text(band_label, "6.5 kHz"); break; case 8U: gtk_label_set_text(band_label, "7.5 kHz"); break; case 9U: gtk_label_set_text(band_label, "8.5 kHz"); break; case 10U: gtk_label_set_text(band_label, "9.5 kHz"); break; case 11U: gtk_label_set_text(band_label, "12.5 kHz"); break; case 12U: gtk_label_set_text(band_label, "17.5 kHz"); break; default: break; } gtk_box_append(self->bands_box, GTK_WIDGET(band_box)); g_object_unref(builder); } } void setup(CrystalizerBox* self, std::shared_ptr<Crystalizer> crystalizer, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->crystalizer = crystalizer; self->settings = g_settings_new_with_path(tags::schema::crystalizer::id, schema_path.c_str()); crystalizer->set_post_messages(true); build_bands(self); self->data->connections.push_back(crystalizer->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(crystalizer->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); } void dispose(GObject* object) { auto* self = EE_CRYSTALIZER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(crystalizer_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_CRYSTALIZER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(crystalizer_box_parent_class)->finalize(object); } void crystalizer_box_class_init(CrystalizerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::crystalizer_ui); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, input_gain); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, output_gain); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, CrystalizerBox, bands_box); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void crystalizer_box_init(CrystalizerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> CrystalizerBox* { return static_cast<CrystalizerBox*>(g_object_new(EE_TYPE_CRYSTALIZER_BOX, nullptr)); } } // namespace ui::crystalizer_box
8,501
C++
.cpp
210
35.671429
120
0.690137
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,635
fir_filter_bandpass.cpp
wwmm_easyeffects/src/fir_filter_bandpass.cpp
/* * 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/>. */ #include "fir_filter_bandpass.hpp" #include <algorithm> #include <cstddef> #include <string> #include <utility> #include "fir_filter_base.hpp" FirFilterBandpass::FirFilterBandpass(std::string tag) : FirFilterBase(std::move(tag)) {} FirFilterBandpass::~FirFilterBandpass() = default; void FirFilterBandpass::setup() { const auto lowpass_kernel = create_lowpass_kernel(max_frequency, transition_band); // high-pass kernel auto highpass_kernel = create_lowpass_kernel(min_frequency, transition_band); std::ranges::for_each(highpass_kernel, [](auto& v) { v *= -1.0F; }); highpass_kernel[(highpass_kernel.size() - 1U) / 2U] += 1.0F; kernel.resize(highpass_kernel.size()); /* Creating a bandpass from a band reject through spectral inversion https://www.dspguide.com/ch16/4.htm */ for (size_t n = 0U; n < kernel.size(); n++) { kernel[n] = lowpass_kernel[n] + highpass_kernel[n]; } std::ranges::for_each(kernel, [](auto& v) { v *= -1.0F; }); kernel[(kernel.size() - 1U) / 2U] += 1.0F; delay = 0.5F * static_cast<float>(kernel.size() - 1U) / static_cast<float>(rate); setup_zita(); }
1,880
C++
.cpp
44
40.181818
105
0.715541
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,636
expander.cpp
wwmm_easyeffects/src/expander.cpp
/* * 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/>. */ #include "expander.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Expander::Expander(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::expander, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_expander_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_expander_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::sidechain-type", G_CALLBACK(+[](GSettings* settings, const char* key, gpointer user_data) { auto* self = static_cast<Expander*>(user_data); self->update_sidechain_links(key); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, const char* key, gpointer user_data) { auto* self = static_cast<Expander*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"em", "mode">(settings); lv2_wrapper->bind_key_enum<"sci", "sidechain-type">(settings); lv2_wrapper->bind_key_enum<"scm", "sidechain-mode">(settings); lv2_wrapper->bind_key_enum<"scs", "sidechain-source">(settings); lv2_wrapper->bind_key_enum<"sscs", "stereo-split-source">(settings); lv2_wrapper->bind_key_enum<"shpm", "hpf-mode">(settings); lv2_wrapper->bind_key_enum<"slpm", "lpf-mode">(settings); lv2_wrapper->bind_key_bool<"ssplit", "stereo-split">(settings); lv2_wrapper->bind_key_bool<"scl", "sidechain-listen">(settings); lv2_wrapper->bind_key_double<"at", "attack">(settings); lv2_wrapper->bind_key_double<"rt", "release">(settings); lv2_wrapper->bind_key_double<"er", "ratio">(settings); lv2_wrapper->bind_key_double<"scr", "sidechain-reactivity">(settings); lv2_wrapper->bind_key_double<"sla", "sidechain-lookahead">(settings); lv2_wrapper->bind_key_double<"shpf", "hpf-frequency">(settings); lv2_wrapper->bind_key_double<"slpf", "lpf-frequency">(settings); lv2_wrapper->bind_key_double_db<"al", "threshold">(settings); lv2_wrapper->bind_key_double_db<"kn", "knee">(settings); lv2_wrapper->bind_key_double_db<"mk", "makeup">(settings); lv2_wrapper->bind_key_double_db<"scp", "sidechain-preamp">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"rrl", "release-threshold", false>(settings); lv2_wrapper->bind_key_double_db<"cdr", "dry", false>(settings); lv2_wrapper->bind_key_double_db<"cwt", "wet", false>(settings); setup_input_output_gain(); } Expander::~Expander() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Expander::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Expander::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { reduction_port_value = 0.5F * (lv2_wrapper->get_control_port_value("rlm_l") + lv2_wrapper->get_control_port_value("rlm_r")); sidechain_port_value = 0.5F * (lv2_wrapper->get_control_port_value("slm_l") + lv2_wrapper->get_control_port_value("slm_r")); curve_port_value = 0.5F * (lv2_wrapper->get_control_port_value("clm_l") + lv2_wrapper->get_control_port_value("clm_r")); envelope_port_value = 0.5F * (lv2_wrapper->get_control_port_value("elm_l") + lv2_wrapper->get_control_port_value("elm_r")); reduction.emit(reduction_port_value); sidechain.emit(sidechain_port_value); curve.emit(curve_port_value); envelope.emit(envelope_port_value); notify(); } } } void Expander::update_sidechain_links(const std::string& key) { if (util::gsettings_get_string(settings, "sidechain-type") != "External") { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void Expander::update_probe_links() { update_sidechain_links(""); } auto Expander::get_latency_seconds() -> float { return this->latency_value; }
7,830
C++
.cpp
184
35.086957
116
0.62307
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,637
crossfeed.cpp
wwmm_easyeffects/src/crossfeed.cpp
/* * 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/>. */ #include "crossfeed.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <algorithm> #include <cstddef> #include <mutex> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Crossfeed::Crossfeed(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::crossfeed, tags::plugin_package::bs2b, schema, schema_path, pipe_manager, pipe_type) { bs2b.set_level_fcut(g_settings_get_int(settings, "fcut")); bs2b.set_level_feed(10 * static_cast<int>(g_settings_get_double(settings, "feed"))); gconnections.push_back(g_signal_connect(settings, "changed::fcut", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Crossfeed*>(user_data); std::scoped_lock<std::mutex> lock(self->data_mutex); self->bs2b.set_level_fcut(g_settings_get_int(settings, key)); }), this)); gconnections.push_back( g_signal_connect(settings, "changed::feed", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Crossfeed*>(user_data); std::scoped_lock<std::mutex> lock(self->data_mutex); self->bs2b.set_level_feed(10 * static_cast<int>(g_settings_get_double(settings, key))); }), this)); setup_input_output_gain(); } Crossfeed::~Crossfeed() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Crossfeed::setup() { std::scoped_lock<std::mutex> lock(data_mutex); data.resize(2U * static_cast<size_t>(n_samples)); if (rate != bs2b.get_srate()) { bs2b.set_srate(rate); } } void Crossfeed::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } for (size_t n = 0U; n < left_in.size(); n++) { data[n * 2U] = left_in[n]; data[n * 2U + 1U] = right_in[n]; } bs2b.cross_feed(data.data(), static_cast<int>(n_samples)); for (size_t n = 0U; n < left_out.size(); n++) { left_out[n] = data[n * 2U]; right_out[n] = data[n * 2U + 1U]; } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto Crossfeed::get_latency_seconds() -> float { return 0.0F; }
4,170
C++
.cpp
109
29.862385
118
0.582652
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,638
plugin_preset_base.cpp
wwmm_easyeffects/src/plugin_preset_base.cpp
/* * 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/>. */ #include "plugin_preset_base.hpp" #include <gio/gio.h> #include <glib-object.h> #include "preset_type.hpp" #include "util.hpp" PluginPresetBase::PluginPresetBase(const char* schema_id, const char* schema_path_input, const char* schema_path_output, PresetType preset_type, const int& index) : index(index), preset_type(preset_type) { switch (preset_type) { case PresetType::input: section = "input"; settings = g_settings_new_with_path(schema_id, (schema_path_input + util::to_string(index) + "/").c_str()); break; case PresetType::output: section = "output"; settings = g_settings_new_with_path(schema_id, (schema_path_output + util::to_string(index) + "/").c_str()); break; } } PluginPresetBase::~PluginPresetBase() { g_object_unref(settings); }
1,699
C++
.cpp
43
33.488372
114
0.6596
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,639
convolver_ui_common.cpp
wwmm_easyeffects/src/convolver_ui_common.cpp
/* * 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/>. */ #include "convolver_ui_common.hpp" #include <cstddef> #include <filesystem> #include <sndfile.hh> #include <string> #include <tuple> #include <vector> #include "util.hpp" namespace ui::convolver { auto read_kernel(std::filesystem::path irs_dir, const std::string& irs_ext, const std::string& file_name) -> std::tuple<int, std::vector<float>, std::vector<float>> { int rate = 0; std::vector<float> buffer; std::vector<float> kernel_L; std::vector<float> kernel_R; auto file_path = irs_dir / std::filesystem::path{file_name}; util::debug("reading the impulse file: " + file_path.string()); if (file_path.extension() != irs_ext) { file_path += irs_ext; } if (!std::filesystem::exists(file_path)) { util::debug("file: " + file_path.string() + " does not exist"); return std::make_tuple(rate, kernel_L, kernel_R); } auto sndfile = SndfileHandle(file_path.string()); if (sndfile.channels() != 2 || sndfile.frames() == 0) { util::warning(" Only stereo impulse responses are supported."); util::warning(" The impulse file was not loaded!"); return std::make_tuple(rate, kernel_L, kernel_R); } buffer.resize(sndfile.frames() * sndfile.channels()); kernel_L.resize(sndfile.frames()); kernel_R.resize(sndfile.frames()); sndfile.readf(buffer.data(), sndfile.frames()); for (size_t n = 0U; n < kernel_L.size(); n++) { kernel_L[n] = buffer[2U * n]; kernel_R[n] = buffer[2U * n + 1U]; } rate = sndfile.samplerate(); return std::make_tuple(rate, kernel_L, kernel_R); } } // namespace ui::convolver
2,330
C++
.cpp
60
35.983333
105
0.696096
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,640
libportal.cpp
wwmm_easyeffects/src/libportal.cpp
/* * 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/>. */ #include "libportal.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <string> #include "tags_app.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace { bool resetting_shutdown = false, resetting_autostart = false; GSettings* settings = nullptr; GtkSwitch *enable_autostart = nullptr, *shutdown_on_window_close = nullptr; } // namespace namespace libportal { using namespace std::string_literals; XdpPortal* portal = nullptr; void on_request_background_called(GObject* source, GAsyncResult* result, gpointer widgets_ptr) { if (enable_autostart == nullptr || shutdown_on_window_close == nullptr) { util::error("Programming error. When using libportal its pointers to our settings widgets must be initialized."); } g_autoptr(GError) error = nullptr; // libportal check if portal request worked if (xdp_portal_request_background_finish(portal, result, &error) == 0) { // NOLINTNEXTLINE(cppcoreguidelines-init-variables) std::string reason; // NOLINTNEXTLINE(cppcoreguidelines-init-variables) std::string explanation; // NOLINTNEXTLINE(cppcoreguidelines-init-variables) std::string error_message; if (error != nullptr) { error_message = error->message; if (error->code == 19) { // 19 seemingly corresponds to the "cancelled" error which actually means the permission is in a revoked state. reason = "Background access has been denied"; explanation = "Please allow Easy Effects to ask again with Flatpak permission-reset "s + tags::app::id; } else { reason = "Generic error"; explanation = "Please verify your system has a XDG Background Portal implementation running and working."; } } else { error_message = "unknown reason"; reason = "Unknown error"; explanation = "No explanation could be provided, error was null"; } util::debug("A background request failed: " + error_message); util::warning(reason); util::warning(explanation); // TODO find a bettery way of getting the preferences window // it shouldn't be possible to open the preferences window without the top level window open, // so the index 1 should correspond with the preferences window ui::show_simple_message_dialog(GTK_WIDGET(g_list_model_get_item(gtk_window_get_toplevels(), 1)), "Unable to get background access: " + reason, explanation); // if autostart is wrongly enabled (we got an error when talking to the portal), we must reset it if (static_cast<bool>(gtk_switch_get_active(enable_autostart)) || static_cast<bool>(gtk_switch_get_state(enable_autostart))) { resetting_autostart = true; util::warning("due to error, setting autostart state and switch to false"); gtk_switch_set_state(enable_autostart, 0); gtk_switch_set_active(enable_autostart, 0); } // if running in the background (which happens if we don't shutdown on window close) is wrongly enabled (we got an // error when talking to the portal), we must reset it if (!static_cast<bool>(gtk_switch_get_active(shutdown_on_window_close)) || !static_cast<bool>(gtk_switch_get_state(shutdown_on_window_close))) { resetting_shutdown = true; util::warning("due to error, setting shutdown on window close state and switch to true"); gtk_switch_set_state(shutdown_on_window_close, 1); gtk_switch_set_active(shutdown_on_window_close, 1); } resetting_autostart = false; resetting_shutdown = false; return; } gtk_switch_set_state(enable_autostart, gtk_switch_get_active(enable_autostart)); gtk_switch_set_state(shutdown_on_window_close, gtk_switch_get_active(shutdown_on_window_close)); resetting_autostart = false; resetting_shutdown = false; util::debug("a background request successfully completed"); } // generic portal update function void update_background_portal(const bool& use_autostart) { // clang-tidy doesn't seem to understand this is actually being inited. // NOLINTNEXTLINE(cppcoreguidelines-init-variables) XdpBackgroundFlags background_flags = XDP_BACKGROUND_FLAG_NONE; g_autoptr(GPtrArray) command_line = nullptr; if (use_autostart) { command_line = g_ptr_array_new_with_free_func(g_free); g_ptr_array_add(command_line, g_strdup("easyeffects")); g_ptr_array_add(command_line, g_strdup("--gapplication-service")); background_flags = XDP_BACKGROUND_FLAG_AUTOSTART; } auto* reason = g_strdup("Easy Effects Background Access"); // libportal portal request xdp_portal_request_background(portal, nullptr, reason, command_line, background_flags, nullptr, on_request_background_called, nullptr); g_free(reason); } void on_enable_autostart(GtkSwitch* obj, gboolean state, gpointer user_data) { // this callback could be triggered when the settings are reset by other code due to an error calling the portal, in // that case we must not call the portal again. if (!resetting_autostart) { state == 1 ? util::debug("requesting autostart file since autostart is enabled") : util::debug("not requesting autostart file since autostart is disabled"); update_background_portal(state != 0); } } void on_shutdown_on_window_close(GtkSwitch* btn, gboolean state, gpointer user_data) { // this callback could be triggered when the settings are reset by other code due to an error calling the portal, in // that case we must not call the portal again. if (!resetting_shutdown) { if (gtk_switch_get_active(enable_autostart) != 0) { const auto* msg = (state == 0) ? "requesting both background access and autostart file since autostart is enabled" : "requesting autostart access since autostart enabled"; util::debug(msg); update_background_portal(true); } else { if (state == 0) { util::debug("requesting only background access, not creating autostart file"); update_background_portal(false); } else { util::debug("not requesting any access since enabling shutdown on window close"); gtk_switch_set_state(shutdown_on_window_close, gtk_switch_get_active(shutdown_on_window_close)); } } } } void init(GtkSwitch* g_enable_autostart, GtkSwitch* g_shutdown_on_window_close) { enable_autostart = g_enable_autostart; shutdown_on_window_close = g_shutdown_on_window_close; if (enable_autostart == nullptr || shutdown_on_window_close == nullptr) { util::error("Programming error. When using libportal its pointers to our settings widgets must be initialized."); } if (portal == nullptr) { portal = xdp_portal_new(); } settings = g_settings_new("com.github.wwmm.easyeffects.libportal"); ui::gsettings_bind_widget(settings, "enable-autostart", g_enable_autostart); g_signal_connect(enable_autostart, "state-set", G_CALLBACK(on_enable_autostart), nullptr); g_signal_connect(shutdown_on_window_close, "state-set", G_CALLBACK(on_shutdown_on_window_close), nullptr); // sanity checks in case switch(es) was somehow already set previously. // give extra info for debugging purposes // the only the case where we must not ask the portal for access is if autostart is disabled and shutdown on window // close is disabled auto enable_autostart_state = gtk_switch_get_active(enable_autostart); auto shutdown_on_window_close_state = gtk_switch_get_active(shutdown_on_window_close); if ((enable_autostart_state == 0) && (shutdown_on_window_close_state == 0)) { util::debug("doing portal sanity check, autostart and shutdown switches are disabled"); update_background_portal(false); } else if ((enable_autostart_state != 0) && (shutdown_on_window_close_state != 0)) { util::debug("doing portal sanity check, autostart and shutdown switches are enabled"); update_background_portal(true); } else if ((enable_autostart_state != 0) && (shutdown_on_window_close_state == 0)) { util::debug("doing portal sanity check, autostart switch is enabled and shutdown switch is disabled"); update_background_portal(true); } else { util::debug( "not doing portal sanity check, autostart switch should be disabled and shutdown switch should be enabled so " "no background portal access is needed"); } } } // namespace libportal
9,249
C++
.cpp
182
45.972527
120
0.719516
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,641
limiter_preset.cpp
wwmm_easyeffects/src/limiter_preset.cpp
/* * 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/>. */ #include "limiter_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" LimiterPreset::LimiterPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::limiter::id, tags::schema::limiter::input_path, tags::schema::limiter::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::limiter).append("#").append(util::to_string(index)); } void LimiterPreset::save(nlohmann::json& json) { json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["oversampling"] = util::gsettings_get_string(settings, "oversampling"); json[section][instance_name]["dithering"] = util::gsettings_get_string(settings, "dithering"); json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["lookahead"] = g_settings_get_double(settings, "lookahead"); json[section][instance_name]["attack"] = g_settings_get_double(settings, "attack"); json[section][instance_name]["release"] = g_settings_get_double(settings, "release"); json[section][instance_name]["threshold"] = g_settings_get_double(settings, "threshold"); json[section][instance_name]["sidechain-preamp"] = g_settings_get_double(settings, "sidechain-preamp"); json[section][instance_name]["stereo-link"] = g_settings_get_double(settings, "stereo-link"); json[section][instance_name]["alr-attack"] = g_settings_get_double(settings, "alr-attack"); json[section][instance_name]["alr-release"] = g_settings_get_double(settings, "alr-release"); json[section][instance_name]["alr-knee"] = g_settings_get_double(settings, "alr-knee"); json[section][instance_name]["alr"] = g_settings_get_boolean(settings, "alr") != 0; json[section][instance_name]["gain-boost"] = g_settings_get_boolean(settings, "gain-boost") != 0; json[section][instance_name]["external-sidechain"] = g_settings_get_boolean(settings, "external-sidechain") != 0; } void LimiterPreset::load(const nlohmann::json& json) { update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<gchar*>(json.at(section).at(instance_name), settings, "oversampling", "oversampling"); update_key<gchar*>(json.at(section).at(instance_name), settings, "dithering", "dithering"); update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "lookahead", "lookahead"); update_key<double>(json.at(section).at(instance_name), settings, "attack", "attack"); update_key<double>(json.at(section).at(instance_name), settings, "release", "release"); update_key<double>(json.at(section).at(instance_name), settings, "threshold", "threshold"); update_key<double>(json.at(section).at(instance_name), settings, "sidechain-preamp", "sidechain-preamp"); update_key<double>(json.at(section).at(instance_name), settings, "stereo-link", "stereo-link"); update_key<double>(json.at(section).at(instance_name), settings, "alr-attack", "alr-attack"); update_key<double>(json.at(section).at(instance_name), settings, "alr-release", "alr-release"); update_key<double>(json.at(section).at(instance_name), settings, "alr-knee", "alr-knee"); update_key<bool>(json.at(section).at(instance_name), settings, "alr", "alr"); update_key<bool>(json.at(section).at(instance_name), settings, "gain-boost", "gain-boost"); update_key<bool>(json.at(section).at(instance_name), settings, "external-sidechain", "external-sidechain"); }
4,955
C++
.cpp
75
62.066667
115
0.716853
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,642
fir_filter_base.cpp
wwmm_easyeffects/src/fir_filter_base.cpp
/* * 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/>. */ #include "fir_filter_base.hpp" #include <sched.h> #include <sys/types.h> #include <zita-convolver.h> #include <algorithm> #include <cmath> #include <cstddef> #include <numbers> #include <string> #include <utility> #include <vector> #include "util.hpp" namespace { constexpr auto CONVPROC_SCHEDULER_PRIORITY = 0; constexpr auto CONVPROC_SCHEDULER_CLASS = SCHED_FIFO; } // namespace FirFilterBase::FirFilterBase(std::string tag) : log_tag(std::move(tag)) {} FirFilterBase::~FirFilterBase() { zita_ready = false; if (conv != nullptr) { conv->stop_process(); conv->cleanup(); delete conv; } } void FirFilterBase::set_rate(const uint& value) { rate = value; } void FirFilterBase::set_n_samples(const uint& value) { n_samples = value; } void FirFilterBase::set_min_frequency(const float& value) { min_frequency = value; } void FirFilterBase::set_max_frequency(const float& value) { max_frequency = value; } void FirFilterBase::set_transition_band(const float& value) { transition_band = value; } void FirFilterBase::setup() {} auto FirFilterBase::create_lowpass_kernel(const float& cutoff, const float& transition_band) const -> std::vector<float> { std::vector<float> output; if (rate == 0U) { return output; } /* transition band frequency as a fraction of the sample rate */ const float b = transition_band / static_cast<float>(rate); /* The kernel size must be odd: M + 1 where M is even. This is done so it can be symmetric around the main lobe https://www.dspguide.com/ch16/1.htm The kernel size is related to the transition bandwidth M = 4/BW */ auto M = static_cast<uint>(std::ceil(4.0F / b)); M = (M % 2U == 0U) ? M : M + 1U; // checking if M is even output.resize(M + 1U); /* cutoff frequency as a fraction of the sample rate */ const float fc = cutoff / static_cast<float>(rate); float sum = 0.0F; for (size_t n = 0U; n < output.size(); n++) { /* windowed-sinc kernel https://www.dspguide.com/ch16/1.htm */ if (n == M / 2U) { output[n] = 2.0F * std::numbers::pi_v<float> * fc; } else { output[n] = std::sin(2.0F * std::numbers::pi_v<float> * fc * static_cast<float>(n - static_cast<uint>(M / 2U))) / static_cast<float>(n - static_cast<uint>(M / 2U)); } /* Blackman window https://www.dspguide.com/ch16/1.htm */ const float w = 0.42F - 0.5F * std::cos(2.0F * std::numbers::pi_v<float> * static_cast<float>(n) / static_cast<float>(M)) + 0.08F * std::cos(4.0F * std::numbers::pi_v<float> * static_cast<float>(n) / static_cast<float>(M)); output[n] *= w; sum += output[n]; } /* Normalizing so that we have unit gain at zero frequency */ std::ranges::for_each(output, [&](auto& v) { v /= sum; }); return output; } void FirFilterBase::setup_zita() { zita_ready = false; if (n_samples == 0U || kernel.empty()) { return; } if (conv != nullptr) { conv->stop_process(); conv->cleanup(); delete conv; } conv = new Convproc(); conv->set_options(0); int ret = conv->configure(2, 2, kernel.size(), n_samples, n_samples, n_samples, 0.0F /*density*/); if (ret != 0) { util::warning(log_tag + "can't initialise zita-convolver engine: " + util::to_string(ret, "")); return; } ret = conv->impdata_create(0, 0, 1, kernel.data(), 0, static_cast<int>(kernel.size())); if (ret != 0) { util::warning(log_tag + "left impdata_create failed: " + util::to_string(ret, "")); return; } ret = conv->impdata_create(1, 1, 1, kernel.data(), 0, static_cast<int>(kernel.size())); if (ret != 0) { util::warning(log_tag + "right impdata_create failed: " + util::to_string(ret, "")); return; } ret = conv->start_process(CONVPROC_SCHEDULER_PRIORITY, CONVPROC_SCHEDULER_CLASS); if (ret != 0) { util::warning(log_tag + "start_process failed: " + util::to_string(ret, "")); conv->stop_process(); conv->cleanup(); return; } // conv->print(); zita_ready = true; } void FirFilterBase::direct_conv(const std::vector<float>& a, const std::vector<float>& b, std::vector<float>& c) { const uint M = (c.size() + 1U) / 2U; for (uint n = 0U; n < c.size(); n++) { c[n] = 0.0F; for (uint m = 0U; m < M; m++) { if (n > m && n - m < M) { c[n] += a[n - m] * b[m]; } } } } auto FirFilterBase::get_delay() const -> float { return delay; }
5,269
C++
.cpp
158
29.512658
119
0.644216
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,643
multiband_gate_preset.cpp
wwmm_easyeffects/src/multiband_gate_preset.cpp
/* * 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/>. */ #include "multiband_gate_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <sys/types.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" MultibandGatePreset::MultibandGatePreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::multiband_gate::id, tags::schema::multiband_gate::input_path, tags::schema::multiband_gate::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::multiband_gate).append("#").append(util::to_string(index)); } void MultibandGatePreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["dry"] = g_settings_get_double(settings, "dry"); json[section][instance_name]["wet"] = g_settings_get_double(settings, "wet"); json[section][instance_name]["gate-mode"] = util::gsettings_get_string(settings, "gate-mode"); json[section][instance_name]["envelope-boost"] = util::gsettings_get_string(settings, "envelope-boost"); json[section][instance_name]["stereo-split"] = g_settings_get_boolean(settings, "stereo-split") != 0; for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); const auto bandn = "band" + nstr; if (n > 0U) { json[section][instance_name][bandn]["enable-band"] = g_settings_get_boolean(settings, ("enable-band" + nstr).c_str()) != 0; json[section][instance_name][bandn]["split-frequency"] = g_settings_get_double(settings, ("split-frequency" + nstr).c_str()); } json[section][instance_name][bandn]["gate-enable"] = g_settings_get_boolean(settings, ("gate-enable" + nstr).c_str()) != 0; json[section][instance_name][bandn]["solo"] = g_settings_get_boolean(settings, ("solo" + nstr).c_str()) != 0; json[section][instance_name][bandn]["mute"] = g_settings_get_boolean(settings, ("mute" + nstr).c_str()) != 0; json[section][instance_name][bandn]["attack-time"] = g_settings_get_double(settings, ("attack-time" + nstr).c_str()); json[section][instance_name][bandn]["release-time"] = g_settings_get_double(settings, ("release-time" + nstr).c_str()); json[section][instance_name][bandn]["hysteresis"] = g_settings_get_boolean(settings, ("hysteresis" + nstr).c_str()) != 0; json[section][instance_name][bandn]["hysteresis-threshold"] = g_settings_get_double(settings, ("hysteresis-threshold" + nstr).c_str()); json[section][instance_name][bandn]["hysteresis-zone"] = g_settings_get_double(settings, ("hysteresis-zone" + nstr).c_str()); json[section][instance_name][bandn]["curve-threshold"] = g_settings_get_double(settings, ("curve-threshold" + nstr).c_str()); json[section][instance_name][bandn]["curve-zone"] = g_settings_get_double(settings, ("curve-zone" + nstr).c_str()); json[section][instance_name][bandn]["reduction"] = g_settings_get_double(settings, ("reduction" + nstr).c_str()); json[section][instance_name][bandn]["makeup"] = g_settings_get_double(settings, ("makeup" + nstr).c_str()); json[section][instance_name][bandn]["external-sidechain"] = g_settings_get_boolean(settings, ("external-sidechain" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-mode"] = util::gsettings_get_string(settings, ("sidechain-mode" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-source"] = util::gsettings_get_string(settings, ("sidechain-source" + nstr).c_str()); json[section][instance_name][bandn]["stereo-split-source"] = util::gsettings_get_string(settings, ("stereo-split-source" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-lookahead"] = g_settings_get_double(settings, ("sidechain-lookahead" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-reactivity"] = g_settings_get_double(settings, ("sidechain-reactivity" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-preamp"] = g_settings_get_double(settings, ("sidechain-preamp" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-custom-lowcut-filter"] = g_settings_get_boolean(settings, ("sidechain-custom-lowcut-filter" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-custom-highcut-filter"] = g_settings_get_boolean(settings, ("sidechain-custom-highcut-filter" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-lowcut-frequency"] = g_settings_get_double(settings, ("sidechain-lowcut-frequency" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-highcut-frequency"] = g_settings_get_double(settings, ("sidechain-highcut-frequency" + nstr).c_str()); } } void MultibandGatePreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "dry", "dry"); update_key<double>(json.at(section).at(instance_name), settings, "wet", "wet"); update_key<gchar*>(json.at(section).at(instance_name), settings, "gate-mode", "gate-mode"); update_key<gchar*>(json.at(section).at(instance_name), settings, "envelope-boost", "envelope-boost"); update_key<bool>(json.at(section).at(instance_name), settings, "stereo-split", "stereo-split"); for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); const auto bandn = "band" + nstr; if (n > 0U) { update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "enable-band" + nstr, "enable-band"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "split-frequency" + nstr, "split-frequency"); } update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "gate-enable" + nstr, "gate-enable"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "solo" + nstr, "solo"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "mute" + nstr, "mute"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "attack-time" + nstr, "attack-time"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "release-time" + nstr, "release-time"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "hysteresis" + nstr, "hysteresis"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "hysteresis-threshold" + nstr, "hysteresis-threshold"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "hysteresis-zone" + nstr, "hysteresis-zone"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "curve-threshold" + nstr, "curve-threshold"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "curve-zone" + nstr, "curve-zone"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "reduction" + nstr, "reduction"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "makeup" + nstr, "makeup"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "external-sidechain" + nstr, "external-sidechain"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-mode" + nstr, "sidechain-mode"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-source" + nstr, "sidechain-source"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "stereo-split-source" + nstr, "stereo-split-source"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-lookahead" + nstr, "sidechain-lookahead"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-reactivity" + nstr, "sidechain-reactivity"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-preamp" + nstr, "sidechain-preamp"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-custom-lowcut-filter" + nstr, "sidechain-custom-lowcut-filter"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-custom-highcut-filter" + nstr, "sidechain-custom-highcut-filter"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-lowcut-frequency" + nstr, "sidechain-lowcut-frequency"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-highcut-frequency" + nstr, "sidechain-highcut-frequency"); } }
10,435
C++
.cpp
153
60.862745
119
0.668821
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,644
maximizer_preset.cpp
wwmm_easyeffects/src/maximizer_preset.cpp
/* * 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/>. */ #include "maximizer_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" MaximizerPreset::MaximizerPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::maximizer::id, tags::schema::maximizer::input_path, tags::schema::maximizer::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::maximizer).append("#").append(util::to_string(index)); } void MaximizerPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["release"] = g_settings_get_double(settings, "release"); json[section][instance_name]["threshold"] = g_settings_get_double(settings, "threshold"); } void MaximizerPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "release", "release"); update_key<double>(json.at(section).at(instance_name), settings, "threshold", "threshold"); }
2,444
C++
.cpp
48
46.854167
97
0.713507
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,645
blocklist_menu.cpp
wwmm_easyeffects/src/blocklist_menu.cpp
/* * 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/>. */ #include "blocklist_menu.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkbutton.h> #include <gtk/gtkcheckbutton.h> #include <gtk/gtklabel.h> #include <gtk/gtklistitem.h> #include <gtk/gtklistview.h> #include <gtk/gtkpopover.h> #include <gtk/gtkscrolledwindow.h> #include <gtk/gtkshortcut.h> #include <gtk/gtksignallistitemfactory.h> #include <gtk/gtkstringlist.h> #include <gtk/gtktext.h> #include <pango/pango-layout.h> #include <sigc++/connection.h> #include <algorithm> #include <vector> #include "application.hpp" #include "pipeline_type.hpp" #include "tags_app.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "util.hpp" namespace ui::blocklist_menu { struct Data { public: ~Data() { util::debug("data struct destroyed"); } app::Application* application; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _BlocklistMenu { GtkPopover parent_instance; GtkScrolledWindow* scrolled_window; GtkListView* listview; GtkText* app_name; GtkCheckButton* show_blocklisted_apps; GtkStringList* string_list; GSettings *settings, *app_settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(BlocklistMenu, blocklist_menu, GTK_TYPE_POPOVER) void on_add_to_blocklist(BlocklistMenu* self, GtkButton* button) { auto status = util::add_new_blocklist_entry(self->settings, gtk_editable_get_text(GTK_EDITABLE(self->app_name))); if (status) { gtk_editable_set_text(GTK_EDITABLE(self->app_name), ""); } } void setup_listview(BlocklistMenu* self) { auto* factory = gtk_signal_list_item_factory_new(); // setting the factory callbacks g_signal_connect( factory, "setup", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, BlocklistMenu* self) { auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); auto* label = gtk_label_new(nullptr); auto* button = gtk_button_new_from_icon_name("user-trash-symbolic"); gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START); gtk_widget_set_hexpand(GTK_WIDGET(label), 1); gtk_label_set_ellipsize(GTK_LABEL(label), PANGO_ELLIPSIZE_END); gtk_label_set_max_width_chars(GTK_LABEL(label), 100); gtk_box_append(GTK_BOX(box), GTK_WIDGET(label)); gtk_box_append(GTK_BOX(box), GTK_WIDGET(button)); gtk_list_item_set_activatable(item, 0); gtk_list_item_set_child(item, GTK_WIDGET(box)); g_object_set_data(G_OBJECT(item), "name", label); g_object_set_data(G_OBJECT(item), "remove", button); g_signal_connect( button, "clicked", G_CALLBACK(+[](GtkButton* btn, BlocklistMenu* self) { if (auto* string_object = GTK_STRING_OBJECT(g_object_get_data(G_OBJECT(btn), "string-object")); string_object != nullptr) { auto* name = gtk_string_object_get_string(string_object); auto list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "blocklist")); list.erase( std::remove_if(list.begin(), list.end(), [=](const auto& app_name) { return app_name == name; }), list.end()); g_settings_set_strv(self->settings, "blocklist", util::make_gchar_pointer_vector(list).data()); } }), self); }), self); g_signal_connect(factory, "bind", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, BlocklistMenu* self) { auto* label = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "name")); auto* btn_remove = static_cast<GtkButton*>(g_object_get_data(G_OBJECT(item), "remove")); auto* child_item = gtk_list_item_get_item(item); auto* string_object = GTK_STRING_OBJECT(child_item); g_object_set_data(G_OBJECT(btn_remove), "string-object", string_object); auto* name = gtk_string_object_get_string(GTK_STRING_OBJECT(child_item)); gtk_label_set_text(label, name); }), self); gtk_list_view_set_factory(self->listview, factory); g_object_unref(factory); for (auto& name : util::gchar_array_to_vector(g_settings_get_strv(self->settings, "blocklist"))) { gtk_string_list_append(self->string_list, name.c_str()); } self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::blocklist", G_CALLBACK(+[](GSettings* settings, char* key, BlocklistMenu* self) { gtk_string_list_splice(self->string_list, 0, g_list_model_get_n_items(G_LIST_MODEL(self->string_list)), g_settings_get_strv(settings, key)); }), self)); } void setup(BlocklistMenu* self, app::Application* application, PipelineType pipeline_type) { self->data->application = application; switch (pipeline_type) { case PipelineType::input: { self->settings = g_settings_new(tags::schema::id_input); break; } case PipelineType::output: { self->settings = g_settings_new(tags::schema::id_output); break; } } g_settings_bind(self->settings, "show-blocklisted-apps", self->show_blocklisted_apps, "active", G_SETTINGS_BIND_DEFAULT); setup_listview(self); } void show(GtkWidget* widget) { auto* self = EE_BLOCKLIST_MENU(widget); auto* active_window = gtk_application_get_active_window(GTK_APPLICATION(self->data->application)); auto active_window_height = gtk_widget_get_height(GTK_WIDGET(active_window)); const int menu_height = static_cast<int>(0.5F * static_cast<float>(active_window_height)); gtk_scrolled_window_set_max_content_height(self->scrolled_window, menu_height); GTK_WIDGET_CLASS(blocklist_menu_parent_class)->show(widget); } void dispose(GObject* object) { auto* self = EE_BLOCKLIST_MENU(object); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); g_object_unref(self->app_settings); util::debug("disposed"); G_OBJECT_CLASS(blocklist_menu_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_BLOCKLIST_MENU(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(blocklist_menu_parent_class)->finalize(object); } void blocklist_menu_class_init(BlocklistMenuClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; widget_class->show = show; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::blocklist_menu_ui); gtk_widget_class_bind_template_child(widget_class, BlocklistMenu, string_list); gtk_widget_class_bind_template_child(widget_class, BlocklistMenu, scrolled_window); gtk_widget_class_bind_template_child(widget_class, BlocklistMenu, listview); gtk_widget_class_bind_template_child(widget_class, BlocklistMenu, app_name); gtk_widget_class_bind_template_child(widget_class, BlocklistMenu, show_blocklisted_apps); gtk_widget_class_bind_template_callback(widget_class, on_add_to_blocklist); } void blocklist_menu_init(BlocklistMenu* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->app_settings = g_settings_new(tags::app::id); g_settings_bind(self->app_settings, "autohide-popovers", self, "autohide", G_SETTINGS_BIND_DEFAULT); } auto create() -> BlocklistMenu* { return static_cast<BlocklistMenu*>(g_object_new(EE_TYPE_BLOCKLIST_MENU, nullptr)); } } // namespace ui::blocklist_menu
8,705
C++
.cpp
196
38.943878
117
0.690493
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,646
spectrum.cpp
wwmm_easyeffects/src/spectrum.cpp
/* * 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/>. */ #include "spectrum.hpp" #include <fftw3.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <cassert> #include <cmath> #include <cstddef> #include <cstring> #include <mutex> #include <numbers> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Spectrum::Spectrum(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, "spectrum", tags::plugin_package::ee, schema, schema_path, pipe_manager, pipe_type), fftw_ready(true) { // Precompute the Hann window, which is an expensive operation. // https://en.wikipedia.org/wiki/Hann_function for (size_t n = 0; n < n_bands; n++) { hann_window[n] = 0.5F * (1.0F - std::cos(2.0F * std::numbers::pi_v<float> * static_cast<float>(n) / static_cast<float>(n_bands-1))); } complex_output = fftwf_alloc_complex(n_bands); plan = fftwf_plan_dft_r2c_1d(static_cast<int>(n_bands), real_input.data(), complex_output, FFTW_ESTIMATE); lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/comp_delay_x2_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/comp_delay_x2_stereo is not installed, spectrum will not have A/V sync compensation"); } lv2_wrapper->set_control_port_value("mode_l", 2); lv2_wrapper->set_control_port_value("mode_r", 2); lv2_wrapper->set_control_port_value("dry_l", 0.0F); lv2_wrapper->set_control_port_value("dry_r", 0.0F); lv2_wrapper->set_control_port_value("wet_l", static_cast<float>(util::db_to_linear(0.0F))); lv2_wrapper->set_control_port_value("wet_r", static_cast<float>(util::db_to_linear(0.0F))); lv2_wrapper->bind_key_int<"time_l", "avsync-delay">(settings); lv2_wrapper->bind_key_int<"time_r", "avsync-delay">(settings); g_signal_connect(settings, "changed::show", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Spectrum*>(user_data); self->bypass = g_settings_get_boolean(settings, key) == 0; }), this); } Spectrum::~Spectrum() { if (connected_to_pw) { disconnect_from_pw(); } fftw_ready = false; if (complex_output != nullptr) { fftwf_free(complex_output); } fftwf_destroy_plan(plan); util::debug(log_tag + name + " destroyed"); } void Spectrum::setup() { std::ranges::fill(real_input, 0.0F); std::ranges::fill(latest_samples_mono, 0.0F); left_delayed_vector.resize(n_samples, 0.0F); right_delayed_vector.resize(n_samples, 0.0F); left_delayed = std::span<float>(left_delayed_vector); right_delayed = std::span<float>(right_delayed_vector); lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { util::debug(log_tag + " creating instance of comp delay x2 stereo for spectrum A/V sync"); lv2_wrapper->create_instance(rate); } } void Spectrum::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); if (bypass || !fftw_ready) { return; } // delay the visualization of the spectrum by the reported latency // of the output device, so that the spectrum is visually in sync // with the audio as experienced by the user. (A/V sync) if ( lv2_wrapper->found_plugin && lv2_wrapper->has_instance() ) { lv2_wrapper->connect_data_ports(left_in, right_in, left_delayed, right_delayed); lv2_wrapper->run(); // Downmix the latest n_bands samples from the delayed signal. if (n_samples < n_bands) { // Drop the oldest quantum. std::memmove(&latest_samples_mono[0], &latest_samples_mono[n_samples], (n_bands - n_samples) * sizeof(float)); // Copy the new quantum. for (size_t n = 0; n < n_samples; n++) { latest_samples_mono[n_bands - n_samples + n] = 0.5F * (left_delayed[n] + right_delayed[n]); } } else { // Copy the latest n_bands samples. for (size_t n = 0; n < n_bands; n++) latest_samples_mono[n] = 0.5F * (left_delayed[n_samples - n_bands + n] + right_delayed[n_samples - n_bands + n]); } } else { // Downmix the latest n_bands samples from the non-delayed signal. if (n_samples < n_bands) { // Drop the oldest quantum. std::memmove(&latest_samples_mono[0], &latest_samples_mono[n_samples], (n_bands - n_samples) * sizeof(float)); // Copy the new quantum. for (size_t n = 0; n < n_samples; n++) { latest_samples_mono[n_bands - n_samples + n] = 0.5F * (left_in[n] + right_in[n]); } } else { // Copy the latest n_bands samples. for (size_t n = 0; n < n_bands; n++) latest_samples_mono[n] = 0.5F * (left_in[n_samples - n_bands + n] + right_in[n_samples - n_bands + n]); } } /* * OK, we have the latest_samples_mono array that contains n_bands samples. We * want to export it to the GUI thread. We don't wakeup the GUI thread from * realtime, we only want to update the buffer and let the GUI thread follow * its scheduling and have access to our new buffer. We accept losing old data. * * For that, we want to synchronise both threads. Realtime shouldn't have to * wait (ie loop or syscall). It is fine if GUI waits a little. * * The overall concept is to use two buffers. When realtime comes in, it * writes into one. When GUI arrives, it waits for realtime to be done * writing (if it is busy) and it switches the active buffer to become the * other one. As GUI is the one doing the toggle, it knows it can read at its * pace the inactive buffer. Realtime will always have a buffer to write * into, and it is fine if it overwrites data. * * We use an atomic integer (db_control) that contains three bits: * - DB_BIT_IDX: the current buffer index. * - DB_BIT_NEWDATA: indicates if realtime wrote new data. * - DB_BIT_BUSY: indicates if realtime is currently busy writing data. * * Realtime does this: * - Grab db_control and enable its BUSY bit. * - Write data into the correct buffer based on the IDX bit. * - Write db_control with same index as before, BUSY bit disabled and * NEWDATA bit enabled. * * GUI does this: * - Early return if NEWDATA is not enabled. It means realtime hasn't ran * since the last time GUI ran. * - Then it tries toggling the IDX bit. "Tries" because the operation fails * as long as the BUSY bit is active. * - From now on it can read the previous buffer knowing realtime cannot be * writing into it. * * This is single-producer single-consumer double-buffering. The * implementation is inspired from the "Real-time 101" ADC19 talk * (David Rowland & Fabian Renn-Giles). * * Talk part 1 & 2, slides (page 74 onwards) and illustrating library: * https://www.youtube.com/watch?v=Q0vrQFyAdWI * https://www.youtube.com/watch?v=PoZAo2Vikbo * https://github.com/drowaudio/presentations/blob/master/ADC%202019%20-%20Real-time%20101/Real-time%20101.pdf * https://github.com/hogliux/farbot */ // Grab the current index AND mark as busy at the same time. int index = db_control.fetch_or(DB_BIT_BUSY) & DB_BIT_IDX; // Fill the buffer. db_buffers[index] = latest_samples_mono; // Mark new data available AND mark as not busy anymore. db_control.store(index | DB_BIT_NEWDATA); } std::tuple<uint, uint, double*> Spectrum::compute_magnitudes() { // Early return if no new data is available, ie if process() has not been // called since our last compute_magnitudes() call. int curr_control = db_control.load(); if (!(curr_control & DB_BIT_NEWDATA)) { return std::tuple<uint, uint, double*>(0, 0, nullptr); } // CAS loop to toggle the buffer used and remove NEWDATA flag, waiting for !BUSY. int next_control; do { curr_control &= ~DB_BIT_BUSY; next_control = (curr_control ^ DB_BIT_IDX) & DB_BIT_IDX; } while (!db_control.compare_exchange_weak(curr_control, next_control)); // Buffer with data is at the index which was found inside db_control. int index = curr_control & DB_BIT_IDX; float *buf = db_buffers[index].data(); // https://en.wikipedia.org/wiki/Hann_function for (size_t n = 0; n < n_bands; n++) { real_input[n] = buf[n] * hann_window[n]; } fftwf_execute(plan); for (uint i = 0U; i < output.size(); i++) { float sqr = complex_output[i][0] * complex_output[i][0] + complex_output[i][1] * complex_output[i][1]; sqr /= static_cast<float>(output.size() * output.size()); output[i] = static_cast<double>(sqr); } return std::tuple<uint, uint, double*>(rate, output.size(), output.data()); } auto Spectrum::get_latency_seconds() -> float { return 0.0F; }
10,104
C++
.cpp
225
39.928889
144
0.662327
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,647
plugins_box.cpp
wwmm_easyeffects/src/plugins_box.cpp
/* * 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/>. */ #include "plugins_box.hpp" #include <STTypes.h> #include <adwaita.h> #include <gdk/gdk.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdroptarget.h> #include <gtk/gtkshortcut.h> #include <gtk/gtkwidgetpaintable.h> #include <sigc++/connection.h> #include <algorithm> #include <map> #include <ranges> #include <string> #include <vector> #include "application.hpp" #include "autogain.hpp" #include "autogain_ui.hpp" #include "bass_enhancer.hpp" #include "bass_enhancer_ui.hpp" #include "bass_loudness.hpp" #include "bass_loudness_ui.hpp" #include "compressor.hpp" #include "compressor_ui.hpp" #include "convolver.hpp" #include "convolver_ui.hpp" #include "crossfeed.hpp" #include "crossfeed_ui.hpp" #include "crystalizer.hpp" #include "crystalizer_ui.hpp" #include "deepfilternet.hpp" #include "deepfilternet_ui.hpp" #include "deesser.hpp" #include "deesser_ui.hpp" #include "delay.hpp" #include "delay_ui.hpp" #include "echo_canceller.hpp" #include "echo_canceller_ui.hpp" #include "effects_base.hpp" #include "equalizer.hpp" #include "equalizer_ui.hpp" #include "exciter.hpp" #include "exciter_ui.hpp" #include "expander.hpp" #include "expander_ui.hpp" #include "filter.hpp" #include "filter_ui.hpp" #include "gate.hpp" #include "gate_ui.hpp" #include "level_meter.hpp" #include "level_meter_ui.hpp" #include "limiter.hpp" #include "limiter_ui.hpp" #include "loudness.hpp" #include "loudness_ui.hpp" #include "maximizer.hpp" #include "maximizer_ui.hpp" #include "multiband_compressor.hpp" #include "multiband_compressor_ui.hpp" #include "multiband_gate.hpp" #include "multiband_gate_ui.hpp" #include "pipeline_type.hpp" #include "pitch.hpp" #include "pitch_ui.hpp" #include "plugins_menu.hpp" #include "reverb.hpp" #include "reverb_ui.hpp" #include "rnnoise.hpp" #include "rnnoise_ui.hpp" #include "speex.hpp" #include "speex_ui.hpp" #include "stereo_tools.hpp" #include "stereo_tools_ui.hpp" #include "tags_app.hpp" #include "tags_plugin_name.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::plugins_box { using namespace std::string_literals; struct Data { public: Data() { this->translated = tags::plugin_name::get_translated(); } ~Data() { util::debug("data struct destroyed"); } bool schedule_signal_idle = false; app::Application* application = nullptr; PipelineType pipeline_type{}; std::string schema_path; std::map<std::string, std::string> translated; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _PluginsBox { GtkBox parent_instance; GtkToggleButton* toggle_plugins_list; GtkMenuButton* menubutton_plugins; GtkOverlay* plugin_overlay; AdwStatusPage* overlay_no_plugins; GtkListView* listview; GtkStack* stack; GtkBox *startpoint_box, *endpoint_box; GtkImage *startpoint_icon, *endpoint_icon; GtkLabel *startpoint_name, *endpoint_name; ui::plugins_menu::PluginsMenu* plugins_menu; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PluginsBox, plugins_box, GTK_TYPE_BOX) template <PipelineType pipeline_type> void add_plugins_to_stack(PluginsBox* self) { EffectsBase* effects_base = nullptr; if constexpr (pipeline_type == PipelineType::input) { effects_base = self->data->application->sie; } else if constexpr (pipeline_type == PipelineType::output) { effects_base = self->data->application->soe; } // saving the current visible page name for later usage const std::string visible_page_name = (gtk_stack_get_visible_child_name(self->stack) != nullptr) ? gtk_stack_get_visible_child_name(self->stack) : ""; // removing all plugins for (auto* child = gtk_widget_get_first_child(GTK_WIDGET(self->stack)); child != nullptr;) { auto* next_child = gtk_widget_get_next_sibling(child); uint serial = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(child), "serial")); set_ignore_filter_idle_add(serial, true); gtk_stack_remove(self->stack, child); child = next_child; } // Adding to the stack the plugins in the list that are not there yet auto plugins_list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "plugins")); for (const auto& name : plugins_list) { auto path = self->data->schema_path + tags::plugin_name::get_base_name(name) + "/" + util::to_string(tags::plugin_name::get_id(name)) + "/"; path.erase(std::remove(path.begin(), path.end(), '_'), path.end()); if (name.starts_with(tags::plugin_name::autogain)) { auto plugin_ptr = effects_base->get_plugin_instance<AutoGain>(name); auto* box = ui::autogain_box::create(); ui::autogain_box::setup(box, plugin_ptr, path); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::bass_enhancer)) { auto plugin_ptr = effects_base->get_plugin_instance<BassEnhancer>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::bass_enhancer_box::create(); ui::bass_enhancer_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::bass_loudness)) { auto plugin_ptr = effects_base->get_plugin_instance<BassLoudness>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::bass_loudness_box::create(); ui::bass_loudness_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::compressor)) { auto plugin_ptr = effects_base->get_plugin_instance<Compressor>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::compressor_box::create(); ui::compressor_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (name.starts_with(tags::plugin_name::convolver)) { auto plugin_ptr = effects_base->get_plugin_instance<Convolver>(name); auto* box = ui::convolver_box::create(); ui::convolver_box::setup(box, plugin_ptr, path, self->data->application); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (name.starts_with(tags::plugin_name::crossfeed)) { auto plugin_ptr = effects_base->get_plugin_instance<Crossfeed>(name); auto* box = ui::crossfeed_box::create(); ui::crossfeed_box::setup(box, plugin_ptr, path); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (name.starts_with(tags::plugin_name::crystalizer)) { auto plugin_ptr = effects_base->get_plugin_instance<Crystalizer>(name); auto* box = ui::crystalizer_box::create(); ui::crystalizer_box::setup(box, plugin_ptr, path); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::deepfilternet)) { auto plugin_ptr = effects_base->get_plugin_instance<DeepFilterNet>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::deepfilternet_box::create(); ui::deepfilternet_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::deesser)) { auto plugin_ptr = effects_base->get_plugin_instance<Deesser>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::deesser_box::create(); ui::deesser_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::delay)) { auto plugin_ptr = effects_base->get_plugin_instance<Delay>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::delay_box::create(); ui::delay_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (name.starts_with(tags::plugin_name::echo_canceller)) { auto plugin_ptr = effects_base->get_plugin_instance<EchoCanceller>(name); auto* box = ui::echo_canceller_box::create(); ui::echo_canceller_box::setup(box, plugin_ptr, path); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::exciter)) { auto plugin_ptr = effects_base->get_plugin_instance<Exciter>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::exciter_box::create(); ui::exciter_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::expander)) { auto plugin_ptr = effects_base->get_plugin_instance<Expander>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::expander_box::create(); ui::expander_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::equalizer)) { auto plugin_ptr = effects_base->get_plugin_instance<Equalizer>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::equalizer_box::create(); ui::equalizer_box::setup(plugin_box, plugin_ptr, path, self->data->application); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::filter)) { auto plugin_ptr = effects_base->get_plugin_instance<Filter>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::filter_box::create(); ui::filter_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::gate)) { auto plugin_ptr = effects_base->get_plugin_instance<Gate>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::gate_box::create(); ui::gate_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::level_meter)) { auto plugin_ptr = effects_base->get_plugin_instance<LevelMeter>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::level_meter_box::create(); ui::level_meter_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::limiter)) { auto plugin_ptr = effects_base->get_plugin_instance<Limiter>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::limiter_box::create(); ui::limiter_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::loudness)) { auto plugin_ptr = effects_base->get_plugin_instance<Loudness>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::loudness_box::create(); ui::loudness_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::maximizer)) { auto plugin_ptr = effects_base->get_plugin_instance<Maximizer>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::maximizer_box::create(); ui::maximizer_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::multiband_compressor)) { auto plugin_ptr = effects_base->get_plugin_instance<MultibandCompressor>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::multiband_compressor_box::create(); ui::multiband_compressor_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::multiband_gate)) { auto plugin_ptr = effects_base->get_plugin_instance<MultibandGate>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::multiband_gate_box::create(); ui::multiband_gate_box::setup(plugin_box, plugin_ptr, path, self->data->application->pm); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (name.starts_with(tags::plugin_name::pitch)) { auto plugin_ptr = effects_base->get_plugin_instance<Pitch>(name); auto* box = ui::pitch_box::create(); ui::pitch_box::setup(box, plugin_ptr, path); gtk_stack_add_named(self->stack, GTK_WIDGET(box), name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::reverb)) { auto plugin_ptr = effects_base->get_plugin_instance<Reverb>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::reverb_box::create(); ui::reverb_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::rnnoise)) { auto plugin_ptr = effects_base->get_plugin_instance<RNNoise>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::rnnoise_box::create(); ui::rnnoise_box::setup(plugin_box, plugin_ptr, path, self->data->application); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::speex)) { auto plugin_ptr = effects_base->get_plugin_instance<Speex>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::speex_box::create(); ui::speex_box::setup(plugin_box, plugin_ptr, path, self->data->application); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } else if (GtkWidget* box = nullptr; name.starts_with(tags::plugin_name::stereo_tools)) { auto plugin_ptr = effects_base->get_plugin_instance<StereoTools>(name); if (plugin_ptr->package_installed) { auto* plugin_box = ui::stereo_tools_box::create(); ui::stereo_tools_box::setup(plugin_box, plugin_ptr, path); box = GTK_WIDGET(plugin_box); } else { box = ui::missing_plugin_box(plugin_ptr->name, plugin_ptr->package); } gtk_stack_add_named(self->stack, box, name.c_str()); } } if (plugins_list.empty()) { gtk_widget_set_visible(GTK_WIDGET(self->overlay_no_plugins), 1); gtk_widget_set_visible(GTK_WIDGET(self->startpoint_box), 0); gtk_widget_set_visible(GTK_WIDGET(self->endpoint_box), 0); } else { gtk_widget_set_visible(GTK_WIDGET(self->overlay_no_plugins), 0); gtk_widget_set_visible(GTK_WIDGET(self->startpoint_box), 1); gtk_widget_set_visible(GTK_WIDGET(self->endpoint_box), 1); if (std::ranges::find(plugins_list, visible_page_name) != plugins_list.end()) { gtk_stack_set_visible_child_name(self->stack, visible_page_name.c_str()); } } } void show_adjacent_plugin(PluginsBox* self, const int& increment) { const auto plugins_list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "plugins")); if (plugins_list.empty()) { return; } const std::string visible_page_name = (gtk_stack_get_visible_child_name(self->stack) != nullptr) ? gtk_stack_get_visible_child_name(self->stack) : ""; if (visible_page_name.empty()) { return; } auto it = std::ranges::find(plugins_list, visible_page_name); if (it == plugins_list.end()) { return; } if (auto adj_it = it + increment; adj_it >= plugins_list.begin() && adj_it < plugins_list.end()) { gtk_stack_set_visible_child_name(self->stack, (*adj_it).c_str()); } } void on_prev_plugin(PluginsBox* self, GtkButton* button) { show_adjacent_plugin(self, -1); } void on_next_plugin(PluginsBox* self, GtkButton* button) { show_adjacent_plugin(self, 1); } void setup_listview(PluginsBox* self) { auto* factory = gtk_signal_list_item_factory_new(); // setting the factory callbacks g_signal_connect( factory, "setup", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PluginsBox* self) { auto builder = gtk_builder_new_from_resource(tags::resources::plugin_row_ui); auto* top_box = gtk_builder_get_object(builder, "top_box"); auto* plugin_enabled_icon = gtk_builder_get_object(builder, "plugin_enabled_icon"); auto* plugin_bypassed_icon = gtk_builder_get_object(builder, "plugin_bypassed_icon"); auto* remove = gtk_builder_get_object(builder, "remove"); auto* enable = gtk_builder_get_object(builder, "enable"); auto* drag_handle = gtk_builder_get_object(builder, "drag_handle"); g_object_set_data(G_OBJECT(item), "top_box", top_box); g_object_set_data(G_OBJECT(item), "plugin_enabled_icon", plugin_enabled_icon); g_object_set_data(G_OBJECT(item), "plugin_bypassed_icon", plugin_bypassed_icon); g_object_set_data(G_OBJECT(item), "name", gtk_builder_get_object(builder, "name")); g_object_set_data(G_OBJECT(item), "remove", remove); g_object_set_data(G_OBJECT(item), "enable", enable); g_object_set_data(G_OBJECT(item), "drag_handle", drag_handle); gtk_list_item_set_child(item, GTK_WIDGET(top_box)); g_object_unref(builder); // showing/hiding icons based on wether the mouse is over the plugin row auto* controller = gtk_event_controller_motion_new(); g_object_set_data(G_OBJECT(controller), "remove", remove); g_object_set_data(G_OBJECT(controller), "enable", enable); g_object_set_data(G_OBJECT(controller), "drag_handle", drag_handle); g_signal_connect(controller, "enter", G_CALLBACK(+[](GtkEventControllerMotion* controller, gdouble x, gdouble y, PluginsBox* self) { gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "remove")), 1.0); gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "enable")), 1.0); gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "drag_handle")), 1.0); }), self); g_signal_connect(controller, "leave", G_CALLBACK(+[](GtkEventControllerMotion* controller, PluginsBox* self) { gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "remove")), 0.0); gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "enable")), 0.0); gtk_widget_set_opacity(GTK_WIDGET(g_object_get_data(G_OBJECT(controller), "drag_handle")), 0.0); }), self); gtk_widget_add_controller(GTK_WIDGET(top_box), controller); // Configuring row drag and drop auto* drag_source = gtk_drag_source_new(); gtk_drag_source_set_actions(drag_source, GDK_ACTION_MOVE); g_object_set_data(G_OBJECT(drag_source), "top_box", top_box); g_signal_connect( drag_source, "prepare", G_CALLBACK(+[](GtkDragSource* source, double x, double y, PluginsBox* self) { auto* top_box = static_cast<GtkBox*>(g_object_get_data(G_OBJECT(source), "top_box")); auto* paintable = gtk_widget_paintable_new(GTK_WIDGET(top_box)); gtk_drag_source_set_icon(source, paintable, 0, 0); if (auto* plugin_name = static_cast<const char*>(g_object_get_data(G_OBJECT(top_box), "page-name")); plugin_name != nullptr) { return gdk_content_provider_new_typed(G_TYPE_STRING, plugin_name); } return gdk_content_provider_new_typed(G_TYPE_STRING, ""); }), self); auto* drop_target = gtk_drop_target_new(G_TYPE_STRING, GDK_ACTION_MOVE); g_object_set_data(G_OBJECT(drop_target), "top_box", top_box); g_signal_connect( drop_target, "drop", G_CALLBACK(+[](GtkDropTarget* target, const GValue* value, double x, double y, PluginsBox* self) { if (!G_VALUE_HOLDS(value, G_TYPE_STRING)) { return false; } auto* top_box = static_cast<GtkBox*>(g_object_get_data(G_OBJECT(target), "top_box")); if (auto* dst = static_cast<const char*>(g_object_get_data(G_OBJECT(top_box), "page-name")); dst != nullptr) { auto* src = g_value_get_string(value); if (g_strcmp0(src, dst) != 0) { auto list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "plugins")); auto iter_src = std::ranges::find(list, src); auto iter_dst = std::ranges::find(list, dst); auto insert_after = iter_src - list.begin() < iter_dst - list.begin(); list.erase(iter_src); iter_dst = std::ranges::find(list, dst); list.insert(((insert_after) ? (iter_dst + 1) : iter_dst), src); g_settings_set_strv(self->settings, "plugins", util::make_gchar_pointer_vector(list).data()); return true; } return false; } return false; }), self); gtk_widget_add_controller(GTK_WIDGET(drag_handle), GTK_EVENT_CONTROLLER(drag_source)); gtk_widget_add_controller(GTK_WIDGET(top_box), GTK_EVENT_CONTROLLER(drop_target)); g_signal_connect(remove, "clicked", G_CALLBACK(+[](GtkButton* btn, PluginsBox* self) { if (auto* name = static_cast<const char*>(g_object_get_data(G_OBJECT(btn), "page-name")); name != nullptr) { auto list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "plugins")); list.erase(std::remove_if(list.begin(), list.end(), [=](const auto& plugin_name) { return plugin_name == name; }), list.end()); g_settings_set_strv(self->settings, "plugins", util::make_gchar_pointer_vector(list).data()); } }), self); }), self); g_signal_connect( factory, "bind", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PluginsBox* self) { auto* top_box = static_cast<GtkBox*>(g_object_get_data(G_OBJECT(item), "top_box")); auto* label = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "name")); auto* remove = static_cast<GtkButton*>(g_object_get_data(G_OBJECT(item), "remove")); auto* enable = static_cast<GtkToggleButton*>(g_object_get_data(G_OBJECT(item), "enable")); auto* child_item = gtk_list_item_get_item(item); auto page = GTK_STACK_PAGE(child_item); auto page_name = gtk_stack_page_get_name(page); const auto base_name = tags::plugin_name::get_base_name(page_name); g_object_set_data(G_OBJECT(top_box), "page-name", const_cast<char*>(page_name)); g_object_set_data(G_OBJECT(remove), "page-name", const_cast<char*>(page_name)); gtk_label_set_text(label, self->data->translated[base_name].c_str()); gtk_accessible_update_property(GTK_ACCESSIBLE(remove), GTK_ACCESSIBLE_PROPERTY_LABEL, (_("Remove") + " "s + self->data->translated[base_name]).c_str(), -1); // binding the enable button to the bypass key auto gname = base_name; gname.erase(std::remove(gname.begin(), gname.end(), '_'), gname.end()); auto schema_path = self->data->schema_path + gname + "/" + util::to_string(tags::plugin_name::get_id(page_name)) + "/"; auto schema_id = tags::app::id + "."s + gname; auto* settings = g_settings_new_with_path(schema_id.c_str(), schema_path.c_str()); gsettings_bind_widget(settings, "bypass", enable, G_SETTINGS_BIND_INVERT_BOOLEAN); g_object_unref(settings); }), self); gtk_list_view_set_factory(self->listview, factory); g_object_unref(factory); } void setup(PluginsBox* self, app::Application* application, PipelineType pipeline_type) { self->data->application = application; self->data->pipeline_type = pipeline_type; switch (pipeline_type) { case PipelineType::input: { self->settings = g_settings_new(tags::schema::id_input); self->data->schema_path = tags::app::path_stream_inputs; add_plugins_to_stack<PipelineType::input>(self); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::plugins", G_CALLBACK(+[](GSettings* settings, char* key, PluginsBox* self) { add_plugins_to_stack<PipelineType::input>(self); }), self)); gtk_image_set_from_icon_name(self->startpoint_icon, "audio-input-microphone-symbolic"); gtk_image_set_from_icon_name(self->endpoint_icon, "ee-applications-multimedia-symbolic"); gtk_label_set_text(self->startpoint_name, _("Input Device")); gtk_label_set_text(self->endpoint_name, _("Recorders")); break; } case PipelineType::output: { self->settings = g_settings_new(tags::schema::id_output); self->data->schema_path = tags::app::path_stream_outputs; add_plugins_to_stack<PipelineType::output>(self); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::plugins", G_CALLBACK(+[](GSettings* settings, char* key, PluginsBox* self) { add_plugins_to_stack<PipelineType::output>(self); }), self)); gtk_image_set_from_icon_name(self->startpoint_icon, "ee-applications-multimedia-symbolic"); gtk_image_set_from_icon_name(self->endpoint_icon, "audio-speakers-symbolic"); gtk_label_set_text(self->startpoint_name, _("Players")); gtk_label_set_text(self->endpoint_name, _("Output Device")); break; } } gsettings_bind_widget(self->settings, "show-plugins-list", self->toggle_plugins_list); ui::plugins_menu::setup(self->plugins_menu, application, pipeline_type); setup_listview(self); } void realize(GtkWidget* widget) { auto* self = EE_PLUGINS_BOX(widget); self->data->schedule_signal_idle = true; GTK_WIDGET_CLASS(plugins_box_parent_class)->realize(widget); } void unroot(GtkWidget* widget) { auto* self = EE_PLUGINS_BOX(widget); self->data->schedule_signal_idle = false; GTK_WIDGET_CLASS(plugins_box_parent_class)->unroot(widget); } void dispose(GObject* object) { auto* self = EE_PLUGINS_BOX(object); // Setting post_messages = false for all plugins now that the window is not visible. EffectsBase* effects_base = nullptr; if (self->data->pipeline_type == PipelineType::input) { effects_base = self->data->application->sie; } else if (self->data->pipeline_type == PipelineType::output) { effects_base = self->data->application->soe; } for (auto& plugin : effects_base->get_plugins_map() | std::views::values) { plugin->set_post_messages(false); } // Removing gsettings connections for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); // Trying to avoid that the functions scheduled by the plugins are executed when the widgets have already been // disposed for (auto* child = gtk_widget_get_first_child(GTK_WIDGET(self->stack)); child != nullptr;) { auto* next_child = gtk_widget_get_next_sibling(child); uint serial = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(child), "serial")); set_ignore_filter_idle_add(serial, true); child = next_child; } util::debug("disposed"); G_OBJECT_CLASS(plugins_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_PLUGINS_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(plugins_box_parent_class)->finalize(object); } void plugins_box_class_init(PluginsBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; widget_class->realize = realize; widget_class->unroot = unroot; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::plugins_box_ui); gtk_widget_class_bind_template_child(widget_class, PluginsBox, toggle_plugins_list); gtk_widget_class_bind_template_child(widget_class, PluginsBox, menubutton_plugins); gtk_widget_class_bind_template_child(widget_class, PluginsBox, plugin_overlay); gtk_widget_class_bind_template_child(widget_class, PluginsBox, overlay_no_plugins); gtk_widget_class_bind_template_child(widget_class, PluginsBox, listview); gtk_widget_class_bind_template_child(widget_class, PluginsBox, stack); gtk_widget_class_bind_template_child(widget_class, PluginsBox, startpoint_box); gtk_widget_class_bind_template_child(widget_class, PluginsBox, startpoint_icon); gtk_widget_class_bind_template_child(widget_class, PluginsBox, startpoint_name); gtk_widget_class_bind_template_child(widget_class, PluginsBox, endpoint_box); gtk_widget_class_bind_template_child(widget_class, PluginsBox, endpoint_icon); gtk_widget_class_bind_template_child(widget_class, PluginsBox, endpoint_name); gtk_widget_class_bind_template_callback(widget_class, on_prev_plugin); gtk_widget_class_bind_template_callback(widget_class, on_next_plugin); } void plugins_box_init(PluginsBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->data->schedule_signal_idle = false; self->plugins_menu = ui::plugins_menu::create(); gtk_menu_button_set_popover(self->menubutton_plugins, GTK_WIDGET(self->plugins_menu)); gtk_overlay_set_clip_overlay(self->plugin_overlay, GTK_WIDGET(self->overlay_no_plugins), 1); } auto create() -> PluginsBox* { return static_cast<PluginsBox*>(g_object_new(EE_TYPE_PLUGINS_BOX, nullptr)); } } // namespace ui::plugins_box
34,987
C++
.cpp
691
43.431259
119
0.653646
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,648
plugins_menu.cpp
wwmm_easyeffects/src/plugins_menu.cpp
/* * 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/>. */ #include "plugins_menu.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkshortcut.h> #include <sigc++/connection.h> #include <algorithm> #include <array> #include <map> #include <ranges> #include <string> #include <vector> #include "application.hpp" #include "pipeline_type.hpp" #include "tags_app.hpp" #include "tags_plugin_name.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "util.hpp" namespace ui::plugins_menu { using namespace std::string_literals; struct Data { public: Data() { this->translated = tags::plugin_name::get_translated(); } ~Data() { util::debug("data struct destroyed"); } bool schedule_signal_idle; app::Application* application; std::map<std::string, std::string> translated; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _PluginsMenu { GtkPopover parent_instance; GtkScrolledWindow* scrolled_window; GtkListView* listview; GtkStringList* string_list; GSettings *settings, *app_settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PluginsMenu, plugins_menu, GTK_TYPE_POPOVER) void add_new_plugin_to_pipeline(GtkButton* btn, PluginsMenu* self) { auto* string_object = GTK_STRING_OBJECT(g_object_get_data(G_OBJECT(btn), "string-object")); if (string_object == nullptr) { return; } auto* translated_name = gtk_string_object_get_string(string_object); std::string base_name; for (const auto& [key, value] : self->data->translated) { if (translated_name == value) { base_name = key; break; } } if (base_name.empty()) { return; } auto list = util::gchar_array_to_vector(g_settings_get_strv(self->settings, "plugins")); std::vector<uint> index_list; for (const auto& name : list) { if (tags::plugin_name::get_base_name(name) == base_name) { index_list.emplace_back(tags::plugin_name::get_id(name)); } } auto new_id = (index_list.empty()) ? 0 : std::ranges::max(index_list) + 1; auto new_name = base_name + "#" + util::to_string(new_id); if (list.empty()) { list.push_back(new_name); g_settings_set_strv(self->settings, "plugins", util::make_gchar_pointer_vector(list).data()); return; } // If the list is not empty and the user is careful protecting // their device with a plugin of type limiter at the last position // of the filter chain, we follow this behaviour trying to insert // the new plugin at the second to last position. // To do so, we first check if the new plugin is a limiter or the // level meter and place it directly at the last position (those // plugins do not need to be placed elsewhere and in most of the // cases the user wants them at the bottom of the pipeline). static constexpr auto limiters_and_meters = std::to_array({tags::plugin_name::limiter, tags::plugin_name::maximizer, tags::plugin_name::level_meter}); if (std::any_of(limiters_and_meters.begin(), limiters_and_meters.end(), [&](const auto& str) { return new_name.starts_with(str); })) { list.push_back(new_name); g_settings_set_strv(self->settings, "plugins", util::make_gchar_pointer_vector(list).data()); return; } // If the new plugin is not one of the above mentioned, we have to // check the last plugin of the pipeline handling various cases. static constexpr auto limiters = std::to_array({tags::plugin_name::limiter, tags::plugin_name::maximizer}); if (std::any_of(limiters.begin(), limiters.end(), [&](const auto& str) { return list.back().starts_with(str); })) { // If the last plugin is a limiter, we place the new plugin at // the second to last position. list.insert(list.cend() - 1U, new_name); } else if (list.back().starts_with(tags::plugin_name::level_meter)) { // If the last plugin is not a limiter, but a level meter, we still // try to place the new plugin before a limiter, if this limiter is in // the second to last position. // The reason is that we still want to preserve the "limiter protection" // in case the last plugins are a limiter followed by a meter. // Calculate the position of the second to last element. const auto second_to_last_pos = std::max(static_cast<int>(list.size()) - 2, 0); // Check if the plugin at the second to last position is a limiter. if (std::any_of(limiters.begin(), limiters.end(), [&](const auto& str) { return list.at(second_to_last_pos).starts_with(str); })) { // It's a limiter, so place the new plugin before it. const auto second_to_last_iter = std::max(list.cend() - 2U, list.cbegin()); list.insert(second_to_last_iter, new_name); } else { // It's not a limiter, so place the new plugin after the level meter. list.push_back(new_name); } } else { // If the last plugin is neither a limiter nor a meter, just place // the new plugin at the last position. list.push_back(new_name); } g_settings_set_strv(self->settings, "plugins", util::make_gchar_pointer_vector(list).data()); } void setup_listview(PluginsMenu* self) { auto* factory = gtk_signal_list_item_factory_new(); // setting the factory callbacks g_signal_connect(factory, "setup", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PluginsMenu* self) { auto* box = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); auto* label = gtk_label_new(nullptr); auto* button = gtk_button_new_from_icon_name("list-add-symbolic"); gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_START); gtk_widget_set_hexpand(GTK_WIDGET(label), 1); gtk_box_append(GTK_BOX(box), GTK_WIDGET(label)); gtk_box_append(GTK_BOX(box), GTK_WIDGET(button)); gtk_widget_add_css_class(GTK_WIDGET(button), "circular"); gtk_list_item_set_activatable(item, 0); gtk_list_item_set_child(item, GTK_WIDGET(box)); g_object_set_data(G_OBJECT(item), "name", label); g_object_set_data(G_OBJECT(item), "add", button); g_signal_connect(button, "clicked", G_CALLBACK(add_new_plugin_to_pipeline), self); }), self); g_signal_connect(factory, "bind", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, PluginsMenu* self) { auto* label = static_cast<GtkLabel*>(g_object_get_data(G_OBJECT(item), "name")); auto* btn_add = static_cast<GtkButton*>(g_object_get_data(G_OBJECT(item), "add")); auto* child_item = gtk_list_item_get_item(item); auto* string_object = GTK_STRING_OBJECT(child_item); g_object_set_data(G_OBJECT(btn_add), "string-object", string_object); auto* translated_name = gtk_string_object_get_string(GTK_STRING_OBJECT(child_item)); gtk_label_set_text(label, translated_name); gtk_accessible_update_property(GTK_ACCESSIBLE(btn_add), GTK_ACCESSIBLE_PROPERTY_LABEL, (_("Add") + " "s + translated_name).c_str(), -1); }), self); gtk_list_view_set_factory(self->listview, factory); g_object_unref(factory); for (const auto& translated_name : std::views::values(self->data->translated)) { gtk_string_list_append(self->string_list, translated_name.c_str()); } } void setup(PluginsMenu* self, app::Application* application, PipelineType pipeline_type) { self->data->application = application; switch (pipeline_type) { case PipelineType::input: { self->settings = g_settings_new(tags::schema::id_input); break; } case PipelineType::output: { self->settings = g_settings_new(tags::schema::id_output); break; } } setup_listview(self); } void show(GtkWidget* widget) { auto* self = EE_PLUGINS_MENU(widget); auto* active_window = gtk_application_get_active_window(GTK_APPLICATION(self->data->application)); auto active_window_height = gtk_widget_get_height(GTK_WIDGET(active_window)); const int menu_height = static_cast<int>(0.5F * static_cast<float>(active_window_height)); gtk_scrolled_window_set_max_content_height(self->scrolled_window, menu_height); GTK_WIDGET_CLASS(plugins_menu_parent_class)->show(widget); } void dispose(GObject* object) { auto* self = EE_PLUGINS_MENU(object); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); g_object_unref(self->app_settings); util::debug("disposed"); G_OBJECT_CLASS(plugins_menu_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_PLUGINS_MENU(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(plugins_menu_parent_class)->finalize(object); } void plugins_menu_class_init(PluginsMenuClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; widget_class->show = show; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::plugins_menu_ui); gtk_widget_class_bind_template_child(widget_class, PluginsMenu, string_list); gtk_widget_class_bind_template_child(widget_class, PluginsMenu, scrolled_window); gtk_widget_class_bind_template_child(widget_class, PluginsMenu, listview); } void plugins_menu_init(PluginsMenu* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->app_settings = g_settings_new(tags::app::id); g_settings_bind(self->app_settings, "autohide-popovers", self, "autohide", G_SETTINGS_BIND_DEFAULT); } auto create() -> PluginsMenu* { return static_cast<PluginsMenu*>(g_object_new(EE_TYPE_PLUGINS_MENU, nullptr)); } } // namespace ui::plugins_menu
11,164
C++
.cpp
244
39.918033
117
0.674032
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,649
equalizer_ui.cpp
wwmm_easyeffects/src/equalizer_ui.cpp
/* * 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/>. */ #include "equalizer_ui.hpp" #include <STTypes.h> #include <adwaita.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <sigc++/connection.h> #include <algorithm> #include <cctype> #include <cmath> #include <filesystem> #include <fstream> #include <memory> #include <numbers> #include <numeric> #include <regex> #include <sstream> #include <stdexcept> #include <string> #include <vector> #include "application.hpp" #include "equalizer.hpp" #include "equalizer_band_box.hpp" #include "tags_equalizer.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::equalizer_box { using namespace tags::equalizer; enum Channel { left, right }; struct APO_Band { std::string type; float freq = 1000.0F; float gain = 0.0F; float quality = (1.0F / std::numbers::sqrt2_v<float>); // default in LSP APO import }; struct GraphicEQ_Band { float freq = 1000.0F; float gain = 0.0F; }; std::map<std::string, std::string> const ApoToEasyEffectsFilter = { {"OFF", "Off"}, {"PK", "Bell"}, {"MODAL", "Bell"}, {"PEQ", "Bell"}, {"LP", "Lo-pass"}, {"LPQ", "Lo-pass"}, {"HP", "Hi-pass"}, {"HPQ", "Hi-pass"}, {"BP", "Bandpass"}, {"LS", "Lo-shelf"}, {"LSC", "Lo-shelf"}, {"LS 6DB", "Lo-shelf"}, {"LS 12DB", "Lo-shelf"}, {"HS", "Hi-shelf"}, {"HSC", "Hi-shelf"}, {"HS 6DB", "Hi-shelf"}, {"HS 12DB", "Hi-shelf"}, {"NO", "Notch"}, {"AP", "Allpass"}}; std::map<std::string, std::string> const EasyEffectsToApoFilter = { {"Bell", "PK"}, {"Lo-pass", "LPQ"}, {"Hi-pass", "HPQ"}, {"Lo-shelf", "LSC"}, {"Hi-shelf", "HSC"}, {"Notch", "NO"}, {"Allpass", "AP"}, {"Bandpass", "BP"}}; struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; app::Application* application{}; std::shared_ptr<Equalizer> equalizer; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _EqualizerBox { GtkBox parent_instance; AdwToastOverlay* toast_overlay; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkStack* stack; GtkListView *listview_left, *listview_right; GtkSpinButton *nbands, *balance, *pitch_left, *pitch_right; GtkDropDown* mode; GtkToggleButton *split_channels, *show_native_ui; GSettings *settings, *settings_left, *settings_right; GtkStringList *string_list_left, *string_list_right; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(EqualizerBox, equalizer_box, GTK_TYPE_BOX) void on_reset(EqualizerBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); util::reset_all_keys_except(self->settings_left); util::reset_all_keys_except(self->settings_right); } void on_show_native_window(EqualizerBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->equalizer->show_native_ui(); } else { self->data->equalizer->close_native_ui(); } } void on_flat_response(EqualizerBox* self, GtkButton* btn) { const auto& max_bands = self->data->equalizer->max_bands; for (uint n = 0U; n < max_bands; n++) { g_settings_reset(self->settings_left, band_gain[n].data()); g_settings_reset(self->settings_right, band_gain[n].data()); } } void on_calculate_frequencies(EqualizerBox* self, GtkButton* btn) { constexpr double min_freq = 20.0; constexpr double max_freq = 20000.0; double freq0 = min_freq; double freq1 = 0.0; const auto nbands = g_settings_get_int(self->settings, "num-bands"); // code taken from gstreamer equalizer sources: gstiirequalizer.c // function: gst_iir_equalizer_compute_frequencies const double step = std::pow(max_freq / min_freq, 1.0 / static_cast<double>(nbands)); for (int n = 0; n < nbands; n++) { freq1 = freq0 * step; const double freq = freq0 + 0.5 * (freq1 - freq0); const double width = freq1 - freq0; const double q = freq / width; // std::cout << n << "\t" << freq << "\t" << width << std::endl; g_settings_set_double(self->settings_left, band_frequency[n].data(), freq); g_settings_set_double(self->settings_left, band_q[n].data(), q); g_settings_reset(self->settings_left, band_width[n].data()); g_settings_set_double(self->settings_right, band_frequency[n].data(), freq); g_settings_set_double(self->settings_right, band_q[n].data(), q); g_settings_reset(self->settings_right, band_width[n].data()); freq0 = freq1; } } // ### APO Preset Section ### auto parse_apo_preamp(const std::string& line, double& preamp) -> bool { std::smatch matches; static const auto re_preamp = std::regex(R"(preamp\s*:\s*([+-]?\d+(?:\.\d+)?)\s*db)", std::regex::icase); std::regex_search(line, matches, re_preamp); if (matches.size() != 2U) { return false; } return util::str_to_num(matches.str(1), preamp); } auto parse_apo_filter_type(const std::string& line, struct APO_Band& filter) -> bool { // Look for disabled filter. std::smatch matches_off; static const auto re_filter_off = std::regex(R"(filter\s*\d*\s*:\s*off\s)", std::regex::icase); std::regex_search(line, matches_off, re_filter_off); if (matches_off.size() == 1U) { // If the APO filter is disabled, we assume the "OFF" type. filter.type = "OFF"; return true; } // If the filter is enabled, look for the filter type. std::smatch matches_filter; static const auto re_filter_type = std::regex(R"(filter\s*\d*\s*:\s*on\s+([a-z]+(?:\s+(?:6|12)db)?))", std::regex::icase); std::regex_search(line, matches_filter, re_filter_type); if (matches_filter.size() != 2U) { return false; } // Possible multiple whitespaces are replaced by a single space filter.type = std::regex_replace(matches_filter.str(1), std::regex(R"(\s+)"), " "); // Filter string needed in uppercase for lookup in map std::transform(filter.type.begin(), filter.type.end(), filter.type.begin(), [](unsigned char c) { return std::toupper(c); }); return !filter.type.empty(); } auto parse_apo_frequency(const std::string& line, struct APO_Band& filter) -> bool { std::smatch matches; static const auto re_freq = std::regex(R"(fc\s+(\d+(?:,\d+)?(?:\.\d+)?)\s*hz)", std::regex::icase); std::regex_search(line, matches, re_freq); if (matches.size() != 2U) { return false; } // Frequency could have a comma as thousands separator // to be removed for the correct float conversion. return util::str_to_num(std::regex_replace(matches.str(1), std::regex(","), ""), filter.freq); } auto parse_apo_gain(const std::string& line, struct APO_Band& filter) -> bool { std::smatch matches; static const auto re_gain = std::regex(R"(gain\s+([+-]?\d+(?:\.\d+)?)\s*db)", std::regex::icase); std::regex_search(line, matches, re_gain); if (matches.size() != 2U) { return false; } return util::str_to_num(matches.str(1), filter.gain); } auto parse_apo_quality(const std::string& line, struct APO_Band& filter) -> bool { std::smatch matches; static const auto re_quality = std::regex(R"(q\s+(\d+(?:\.\d+)?))", std::regex::icase); std::regex_search(line, matches, re_quality); if (matches.size() != 2U) { return false; } return util::str_to_num(matches.str(1), filter.quality); } auto parse_apo_config_line(const std::string& line, struct APO_Band& filter) -> bool { // Retrieve filter type. if (!parse_apo_filter_type(line, filter)) { // If we can't parse the filter type, there's something wrong in the text line, // so exit with false. return false; } // Retrieve frequency. // To make it more permissive, we do not exit on false here (assume default). parse_apo_frequency(line, filter); // The following has been inspired by the function // "para_equalizer_ui::import_rew_file(const LSPString*)" // inside 'lsp-plugins/src/ui/plugins/para_equalizer_ui.cpp' at // https://github.com/sadko4u/lsp-plugins // Retrieve gain and/or quality parameters based on a specific filter type. // Calculate frequency/quality if needed. // If the APO filter type is different than the ones specified below, // it's set as "Off" and default values are assumed since // it may not be supported by LSP Equalizer. if (filter.type == "OFF") { // On disabled filter state, we still try to retrieve gain and quality, // even if the band won't be processed by LSP equalizer. parse_apo_gain(line, filter); parse_apo_quality(line, filter); } else if (filter.type == "PK" || filter.type == "MODAL" || filter.type == "PEQ") { // Peak/Bell filter parse_apo_gain(line, filter); parse_apo_quality(line, filter); } else if (filter.type == "LP" || filter.type == "LPQ" || filter.type == "HP" || filter.type == "HPQ" || filter.type == "BP") { // Low-pass, High-pass and Band-pass filters, // (LSP does not import Band-pass, but we do it anyway). parse_apo_quality(line, filter); } else if (filter.type == "LS" || filter.type == "LSC" || filter.type == "HS" || filter.type == "HSC") { // Low-shelf and High-shelf filters (with center freq., x dB per oct.) parse_apo_gain(line, filter); // Q value is optional for these filters according to APO config documentation, // but LSP import function always sets it to 2/3. filter.quality = 2.0F / 3.0F; } else if (filter.type == "LS 6DB") { // Low-shelf filter (6 dB per octave with corner freq.) parse_apo_gain(line, filter); // LSP import function sets custom freq and quality for this filter. filter.freq = filter.freq * 2.0F / 3.0F; filter.quality = std::numbers::sqrt2_v<float> / 3.0F; } else if (filter.type == "LS 12DB") { // Low-shelf filter (12 dB per octave with corner freq.) parse_apo_gain(line, filter); // LSP import function sets custom freq for this filter. filter.freq = filter.freq * 3.0F / 2.0F; } else if (filter.type == "HS 6DB") { // High-shelf filter (6 dB per octave with corner freq.) parse_apo_gain(line, filter); // LSP import function sets custom freq and quality for this filter. filter.freq = filter.freq / (1.0F / std::numbers::sqrt2_v<float>); filter.quality = std::numbers::sqrt2_v<float> / 3.0F; } else if (filter.type == "HS 12DB") { // High-shelf filter (12 dB per octave with corner freq.) parse_apo_gain(line, filter); // LSP import function sets custom freq for this filter. filter.freq = filter.freq * (1.0F / std::numbers::sqrt2_v<float>); } else if (filter.type == "NO") { // Notch filter // Q value is optional for this filter according to APO config documentation, // but LSP import function always sets it to 100/3. filter.quality = 100.0F / 3.0F; } else if (filter.type == "AP") { // All-pass filter // Q value is mandatory for this filter according to APO config documentation, // but LSP import function always sets it to 0, // no matter which quality value the APO config has. filter.quality = 0.0F; } return true; } auto import_apo_preset(EqualizerBox* self, const std::string& file_path) -> bool { std::filesystem::path p{file_path}; if (!std::filesystem::is_regular_file(p)) { return false; } std::ifstream eq_file; eq_file.open(p.c_str()); std::vector<struct APO_Band> bands; double preamp = 0.0; if (const auto re = std::regex(R"(^[ \t]*#)"); eq_file.is_open()) { for (std::string line; std::getline(eq_file, line);) { if (std::regex_search(line, re)) { // Avoid commented lines continue; } if (struct APO_Band filter; parse_apo_config_line(line, filter)) { bands.push_back(filter); } else { parse_apo_preamp(line, preamp); } } } eq_file.close(); if (bands.empty()) { return false; } /* Sort bands by freq is made by user through Equalizer::sort_bands() std::ranges::stable_sort(bands, {}, &APO_Band::freq); */ const auto& max_bands = self->data->equalizer->max_bands; // Apply APO parameters obtained g_settings_set_int(self->settings, "num-bands", static_cast<int>(std::min(static_cast<uint>(bands.size()), max_bands))); g_settings_set_double(self->settings, "input-gain", preamp); std::vector<GSettings*> settings_channels; // Whether to apply the parameters to both channels or the selected one only if (g_settings_get_boolean(self->settings, "split-channels") == 0) { settings_channels.push_back(self->settings_left); settings_channels.push_back(self->settings_right); } else if (g_strcmp0(gtk_stack_get_visible_child_name(self->stack), "page_left_channel") == 0) { settings_channels.push_back(self->settings_left); } else { settings_channels.push_back(self->settings_right); } // Retrieve GSettingsSchema* for range check GSettingsSchema* schema = nullptr; g_object_get(self->settings_left, "settings-schema", &schema, nullptr); if (schema == nullptr) { return false; } // Apply APO parameters obtained for each band for (uint n = 0U, apo_bands = bands.size(); n < max_bands; n++) { for (auto* channel : settings_channels) { if (n < apo_bands) { // Band frequency and type auto* freq_schema_key = g_settings_schema_get_key(schema, band_frequency[n].data()); auto* freq_variant = g_variant_new_double(static_cast<gdouble>(bands[n].freq)); if (g_settings_schema_key_range_check(freq_schema_key, freq_variant) != 0) { g_settings_set_double(channel, band_frequency[n].data(), bands[n].freq); std::string curr_band_type; try { curr_band_type = ApoToEasyEffectsFilter.at(bands[n].type); } catch (std::out_of_range const&) { curr_band_type = "Off"; } g_settings_set_string(channel, band_type[n].data(), curr_band_type.c_str()); } else { // If the frequency is not in the valid range, we assume the filter is // unsupported or disabled, so reset to default frequency and set type Off. g_settings_reset(channel, band_frequency[n].data()); g_settings_set_string(channel, band_type[n].data(), "Off"); } g_variant_unref(freq_variant); g_settings_schema_key_unref(freq_schema_key); // Band gain auto* gain_schema_key = g_settings_schema_get_key(schema, band_gain[n].data()); auto* gain_variant = g_variant_new_double(static_cast<gdouble>(bands[n].gain)); if (g_settings_schema_key_range_check(gain_schema_key, gain_variant) != 0) { g_settings_set_double(channel, band_gain[n].data(), bands[n].gain); } else { g_settings_reset(channel, band_gain[n].data()); } g_variant_unref(gain_variant); g_settings_schema_key_unref(gain_schema_key); // Band quality auto* q_schema_key = g_settings_schema_get_key(schema, band_q[n].data()); auto* q_variant = g_variant_new_double(static_cast<gdouble>(bands[n].quality)); if (g_settings_schema_key_range_check(q_schema_key, q_variant) != 0) { g_settings_set_double(channel, band_q[n].data(), bands[n].quality); } else { g_settings_reset(channel, band_q[n].data()); } g_variant_unref(q_variant); g_settings_schema_key_unref(q_schema_key); // Band mode g_settings_set_string(channel, band_mode[n].data(), "APO (DR)"); } else { g_settings_reset(channel, band_frequency[n].data()); g_settings_set_string(channel, band_type[n].data(), "Off"); g_settings_reset(channel, band_gain[n].data()); g_settings_reset(channel, band_q[n].data()); g_settings_reset(channel, band_mode[n].data()); } g_settings_reset(channel, band_width[n].data()); g_settings_reset(channel, band_slope[n].data()); g_settings_reset(channel, band_mute[n].data()); g_settings_reset(channel, band_solo[n].data()); } } g_settings_schema_unref(schema); return true; } void on_import_apo_preset_clicked(EqualizerBox* self, GtkButton* btn) { auto* active_window = gtk_application_get_active_window(GTK_APPLICATION(self->data->application)); auto* dialog = gtk_file_dialog_new(); gtk_file_dialog_set_title(dialog, _("Import APO Preset File")); gtk_file_dialog_set_accept_label(dialog, _("Open")); GListStore* filters = g_list_store_new(GTK_TYPE_FILE_FILTER); auto* filter = gtk_file_filter_new(); gtk_file_filter_add_mime_type(filter, "text/plain"); gtk_file_filter_set_name(filter, _("APO Presets")); g_list_store_append(filters, filter); g_object_unref(filter); gtk_file_dialog_set_filters(dialog, G_LIST_MODEL(filters)); g_object_unref(filters); gtk_file_dialog_open( dialog, active_window, nullptr, +[](GObject* source_object, GAsyncResult* result, gpointer user_data) { auto* self = static_cast<EqualizerBox*>(user_data); auto* dialog = GTK_FILE_DIALOG(source_object); auto* file = gtk_file_dialog_open_finish(dialog, result, nullptr); if (file != nullptr) { auto* path = g_file_get_path(file); if (!import_apo_preset(self, path)) { // notify error on preset loading ui::show_fixed_toast( self->toast_overlay, _("APO Preset Not Loaded. File Format May Be Not Supported. Please Check Its Content.")); } g_free(path); g_object_unref(file); } }, self); } auto export_apo_preset(EqualizerBox* self, GFile* file) { GFileOutputStream* output_stream = g_file_replace(file, nullptr, false, G_FILE_CREATE_NONE, nullptr, nullptr); if (output_stream == nullptr) { return false; } std::ostringstream write_buffer; const double preamp = g_settings_get_double(self->settings, "input-gain"); write_buffer << "Preamp: " << util::to_string(preamp) << " db" << "\n"; const auto nbands = gtk_spin_button_get_value_as_int(self->nbands); for (int i = 0, k = 1; i < nbands; ++i) { const auto curr_band_type = util::gsettings_get_string(self->settings_left, band_type[i].data()); if (curr_band_type == "Off") { // Skip disabled filters, we only export active ones. continue; } APO_Band apo_band; apo_band.type = EasyEffectsToApoFilter.at(curr_band_type); apo_band.freq = g_settings_get_double(self->settings_left, band_frequency[i].data()); apo_band.gain = g_settings_get_double(self->settings_left, band_gain[i].data()); apo_band.quality = g_settings_get_double(self->settings_left, band_q[i].data()); write_buffer << "Filter " << util::to_string(k++) << ": ON " << apo_band.type << " Fc " << util::to_string(apo_band.freq) << " Hz"; if (curr_band_type == "Bell" || curr_band_type == "Lo-shelf" || curr_band_type == "Hi-shelf") { // According to APO config documentation, gain value should only be defined // for Peak, Low-shelf and High-shelf filters. write_buffer << " Gain " << util::to_string(apo_band.gain) << " dB"; } write_buffer << " Q " << util::to_string(apo_band.quality) << "\n"; } if (g_output_stream_write(G_OUTPUT_STREAM(output_stream), write_buffer.str().c_str(), write_buffer.str().size(), nullptr, nullptr) == -1) { return false; } return g_output_stream_close(G_OUTPUT_STREAM(output_stream), nullptr, nullptr) != 0; } void on_export_apo_preset_clicked(EqualizerBox* self, GtkButton* btn) { if (static_cast<bool>(g_settings_get_boolean(self->settings, "split-channels"))) { ui::show_fixed_toast(self->toast_overlay, _("Split channels not yet supported when exporting APO presets.")); return; } auto* active_window = gtk_application_get_active_window(GTK_APPLICATION(self->data->application)); auto* dialog = gtk_file_dialog_new(); gtk_file_dialog_set_title(dialog, _("Export EqualizerAPO Preset File")); gtk_file_dialog_set_accept_label(dialog, _("Save")); GListStore* filters = g_list_store_new(GTK_TYPE_FILE_FILTER); auto* filter = gtk_file_filter_new(); gtk_file_filter_add_mime_type(filter, "text/plain"); gtk_file_filter_set_name(filter, _("EqualizerAPO Presets")); g_list_store_append(filters, filter); g_object_unref(filter); gtk_file_dialog_set_filters(dialog, G_LIST_MODEL(filters)); g_object_unref(filters); gtk_file_dialog_save( dialog, active_window, nullptr, +[](GObject* source_object, GAsyncResult* result, gpointer user_data) { auto* self = static_cast<EqualizerBox*>(user_data); auto* dialog = GTK_FILE_DIALOG(source_object); if (auto* file = gtk_file_dialog_save_finish(dialog, result, nullptr); file != nullptr) { export_apo_preset(self, file); g_object_unref(file); } }, self); } // ### End APO Preset Section ### // ### GraphicEQ Section ### auto parse_graphiceq_config(const std::string& str, std::vector<struct GraphicEQ_Band>& bands) -> bool { std::smatch full_match; // The first parsing stage is to ensure the given string contains a // substring corresponding to the GraphicEQ format reported in the documentation: // https://sourceforge.net/p/equalizerapo/wiki/Configuration%20reference/#graphiceq-since-version-10 // In order to do it, the following regular expression is used: static const auto re_geq = std::regex( R"(graphiceq\s*:((?:\s*\d+(?:,\d+)?(?:\.\d+)?\s+[+-]?\d+(?:\.\d+)?[ \t]*(?:;|$))+))", std::regex::icase); // That regex is quite permissive since: // - It's case insensitive; // - Gain values can be signed (with leading +/-); // - Frequency values can use a comma as thousand separator. // Note that the last class does not include the newline as whitespaces to allow // matching the `$` as the end of line (not needed in this case, but it will also // work if the input string will be multiline in the future). // This ensures the last band is captured with or without the final `;`. // The regex has been tested at https://regex101.com/r/JRwf4G/1 std::regex_search(str, full_match, re_geq); // The regex captures the full match and a group related to the sequential bands. if (full_match.size() != 2U) { return false; } // Save the substring with all the bands and use it to extract the values. // It can't be const because it's used to store the sub-sequential strings // from the match_result class with suffix(). See the following while loop. auto bands_substr = full_match.str(1); // Couldn't we extract the values in one only regex checking also the GraphicEQ format? // No, there's no way. Even with Perl Compatible Regex (PCRE) checking the whole format // and capturing the values will return only the last repeated group (the last band), // but we need all of them. std::smatch band_match; static const auto re_geq_band = std::regex(R"((\d+(?:,\d+)?(?:\.\d+)?)\s+([+-]?\d+(?:\.\d+)?))"); // C++ regex does not support the global PCRE flag, so we need to repeat the search in a loop. while (std::regex_search(bands_substr, band_match, re_geq_band)) { // The size of the match should be 3: // The full match with two additional groups (frequency and gain value). if (band_match.size() != 3U) { break; } struct GraphicEQ_Band band; // Extract frequency. It could have a comma as thousands separator // to be removed for the correct float conversion. const auto freq_str = std::regex_replace(band_match.str(1), std::regex(","), ""); util::str_to_num(freq_str, band.freq); // Extract gain. const auto gain_str = band_match.str(2); util::str_to_num(gain_str, band.gain); // Push the band into the vector. bands.push_back(band); // Save the sub-sequential string, so the regex can return the match // for the following band (if existing). bands_substr = band_match.suffix().str(); } return !bands.empty(); } auto import_graphiceq_preset(EqualizerBox* self, const std::string& file_path) -> bool { std::filesystem::path p{file_path}; if (!std::filesystem::is_regular_file(p)) { return false; } std::ifstream eq_file; eq_file.open(p.c_str()); std::vector<struct GraphicEQ_Band> bands; if (const auto re = std::regex(R"(^[ \t]*#)"); eq_file.is_open()) { for (std::string line; std::getline(eq_file, line);) { if (std::regex_search(line, re)) { // Avoid commented lines continue; } if (parse_graphiceq_config(line, bands)) { break; } } } eq_file.close(); if (bands.empty()) { return false; } /* Sort bands by freq is made by user through Equalizer::sort_bands() std::ranges::stable_sort(bands, {}, &GraphicEQ_Band::freq); */ const auto& max_bands = self->data->equalizer->max_bands; // Reset preamp g_settings_reset(self->settings, "input-gain"); // Apply GraphicEQ parameters obtained g_settings_set_int(self->settings, "num-bands", static_cast<int>(std::min(static_cast<uint>(bands.size()), max_bands))); std::vector<GSettings*> settings_channels; // Whether to apply the parameters to both channels or the selected one only if (g_settings_get_boolean(self->settings, "split-channels") == 0) { settings_channels.push_back(self->settings_left); settings_channels.push_back(self->settings_right); } else if (g_strcmp0(gtk_stack_get_visible_child_name(self->stack), "page_left_channel") == 0) { settings_channels.push_back(self->settings_left); } else { settings_channels.push_back(self->settings_right); } // Retrieve GSettingsSchema* for range check GSettingsSchema* schema = nullptr; g_object_get(self->settings_left, "settings-schema", &schema, nullptr); if (schema == nullptr) { return false; } // Apply GraphicEQ parameters obtained for each band for (uint n = 0U, geq_bands = bands.size(); n < max_bands; n++) { for (auto* channel : settings_channels) { if (n < geq_bands) { // Band frequency and type auto* freq_schema_key = g_settings_schema_get_key(schema, band_frequency[n].data()); auto* freq_variant = g_variant_new_double(static_cast<gdouble>(bands[n].freq)); if (g_settings_schema_key_range_check(freq_schema_key, freq_variant) != 0) { g_settings_set_double(channel, band_frequency[n].data(), bands[n].freq); g_settings_set_string(channel, band_type[n].data(), "Bell"); } else { // If the frequency is not in the valid range, we assume the filter is // unsupported or disabled, so reset to default frequency and set type Off. g_settings_reset(channel, band_frequency[n].data()); g_settings_set_string(channel, band_type[n].data(), "Off"); } g_variant_unref(freq_variant); g_settings_schema_key_unref(freq_schema_key); // Band gain auto* gain_schema_key = g_settings_schema_get_key(schema, band_gain[n].data()); auto* gain_variant = g_variant_new_double(static_cast<gdouble>(bands[n].gain)); if (g_settings_schema_key_range_check(gain_schema_key, gain_variant) != 0) { g_settings_set_double(channel, band_gain[n].data(), bands[n].gain); } else { g_settings_reset(channel, band_gain[n].data()); } g_variant_unref(gain_variant); g_settings_schema_key_unref(gain_schema_key); } else { g_settings_reset(channel, band_frequency[n].data()); g_settings_reset(channel, band_gain[n].data()); g_settings_set_string(channel, band_type[n].data(), "Off"); } g_settings_reset(channel, band_mode[n].data()); g_settings_reset(channel, band_q[n].data()); g_settings_reset(channel, band_width[n].data()); g_settings_reset(channel, band_slope[n].data()); g_settings_reset(channel, band_solo[n].data()); g_settings_reset(channel, band_mute[n].data()); } } g_settings_schema_unref(schema); return true; } void on_import_geq_preset_clicked(EqualizerBox* self, GtkButton* btn) { auto* active_window = gtk_application_get_active_window(GTK_APPLICATION(self->data->application)); auto* dialog = gtk_file_dialog_new(); gtk_file_dialog_set_title(dialog, _("Import GraphicEQ Preset File")); gtk_file_dialog_set_accept_label(dialog, _("Open")); GListStore* filters = g_list_store_new(GTK_TYPE_FILE_FILTER); auto* filter = gtk_file_filter_new(); gtk_file_filter_add_mime_type(filter, "text/plain"); gtk_file_filter_set_name(filter, _("GraphicEQ Presets")); g_list_store_append(filters, filter); g_object_unref(filter); gtk_file_dialog_set_filters(dialog, G_LIST_MODEL(filters)); g_object_unref(filters); gtk_file_dialog_open( dialog, active_window, nullptr, +[](GObject* source_object, GAsyncResult* result, gpointer user_data) { auto* self = static_cast<EqualizerBox*>(user_data); auto* dialog = GTK_FILE_DIALOG(source_object); auto* file = gtk_file_dialog_open_finish(dialog, result, nullptr); if (file != nullptr) { auto* path = g_file_get_path(file); if (!import_graphiceq_preset(self, path)) { // notify error on preset loading ui::show_fixed_toast( self->toast_overlay, _("GraphicEQ Preset Not Loaded. File Format May Be Not Supported. Please Check Its Content.")); } g_free(path); g_object_unref(file); } }, self); } // ### End GraphicEQ Section ### auto sort_band_widgets(EqualizerBox* self, const int nbands, GSettings* settings, const bool& sort_by_freq) -> std::vector<std::string> { std::vector<int> list(nbands); std::iota(list.begin(), list.end(), 0); if (sort_by_freq) { std::ranges::sort(list, [=](const int& a, const int& b) { const auto freq_a = g_settings_get_double(settings, band_frequency[a].data()); const auto freq_b = g_settings_get_double(settings, band_frequency[b].data()); return freq_a < freq_b; }); } std::vector<std::string> output; output.reserve(nbands); for (int n = 0; n < nbands; n++) { output.push_back(util::to_string(list[n])); } return output; } void build_all_bands(EqualizerBox* self, const bool& sort_by_freq = false) { const auto split = g_settings_get_boolean(self->settings, "split-channels") != 0; const auto nbands = g_settings_get_int(self->settings, "num-bands"); auto list = sort_band_widgets(self, nbands, self->settings_left, sort_by_freq); gtk_string_list_splice(self->string_list_left, 0, g_list_model_get_n_items(G_LIST_MODEL(self->string_list_left)), util::make_gchar_pointer_vector(list).data()); if (split) { list = sort_band_widgets(self, nbands, self->settings_right, sort_by_freq); gtk_string_list_splice(self->string_list_right, 0, g_list_model_get_n_items(G_LIST_MODEL(self->string_list_right)), util::make_gchar_pointer_vector(list).data()); } } void on_sort_bands(EqualizerBox* self, GtkButton* btn) { self->data->equalizer->sort_bands(); } template <Channel channel> void setup_listview(EqualizerBox* self) { auto* factory = gtk_signal_list_item_factory_new(); // setting the factory callbacks g_signal_connect(factory, "setup", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, EqualizerBox* self) { auto* band_box = ui::equalizer_band_box::create(); gtk_list_item_set_activatable(item, 0); gtk_list_item_set_child(item, GTK_WIDGET(band_box)); g_object_set_data(G_OBJECT(item), "band-box", band_box); if constexpr (channel == Channel::left) { ui::equalizer_band_box::setup(band_box, self->settings_left); } else if constexpr (channel == Channel::right) { ui::equalizer_band_box::setup(band_box, self->settings_right); } }), self); g_signal_connect( factory, "bind", G_CALLBACK(+[](GtkSignalListItemFactory* factory, GtkListItem* item, EqualizerBox* self) { auto* band_box = static_cast<ui::equalizer_band_box::EqualizerBandBox*>(g_object_get_data(G_OBJECT(item), "band-box")); auto* child_item = gtk_list_item_get_item(item); auto* band_id_str = gtk_string_object_get_string(GTK_STRING_OBJECT(child_item)); int band_id = 0; util::str_to_num(band_id_str, band_id); ui::equalizer_band_box::bind(band_box, band_id); }), self); if constexpr (channel == Channel::left) { gtk_list_view_set_factory(self->listview_left, factory); } else if constexpr (channel == Channel::right) { gtk_list_view_set_factory(self->listview_right, factory); } g_object_unref(factory); } void setup(EqualizerBox* self, std::shared_ptr<Equalizer> equalizer, const std::string& schema_path, app::Application* application) { self->data->equalizer = equalizer; self->data->application = application; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::equalizer::id, schema_path.c_str()); self->settings_left = g_settings_new_with_path(tags::schema::equalizer::channel_id, (schema_path + "leftchannel/").c_str()); self->settings_right = g_settings_new_with_path(tags::schema::equalizer::channel_id, (schema_path + "rightchannel/").c_str()); equalizer->set_post_messages(true); setup_listview<Channel::left>(self); setup_listview<Channel::right>(self); build_all_bands(self); self->data->connections.push_back(equalizer->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(equalizer->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->equalizer->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "num-bands", gtk_spin_button_get_adjustment(self->nbands), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "split-channels", self->split_channels, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "mode", self->mode); g_settings_bind(self->settings, "balance", gtk_spin_button_get_adjustment(self->balance), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "pitch-left", gtk_spin_button_get_adjustment(self->pitch_left), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "pitch-right", gtk_spin_button_get_adjustment(self->pitch_right), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::num-bands", G_CALLBACK(+[](GSettings* settings, char* key, EqualizerBox* self) { build_all_bands(self); }), self)); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::split-channels", G_CALLBACK(+[](GSettings* settings, char* key, EqualizerBox* self) { gtk_stack_set_visible_child_name(self->stack, "page_left_channel"); build_all_bands(self); }), self)); } void dispose(GObject* object) { auto* self = EE_EQUALIZER_BOX(object); self->data->equalizer->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); g_object_unref(self->settings_left); g_object_unref(self->settings_right); util::debug("disposed"); G_OBJECT_CLASS(equalizer_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_EQUALIZER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(equalizer_box_parent_class)->finalize(object); } void equalizer_box_class_init(EqualizerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::equalizer_ui); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, toast_overlay); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, input_gain); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, output_gain); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, stack); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, listview_left); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, listview_right); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, string_list_left); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, string_list_right); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, nbands); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, mode); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, split_channels); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, balance); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, pitch_left); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, pitch_right); gtk_widget_class_bind_template_child(widget_class, EqualizerBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); gtk_widget_class_bind_template_callback(widget_class, on_flat_response); gtk_widget_class_bind_template_callback(widget_class, on_calculate_frequencies); gtk_widget_class_bind_template_callback(widget_class, on_sort_bands); gtk_widget_class_bind_template_callback(widget_class, on_import_apo_preset_clicked); gtk_widget_class_bind_template_callback(widget_class, on_import_geq_preset_clicked); gtk_widget_class_bind_template_callback(widget_class, on_export_apo_preset_clicked); } void equalizer_box_init(EqualizerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"%">(self->balance); prepare_spinbuttons<"st">(self->pitch_left, self->pitch_right); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> EqualizerBox* { return static_cast<EqualizerBox*>(g_object_new(EE_TYPE_EQUALIZER_BOX, nullptr)); } } // namespace ui::equalizer_box
42,090
C++
.cpp
880
42.436364
119
0.667115
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,650
deesser_preset.cpp
wwmm_easyeffects/src/deesser_preset.cpp
/* * 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/>. */ #include "deesser_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" DeesserPreset::DeesserPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::deesser::id, tags::schema::deesser::input_path, tags::schema::deesser::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::deesser).append("#").append(util::to_string(index)); } void DeesserPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["detection"] = util::gsettings_get_string(settings, "detection"); json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["threshold"] = g_settings_get_double(settings, "threshold"); json[section][instance_name]["ratio"] = g_settings_get_double(settings, "ratio"); json[section][instance_name]["laxity"] = g_settings_get_int(settings, "laxity"); json[section][instance_name]["makeup"] = g_settings_get_double(settings, "makeup"); json[section][instance_name]["f1-freq"] = g_settings_get_double(settings, "f1-freq"); json[section][instance_name]["f2-freq"] = g_settings_get_double(settings, "f2-freq"); json[section][instance_name]["f1-level"] = g_settings_get_double(settings, "f1-level"); json[section][instance_name]["f2-level"] = g_settings_get_double(settings, "f2-level"); json[section][instance_name]["f2-q"] = g_settings_get_double(settings, "f2-q"); json[section][instance_name]["sc-listen"] = g_settings_get_boolean(settings, "sc-listen") != 0; } void DeesserPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<gchar*>(json.at(section).at(instance_name), settings, "detection", "detection"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<double>(json.at(section).at(instance_name), settings, "threshold", "threshold"); update_key<double>(json.at(section).at(instance_name), settings, "ratio", "ratio"); update_key<int>(json.at(section).at(instance_name), settings, "laxity", "laxity"); update_key<double>(json.at(section).at(instance_name), settings, "makeup", "makeup"); update_key<double>(json.at(section).at(instance_name), settings, "f1-freq", "f1-freq"); update_key<double>(json.at(section).at(instance_name), settings, "f2-freq", "f2-freq"); update_key<double>(json.at(section).at(instance_name), settings, "f1-level", "f1-level"); update_key<double>(json.at(section).at(instance_name), settings, "f2-level", "f2-level"); update_key<double>(json.at(section).at(instance_name), settings, "f2-q", "f2-q"); update_key<bool>(json.at(section).at(instance_name), settings, "sc-listen", "sc-listen"); }
4,236
C++
.cpp
69
57.391304
97
0.707376
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,651
exciter_ui.cpp
wwmm_easyeffects/src/exciter_ui.cpp
/* * 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/>. */ #include "exciter_ui.hpp" #include <STTypes.h> #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "exciter.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::exciter_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Exciter> exciter; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _ExciterBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkLevelBar* harmonics_levelbar; GtkLabel* harmonics_levelbar_label; GtkSpinButton *ceil, *amount, *harmonics, *scope; GtkScale* blend; GtkToggleButton *ceil_active, *listen; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(ExciterBox, exciter_box, GTK_TYPE_BOX) void on_reset(ExciterBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(ExciterBox* self, std::shared_ptr<Exciter> exciter, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->exciter = exciter; self->settings = g_settings_new_with_path(tags::schema::exciter::id, schema_path.c_str()); exciter->set_post_messages(true); self->data->connections.push_back(exciter->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(exciter->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(exciter->harmonics.connect([=](const double value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LEVEL_BAR(self->harmonics_levelbar) || !GTK_IS_LABEL(self->harmonics_levelbar_label)) { return; } gtk_level_bar_set_value(self->harmonics_levelbar, value); gtk_label_set_text(self->harmonics_levelbar_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->exciter->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "amount", gtk_spin_button_get_adjustment(self->amount), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "harmonics", gtk_spin_button_get_adjustment(self->harmonics), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "scope", gtk_spin_button_get_adjustment(self->scope), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "ceil", gtk_spin_button_get_adjustment(self->ceil), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "blend", gtk_range_get_adjustment(GTK_RANGE(self->blend)), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "listen", self->listen, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "ceil-active", self->ceil_active, "active", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_EXCITER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(exciter_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_EXCITER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(exciter_box_parent_class)->finalize(object); } void exciter_box_class_init(ExciterBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::exciter_ui); gtk_widget_class_bind_template_child(widget_class, ExciterBox, input_gain); gtk_widget_class_bind_template_child(widget_class, ExciterBox, output_gain); gtk_widget_class_bind_template_child(widget_class, ExciterBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, ExciterBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, ExciterBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, ExciterBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, ExciterBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, ExciterBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, ExciterBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, ExciterBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, ExciterBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, ExciterBox, harmonics_levelbar_label); gtk_widget_class_bind_template_child(widget_class, ExciterBox, harmonics_levelbar); gtk_widget_class_bind_template_child(widget_class, ExciterBox, ceil); gtk_widget_class_bind_template_child(widget_class, ExciterBox, amount); gtk_widget_class_bind_template_child(widget_class, ExciterBox, harmonics); gtk_widget_class_bind_template_child(widget_class, ExciterBox, scope); gtk_widget_class_bind_template_child(widget_class, ExciterBox, blend); gtk_widget_class_bind_template_child(widget_class, ExciterBox, ceil_active); gtk_widget_class_bind_template_child(widget_class, ExciterBox, listen); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void exciter_box_init(ExciterBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"dB">(self->amount); prepare_spinbuttons<"Hz">(self->scope, self->ceil); prepare_spinbuttons<"">(self->harmonics); prepare_scales<"">(self->blend); } auto create() -> ExciterBox* { return static_cast<ExciterBox*>(g_object_new(EE_TYPE_EXCITER_BOX, nullptr)); } } // namespace ui::exciter_box
8,571
C++
.cpp
187
41.315508
120
0.708273
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,652
autogain_preset.cpp
wwmm_easyeffects/src/autogain_preset.cpp
/* * 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/>. */ #include "autogain_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" AutoGainPreset::AutoGainPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::autogain::id, tags::schema::autogain::input_path, tags::schema::autogain::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::autogain).append("#").append(util::to_string(index)); } void AutoGainPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["target"] = g_settings_get_double(settings, "target"); json[section][instance_name]["silence-threshold"] = g_settings_get_double(settings, "silence-threshold"); json[section][instance_name]["maximum-history"] = g_settings_get_int(settings, "maximum-history"); json[section][instance_name]["reference"] = util::gsettings_get_string(settings, "reference"); } void AutoGainPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "target", "target"); update_key<double>(json.at(section).at(instance_name), settings, "silence-threshold", "silence-threshold"); update_key<int>(json.at(section).at(instance_name), settings, "maximum-history", "maximum-history"); update_key<gchar*>(json.at(section).at(instance_name), settings, "reference", "reference"); }
2,880
C++
.cpp
53
50.339623
109
0.716827
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,653
autogain_ui.cpp
wwmm_easyeffects/src/autogain_ui.cpp
/* * 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/>. */ #include "autogain_ui.hpp" #include <STTypes.h> #include <adwaita.h> #include <fmt/core.h> #include <fmt/format.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "autogain.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::autogain_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<AutoGain> autogain; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _AutogainBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *target, *silence_threshold, *maximum_history; GtkLevelBar *m_level, *s_level, *i_level, *r_level, *g_level, *l_level, *lra_level; GtkLabel *m_label, *s_label, *i_label, *r_label, *g_label, *l_label, *lra_label; GtkButton* reset_history; AdwComboRow* reference; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(AutogainBox, autogain_box, GTK_TYPE_BOX) void on_reset(AutogainBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_reset_history(AutogainBox* self, GtkButton* btn) { // it is ugly but will ensure that third party tools are able to reset this plugin history g_settings_set_boolean(self->settings, "reset-history", static_cast<gboolean>(g_settings_get_boolean(self->settings, "reset-history") == 0)); } void setup(AutogainBox* self, std::shared_ptr<AutoGain> autogain, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->autogain = autogain; self->settings = g_settings_new_with_path(tags::schema::autogain::id, schema_path.c_str()); autogain->set_post_messages(true); self->data->connections.push_back(autogain->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(autogain->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(autogain->results.connect([=](const double loudness, const double gain, const double momentary, const double shortterm, const double integrated, const double relative, const double range) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LEVEL_BAR(self->l_level) || !GTK_IS_LABEL(self->l_label) || !GTK_IS_LEVEL_BAR(self->g_level) || !GTK_IS_LABEL(self->g_label) || !GTK_IS_LEVEL_BAR(self->m_level) || !GTK_IS_LABEL(self->m_label) || !GTK_IS_LEVEL_BAR(self->s_level) || !GTK_IS_LABEL(self->s_label) || !GTK_IS_LEVEL_BAR(self->i_level) || !GTK_IS_LABEL(self->i_label) || !GTK_IS_LEVEL_BAR(self->r_level) || !GTK_IS_LABEL(self->r_label) || !GTK_IS_LEVEL_BAR(self->lra_level) || !GTK_IS_LABEL(self->lra_label)) { return; } gtk_level_bar_set_value(self->l_level, util::db_to_linear(loudness)); gtk_label_set_text(self->l_label, fmt::format("{0:.0f} LUFS", loudness).c_str()); gtk_level_bar_set_value(self->g_level, gain); gtk_label_set_text(self->g_label, fmt::format(ui::get_user_locale(), "{0:.2Lf} dB", util::linear_to_db(gain)).c_str()); gtk_level_bar_set_value(self->m_level, util::db_to_linear(momentary)); gtk_label_set_text(self->m_label, fmt::format("{0:.0f} LUFS", momentary).c_str()); gtk_level_bar_set_value(self->s_level, util::db_to_linear(shortterm)); gtk_label_set_text(self->s_label, fmt::format("{0:.0f} LUFS", shortterm).c_str()); gtk_level_bar_set_value(self->i_level, util::db_to_linear(integrated)); gtk_label_set_text(self->i_label, fmt::format("{0:.0f} LUFS", integrated).c_str()); gtk_level_bar_set_value(self->r_level, util::db_to_linear(relative)); gtk_label_set_text(self->r_label, fmt::format("{0:.0f} LUFS", relative).c_str()); gtk_level_bar_set_value(self->lra_level, util::db_to_linear(range)); gtk_label_set_text(self->lra_label, fmt::format("{0:.0f} LU", range).c_str()); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->autogain->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); gsettings_bind_widgets<"target", "silence-threshold", "maximum-history">( self->settings, self->target, self->silence_threshold, self->maximum_history); ui::gsettings_bind_enum_to_combo_widget(self->settings, "reference", self->reference); } void dispose(GObject* object) { auto* self = EE_AUTOGAIN_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(autogain_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_AUTOGAIN_BOX(object); delete self->data; util::debug("finalize"); G_OBJECT_CLASS(autogain_box_parent_class)->finalize(object); } void autogain_box_class_init(AutogainBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::autogain_ui); gtk_widget_class_bind_template_child(widget_class, AutogainBox, input_gain); gtk_widget_class_bind_template_child(widget_class, AutogainBox, output_gain); gtk_widget_class_bind_template_child(widget_class, AutogainBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, AutogainBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, AutogainBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, AutogainBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, AutogainBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, AutogainBox, target); gtk_widget_class_bind_template_child(widget_class, AutogainBox, silence_threshold); gtk_widget_class_bind_template_child(widget_class, AutogainBox, maximum_history); gtk_widget_class_bind_template_child(widget_class, AutogainBox, reference); gtk_widget_class_bind_template_child(widget_class, AutogainBox, reset_history); gtk_widget_class_bind_template_child(widget_class, AutogainBox, m_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, s_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, i_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, r_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, g_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, l_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, lra_level); gtk_widget_class_bind_template_child(widget_class, AutogainBox, m_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, s_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, i_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, r_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, g_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, l_label); gtk_widget_class_bind_template_child(widget_class, AutogainBox, lra_label); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_reset_history); } void autogain_box_init(AutogainBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"dB">(self->target, self->silence_threshold); prepare_spinbuttons<"s">(self->maximum_history); } auto create() -> AutogainBox* { return static_cast<AutogainBox*>(g_object_new(EE_TYPE_AUTOGAIN_BOX, nullptr)); } } // namespace ui::autogain_box
11,070
C++
.cpp
215
45.651163
117
0.687726
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,654
presets_autoloading_holder.cpp
wwmm_easyeffects/src/presets_autoloading_holder.cpp
/* * 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/>. */ #include "presets_autoloading_holder.hpp" #include <glib-object.h> #include <gobject/gobject.h> #include <string> #include "util.hpp" namespace ui::holders { // NOLINTNEXTLINE G_DEFINE_TYPE(PresetsAutoloadingHolder, presets_autoloading_holder, G_TYPE_OBJECT); void presets_autoloading_holder_finalize(GObject* object) { auto* self = EE_PRESETS_AUTOLOADING_HOLDER(object); util::debug(self->data->device + ", " + self->data->preset_name + " finalized"); delete self->data; G_OBJECT_CLASS(presets_autoloading_holder_parent_class)->finalize(object); } void presets_autoloading_holder_class_init(PresetsAutoloadingHolderClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); object_class->finalize = presets_autoloading_holder_finalize; } void presets_autoloading_holder_init(PresetsAutoloadingHolder* self) { self->data = new PresetsAutoLoadingData(); } auto create(const std::string& device, const std::string& device_description, const std::string& device_profile, const std::string& preset_name) -> PresetsAutoloadingHolder* { auto* holder = static_cast<PresetsAutoloadingHolder*>(g_object_new(EE_TYPE_PRESETS_AUTOLOADING_HOLDER, nullptr)); holder->data->device = device; holder->data->device_description = device_description; holder->data->device_profile = device_profile; holder->data->preset_name = preset_name; return holder; } } // namespace ui::holders
2,193
C++
.cpp
51
40.196078
115
0.752466
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,655
resampler.cpp
wwmm_easyeffects/src/resampler.cpp
/* * 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/>. */ #include "resampler.hpp" #include <samplerate.h> Resampler::Resampler(const int& input_rate, const int& output_rate) : output(1, 0) { resample_ratio = static_cast<double>(output_rate) / static_cast<double>(input_rate); src_state = src_new(SRC_SINC_FASTEST, 1, nullptr); } Resampler::~Resampler() { if (src_state != nullptr) { src_delete(src_state); } }
1,122
C++
.cpp
29
36.551724
86
0.733701
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,656
easyeffects.cpp
wwmm_easyeffects/src/easyeffects.cpp
/* * 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/>. */ #include <gio/gio.h> #include <glib-object.h> #include <glib-unix.h> #include <glib.h> #include <libintl.h> #include <cerrno> #include <cstdlib> #include <exception> #include <iostream> #include <ostream> #include <string> #include "application.hpp" #include "config.h" #include "util.hpp" auto sigterm(void* data) -> int { auto* app = G_APPLICATION(data); app::hide_all_windows(app); g_application_quit(app); return G_SOURCE_REMOVE; } auto main(int argc, char* argv[]) -> int { util::debug("easyeffects version: " + std::string(VERSION)); try { // Init internationalization support before anything else auto* bindtext_output = bindtextdomain(GETTEXT_PACKAGE, LOCALE_DIR); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); if (bindtext_output != nullptr) { util::debug("locale directory: " + std::string(bindtext_output)); } else if (errno == ENOMEM) { util::warning("bindtextdomain: Not enough memory available!"); return errno; } auto* app = app::application_new(); g_unix_signal_add(2, G_SOURCE_FUNC(sigterm), app); auto status = g_application_run(app, argc, argv); g_object_unref(app); util::debug("Exitting the main function with status: " + util::to_string(status, "")); return status; } catch (const std::exception& e) { std::cerr << e.what() << '\n'; return EXIT_FAILURE; } }
2,178
C++
.cpp
62
32.064516
90
0.706527
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,657
module_info_holder.cpp
wwmm_easyeffects/src/module_info_holder.cpp
/* * 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/>. */ #include "module_info_holder.hpp" #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <spa/utils/defs.h> #include "pipe_objects.hpp" #include "util.hpp" namespace ui::holders { enum { PROP_0, PROP_ID, PROP_NAME, PROP_DESCRIPTION, PROP_FILENAME }; // NOLINTNEXTLINE G_DEFINE_TYPE(ModuleInfoHolder, module_info_holder, G_TYPE_OBJECT); void module_info_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { auto* self = EE_MODULE_INFO_HOLDER(object); switch (prop_id) { case PROP_ID: self->info->id = g_value_get_uint(value); break; case PROP_NAME: self->info->name = g_value_get_string(value); break; case PROP_DESCRIPTION: self->info->description = g_value_get_string(value); break; case PROP_FILENAME: self->info->filename = g_value_get_string(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void module_info_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { auto* self = EE_MODULE_INFO_HOLDER(object); switch (prop_id) { case PROP_ID: g_value_set_uint(value, self->info->id); break; case PROP_NAME: g_value_set_string(value, self->info->name.c_str()); break; case PROP_DESCRIPTION: g_value_set_string(value, self->info->description.c_str()); break; case PROP_FILENAME: g_value_set_string(value, self->info->filename.c_str()); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void module_info_holder_finalize(GObject* object) { auto* self = EE_MODULE_INFO_HOLDER(object); self->info_updated.clear(); util::debug(util::to_string(self->info->id) + ", " + self->info->name + " finalized"); delete self->info; G_OBJECT_CLASS(module_info_holder_parent_class)->finalize(object); } void module_info_holder_class_init(ModuleInfoHolderClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); object_class->finalize = module_info_holder_finalize; object_class->set_property = module_info_set_property; object_class->get_property = module_info_get_property; g_object_class_install_property( object_class, PROP_ID, g_param_spec_uint("id", "Id", "Id", G_MININT, G_MAXUINT, SPA_ID_INVALID, G_PARAM_READWRITE)); g_object_class_install_property(object_class, PROP_NAME, g_param_spec_string("name", "Name", "Name", nullptr, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_DESCRIPTION, g_param_spec_string("description", "Description", "Description", nullptr, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_FILENAME, g_param_spec_string("file-name", "File Name", "File Name", nullptr, G_PARAM_READWRITE)); } void module_info_holder_init(ModuleInfoHolder* self) { self->info = new ModuleInfo(); } auto create(const ModuleInfo& info) -> ModuleInfoHolder* { auto* holder = static_cast<ModuleInfoHolder*>(g_object_new(EE_TYPE_MODULE_INFO_HOLDER, nullptr)); holder->info->id = info.id; holder->info->name = info.name; holder->info->description = info.description; holder->info->filename = info.filename; return holder; } } // namespace ui::holders
4,139
C++
.cpp
106
35
107
0.70242
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,658
bass_loudness_ui.cpp
wwmm_easyeffects/src/bass_loudness_ui.cpp
/* * 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/>. */ #include "bass_loudness_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "bass_loudness.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::bass_loudness_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<BassLoudness> bass_loudness; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _BassLoudnessBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *loudness, *output, *link; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(BassLoudnessBox, bass_loudness_box, GTK_TYPE_BOX) void on_reset(BassLoudnessBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(BassLoudnessBox* self, std::shared_ptr<BassLoudness> bass_loudness, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->bass_loudness = bass_loudness; self->settings = g_settings_new_with_path(tags::schema::bass_loudness::id, schema_path.c_str()); bass_loudness->set_post_messages(true); self->data->connections.push_back(bass_loudness->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(bass_loudness->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->bass_loudness->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); gsettings_bind_widgets<"loudness", "output", "link">(self->settings, self->loudness, self->output, self->link); } void dispose(GObject* object) { auto* self = EE_BASS_LOUDNESS_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(bass_loudness_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_BASS_LOUDNESS_BOX(object); delete self->data; util::debug("finalize"); G_OBJECT_CLASS(bass_loudness_box_parent_class)->finalize(object); } void bass_loudness_box_class_init(BassLoudnessBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::bass_loudness_ui); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, input_gain); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output_gain); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, loudness); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, output); gtk_widget_class_bind_template_child(widget_class, BassLoudnessBox, link); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void bass_loudness_box_init(BassLoudnessBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"dB">(self->loudness, self->output, self->link); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> BassLoudnessBox* { return static_cast<BassLoudnessBox*>(g_object_new(EE_TYPE_BASS_LOUDNESS_BOX, nullptr)); } } // namespace ui::bass_loudness_box
6,655
C++
.cpp
148
41.155405
120
0.725934
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,659
limiter.cpp
wwmm_easyeffects/src/limiter.cpp
/* * 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/>. */ #include "limiter.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Limiter::Limiter(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::limiter, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_limiter_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_limiter_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::external-sidechain", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Limiter*>(user_data); self->update_sidechain_links(key); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Limiter*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"mode", "mode">(settings); lv2_wrapper->bind_key_enum<"ovs", "oversampling">(settings); lv2_wrapper->bind_key_enum<"dith", "dithering">(settings); lv2_wrapper->bind_key_double<"lk", "lookahead">(settings); lv2_wrapper->bind_key_double<"at", "attack">(settings); lv2_wrapper->bind_key_double<"rt", "release">(settings); lv2_wrapper->bind_key_double_db<"th", "threshold">(settings); lv2_wrapper->bind_key_bool<"boost", "gain-boost">(settings); lv2_wrapper->bind_key_double_db<"scp", "sidechain-preamp">(settings); lv2_wrapper->bind_key_double<"slink", "stereo-link">(settings); lv2_wrapper->bind_key_bool<"alr", "alr">(settings); lv2_wrapper->bind_key_double<"alr_at", "alr-attack">(settings); lv2_wrapper->bind_key_double<"alr_rt", "alr-release">(settings); lv2_wrapper->bind_key_double_db<"knee", "alr-knee">(settings); lv2_wrapper->bind_key_bool<"extsc", "external-sidechain">(settings); setup_input_output_gain(); } Limiter::~Limiter() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Limiter::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Limiter::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { gain_l_port_value = lv2_wrapper->get_control_port_value("grlm_l"); gain_r_port_value = lv2_wrapper->get_control_port_value("grlm_r"); sidechain_l_port_value = lv2_wrapper->get_control_port_value("sclm_l"); sidechain_r_port_value = lv2_wrapper->get_control_port_value("sclm_r"); gain_left.emit(gain_l_port_value); gain_right.emit(gain_r_port_value); sidechain_left.emit(sidechain_l_port_value); sidechain_right.emit(sidechain_r_port_value); notify(); } } } void Limiter::update_sidechain_links(const std::string& key) { if (g_settings_get_boolean(settings, "external-sidechain") == 0) { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void Limiter::update_probe_links() { update_sidechain_links(""); } auto Limiter::get_latency_seconds() -> float { return this->latency_value; }
6,943
C++
.cpp
171
33.122807
110
0.61826
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,660
level_meter_ui.cpp
wwmm_easyeffects/src/level_meter_ui.cpp
/* * 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/>. */ #include "level_meter_ui.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "level_meter.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::level_meter_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<LevelMeter> level_meter; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _LevelMeterBox { GtkBox parent_instance; GtkLevelBar *input_level_left, *input_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *plugin_credit; GtkLevelBar *m_level, *s_level, *i_level, *r_level, *lra_level; GtkLabel *m_label, *s_label, *i_label, *r_label, *lra_label, *true_peak_left_label, *true_peak_right_label; GtkButton* reset_history; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(LevelMeterBox, level_meter_box, GTK_TYPE_BOX) void on_reset_history(LevelMeterBox* self, GtkButton* btn) { // Since there's no reason why someone would want to activate the reset-history // through a third party tool, we do not bind this action to a gsettings key // like it's done in the AutoGain. self->data->level_meter->reset_history(); } void setup(LevelMeterBox* self, std::shared_ptr<LevelMeter> level_meter, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->level_meter = level_meter; self->settings = g_settings_new_with_path(tags::schema::level_meter::id, schema_path.c_str()); level_meter->set_post_messages(true); self->data->connections.push_back(level_meter->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(level_meter->results.connect( [=](const double momentary, const double shortterm, const double integrated, const double relative, const double range, const double true_peak_L, const double true_peak_R) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LEVEL_BAR(self->m_level) || !GTK_IS_LABEL(self->m_label) || !GTK_IS_LEVEL_BAR(self->s_level) || !GTK_IS_LABEL(self->s_label) || !GTK_IS_LEVEL_BAR(self->i_level) || !GTK_IS_LABEL(self->i_label) || !GTK_IS_LEVEL_BAR(self->r_level) || !GTK_IS_LABEL(self->r_label) || !GTK_IS_LEVEL_BAR(self->lra_level) || !GTK_IS_LABEL(self->lra_label) || !GTK_IS_LABEL(self->true_peak_left_label) || !GTK_IS_LABEL(self->true_peak_right_label)) { return; } gtk_label_set_text(self->true_peak_left_label, fmt::format("{0:.0f} dB", util::linear_to_db(true_peak_L)).c_str()); gtk_label_set_text(self->true_peak_right_label, fmt::format("{0:.0f} dB", util::linear_to_db(true_peak_R)).c_str()); gtk_level_bar_set_value(self->m_level, util::db_to_linear(momentary)); gtk_label_set_text(self->m_label, fmt::format("{0:.0f} LUFS", momentary).c_str()); gtk_level_bar_set_value(self->s_level, util::db_to_linear(shortterm)); gtk_label_set_text(self->s_label, fmt::format("{0:.0f} LUFS", shortterm).c_str()); gtk_level_bar_set_value(self->i_level, util::db_to_linear(integrated)); gtk_label_set_text(self->i_label, fmt::format("{0:.0f} LUFS", integrated).c_str()); gtk_level_bar_set_value(self->r_level, util::db_to_linear(relative)); gtk_label_set_text(self->r_label, fmt::format("{0:.0f} LUFS", relative).c_str()); gtk_level_bar_set_value(self->lra_level, util::db_to_linear(range)); gtk_label_set_text(self->lra_label, fmt::format("{0:.0f} LU", range).c_str()); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->level_meter->package).c_str()); } void dispose(GObject* object) { auto* self = EE_LEVEL_METER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(level_meter_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_LEVEL_METER_BOX(object); delete self->data; util::debug("finalize"); G_OBJECT_CLASS(level_meter_box_parent_class)->finalize(object); } void level_meter_box_class_init(LevelMeterBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::level_meter_ui); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, reset_history); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, m_level); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, s_level); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, i_level); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, r_level); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, lra_level); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, m_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, s_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, i_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, r_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, lra_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, true_peak_left_label); gtk_widget_class_bind_template_child(widget_class, LevelMeterBox, true_peak_right_label); gtk_widget_class_bind_template_callback(widget_class, on_reset_history); } void level_meter_box_init(LevelMeterBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); } auto create() -> LevelMeterBox* { return static_cast<LevelMeterBox*>(g_object_new(EE_TYPE_LEVEL_METER_BOX, nullptr)); } } // namespace ui::level_meter_box
8,605
C++
.cpp
175
43.537143
118
0.684154
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,661
bass_enhancer_ui.cpp
wwmm_easyeffects/src/bass_enhancer_ui.cpp
/* * 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/>. */ #include "bass_enhancer_ui.hpp" #include <STTypes.h> #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkbox.h> #include <gtk/gtkbutton.h> #include <gtk/gtklabel.h> #include <gtk/gtklevelbar.h> #include <gtk/gtkscale.h> #include <gtk/gtkspinbutton.h> #include <gtk/gtktogglebutton.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "bass_enhancer.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::bass_enhancer_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<BassEnhancer> bass_enhancer; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _BassEnhancerBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkLevelBar* harmonics_levelbar; GtkLabel* harmonics_levelbar_label; GtkSpinButton *floor, *amount, *harmonics, *scope; GtkScale* blend; GtkToggleButton *floor_active, *listen; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(BassEnhancerBox, bass_enhancer_box, GTK_TYPE_BOX) void on_reset(BassEnhancerBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(BassEnhancerBox* self, std::shared_ptr<BassEnhancer> bass_enhancer, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->bass_enhancer = bass_enhancer; self->settings = g_settings_new_with_path(tags::schema::bass_enhancer::id, schema_path.c_str()); bass_enhancer->set_post_messages(true); self->data->connections.push_back(bass_enhancer->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(bass_enhancer->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(bass_enhancer->harmonics.connect([=](const double value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LEVEL_BAR(self->harmonics_levelbar) || !GTK_IS_LABEL(self->harmonics_levelbar_label)) { return; } gtk_level_bar_set_value(self->harmonics_levelbar, value); gtk_label_set_text(self->harmonics_levelbar_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->bass_enhancer->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); gsettings_bind_widgets<"amount", "harmonics", "scope", "floor", "blend", "listen", "floor-active">( self->settings, self->amount, self->harmonics, self->scope, self->floor, self->blend, self->listen, self->floor_active); } void dispose(GObject* object) { auto* self = EE_BASS_ENHANCER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(bass_enhancer_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_BASS_ENHANCER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(bass_enhancer_box_parent_class)->finalize(object); } void bass_enhancer_box_class_init(BassEnhancerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::bass_enhancer_ui); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, input_gain); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, output_gain); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, harmonics_levelbar_label); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, harmonics_levelbar); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, floor); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, amount); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, harmonics); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, scope); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, blend); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, floor_active); gtk_widget_class_bind_template_child(widget_class, BassEnhancerBox, listen); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void bass_enhancer_box_init(BassEnhancerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"dB">(self->amount); prepare_spinbuttons<"Hz">(self->scope, self->floor); prepare_spinbuttons<"">(self->harmonics); prepare_scales<"">(self->blend); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> BassEnhancerBox* { return static_cast<BassEnhancerBox*>(g_object_new(EE_TYPE_BASS_ENHANCER_BOX, nullptr)); } } // namespace ui::bass_enhancer_box
8,394
C++
.cpp
186
40.994624
120
0.719391
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,662
crystalizer_preset.cpp
wwmm_easyeffects/src/crystalizer_preset.cpp
/* * 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/>. */ #include "crystalizer_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" CrystalizerPreset::CrystalizerPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::crystalizer::id, tags::schema::crystalizer::input_path, tags::schema::crystalizer::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::crystalizer).append("#").append(util::to_string(index)); } void CrystalizerPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); for (int n = 0; n < 13; n++) { const auto bandn = "band" + util::to_string(n); json[section][instance_name][bandn]["intensity"] = g_settings_get_double(settings, ("intensity-" + bandn).c_str()); json[section][instance_name][bandn]["mute"] = g_settings_get_boolean(settings, ("mute-" + bandn).c_str()) != 0; json[section][instance_name][bandn]["bypass"] = g_settings_get_boolean(settings, ("bypass-" + bandn).c_str()) != 0; } } void CrystalizerPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); for (int n = 0; n < 13; n++) { const auto bandn = "band" + util::to_string(n); update_key<double>(json.at(section).at(instance_name)[bandn], settings, "intensity-" + bandn, "intensity"); update_key<bool>(json.at(section).at(instance_name)[bandn], settings, "mute-" + bandn, "mute"); update_key<bool>(json.at(section).at(instance_name)[bandn], settings, "bypass-" + bandn, "bypass"); } }
2,952
C++
.cpp
56
48.446429
119
0.690278
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,663
convolver_ui.cpp
wwmm_easyeffects/src/convolver_ui.cpp
/* * 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/>. */ #include "convolver_ui.hpp" #include <STTypes.h> #include <fftw3.h> #include <fmt/format.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gsl/gsl_interp.h> #include <gsl/gsl_spline.h> #include <gtk/gtk.h> #include <gtk/gtkshortcut.h> #include <sigc++/connection.h> #include <algorithm> #include <cmath> #include <cstddef> #include <filesystem> #include <memory> #include <mutex> #include <numbers> #include <string> #include <thread> #include <vector> #include "application.hpp" #include "chart.hpp" #include "convolver.hpp" #include "convolver_menu_combine.hpp" #include "convolver_menu_impulses.hpp" #include "convolver_ui_common.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::convolver_box { using namespace std::string_literals; auto constexpr irs_ext = ".irs"; static std::filesystem::path irs_dir = g_get_user_config_dir() + "/easyeffects/irs"s; struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; app::Application* application; std::shared_ptr<Convolver> convolver; std::mutex lock_guard_irs_info; std::vector<std::thread> mythreads; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; std::vector<double> left_mag, right_mag, time_axis, left_spectrum, right_spectrum, freq_axis; }; struct _ConvolverBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkMenuButton *menu_button_impulses, *menu_button_combine; GtkLabel *label_file_name, *label_sampling_rate, *label_samples, *label_duration; GtkSpinButton* ir_width; GtkCheckButton *check_left, *check_right; GtkToggleButton *show_fft, *enable_log_scale; GtkBox* chart_box; ui::convolver_menu_impulses::ConvolverMenuImpulses* impulses_menu; ui::convolver_menu_combine::ConvolverMenuCombine* combine_menu; ui::chart::Chart* chart; GSettings* settings; GFileMonitor* folder_monitor; Data* data; GtkToggleButton* autogain; }; // NOLINTNEXTLINE G_DEFINE_TYPE(ConvolverBox, convolver_box, GTK_TYPE_BOX) void on_reset(ConvolverBox* self, GtkButton* btn) { gtk_toggle_button_set_active(self->autogain, 0); util::reset_all_keys_except(self->settings); } void plot_fft(ConvolverBox* self) { if (self->data->freq_axis.empty() || self->data->left_spectrum.empty() || self->data->right_spectrum.empty()) { return; } ui::chart::set_chart_type(self->chart, ui::chart::ChartType::line); ui::chart::set_fill_bars(self->chart, false); ui::chart::set_line_width(self->chart, 2.0F); ui::chart::set_n_x_decimals(self->chart, 0); ui::chart::set_n_y_decimals(self->chart, 2); ui::chart::set_x_unit(self->chart, "Hz"); if (gtk_toggle_button_get_active(self->enable_log_scale) != 0) { ui::chart::set_chart_scale(self->chart, ui::chart::ChartScale::logarithmic); } else { ui::chart::set_chart_scale(self->chart, ui::chart::ChartScale::linear); } ui::chart::set_x_data(self->chart, self->data->freq_axis); if (gtk_check_button_get_active(self->check_left) != 0) { ui::chart::set_y_data(self->chart, self->data->left_spectrum); } else if (gtk_check_button_get_active(self->check_right) != 0) { ui::chart::set_y_data(self->chart, self->data->right_spectrum); } } void plot_waveform(ConvolverBox* self) { if (self->data->time_axis.empty() || self->data->left_mag.empty() || self->data->right_mag.empty()) { return; } ui::chart::set_chart_type(self->chart, ui::chart::ChartType::line); ui::chart::set_chart_scale(self->chart, ui::chart::ChartScale::linear); ui::chart::set_fill_bars(self->chart, false); ui::chart::set_line_width(self->chart, 2.0F); ui::chart::set_n_x_decimals(self->chart, 2); ui::chart::set_n_y_decimals(self->chart, 2); ui::chart::set_x_unit(self->chart, "s"); ui::chart::set_x_data(self->chart, self->data->time_axis); if (gtk_check_button_get_active(self->check_left) != 0) { ui::chart::set_y_data(self->chart, self->data->left_mag); } else if (gtk_check_button_get_active(self->check_right) != 0) { ui::chart::set_y_data(self->chart, self->data->right_mag); } } void on_show_fft(ConvolverBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { plot_fft(self); } else { plot_waveform(self); } } void on_show_channel(ConvolverBox* self, GtkCheckButton* btn) { if (gtk_check_button_get_active(btn) != 0) { on_show_fft(self, self->show_fft); } } void on_enable_log_scale(ConvolverBox* self, GtkToggleButton* btn) { plot_fft(self); } auto interpolate(const std::vector<double>& x_source, const std::vector<double>& y_source, const std::vector<double>& x_new) -> std::vector<double> { auto* acc = gsl_interp_accel_alloc(); auto* spline = gsl_spline_alloc(gsl_interp_steffen, x_source.size()); gsl_spline_init(spline, x_source.data(), y_source.data(), x_source.size()); std::vector<double> output(x_new.size()); for (size_t n = 0; n < x_new.size(); n++) { output[n] = static_cast<float>(gsl_spline_eval(spline, x_new[n], acc)); } gsl_spline_free(spline); gsl_interp_accel_free(acc); return output; } void get_irs_spectrum(ConvolverBox* self, const int& rate) { if (self->data->left_mag.empty() || self->data->right_mag.empty() || self->data->left_mag.size() != self->data->right_mag.size()) { util::debug(" aborting the impulse fft calculation..."); return; } util::debug(" calculating the impulse fft..."); self->data->left_spectrum.resize(self->data->left_mag.size() / 2U + 1U); self->data->right_spectrum.resize(self->data->right_mag.size() / 2U + 1U); auto real_input = self->data->left_mag; for (uint n = 0U; n < real_input.size(); n++) { // https://en.wikipedia.org/wiki/Hann_function const float w = 0.5F * (1.0F - std::cos(2.0F * std::numbers::pi_v<float> * static_cast<float>(n) / static_cast<float>(real_input.size() - 1U))); real_input[n] *= w; } auto* complex_output = fftw_alloc_complex(real_input.size()); auto* plan = fftw_plan_dft_r2c_1d(static_cast<int>(real_input.size()), real_input.data(), complex_output, FFTW_ESTIMATE); fftw_execute(plan); for (uint i = 0U; i < self->data->left_spectrum.size(); i++) { double sqr = complex_output[i][0] * complex_output[i][0] + complex_output[i][1] * complex_output[i][1]; sqr /= static_cast<double>(self->data->left_spectrum.size() * self->data->left_spectrum.size()); self->data->left_spectrum[i] = sqr; } // right channel fft real_input = self->data->right_mag; for (uint n = 0U; n < real_input.size(); n++) { // https://en.wikipedia.org/wiki/Hann_function const float w = 0.5F * (1.0F - std::cos(2.0F * std::numbers::pi_v<float> * static_cast<float>(n) / static_cast<float>(real_input.size() - 1U))); real_input[n] *= w; } fftw_execute(plan); for (uint i = 0U; i < self->data->right_spectrum.size(); i++) { double sqr = complex_output[i][0] * complex_output[i][0] + complex_output[i][1] * complex_output[i][1]; sqr /= static_cast<double>(self->data->right_spectrum.size() * self->data->right_spectrum.size()); self->data->right_spectrum[i] = sqr; } // cleaning if (complex_output != nullptr) { fftw_free(complex_output); } fftw_destroy_plan(plan); // initializing the frequency axis self->data->freq_axis.resize(self->data->left_spectrum.size()); for (uint n = 0U; n < self->data->freq_axis.size(); n++) { self->data->freq_axis[n] = 0.5F * static_cast<float>(rate) * static_cast<float>(n) / static_cast<float>(self->data->freq_axis.size()); } // removing the DC component at f = 0 Hz self->data->freq_axis.erase(self->data->freq_axis.begin()); self->data->left_spectrum.erase(self->data->left_spectrum.begin()); self->data->right_spectrum.erase(self->data->right_spectrum.begin()); const auto chart_width = static_cast<uint>(gtk_widget_get_width(GTK_WIDGET(self->chart))); const auto n_interp_points = (chart_width > 0U) ? chart_width : 1000U; // initializing the logarithmic frequency axis auto max_freq = std::ranges::max(self->data->freq_axis); auto min_freq = std::ranges::min(self->data->freq_axis); util::debug("min fft frequency: " + util::to_string(min_freq, "")); util::debug("max fft frequency: " + util::to_string(max_freq, "")); const auto log_axis = util::logspace(min_freq, max_freq, n_interp_points); // const auto log_axis = util::logspace(20.0F, 22000.0F, self->data->freq_axis.size()); std::vector<double> freq_axis(log_axis.size()); std::copy(log_axis.begin(), log_axis.end(), freq_axis.begin()); self->data->left_spectrum = interpolate(self->data->freq_axis, self->data->left_spectrum, freq_axis); self->data->right_spectrum = interpolate(self->data->freq_axis, self->data->right_spectrum, freq_axis); self->data->freq_axis = freq_axis; // it has to be after the two previous lines // find min and max values const auto fft_min_left = std::ranges::min(self->data->left_spectrum); const auto fft_max_left = std::ranges::max(self->data->left_spectrum); const auto fft_min_right = std::ranges::min(self->data->right_spectrum); const auto fft_max_right = std::ranges::max(self->data->right_spectrum); // rescaling between 0 and 1 for (uint n = 0U; n < self->data->left_spectrum.size(); n++) { self->data->left_spectrum[n] = (self->data->left_spectrum[n] - fft_min_left) / (fft_max_left - fft_min_left); self->data->right_spectrum[n] = (self->data->right_spectrum[n] - fft_min_right) / (fft_max_right - fft_min_right); } g_object_ref(self); util::idle_add( [=]() { if (self == nullptr) { return; } if (!ui::chart::get_is_visible(self->chart)) { return; } if (gtk_toggle_button_get_active(self->show_fft) != 0) { plot_fft(self); } }, [=]() { g_object_unref(self); }); } void get_irs_info(ConvolverBox* self) { bool can_read_irs = false; std::string path; const auto name = util::gsettings_get_string(self->settings, "kernel-name"); if (name.empty()) { util::warning("irs name is empty!"); } else { path = self->data->convolver->search_irs_path(name); if (!path.empty()) { can_read_irs = true; } else { util::warning("irs file path is null!"); } } if (!can_read_irs) { // Set label to initial empty state gtk_widget_remove_css_class(GTK_WIDGET(self->label_file_name), "error"); gtk_widget_add_css_class(GTK_WIDGET(self->label_file_name), "dim-label"); gtk_label_set_text(self->label_file_name, _("No Impulse File Loaded")); gtk_label_set_text(self->label_sampling_rate, ""); gtk_label_set_text(self->label_samples, ""); gtk_label_set_text(self->label_duration, ""); return; } auto [rate, kernel_L, kernel_R] = ui::convolver::read_kernel(irs_dir, irs_ext, path); if (rate == 0) { // warning the user that there is a problem util::idle_add([=]() { if (self == nullptr) { return; } if (!ui::chart::get_is_visible(self->chart)) { return; } // Move label to error state gtk_widget_remove_css_class(GTK_WIDGET(self->label_file_name), "dim-label"); gtk_widget_add_css_class(GTK_WIDGET(self->label_file_name), "error"); gtk_label_set_text(self->label_file_name, _("Failed To Load The Impulse File")); gtk_label_set_text(self->label_sampling_rate, ""); gtk_label_set_text(self->label_samples, ""); gtk_label_set_text(self->label_duration, ""); }); return; } const auto dt = 1.0 / rate; const double duration = (static_cast<double>(kernel_L.size()) - 1.0) * dt; self->data->time_axis.resize(kernel_L.size()); self->data->left_mag.resize(kernel_L.size()); self->data->right_mag.resize(kernel_R.size()); std::copy(kernel_L.begin(), kernel_L.end(), self->data->left_mag.begin()); std::copy(kernel_R.begin(), kernel_R.end(), self->data->right_mag.begin()); for (size_t n = 0U; n < self->data->time_axis.size(); n++) { self->data->time_axis[n] = static_cast<double>(n) * dt; } get_irs_spectrum(self, rate); const auto chart_width = static_cast<uint>(gtk_widget_get_width(GTK_WIDGET(self->chart))); const auto n_interp_points = (chart_width > 0U) ? chart_width : 1000; auto x_linear = util::linspace(self->data->time_axis.front(), self->data->time_axis.back(), n_interp_points); std::vector<double> x_axis(x_linear.size()); std::copy(x_linear.begin(), x_linear.end(), x_axis.begin()); self->data->left_mag = interpolate(self->data->time_axis, self->data->left_mag, x_axis); self->data->right_mag = interpolate(self->data->time_axis, self->data->right_mag, x_axis); self->data->time_axis = x_axis; // it has to be after the two previous lines self->data->time_axis.shrink_to_fit(); self->data->left_mag.shrink_to_fit(); self->data->right_mag.shrink_to_fit(); // find min and max values const auto min_left = std::ranges::min(self->data->left_mag); const auto max_left = std::ranges::max(self->data->left_mag); const auto min_right = std::ranges::min(self->data->right_mag); const auto max_right = std::ranges::max(self->data->right_mag); // rescaling between 0 and 1 for (size_t n = 0U; n < self->data->left_mag.size(); n++) { self->data->left_mag[n] = (self->data->left_mag[n] - min_left) / (max_left - min_left); self->data->right_mag[n] = (self->data->right_mag[n] - min_right) / (max_right - min_right); } // updating interface with ir file info auto rate_copy = rate; auto n_samples = kernel_L.size(); util::idle_add([=]() { if (self == nullptr) { return; } if (!ui::chart::get_is_visible(self->chart)) { return; } const auto fpath = std::filesystem::path{path}; // Set label to ready state and update with filename gtk_widget_remove_css_class(GTK_WIDGET(self->label_file_name), "error"); gtk_widget_add_css_class(GTK_WIDGET(self->label_file_name), "dim-label"); gtk_label_set_text(self->label_file_name, fpath.stem().c_str()); gtk_label_set_text(self->label_sampling_rate, fmt::format(ui::get_user_locale(), "{0:Ld} Hz", rate_copy).c_str()); gtk_label_set_text(self->label_samples, fmt::format(ui::get_user_locale(), "{0:Ld}", n_samples).c_str()); gtk_label_set_text(self->label_duration, fmt::format(ui::get_user_locale(), "{0:.3Lf}", duration).c_str()); if (gtk_toggle_button_get_active(self->show_fft) == 0) { plot_waveform(self); } }); } void setup(ConvolverBox* self, std::shared_ptr<Convolver> convolver, const std::string& schema_path, app::Application* application) { self->data->convolver = convolver; self->data->application = application; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::convolver::id, schema_path.c_str()); convolver->set_post_messages(true); ui::convolver_menu_impulses::setup(self->impulses_menu, schema_path, application, convolver); self->data->connections.push_back(convolver->input_level.connect([=](const float left, const float right) { util::idle_add([=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }); })); self->data->connections.push_back(convolver->output_level.connect([=](const float left, const float right) { util::idle_add([=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }); })); self->data->gconnections.push_back(g_signal_connect( self->settings, "changed::kernel-name", G_CALLBACK(+[](GSettings* settings, char* key, ConvolverBox* self) { self->data->mythreads.emplace_back([=]() { std::scoped_lock<std::mutex> lock(self->data->lock_guard_irs_info); get_irs_info(self); }); }), self)); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->convolver->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain", "autogain">(self->settings, self->input_gain, self->output_gain, self->autogain); g_settings_bind(self->settings, "ir-width", gtk_spin_button_get_adjustment(self->ir_width), "value", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_CONVOLVER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); g_file_monitor_cancel(self->folder_monitor); g_object_unref(self->folder_monitor); for (auto& t : self->data->mythreads) { t.join(); } self->data->mythreads.clear(); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(convolver_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_CONVOLVER_BOX(object); for (auto& t : self->data->mythreads) { t.join(); } self->data->mythreads.clear(); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(convolver_box_parent_class)->finalize(object); } void convolver_box_class_init(ConvolverBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::convolver_ui); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, input_gain); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, output_gain); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, menu_button_impulses); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, menu_button_combine); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, label_file_name); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, label_sampling_rate); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, label_samples); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, label_duration); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, ir_width); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, check_left); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, check_right); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, show_fft); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, enable_log_scale); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, chart_box); gtk_widget_class_bind_template_child(widget_class, ConvolverBox, autogain); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_fft); gtk_widget_class_bind_template_callback(widget_class, on_show_channel); gtk_widget_class_bind_template_callback(widget_class, on_enable_log_scale); } void convolver_box_init(ConvolverBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"%">(self->ir_width); prepare_scales<"dB">(self->input_gain, self->output_gain); self->chart = ui::chart::create(); gtk_widget_set_vexpand(GTK_WIDGET(self->chart), 1); self->impulses_menu = ui::convolver_menu_impulses::create(); self->combine_menu = ui::convolver_menu_combine::create(); gtk_menu_button_set_popover(self->menu_button_impulses, GTK_WIDGET(self->impulses_menu)); gtk_menu_button_set_popover(self->menu_button_combine, GTK_WIDGET(self->combine_menu)); gtk_box_insert_child_after(self->chart_box, GTK_WIDGET(self->chart), gtk_widget_get_first_child(GTK_WIDGET(self->chart_box))); // setting some signals auto* gfile = g_file_new_for_path(irs_dir.c_str()); self->folder_monitor = g_file_monitor_directory(gfile, G_FILE_MONITOR_NONE, nullptr, nullptr); g_signal_connect(self->folder_monitor, "changed", G_CALLBACK(+[](GFileMonitor* monitor, GFile* file, GFile* other_file, GFileMonitorEvent event_type, ConvolverBox* self) { const auto irs_filename = util::remove_filename_extension(g_file_get_basename(file)); if (irs_filename.empty()) { util::warning("can't retrieve information about irs file"); return; } switch (event_type) { case G_FILE_MONITOR_EVENT_CREATED: { ui::convolver_menu_impulses::append_to_string_list(self->impulses_menu, irs_filename); ui::convolver_menu_combine::append_to_string_list(self->combine_menu, irs_filename); break; } case G_FILE_MONITOR_EVENT_DELETED: { ui::convolver_menu_impulses::remove_from_string_list(self->impulses_menu, irs_filename); ui::convolver_menu_combine::remove_from_string_list(self->combine_menu, irs_filename); break; } default: break; } }), self); g_object_unref(gfile); g_signal_connect(GTK_WIDGET(self), "realize", G_CALLBACK(+[](GtkWidget* widget, ConvolverBox* self) { /* Reading the current configured irs file. We do this here because we need some widgets to be ready when the impulse response file information is available */ self->data->mythreads.emplace_back([=]() { // Using emplace_back here makes sense std::scoped_lock<std::mutex> lock(self->data->lock_guard_irs_info); get_irs_info(self); }); }), self); } auto create() -> ConvolverBox* { return static_cast<ConvolverBox*>(g_object_new(EE_TYPE_CONVOLVER_BOX, nullptr)); } } // namespace ui::convolver_box
24,952
C++
.cpp
524
41.975191
120
0.66485
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,664
node_info_holder.cpp
wwmm_easyeffects/src/node_info_holder.cpp
/* * 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/>. */ #include "node_info_holder.hpp" #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <spa/utils/defs.h> #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "util.hpp" namespace ui::holders { enum { PROP_0, PROP_SERIAL, PROP_ID, PROP_DEVICE_ID, PROP_NAME, PROP_MEDIA_CLASS, PROP_DESCRIPTION, PROP_ICON_NAME }; // NOLINTNEXTLINE G_DEFINE_TYPE(NodeInfoHolder, node_info_holder, G_TYPE_OBJECT); void node_info_set_property(GObject* object, guint prop_id, const GValue* value, GParamSpec* pspec) { auto* self = EE_NODE_INFO_HOLDER(object); switch (prop_id) { case PROP_SERIAL: self->info->serial = g_value_get_uint64(value); break; case PROP_ID: self->info->id = g_value_get_uint(value); break; case PROP_DEVICE_ID: self->info->device_id = g_value_get_uint(value); break; case PROP_NAME: self->info->name = g_value_get_string(value); break; case PROP_MEDIA_CLASS: self->info->media_class = g_value_get_string(value); break; case PROP_DESCRIPTION: self->info->description = g_value_get_string(value); break; case PROP_ICON_NAME: self->icon_name = g_value_get_string(value); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void node_info_get_property(GObject* object, guint prop_id, GValue* value, GParamSpec* pspec) { auto* self = EE_NODE_INFO_HOLDER(object); switch (prop_id) { case PROP_SERIAL: g_value_set_uint64(value, self->info->serial); break; case PROP_ID: g_value_set_uint(value, self->info->id); break; case PROP_DEVICE_ID: g_value_set_uint(value, self->info->device_id); break; case PROP_NAME: g_value_set_string(value, self->info->name.c_str()); break; case PROP_MEDIA_CLASS: g_value_set_string(value, self->info->media_class.c_str()); break; case PROP_DESCRIPTION: g_value_set_string(value, self->info->description.c_str()); break; case PROP_ICON_NAME: g_value_set_string(value, self->icon_name.c_str()); break; default: G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec); break; } } void node_info_holder_finalize(GObject* object) { auto* self = EE_NODE_INFO_HOLDER(object); self->info_updated.clear(); util::debug(util::to_string(self->info->id) + ", " + self->info->name + " finalized"); delete self->info; G_OBJECT_CLASS(node_info_holder_parent_class)->finalize(object); } void node_info_holder_class_init(NodeInfoHolderClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); object_class->finalize = node_info_holder_finalize; object_class->set_property = node_info_set_property; object_class->get_property = node_info_get_property; // Using G_MININT64 as minimum parameter causes // assertion 'default_value >= minimum && default_value <= maximum' failed g_object_class_install_property(object_class, PROP_SERIAL, g_param_spec_uint64("serial", "Serial", "Serial", SPA_ID_INVALID, G_MAXUINT64, SPA_ID_INVALID, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_ID, g_param_spec_uint("id", "Id", "Id", G_MININT, G_MAXUINT, SPA_ID_INVALID, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_DEVICE_ID, g_param_spec_uint("device-id", "Device Id", "Device Id", G_MININT, G_MAXUINT, SPA_ID_INVALID, G_PARAM_READWRITE)); g_object_class_install_property(object_class, PROP_NAME, g_param_spec_string("name", "Name", "Name", nullptr, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_MEDIA_CLASS, g_param_spec_string("media-class", "Media Class", "Media Class", nullptr, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_DESCRIPTION, g_param_spec_string("description", "Description", "Description", nullptr, G_PARAM_READWRITE)); g_object_class_install_property( object_class, PROP_ICON_NAME, g_param_spec_string("icon-name", "Icon Name", "Icon Name", nullptr, G_PARAM_READWRITE)); } void node_info_holder_init(NodeInfoHolder* self) { self->info = new NodeInfo(); } auto create(const NodeInfo& info) -> NodeInfoHolder* { auto* holder = static_cast<NodeInfoHolder*>(g_object_new(EE_TYPE_NODE_INFO_HOLDER, nullptr)); *holder->info = info; if (info.media_class == tags::pipewire::media_class::sink || info.name.starts_with("ee_soe")) { holder->icon_name = "audio-speakers-symbolic"; } else if (info.media_class == tags::pipewire::media_class::source || info.media_class == tags::pipewire::media_class::virtual_source || info.name.starts_with("ee_sie")) { holder->icon_name = "audio-input-microphone-symbolic"; } return holder; } } // namespace ui::holders
5,763
C++
.cpp
139
36.388489
120
0.680129
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,665
lv2_wrapper.cpp
wwmm_easyeffects/src/lv2_wrapper.cpp
/* * 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/>. */ #include "lv2_wrapper.hpp" #include <dlfcn.h> #include <lilv/lilv.h> #include <lv2/atom/atom.h> #include <lv2/buf-size/buf-size.h> #include <lv2/core/lv2.h> #include <lv2/data-access/data-access.h> #include <lv2/instance-access/instance-access.h> #include <lv2/lv2plug.in/ns/ext/log/log.h> #include <lv2/options/options.h> #include <lv2/parameters/parameters.h> #include <lv2/ui/ui.h> #include <lv2/urid/urid.h> #include <sys/types.h> #include <array> #include <chrono> #include <cmath> #include <cstdarg> #include <cstdint> #include <cstdio> #include <functional> #include <mutex> #include <span> #include <string> #include <thread> #include <vector> #include "util.hpp" namespace lv2 { constexpr auto min_quantum = 32; constexpr auto max_quantum = 8192; auto lv2_printf(LV2_Log_Handle handle, LV2_URID type, const char* format, ...) -> int { va_list args; va_start(args, format); int r = std::vprintf(format, args); va_end(args); return r; } Lv2Wrapper::Lv2Wrapper(const std::string& plugin_uri) : plugin_uri(plugin_uri), world(lilv_world_new()) { if (world == nullptr) { util::warning("failed to initialized the world"); return; } auto* const uri = lilv_new_uri(world, plugin_uri.c_str()); if (uri == nullptr) { util::warning("Invalid plugin URI: " + plugin_uri); return; } lilv_world_load_all(world); const LilvPlugins* plugins = lilv_world_get_all_plugins(world); plugin = lilv_plugins_get_by_uri(plugins, uri); lilv_node_free(uri); if (plugin == nullptr) { util::warning("Could not find the plugin: " + plugin_uri); return; } found_plugin = true; check_required_features(); create_ports(); } Lv2Wrapper::~Lv2Wrapper() { if (instance != nullptr) { lilv_instance_deactivate(instance); lilv_instance_free(instance); instance = nullptr; } if (world != nullptr) { lilv_world_free(world); } } void Lv2Wrapper::check_required_features() { LilvNodes* required_features = lilv_plugin_get_required_features(plugin); if (required_features != nullptr) { for (auto* i = lilv_nodes_begin(required_features); !lilv_nodes_is_end(required_features, i); i = lilv_nodes_next(required_features, i)) { const LilvNode* required_feature = lilv_nodes_get(required_features, i); const char* required_feature_uri = lilv_node_as_uri(required_feature); util::debug(plugin_uri + " requires feature: " + required_feature_uri); } lilv_nodes_free(required_features); } } void Lv2Wrapper::create_ports() { n_ports = lilv_plugin_get_num_ports(plugin); ports.resize(n_ports); // Get min, max and default values for all ports std::vector<float> values(n_ports); std::vector<float> minimum(n_ports); std::vector<float> maximum(n_ports); lilv_plugin_get_port_ranges_float(plugin, minimum.data(), maximum.data(), values.data()); LilvNode* lv2_InputPort = lilv_new_uri(world, LV2_CORE__InputPort); LilvNode* lv2_OutputPort = lilv_new_uri(world, LV2_CORE__OutputPort); LilvNode* lv2_AudioPort = lilv_new_uri(world, LV2_CORE__AudioPort); LilvNode* lv2_ControlPort = lilv_new_uri(world, LV2_CORE__ControlPort); LilvNode* lv2_AtomPort = lilv_new_uri(world, LV2_ATOM__AtomPort); LilvNode* lv2_connectionOptional = lilv_new_uri(world, LV2_CORE__connectionOptional); data_ports.in.left = data_ports.in.right = UINT_MAX; data_ports.probe.left = data_ports.probe.right = UINT_MAX; data_ports.out.left = data_ports.out.right = UINT_MAX; for (uint n = 0U; n < n_ports; n++) { auto* port = &ports[n]; const auto* lilv_port = lilv_plugin_get_port_by_index(plugin, n); auto* port_name = lilv_port_get_name(plugin, lilv_port); port->index = n; port->name = lilv_node_as_string(port_name); port->symbol = lilv_node_as_string(lilv_port_get_symbol(plugin, lilv_port)); port->optional = lilv_port_has_property(plugin, lilv_port, lv2_connectionOptional); // Save port default value if (!std::isnan(values[n])) { port->value = values[n]; } // Save minimum and maximum values if (!std::isnan(minimum[n])) { port->min = minimum[n]; } if (!std::isnan(maximum[n])) { port->max = maximum[n]; } // util::warning("port name: " + port->name); // util::warning("port symbol: " + port->symbol); if (lilv_port_is_a(plugin, lilv_port, lv2_InputPort)) { port->is_input = true; } else if (!lilv_port_is_a(plugin, lilv_port, lv2_OutputPort) && !port->optional) { util::warning("Port " + port->name + " is neither input nor output!"); } if (lilv_port_is_a(plugin, lilv_port, lv2_ControlPort)) { port->type = TYPE_CONTROL; } else if (lilv_port_is_a(plugin, lilv_port, lv2_AtomPort)) { port->type = TYPE_ATOM; // util::warning("port name: " + port->name); } else if (lilv_port_is_a(plugin, lilv_port, lv2_AudioPort)) { port->type = TYPE_AUDIO; if (port->is_input) { if (n_audio_in == 0) data_ports.in.left = port->index; else if (n_audio_in == 1) data_ports.in.right = port->index; else if (n_audio_in == 2) data_ports.probe.left = port->index; else if (n_audio_in == 3) data_ports.probe.right = port->index; n_audio_in++; } else { if (n_audio_out == 0) data_ports.out.left = port->index; else if (n_audio_out == 1) data_ports.out.right = port->index; n_audio_out++; } } else if (!port->optional) { util::warning("Port " + port->name + " has un unsupported type!"); } lilv_node_free(port_name); } // util::warning("n audio_in ports: " + util::to_string(n_audio_in)); // util::warning("n audio_out ports: " + util::to_string(n_audio_out)); lilv_node_free(lv2_connectionOptional); lilv_node_free(lv2_ControlPort); lilv_node_free(lv2_AtomPort); lilv_node_free(lv2_AudioPort); lilv_node_free(lv2_OutputPort); lilv_node_free(lv2_InputPort); } auto Lv2Wrapper::create_instance(const uint& rate) -> bool { this->rate = rate; if (instance != nullptr) { deactivate(); lilv_instance_free(instance); instance = nullptr; } LV2_Log_Log lv2_log = {this, &lv2_printf, [](LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap) { return std::vprintf(fmt, ap); }}; LV2_URID_Map lv2_map = {this, [](LV2_URID_Map_Handle handle, const char* uri) { auto* lw = static_cast<Lv2Wrapper*>(handle); return lw->map_urid(uri); }}; LV2_URID_Unmap lv2_unmap = {this, [](LV2_URID_Unmap_Handle handle, LV2_URID urid) { auto* lw = static_cast<Lv2Wrapper*>(handle); return lw->map_urid_to_uri[urid].c_str(); }}; const LV2_Feature lv2_log_feature = {LV2_LOG__log, &lv2_log}; const LV2_Feature lv2_map_feature = {LV2_URID__map, &lv2_map}; const LV2_Feature lv2_unmap_feature = {LV2_URID__unmap, &lv2_unmap}; auto options = std::to_array<LV2_Options_Option>( {{LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_PARAMETERS__sampleRate), sizeof(float), map_urid(LV2_ATOM__Float), &rate}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__minBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &min_quantum}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__maxBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &max_quantum}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__nominalBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &n_samples}, {LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, nullptr}}); LV2_Feature feature_options = {.URI = LV2_OPTIONS__options, .data = options.data()}; const auto features = std::to_array<const LV2_Feature*>( {&lv2_log_feature, &lv2_map_feature, &lv2_unmap_feature, &feature_options, static_features.data(), nullptr}); instance = lilv_plugin_instantiate(plugin, rate, features.data()); if (instance == nullptr) { util::warning("failed to instantiate " + plugin_uri); return false; } connect_control_ports(); activate(); return true; } void Lv2Wrapper::connect_control_ports() { for (auto& p : ports) { if (p.type == PortType::TYPE_CONTROL) { lilv_instance_connect_port(instance, p.index, &p.value); } } } void Lv2Wrapper::connect_data_ports(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (instance == nullptr) { return; } if (data_ports.in.left != UINT_MAX) lilv_instance_connect_port(instance, data_ports.in.left, left_in.data()); if (data_ports.in.right != UINT_MAX) lilv_instance_connect_port(instance, data_ports.in.right, right_in.data()); if (data_ports.out.left != UINT_MAX) lilv_instance_connect_port(instance, data_ports.out.left, left_out.data()); if (data_ports.out.right != UINT_MAX) lilv_instance_connect_port(instance, data_ports.out.right, right_out.data()); } void Lv2Wrapper::connect_data_ports(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) { if (instance == nullptr) { return; } if (data_ports.in.left != UINT_MAX) lilv_instance_connect_port(instance, data_ports.in.left, left_in.data()); if (data_ports.in.right != UINT_MAX) lilv_instance_connect_port(instance, data_ports.in.right, right_in.data()); if (data_ports.probe.left != UINT_MAX) lilv_instance_connect_port(instance, data_ports.probe.left, probe_left.data()); if (data_ports.probe.right != UINT_MAX) lilv_instance_connect_port(instance, data_ports.probe.right, probe_right.data()); if (data_ports.out.left != UINT_MAX) lilv_instance_connect_port(instance, data_ports.out.left, left_out.data()); if (data_ports.out.right != UINT_MAX) lilv_instance_connect_port(instance, data_ports.out.right, right_out.data()); } void Lv2Wrapper::set_n_samples(const uint& value) { this->n_samples = value; } auto Lv2Wrapper::get_n_samples() const -> uint { return this->n_samples; } auto Lv2Wrapper::get_rate() const -> uint { return this->rate; } void Lv2Wrapper::activate() { lilv_instance_activate(instance); } void Lv2Wrapper::run() const { if (instance != nullptr) { lilv_instance_run(instance, n_samples); } } void Lv2Wrapper::deactivate() { lilv_instance_deactivate(instance); } void Lv2Wrapper::set_control_port_value(const std::string& symbol, const float& value) { auto found = false; for (auto& p : ports) { if (p.type == PortType::TYPE_CONTROL && p.symbol == symbol) { if (!p.is_input) { util::warning(plugin_uri + " port " + symbol + " is not an input!"); return; } ui_port_event(p.index, value); // Check port bounds if (value < p.min) { // util::warning(plugin_uri + ": value " + util::to_string(value) + " is out of minimum limit for port " + // p.symbol + " (" + p.name + ")"); p.value = p.min; } else if (value > p.max) { // util::warning(plugin_uri + ": value " + util::to_string(value) + " is out of maximum limit for port " + // p.symbol + " (" + p.name + ")"); p.value = p.max; } else { p.value = value; } found = true; break; } } if (!found) { util::warning(plugin_uri + " port symbol not found: " + symbol); } } auto Lv2Wrapper::get_control_port_value(const std::string& symbol) -> float { size_t hash = std::hash<std::string>{}(symbol); for (const auto & slot : control_ports_cache) { // We use hash == 0 to mean the cache slot and all following are empty. // We might get collisions with hash == 0, which is fine. if (slot.first == 0) break; if (slot.first != hash) continue; // Ignore false positives. const Port & p = ports[slot.second]; if (p.type == PortType::TYPE_CONTROL && p.symbol == symbol) return p.value; } for (const auto& p : ports) { if (p.type == PortType::TYPE_CONTROL && p.symbol == symbol) { // Add to cache. for (size_t i = 0; i < control_ports_cache.size(); i++) { if (control_ports_cache[i].first == 0) { control_ports_cache[i] = std::pair<size_t, uint>(hash, p.index); break; } } return p.value; } } util::warning(plugin_uri + " port symbol not found: " + symbol); return 0.0F; } auto Lv2Wrapper::has_instance() -> bool { return instance != nullptr; } auto Lv2Wrapper::map_urid(const std::string& uri) -> LV2_URID { if (map_uri_to_urid.contains(uri)) { return map_uri_to_urid[uri]; } const auto hash = std::hash<std::string>{}(uri); map_uri_to_urid[uri] = hash; map_urid_to_uri[hash] = uri; return static_cast<LV2_URID>(hash); } void Lv2Wrapper::load_ui() { // preparing the thread that loads the native ui and updates it over time std::thread ui_updater([this]() { { std::scoped_lock<std::mutex> lku(ui_mutex); if (instance == nullptr) { return; } LilvUIs* uis = lilv_plugin_get_uis(plugin); if (uis == nullptr) { return; } /* Code based on: https://github.com/moddevices/mod-host/blob/f36bce78eed80f4f7194c923afd4dcae2c80bc79/src/effects.c#L8203 https://github.com/zrythm/zrythm/blob/1bc89335ca42b83ce759fd4cd0fd518e43b7983d/src/plugins/lv2/lv2_ui.c#L394 */ LILV_FOREACH(uis, u, uis) { const LilvUI* ui = lilv_uis_get(uis, u); std::string ui_uri = lilv_node_as_uri(lilv_ui_get_uri(ui)); util::debug(plugin_uri + " ui uri: " + ui_uri); const LilvNode* binary_node = lilv_ui_get_binary_uri(ui); const LilvNode* bundle_node = lilv_ui_get_bundle_uri(ui); { auto path = lilv_file_uri_parse(lilv_node_as_uri(binary_node), nullptr); libhandle = dlopen(path, RTLD_NOW); lilv_free(path); } if (libhandle == nullptr) { continue; } auto descfn = reinterpret_cast<LV2UI_DescriptorFunction>(dlsym(libhandle, "lv2ui_descriptor")); if (descfn == nullptr) { dlclose(libhandle); continue; } const LV2UI_Show_Interface* show_iface = nullptr; uint32_t index = 0U; while ((ui_descriptor = descfn(index++)) != nullptr) { if (ui_descriptor->extension_data == nullptr || ui_descriptor->URI != ui_uri) { continue; } idle_iface = static_cast<const LV2UI_Idle_Interface*>(ui_descriptor->extension_data(LV2_UI__idleInterface)); show_iface = static_cast<const LV2UI_Show_Interface*>(ui_descriptor->extension_data(LV2_UI__showInterface)); if (idle_iface == nullptr) { continue; } // initializing features LV2_Log_Log lv2_log = { this, &lv2_printf, [](LV2_Log_Handle handle, LV2_URID type, const char* fmt, va_list ap) { return std::vprintf(fmt, ap); }}; LV2_URID_Map lv2_map = {this, [](LV2_URID_Map_Handle handle, const char* uri) { auto* lw = static_cast<Lv2Wrapper*>(handle); return lw->map_urid(uri); }}; LV2_URID_Unmap lv2_unmap = {this, [](LV2_URID_Unmap_Handle handle, LV2_URID urid) { auto* lw = static_cast<Lv2Wrapper*>(handle); return lw->map_urid_to_uri[urid].c_str(); }}; const LV2_Feature lv2_log_feature = {LV2_LOG__log, &lv2_log}; const LV2_Feature lv2_map_feature = {LV2_URID__map, &lv2_map}; const LV2_Feature lv2_unmap_feature = {LV2_URID__unmap, &lv2_unmap}; auto options = std::to_array<LV2_Options_Option>({{LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_PARAMETERS__sampleRate), sizeof(float), map_urid(LV2_ATOM__Float), &rate}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__minBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &min_quantum}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__maxBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &max_quantum}, {LV2_OPTIONS_INSTANCE, 0, map_urid(LV2_BUF_SIZE__nominalBlockLength), sizeof(int32_t), map_urid(LV2_ATOM__Int), &n_samples}, {LV2_OPTIONS_INSTANCE, 0, 0, 0, 0, nullptr}}); LV2_Feature feature_options = {.URI = LV2_OPTIONS__options, .data = options.data()}; LV2_Extension_Data_Feature extension_data = {instance->lv2_descriptor->extension_data}; const LV2_Feature feature_dataAccess = {LV2_DATA_ACCESS_URI, &extension_data}; const LV2_Feature feature_instAccess = {LV2_INSTANCE_ACCESS_URI, instance->lv2_handle}; const LV2_Feature idle_feature = {LV2_UI__idleInterface, nullptr}; const LV2_Feature parent_feature = {LV2_UI__parent, nullptr}; const LV2_Feature fixed_size_feature = {LV2_UI__fixedSize, nullptr}; const LV2_Feature no_user_resize_feature = {LV2_UI__noUserResize, nullptr}; const LV2_Feature make_resident_feature = {LV2_UI_makeResident, nullptr}; const LV2_Feature make_soname_resident_feature = {LV2_UI_makeSONameResident, nullptr}; const auto features = std::to_array<const LV2_Feature*>( {&lv2_log_feature, &lv2_map_feature, &lv2_unmap_feature, &feature_options, static_features.data(), &feature_dataAccess, &feature_instAccess, &idle_feature, &parent_feature, &fixed_size_feature, &no_user_resize_feature, &make_resident_feature, &make_soname_resident_feature, nullptr}); LV2UI_Widget widget = nullptr; auto bundle_path = lilv_file_uri_parse(lilv_node_as_uri(bundle_node), nullptr); ui_handle = ui_descriptor->instantiate( ui_descriptor, plugin_uri.c_str(), bundle_path, +[](LV2UI_Controller controller, uint32_t port_index, uint32_t buffer_size, uint32_t port_protocol, const void* buffer) { auto self = static_cast<Lv2Wrapper*>(controller); for (auto& p : self->ports) { if (p.index == port_index) { // util::warning("The user clicked on port: " + p.name + " -> " + p.symbol); if (port_protocol == 0) { // port is a ui:floatProtocol p.value = *static_cast<const float*>(buffer); } } } }, this, &widget, features.data()); lilv_free(bundle_path); if (ui_handle == nullptr) { continue; } util::debug("found ui handle for" + ui_uri); if (show_iface != nullptr) { if (show_iface->show(ui_handle) != 0) { util::warning("failed to show ui for " + ui_uri); } } break; } } lilv_uis_free(uis); } // initilizing the ui with the current control values for (const auto& p : ports) { if (p.type == PortType::TYPE_CONTROL) { ui_descriptor->port_event(ui_handle, p.index, sizeof(float), 0, &p.value); } } while (has_ui()) { { std::scoped_lock<std::mutex> lk(ui_mutex); notify_ui(); update_ui(); } std::this_thread::sleep_for(std::chrono::milliseconds(static_cast<long>(1000.0 / ui_update_rate))); } }); ui_updater.detach(); } void Lv2Wrapper::notify_ui() { if (ui_descriptor == nullptr || ui_handle == nullptr) { return; } if (ui_descriptor->port_event == nullptr) { return; } for (const auto& p : ports) { if (p.type == PortType::TYPE_CONTROL && !p.is_input) { ui_descriptor->port_event(ui_handle, p.index, sizeof(float), 0, &p.value); } } } void Lv2Wrapper::update_ui() { if (idle_iface == nullptr || ui_handle == nullptr) { return; } idle_iface->idle(ui_handle); } auto Lv2Wrapper::has_ui() -> bool { return ui_handle != nullptr; } void Lv2Wrapper::close_ui() { std::scoped_lock<std::mutex> lk(ui_mutex); if (ui_descriptor != nullptr && ui_handle != nullptr) { ui_descriptor->cleanup(ui_handle); } if (libhandle != nullptr) { dlclose(libhandle); } ui_handle = nullptr; ui_descriptor = nullptr; libhandle = nullptr; } void Lv2Wrapper::set_ui_update_rate(const uint& value) { ui_update_rate = value; } void Lv2Wrapper::ui_port_event(const uint& port_index, const float& value) { if (ui_descriptor == nullptr || ui_handle == nullptr) { return; } ui_descriptor->port_event(ui_handle, port_index, sizeof(float), 0, &value); } void Lv2Wrapper::native_ui_to_gsettings() { if (ui_descriptor == nullptr || ui_handle == nullptr) { // only write to the database if the native ui is being used return; } for (const auto& func : gsettings_sync_funcs) { func(); } } } // namespace lv2
22,737
C++
.cpp
544
34.181985
120
0.608933
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,666
expander_ui.cpp
wwmm_easyeffects/src/expander_ui.cpp
/* * 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/>. */ #include "expander_ui.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "expander.hpp" #include "node_info_holder.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::expander_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Expander> expander; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _ExpanderBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkLabel *gain_label, *sidechain_label, *curve_label, *envelope_label; GtkSpinButton *attack, *release, *release_threshold, *threshold, *knee, *ratio, *makeup, *dry, *wet, *preamp, *reactivity, *lookahead, *hpf_freq, *lpf_freq; GtkToggleButton *listen, *show_native_ui; GtkCheckButton* stereo_split; GtkDropDown *expander_mode, *sidechain_type, *sidechain_mode, *sidechain_source, *stereo_split_source, *lpf_mode, *hpf_mode, *dropdown_input_devices; GListStore* input_devices_model; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(ExpanderBox, expander_box, GTK_TYPE_BOX) void on_reset(ExpanderBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(ExpanderBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->expander->show_native_ui(); } else { self->data->expander->close_native_ui(); } } auto set_dropdown_sensitive(ExpanderBox* self, const guint selected_id) -> gboolean { // Sensitive on External Device selected return (selected_id == 1U) ? 1 : 0; } void setup_dropdown_input_device(ExpanderBox* self) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(self->input_devices_model)); g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, ExpanderBox* self) { if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->settings, "sidechain-input-device", holder->info->name.c_str()); } }), self); gtk_drop_down_set_model(self->dropdown_input_devices, G_LIST_MODEL(self->input_devices_model)); g_object_unref(selection); } void setup(ExpanderBox* self, std::shared_ptr<Expander> expander, const std::string& schema_path, PipeManager* pm) { self->data->expander = expander; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::expander::id, schema_path.c_str()); expander->set_post_messages(true); setup_dropdown_input_device(self); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source || node.media_role == tags::pipewire::media_role::dsp) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); } } self->data->connections.push_back(expander->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(expander->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(expander->reduction.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->gain_label)) { return; } gtk_label_set_text(self->gain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(expander->envelope.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->envelope_label)) { return; } gtk_label_set_text(self->envelope_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(expander->sidechain.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->sidechain_label)) { return; } gtk_label_set_text(self->sidechain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(expander->curve.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->curve_label)) { return; } gtk_label_set_text(self->curve_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->expander->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "dry", gtk_spin_button_get_adjustment(self->dry), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet", gtk_spin_button_get_adjustment(self->wet), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "attack", gtk_spin_button_get_adjustment(self->attack), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "knee", gtk_spin_button_get_adjustment(self->knee), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "makeup", gtk_spin_button_get_adjustment(self->makeup), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "ratio", gtk_spin_button_get_adjustment(self->ratio), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release", gtk_spin_button_get_adjustment(self->release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "threshold", gtk_spin_button_get_adjustment(self->threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-preamp", gtk_spin_button_get_adjustment(self->preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-reactivity", gtk_spin_button_get_adjustment(self->reactivity), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-lookahead", gtk_spin_button_get_adjustment(self->lookahead), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release-threshold", gtk_spin_button_get_adjustment(self->release_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hpf-frequency", gtk_spin_button_get_adjustment(self->hpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "lpf-frequency", gtk_spin_button_get_adjustment(self->lpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-listen", self->listen, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "stereo-split", self->stereo_split, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "mode", self->expander_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-type", self->sidechain_type); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-mode", self->sidechain_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-source", self->sidechain_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "stereo-split-source", self->stereo_split_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "hpf-mode", self->hpf_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "lpf-mode", self->lpf_mode); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); // bind source dropdowns sensitive property to split-stereo gsettings boolean g_settings_bind(self->settings, "stereo-split", self->sidechain_source, "sensitive", static_cast<GSettingsBindFlags>(G_SETTINGS_BIND_DEFAULT | G_SETTINGS_BIND_INVERT_BOOLEAN)); g_settings_bind(self->settings, "stereo-split", self->stereo_split_source, "sensitive", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_EXPANDER_BOX(object); self->data->expander->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(expander_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_EXPANDER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(expander_box_parent_class)->finalize(object); } void expander_box_class_init(ExpanderBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::expander_ui); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, input_gain); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, output_gain); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, gain_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, sidechain_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, curve_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, envelope_label); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, attack); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, release); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, release_threshold); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, threshold); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, knee); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, ratio); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, makeup); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, dry); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, wet); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, preamp); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, reactivity); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, lookahead); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, hpf_freq); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, lpf_freq); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, expander_mode); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, sidechain_type); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, sidechain_mode); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, sidechain_source); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, stereo_split_source); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, stereo_split); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, lpf_mode); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, hpf_mode); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, listen); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, ExpanderBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); gtk_widget_class_bind_template_callback(widget_class, set_dropdown_sensitive); } void expander_box_init(ExpanderBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); prepare_spinbuttons<"dB">(self->threshold, self->knee, self->makeup, self->preamp); prepare_spinbuttons<"Hz">(self->hpf_freq, self->lpf_freq); prepare_spinbuttons<"ms">(self->attack, self->release, self->lookahead, self->reactivity); prepare_spinbuttons<"">(self->ratio); prepare_scales<"dB">(self->input_gain, self->output_gain); // The following spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->release_threshold, self->dry, self->wet); } auto create() -> ExpanderBox* { return static_cast<ExpanderBox*>(g_object_new(EE_TYPE_EXPANDER_BOX, nullptr)); } } // namespace ui::expander_box
18,178
C++
.cpp
357
45.190476
120
0.691712
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,667
speex_ui.cpp
wwmm_easyeffects/src/speex_ui.cpp
/* * 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/>. */ #include "speex_ui.hpp" #include <STTypes.h> #include <adwaita.h> #include <gio/gio.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "application.hpp" #include "speex.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::speex_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; app::Application* application; std::shared_ptr<Speex> speex; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _SpeexBox { GtkBox parent_instance; AdwToastOverlay* toast_overlay; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *noise_suppression_label, *plugin_credit; GtkSwitch *enable_denoise, *enable_agc, *enable_vad, *enable_dereverb; GtkSpinButton *noise_suppression, *vad_probability_start, *vad_probability_continue; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(SpeexBox, speex_box, GTK_TYPE_BOX) void on_reset(SpeexBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(SpeexBox* self, std::shared_ptr<Speex> speex, const std::string& schema_path, app::Application* application) { self->data->speex = speex; self->data->application = application; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::speex::id, schema_path.c_str()); speex->set_post_messages(true); self->data->connections.push_back(speex->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(speex->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->speex->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain", "enable-denoise", "noise-suppression", "enable-agc", "enable-vad", "vad-probability-start", "vad-probability-continue", "enable-dereverb">( self->settings, self->input_gain, self->output_gain, self->enable_denoise, self->noise_suppression, self->enable_agc, self->enable_vad, self->vad_probability_start, self->vad_probability_continue, self->enable_dereverb); } void dispose(GObject* object) { auto* self = EE_SPEEX_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(speex_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_SPEEX_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(speex_box_parent_class)->finalize(object); } void speex_box_class_init(SpeexBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::speex_ui); gtk_widget_class_bind_template_child(widget_class, SpeexBox, toast_overlay); gtk_widget_class_bind_template_child(widget_class, SpeexBox, input_gain); gtk_widget_class_bind_template_child(widget_class, SpeexBox, output_gain); gtk_widget_class_bind_template_child(widget_class, SpeexBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, SpeexBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, SpeexBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, SpeexBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, SpeexBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, SpeexBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, SpeexBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, SpeexBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, SpeexBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, SpeexBox, enable_denoise); gtk_widget_class_bind_template_child(widget_class, SpeexBox, enable_agc); gtk_widget_class_bind_template_child(widget_class, SpeexBox, enable_vad); gtk_widget_class_bind_template_child(widget_class, SpeexBox, enable_dereverb); gtk_widget_class_bind_template_child(widget_class, SpeexBox, noise_suppression); gtk_widget_class_bind_template_child(widget_class, SpeexBox, vad_probability_start); gtk_widget_class_bind_template_child(widget_class, SpeexBox, vad_probability_continue); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void speex_box_init(SpeexBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"dB">(self->noise_suppression); prepare_spinbuttons<"%">(self->vad_probability_start); prepare_spinbuttons<"%">(self->vad_probability_continue); } auto create() -> SpeexBox* { return static_cast<SpeexBox*>(g_object_new(EE_TYPE_SPEEX_BOX, nullptr)); } } // namespace ui::speex_box
7,425
C++
.cpp
166
40.626506
120
0.718611
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,668
stream_input_effects.cpp
wwmm_easyeffects/src/stream_input_effects.cpp
/* * 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/>. */ #include "stream_input_effects.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <pipewire/link.h> #include <sigc++/functors/mem_fun.h> #include <spa/utils/defs.h> #include <algorithm> #include <chrono> #include <cstdlib> #include <ranges> #include <set> #include <string> #include <thread> #include <vector> #include "effects_base.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" StreamInputEffects::StreamInputEffects(PipeManager* pipe_manager) : EffectsBase("sie: ", tags::schema::id_input, pipe_manager, PipelineType::input) { auto* PULSE_SOURCE = std::getenv("PULSE_SOURCE"); if (PULSE_SOURCE != nullptr && PULSE_SOURCE != tags::pipewire::ee_source_name) { for (const auto& [serial, node] : pm->node_map) { if (node.name == PULSE_SOURCE) { pm->input_device = node; g_settings_set_string(settings, "input-device", pm->input_device.name.c_str()); break; } } } connections.push_back(pm->source_added.connect([this](const NodeInfo node) { if (node.name == util::gsettings_get_string(settings, "input-device")) { pm->input_device = node; if (g_settings_get_boolean(global_settings, "bypass") != 0) { g_settings_set_boolean(global_settings, "bypass", 0); return; // filter connected through update_bypass_state } set_bypass(false); } })); connections.push_back(pm->source_removed.connect([this](const NodeInfo node) { if (g_settings_get_boolean(settings, "use-default-input-device") == 0) { if (node.name == util::gsettings_get_string(settings, "input-device")) { pm->input_device.id = SPA_ID_INVALID; pm->input_device.serial = SPA_ID_INVALID; } } })); connections.push_back(pm->stream_input_added.connect(sigc::mem_fun(*this, &StreamInputEffects::on_app_added))); connections.push_back(pm->link_changed.connect(sigc::mem_fun(*this, &StreamInputEffects::on_link_changed))); connect_filters(); gconnections.push_back(g_signal_connect(settings, "changed::input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<StreamInputEffects*>(user_data); const auto name = util::gsettings_get_string(settings, key); if (name.empty()) { return; } for (const auto& [serial, node] : self->pm->node_map) { if (node.name == name) { self->pm->input_device = node; if (g_settings_get_boolean(self->global_settings, "bypass") != 0) { g_settings_set_boolean(self->global_settings, "bypass", 0); return; // filter connected through update_bypass_state } self->set_bypass(false); break; } } }), this)); gconnections.push_back(g_signal_connect(settings, "changed::plugins", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<StreamInputEffects*>(user_data); if (g_settings_get_boolean(self->global_settings, "bypass") != 0) { g_settings_set_boolean(self->global_settings, "bypass", 0); return; // filter connected through update_bypass_state } self->set_bypass(false); }), this)); } StreamInputEffects::~StreamInputEffects() { disconnect_filters(); util::debug("destroyed"); } void StreamInputEffects::on_app_added(const NodeInfo node_info) { const auto blocklist = util::gchar_array_to_vector(g_settings_get_strv(settings, "blocklist")); auto is_blocklisted = std::ranges::find(blocklist, node_info.application_id) != blocklist.end(); is_blocklisted = is_blocklisted || std::ranges::find(blocklist, node_info.name) != blocklist.end(); if (g_settings_get_boolean(global_settings, "process-all-inputs") != 0 && !is_blocklisted) { pm->connect_stream_input(node_info.id); } } auto StreamInputEffects::apps_want_to_play() -> bool { return std::ranges::any_of(pm->list_links, [&](const auto& link) { return (link.output_node_id == pm->ee_source_node.id) && (link.state == PW_LINK_STATE_ACTIVE); }); return false; } void StreamInputEffects::on_link_changed(const LinkInfo link_info) { // We are not interested in the other link states if (link_info.state != PW_LINK_STATE_ACTIVE && link_info.state != PW_LINK_STATE_PAUSED) { return; } if (pm->default_input_device_name == pm->ee_source_node.name) { return; } /* If bypass is enabled do not touch the plugin pipeline */ if (bypass) { return; } if (apps_want_to_play()) { if (list_proxies.empty()) { util::debug("At least one app linked to our device wants to play. Linking our filters."); connect_filters(); }; } else { // no apps want to play, check if the inactivity timer is enabled if (g_settings_get_boolean(global_settings, "inactivity-timer-enable")) { // if the timer is enabled, wait for the timeout, then unlink plugin pipeline int inactivity_timeout = g_settings_get_int(global_settings, "inactivity-timeout"); g_timeout_add_seconds(inactivity_timeout, GSourceFunc(+[](StreamInputEffects* self) { if (!self->apps_want_to_play() && !self->list_proxies.empty()) { util::debug("No app linked to our device wants to play. Unlinking our filters."); self->disconnect_filters(); } return G_SOURCE_REMOVE; }), this); } else { // otherwise, do nothing if (!list_proxies.empty()) { util::debug( "No app linked to our device wants to play, but the inactivity timer is disabled. Leaving filters linked."); }; }; }; } void StreamInputEffects::connect_filters(const bool& bypass) { const auto input_device_name = util::gsettings_get_string(settings, "input-device"); // checking if the output device exists if (input_device_name.empty()) { util::debug("No input device set. Aborting the link"); return; } bool dev_exists = false; for (const auto& [serial, node] : pm->node_map) { if (node.name == input_device_name) { dev_exists = true; pm->input_device = node; break; } } if (!dev_exists) { util::debug("The input device " + input_device_name + " is not available. Aborting the link"); return; } const auto list = (bypass) ? std::vector<std::string>() : util::gchar_array_to_vector(g_settings_get_strv(settings, "plugins")); auto mic_linked = false; // waiting for the input device ports information to be available. int timeout = 0; while (pm->count_node_ports(pm->input_device.id) < 1) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); timeout++; if (timeout > 10000) { util::warning("Information about the ports of the input device " + pm->input_device.name + " with id " + util::to_string(pm->input_device.id) + " are taking to long to be available. Aborting the link"); return; } } uint prev_node_id = pm->input_device.id; uint next_node_id = 0U; // link plugins if (!list.empty()) { for (const auto& name : list) { if (!plugins.contains(name)) { continue; } if (!plugins[name]->connected_to_pw ? plugins[name]->connect_to_pw() : true) { next_node_id = plugins[name]->get_node_id(); const auto links = pm->link_nodes(prev_node_id, next_node_id); for (auto* link : links) { list_proxies.push_back(link); } if (mic_linked && (links.size() == 2U)) { prev_node_id = next_node_id; } else if (!mic_linked && (!links.empty())) { prev_node_id = next_node_id; mic_linked = true; } else { util::warning(" link from node " + util::to_string(prev_node_id) + " to node " + util::to_string(next_node_id) + " failed"); } } } // checking if we have to link the echo_canceller probe to the output device for (const auto& name : list) { if (!plugins.contains(name)) { continue; } if (name.starts_with(tags::plugin_name::echo_canceller)) { if (plugins[name]->connected_to_pw) { for (const auto& link : pm->link_nodes(pm->output_device.id, plugins[name]->get_node_id(), true)) { list_proxies.push_back(link); } } } plugins[name]->update_probe_links(); } } // link spectrum, output level meter and source node for (const auto node_id : {spectrum->get_node_id(), output_level->get_node_id(), pm->ee_source_node.id}) { next_node_id = node_id; const auto links = pm->link_nodes(prev_node_id, next_node_id); for (auto* link : links) { list_proxies.push_back(link); } if (mic_linked && (links.size() == 2U)) { prev_node_id = next_node_id; } else if (!mic_linked && (!links.empty())) { prev_node_id = next_node_id; mic_linked = true; } else { util::warning(" link from node " + util::to_string(prev_node_id) + " to node " + util::to_string(next_node_id) + " failed"); } } } void StreamInputEffects::disconnect_filters() { std::set<uint> link_id_list; const auto selected_plugins_list = (bypass) ? std::vector<std::string>() : util::gchar_array_to_vector(g_settings_get_strv(settings, "plugins")); for (const auto& plugin : plugins | std::views::values) { for (const auto& link : pm->list_links) { if (link.input_node_id == plugin->get_node_id() || link.output_node_id == plugin->get_node_id()) { link_id_list.insert(link.id); } } if (plugin->connected_to_pw) { if (std::ranges::find(selected_plugins_list, plugin->name) == selected_plugins_list.end()) { util::debug("disconnecting the " + plugin->name + " filter from PipeWire"); plugin->disconnect_from_pw(); } } } for (const auto& link : pm->list_links) { if (link.input_node_id == spectrum->get_node_id() || link.output_node_id == spectrum->get_node_id() || link.input_node_id == output_level->get_node_id() || link.output_node_id == output_level->get_node_id()) { link_id_list.insert(link.id); } } for (const auto& id : link_id_list) { pm->destroy_object(static_cast<int>(id)); } pm->destroy_links(list_proxies); list_proxies.clear(); // remove_unused_filters(); } void StreamInputEffects::set_bypass(const bool& state) { bypass = state; disconnect_filters(); connect_filters(state); } void StreamInputEffects::set_listen_to_mic(const bool& state) { if (state) { for (const auto& link : pm->link_nodes(pm->ee_source_node.id, pm->output_device.id, false, false)) { list_proxies_listen_mic.push_back(link); } } else { pm->destroy_links(list_proxies_listen_mic); list_proxies_listen_mic.clear(); } }
13,007
C++
.cpp
300
33.863333
120
0.583148
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,669
deepfilternet_ui.cpp
wwmm_easyeffects/src/deepfilternet_ui.cpp
/* * 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/>. */ #include "deepfilternet_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "deepfilternet.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::deepfilternet_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<DeepFilterNet> deepfilternet; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _DeepFilterNetBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkScale* att_limit; GtkLabel *att_limit_label, *min_processing_thresh_label, *max_erb_processing_thresh_label, *max_df_processing_thresh_label, *min_processing_buffer_label, *post_filter_beta_label; GtkSpinButton *min_processing_thresh, *max_erb_processing_thresh, *max_df_processing_thresh, *min_processing_buffer, *post_filter_beta; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(DeepFilterNetBox, deepfilternet_box, GTK_TYPE_BOX) void on_reset(DeepFilterNetBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(DeepFilterNetBox* self, std::shared_ptr<DeepFilterNet> deepfilternet, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->deepfilternet = deepfilternet; self->settings = g_settings_new_with_path(tags::schema::deepfilternet::id, schema_path.c_str()); deepfilternet->set_post_messages(true); self->data->connections.push_back(deepfilternet->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(deepfilternet->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->deepfilternet->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); gsettings_bind_widgets<"attenuation-limit", "min-processing-threshold", "max-erb-processing-threshold", "max-df-processing-threshold", "min-processing-buffer", "post-filter-beta">( self->settings, self->att_limit, self->min_processing_thresh, self->max_erb_processing_thresh, self->max_df_processing_thresh, self->min_processing_buffer, self->post_filter_beta); } void dispose(GObject* object) { auto* self = EE_DEEPFILTERNET_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(deepfilternet_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_DEEPFILTERNET_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(deepfilternet_box_parent_class)->finalize(object); } void deepfilternet_box_class_init(DeepFilterNetBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::deepfilternet_ui); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, input_gain); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, output_gain); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, att_limit); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, min_processing_thresh); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, max_erb_processing_thresh); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, max_df_processing_thresh); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, min_processing_buffer); gtk_widget_class_bind_template_child(widget_class, DeepFilterNetBox, post_filter_beta); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void deepfilternet_box_init(DeepFilterNetBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"dB">(self->min_processing_thresh); prepare_spinbuttons<"dB">(self->max_erb_processing_thresh); prepare_spinbuttons<"dB">(self->max_df_processing_thresh); prepare_spinbuttons<"frames">(self->min_processing_buffer); prepare_spinbuttons<"dB">(self->post_filter_beta); prepare_scales<"dB">(self->att_limit); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> DeepFilterNetBox* { return static_cast<DeepFilterNetBox*>(g_object_new(EE_TYPE_DEEPFILTERNET_BOX, nullptr)); } } // namespace ui::deepfilternet_box
7,858
C++
.cpp
163
44.214724
120
0.734678
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,670
gate_ui.cpp
wwmm_easyeffects/src/gate_ui.cpp
/* * 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/>. */ #include "gate_ui.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <fmt/format.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "gate.hpp" #include "node_info_holder.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::gate_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Gate> gate; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _GateBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkLabel *attack_zone_start_label, *attack_threshold_label, *release_zone_start_label, *release_threshold_label; GtkLabel *gain_label, *sidechain_label, *curve_label, *envelope_label; GtkToggleButton *hysteresis, *listen, *show_native_ui; GtkCheckButton* stereo_split; GtkSpinButton *attack, *release, *curve_threshold, *curve_zone, *hysteresis_threshold, *hysteresis_zone, *dry, *wet, *reduction, *makeup, *preamp, *reactivity, *lookahead, *hpf_freq, *lpf_freq; GtkDropDown *sidechain_source, *stereo_split_source, *sidechain_mode, *dropdown_input_devices, *sidechain_input, *lpf_mode, *hpf_mode; GListStore* input_devices_model; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(GateBox, gate_box, GTK_TYPE_BOX) void on_reset(GateBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(GateBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->gate->show_native_ui(); } else { self->data->gate->close_native_ui(); } } auto set_dropdown_sensitive(GateBox* self, const guint selected_id) -> gboolean { // Sensitive on External Device selected return (selected_id == 0U) ? 0 : 1; } void setup_dropdown_input_device(GateBox* self) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(self->input_devices_model)); g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, GateBox* self) { if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->settings, "sidechain-input-device", holder->info->name.c_str()); } }), self); gtk_drop_down_set_model(self->dropdown_input_devices, G_LIST_MODEL(self->input_devices_model)); g_object_unref(selection); } void setup(GateBox* self, std::shared_ptr<Gate> gate, const std::string& schema_path, PipeManager* pm) { self->data->gate = gate; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::gate::id, schema_path.c_str()); gate->set_post_messages(true); setup_dropdown_input_device(self); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source || node.media_role == tags::pipewire::media_role::dsp) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); } } self->data->connections.push_back(gate->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->attack_zone_start.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->attack_zone_start_label)) { return; } gtk_label_set_text(self->attack_zone_start_label, fmt::format(ui::get_user_locale(), "{0:.1Lf}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->attack_threshold.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->attack_threshold_label)) { return; } gtk_label_set_text(self->attack_threshold_label, fmt::format(ui::get_user_locale(), "{0:.1Lf}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->release_zone_start.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->release_zone_start_label)) { return; } gtk_label_set_text(self->release_zone_start_label, fmt::format(ui::get_user_locale(), "{0:.1Lf}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->release_threshold.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->release_threshold_label)) { return; } gtk_label_set_text(self->release_threshold_label, fmt::format(ui::get_user_locale(), "{0:.1Lf}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->reduction.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->gain_label)) { return; } gtk_label_set_text(self->gain_label, fmt::format("{0:.0Lf}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->envelope.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->envelope_label)) { return; } gtk_label_set_text(self->envelope_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->sidechain.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->sidechain_label)) { return; } gtk_label_set_text(self->sidechain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(gate->curve.connect([=](const float value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LABEL(self->curve_label)) { return; } gtk_label_set_text(self->curve_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->gate->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "dry", gtk_spin_button_get_adjustment(self->dry), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet", gtk_spin_button_get_adjustment(self->wet), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "attack", gtk_spin_button_get_adjustment(self->attack), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "release", gtk_spin_button_get_adjustment(self->release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "curve-threshold", gtk_spin_button_get_adjustment(self->curve_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "curve-zone", gtk_spin_button_get_adjustment(self->curve_zone), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hysteresis", self->hysteresis, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hysteresis-threshold", gtk_spin_button_get_adjustment(self->hysteresis_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hysteresis-zone", gtk_spin_button_get_adjustment(self->hysteresis_zone), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "reduction", gtk_spin_button_get_adjustment(self->reduction), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "makeup", gtk_spin_button_get_adjustment(self->makeup), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-preamp", gtk_spin_button_get_adjustment(self->preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-reactivity", gtk_spin_button_get_adjustment(self->reactivity), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-lookahead", gtk_spin_button_get_adjustment(self->lookahead), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "hpf-frequency", gtk_spin_button_get_adjustment(self->hpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "lpf-frequency", gtk_spin_button_get_adjustment(self->lpf_freq), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "sidechain-listen", self->listen, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "stereo-split", self->stereo_split, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-input", self->sidechain_input); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-mode", self->sidechain_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "sidechain-source", self->sidechain_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "stereo-split-source", self->stereo_split_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, "hpf-mode", self->hpf_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "lpf-mode", self->lpf_mode); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); // bind source dropdowns sensitive property to split-stereo gsettings boolean g_settings_bind(self->settings, "stereo-split", self->sidechain_source, "sensitive", static_cast<GSettingsBindFlags>(G_SETTINGS_BIND_DEFAULT | G_SETTINGS_BIND_INVERT_BOOLEAN)); g_settings_bind(self->settings, "stereo-split", self->stereo_split_source, "sensitive", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_GATE_BOX(object); self->data->gate->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(gate_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_GATE_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(gate_box_parent_class)->finalize(object); } void gate_box_class_init(GateBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::gate_ui); gtk_widget_class_bind_template_child(widget_class, GateBox, input_gain); gtk_widget_class_bind_template_child(widget_class, GateBox, output_gain); gtk_widget_class_bind_template_child(widget_class, GateBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, GateBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, GateBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, GateBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, GateBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, GateBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, GateBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, GateBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, GateBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, GateBox, attack_zone_start_label); gtk_widget_class_bind_template_child(widget_class, GateBox, attack_threshold_label); gtk_widget_class_bind_template_child(widget_class, GateBox, release_zone_start_label); gtk_widget_class_bind_template_child(widget_class, GateBox, release_threshold_label); gtk_widget_class_bind_template_child(widget_class, GateBox, gain_label); gtk_widget_class_bind_template_child(widget_class, GateBox, sidechain_label); gtk_widget_class_bind_template_child(widget_class, GateBox, curve_label); gtk_widget_class_bind_template_child(widget_class, GateBox, envelope_label); gtk_widget_class_bind_template_child(widget_class, GateBox, attack); gtk_widget_class_bind_template_child(widget_class, GateBox, release); gtk_widget_class_bind_template_child(widget_class, GateBox, curve_threshold); gtk_widget_class_bind_template_child(widget_class, GateBox, curve_zone); gtk_widget_class_bind_template_child(widget_class, GateBox, hysteresis); gtk_widget_class_bind_template_child(widget_class, GateBox, hysteresis_threshold); gtk_widget_class_bind_template_child(widget_class, GateBox, hysteresis_zone); gtk_widget_class_bind_template_child(widget_class, GateBox, dry); gtk_widget_class_bind_template_child(widget_class, GateBox, wet); gtk_widget_class_bind_template_child(widget_class, GateBox, reduction); gtk_widget_class_bind_template_child(widget_class, GateBox, makeup); gtk_widget_class_bind_template_child(widget_class, GateBox, preamp); gtk_widget_class_bind_template_child(widget_class, GateBox, reactivity); gtk_widget_class_bind_template_child(widget_class, GateBox, lookahead); gtk_widget_class_bind_template_child(widget_class, GateBox, hpf_freq); gtk_widget_class_bind_template_child(widget_class, GateBox, lpf_freq); gtk_widget_class_bind_template_child(widget_class, GateBox, sidechain_input); gtk_widget_class_bind_template_child(widget_class, GateBox, sidechain_mode); gtk_widget_class_bind_template_child(widget_class, GateBox, sidechain_source); gtk_widget_class_bind_template_child(widget_class, GateBox, stereo_split_source); gtk_widget_class_bind_template_child(widget_class, GateBox, stereo_split); gtk_widget_class_bind_template_child(widget_class, GateBox, lpf_mode); gtk_widget_class_bind_template_child(widget_class, GateBox, hpf_mode); gtk_widget_class_bind_template_child(widget_class, GateBox, listen); gtk_widget_class_bind_template_child(widget_class, GateBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, GateBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); gtk_widget_class_bind_template_callback(widget_class, set_dropdown_sensitive); } void gate_box_init(GateBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); prepare_spinbuttons<"dB">(self->curve_threshold, self->curve_zone, self->hysteresis_threshold, self->hysteresis_zone, self->reduction, self->makeup, self->preamp); prepare_spinbuttons<"Hz">(self->hpf_freq, self->lpf_freq); prepare_spinbuttons<"ms">(self->attack, self->release, self->lookahead, self->reactivity); prepare_scales<"dB">(self->input_gain, self->output_gain); // The following spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->dry, self->wet); } auto create() -> GateBox* { return static_cast<GateBox*>(g_object_new(EE_TYPE_GATE_BOX, nullptr)); } } // namespace ui::gate_box
21,020
C++
.cpp
427
42.751756
119
0.669406
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,671
expander_preset.cpp
wwmm_easyeffects/src/expander_preset.cpp
/* * 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/>. */ #include "expander_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" ExpanderPreset::ExpanderPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::expander::id, tags::schema::expander::input_path, tags::schema::expander::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::expander).append("#").append(util::to_string(index)); } void ExpanderPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["dry"] = g_settings_get_double(settings, "dry"); json[section][instance_name]["wet"] = g_settings_get_double(settings, "wet"); json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["attack"] = g_settings_get_double(settings, "attack"); json[section][instance_name]["release"] = g_settings_get_double(settings, "release"); json[section][instance_name]["release-threshold"] = g_settings_get_double(settings, "release-threshold"); json[section][instance_name]["threshold"] = g_settings_get_double(settings, "threshold"); json[section][instance_name]["ratio"] = g_settings_get_double(settings, "ratio"); json[section][instance_name]["knee"] = g_settings_get_double(settings, "knee"); json[section][instance_name]["makeup"] = g_settings_get_double(settings, "makeup"); json[section][instance_name]["stereo-split"] = g_settings_get_boolean(settings, "stereo-split") != 0; json[section][instance_name]["sidechain"]["type"] = util::gsettings_get_string(settings, "sidechain-type"); json[section][instance_name]["sidechain"]["mode"] = util::gsettings_get_string(settings, "sidechain-mode"); json[section][instance_name]["sidechain"]["source"] = util::gsettings_get_string(settings, "sidechain-source"); json[section][instance_name]["sidechain"]["stereo-split-source"] = util::gsettings_get_string(settings, "stereo-split-source"); json[section][instance_name]["sidechain"]["preamp"] = g_settings_get_double(settings, "sidechain-preamp"); json[section][instance_name]["sidechain"]["reactivity"] = g_settings_get_double(settings, "sidechain-reactivity"); json[section][instance_name]["sidechain"]["lookahead"] = g_settings_get_double(settings, "sidechain-lookahead"); json[section][instance_name]["hpf-mode"] = util::gsettings_get_string(settings, "hpf-mode"); json[section][instance_name]["hpf-frequency"] = g_settings_get_double(settings, "hpf-frequency"); json[section][instance_name]["lpf-mode"] = util::gsettings_get_string(settings, "lpf-mode"); json[section][instance_name]["lpf-frequency"] = g_settings_get_double(settings, "lpf-frequency"); } void ExpanderPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "dry", "dry"); update_key<double>(json.at(section).at(instance_name), settings, "wet", "wet"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<double>(json.at(section).at(instance_name), settings, "attack", "attack"); update_key<double>(json.at(section).at(instance_name), settings, "release", "release"); update_key<double>(json.at(section).at(instance_name), settings, "release-threshold", "release-threshold"); update_key<double>(json.at(section).at(instance_name), settings, "threshold", "threshold"); update_key<double>(json.at(section).at(instance_name), settings, "ratio", "ratio"); update_key<double>(json.at(section).at(instance_name), settings, "knee", "knee"); update_key<double>(json.at(section).at(instance_name), settings, "makeup", "makeup"); update_key<bool>(json.at(section).at(instance_name), settings, "stereo-split", "stereo-split"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-type", "type"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-mode", "mode"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "stereo-split-source", "stereo-split-source"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-source", "source"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-preamp", "preamp"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-reactivity", "reactivity"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-lookahead", "lookahead"); update_key<gchar*>(json.at(section).at(instance_name), settings, "hpf-mode", "hpf-mode"); update_key<double>(json.at(section).at(instance_name), settings, "hpf-frequency", "hpf-frequency"); update_key<gchar*>(json.at(section).at(instance_name), settings, "lpf-mode", "lpf-mode"); update_key<double>(json.at(section).at(instance_name), settings, "lpf-frequency", "lpf-frequency"); }
6,543
C++
.cpp
92
66.695652
119
0.712768
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,672
delay_ui.cpp
wwmm_easyeffects/src/delay_ui.cpp
/* * 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/>. */ #include "delay_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "delay.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::delay_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Delay> delay; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _DelayBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *time_l, *time_r, *dry_l, *dry_r, *wet_l, *wet_r; GtkToggleButton* show_native_ui; GtkSwitch *invert_phase_l, *invert_phase_r; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(DelayBox, delay_box, GTK_TYPE_BOX) void on_reset(DelayBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(DelayBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->delay->show_native_ui(); } else { self->data->delay->close_native_ui(); } } void setup(DelayBox* self, std::shared_ptr<Delay> delay, const std::string& schema_path) { self->data->delay = delay; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::delay::id, schema_path.c_str()); delay->set_post_messages(true); self->data->connections.push_back(delay->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(delay->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->delay->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "time-l", gtk_spin_button_get_adjustment(self->time_l), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "time-r", gtk_spin_button_get_adjustment(self->time_r), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "dry-l", gtk_spin_button_get_adjustment(self->dry_l), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "dry-r", gtk_spin_button_get_adjustment(self->dry_r), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet-l", gtk_spin_button_get_adjustment(self->wet_l), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet-r", gtk_spin_button_get_adjustment(self->wet_r), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "invert-phase-l", self->invert_phase_l, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "invert-phase-r", self->invert_phase_r, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_DELAY_BOX(object); self->data->delay->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(delay_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_DELAY_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(delay_box_parent_class)->finalize(object); } void delay_box_class_init(DelayBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::delay_ui); gtk_widget_class_bind_template_child(widget_class, DelayBox, input_gain); gtk_widget_class_bind_template_child(widget_class, DelayBox, output_gain); gtk_widget_class_bind_template_child(widget_class, DelayBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, DelayBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, DelayBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, DelayBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, DelayBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, DelayBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, DelayBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, DelayBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, DelayBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, DelayBox, time_l); gtk_widget_class_bind_template_child(widget_class, DelayBox, time_r); gtk_widget_class_bind_template_child(widget_class, DelayBox, dry_l); gtk_widget_class_bind_template_child(widget_class, DelayBox, dry_r); gtk_widget_class_bind_template_child(widget_class, DelayBox, wet_l); gtk_widget_class_bind_template_child(widget_class, DelayBox, wet_r); gtk_widget_class_bind_template_child(widget_class, DelayBox, invert_phase_l); gtk_widget_class_bind_template_child(widget_class, DelayBox, invert_phase_r); gtk_widget_class_bind_template_child(widget_class, DelayBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); } void delay_box_init(DelayBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"ms">(self->time_l, self->time_r); prepare_scales<"dB">(self->input_gain, self->output_gain); // The following spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->dry_l, self->dry_r, self->wet_l, self->wet_r); } auto create() -> DelayBox* { return static_cast<DelayBox*>(g_object_new(EE_TYPE_DELAY_BOX, nullptr)); } } // namespace ui::delay_box
8,445
C++
.cpp
182
42.049451
114
0.706213
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,673
fir_filter_highpass.cpp
wwmm_easyeffects/src/fir_filter_highpass.cpp
/* * 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/>. */ #include "fir_filter_highpass.hpp" #include <algorithm> #include <string> #include <utility> #include "fir_filter_base.hpp" FirFilterHighpass::FirFilterHighpass(std::string tag) : FirFilterBase(std::move(tag)) {} FirFilterHighpass::~FirFilterHighpass() = default; void FirFilterHighpass::setup() { kernel = create_lowpass_kernel(min_frequency, transition_band); std::ranges::for_each(kernel, [](auto& v) { v *= -1.0F; }); kernel[(kernel.size() - 1U) / 2U] += 1.0F; delay = 0.5F * static_cast<float>(kernel.size() - 1U) / static_cast<float>(rate); setup_zita(); }
1,334
C++
.cpp
32
39.59375
88
0.731066
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,674
echo_canceller.cpp
wwmm_easyeffects/src/echo_canceller.cpp
/* * 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/>. */ #include "echo_canceller.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <speex/speex_echo.h> #include <speex/speex_preprocess.h> #include <speex/speexdsp_config_types.h> #include <sys/types.h> #include <algorithm> #include <climits> #include <cstddef> #include <mutex> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" EchoCanceller::EchoCanceller(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::echo_canceller, tags::plugin_package::speex, schema, schema_path, pipe_manager, pipe_type, true), residual_echo_suppression(g_settings_get_int(settings, "residual-echo-suppression")), near_end_suppression(g_settings_get_int(settings, "near-end-suppression")) { gconnections.push_back(g_signal_connect(settings, "changed::filter-length", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<EchoCanceller*>(user_data); std::scoped_lock<std::mutex> lock(self->data_mutex); self->filter_length_ms = g_settings_get_int(settings, key); self->init_speex(); }), this)); gconnections.push_back(g_signal_connect( settings, "changed::residual-echo-suppression", G_CALLBACK(+[](GSettings* settings, char* key, EchoCanceller* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->residual_echo_suppression = g_settings_get_int(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS, &self->residual_echo_suppression); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS, &self->residual_echo_suppression); } }), this)); gconnections.push_back(g_signal_connect( settings, "changed::near-end-suppression", G_CALLBACK(+[](GSettings* settings, char* key, EchoCanceller* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->near_end_suppression = g_settings_get_int(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE, &self->near_end_suppression); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE, &self->near_end_suppression); } }), this)); setup_input_output_gain(); } EchoCanceller::~EchoCanceller() { if (connected_to_pw) { disconnect_from_pw(); } data_mutex.lock(); ready = false; if (echo_state_L != nullptr) { speex_echo_state_destroy(echo_state_L); } if (echo_state_R != nullptr) { speex_echo_state_destroy(echo_state_R); } free_speex(); data_mutex.unlock(); util::debug(log_tag + name + " destroyed"); } void EchoCanceller::setup() { std::scoped_lock<std::mutex> lock(data_mutex); ready = false; notify_latency = true; latency_n_frames = 0U; init_speex(); } void EchoCanceller::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) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass || !ready) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } for (size_t j = 0U; j < left_in.size(); j++) { data_L[j] = static_cast<spx_int16_t>(left_in[j] * (SHRT_MAX + 1)); data_R[j] = static_cast<spx_int16_t>(right_in[j] * (SHRT_MAX + 1)); /* This is a very naive and not corect attempt to mitigate the shortcomes discussed at https://github.com/wwmm/easyeffects/issues/1566. */ probe_mono[j] = static_cast<spx_int16_t>(0.5F * (probe_left[j] + probe_right[j]) * (SHRT_MAX + 1)); } speex_echo_cancellation(echo_state_L, data_L.data(), probe_mono.data(), filtered_L.data()); speex_echo_cancellation(echo_state_R, data_R.data(), probe_mono.data(), filtered_R.data()); speex_preprocess_run(state_left, filtered_L.data()); speex_preprocess_run(state_right, filtered_R.data()); for (size_t j = 0U; j < filtered_L.size(); j++) { left_out[j] = static_cast<float>(filtered_L[j]) * inv_short_max; right_out[j] = static_cast<float>(filtered_R[j]) * inv_short_max; } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (notify_latency) { const float latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); notify_latency = false; } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } void EchoCanceller::init_speex() { if (n_samples == 0U || rate == 0U) { return; } data_L.resize(n_samples); data_R.resize(n_samples); probe_mono.resize(n_samples); filtered_L.resize(n_samples); filtered_R.resize(n_samples); const uint filter_length = static_cast<uint>(0.001F * static_cast<float>(filter_length_ms * rate)); util::debug(log_tag + name + " filter length: " + util::to_string(filter_length)); if (echo_state_L != nullptr) { speex_echo_state_destroy(echo_state_L); } echo_state_L = speex_echo_state_init(static_cast<int>(n_samples), static_cast<int>(filter_length)); if (speex_echo_ctl(echo_state_L, SPEEX_ECHO_SET_SAMPLING_RATE, &rate) != 0) { util::warning(log_tag + name + "SPEEX_ECHO_SET_SAMPLING_RATE: unknown request"); } if (echo_state_R != nullptr) { speex_echo_state_destroy(echo_state_R); } echo_state_R = speex_echo_state_init(static_cast<int>(n_samples), static_cast<int>(filter_length)); if (speex_echo_ctl(echo_state_R, SPEEX_ECHO_SET_SAMPLING_RATE, &rate) != 0) { util::warning(log_tag + name + "SPEEX_ECHO_SET_SAMPLING_RATE: unknown request"); } if (state_left != nullptr) { speex_preprocess_state_destroy(state_left); } if (state_right != nullptr) { speex_preprocess_state_destroy(state_right); } state_left = speex_preprocess_state_init(static_cast<int>(n_samples), static_cast<int>(rate)); state_right = speex_preprocess_state_init(static_cast<int>(n_samples), static_cast<int>(rate)); if (state_left != nullptr) { speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_ECHO_STATE, echo_state_L); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS, &residual_echo_suppression); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE, &near_end_suppression); } if (state_right != nullptr) { speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_ECHO_STATE, echo_state_R); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS, &residual_echo_suppression); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_ECHO_SUPPRESS_ACTIVE, &near_end_suppression); } ready = true; } void EchoCanceller::free_speex() { if (state_left != nullptr) { speex_preprocess_state_destroy(state_left); } if (state_right != nullptr) { speex_preprocess_state_destroy(state_right); } state_left = nullptr; state_right = nullptr; } auto EchoCanceller::get_latency_seconds() -> float { return latency_value; }
9,292
C++
.cpp
223
34.511211
120
0.632696
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,675
equalizer_preset.cpp
wwmm_easyeffects/src/equalizer_preset.cpp
/* * 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/>. */ #include "equalizer_preset.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_equalizer.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" using namespace tags::equalizer; EqualizerPreset::EqualizerPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::equalizer::id, tags::schema::equalizer::input_path, tags::schema::equalizer::output_path, preset_type, index) { input_settings_left = g_settings_new_with_path( tags::schema::equalizer::channel_id, (tags::schema::equalizer::input_path + util::to_string(index) + "/leftchannel/").c_str()); input_settings_right = g_settings_new_with_path( tags::schema::equalizer::channel_id, (tags::schema::equalizer::input_path + util::to_string(index) + "/rightchannel/").c_str()); output_settings_left = g_settings_new_with_path( tags::schema::equalizer::channel_id, (tags::schema::equalizer::output_path + util::to_string(index) + "/leftchannel/").c_str()); output_settings_right = g_settings_new_with_path( tags::schema::equalizer::channel_id, (tags::schema::equalizer::output_path + util::to_string(index) + "/rightchannel/").c_str()); instance_name.assign(tags::plugin_name::equalizer).append("#").append(util::to_string(index)); } EqualizerPreset::~EqualizerPreset() { g_object_unref(input_settings_left); g_object_unref(input_settings_right); g_object_unref(output_settings_left); g_object_unref(output_settings_right); } void EqualizerPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["split-channels"] = g_settings_get_boolean(settings, "split-channels") != 0; json[section][instance_name]["balance"] = g_settings_get_double(settings, "balance"); json[section][instance_name]["pitch-left"] = g_settings_get_double(settings, "pitch-left"); json[section][instance_name]["pitch-right"] = g_settings_get_double(settings, "pitch-right"); const auto nbands = g_settings_get_int(settings, "num-bands"); json[section][instance_name]["num-bands"] = nbands; if (section == "input") { save_channel(json[section][instance_name]["left"], input_settings_left, nbands); save_channel(json[section][instance_name]["right"], input_settings_right, nbands); } else if (section == "output") { save_channel(json[section][instance_name]["left"], output_settings_left, nbands); save_channel(json[section][instance_name]["right"], output_settings_right, nbands); } } void EqualizerPreset::save_channel(nlohmann::json& json, GSettings* settings, const int& nbands) { for (int n = 0; n < nbands; n++) { const auto* const bandn = band_id[n]; json[bandn]["type"] = util::gsettings_get_string(settings, band_type[n].data()); json[bandn]["mode"] = util::gsettings_get_string(settings, band_mode[n].data()); json[bandn]["slope"] = util::gsettings_get_string(settings, band_slope[n].data()); json[bandn]["solo"] = g_settings_get_boolean(settings, band_solo[n].data()) != 0; json[bandn]["mute"] = g_settings_get_boolean(settings, band_mute[n].data()) != 0; json[bandn]["gain"] = g_settings_get_double(settings, band_gain[n].data()); json[bandn]["frequency"] = g_settings_get_double(settings, band_frequency[n].data()); json[bandn]["q"] = g_settings_get_double(settings, band_q[n].data()); json[bandn]["width"] = g_settings_get_double(settings, band_width[n].data()); } } void EqualizerPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<int>(json.at(section).at(instance_name), settings, "num-bands", "num-bands"); update_key<bool>(json.at(section).at(instance_name), settings, "split-channels", "split-channels"); update_key<double>(json.at(section).at(instance_name), settings, "balance", "balance"); update_key<double>(json.at(section).at(instance_name), settings, "pitch-left", "pitch-left"); update_key<double>(json.at(section).at(instance_name), settings, "pitch-right", "pitch-right"); const auto nbands = g_settings_get_int(settings, "num-bands"); if (section == "input") { load_channel(json.at(section).at(instance_name).at("left"), input_settings_left, nbands); load_channel(json.at(section).at(instance_name).at("right"), input_settings_right, nbands); } else if (section == "output") { load_channel(json.at(section).at(instance_name).at("left"), output_settings_left, nbands); load_channel(json.at(section).at(instance_name).at("right"), output_settings_right, nbands); } } void EqualizerPreset::load_channel(const nlohmann::json& json, GSettings* settings, const int& nbands) { for (int n = 0; n < nbands; n++) { const auto bandn = "band" + util::to_string(n); update_key<gchar*>(json.at(bandn), settings, band_type[n].data(), "type"); update_key<gchar*>(json.at(bandn), settings, band_mode[n].data(), "mode"); update_key<gchar*>(json.at(bandn), settings, band_slope[n].data(), "slope"); update_key<bool>(json.at(bandn), settings, band_solo[n].data(), "solo"); update_key<bool>(json.at(bandn), settings, band_mute[n].data(), "mute"); update_key<double>(json.at(bandn), settings, band_gain[n].data(), "gain"); update_key<double>(json.at(bandn), settings, band_frequency[n].data(), "frequency"); update_key<double>(json.at(bandn), settings, band_q[n].data(), "q"); update_key<double>(json.at(bandn), settings, band_width[n].data(), "width"); } }
7,128
C++
.cpp
122
54.139344
107
0.694221
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,676
presets_manager.cpp
wwmm_easyeffects/src/presets_manager.cpp
/* * 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/>. */ #include "presets_manager.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <sys/types.h> #include <exception> #include <filesystem> #include <fstream> #include <iomanip> #include <memory> #include <nlohmann/json_fwd.hpp> #include <optional> #include <ostream> #include <regex> #include <stdexcept> #include <string> #include <string_view> #include <utility> #include <vector> #include "autogain_preset.hpp" #include "bass_enhancer_preset.hpp" #include "bass_loudness_preset.hpp" #include "compressor_preset.hpp" #include "convolver_preset.hpp" #include "crossfeed_preset.hpp" #include "crystalizer_preset.hpp" #include "deepfilternet_preset.hpp" #include "deesser_preset.hpp" #include "delay_preset.hpp" #include "echo_canceller_preset.hpp" #include "equalizer_preset.hpp" #include "exciter_preset.hpp" #include "expander_preset.hpp" #include "filter_preset.hpp" #include "gate_preset.hpp" #include "level_meter_preset.hpp" #include "limiter_preset.hpp" #include "loudness_preset.hpp" #include "maximizer_preset.hpp" #include "multiband_compressor_preset.hpp" #include "multiband_gate_preset.hpp" #include "pitch_preset.hpp" #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "reverb_preset.hpp" #include "rnnoise_preset.hpp" #include "speex_preset.hpp" #include "stereo_tools_preset.hpp" #include "tags_app.hpp" #include "tags_plugin_name.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "util.hpp" PresetsManager::PresetsManager() : user_config_dir(g_get_user_config_dir()), user_input_dir(user_config_dir + "/easyeffects/input"), user_output_dir(user_config_dir + "/easyeffects/output"), user_irs_dir(user_config_dir + "/easyeffects/irs"), user_rnnoise_dir(user_config_dir + "/easyeffects/rnnoise"), autoload_input_dir(user_config_dir + "/easyeffects/autoload/input"), autoload_output_dir(user_config_dir + "/easyeffects/autoload/output"), settings(g_settings_new(tags::app::id)), soe_settings(g_settings_new(tags::schema::id_output)), sie_settings(g_settings_new(tags::schema::id_input)) { // Initialize input and output directories for community presets. // Flatpak specific path (.flatpak-info always present for apps running in the flatpak sandbox). if (std::filesystem::is_regular_file(tags::resources::flatpak_info_file)) { system_data_dir_input.push_back("/app/extensions/Presets/input"); system_data_dir_output.push_back("/app/extensions/Presets/output"); system_data_dir_irs.push_back("/app/extensions/Presets/irs"); system_data_dir_rnnoise.push_back("/app/extensions/Presets/rnnoise"); } // Regular paths. for (const gchar* const* xdg_data_dirs = g_get_system_data_dirs(); *xdg_data_dirs != nullptr;) { std::string dir = *xdg_data_dirs++; dir += dir.ends_with("/") ? "" : "/"; system_data_dir_input.push_back(dir + "easyeffects/input"); system_data_dir_output.push_back(dir + "easyeffects/output"); system_data_dir_irs.push_back(dir + "easyeffects/irs"); system_data_dir_rnnoise.push_back(dir + "easyeffects/rnnoise"); } // create user presets directories create_user_directory(user_input_dir); create_user_directory(user_output_dir); create_user_directory(user_irs_dir); create_user_directory(user_rnnoise_dir); create_user_directory(autoload_input_dir); create_user_directory(autoload_output_dir); auto* gfile = g_file_new_for_path(user_output_dir.c_str()); user_output_monitor = g_file_monitor_directory(gfile, G_FILE_MONITOR_NONE, nullptr, nullptr); g_signal_connect(user_output_monitor, "changed", G_CALLBACK(+[](GFileMonitor* monitor, GFile* file, GFile* other_file, GFileMonitorEvent event_type, gpointer user_data) { auto* self = static_cast<PresetsManager*>(user_data); switch (event_type) { case G_FILE_MONITOR_EVENT_CREATED: { const auto preset_name = util::remove_filename_extension(g_file_get_basename(file)); self->user_output_preset_created.emit(preset_name); break; } case G_FILE_MONITOR_EVENT_DELETED: { const auto preset_name = util::remove_filename_extension(g_file_get_basename(file)); self->user_output_preset_removed.emit(preset_name); break; } default: break; } }), this); g_object_unref(gfile); gfile = g_file_new_for_path(user_input_dir.c_str()); user_input_monitor = g_file_monitor_directory(gfile, G_FILE_MONITOR_NONE, nullptr, nullptr); g_signal_connect(user_input_monitor, "changed", G_CALLBACK(+[](GFileMonitor* monitor, GFile* file, GFile* other_file, GFileMonitorEvent event_type, gpointer user_data) { auto* self = static_cast<PresetsManager*>(user_data); switch (event_type) { case G_FILE_MONITOR_EVENT_CREATED: { const auto preset_name = util::remove_filename_extension(g_file_get_basename(file)); self->user_input_preset_created.emit(preset_name); break; } case G_FILE_MONITOR_EVENT_DELETED: { const auto preset_name = util::remove_filename_extension(g_file_get_basename(file)); self->user_input_preset_removed.emit(preset_name); break; } default: break; } }), this); g_object_unref(gfile); gfile = g_file_new_for_path(autoload_input_dir.c_str()); autoload_input_monitor = g_file_monitor_directory(gfile, G_FILE_MONITOR_NONE, nullptr, nullptr); g_signal_connect(autoload_input_monitor, "changed", G_CALLBACK(+[](GFileMonitor* monitor, GFile* file, GFile* other_file, GFileMonitorEvent event_type, gpointer user_data) { auto* self = static_cast<PresetsManager*>(user_data); if (event_type == G_FILE_MONITOR_EVENT_CREATED || event_type == G_FILE_MONITOR_EVENT_DELETED) { const auto profiles = self->get_autoload_profiles(PresetType::input); self->autoload_input_profiles_changed.emit(profiles); } }), this); g_object_unref(gfile); gfile = g_file_new_for_path(autoload_output_dir.c_str()); autoload_output_monitor = g_file_monitor_directory(gfile, G_FILE_MONITOR_NONE, nullptr, nullptr); g_signal_connect(autoload_output_monitor, "changed", G_CALLBACK(+[](GFileMonitor* monitor, GFile* file, GFile* other_file, GFileMonitorEvent event_type, gpointer user_data) { auto* self = static_cast<PresetsManager*>(user_data); if (event_type == G_FILE_MONITOR_EVENT_CREATED || event_type == G_FILE_MONITOR_EVENT_DELETED) { const auto profiles = self->get_autoload_profiles(PresetType::output); self->autoload_output_profiles_changed.emit(profiles); } }), this); g_object_unref(gfile); } PresetsManager::~PresetsManager() { g_file_monitor_cancel(user_output_monitor); g_file_monitor_cancel(user_input_monitor); g_file_monitor_cancel(autoload_input_monitor); g_file_monitor_cancel(autoload_output_monitor); g_object_unref(user_output_monitor); g_object_unref(user_input_monitor); g_object_unref(autoload_input_monitor); g_object_unref(autoload_output_monitor); g_object_unref(settings); g_object_unref(sie_settings); g_object_unref(soe_settings); util::debug("destroyed"); } void PresetsManager::create_user_directory(const std::filesystem::path& path) { if (std::filesystem::is_directory(path)) { util::debug("user presets directory already exists: " + path.string()); return; } if (std::filesystem::create_directories(path)) { util::debug("user presets directory created: " + path.string()); return; } util::warning("failed to create user presets directory: " + path.string()); } auto PresetsManager::get_local_presets_name(const PresetType& preset_type) -> std::vector<std::string> { const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir : user_input_dir; auto it = std::filesystem::directory_iterator{conf_dir}; auto names = search_names(it); // Sort alphabetically not needed anymore because // the GtkSortListModel does it already. // std::sort(names.begin(), names.end()); // Removing duplicates not needed anymore because // we get the presets from a single folder. // names.erase(std::unique(names.begin(), names.end()), names.end()); return names; } auto PresetsManager::search_names(std::filesystem::directory_iterator& it) -> std::vector<std::string> { std::vector<std::string> names; try { while (it != std::filesystem::directory_iterator{}) { if (std::filesystem::is_regular_file(it->status()) && it->path().extension().c_str() == json_ext) { names.emplace_back(it->path().stem().c_str()); } ++it; } } catch (const std::exception& e) { util::warning(e.what()); } return names; } void PresetsManager::add(const PresetType& preset_type, const std::string& name) { // This method assumes the filename is valid. for (const auto& p : get_local_presets_name(preset_type)) { if (p == name) { return; } } save_preset_file(preset_type, name); } auto PresetsManager::get_all_community_presets_paths(const PresetType& preset_type) -> std::vector<std::string> { std::vector<std::string> cp_paths; const auto scan_level = 2U; const auto cp_dir_vect = (preset_type == PresetType::output) ? system_data_dir_output : system_data_dir_input; for (const auto& cp_dir : cp_dir_vect) { auto cp_fs_path = std::filesystem::path{cp_dir}; if (!std::filesystem::exists(cp_fs_path)) { continue; } // Scan community package directories for 2 levels (the folder itself and only its subfolders). auto it = std::filesystem::directory_iterator{cp_fs_path}; try { while (it != std::filesystem::directory_iterator{}) { if (auto package_path = it->path(); std::filesystem::is_directory(it->status())) { const auto package_path_name = package_path.string(); util::debug("scan directory for community presets: " + package_path_name); auto package_it = std::filesystem::directory_iterator{package_path}; /* When C++23 is available, the following line is enough: cp_paths.append_range( scan_community_package_recursive(package_it, scan_level, package_path_name)); */ const auto sub_cp_vect = scan_community_package_recursive(package_it, scan_level, package_path_name); cp_paths.insert(cp_paths.end(), sub_cp_vect.cbegin(), sub_cp_vect.cend()); } ++it; } } catch (const std::exception& e) { util::warning(e.what()); } } return cp_paths; } auto PresetsManager::scan_community_package_recursive(std::filesystem::directory_iterator& it, const uint& top_scan_level, const std::string& origin) -> std::vector<std::string> { const auto scan_level = top_scan_level - 1U; std::vector<std::string> cp_paths; try { while (it != std::filesystem::directory_iterator{}) { if (std::filesystem::is_regular_file(it->status()) && it->path().extension().c_str() == json_ext) { cp_paths.emplace_back(origin + "/" + it->path().stem().c_str()); } else if (scan_level > 0U && std::filesystem::is_directory(it->status())) { if (auto path = it->path(); !path.empty()) { auto subdir_it = std::filesystem::directory_iterator{path}; /* When C++23 is available, the following line is enough: cp_paths.append_range( scan_community_package_recursive(subdir_it, scan_level, origin + "/" + path.filename().c_str())); */ const auto sub_cp_vect = scan_community_package_recursive(subdir_it, scan_level, origin + "/" + path.filename().c_str()); cp_paths.insert(cp_paths.end(), sub_cp_vect.cbegin(), sub_cp_vect.cend()); } } ++it; } } catch (const std::exception& e) { util::warning(e.what()); } return cp_paths; } auto PresetsManager::get_community_preset_info(const PresetType& preset_type, const std::string& path) -> std::pair<std::string, std::string> { // Given the full path of a community preset, extract and return: // 1. the preset name // 2. the package name static const auto re_pack_name = std::regex(R"(^\/([^/]+))"); static const auto re_preset_name = std::regex(R"([^/]+$)"); const auto cp_dir_vect = (preset_type == PresetType::output) ? system_data_dir_output : system_data_dir_input; for (const auto& cp_dir : cp_dir_vect) { // In order to extract the package name, let's check if // the preset belongs to the selected system data directory. const auto cp_dir_size = cp_dir.size(); // Skip if the lenght of the path is shorter than `cp_dir + "/"`. if (path.size() <= cp_dir_size + 1U) { continue; } // Check if the preset is contained in the selected system data directory. // starts_with gets a string_view, so we use the version with character array. if (!path.starts_with(cp_dir.c_str())) { continue; } // Extract the package name. std::smatch pack_match; // Get the subdirectory/package. // - Full match: "/pack_name" // - Group 1: "pack_name" std::regex_search(path.cbegin() + cp_dir_size, path.cend(), pack_match, re_pack_name); // Skip if the match failed. if (pack_match.size() != 2U) { continue; } // Extract the preset name. std::smatch name_match; std::regex_search(path.cbegin() + cp_dir_size, path.cend(), name_match, re_preset_name); // Skip if the match failed. if (name_match.size() != 1U) { continue; } return std::make_pair(name_match.str(0), pack_match.str(1)); } util::warning("can't extract info strings for the community preset: " + path); // Placeholders in case of issues return std::make_pair(std::string(_("Community Preset")), std::string(_("Package"))); } void PresetsManager::save_blocklist(const PresetType& preset_type, nlohmann::json& json) { std::vector<std::string> blocklist; switch (preset_type) { case PresetType::output: { const auto list = util::gchar_array_to_vector(g_settings_get_strv(soe_settings, "blocklist")); for (const auto& l : list) { blocklist.push_back(l); } json["output"]["blocklist"] = blocklist; break; } case PresetType::input: { const auto list = util::gchar_array_to_vector(g_settings_get_strv(sie_settings, "blocklist")); for (const auto& l : list) { blocklist.push_back(l); } json["input"]["blocklist"] = blocklist; break; } } } auto PresetsManager::load_blocklist(const PresetType& preset_type, const nlohmann::json& json) -> bool { std::vector<std::string> blocklist; switch (preset_type) { case PresetType::input: { try { auto list = json.at("input").at("blocklist").get<std::vector<std::string>>(); g_settings_set_strv(sie_settings, "blocklist", util::make_gchar_pointer_vector(list).data()); } catch (const nlohmann::json::exception& e) { g_settings_reset(sie_settings, "blocklist"); notify_error(PresetError::blocklist_format); util::warning(e.what()); return false; } catch (...) { g_settings_reset(sie_settings, "blocklist"); notify_error(PresetError::blocklist_generic); return false; } break; } case PresetType::output: { try { auto list = json.at("output").at("blocklist").get<std::vector<std::string>>(); g_settings_set_strv(soe_settings, "blocklist", util::make_gchar_pointer_vector(list).data()); } catch (const nlohmann::json::exception& e) { g_settings_reset(soe_settings, "blocklist"); notify_error(PresetError::blocklist_format); util::warning(e.what()); return false; } catch (...) { g_settings_reset(soe_settings, "blocklist"); notify_error(PresetError::blocklist_generic); return false; } break; } } return true; } void PresetsManager::save_preset_file(const PresetType& preset_type, const std::string& name) { nlohmann::json json; std::filesystem::path output_file; save_blocklist(preset_type, json); switch (preset_type) { case PresetType::output: { const auto plugins = util::gchar_array_to_vector(g_settings_get_strv(soe_settings, "plugins")); std::vector<std::string> list; list.reserve(plugins.size()); for (const auto& p : plugins) { list.push_back(p); } json["output"]["plugins_order"] = list; write_plugins_preset(preset_type, plugins, json); output_file = user_output_dir / std::filesystem::path{name + json_ext}; break; } case PresetType::input: { const auto plugins = util::gchar_array_to_vector(g_settings_get_strv(sie_settings, "plugins")); std::vector<std::string> list; list.reserve(plugins.size()); for (const auto& p : plugins) { list.push_back(p); } json["input"]["plugins_order"] = list; write_plugins_preset(preset_type, plugins, json); output_file = user_input_dir / std::filesystem::path{name + json_ext}; break; } } std::ofstream o(output_file.c_str()); o << std::setw(4) << json << '\n'; // std::cout << std::setw(4) << json << std::endl; util::debug("saved preset: " + output_file.string()); } void PresetsManager::write_plugins_preset(const PresetType& preset_type, const std::vector<std::string>& plugins, nlohmann::json& json) { for (const auto& name : plugins) { if (auto wrapper = create_wrapper(preset_type, name); wrapper != std::nullopt) { if (wrapper.has_value()) { wrapper.value()->write(json); } } } } void PresetsManager::remove(const PresetType& preset_type, const std::string& name) { std::filesystem::path preset_file; const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir : user_input_dir; preset_file = conf_dir / std::filesystem::path{name + json_ext}; if (std::filesystem::exists(preset_file)) { std::filesystem::remove(preset_file); util::debug("removed preset: " + preset_file.string()); } } auto PresetsManager::load_local_preset_file(const PresetType& preset_type, const std::string& name) -> bool { const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir : user_input_dir; const auto input_file = conf_dir / std::filesystem::path{name + json_ext}; // Check preset existence if (!std::filesystem::exists(input_file)) { util::debug("can't find the local preset \"" + name + "\" on the filesystem"); return false; } set_last_preset_keys(preset_type, name); const auto loaded = load_preset_file(preset_type, input_file); if (!loaded) { set_last_preset_keys(preset_type); } return loaded; } auto PresetsManager::load_community_preset_file(const PresetType& preset_type, const std::string& full_path_stem, const std::string& package_name) -> bool { const auto input_file = std::filesystem::path{full_path_stem + json_ext}; // Check preset existence if (!std::filesystem::exists(input_file)) { util::warning("the community preset \"" + input_file.string() + "\" does not exist on the filesystem"); return false; } set_last_preset_keys(preset_type, input_file.stem().string(), package_name); const auto loaded = load_preset_file(preset_type, input_file); if (!loaded) { set_last_preset_keys(preset_type); } return loaded; } auto PresetsManager::load_preset_file(const PresetType& preset_type, const std::filesystem::path& input_file) -> bool { nlohmann::json json; std::vector<std::string> plugins; // Read effects_pipeline if (!read_effects_pipeline_from_preset(preset_type, input_file, json, plugins)) { return false; } // After the plugin order list, load the blocklist and then // apply the parameters of the loaded plugins. if (load_blocklist(preset_type, json) && read_plugins_preset(preset_type, plugins, json)) { util::debug("successfully loaded the preset: " + input_file.string()); return true; } return false; } auto PresetsManager::read_effects_pipeline_from_preset(const PresetType& preset_type, const std::filesystem::path& input_file, nlohmann::json& json, std::vector<std::string>& plugins) -> bool { const auto* preset_type_str = (preset_type == PresetType::input) ? "input" : "output"; GSettings* settings = (preset_type == PresetType::input) ? sie_settings : soe_settings; try { std::ifstream is(input_file); is >> json; for (const auto& p : json.at(preset_type_str).at("plugins_order").get<std::vector<std::string>>()) { for (const auto& v : tags::plugin_name::list) { if (p.starts_with(v)) { /* Old format presets do not have the instance id number in the filter names. They are equal to the base name. */ if (p != v) { plugins.push_back(p); } else { plugins.push_back(p + "#0"); } break; } } } } catch (const nlohmann::json::exception& e) { notify_error(PresetError::pipeline_format); util::warning(e.what()); return false; } catch (...) { notify_error(PresetError::pipeline_generic); return false; } g_settings_set_strv(settings, "plugins", util::make_gchar_pointer_vector(plugins).data()); return true; } auto PresetsManager::read_plugins_preset(const PresetType& preset_type, const std::vector<std::string>& plugins, const nlohmann::json& json) -> bool { for (const auto& name : plugins) { if (auto wrapper = create_wrapper(preset_type, name); wrapper != std::nullopt) { try { if (wrapper.has_value()) { wrapper.value()->read(json); } } catch (const nlohmann::json::exception& e) { notify_error(PresetError::plugin_format, name); util::warning(e.what()); return false; } catch (...) { notify_error(PresetError::plugin_generic, name); return false; } } } return true; } void PresetsManager::import_from_filesystem(const PresetType& preset_type, const std::string& file_path) { // When importing presets from the filesystem, we overwrite the file if it already exists. std::filesystem::path p{file_path}; if (!std::filesystem::is_regular_file(p)) { util::warning(p.string() + " is not a file!"); return; } if (p.extension().c_str() != json_ext) { return; } const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir : user_input_dir; const std::filesystem::path out_path = conf_dir / p.filename(); try { std::filesystem::copy_file(p, out_path, std::filesystem::copy_options::overwrite_existing); util::debug("imported preset to: " + out_path.string()); } catch (const std::exception& e) { util::warning("can't import preset to: " + out_path.string()); util::warning(e.what()); } } auto PresetsManager::import_addons_from_community_package(const PresetType& preset_type, const std::filesystem::path& path, const std::string& package) -> bool { /* Here we parse the json community preset in order to import the list of addons: * 1. Convolver Impulse Response Files * 2. RNNoise Models */ // This method assumes that the path is valid and package string is not empty, // their check has already been made in import_from_community_package(); std::ifstream is(path); nlohmann::json json; const auto irs_ext = ".irs"; const auto rnnn_ext = ".rnnn"; try { is >> json; std::vector<std::string> conv_irs, rn_models; const auto* pt_key = (preset_type == PresetType::output) ? "output" : "input"; // Fill conv_irs and rn_models vectors extracting the addon names from // the json preset and append the respective file extension. for (const auto& plugin : json.at(pt_key).at("plugins_order").get<std::vector<std::string>>()) { if (plugin.starts_with(tags::plugin_name::convolver)) { conv_irs.push_back(json.at(pt_key).at(plugin).at("kernel-name").get<std::string>() + irs_ext); } if (plugin.starts_with(tags::plugin_name::rnnoise)) { rn_models.push_back(json.at(pt_key).at(plugin).at("model-name").get<std::string>() + rnnn_ext); } } // For every filename of both vectors, search the full path and copy the file locally. for (const auto& irs_name : conv_irs) { std::string path; bool found = false; for (const auto& xdg_dir : system_data_dir_irs) { if (util::search_filename(std::filesystem::path{xdg_dir + "/" + package}, irs_name, path, 3U)) { const auto out_path = std::filesystem::path{user_irs_dir} / irs_name; std::filesystem::copy_file(path, out_path, std::filesystem::copy_options::overwrite_existing); util::debug("successfully imported community preset addon " + irs_name + " locally"); found = true; break; } } if (!found) { util::warning("community preset addon " + irs_name + " not found!"); return false; } } for (const auto& model_name : rn_models) { std::string path; bool found = false; for (const auto& xdg_dir : system_data_dir_rnnoise) { if (util::search_filename(std::filesystem::path{xdg_dir + "/" + package}, model_name, path, 3U)) { const auto out_path = std::filesystem::path{user_rnnoise_dir} / model_name; std::filesystem::copy_file(path, out_path, std::filesystem::copy_options::overwrite_existing); util::debug("successfully imported community preset addon " + model_name + " locally"); found = true; break; } } if (!found) { util::warning("community preset addon " + model_name + " not found!"); return false; } } return true; } catch (const std::exception& e) { util::warning(e.what()); return false; } } void PresetsManager::import_from_community_package(const PresetType& preset_type, const std::string& file_path, const std::string& package) { // When importing presets from a community package, we do NOT overwrite // the local preset if it has the same name. std::filesystem::path p{file_path}; if (!std::filesystem::exists(p) || package.empty()) { util::warning(p.string() + " does not exist! Please reload the community preset list"); return; } if (!std::filesystem::is_regular_file(p)) { util::warning(p.string() + " is not a file! Please reload the community preset list"); return; } if (p.extension().c_str() != json_ext) { return; } bool preset_can_be_copied = false; // We limit the max copy attempts in order to not flood the local directory // if the user keeps clicking the import button. uint i = 0U; static const auto max_copy_attempts = 10; const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir.string() : user_input_dir.string(); std::filesystem::path out_path; try { do { // In case of destination file already existing, we try to append // an incremental numeric suffix. const auto suffix = (i == 0U) ? "" : "-" + util::to_string(i); out_path = conf_dir + "/" + p.stem().c_str() + suffix + json_ext; if (!std::filesystem::exists(out_path)) { preset_can_be_copied = true; break; } } while (++i < max_copy_attempts); } catch (const std::exception& e) { util::warning("can't import the community preset: " + p.string()); util::warning(e.what()); return; } if (!preset_can_be_copied) { util::warning("can't import the community preset: " + p.string()); util::warning("exceeded the maximum copy attempts; please delete or rename your local preset"); return; } // Now we know that the preset is OK to be copied, but we first check for addons. if (!import_addons_from_community_package(preset_type, p, package)) { util::warning("can't import addons for the community preset: " + p.string() + "; import stage aborted, please reload the community preset list"); util::warning("if the issue goes on, contact the maintainer of the community package"); return; } std::filesystem::copy_file(p, out_path); util::debug("successfully imported the community preset to: " + out_path.string()); } void PresetsManager::add_autoload(const PresetType& preset_type, const std::string& preset_name, const std::string& device_name, const std::string& device_description, const std::string& device_profile) { nlohmann::json json; std::filesystem::path output_file; switch (preset_type) { case PresetType::output: output_file = autoload_output_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; case PresetType::input: output_file = autoload_input_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; } std::ofstream o(output_file.c_str()); json["device"] = device_name; json["device-description"] = device_description; json["device-profile"] = device_profile; json["preset-name"] = preset_name; o << std::setw(4) << json << '\n'; util::debug("added autoload preset file: " + output_file.string()); } void PresetsManager::remove_autoload(const PresetType& preset_type, const std::string& preset_name, const std::string& device_name, const std::string& device_profile) { std::filesystem::path input_file; switch (preset_type) { case PresetType::output: input_file = autoload_output_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; case PresetType::input: input_file = autoload_input_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; } if (!std::filesystem::is_regular_file(input_file)) { return; } nlohmann::json json; std::ifstream is(input_file); is >> json; if (preset_name == json.value("preset-name", "") && device_profile == json.value("device-profile", "")) { std::filesystem::remove(input_file); util::debug("removed autoload: " + input_file.string()); } } auto PresetsManager::find_autoload(const PresetType& preset_type, const std::string& device_name, const std::string& device_profile) -> std::string { std::filesystem::path input_file; switch (preset_type) { case PresetType::output: input_file = autoload_output_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; case PresetType::input: input_file = autoload_input_dir / std::filesystem::path{device_name + ":" + device_profile + json_ext}; break; } if (!std::filesystem::is_regular_file(input_file)) { return ""; } nlohmann::json json; std::ifstream is(input_file); is >> json; return json.value("preset-name", ""); } void PresetsManager::autoload(const PresetType& preset_type, const std::string& device_name, const std::string& device_profile) { const auto name = find_autoload(preset_type, device_name, device_profile); if (name.empty()) { return; } util::debug("autoloading local preset " + name + " for device " + device_name); load_local_preset_file(preset_type, name); } auto PresetsManager::get_autoload_profiles(const PresetType& preset_type) -> std::vector<nlohmann::json> { std::filesystem::path autoload_dir; std::vector<nlohmann::json> list; switch (preset_type) { case PresetType::output: autoload_dir = autoload_output_dir; break; case PresetType::input: autoload_dir = autoload_input_dir; break; } auto it = std::filesystem::directory_iterator{autoload_dir}; try { while (it != std::filesystem::directory_iterator{}) { if (std::filesystem::is_regular_file(it->status())) { if (it->path().extension().c_str() == json_ext) { nlohmann::json json; std::ifstream is(autoload_dir / it->path()); is >> json; list.push_back(json); } } ++it; } return list; } catch (const std::exception& e) { util::warning(e.what()); return list; } } void PresetsManager::set_last_preset_keys(const PresetType& preset_type, const std::string& preset_name, const std::string& package_name) { const auto* lp_key = (preset_type == PresetType::input) ? "last-loaded-input-preset" : "last-loaded-output-preset"; const auto* lcp_key = (preset_type == PresetType::input) ? "last-loaded-input-community-package" : "last-loaded-output-community-package"; // In order to avoid race conditions, the community package key should be set before the preset name. if (package_name.empty()) { g_settings_reset(settings, lcp_key); } else { g_settings_set_string(settings, lcp_key, package_name.c_str()); } if (preset_name.empty()) { g_settings_reset(settings, lp_key); } else { g_settings_set_string(settings, lp_key, preset_name.c_str()); } } auto PresetsManager::preset_file_exists(const PresetType& preset_type, const std::string& name) -> bool { const auto conf_dir = (preset_type == PresetType::output) ? user_output_dir : user_input_dir; const auto input_file = conf_dir / std::filesystem::path{name + json_ext}; return std::filesystem::exists(input_file); } void PresetsManager::notify_error(const PresetError& preset_error, const std::string& plugin_name) { std::string plugin_translated; try { const auto base_name = tags::plugin_name::get_base_name(plugin_name); plugin_translated = tags::plugin_name::get_translated().at(base_name) + ": "; } catch (std::out_of_range& e) { util::debug(e.what()); } switch (preset_error) { case PresetError::blocklist_format: { util::warning( "A parsing error occurred while trying to load the blocklist from the preset. The file could be invalid " "or corrupted. Please check its content."); preset_load_error.emit(_("Preset Not Loaded Correctly"), _("Wrong Format in Excluded Apps List")); break; } case PresetError::blocklist_generic: { util::warning("A generic error occurred while trying to load the blocklist from the preset."); preset_load_error.emit(_("Preset Not Loaded Correctly"), _("Generic Error While Loading Excluded Apps List")); break; } case PresetError::pipeline_format: { util::warning( "A parsing error occurred while trying to load the pipeline from the preset. The file could be invalid " "or corrupted. Please check its content."); preset_load_error.emit(_("Preset Not Loaded Correctly"), _("Wrong Format in Effects List")); break; } case PresetError::pipeline_generic: { util::warning("A generic error occurred while trying to load the pipeline from the preset."); preset_load_error.emit(_("Preset Not Loaded Correctly"), _("Generic Error While Loading Effects List")); break; } case PresetError::plugin_format: { util::warning("A parsing error occurred while trying to load the " + plugin_name + " plugin from the preset. The file could be invalid or " "corrupted. Please check its content."); preset_load_error.emit(_("Preset Not Loaded Correctly"), plugin_translated + _("One or More Parameters Have a Wrong Format")); break; } case PresetError::plugin_generic: { util::warning("A generic error occurred while trying to load the " + plugin_name + " plugin from the preset."); preset_load_error.emit(_("Preset Not Loaded Correctly"), plugin_translated + _("Generic Error While Loading The Effect")); break; } default: break; } } auto PresetsManager::create_wrapper(const PresetType& preset_type, std::string_view filter_name) -> std::optional<std::unique_ptr<PluginPresetBase>> { auto instance_id = tags::plugin_name::get_id(std::string(filter_name)); if (filter_name.starts_with(tags::plugin_name::autogain)) { return std::make_unique<AutoGainPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::bass_enhancer)) { return std::make_unique<BassEnhancerPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::bass_loudness)) { return std::make_unique<BassLoudnessPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::compressor)) { return std::make_unique<CompressorPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::convolver)) { return std::make_unique<ConvolverPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::crossfeed)) { return std::make_unique<CrossfeedPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::crystalizer)) { return std::make_unique<CrystalizerPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::deesser)) { return std::make_unique<DeesserPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::delay)) { return std::make_unique<DelayPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::deepfilternet)) { return std::make_unique<DeepFilterNetPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::echo_canceller)) { return std::make_unique<EchoCancellerPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::equalizer)) { return std::make_unique<EqualizerPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::exciter)) { return std::make_unique<ExciterPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::expander)) { return std::make_unique<ExpanderPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::filter)) { return std::make_unique<FilterPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::gate)) { return std::make_unique<GatePreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::level_meter)) { return std::make_unique<LevelMeterPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::limiter)) { return std::make_unique<LimiterPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::loudness)) { return std::make_unique<LoudnessPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::maximizer)) { return std::make_unique<MaximizerPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::multiband_compressor)) { return std::make_unique<MultibandCompressorPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::multiband_gate)) { return std::make_unique<MultibandGatePreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::pitch)) { return std::make_unique<PitchPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::reverb)) { return std::make_unique<ReverbPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::rnnoise)) { return std::make_unique<RNNoisePreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::speex)) { return std::make_unique<SpeexPreset>(preset_type, instance_id); } if (filter_name.starts_with(tags::plugin_name::stereo_tools)) { return std::make_unique<StereoToolsPreset>(preset_type, instance_id); } util::warning("The filter name " + std::string(filter_name) + " base name could not be recognized"); return std::nullopt; }
43,131
C++
.cpp
972
37.037037
119
0.639709
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,677
ui_helpers.cpp
wwmm_easyeffects/src/ui_helpers.cpp
/* * 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/>. */ #include "ui_helpers.hpp" #include <adwaita.h> #include <glib-object.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <fmt/format.h> #include <gio/gio.h> #include <glib.h> #include <glib/gi18n.h> #include <gtk/gtk.h> #include <gtk/gtkshortcut.h> #include <sys/types.h> #include <algorithm> #include <locale> #include <map> #include <sstream> #include <stdexcept> #include <string> #include "tags_app.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" namespace { uint widget_serial = 0U; std::locale user_locale; std::map<uint, bool> map_ignore_filter_idle_add; GSettings* global_app_settings = nullptr; } // namespace namespace ui { using namespace std::string_literals; void show_autohiding_toast(AdwToastOverlay* toast_overlay, const std::string& text, const uint& timeout, const AdwToastPriority& priority) { // Construct AdwToast auto* toast = adw_toast_new(text.c_str()); adw_toast_set_timeout(toast, timeout); adw_toast_set_priority(toast, priority); // Show AdwToast adw_toast_overlay_add_toast(toast_overlay, toast); } void show_fixed_toast(AdwToastOverlay* toast_overlay, const std::string& text, const AdwToastPriority& priority) { show_autohiding_toast(toast_overlay, text, 0U, priority); } auto missing_plugin_box(const std::string& base_name, const std::string& package) -> GtkWidget* { // Since the plugin name should be translated in the local language, // this function needs the base name as parameter, retrieved from // get_base_name() util. auto* box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); gtk_widget_set_margin_start(box, 6); gtk_widget_set_margin_end(box, 6); gtk_widget_set_margin_bottom(box, 6); gtk_widget_set_margin_top(box, 6); gtk_widget_set_valign(box, GTK_ALIGN_CENTER); auto* status_page = adw_status_page_new(); try { // For translators: {} is replaced by the effect name. const auto format_title = fmt::runtime(_("{} Not Available")); // For translators: the first {} is replaced by the effect name, the second {} is replaced by the package name. auto translated_descr = _("The software required for the {} effect, \"{}\", is not installed. Consider using the Easy Effects Flatpak " "package or installing the software yourself. If you've installed the missing software, you must restart " "Easy Effects using the 'Quit' option inside the menu in order to make the effect availble to use."); if (base_name == tags::plugin_name::rnnoise) { // For translators: the first {} is replaced by the effect name, the second {} is replaced by the package name. translated_descr = _("The {} effect was disabled when Easy Effects was compiled. This is perhaps since the " "software required for this effect, \"{}\", was not available. Consider using the Easy " "Effects Flatpak package or building your own Easy Effects package."); } const auto format_descr = fmt::runtime(translated_descr); const std::string translated_name = tags::plugin_name::get_translated().at(base_name); adw_status_page_set_title(ADW_STATUS_PAGE(status_page), fmt::format(format_title, translated_name).c_str()); adw_status_page_set_description(ADW_STATUS_PAGE(status_page), fmt::format(format_descr, translated_name, package).c_str()); } catch (std::out_of_range& e) { util::debug(e.what()); } adw_status_page_set_icon_name(ADW_STATUS_PAGE(status_page), "emblem-music-symbolic"); gtk_box_append(GTK_BOX(box), status_page); return box; } void show_simple_message_dialog(GtkWidget* parent, const std::string& title, const std::string& descr) { if (parent == nullptr) { return; } auto* dialog = adw_alert_dialog_new(title.c_str(), descr.c_str()); const std::string response_id = "close"; adw_alert_dialog_add_response(ADW_ALERT_DIALOG(dialog), response_id.c_str(), "Close (Press ESC)"); adw_alert_dialog_set_default_response(ADW_ALERT_DIALOG(dialog), response_id.c_str()); adw_dialog_present(dialog, parent); } auto parse_spinbutton_output(GtkSpinButton* button, const char* unit, const bool& lower_bound) -> gboolean { auto* adjustment = gtk_spin_button_get_adjustment(button); const auto value = gtk_adjustment_get_value(adjustment); const auto precision = gtk_spin_button_get_digits(button); const auto str_unit = (unit != nullptr) ? (" "s + unit) : ""; const bool minus_infinity = (!lower_bound && value <= util::minimum_db_d_level); auto text = (minus_infinity) ? (_("-inf") + str_unit) // format string: 0 = value, 1 = precision, 2 = unit : fmt::format(ui::get_user_locale(), "{0:.{1}Lf}{2}", value, precision, str_unit); gtk_editable_set_text(GTK_EDITABLE(button), text.c_str()); return TRUE; } auto parse_spinbutton_input(GtkSpinButton* button, gdouble* new_value, const bool& lower_bound) -> gint { auto min = 0.0; auto max = 0.0; gtk_spin_button_get_range(button, &min, &max); std::istringstream str(gtk_editable_get_text(GTK_EDITABLE(button))); if (!lower_bound) { auto s = str.str(); util::str_trim_start(s); if (s.starts_with(_("-inf"))) { *new_value = util::minimum_db_d_level; return TRUE; } } str.imbue(ui::get_user_locale()); auto v = 0.0; if (str >> v) { *new_value = std::clamp(v, min, max); return TRUE; } return GTK_INPUT_ERROR; } auto get_new_filter_serial() -> uint { widget_serial++; return widget_serial; } void set_ignore_filter_idle_add(const uint& serial, const bool& state) { map_ignore_filter_idle_add[serial] = state; } auto get_ignore_filter_idle_add(const uint& serial) -> bool { return map_ignore_filter_idle_add[serial]; } void save_user_locale() { try { user_locale = std::locale(""); } catch (...) { util::warning("We could not get the user locale in your system! Your locale configuration is broken!"); util::warning("Falling back to the C locale"); } } auto get_user_locale() -> std::locale { return user_locale; } void update_level(GtkLevelBar* w_left, GtkLabel* w_left_label, GtkLevelBar* w_right, GtkLabel* w_right_label, const float& left, const float& right) { if (!GTK_IS_LEVEL_BAR(w_left) || !GTK_IS_LABEL(w_left_label) || !GTK_IS_LEVEL_BAR(w_right) || !GTK_IS_LABEL(w_right_label)) { return; } if (left >= -99.0F) { // Level bar widget needs double value const auto linear_value = static_cast<double>(std::clamp(util::db_to_linear(left), 0.0F, 1.0F)); gtk_level_bar_set_value(w_left, linear_value); gtk_label_set_text(w_left_label, fmt::format("{0:.0f}", left).c_str()); } else { gtk_level_bar_set_value(w_left, 0.0); gtk_label_set_text(w_left_label, "-99"); } if (right >= -99.0F) { // Level bar widget needs double value const auto linear_value = static_cast<double>(std::clamp(util::db_to_linear(right), 0.0F, 1.0F)); gtk_level_bar_set_value(w_right, linear_value); gtk_label_set_text(w_right_label, fmt::format("{0:.0f}", right).c_str()); } else { gtk_level_bar_set_value(w_right, 0.0); gtk_label_set_text(w_right_label, "-99"); } } auto get_plugin_credit_translated(const std::string& plugin_package) -> std::string { try { // For translators: {} is replaced by the library used by the plugin. I.e. "Using Calf Studio". const auto format = fmt::runtime(_("Using {}")); return fmt::format(format, plugin_package); } catch (...) { return plugin_package; } } void append_to_string_list(GtkStringList* string_list, const std::string& name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(string_list)); n++) { if (gtk_string_list_get_string(string_list, n) == name) { return; } } gtk_string_list_append(string_list, name.c_str()); } void remove_from_string_list(GtkStringList* string_list, const std::string& name) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(string_list)); n++) { if (gtk_string_list_get_string(string_list, n) == name) { gtk_string_list_remove(string_list, n); return; } } } void init_global_app_settings() { global_app_settings = g_settings_new(tags::app::id); } void unref_global_app_settings() { g_object_unref(global_app_settings); } auto get_global_app_settings() -> GSettings* { return global_app_settings; } } // namespace ui
9,370
C++
.cpp
227
36.819383
119
0.675777
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,678
crystalizer.cpp
wwmm_easyeffects/src/crystalizer.cpp
/* * 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/>. */ #include "crystalizer.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <cstddef> #include <memory> #include <mutex> #include <span> #include <string> #include "fir_filter_bandpass.hpp" #include "fir_filter_base.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Crystalizer::Crystalizer(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::crystalizer, tags::plugin_package::ee, schema, schema_path, pipe_manager, pipe_type) { for (uint n = 0U; n < nbands; n++) { filters.at(n) = std::make_unique<FirFilterBandpass>(log_tag + name + " band" + util::to_string(n)); } std::ranges::fill(band_mute, false); std::ranges::fill(band_bypass, false); std::ranges::fill(band_intensity, 1.0F); std::ranges::fill(band_last_L, 0.0F); std::ranges::fill(band_last_R, 0.0F); frequencies[0] = 20.0F; frequencies[1] = 520.0F; frequencies[2] = 1020.0F; frequencies[3] = 2020.0F; frequencies[4] = 3020.0F; frequencies[5] = 4020.0F; frequencies[6] = 5020.0F; frequencies[7] = 6020.0F; frequencies[8] = 7020.0F; frequencies[9] = 8020.0F; frequencies[10] = 9020.0F; frequencies[11] = 10020.0F; frequencies[12] = 15020.0F; frequencies[13] = 20020.0F; for (uint n = 0U; n < nbands; n++) { bind_band(static_cast<int>(n)); } setup_input_output_gain(); } Crystalizer::~Crystalizer() { if (connected_to_pw) { disconnect_from_pw(); } data_mutex.lock(); filters_are_ready = false; data_mutex.unlock(); util::debug(log_tag + name + " destroyed"); } void Crystalizer::setup() { data_mutex.lock(); filters_are_ready = false; data_mutex.unlock(); /* As zita uses fftw we have to be careful when reinitializing it. The thread that creates the fftw plan has to be the same that destroys it. Otherwise segmentation faults can happen. As we do not want to do this initializing in the plugin realtime thread we send it to the main thread through g_idle_add().connect_once */ util::idle_add([&, this] { if (filters_are_ready) { return; } blocksize = n_samples; n_samples_is_power_of_2 = (n_samples & (n_samples - 1U)) == 0 && n_samples != 0U; if (!n_samples_is_power_of_2) { while ((blocksize & (blocksize - 1U)) != 0 && blocksize > 2U) { blocksize--; } } util::debug(log_tag + name + " blocksize: " + util::to_string(blocksize)); notify_latency = true; do_first_rotation = true; latency_n_frames = 1U; // the second derivative forces us to delay at least one sample deque_out_L.resize(0U); deque_out_R.resize(0U); data_L.resize(0U); data_R.resize(0U); for (uint n = 0U; n < nbands; n++) { band_data_L.at(n).resize(blocksize); band_data_R.at(n).resize(blocksize); band_second_derivative_L.at(n).resize(blocksize); band_second_derivative_R.at(n).resize(blocksize); } for (uint n = 0U; n < nbands; n++) { filters.at(n)->set_n_samples(blocksize); filters.at(n)->set_rate(rate); filters.at(n)->set_min_frequency(frequencies.at(n)); filters.at(n)->set_max_frequency(frequencies.at(n + 1U)); filters.at(n)->setup(); } data_mutex.lock(); filters_are_ready = true; data_mutex.unlock(); }); } void Crystalizer::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass || !filters_are_ready) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } if (n_samples_is_power_of_2 && blocksize == n_samples) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); enhance_peaks(left_out, right_out); } else { for (size_t j = 0U; j < left_in.size(); j++) { data_L.push_back(left_in[j]); data_R.push_back(right_in[j]); if (data_L.size() == blocksize) { enhance_peaks(data_L, data_R); for (const auto& v : data_L) { deque_out_L.push_back(v); } for (const auto& v : data_R) { deque_out_R.push_back(v); } data_L.resize(0U); data_R.resize(0U); } } // copying the processed samples to the output buffers if (deque_out_L.size() >= left_out.size()) { for (float& v : left_out) { v = deque_out_L.front(); deque_out_L.pop_front(); } for (float& v : right_out) { v = deque_out_R.front(); deque_out_R.pop_front(); } } else { uint offset = 2U * (left_out.size() - deque_out_L.size()); if (offset != latency_n_frames) { latency_n_frames = offset + 1U; // the second derivative forces us to delay at least one sample notify_latency = true; } for (uint n = 0U; !deque_out_L.empty() && n < left_out.size(); n++) { if (n < offset) { left_out[n] = 0.0F; right_out[n] = 0.0F; } else { left_out[n] = deque_out_L.front(); right_out[n] = deque_out_R.front(); deque_out_R.pop_front(); deque_out_L.pop_front(); } } } } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (notify_latency) { latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); notify_latency = false; } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } void Crystalizer::bind_band(const int& n) { const std::string bandn = "band" + util::to_string(n); band_intensity.at(n) = static_cast<float>(util::db_to_linear(g_settings_get_double(settings, ("intensity-" + bandn).c_str()))); band_mute.at(n) = g_settings_get_boolean(settings, ("mute-" + bandn).c_str()) != 0; band_bypass.at(n) = g_settings_get_boolean(settings, ("bypass-" + bandn).c_str()) != 0; using namespace std::string_literals; gconnections.push_back(g_signal_connect(settings, ("changed::"s + "intensity-"s + bandn).c_str(), G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto s_key = std::string(key); int index = 0; if (util::str_to_num(s_key.substr(s_key.find("-band") + 5U), index)) { auto* self = static_cast<Crystalizer*>(user_data); self->band_intensity.at(index) = g_settings_get_double(settings, key) != 0; } }), this)); gconnections.push_back(g_signal_connect(settings, ("changed::"s + "mute-"s + bandn).c_str(), G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto s_key = std::string(key); int index = 0; if (util::str_to_num(s_key.substr(s_key.find("-band") + 5U), index)) { auto* self = static_cast<Crystalizer*>(user_data); self->band_mute.at(index) = g_settings_get_boolean(settings, key) != 0; } }), this)); gconnections.push_back(g_signal_connect(settings, ("changed::"s + "bypass-"s + bandn).c_str(), G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto s_key = std::string(key); int index = 0; if (util::str_to_num(s_key.substr(s_key.find("-band") + 5U), index)) { auto* self = static_cast<Crystalizer*>(user_data); self->band_bypass.at(index) = g_settings_get_boolean(settings, key) != 0; } }), this)); } auto Crystalizer::get_latency_seconds() -> float { return this->latency_value; }
10,315
C++
.cpp
255
30.298039
119
0.543825
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,679
test_signals.cpp
wwmm_easyeffects/src/test_signals.cpp
/* * 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/>. */ #include "test_signals.hpp" #include <pipewire/filter.h> #include <pipewire/keys.h> #include <pipewire/port.h> #include <pipewire/properties.h> #include <spa/node/io.h> #include <spa/utils/hook.h> #include <sys/types.h> #include <chrono> #include <cmath> #include <numbers> #include <span> #include <thread> #include "pipe_manager.hpp" #include "tags_app.hpp" #include "util.hpp" namespace { constexpr auto pi_x_2 = 2.0F * std::numbers::pi_v<float>; void on_process(void* userdata, spa_io_position* position) { auto* d = static_cast<TestSignals::data*>(userdata); const auto n_samples = position->clock.duration; const auto rate = position->clock.rate.denom; if (n_samples == 0 || rate == 0) { return; } if (rate != d->ts->rate || n_samples != d->ts->n_samples) { d->ts->rate = rate; d->ts->n_samples = n_samples; d->ts->sine_phase = 0.0F; } // util::warning("processing: " + util::to_string(n_samples)); auto* out_left = static_cast<float*>(pw_filter_get_dsp_buffer(d->out_left, n_samples)); auto* out_right = static_cast<float*>(pw_filter_get_dsp_buffer(d->out_right, n_samples)); if (out_left == nullptr || out_right == nullptr) { return; } std::span left_out(out_left, n_samples); std::span right_out(out_right, n_samples); const auto phase_delta = pi_x_2 * d->ts->sine_frequency / static_cast<float>(rate); for (uint n = 0U; n < n_samples; n++) { float signal = 0.0F; left_out[n] = 0.0F; right_out[n] = 0.0F; switch (d->ts->signal_type) { case TestSignalType::sine_wave: { d->ts->sine_phase += phase_delta; if (d->ts->sine_phase >= pi_x_2) { d->ts->sine_phase -= pi_x_2; } signal = 0.5F * std::sin(d->ts->sine_phase); break; } case TestSignalType::gaussian: { signal = d->ts->white_noise(); break; } case TestSignalType::pink: { break; } } if (d->ts->create_left_channel) { left_out[n] = signal; } if (d->ts->create_right_channel) { right_out[n] = signal; } } } void on_filter_state_changed(void* userdata, pw_filter_state old, pw_filter_state state, const char* error) { auto* d = static_cast<TestSignals::data*>(userdata); d->ts->state = state; switch (state) { case PW_FILTER_STATE_ERROR: d->ts->can_get_node_id = false; break; case PW_FILTER_STATE_UNCONNECTED: d->ts->can_get_node_id = false; break; case PW_FILTER_STATE_CONNECTING: d->ts->can_get_node_id = false; break; case PW_FILTER_STATE_STREAMING: d->ts->can_get_node_id = true; break; case PW_FILTER_STATE_PAUSED: d->ts->can_get_node_id = true; break; default: break; } } const struct pw_filter_events filter_events = {.state_changed = on_filter_state_changed, .process = on_process}; } // namespace TestSignals::TestSignals(PipeManager* pipe_manager) : pm(pipe_manager), random_generator(rd()) { pf_data.ts = this; const auto* filter_name = "ee_test_signals"; pm->lock(); auto* props_filter = pw_properties_new(nullptr, nullptr); pw_properties_set(props_filter, PW_KEY_APP_ID, tags::app::id); pw_properties_set(props_filter, PW_KEY_NODE_NAME, filter_name); pw_properties_set(props_filter, PW_KEY_NODE_DESCRIPTION, "Easy Effects Filter"); pw_properties_set(props_filter, PW_KEY_NODE_DRIVER, "true"); pw_properties_set(props_filter, PW_KEY_MEDIA_TYPE, "Audio"); pw_properties_set(props_filter, PW_KEY_MEDIA_CATEGORY, "Source"); pw_properties_set(props_filter, PW_KEY_MEDIA_ROLE, "DSP"); // pw_properties_set(props_filter, PW_KEY_MEDIA_CLASS, tags::pipewire::media_class::output_stream); filter = pw_filter_new(pm->core, filter_name, props_filter); // left channel output auto* props_out_left = pw_properties_new(nullptr, nullptr); pw_properties_set(props_out_left, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_out_left, PW_KEY_PORT_NAME, "output_FL"); pw_properties_set(props_out_left, "audio.channel", "FL"); pf_data.out_left = static_cast<port*>(pw_filter_add_port(filter, PW_DIRECTION_OUTPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_out_left, nullptr, 0)); // right channel output auto* props_out_right = pw_properties_new(nullptr, nullptr); pw_properties_set(props_out_right, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_out_right, PW_KEY_PORT_NAME, "output_FR"); pw_properties_set(props_out_right, "audio.channel", "FR"); pf_data.out_right = static_cast<port*>(pw_filter_add_port( filter, PW_DIRECTION_OUTPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_out_right, nullptr, 0)); if (pw_filter_connect(filter, PW_FILTER_FLAG_RT_PROCESS, nullptr, 0) != 0) { using namespace std::string_literals; pm->unlock(); util::warning(filter_name + " cannot connect the filter to PipeWire!"s); return; } pw_filter_add_listener(filter, &listener, &filter_events, &pf_data); pm->sync_wait_unlock(); while (!can_get_node_id) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (state == PW_FILTER_STATE_ERROR) { using namespace std::string_literals; util::warning(filter_name + " is in an error"s); return; } } pm->lock(); node_id = pw_filter_get_node_id(filter); pm->sync_wait_unlock(); } TestSignals::~TestSignals() { util::debug("destroyed"); pm->lock(); spa_hook_remove(&listener); pw_filter_set_active(filter, false); pw_filter_disconnect(filter); pw_filter_destroy(filter); pm->sync_wait_unlock(); } void TestSignals::set_state(const bool& state) { sine_phase = 0.0F; if (state) { for (const auto& link : pm->link_nodes(node_id, pm->ee_sink_node.id, false, false)) { list_proxies.push_back(link); } } else { pm->destroy_links(list_proxies); list_proxies.clear(); } } void TestSignals::set_frequency(const float& value) { sine_frequency = value; sine_phase = 0.0F; } auto TestSignals::white_noise() -> float { const auto v = normal_distribution(random_generator); return (v > 1.0F) ? 1.0F : ((v < -1.0F) ? -1.0F : v); }
7,027
C++
.cpp
187
33.235294
120
0.667208
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,680
filter_ui.cpp
wwmm_easyeffects/src/filter_ui.cpp
/* * 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/>. */ #include "filter_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "filter.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::filter_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Filter> filter; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _FilterBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkDropDown *mode, *equalizer_mode, *type, *slope; GtkSpinButton *frequency, *width, *gain, *quality, *balance; GtkToggleButton* show_native_ui; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(FilterBox, filter_box, GTK_TYPE_BOX) void on_reset(FilterBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(FilterBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->filter->show_native_ui(); } else { self->data->filter->close_native_ui(); } } void setup(FilterBox* self, std::shared_ptr<Filter> filter, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->filter = filter; self->settings = g_settings_new_with_path(tags::schema::filter::id, schema_path.c_str()); filter->set_post_messages(true); self->data->connections.push_back(filter->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(filter->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->filter->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "frequency", gtk_spin_button_get_adjustment(self->frequency), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "width", gtk_spin_button_get_adjustment(self->width), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "gain", gtk_spin_button_get_adjustment(self->gain), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "quality", gtk_spin_button_get_adjustment(self->quality), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "balance", gtk_spin_button_get_adjustment(self->balance), "value", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "type", self->type); ui::gsettings_bind_enum_to_combo_widget(self->settings, "mode", self->mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "equal-mode", self->equalizer_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "slope", self->slope); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_FILTER_BOX(object); self->data->filter->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(filter_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_FILTER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(filter_box_parent_class)->finalize(object); } void filter_box_class_init(FilterBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::filter_ui); gtk_widget_class_bind_template_child(widget_class, FilterBox, input_gain); gtk_widget_class_bind_template_child(widget_class, FilterBox, output_gain); gtk_widget_class_bind_template_child(widget_class, FilterBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, FilterBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, FilterBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, FilterBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, FilterBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, FilterBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, FilterBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, FilterBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, FilterBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, FilterBox, type); gtk_widget_class_bind_template_child(widget_class, FilterBox, mode); gtk_widget_class_bind_template_child(widget_class, FilterBox, equalizer_mode); gtk_widget_class_bind_template_child(widget_class, FilterBox, slope); gtk_widget_class_bind_template_child(widget_class, FilterBox, frequency); gtk_widget_class_bind_template_child(widget_class, FilterBox, width); gtk_widget_class_bind_template_child(widget_class, FilterBox, gain); gtk_widget_class_bind_template_child(widget_class, FilterBox, quality); gtk_widget_class_bind_template_child(widget_class, FilterBox, balance); gtk_widget_class_bind_template_child(widget_class, FilterBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); } void filter_box_init(FilterBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"Hz">(self->frequency); prepare_spinbuttons<"dB">(self->gain); prepare_spinbuttons<"">(self->width, self->quality); prepare_spinbuttons<"%">(self->balance); } auto create() -> FilterBox* { return static_cast<FilterBox*>(g_object_new(EE_TYPE_FILTER_BOX, nullptr)); } } // namespace ui::filter_box
8,558
C++
.cpp
184
42.358696
120
0.71592
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,681
multiband_compressor.cpp
wwmm_easyeffects/src/multiband_compressor.cpp
/* * 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/>. */ #include "multiband_compressor.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include <utility> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" MultibandCompressor::MultibandCompressor(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::multiband_compressor, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_mb_compressor_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_mb_compressor_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<MultibandCompressor*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"mode", "compressor-mode">(settings); lv2_wrapper->bind_key_enum<"envb", "envelope-boost">(settings); lv2_wrapper->bind_key_bool<"ssplit", "stereo-split">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"g_dry", "dry", false>(settings); lv2_wrapper->bind_key_double_db<"g_wet", "wet", false>(settings); bind_bands(std::make_index_sequence<n_bands>()); setup_input_output_gain(); } MultibandCompressor::~MultibandCompressor() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void MultibandCompressor::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void MultibandCompressor::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); frequency_range_end_port_array.at(n) = lv2_wrapper->get_control_port_value("fre_" + nstr); envelope_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("elm_" + nstr + "l") + lv2_wrapper->get_control_port_value("elm_" + nstr + "r")); curve_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("clm_" + nstr + "l") + lv2_wrapper->get_control_port_value("clm_" + nstr + "r")); reduction_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("rlm_" + nstr + "l") + lv2_wrapper->get_control_port_value("rlm_" + nstr + "r")); } frequency_range.emit(frequency_range_end_port_array); envelope.emit(envelope_port_array); curve.emit(curve_port_array); reduction.emit(reduction_port_array); notify(); } } } void MultibandCompressor::update_sidechain_links(const std::string& key) { auto external_sidechain_enabled = false; for (uint n = 0U; !external_sidechain_enabled && n < n_bands; n++) { const auto nstr = util::to_string(n); external_sidechain_enabled = g_settings_get_boolean(settings, ("external-sidechain" + nstr).c_str()) != 0; } if (!external_sidechain_enabled) { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void MultibandCompressor::update_probe_links() { update_sidechain_links(""); } auto MultibandCompressor::get_latency_seconds() -> float { return latency_value; }
7,034
C++
.cpp
169
33.52071
110
0.6074
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,682
stream_output_effects.cpp
wwmm_easyeffects/src/stream_output_effects.cpp
/* * 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/>. */ #include "stream_output_effects.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <pipewire/link.h> #include <pipewire/node.h> #include <sigc++/functors/mem_fun.h> #include <spa/utils/defs.h> #include <algorithm> #include <chrono> #include <cstdlib> #include <ranges> #include <set> #include <string> #include <thread> #include <vector> #include "effects_base.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_pipewire.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" StreamOutputEffects::StreamOutputEffects(PipeManager* pipe_manager) : EffectsBase("soe: ", tags::schema::id_output, pipe_manager, PipelineType::output) { auto* PULSE_SINK = std::getenv("PULSE_SINK"); if (PULSE_SINK != nullptr && PULSE_SINK != tags::pipewire::ee_sink_name) { for (const auto& [serial, node] : pm->node_map) { if (node.name == PULSE_SINK) { pm->output_device = node; g_settings_set_string(settings, "output-device", pm->output_device.name.c_str()); break; } } } connections.push_back(pm->sink_added.connect([this](const NodeInfo node) { if (node.name == util::gsettings_get_string(settings, "output-device")) { pm->output_device = node; if (g_settings_get_boolean(global_settings, "bypass") != 0) { g_settings_set_boolean(global_settings, "bypass", 0); return; // filter connected through update_bypass_state } set_bypass(false); } })); connections.push_back(pm->sink_removed.connect([this](const NodeInfo node) { if (g_settings_get_boolean(settings, "use-default-output-device") == 0) { if (node.name == util::gsettings_get_string(settings, "output-device")) { pm->output_device.id = SPA_ID_INVALID; pm->output_device.serial = SPA_ID_INVALID; } } })); connections.push_back(pm->stream_output_added.connect(sigc::mem_fun(*this, &StreamOutputEffects::on_app_added))); connect_filters(); gconnections.push_back(g_signal_connect(settings, "changed::output-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<StreamOutputEffects*>(user_data); const auto name = util::gsettings_get_string(settings, key); if (name.empty()) { return; } for (const auto& [serial, node] : self->pm->node_map) { if (node.name == name) { self->pm->output_device = node; if (g_settings_get_boolean(self->global_settings, "bypass") != 0) { g_settings_set_boolean(self->global_settings, "bypass", 0); return; // filter connected through update_bypass_state } self->set_bypass(false); break; } } }), this)); gconnections.push_back(g_signal_connect(settings, "changed::plugins", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<StreamOutputEffects*>(user_data); if (g_settings_get_boolean(self->global_settings, "bypass") != 0) { g_settings_set_boolean(self->global_settings, "bypass", 0); return; // filter connected through update_bypass_state } self->set_bypass(false); }), this)); } StreamOutputEffects::~StreamOutputEffects() { disconnect_filters(); util::debug("destroyed"); } void StreamOutputEffects::on_app_added(const NodeInfo node_info) { const auto blocklist = util::gchar_array_to_vector(g_settings_get_strv(settings, "blocklist")); auto is_blocklisted = std::ranges::find(blocklist, node_info.application_id) != blocklist.end(); is_blocklisted = is_blocklisted || std::ranges::find(blocklist, node_info.name) != blocklist.end(); if (g_settings_get_boolean(global_settings, "process-all-outputs") != 0 && !is_blocklisted) { pm->connect_stream_output(node_info.id); } } auto StreamOutputEffects::apps_want_to_play() -> bool { return std::ranges::any_of(pm->list_links, [&](const auto& link) { return (link.input_node_id == pm->ee_sink_node.id) && (link.state == PW_LINK_STATE_ACTIVE); }); } void StreamOutputEffects::connect_filters(const bool& bypass) { const auto output_device_name = util::gsettings_get_string(settings, "output-device"); // checking if the output device exists if (output_device_name.empty()) { util::debug("No output device set. Aborting the link"); return; } bool dev_exists = false; for (const auto& [serial, node] : pm->node_map) { if (node.name == output_device_name) { dev_exists = true; pm->output_device = node; break; } } if (!dev_exists) { util::debug("The output device " + output_device_name + " is not available. Aborting the link"); return; } const auto list = (bypass) ? std::vector<std::string>() : util::gchar_array_to_vector(g_settings_get_strv(settings, "plugins")); uint prev_node_id = pm->ee_sink_node.id; uint next_node_id = 0U; // link plugins if (!list.empty()) { for (const auto& name : list) { if (!plugins.contains(name)) { continue; } if (!plugins[name]->connected_to_pw ? plugins[name]->connect_to_pw() : true) { next_node_id = plugins[name]->get_node_id(); const auto links = pm->link_nodes(prev_node_id, next_node_id); for (auto* link : links) { list_proxies.push_back(link); } if (links.size() == 2U) { prev_node_id = next_node_id; } else { util::warning(" link from node " + util::to_string(prev_node_id) + " to node " + util::to_string(next_node_id) + " failed"); } } } // checking if we have to link the echo_canceller probe to the output device for (const auto& name : list) { if (!plugins.contains(name)) { continue; } if (name.starts_with(tags::plugin_name::echo_canceller)) { if (plugins[name]->connected_to_pw) { for (const auto& link : pm->link_nodes(pm->output_device.id, plugins[name]->get_node_id(), true)) { list_proxies.push_back(link); } } } plugins[name]->update_probe_links(); } } // link spectrum and output level meter for (const auto& node_id : {spectrum->get_node_id(), output_level->get_node_id()}) { next_node_id = node_id; const auto links = pm->link_nodes(prev_node_id, next_node_id); for (auto* link : links) { list_proxies.push_back(link); } if (links.size() == 2U) { prev_node_id = next_node_id; } else { util::warning(" link from node " + util::to_string(prev_node_id) + " to node " + util::to_string(next_node_id) + " failed"); } } // waiting for the output device ports information to be available. int timeout = 0; while (pm->count_node_ports(pm->output_device.id) < 2) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); timeout++; if (timeout > 10000) { // 10 seconds util::warning("Information about the ports of the output device " + pm->output_device.name + " with id " + util::to_string(pm->output_device.id) + " are taking to long to be available. Aborting the link"); return; } } // link output device next_node_id = pm->output_device.id; const auto links = pm->link_nodes(prev_node_id, next_node_id); for (auto* link : links) { list_proxies.push_back(link); } if (links.size() < 2U) { util::warning(" link from node " + util::to_string(prev_node_id) + " to output device " + util::to_string(next_node_id) + " failed"); } } void StreamOutputEffects::disconnect_filters() { std::set<uint> link_id_list; const auto selected_plugins_list = (bypass) ? std::vector<std::string>() : util::gchar_array_to_vector(g_settings_get_strv(settings, "plugins")); for (const auto& plugin : plugins | std::views::values) { for (const auto& link : pm->list_links) { if (link.input_node_id == plugin->get_node_id() || link.output_node_id == plugin->get_node_id()) { link_id_list.insert(link.id); } } if (plugin->connected_to_pw) { if (std::ranges::find(selected_plugins_list, plugin->name) == selected_plugins_list.end()) { util::debug("disconnecting the " + plugin->name + " filter from PipeWire"); plugin->disconnect_from_pw(); } } } for (const auto& link : pm->list_links) { if (link.input_node_id == spectrum->get_node_id() || link.output_node_id == spectrum->get_node_id() || link.input_node_id == output_level->get_node_id() || link.output_node_id == output_level->get_node_id()) { link_id_list.insert(link.id); } } for (const auto& id : link_id_list) { pm->destroy_object(static_cast<int>(id)); } pm->destroy_links(list_proxies); list_proxies.clear(); // remove_unused_filters(); } void StreamOutputEffects::set_bypass(const bool& state) { bypass = state; disconnect_filters(); connect_filters(state); }
10,962
C++
.cpp
251
34.071713
118
0.58077
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,683
reverb_preset.cpp
wwmm_easyeffects/src/reverb_preset.cpp
/* * 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/>. */ #include "reverb_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" ReverbPreset::ReverbPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::reverb::id, tags::schema::reverb::input_path, tags::schema::reverb::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::reverb).append("#").append(util::to_string(index)); } void ReverbPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["room-size"] = util::gsettings_get_string(settings, "room-size"); json[section][instance_name]["decay-time"] = g_settings_get_double(settings, "decay-time"); json[section][instance_name]["hf-damp"] = g_settings_get_double(settings, "hf-damp"); json[section][instance_name]["diffusion"] = g_settings_get_double(settings, "diffusion"); json[section][instance_name]["amount"] = g_settings_get_double(settings, "amount"); json[section][instance_name]["dry"] = g_settings_get_double(settings, "dry"); json[section][instance_name]["predelay"] = g_settings_get_double(settings, "predelay"); json[section][instance_name]["bass-cut"] = g_settings_get_double(settings, "bass-cut"); json[section][instance_name]["treble-cut"] = g_settings_get_double(settings, "treble-cut"); } void ReverbPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<gchar*>(json.at(section).at(instance_name), settings, "room-size", "room-size"); update_key<double>(json.at(section).at(instance_name), settings, "decay-time", "decay-time"); update_key<double>(json.at(section).at(instance_name), settings, "hf-damp", "hf-damp"); update_key<double>(json.at(section).at(instance_name), settings, "diffusion", "diffusion"); update_key<double>(json.at(section).at(instance_name), settings, "amount", "amount"); update_key<double>(json.at(section).at(instance_name), settings, "dry", "dry"); update_key<double>(json.at(section).at(instance_name), settings, "predelay", "predelay"); update_key<double>(json.at(section).at(instance_name), settings, "bass-cut", "bass-cut"); update_key<double>(json.at(section).at(instance_name), settings, "treble-cut", "treble-cut"); }
3,720
C++
.cpp
63
55.047619
97
0.709997
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,684
convolver.cpp
wwmm_easyeffects/src/convolver.cpp
/* * 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/>. */ #include "convolver.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sched.h> #include <sys/types.h> #include <zita-convolver.h> #include <algorithm> #include <cmath> #include <cstddef> #include <memory> #include <mutex> #include <sndfile.hh> #include <span> #include <string> #include <vector> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "resampler.hpp" #include "tags_plugin_name.hpp" #include "tags_resources.hpp" #include "util.hpp" namespace { constexpr auto CONVPROC_SCHEDULER_PRIORITY = 0; constexpr auto CONVPROC_SCHEDULER_CLASS = SCHED_FIFO; } // namespace Convolver::Convolver(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::convolver, tags::plugin_package::zita, schema, schema_path, pipe_manager, pipe_type), do_autogain(g_settings_get_boolean(settings, "autogain") != 0), ir_width(g_settings_get_int(settings, "ir-width")) { // Initialize directories for local and community irs local_dir_irs = std::string{g_get_user_config_dir()} + "/easyeffects/irs"; // Flatpak specific path (.flatpak-info always present for apps running in the flatpak sandbox) if (std::filesystem::is_regular_file(tags::resources::flatpak_info_file)) { system_data_dir_irs.push_back("/app/extensions/Presets/irs"); } // Regular paths for (const gchar* const* xdg_data_dirs = g_get_system_data_dirs(); *xdg_data_dirs != nullptr;) { std::string dir = *xdg_data_dirs++; dir += dir.ends_with("/") ? "" : "/"; system_data_dir_irs.push_back(dir + "easyeffects/irs"); } gconnections.push_back(g_signal_connect(settings, "changed::ir-width", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Convolver*>(user_data); self->ir_width = g_settings_get_int(self->settings, key); std::scoped_lock<std::mutex> lock(self->data_mutex); if (self->kernel_is_initialized) { self->kernel_L = self->original_kernel_L; self->kernel_R = self->original_kernel_R; self->set_kernel_stereo_width(); self->apply_kernel_autogain(); } }), this)); gconnections.push_back(g_signal_connect(settings, "changed::kernel-name", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Convolver*>(user_data); self->prepare_kernel(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::autogain", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Convolver*>(user_data); self->do_autogain = g_settings_get_boolean(settings, key) != 0; self->prepare_kernel(); }), this)); setup_input_output_gain(); } Convolver::~Convolver() { if (connected_to_pw) { disconnect_from_pw(); } for (auto& t : mythreads) { t.join(); } mythreads.clear(); std::scoped_lock<std::mutex> lock(data_mutex); ready = false; if (conv != nullptr) { conv->stop_process(); conv->cleanup(); delete conv; } util::debug(log_tag + name + " destroyed"); } void Convolver::setup() { ready = false; /* As zita uses fftw we have to be careful when reinitializing it. The thread that creates the fftw plan has to be the same that destroys it. Otherwise segmentation faults can happen. As we do not want to do this initializing in the plugin realtime thread we send it to the main thread through g_idle_add().connect_once */ util::idle_add([&, this] { if (ready) { return; } blocksize = n_samples; n_samples_is_power_of_2 = (n_samples & (n_samples - 1U)) == 0U && n_samples != 0U; if (!n_samples_is_power_of_2) { while ((blocksize & (blocksize - 1)) != 0 && blocksize > 2) { blocksize--; } } data_L.resize(0U); data_R.resize(0U); deque_out_L.resize(0U); deque_out_R.resize(0U); notify_latency = true; latency_n_frames = 0U; read_kernel_file(); if (kernel_is_initialized) { kernel_L = original_kernel_L; kernel_R = original_kernel_R; set_kernel_stereo_width(); apply_kernel_autogain(); setup_zita(); } std::scoped_lock<std::mutex> lock(data_mutex); ready = kernel_is_initialized && zita_ready; }); } void Convolver::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass || !ready) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } if (n_samples_is_power_of_2) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); do_convolution(left_out, right_out); } else { for (size_t j = 0U; j < left_in.size(); j++) { data_L.push_back(left_in[j]); data_R.push_back(right_in[j]); if (data_L.size() == blocksize) { do_convolution(data_L, data_R); for (const auto& v : data_L) { deque_out_L.push_back(v); } for (const auto& v : data_R) { deque_out_R.push_back(v); } data_L.resize(0U); data_R.resize(0U); } } // copying the processed samples to the output buffers if (deque_out_L.size() >= left_out.size()) { for (float& v : left_out) { v = deque_out_L.front(); deque_out_L.pop_front(); } for (float& v : right_out) { v = deque_out_R.front(); deque_out_R.pop_front(); } } else { const uint offset = 2U * (left_out.size() - deque_out_L.size()); if (offset != latency_n_frames) { latency_n_frames = offset; notify_latency = true; } for (uint n = 0U; !deque_out_L.empty() && n < left_out.size(); n++) { if (n < offset) { left_out[n] = 0.0F; right_out[n] = 0.0F; } else { left_out[n] = deque_out_L.front(); right_out[n] = deque_out_R.front(); deque_out_R.pop_front(); deque_out_L.pop_front(); } } } } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (notify_latency) { latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this] { latency.emit(); }); update_filter_params(); notify_latency = false; } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto Convolver::search_irs_path(const std::string& name) -> std::string { // Given the irs name without extension, search the full path on the filesystem. const auto irs_filename = name + irs_ext; const auto* lcp_key = (pipeline_type == PipelineType::input) ? "last-loaded-input-community-package" : "last-loaded-output-community-package"; const auto community_package = util::gsettings_get_string(global_settings, lcp_key); std::string irs_full_path; if (community_package.empty()) { // Search local irs file. const auto local_irs_file = std::filesystem::path{local_dir_irs + "/" + irs_filename}; if (std::filesystem::exists(local_irs_file)) { irs_full_path = local_irs_file.c_str(); } } else { // Search irs file in community package paths. for (const auto& xdg_irs_dir : system_data_dir_irs) { if (util::search_filename(std::filesystem::path{xdg_irs_dir + "/" + community_package}, irs_filename, irs_full_path, 3U)) { break; } } } return irs_full_path; } void Convolver::read_kernel_file() { kernel_is_initialized = false; const auto name = util::gsettings_get_string(settings, "kernel-name"); if (name.empty()) { util::warning(log_tag + name + ": irs filename is null. Entering passthrough mode..."); return; } const auto path = search_irs_path(name); // If the search fails, the path is empty if (path.empty()) { util::warning(log_tag + name + ": irs filename does not exist. Entering passthrough mode..."); return; } util::debug("trying to load irs: " + path); // SndfileHandle might have issues with std::string, so we provide cstring SndfileHandle file = SndfileHandle(path.c_str()); if (file.channels() == 0 || file.frames() == 0) { util::warning(log_tag + name + ": irs file does not exists or it is empty: " + path); util::warning(log_tag + name + ": Entering passthrough mode..."); return; } util::debug(log_tag + name + ": irs file: " + path); util::debug(log_tag + name + ": irs rate: " + util::to_string(file.samplerate()) + " Hz"); util::debug(log_tag + name + ": irs channels: " + util::to_string(file.channels())); util::debug(log_tag + name + ": irs frames: " + util::to_string(file.frames())); // for now only stereo irs files are supported if (file.channels() != 2) { util::warning(log_tag + name + " Only stereo impulse responses are supported."); util::warning(log_tag + name + " The impulse file was not loaded!"); return; } std::vector<float> buffer(file.frames() * file.channels()); std::vector<float> buffer_L(file.frames()); std::vector<float> buffer_R(file.frames()); file.readf(buffer.data(), file.frames()); for (size_t n = 0U; n < buffer_L.size(); n++) { buffer_L[n] = buffer[2U * n]; buffer_R[n] = buffer[2U * n + 1U]; } if (file.samplerate() != static_cast<int>(rate)) { util::debug(log_tag + name + " resampling the kernel to " + util::to_string(rate)); auto resampler = std::make_unique<Resampler>(file.samplerate(), rate); original_kernel_L = resampler->process(buffer_L, true); resampler = std::make_unique<Resampler>(file.samplerate(), rate); original_kernel_R = resampler->process(buffer_R, true); } else { original_kernel_L = buffer_L; original_kernel_R = buffer_R; } kernel_is_initialized = true; util::debug(log_tag + name + ": kernel correctly initialized"); } void Convolver::apply_kernel_autogain() { if (!do_autogain) { return; } if (kernel_L.empty() || kernel_R.empty()) { return; } const float abs_peak_L = std::ranges::max(kernel_L, [](const auto& a, const auto& b) { return (std::fabs(a) < std::fabs(b)); }); const float abs_peak_R = std::ranges::max(kernel_R, [](const auto& a, const auto& b) { return (std::fabs(a) < std::fabs(b)); }); const float peak = (abs_peak_L > abs_peak_R) ? abs_peak_L : abs_peak_R; // normalize std::ranges::for_each(kernel_L, [&](auto& v) { v /= peak; }); std::ranges::for_each(kernel_R, [&](auto& v) { v /= peak; }); // find average power float power_L = 0.0F; float power_R = 0.0F; std::ranges::for_each(kernel_L, [&](const auto& v) { power_L += v * v; }); std::ranges::for_each(kernel_R, [&](const auto& v) { power_R += v * v; }); const float power = std::max(power_L, power_R); const float autogain = std::min(1.0F, 1.0F / std::sqrt(power)); util::debug(log_tag + "autogain factor: " + util::to_string(autogain)); std::ranges::for_each(kernel_L, [&](auto& v) { v *= autogain; }); std::ranges::for_each(kernel_R, [&](auto& v) { v *= autogain; }); } /* Mid-Side based Stereo width effect taken from https://github.com/tomszilagyi/ir.lv2/blob/automatable/ir.cc */ void Convolver::set_kernel_stereo_width() { const float w = static_cast<float>(ir_width) * 0.01F; const float x = (1.0F - w) / (1.0F + w); // M-S coeff.; L_out = L + x*R; R_out = R + x*L for (uint i = 0U; i < original_kernel_L.size(); i++) { const auto L = original_kernel_L[i]; const auto R = original_kernel_R[i]; kernel_L[i] = L + x * R; kernel_R[i] = R + x * L; } } void Convolver::setup_zita() { zita_ready = false; if (n_samples == 0U || !kernel_is_initialized) { return; } const uint max_convolution_size = kernel_L.size(); const uint buffer_size = get_zita_buffer_size(); if (conv != nullptr) { conv->stop_process(); conv->cleanup(); delete conv; } conv = new Convproc(); conv->set_options(0); int ret = conv->configure(2, 2, max_convolution_size, buffer_size, buffer_size, buffer_size, 0.0F /*density*/); if (ret != 0) { util::warning(log_tag + name + " can't initialise zita-convolver engine: " + util::to_string(ret, "")); return; } ret = conv->impdata_create(0, 0, 1, kernel_L.data(), 0, static_cast<int>(kernel_L.size())); if (ret != 0) { util::warning(log_tag + name + " left impdata_create failed: " + util::to_string(ret)); return; } ret = conv->impdata_create(1, 1, 1, kernel_R.data(), 0, static_cast<int>(kernel_R.size())); if (ret != 0) { util::warning(log_tag + name + " right impdata_create failed: " + util::to_string(ret, "")); return; } ret = conv->start_process(CONVPROC_SCHEDULER_PRIORITY, CONVPROC_SCHEDULER_CLASS); if (ret != 0) { util::warning(log_tag + name + " start_process failed: " + util::to_string(ret, "")); conv->stop_process(); conv->cleanup(); return; } zita_ready = true; util::debug(log_tag + name + ": zita is ready"); } auto Convolver::get_zita_buffer_size() -> uint { if (n_samples_is_power_of_2) { return n_samples; } return blocksize; } auto Convolver::get_latency_seconds() -> float { return this->latency_value; } void Convolver::prepare_kernel() { if (n_samples == 0U || rate == 0U) { return; } data_mutex.lock(); ready = false; data_mutex.unlock(); read_kernel_file(); if (kernel_is_initialized) { kernel_L = original_kernel_L; kernel_R = original_kernel_R; set_kernel_stereo_width(); apply_kernel_autogain(); setup_zita(); data_mutex.lock(); ready = kernel_is_initialized && zita_ready; data_mutex.unlock(); } }
16,227
C++
.cpp
413
31.881356
119
0.588247
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,685
chart.cpp
wwmm_easyeffects/src/chart.cpp
/* * 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/>. */ #include "chart.hpp" #include <cairo.h> #include <fmt/format.h> #include <gdk/gdk.h> #include <glib-object.h> #include <gobject/gobject.h> #include <graphene.h> #include <gsk/gsk.h> #include <gtk/gtk.h> #include <gtk/gtkshortcut.h> #include <pango/pango-font.h> #include <pango/pango-layout.h> #include <sys/types.h> #include <algorithm> #include <array> #include <cmath> #include <cstddef> #include <string> #include <vector> #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::chart { struct Data { public: ~Data() { util::debug("data struct destroyed"); } bool draw_bar_border, fill_bars, is_visible, rounded_corners, dynamic_y_scale = true; int x_axis_height, n_x_decimals, n_y_decimals; double mouse_y, mouse_x, margin, line_width; double x_min, x_max, y_min, y_max; double x_min_log, x_max_log; double global_min_y = 0.0, global_max_y = 0.0; ChartType chart_type; ChartScale chart_scale; GdkRGBA background_color, color, color_axis_labels, gradient_color; std::string x_unit, y_unit; std::vector<double> y_axis, x_axis, x_axis_log, objects_x; }; struct _Chart { GtkBox parent_instance; GtkEventController* controller_motion; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(Chart, chart, GTK_TYPE_WIDGET) void set_chart_type(Chart* self, const ChartType& value) { if (self->data == nullptr) { return; } self->data->chart_type = value; } void set_chart_scale(Chart* self, const ChartScale& value) { if (self->data == nullptr) { return; } self->data->chart_scale = value; } void set_background_color(Chart* self, GdkRGBA color) { if (self->data == nullptr) { return; } self->data->background_color = color; } void set_color(Chart* self, GdkRGBA color) { if (self->data == nullptr) { return; } self->data->color = color; } void set_axis_labels_color(Chart* self, GdkRGBA color) { if (self->data == nullptr) { return; } self->data->color_axis_labels = color; } void set_line_width(Chart* self, const float& value) { if (self->data == nullptr) { return; } self->data->line_width = value; } void set_draw_bar_border(Chart* self, const bool& v) { if (self->data == nullptr) { return; } self->data->draw_bar_border = v; } void set_rounded_corners(Chart* self, const bool& v) { if (self->data == nullptr) { return; } self->data->rounded_corners = v; } void set_fill_bars(Chart* self, const bool& v) { if (self->data == nullptr) { return; } self->data->fill_bars = v; } void set_n_x_decimals(Chart* self, const int& v) { if (self->data == nullptr) { return; } self->data->n_x_decimals = v; } void set_n_y_decimals(Chart* self, const int& v) { if (self->data == nullptr) { return; } self->data->n_y_decimals = v; } void set_x_unit(Chart* self, const std::string& value) { if (self->data == nullptr) { return; } self->data->x_unit = value; } void set_y_unit(Chart* self, const std::string& value) { if (self->data == nullptr) { return; } self->data->y_unit = value; } void set_margin(Chart* self, const float& v) { if (self->data == nullptr) { return; } self->data->margin = v; } auto get_is_visible(Chart* self) -> bool { if (!GTK_IS_WIDGET(self)) { return false; } if (self->data == nullptr) { return false; } return self->data->is_visible; } void set_dynamic_y_scale(Chart* self, const bool& v) { if (self->data == nullptr) { return; } self->data->dynamic_y_scale = v; self->data->global_min_y = 0.0; self->data->global_max_y = 0.0; } void set_x_data(Chart* self, const std::vector<double>& x) { if (!GTK_IS_WIDGET(self) || x.empty()) { return; } if (self->data == nullptr) { return; } self->data->x_axis = x; self->data->x_min = std::ranges::min(x); self->data->x_max = std::ranges::max(x); self->data->objects_x.resize(x.size()); self->data->x_min_log = std::log10(self->data->x_min); self->data->x_max_log = std::log10(self->data->x_max); self->data->x_axis_log.resize(x.size()); for (size_t n = 0U; n < self->data->x_axis_log.size(); n++) { self->data->x_axis_log[n] = std::log10(self->data->x_axis[n]); } // making each x value a number between 0 and 1 std::ranges::for_each(self->data->x_axis, [&](auto& v) { v = (v - self->data->x_min) / (self->data->x_max - self->data->x_min); }); std::ranges::for_each(self->data->x_axis_log, [&](auto& v) { v = (v - self->data->x_min_log) / (self->data->x_max_log - self->data->x_min_log); }); } void set_y_data(Chart* self, const std::vector<double>& y) { if (!GTK_IS_WIDGET(self) || y.empty()) { return; } self->data->y_axis = y; auto min_y = std::ranges::min(y); auto max_y = std::ranges::max(y); if (self->data->dynamic_y_scale) { self->data->y_min = min_y; self->data->y_max = max_y; } else { self->data->global_min_y = (min_y < self->data->global_min_y) ? min_y : self->data->global_min_y; self->data->global_max_y = (max_y > self->data->global_max_y) ? max_y : self->data->global_max_y; self->data->y_min = self->data->global_min_y; self->data->y_max = self->data->global_max_y; } if (std::fabs(self->data->y_max - self->data->y_min) < 0.00001) { std::ranges::fill(self->data->y_axis, 0.0); } else { // making each y value a number between 0 and 1 std::ranges::for_each(self->data->y_axis, [&](auto& v) { v = (v - self->data->y_min) / (self->data->y_max - self->data->y_min); }); } gtk_widget_queue_draw(GTK_WIDGET(self)); } void on_pointer_motion(GtkEventControllerMotion* controller, double xpos, double ypos, Chart* self) { // Static cast trying to fix codeql issue const auto x = xpos; const auto y = ypos; const auto width = static_cast<double>(gtk_widget_get_width(GTK_WIDGET(self))); const auto height = static_cast<double>(gtk_widget_get_height(GTK_WIDGET(self))); const auto usable_height = height - self->data->margin * height - self->data->x_axis_height; if (y < height - self->data->x_axis_height && y > self->data->margin * height && x > self->data->margin * width && x < width - self->data->margin * width) { // At least for now the y axis is always linear self->data->mouse_y = (usable_height - y) / usable_height * (self->data->y_max - self->data->y_min) + self->data->y_min; switch (self->data->chart_scale) { case ChartScale::logarithmic: { const double mouse_x_log = (x - self->data->margin * width) / (width - 2 * self->data->margin * width) * (self->data->x_max_log - self->data->x_min_log) + self->data->x_min_log; self->data->mouse_x = std::pow(10.0, mouse_x_log); // exp10 does not exist on FreeBSD break; } case ChartScale::linear: { self->data->mouse_x = (x - self->data->margin * width) / (width - 2 * self->data->margin * width) * (self->data->x_max - self->data->x_min) + self->data->x_min; break; } } gtk_widget_queue_draw(GTK_WIDGET(self)); } } auto draw_unit(Chart* self, GtkSnapshot* snapshot, const int& width, const int& height, const std::string& unit) { auto* layout = gtk_widget_create_pango_layout(GTK_WIDGET(self), unit.c_str()); auto* description = pango_font_description_from_string("monospace bold"); pango_layout_set_font_description(layout, description); pango_font_description_free(description); int text_width = 0; int text_height = 0; pango_layout_get_pixel_size(layout, &text_width, &text_height); gtk_snapshot_save(snapshot); auto point = GRAPHENE_POINT_INIT(static_cast<float>(width - text_width), static_cast<float>(height - text_height)); gtk_snapshot_translate(snapshot, &point); gtk_snapshot_append_layout(snapshot, layout, &self->data->color_axis_labels); gtk_snapshot_restore(snapshot); g_object_unref(layout); } auto draw_x_labels(Chart* self, GtkSnapshot* snapshot, const int& width, const int& height) -> int { double labels_offset = 0.1 * width; int n_x_labels = static_cast<int>(std::ceil((width - 2 * self->data->margin * width) / labels_offset)) + 1; if (n_x_labels < 2) { return 0; } /* Correcting the offset based on the final n_x_labels value */ labels_offset = (width - 2.0 * self->data->margin * width) / static_cast<float>(n_x_labels - 1); std::vector<double> labels; switch (self->data->chart_scale) { case ChartScale::logarithmic: { labels = util::logspace(self->data->x_min, self->data->x_max, n_x_labels); break; } case ChartScale::linear: { labels = util::linspace(self->data->x_min, self->data->x_max, n_x_labels); break; } } draw_unit(self, snapshot, width, height, " " + self->data->x_unit + " "); /* There is no space left in the window to show the last label. So we skip it. All labels are enclosed by whitespaces to not stick the first and the final at window borders. */ for (size_t n = 0U; n < labels.size() - 1U; n++) { const auto msg = fmt::format(ui::get_user_locale(), " {0:.{1}Lf} ", labels[n], self->data->n_x_decimals); auto* layout = gtk_widget_create_pango_layout(GTK_WIDGET(self), msg.c_str()); auto* description = pango_font_description_from_string("monospace bold"); pango_layout_set_font_description(layout, description); pango_font_description_free(description); int text_width = 0; int text_height = 0; pango_layout_get_pixel_size(layout, &text_width, &text_height); gtk_snapshot_save(snapshot); auto point = GRAPHENE_POINT_INIT(static_cast<float>(self->data->margin * width + n * labels_offset), static_cast<float>(height - text_height)); gtk_snapshot_translate(snapshot, &point); gtk_snapshot_append_layout(snapshot, layout, &self->data->color_axis_labels); gtk_snapshot_restore(snapshot); g_object_unref(layout); if (n == labels.size() - 2U) { return text_height; } } return 0; } void snapshot(GtkWidget* widget, GtkSnapshot* snapshot) { auto* self = EE_CHART(widget); switch (self->data->chart_scale) { case ChartScale::logarithmic: { if (self->data->y_axis.size() != self->data->x_axis_log.size()) { return; } break; } case ChartScale::linear: { if (self->data->y_axis.size() != self->data->x_axis.size()) { return; } break; } } auto width = gtk_widget_get_width(widget); auto height = gtk_widget_get_height(widget); auto widget_rectangle = GRAPHENE_RECT_INIT(0.0F, 0.0F, static_cast<float>(width), static_cast<float>(height)); gtk_snapshot_append_color(snapshot, &self->data->background_color, &widget_rectangle); if (const auto n_points = self->data->y_axis.size(); n_points > 0) { double usable_width = width - 2.0 * (self->data->line_width + self->data->margin * width); auto usable_height = (height - self->data->margin * height) - self->data->x_axis_height; switch (self->data->chart_scale) { case ChartScale::logarithmic: { for (size_t n = 0U; n < n_points; n++) { self->data->objects_x[n] = usable_width * self->data->x_axis_log[n] + self->data->line_width + self->data->margin * width; } break; } case ChartScale::linear: { for (size_t n = 0U; n < n_points; n++) { self->data->objects_x[n] = usable_width * self->data->x_axis[n] + self->data->line_width + self->data->margin * width; } break; } } self->data->x_axis_height = draw_x_labels(self, snapshot, width, height); auto border_color = std::to_array({self->data->color, self->data->color, self->data->color, self->data->color}); std::array<float, 4> border_width = { static_cast<float>(self->data->line_width), static_cast<float>(self->data->line_width), static_cast<float>(self->data->line_width), static_cast<float>(self->data->line_width)}; float radius = (self->data->rounded_corners) ? 5.0F : 0.0F; switch (self->data->chart_type) { case ChartType::bar: { double dw = width / static_cast<double>(n_points); for (uint n = 0U; n < n_points; n++) { double bar_height = usable_height * self->data->y_axis[n]; double rect_x = self->data->objects_x[n]; double rect_y = self->data->margin * height + usable_height - bar_height; double rect_height = bar_height; double rect_width = dw; if (self->data->draw_bar_border) { rect_width -= self->data->line_width; } auto bar_rectangle = GRAPHENE_RECT_INIT(static_cast<float>(rect_x), static_cast<float>(rect_y), static_cast<float>(rect_width), static_cast<float>(rect_height)); GskRoundedRect outline; gsk_rounded_rect_init_from_rect(&outline, &bar_rectangle, radius); if (self->data->fill_bars) { gtk_snapshot_push_rounded_clip(snapshot, &outline); gtk_snapshot_append_color(snapshot, &self->data->color, &outline.bounds); gtk_snapshot_pop(snapshot); } else { gtk_snapshot_append_border(snapshot, &outline, border_width.data(), border_color.data()); } } break; } case ChartType::dots: { double dw = width / static_cast<double>(n_points); usable_height -= radius; // this avoids the dots being drawn over the axis label for (uint n = 0U; n < n_points; n++) { double dot_y = usable_height * self->data->y_axis[n]; double rect_x = self->data->objects_x[n]; double rect_y = self->data->margin * height + radius + usable_height - dot_y; double rect_width = dw; if (self->data->draw_bar_border) { rect_width -= self->data->line_width; } auto rectangle = GRAPHENE_RECT_INIT(static_cast<float>(rect_x - radius), static_cast<float>(rect_y - radius), static_cast<float>(rect_width), static_cast<float>(rect_width)); GskRoundedRect outline; gsk_rounded_rect_init_from_rect(&outline, &rectangle, radius); if (self->data->fill_bars) { gtk_snapshot_push_rounded_clip(snapshot, &outline); gtk_snapshot_append_color(snapshot, &self->data->color, &outline.bounds); gtk_snapshot_pop(snapshot); } else { gtk_snapshot_append_border(snapshot, &outline, border_width.data(), border_color.data()); } } break; } case ChartType::line: { auto* ctx = gtk_snapshot_append_cairo(snapshot, &widget_rectangle); cairo_set_source_rgba(ctx, static_cast<double>(self->data->color.red), static_cast<double>(self->data->color.green), static_cast<double>(self->data->color.blue), static_cast<double>(self->data->color.alpha)); if (self->data->fill_bars) { cairo_move_to(ctx, self->data->margin * width, self->data->margin * height + usable_height); } else { const auto point_height = self->data->y_axis.front() * usable_height; cairo_move_to(ctx, self->data->objects_x.front(), self->data->margin * height + usable_height - point_height); } for (uint n = 0U; n < n_points - 1U; n++) { const auto next_point_height = self->data->y_axis[n + 1U] * usable_height; cairo_line_to(ctx, self->data->objects_x[n + 1U], self->data->margin * height + usable_height - next_point_height); } if (self->data->fill_bars) { cairo_line_to(ctx, self->data->objects_x.back(), self->data->margin * height + usable_height); cairo_move_to(ctx, self->data->objects_x.back(), self->data->margin * height + usable_height); cairo_close_path(ctx); } cairo_set_line_width(ctx, self->data->line_width); if (self->data->fill_bars) { cairo_fill(ctx); } else { cairo_stroke(ctx); } cairo_destroy(ctx); break; } } if (gtk_event_controller_motion_contains_pointer(GTK_EVENT_CONTROLLER_MOTION(self->controller_motion)) != 0) { // We leave a withespace at the end to not stick the string at the window border. const auto msg = fmt::format(ui::get_user_locale(), "x = {0:.{1}Lf} {2} y = {3:.{4}Lf} {5} ", self->data->mouse_x, self->data->n_x_decimals, self->data->x_unit, self->data->mouse_y, self->data->n_y_decimals, self->data->y_unit); auto* layout = gtk_widget_create_pango_layout(GTK_WIDGET(self), msg.c_str()); auto* description = pango_font_description_from_string("monospace bold"); pango_layout_set_font_description(layout, description); pango_font_description_free(description); int text_width = 0; int text_height = 0; pango_layout_get_pixel_size(layout, &text_width, &text_height); gtk_snapshot_save(snapshot); auto point = GRAPHENE_POINT_INIT(width - static_cast<float>(text_width), 0.0F); gtk_snapshot_translate(snapshot, &point); gtk_snapshot_append_layout(snapshot, layout, &self->data->color); gtk_snapshot_restore(snapshot); g_object_unref(layout); } } } void unroot(GtkWidget* widget) { auto* self = EE_CHART(widget); self->data->is_visible = false; GTK_WIDGET_CLASS(chart_parent_class)->unmap(widget); } void finalize(GObject* object) { auto* self = EE_CHART(object); delete self->data; self->data = nullptr; util::debug("finalized"); G_OBJECT_CLASS(chart_parent_class)->finalize(object); } void chart_class_init(ChartClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->finalize = finalize; widget_class->snapshot = snapshot; widget_class->unroot = unroot; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::chart_ui); } void chart_init(Chart* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->data->draw_bar_border = true; self->data->fill_bars = true; self->data->is_visible = true; self->data->x_axis_height = 0; self->data->n_x_decimals = 1; self->data->n_y_decimals = 1; self->data->line_width = 2.0; self->data->margin = 0.02; self->data->x_min = 0.0; self->data->y_min = 0.0; self->data->x_max = 1.0; self->data->y_max = 1.0; self->data->background_color = GdkRGBA{0.0F, 0.0F, 0.0F, 1.0F}; self->data->color = GdkRGBA{1.0F, 1.0F, 1.0F, 1.0F}; self->data->color_axis_labels = GdkRGBA{1.0F, 1.0F, 1.0F, 1.0F}; self->data->gradient_color = GdkRGBA{1.0F, 1.0F, 1.0F, 1.0F}; self->data->chart_type = ChartType::bar; self->data->chart_scale = ChartScale::logarithmic; self->controller_motion = gtk_event_controller_motion_new(); g_signal_connect(self->controller_motion, "motion", G_CALLBACK(on_pointer_motion), self); g_signal_connect(GTK_WIDGET(self), "hide", G_CALLBACK(+[](GtkWidget* widget, Chart* self) { self->data->is_visible = false; }), self); g_signal_connect(GTK_WIDGET(self), "show", G_CALLBACK(+[](GtkWidget* widget, Chart* self) { self->data->is_visible = true; }), self); gtk_widget_add_controller(GTK_WIDGET(self), self->controller_motion); } auto create() -> Chart* { return static_cast<Chart*>(g_object_new(EE_TYPE_CHART, nullptr)); } } // namespace ui::chart
20,673
C++
.cpp
508
34.793307
120
0.627242
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,686
crossfeed_ui.cpp
wwmm_easyeffects/src/crossfeed_ui.cpp
/* * 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/>. */ #include "crossfeed_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "crossfeed.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::crossfeed_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Crossfeed> crossfeed; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _CrossfeedBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *fcut, *feed; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(CrossfeedBox, crossfeed_box, GTK_TYPE_BOX) void on_reset(CrossfeedBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_preset_cmoy(CrossfeedBox* self, GtkButton* btn) { gtk_spin_button_set_value(self->fcut, 700.0); gtk_spin_button_set_value(self->feed, 6.0); } void on_preset_default(CrossfeedBox* self, GtkButton* btn) { gtk_spin_button_set_value(self->fcut, 700.0); gtk_spin_button_set_value(self->feed, 4.5); } void on_preset_jmeier(CrossfeedBox* self, GtkButton* btn) { gtk_spin_button_set_value(self->fcut, 650.0); gtk_spin_button_set_value(self->feed, 9.5); } void setup(CrossfeedBox* self, std::shared_ptr<Crossfeed> crossfeed, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->crossfeed = crossfeed; self->settings = g_settings_new_with_path(tags::schema::crossfeed::id, schema_path.c_str()); crossfeed->set_post_messages(true); self->data->connections.push_back(crossfeed->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(crossfeed->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->crossfeed->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "fcut", gtk_spin_button_get_adjustment(self->fcut), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "feed", gtk_spin_button_get_adjustment(self->feed), "value", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_CROSSFEED_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(crossfeed_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_CROSSFEED_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(crossfeed_box_parent_class)->finalize(object); } void crossfeed_box_class_init(CrossfeedBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::crossfeed_ui); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, input_gain); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, output_gain); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, fcut); gtk_widget_class_bind_template_child(widget_class, CrossfeedBox, feed); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_preset_cmoy); gtk_widget_class_bind_template_callback(widget_class, on_preset_default); gtk_widget_class_bind_template_callback(widget_class, on_preset_jmeier); } void crossfeed_box_init(CrossfeedBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"Hz">(self->fcut); prepare_spinbuttons<"dB">(self->feed); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> CrossfeedBox* { return static_cast<CrossfeedBox*>(g_object_new(EE_TYPE_CROSSFEED_BOX, nullptr)); } } // namespace ui::crossfeed_box
7,237
C++
.cpp
164
40.445122
120
0.724226
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,687
compressor.cpp
wwmm_easyeffects/src/compressor.cpp
/* * 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/>. */ #include "compressor.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Compressor::Compressor(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::compressor, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_compressor_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_compressor_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::sidechain-type", G_CALLBACK(+[](GSettings* settings, const char* key, gpointer user_data) { auto* self = static_cast<Compressor*>(user_data); self->update_sidechain_links(key); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, const char* key, gpointer user_data) { auto* self = static_cast<Compressor*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"cm", "mode">(settings); lv2_wrapper->bind_key_enum<"sct", "sidechain-type">(settings); lv2_wrapper->bind_key_enum<"scm", "sidechain-mode">(settings); lv2_wrapper->bind_key_enum<"scs", "sidechain-source">(settings); lv2_wrapper->bind_key_enum<"sscs", "stereo-split-source">(settings); lv2_wrapper->bind_key_enum<"shpm", "hpf-mode">(settings); lv2_wrapper->bind_key_enum<"slpm", "lpf-mode">(settings); lv2_wrapper->bind_key_bool<"ssplit", "stereo-split">(settings); lv2_wrapper->bind_key_bool<"scl", "sidechain-listen">(settings); lv2_wrapper->bind_key_double<"at", "attack">(settings); lv2_wrapper->bind_key_double<"rt", "release">(settings); lv2_wrapper->bind_key_double<"cr", "ratio">(settings); lv2_wrapper->bind_key_double<"scr", "sidechain-reactivity">(settings); lv2_wrapper->bind_key_double<"sla", "sidechain-lookahead">(settings); lv2_wrapper->bind_key_double<"shpf", "hpf-frequency">(settings); lv2_wrapper->bind_key_double<"slpf", "lpf-frequency">(settings); lv2_wrapper->bind_key_double_db<"bth", "boost-threshold">(settings); lv2_wrapper->bind_key_double_db<"bsa", "boost-amount">(settings); lv2_wrapper->bind_key_double_db<"al", "threshold">(settings); lv2_wrapper->bind_key_double_db<"kn", "knee">(settings); lv2_wrapper->bind_key_double_db<"mk", "makeup">(settings); lv2_wrapper->bind_key_double_db<"scp", "sidechain-preamp">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"rrl", "release-threshold", false>(settings); lv2_wrapper->bind_key_double_db<"cdr", "dry", false>(settings); lv2_wrapper->bind_key_double_db<"cwt", "wet", false>(settings); setup_input_output_gain(); } Compressor::~Compressor() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Compressor::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Compressor::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { reduction_port_value = 0.5F * (lv2_wrapper->get_control_port_value("rlm_l") + lv2_wrapper->get_control_port_value("rlm_r")); sidechain_port_value = 0.5F * (lv2_wrapper->get_control_port_value("slm_l") + lv2_wrapper->get_control_port_value("slm_r")); curve_port_value = 0.5F * (lv2_wrapper->get_control_port_value("clm_l") + lv2_wrapper->get_control_port_value("clm_r")); envelope_port_value = 0.5F * (lv2_wrapper->get_control_port_value("elm_l") + lv2_wrapper->get_control_port_value("elm_r")); reduction.emit(reduction_port_value); sidechain.emit(sidechain_port_value); curve.emit(curve_port_value); envelope.emit(envelope_port_value); notify(); } } } void Compressor::update_sidechain_links(const std::string& key) { if (util::gsettings_get_string(settings, "sidechain-type") != "External") { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void Compressor::update_probe_links() { update_sidechain_links(""); } auto Compressor::get_latency_seconds() -> float { return this->latency_value; }
8,027
C++
.cpp
186
35.586022
116
0.623938
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,688
exciter.cpp
wwmm_easyeffects/src/exciter.cpp
/* * 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/>. */ #include "exciter.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Exciter::Exciter(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::exciter, tags::plugin_package::calf, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://calf.sourceforge.net/plugins/Exciter"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://calf.sourceforge.net/plugins/Exciter is not installed"); } lv2_wrapper->bind_key_double_db<"amount", "amount">(settings); lv2_wrapper->bind_key_double<"drive", "harmonics">(settings); lv2_wrapper->bind_key_double<"freq", "scope">(settings); lv2_wrapper->bind_key_double<"ceil", "ceil">(settings); lv2_wrapper->bind_key_double<"blend", "blend">(settings); lv2_wrapper->bind_key_bool<"ceil_active", "ceil-active">(settings); lv2_wrapper->bind_key_bool<"listen", "listen">(settings); setup_input_output_gain(); } Exciter::~Exciter() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Exciter::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Exciter::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { /// harmonics needed as double for levelbar widget ui, so we convert it here harmonics_port_value = static_cast<double>(lv2_wrapper->get_control_port_value("meter_drive")); if (!post_messages) { return; } harmonics.emit(harmonics_port_value); notify(); } } } auto Exciter::get_latency_seconds() -> float { return 0.0F; }
3,694
C++
.cpp
102
30.901961
101
0.653101
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,689
multiband_gate.cpp
wwmm_easyeffects/src/multiband_gate.cpp
/* * 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/>. */ #include "multiband_gate.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <sys/types.h> #include <algorithm> #include <memory> #include <span> #include <string> #include <utility> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" MultibandGate::MultibandGate(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::multiband_gate, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type, true) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/sc_mb_gate_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_mb_gate_stereo is not installed"); } gconnections.push_back(g_signal_connect(settings, "changed::sidechain-input-device", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<MultibandGate*>(user_data); self->update_sidechain_links(key); }), this)); lv2_wrapper->bind_key_enum<"mode", "gate-mode">(settings); lv2_wrapper->bind_key_enum<"envb", "envelope-boost">(settings); lv2_wrapper->bind_key_bool<"ssplit", "stereo-split">(settings); // The following controls can assume -inf lv2_wrapper->bind_key_double_db<"g_dry", "dry", false>(settings); lv2_wrapper->bind_key_double_db<"g_wet", "wet", false>(settings); bind_bands(std::make_index_sequence<n_bands>()); setup_input_output_gain(); } MultibandGate::~MultibandGate() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void MultibandGate::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void MultibandGate::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) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out, probe_left, probe_right); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } /* This plugin gives the latency in number of samples */ const auto lv = static_cast<uint>(lv2_wrapper->get_control_port_value("out_latency")); if (latency_n_frames != lv) { latency_n_frames = lv; latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); frequency_range_end_port_array.at(n) = lv2_wrapper->get_control_port_value("fre_" + nstr); envelope_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("elm_" + nstr + "l") + lv2_wrapper->get_control_port_value("elm_" + nstr + "r")); curve_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("clm_" + nstr + "l") + lv2_wrapper->get_control_port_value("clm_" + nstr + "r")); reduction_port_array.at(n) = 0.5F * (lv2_wrapper->get_control_port_value("rlm_" + nstr + "l") + lv2_wrapper->get_control_port_value("rlm_" + nstr + "r")); } frequency_range.emit(frequency_range_end_port_array); envelope.emit(envelope_port_array); curve.emit(curve_port_array); reduction.emit(reduction_port_array); notify(); } } } void MultibandGate::update_sidechain_links(const std::string& key) { auto external_sidechain_enabled = false; for (uint n = 0U; !external_sidechain_enabled && n < n_bands; n++) { const auto nstr = util::to_string(n); external_sidechain_enabled = g_settings_get_boolean(settings, ("external-sidechain" + nstr).c_str()) != 0; } if (!external_sidechain_enabled) { pm->destroy_links(list_proxies); list_proxies.clear(); return; } const auto device_name = util::gsettings_get_string(settings, "sidechain-input-device"); NodeInfo input_device = pm->ee_source_node; for (const auto& [serial, node] : pm->node_map) { if (node.name == device_name) { input_device = node; break; } } pm->destroy_links(list_proxies); list_proxies.clear(); for (const auto& link : pm->link_nodes(input_device.id, get_node_id(), true)) { list_proxies.push_back(link); } } void MultibandGate::update_probe_links() { update_sidechain_links(""); } auto MultibandGate::get_latency_seconds() -> float { return 0.0F; }
6,857
C++
.cpp
169
32.934911
110
0.608683
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,690
multiband_compressor_ui.cpp
wwmm_easyeffects/src/multiband_compressor_ui.cpp
/* * 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/>. */ #include "multiband_compressor_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <gio/gliststore.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <gtk/gtksingleselection.h> #include <sigc++/connection.h> #include <array> #include <cstddef> #include <memory> #include <string> #include <vector> #include "multiband_compressor.hpp" #include "multiband_compressor_band_box.hpp" #include "node_info_holder.hpp" #include "pipe_manager.hpp" #include "pipe_objects.hpp" #include "tags_multiband_compressor.hpp" #include "tags_pipewire.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::multiband_compressor_box { using namespace std::string_literals; struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<MultibandCompressor> multiband_compressor; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _MultibandCompressorBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkStack* stack; GtkCheckButton *enable_band1, *enable_band2, *enable_band3, *enable_band4, *enable_band5, *enable_band6, *enable_band7; GtkSpinButton *dry, *wet; GtkDropDown *compressor_mode, *envelope_boost; GtkDropDown* dropdown_input_devices; GtkToggleButton *show_native_ui, *stereo_split; GListStore* input_devices_model; GSettings* settings; std::array<ui::multiband_compressor_band_box::MultibandCompressorBandBox*, tags::multiband_compressor::n_bands> bands; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(MultibandCompressorBox, multiband_compressor_box, GTK_TYPE_BOX) void on_reset(MultibandCompressorBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void on_show_native_window(MultibandCompressorBox* self, GtkToggleButton* btn) { if (gtk_toggle_button_get_active(btn) != 0) { self->data->multiband_compressor->show_native_ui(); } else { self->data->multiband_compressor->close_native_ui(); } } void on_listbox_row_selected(MultibandCompressorBox* self, GtkListBoxRow* row, GtkListBox* listbox) { if (auto* selected_row = gtk_list_box_get_selected_row(listbox); selected_row != nullptr) { if (auto index = gtk_list_box_row_get_index(selected_row); index != -1) { gtk_stack_set_visible_child_name(self->stack, ("band" + util::to_string(index)).c_str()); } } } void set_dropdown_input_devices_sensitivity(MultibandCompressorBox* self) { for (uint n = 0U; n < tags::multiband_compressor::n_bands; n++) { if (g_settings_get_boolean(self->settings, tags::multiband_compressor::band_external_sidechain[n].data()) != 0) { gtk_widget_set_sensitive(GTK_WIDGET(self->dropdown_input_devices), 1); return; } } gtk_widget_set_sensitive(GTK_WIDGET(self->dropdown_input_devices), 0); } void create_bands(MultibandCompressorBox* self) { for (uint n = 0U; n < tags::multiband_compressor::n_bands; n++) { auto* band_box = ui::multiband_compressor_band_box::create(); ui::multiband_compressor_band_box::setup(band_box, self->settings, n); gtk_stack_add_named(self->stack, GTK_WIDGET(band_box), ("band" + util::to_string(n)).c_str()); self->bands[n] = band_box; self->data->gconnections.push_back(g_signal_connect( self->settings, ("changed::"s + tags::multiband_compressor::band_external_sidechain[n].data()).c_str(), G_CALLBACK(+[](GSettings* settings, char* key, MultibandCompressorBox* self) { set_dropdown_input_devices_sensitivity(self); }), self)); } } void setup_dropdown_input_device(MultibandCompressorBox* self) { auto* selection = gtk_single_selection_new(G_LIST_MODEL(self->input_devices_model)); g_signal_connect(self->dropdown_input_devices, "notify::selected-item", G_CALLBACK(+[](GtkDropDown* dropdown, GParamSpec* pspec, MultibandCompressorBox* self) { if (auto selected_item = gtk_drop_down_get_selected_item(dropdown); selected_item != nullptr) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(selected_item); g_settings_set_string(self->settings, "sidechain-input-device", holder->info->name.c_str()); } }), self); gtk_drop_down_set_model(self->dropdown_input_devices, G_LIST_MODEL(self->input_devices_model)); g_object_unref(selection); } void setup(MultibandCompressorBox* self, std::shared_ptr<MultibandCompressor> multiband_compressor, const std::string& schema_path, PipeManager* pm) { self->data->multiband_compressor = multiband_compressor; auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->settings = g_settings_new_with_path(tags::schema::multiband_compressor::id, schema_path.c_str()); multiband_compressor->set_post_messages(true); setup_dropdown_input_device(self); set_dropdown_input_devices_sensitivity(self); create_bands(self); for (const auto& [serial, node] : pm->node_map) { if (node.name == tags::pipewire::ee_sink_name || node.name == tags::pipewire::ee_source_name) { continue; } if (node.media_class == tags::pipewire::media_class::source || node.media_class == tags::pipewire::media_class::virtual_source || node.media_role == tags::pipewire::media_role::dsp) { auto* holder = ui::holders::create(node); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); } } self->data->connections.push_back(multiband_compressor->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back( multiband_compressor->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(multiband_compressor->frequency_range.connect( [=](const std::array<float, tags::multiband_compressor::n_bands> values) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } for (size_t n = 0U; n < values.size(); n++) { ui::multiband_compressor_band_box::set_end_label(self->bands[n], values[n]); } }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back( multiband_compressor->envelope.connect([=](const std::array<float, tags::multiband_compressor::n_bands> values) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } for (size_t n = 0U; n < values.size(); n++) { ui::multiband_compressor_band_box::set_envelope_label(self->bands[n], values[n]); } }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back( multiband_compressor->curve.connect([=](const std::array<float, tags::multiband_compressor::n_bands> values) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } for (size_t n = 0U; n < values.size(); n++) { ui::multiband_compressor_band_box::set_curve_label(self->bands[n], values[n]); } }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back( multiband_compressor->reduction.connect([=](const std::array<float, tags::multiband_compressor::n_bands> values) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } for (size_t n = 0U; n < values.size(); n++) { ui::multiband_compressor_band_box::set_gain_label(self->bands[n], values[n]); } }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pm->source_added.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_object_unref(holder); return; } g_object_unref(holder); } auto* holder = ui::holders::create(info); g_list_store_append(self->input_devices_model, holder); g_object_unref(holder); })); self->data->connections.push_back(pm->source_removed.connect([=](const NodeInfo info) { for (guint n = 0U; n < g_list_model_get_n_items(G_LIST_MODEL(self->input_devices_model)); n++) { auto* holder = static_cast<ui::holders::NodeInfoHolder*>(g_list_model_get_item(G_LIST_MODEL(self->input_devices_model), n)); if (holder->info->id == info.id) { g_list_store_remove(self->input_devices_model, n); g_object_unref(holder); return; } g_object_unref(holder); } })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->multiband_compressor->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "dry", gtk_spin_button_get_adjustment(self->dry), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "wet", gtk_spin_button_get_adjustment(self->wet), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "stereo-split", self->stereo_split, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, "compressor-mode", self->compressor_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, "envelope-boost", self->envelope_boost); g_settings_bind(self->settings, "enable-band1", self->enable_band1, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band2", self->enable_band2, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band3", self->enable_band3, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band4", self->enable_band4, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band5", self->enable_band5, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band6", self->enable_band6, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "enable-band7", self->enable_band7, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(ui::get_global_app_settings(), "show-native-plugin-ui", self->show_native_ui, "visible", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_MULTIBAND_COMPRESSOR_BOX(object); self->data->multiband_compressor->close_native_ui(); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(multiband_compressor_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_MULTIBAND_COMPRESSOR_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(multiband_compressor_box_parent_class)->finalize(object); } void multiband_compressor_box_class_init(MultibandCompressorBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::multiband_compressor_ui); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, input_gain); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, output_gain); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, stack); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band1); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band2); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band3); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band4); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band5); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band6); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, enable_band7); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, dry); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, wet); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, stereo_split); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, compressor_mode); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, envelope_boost); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, dropdown_input_devices); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBox, show_native_ui); gtk_widget_class_bind_template_callback(widget_class, on_reset); gtk_widget_class_bind_template_callback(widget_class, on_show_native_window); gtk_widget_class_bind_template_callback(widget_class, on_listbox_row_selected); } void multiband_compressor_box_init(MultibandCompressorBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->input_devices_model = g_list_store_new(ui::holders::node_info_holder_get_type()); // The following spinbuttons can assume -inf prepare_spinbuttons<"dB", false>(self->dry, self->wet); prepare_scales<"dB">(self->input_gain, self->output_gain); } auto create() -> MultibandCompressorBox* { return static_cast<MultibandCompressorBox*>(g_object_new(EE_TYPE_MULTIBAND_COMPRESSOR_BOX, nullptr)); } } // namespace ui::multiband_compressor_box
17,462
C++
.cpp
350
43.8
120
0.687754
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,691
level_meter.cpp
wwmm_easyeffects/src/level_meter.cpp
/* * 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/>. */ #include "level_meter.hpp" #include <ebur128.h> #include <algorithm> #include <cstddef> #include <mutex> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" LevelMeter::LevelMeter(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::level_meter, tags::plugin_package::ebur128, schema, schema_path, pipe_manager, pipe_type) {} LevelMeter::~LevelMeter() { if (connected_to_pw) { disconnect_from_pw(); } for (auto& t : mythreads) { t.join(); } mythreads.clear(); std::scoped_lock<std::mutex> lock(data_mutex); if (ebur_state != nullptr) { ebur128_destroy(&ebur_state); } util::debug(log_tag + name + " destroyed"); } auto LevelMeter::init_ebur128() -> bool { if (n_samples == 0U || rate == 0U) { return false; } if (ebur_state != nullptr) { ebur128_destroy(&ebur_state); ebur_state = nullptr; } ebur_state = ebur128_init( 2U, rate, EBUR128_MODE_S | EBUR128_MODE_I | EBUR128_MODE_LRA | EBUR128_MODE_TRUE_PEAK | EBUR128_MODE_HISTOGRAM); ebur128_set_channel(ebur_state, 0U, EBUR128_LEFT); ebur128_set_channel(ebur_state, 1U, EBUR128_RIGHT); return ebur_state != nullptr; } void LevelMeter::setup() { if (2U * static_cast<size_t>(n_samples) != data.size()) { data.resize(static_cast<size_t>(n_samples) * 2U); } if (rate != old_rate) { data_mutex.lock(); ebur128_ready = false; data_mutex.unlock(); mythreads.emplace_back([this]() { // Using emplace_back here makes sense if (ebur128_ready) { return; } auto status = true; old_rate = rate; status = init_ebur128(); data_mutex.lock(); ebur128_ready = status; data_mutex.unlock(); }); } } void LevelMeter::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); if (bypass || !ebur128_ready) { return; } for (size_t n = 0U; n < n_samples; n++) { data[2U * n] = left_in[n]; data[2U * n + 1U] = right_in[n]; } ebur128_add_frames_float(ebur_state, data.data(), n_samples); if (EBUR128_SUCCESS != ebur128_loudness_momentary(ebur_state, &momentary)) { momentary = 0.0; } if (EBUR128_SUCCESS != ebur128_loudness_shortterm(ebur_state, &shortterm)) { shortterm = 0.0; } if (EBUR128_SUCCESS != ebur128_loudness_global(ebur_state, &global)) { global = 0.0; } if (EBUR128_SUCCESS != ebur128_relative_threshold(ebur_state, &relative)) { relative = 0.0; } if (EBUR128_SUCCESS != ebur128_loudness_range(ebur_state, &range)) { range = 0.0; } if (EBUR128_SUCCESS != ebur128_true_peak(ebur_state, 0U, &true_peak_L)) { true_peak_L = 0.0; } if (EBUR128_SUCCESS != ebur128_true_peak(ebur_state, 1U, &true_peak_R)) { true_peak_R = 0.0; } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { results.emit(momentary, shortterm, global, relative, range, true_peak_L, true_peak_R); notify(); } } } auto LevelMeter::get_latency_seconds() -> float { return 0.0F; } void LevelMeter::reset_history() { mythreads.emplace_back([this]() { // Using emplace_back here makes sense data_mutex.lock(); ebur128_ready = false; data_mutex.unlock(); auto status = init_ebur128(); data_mutex.lock(); ebur128_ready = status; data_mutex.unlock(); }); }
4,813
C++
.cpp
148
27.222973
118
0.633745
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,692
multiband_compressor_band_box.cpp
wwmm_easyeffects/src/multiband_compressor_band_box.cpp
/* * 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/>. */ #include "multiband_compressor_band_box.hpp" #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkdropdown.h> #include <vector> #include "tags_multiband_compressor.hpp" #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::multiband_compressor_band_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } int index; std::vector<gulong> gconnections; }; struct _MultibandCompressorBandBox { GtkBox parent_instance; GtkToggleButton *bypass, *mute, *solo, *external_sidechain; GtkLabel *end_label, *gain_label, *envelope_label, *curve_label; GtkSpinButton *split_frequency, *lowcut_filter_frequency, *highcut_filter_frequency, *attack_time, *attack_threshold, *release_time, *release_threshold, *ratio, *knee, *makeup, *sidechain_preamp, *sidechain_reactivity, *sidechain_lookahead, *boost_amount, *boost_threshold; GtkCheckButton *lowcut_filter, *highcut_filter; GtkDropDown *compression_mode, *sidechain_mode, *sidechain_source, *stereo_split_source; GtkBox* split_frequency_box; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(MultibandCompressorBandBox, multiband_compressor_band_box, GTK_TYPE_BOX) gboolean set_boost_threshold_sensitive(MultibandCompressorBandBox* self, const guint selected_id) { switch (selected_id) { case 0U: // Downward case 2U: // Boosting return 0; default: break; } return 1; } gboolean set_boost_amount_sensitive(MultibandCompressorBandBox* self, const guint selected_id) { switch (selected_id) { case 0U: // Downward case 1U: // Upward return 0; default: break; } return 1; } void set_end_label(MultibandCompressorBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->end_label)) { return; } gtk_label_set_text(self->end_label, fmt::format("{0:.0f}", value).c_str()); } void set_envelope_label(MultibandCompressorBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->envelope_label)) { return; } gtk_label_set_text(self->envelope_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void set_curve_label(MultibandCompressorBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->curve_label)) { return; } gtk_label_set_text(self->curve_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void set_gain_label(MultibandCompressorBandBox* self, const float& value) { if (!GTK_IS_WIDGET(self)) { return; } if (!GTK_IS_LABEL(self->gain_label)) { return; } gtk_label_set_text(self->gain_label, fmt::format("{0:.0f}", util::linear_to_db(value)).c_str()); } void setup(MultibandCompressorBandBox* self, GSettings* settings, int index) { self->data->index = index; self->settings = settings; using namespace tags::multiband_compressor; if (index > 0) { g_settings_bind(settings, band_split_frequency[index].data(), gtk_spin_button_get_adjustment(self->split_frequency), "value", G_SETTINGS_BIND_DEFAULT); } else { // removing split frequency from band 0 for (auto* child = gtk_widget_get_last_child(GTK_WIDGET(self->split_frequency_box)); child != nullptr; child = gtk_widget_get_last_child(GTK_WIDGET(self->split_frequency_box))) { gtk_box_remove(self->split_frequency_box, child); } auto* label = gtk_label_new("0 Hz"); gtk_widget_set_halign(GTK_WIDGET(label), GTK_ALIGN_CENTER); gtk_box_append(self->split_frequency_box, GTK_WIDGET(label)); } ui::gsettings_bind_enum_to_combo_widget(self->settings, band_compression_mode[index].data(), self->compression_mode); g_settings_bind(self->settings, band_compressor_enable[index].data(), self->bypass, "active", G_SETTINGS_BIND_INVERT_BOOLEAN); g_settings_bind(self->settings, band_mute[index].data(), self->mute, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_solo[index].data(), self->solo, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_lowcut_filter[index].data(), self->lowcut_filter, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_highcut_filter[index].data(), self->highcut_filter, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, band_external_sidechain[index].data(), self->external_sidechain, "active", G_SETTINGS_BIND_DEFAULT); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_sidechain_mode[index].data(), self->sidechain_mode); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_sidechain_source[index].data(), self->sidechain_source); ui::gsettings_bind_enum_to_combo_widget(self->settings, band_stereo_split_source[index].data(), self->stereo_split_source); g_settings_bind(settings, band_lowcut_filter_frequency[index].data(), gtk_spin_button_get_adjustment(self->lowcut_filter_frequency), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_highcut_filter_frequency[index].data(), gtk_spin_button_get_adjustment(self->highcut_filter_frequency), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_attack_time[index].data(), gtk_spin_button_get_adjustment(self->attack_time), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_attack_threshold[index].data(), gtk_spin_button_get_adjustment(self->attack_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_release_time[index].data(), gtk_spin_button_get_adjustment(self->release_time), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_release_threshold[index].data(), gtk_spin_button_get_adjustment(self->release_threshold), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_ratio[index].data(), gtk_spin_button_get_adjustment(self->ratio), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_knee[index].data(), gtk_spin_button_get_adjustment(self->knee), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_makeup[index].data(), gtk_spin_button_get_adjustment(self->makeup), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_preamp[index].data(), gtk_spin_button_get_adjustment(self->sidechain_preamp), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_reactivity[index].data(), gtk_spin_button_get_adjustment(self->sidechain_reactivity), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_sidechain_lookahead[index].data(), gtk_spin_button_get_adjustment(self->sidechain_lookahead), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_boost_amount[index].data(), gtk_spin_button_get_adjustment(self->boost_amount), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(settings, band_boost_threshold[index].data(), gtk_spin_button_get_adjustment(self->boost_threshold), "value", G_SETTINGS_BIND_DEFAULT); // bind source dropdowns sensitive property to split-stereo gsettings boolean g_settings_bind(self->settings, "stereo-split", self->sidechain_source, "sensitive", static_cast<GSettingsBindFlags>(G_SETTINGS_BIND_DEFAULT | G_SETTINGS_BIND_INVERT_BOOLEAN)); g_settings_bind(self->settings, "stereo-split", self->stereo_split_source, "sensitive", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_MULTIBAND_COMPRESSOR_BAND_BOX(object); for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->gconnections.clear(); util::debug("index: " + util::to_string(self->data->index) + " disposed"); G_OBJECT_CLASS(multiband_compressor_band_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_MULTIBAND_COMPRESSOR_BAND_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(multiband_compressor_band_box_parent_class)->finalize(object); } void multiband_compressor_band_box_class_init(MultibandCompressorBandBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::multiband_compressor_band_ui); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, bypass); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, mute); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, solo); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, external_sidechain); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, end_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, gain_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, envelope_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, curve_label); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, split_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, split_frequency_box); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, lowcut_filter); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, highcut_filter); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, lowcut_filter_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, highcut_filter_frequency); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, attack_time); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, attack_threshold); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, release_time); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, release_threshold); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, ratio); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, knee); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, makeup); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, sidechain_preamp); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, sidechain_reactivity); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, sidechain_lookahead); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, boost_amount); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, boost_threshold); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, compression_mode); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, sidechain_mode); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, sidechain_source); gtk_widget_class_bind_template_child(widget_class, MultibandCompressorBandBox, stereo_split_source); gtk_widget_class_bind_template_callback(widget_class, set_boost_amount_sensitive); gtk_widget_class_bind_template_callback(widget_class, set_boost_threshold_sensitive); } void multiband_compressor_band_box_init(MultibandCompressorBandBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_spinbuttons<"Hz">(self->lowcut_filter_frequency, self->highcut_filter_frequency, self->split_frequency); prepare_spinbuttons<"ms">(self->attack_time, self->release_time, self->sidechain_reactivity, self->sidechain_lookahead); prepare_spinbuttons<"dB">(self->attack_threshold, self->knee, self->makeup, self->sidechain_preamp, self->boost_amount, self->boost_threshold); prepare_spinbuttons<"">(self->ratio); // This spinbutton can assume -inf prepare_spinbuttons<"dB", false>(self->release_threshold); } auto create() -> MultibandCompressorBandBox* { return static_cast<MultibandCompressorBandBox*>(g_object_new(EE_TYPE_MULTIBAND_COMPRESSOR_BAND_BOX, nullptr)); } } // namespace ui::multiband_compressor_band_box
13,757
C++
.cpp
245
51.228571
120
0.737297
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,693
ladspa_wrapper.cpp
wwmm_easyeffects/src/ladspa_wrapper.cpp
/* * 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/>. */ #include "ladspa_wrapper.hpp" #include <dlfcn.h> #include <ladspa.h> #include <sys/types.h> #include <cassert> #include <cmath> #include <cstdlib> #include <cstring> #include <limits> #include <span> #include <string> #include <tuple> #include <utility> #include "config.h" #include "util.hpp" namespace ladspa { static inline const char* get_ladspa_path() { const char* path = std::getenv("LADSPA_PATH"); if (path == nullptr || path[0] == '\0') { path = "/usr/local/lib/ladspa/:" LIB_DIR "/ladspa/:/usr/lib/ladspa/"; } return path; } struct dlhandle { dlhandle(void* handle) : dl_handle(handle) {} ~dlhandle() { if (dl_handle != nullptr) { dlclose(dl_handle); } } dlhandle(const dlhandle&) = delete; auto operator=(const dlhandle&) -> dlhandle& = delete; dlhandle(dlhandle&& other) noexcept : dl_handle(std::exchange(other.dl_handle, nullptr)) {} auto operator=(dlhandle&& other) noexcept -> dlhandle& { std::swap(dl_handle, other.dl_handle); return *this; } void disable() { dl_handle = nullptr; } void* dl_handle; }; static inline bool validate_ports(const LADSPA_Descriptor* descriptor) { unsigned long count_input = 0UL; unsigned long count_output = 0UL; for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { if (LADSPA_IS_PORT_AUDIO(descriptor->PortDescriptors[i])) { return false; } } else if (LADSPA_IS_PORT_AUDIO(descriptor->PortDescriptors[i])) { if (LADSPA_IS_PORT_INPUT(descriptor->PortDescriptors[i])) { if (++count_input > 4UL) { return false; } } else if (LADSPA_IS_PORT_OUTPUT(descriptor->PortDescriptors[i])) { if (++count_output > 2UL) { return false; } } else { return false; } } } return true; } LadspaWrapper::LadspaWrapper(const std::string& plugin_filename, const std::string& plugin_label) : plugin_name(plugin_label) { const char* ladspa_path = get_ladspa_path(); const char* p = nullptr; do { p = std::strchr(ladspa_path, ':'); if (!p) { p = std::strchr(ladspa_path, '\0'); } std::string path(ladspa_path, p - ladspa_path); if (*p == ':') { p++; } if (path.empty() || path[path.length() - 1] != '/') { path.push_back('/'); } path.append(plugin_filename); void* dl_handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); if (dl_handle == nullptr) { continue; } dlhandle h(dl_handle); auto func = (LADSPA_Descriptor_Function)dlsym(dl_handle, "ladspa_descriptor"); if (func == nullptr) { continue; } unsigned long i = 0UL; const LADSPA_Descriptor* descriptor = nullptr; do { descriptor = func(i); if (descriptor == nullptr) { break; } if (std::strcmp(descriptor->Label, plugin_label.c_str()) == 0) { break; } } while (i++ < std::numeric_limits<unsigned long>::max()); if (descriptor != nullptr) { if (descriptor->instantiate != nullptr && descriptor->connect_port != nullptr && descriptor->run != nullptr && validate_ports(descriptor)) { unsigned long count = 0UL; for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { count++; } } auto* control_ports = new LADSPA_Data[count](); auto* control_ports_initialized = new bool[count](); h.disable(); this->dl_handle = dl_handle; this->descriptor = descriptor; this->found = true; this->control_ports = control_ports; this->control_ports_initialized = control_ports_initialized; for (unsigned long i = 0UL, j = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { map_cp_name_to_idx.insert(std::make_pair(descriptor->PortNames[i], j++)); } } } break; } } while (*(ladspa_path = p) != '\0'); } LadspaWrapper::~LadspaWrapper() { if (active) { deactivate(); } LADSPA_Handle instance = std::exchange(this->instance, nullptr); if (instance != nullptr && descriptor->cleanup != nullptr) { descriptor->cleanup(instance); } if (control_ports_initialized) { delete[] std::exchange(control_ports_initialized, nullptr); } if (control_ports) { delete[] std::exchange(control_ports, nullptr); } if (dl_handle != nullptr) { dlclose(std::exchange(dl_handle, nullptr)); } } struct ladspahandle { ladspahandle(LADSPA_Handle instance, void (*cleanup)(LADSPA_Handle)) : instance(instance), cleanup(cleanup) {} ~ladspahandle() { if (instance != nullptr) { cleanup(instance); } } ladspahandle(const ladspahandle&) = delete; auto operator=(const ladspahandle&) -> ladspahandle& = delete; ladspahandle(ladspahandle&& other) noexcept : instance(std::exchange(other.instance, nullptr)), cleanup(other.cleanup) {} auto operator=(ladspahandle&& other) noexcept -> ladspahandle& { std::swap(instance, other.instance); std::swap(cleanup, other.cleanup); return *this; } void disable() { instance = nullptr; } void* instance; void (*cleanup)(LADSPA_Handle); }; static inline void get_port_bounds(const LADSPA_Descriptor* descriptor, unsigned long port, uint rate, LADSPA_Data& min, LADSPA_Data& max) { min = -std::numeric_limits<LADSPA_Data>::infinity(); max = std::numeric_limits<LADSPA_Data>::infinity(); const LADSPA_PortRangeHint* hint = &descriptor->PortRangeHints[port]; if (LADSPA_IS_HINT_BOUNDED_BELOW(hint->HintDescriptor)) { min = hint->LowerBound; if (LADSPA_IS_HINT_SAMPLE_RATE(hint->HintDescriptor)) { min *= rate; } } if (LADSPA_IS_HINT_BOUNDED_ABOVE(hint->HintDescriptor)) { max = hint->UpperBound; if (LADSPA_IS_HINT_SAMPLE_RATE(hint->HintDescriptor)) { min *= rate; } } if (LADSPA_IS_HINT_TOGGLED(hint->HintDescriptor)) { min = 0.0F; max = 1.0F; } } static inline LADSPA_Data get_port_default_raw(const LADSPA_Descriptor* descriptor, unsigned long port, uint rate) { const LADSPA_PortRangeHint* hint = &descriptor->PortRangeHints[port]; if (LADSPA_IS_HINT_HAS_DEFAULT(hint->HintDescriptor)) { if (LADSPA_IS_HINT_DEFAULT_0(hint->HintDescriptor)) { return 0.0F; } else if (LADSPA_IS_HINT_DEFAULT_1(hint->HintDescriptor)) { return 1.0F; } else if (LADSPA_IS_HINT_DEFAULT_100(hint->HintDescriptor)) { return 100.0F; } else if (LADSPA_IS_HINT_DEFAULT_440(hint->HintDescriptor)) { return 440.0F; } else { LADSPA_Data min = 0.0F; LADSPA_Data max = 0.0F; get_port_bounds(descriptor, port, rate, min, max); if (LADSPA_IS_HINT_DEFAULT_MINIMUM(hint->HintDescriptor)) { return min; } else if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(hint->HintDescriptor)) { return max; } else if (LADSPA_IS_HINT_LOGARITHMIC(hint->HintDescriptor)) { if (LADSPA_IS_HINT_DEFAULT_LOW(hint->HintDescriptor)) { return std::exp(std::log(min) * 0.75 + std::log(max) * 0.25); } else if (LADSPA_IS_HINT_DEFAULT_MIDDLE(hint->HintDescriptor)) { return std::exp(std::log(min) * 0.5 + std::log(max) * 0.5); } else if (LADSPA_IS_HINT_DEFAULT_HIGH(hint->HintDescriptor)) { return std::exp(std::log(min) * 0.25 + std::log(max) * 0.75); } } else { if (LADSPA_IS_HINT_DEFAULT_LOW(hint->HintDescriptor)) { return min * 0.75F + max * 0.25F; } else if (LADSPA_IS_HINT_DEFAULT_MIDDLE(hint->HintDescriptor)) { return min * 0.5F + max * 0.5F; } else if (LADSPA_IS_HINT_DEFAULT_HIGH(hint->HintDescriptor)) { return min * 0.25F + max * 0.75F; } } } } return 0.0F; } static inline LADSPA_Data clamp_port_value(const LADSPA_Descriptor* descriptor, unsigned long port, uint rate, LADSPA_Data val) { LADSPA_Data min = 0.0F; LADSPA_Data max = 0.0F; get_port_bounds(descriptor, port, rate, min, max); if (val < min) { val = min; } if (val > max) { val = max; } return val; } static inline LADSPA_Data get_port_default(const LADSPA_Descriptor* descriptor, unsigned long port, uint rate) { LADSPA_Data val = get_port_default_raw(descriptor, port, rate); return clamp_port_value(descriptor, port, rate, val); } static inline void scale_control_ports(const LADSPA_Descriptor* descriptor, LADSPA_Data* control_ports, bool* control_ports_initialized, uint old_rate, uint rate) { for (unsigned long i = 0UL, j = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { if (!control_ports_initialized[j]) { control_ports[j] = get_port_default(descriptor, i, rate); control_ports_initialized[j] = true; } else if (old_rate != 0U) { const LADSPA_PortRangeHint* hint = &descriptor->PortRangeHints[i]; if (LADSPA_IS_HINT_SAMPLE_RATE(hint->HintDescriptor)) { LADSPA_Data val = control_ports[j] * rate / old_rate; control_ports[j] = clamp_port_value(descriptor, i, rate, val); } } j++; } } } auto LadspaWrapper::create_instance(uint rate) -> bool { LADSPA_Handle new_instance = descriptor->instantiate(descriptor, rate); if (new_instance == nullptr) { return false; } ladspahandle h(new_instance, descriptor->cleanup); scale_control_ports(descriptor, control_ports, control_ports_initialized, this->rate, rate); for (unsigned long i = 0UL, j = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { descriptor->connect_port(new_instance, i, &control_ports[j++]); } } if (active) { deactivate(); } if (instance != nullptr && descriptor->cleanup != nullptr) { descriptor->cleanup(instance); } h.disable(); this->instance = new_instance; this->rate = rate; activate(); return true; } static inline int stricmp(const char* str1, const char* str2) { char c1 = 0; char c2 = 0; do { c1 = *str1; c2 = *str2; if (c1 != c2) { if (c1 >= 'A' && c1 <= 'Z') { c1 -= 'A'; } if (c2 >= 'A' && c2 <= 'Z') { c2 -= 'A'; } if (c1 != c2) { break; } } } while (c1 != '\0'); return (int)c1 - c2; } template <std::size_t N> static inline bool striendswith(const char* str, const char (&end)[N]) { std::size_t len = std::strlen(str); return len < (N - 1) && stricmp(&str[len - (N - 1)], end) == 0; } void LadspaWrapper::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) { if (instance == nullptr) { return; } unsigned long left_in_idx = -1L; unsigned long right_in_idx = -1L; unsigned long first_in_idx = -1L; unsigned long second_in_idx = -1L; unsigned long left_out_idx = -1L; unsigned long right_out_idx = -1L; unsigned long first_out_idx = -1L; unsigned long second_out_idx = -1L; int count_input = 0; int count_output = 0; for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_AUDIO(descriptor->PortDescriptors[i])) { if (LADSPA_IS_PORT_INPUT(descriptor->PortDescriptors[i])) { if (striendswith(descriptor->PortNames[i], " L") || striendswith(descriptor->PortNames[i], " (L)")) { left_in_idx = i; } else if (striendswith(descriptor->PortNames[i], " R") || striendswith(descriptor->PortNames[i], " (R)")) { right_in_idx = i; } if (count_input == 0) { first_in_idx = i; } else if (count_input == 1) { second_in_idx = i; } count_input++; } else if (LADSPA_IS_PORT_OUTPUT(descriptor->PortDescriptors[i])) { if (striendswith(descriptor->PortNames[i], " L") || striendswith(descriptor->PortNames[i], " (L)")) { left_out_idx = i; } else if (striendswith(descriptor->PortNames[i], " R") || striendswith(descriptor->PortNames[i], " (R)")) { right_out_idx = i; } if (count_output == 0) { first_out_idx = i; } else if (count_output == 1) { second_out_idx = i; } count_output++; } } } if (left_in_idx == null_ul || right_in_idx == null_ul) { left_in_idx = first_in_idx; right_in_idx = second_in_idx; } if (left_in_idx != null_ul) { descriptor->connect_port(instance, left_in_idx, const_cast<LADSPA_Data*>(left_in.data())); } if (right_in_idx != null_ul) { descriptor->connect_port(instance, right_in_idx, const_cast<LADSPA_Data*>(right_in.data())); } if (left_out_idx == null_ul || right_out_idx == null_ul) { left_out_idx = first_out_idx; right_out_idx = second_out_idx; } if (left_out_idx != null_ul) { descriptor->connect_port(instance, left_out_idx, left_out.data()); } if (right_out_idx != null_ul) { descriptor->connect_port(instance, right_out_idx, right_out.data()); } } static inline char* stristr(const char* haystack, const char* needle) { size_t hlen = std::strlen(haystack); size_t nlen = std::strlen(needle); while (nlen <= hlen) { if (stricmp(haystack, needle) == 0) { return (char*)haystack; } haystack++; hlen--; } return nullptr; } void LadspaWrapper::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) { if (instance == nullptr) { return; } unsigned long left_in_idx = -1L; unsigned long right_in_idx = -1L; unsigned long first_in_idx = -1L; unsigned long second_in_idx = -1L; unsigned long probe_left_idx = -1L; unsigned long probe_right_idx = -1L; unsigned long third_in_idx = -1L; unsigned long fourth_in_idx = -1L; unsigned long left_out_idx = -1L; unsigned long right_out_idx = -1L; unsigned long first_out_idx = -1L; unsigned long second_out_idx = -1L; int count_input = 0; int count_output = 0; for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_AUDIO(descriptor->PortDescriptors[i])) { if (LADSPA_IS_PORT_INPUT(descriptor->PortDescriptors[i])) { bool sc = stristr(descriptor->PortNames[i], "Probe") != nullptr || stristr(descriptor->PortNames[i], "Sidechain") != nullptr; if (striendswith(descriptor->PortNames[i], " L") || striendswith(descriptor->PortNames[i], " (L)")) { if (sc) { probe_left_idx = i; } else { left_in_idx = i; } } else if (striendswith(descriptor->PortNames[i], " R") || striendswith(descriptor->PortNames[i], " (R)")) { if (sc) { probe_right_idx = i; } else { right_in_idx = i; } } if (count_input == 0) { first_in_idx = i; } else if (count_input == 1) { second_in_idx = i; } else if (count_input == 2) { third_in_idx = i; } else if (count_input == 3) { fourth_in_idx = i; } count_input++; } else if (LADSPA_IS_PORT_OUTPUT(descriptor->PortDescriptors[i])) { if (striendswith(descriptor->PortNames[i], " L") || striendswith(descriptor->PortNames[i], " (L)")) { left_out_idx = i; } else if (striendswith(descriptor->PortNames[i], " R") || striendswith(descriptor->PortNames[i], " (R)")) { right_out_idx = i; } if (count_output == 0) { first_out_idx = i; } else if (count_output == 1) { second_out_idx = i; } count_output++; } } } if (left_in_idx == null_ul || right_in_idx == null_ul) { left_in_idx = first_in_idx; right_in_idx = second_in_idx; } if (left_in_idx != null_ul) { descriptor->connect_port(instance, left_in_idx, const_cast<LADSPA_Data*>(left_in.data())); } if (right_in_idx != null_ul) { descriptor->connect_port(instance, right_in_idx, const_cast<LADSPA_Data*>(left_in.data())); } if (probe_left_idx == null_ul || probe_right_idx == null_ul) { if (left_in_idx == first_in_idx) { if (right_in_idx == second_in_idx) { probe_left_idx = third_in_idx; } else { probe_left_idx = second_in_idx; } } else if (right_in_idx == first_in_idx) { if (left_in_idx == second_in_idx) { probe_left_idx = third_in_idx; } else { probe_left_idx = second_in_idx; } } else { probe_left_idx = first_in_idx; } if (left_in_idx == second_in_idx) { if (right_in_idx == third_in_idx) { probe_right_idx = fourth_in_idx; } else { probe_right_idx = third_in_idx; } } else if (right_in_idx == second_in_idx) { if (left_in_idx == third_in_idx) { probe_right_idx = fourth_in_idx; } else { probe_right_idx = third_in_idx; } } else { probe_right_idx = second_in_idx; } } if (probe_left_idx != null_ul) { descriptor->connect_port(instance, probe_left_idx, const_cast<LADSPA_Data*>(probe_left.data())); } if (probe_right_idx != null_ul) { descriptor->connect_port(instance, probe_right_idx, const_cast<LADSPA_Data*>(probe_right.data())); } if (left_out_idx == null_ul || right_out_idx == null_ul) { left_out_idx = first_out_idx; right_out_idx = second_out_idx; } if (left_out_idx != null_ul) { descriptor->connect_port(instance, left_out_idx, left_out.data()); } if (right_out_idx != null_ul) { descriptor->connect_port(instance, right_out_idx, left_out.data()); } } void LadspaWrapper::activate() { if (!active && descriptor->activate != nullptr) { descriptor->activate(instance); } active = true; } void LadspaWrapper::deactivate() { if (active && descriptor->activate != nullptr && descriptor->deactivate != nullptr) { descriptor->deactivate(instance); } active = false; } void LadspaWrapper::run() const { assert(active); assert(instance); descriptor->run(instance, n_samples); } auto LadspaWrapper::get_control_port_count() const -> uint { uint count = 0U; for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { count++; } } return count; } static inline unsigned long cp_to_port_idx(const LADSPA_Descriptor* descriptor, uint index) { for (unsigned long i = 0UL; i < descriptor->PortCount; i++) { if (LADSPA_IS_PORT_CONTROL(descriptor->PortDescriptors[i])) { if (index-- == 0U) { return i; } } } return (unsigned long)-1L; } auto LadspaWrapper::get_control_port_name(uint index) const -> std::string { const unsigned long i = cp_to_port_idx(descriptor, index); if (i == null_ul) { return {}; } return descriptor->PortNames[i]; } auto LadspaWrapper::is_control_port_output(uint index) const -> bool { const unsigned long i = cp_to_port_idx(descriptor, index); if (i == null_ul) { return false; } return LADSPA_IS_PORT_OUTPUT(descriptor->PortDescriptors[i]); } auto LadspaWrapper::get_control_port_range(uint index) const -> std::tuple<float, float> { const unsigned long i = cp_to_port_idx(descriptor, index); if (i == null_ul) { return std::make_tuple(0.0F, 0.0F); } LADSPA_Data min = 0.0F; LADSPA_Data max = 0.0F; get_port_bounds(descriptor, i, rate, min, max); return std::make_tuple(min, max); } auto LadspaWrapper::get_control_port_default(uint index) const -> float { const unsigned long i = cp_to_port_idx(descriptor, index); if (i == null_ul) { return 0.0F; } return get_port_default(descriptor, i, rate); } auto LadspaWrapper::get_control_port_value(uint index) const -> float { assert(cp_to_port_idx(descriptor, index) != null_ul); assert(control_ports_initialized[index]); return control_ports[index]; } auto LadspaWrapper::get_control_port_value(const std::string& symbol) const -> float { auto iter = map_cp_name_to_idx.find(symbol); if (iter == map_cp_name_to_idx.end()) { util::warning(plugin_name + " port symbol not found: " + symbol); return 0.0F; } return get_control_port_value(static_cast<uint>(iter->second)); } auto LadspaWrapper::set_control_port_value_clamp(uint index, float value) -> float { const unsigned long i = cp_to_port_idx(descriptor, index); assert(i != null_ul); // If the value is out of bounds, get a new clamped one in LADSPA_Data (float) value = clamp_port_value(descriptor, i, rate, value); control_ports[index] = value; control_ports_initialized[index] = true; return value; } auto LadspaWrapper::set_control_port_value_clamp(const std::string& symbol, float value) -> float { auto iter = map_cp_name_to_idx.find(symbol); if (iter == map_cp_name_to_idx.end()) { util::warning(plugin_name + " port symbol not found: " + symbol); return value; } return set_control_port_value_clamp(static_cast<uint>(iter->second), value); } } // namespace ladspa
22,940
C++
.cpp
640
29.6375
116
0.61216
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,694
deepfilternet.cpp
wwmm_easyeffects/src/deepfilternet.cpp
/* * 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/>. */ #include "deepfilternet.hpp" #include <algorithm> #include <memory> #include <mutex> #include <span> #include <string> #include <vector> #include "ladspa_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "resampler.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" DeepFilterNet::DeepFilterNet(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::deepfilternet, tags::plugin_package::deepfilternet, schema, schema_path, pipe_manager, pipe_type) { ladspa_wrapper = std::make_unique<ladspa::LadspaWrapper>("libdeep_filter_ladspa.so", "deep_filter_stereo"); package_installed = ladspa_wrapper->found_plugin(); if (!package_installed) { util::debug(log_tag + "libdeep_filter_ladspa is not installed"); } ladspa_wrapper->bind_key_double_db_exponential<"Attenuation Limit (dB)", "attenuation-limit", false>(settings); ladspa_wrapper->bind_key_double_db_exponential<"Min processing threshold (dB)", "min-processing-threshold", false>( settings); ladspa_wrapper ->bind_key_double_db_exponential<"Max ERB processing threshold (dB)", "max-erb-processing-threshold", false>( settings); ladspa_wrapper ->bind_key_double_db_exponential<"Max DF processing threshold (dB)", "max-df-processing-threshold", false>( settings); ladspa_wrapper->bind_key_int<"Min Processing Buffer (frames)", "min-processing-buffer">(settings); ladspa_wrapper->bind_key_double<"Post Filter Beta", "post-filter-beta">(settings); setup_input_output_gain(); } DeepFilterNet::~DeepFilterNet() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void DeepFilterNet::setup() { std::scoped_lock<std::mutex> lock(data_mutex); if (!ladspa_wrapper->found_plugin()) { return; } resample = rate != 48000; resampler_ready = !resample; util::idle_add([&, this] { ladspa_wrapper->n_samples = n_samples; std::scoped_lock<std::mutex> lock(data_mutex); if (ladspa_wrapper->get_rate() != 48000) { ladspa_wrapper->create_instance(48000); ladspa_wrapper->activate(); } if (resample && !resampler_ready) { resampler_inL = std::make_unique<Resampler>(rate, 48000); resampler_inR = std::make_unique<Resampler>(rate, 48000); resampler_outL = std::make_unique<Resampler>(48000, rate); resampler_outR = std::make_unique<Resampler>(48000, rate); std::vector<float> dummy(n_samples); const auto resampled_inL = resampler_inL->process(dummy, false); const auto resampled_inR = resampler_inR->process(dummy, false); resampled_outL.resize(resampled_inL.size()); resampled_outR.resize(resampled_inR.size()); resampler_outL->process(resampled_inL, false); resampler_outR->process(resampled_inR, false); carryover_l.clear(); carryover_r.clear(); carryover_l.reserve(4); // chosen by fair dice roll. carryover_r.reserve(4); // guaranteed to be random. carryover_l.push_back(0.0F); carryover_r.push_back(0.0F); resampler_ready = true; } }); } void DeepFilterNet::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (!ladspa_wrapper->found_plugin() || !ladspa_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } if (resample) { const auto& resampled_inL = resampler_inL->process(left_in, false); const auto& resampled_inR = resampler_inR->process(right_in, false); resampled_outL.resize(resampled_inL.size()); resampled_outR.resize(resampled_inR.size()); ladspa_wrapper->n_samples = resampled_inL.size(); ladspa_wrapper->connect_data_ports(resampled_inL, resampled_inR, resampled_outL, resampled_outR); } else { ladspa_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); } ladspa_wrapper->run(); if (resample) { const auto& outL = resampler_outL->process(resampled_outL, false); const auto& outR = resampler_outR->process(resampled_outR, false); auto carryover_end_l = std::min(carryover_l.size(), left_out.size()); auto carryover_end_r = std::min(carryover_r.size(), right_out.size()); auto left_offset = carryover_end_l + outL.size() > left_out.size() ? carryover_end_l : left_out.size() - outL.size(); auto right_offset = carryover_end_r + outR.size() > right_out.size() ? carryover_end_r : right_out.size() - outR.size(); auto left_count = std::min(outL.size(), left_out.size() - left_offset); auto right_count = std::min(outR.size(), right_out.size() - right_offset); std::copy(carryover_l.begin(), carryover_l.begin() + carryover_end_l, left_out.begin()); std::copy(carryover_r.begin(), carryover_r.begin() + carryover_end_r, right_out.begin()); carryover_l.erase(carryover_l.begin(), carryover_l.begin() + carryover_end_l); carryover_r.erase(carryover_r.begin(), carryover_r.begin() + carryover_end_r); std::fill(left_out.begin() + carryover_end_l, left_out.begin() + left_offset, 0); std::fill(right_out.begin() + carryover_end_r, right_out.begin() + right_offset, 0); std::copy(outL.begin(), outL.begin() + left_count, left_out.begin() + left_offset); std::copy(outR.begin(), outR.begin() + right_count, right_out.begin() + right_offset); carryover_l.insert(carryover_l.end(), outL.begin() + left_count, outL.end()); carryover_r.insert(carryover_r.end(), outR.begin() + right_count, outR.end()); std::fill(left_out.begin() + left_offset + left_count, left_out.end(), 0); std::fill(right_out.begin() + right_offset + right_count, right_out.end(), 0); } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto DeepFilterNet::get_latency_seconds() -> float { return 0.02F + 1.0F / rate; }
7,410
C++
.cpp
164
39.304878
117
0.661481
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,695
preferences_general.cpp
wwmm_easyeffects/src/preferences_general.cpp
/* * 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/>. */ #include "preferences_general.hpp" #include <adwaita.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <filesystem> #include <fstream> #include "tags_app.hpp" #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::preferences::general { using namespace std::string_literals; struct _PreferencesGeneral { AdwPreferencesPage parent_instance; GtkSwitch *enable_autostart, *process_all_inputs, *process_all_outputs, *theme_switch, *shutdown_on_window_close, *use_cubic_volumes, *inactivity_timer_enable, *autohide_popovers, *exclude_monitor_streams, *show_native_plugin_ui; GtkSpinButton *inactivity_timeout, *meters_update_interval, *lv2ui_update_frequency; GSettings* settings; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PreferencesGeneral, preferences_general, ADW_TYPE_PREFERENCES_PAGE) #ifndef ENABLE_LIBPORTAL auto on_enable_autostart(GtkSwitch* obj, gboolean state, gpointer user_data) -> gboolean { std::filesystem::path autostart_dir{g_get_user_config_dir() + "/autostart"s}; if (!std::filesystem::is_directory(autostart_dir)) { std::filesystem::create_directories(autostart_dir); } std::filesystem::path autostart_file{g_get_user_config_dir() + "/autostart/easyeffects-service.desktop"s}; if (state != 0) { if (!std::filesystem::exists(autostart_file)) { std::ofstream ofs{autostart_file}; ofs << "[Desktop Entry]\n"; ofs << "Name=Easy Effects\n"; ofs << "Comment=Easy Effects Service\n"; ofs << "Exec=easyeffects --gapplication-service\n"; ofs << "Icon=com.github.wwmm.easyeffects\n"; ofs << "StartupNotify=false\n"; ofs << "Terminal=false\n"; ofs << "Type=Application\n"; ofs.close(); util::debug("autostart file created"); } } else { if (std::filesystem::exists(autostart_file)) { std::filesystem::remove(autostart_file); util::debug("autostart file removed"); } } return 0; } #endif void dispose(GObject* object) { auto* self = EE_PREFERENCES_GENERAL(object); g_object_unref(self->settings); #ifdef ENABLE_LIBPORTAL g_settings_unbind(self->enable_autostart, "active"); g_settings_unbind(self->shutdown_on_window_close, "active"); #endif util::debug("disposed"); G_OBJECT_CLASS(preferences_general_parent_class)->dispose(object); } void preferences_general_class_init(PreferencesGeneralClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::preferences_general_ui); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, enable_autostart); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, process_all_inputs); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, process_all_outputs); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, theme_switch); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, autohide_popovers); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, shutdown_on_window_close); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, use_cubic_volumes); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, exclude_monitor_streams); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, inactivity_timer_enable); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, inactivity_timeout); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, meters_update_interval); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, lv2ui_update_frequency); gtk_widget_class_bind_template_child(widget_class, PreferencesGeneral, show_native_plugin_ui); } void preferences_general_init(PreferencesGeneral* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->settings = g_settings_new(tags::app::id); prepare_spinbuttons<"s">(self->inactivity_timeout); prepare_spinbuttons<"ms">(self->meters_update_interval); prepare_spinbuttons<"Hz">(self->lv2ui_update_frequency); // initializing some widgets gsettings_bind_widgets<"process-all-inputs", "process-all-outputs", "use-dark-theme", "shutdown-on-window-close", "use-cubic-volumes", "autohide-popovers", "exclude-monitor-streams", "inactivity-timer-enable", "inactivity-timeout", "meters-update-interval", "lv2ui-update-frequency", "show-native-plugin-ui">( self->settings, self->process_all_inputs, self->process_all_outputs, self->theme_switch, self->shutdown_on_window_close, self->use_cubic_volumes, self->autohide_popovers, self->exclude_monitor_streams, self->inactivity_timer_enable, self->inactivity_timeout, self->meters_update_interval, self->lv2ui_update_frequency, self->show_native_plugin_ui); #ifdef ENABLE_LIBPORTAL libportal::init(self->enable_autostart, self->shutdown_on_window_close); #else gtk_switch_set_active(self->enable_autostart, static_cast<gboolean>(std::filesystem::is_regular_file( g_get_user_config_dir() + "/autostart/easyeffects-service.desktop"s))); g_signal_connect(self->enable_autostart, "state-set", G_CALLBACK(on_enable_autostart), nullptr); #endif } auto create() -> PreferencesGeneral* { return static_cast<PreferencesGeneral*>(g_object_new(EE_TYPE_PREFERENCES_GENERAL, nullptr)); } } // namespace ui::preferences::general
6,459
C++
.cpp
130
45.546154
120
0.7409
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,696
crossfeed_preset.cpp
wwmm_easyeffects/src/crossfeed_preset.cpp
/* * 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/>. */ #include "crossfeed_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" CrossfeedPreset::CrossfeedPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::crossfeed::id, tags::schema::crossfeed::input_path, tags::schema::crossfeed::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::crossfeed).append("#").append(util::to_string(index)); } void CrossfeedPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["fcut"] = g_settings_get_int(settings, "fcut"); json[section][instance_name]["feed"] = g_settings_get_double(settings, "feed"); } void CrossfeedPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<int>(json.at(section).at(instance_name), settings, "fcut", "fcut"); update_key<double>(json.at(section).at(instance_name), settings, "feed", "feed"); }
2,406
C++
.cpp
48
46.0625
97
0.708866
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,697
compressor_preset.cpp
wwmm_easyeffects/src/compressor_preset.cpp
/* * 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/>. */ #include "compressor_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" CompressorPreset::CompressorPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::compressor::id, tags::schema::compressor::input_path, tags::schema::compressor::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::compressor).append("#").append(util::to_string(index)); } void CompressorPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["dry"] = g_settings_get_double(settings, "dry"); json[section][instance_name]["wet"] = g_settings_get_double(settings, "wet"); json[section][instance_name]["mode"] = util::gsettings_get_string(settings, "mode"); json[section][instance_name]["attack"] = g_settings_get_double(settings, "attack"); json[section][instance_name]["release"] = g_settings_get_double(settings, "release"); json[section][instance_name]["release-threshold"] = g_settings_get_double(settings, "release-threshold"); json[section][instance_name]["threshold"] = g_settings_get_double(settings, "threshold"); json[section][instance_name]["ratio"] = g_settings_get_double(settings, "ratio"); json[section][instance_name]["knee"] = g_settings_get_double(settings, "knee"); json[section][instance_name]["makeup"] = g_settings_get_double(settings, "makeup"); json[section][instance_name]["boost-threshold"] = g_settings_get_double(settings, "boost-threshold"); json[section][instance_name]["boost-amount"] = g_settings_get_double(settings, "boost-amount"); json[section][instance_name]["stereo-split"] = g_settings_get_boolean(settings, "stereo-split") != 0; json[section][instance_name]["sidechain"]["type"] = util::gsettings_get_string(settings, "sidechain-type"); json[section][instance_name]["sidechain"]["mode"] = util::gsettings_get_string(settings, "sidechain-mode"); json[section][instance_name]["sidechain"]["source"] = util::gsettings_get_string(settings, "sidechain-source"); json[section][instance_name]["sidechain"]["stereo-split-source"] = util::gsettings_get_string(settings, "stereo-split-source"); json[section][instance_name]["sidechain"]["preamp"] = g_settings_get_double(settings, "sidechain-preamp"); json[section][instance_name]["sidechain"]["reactivity"] = g_settings_get_double(settings, "sidechain-reactivity"); json[section][instance_name]["sidechain"]["lookahead"] = g_settings_get_double(settings, "sidechain-lookahead"); json[section][instance_name]["hpf-mode"] = util::gsettings_get_string(settings, "hpf-mode"); json[section][instance_name]["hpf-frequency"] = g_settings_get_double(settings, "hpf-frequency"); json[section][instance_name]["lpf-mode"] = util::gsettings_get_string(settings, "lpf-mode"); json[section][instance_name]["lpf-frequency"] = g_settings_get_double(settings, "lpf-frequency"); } void CompressorPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "dry", "dry"); update_key<double>(json.at(section).at(instance_name), settings, "wet", "wet"); update_key<gchar*>(json.at(section).at(instance_name), settings, "mode", "mode"); update_key<double>(json.at(section).at(instance_name), settings, "attack", "attack"); update_key<double>(json.at(section).at(instance_name), settings, "release", "release"); update_key<double>(json.at(section).at(instance_name), settings, "release-threshold", "release-threshold"); update_key<double>(json.at(section).at(instance_name), settings, "threshold", "threshold"); update_key<double>(json.at(section).at(instance_name), settings, "ratio", "ratio"); update_key<double>(json.at(section).at(instance_name), settings, "knee", "knee"); update_key<double>(json.at(section).at(instance_name), settings, "makeup", "makeup"); update_key<double>(json.at(section).at(instance_name), settings, "boost-threshold", "boost-threshold"); update_key<double>(json.at(section).at(instance_name), settings, "boost-amount", "boost-amount"); update_key<bool>(json.at(section).at(instance_name), settings, "stereo-split", "stereo-split"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-type", "type"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-mode", "mode"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "stereo-split-source", "stereo-split-source"); update_key<gchar*>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-source", "source"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-preamp", "preamp"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-reactivity", "reactivity"); update_key<double>(json.at(section).at(instance_name).at("sidechain"), settings, "sidechain-lookahead", "lookahead"); update_key<gchar*>(json.at(section).at(instance_name), settings, "hpf-mode", "hpf-mode"); update_key<double>(json.at(section).at(instance_name), settings, "hpf-frequency", "hpf-frequency"); update_key<gchar*>(json.at(section).at(instance_name), settings, "lpf-mode", "lpf-mode"); update_key<double>(json.at(section).at(instance_name), settings, "lpf-frequency", "lpf-frequency"); }
6,973
C++
.cpp
96
68.229167
119
0.714998
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,698
speex.cpp
wwmm_easyeffects/src/speex.cpp
/* * 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/>. */ #include "speex.hpp" #include <gio/gio.h> #include <glib-object.h> #include <speex/speex_preprocess.h> #include <speex/speexdsp_config_types.h> #include <algorithm> #include <climits> #include <cstddef> #include <mutex> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Speex::Speex(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::speex, tags::plugin_package::speex, schema, schema_path, pipe_manager, pipe_type), enable_denoise(g_settings_get_boolean(settings, "enable-denoise")), noise_suppression(g_settings_get_int(settings, "noise-suppression")), enable_agc(g_settings_get_boolean(settings, "enable-agc")), enable_vad(g_settings_get_boolean(settings, "enable-vad")), vad_probability_start(g_settings_get_int(settings, "vad-probability-start")), vad_probability_continue(g_settings_get_int(settings, "vad-probability-continue")), enable_dereverb(g_settings_get_boolean(settings, "enable-dereverb")) { gconnections.push_back(g_signal_connect( settings, "changed::enable-denoise", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->enable_denoise = g_settings_get_boolean(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_DENOISE, &self->enable_denoise); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_DENOISE, &self->enable_denoise); } }), this)); gconnections.push_back(g_signal_connect( settings, "changed::noise-suppression", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->noise_suppression = g_settings_get_int(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &self->noise_suppression); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &self->noise_suppression); } }), this)); gconnections.push_back( g_signal_connect(settings, "changed::enable-agc", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->enable_agc = g_settings_get_boolean(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_AGC, &self->enable_agc); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_AGC, &self->enable_agc); } }), this)); gconnections.push_back( g_signal_connect(settings, "changed::enable-vad", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->enable_vad = g_settings_get_boolean(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_VAD, &self->enable_vad); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_VAD, &self->enable_vad); } }), this)); gconnections.push_back(g_signal_connect( settings, "changed::vad-probability-start", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->vad_probability_start = g_settings_get_int(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_PROB_START, &self->vad_probability_start); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_PROB_START, &self->vad_probability_start); } }), this)); gconnections.push_back(g_signal_connect( settings, "changed::vad-probability-continue", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->vad_probability_continue = g_settings_get_int(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_PROB_CONTINUE, &self->vad_probability_continue); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_PROB_CONTINUE, &self->vad_probability_continue); } }), this)); gconnections.push_back(g_signal_connect( settings, "changed::enable-dereverb", G_CALLBACK(+[](GSettings* settings, char* key, Speex* self) { std::scoped_lock<std::mutex> lock(self->data_mutex); self->enable_dereverb = g_settings_get_boolean(settings, key); if (self->state_left) { speex_preprocess_ctl(self->state_left, SPEEX_PREPROCESS_SET_DEREVERB, &self->enable_dereverb); } if (self->state_right) { speex_preprocess_ctl(self->state_right, SPEEX_PREPROCESS_SET_DEREVERB, &self->enable_dereverb); } }), this)); setup_input_output_gain(); } Speex::~Speex() { if (connected_to_pw) { disconnect_from_pw(); } std::scoped_lock<std::mutex> lock(data_mutex); free_speex(); util::debug(log_tag + name + " destroyed"); } void Speex::setup() { std::scoped_lock<std::mutex> lock(data_mutex); latency_n_frames = 0U; speex_ready = false; data_L.resize(n_samples); data_R.resize(n_samples); if (state_left != nullptr) { speex_preprocess_state_destroy(state_left); } if (state_right != nullptr) { speex_preprocess_state_destroy(state_right); } state_left = speex_preprocess_state_init(static_cast<int>(n_samples), static_cast<int>(rate)); state_right = speex_preprocess_state_init(static_cast<int>(n_samples), static_cast<int>(rate)); if (state_left != nullptr) { speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_DENOISE, &enable_denoise); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &noise_suppression); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_AGC, &enable_agc); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_VAD, &enable_vad); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_PROB_START, &vad_probability_start); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_PROB_CONTINUE, &vad_probability_continue); speex_preprocess_ctl(state_left, SPEEX_PREPROCESS_SET_DEREVERB, &enable_dereverb); } if (state_right != nullptr) { speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_DENOISE, &enable_denoise); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &noise_suppression); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_AGC, &enable_agc); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_VAD, &enable_vad); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_PROB_START, &vad_probability_start); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_PROB_CONTINUE, &vad_probability_continue); speex_preprocess_ctl(state_right, SPEEX_PREPROCESS_SET_DEREVERB, &enable_dereverb); } speex_ready = true; } void Speex::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass || !speex_ready) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } for (size_t i = 0; i < n_samples; i++) { data_L[i] = static_cast<spx_int16_t>(left_in[i] * (SHRT_MAX + 1)); data_R[i] = static_cast<spx_int16_t>(right_in[i] * (SHRT_MAX + 1)); } if (speex_preprocess_run(state_left, data_L.data()) == 1) { for (size_t i = 0; i < n_samples; i++) { left_out[i] = static_cast<float>(data_L[i]) * inv_short_max; } } else { std::ranges::fill(left_out, 0.0F); } if (speex_preprocess_run(state_right, data_R.data()) == 1) { for (size_t i = 0; i < n_samples; i++) { right_out[i] = static_cast<float>(data_R[i]) * inv_short_max; } } else { std::ranges::fill(right_out, 0.0F); } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } void Speex::free_speex() { if (state_left != nullptr) { speex_preprocess_state_destroy(state_left); } if (state_right != nullptr) { speex_preprocess_state_destroy(state_right); } state_left = nullptr; state_right = nullptr; } auto Speex::get_latency_seconds() -> float { return latency_value; }
10,491
C++
.cpp
234
37.217949
119
0.638638
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,699
delay_preset.cpp
wwmm_easyeffects/src/delay_preset.cpp
/* * 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/>. */ #include "delay_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" DelayPreset::DelayPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::delay::id, tags::schema::delay::input_path, tags::schema::delay::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::delay).append("#").append(util::to_string(index)); } void DelayPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["time-l"] = g_settings_get_double(settings, "time-l"); json[section][instance_name]["time-r"] = g_settings_get_double(settings, "time-r"); json[section][instance_name]["dry-l"] = g_settings_get_double(settings, "dry-l"); json[section][instance_name]["dry-r"] = g_settings_get_double(settings, "dry-r"); json[section][instance_name]["wet-l"] = g_settings_get_double(settings, "wet-l"); json[section][instance_name]["wet-r"] = g_settings_get_double(settings, "wet-r"); json[section][instance_name]["invert-phase-l"] = g_settings_get_boolean(settings, "invert-phase-l") != 0; json[section][instance_name]["invert-phase-r"] = g_settings_get_boolean(settings, "invert-phase-r") != 0; } void DelayPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "time-l", "time-l"); update_key<double>(json.at(section).at(instance_name), settings, "time-r", "time-r"); update_key<double>(json.at(section).at(instance_name), settings, "dry-l", "dry-l"); update_key<double>(json.at(section).at(instance_name), settings, "dry-r", "dry-r"); update_key<double>(json.at(section).at(instance_name), settings, "wet-l", "wet-l"); update_key<double>(json.at(section).at(instance_name), settings, "wet-r", "wet-r"); update_key<bool>(json.at(section).at(instance_name), settings, "invert-phase-l", "invert-phase-l"); update_key<bool>(json.at(section).at(instance_name), settings, "invert-phase-r", "invert-phase-r"); }
3,504
C++
.cpp
60
54.35
107
0.700292
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,700
bass_enhancer.cpp
wwmm_easyeffects/src/bass_enhancer.cpp
/* * 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/>. */ #include "bass_enhancer.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" BassEnhancer::BassEnhancer(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::bass_enhancer, tags::plugin_package::calf, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://calf.sourceforge.net/plugins/BassEnhancer"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://calf.sourceforge.net/plugins/BassEnhancer is not installed"); } lv2_wrapper->bind_key_double_db<"amount", "amount">(settings); lv2_wrapper->bind_key_double<"drive", "harmonics">(settings); lv2_wrapper->bind_key_double<"freq", "scope">(settings); lv2_wrapper->bind_key_double<"floor", "floor">(settings); lv2_wrapper->bind_key_double<"blend", "blend">(settings); lv2_wrapper->bind_key_bool<"floor_active", "floor-active">(settings); lv2_wrapper->bind_key_bool<"listen", "listen">(settings); setup_input_output_gain(); } BassEnhancer::~BassEnhancer() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void BassEnhancer::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void BassEnhancer::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { // harmonics needed as double for levelbar widget ui, so we convert it here harmonics_port_value = static_cast<double>(lv2_wrapper->get_control_port_value("meter_drive")); if (!post_messages) { return; } harmonics.emit(harmonics_port_value); notify(); } } } auto BassEnhancer::get_latency_seconds() -> float { return 0.0F; }
3,809
C++
.cpp
102
31.490196
102
0.648722
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,701
application_ui.cpp
wwmm_easyeffects/src/application_ui.cpp
/* * 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/>. */ #include "application_ui.hpp" #include <adwaita.h> #include <gdk/gdk.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <gtk/gtkcssprovider.h> #include <gtk/gtkshortcut.h> #include <sigc++/connection.h> #include <string> #include <vector> #include "application.hpp" #include "config.h" #include "effects_box.hpp" #include "pipe_manager_box.hpp" #include "pipeline_type.hpp" #include "preset_type.hpp" #include "presets_menu.hpp" #include "tags_app.hpp" #include "tags_resources.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::application_window { using namespace std::string_literals; struct Data { public: ~Data() { util::debug("data struct destroyed"); } int width = 0, height = 0; bool maximized = false, fullscreen = false; GApplication* gapp = nullptr; GtkIconTheme* icon_theme = nullptr; std::vector<sigc::connection> connections; }; struct _ApplicationWindow { AdwWindow parent_instance; AdwViewStack* stack; GtkMenuButton* presets_menu_button; GtkToggleButton* bypass_button; ui::presets_menu::PresetsMenu *input_presets_menu, *output_presets_menu; ui::effects_box::EffectsBox* soe_ui; ui::effects_box::EffectsBox* sie_ui; ui::pipe_manager_box::PipeManagerBox* pm_box; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(ApplicationWindow, application_window, ADW_TYPE_APPLICATION_WINDOW) void init_theme_color(ApplicationWindow* self) { if (g_settings_get_boolean(self->settings, "use-dark-theme") == 0) { adw_style_manager_set_color_scheme(adw_style_manager_get_default(), ADW_COLOR_SCHEME_PREFER_LIGHT); } else { adw_style_manager_set_color_scheme(adw_style_manager_get_default(), ADW_COLOR_SCHEME_PREFER_DARK); } } auto setup_icon_theme() -> GtkIconTheme* { auto* icon_theme = gtk_icon_theme_get_for_display(gdk_display_get_default()); if (icon_theme == nullptr) { util::warning("can't retrieve the icon theme in use on the system. App icons won't be shown."); return nullptr; } auto* name = gtk_icon_theme_get_theme_name(icon_theme); if (name == nullptr) { util::debug("Icon Theme detected, but the name is empty"); } else { util::debug("Icon Theme "s + name + " detected"); g_free(name); } gtk_icon_theme_add_resource_path(icon_theme, tags::resources::icons); return icon_theme; } void apply_css_style() { auto* provider = gtk_css_provider_new(); gtk_css_provider_load_from_resource(provider, tags::resources::css); gtk_style_context_add_provider_for_display(gdk_display_get_default(), GTK_STYLE_PROVIDER(provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION); } void stack_visible_child_changed(ApplicationWindow* self, GParamSpec* pspec, GtkWidget* stack) { if (!GTK_MENU_BUTTON(self->presets_menu_button)) { return; } if (!GTK_WIDGET(self->output_presets_menu) || !GTK_WIDGET(self->input_presets_menu)) { return; } if (self->data->gapp == nullptr) { return; } const auto* name = adw_view_stack_get_visible_child_name(ADW_VIEW_STACK(stack)); if (g_strcmp0(name, "stream_output") == 0) { gtk_menu_button_set_popover(self->presets_menu_button, GTK_WIDGET(self->output_presets_menu)); } else if (g_strcmp0(name, "stream_input") == 0) { gtk_menu_button_set_popover(self->presets_menu_button, GTK_WIDGET(self->input_presets_menu)); } else if (g_strcmp0(name, "page_pipewire") == 0) { gtk_menu_button_set_popover(self->presets_menu_button, nullptr); } } void constructed(GObject* object) { auto* self = EE_APP_WINDOW(object); self->data->maximized = g_settings_get_boolean(self->settings, "window-maximized") != 0; self->data->fullscreen = g_settings_get_boolean(self->settings, "window-fullscreen") != 0; self->data->width = g_settings_get_int(self->settings, "window-width"); self->data->height = g_settings_get_int(self->settings, "window-height"); gtk_window_set_default_size(GTK_WINDOW(self), self->data->width, self->data->height); gtk_window_set_default_icon_name(IS_DEVEL_BUILD ? std::string(tags::app::id).append(".Devel").c_str() : tags::app::id); if (self->data->maximized) { gtk_window_maximize(GTK_WINDOW(self)); } if (self->data->fullscreen) { gtk_window_fullscreen(GTK_WINDOW(self)); } G_OBJECT_CLASS(application_window_parent_class)->constructed(object); } void size_allocate(GtkWidget* widget, int width, int height, int baseline) { auto* self = EE_APP_WINDOW(widget); GTK_WIDGET_CLASS(application_window_parent_class)->size_allocate(widget, width, height, baseline); if (!self->data->maximized && !self->data->fullscreen) { gtk_window_get_default_size(GTK_WINDOW(self), &self->data->width, &self->data->height); } } void surface_state_changed(GtkWidget* widget) { auto* self = EE_APP_WINDOW(widget); GdkToplevelState new_state = GDK_TOPLEVEL_STATE_MAXIMIZED; new_state = gdk_toplevel_get_state(GDK_TOPLEVEL(gtk_native_get_surface(GTK_NATIVE(widget)))); self->data->maximized = (new_state & GDK_TOPLEVEL_STATE_MAXIMIZED) != 0; self->data->fullscreen = (new_state & GDK_TOPLEVEL_STATE_FULLSCREEN) != 0; } void realize(GtkWidget* widget) { GTK_WIDGET_CLASS(application_window_parent_class)->realize(widget); g_signal_connect_swapped(gtk_native_get_surface(GTK_NATIVE(widget)), "notify::state", G_CALLBACK(surface_state_changed), widget); auto* self = EE_APP_WINDOW(widget); /* Getting the gapp pointer here because it is not defined when "init" is called */ self->data->gapp = G_APPLICATION(gtk_window_get_application(GTK_WINDOW(widget))); ui::presets_menu::setup(self->output_presets_menu, app::EE_APP(self->data->gapp), PresetType::output); ui::presets_menu::setup(self->input_presets_menu, app::EE_APP(self->data->gapp), PresetType::input); ui::effects_box::setup(self->soe_ui, app::EE_APP(self->data->gapp), PipelineType::output, self->data->icon_theme); ui::effects_box::setup(self->sie_ui, app::EE_APP(self->data->gapp), PipelineType::input, self->data->icon_theme); ui::pipe_manager_box::setup(self->pm_box, app::EE_APP(self->data->gapp)); self->data->connections.push_back( app::EE_APP(self->data->gapp) ->presets_manager->preset_load_error.connect([=](const std::string& title, const std::string& descr) { ui::show_simple_message_dialog(widget, title, descr); })); } void unrealize(GtkWidget* widget) { auto* self = EE_APP_WINDOW(widget); for (auto& c : self->data->connections) { c.disconnect(); } self->data->connections.clear(); g_signal_handlers_disconnect_by_func(gtk_native_get_surface(GTK_NATIVE((widget))), reinterpret_cast<gpointer>(surface_state_changed), widget); GTK_WIDGET_CLASS(application_window_parent_class)->unrealize(widget); } void dispose(GObject* object) { auto* self = EE_APP_WINDOW(object); g_settings_set_int(self->settings, "window-width", self->data->width); g_settings_set_int(self->settings, "window-height", self->data->height); g_settings_set_boolean(self->settings, "window-maximized", static_cast<gboolean>(self->data->maximized)); g_settings_set_boolean(self->settings, "window-fullscreen", static_cast<gboolean>(self->data->fullscreen)); if (g_settings_get_boolean(self->settings, "shutdown-on-window-close") != 0 && (g_application_get_flags(self->data->gapp) & G_APPLICATION_IS_SERVICE) != 0) { g_application_release(self->data->gapp); } g_object_unref(self->settings); // removing the extra reference g_object_unref(self->output_presets_menu); g_object_unref(self->input_presets_menu); ui::unref_global_app_settings(); util::debug("disposed"); G_OBJECT_CLASS(application_window_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_APP_WINDOW(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(application_window_parent_class)->finalize(object); } void application_window_class_init(ApplicationWindowClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->constructed = constructed; object_class->dispose = dispose; object_class->finalize = finalize; widget_class->size_allocate = size_allocate; widget_class->realize = realize; widget_class->unrealize = unrealize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::application_window_ui); gtk_widget_class_bind_template_child(widget_class, ApplicationWindow, stack); gtk_widget_class_bind_template_child(widget_class, ApplicationWindow, presets_menu_button); gtk_widget_class_bind_template_child(widget_class, ApplicationWindow, bypass_button); gtk_widget_class_bind_template_callback(widget_class, stack_visible_child_changed); } void application_window_init(ApplicationWindow* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); self->data->width = -1; self->data->height = -1; self->data->maximized = false; self->data->fullscreen = false; self->settings = g_settings_new(tags::app::id); init_theme_color(self); apply_css_style(); if (IS_DEVEL_BUILD) { gtk_widget_add_css_class(GTK_WIDGET(self), "devel"); } self->data->icon_theme = setup_icon_theme(); /* We save the user locale here because we have to wait for the changes GTK is going to make to the global locale. It seems that the init method of the main window widget is a good place for this. */ ui::save_user_locale(); ui::init_global_app_settings(); self->output_presets_menu = ui::presets_menu::create(); self->input_presets_menu = ui::presets_menu::create(); /* Adding an extra reference so that the menu sin ´t destroyed when alternating between the input and output effects section */ g_object_ref(self->output_presets_menu); g_object_ref(self->input_presets_menu); self->soe_ui = ui::effects_box::create(); self->sie_ui = ui::effects_box::create(); self->pm_box = ui::pipe_manager_box::create(); auto* soe_ui_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->soe_ui), "stream_output", _("_Output")); auto* sie_ui_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->sie_ui), "stream_input", _("_Input")); auto* pm_box_page = adw_view_stack_add_titled(self->stack, GTK_WIDGET(self->pm_box), "page_pipewire", _("_PipeWire")); adw_view_stack_page_set_use_underline(soe_ui_page, true); adw_view_stack_page_set_use_underline(sie_ui_page, true); adw_view_stack_page_set_use_underline(pm_box_page, true); adw_view_stack_page_set_icon_name(soe_ui_page, "audio-speakers-symbolic"); adw_view_stack_page_set_icon_name(sie_ui_page, "audio-input-microphone-symbolic"); adw_view_stack_page_set_icon_name(pm_box_page, "network-server-symbolic"); gtk_menu_button_set_popover(self->presets_menu_button, GTK_WIDGET(self->output_presets_menu)); g_settings_bind(self->settings, "bypass", self->bypass_button, "active", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "autohide-popovers", self->output_presets_menu, "autohide", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "autohide-popovers", self->input_presets_menu, "autohide", G_SETTINGS_BIND_DEFAULT); g_signal_connect(self->settings, "changed::use-dark-theme", G_CALLBACK(+[](GSettings* settings, char* key, ApplicationWindow* self) { init_theme_color(self); }), self); } auto create(GApplication* gapp) -> ApplicationWindow* { return static_cast<ApplicationWindow*>(g_object_new(EE_TYPE_APPLICATION_WINDOW, "application", gapp, nullptr)); } } // namespace ui::application_window
12,644
C++
.cpp
268
43.317164
120
0.714181
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,702
pitch.cpp
wwmm_easyeffects/src/pitch.cpp
/* * 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/>. */ #include "pitch.hpp" #include <STTypes.h> #include <SoundTouch.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <algorithm> #include <cstddef> #include <mutex> #include <span> #include <string> #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Pitch::Pitch(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::pitch, tags::plugin_package::sound_touch, schema, schema_path, pipe_manager, pipe_type) { quick_seek = g_settings_get_boolean(settings, "quick-seek") != 0; anti_alias = g_settings_get_boolean(settings, "anti-alias") != 0; sequence_length_ms = g_settings_get_int(settings, "sequence-length"); seek_window_ms = g_settings_get_int(settings, "seek-window"); overlap_length_ms = g_settings_get_int(settings, "overlap-length"); tempo_difference = g_settings_get_double(settings, "tempo-difference"); rate_difference = g_settings_get_double(settings, "rate-difference"); semitones = g_settings_get_double(settings, "semitones"); // resetting soundtouch when bypass is pressed so its internal data is discarded gconnections.push_back(g_signal_connect(settings, "changed::bypass", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); util::idle_add([&, self] { self->data_mutex.lock(); self->soundtouch_ready = false; self->data_mutex.unlock(); self->init_soundtouch(); self->data_mutex.lock(); self->soundtouch_ready = true; self->data_mutex.unlock(); }); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::quick-seek", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->quick_seek = g_settings_get_boolean(settings, key) != 0; if (!self->soundtouch_ready) { return; } self->set_quick_seek(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::anti-alias", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->anti_alias = g_settings_get_boolean(settings, key) != 0; if (!self->soundtouch_ready) { return; } self->set_quick_seek(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::sequence-length", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->sequence_length_ms = g_settings_get_int(settings, key); if (!self->soundtouch_ready) { return; } self->set_sequence_length(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::seek-window", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->seek_window_ms = g_settings_get_int(settings, key); if (!self->soundtouch_ready) { return; } self->set_seek_window(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::overlap-length", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->overlap_length_ms = g_settings_get_int(settings, key); if (!self->soundtouch_ready) { return; } self->set_overlap_length(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::tempo-difference", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->tempo_difference = g_settings_get_double(settings, key); if (!self->soundtouch_ready) { return; } self->set_tempo_difference(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::rate-difference", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->rate_difference = g_settings_get_double(settings, key); if (!self->soundtouch_ready) { return; } self->set_rate_difference(); }), this)); gconnections.push_back(g_signal_connect(settings, "changed::semitones", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<Pitch*>(user_data); self->semitones = g_settings_get_double(settings, key); if (!self->soundtouch_ready) { return; } self->set_semitones(); }), this)); setup_input_output_gain(); } Pitch::~Pitch() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Pitch::setup() { soundtouch_ready = false; latency_n_frames = 0U; if (data.size() != static_cast<size_t>(n_samples) * 2) { data.resize(2U * static_cast<size_t>(n_samples)); } deque_out_L.resize(0U); deque_out_R.resize(0U); util::idle_add([&, this] { if (soundtouch_ready) { return; } init_soundtouch(); std::scoped_lock<std::mutex> lock(data_mutex); soundtouch_ready = true; }); } void Pitch::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { std::scoped_lock<std::mutex> lock(data_mutex); if (bypass || !soundtouch_ready) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } for (size_t n = 0U; n < left_in.size(); n++) { data[n * 2U] = left_in[n]; data[n * 2U + 1U] = right_in[n]; } snd_touch->putSamples(data.data(), n_samples); uint n_received = 0U; do { n_received = snd_touch->receiveSamples(data.data(), n_samples); for (size_t n = 0U; n < n_received; n++) { deque_out_L.push_back(data[n * 2U]); deque_out_R.push_back(data[n * 2U + 1U]); } } while (n_received != 0); if (deque_out_L.size() >= left_out.size()) { for (float& v : left_out) { v = deque_out_L.front(); deque_out_L.pop_front(); } for (float& v : right_out) { v = deque_out_R.front(); deque_out_R.pop_front(); } } else { const uint offset = left_out.size() - deque_out_L.size(); if (offset != latency_n_frames) { latency_n_frames = offset; notify_latency = true; } for (uint n = 0U; !deque_out_L.empty() && n < left_out.size(); n++) { if (n < offset) { left_out[n] = 0.0F; right_out[n] = 0.0F; } else { left_out[n] = deque_out_L.front(); right_out[n] = deque_out_R.front(); deque_out_R.pop_front(); deque_out_L.pop_front(); } } } if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (notify_latency) { latency_value = static_cast<float>(latency_n_frames) / static_cast<float>(rate); util::debug(log_tag + name + " latency: " + util::to_string(latency_value, "") + " s"); util::idle_add([this]() { if (!post_messages || latency.empty()) { return; } latency.emit(); }); update_filter_params(); notify_latency = false; } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } void Pitch::set_semitones() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setPitchSemiTones(semitones); } void Pitch::set_sequence_length() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setSetting(SETTING_SEQUENCE_MS, sequence_length_ms); } void Pitch::set_seek_window() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setSetting(SETTING_SEEKWINDOW_MS, seek_window_ms); } void Pitch::set_overlap_length() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setSetting(SETTING_OVERLAP_MS, overlap_length_ms); } void Pitch::set_quick_seek() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setSetting(SETTING_USE_QUICKSEEK, static_cast<int>(quick_seek)); } void Pitch::set_anti_alias() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setSetting(SETTING_USE_AA_FILTER, static_cast<int>(anti_alias)); } void Pitch::set_tempo_difference() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setTempoChange(tempo_difference); } void Pitch::set_rate_difference() { if (snd_touch == nullptr) { return; } std::scoped_lock<std::mutex> lock(data_mutex); snd_touch->setRateChange(rate_difference); } void Pitch::init_soundtouch() { delete snd_touch; snd_touch = new soundtouch::SoundTouch(); snd_touch->setSampleRate(rate); snd_touch->setChannels(2); set_semitones(); set_quick_seek(); set_anti_alias(); set_sequence_length(); set_seek_window(); set_overlap_length(); set_tempo_difference(); set_rate_difference(); } auto Pitch::get_latency_seconds() -> float { return latency_value; }
13,903
C++
.cpp
321
28.049844
110
0.483258
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,703
multiband_compressor_preset.cpp
wwmm_easyeffects/src/multiband_compressor_preset.cpp
/* * 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/>. */ #include "multiband_compressor_preset.hpp" #include <gio/gio.h> #include <glib.h> #include <sys/types.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" MultibandCompressorPreset::MultibandCompressorPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::multiband_compressor::id, tags::schema::multiband_compressor::input_path, tags::schema::multiband_compressor::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::multiband_compressor).append("#").append(util::to_string(index)); } void MultibandCompressorPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["dry"] = g_settings_get_double(settings, "dry"); json[section][instance_name]["wet"] = g_settings_get_double(settings, "wet"); json[section][instance_name]["compressor-mode"] = util::gsettings_get_string(settings, "compressor-mode"); json[section][instance_name]["envelope-boost"] = util::gsettings_get_string(settings, "envelope-boost"); json[section][instance_name]["stereo-split"] = g_settings_get_boolean(settings, "stereo-split") != 0; for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); const auto bandn = "band" + nstr; if (n > 0U) { json[section][instance_name][bandn]["enable-band"] = g_settings_get_boolean(settings, ("enable-band" + nstr).c_str()) != 0; json[section][instance_name][bandn]["split-frequency"] = g_settings_get_double(settings, ("split-frequency" + nstr).c_str()); } json[section][instance_name][bandn]["compressor-enable"] = g_settings_get_boolean(settings, ("compressor-enable" + nstr).c_str()) != 0; json[section][instance_name][bandn]["solo"] = g_settings_get_boolean(settings, ("solo" + nstr).c_str()) != 0; json[section][instance_name][bandn]["mute"] = g_settings_get_boolean(settings, ("mute" + nstr).c_str()) != 0; json[section][instance_name][bandn]["attack-threshold"] = g_settings_get_double(settings, ("attack-threshold" + nstr).c_str()); json[section][instance_name][bandn]["attack-time"] = g_settings_get_double(settings, ("attack-time" + nstr).c_str()); json[section][instance_name][bandn]["release-threshold"] = g_settings_get_double(settings, ("release-threshold" + nstr).c_str()); json[section][instance_name][bandn]["release-time"] = g_settings_get_double(settings, ("release-time" + nstr).c_str()); json[section][instance_name][bandn]["ratio"] = g_settings_get_double(settings, ("ratio" + nstr).c_str()); json[section][instance_name][bandn]["knee"] = g_settings_get_double(settings, ("knee" + nstr).c_str()); json[section][instance_name][bandn]["makeup"] = g_settings_get_double(settings, ("makeup" + nstr).c_str()); json[section][instance_name][bandn]["compression-mode"] = util::gsettings_get_string(settings, ("compression-mode" + nstr).c_str()); json[section][instance_name][bandn]["external-sidechain"] = g_settings_get_boolean(settings, ("external-sidechain" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-mode"] = util::gsettings_get_string(settings, ("sidechain-mode" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-source"] = util::gsettings_get_string(settings, ("sidechain-source" + nstr).c_str()); json[section][instance_name][bandn]["stereo-split-source"] = util::gsettings_get_string(settings, ("stereo-split-source" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-lookahead"] = g_settings_get_double(settings, ("sidechain-lookahead" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-reactivity"] = g_settings_get_double(settings, ("sidechain-reactivity" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-preamp"] = g_settings_get_double(settings, ("sidechain-preamp" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-custom-lowcut-filter"] = g_settings_get_boolean(settings, ("sidechain-custom-lowcut-filter" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-custom-highcut-filter"] = g_settings_get_boolean(settings, ("sidechain-custom-highcut-filter" + nstr).c_str()) != 0; json[section][instance_name][bandn]["sidechain-lowcut-frequency"] = g_settings_get_double(settings, ("sidechain-lowcut-frequency" + nstr).c_str()); json[section][instance_name][bandn]["sidechain-highcut-frequency"] = g_settings_get_double(settings, ("sidechain-highcut-frequency" + nstr).c_str()); json[section][instance_name][bandn]["boost-threshold"] = g_settings_get_double(settings, ("boost-threshold" + nstr).c_str()); json[section][instance_name][bandn]["boost-amount"] = g_settings_get_double(settings, ("boost-amount" + nstr).c_str()); } } void MultibandCompressorPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<double>(json.at(section).at(instance_name), settings, "dry", "dry"); update_key<double>(json.at(section).at(instance_name), settings, "wet", "wet"); update_key<gchar*>(json.at(section).at(instance_name), settings, "compressor-mode", "compressor-mode"); update_key<gchar*>(json.at(section).at(instance_name), settings, "envelope-boost", "envelope-boost"); update_key<bool>(json.at(section).at(instance_name), settings, "stereo-split", "stereo-split"); for (uint n = 0U; n < n_bands; n++) { const auto nstr = util::to_string(n); const auto bandn = "band" + nstr; if (n > 0U) { update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "enable-band" + nstr, "enable-band"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "split-frequency" + nstr, "split-frequency"); } update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "compressor-enable" + nstr, "compressor-enable"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "solo" + nstr, "solo"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "mute" + nstr, "mute"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "attack-threshold" + nstr, "attack-threshold"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "attack-time" + nstr, "attack-time"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "release-threshold" + nstr, "release-threshold"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "release-time" + nstr, "release-time"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "ratio" + nstr, "ratio"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "knee" + nstr, "knee"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "makeup" + nstr, "makeup"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "compression-mode" + nstr, "compression-mode"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "external-sidechain" + nstr, "external-sidechain"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-mode" + nstr, "sidechain-mode"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-source" + nstr, "sidechain-source"); update_key<gchar*>(json.at(section).at(instance_name).at(bandn), settings, "stereo-split-source" + nstr, "stereo-split-source"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-lookahead" + nstr, "sidechain-lookahead"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-reactivity" + nstr, "sidechain-reactivity"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-preamp" + nstr, "sidechain-preamp"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-custom-lowcut-filter" + nstr, "sidechain-custom-lowcut-filter"); update_key<bool>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-custom-highcut-filter" + nstr, "sidechain-custom-highcut-filter"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-lowcut-frequency" + nstr, "sidechain-lowcut-frequency"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "sidechain-highcut-frequency" + nstr, "sidechain-highcut-frequency"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "boost-threshold" + nstr, "boost-threshold"); update_key<double>(json.at(section).at(instance_name).at(bandn), settings, "boost-amount" + nstr, "boost-amount"); } }
10,811
C++
.cpp
158
60.892405
118
0.668935
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,704
echo_canceller_preset.cpp
wwmm_easyeffects/src/echo_canceller_preset.cpp
/* * 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/>. */ #include "echo_canceller_preset.hpp" #include <gio/gio.h> #include <nlohmann/json_fwd.hpp> #include "plugin_preset_base.hpp" #include "preset_type.hpp" #include "tags_plugin_name.hpp" #include "tags_schema.hpp" #include "util.hpp" EchoCancellerPreset::EchoCancellerPreset(PresetType preset_type, const int& index) : PluginPresetBase(tags::schema::echo_canceller::id, tags::schema::echo_canceller::input_path, tags::schema::echo_canceller::output_path, preset_type, index) { instance_name.assign(tags::plugin_name::echo_canceller).append("#").append(util::to_string(index)); } void EchoCancellerPreset::save(nlohmann::json& json) { json[section][instance_name]["bypass"] = g_settings_get_boolean(settings, "bypass") != 0; json[section][instance_name]["input-gain"] = g_settings_get_double(settings, "input-gain"); json[section][instance_name]["output-gain"] = g_settings_get_double(settings, "output-gain"); json[section][instance_name]["filter-length"] = g_settings_get_int(settings, "filter-length"); json[section][instance_name]["residual-echo-suppression"] = g_settings_get_int(settings, "residual-echo-suppression"); json[section][instance_name]["near-end-suppression"] = g_settings_get_int(settings, "near-end-suppression"); } void EchoCancellerPreset::load(const nlohmann::json& json) { update_key<bool>(json.at(section).at(instance_name), settings, "bypass", "bypass"); update_key<double>(json.at(section).at(instance_name), settings, "input-gain", "input-gain"); update_key<double>(json.at(section).at(instance_name), settings, "output-gain", "output-gain"); update_key<int>(json.at(section).at(instance_name), settings, "filter-length", "filter-length"); update_key<int>(json.at(section).at(instance_name), settings, "residual-echo-suppression", "residual-echo-suppression"); update_key<int>(json.at(section).at(instance_name), settings, "near-end-suppression", "near-end-suppression"); }
2,805
C++
.cpp
51
50.647059
120
0.717518
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,705
pitch_ui.cpp
wwmm_easyeffects/src/pitch_ui.cpp
/* * 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/>. */ #include "pitch_ui.hpp" #include <STTypes.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "pitch.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::pitch_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Pitch> pitch; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _PitchBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *semitones, *sequence_length, *seek_window, *overlap_length, *tempo_difference, *rate_difference; GtkSwitch *quick_seek, *anti_alias; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(PitchBox, pitch_box, GTK_TYPE_BOX) void on_reset(PitchBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(PitchBox* self, std::shared_ptr<Pitch> pitch, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->pitch = pitch; self->settings = g_settings_new_with_path(tags::schema::pitch::id, schema_path.c_str()); pitch->set_post_messages(true); self->data->connections.push_back(pitch->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(pitch->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->pitch->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); gsettings_bind_widgets<"quick-seek", "anti-alias", "sequence-length", "seek-window", "overlap-length", "tempo-difference", "rate-difference", "semitones">( self->settings, self->quick_seek, self->anti_alias, self->sequence_length, self->seek_window, self->overlap_length, self->tempo_difference, self->rate_difference, self->semitones); } void dispose(GObject* object) { auto* self = EE_PITCH_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(pitch_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_PITCH_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(pitch_box_parent_class)->finalize(object); } void pitch_box_class_init(PitchBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::pitch_ui); gtk_widget_class_bind_template_child(widget_class, PitchBox, input_gain); gtk_widget_class_bind_template_child(widget_class, PitchBox, output_gain); gtk_widget_class_bind_template_child(widget_class, PitchBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, PitchBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, PitchBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, PitchBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, PitchBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, PitchBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, PitchBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, PitchBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, PitchBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, PitchBox, quick_seek); gtk_widget_class_bind_template_child(widget_class, PitchBox, anti_alias); gtk_widget_class_bind_template_child(widget_class, PitchBox, sequence_length); gtk_widget_class_bind_template_child(widget_class, PitchBox, seek_window); gtk_widget_class_bind_template_child(widget_class, PitchBox, overlap_length); gtk_widget_class_bind_template_child(widget_class, PitchBox, tempo_difference); gtk_widget_class_bind_template_child(widget_class, PitchBox, rate_difference); gtk_widget_class_bind_template_child(widget_class, PitchBox, semitones); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void pitch_box_init(PitchBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbuttons<"ms">(self->sequence_length, self->seek_window, self->overlap_length); prepare_spinbuttons<"%">(self->tempo_difference, self->rate_difference); } auto create() -> PitchBox* { return static_cast<PitchBox*>(g_object_new(EE_TYPE_PITCH_BOX, nullptr)); } } // namespace ui::pitch_box
7,194
C++
.cpp
158
41.563291
114
0.718687
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,706
maximizer_ui.cpp
wwmm_easyeffects/src/maximizer_ui.cpp
/* * 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/>. */ #include "maximizer_ui.hpp" #include <STTypes.h> #define FMT_HEADER_ONLY #include <fmt/core.h> #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glibconfig.h> #include <gobject/gobject.h> #include <gtk/gtk.h> #include <sigc++/connection.h> #include <memory> #include <string> #include <vector> #include "maximizer.hpp" #include "tags_resources.hpp" #include "tags_schema.hpp" #include "ui_helpers.hpp" #include "util.hpp" namespace ui::maximizer_box { struct Data { public: ~Data() { util::debug("data struct destroyed"); } uint serial = 0U; std::shared_ptr<Maximizer> maximizer; std::vector<sigc::connection> connections; std::vector<gulong> gconnections; }; struct _MaximizerBox { GtkBox parent_instance; GtkScale *input_gain, *output_gain; GtkLevelBar *input_level_left, *input_level_right, *output_level_left, *output_level_right; GtkLabel *input_level_left_label, *input_level_right_label, *output_level_left_label, *output_level_right_label, *plugin_credit; GtkSpinButton *release, *threshold; GtkLevelBar* reduction_levelbar; GtkLabel* reduction_label; GSettings* settings; Data* data; }; // NOLINTNEXTLINE G_DEFINE_TYPE(MaximizerBox, maximizer_box, GTK_TYPE_BOX) void on_reset(MaximizerBox* self, GtkButton* btn) { util::reset_all_keys_except(self->settings); } void setup(MaximizerBox* self, std::shared_ptr<Maximizer> maximizer, const std::string& schema_path) { auto serial = get_new_filter_serial(); self->data->serial = serial; g_object_set_data(G_OBJECT(self), "serial", GUINT_TO_POINTER(serial)); set_ignore_filter_idle_add(serial, false); self->data->maximizer = maximizer; self->settings = g_settings_new_with_path(tags::schema::maximizer::id, schema_path.c_str()); maximizer->set_post_messages(true); self->data->connections.push_back(maximizer->input_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->input_level_left, self->input_level_left_label, self->input_level_right, self->input_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(maximizer->output_level.connect([=](const float left, const float right) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } update_level(self->output_level_left, self->output_level_left_label, self->output_level_right, self->output_level_right_label, left, right); }, [=]() { g_object_unref(self); }); })); self->data->connections.push_back(maximizer->reduction.connect([=](const double value) { g_object_ref(self); util::idle_add( [=]() { if (get_ignore_filter_idle_add(serial)) { return; } if (!GTK_IS_LEVEL_BAR(self->reduction_levelbar) || !GTK_IS_LABEL(self->reduction_label)) { return; } gtk_level_bar_set_value(self->reduction_levelbar, value); gtk_label_set_text(self->reduction_label, fmt::format("{0:.0f}", value).c_str()); }, [=]() { g_object_unref(self); }); })); gtk_label_set_text(self->plugin_credit, ui::get_plugin_credit_translated(self->data->maximizer->package).c_str()); gsettings_bind_widgets<"input-gain", "output-gain">(self->settings, self->input_gain, self->output_gain); g_settings_bind(self->settings, "release", gtk_spin_button_get_adjustment(self->release), "value", G_SETTINGS_BIND_DEFAULT); g_settings_bind(self->settings, "threshold", gtk_spin_button_get_adjustment(self->threshold), "value", G_SETTINGS_BIND_DEFAULT); } void dispose(GObject* object) { auto* self = EE_MAXIMIZER_BOX(object); set_ignore_filter_idle_add(self->data->serial, true); for (auto& c : self->data->connections) { c.disconnect(); } for (auto& handler_id : self->data->gconnections) { g_signal_handler_disconnect(self->settings, handler_id); } self->data->connections.clear(); self->data->gconnections.clear(); g_object_unref(self->settings); util::debug("disposed"); G_OBJECT_CLASS(maximizer_box_parent_class)->dispose(object); } void finalize(GObject* object) { auto* self = EE_MAXIMIZER_BOX(object); delete self->data; util::debug("finalized"); G_OBJECT_CLASS(maximizer_box_parent_class)->finalize(object); } void maximizer_box_class_init(MaximizerBoxClass* klass) { auto* object_class = G_OBJECT_CLASS(klass); auto* widget_class = GTK_WIDGET_CLASS(klass); object_class->dispose = dispose; object_class->finalize = finalize; gtk_widget_class_set_template_from_resource(widget_class, tags::resources::maximizer_ui); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, input_gain); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, output_gain); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, input_level_left); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, input_level_right); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, output_level_left); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, output_level_right); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, input_level_left_label); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, input_level_right_label); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, output_level_left_label); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, output_level_right_label); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, plugin_credit); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, release); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, threshold); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, reduction_levelbar); gtk_widget_class_bind_template_child(widget_class, MaximizerBox, reduction_label); gtk_widget_class_bind_template_callback(widget_class, on_reset); } void maximizer_box_init(MaximizerBox* self) { gtk_widget_init_template(GTK_WIDGET(self)); self->data = new Data(); prepare_scales<"dB">(self->input_gain, self->output_gain); prepare_spinbutton<"dB">(self->threshold); prepare_spinbuttons<"ms">(self->release); } auto create() -> MaximizerBox* { return static_cast<MaximizerBox*>(g_object_new(EE_TYPE_MAXIMIZER_BOX, nullptr)); } } // namespace ui::maximizer_box
7,495
C++
.cpp
172
39.151163
116
0.709366
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,707
filter.cpp
wwmm_easyeffects/src/filter.cpp
/* * 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/>. */ #include "filter.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Filter::Filter(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::filter, tags::plugin_package::lsp, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://lsp-plug.in/plugins/lv2/filter_stereo"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://lsp-plug.in/plugins/lv2/sc_gate_stereo is not installed"); } lv2_wrapper->bind_key_double<"f", "frequency">(settings); lv2_wrapper->bind_key_double<"w", "width">(settings); lv2_wrapper->bind_key_double<"q", "quality">(settings); lv2_wrapper->bind_key_double<"bal", "balance">(settings); lv2_wrapper->bind_key_double_db<"g", "gain">(settings); lv2_wrapper->bind_key_enum<"ft", "type">(settings); lv2_wrapper->bind_key_enum<"fm", "mode">(settings); lv2_wrapper->bind_key_enum<"mode", "equal-mode">(settings); lv2_wrapper->bind_key_enum<"s", "slope">(settings); setup_input_output_gain(); // g_timeout_add_seconds(1, GSourceFunc(+[](Filter* self) { // if (!self->lv2_wrapper->has_ui()) { // self->lv2_wrapper->load_ui(); // } else { // self->lv2_wrapper->notify_ui(); // self->lv2_wrapper->update_ui(); // } // return 1; // }), // this); } Filter::~Filter() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Filter::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Filter::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { notify(); } } } auto Filter::get_latency_seconds() -> float { return 0.0F; }
3,962
C++
.cpp
108
31.842593
98
0.605229
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,708
deesser.cpp
wwmm_easyeffects/src/deesser.cpp
/* * 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/>. */ #include "deesser.hpp" #include <algorithm> #include <memory> #include <span> #include <string> #include "lv2_wrapper.hpp" #include "pipe_manager.hpp" #include "plugin_base.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" Deesser::Deesser(const std::string& tag, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type) : PluginBase(tag, tags::plugin_name::deesser, tags::plugin_package::calf, schema, schema_path, pipe_manager, pipe_type) { lv2_wrapper = std::make_unique<lv2::Lv2Wrapper>("http://calf.sourceforge.net/plugins/Deesser"); package_installed = lv2_wrapper->found_plugin; if (!package_installed) { util::debug(log_tag + "http://calf.sourceforge.net/plugins/Deesser is not installed"); } lv2_wrapper->bind_key_enum<"mode", "mode">(settings); lv2_wrapper->bind_key_enum<"detection", "detection">(settings); lv2_wrapper->bind_key_double<"ratio", "ratio">(settings); lv2_wrapper->bind_key_double<"f1_freq", "f1-freq">(settings); lv2_wrapper->bind_key_double<"f2_freq", "f2-freq">(settings); lv2_wrapper->bind_key_double<"f2_q", "f2-q">(settings); lv2_wrapper->bind_key_double_db<"threshold", "threshold">(settings); lv2_wrapper->bind_key_double_db<"makeup", "makeup">(settings); lv2_wrapper->bind_key_double_db<"f1_level", "f1-level">(settings); lv2_wrapper->bind_key_double_db<"f2_level", "f2-level">(settings); lv2_wrapper->bind_key_int<"laxity", "laxity">(settings); lv2_wrapper->bind_key_bool<"sc_listen", "sc-listen">(settings); setup_input_output_gain(); } Deesser::~Deesser() { if (connected_to_pw) { disconnect_from_pw(); } util::debug(log_tag + name + " destroyed"); } void Deesser::setup() { if (!lv2_wrapper->found_plugin) { return; } lv2_wrapper->set_n_samples(n_samples); if (lv2_wrapper->get_rate() != rate) { lv2_wrapper->create_instance(rate); } } void Deesser::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!lv2_wrapper->found_plugin || !lv2_wrapper->has_instance() || bypass) { std::copy(left_in.begin(), left_in.end(), left_out.begin()); std::copy(right_in.begin(), right_in.end(), right_out.begin()); return; } if (input_gain != 1.0F) { apply_gain(left_in, right_in, input_gain); } lv2_wrapper->connect_data_ports(left_in, right_in, left_out, right_out); lv2_wrapper->run(); if (output_gain != 1.0F) { apply_gain(left_out, right_out, output_gain); } if (post_messages) { get_peaks(left_in, right_in, left_out, right_out); if (send_notifications) { // values needed as double for levelbars widget ui, so we convert them here detected_port_value = static_cast<double>(lv2_wrapper->get_control_port_value("detected")); compression_port_value = static_cast<double>(lv2_wrapper->get_control_port_value("compression")); detected.emit(detected_port_value); compression.emit(compression_port_value); notify(); } } } auto Deesser::get_latency_seconds() -> float { return 0.0F; }
4,122
C++
.cpp
106
33.679245
103
0.661813
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,709
plugin_base.cpp
wwmm_easyeffects/src/plugin_base.cpp
/* * 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/>. */ #include "plugin_base.hpp" #include <gio/gio.h> #include <glib-object.h> #include <glib.h> #include <glib/gi18n.h> #include <pipewire/filter.h> #include <pipewire/keys.h> #include <pipewire/loop.h> #include <pipewire/port.h> #include <pipewire/properties.h> #include <pipewire/thread-loop.h> #include <spa/node/io.h> #include <spa/param/latency-utils.h> #include <spa/param/latency.h> #include <spa/param/param.h> #include <spa/pod/builder.h> #include <spa/pod/pod.h> #include <spa/support/loop.h> #include <spa/utils/defs.h> #include <spa/utils/hook.h> #include <sys/types.h> #include <algorithm> #include <array> #include <chrono> #include <cstddef> #include <cstdint> #include <span> #include <string> #include <thread> #include <utility> #include "pipe_manager.hpp" #include "tags_app.hpp" #include "tags_plugin_name.hpp" #include "util.hpp" namespace { void on_process(void* userdata, spa_io_position* position) { auto* d = static_cast<PluginBase::data*>(userdata); const auto n_samples = position->clock.duration; const auto rate = position->clock.rate.denom; if (n_samples == 0 || rate == 0) { return; } if (rate != d->pb->rate || n_samples != d->pb->n_samples) { d->pb->rate = rate; d->pb->n_samples = n_samples; d->pb->dummy_left.resize(n_samples); d->pb->dummy_right.resize(n_samples); std::ranges::fill(d->pb->dummy_left, 0.0F); std::ranges::fill(d->pb->dummy_right, 0.0F); d->pb->clock_start = std::chrono::system_clock::now(); d->pb->setup(); } d->pb->delta_t = 0.001F * static_cast<float>(std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now() - d->pb->clock_start) .count()); d->pb->send_notifications = d->pb->delta_t >= d->pb->notification_time_window; // util::warning("processing: " + util::to_string(n_samples)); auto* in_left = static_cast<float*>(pw_filter_get_dsp_buffer(d->in_left, n_samples)); auto* in_right = static_cast<float*>(pw_filter_get_dsp_buffer(d->in_right, n_samples)); auto* out_left = static_cast<float*>(pw_filter_get_dsp_buffer(d->out_left, n_samples)); auto* out_right = static_cast<float*>(pw_filter_get_dsp_buffer(d->out_right, n_samples)); std::span<float> left_in; std::span<float> right_in; std::span<float> left_out; std::span<float> right_out; if (in_left != nullptr) { left_in = std::span(in_left, n_samples); } else { left_in = d->pb->dummy_left; } if (in_right != nullptr) { right_in = std::span(in_right, n_samples); } else { right_in = d->pb->dummy_right; } if (out_left != nullptr) { left_out = std::span(out_left, n_samples); } else { left_out = d->pb->dummy_left; } if (out_right != nullptr) { right_out = std::span(out_right, n_samples); } else { right_out = d->pb->dummy_right; } if (!d->pb->enable_probe) { d->pb->process(left_in, right_in, left_out, right_out); } else { auto* probe_left = static_cast<float*>(pw_filter_get_dsp_buffer(d->probe_left, n_samples)); auto* probe_right = static_cast<float*>(pw_filter_get_dsp_buffer(d->probe_right, n_samples)); if (probe_left == nullptr || probe_right == nullptr) { std::span l(d->pb->dummy_left.data(), n_samples); std::span r(d->pb->dummy_right.data(), n_samples); d->pb->process(left_in, right_in, left_out, right_out, l, r); } else { std::span l(probe_left, n_samples); std::span r(probe_right, n_samples); d->pb->process(left_in, right_in, left_out, right_out, l, r); } } if (d->pb->send_notifications) { d->pb->clock_start = std::chrono::system_clock::now(); d->pb->send_notifications = false; } } auto update_filter(struct spa_loop* loop, bool async, uint32_t seq, const void* data, size_t size, void* user_data) -> int { auto* self = static_cast<PluginBase*>(user_data); spa_process_latency_info latency_info{}; latency_info.ns = static_cast<uint64_t>(self->latency_value * 1000000000.0F); std::array<char, 1024U> buffer{}; spa_pod_builder b{}; spa_pod_builder_init(&b, buffer.data(), sizeof(buffer)); const spa_pod* param = spa_process_latency_build(&b, SPA_PARAM_ProcessLatency, &latency_info); pw_filter_update_params(self->filter, nullptr, &param, 1); return 0; } void on_filter_state_changed(void* userdata, pw_filter_state old, pw_filter_state state, const char* error) { auto* d = static_cast<PluginBase::data*>(userdata); d->pb->state = state; switch (state) { case PW_FILTER_STATE_ERROR: d->pb->can_get_node_id = false; break; case PW_FILTER_STATE_UNCONNECTED: d->pb->can_get_node_id = false; break; case PW_FILTER_STATE_CONNECTING: d->pb->can_get_node_id = false; break; case PW_FILTER_STATE_STREAMING: d->pb->can_get_node_id = true; break; case PW_FILTER_STATE_PAUSED: d->pb->can_get_node_id = true; break; default: break; } } const struct pw_filter_events filter_events = {.state_changed = on_filter_state_changed, .process = on_process}; } // namespace PluginBase::PluginBase(std::string tag, std::string plugin_name, std::string package, const std::string& schema, const std::string& schema_path, PipeManager* pipe_manager, PipelineType pipe_type, const bool& enable_probe) : log_tag(std::move(tag)), name(std::move(plugin_name)), package(std::move(package)), pipeline_type(pipe_type), enable_probe(enable_probe), settings(g_settings_new_with_path(schema.c_str(), schema_path.c_str())), global_settings(g_settings_new(tags::app::id)), pm(pipe_manager) { std::string description; if (name != "output_level" && name != "spectrum") { description = tags::plugin_name::get_translated()[name]; bypass = g_settings_get_boolean(settings, "bypass") != 0; gconnections.push_back(g_signal_connect(settings, "changed::bypass", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<PluginBase*>(user_data); self->bypass = g_settings_get_boolean(settings, "bypass") != 0; }), this)); } else if (name == "output_level") { description = _("Output Level Meter"); } else if (name == "spectrum") { description = _("Spectrum"); } pf_data.pb = this; const auto filter_name = "ee_" + log_tag.substr(0U, log_tag.size() - 2U) + "_" + name; pm->lock(); auto* props_filter = pw_properties_new(nullptr, nullptr); pw_properties_set(props_filter, PW_KEY_APP_ID, tags::app::id); pw_properties_set(props_filter, PW_KEY_NODE_NAME, filter_name.c_str()); pw_properties_set(props_filter, PW_KEY_NODE_NICK, name.c_str()); pw_properties_set(props_filter, PW_KEY_NODE_DESCRIPTION, description.c_str()); pw_properties_set(props_filter, PW_KEY_MEDIA_TYPE, "Audio"); pw_properties_set(props_filter, PW_KEY_MEDIA_CATEGORY, "Filter"); pw_properties_set(props_filter, PW_KEY_MEDIA_ROLE, "DSP"); pw_properties_set(props_filter, PW_KEY_NODE_PASSIVE, "true"); filter = pw_filter_new(pm->core, filter_name.c_str(), props_filter); // left channel input auto* props_in_left = pw_properties_new(nullptr, nullptr); pw_properties_set(props_in_left, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_in_left, PW_KEY_PORT_NAME, "input_FL"); pw_properties_set(props_in_left, "audio.channel", "FL"); pf_data.in_left = static_cast<port*>(pw_filter_add_port(filter, PW_DIRECTION_INPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_in_left, nullptr, 0)); // right channel input auto* props_in_right = pw_properties_new(nullptr, nullptr); pw_properties_set(props_in_right, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_in_right, PW_KEY_PORT_NAME, "input_FR"); pw_properties_set(props_in_right, "audio.channel", "FR"); pf_data.in_right = static_cast<port*>(pw_filter_add_port(filter, PW_DIRECTION_INPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_in_right, nullptr, 0)); // left channel output auto* props_out_left = pw_properties_new(nullptr, nullptr); pw_properties_set(props_out_left, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_out_left, PW_KEY_PORT_NAME, "output_FL"); pw_properties_set(props_out_left, "audio.channel", "FL"); pf_data.out_left = static_cast<port*>(pw_filter_add_port(filter, PW_DIRECTION_OUTPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_out_left, nullptr, 0)); // right channel output auto* props_out_right = pw_properties_new(nullptr, nullptr); pw_properties_set(props_out_right, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_out_right, PW_KEY_PORT_NAME, "output_FR"); pw_properties_set(props_out_right, "audio.channel", "FR"); pf_data.out_right = static_cast<port*>(pw_filter_add_port( filter, PW_DIRECTION_OUTPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_out_right, nullptr, 0)); if (enable_probe) { n_ports += 2; // probe left input auto* props_left = pw_properties_new(nullptr, nullptr); pw_properties_set(props_left, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_left, PW_KEY_PORT_NAME, "probe_FL"); pw_properties_set(props_left, "audio.channel", "PROBE_FL"); pf_data.probe_left = static_cast<port*>(pw_filter_add_port( filter, PW_DIRECTION_INPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_left, nullptr, 0)); // probe right input auto* props_right = pw_properties_new(nullptr, nullptr); pw_properties_set(props_right, PW_KEY_FORMAT_DSP, "32 bit float mono audio"); pw_properties_set(props_right, PW_KEY_PORT_NAME, "probe_FR"); pw_properties_set(props_right, "audio.channel", "PROBE_FR"); pf_data.probe_right = static_cast<port*>(pw_filter_add_port( filter, PW_DIRECTION_INPUT, PW_FILTER_PORT_FLAG_MAP_BUFFERS, sizeof(port), props_right, nullptr, 0)); } pm->sync_wait_unlock(); } PluginBase::~PluginBase() { post_messages = false; pm->lock(); if (listener.link.next != nullptr || listener.link.prev != nullptr) { spa_hook_remove(&listener); } pw_filter_destroy(filter); pm->sync_wait_unlock(); for (auto& handler_id : gconnections) { g_signal_handler_disconnect(settings, handler_id); } gconnections.clear(); g_object_unref(settings); } void PluginBase::set_post_messages(const bool& state) { post_messages = state; } void PluginBase::reset_settings() { util::reset_all_keys_except(settings); } auto PluginBase::connect_to_pw() -> bool { connected_to_pw = false; can_get_node_id = false; state = PW_FILTER_STATE_UNCONNECTED; pm->lock(); if (pw_filter_connect(filter, PW_FILTER_FLAG_RT_PROCESS, nullptr, 0) != 0) { pm->unlock(); util::warning(log_tag + name + " cannot connect the filter to PipeWire!"); return false; } initialize_listener(); pm->sync_wait_unlock(); while (!can_get_node_id) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); if (state == PW_FILTER_STATE_ERROR) { util::warning(log_tag + name + " is in an error"); return false; } } pm->lock(); node_id = pw_filter_get_node_id(filter); pm->sync_wait_unlock(); /* The filter we link in our pipeline have at least 4 ports. Some have six. Before we try to link filters we have to wait until the information about their ports is available in PipeManager's list_ports vector. */ while (pm->count_node_ports(node_id) != n_ports) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); } connected_to_pw = true; util::debug(log_tag + name + " successfully connected to PipeWire graph"); return true; } void PluginBase::initialize_listener() { pw_filter_add_listener(filter, &listener, &filter_events, &pf_data); } auto PluginBase::get_node_id() const -> uint { return node_id; } void PluginBase::set_active(const bool& state) const { pw_filter_set_active(filter, state); } void PluginBase::disconnect_from_pw() { pm->lock(); set_active(false); // NOLINTNEXTLINE(clang-analyzer-core.NullDereference) if (listener.link.next != nullptr || listener.link.prev != nullptr) { spa_hook_remove(&listener); } pw_filter_disconnect(filter); connected_to_pw = false; pm->sync_wait_unlock(); node_id = SPA_ID_INVALID; } void PluginBase::setup() {} void PluginBase::process(std::span<float>& left_in, std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) {} void PluginBase::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) {} auto PluginBase::get_latency_seconds() -> float { return 0.0F; } void PluginBase::show_native_ui() { if (lv2_wrapper == nullptr) { return; } if (!lv2_wrapper->has_ui()) { lv2_wrapper->load_ui(); } } void PluginBase::close_native_ui() { if (lv2_wrapper == nullptr) { return; } lv2_wrapper->native_ui_to_gsettings(); lv2_wrapper->close_ui(); } void PluginBase::set_native_ui_update_frequency(const uint& value) { if (lv2_wrapper == nullptr) { return; } lv2_wrapper->set_ui_update_rate(value); } void PluginBase::get_peaks(const std::span<float>& left_in, const std::span<float>& right_in, std::span<float>& left_out, std::span<float>& right_out) { if (!post_messages) { return; } // input level float peak_l = std::ranges::max(left_in); float peak_r = std::ranges::max(right_in); input_peak_left = (peak_l > input_peak_left) ? peak_l : input_peak_left; input_peak_right = (peak_r > input_peak_right) ? peak_r : input_peak_right; // output level peak_l = std::ranges::max(left_out); peak_r = std::ranges::max(right_out); output_peak_left = (peak_l > output_peak_left) ? peak_l : output_peak_left; output_peak_right = (peak_r > output_peak_right) ? peak_r : output_peak_right; } void PluginBase::setup_input_output_gain() { input_gain = static_cast<float>(util::db_to_linear(g_settings_get_double(settings, "input-gain"))); output_gain = static_cast<float>(util::db_to_linear(g_settings_get_double(settings, "output-gain"))); g_signal_connect(settings, "changed::input-gain", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<PluginBase*>(user_data); self->input_gain = util::db_to_linear(g_settings_get_double(settings, key)); }), this); g_signal_connect(settings, "changed::output-gain", G_CALLBACK(+[](GSettings* settings, char* key, gpointer user_data) { auto* self = static_cast<PluginBase*>(user_data); self->output_gain = util::db_to_linear(g_settings_get_double(settings, key)); }), this); } void PluginBase::apply_gain(std::span<float>& left, std::span<float>& right, const float& gain) { if (left.empty() || right.empty()) { return; } std::ranges::for_each(left, [&](auto& v) { v *= gain; }); std::ranges::for_each(right, [&](auto& v) { v *= gain; }); } void PluginBase::notify() { const auto input_peak_db_l = util::linear_to_db(input_peak_left); const auto input_peak_db_r = util::linear_to_db(input_peak_right); const auto output_peak_db_l = util::linear_to_db(output_peak_left); const auto output_peak_db_r = util::linear_to_db(output_peak_right); input_level.emit(input_peak_db_l, input_peak_db_r); output_level.emit(output_peak_db_l, output_peak_db_r); input_peak_left = util::minimum_linear_level; input_peak_right = util::minimum_linear_level; output_peak_left = util::minimum_linear_level; output_peak_right = util::minimum_linear_level; } void PluginBase::update_probe_links() {} void PluginBase::update_filter_params() { pw_loop_invoke(pw_thread_loop_get_loop(pm->thread_loop), update_filter, 1, nullptr, 0, false, this); }
17,714
C++
.cpp
416
36.536058
120
0.643619
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