pulseaudio.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 2009 by Konstantinos Natsakis <[email protected]>
  4. * Copyright (C) 2010 by Chris Robinson <[email protected]>
  5. * This library is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU Library General Public
  7. * License as published by the Free Software Foundation; either
  8. * version 2 of the License, or (at your option) any later version.
  9. *
  10. * This library is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. * Library General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU Library General Public
  16. * License along with this library; if not, write to the
  17. * Free Software Foundation, Inc.,
  18. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  19. * Or go to http://www.gnu.org/copyleft/lgpl.html
  20. */
  21. #include "config.h"
  22. #include "pulseaudio.h"
  23. #include <algorithm>
  24. #include <array>
  25. #include <atomic>
  26. #include <bitset>
  27. #include <chrono>
  28. #include <cmath>
  29. #include <cstddef>
  30. #include <cstdint>
  31. #include <cstring>
  32. #include <limits>
  33. #include <mutex>
  34. #include <optional>
  35. #include <string>
  36. #include <string_view>
  37. #include <sys/types.h>
  38. #include <utility>
  39. #include <vector>
  40. #include "alc/alconfig.h"
  41. #include "alnumeric.h"
  42. #include "alspan.h"
  43. #include "base.h"
  44. #include "core/devformat.h"
  45. #include "core/device.h"
  46. #include "core/logging.h"
  47. #include "dynload.h"
  48. #include "fmt/core.h"
  49. #include "opthelpers.h"
  50. #include "strutils.h"
  51. #include <pulse/pulseaudio.h>
  52. namespace {
  53. using namespace std::string_view_literals;
  54. using uint = unsigned int;
  55. #if HAVE_DYNLOAD
  56. #define PULSE_FUNCS(MAGIC) \
  57. MAGIC(pa_context_new); \
  58. MAGIC(pa_context_unref); \
  59. MAGIC(pa_context_get_state); \
  60. MAGIC(pa_context_disconnect); \
  61. MAGIC(pa_context_set_state_callback); \
  62. MAGIC(pa_context_set_subscribe_callback); \
  63. MAGIC(pa_context_subscribe); \
  64. MAGIC(pa_context_errno); \
  65. MAGIC(pa_context_connect); \
  66. MAGIC(pa_context_get_server_info); \
  67. MAGIC(pa_context_get_sink_info_by_index); \
  68. MAGIC(pa_context_get_sink_info_by_name); \
  69. MAGIC(pa_context_get_sink_info_list); \
  70. MAGIC(pa_context_get_source_info_by_index); \
  71. MAGIC(pa_context_get_source_info_by_name); \
  72. MAGIC(pa_context_get_source_info_list); \
  73. MAGIC(pa_stream_new); \
  74. MAGIC(pa_stream_unref); \
  75. MAGIC(pa_stream_drop); \
  76. MAGIC(pa_stream_get_state); \
  77. MAGIC(pa_stream_peek); \
  78. MAGIC(pa_stream_write); \
  79. MAGIC(pa_stream_connect_record); \
  80. MAGIC(pa_stream_connect_playback); \
  81. MAGIC(pa_stream_readable_size); \
  82. MAGIC(pa_stream_writable_size); \
  83. MAGIC(pa_stream_is_corked); \
  84. MAGIC(pa_stream_cork); \
  85. MAGIC(pa_stream_is_suspended); \
  86. MAGIC(pa_stream_get_device_name); \
  87. MAGIC(pa_stream_get_latency); \
  88. MAGIC(pa_stream_set_write_callback); \
  89. MAGIC(pa_stream_set_buffer_attr); \
  90. MAGIC(pa_stream_get_buffer_attr); \
  91. MAGIC(pa_stream_get_sample_spec); \
  92. MAGIC(pa_stream_get_time); \
  93. MAGIC(pa_stream_set_read_callback); \
  94. MAGIC(pa_stream_set_state_callback); \
  95. MAGIC(pa_stream_set_moved_callback); \
  96. MAGIC(pa_stream_set_underflow_callback); \
  97. MAGIC(pa_stream_new_with_proplist); \
  98. MAGIC(pa_stream_disconnect); \
  99. MAGIC(pa_stream_set_buffer_attr_callback); \
  100. MAGIC(pa_stream_begin_write); \
  101. MAGIC(pa_threaded_mainloop_free); \
  102. MAGIC(pa_threaded_mainloop_get_api); \
  103. MAGIC(pa_threaded_mainloop_lock); \
  104. MAGIC(pa_threaded_mainloop_new); \
  105. MAGIC(pa_threaded_mainloop_signal); \
  106. MAGIC(pa_threaded_mainloop_start); \
  107. MAGIC(pa_threaded_mainloop_stop); \
  108. MAGIC(pa_threaded_mainloop_unlock); \
  109. MAGIC(pa_threaded_mainloop_wait); \
  110. MAGIC(pa_channel_map_init_auto); \
  111. MAGIC(pa_channel_map_parse); \
  112. MAGIC(pa_channel_map_snprint); \
  113. MAGIC(pa_channel_map_equal); \
  114. MAGIC(pa_channel_map_superset); \
  115. MAGIC(pa_channel_position_to_string); \
  116. MAGIC(pa_operation_get_state); \
  117. MAGIC(pa_operation_unref); \
  118. MAGIC(pa_sample_spec_valid); \
  119. MAGIC(pa_frame_size); \
  120. MAGIC(pa_strerror); \
  121. MAGIC(pa_path_get_filename); \
  122. MAGIC(pa_get_binary_name); \
  123. MAGIC(pa_xmalloc); \
  124. MAGIC(pa_xfree);
  125. void *pulse_handle;
  126. #define MAKE_FUNC(x) decltype(x) * p##x
  127. PULSE_FUNCS(MAKE_FUNC)
  128. #undef MAKE_FUNC
  129. #ifndef IN_IDE_PARSER
  130. #define pa_context_new ppa_context_new
  131. #define pa_context_unref ppa_context_unref
  132. #define pa_context_get_state ppa_context_get_state
  133. #define pa_context_disconnect ppa_context_disconnect
  134. #define pa_context_set_state_callback ppa_context_set_state_callback
  135. #define pa_context_set_subscribe_callback ppa_context_set_subscribe_callback
  136. #define pa_context_subscribe ppa_context_subscribe
  137. #define pa_context_errno ppa_context_errno
  138. #define pa_context_connect ppa_context_connect
  139. #define pa_context_get_server_info ppa_context_get_server_info
  140. #define pa_context_get_sink_info_by_index ppa_context_get_sink_info_by_index
  141. #define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name
  142. #define pa_context_get_sink_info_list ppa_context_get_sink_info_list
  143. #define pa_context_get_source_info_by_index ppa_context_get_source_info_by_index
  144. #define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name
  145. #define pa_context_get_source_info_list ppa_context_get_source_info_list
  146. #define pa_stream_new ppa_stream_new
  147. #define pa_stream_unref ppa_stream_unref
  148. #define pa_stream_disconnect ppa_stream_disconnect
  149. #define pa_stream_drop ppa_stream_drop
  150. #define pa_stream_set_write_callback ppa_stream_set_write_callback
  151. #define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr
  152. #define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr
  153. #define pa_stream_get_sample_spec ppa_stream_get_sample_spec
  154. #define pa_stream_get_time ppa_stream_get_time
  155. #define pa_stream_set_read_callback ppa_stream_set_read_callback
  156. #define pa_stream_set_state_callback ppa_stream_set_state_callback
  157. #define pa_stream_set_moved_callback ppa_stream_set_moved_callback
  158. #define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback
  159. #define pa_stream_connect_record ppa_stream_connect_record
  160. #define pa_stream_connect_playback ppa_stream_connect_playback
  161. #define pa_stream_readable_size ppa_stream_readable_size
  162. #define pa_stream_writable_size ppa_stream_writable_size
  163. #define pa_stream_is_corked ppa_stream_is_corked
  164. #define pa_stream_cork ppa_stream_cork
  165. #define pa_stream_is_suspended ppa_stream_is_suspended
  166. #define pa_stream_get_device_name ppa_stream_get_device_name
  167. #define pa_stream_get_latency ppa_stream_get_latency
  168. #define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback
  169. #define pa_stream_begin_write ppa_stream_begin_write
  170. #define pa_threaded_mainloop_free ppa_threaded_mainloop_free
  171. #define pa_threaded_mainloop_get_api ppa_threaded_mainloop_get_api
  172. #define pa_threaded_mainloop_lock ppa_threaded_mainloop_lock
  173. #define pa_threaded_mainloop_new ppa_threaded_mainloop_new
  174. #define pa_threaded_mainloop_signal ppa_threaded_mainloop_signal
  175. #define pa_threaded_mainloop_start ppa_threaded_mainloop_start
  176. #define pa_threaded_mainloop_stop ppa_threaded_mainloop_stop
  177. #define pa_threaded_mainloop_unlock ppa_threaded_mainloop_unlock
  178. #define pa_threaded_mainloop_wait ppa_threaded_mainloop_wait
  179. #define pa_channel_map_init_auto ppa_channel_map_init_auto
  180. #define pa_channel_map_parse ppa_channel_map_parse
  181. #define pa_channel_map_snprint ppa_channel_map_snprint
  182. #define pa_channel_map_equal ppa_channel_map_equal
  183. #define pa_channel_map_superset ppa_channel_map_superset
  184. #define pa_channel_position_to_string ppa_channel_position_to_string
  185. #define pa_operation_get_state ppa_operation_get_state
  186. #define pa_operation_unref ppa_operation_unref
  187. #define pa_sample_spec_valid ppa_sample_spec_valid
  188. #define pa_frame_size ppa_frame_size
  189. #define pa_strerror ppa_strerror
  190. #define pa_stream_get_state ppa_stream_get_state
  191. #define pa_stream_peek ppa_stream_peek
  192. #define pa_stream_write ppa_stream_write
  193. #define pa_xfree ppa_xfree
  194. #define pa_path_get_filename ppa_path_get_filename
  195. #define pa_get_binary_name ppa_get_binary_name
  196. #define pa_xmalloc ppa_xmalloc
  197. #endif /* IN_IDE_PARSER */
  198. #endif
  199. constexpr pa_channel_map MonoChanMap{
  200. 1, {PA_CHANNEL_POSITION_MONO}
  201. }, StereoChanMap{
  202. 2, {PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT}
  203. }, QuadChanMap{
  204. 4, {
  205. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  206. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
  207. }
  208. }, X51ChanMap{
  209. 6, {
  210. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  211. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  212. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  213. }
  214. }, X51RearChanMap{
  215. 6, {
  216. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  217. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  218. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
  219. }
  220. }, X61ChanMap{
  221. 7, {
  222. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  223. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  224. PA_CHANNEL_POSITION_REAR_CENTER,
  225. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  226. }
  227. }, X71ChanMap{
  228. 8, {
  229. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  230. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  231. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
  232. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  233. }
  234. }, X714ChanMap{
  235. 12, {
  236. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  237. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  238. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
  239. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT,
  240. PA_CHANNEL_POSITION_TOP_FRONT_LEFT, PA_CHANNEL_POSITION_TOP_FRONT_RIGHT,
  241. PA_CHANNEL_POSITION_TOP_REAR_LEFT, PA_CHANNEL_POSITION_TOP_REAR_RIGHT
  242. }
  243. };
  244. /* NOLINTBEGIN(*EnumCastOutOfRange) *grumble* Don't use enums for bitflags. */
  245. constexpr pa_stream_flags_t operator|(pa_stream_flags_t lhs, pa_stream_flags_t rhs)
  246. { return pa_stream_flags_t(lhs | al::to_underlying(rhs)); }
  247. constexpr pa_stream_flags_t& operator|=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
  248. {
  249. lhs = lhs | rhs;
  250. return lhs;
  251. }
  252. constexpr pa_stream_flags_t operator~(pa_stream_flags_t flag)
  253. { return pa_stream_flags_t(~al::to_underlying(flag)); }
  254. constexpr pa_stream_flags_t& operator&=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
  255. {
  256. lhs = pa_stream_flags_t(al::to_underlying(lhs) & rhs);
  257. return lhs;
  258. }
  259. constexpr pa_context_flags_t operator|(pa_context_flags_t lhs, pa_context_flags_t rhs)
  260. { return pa_context_flags_t(lhs | al::to_underlying(rhs)); }
  261. constexpr pa_context_flags_t& operator|=(pa_context_flags_t &lhs, pa_context_flags_t rhs)
  262. {
  263. lhs = lhs | rhs;
  264. return lhs;
  265. }
  266. constexpr pa_subscription_mask_t operator|(pa_subscription_mask_t lhs, pa_subscription_mask_t rhs)
  267. { return pa_subscription_mask_t(lhs | al::to_underlying(rhs)); }
  268. /* NOLINTEND(*EnumCastOutOfRange) */
  269. struct DevMap {
  270. std::string name;
  271. std::string device_name;
  272. uint32_t index{};
  273. };
  274. bool checkName(const al::span<const DevMap> list, const std::string &name)
  275. {
  276. auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; };
  277. return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
  278. }
  279. std::vector<DevMap> PlaybackDevices;
  280. std::vector<DevMap> CaptureDevices;
  281. std::string DefaultPlaybackDevName;
  282. std::string DefaultCaptureDevName;
  283. /* Global flags and properties */
  284. pa_context_flags_t pulse_ctx_flags;
  285. class PulseMainloop {
  286. pa_threaded_mainloop *mLoop{};
  287. pa_context *mContext{};
  288. public:
  289. PulseMainloop() = default;
  290. PulseMainloop(const PulseMainloop&) = delete;
  291. PulseMainloop(PulseMainloop&& rhs) noexcept : mLoop{rhs.mLoop} { rhs.mLoop = nullptr; }
  292. explicit PulseMainloop(pa_threaded_mainloop *loop) noexcept : mLoop{loop} { }
  293. ~PulseMainloop();
  294. PulseMainloop& operator=(const PulseMainloop&) = delete;
  295. PulseMainloop& operator=(PulseMainloop&& rhs) noexcept
  296. { std::swap(mLoop, rhs.mLoop); return *this; }
  297. PulseMainloop& operator=(std::nullptr_t) noexcept
  298. {
  299. if(mLoop)
  300. pa_threaded_mainloop_free(mLoop);
  301. mLoop = nullptr;
  302. return *this;
  303. }
  304. explicit operator bool() const noexcept { return mLoop != nullptr; }
  305. [[nodiscard]]
  306. auto start() const { return pa_threaded_mainloop_start(mLoop); }
  307. auto stop() const { return pa_threaded_mainloop_stop(mLoop); }
  308. [[nodiscard]] auto getApi() const { return pa_threaded_mainloop_get_api(mLoop); }
  309. [[nodiscard]] auto getContext() const noexcept { return mContext; }
  310. auto lock() const { return pa_threaded_mainloop_lock(mLoop); }
  311. auto unlock() const { return pa_threaded_mainloop_unlock(mLoop); }
  312. auto signal(bool wait=false) const { return pa_threaded_mainloop_signal(mLoop, wait); }
  313. static auto Create() { return PulseMainloop{pa_threaded_mainloop_new()}; }
  314. void streamSuccessCallback(pa_stream*, int) const noexcept { signal(); }
  315. static void streamSuccessCallbackC(pa_stream *stream, int success, void *pdata) noexcept
  316. { static_cast<PulseMainloop*>(pdata)->streamSuccessCallback(stream, success); }
  317. void close(pa_stream *stream=nullptr);
  318. void updateDefaultDevice(pa_context*, const pa_server_info *info) const
  319. {
  320. auto default_sink = info->default_sink_name ? std::string_view{info->default_sink_name}
  321. : std::string_view{};
  322. auto default_src = info->default_source_name ? std::string_view{info->default_source_name}
  323. : std::string_view{};
  324. if(default_sink != DefaultPlaybackDevName)
  325. {
  326. TRACE("Default playback device: {}", default_sink);
  327. DefaultPlaybackDevName = default_sink;
  328. const auto msg = fmt::format("Default playback device changed: {}", default_sink);
  329. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Playback, msg);
  330. }
  331. if(default_src != DefaultCaptureDevName)
  332. {
  333. TRACE("Default capture device: {}", default_src);
  334. DefaultCaptureDevName = default_src;
  335. const auto msg = fmt::format("Default capture device changed: {}", default_src);
  336. alc::Event(alc::EventType::DefaultDeviceChanged, alc::DeviceType::Capture, msg);
  337. }
  338. signal();
  339. }
  340. void deviceSinkCallback(pa_context*, const pa_sink_info *info, int eol) const noexcept
  341. {
  342. if(eol)
  343. {
  344. signal();
  345. return;
  346. }
  347. /* Skip this device is if it's already in the list. */
  348. auto match_devname = [info](const DevMap &entry) -> bool
  349. { return entry.device_name == info->name; };
  350. if(std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_devname) != PlaybackDevices.cend())
  351. return;
  352. /* Make sure the display name (description) is unique. Append a number
  353. * counter as needed.
  354. */
  355. auto count = 1;
  356. auto newname = std::string{info->description};
  357. while(checkName(PlaybackDevices, newname))
  358. newname = fmt::format("{} #{}", info->description, ++count);
  359. const auto &newentry = PlaybackDevices.emplace_back(DevMap{std::move(newname),
  360. info->name, info->index});
  361. TRACE("Got device \"{}\", \"{}\" ({})", newentry.name, newentry.device_name,
  362. newentry.index);
  363. const auto msg = fmt::format("Device added: {}", newentry.device_name);
  364. alc::Event(alc::EventType::DeviceAdded, alc::DeviceType::Playback, msg);
  365. }
  366. void deviceSourceCallback(pa_context*, const pa_source_info *info, int eol) const noexcept
  367. {
  368. if(eol)
  369. {
  370. signal();
  371. return;
  372. }
  373. /* Skip this device is if it's already in the list. */
  374. auto match_devname = [info](const DevMap &entry) -> bool
  375. { return entry.device_name == info->name; };
  376. if(std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_devname) != CaptureDevices.cend())
  377. return;
  378. /* Make sure the display name (description) is unique. Append a number
  379. * counter as needed.
  380. */
  381. auto count = 1;
  382. auto newname = std::string{info->description};
  383. while(checkName(CaptureDevices, newname))
  384. newname = fmt::format("{} #{}", info->description, ++count);
  385. const auto &newentry = CaptureDevices.emplace_back(DevMap{std::move(newname), info->name,
  386. info->index});
  387. TRACE("Got device \"{}\", \"{}\" ({})", newentry.name, newentry.device_name,
  388. newentry.index);
  389. const auto msg = fmt::format("Device added: {}", newentry.device_name);
  390. alc::Event(alc::EventType::DeviceAdded, alc::DeviceType::Capture, msg);
  391. }
  392. void eventCallback(pa_context *context, pa_subscription_event_type_t t, uint32_t idx) noexcept
  393. {
  394. const auto eventFacility = (t & PA_SUBSCRIPTION_EVENT_FACILITY_MASK);
  395. const auto eventType = (t & PA_SUBSCRIPTION_EVENT_TYPE_MASK);
  396. if(eventFacility == PA_SUBSCRIPTION_EVENT_SERVER
  397. && eventType == PA_SUBSCRIPTION_EVENT_CHANGE)
  398. {
  399. static constexpr auto server_cb = [](pa_context *ctx, const pa_server_info *info,
  400. void *pdata) noexcept
  401. { return static_cast<PulseMainloop*>(pdata)->updateDefaultDevice(ctx, info); };
  402. auto *op = pa_context_get_server_info(context, server_cb, this);
  403. if(op) pa_operation_unref(op);
  404. }
  405. if(eventFacility != PA_SUBSCRIPTION_EVENT_SINK
  406. && eventFacility != PA_SUBSCRIPTION_EVENT_SOURCE)
  407. return;
  408. const auto devtype = (eventFacility == PA_SUBSCRIPTION_EVENT_SINK)
  409. ? alc::DeviceType::Playback : alc::DeviceType::Capture;
  410. if(eventType == PA_SUBSCRIPTION_EVENT_NEW)
  411. {
  412. if(eventFacility == PA_SUBSCRIPTION_EVENT_SINK)
  413. {
  414. static constexpr auto devcallback = [](pa_context *ctx, const pa_sink_info *info,
  415. int eol, void *pdata) noexcept
  416. { return static_cast<PulseMainloop*>(pdata)->deviceSinkCallback(ctx, info, eol); };
  417. auto *op = pa_context_get_sink_info_by_index(context, idx, devcallback, this);
  418. if(op) pa_operation_unref(op);
  419. }
  420. else
  421. {
  422. static constexpr auto devcallback = [](pa_context *ctx, const pa_source_info *info,
  423. int eol, void *pdata) noexcept
  424. { return static_cast<PulseMainloop*>(pdata)->deviceSourceCallback(ctx,info,eol); };
  425. auto *op = pa_context_get_source_info_by_index(context, idx, devcallback, this);
  426. if(op) pa_operation_unref(op);
  427. }
  428. }
  429. else if(eventType == PA_SUBSCRIPTION_EVENT_REMOVE)
  430. {
  431. auto find_index = [idx](const DevMap &entry) noexcept { return entry.index == idx; };
  432. auto &devlist = (eventFacility == PA_SUBSCRIPTION_EVENT_SINK)
  433. ? PlaybackDevices : CaptureDevices;
  434. auto iter = std::find_if(devlist.cbegin(), devlist.cend(), find_index);
  435. if(iter != devlist.cend())
  436. {
  437. devlist.erase(iter);
  438. const auto msg = fmt::format("Device removed: {}", idx);
  439. alc::Event(alc::EventType::DeviceRemoved, devtype, msg);
  440. }
  441. }
  442. }
  443. friend struct MainloopUniqueLock;
  444. };
  445. struct MainloopUniqueLock : public std::unique_lock<PulseMainloop> {
  446. using std::unique_lock<PulseMainloop>::unique_lock;
  447. MainloopUniqueLock& operator=(MainloopUniqueLock&&) = default;
  448. auto wait() const -> void
  449. { pa_threaded_mainloop_wait(mutex()->mLoop); }
  450. template<typename Predicate>
  451. auto wait(Predicate done_waiting) const -> void
  452. { while(!done_waiting()) wait(); }
  453. void waitForOperation(pa_operation *op) const
  454. {
  455. if(op)
  456. {
  457. wait([op]{ return pa_operation_get_state(op) != PA_OPERATION_RUNNING; });
  458. pa_operation_unref(op);
  459. }
  460. }
  461. void setEventHandler()
  462. {
  463. auto *context = mutex()->mContext;
  464. /* Watch for device added/removed and server changed events. */
  465. static constexpr auto submask = PA_SUBSCRIPTION_MASK_SINK | PA_SUBSCRIPTION_MASK_SOURCE
  466. | PA_SUBSCRIPTION_MASK_SERVER;
  467. static constexpr auto do_signal = [](pa_context*, int, void *pdata) noexcept
  468. { static_cast<PulseMainloop*>(pdata)->signal(); };
  469. auto *op = pa_context_subscribe(context, submask, do_signal, mutex());
  470. waitForOperation(op);
  471. static constexpr auto handler = [](pa_context *ctx, pa_subscription_event_type_t t,
  472. uint32_t index, void *pdata) noexcept
  473. { return static_cast<PulseMainloop*>(pdata)->eventCallback(ctx, t, index); };
  474. pa_context_set_subscribe_callback(context, handler, mutex());
  475. /* Fill in the initial device lists, and get the defaults. */
  476. auto sink_callback = [](pa_context *ctx, const pa_sink_info *info, int eol, void *pdata) noexcept
  477. { return static_cast<PulseMainloop*>(pdata)->deviceSinkCallback(ctx, info, eol); };
  478. auto src_callback = [](pa_context *ctx, const pa_source_info *info, int eol, void *pdata) noexcept
  479. { return static_cast<PulseMainloop*>(pdata)->deviceSourceCallback(ctx, info, eol); };
  480. auto server_callback = [](pa_context *ctx, const pa_server_info *info, void *pdata) noexcept
  481. { return static_cast<PulseMainloop*>(pdata)->updateDefaultDevice(ctx, info); };
  482. auto *sinkop = pa_context_get_sink_info_list(context, sink_callback, mutex());
  483. auto *srcop = pa_context_get_source_info_list(context, src_callback, mutex());
  484. auto *serverop = pa_context_get_server_info(context, server_callback, mutex());
  485. waitForOperation(sinkop);
  486. waitForOperation(srcop);
  487. waitForOperation(serverop);
  488. }
  489. void contextStateCallback(pa_context *context) noexcept
  490. {
  491. pa_context_state_t state{pa_context_get_state(context)};
  492. if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state))
  493. mutex()->signal();
  494. }
  495. void streamStateCallback(pa_stream *stream) noexcept
  496. {
  497. pa_stream_state_t state{pa_stream_get_state(stream)};
  498. if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state))
  499. mutex()->signal();
  500. }
  501. void connectContext();
  502. pa_stream *connectStream(const char *device_name, pa_stream_flags_t flags,
  503. pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type);
  504. pa_stream *connectStream(const std::string &device_name, pa_stream_flags_t flags,
  505. pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type)
  506. {
  507. return connectStream(device_name.empty() ? nullptr : device_name.c_str(), flags, attr,
  508. spec, chanmap, type);
  509. }
  510. };
  511. using MainloopLockGuard = std::lock_guard<PulseMainloop>;
  512. PulseMainloop::~PulseMainloop()
  513. {
  514. if(mContext)
  515. {
  516. MainloopUniqueLock looplock{*this};
  517. pa_context_disconnect(mContext);
  518. pa_context_unref(mContext);
  519. }
  520. if(mLoop)
  521. pa_threaded_mainloop_free(mLoop);
  522. }
  523. void MainloopUniqueLock::connectContext()
  524. {
  525. if(mutex()->mContext)
  526. return;
  527. mutex()->mContext = pa_context_new(mutex()->getApi(), nullptr);
  528. if(!mutex()->mContext) throw al::backend_exception{al::backend_error::OutOfMemory,
  529. "pa_context_new() failed"};
  530. pa_context_set_state_callback(mutex()->mContext, [](pa_context *ctx, void *pdata) noexcept
  531. { return static_cast<MainloopUniqueLock*>(pdata)->contextStateCallback(ctx); }, this);
  532. int err{pa_context_connect(mutex()->mContext, nullptr, pulse_ctx_flags, nullptr)};
  533. if(err >= 0)
  534. {
  535. wait([&err,this]()
  536. {
  537. pa_context_state_t state{pa_context_get_state(mutex()->mContext)};
  538. if(!PA_CONTEXT_IS_GOOD(state))
  539. {
  540. err = pa_context_errno(mutex()->mContext);
  541. if(err > 0) err = -err;
  542. return true;
  543. }
  544. return state == PA_CONTEXT_READY;
  545. });
  546. }
  547. pa_context_set_state_callback(mutex()->mContext, nullptr, nullptr);
  548. if(err < 0)
  549. {
  550. pa_context_unref(mutex()->mContext);
  551. mutex()->mContext = nullptr;
  552. throw al::backend_exception{al::backend_error::DeviceError, "Context did not connect ({})",
  553. pa_strerror(err)};
  554. }
  555. }
  556. pa_stream *MainloopUniqueLock::connectStream(const char *device_name, pa_stream_flags_t flags,
  557. pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type)
  558. {
  559. const char *stream_id{(type==BackendType::Playback) ? "Playback Stream" : "Capture Stream"};
  560. pa_stream *stream{pa_stream_new(mutex()->mContext, stream_id, spec, chanmap)};
  561. if(!stream)
  562. throw al::backend_exception{al::backend_error::OutOfMemory, "pa_stream_new() failed ({})",
  563. pa_strerror(pa_context_errno(mutex()->mContext))};
  564. pa_stream_set_state_callback(stream, [](pa_stream *strm, void *pdata) noexcept
  565. { return static_cast<MainloopUniqueLock*>(pdata)->streamStateCallback(strm); }, this);
  566. int err{(type==BackendType::Playback) ?
  567. pa_stream_connect_playback(stream, device_name, attr, flags, nullptr, nullptr) :
  568. pa_stream_connect_record(stream, device_name, attr, flags)};
  569. if(err < 0)
  570. {
  571. pa_stream_unref(stream);
  572. throw al::backend_exception{al::backend_error::DeviceError, "%s did not connect ({})",
  573. stream_id, pa_strerror(err)};
  574. }
  575. wait([&err,stream,stream_id,this]()
  576. {
  577. pa_stream_state_t state{pa_stream_get_state(stream)};
  578. if(!PA_STREAM_IS_GOOD(state))
  579. {
  580. err = pa_context_errno(mutex()->mContext);
  581. pa_stream_unref(stream);
  582. throw al::backend_exception{al::backend_error::DeviceError,
  583. "{} did not get ready ({})", stream_id, pa_strerror(err)};
  584. }
  585. return state == PA_STREAM_READY;
  586. });
  587. pa_stream_set_state_callback(stream, nullptr, nullptr);
  588. return stream;
  589. }
  590. void PulseMainloop::close(pa_stream *stream)
  591. {
  592. if(!stream)
  593. return;
  594. MainloopUniqueLock looplock{*this};
  595. pa_stream_set_state_callback(stream, nullptr, nullptr);
  596. pa_stream_set_moved_callback(stream, nullptr, nullptr);
  597. pa_stream_set_write_callback(stream, nullptr, nullptr);
  598. pa_stream_set_buffer_attr_callback(stream, nullptr, nullptr);
  599. pa_stream_disconnect(stream);
  600. pa_stream_unref(stream);
  601. }
  602. /* Used for initial connection test and enumeration. */
  603. PulseMainloop gGlobalMainloop;
  604. struct PulsePlayback final : public BackendBase {
  605. explicit PulsePlayback(DeviceBase *device) noexcept : BackendBase{device} { }
  606. ~PulsePlayback() override;
  607. void bufferAttrCallback(pa_stream *stream) noexcept;
  608. void streamStateCallback(pa_stream *stream) noexcept;
  609. void streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept;
  610. void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
  611. void sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
  612. void streamMovedCallback(pa_stream *stream) noexcept;
  613. void open(std::string_view name) override;
  614. bool reset() override;
  615. void start() override;
  616. void stop() override;
  617. ClockLatency getClockLatency() override;
  618. PulseMainloop mMainloop;
  619. std::optional<std::string> mDeviceId{std::nullopt};
  620. bool mIs51Rear{false};
  621. pa_buffer_attr mAttr{};
  622. pa_sample_spec mSpec{};
  623. pa_stream *mStream{nullptr};
  624. uint mFrameSize{0u};
  625. };
  626. PulsePlayback::~PulsePlayback()
  627. { if(mStream) mMainloop.close(mStream); }
  628. void PulsePlayback::bufferAttrCallback(pa_stream *stream) noexcept
  629. {
  630. /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new
  631. * buffer attributes? Changing UpdateSize will change the ALC_REFRESH
  632. * property, which probably shouldn't change between device resets. But
  633. * leaving it alone means ALC_REFRESH will be off.
  634. */
  635. mAttr = *(pa_stream_get_buffer_attr(stream));
  636. TRACE("minreq={}, tlength={}, prebuf={}", mAttr.minreq, mAttr.tlength, mAttr.prebuf);
  637. }
  638. void PulsePlayback::streamStateCallback(pa_stream *stream) noexcept
  639. {
  640. if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
  641. {
  642. ERR("Received stream failure!");
  643. mDevice->handleDisconnect("Playback stream failure");
  644. }
  645. mMainloop.signal();
  646. }
  647. void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept
  648. {
  649. do {
  650. pa_free_cb_t free_func{nullptr};
  651. auto buflen = static_cast<size_t>(-1);
  652. void *buf{};
  653. if(pa_stream_begin_write(stream, &buf, &buflen) || !buf) UNLIKELY
  654. {
  655. buflen = nbytes;
  656. buf = pa_xmalloc(buflen);
  657. free_func = pa_xfree;
  658. }
  659. else
  660. buflen = std::min(buflen, nbytes);
  661. nbytes -= buflen;
  662. mDevice->renderSamples(buf, static_cast<uint>(buflen/mFrameSize), mSpec.channels);
  663. int ret{pa_stream_write(stream, buf, buflen, free_func, 0, PA_SEEK_RELATIVE)};
  664. if(ret != PA_OK) UNLIKELY
  665. ERR("Failed to write to stream: {}, {}", ret, pa_strerror(ret));
  666. } while(nbytes > 0);
  667. }
  668. void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
  669. {
  670. struct ChannelMap {
  671. DevFmtChannels fmt;
  672. pa_channel_map map;
  673. bool is_51rear;
  674. };
  675. static constexpr std::array<ChannelMap,8> chanmaps{{
  676. { DevFmtX714, X714ChanMap, false },
  677. { DevFmtX71, X71ChanMap, false },
  678. { DevFmtX61, X61ChanMap, false },
  679. { DevFmtX51, X51ChanMap, false },
  680. { DevFmtX51, X51RearChanMap, true },
  681. { DevFmtQuad, QuadChanMap, false },
  682. { DevFmtStereo, StereoChanMap, false },
  683. { DevFmtMono, MonoChanMap, false }
  684. }};
  685. if(eol)
  686. {
  687. mMainloop.signal();
  688. return;
  689. }
  690. auto chaniter = std::find_if(chanmaps.cbegin(), chanmaps.cend(),
  691. [info](const ChannelMap &chanmap) -> bool
  692. { return pa_channel_map_superset(&info->channel_map, &chanmap.map); }
  693. );
  694. if(chaniter != chanmaps.cend())
  695. {
  696. if(!mDevice->Flags.test(ChannelsRequest))
  697. mDevice->FmtChans = chaniter->fmt;
  698. mIs51Rear = chaniter->is_51rear;
  699. }
  700. else
  701. {
  702. mIs51Rear = false;
  703. std::array<char,PA_CHANNEL_MAP_SNPRINT_MAX> chanmap_str{};
  704. pa_channel_map_snprint(chanmap_str.data(), chanmap_str.size(), &info->channel_map);
  705. WARN("Failed to find format for channel map:\n {}", chanmap_str.data());
  706. }
  707. if(info->active_port)
  708. TRACE("Active port: {} ({})", info->active_port->name, info->active_port->description);
  709. mDevice->Flags.set(DirectEar, (info->active_port
  710. && strcmp(info->active_port->name, "analog-output-headphones") == 0));
  711. }
  712. void PulsePlayback::sinkNameCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
  713. {
  714. if(eol)
  715. {
  716. mMainloop.signal();
  717. return;
  718. }
  719. mDeviceName = info->description;
  720. }
  721. void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept
  722. {
  723. mDeviceId = pa_stream_get_device_name(stream);
  724. TRACE("Stream moved to {}", *mDeviceId);
  725. }
  726. void PulsePlayback::open(std::string_view name)
  727. {
  728. mMainloop = PulseMainloop::Create();
  729. if(mMainloop.start() != 0)
  730. throw al::backend_exception{al::backend_error::DeviceError,
  731. "Failed to start device mainloop"};
  732. auto pulse_name = std::string{};
  733. if(!name.empty())
  734. {
  735. auto match_name = [name](const DevMap &entry) -> bool
  736. { return entry.name == name || entry.device_name == name; };
  737. auto plock = MainloopUniqueLock{gGlobalMainloop};
  738. auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_name);
  739. if(iter == PlaybackDevices.cend())
  740. throw al::backend_exception{al::backend_error::NoDevice,
  741. "Device name \"{}\" not found", name};
  742. pulse_name = iter->device_name;
  743. mDeviceName = iter->name;
  744. }
  745. MainloopUniqueLock plock{mMainloop};
  746. plock.connectContext();
  747. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
  748. PA_STREAM_FIX_CHANNELS};
  749. if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
  750. flags |= PA_STREAM_DONT_MOVE;
  751. pa_sample_spec spec{};
  752. spec.format = PA_SAMPLE_S16NE;
  753. spec.rate = 44100;
  754. spec.channels = 2;
  755. if(pulse_name.empty())
  756. {
  757. static const auto defname = al::getenv("ALSOFT_PULSE_DEFAULT");
  758. if(defname) pulse_name = *defname;
  759. }
  760. TRACE("Connecting to \"{}\"", pulse_name.empty() ? "(default)"sv:std::string_view{pulse_name});
  761. mStream = plock.connectStream(pulse_name, flags, nullptr, &spec, nullptr,
  762. BackendType::Playback);
  763. static constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
  764. { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); };
  765. pa_stream_set_moved_callback(mStream, move_callback, this);
  766. mFrameSize = static_cast<uint>(pa_frame_size(pa_stream_get_sample_spec(mStream)));
  767. if(!pulse_name.empty())
  768. mDeviceId.emplace(std::move(pulse_name));
  769. if(mDeviceName.empty())
  770. {
  771. static constexpr auto name_callback = [](pa_context *context, const pa_sink_info *info,
  772. int eol, void *pdata) noexcept
  773. { return static_cast<PulsePlayback*>(pdata)->sinkNameCallback(context, info, eol); };
  774. pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(),
  775. pa_stream_get_device_name(mStream), name_callback, this)};
  776. plock.waitForOperation(op);
  777. }
  778. }
  779. bool PulsePlayback::reset()
  780. {
  781. MainloopUniqueLock plock{mMainloop};
  782. const auto deviceName = mDeviceId ? mDeviceId->c_str() : nullptr;
  783. if(mStream)
  784. {
  785. pa_stream_set_state_callback(mStream, nullptr, nullptr);
  786. pa_stream_set_moved_callback(mStream, nullptr, nullptr);
  787. pa_stream_set_write_callback(mStream, nullptr, nullptr);
  788. pa_stream_set_buffer_attr_callback(mStream, nullptr, nullptr);
  789. pa_stream_disconnect(mStream);
  790. pa_stream_unref(mStream);
  791. mStream = nullptr;
  792. }
  793. auto info_cb = [](pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
  794. { return static_cast<PulsePlayback*>(pdata)->sinkInfoCallback(context, info, eol); };
  795. pa_operation *op{pa_context_get_sink_info_by_name(mMainloop.getContext(), deviceName, info_cb,
  796. this)};
  797. plock.waitForOperation(op);
  798. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING |
  799. PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS};
  800. if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
  801. flags |= PA_STREAM_DONT_MOVE;
  802. if(GetConfigValueBool(mDevice->mDeviceName, "pulse", "adjust-latency", false))
  803. {
  804. /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some
  805. * reason. So if the user wants to adjust the overall device latency,
  806. * we can't ask to get write signals as soon as minreq is reached.
  807. */
  808. flags &= ~PA_STREAM_EARLY_REQUESTS;
  809. flags |= PA_STREAM_ADJUST_LATENCY;
  810. }
  811. if(GetConfigValueBool(mDevice->mDeviceName, "pulse", "fix-rate", false)
  812. || !mDevice->Flags.test(FrequencyRequest))
  813. flags |= PA_STREAM_FIX_RATE;
  814. pa_channel_map chanmap{};
  815. switch(mDevice->FmtChans)
  816. {
  817. case DevFmtMono:
  818. chanmap = MonoChanMap;
  819. break;
  820. case DevFmtAmbi3D:
  821. mDevice->FmtChans = DevFmtStereo;
  822. /*fall-through*/
  823. case DevFmtStereo:
  824. chanmap = StereoChanMap;
  825. break;
  826. case DevFmtQuad:
  827. chanmap = QuadChanMap;
  828. break;
  829. case DevFmtX51:
  830. chanmap = (mIs51Rear ? X51RearChanMap : X51ChanMap);
  831. break;
  832. case DevFmtX61:
  833. chanmap = X61ChanMap;
  834. break;
  835. case DevFmtX71:
  836. case DevFmtX3D71:
  837. chanmap = X71ChanMap;
  838. break;
  839. case DevFmtX7144:
  840. mDevice->FmtChans = DevFmtX714;
  841. /*fall-through*/
  842. case DevFmtX714:
  843. chanmap = X714ChanMap;
  844. break;
  845. }
  846. setDefaultWFXChannelOrder();
  847. switch(mDevice->FmtType)
  848. {
  849. case DevFmtByte:
  850. mDevice->FmtType = DevFmtUByte;
  851. /* fall-through */
  852. case DevFmtUByte:
  853. mSpec.format = PA_SAMPLE_U8;
  854. break;
  855. case DevFmtUShort:
  856. mDevice->FmtType = DevFmtShort;
  857. /* fall-through */
  858. case DevFmtShort:
  859. mSpec.format = PA_SAMPLE_S16NE;
  860. break;
  861. case DevFmtUInt:
  862. mDevice->FmtType = DevFmtInt;
  863. /* fall-through */
  864. case DevFmtInt:
  865. mSpec.format = PA_SAMPLE_S32NE;
  866. break;
  867. case DevFmtFloat:
  868. mSpec.format = PA_SAMPLE_FLOAT32NE;
  869. break;
  870. }
  871. mSpec.rate = mDevice->mSampleRate;
  872. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  873. if(pa_sample_spec_valid(&mSpec) == 0)
  874. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"};
  875. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  876. mAttr.maxlength = ~0u;
  877. mAttr.tlength = mDevice->mBufferSize * frame_size;
  878. mAttr.prebuf = 0u;
  879. mAttr.minreq = mDevice->mUpdateSize * frame_size;
  880. mAttr.fragsize = ~0u;
  881. mStream = plock.connectStream(deviceName, flags, &mAttr, &mSpec, &chanmap,
  882. BackendType::Playback);
  883. constexpr auto state_callback = [](pa_stream *stream, void *pdata) noexcept
  884. { return static_cast<PulsePlayback*>(pdata)->streamStateCallback(stream); };
  885. pa_stream_set_state_callback(mStream, state_callback, this);
  886. constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
  887. { return static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); };
  888. pa_stream_set_moved_callback(mStream, move_callback, this);
  889. mSpec = *(pa_stream_get_sample_spec(mStream));
  890. mFrameSize = static_cast<uint>(pa_frame_size(&mSpec));
  891. if(mDevice->mSampleRate != mSpec.rate)
  892. {
  893. /* Server updated our playback rate, so modify the buffer attribs
  894. * accordingly.
  895. */
  896. const auto scale = static_cast<double>(mSpec.rate) / mDevice->mSampleRate;
  897. const auto perlen = std::clamp(std::round(scale*mDevice->mUpdateSize), 64.0, 8192.0);
  898. const auto bufmax = uint{std::numeric_limits<int>::max()} / mFrameSize;
  899. const auto buflen = std::clamp(std::round(scale*mDevice->mBufferSize), perlen*2.0,
  900. static_cast<double>(bufmax));
  901. mAttr.maxlength = ~0u;
  902. mAttr.tlength = static_cast<uint>(buflen) * mFrameSize;
  903. mAttr.prebuf = 0u;
  904. mAttr.minreq = static_cast<uint>(perlen) * mFrameSize;
  905. op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC,
  906. &mMainloop);
  907. plock.waitForOperation(op);
  908. mDevice->mSampleRate = mSpec.rate;
  909. }
  910. constexpr auto attr_callback = [](pa_stream *stream, void *pdata) noexcept
  911. { return static_cast<PulsePlayback*>(pdata)->bufferAttrCallback(stream); };
  912. pa_stream_set_buffer_attr_callback(mStream, attr_callback, this);
  913. bufferAttrCallback(mStream);
  914. mDevice->mBufferSize = mAttr.tlength / mFrameSize;
  915. mDevice->mUpdateSize = mAttr.minreq / mFrameSize;
  916. return true;
  917. }
  918. void PulsePlayback::start()
  919. {
  920. MainloopUniqueLock plock{mMainloop};
  921. /* Write some samples to fill the buffer before we start feeding it newly
  922. * mixed samples.
  923. */
  924. if(size_t todo{pa_stream_writable_size(mStream)})
  925. {
  926. void *buf{pa_xmalloc(todo)};
  927. mDevice->renderSamples(buf, static_cast<uint>(todo/mFrameSize), mSpec.channels);
  928. pa_stream_write(mStream, buf, todo, pa_xfree, 0, PA_SEEK_RELATIVE);
  929. }
  930. constexpr auto stream_write = [](pa_stream *stream, size_t nbytes, void *pdata) noexcept
  931. { return static_cast<PulsePlayback*>(pdata)->streamWriteCallback(stream, nbytes); };
  932. pa_stream_set_write_callback(mStream, stream_write, this);
  933. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  934. &mMainloop)};
  935. plock.waitForOperation(op);
  936. }
  937. void PulsePlayback::stop()
  938. {
  939. MainloopUniqueLock plock{mMainloop};
  940. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  941. &mMainloop)};
  942. plock.waitForOperation(op);
  943. pa_stream_set_write_callback(mStream, nullptr, nullptr);
  944. }
  945. ClockLatency PulsePlayback::getClockLatency()
  946. {
  947. ClockLatency ret{};
  948. pa_usec_t latency{};
  949. int neg{}, err{};
  950. {
  951. MainloopUniqueLock plock{mMainloop};
  952. ret.ClockTime = mDevice->getClockTime();
  953. err = pa_stream_get_latency(mStream, &latency, &neg);
  954. }
  955. if(err != 0) UNLIKELY
  956. {
  957. /* If err = -PA_ERR_NODATA, it means we were called too soon after
  958. * starting the stream and no timing info has been received from the
  959. * server yet. Give a generic value since nothing better is available.
  960. */
  961. if(err != -PA_ERR_NODATA)
  962. ERR("Failed to get stream latency: {:#x}", as_unsigned(err));
  963. latency = mDevice->mBufferSize - mDevice->mUpdateSize;
  964. neg = 0;
  965. }
  966. else if(neg) UNLIKELY
  967. latency = 0;
  968. ret.Latency = std::chrono::microseconds{latency};
  969. return ret;
  970. }
  971. struct PulseCapture final : public BackendBase {
  972. explicit PulseCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  973. ~PulseCapture() override;
  974. void streamStateCallback(pa_stream *stream) noexcept;
  975. void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept;
  976. void streamMovedCallback(pa_stream *stream) noexcept;
  977. void open(std::string_view name) override;
  978. void start() override;
  979. void stop() override;
  980. void captureSamples(std::byte *buffer, uint samples) override;
  981. uint availableSamples() override;
  982. ClockLatency getClockLatency() override;
  983. PulseMainloop mMainloop;
  984. std::optional<std::string> mDeviceId{std::nullopt};
  985. al::span<const std::byte> mCapBuffer;
  986. size_t mHoleLength{0};
  987. size_t mPacketLength{0};
  988. uint mLastReadable{0u};
  989. std::byte mSilentVal{};
  990. pa_buffer_attr mAttr{};
  991. pa_sample_spec mSpec{};
  992. pa_stream *mStream{nullptr};
  993. };
  994. PulseCapture::~PulseCapture()
  995. { if(mStream) mMainloop.close(mStream); }
  996. void PulseCapture::streamStateCallback(pa_stream *stream) noexcept
  997. {
  998. if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
  999. {
  1000. ERR("Received stream failure!");
  1001. mDevice->handleDisconnect("Capture stream failure");
  1002. }
  1003. mMainloop.signal();
  1004. }
  1005. void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept
  1006. {
  1007. if(eol)
  1008. {
  1009. mMainloop.signal();
  1010. return;
  1011. }
  1012. mDeviceName = info->description;
  1013. }
  1014. void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept
  1015. {
  1016. mDeviceId = pa_stream_get_device_name(stream);
  1017. TRACE("Stream moved to {}", *mDeviceId);
  1018. }
  1019. void PulseCapture::open(std::string_view name)
  1020. {
  1021. if(!mMainloop)
  1022. {
  1023. mMainloop = PulseMainloop::Create();
  1024. if(mMainloop.start() != 0)
  1025. throw al::backend_exception{al::backend_error::DeviceError,
  1026. "Failed to start device mainloop"};
  1027. }
  1028. auto pulse_name = std::string{};
  1029. if(!name.empty())
  1030. {
  1031. auto match_name = [name](const DevMap &entry) -> bool
  1032. { return entry.name == name || entry.device_name == name; };
  1033. auto plock = MainloopUniqueLock{gGlobalMainloop};
  1034. auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_name);
  1035. if(iter == CaptureDevices.cend())
  1036. throw al::backend_exception{al::backend_error::NoDevice,
  1037. "Device name \"{}\" not found", name};
  1038. pulse_name = iter->device_name;
  1039. mDeviceName = iter->name;
  1040. }
  1041. MainloopUniqueLock plock{mMainloop};
  1042. plock.connectContext();
  1043. pa_channel_map chanmap{};
  1044. switch(mDevice->FmtChans)
  1045. {
  1046. case DevFmtMono: chanmap = MonoChanMap; break;
  1047. case DevFmtStereo: chanmap = StereoChanMap; break;
  1048. case DevFmtQuad: chanmap = QuadChanMap; break;
  1049. case DevFmtX51: chanmap = X51ChanMap; break;
  1050. case DevFmtX61: chanmap = X61ChanMap; break;
  1051. case DevFmtX71: chanmap = X71ChanMap; break;
  1052. case DevFmtX714: chanmap = X714ChanMap; break;
  1053. case DevFmtX7144:
  1054. case DevFmtX3D71:
  1055. case DevFmtAmbi3D:
  1056. throw al::backend_exception{al::backend_error::DeviceError, "{} capture not supported",
  1057. DevFmtChannelsString(mDevice->FmtChans)};
  1058. }
  1059. setDefaultWFXChannelOrder();
  1060. switch(mDevice->FmtType)
  1061. {
  1062. case DevFmtUByte:
  1063. mSilentVal = std::byte(0x80);
  1064. mSpec.format = PA_SAMPLE_U8;
  1065. break;
  1066. case DevFmtShort:
  1067. mSpec.format = PA_SAMPLE_S16NE;
  1068. break;
  1069. case DevFmtInt:
  1070. mSpec.format = PA_SAMPLE_S32NE;
  1071. break;
  1072. case DevFmtFloat:
  1073. mSpec.format = PA_SAMPLE_FLOAT32NE;
  1074. break;
  1075. case DevFmtByte:
  1076. case DevFmtUShort:
  1077. case DevFmtUInt:
  1078. throw al::backend_exception{al::backend_error::DeviceError,
  1079. "{} capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
  1080. }
  1081. mSpec.rate = mDevice->mSampleRate;
  1082. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  1083. if(pa_sample_spec_valid(&mSpec) == 0)
  1084. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"};
  1085. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  1086. const uint samples{std::max(mDevice->mBufferSize, mDevice->mSampleRate*100u/1000u)};
  1087. mAttr.minreq = ~0u;
  1088. mAttr.prebuf = ~0u;
  1089. mAttr.maxlength = samples * frame_size;
  1090. mAttr.tlength = ~0u;
  1091. mAttr.fragsize = std::min(samples, mDevice->mSampleRate*50u/1000u) * frame_size;
  1092. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY};
  1093. if(!GetConfigValueBool({}, "pulse", "allow-moves", true))
  1094. flags |= PA_STREAM_DONT_MOVE;
  1095. TRACE("Connecting to \"{}\"", pulse_name.empty() ? "(default)"sv:std::string_view{pulse_name});
  1096. mStream = plock.connectStream(pulse_name, flags, &mAttr, &mSpec, &chanmap,
  1097. BackendType::Capture);
  1098. constexpr auto move_callback = [](pa_stream *stream, void *pdata) noexcept
  1099. { return static_cast<PulseCapture*>(pdata)->streamMovedCallback(stream); };
  1100. pa_stream_set_moved_callback(mStream, move_callback, this);
  1101. constexpr auto state_callback = [](pa_stream *stream, void *pdata) noexcept
  1102. { return static_cast<PulseCapture*>(pdata)->streamStateCallback(stream); };
  1103. pa_stream_set_state_callback(mStream, state_callback, this);
  1104. if(!pulse_name.empty())
  1105. mDeviceId.emplace(std::move(pulse_name));
  1106. if(mDeviceName.empty())
  1107. {
  1108. constexpr auto name_callback = [](pa_context *context, const pa_source_info *info, int eol,
  1109. void *pdata) noexcept
  1110. { return static_cast<PulseCapture*>(pdata)->sourceNameCallback(context, info, eol); };
  1111. pa_operation *op{pa_context_get_source_info_by_name(mMainloop.getContext(),
  1112. pa_stream_get_device_name(mStream), name_callback, this)};
  1113. plock.waitForOperation(op);
  1114. }
  1115. }
  1116. void PulseCapture::start()
  1117. {
  1118. MainloopUniqueLock plock{mMainloop};
  1119. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  1120. &mMainloop)};
  1121. plock.waitForOperation(op);
  1122. }
  1123. void PulseCapture::stop()
  1124. {
  1125. MainloopUniqueLock plock{mMainloop};
  1126. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  1127. &mMainloop)};
  1128. plock.waitForOperation(op);
  1129. }
  1130. void PulseCapture::captureSamples(std::byte *buffer, uint samples)
  1131. {
  1132. al::span<std::byte> dstbuf{buffer, samples * pa_frame_size(&mSpec)};
  1133. /* Capture is done in fragment-sized chunks, so we loop until we get all
  1134. * that's available.
  1135. */
  1136. mLastReadable -= static_cast<uint>(dstbuf.size());
  1137. while(!dstbuf.empty())
  1138. {
  1139. if(mHoleLength > 0) UNLIKELY
  1140. {
  1141. const size_t rem{std::min(dstbuf.size(), mHoleLength)};
  1142. std::fill_n(dstbuf.begin(), rem, mSilentVal);
  1143. dstbuf = dstbuf.subspan(rem);
  1144. mHoleLength -= rem;
  1145. continue;
  1146. }
  1147. if(!mCapBuffer.empty())
  1148. {
  1149. const size_t rem{std::min(dstbuf.size(), mCapBuffer.size())};
  1150. std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin());
  1151. dstbuf = dstbuf.subspan(rem);
  1152. mCapBuffer = mCapBuffer.subspan(rem);
  1153. continue;
  1154. }
  1155. if(!mDevice->Connected.load(std::memory_order_acquire)) UNLIKELY
  1156. break;
  1157. MainloopUniqueLock plock{mMainloop};
  1158. if(mPacketLength > 0)
  1159. {
  1160. pa_stream_drop(mStream);
  1161. mPacketLength = 0;
  1162. }
  1163. const pa_stream_state_t state{pa_stream_get_state(mStream)};
  1164. if(!PA_STREAM_IS_GOOD(state)) UNLIKELY
  1165. {
  1166. mDevice->handleDisconnect("Bad capture state: {}", al::to_underlying(state));
  1167. break;
  1168. }
  1169. const void *capbuf{};
  1170. size_t caplen{};
  1171. if(pa_stream_peek(mStream, &capbuf, &caplen) < 0) UNLIKELY
  1172. {
  1173. mDevice->handleDisconnect("Failed retrieving capture samples: {}",
  1174. pa_strerror(pa_context_errno(mMainloop.getContext())));
  1175. break;
  1176. }
  1177. plock.unlock();
  1178. if(caplen == 0) break;
  1179. if(!capbuf) UNLIKELY
  1180. mHoleLength = caplen;
  1181. else
  1182. mCapBuffer = {static_cast<const std::byte*>(capbuf), caplen};
  1183. mPacketLength = caplen;
  1184. }
  1185. if(!dstbuf.empty())
  1186. std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal);
  1187. }
  1188. uint PulseCapture::availableSamples()
  1189. {
  1190. size_t readable{std::max(mCapBuffer.size(), mHoleLength)};
  1191. if(mDevice->Connected.load(std::memory_order_acquire))
  1192. {
  1193. MainloopUniqueLock plock{mMainloop};
  1194. size_t got{pa_stream_readable_size(mStream)};
  1195. if(static_cast<ssize_t>(got) < 0) UNLIKELY
  1196. {
  1197. const char *err{pa_strerror(static_cast<int>(got))};
  1198. ERR("pa_stream_readable_size() failed: {}", err);
  1199. mDevice->handleDisconnect("Failed getting readable size: {}", err);
  1200. }
  1201. else
  1202. {
  1203. /* "readable" is the number of bytes from the last packet that have
  1204. * not yet been read by the caller. So add the stream's readable
  1205. * size excluding the last packet (the stream size includes the
  1206. * last packet until it's dropped).
  1207. */
  1208. if(got > mPacketLength)
  1209. readable += got - mPacketLength;
  1210. }
  1211. }
  1212. /* Avoid uint overflow, and avoid decreasing the readable count. */
  1213. readable = std::min<size_t>(readable, std::numeric_limits<uint>::max());
  1214. mLastReadable = std::max(mLastReadable, static_cast<uint>(readable));
  1215. return mLastReadable / static_cast<uint>(pa_frame_size(&mSpec));
  1216. }
  1217. ClockLatency PulseCapture::getClockLatency()
  1218. {
  1219. ClockLatency ret{};
  1220. pa_usec_t latency{};
  1221. int neg{}, err{};
  1222. {
  1223. MainloopUniqueLock plock{mMainloop};
  1224. ret.ClockTime = mDevice->getClockTime();
  1225. err = pa_stream_get_latency(mStream, &latency, &neg);
  1226. }
  1227. if(err != 0) UNLIKELY
  1228. {
  1229. ERR("Failed to get stream latency: {:#x}", as_unsigned(err));
  1230. latency = 0;
  1231. neg = 0;
  1232. }
  1233. else if(neg) UNLIKELY
  1234. latency = 0;
  1235. ret.Latency = std::chrono::microseconds{latency};
  1236. return ret;
  1237. }
  1238. } // namespace
  1239. bool PulseBackendFactory::init()
  1240. {
  1241. #if HAVE_DYNLOAD
  1242. if(!pulse_handle)
  1243. {
  1244. #ifdef _WIN32
  1245. #define PALIB "libpulse-0.dll"
  1246. #elif defined(__APPLE__) && defined(__MACH__)
  1247. #define PALIB "libpulse.0.dylib"
  1248. #else
  1249. #define PALIB "libpulse.so.0"
  1250. #endif
  1251. pulse_handle = LoadLib(PALIB);
  1252. if(!pulse_handle)
  1253. {
  1254. WARN("Failed to load {}", PALIB);
  1255. return false;
  1256. }
  1257. std::string missing_funcs;
  1258. #define LOAD_FUNC(x) do { \
  1259. p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
  1260. if(!(p##x)) missing_funcs += "\n" #x; \
  1261. } while(0)
  1262. PULSE_FUNCS(LOAD_FUNC)
  1263. #undef LOAD_FUNC
  1264. if(!missing_funcs.empty())
  1265. {
  1266. WARN("Missing expected functions:{}", missing_funcs);
  1267. CloseLib(pulse_handle);
  1268. pulse_handle = nullptr;
  1269. return false;
  1270. }
  1271. }
  1272. #endif
  1273. pulse_ctx_flags = PA_CONTEXT_NOFLAGS;
  1274. if(!GetConfigValueBool({}, "pulse", "spawn-server", false))
  1275. pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
  1276. try {
  1277. if(!gGlobalMainloop)
  1278. {
  1279. gGlobalMainloop = PulseMainloop::Create();
  1280. if(gGlobalMainloop.start() != 0)
  1281. {
  1282. gGlobalMainloop = nullptr;
  1283. return false;
  1284. }
  1285. }
  1286. MainloopUniqueLock plock{gGlobalMainloop};
  1287. plock.connectContext();
  1288. plock.setEventHandler();
  1289. return true;
  1290. }
  1291. catch(...) {
  1292. return false;
  1293. }
  1294. }
  1295. bool PulseBackendFactory::querySupport(BackendType type)
  1296. { return type == BackendType::Playback || type == BackendType::Capture; }
  1297. auto PulseBackendFactory::enumerate(BackendType type) -> std::vector<std::string>
  1298. {
  1299. std::vector<std::string> outnames;
  1300. auto add_playback_device = [&outnames](const DevMap &entry) -> void
  1301. {
  1302. if(entry.device_name == DefaultPlaybackDevName)
  1303. outnames.emplace(outnames.cbegin(), entry.name);
  1304. else
  1305. outnames.push_back(entry.name);
  1306. };
  1307. auto add_capture_device = [&outnames](const DevMap &entry) -> void
  1308. {
  1309. if(entry.device_name == DefaultCaptureDevName)
  1310. outnames.emplace(outnames.cbegin(), entry.name);
  1311. else
  1312. outnames.push_back(entry.name);
  1313. };
  1314. auto plock = MainloopUniqueLock{gGlobalMainloop};
  1315. switch(type)
  1316. {
  1317. case BackendType::Playback:
  1318. outnames.reserve(PlaybackDevices.size());
  1319. std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_playback_device);
  1320. break;
  1321. case BackendType::Capture:
  1322. outnames.reserve(CaptureDevices.size());
  1323. std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_capture_device);
  1324. break;
  1325. }
  1326. return outnames;
  1327. }
  1328. BackendPtr PulseBackendFactory::createBackend(DeviceBase *device, BackendType type)
  1329. {
  1330. if(type == BackendType::Playback)
  1331. return BackendPtr{new PulsePlayback{device}};
  1332. if(type == BackendType::Capture)
  1333. return BackendPtr{new PulseCapture{device}};
  1334. return nullptr;
  1335. }
  1336. BackendFactory &PulseBackendFactory::getFactory()
  1337. {
  1338. static PulseBackendFactory factory{};
  1339. return factory;
  1340. }
  1341. alc::EventSupport PulseBackendFactory::queryEventSupport(alc::EventType eventType, BackendType)
  1342. {
  1343. switch(eventType)
  1344. {
  1345. case alc::EventType::DeviceAdded:
  1346. case alc::EventType::DeviceRemoved:
  1347. case alc::EventType::DefaultDeviceChanged:
  1348. return alc::EventSupport::FullSupport;
  1349. case alc::EventType::Count:
  1350. break;
  1351. }
  1352. return alc::EventSupport::NoSupport;
  1353. }