linux_volume_catcher.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /**
  2. * @file linux_volume_catcher.cpp
  3. * @brief A Linux-specific, PulseAudio-specific hack to detect and volume-adjust new audio sources
  4. *
  5. * @cond
  6. * $LicenseInfo:firstyear=2010&license=viewerlgpl$
  7. * Second Life Viewer Source Code
  8. * Copyright (C) 2010, Linden Research, Inc.
  9. *
  10. * This library is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU Lesser General Public
  12. * License as published by the Free Software Foundation;
  13. * version 2.1 of the License only.
  14. *
  15. * This library is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * Lesser General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Lesser General Public
  21. * License along with this library; if not, write to the Free Software
  22. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  23. *
  24. * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
  25. * $/LicenseInfo$
  26. * @endcond
  27. */
  28. /*
  29. The high-level design is as follows:
  30. 1) Connect to the PulseAudio daemon
  31. 2) Watch for the creation of new audio players connecting to the daemon (this includes ALSA clients running on the PulseAudio emulation layer, such as Flash plugins)
  32. 3) Examine any new audio player's PID to see if it belongs to our own process
  33. 4) If so, tell PA to adjust the volume of that audio player ('sink input' in PA parlance)
  34. 5) Keep a list of all living audio players that we care about, adjust the volumes of all of them when we get a new setVolume() call
  35. */
  36. #include "linden_common.h"
  37. #include "volume_catcher.h"
  38. extern "C" {
  39. #include <glib.h>
  40. #include <glib-object.h>
  41. #include <pulse/introspect.h>
  42. #include <pulse/context.h>
  43. #include <pulse/subscribe.h>
  44. #include <pulse/glib-mainloop.h> // There's no special reason why we want the *glib* PA mainloop, but the generic polling implementation seems broken.
  45. #include "apr_pools.h"
  46. #include "apr_dso.h"
  47. }
  48. ////////////////////////////////////////////////////
  49. #define DEBUGMSG(...) do {} while(0)
  50. #define INFOMSG(...) do {} while(0)
  51. #define WARNMSG(...) do {} while(0)
  52. #define LL_PA_SYM(REQUIRED, PASYM, RTN, ...) RTN (*ll##PASYM)(__VA_ARGS__) = NULL
  53. #include "linux_volume_catcher_pa_syms.inc"
  54. #include "linux_volume_catcher_paglib_syms.inc"
  55. #undef LL_PA_SYM
  56. static bool sSymsGrabbed = false;
  57. static apr_pool_t *sSymPADSOMemoryPool = NULL;
  58. static apr_dso_handle_t *sSymPADSOHandleG = NULL;
  59. bool grab_pa_syms(std::string pulse_dso_name)
  60. {
  61. if (sSymsGrabbed)
  62. {
  63. // already have grabbed good syms
  64. return true;
  65. }
  66. bool sym_error = false;
  67. bool rtn = false;
  68. apr_status_t rv;
  69. apr_dso_handle_t *sSymPADSOHandle = NULL;
  70. #define LL_PA_SYM(REQUIRED, PASYM, RTN, ...) do{rv = apr_dso_sym((apr_dso_handle_sym_t*)&ll##PASYM, sSymPADSOHandle, #PASYM); if (rv != APR_SUCCESS) {INFOMSG("Failed to grab symbol: %s", #PASYM); if (REQUIRED) sym_error = true;} else DEBUGMSG("grabbed symbol: %s from %p", #PASYM, (void*)ll##PASYM);}while(0)
  71. //attempt to load the shared library
  72. apr_pool_create(&sSymPADSOMemoryPool, NULL);
  73. if (APR_SUCCESS == (rv = apr_dso_load(&sSymPADSOHandle,
  74. pulse_dso_name.c_str(),
  75. sSymPADSOMemoryPool)))
  76. {
  77. INFOMSG("Found DSO: %s", pulse_dso_name.c_str());
  78. #include "linux_volume_catcher_pa_syms.inc"
  79. #include "linux_volume_catcher_paglib_syms.inc"
  80. if (sSymPADSOHandle)
  81. {
  82. sSymPADSOHandleG = sSymPADSOHandle;
  83. sSymPADSOHandle = NULL;
  84. }
  85. rtn = !sym_error;
  86. }
  87. else
  88. {
  89. INFOMSG("Couldn't load DSO: %s", pulse_dso_name.c_str());
  90. rtn = false; // failure
  91. }
  92. if (sym_error)
  93. {
  94. WARNMSG("Failed to find necessary symbols in PulseAudio libraries.");
  95. }
  96. #undef LL_PA_SYM
  97. sSymsGrabbed = rtn;
  98. return rtn;
  99. }
  100. void ungrab_pa_syms()
  101. {
  102. // should be safe to call regardless of whether we've
  103. // actually grabbed syms.
  104. if (sSymPADSOHandleG)
  105. {
  106. apr_dso_unload(sSymPADSOHandleG);
  107. sSymPADSOHandleG = NULL;
  108. }
  109. if (sSymPADSOMemoryPool)
  110. {
  111. apr_pool_destroy(sSymPADSOMemoryPool);
  112. sSymPADSOMemoryPool = NULL;
  113. }
  114. // NULL-out all of the symbols we'd grabbed
  115. #define LL_PA_SYM(REQUIRED, PASYM, RTN, ...) do{ll##PASYM = NULL;}while(0)
  116. #include "linux_volume_catcher_pa_syms.inc"
  117. #include "linux_volume_catcher_paglib_syms.inc"
  118. #undef LL_PA_SYM
  119. sSymsGrabbed = false;
  120. }
  121. ////////////////////////////////////////////////////
  122. // PulseAudio requires a chain of callbacks with C linkage
  123. extern "C" {
  124. void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *i, int eol, void *userdata);
  125. void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata);
  126. void callback_context_state(pa_context *context, void *userdata);
  127. }
  128. class VolumeCatcherImpl
  129. {
  130. public:
  131. VolumeCatcherImpl();
  132. ~VolumeCatcherImpl();
  133. void setVolume(F32 volume);
  134. void pump();
  135. // For internal use: cannot be private because used from our C callbacks
  136. bool loadsyms(std::string pulse_dso_name);
  137. void init();
  138. void cleanup();
  139. void update_all_volumes(F32 volume);
  140. void update_index_volume(U32 index, F32 volume);
  141. void connected_okay();
  142. std::set<U32> mSinkInputIndices;
  143. std::map<U32,U32> mSinkInputNumChannels;
  144. F32 mDesiredVolume;
  145. pa_glib_mainloop *mMainloop;
  146. pa_context *mPAContext;
  147. bool mConnected;
  148. bool mGotSyms;
  149. };
  150. VolumeCatcherImpl::VolumeCatcherImpl()
  151. : mDesiredVolume(0.0f),
  152. mMainloop(NULL),
  153. mPAContext(NULL),
  154. mConnected(false),
  155. mGotSyms(false)
  156. {
  157. init();
  158. }
  159. VolumeCatcherImpl::~VolumeCatcherImpl()
  160. {
  161. cleanup();
  162. }
  163. bool VolumeCatcherImpl::loadsyms(std::string pulse_dso_name)
  164. {
  165. return grab_pa_syms(pulse_dso_name);
  166. }
  167. void VolumeCatcherImpl::init()
  168. {
  169. // try to be as defensive as possible because PA's interface is a
  170. // bit fragile and (for our purposes) we'd rather simply not function
  171. // than crash
  172. // we cheat and rely upon libpulse-mainloop-glib.so.0 to pull-in
  173. // libpulse.so.0 - this isn't a great assumption, and the two DSOs should
  174. // probably be loaded separately. Our Linux DSO framework needs refactoring,
  175. // we do this sort of thing a lot with practically identical logic...
  176. mGotSyms = loadsyms("libpulse-mainloop-glib.so.0");
  177. if (!mGotSyms) return;
  178. // better make double-sure glib itself is initialized properly.
  179. if (!g_thread_supported ()) g_thread_init (NULL);
  180. g_type_init();
  181. mMainloop = llpa_glib_mainloop_new(g_main_context_default());
  182. if (mMainloop)
  183. {
  184. pa_mainloop_api *api = llpa_glib_mainloop_get_api(mMainloop);
  185. if (api)
  186. {
  187. pa_proplist *proplist = llpa_proplist_new();
  188. if (proplist)
  189. {
  190. llpa_proplist_sets(proplist, PA_PROP_APPLICATION_ICON_NAME, "multimedia-player");
  191. llpa_proplist_sets(proplist, PA_PROP_APPLICATION_ID, "com.secondlife.viewer.mediaplugvoladjust");
  192. llpa_proplist_sets(proplist, PA_PROP_APPLICATION_NAME, "SL Plugin Volume Adjuster");
  193. llpa_proplist_sets(proplist, PA_PROP_APPLICATION_VERSION, "1");
  194. // plain old pa_context_new() is broken!
  195. mPAContext = llpa_context_new_with_proplist(api, NULL, proplist);
  196. llpa_proplist_free(proplist);
  197. }
  198. }
  199. }
  200. // Now we've set up a PA context and mainloop, try connecting the
  201. // PA context to a PA daemon.
  202. if (mPAContext)
  203. {
  204. llpa_context_set_state_callback(mPAContext, callback_context_state, this);
  205. pa_context_flags_t cflags = (pa_context_flags)0; // maybe add PA_CONTEXT_NOAUTOSPAWN?
  206. if (llpa_context_connect(mPAContext, NULL, cflags, NULL) >= 0)
  207. {
  208. // Okay! We haven't definitely connected, but we
  209. // haven't definitely failed yet.
  210. }
  211. else
  212. {
  213. // Failed to connect to PA manager... we'll leave
  214. // things like that. Perhaps we should try again later.
  215. }
  216. }
  217. }
  218. void VolumeCatcherImpl::cleanup()
  219. {
  220. mConnected = false;
  221. if (mGotSyms && mPAContext)
  222. {
  223. llpa_context_disconnect(mPAContext);
  224. llpa_context_unref(mPAContext);
  225. }
  226. mPAContext = NULL;
  227. if (mGotSyms && mMainloop)
  228. {
  229. llpa_glib_mainloop_free(mMainloop);
  230. }
  231. mMainloop = NULL;
  232. }
  233. void VolumeCatcherImpl::setVolume(F32 volume)
  234. {
  235. mDesiredVolume = volume;
  236. if (!mGotSyms) return;
  237. if (mConnected && mPAContext)
  238. {
  239. update_all_volumes(mDesiredVolume);
  240. }
  241. pump();
  242. }
  243. void VolumeCatcherImpl::pump()
  244. {
  245. gboolean may_block = FALSE;
  246. g_main_context_iteration(g_main_context_default(), may_block);
  247. }
  248. void VolumeCatcherImpl::connected_okay()
  249. {
  250. pa_operation *op;
  251. // fetch global list of existing sinkinputs
  252. if ((op = llpa_context_get_sink_input_info_list(mPAContext,
  253. callback_discovered_sinkinput,
  254. this)))
  255. {
  256. llpa_operation_unref(op);
  257. }
  258. // subscribe to future global sinkinput changes
  259. llpa_context_set_subscribe_callback(mPAContext,
  260. callback_subscription_alert,
  261. this);
  262. if ((op = llpa_context_subscribe(mPAContext, (pa_subscription_mask_t)
  263. (PA_SUBSCRIPTION_MASK_SINK_INPUT),
  264. NULL, NULL)))
  265. {
  266. llpa_operation_unref(op);
  267. }
  268. }
  269. void VolumeCatcherImpl::update_all_volumes(F32 volume)
  270. {
  271. for (std::set<U32>::iterator it = mSinkInputIndices.begin();
  272. it != mSinkInputIndices.end(); ++it)
  273. {
  274. update_index_volume(*it, volume);
  275. }
  276. }
  277. void VolumeCatcherImpl::update_index_volume(U32 index, F32 volume)
  278. {
  279. static pa_cvolume cvol;
  280. llpa_cvolume_set(&cvol, mSinkInputNumChannels[index],
  281. llpa_sw_volume_from_linear(volume));
  282. pa_context *c = mPAContext;
  283. uint32_t idx = index;
  284. const pa_cvolume *cvolumep = &cvol;
  285. pa_context_success_cb_t cb = NULL; // okay as null
  286. void *userdata = NULL; // okay as null
  287. pa_operation *op;
  288. if ((op = llpa_context_set_sink_input_volume(c, idx, cvolumep, cb, userdata)))
  289. {
  290. llpa_operation_unref(op);
  291. }
  292. }
  293. void callback_discovered_sinkinput(pa_context *context, const pa_sink_input_info *sii, int eol, void *userdata)
  294. {
  295. VolumeCatcherImpl *impl = dynamic_cast<VolumeCatcherImpl*>((VolumeCatcherImpl*)userdata);
  296. llassert(impl);
  297. if (0 == eol)
  298. {
  299. pa_proplist *proplist = sii->proplist;
  300. pid_t sinkpid = atoll(llpa_proplist_gets(proplist, PA_PROP_APPLICATION_PROCESS_ID));
  301. if (sinkpid == getpid()) // does the discovered sinkinput belong to this process?
  302. {
  303. bool is_new = (impl->mSinkInputIndices.find(sii->index) ==
  304. impl->mSinkInputIndices.end());
  305. impl->mSinkInputIndices.insert(sii->index);
  306. impl->mSinkInputNumChannels[sii->index] = sii->channel_map.channels;
  307. if (is_new)
  308. {
  309. // new!
  310. impl->update_index_volume(sii->index, impl->mDesiredVolume);
  311. }
  312. else
  313. {
  314. // seen it already, do nothing.
  315. }
  316. }
  317. }
  318. }
  319. void callback_subscription_alert(pa_context *context, pa_subscription_event_type_t t, uint32_t index, void *userdata)
  320. {
  321. VolumeCatcherImpl *impl = dynamic_cast<VolumeCatcherImpl*>((VolumeCatcherImpl*)userdata);
  322. llassert(impl);
  323. switch (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK)
  324. {
  325. case PA_SUBSCRIPTION_EVENT_SINK_INPUT:
  326. if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_REMOVE)
  327. {
  328. // forget this sinkinput, if we were caring about it
  329. impl->mSinkInputIndices.erase(index);
  330. impl->mSinkInputNumChannels.erase(index);
  331. }
  332. else if ((t & PA_SUBSCRIPTION_EVENT_TYPE_MASK) == PA_SUBSCRIPTION_EVENT_NEW)
  333. {
  334. // ask for more info about this new sinkinput
  335. pa_operation *op;
  336. if ((op = llpa_context_get_sink_input_info(impl->mPAContext, index, callback_discovered_sinkinput, impl)))
  337. {
  338. llpa_operation_unref(op);
  339. }
  340. }
  341. else
  342. {
  343. // property change on this sinkinput - we don't care.
  344. }
  345. break;
  346. default:;
  347. }
  348. }
  349. void callback_context_state(pa_context *context, void *userdata)
  350. {
  351. VolumeCatcherImpl *impl = dynamic_cast<VolumeCatcherImpl*>((VolumeCatcherImpl*)userdata);
  352. llassert(impl);
  353. switch (llpa_context_get_state(context))
  354. {
  355. case PA_CONTEXT_READY:
  356. impl->mConnected = true;
  357. impl->connected_okay();
  358. break;
  359. case PA_CONTEXT_TERMINATED:
  360. impl->mConnected = false;
  361. break;
  362. case PA_CONTEXT_FAILED:
  363. impl->mConnected = false;
  364. break;
  365. default:;
  366. }
  367. }
  368. /////////////////////////////////////////////////////
  369. VolumeCatcher::VolumeCatcher()
  370. {
  371. pimpl = new VolumeCatcherImpl();
  372. }
  373. VolumeCatcher::~VolumeCatcher()
  374. {
  375. delete pimpl;
  376. pimpl = NULL;
  377. }
  378. void VolumeCatcher::setVolume(F32 volume)
  379. {
  380. llassert(pimpl);
  381. pimpl->setVolume(volume);
  382. }
  383. void VolumeCatcher::setPan(F32 pan)
  384. {
  385. // TODO: implement this (if possible)
  386. }
  387. void VolumeCatcher::pump()
  388. {
  389. llassert(pimpl);
  390. pimpl->pump();
  391. }