From 61c9951dae64e79cbc1983098b5fd52317578103 Mon Sep 17 00:00:00 2001 From: Benjamin Barenblat Date: Thu, 27 Jan 2022 11:10:37 -0500 Subject: pavmon, a simple tool to monitor the volume of a PulseAudio sink --- .gitignore | 17 +++ LICENSE | 202 ++++++++++++++++++++++++++++++++++ build.ninja | 35 ++++++ pavmon.cc | 184 +++++++++++++++++++++++++++++++ pulse.cc | 360 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pulse.h | 242 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 1040 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 build.ninja create mode 100644 pavmon.cc create mode 100644 pulse.cc create mode 100644 pulse.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d64805a --- /dev/null +++ b/.gitignore @@ -0,0 +1,17 @@ +# Copyright 2022 Benjamin Barenblat +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +.ninja_* +*.o +pavmon diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/build.ninja b/build.ninja new file mode 100644 index 0000000..7824f0b --- /dev/null +++ b/build.ninja @@ -0,0 +1,35 @@ +# Copyright 2022 Benjamin Barenblat +# +# Licensed under the Apache License, Version 2.0 (the "License"); you may not +# use this file except in compliance with the License. You may obtain a copy of +# the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +# License for the specific language governing permissions and limitations under +# the License. + +ninja_required_version = 1.3 + +rule cxx + command = g++ -MD -MT $out -MF $out.d -pipe -std=c++20 -fno-rtti -Wall $ + -Wextra -Wno-sign-compare -fdiagnostics-show-template-tree -O3 -flto $ + -fstack-protector-strong -Wformat -Werror=format-security $ + -D_FORTIFY_SOURCE=2 -DNDEBUG -D_REENTRANT -ffunction-sections $ + -fdata-sections -c $in -o $out + description = Compiling $out + depfile = $out.d + deps = gcc + +rule link + command = g++ -fuse-ld=gold -flto -Wl,-O2 -Wl,--gc-sections -Wl,--as-needed $ + -Wl,-z,relro -Wl,-z,now -o $out $in $libs && strip $out + description = Linking $out + +build pavmon.o: cxx pavmon.cc +build pulse.o: cxx pulse.cc +build pavmon: link pavmon.o pulse.o + libs = -lpulse diff --git a/pavmon.cc b/pavmon.cc new file mode 100644 index 0000000..df639e4 --- /dev/null +++ b/pavmon.cc @@ -0,0 +1,184 @@ +// Copyright 2022 Benjamin Barenblat +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "pulse.h" + +namespace { + +constexpr std::string_view kShortUsage = "Usage: pavmon SINK_NAME\n"; + +constexpr std::string_view kHelp = R"( +Monitor the volume level of a PulseAudio sink, printing a new line each time it +changes. + +Options: + --help display this help and exit + --version display version information and exit +)"; + +constexpr std::string_view kAskForHelp = + "Try \"pavmon --help\" for more information.\n"; + +constexpr std::string_view kVersionInfo = R"(pavmon 1.0.0 +Copyright 2022 Benjamin Barenblat +Licensed under the Apache License, Version 2.0 +)"; + +enum { + kHelpLongOption = 128, + kVersionLongOption, +}; + +void GetAndPrintVolume(const std::string& sink_name, pulse::PollMainLoop& loop, + pulse::Context& ctx) noexcept { + ctx.GetSinkInfo( + sink_name.c_str(), + [&]() noexcept { + std::clog << "pavmon: failed to get volume" << std::endl; + loop.Quit(1); + }, + [&](const pa_sink_info& info) noexcept { + if (info.mute) { + std::cout << "muted ("; + } + std::cout << std::fixed << std::setprecision(1) + << pa_sw_volume_to_dB(pa_cvolume_avg(&info.volume)) << " dB"; + if (info.mute) { + std::cout << ')'; + } + std::cout << std::endl; + }); +} + +void SubscribeToEvents(const std::string& sink_name, pulse::PollMainLoop& loop, + pulse::Context& ctx) noexcept { + ctx.Subscribe( + PA_SUBSCRIPTION_MASK_SINK, + [&]() noexcept { + std::clog << "pavmon: failed to subscribe to events" << std::endl; + loop.Quit(1); + }, + [&](pa_subscription_event_type_t) noexcept { + GetAndPrintVolume(sink_name, loop, ctx); + }); +} + +} // namespace + +int main(int argc, char* argv[]) { + std::locale loc(""); + std::locale::global(loc); + std::cin.imbue(loc); + std::cout.imbue(loc); + std::cerr.imbue(loc); + std::clog.imbue(loc); + std::wcin.imbue(loc); + std::wcout.imbue(loc); + std::wcerr.imbue(loc); + std::wclog.imbue(loc); + + std::ios_base::sync_with_stdio(false); + + static option long_options[] = { + {"help", no_argument, nullptr, kHelpLongOption}, + {"version", no_argument, nullptr, kVersionLongOption}, + {nullptr, 0, nullptr, 0}, + }; + while (true) { + int c = getopt_long(argc, argv, "", long_options, /*longindex=*/nullptr); + if (c == -1) { + break; + } + switch (c) { + case kHelpLongOption: + std::cout << kShortUsage << kHelp; + return 0; + case kVersionLongOption: + std::cout << kVersionInfo; + return 0; + case '?': + std::clog << kAskForHelp; + return 1; + default: + std::clog << "Internal error; please report.\n"; + return 1; + } + } + if (optind != argc - 1) { + std::clog << kShortUsage << kAskForHelp; + return 1; + } + + std::string sink_name = argv[1]; + + pulse::PollMainLoop loop; + + loop.HandleSignals(); + auto quit_on_signal = [&]() noexcept { loop.Quit(0); }; + pulse::SignalEventSource quit_on_sigterm(SIGTERM, quit_on_signal); + pulse::SignalEventSource quit_on_sigint(SIGINT, quit_on_signal); + + pulse::PropertyList proplist; + proplist.Set(PA_PROP_APPLICATION_NAME, "PulseAudio volume monitor"); + proplist.Set(PA_PROP_APPLICATION_ID, "pavmon"); + proplist.Set(PA_PROP_APPLICATION_VERSION, "1.0.0"); + proplist.Set(PA_PROP_APPLICATION_PROCESS_ID, std::to_string(getpid())); + if (const char* user = getlogin(); user != nullptr) { + proplist.Set(PA_PROP_APPLICATION_PROCESS_USER, user); + } + // TODO(bbarenblat@gmail.com): More of these? + + pulse::Context ctx("PulseAudio volume meter", proplist, loop); + ctx.Connect(PA_CONTEXT_NOFAIL, [&](pa_context_state_t state) noexcept { + switch (state) { + case PA_CONTEXT_UNCONNECTED: + case PA_CONTEXT_CONNECTING: + case PA_CONTEXT_AUTHORIZING: + case PA_CONTEXT_SETTING_NAME: + break; + + case PA_CONTEXT_READY: + GetAndPrintVolume(sink_name, loop, ctx); + SubscribeToEvents(sink_name, loop, ctx); + break; + + case PA_CONTEXT_TERMINATED: + loop.Quit(0); + break; + + case PA_CONTEXT_FAILED: + default: + std::clog << "pavmon: failed to connect to PulseAudio" << std::endl; + loop.Quit(1); + break; + } + }); + + return loop.Run(); +} diff --git a/pulse.cc b/pulse.cc new file mode 100644 index 0000000..ebe72b9 --- /dev/null +++ b/pulse.cc @@ -0,0 +1,360 @@ +// Copyright 2022 Benjamin Barenblat +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +#include "pulse.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace pulse { + +// Adapters for libpulse callbacks. +// +// libpulse presents a callback-driven C API--callbacks must be C function +// pointers, and each callback can be passed a user-controlled void*. This isn't +// a great API for a C++ library, though, so this library accepts std::functions +// and pass them by pointer to statically defined callbacks. +// +// Even though these functions are defined in an anonymous namespace, the extern +// "C" means they need "static" to get the desired internal linkage. + +namespace { + +using SignalCallback = std::function; + +extern "C" { + +static void CallSignalCallback(pa_mainloop_api*, pa_signal_event*, + int /*signal*/, void* real_callback) noexcept { + assert(real_callback != nullptr); + (*reinterpret_cast(real_callback))(); +} + +static void DeleteSignalCallback(pa_mainloop_api*, pa_signal_event*, + void* real_callback) noexcept { + assert(real_callback != nullptr); + delete reinterpret_cast(real_callback); +} + +} // extern "C" + +using ContextNotifyCallback = std::function; + +extern "C" { + +static void CallContextNotifyCallback(pa_context* ctx, + void* real_callback) noexcept { + assert(real_callback != nullptr); + (*reinterpret_cast(real_callback))( + pa_context_get_state(ctx)); +} + +} // extern "C" + +struct SinkInfoCallbacks { + std::function on_failure; + std::function on_data; +}; + +extern "C" { + +static void CallOrDeleteSinkInfoCallbacks(pa_context*, const pa_sink_info* info, + int status, + void* real_callbacks) noexcept { + assert(real_callbacks != nullptr); + auto* sink_info_callbacks = + reinterpret_cast(real_callbacks); + + if (status == 0) { + // The RPC succeeded, and info contains sink information. Tell the user. + assert(info != nullptr); + sink_info_callbacks->on_data(*info); + } else { + // No sink information came through... + if (status < 0) { + // ...because of an error. Tell the user. + sink_info_callbacks->on_failure(); + } else { + // ...because no more data is available from the PulseAudio server. The + // user doesn't need to hear about that. + } + + // In any case, no more data are coming, so don't hang onto the callbacks + // anymore. + delete sink_info_callbacks; + } +} + +} // extern "C" + +struct RpcResultCallbacks { + std::function on_failure; + std::function on_success; +}; + +extern "C" { + +static void CallAndDeleteRpcResultCallbacks(pa_context*, int success, + void* real_callbacks) noexcept { + assert(real_callbacks != nullptr); + auto* rpc_result_callbacks = + reinterpret_cast(real_callbacks); + if (success) { + rpc_result_callbacks->on_success(); + } else { + rpc_result_callbacks->on_failure(); + } + delete rpc_result_callbacks; +} + +} // extern "C" + +using SubscribeCallback = std::function; + +extern "C" { + +static void CallSubscribeCallback(pa_context*, + pa_subscription_event_type_t type, + uint32_t /*index*/, + void* real_callback) noexcept { + assert(real_callback != nullptr); + (*reinterpret_cast(real_callback))(type); +} + +} // extern "C" + +} // namespace + +PropertyList::PropertyList() : list_(pa_proplist_new()) { + if (list_ == nullptr) { + throw Error::InFunction("pa_proplist_new"); + } +} + +PropertyList::PropertyList(const PropertyList& other) + : list_(pa_proplist_copy(other.list_)) { + if (list_ == nullptr) { + throw Error::InFunction("pa_proplist_copy"); + } +} + +PropertyList& PropertyList::operator=(const PropertyList& other) { + if (this != &other) { + PropertyList other2(other); + swap(*this, other2); + } + return *this; +} + +PropertyList::~PropertyList() noexcept { + if (list_ != nullptr) { + pa_proplist_free(list_); + } +} + +void PropertyList::Set(const char key[], std::string_view value) { + if (pa_proplist_set(list_, key, value.data(), value.size())) { + throw Error::InFunction("pa_proplist_set"); + } +} + +PollMainLoop::PollMainLoop() + : loop_(pa_mainloop_new()), handling_signals_(false) { + if (loop_ == nullptr) { + throw Error::InFunction("pa_mainloop_new"); + } + api_ = pa_mainloop_get_api(loop_); +} + +PollMainLoop::~PollMainLoop() noexcept { + if (handling_signals_) { + StopHandlingSignals(); + } + if (loop_ != nullptr) { + pa_mainloop_free(loop_); + } +} + +void PollMainLoop::HandleSignals() { + if (pa_signal_init(api_)) { + throw Error::InFunction("pa_signal_init"); + } + handling_signals_ = true; +} + +int PollMainLoop::Run() { + int r; + if (pa_mainloop_run(loop_, &r) < 0) { + throw Error::InFunction("pa_mainloop_run"); + } + return r; +} + +SignalEventSource::SignalEventSource(int signal, + std::function real_callback) { + // Construct source_ using CallSignalCallback as the C callback and + // real_callback as the real callback. real_callback is going to get passed by + // pointer, so that address needs to continue to point to real_callback until + // pa_signal_free. Happily, libpulse provides a mechanism to run an arbitrary + // callback during pa_signal_free, so move the callback onto the heap and + // delete it during pa_signal_free. This function is still responsible for + // deleting it if pa_signal_new fails, though, so stash it inside a unique_ptr + // and release the unique_ptr if pa_signal_new succeeds. + auto heap_callback = + std::make_unique(std::move(real_callback)); + source_ = pa_signal_new(signal, &CallSignalCallback, heap_callback.get()); + if (source_ == nullptr) { + throw Error::InFunction("pa_signal_new"); + } + pa_signal_set_destroy(source_, &DeleteSignalCallback); + heap_callback.release(); +} + +SignalEventSource::~SignalEventSource() noexcept { + if (source_ != nullptr) { + pa_signal_free(source_); + } +} + +Context::Context(const char application_name[], PropertyList& proplist, + PollMainLoop& loop) + : ctx_(pa_context_new_with_proplist(pa_mainloop_get_api(loop.get()), + application_name, proplist.get())) { + if (ctx_ == nullptr) { + throw Error::InFunction("pa_context_new_with_proplist"); + } +} + +Context::~Context() noexcept { + if (state_callback_ != nullptr) { + Disconnect(); + } + if (ctx_ != nullptr) { + pa_context_unref(ctx_); + } +} + +void Context::Connect( + pa_context_flags_t flags, + std::function on_state_change) noexcept { + // Set Up CallContextNotifyCallback to call on_state_change. on_state_change + // is going to get passed by pointer, so its address needs to continue to + // point to on_state_change until pa_context_disconnect. Saving the callback + // as a member ensures it stays alive long enough, but it doesn't ensure + // pointer stability; to get that, save it on the heap and keep a unique_ptr + // to it as a member. + state_callback_ = + std::make_unique(std::move(on_state_change)); + pa_context_set_state_callback(ctx_, &CallContextNotifyCallback, + state_callback_.get()); + if (pa_context_connect(ctx_, /*server=*/nullptr, flags, + /*spawn_api=*/nullptr)) { + // The RPC never even went out. libpulse won't call the callback in this + // case, so do it manually. + (*state_callback_)(PA_CONTEXT_FAILED); + + // The callback will never be called again at this point, and hanging onto + // it could cause resource leakage (e.g., if it captured a std::shared_ptr). + // Get rid of it. + state_callback_ = nullptr; + } +} + +void Context::GetSinkInfo( + const char name[], std::function on_failure, + std::function on_data) const noexcept { + // Set up CallOrDeleteSinkInfoCallbacks to call on_failure or on_data as + // appropriate. These callbacks are going to get passed by pointer, so they + // need to live on the heap. If constructing the get_sink_info_by_name RPC + // fails, though, libpulse won't call on_failure; to allow calling it + // manually, stash the callbacks inside a unique_ptr and release the + // unique_ptr if the RPC actually gets dispatched. + auto callbacks = std::make_unique(); + callbacks->on_failure = std::move(on_failure); + callbacks->on_data = std::move(on_data); + pa_operation* op = pa_context_get_sink_info_by_name( + ctx_, name, &CallOrDeleteSinkInfoCallbacks, callbacks.get()); + if (op == nullptr) { + // The RPC never even went out. libpulse won't call on_failure in this case, + // so do it manually. + callbacks->on_failure(); + } else { + pa_operation_unref(op); // The RPC handle is no longer needed. + + // The RPC is running, which means CallOrDeleteSinkInfoCallbacks will be + // called. (In fact, it's possible that CallOrDeleteSinkInfoCallbacks has + // already been called and the callbacks struct has already been deleted!) + // Stop managing the callbacks struct. + callbacks.release(); + } +} + +void Context::Subscribe( + pa_subscription_mask_t desired_events, std::function on_failure, + std::function on_event) const noexcept { + // Set up CallSubscribeCallback to call on_event. This callback is going to + // get passed by pointer, so its address needs to continue to point to + // on_event until pa_context_disconnect. Saving the callback as a member + // ensures it stays alive long enough, but it doesn't ensure pointer + // stability; to get that, save it on the heap and keep a unique_ptr to it as + // a member. + subscribe_callback_ = + std::make_unique(std::move(on_event)); + pa_context_set_subscribe_callback(ctx_, &CallSubscribeCallback, + subscribe_callback_.get()); + + // Set up CallAndDeleteRpcResultCallbacks to handle the result of the + // subscribe RPC. The real callbacks struct is going to get passed by pointer, + // so it needs to live on the heap. If constructing the subscribe RPC fails, + // though, libpulse won't call on_failure; to allow calling it manually, stash + // the callbacks inside a unique_ptr and release the unique_ptr if the RPC + // actually gets dispatched. + auto subscribe_completion_callbacks = std::make_unique(); + subscribe_completion_callbacks->on_failure = std::move(on_failure); + // We don't need to tell the user the RPC succeded; the event callback can + // tell them that. + subscribe_completion_callbacks->on_success = []() noexcept {}; + pa_operation* op = pa_context_subscribe(ctx_, desired_events, + &CallAndDeleteRpcResultCallbacks, + subscribe_completion_callbacks.get()); + if (op == nullptr) { + // The RPC never even went out. libpulse won't call + // CallAndDeleteRpcResultCallbacks in this case, call on_failure manually. + subscribe_completion_callbacks->on_failure(); + } else { + pa_operation_unref(op); // The RPC handle is no longer needed. + + // The RPC is running, which means CallAndDeleteRpcResultCallbacks will be + // called. (In fact, it's possible that CallAndDeleteRpcResultCallbacks has + // already been called and the result callbacks struct has already been + // deleted!) Stop managing the result callbacks struct. + subscribe_completion_callbacks.release(); + } +} + +} // namespace pulse diff --git a/pulse.h b/pulse.h new file mode 100644 index 0000000..e71e5f2 --- /dev/null +++ b/pulse.h @@ -0,0 +1,242 @@ +// Copyright 2022 Benjamin Barenblat +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may not +// use this file except in compliance with the License. You may obtain a copy of +// the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations under +// the License. + +// An idiomatic C++ interface to (parts of) PulseAudio. + +#ifndef PAVMON_PULSE_H_ +#define PAVMON_PULSE_H_ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace pulse { + +// The base exception type for all exceptions thrown by this library. +class Error final : public std::exception { + public: + static Error InFunction(std::string function_name) noexcept { + return Error(function_name + " failed"); + } + + explicit Error(std::string what) noexcept : what_(std::move(what)) {} + + Error(const Error&) = default; + Error& operator=(const Error&) = default; + Error(Error&&) noexcept = default; + Error& operator=(Error&&) noexcept = default; + + const char* what() const noexcept override { return what_.c_str(); } + + private: + std::string what_; +}; + +// A simple key-value store. +// +// This class is thread-compatible. +class PropertyList final { + public: + explicit PropertyList(); + + PropertyList(const PropertyList&); + + PropertyList& operator=(const PropertyList& other); + + PropertyList(PropertyList&& other) noexcept : list_(nullptr) { + *this = std::move(other); + } + + PropertyList& operator=(PropertyList&& other) noexcept { + swap(*this, other); + return *this; + } + + ~PropertyList() noexcept; + + // Adds or overwrites a mapping. Useful keys are #defined in + // . + void Set(const char key[], std::string_view value); + + pa_proplist* get() noexcept { return list_; } + + friend void swap(PropertyList& left, PropertyList& right) noexcept { + using ::std::swap; + swap(left.list_, right.list_); + } + + private: + pa_proplist* list_; +}; + +// A main event loop implementation based on poll(2). +// +// This class is thread-compatible. +class PollMainLoop final { + public: + explicit PollMainLoop(); + + PollMainLoop(PollMainLoop&& other) noexcept + : loop_(nullptr), api_(nullptr), handling_signals_(false) { + *this = std::move(other); + } + + PollMainLoop& operator=(PollMainLoop&& other) noexcept { + swap(*this, other); + return *this; + } + + ~PollMainLoop() noexcept; + + // Configures process signals to be delivered to the event loop. + void HandleSignals(); + + // Undoes a HandleSignals call. + void StopHandlingSignals() noexcept { + pa_signal_done(); + handling_signals_ = false; + } + + // Runs the main loop. This function does not return until somebody invokes + // Quit or an error occurs; it returns the argument to Quit. + int Run(); + + // Instructs the main loop to stop and return the specified code. + void Quit(int retval) noexcept { api_->quit(api_, retval); } + + pa_mainloop* get() noexcept { return loop_; } + + friend void swap(PollMainLoop& left, PollMainLoop& right) noexcept { + using ::std::swap; + swap(left.loop_, right.loop_); + swap(left.api_, right.api_); + swap(left.handling_signals_, right.handling_signals_); + } + + private: + pa_mainloop* loop_; + pa_mainloop_api* api_; + + bool handling_signals_; +}; + +// An RAII object to control signal handling in the event loop. Call +// HandleSignals() on the event loop and then create one of these for each +// signal you'd like to handle. +// +// This class is thread-compatible. +class SignalEventSource final { + public: + // Starts handling a particular signal. Calls the specified callback whenever + // that signal is received. + explicit SignalEventSource(int signal, std::function); + + SignalEventSource(SignalEventSource&& other) noexcept : source_(nullptr) { + *this = std::move(other); + } + + SignalEventSource& operator=(SignalEventSource&& other) noexcept { + swap(*this, other); + return *this; + } + + ~SignalEventSource() noexcept; + + friend void swap(SignalEventSource& left, SignalEventSource& right) noexcept { + using ::std::swap; + swap(left.source_, right.source_); + } + + private: + pa_signal_event* source_; +}; + +// A connection to a PulseAudio server. +// +// This class is thread-compatible. +class Context final { + public: + explicit Context(const char application_name[], PropertyList&, PollMainLoop&); + + Context(Context&& other) noexcept : ctx_(nullptr) { + *this = std::move(other); + } + + Context& operator=(Context&& other) noexcept { + swap(*this, other); + return *this; + } + + ~Context() noexcept; + + // Connects to the default PulseAudio server. Set options by bitwise-ORing + // flags defined in . Calls the specified callback each time the + // state of the connection changes. + void Connect( + pa_context_flags_t, + std::function on_state_change) noexcept; + + // Disconnects from the server. + void Disconnect() noexcept { + pa_context_disconnect(ctx_); + state_callback_ = nullptr; + } + + // Requests information about a sink specified by name. Calls on_failure if + // the request fails; calls on_data if it succeeds. Each callback will only be + // called once. + void GetSinkInfo( + const char name[], std::function on_failure, + std::function on_data) const noexcept; + + // Subscribes to some subset of server event notifications (see + // for allowable mask values and event types). Calls on_failure once if the + // request fails. If the request succeeds, calls on_data once every time an + // event occurs. + void Subscribe(pa_subscription_mask_t, std::function on_failure, + std::function on_event) + const noexcept; + + friend void swap(Context& left, Context& right) noexcept { + using ::std::swap; + swap(left.ctx_, right.ctx_); + swap(left.state_callback_, right.state_callback_); + swap(left.subscribe_callback_, right.subscribe_callback_); + } + + private: + pa_context* ctx_; + + // These are pointers so the underlying std::function is always + // at the same address, even if this object gets moved. + std::unique_ptr> state_callback_; + mutable std::unique_ptr> + subscribe_callback_; +}; + +} // namespace pulse + +#endif // PAVMON_PULSE_H_ -- cgit v1.2.3