🛠️🐜 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.

1470 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. case DevFmtX3D71:
  774. chanmap = X71ChanMap;
  775. break;
  776. }
  777. setDefaultWFXChannelOrder();
  778. switch(mDevice->FmtType)
  779. {
  780. case DevFmtByte:
  781. mDevice->FmtType = DevFmtUByte;
  782. /* fall-through */
  783. case DevFmtUByte:
  784. mSpec.format = PA_SAMPLE_U8;
  785. break;
  786. case DevFmtUShort:
  787. mDevice->FmtType = DevFmtShort;
  788. /* fall-through */
  789. case DevFmtShort:
  790. mSpec.format = PA_SAMPLE_S16NE;
  791. break;
  792. case DevFmtUInt:
  793. mDevice->FmtType = DevFmtInt;
  794. /* fall-through */
  795. case DevFmtInt:
  796. mSpec.format = PA_SAMPLE_S32NE;
  797. break;
  798. case DevFmtFloat:
  799. mSpec.format = PA_SAMPLE_FLOAT32NE;
  800. break;
  801. }
  802. mSpec.rate = mDevice->Frequency;
  803. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  804. if(pa_sample_spec_valid(&mSpec) == 0)
  805. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample spec"};
  806. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  807. mAttr.maxlength = ~0u;
  808. mAttr.tlength = mDevice->BufferSize * frame_size;
  809. mAttr.prebuf = 0u;
  810. mAttr.minreq = mDevice->UpdateSize * frame_size;
  811. mAttr.fragsize = ~0u;
  812. mStream = mMainloop.connectStream(deviceName, plock, mContext, flags, &mAttr, &mSpec,
  813. &chanmap, BackendType::Playback);
  814. pa_stream_set_state_callback(mStream, &PulsePlayback::streamStateCallbackC, this);
  815. pa_stream_set_moved_callback(mStream, &PulsePlayback::streamMovedCallbackC, this);
  816. mSpec = *(pa_stream_get_sample_spec(mStream));
  817. mFrameSize = static_cast<uint>(pa_frame_size(&mSpec));
  818. if(mDevice->Frequency != mSpec.rate)
  819. {
  820. /* Server updated our playback rate, so modify the buffer attribs
  821. * accordingly.
  822. */
  823. const auto scale = static_cast<double>(mSpec.rate) / mDevice->Frequency;
  824. const auto perlen = static_cast<uint>(clampd(scale*mDevice->UpdateSize + 0.5, 64.0,
  825. 8192.0));
  826. const auto buflen = static_cast<uint>(clampd(scale*mDevice->BufferSize + 0.5, perlen*2,
  827. std::numeric_limits<int>::max()/mFrameSize));
  828. mAttr.maxlength = ~0u;
  829. mAttr.tlength = buflen * mFrameSize;
  830. mAttr.prebuf = 0u;
  831. mAttr.minreq = perlen * mFrameSize;
  832. op = pa_stream_set_buffer_attr(mStream, &mAttr, &PulseMainloop::streamSuccessCallbackC,
  833. &mMainloop);
  834. mMainloop.waitForOperation(op, plock);
  835. mDevice->Frequency = mSpec.rate;
  836. }
  837. pa_stream_set_buffer_attr_callback(mStream, &PulsePlayback::bufferAttrCallbackC, this);
  838. bufferAttrCallback(mStream);
  839. mDevice->BufferSize = mAttr.tlength / mFrameSize;
  840. mDevice->UpdateSize = mAttr.minreq / mFrameSize;
  841. return true;
  842. }
  843. void PulsePlayback::start()
  844. {
  845. auto plock = mMainloop.getUniqueLock();
  846. /* Write some (silent) samples to fill the buffer before we start feeding
  847. * it newly mixed samples.
  848. */
  849. if(size_t todo{pa_stream_writable_size(mStream)})
  850. {
  851. void *buf{pa_xmalloc(todo)};
  852. switch(mSpec.format)
  853. {
  854. case PA_SAMPLE_U8:
  855. std::fill_n(static_cast<uint8_t*>(buf), todo, 0x80);
  856. break;
  857. case PA_SAMPLE_ALAW:
  858. std::fill_n(static_cast<uint8_t*>(buf), todo, 0xD5);
  859. break;
  860. case PA_SAMPLE_ULAW:
  861. std::fill_n(static_cast<uint8_t*>(buf), todo, 0x7f);
  862. break;
  863. default:
  864. std::fill_n(static_cast<uint8_t*>(buf), todo, 0x00);
  865. break;
  866. }
  867. pa_stream_write(mStream, buf, todo, pa_xfree, 0, PA_SEEK_RELATIVE);
  868. }
  869. pa_stream_set_write_callback(mStream, &PulsePlayback::streamWriteCallbackC, this);
  870. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  871. &mMainloop)};
  872. mMainloop.waitForOperation(op, plock);
  873. }
  874. void PulsePlayback::stop()
  875. {
  876. auto plock = mMainloop.getUniqueLock();
  877. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  878. &mMainloop)};
  879. mMainloop.waitForOperation(op, plock);
  880. pa_stream_set_write_callback(mStream, nullptr, nullptr);
  881. }
  882. ClockLatency PulsePlayback::getClockLatency()
  883. {
  884. ClockLatency ret;
  885. pa_usec_t latency;
  886. int neg, err;
  887. {
  888. auto plock = mMainloop.getUniqueLock();
  889. ret.ClockTime = GetDeviceClockTime(mDevice);
  890. err = pa_stream_get_latency(mStream, &latency, &neg);
  891. }
  892. if UNLIKELY(err != 0)
  893. {
  894. /* If err = -PA_ERR_NODATA, it means we were called too soon after
  895. * starting the stream and no timing info has been received from the
  896. * server yet. Give a generic value since nothing better is available.
  897. */
  898. if(err != -PA_ERR_NODATA)
  899. ERR("Failed to get stream latency: 0x%x\n", err);
  900. latency = mDevice->BufferSize - mDevice->UpdateSize;
  901. neg = 0;
  902. }
  903. else if UNLIKELY(neg)
  904. latency = 0;
  905. ret.Latency = std::chrono::microseconds{latency};
  906. return ret;
  907. }
  908. struct PulseCapture final : public BackendBase {
  909. PulseCapture(DeviceBase *device) noexcept : BackendBase{device} { }
  910. ~PulseCapture() override;
  911. void streamStateCallback(pa_stream *stream) noexcept;
  912. static void streamStateCallbackC(pa_stream *stream, void *pdata) noexcept
  913. { static_cast<PulseCapture*>(pdata)->streamStateCallback(stream); }
  914. void sourceNameCallback(pa_context *context, const pa_source_info *info, int eol) noexcept;
  915. static void sourceNameCallbackC(pa_context *context, const pa_source_info *info, int eol, void *pdata) noexcept
  916. { static_cast<PulseCapture*>(pdata)->sourceNameCallback(context, info, eol); }
  917. void streamMovedCallback(pa_stream *stream) noexcept;
  918. static void streamMovedCallbackC(pa_stream *stream, void *pdata) noexcept
  919. { static_cast<PulseCapture*>(pdata)->streamMovedCallback(stream); }
  920. void open(const char *name) override;
  921. void start() override;
  922. void stop() override;
  923. void captureSamples(al::byte *buffer, uint samples) override;
  924. uint availableSamples() override;
  925. ClockLatency getClockLatency() override;
  926. PulseMainloop mMainloop;
  927. al::optional<std::string> mDeviceName{al::nullopt};
  928. uint mLastReadable{0u};
  929. al::byte mSilentVal{};
  930. al::span<const al::byte> mCapBuffer;
  931. ssize_t mCapLen{0};
  932. pa_buffer_attr mAttr{};
  933. pa_sample_spec mSpec{};
  934. pa_stream *mStream{nullptr};
  935. pa_context *mContext{nullptr};
  936. DEF_NEWDEL(PulseCapture)
  937. };
  938. PulseCapture::~PulseCapture()
  939. {
  940. if(!mContext)
  941. return;
  942. mMainloop.close(mContext, mStream);
  943. mContext = nullptr;
  944. mStream = nullptr;
  945. }
  946. void PulseCapture::streamStateCallback(pa_stream *stream) noexcept
  947. {
  948. if(pa_stream_get_state(stream) == PA_STREAM_FAILED)
  949. {
  950. ERR("Received stream failure!\n");
  951. mDevice->handleDisconnect("Capture stream failure");
  952. }
  953. mMainloop.getCondVar().notify_all();
  954. }
  955. void PulseCapture::sourceNameCallback(pa_context*, const pa_source_info *info, int eol) noexcept
  956. {
  957. if(eol)
  958. {
  959. mMainloop.getCondVar().notify_all();
  960. return;
  961. }
  962. mDevice->DeviceName = info->description;
  963. }
  964. void PulseCapture::streamMovedCallback(pa_stream *stream) noexcept
  965. {
  966. mDeviceName = pa_stream_get_device_name(stream);
  967. TRACE("Stream moved to %s\n", mDeviceName->c_str());
  968. }
  969. void PulseCapture::open(const char *name)
  970. {
  971. const char *pulse_name{nullptr};
  972. if(name)
  973. {
  974. if(CaptureDevices.empty())
  975. mMainloop.probeCaptureDevices();
  976. auto iter = std::find_if(CaptureDevices.cbegin(), CaptureDevices.cend(),
  977. [name](const DevMap &entry) -> bool { return entry.name == name; });
  978. if(iter == CaptureDevices.cend())
  979. throw al::backend_exception{al::backend_error::NoDevice,
  980. "Device name \"%s\" not found", name};
  981. pulse_name = iter->device_name.c_str();
  982. mDevice->DeviceName = iter->name;
  983. }
  984. auto plock = mMainloop.getUniqueLock();
  985. mContext = mMainloop.connectContext(plock);
  986. pa_channel_map chanmap{};
  987. switch(mDevice->FmtChans)
  988. {
  989. case DevFmtMono:
  990. chanmap = MonoChanMap;
  991. break;
  992. case DevFmtStereo:
  993. chanmap = StereoChanMap;
  994. break;
  995. case DevFmtQuad:
  996. chanmap = QuadChanMap;
  997. break;
  998. case DevFmtX51:
  999. chanmap = X51ChanMap;
  1000. break;
  1001. case DevFmtX61:
  1002. chanmap = X61ChanMap;
  1003. break;
  1004. case DevFmtX71:
  1005. chanmap = X71ChanMap;
  1006. break;
  1007. case DevFmtX3D71:
  1008. case DevFmtAmbi3D:
  1009. throw al::backend_exception{al::backend_error::DeviceError, "%s capture not supported",
  1010. DevFmtChannelsString(mDevice->FmtChans)};
  1011. }
  1012. setDefaultWFXChannelOrder();
  1013. switch(mDevice->FmtType)
  1014. {
  1015. case DevFmtUByte:
  1016. mSilentVal = al::byte(0x80);
  1017. mSpec.format = PA_SAMPLE_U8;
  1018. break;
  1019. case DevFmtShort:
  1020. mSpec.format = PA_SAMPLE_S16NE;
  1021. break;
  1022. case DevFmtInt:
  1023. mSpec.format = PA_SAMPLE_S32NE;
  1024. break;
  1025. case DevFmtFloat:
  1026. mSpec.format = PA_SAMPLE_FLOAT32NE;
  1027. break;
  1028. case DevFmtByte:
  1029. case DevFmtUShort:
  1030. case DevFmtUInt:
  1031. throw al::backend_exception{al::backend_error::DeviceError,
  1032. "%s capture samples not supported", DevFmtTypeString(mDevice->FmtType)};
  1033. }
  1034. mSpec.rate = mDevice->Frequency;
  1035. mSpec.channels = static_cast<uint8_t>(mDevice->channelsFromFmt());
  1036. if(pa_sample_spec_valid(&mSpec) == 0)
  1037. throw al::backend_exception{al::backend_error::DeviceError, "Invalid sample format"};
  1038. const auto frame_size = static_cast<uint>(pa_frame_size(&mSpec));
  1039. const uint samples{maxu(mDevice->BufferSize, 100 * mDevice->Frequency / 1000)};
  1040. mAttr.minreq = ~0u;
  1041. mAttr.prebuf = ~0u;
  1042. mAttr.maxlength = samples * frame_size;
  1043. mAttr.tlength = ~0u;
  1044. mAttr.fragsize = minu(samples, 50*mDevice->Frequency/1000) * frame_size;
  1045. pa_stream_flags_t flags{PA_STREAM_START_CORKED | PA_STREAM_ADJUST_LATENCY};
  1046. if(!GetConfigValueBool(nullptr, "pulse", "allow-moves", 1))
  1047. flags |= PA_STREAM_DONT_MOVE;
  1048. TRACE("Connecting to \"%s\"\n", pulse_name ? pulse_name : "(default)");
  1049. mStream = mMainloop.connectStream(pulse_name, plock, mContext, flags, &mAttr, &mSpec, &chanmap,
  1050. BackendType::Capture);
  1051. pa_stream_set_moved_callback(mStream, &PulseCapture::streamMovedCallbackC, this);
  1052. pa_stream_set_state_callback(mStream, &PulseCapture::streamStateCallbackC, this);
  1053. mDeviceName = pulse_name ? al::make_optional<std::string>(pulse_name) : al::nullopt;
  1054. if(mDevice->DeviceName.empty())
  1055. {
  1056. pa_operation *op{pa_context_get_source_info_by_name(mContext,
  1057. pa_stream_get_device_name(mStream), &PulseCapture::sourceNameCallbackC, this)};
  1058. mMainloop.waitForOperation(op, plock);
  1059. }
  1060. }
  1061. void PulseCapture::start()
  1062. {
  1063. auto plock = mMainloop.getUniqueLock();
  1064. pa_operation *op{pa_stream_cork(mStream, 0, &PulseMainloop::streamSuccessCallbackC,
  1065. &mMainloop)};
  1066. mMainloop.waitForOperation(op, plock);
  1067. }
  1068. void PulseCapture::stop()
  1069. {
  1070. auto plock = mMainloop.getUniqueLock();
  1071. pa_operation *op{pa_stream_cork(mStream, 1, &PulseMainloop::streamSuccessCallbackC,
  1072. &mMainloop)};
  1073. mMainloop.waitForOperation(op, plock);
  1074. }
  1075. void PulseCapture::captureSamples(al::byte *buffer, uint samples)
  1076. {
  1077. al::span<al::byte> dstbuf{buffer, samples * pa_frame_size(&mSpec)};
  1078. /* Capture is done in fragment-sized chunks, so we loop until we get all
  1079. * that's available */
  1080. mLastReadable -= static_cast<uint>(dstbuf.size());
  1081. while(!dstbuf.empty())
  1082. {
  1083. if(!mCapBuffer.empty())
  1084. {
  1085. const size_t rem{minz(dstbuf.size(), mCapBuffer.size())};
  1086. if UNLIKELY(mCapLen < 0)
  1087. std::fill_n(dstbuf.begin(), rem, mSilentVal);
  1088. else
  1089. std::copy_n(mCapBuffer.begin(), rem, dstbuf.begin());
  1090. dstbuf = dstbuf.subspan(rem);
  1091. mCapBuffer = mCapBuffer.subspan(rem);
  1092. continue;
  1093. }
  1094. if UNLIKELY(!mDevice->Connected.load(std::memory_order_acquire))
  1095. break;
  1096. auto plock = mMainloop.getUniqueLock();
  1097. if(mCapLen != 0)
  1098. {
  1099. pa_stream_drop(mStream);
  1100. mCapBuffer = {};
  1101. mCapLen = 0;
  1102. }
  1103. const pa_stream_state_t state{pa_stream_get_state(mStream)};
  1104. if UNLIKELY(!PA_STREAM_IS_GOOD(state))
  1105. {
  1106. mDevice->handleDisconnect("Bad capture state: %u", state);
  1107. break;
  1108. }
  1109. const void *capbuf;
  1110. size_t caplen;
  1111. if UNLIKELY(pa_stream_peek(mStream, &capbuf, &caplen) < 0)
  1112. {
  1113. mDevice->handleDisconnect("Failed retrieving capture samples: %s",
  1114. pa_strerror(pa_context_errno(mContext)));
  1115. break;
  1116. }
  1117. plock.unlock();
  1118. if(caplen == 0) break;
  1119. if UNLIKELY(!capbuf)
  1120. mCapLen = -static_cast<ssize_t>(caplen);
  1121. else
  1122. mCapLen = static_cast<ssize_t>(caplen);
  1123. mCapBuffer = {static_cast<const al::byte*>(capbuf), caplen};
  1124. }
  1125. if(!dstbuf.empty())
  1126. std::fill(dstbuf.begin(), dstbuf.end(), mSilentVal);
  1127. }
  1128. uint PulseCapture::availableSamples()
  1129. {
  1130. size_t readable{mCapBuffer.size()};
  1131. if(mDevice->Connected.load(std::memory_order_acquire))
  1132. {
  1133. auto plock = mMainloop.getUniqueLock();
  1134. size_t got{pa_stream_readable_size(mStream)};
  1135. if UNLIKELY(static_cast<ssize_t>(got) < 0)
  1136. {
  1137. const char *err{pa_strerror(static_cast<int>(got))};
  1138. ERR("pa_stream_readable_size() failed: %s\n", err);
  1139. mDevice->handleDisconnect("Failed getting readable size: %s", err);
  1140. }
  1141. else
  1142. {
  1143. const auto caplen = static_cast<size_t>(std::abs(mCapLen));
  1144. if(got > caplen) readable += got - caplen;
  1145. }
  1146. }
  1147. readable = std::min<size_t>(readable, std::numeric_limits<uint>::max());
  1148. mLastReadable = std::max(mLastReadable, static_cast<uint>(readable));
  1149. return mLastReadable / static_cast<uint>(pa_frame_size(&mSpec));
  1150. }
  1151. ClockLatency PulseCapture::getClockLatency()
  1152. {
  1153. ClockLatency ret;
  1154. pa_usec_t latency;
  1155. int neg, err;
  1156. {
  1157. auto plock = mMainloop.getUniqueLock();
  1158. ret.ClockTime = GetDeviceClockTime(mDevice);
  1159. err = pa_stream_get_latency(mStream, &latency, &neg);
  1160. }
  1161. if UNLIKELY(err != 0)
  1162. {
  1163. ERR("Failed to get stream latency: 0x%x\n", err);
  1164. latency = 0;
  1165. neg = 0;
  1166. }
  1167. else if UNLIKELY(neg)
  1168. latency = 0;
  1169. ret.Latency = std::chrono::microseconds{latency};
  1170. return ret;
  1171. }
  1172. } // namespace
  1173. bool PulseBackendFactory::init()
  1174. {
  1175. #ifdef HAVE_DYNLOAD
  1176. if(!pulse_handle)
  1177. {
  1178. bool ret{true};
  1179. std::string missing_funcs;
  1180. #ifdef _WIN32
  1181. #define PALIB "libpulse-0.dll"
  1182. #elif defined(__APPLE__) && defined(__MACH__)
  1183. #define PALIB "libpulse.0.dylib"
  1184. #else
  1185. #define PALIB "libpulse.so.0"
  1186. #endif
  1187. pulse_handle = LoadLib(PALIB);
  1188. if(!pulse_handle)
  1189. {
  1190. WARN("Failed to load %s\n", PALIB);
  1191. return false;
  1192. }
  1193. #define LOAD_FUNC(x) do { \
  1194. p##x = reinterpret_cast<decltype(p##x)>(GetSymbol(pulse_handle, #x)); \
  1195. if(!(p##x)) { \
  1196. ret = false; \
  1197. missing_funcs += "\n" #x; \
  1198. } \
  1199. } while(0)
  1200. PULSE_FUNCS(LOAD_FUNC)
  1201. #undef LOAD_FUNC
  1202. if(!ret)
  1203. {
  1204. WARN("Missing expected functions:%s\n", missing_funcs.c_str());
  1205. CloseLib(pulse_handle);
  1206. pulse_handle = nullptr;
  1207. return false;
  1208. }
  1209. }
  1210. #endif /* HAVE_DYNLOAD */
  1211. pulse_ctx_flags = PA_CONTEXT_NOFLAGS;
  1212. if(!GetConfigValueBool(nullptr, "pulse", "spawn-server", 1))
  1213. pulse_ctx_flags |= PA_CONTEXT_NOAUTOSPAWN;
  1214. try {
  1215. auto plock = gGlobalMainloop.getUniqueLock();
  1216. pa_context *context{gGlobalMainloop.connectContext(plock)};
  1217. pa_context_disconnect(context);
  1218. pa_context_unref(context);
  1219. return true;
  1220. }
  1221. catch(...) {
  1222. return false;
  1223. }
  1224. }
  1225. bool PulseBackendFactory::querySupport(BackendType type)
  1226. { return type == BackendType::Playback || type == BackendType::Capture; }
  1227. std::string PulseBackendFactory::probe(BackendType type)
  1228. {
  1229. std::string outnames;
  1230. auto add_device = [&outnames](const DevMap &entry) -> void
  1231. {
  1232. /* +1 to also append the null char (to ensure a null-separated list and
  1233. * double-null terminated list).
  1234. */
  1235. outnames.append(entry.name.c_str(), entry.name.length()+1);
  1236. };
  1237. switch(type)
  1238. {
  1239. case BackendType::Playback:
  1240. gGlobalMainloop.probePlaybackDevices();
  1241. std::for_each(PlaybackDevices.cbegin(), PlaybackDevices.cend(), add_device);
  1242. break;
  1243. case BackendType::Capture:
  1244. gGlobalMainloop.probeCaptureDevices();
  1245. std::for_each(CaptureDevices.cbegin(), CaptureDevices.cend(), add_device);
  1246. break;
  1247. }
  1248. return outnames;
  1249. }
  1250. BackendPtr PulseBackendFactory::createBackend(DeviceBase *device, BackendType type)
  1251. {
  1252. if(type == BackendType::Playback)
  1253. return BackendPtr{new PulsePlayback{device}};
  1254. if(type == BackendType::Capture)
  1255. return BackendPtr{new PulseCapture{device}};
  1256. return nullptr;
  1257. }
  1258. BackendFactory &PulseBackendFactory::getFactory()
  1259. {
  1260. static PulseBackendFactory factory{};
  1261. return factory;
  1262. }