pulseaudio.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521
  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 "backends/pulseaudio.h"
  23. #include <poll.h>
  24. #include <cstring>
  25. #include <array>
  26. #include <string>
  27. #include <vector>
  28. #include <atomic>
  29. #include <thread>
  30. #include <algorithm>
  31. #include <functional>
  32. #include <condition_variable>
  33. #include "alcmain.h"
  34. #include "alu.h"
  35. #include "alconfig.h"
  36. #include "compat.h"
  37. #include "core/logging.h"
  38. #include "dynload.h"
  39. #include "strutils.h"
  40. #include <pulse/pulseaudio.h>
  41. namespace {
  42. #ifdef HAVE_DYNLOAD
  43. #define PULSE_FUNCS(MAGIC) \
  44. MAGIC(pa_mainloop_new); \
  45. MAGIC(pa_mainloop_free); \
  46. MAGIC(pa_mainloop_set_poll_func); \
  47. MAGIC(pa_mainloop_run); \
  48. MAGIC(pa_mainloop_quit); \
  49. MAGIC(pa_mainloop_get_api); \
  50. MAGIC(pa_context_new); \
  51. MAGIC(pa_context_unref); \
  52. MAGIC(pa_context_get_state); \
  53. MAGIC(pa_context_disconnect); \
  54. MAGIC(pa_context_set_state_callback); \
  55. MAGIC(pa_context_errno); \
  56. MAGIC(pa_context_connect); \
  57. MAGIC(pa_context_get_server_info); \
  58. MAGIC(pa_context_get_sink_info_by_name); \
  59. MAGIC(pa_context_get_sink_info_list); \
  60. MAGIC(pa_context_get_source_info_by_name); \
  61. MAGIC(pa_context_get_source_info_list); \
  62. MAGIC(pa_stream_new); \
  63. MAGIC(pa_stream_unref); \
  64. MAGIC(pa_stream_drop); \
  65. MAGIC(pa_stream_get_state); \
  66. MAGIC(pa_stream_peek); \
  67. MAGIC(pa_stream_write); \
  68. MAGIC(pa_stream_connect_record); \
  69. MAGIC(pa_stream_connect_playback); \
  70. MAGIC(pa_stream_readable_size); \
  71. MAGIC(pa_stream_writable_size); \
  72. MAGIC(pa_stream_is_corked); \
  73. MAGIC(pa_stream_cork); \
  74. MAGIC(pa_stream_is_suspended); \
  75. MAGIC(pa_stream_get_device_name); \
  76. MAGIC(pa_stream_get_latency); \
  77. MAGIC(pa_stream_set_write_callback); \
  78. MAGIC(pa_stream_set_buffer_attr); \
  79. MAGIC(pa_stream_get_buffer_attr); \
  80. MAGIC(pa_stream_get_sample_spec); \
  81. MAGIC(pa_stream_get_time); \
  82. MAGIC(pa_stream_set_read_callback); \
  83. MAGIC(pa_stream_set_state_callback); \
  84. MAGIC(pa_stream_set_moved_callback); \
  85. MAGIC(pa_stream_set_underflow_callback); \
  86. MAGIC(pa_stream_new_with_proplist); \
  87. MAGIC(pa_stream_disconnect); \
  88. MAGIC(pa_stream_set_buffer_attr_callback); \
  89. MAGIC(pa_stream_begin_write); \
  90. MAGIC(pa_channel_map_init_auto); \
  91. MAGIC(pa_channel_map_parse); \
  92. MAGIC(pa_channel_map_snprint); \
  93. MAGIC(pa_channel_map_equal); \
  94. MAGIC(pa_channel_map_superset); \
  95. MAGIC(pa_channel_position_to_string); \
  96. MAGIC(pa_operation_get_state); \
  97. MAGIC(pa_operation_unref); \
  98. MAGIC(pa_sample_spec_valid); \
  99. MAGIC(pa_frame_size); \
  100. MAGIC(pa_strerror); \
  101. MAGIC(pa_path_get_filename); \
  102. MAGIC(pa_get_binary_name); \
  103. MAGIC(pa_xmalloc); \
  104. MAGIC(pa_xfree);
  105. void *pulse_handle;
  106. #define MAKE_FUNC(x) decltype(x) * p##x
  107. PULSE_FUNCS(MAKE_FUNC)
  108. #undef MAKE_FUNC
  109. #ifndef IN_IDE_PARSER
  110. #define pa_mainloop_new ppa_mainloop_new
  111. #define pa_mainloop_free ppa_mainloop_free
  112. #define pa_mainloop_set_poll_func ppa_mainloop_set_poll_func
  113. #define pa_mainloop_run ppa_mainloop_run
  114. #define pa_mainloop_quit ppa_mainloop_quit
  115. #define pa_mainloop_get_api ppa_mainloop_get_api
  116. #define pa_context_new ppa_context_new
  117. #define pa_context_unref ppa_context_unref
  118. #define pa_context_get_state ppa_context_get_state
  119. #define pa_context_disconnect ppa_context_disconnect
  120. #define pa_context_set_state_callback ppa_context_set_state_callback
  121. #define pa_context_errno ppa_context_errno
  122. #define pa_context_connect ppa_context_connect
  123. #define pa_context_get_server_info ppa_context_get_server_info
  124. #define pa_context_get_sink_info_by_name ppa_context_get_sink_info_by_name
  125. #define pa_context_get_sink_info_list ppa_context_get_sink_info_list
  126. #define pa_context_get_source_info_by_name ppa_context_get_source_info_by_name
  127. #define pa_context_get_source_info_list ppa_context_get_source_info_list
  128. #define pa_stream_new ppa_stream_new
  129. #define pa_stream_unref ppa_stream_unref
  130. #define pa_stream_disconnect ppa_stream_disconnect
  131. #define pa_stream_drop ppa_stream_drop
  132. #define pa_stream_set_write_callback ppa_stream_set_write_callback
  133. #define pa_stream_set_buffer_attr ppa_stream_set_buffer_attr
  134. #define pa_stream_get_buffer_attr ppa_stream_get_buffer_attr
  135. #define pa_stream_get_sample_spec ppa_stream_get_sample_spec
  136. #define pa_stream_get_time ppa_stream_get_time
  137. #define pa_stream_set_read_callback ppa_stream_set_read_callback
  138. #define pa_stream_set_state_callback ppa_stream_set_state_callback
  139. #define pa_stream_set_moved_callback ppa_stream_set_moved_callback
  140. #define pa_stream_set_underflow_callback ppa_stream_set_underflow_callback
  141. #define pa_stream_connect_record ppa_stream_connect_record
  142. #define pa_stream_connect_playback ppa_stream_connect_playback
  143. #define pa_stream_readable_size ppa_stream_readable_size
  144. #define pa_stream_writable_size ppa_stream_writable_size
  145. #define pa_stream_is_corked ppa_stream_is_corked
  146. #define pa_stream_cork ppa_stream_cork
  147. #define pa_stream_is_suspended ppa_stream_is_suspended
  148. #define pa_stream_get_device_name ppa_stream_get_device_name
  149. #define pa_stream_get_latency ppa_stream_get_latency
  150. #define pa_stream_set_buffer_attr_callback ppa_stream_set_buffer_attr_callback
  151. #define pa_stream_begin_write ppa_stream_begin_write
  152. #define pa_channel_map_init_auto ppa_channel_map_init_auto
  153. #define pa_channel_map_parse ppa_channel_map_parse
  154. #define pa_channel_map_snprint ppa_channel_map_snprint
  155. #define pa_channel_map_equal ppa_channel_map_equal
  156. #define pa_channel_map_superset ppa_channel_map_superset
  157. #define pa_channel_position_to_string ppa_channel_position_to_string
  158. #define pa_operation_get_state ppa_operation_get_state
  159. #define pa_operation_unref ppa_operation_unref
  160. #define pa_sample_spec_valid ppa_sample_spec_valid
  161. #define pa_frame_size ppa_frame_size
  162. #define pa_strerror ppa_strerror
  163. #define pa_stream_get_state ppa_stream_get_state
  164. #define pa_stream_peek ppa_stream_peek
  165. #define pa_stream_write ppa_stream_write
  166. #define pa_xfree ppa_xfree
  167. #define pa_path_get_filename ppa_path_get_filename
  168. #define pa_get_binary_name ppa_get_binary_name
  169. #define pa_xmalloc ppa_xmalloc
  170. #endif /* IN_IDE_PARSER */
  171. #endif
  172. constexpr pa_channel_map MonoChanMap{
  173. 1, {PA_CHANNEL_POSITION_MONO}
  174. }, StereoChanMap{
  175. 2, {PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT}
  176. }, QuadChanMap{
  177. 4, {
  178. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  179. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
  180. }
  181. }, X51ChanMap{
  182. 6, {
  183. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  184. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  185. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  186. }
  187. }, X51RearChanMap{
  188. 6, {
  189. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  190. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  191. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT
  192. }
  193. }, X61ChanMap{
  194. 7, {
  195. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  196. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  197. PA_CHANNEL_POSITION_REAR_CENTER,
  198. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  199. }
  200. }, X71ChanMap{
  201. 8, {
  202. PA_CHANNEL_POSITION_FRONT_LEFT, PA_CHANNEL_POSITION_FRONT_RIGHT,
  203. PA_CHANNEL_POSITION_FRONT_CENTER, PA_CHANNEL_POSITION_LFE,
  204. PA_CHANNEL_POSITION_REAR_LEFT, PA_CHANNEL_POSITION_REAR_RIGHT,
  205. PA_CHANNEL_POSITION_SIDE_LEFT, PA_CHANNEL_POSITION_SIDE_RIGHT
  206. }
  207. };
  208. al::optional<Channel> ChannelFromPulse(pa_channel_position_t chan)
  209. {
  210. switch(chan)
  211. {
  212. case PA_CHANNEL_POSITION_INVALID: break;
  213. case PA_CHANNEL_POSITION_MONO: return al::make_optional(FrontCenter);
  214. case PA_CHANNEL_POSITION_FRONT_LEFT: return al::make_optional(FrontLeft);
  215. case PA_CHANNEL_POSITION_FRONT_RIGHT: return al::make_optional(FrontRight);
  216. case PA_CHANNEL_POSITION_FRONT_CENTER: return al::make_optional(FrontCenter);
  217. case PA_CHANNEL_POSITION_REAR_CENTER: return al::make_optional(BackCenter);
  218. case PA_CHANNEL_POSITION_REAR_LEFT: return al::make_optional(BackLeft);
  219. case PA_CHANNEL_POSITION_REAR_RIGHT: return al::make_optional(BackRight);
  220. case PA_CHANNEL_POSITION_LFE: return al::make_optional(LFE);
  221. case PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: break;
  222. case PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: break;
  223. case PA_CHANNEL_POSITION_SIDE_LEFT: return al::make_optional(SideLeft);
  224. case PA_CHANNEL_POSITION_SIDE_RIGHT: return al::make_optional(SideRight);
  225. case PA_CHANNEL_POSITION_AUX0: break;
  226. case PA_CHANNEL_POSITION_AUX1: break;
  227. case PA_CHANNEL_POSITION_AUX2: break;
  228. case PA_CHANNEL_POSITION_AUX3: break;
  229. case PA_CHANNEL_POSITION_AUX4: break;
  230. case PA_CHANNEL_POSITION_AUX5: break;
  231. case PA_CHANNEL_POSITION_AUX6: break;
  232. case PA_CHANNEL_POSITION_AUX7: break;
  233. case PA_CHANNEL_POSITION_AUX8: break;
  234. case PA_CHANNEL_POSITION_AUX9: break;
  235. case PA_CHANNEL_POSITION_AUX10: break;
  236. case PA_CHANNEL_POSITION_AUX11: break;
  237. case PA_CHANNEL_POSITION_AUX12: break;
  238. case PA_CHANNEL_POSITION_AUX13: break;
  239. case PA_CHANNEL_POSITION_AUX14: break;
  240. case PA_CHANNEL_POSITION_AUX15: break;
  241. case PA_CHANNEL_POSITION_AUX16: break;
  242. case PA_CHANNEL_POSITION_AUX17: break;
  243. case PA_CHANNEL_POSITION_AUX18: break;
  244. case PA_CHANNEL_POSITION_AUX19: break;
  245. case PA_CHANNEL_POSITION_AUX20: break;
  246. case PA_CHANNEL_POSITION_AUX21: break;
  247. case PA_CHANNEL_POSITION_AUX22: break;
  248. case PA_CHANNEL_POSITION_AUX23: break;
  249. case PA_CHANNEL_POSITION_AUX24: break;
  250. case PA_CHANNEL_POSITION_AUX25: break;
  251. case PA_CHANNEL_POSITION_AUX26: break;
  252. case PA_CHANNEL_POSITION_AUX27: break;
  253. case PA_CHANNEL_POSITION_AUX28: break;
  254. case PA_CHANNEL_POSITION_AUX29: break;
  255. case PA_CHANNEL_POSITION_AUX30: break;
  256. case PA_CHANNEL_POSITION_AUX31: break;
  257. case PA_CHANNEL_POSITION_TOP_CENTER: return al::make_optional(TopCenter);
  258. case PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return al::make_optional(TopFrontLeft);
  259. case PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return al::make_optional(TopFrontRight);
  260. case PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return al::make_optional(TopFrontCenter);
  261. case PA_CHANNEL_POSITION_TOP_REAR_LEFT: return al::make_optional(TopBackLeft);
  262. case PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return al::make_optional(TopBackRight);
  263. case PA_CHANNEL_POSITION_TOP_REAR_CENTER: return al::make_optional(TopBackCenter);
  264. case PA_CHANNEL_POSITION_MAX: break;
  265. }
  266. WARN("Unexpected channel enum %d (%s)\n", chan, pa_channel_position_to_string(chan));
  267. return al::nullopt;
  268. }
  269. void SetChannelOrderFromMap(ALCdevice *device, const pa_channel_map &chanmap)
  270. {
  271. device->RealOut.ChannelIndex.fill(INVALID_CHANNEL_INDEX);
  272. for(uint i{0};i < chanmap.channels;++i)
  273. {
  274. if(auto label = ChannelFromPulse(chanmap.map[i]))
  275. device->RealOut.ChannelIndex[*label] = i;
  276. }
  277. }
  278. /* *grumble* Don't use enums for bitflags. */
  279. constexpr inline pa_stream_flags_t operator|(pa_stream_flags_t lhs, pa_stream_flags_t rhs)
  280. { return pa_stream_flags_t(int(lhs) | int(rhs)); }
  281. inline pa_stream_flags_t& operator|=(pa_stream_flags_t &lhs, pa_stream_flags_t rhs)
  282. {
  283. lhs = lhs | rhs;
  284. return lhs;
  285. }
  286. inline pa_stream_flags_t& operator&=(pa_stream_flags_t &lhs, int rhs)
  287. {
  288. lhs = pa_stream_flags_t(int(lhs) & rhs);
  289. return lhs;
  290. }
  291. inline pa_context_flags_t& operator|=(pa_context_flags_t &lhs, pa_context_flags_t rhs)
  292. {
  293. lhs = pa_context_flags_t(int(lhs) | int(rhs));
  294. return lhs;
  295. }
  296. struct DevMap {
  297. std::string name;
  298. std::string device_name;
  299. };
  300. bool checkName(const al::span<const DevMap> list, const std::string &name)
  301. {
  302. auto match_name = [&name](const DevMap &entry) -> bool { return entry.name == name; };
  303. return std::find_if(list.cbegin(), list.cend(), match_name) != list.cend();
  304. }
  305. al::vector<DevMap> PlaybackDevices;
  306. al::vector<DevMap> CaptureDevices;
  307. /* Global flags and properties */
  308. pa_context_flags_t pulse_ctx_flags;
  309. class PulseMainloop {
  310. std::thread mThread;
  311. std::mutex mMutex;
  312. std::condition_variable mCondVar;
  313. pa_mainloop *mMainloop{nullptr};
  314. static int poll(struct pollfd *ufds, unsigned long nfds, int timeout, void *userdata) noexcept
  315. {
  316. auto plock = static_cast<std::unique_lock<std::mutex>*>(userdata);
  317. plock->unlock();
  318. int r{::poll(ufds, nfds, timeout)};
  319. plock->lock();
  320. return r;
  321. }
  322. int mainloop_proc()
  323. {
  324. SetRTPriority();
  325. std::unique_lock<std::mutex> plock{mMutex};
  326. mMainloop = pa_mainloop_new();
  327. pa_mainloop_set_poll_func(mMainloop, poll, &plock);
  328. mCondVar.notify_all();
  329. int ret{};
  330. pa_mainloop_run(mMainloop, &ret);
  331. pa_mainloop_free(mMainloop);
  332. mMainloop = nullptr;
  333. return ret;
  334. }
  335. public:
  336. ~PulseMainloop()
  337. {
  338. if(mThread.joinable())
  339. {
  340. {
  341. std::lock_guard<std::mutex> _{mMutex};
  342. pa_mainloop_quit(mMainloop, 0);
  343. }
  344. mThread.join();
  345. }
  346. }
  347. std::unique_lock<std::mutex> getUniqueLock() { return std::unique_lock<std::mutex>{mMutex}; }
  348. std::condition_variable &getCondVar() noexcept { return mCondVar; }
  349. void contextStateCallback(pa_context *context) noexcept
  350. {
  351. pa_context_state_t state{pa_context_get_state(context)};
  352. if(state == PA_CONTEXT_READY || !PA_CONTEXT_IS_GOOD(state))
  353. mCondVar.notify_all();
  354. }
  355. static void contextStateCallbackC(pa_context *context, void *pdata) noexcept
  356. { static_cast<PulseMainloop*>(pdata)->contextStateCallback(context); }
  357. void streamStateCallback(pa_stream *stream) noexcept
  358. {
  359. pa_stream_state_t state{pa_stream_get_state(stream)};
  360. if(state == PA_STREAM_READY || !PA_STREAM_IS_GOOD(state))
  361. mCondVar.notify_all();
  362. }
  363. static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept
  364. { static_cast<PulseMainloop*>(pdata)->streamStateCallback(stream); }
  365. void streamSuccessCallback(pa_stream*, int) noexcept
  366. { mCondVar.notify_all(); }
  367. static void streamSuccessCallbackC(pa_stream *stream, int success, void *pdata) noexcept
  368. { static_cast<PulseMainloop*>(pdata)->streamSuccessCallback(stream, success); }
  369. void waitForOperation(pa_operation *op, std::unique_lock<std::mutex> &plock)
  370. {
  371. if(op)
  372. {
  373. mCondVar.wait(plock,
  374. [op]() -> bool { return pa_operation_get_state(op) != PA_OPERATION_RUNNING; });
  375. pa_operation_unref(op);
  376. }
  377. }
  378. pa_context *connectContext(std::unique_lock<std::mutex> &plock);
  379. pa_stream *connectStream(const char *device_name, std::unique_lock<std::mutex> &plock,
  380. pa_context *context, pa_stream_flags_t flags, pa_buffer_attr *attr, pa_sample_spec *spec,
  381. pa_channel_map *chanmap, BackendType type);
  382. void close(pa_context *context, pa_stream *stream);
  383. void deviceSinkCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
  384. {
  385. if(eol)
  386. {
  387. mCondVar.notify_all();
  388. return;
  389. }
  390. /* Skip this device is if it's already in the list. */
  391. auto match_devname = [info](const DevMap &entry) -> bool
  392. { return entry.device_name == info->name; };
  393. if(std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(), match_devname) != PlaybackDevices.cend())
  394. return;
  395. /* Make sure the display name (description) is unique. Append a number
  396. * counter as needed.
  397. */
  398. int count{1};
  399. std::string newname{info->description};
  400. while(checkName(PlaybackDevices, newname))
  401. {
  402. newname = info->description;
  403. newname += " #";
  404. newname += std::to_string(++count);
  405. }
  406. PlaybackDevices.emplace_back(DevMap{std::move(newname), info->name});
  407. DevMap &newentry = PlaybackDevices.back();
  408. TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
  409. }
  410. static void deviceSinkCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
  411. { static_cast<PulseMainloop*>(pdata)->deviceSinkCallback(context, info, eol); }
  412. void deviceSourceCallback(pa_context*, const pa_source_info *info, int eol) noexcept
  413. {
  414. if(eol)
  415. {
  416. mCondVar.notify_all();
  417. return;
  418. }
  419. /* Skip this device is if it's already in the list. */
  420. auto match_devname = [info](const DevMap &entry) -> bool
  421. { return entry.device_name == info->name; };
  422. if(std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(), match_devname) != CaptureDevices.cend())
  423. return;
  424. /* Make sure the display name (description) is unique. Append a number
  425. * counter as needed.
  426. */
  427. int count{1};
  428. std::string newname{info->description};
  429. while(checkName(CaptureDevices, newname))
  430. {
  431. newname = info->description;
  432. newname += " #";
  433. newname += std::to_string(++count);
  434. }
  435. CaptureDevices.emplace_back(DevMap{std::move(newname), info->name});
  436. DevMap &newentry = CaptureDevices.back();
  437. TRACE("Got device \"%s\", \"%s\"\n", newentry.name.c_str(), newentry.device_name.c_str());
  438. }
  439. static void deviceSourceCallbackC(pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept
  440. { static_cast<PulseMainloop*>(pdata)->deviceSourceCallback(context, info, eol); }
  441. void probePlaybackDevices();
  442. void probeCaptureDevices();
  443. };
  444. pa_context *PulseMainloop::connectContext(std::unique_lock<std::mutex> &plock)
  445. {
  446. const char *name{"OpenAL Soft"};
  447. const PathNamePair &binname = GetProcBinary();
  448. if(!binname.fname.empty())
  449. name = binname.fname.c_str();
  450. if(!mMainloop)
  451. {
  452. mThread = std::thread{std::mem_fn(&PulseMainloop::mainloop_proc), this};
  453. mCondVar.wait(plock, [this]() noexcept { return mMainloop; });
  454. }
  455. pa_context *context{pa_context_new(pa_mainloop_get_api(mMainloop), name)};
  456. if(!context) throw al::backend_exception{al::backend_error::OutOfMemory,
  457. "pa_context_new() failed"};
  458. pa_context_set_state_callback(context, &contextStateCallbackC, this);
  459. int err;
  460. if((err=pa_context_connect(context, nullptr, pulse_ctx_flags, nullptr)) >= 0)
  461. {
  462. pa_context_state_t state;
  463. while((state=pa_context_get_state(context)) != PA_CONTEXT_READY)
  464. {
  465. if(!PA_CONTEXT_IS_GOOD(state))
  466. {
  467. err = pa_context_errno(context);
  468. if(err > 0) err = -err;
  469. break;
  470. }
  471. mCondVar.wait(plock);
  472. }
  473. }
  474. pa_context_set_state_callback(context, nullptr, nullptr);
  475. if(err < 0)
  476. {
  477. pa_context_unref(context);
  478. throw al::backend_exception{al::backend_error::DeviceError, "Context did not connect (%s)",
  479. pa_strerror(err)};
  480. }
  481. return context;
  482. }
  483. pa_stream *PulseMainloop::connectStream(const char *device_name,
  484. std::unique_lock<std::mutex> &plock, pa_context *context, pa_stream_flags_t flags,
  485. pa_buffer_attr *attr, pa_sample_spec *spec, pa_channel_map *chanmap, BackendType type)
  486. {
  487. const char *stream_id{(type==BackendType::Playback) ? "Playback Stream" : "Capture Stream"};
  488. pa_stream *stream{pa_stream_new(context, stream_id, spec, chanmap)};
  489. if(!stream)
  490. throw al::backend_exception{al::backend_error::OutOfMemory, "pa_stream_new() failed (%s)",
  491. pa_strerror(pa_context_errno(context))};
  492. pa_stream_set_state_callback(stream, &streamStateCallbackC, this);
  493. int err{(type==BackendType::Playback) ?
  494. pa_stream_connect_playback(stream, device_name, attr, flags, nullptr, nullptr) :
  495. pa_stream_connect_record(stream, device_name, attr, flags)};
  496. if(err < 0)
  497. {
  498. pa_stream_unref(stream);
  499. throw al::backend_exception{al::backend_error::DeviceError, "%s did not connect (%s)",
  500. stream_id, pa_strerror(err)};
  501. }
  502. pa_stream_state_t state;
  503. while((state=pa_stream_get_state(stream)) != PA_STREAM_READY)
  504. {
  505. if(!PA_STREAM_IS_GOOD(state))
  506. {
  507. err = pa_context_errno(context);
  508. pa_stream_unref(stream);
  509. throw al::backend_exception{al::backend_error::DeviceError,
  510. "%s did not get ready (%s)", stream_id, pa_strerror(err)};
  511. }
  512. mCondVar.wait(plock);
  513. }
  514. pa_stream_set_state_callback(stream, nullptr, nullptr);
  515. return stream;
  516. }
  517. void PulseMainloop::close(pa_context *context, pa_stream *stream)
  518. {
  519. std::lock_guard<std::mutex> _{mMutex};
  520. if(stream)
  521. {
  522. pa_stream_set_state_callback(stream, nullptr, nullptr);
  523. pa_stream_set_moved_callback(stream, nullptr, nullptr);
  524. pa_stream_set_write_callback(stream, nullptr, nullptr);
  525. pa_stream_set_buffer_attr_callback(stream, nullptr, nullptr);
  526. pa_stream_disconnect(stream);
  527. pa_stream_unref(stream);
  528. }
  529. pa_context_disconnect(context);
  530. pa_context_unref(context);
  531. }
  532. void PulseMainloop::probePlaybackDevices()
  533. {
  534. pa_context *context{};
  535. pa_stream *stream{};
  536. PlaybackDevices.clear();
  537. try {
  538. std::unique_lock<std::mutex> plock{mMutex};
  539. context = connectContext(plock);
  540. pa_operation *op{pa_context_get_sink_info_by_name(context, nullptr,
  541. &deviceSinkCallbackC, this)};
  542. waitForOperation(op, plock);
  543. op = pa_context_get_sink_info_list(context, &deviceSinkCallbackC, this);
  544. waitForOperation(op, plock);
  545. pa_context_disconnect(context);
  546. pa_context_unref(context);
  547. context = nullptr;
  548. }
  549. catch(std::exception &e) {
  550. ERR("Error enumerating devices: %s\n", e.what());
  551. if(context) close(context, stream);
  552. }
  553. }
  554. void PulseMainloop::probeCaptureDevices()
  555. {
  556. pa_context *context{};
  557. pa_stream *stream{};
  558. CaptureDevices.clear();
  559. try {
  560. std::unique_lock<std::mutex> plock{mMutex};
  561. context = connectContext(plock);
  562. pa_operation *op{pa_context_get_source_info_by_name(context, nullptr,
  563. &deviceSourceCallbackC, this)};
  564. waitForOperation(op, plock);
  565. op = pa_context_get_source_info_list(context, &deviceSourceCallbackC, this);
  566. waitForOperation(op, plock);
  567. pa_context_disconnect(context);
  568. pa_context_unref(context);
  569. context = nullptr;
  570. }
  571. catch(std::exception &e) {
  572. ERR("Error enumerating devices: %s\n", e.what());
  573. if(context) close(context, stream);
  574. }
  575. }
  576. /* Used for initial connection test and enumeration. */
  577. PulseMainloop gGlobalMainloop;
  578. struct PulsePlayback final : public BackendBase {
  579. PulsePlayback(ALCdevice *device) noexcept : BackendBase{device} { }
  580. ~PulsePlayback() override;
  581. void bufferAttrCallback(pa_stream *stream) noexcept;
  582. static void bufferAttrCallbackC(pa_stream *stream, void *pdata) noexcept
  583. { static_cast<PulsePlayback*>(pdata)->bufferAttrCallback(stream); }
  584. void streamStateCallback(pa_stream *stream) noexcept;
  585. static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept
  586. { static_cast<PulsePlayback*>(pdata)->streamStateCallback(stream); }
  587. void streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept;
  588. static void streamWriteCallbackC(pa_stream *stream, size_t nbytes, void *pdata) noexcept
  589. { static_cast<PulsePlayback*>(pdata)->streamWriteCallback(stream, nbytes); }
  590. void sinkInfoCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
  591. static void sinkInfoCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
  592. { static_cast<PulsePlayback*>(pdata)->sinkInfoCallback(context, info, eol); }
  593. void sinkNameCallback(pa_context *context, const pa_sink_info *info, int eol) noexcept;
  594. static void sinkNameCallbackC(pa_context *context, const pa_sink_info *info, int eol, void *pdata) noexcept
  595. { static_cast<PulsePlayback*>(pdata)->sinkNameCallback(context, info, eol); }
  596. void streamMovedCallback(pa_stream *stream) noexcept;
  597. static void streamMovedCallbackC(pa_stream *stream, void *pdata) noexcept
  598. { static_cast<PulsePlayback*>(pdata)->streamMovedCallback(stream); }
  599. void open(const char *name) override;
  600. bool reset() override;
  601. void start() override;
  602. void stop() override;
  603. ClockLatency getClockLatency() override;
  604. PulseMainloop mMainloop;
  605. al::optional<std::string> mDeviceName{al::nullopt};
  606. pa_buffer_attr mAttr;
  607. pa_sample_spec mSpec;
  608. pa_stream *mStream{nullptr};
  609. pa_context *mContext{nullptr};
  610. uint mFrameSize{0u};
  611. DEF_NEWDEL(PulsePlayback)
  612. };
  613. PulsePlayback::~PulsePlayback()
  614. {
  615. if(!mContext)
  616. return;
  617. mMainloop.close(mContext, mStream);
  618. mContext = nullptr;
  619. mStream = nullptr;
  620. }
  621. void PulsePlayback::bufferAttrCallback(pa_stream *stream) noexcept
  622. {
  623. /* FIXME: Update the device's UpdateSize (and/or BufferSize) using the new
  624. * buffer attributes? Changing UpdateSize will change the ALC_REFRESH
  625. * property, which probably shouldn't change between device resets. But
  626. * leaving it alone means ALC_REFRESH will be off.
  627. */
  628. mAttr = *(pa_stream_get_buffer_attr(stream));
  629. TRACE("minreq=%d, tlength=%d, prebuf=%d\n", mAttr.minreq, mAttr.tlength, mAttr.prebuf);
  630. }
  631. void PulsePlayback::streamStateCallback(pa_stream *stream) noexcept
  632. {
  633. if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
  634. {
  635. ERR("Received stream failure!\n");
  636. mDevice->handleDisconnect("Playback stream failure");
  637. }
  638. mMainloop.getCondVar().notify_all();
  639. }
  640. void PulsePlayback::streamWriteCallback(pa_stream *stream, size_t nbytes) noexcept
  641. {
  642. do {
  643. pa_free_cb_t free_func{nullptr};
  644. auto buflen = static_cast<size_t>(-1);
  645. void *buf;
  646. if UNLIKELY(pa_stream_begin_write(stream, &buf, &buflen) || !buf)
  647. {
  648. buflen = nbytes;
  649. buf = pa_xmalloc(buflen);
  650. free_func = pa_xfree;
  651. }
  652. else
  653. buflen = minz(buflen, nbytes);
  654. nbytes -= buflen;
  655. mDevice->renderSamples(buf, static_cast<uint>(buflen/mFrameSize), mSpec.channels);
  656. int ret{pa_stream_write(stream, buf, buflen, free_func, 0, PA_SEEK_RELATIVE)};
  657. if UNLIKELY(ret != PA_OK)
  658. ERR("Failed to write to stream: %d, %s\n", ret, pa_strerror(ret));
  659. } while(nbytes > 0);
  660. }
  661. void PulsePlayback::sinkInfoCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
  662. {
  663. struct ChannelMap {
  664. DevFmtChannels fmt;
  665. pa_channel_map map;
  666. };
  667. static constexpr std::array<ChannelMap,7> chanmaps{{
  668. { DevFmtX71, X71ChanMap },
  669. { DevFmtX61, X61ChanMap },
  670. { DevFmtX51, X51ChanMap },
  671. { DevFmtX51Rear, X51RearChanMap },
  672. { DevFmtQuad, QuadChanMap },
  673. { DevFmtStereo, StereoChanMap },
  674. { DevFmtMono, MonoChanMap }
  675. }};
  676. if(eol)
  677. {
  678. mMainloop.getCondVar().notify_all();
  679. return;
  680. }
  681. auto chaniter = std::find_if(chanmaps.cbegin(), chanmaps.cend(),
  682. [info](const ChannelMap &chanmap) -> bool
  683. { return pa_channel_map_superset(&info->channel_map, &chanmap.map); }
  684. );
  685. if(chaniter != chanmaps.cend())
  686. {
  687. if(!mDevice->Flags.test(ChannelsRequest))
  688. mDevice->FmtChans = chaniter->fmt;
  689. }
  690. else
  691. {
  692. char chanmap_str[PA_CHANNEL_MAP_SNPRINT_MAX]{};
  693. pa_channel_map_snprint(chanmap_str, sizeof(chanmap_str), &info->channel_map);
  694. WARN("Failed to find format for channel map:\n %s\n", chanmap_str);
  695. }
  696. if(info->active_port)
  697. TRACE("Active port: %s (%s)\n", info->active_port->name, info->active_port->description);
  698. mDevice->IsHeadphones = (mDevice->FmtChans == DevFmtStereo
  699. && info->active_port && strcmp(info->active_port->name, "analog-output-headphones") == 0);
  700. }
  701. void PulsePlayback::sinkNameCallback(pa_context*, const pa_sink_info *info, int eol) noexcept
  702. {
  703. if(eol)
  704. {
  705. mMainloop.getCondVar().notify_all();
  706. return;
  707. }
  708. mDevice->DeviceName = info->description;
  709. }
  710. void PulsePlayback::streamMovedCallback(pa_stream *stream) noexcept
  711. {
  712. mDeviceName = pa_stream_get_device_name(stream);
  713. TRACE("Stream moved to %s\n", mDeviceName->c_str());
  714. }
  715. void PulsePlayback::open(const char *name)
  716. {
  717. const char *pulse_name{nullptr};
  718. const char *dev_name{nullptr};
  719. if(name)
  720. {
  721. if(PlaybackDevices.empty())
  722. mMainloop.probePlaybackDevices();
  723. auto iter = std::find_if(PlaybackDevices.cbegin(), PlaybackDevices.cend(),
  724. [name](const DevMap &entry) -> bool { return entry.name == name; });
  725. if(iter == PlaybackDevices.cend())
  726. throw al::backend_exception{al::backend_error::NoDevice,
  727. "Device name \"%s\" not found", name};
  728. pulse_name = iter->device_name.c_str();
  729. dev_name = iter->name.c_str();
  730. }
  731. auto plock = mMainloop.getUniqueLock();
  732. mContext = mMainloop.connectContext(plock);
  733. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_FIX_FORMAT | PA_STREAM_FIX_RATE |
  734. PA_STREAM_FIX_CHANNELS};
  735. if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1))
  736. flags |= PA_STREAM_DONT_MOVE;
  737. pa_sample_spec spec{};
  738. spec.format = PA_SAMPLE_S16NE;
  739. spec.rate = 44100;
  740. spec.channels = 2;
  741. if(!pulse_name)
  742. {
  743. static const auto defname = al::getenv("ALSOFT_PULSE_DEFAULT");
  744. if(defname) pulse_name = defname->c_str();
  745. }
  746. TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
  747. mStream = mMainloop.connectStream(pulse_name, plock, mContext, flags, nullptr, &spec, nullptr,
  748. BackendType::Playback);
  749. pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this);
  750. mFrameSize = static_cast<uint>(pa_frame_size(pa_stream_get_sample_spec(mStream)));
  751. mDeviceName = pulse_name ? al::make_optional<std::string>(pulse_name) : al::nullopt;
  752. if(!dev_name)
  753. {
  754. pa_operation *op{pa_context_get_sink_info_by_name(mContext,
  755. pa_stream_get_device_name(mStream), &PulsePlayback::sinkNameCallbackC, this)};
  756. mMainloop.waitForOperation(op, plock);
  757. }
  758. else
  759. mDevice->DeviceName = dev_name;
  760. }
  761. bool PulsePlayback::reset()
  762. {
  763. auto plock = mMainloop.getUniqueLock();
  764. const auto deviceName = mDeviceName ? mDeviceName->c_str() : nullptr;
  765. if(mStream)
  766. {
  767. pa_stream_set_state_callback(mStream, nullptr, nullptr);
  768. pa_stream_set_moved_callback(mStream, nullptr, nullptr);
  769. pa_stream_set_write_callback(mStream, nullptr, nullptr);
  770. pa_stream_set_buffer_attr_callback(mStream, nullptr, nullptr);
  771. pa_stream_disconnect(mStream);
  772. pa_stream_unref(mStream);
  773. mStream = nullptr;
  774. }
  775. pa_operation *op{pa_context_get_sink_info_by_name(mContext, deviceName,
  776. &PulsePlayback::sinkInfoCallbackC, this)};
  777. mMainloop.waitForOperation(op, plock);
  778. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_INTERPOLATE_TIMING |
  779. PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_EARLY_REQUESTS};
  780. if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1))
  781. flags |= PA_STREAM_DONT_MOVE;
  782. if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "adjust-latency", 0))
  783. {
  784. /* ADJUST_LATENCY can't be specified with EARLY_REQUESTS, for some
  785. * reason. So if the user wants to adjust the overall device latency,
  786. * we can't ask to get write signals as soon as minreq is reached.
  787. */
  788. flags &= ~PA_STREAM_EARLY_REQUESTS;
  789. flags |= PA_STREAM_ADJUST_LATENCY;
  790. }
  791. if(GetConfigValueBool(mDevice->DeviceName.c_str(), "pulse", "fix-rate", 0)
  792. || !mDevice->Flags.test(FrequencyRequest))
  793. flags |= PA_STREAM_FIX_RATE;
  794. pa_channel_map chanmap{};
  795. switch(mDevice->FmtChans)
  796. {
  797. case DevFmtMono:
  798. chanmap = MonoChanMap;
  799. break;
  800. case DevFmtAmbi3D:
  801. mDevice->FmtChans = DevFmtStereo;
  802. /*fall-through*/
  803. case DevFmtStereo:
  804. chanmap = StereoChanMap;
  805. break;
  806. case DevFmtQuad:
  807. chanmap = QuadChanMap;
  808. break;
  809. case DevFmtX51:
  810. chanmap = X51ChanMap;
  811. break;
  812. case DevFmtX51Rear:
  813. chanmap = X51RearChanMap;
  814. break;
  815. case DevFmtX61:
  816. chanmap = X61ChanMap;
  817. break;
  818. case DevFmtX71:
  819. chanmap = X71ChanMap;
  820. break;
  821. }
  822. SetChannelOrderFromMap(mDevice, chanmap);
  823. switch(mDevice->FmtType)
  824. {
  825. case DevFmtByte:
  826. mDevice->FmtType = DevFmtUByte;
  827. /* fall-through */
  828. case DevFmtUByte:
  829. mSpec.format = PA_SAMPLE_U8;
  830. break;
  831. case DevFmtUShort:
  832. mDevice->FmtType = DevFmtShort;
  833. /* fall-through */
  834. case DevFmtShort:
  835. mSpec.format = PA_SAMPLE_S16NE;
  836. break;
  837. case DevFmtUInt:
  838. mDevice->FmtType = DevFmtInt;
  839. /* fall-through */
  840. case DevFmtInt:
  841. mSpec.format = PA_SAMPLE_S32NE;
  842. break;
  843. case DevFmtFloat:
  844. mSpec.format = PA_SAMPLE_FLOAT32NE;
  845. break;
  846. }
  847. mSpec.rate = mDevice->Frequency;
  848. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  849. if(pa_sample_spec_valid(&mSpec) == 0)
  850. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"};
  851. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  852. mAttr.maxlength = ~0u;
  853. mAttr.tlength = mDevice->BufferSize * frame_size;
  854. mAttr.prebuf = 0u;
  855. mAttr.minreq = mDevice->UpdateSize * frame_size;
  856. mAttr.fragsize = ~0u;
  857. mStream = mMainloop.connectStream(deviceName, plock, mContext, flags, &mAttr, &mSpec,
  858. &chanmap, BackendType::Playback);
  859. pa_stream_set_state_callback(mStream, &PulsePlayback::streamStateCallbackC, this);
  860. pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this);
  861. mSpec = *(pa_stream_get_sample_spec(mStream));
  862. mFrameSize = static_cast<uint>(pa_frame_size(&mSpec));
  863. if(mDevice->Frequency != mSpec.rate)
  864. {
  865. /* Server updated our playback rate, so modify the buffer attribs
  866. * accordingly.
  867. */
  868. const auto scale = static_cast<double>(mSpec.rate) / mDevice->Frequency;
  869. const auto perlen = static_cast<uint>(clampd(scale*mDevice->UpdateSize + 0.5, 64.0,
  870. 8192.0));
  871. const auto buflen = static_cast<uint>(clampd(scale*mDevice->BufferSize + 0.5, perlen*2,
  872. std::numeric_limits<int>::max()/mFrameSize));
  873. mAttr.maxlength = ~0u;
  874. mAttr.tlength = buflen * mFrameSize;
  875. mAttr.prebuf = 0u;
  876. mAttr.minreq = perlen * mFrameSize;
  877. op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC,
  878. &mMainloop);
  879. mMainloop.waitForOperation(op, plock);
  880. mDevice->Frequency = mSpec.rate;
  881. }
  882. pa_stream_set_buffer_attr_callback(mStream, &PulsePlayback::bufferAttrCallbackC, this);
  883. bufferAttrCallback(mStream);
  884. mDevice->BufferSize = mAttr.tlength / mFrameSize;
  885. mDevice->UpdateSize = mAttr.minreq / mFrameSize;
  886. return true;
  887. }
  888. void PulsePlayback::start()
  889. {
  890. auto plock = mMainloop.getUniqueLock();
  891. pa_stream_set_write_callback(mStream, &PulsePlayback::streamWriteCallbackC, this);
  892. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  893. &mMainloop)};
  894. /* Write some (silent) samples to fill the prebuf amount if needed. */
  895. if(size_t prebuf{mAttr.prebuf})
  896. {
  897. prebuf = minz(prebuf, pa_stream_writable_size(mStream));
  898. void *buf{pa_xmalloc(prebuf)};
  899. switch(mSpec.format)
  900. {
  901. case PA_SAMPLE_U8:
  902. std::fill_n(static_cast<uint8_t*>(buf), prebuf, 0x80);
  903. break;
  904. case PA_SAMPLE_ALAW:
  905. std::fill_n(static_cast<uint8_t*>(buf), prebuf, 0xD5);
  906. break;
  907. case PA_SAMPLE_ULAW:
  908. std::fill_n(static_cast<uint8_t*>(buf), prebuf, 0x7f);
  909. break;
  910. default:
  911. std::fill_n(static_cast<uint8_t*>(buf), prebuf, 0x00);
  912. break;
  913. }
  914. pa_stream_write(mStream, buf, prebuf, pa_xfree, 0, PA_SEEK_RELATIVE);
  915. }
  916. mMainloop.waitForOperation(op, plock);
  917. }
  918. void PulsePlayback::stop()
  919. {
  920. auto plock = mMainloop.getUniqueLock();
  921. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  922. &mMainloop)};
  923. mMainloop.waitForOperation(op, plock);
  924. pa_stream_set_write_callback(mStream, nullptr, nullptr);
  925. }
  926. ClockLatency PulsePlayback::getClockLatency()
  927. {
  928. ClockLatency ret;
  929. pa_usec_t latency;
  930. int neg, err;
  931. {
  932. auto plock = mMainloop.getUniqueLock();
  933. ret.ClockTime = GetDeviceClockTime(mDevice);
  934. err = pa_stream_get_latency(mStream, &latency, &neg);
  935. }
  936. if UNLIKELY(err != 0)
  937. {
  938. /* If err = -PA_ERR_NODATA, it means we were called too soon after
  939. * starting the stream and no timing info has been received from the
  940. * server yet. Give a generic value since nothing better is available.
  941. */
  942. if(err != -PA_ERR_NODATA)
  943. ERR("Failed to get stream latency: 0x%x\n", err);
  944. latency = mDevice->BufferSize - mDevice->UpdateSize;
  945. neg = 0;
  946. }
  947. else if UNLIKELY(neg)
  948. latency = 0;
  949. ret.Latency = std::chrono::microseconds{latency};
  950. return ret;
  951. }
  952. struct PulseCapture final : public BackendBase {
  953. PulseCapture(ALCdevice *device) noexcept : BackendBase{device} { }
  954. ~PulseCapture() override;
  955. void streamStateCallback(pa_stream *stream) noexcept;
  956. static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept
  957. { static_cast<PulseCapture*>(pdata)->streamStateCallback(stream); }
  958. void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept;
  959. static void sourceNameCallbackC(pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept
  960. { static_cast<PulseCapture*>(pdata)->sourceNameCallback(context, info, eol); }
  961. void streamMovedCallback(pa_stream *stream) noexcept;
  962. static void streamMovedCallbackC(pa_stream *stream, void *pdata) noexcept
  963. { static_cast<PulseCapture*>(pdata)->streamMovedCallback(stream); }
  964. void open(const char *name) override;
  965. void start() override;
  966. void stop() override;
  967. void captureSamples(al::byte *buffer, uint samples) override;
  968. uint availableSamples() override;
  969. ClockLatency getClockLatency() override;
  970. PulseMainloop mMainloop;
  971. al::optional<std::string> mDeviceName{al::nullopt};
  972. uint mLastReadable{0u};
  973. al::byte mSilentVal{};
  974. al::span<const al::byte> mCapBuffer;
  975. ssize_t mCapLen{0};
  976. pa_buffer_attr mAttr{};
  977. pa_sample_spec mSpec{};
  978. pa_stream *mStream{nullptr};
  979. pa_context *mContext{nullptr};
  980. DEF_NEWDEL(PulseCapture)
  981. };
  982. PulseCapture::~PulseCapture()
  983. {
  984. if(!mContext)
  985. return;
  986. mMainloop.close(mContext, mStream);
  987. mContext = nullptr;
  988. mStream = nullptr;
  989. }
  990. void PulseCapture::streamStateCallback(pa_stream *stream) noexcept
  991. {
  992. if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
  993. {
  994. ERR("Received stream failure!\n");
  995. mDevice->handleDisconnect("Capture stream failure");
  996. }
  997. mMainloop.getCondVar().notify_all();
  998. }
  999. void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept
  1000. {
  1001. if(eol)
  1002. {
  1003. mMainloop.getCondVar().notify_all();
  1004. return;
  1005. }
  1006. mDevice->DeviceName = info->description;
  1007. }
  1008. void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept
  1009. {
  1010. mDeviceName = pa_stream_get_device_name(stream);
  1011. TRACE("Stream moved to %s\n", mDeviceName->c_str());
  1012. }
  1013. void PulseCapture::open(const char *name)
  1014. {
  1015. const char *pulse_name{nullptr};
  1016. if(name)
  1017. {
  1018. if(CaptureDevices.empty())
  1019. mMainloop.probeCaptureDevices();
  1020. auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
  1021. [name](const DevMap &entry) -> bool { return entry.name == name; });
  1022. if(iter == CaptureDevices.cend())
  1023. throw al::backend_exception{al::backend_error::NoDevice,
  1024. "Device name \"%s\" not found", name};
  1025. pulse_name = iter->device_name.c_str();
  1026. mDevice->DeviceName = iter->name;
  1027. }
  1028. auto plock = mMainloop.getUniqueLock();
  1029. mContext = mMainloop.connectContext(plock);
  1030. pa_channel_map chanmap{};
  1031. switch(mDevice->FmtChans)
  1032. {
  1033. case DevFmtMono:
  1034. chanmap = MonoChanMap;
  1035. break;
  1036. case DevFmtStereo:
  1037. chanmap = StereoChanMap;
  1038. break;
  1039. case DevFmtQuad:
  1040. chanmap = QuadChanMap;
  1041. break;
  1042. case DevFmtX51:
  1043. chanmap = X51ChanMap;
  1044. break;
  1045. case DevFmtX51Rear:
  1046. chanmap = X51RearChanMap;
  1047. break;
  1048. case DevFmtX61:
  1049. chanmap = X61ChanMap;
  1050. break;
  1051. case DevFmtX71:
  1052. chanmap = X71ChanMap;
  1053. break;
  1054. case DevFmtAmbi3D:
  1055. throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
  1056. DevFmtChannelsString(mDevice->FmtChans)};
  1057. }
  1058. SetChannelOrderFromMap(mDevice, chanmap);
  1059. switch(mDevice->FmtType)
  1060. {
  1061. case DevFmtUByte:
  1062. mSilentVal = al::byte(0x80);
  1063. mSpec.format = PA_SAMPLE_U8;
  1064. break;
  1065. case DevFmtShort:
  1066. mSpec.format = PA_SAMPLE_S16NE;
  1067. break;
  1068. case DevFmtInt:
  1069. mSpec.format = PA_SAMPLE_S32NE;
  1070. break;
  1071. case DevFmtFloat:
  1072. mSpec.format = PA_SAMPLE_FLOAT32NE;
  1073. break;
  1074. case DevFmtByte:
  1075. case DevFmtUShort:
  1076. case DevFmtUInt:
  1077. throw al::backend_exception{al::backend_error::DeviceError,
  1078. "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
  1079. }
  1080. mSpec.rate = mDevice->Frequency;
  1081. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  1082. if(pa_sample_spec_valid(&mSpec) == 0)
  1083. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"};
  1084. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  1085. const uint samples{maxu(mDevice->BufferSize, 100 * mDevice->Frequency / 1000)};
  1086. mAttr.minreq = ~0u;
  1087. mAttr.prebuf = ~0u;
  1088. mAttr.maxlength = samples * frame_size;
  1089. mAttr.tlength = ~0u;
  1090. mAttr.fragsize = minu(samples, 50*mDevice->Frequency/1000) * frame_size;
  1091. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY};
  1092. if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1))
  1093. flags |= PA_STREAM_DONT_MOVE;
  1094. TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
  1095. mStream = mMainloop.connectStream(pulse_name, plock, mContext, flags, &mAttr, &mSpec, &chanmap,
  1096. BackendType::Capture);
  1097. pa_stream_set_moved_callback(mStream, &PulseCapture::streamMovedCallbackC, this);
  1098. pa_stream_set_state_callback(mStream, &PulseCapture::streamStateCallbackC, this);
  1099. mDeviceName = pulse_name ? al::make_optional<std::string>(pulse_name) : al::nullopt;
  1100. if(mDevice->DeviceName.empty())
  1101. {
  1102. pa_operation *op{pa_context_get_source_info_by_name(mContext,
  1103. pa_stream_get_device_name(mStream), &PulseCapture::sourceNameCallbackC, this)};
  1104. mMainloop.waitForOperation(op, plock);
  1105. }
  1106. }
  1107. void PulseCapture::start()
  1108. {
  1109. auto plock = mMainloop.getUniqueLock();
  1110. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  1111. &mMainloop)};
  1112. mMainloop.waitForOperation(op, plock);
  1113. }
  1114. void PulseCapture::stop()
  1115. {
  1116. auto plock = mMainloop.getUniqueLock();
  1117. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  1118. &mMainloop)};
  1119. mMainloop.waitForOperation(op, plock);
  1120. }
  1121. void PulseCapture::captureSamples(al::byte *buffer, uint samples)
  1122. {
  1123. al::span<al::byte> dstbuf{buffer, samples * pa_frame_size(&mSpec)};
  1124. /* Capture is done in fragment-sized chunks, so we loop until we get all
  1125. * that's available */
  1126. mLastReadable -= static_cast<uint>(dstbuf.size());
  1127. while(!dstbuf.empty())
  1128. {
  1129. if(!mCapBuffer.empty())
  1130. {
  1131. const size_t rem{minz(dstbuf.size(), mCapBuffer.size())};
  1132. if UNLIKELY(mCapLen < 0)
  1133. std::fill_n(dstbuf.begin(), rem, mSilentVal);
  1134. else
  1135. std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin());
  1136. dstbuf = dstbuf.subspan(rem);
  1137. mCapBuffer = mCapBuffer.subspan(rem);
  1138. continue;
  1139. }
  1140. if UNLIKELY(!mDevice->Connected.load(std::memory_order_acquire))
  1141. break;
  1142. auto plock = mMainloop.getUniqueLock();
  1143. if(mCapLen != 0)
  1144. {
  1145. pa_stream_drop(mStream);
  1146. mCapBuffer = {};
  1147. mCapLen = 0;
  1148. }
  1149. const pa_stream_state_t state{pa_stream_get_state(mStream)};
  1150. if UNLIKELY(!PA_STREAM_IS_GOOD(state))
  1151. {
  1152. mDevice->handleDisconnect("Bad capture state: %u", state);
  1153. break;
  1154. }
  1155. const void *capbuf;
  1156. size_t caplen;
  1157. if UNLIKELY(pa_stream_peek(mStream, &capbuf, &caplen) < 0)
  1158. {
  1159. mDevice->handleDisconnect("Failed retrieving capture samples: %s",
  1160. pa_strerror(pa_context_errno(mContext)));
  1161. break;
  1162. }
  1163. plock.unlock();
  1164. if(caplen == 0) break;
  1165. if UNLIKELY(!capbuf)
  1166. mCapLen = -static_cast<ssize_t>(caplen);
  1167. else
  1168. mCapLen = static_cast<ssize_t>(caplen);
  1169. mCapBuffer = {static_cast<const al::byte*>(capbuf), caplen};
  1170. }
  1171. if(!dstbuf.empty())
  1172. std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal);
  1173. }
  1174. uint PulseCapture::availableSamples()
  1175. {
  1176. size_t readable{mCapBuffer.size()};
  1177. if(mDevice->Connected.load(std::memory_order_acquire))
  1178. {
  1179. auto plock = mMainloop.getUniqueLock();
  1180. size_t got{pa_stream_readable_size(mStream)};
  1181. if UNLIKELY(static_cast<ssize_t>(got) < 0)
  1182. {
  1183. const char *err{pa_strerror(static_cast<int>(got))};
  1184. ERR("pa_stream_readable_size() failed: %s\n", err);
  1185. mDevice->handleDisconnect("Failed getting readable size: %s", err);
  1186. }
  1187. else
  1188. {
  1189. const auto caplen = static_cast<size_t>(std::abs(mCapLen));
  1190. if(got > caplen) readable += got - caplen;
  1191. }
  1192. }
  1193. readable = std::min<size_t>(readable, std::numeric_limits<uint>::max());
  1194. mLastReadable = std::max(mLastReadable, static_cast<uint>(readable));
  1195. return mLastReadable / static_cast<uint>(pa_frame_size(&mSpec));
  1196. }
  1197. ClockLatency PulseCapture::getClockLatency()
  1198. {
  1199. ClockLatency ret;
  1200. pa_usec_t latency;
  1201. int neg, err;
  1202. {
  1203. auto plock = mMainloop.getUniqueLock();
  1204. ret.ClockTime = GetDeviceClockTime(mDevice);
  1205. err = pa_stream_get_latency(mStream, &latency, &neg);
  1206. }
  1207. if UNLIKELY(err != 0)
  1208. {
  1209. ERR("Failed to get stream latency: 0x%x\n", err);
  1210. latency = 0;
  1211. neg = 0;
  1212. }
  1213. else if UNLIKELY(neg)
  1214. latency = 0;
  1215. ret.Latency = std::chrono::microseconds{latency};
  1216. return ret;
  1217. }
  1218. } // namespace
  1219. bool PulseBackendFactory::init()
  1220. {
  1221. #ifdef HAVE_DYNLOAD
  1222. if(!pulse_handle)
  1223. {
  1224. bool ret{true};
  1225. std::string missing_funcs;
  1226. #ifdef _WIN32
  1227. #define PALIB "libpulse-0.dll"
  1228. #elif defined(__APPLE__) && defined(__MACH__)
  1229. #define PALIB "libpulse.0.dylib"
  1230. #else
  1231. #define PALIB "libpulse.so.0"
  1232. #endif
  1233. pulse_handle = LoadLib(PALIB);
  1234. if(!pulse_handle)
  1235. {
  1236. WARN("Failed to load %s\n", PALIB);
  1237. return false;
  1238. }
  1239. #define LOAD_FUNC(x) do { \
  1240. p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
  1241. if(!(p##x)) { \
  1242. ret = false; \
  1243. missing_funcs += "\n" #x; \
  1244. } \
  1245. } while(0)
  1246. PULSE_FUNCS(LOAD_FUNC)
  1247. #undef LOAD_FUNC
  1248. if(!ret)
  1249. {
  1250. WARN("Missing expected functions:%s\n", missing_funcs.c_str());
  1251. CloseLib(pulse_handle);
  1252. pulse_handle = nullptr;
  1253. return false;
  1254. }
  1255. }
  1256. #endif /* HAVE_DYNLOAD */
  1257. pulse_ctx_flags = PA_CONTEXT_NOFLAGS;
  1258. if(!GetConfigValueBool(nullptr, "pulse", "spawn-server", 1))
  1259. pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
  1260. try {
  1261. auto plock = gGlobalMainloop.getUniqueLock();
  1262. pa_context *context{gGlobalMainloop.connectContext(plock)};
  1263. pa_context_disconnect(context);
  1264. pa_context_unref(context);
  1265. return true;
  1266. }
  1267. catch(...) {
  1268. return false;
  1269. }
  1270. }
  1271. bool PulseBackendFactory::querySupport(BackendType type)
  1272. { return type == BackendType::Playback || type == BackendType::Capture; }
  1273. std::string PulseBackendFactory::probe(BackendType type)
  1274. {
  1275. std::string outnames;
  1276. auto add_device = [&outnames](const DevMap &entry) -> void
  1277. {
  1278. /* +1 to also append the null char (to ensure a null-separated list and
  1279. * double-null terminated list).
  1280. */
  1281. outnames.append(entry.name.c_str(), entry.name.length()+1);
  1282. };
  1283. switch(type)
  1284. {
  1285. case BackendType::Playback:
  1286. gGlobalMainloop.probePlaybackDevices();
  1287. std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
  1288. break;
  1289. case BackendType::Capture:
  1290. gGlobalMainloop.probeCaptureDevices();
  1291. std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
  1292. break;
  1293. }
  1294. return outnames;
  1295. }
  1296. BackendPtr PulseBackendFactory::createBackend(ALCdevice *device, BackendType type)
  1297. {
  1298. if(type == BackendType::Playback)
  1299. return BackendPtr{new PulsePlayback{device}};
  1300. if(type == BackendType::Capture)
  1301. return BackendPtr{new PulseCapture{device}};
  1302. return nullptr;
  1303. }
  1304. BackendFactory &PulseBackendFactory::getFactory()
  1305. {
  1306. static PulseBackendFactory factory{};
  1307. return factory;
  1308. }