🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1468 lines
50 KiB

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