SDL_pipewire.c 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <[email protected]>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #ifdef SDL_AUDIO_DRIVER_PIPEWIRE
  20. #include "SDL_pipewire.h"
  21. #include <pipewire/extensions/metadata.h>
  22. #include <spa/param/audio/format-utils.h>
  23. #include <spa/utils/json.h>
  24. /*
  25. * This seems to be a sane lower limit as Pipewire
  26. * uses it in several of it's own modules.
  27. */
  28. #define PW_MIN_SAMPLES 32 // About 0.67ms at 48kHz
  29. #define PW_BASE_CLOCK_RATE 48000
  30. #define PW_POD_BUFFER_LENGTH 1024
  31. #define PW_THREAD_NAME_BUFFER_LENGTH 128
  32. #define PW_MAX_IDENTIFIER_LENGTH 256
  33. enum PW_READY_FLAGS
  34. {
  35. PW_READY_FLAG_BUFFER_ADDED = 0x1,
  36. PW_READY_FLAG_STREAM_READY = 0x2,
  37. PW_READY_FLAG_ALL_PREOPEN_BITS = 0x3,
  38. PW_READY_FLAG_OPEN_COMPLETE = 0x4,
  39. PW_READY_FLAG_ALL_BITS = 0x7
  40. };
  41. #define PW_ID_TO_HANDLE(x) (void *)((uintptr_t)x)
  42. #define PW_HANDLE_TO_ID(x) (uint32_t)((uintptr_t)x)
  43. static bool pipewire_initialized = false;
  44. // Pipewire entry points
  45. static const char *(*PIPEWIRE_pw_get_library_version)(void);
  46. static void (*PIPEWIRE_pw_init)(int *, char ***);
  47. static void (*PIPEWIRE_pw_deinit)(void);
  48. static struct pw_main_loop *(*PIPEWIRE_pw_main_loop_new)(const struct spa_dict *loop);
  49. static struct pw_loop *(*PIPEWIRE_pw_main_loop_get_loop)(struct pw_main_loop *loop);
  50. static int (*PIPEWIRE_pw_main_loop_run)(struct pw_main_loop *loop);
  51. static int (*PIPEWIRE_pw_main_loop_quit)(struct pw_main_loop *loop);
  52. static void(*PIPEWIRE_pw_main_loop_destroy)(struct pw_main_loop *loop);
  53. static struct pw_thread_loop *(*PIPEWIRE_pw_thread_loop_new)(const char *, const struct spa_dict *);
  54. static void (*PIPEWIRE_pw_thread_loop_destroy)(struct pw_thread_loop *);
  55. static void (*PIPEWIRE_pw_thread_loop_stop)(struct pw_thread_loop *);
  56. static struct pw_loop *(*PIPEWIRE_pw_thread_loop_get_loop)(struct pw_thread_loop *);
  57. static void (*PIPEWIRE_pw_thread_loop_lock)(struct pw_thread_loop *);
  58. static void (*PIPEWIRE_pw_thread_loop_unlock)(struct pw_thread_loop *);
  59. static void (*PIPEWIRE_pw_thread_loop_signal)(struct pw_thread_loop *, bool);
  60. static void (*PIPEWIRE_pw_thread_loop_wait)(struct pw_thread_loop *);
  61. static int (*PIPEWIRE_pw_thread_loop_start)(struct pw_thread_loop *);
  62. static struct pw_context *(*PIPEWIRE_pw_context_new)(struct pw_loop *, struct pw_properties *, size_t);
  63. static void (*PIPEWIRE_pw_context_destroy)(struct pw_context *);
  64. static struct pw_core *(*PIPEWIRE_pw_context_connect)(struct pw_context *, struct pw_properties *, size_t);
  65. static void (*PIPEWIRE_pw_proxy_add_object_listener)(struct pw_proxy *, struct spa_hook *, const void *, void *);
  66. static void *(*PIPEWIRE_pw_proxy_get_user_data)(struct pw_proxy *);
  67. static void (*PIPEWIRE_pw_proxy_destroy)(struct pw_proxy *);
  68. static int (*PIPEWIRE_pw_core_disconnect)(struct pw_core *);
  69. static struct pw_stream *(*PIPEWIRE_pw_stream_new_simple)(struct pw_loop *, const char *, struct pw_properties *,
  70. const struct pw_stream_events *, void *);
  71. static void (*PIPEWIRE_pw_stream_destroy)(struct pw_stream *);
  72. static int (*PIPEWIRE_pw_stream_connect)(struct pw_stream *, enum pw_direction, uint32_t, enum pw_stream_flags,
  73. const struct spa_pod **, uint32_t);
  74. static enum pw_stream_state (*PIPEWIRE_pw_stream_get_state)(struct pw_stream *stream, const char **error);
  75. static struct pw_buffer *(*PIPEWIRE_pw_stream_dequeue_buffer)(struct pw_stream *);
  76. static int (*PIPEWIRE_pw_stream_queue_buffer)(struct pw_stream *, struct pw_buffer *);
  77. static struct pw_properties *(*PIPEWIRE_pw_properties_new)(const char *, ...)SPA_SENTINEL;
  78. static int (*PIPEWIRE_pw_properties_set)(struct pw_properties *, const char *, const char *);
  79. static int (*PIPEWIRE_pw_properties_setf)(struct pw_properties *, const char *, const char *, ...) SPA_PRINTF_FUNC(3, 4);
  80. #ifdef SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC
  81. static const char *pipewire_library = SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC;
  82. static SDL_SharedObject *pipewire_handle = NULL;
  83. static bool pipewire_dlsym(const char *fn, void **addr)
  84. {
  85. *addr = SDL_LoadFunction(pipewire_handle, fn);
  86. if (!*addr) {
  87. // Don't call SDL_SetError(): SDL_LoadFunction already did.
  88. return false;
  89. }
  90. return true;
  91. }
  92. #define SDL_PIPEWIRE_SYM(x) \
  93. if (!pipewire_dlsym(#x, (void **)(char *)&PIPEWIRE_##x)) \
  94. return false
  95. static bool load_pipewire_library(void)
  96. {
  97. pipewire_handle = SDL_LoadObject(pipewire_library);
  98. return pipewire_handle ? true : false;
  99. }
  100. static void unload_pipewire_library(void)
  101. {
  102. if (pipewire_handle) {
  103. SDL_UnloadObject(pipewire_handle);
  104. pipewire_handle = NULL;
  105. }
  106. }
  107. #else
  108. #define SDL_PIPEWIRE_SYM(x) PIPEWIRE_##x = x
  109. static bool load_pipewire_library(void)
  110. {
  111. return true;
  112. }
  113. static void unload_pipewire_library(void)
  114. {
  115. // Nothing to do
  116. }
  117. #endif // SDL_AUDIO_DRIVER_PIPEWIRE_DYNAMIC
  118. static bool load_pipewire_syms(void)
  119. {
  120. SDL_PIPEWIRE_SYM(pw_get_library_version);
  121. SDL_PIPEWIRE_SYM(pw_init);
  122. SDL_PIPEWIRE_SYM(pw_deinit);
  123. SDL_PIPEWIRE_SYM(pw_main_loop_new);
  124. SDL_PIPEWIRE_SYM(pw_main_loop_get_loop);
  125. SDL_PIPEWIRE_SYM(pw_main_loop_run);
  126. SDL_PIPEWIRE_SYM(pw_main_loop_quit);
  127. SDL_PIPEWIRE_SYM(pw_main_loop_destroy);
  128. SDL_PIPEWIRE_SYM(pw_thread_loop_new);
  129. SDL_PIPEWIRE_SYM(pw_thread_loop_destroy);
  130. SDL_PIPEWIRE_SYM(pw_thread_loop_stop);
  131. SDL_PIPEWIRE_SYM(pw_thread_loop_get_loop);
  132. SDL_PIPEWIRE_SYM(pw_thread_loop_lock);
  133. SDL_PIPEWIRE_SYM(pw_thread_loop_unlock);
  134. SDL_PIPEWIRE_SYM(pw_thread_loop_signal);
  135. SDL_PIPEWIRE_SYM(pw_thread_loop_wait);
  136. SDL_PIPEWIRE_SYM(pw_thread_loop_start);
  137. SDL_PIPEWIRE_SYM(pw_context_new);
  138. SDL_PIPEWIRE_SYM(pw_context_destroy);
  139. SDL_PIPEWIRE_SYM(pw_context_connect);
  140. SDL_PIPEWIRE_SYM(pw_proxy_add_object_listener);
  141. SDL_PIPEWIRE_SYM(pw_proxy_get_user_data);
  142. SDL_PIPEWIRE_SYM(pw_proxy_destroy);
  143. SDL_PIPEWIRE_SYM(pw_core_disconnect);
  144. SDL_PIPEWIRE_SYM(pw_stream_new_simple);
  145. SDL_PIPEWIRE_SYM(pw_stream_destroy);
  146. SDL_PIPEWIRE_SYM(pw_stream_connect);
  147. SDL_PIPEWIRE_SYM(pw_stream_get_state);
  148. SDL_PIPEWIRE_SYM(pw_stream_dequeue_buffer);
  149. SDL_PIPEWIRE_SYM(pw_stream_queue_buffer);
  150. SDL_PIPEWIRE_SYM(pw_properties_new);
  151. SDL_PIPEWIRE_SYM(pw_properties_set);
  152. SDL_PIPEWIRE_SYM(pw_properties_setf);
  153. return true;
  154. }
  155. static bool init_pipewire_library(void)
  156. {
  157. if (load_pipewire_library()) {
  158. if (load_pipewire_syms()) {
  159. PIPEWIRE_pw_init(NULL, NULL);
  160. return true;
  161. }
  162. }
  163. return false;
  164. }
  165. static void deinit_pipewire_library(void)
  166. {
  167. PIPEWIRE_pw_deinit();
  168. unload_pipewire_library();
  169. }
  170. // A generic Pipewire node object used for enumeration.
  171. struct node_object
  172. {
  173. struct spa_list link;
  174. Uint32 id;
  175. int seq;
  176. bool persist;
  177. /*
  178. * NOTE: If used, this is *must* be allocated with SDL_malloc() or similar
  179. * as SDL_free() will be called on it when the node_object is destroyed.
  180. *
  181. * If ownership of the referenced memory is transferred, this must be set
  182. * to NULL or the memory will be freed when the node_object is destroyed.
  183. */
  184. void *userdata;
  185. struct pw_proxy *proxy;
  186. struct spa_hook node_listener;
  187. struct spa_hook core_listener;
  188. };
  189. // A sink/source node used for stream I/O.
  190. struct io_node
  191. {
  192. struct spa_list link;
  193. Uint32 id;
  194. bool recording;
  195. SDL_AudioSpec spec;
  196. const char *name; // Friendly name
  197. const char *path; // OS identifier (i.e. ALSA endpoint)
  198. char buf[]; // Buffer to hold the name and path strings.
  199. };
  200. // The global hotplug thread and associated objects.
  201. static struct pw_thread_loop *hotplug_loop;
  202. static struct pw_core *hotplug_core;
  203. static struct pw_context *hotplug_context;
  204. static struct pw_registry *hotplug_registry;
  205. static struct spa_hook hotplug_registry_listener;
  206. static struct spa_hook hotplug_core_listener;
  207. static struct spa_list hotplug_pending_list;
  208. static struct spa_list hotplug_io_list;
  209. static int hotplug_init_seq_val;
  210. static bool hotplug_init_complete;
  211. static bool hotplug_events_enabled;
  212. static int pipewire_version_major;
  213. static int pipewire_version_minor;
  214. static int pipewire_version_patch;
  215. static char *pipewire_default_sink_id = NULL;
  216. static char *pipewire_default_source_id = NULL;
  217. static bool pipewire_core_version_at_least(int major, int minor, int patch)
  218. {
  219. return (pipewire_version_major >= major) &&
  220. (pipewire_version_major > major || pipewire_version_minor >= minor) &&
  221. (pipewire_version_major > major || pipewire_version_minor > minor || pipewire_version_patch >= patch);
  222. }
  223. // The active node list
  224. static bool io_list_check_add(struct io_node *node)
  225. {
  226. struct io_node *n;
  227. // See if the node is already in the list
  228. spa_list_for_each (n, &hotplug_io_list, link) {
  229. if (n->id == node->id) {
  230. return false;
  231. }
  232. }
  233. // Add to the list if the node doesn't already exist
  234. spa_list_append(&hotplug_io_list, &node->link);
  235. if (hotplug_events_enabled) {
  236. SDL_AddAudioDevice(node->recording, node->name, &node->spec, PW_ID_TO_HANDLE(node->id));
  237. }
  238. return true;
  239. }
  240. static void io_list_remove(Uint32 id)
  241. {
  242. struct io_node *n, *temp;
  243. // Find and remove the node from the list
  244. spa_list_for_each_safe (n, temp, &hotplug_io_list, link) {
  245. if (n->id == id) {
  246. spa_list_remove(&n->link);
  247. if (hotplug_events_enabled) {
  248. SDL_AudioDeviceDisconnected(SDL_FindPhysicalAudioDeviceByHandle(PW_ID_TO_HANDLE(id)));
  249. }
  250. SDL_free(n);
  251. break;
  252. }
  253. }
  254. }
  255. static void io_list_clear(void)
  256. {
  257. struct io_node *n, *temp;
  258. spa_list_for_each_safe (n, temp, &hotplug_io_list, link) {
  259. spa_list_remove(&n->link);
  260. SDL_free(n);
  261. }
  262. }
  263. static struct io_node *io_list_get_by_id(Uint32 id)
  264. {
  265. struct io_node *n, *temp;
  266. spa_list_for_each_safe (n, temp, &hotplug_io_list, link) {
  267. if (n->id == id) {
  268. return n;
  269. }
  270. }
  271. return NULL;
  272. }
  273. static void node_object_destroy(struct node_object *node)
  274. {
  275. SDL_assert(node != NULL);
  276. spa_list_remove(&node->link);
  277. spa_hook_remove(&node->node_listener);
  278. spa_hook_remove(&node->core_listener);
  279. SDL_free(node->userdata);
  280. PIPEWIRE_pw_proxy_destroy(node->proxy);
  281. }
  282. // The pending node list
  283. static void pending_list_add(struct node_object *node)
  284. {
  285. SDL_assert(node != NULL);
  286. spa_list_append(&hotplug_pending_list, &node->link);
  287. }
  288. static void pending_list_remove(Uint32 id)
  289. {
  290. struct node_object *node, *temp;
  291. spa_list_for_each_safe (node, temp, &hotplug_pending_list, link) {
  292. if (node->id == id) {
  293. node_object_destroy(node);
  294. }
  295. }
  296. }
  297. static void pending_list_clear(void)
  298. {
  299. struct node_object *node, *temp;
  300. spa_list_for_each_safe (node, temp, &hotplug_pending_list, link) {
  301. node_object_destroy(node);
  302. }
  303. }
  304. static void *node_object_new(Uint32 id, const char *type, Uint32 version, const void *funcs, const struct pw_core_events *core_events)
  305. {
  306. struct pw_proxy *proxy;
  307. struct node_object *node;
  308. // Create the proxy object
  309. proxy = pw_registry_bind(hotplug_registry, id, type, version, sizeof(struct node_object));
  310. if (!proxy) {
  311. SDL_SetError("Pipewire: Failed to create proxy object (%i)", errno);
  312. return NULL;
  313. }
  314. node = PIPEWIRE_pw_proxy_get_user_data(proxy);
  315. SDL_zerop(node);
  316. node->id = id;
  317. node->proxy = proxy;
  318. // Add the callbacks
  319. pw_core_add_listener(hotplug_core, &node->core_listener, core_events, node);
  320. PIPEWIRE_pw_proxy_add_object_listener(node->proxy, &node->node_listener, funcs, node);
  321. // Add the node to the active list
  322. pending_list_add(node);
  323. return node;
  324. }
  325. // Core sync points
  326. static void core_events_hotplug_init_callback(void *object, uint32_t id, int seq)
  327. {
  328. if (id == PW_ID_CORE && seq == hotplug_init_seq_val) {
  329. // This core listener is no longer needed.
  330. spa_hook_remove(&hotplug_core_listener);
  331. // Signal that the initial I/O list is populated
  332. hotplug_init_complete = true;
  333. PIPEWIRE_pw_thread_loop_signal(hotplug_loop, false);
  334. }
  335. }
  336. static void core_events_hotplug_info_callback(void *data, const struct pw_core_info *info)
  337. {
  338. if (SDL_sscanf(info->version, "%d.%d.%d", &pipewire_version_major, &pipewire_version_minor, &pipewire_version_patch) < 3) {
  339. pipewire_version_major = 0;
  340. pipewire_version_minor = 0;
  341. pipewire_version_patch = 0;
  342. }
  343. }
  344. static void core_events_interface_callback(void *object, uint32_t id, int seq)
  345. {
  346. struct node_object *node = object;
  347. struct io_node *io = node->userdata;
  348. if (id == PW_ID_CORE && seq == node->seq) {
  349. /*
  350. * Move the I/O node to the connected list.
  351. * On success, the list owns the I/O node object.
  352. */
  353. if (io_list_check_add(io)) {
  354. node->userdata = NULL;
  355. }
  356. node_object_destroy(node);
  357. }
  358. }
  359. static void core_events_metadata_callback(void *object, uint32_t id, int seq)
  360. {
  361. struct node_object *node = object;
  362. if (id == PW_ID_CORE && seq == node->seq && !node->persist) {
  363. node_object_destroy(node);
  364. }
  365. }
  366. static const struct pw_core_events hotplug_init_core_events = { PW_VERSION_CORE_EVENTS, .info = core_events_hotplug_info_callback, .done = core_events_hotplug_init_callback };
  367. static const struct pw_core_events interface_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_interface_callback };
  368. static const struct pw_core_events metadata_core_events = { PW_VERSION_CORE_EVENTS, .done = core_events_metadata_callback };
  369. static void hotplug_core_sync(struct node_object *node)
  370. {
  371. /*
  372. * Node sync events *must* come before the hotplug init sync events or the initial
  373. * I/O list will be incomplete when the main hotplug sync point is hit.
  374. */
  375. if (node) {
  376. node->seq = pw_core_sync(hotplug_core, PW_ID_CORE, node->seq);
  377. }
  378. if (!hotplug_init_complete) {
  379. hotplug_init_seq_val = pw_core_sync(hotplug_core, PW_ID_CORE, hotplug_init_seq_val);
  380. }
  381. }
  382. // Helpers for retrieving values from params
  383. static bool get_range_param(const struct spa_pod *param, Uint32 key, int *def, int *min, int *max)
  384. {
  385. const struct spa_pod_prop *prop;
  386. struct spa_pod *value;
  387. Uint32 n_values, choice;
  388. prop = spa_pod_find_prop(param, NULL, key);
  389. if (prop && prop->value.type == SPA_TYPE_Choice) {
  390. value = spa_pod_get_values(&prop->value, &n_values, &choice);
  391. if (n_values == 3 && choice == SPA_CHOICE_Range) {
  392. Uint32 *v = SPA_POD_BODY(value);
  393. if (v) {
  394. if (def) {
  395. *def = (int)v[0];
  396. }
  397. if (min) {
  398. *min = (int)v[1];
  399. }
  400. if (max) {
  401. *max = (int)v[2];
  402. }
  403. return true;
  404. }
  405. }
  406. }
  407. return false;
  408. }
  409. static bool get_int_param(const struct spa_pod *param, Uint32 key, int *val)
  410. {
  411. const struct spa_pod_prop *prop;
  412. Sint32 v;
  413. prop = spa_pod_find_prop(param, NULL, key);
  414. if (prop && spa_pod_get_int(&prop->value, &v) == 0) {
  415. if (val) {
  416. *val = (int)v;
  417. }
  418. return true;
  419. }
  420. return false;
  421. }
  422. static SDL_AudioFormat SPAFormatToSDL(enum spa_audio_format spafmt)
  423. {
  424. switch (spafmt) {
  425. #define CHECKFMT(spa,sdl) case SPA_AUDIO_FORMAT_##spa: return SDL_AUDIO_##sdl
  426. CHECKFMT(U8, U8);
  427. CHECKFMT(S8, S8);
  428. CHECKFMT(S16_LE, S16LE);
  429. CHECKFMT(S16_BE, S16BE);
  430. CHECKFMT(S32_LE, S32LE);
  431. CHECKFMT(S32_BE, S32BE);
  432. CHECKFMT(F32_LE, F32LE);
  433. CHECKFMT(F32_BE, F32BE);
  434. #undef CHECKFMT
  435. default: break;
  436. }
  437. return SDL_AUDIO_UNKNOWN;
  438. }
  439. // Interface node callbacks
  440. static void node_event_info(void *object, const struct pw_node_info *info)
  441. {
  442. struct node_object *node = object;
  443. struct io_node *io = node->userdata;
  444. const char *prop_val;
  445. Uint32 i;
  446. if (info) {
  447. prop_val = spa_dict_lookup(info->props, PW_KEY_AUDIO_CHANNELS);
  448. if (prop_val) {
  449. io->spec.channels = (Uint8)SDL_atoi(prop_val);
  450. }
  451. // Need to parse the parameters to get the sample rate
  452. for (i = 0; i < info->n_params; ++i) {
  453. pw_node_enum_params((struct pw_node*)node->proxy, 0, info->params[i].id, 0, 0, NULL);
  454. }
  455. hotplug_core_sync(node);
  456. }
  457. }
  458. static void node_event_param(void *object, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod *param)
  459. {
  460. struct node_object *node = object;
  461. struct io_node *io = node->userdata;
  462. if ((id == SPA_PARAM_Format) && (io->spec.format == SDL_AUDIO_UNKNOWN)) {
  463. struct spa_audio_info_raw info;
  464. SDL_zero(info);
  465. if (spa_format_audio_raw_parse(param, &info) == 0) {
  466. //SDL_Log("Sink Format: %d, Rate: %d Hz, Channels: %d", info.format, info.rate, info.channels);
  467. io->spec.format = SPAFormatToSDL(info.format);
  468. }
  469. }
  470. // Get the default frequency
  471. if (io->spec.freq == 0) {
  472. get_range_param(param, SPA_FORMAT_AUDIO_rate, &io->spec.freq, NULL, NULL);
  473. }
  474. /*
  475. * The channel count should have come from the node properties,
  476. * but it is stored here as well. If one failed, try the other.
  477. */
  478. if (io->spec.channels == 0) {
  479. int channels;
  480. if (get_int_param(param, SPA_FORMAT_AUDIO_channels, &channels)) {
  481. io->spec.channels = (Uint8)channels;
  482. }
  483. }
  484. }
  485. static const struct pw_node_events interface_node_events = { PW_VERSION_NODE_EVENTS, .info = node_event_info,
  486. .param = node_event_param };
  487. static char *get_name_from_json(const char *json)
  488. {
  489. struct spa_json parser[2];
  490. char key[7]; // "name"
  491. char value[PW_MAX_IDENTIFIER_LENGTH];
  492. spa_json_init(&parser[0], json, SDL_strlen(json));
  493. if (spa_json_enter_object(&parser[0], &parser[1]) <= 0) {
  494. // Not actually JSON
  495. return NULL;
  496. }
  497. if (spa_json_get_string(&parser[1], key, sizeof(key)) <= 0) {
  498. // Not actually a key/value pair
  499. return NULL;
  500. }
  501. if (spa_json_get_string(&parser[1], value, sizeof(value)) <= 0) {
  502. // Somehow had a key with no value?
  503. return NULL;
  504. }
  505. return SDL_strdup(value);
  506. }
  507. static void change_default_device(const char *path)
  508. {
  509. if (hotplug_events_enabled) {
  510. struct io_node *n, *temp;
  511. spa_list_for_each_safe (n, temp, &hotplug_io_list, link) {
  512. if (SDL_strcmp(n->path, path) == 0) {
  513. SDL_DefaultAudioDeviceChanged(SDL_FindPhysicalAudioDeviceByHandle(PW_ID_TO_HANDLE(n->id)));
  514. return; // found it, we're done.
  515. }
  516. }
  517. }
  518. }
  519. // Metadata node callback
  520. static int metadata_property(void *object, Uint32 subject, const char *key, const char *type, const char *value)
  521. {
  522. struct node_object *node = object;
  523. if (subject == PW_ID_CORE && key && value) {
  524. if (!SDL_strcmp(key, "default.audio.sink")) {
  525. if (pipewire_default_sink_id) {
  526. SDL_free(pipewire_default_sink_id);
  527. }
  528. pipewire_default_sink_id = get_name_from_json(value);
  529. node->persist = true;
  530. change_default_device(pipewire_default_sink_id);
  531. } else if (!SDL_strcmp(key, "default.audio.source")) {
  532. if (pipewire_default_source_id) {
  533. SDL_free(pipewire_default_source_id);
  534. }
  535. pipewire_default_source_id = get_name_from_json(value);
  536. node->persist = true;
  537. change_default_device(pipewire_default_source_id);
  538. }
  539. }
  540. return 0;
  541. }
  542. static const struct pw_metadata_events metadata_node_events = { PW_VERSION_METADATA_EVENTS, .property = metadata_property };
  543. // Global registry callbacks
  544. static void registry_event_global_callback(void *object, uint32_t id, uint32_t permissions, const char *type, uint32_t version,
  545. const struct spa_dict *props)
  546. {
  547. struct node_object *node;
  548. // We're only interested in interface and metadata nodes.
  549. if (!SDL_strcmp(type, PW_TYPE_INTERFACE_Node)) {
  550. const char *media_class = spa_dict_lookup(props, PW_KEY_MEDIA_CLASS);
  551. if (media_class) {
  552. const char *node_desc;
  553. const char *node_path;
  554. struct io_node *io;
  555. bool recording;
  556. int desc_buffer_len;
  557. int path_buffer_len;
  558. // Just want sink and source
  559. if (!SDL_strcasecmp(media_class, "Audio/Sink")) {
  560. recording = false;
  561. } else if (!SDL_strcasecmp(media_class, "Audio/Source")) {
  562. recording = true;
  563. } else {
  564. return;
  565. }
  566. node_desc = spa_dict_lookup(props, PW_KEY_NODE_DESCRIPTION);
  567. node_path = spa_dict_lookup(props, PW_KEY_NODE_NAME);
  568. if (node_desc && node_path) {
  569. node = node_object_new(id, type, version, &interface_node_events, &interface_core_events);
  570. if (!node) {
  571. SDL_SetError("Pipewire: Failed to allocate interface node");
  572. return;
  573. }
  574. // Allocate and initialize the I/O node information struct
  575. desc_buffer_len = SDL_strlen(node_desc) + 1;
  576. path_buffer_len = SDL_strlen(node_path) + 1;
  577. node->userdata = io = SDL_calloc(1, sizeof(struct io_node) + desc_buffer_len + path_buffer_len);
  578. if (!io) {
  579. node_object_destroy(node);
  580. return;
  581. }
  582. // Begin setting the node properties
  583. io->id = id;
  584. io->recording = recording;
  585. if (io->spec.format == SDL_AUDIO_UNKNOWN) {
  586. io->spec.format = SDL_AUDIO_S16; // we'll go conservative here if for some reason the format isn't known.
  587. }
  588. io->name = io->buf;
  589. io->path = io->buf + desc_buffer_len;
  590. SDL_strlcpy(io->buf, node_desc, desc_buffer_len);
  591. SDL_strlcpy(io->buf + desc_buffer_len, node_path, path_buffer_len);
  592. // Update sync points
  593. hotplug_core_sync(node);
  594. }
  595. }
  596. } else if (!SDL_strcmp(type, PW_TYPE_INTERFACE_Metadata)) {
  597. node = node_object_new(id, type, version, &metadata_node_events, &metadata_core_events);
  598. if (!node) {
  599. SDL_SetError("Pipewire: Failed to allocate metadata node");
  600. return;
  601. }
  602. // Update sync points
  603. hotplug_core_sync(node);
  604. }
  605. }
  606. static void registry_event_remove_callback(void *object, uint32_t id)
  607. {
  608. io_list_remove(id);
  609. pending_list_remove(id);
  610. }
  611. static const struct pw_registry_events registry_events = { PW_VERSION_REGISTRY_EVENTS, .global = registry_event_global_callback,
  612. .global_remove = registry_event_remove_callback };
  613. // The hotplug thread
  614. static bool hotplug_loop_init(void)
  615. {
  616. int res;
  617. spa_list_init(&hotplug_pending_list);
  618. spa_list_init(&hotplug_io_list);
  619. hotplug_loop = PIPEWIRE_pw_thread_loop_new("SDLPwAudioPlug", NULL);
  620. if (!hotplug_loop) {
  621. return SDL_SetError("Pipewire: Failed to create hotplug detection loop (%i)", errno);
  622. }
  623. hotplug_context = PIPEWIRE_pw_context_new(PIPEWIRE_pw_thread_loop_get_loop(hotplug_loop), NULL, 0);
  624. if (!hotplug_context) {
  625. return SDL_SetError("Pipewire: Failed to create hotplug detection context (%i)", errno);
  626. }
  627. hotplug_core = PIPEWIRE_pw_context_connect(hotplug_context, NULL, 0);
  628. if (!hotplug_core) {
  629. return SDL_SetError("Pipewire: Failed to connect hotplug detection context (%i)", errno);
  630. }
  631. hotplug_registry = pw_core_get_registry(hotplug_core, PW_VERSION_REGISTRY, 0);
  632. if (!hotplug_registry) {
  633. return SDL_SetError("Pipewire: Failed to acquire hotplug detection registry (%i)", errno);
  634. }
  635. spa_zero(hotplug_registry_listener);
  636. pw_registry_add_listener(hotplug_registry, &hotplug_registry_listener, &registry_events, NULL);
  637. spa_zero(hotplug_core_listener);
  638. pw_core_add_listener(hotplug_core, &hotplug_core_listener, &hotplug_init_core_events, NULL);
  639. hotplug_init_seq_val = pw_core_sync(hotplug_core, PW_ID_CORE, 0);
  640. res = PIPEWIRE_pw_thread_loop_start(hotplug_loop);
  641. if (res != 0) {
  642. return SDL_SetError("Pipewire: Failed to start hotplug detection loop");
  643. }
  644. return true;
  645. }
  646. static void hotplug_loop_destroy(void)
  647. {
  648. if (hotplug_loop) {
  649. PIPEWIRE_pw_thread_loop_stop(hotplug_loop);
  650. }
  651. pending_list_clear();
  652. io_list_clear();
  653. hotplug_init_complete = false;
  654. hotplug_events_enabled = false;
  655. if (pipewire_default_sink_id) {
  656. SDL_free(pipewire_default_sink_id);
  657. pipewire_default_sink_id = NULL;
  658. }
  659. if (pipewire_default_source_id) {
  660. SDL_free(pipewire_default_source_id);
  661. pipewire_default_source_id = NULL;
  662. }
  663. if (hotplug_registry) {
  664. PIPEWIRE_pw_proxy_destroy((struct pw_proxy *)hotplug_registry);
  665. hotplug_registry = NULL;
  666. }
  667. if (hotplug_core) {
  668. PIPEWIRE_pw_core_disconnect(hotplug_core);
  669. hotplug_core = NULL;
  670. }
  671. if (hotplug_context) {
  672. PIPEWIRE_pw_context_destroy(hotplug_context);
  673. hotplug_context = NULL;
  674. }
  675. if (hotplug_loop) {
  676. PIPEWIRE_pw_thread_loop_destroy(hotplug_loop);
  677. hotplug_loop = NULL;
  678. }
  679. }
  680. static void PIPEWIRE_DetectDevices(SDL_AudioDevice **default_playback, SDL_AudioDevice **default_recording)
  681. {
  682. struct io_node *io;
  683. PIPEWIRE_pw_thread_loop_lock(hotplug_loop);
  684. // Wait until the initial registry enumeration is complete
  685. if (!hotplug_init_complete) {
  686. PIPEWIRE_pw_thread_loop_wait(hotplug_loop);
  687. }
  688. spa_list_for_each (io, &hotplug_io_list, link) {
  689. SDL_AudioDevice *device = SDL_AddAudioDevice(io->recording, io->name, &io->spec, PW_ID_TO_HANDLE(io->id));
  690. if (pipewire_default_sink_id && SDL_strcmp(io->path, pipewire_default_sink_id) == 0) {
  691. if (!io->recording) {
  692. *default_playback = device;
  693. }
  694. } else if (pipewire_default_source_id && SDL_strcmp(io->path, pipewire_default_source_id) == 0) {
  695. if (io->recording) {
  696. *default_recording = device;
  697. }
  698. }
  699. }
  700. hotplug_events_enabled = true;
  701. PIPEWIRE_pw_thread_loop_unlock(hotplug_loop);
  702. }
  703. // Channel maps that match the order in SDL_Audio.h
  704. static const enum spa_audio_channel PIPEWIRE_channel_map_1[] = { SPA_AUDIO_CHANNEL_MONO };
  705. static const enum spa_audio_channel PIPEWIRE_channel_map_2[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR };
  706. static const enum spa_audio_channel PIPEWIRE_channel_map_3[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_LFE };
  707. static const enum spa_audio_channel PIPEWIRE_channel_map_4[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_RL,
  708. SPA_AUDIO_CHANNEL_RR };
  709. static const enum spa_audio_channel PIPEWIRE_channel_map_5[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_FC,
  710. SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR };
  711. static const enum spa_audio_channel PIPEWIRE_channel_map_6[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_FC,
  712. SPA_AUDIO_CHANNEL_LFE, SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR };
  713. static const enum spa_audio_channel PIPEWIRE_channel_map_7[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_FC,
  714. SPA_AUDIO_CHANNEL_LFE, SPA_AUDIO_CHANNEL_RC, SPA_AUDIO_CHANNEL_RL,
  715. SPA_AUDIO_CHANNEL_RR };
  716. static const enum spa_audio_channel PIPEWIRE_channel_map_8[] = { SPA_AUDIO_CHANNEL_FL, SPA_AUDIO_CHANNEL_FR, SPA_AUDIO_CHANNEL_FC,
  717. SPA_AUDIO_CHANNEL_LFE, SPA_AUDIO_CHANNEL_RL, SPA_AUDIO_CHANNEL_RR,
  718. SPA_AUDIO_CHANNEL_SL, SPA_AUDIO_CHANNEL_SR };
  719. #define COPY_CHANNEL_MAP(c) SDL_memcpy(info->position, PIPEWIRE_channel_map_##c, sizeof(PIPEWIRE_channel_map_##c))
  720. static void initialize_spa_info(const SDL_AudioSpec *spec, struct spa_audio_info_raw *info)
  721. {
  722. info->channels = spec->channels;
  723. info->rate = spec->freq;
  724. switch (spec->channels) {
  725. case 1:
  726. COPY_CHANNEL_MAP(1);
  727. break;
  728. case 2:
  729. COPY_CHANNEL_MAP(2);
  730. break;
  731. case 3:
  732. COPY_CHANNEL_MAP(3);
  733. break;
  734. case 4:
  735. COPY_CHANNEL_MAP(4);
  736. break;
  737. case 5:
  738. COPY_CHANNEL_MAP(5);
  739. break;
  740. case 6:
  741. COPY_CHANNEL_MAP(6);
  742. break;
  743. case 7:
  744. COPY_CHANNEL_MAP(7);
  745. break;
  746. case 8:
  747. COPY_CHANNEL_MAP(8);
  748. break;
  749. }
  750. // Pipewire natively supports all of SDL's sample formats
  751. switch (spec->format) {
  752. case SDL_AUDIO_U8:
  753. info->format = SPA_AUDIO_FORMAT_U8;
  754. break;
  755. case SDL_AUDIO_S8:
  756. info->format = SPA_AUDIO_FORMAT_S8;
  757. break;
  758. case SDL_AUDIO_S16LE:
  759. info->format = SPA_AUDIO_FORMAT_S16_LE;
  760. break;
  761. case SDL_AUDIO_S16BE:
  762. info->format = SPA_AUDIO_FORMAT_S16_BE;
  763. break;
  764. case SDL_AUDIO_S32LE:
  765. info->format = SPA_AUDIO_FORMAT_S32_LE;
  766. break;
  767. case SDL_AUDIO_S32BE:
  768. info->format = SPA_AUDIO_FORMAT_S32_BE;
  769. break;
  770. case SDL_AUDIO_F32LE:
  771. info->format = SPA_AUDIO_FORMAT_F32_LE;
  772. break;
  773. case SDL_AUDIO_F32BE:
  774. info->format = SPA_AUDIO_FORMAT_F32_BE;
  775. break;
  776. default:
  777. info->format = SPA_AUDIO_FORMAT_UNKNOWN;
  778. break;
  779. }
  780. }
  781. static Uint8 *PIPEWIRE_GetDeviceBuf(SDL_AudioDevice *device, int *buffer_size)
  782. {
  783. // See if a buffer is available. If this returns NULL, SDL_PlaybackAudioThreadIterate will return false, but since we own the thread, it won't kill playback.
  784. // !!! FIXME: It's not clear to me if this ever returns NULL or if this was just defensive coding.
  785. struct pw_stream *stream = device->hidden->stream;
  786. struct pw_buffer *pw_buf = PIPEWIRE_pw_stream_dequeue_buffer(stream);
  787. if (pw_buf == NULL) {
  788. return NULL;
  789. }
  790. struct spa_buffer *spa_buf = pw_buf->buffer;
  791. if (spa_buf->datas[0].data == NULL) {
  792. PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
  793. return NULL;
  794. }
  795. device->hidden->pw_buf = pw_buf;
  796. return (Uint8 *) spa_buf->datas[0].data;
  797. }
  798. static bool PIPEWIRE_PlayDevice(SDL_AudioDevice *device, const Uint8 *buffer, int buffer_size)
  799. {
  800. struct pw_stream *stream = device->hidden->stream;
  801. struct pw_buffer *pw_buf = device->hidden->pw_buf;
  802. struct spa_buffer *spa_buf = pw_buf->buffer;
  803. spa_buf->datas[0].chunk->offset = 0;
  804. spa_buf->datas[0].chunk->stride = device->hidden->stride;
  805. spa_buf->datas[0].chunk->size = buffer_size;
  806. PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
  807. device->hidden->pw_buf = NULL;
  808. return true;
  809. }
  810. static void output_callback(void *data)
  811. {
  812. SDL_AudioDevice *device = (SDL_AudioDevice *) data;
  813. // this callback can fire in a background thread during OpenDevice, while we're still blocking
  814. // _with the device lock_ until the stream is ready, causing a deadlock. Write silence in this case.
  815. if (device->hidden->stream_init_status != PW_READY_FLAG_ALL_BITS) {
  816. int bufsize = 0;
  817. Uint8 *buf = PIPEWIRE_GetDeviceBuf(device, &bufsize);
  818. if (buf && bufsize) {
  819. SDL_memset(buf, device->silence_value, bufsize);
  820. }
  821. PIPEWIRE_PlayDevice(device, buf, bufsize);
  822. return;
  823. }
  824. SDL_PlaybackAudioThreadIterate(device);
  825. }
  826. static void PIPEWIRE_FlushRecording(SDL_AudioDevice *device)
  827. {
  828. struct pw_stream *stream = device->hidden->stream;
  829. struct pw_buffer *pw_buf = PIPEWIRE_pw_stream_dequeue_buffer(stream);
  830. if (pw_buf) { // just requeue it without any further thought.
  831. PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
  832. }
  833. }
  834. static int PIPEWIRE_RecordDevice(SDL_AudioDevice *device, void *buffer, int buflen)
  835. {
  836. struct pw_stream *stream = device->hidden->stream;
  837. struct pw_buffer *pw_buf = PIPEWIRE_pw_stream_dequeue_buffer(stream);
  838. if (!pw_buf) {
  839. return 0;
  840. }
  841. struct spa_buffer *spa_buf = pw_buf->buffer;
  842. if (!spa_buf) {
  843. PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
  844. return 0;
  845. }
  846. const Uint8 *src = (const Uint8 *)spa_buf->datas[0].data;
  847. const Uint32 offset = SPA_MIN(spa_buf->datas[0].chunk->offset, spa_buf->datas[0].maxsize);
  848. const Uint32 size = SPA_MIN(spa_buf->datas[0].chunk->size, spa_buf->datas[0].maxsize - offset);
  849. const int cpy = SDL_min(buflen, (int) size);
  850. SDL_assert(size <= buflen); // We'll have to reengineer some stuff if this turns out to not be true.
  851. SDL_memcpy(buffer, src + offset, cpy);
  852. PIPEWIRE_pw_stream_queue_buffer(stream, pw_buf);
  853. return cpy;
  854. }
  855. static void input_callback(void *data)
  856. {
  857. SDL_AudioDevice *device = (SDL_AudioDevice *) data;
  858. // this callback can fire in a background thread during OpenDevice, while we're still blocking
  859. // _with the device lock_ until the stream is ready, causing a deadlock. Drop data in this case.
  860. if (device->hidden->stream_init_status != PW_READY_FLAG_ALL_BITS) {
  861. PIPEWIRE_FlushRecording(device);
  862. return;
  863. }
  864. SDL_RecordingAudioThreadIterate(device);
  865. }
  866. static void stream_add_buffer_callback(void *data, struct pw_buffer *buffer)
  867. {
  868. SDL_AudioDevice *device = (SDL_AudioDevice *) data;
  869. if (device->recording == false) {
  870. /* Clamp the output spec samples and size to the max size of the Pipewire buffer.
  871. If they exceed the maximum size of the Pipewire buffer, double buffering will be used. */
  872. if (device->buffer_size > buffer->buffer->datas[0].maxsize) {
  873. SDL_LockMutex(device->lock);
  874. device->sample_frames = buffer->buffer->datas[0].maxsize / device->hidden->stride;
  875. device->buffer_size = buffer->buffer->datas[0].maxsize;
  876. SDL_UnlockMutex(device->lock);
  877. }
  878. }
  879. device->hidden->stream_init_status |= PW_READY_FLAG_BUFFER_ADDED;
  880. PIPEWIRE_pw_thread_loop_signal(device->hidden->loop, false);
  881. }
  882. static void stream_state_changed_callback(void *data, enum pw_stream_state old, enum pw_stream_state state, const char *error)
  883. {
  884. SDL_AudioDevice *device = (SDL_AudioDevice *) data;
  885. if (state == PW_STREAM_STATE_STREAMING) {
  886. device->hidden->stream_init_status |= PW_READY_FLAG_STREAM_READY;
  887. }
  888. if (state == PW_STREAM_STATE_STREAMING || state == PW_STREAM_STATE_ERROR) {
  889. PIPEWIRE_pw_thread_loop_signal(device->hidden->loop, false);
  890. }
  891. }
  892. static const struct pw_stream_events stream_output_events = { PW_VERSION_STREAM_EVENTS,
  893. .state_changed = stream_state_changed_callback,
  894. .add_buffer = stream_add_buffer_callback,
  895. .process = output_callback };
  896. static const struct pw_stream_events stream_input_events = { PW_VERSION_STREAM_EVENTS,
  897. .state_changed = stream_state_changed_callback,
  898. .add_buffer = stream_add_buffer_callback,
  899. .process = input_callback };
  900. static bool PIPEWIRE_OpenDevice(SDL_AudioDevice *device)
  901. {
  902. /*
  903. * NOTE: The PW_STREAM_FLAG_RT_PROCESS flag can be set to call the stream
  904. * processing callback from the realtime thread. However, it comes with some
  905. * caveats: no file IO, allocations, locking or other blocking operations
  906. * must occur in the mixer callback. As this cannot be guaranteed when the
  907. * callback is in the calling application, this flag is omitted.
  908. */
  909. static const enum pw_stream_flags STREAM_FLAGS = PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS;
  910. char thread_name[PW_THREAD_NAME_BUFFER_LENGTH];
  911. Uint8 pod_buffer[PW_POD_BUFFER_LENGTH];
  912. struct spa_pod_builder b = SPA_POD_BUILDER_INIT(pod_buffer, sizeof(pod_buffer));
  913. struct spa_audio_info_raw spa_info = { 0 };
  914. const struct spa_pod *params = NULL;
  915. struct SDL_PrivateAudioData *priv;
  916. struct pw_properties *props;
  917. const char *app_name, *icon_name, *app_id, *stream_name, *stream_role, *error;
  918. Uint32 node_id = !device->handle ? PW_ID_ANY : PW_HANDLE_TO_ID(device->handle);
  919. const bool recording = device->recording;
  920. int res;
  921. // Clamp the period size to sane values
  922. const int min_period = PW_MIN_SAMPLES * SPA_MAX(device->spec.freq / PW_BASE_CLOCK_RATE, 1);
  923. // Get the hints for the application name, icon name, stream name and role
  924. app_name = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING);
  925. icon_name = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_APP_ICON_NAME);
  926. if (!icon_name || *icon_name == '\0') {
  927. icon_name = "applications-games";
  928. }
  929. // App ID. Default to NULL if not available.
  930. app_id = SDL_GetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING);
  931. stream_name = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_STREAM_NAME);
  932. if (!stream_name || *stream_name == '\0') {
  933. if (app_name) {
  934. stream_name = app_name;
  935. } else if (app_id) {
  936. stream_name = app_id;
  937. } else {
  938. stream_name = "SDL Audio Stream";
  939. }
  940. }
  941. /*
  942. * 'Music' is the default used internally by Pipewire and it's modules,
  943. * but 'Game' seems more appropriate for the majority of SDL applications.
  944. */
  945. stream_role = SDL_GetHint(SDL_HINT_AUDIO_DEVICE_STREAM_ROLE);
  946. if (!stream_role || *stream_role == '\0') {
  947. stream_role = "Game";
  948. }
  949. // Initialize the Pipewire stream info from the SDL audio spec
  950. initialize_spa_info(&device->spec, &spa_info);
  951. params = spa_format_audio_raw_build(&b, SPA_PARAM_EnumFormat, &spa_info);
  952. if (!params) {
  953. return SDL_SetError("Pipewire: Failed to set audio format parameters");
  954. }
  955. priv = SDL_calloc(1, sizeof(struct SDL_PrivateAudioData));
  956. device->hidden = priv;
  957. if (!priv) {
  958. return false;
  959. }
  960. // Size of a single audio frame in bytes
  961. priv->stride = SDL_AUDIO_FRAMESIZE(device->spec);
  962. if (device->sample_frames < min_period) {
  963. device->sample_frames = min_period;
  964. }
  965. SDL_UpdatedAudioDeviceFormat(device);
  966. SDL_GetAudioThreadName(device, thread_name, sizeof(thread_name));
  967. priv->loop = PIPEWIRE_pw_thread_loop_new(thread_name, NULL);
  968. if (!priv->loop) {
  969. return SDL_SetError("Pipewire: Failed to create stream loop (%i)", errno);
  970. }
  971. // Load the realtime module so Pipewire can set the loop thread to the appropriate priority.
  972. props = PIPEWIRE_pw_properties_new(PW_KEY_CONFIG_NAME, "client-rt.conf", NULL);
  973. if (!props) {
  974. return SDL_SetError("Pipewire: Failed to create stream context properties (%i)", errno);
  975. }
  976. priv->context = PIPEWIRE_pw_context_new(PIPEWIRE_pw_thread_loop_get_loop(priv->loop), props, 0);
  977. if (!priv->context) {
  978. return SDL_SetError("Pipewire: Failed to create stream context (%i)", errno);
  979. }
  980. props = PIPEWIRE_pw_properties_new(NULL, NULL);
  981. if (!props) {
  982. return SDL_SetError("Pipewire: Failed to create stream properties (%i)", errno);
  983. }
  984. PIPEWIRE_pw_properties_set(props, PW_KEY_MEDIA_TYPE, "Audio");
  985. PIPEWIRE_pw_properties_set(props, PW_KEY_MEDIA_CATEGORY, recording ? "Capture" : "Playback");
  986. PIPEWIRE_pw_properties_set(props, PW_KEY_MEDIA_ROLE, stream_role);
  987. PIPEWIRE_pw_properties_set(props, PW_KEY_APP_NAME, app_name);
  988. PIPEWIRE_pw_properties_set(props, PW_KEY_APP_ICON_NAME, icon_name);
  989. if (app_id) {
  990. PIPEWIRE_pw_properties_set(props, PW_KEY_APP_ID, app_id);
  991. }
  992. PIPEWIRE_pw_properties_set(props, PW_KEY_NODE_NAME, stream_name);
  993. PIPEWIRE_pw_properties_set(props, PW_KEY_NODE_DESCRIPTION, stream_name);
  994. PIPEWIRE_pw_properties_setf(props, PW_KEY_NODE_LATENCY, "%u/%i", device->sample_frames, device->spec.freq);
  995. PIPEWIRE_pw_properties_setf(props, PW_KEY_NODE_RATE, "1/%u", device->spec.freq);
  996. PIPEWIRE_pw_properties_set(props, PW_KEY_NODE_ALWAYS_PROCESS, "true");
  997. // UPDATE: This prevents users from moving the audio to a new sink (device) using standard tools. This is slightly in conflict
  998. // with how SDL wants to manage audio devices, but if people want to do it, we should let them, so this is commented out
  999. // for now. We might revisit later.
  1000. //PIPEWIRE_pw_properties_set(props, PW_KEY_NODE_DONT_RECONNECT, "true"); // Requesting a specific device, don't migrate to new default hardware.
  1001. if (node_id != PW_ID_ANY) {
  1002. PIPEWIRE_pw_thread_loop_lock(hotplug_loop);
  1003. const struct io_node *node = io_list_get_by_id(node_id);
  1004. if (node) {
  1005. PIPEWIRE_pw_properties_set(props, PW_KEY_TARGET_OBJECT, node->path);
  1006. }
  1007. PIPEWIRE_pw_thread_loop_unlock(hotplug_loop);
  1008. }
  1009. // Create the new stream
  1010. priv->stream = PIPEWIRE_pw_stream_new_simple(PIPEWIRE_pw_thread_loop_get_loop(priv->loop), stream_name, props,
  1011. recording ? &stream_input_events : &stream_output_events, device);
  1012. if (!priv->stream) {
  1013. return SDL_SetError("Pipewire: Failed to create stream (%i)", errno);
  1014. }
  1015. // The target node is passed via PW_KEY_TARGET_OBJECT; target_id is a legacy parameter and must be PW_ID_ANY.
  1016. res = PIPEWIRE_pw_stream_connect(priv->stream, recording ? PW_DIRECTION_INPUT : PW_DIRECTION_OUTPUT, PW_ID_ANY, STREAM_FLAGS,
  1017. &params, 1);
  1018. if (res != 0) {
  1019. return SDL_SetError("Pipewire: Failed to connect stream");
  1020. }
  1021. res = PIPEWIRE_pw_thread_loop_start(priv->loop);
  1022. if (res != 0) {
  1023. return SDL_SetError("Pipewire: Failed to start stream loop");
  1024. }
  1025. // Wait until all pre-open init flags are set or the stream has failed.
  1026. PIPEWIRE_pw_thread_loop_lock(priv->loop);
  1027. while (priv->stream_init_status != PW_READY_FLAG_ALL_PREOPEN_BITS &&
  1028. PIPEWIRE_pw_stream_get_state(priv->stream, NULL) != PW_STREAM_STATE_ERROR) {
  1029. PIPEWIRE_pw_thread_loop_wait(priv->loop);
  1030. }
  1031. priv->stream_init_status |= PW_READY_FLAG_OPEN_COMPLETE;
  1032. PIPEWIRE_pw_thread_loop_unlock(priv->loop);
  1033. if (PIPEWIRE_pw_stream_get_state(priv->stream, &error) == PW_STREAM_STATE_ERROR) {
  1034. return SDL_SetError("Pipewire: Stream error: %s", error);
  1035. }
  1036. return true;
  1037. }
  1038. static void PIPEWIRE_CloseDevice(SDL_AudioDevice *device)
  1039. {
  1040. if (!device->hidden) {
  1041. return;
  1042. }
  1043. if (device->hidden->loop) {
  1044. PIPEWIRE_pw_thread_loop_stop(device->hidden->loop);
  1045. }
  1046. if (device->hidden->stream) {
  1047. PIPEWIRE_pw_stream_destroy(device->hidden->stream);
  1048. }
  1049. if (device->hidden->context) {
  1050. PIPEWIRE_pw_context_destroy(device->hidden->context);
  1051. }
  1052. if (device->hidden->loop) {
  1053. PIPEWIRE_pw_thread_loop_destroy(device->hidden->loop);
  1054. }
  1055. SDL_free(device->hidden);
  1056. device->hidden = NULL;
  1057. SDL_AudioThreadFinalize(device);
  1058. }
  1059. static void PIPEWIRE_DeinitializeStart(void)
  1060. {
  1061. if (pipewire_initialized) {
  1062. hotplug_loop_destroy();
  1063. }
  1064. }
  1065. static void PIPEWIRE_Deinitialize(void)
  1066. {
  1067. if (pipewire_initialized) {
  1068. hotplug_loop_destroy();
  1069. deinit_pipewire_library();
  1070. pipewire_initialized = false;
  1071. }
  1072. }
  1073. static bool PipewireInitialize(SDL_AudioDriverImpl *impl)
  1074. {
  1075. if (!pipewire_initialized) {
  1076. if (!init_pipewire_library()) {
  1077. return false;
  1078. }
  1079. pipewire_initialized = true;
  1080. if (!hotplug_loop_init()) {
  1081. PIPEWIRE_Deinitialize();
  1082. return false;
  1083. }
  1084. }
  1085. impl->DetectDevices = PIPEWIRE_DetectDevices;
  1086. impl->OpenDevice = PIPEWIRE_OpenDevice;
  1087. impl->DeinitializeStart = PIPEWIRE_DeinitializeStart;
  1088. impl->Deinitialize = PIPEWIRE_Deinitialize;
  1089. impl->PlayDevice = PIPEWIRE_PlayDevice;
  1090. impl->GetDeviceBuf = PIPEWIRE_GetDeviceBuf;
  1091. impl->RecordDevice = PIPEWIRE_RecordDevice;
  1092. impl->FlushRecording = PIPEWIRE_FlushRecording;
  1093. impl->CloseDevice = PIPEWIRE_CloseDevice;
  1094. impl->HasRecordingSupport = true;
  1095. impl->ProvidesOwnCallbackThread = true;
  1096. return true;
  1097. }
  1098. static bool PIPEWIRE_PREFERRED_Init(SDL_AudioDriverImpl *impl)
  1099. {
  1100. if (!PipewireInitialize(impl)) {
  1101. return false;
  1102. }
  1103. // run device detection but don't add any devices to SDL; we're just waiting to see if PipeWire sees any devices. If not, fall back to the next backend.
  1104. PIPEWIRE_pw_thread_loop_lock(hotplug_loop);
  1105. // Wait until the initial registry enumeration is complete
  1106. if (!hotplug_init_complete) {
  1107. PIPEWIRE_pw_thread_loop_wait(hotplug_loop);
  1108. }
  1109. const bool no_devices = spa_list_is_empty(&hotplug_io_list);
  1110. PIPEWIRE_pw_thread_loop_unlock(hotplug_loop);
  1111. if (no_devices || !pipewire_core_version_at_least(1, 0, 0)) {
  1112. PIPEWIRE_Deinitialize();
  1113. return false;
  1114. }
  1115. return true; // this will move on to PIPEWIRE_DetectDevices and reuse hotplug_io_list.
  1116. }
  1117. static bool PIPEWIRE_Init(SDL_AudioDriverImpl *impl)
  1118. {
  1119. return PipewireInitialize(impl);
  1120. }
  1121. AudioBootStrap PIPEWIRE_PREFERRED_bootstrap = {
  1122. "pipewire", "Pipewire", PIPEWIRE_PREFERRED_Init, false, true
  1123. };
  1124. AudioBootStrap PIPEWIRE_bootstrap = {
  1125. "pipewire", "Pipewire", PIPEWIRE_Init, false, false
  1126. };
  1127. #endif // SDL_AUDIO_DRIVER_PIPEWIRE