1 /* PipeWire
2  *
3  * Copyright © 2021 Wim Taymans
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  */
24 
25 #include <string.h>
26 #include <stdio.h>
27 #include <errno.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <unistd.h>
32 #include <stdlib.h>
33 #include <signal.h>
34 #include <limits.h>
35 #include <math.h>
36 
37 #include "config.h"
38 
39 #include <spa/utils/result.h>
40 #include <spa/utils/string.h>
41 #include <spa/utils/json.h>
42 #include <spa/utils/ringbuffer.h>
43 #include <spa/debug/pod.h>
44 #include <spa/pod/builder.h>
45 #include <spa/param/audio/format-utils.h>
46 #include <spa/param/audio/raw.h>
47 
48 #include <pipewire/impl.h>
49 #include <pipewire/i18n.h>
50 
51 /** \page page_module_example_sink PipeWire Module: Example Sink
52  */
53 
54 #define NAME "example-sink"
55 
56 PW_LOG_TOPIC_STATIC(mod_topic, "mod." NAME);
57 #define PW_LOG_TOPIC_DEFAULT mod_topic
58 
59 #define DEFAULT_FORMAT "S16"
60 #define DEFAULT_RATE 48000
61 #define DEFAULT_CHANNELS "2"
62 #define DEFAULT_POSITION "[ FL FR ]"
63 
64 #define MODULE_USAGE	"[ node.latency=<latency as fraction> ] "				\
65 			"[ node.name=<name of the nodes> ] "					\
66 			"[ node.description=<description of the nodes> ] "			\
67 			"[ audio.format=<format, default:"DEFAULT_FORMAT"> ] "			\
68 			"[ audio.rate=<sample rate, default: 48000> ] "				\
69 			"[ audio.channels=<number of channels, default:"DEFAULT_CHANNELS"> ] "	\
70 			"[ audio.position=<channel map, default:"DEFAULT_POSITION"> ] "		\
71 			"[ stream.props=<properties> ] "
72 
73 
74 static const struct spa_dict_item module_props[] = {
75 	{ PW_KEY_MODULE_AUTHOR, "Wim Taymans <wim.taymans@gmail.com>" },
76 	{ PW_KEY_MODULE_DESCRIPTION, "An example audio sink" },
77 	{ PW_KEY_MODULE_USAGE, MODULE_USAGE },
78 	{ PW_KEY_MODULE_VERSION, PACKAGE_VERSION },
79 };
80 
81 struct impl {
82 	struct pw_context *context;
83 
84 	struct pw_properties *props;
85 
86 	struct pw_impl_module *module;
87 	struct pw_work_queue *work;
88 
89 	struct spa_hook module_listener;
90 
91 	struct pw_core *core;
92 	struct spa_hook core_proxy_listener;
93 	struct spa_hook core_listener;
94 
95 	struct pw_properties *stream_props;
96 	struct pw_stream *stream;
97 	struct spa_hook stream_listener;
98 	struct spa_audio_info_raw info;
99 	uint32_t frame_size;
100 
101 	unsigned int do_disconnect:1;
102 	unsigned int unloading:1;
103 };
104 
do_unload_module(void * obj,void * data,int res,uint32_t id)105 static void do_unload_module(void *obj, void *data, int res, uint32_t id)
106 {
107 	struct impl *impl = data;
108 	pw_impl_module_destroy(impl->module);
109 }
110 
unload_module(struct impl * impl)111 static void unload_module(struct impl *impl)
112 {
113 	if (!impl->unloading) {
114 		impl->unloading = true;
115 		pw_work_queue_add(impl->work, impl, 0, do_unload_module, impl);
116 	}
117 }
118 
stream_destroy(void * d)119 static void stream_destroy(void *d)
120 {
121 	struct impl *impl = d;
122 	spa_hook_remove(&impl->stream_listener);
123 	impl->stream = NULL;
124 }
125 
stream_state_changed(void * d,enum pw_stream_state old,enum pw_stream_state state,const char * error)126 static void stream_state_changed(void *d, enum pw_stream_state old,
127 		enum pw_stream_state state, const char *error)
128 {
129 	struct impl *impl = d;
130 	switch (state) {
131 	case PW_STREAM_STATE_ERROR:
132 	case PW_STREAM_STATE_UNCONNECTED:
133 		unload_module(impl);
134 		break;
135 	case PW_STREAM_STATE_PAUSED:
136 	case PW_STREAM_STATE_STREAMING:
137 		break;
138 	default:
139 		break;
140 	}
141 }
142 
playback_stream_process(void * d)143 static void playback_stream_process(void *d)
144 {
145 	struct impl *impl = d;
146 	struct pw_buffer *buf;
147 	struct spa_data *bd;
148 	void *data;
149 	uint32_t size;
150 
151 	if ((buf = pw_stream_dequeue_buffer(impl->stream)) == NULL) {
152 		pw_log_debug("out of buffers: %m");
153 		return;
154 	}
155 
156 	bd = &buf->buffer->datas[0];
157 	data = SPA_PTROFF(bd->data, bd->chunk->offset, void);
158 	size = bd->chunk->size;
159 
160 	/* write buffer contents here */
161 	pw_log_info("got buffer of size %d and data %p", size, data);
162 
163 	pw_stream_queue_buffer(impl->stream, buf);
164 }
165 
166 static const struct pw_stream_events playback_stream_events = {
167 	PW_VERSION_STREAM_EVENTS,
168 	.destroy = stream_destroy,
169 	.state_changed = stream_state_changed,
170 	.process = playback_stream_process
171 };
172 
create_stream(struct impl * impl)173 static int create_stream(struct impl *impl)
174 {
175 	int res;
176 	uint32_t n_params;
177 	const struct spa_pod *params[1];
178 	uint8_t buffer[1024];
179 	struct spa_pod_builder b;
180 
181 	impl->stream = pw_stream_new(impl->core, "example sink", impl->stream_props);
182 	impl->stream_props = NULL;
183 
184 	if (impl->stream == NULL)
185 		return -errno;
186 
187 	pw_stream_add_listener(impl->stream,
188 			&impl->stream_listener,
189 			&playback_stream_events, impl);
190 
191 	n_params = 0;
192 	spa_pod_builder_init(&b, buffer, sizeof(buffer));
193 	params[n_params++] = spa_format_audio_raw_build(&b,
194 			SPA_PARAM_EnumFormat, &impl->info);
195 
196 	if ((res = pw_stream_connect(impl->stream,
197 			PW_DIRECTION_INPUT,
198 			PW_ID_ANY,
199 			PW_STREAM_FLAG_AUTOCONNECT |
200 			PW_STREAM_FLAG_MAP_BUFFERS |
201 			PW_STREAM_FLAG_RT_PROCESS,
202 			params, n_params)) < 0)
203 		return res;
204 
205 	return 0;
206 }
207 
core_error(void * data,uint32_t id,int seq,int res,const char * message)208 static void core_error(void *data, uint32_t id, int seq, int res, const char *message)
209 {
210 	struct impl *impl = data;
211 
212 	pw_log_error("error id:%u seq:%d res:%d (%s): %s",
213 			id, seq, res, spa_strerror(res), message);
214 
215 	if (id == PW_ID_CORE && res == -EPIPE)
216 		unload_module(impl);
217 }
218 
219 static const struct pw_core_events core_events = {
220 	PW_VERSION_CORE_EVENTS,
221 	.error = core_error,
222 };
223 
core_destroy(void * d)224 static void core_destroy(void *d)
225 {
226 	struct impl *impl = d;
227 	spa_hook_remove(&impl->core_listener);
228 	impl->core = NULL;
229 	unload_module(impl);
230 }
231 
232 static const struct pw_proxy_events core_proxy_events = {
233 	.destroy = core_destroy,
234 };
235 
impl_destroy(struct impl * impl)236 static void impl_destroy(struct impl *impl)
237 {
238 	if (impl->stream)
239 		pw_stream_destroy(impl->stream);
240 	if (impl->core && impl->do_disconnect)
241 		pw_core_disconnect(impl->core);
242 
243 	pw_properties_free(impl->stream_props);
244 	pw_properties_free(impl->props);
245 
246 	if (impl->work)
247 		pw_work_queue_cancel(impl->work, impl, SPA_ID_INVALID);
248 	free(impl);
249 }
250 
module_destroy(void * data)251 static void module_destroy(void *data)
252 {
253 	struct impl *impl = data;
254 	impl->unloading = true;
255 	spa_hook_remove(&impl->module_listener);
256 	impl_destroy(impl);
257 }
258 
259 static const struct pw_impl_module_events module_events = {
260 	PW_VERSION_IMPL_MODULE_EVENTS,
261 	.destroy = module_destroy,
262 };
263 
format_from_name(const char * name,size_t len)264 static inline uint32_t format_from_name(const char *name, size_t len)
265 {
266 	int i;
267 	for (i = 0; spa_type_audio_format[i].name; i++) {
268 		if (strncmp(name, spa_debug_type_short_name(spa_type_audio_format[i].name), len) == 0)
269 			return spa_type_audio_format[i].type;
270 	}
271 	return SPA_AUDIO_FORMAT_UNKNOWN;
272 }
273 
channel_from_name(const char * name)274 static uint32_t channel_from_name(const char *name)
275 {
276 	int i;
277 	for (i = 0; spa_type_audio_channel[i].name; i++) {
278 		if (spa_streq(name, spa_debug_type_short_name(spa_type_audio_channel[i].name)))
279 			return spa_type_audio_channel[i].type;
280 	}
281 	return SPA_AUDIO_CHANNEL_UNKNOWN;
282 }
283 
parse_position(struct spa_audio_info_raw * info,const char * val,size_t len)284 static void parse_position(struct spa_audio_info_raw *info, const char *val, size_t len)
285 {
286 	struct spa_json it[2];
287 	char v[256];
288 
289 	spa_json_init(&it[0], val, len);
290         if (spa_json_enter_array(&it[0], &it[1]) <= 0)
291                 spa_json_init(&it[1], val, len);
292 
293 	info->channels = 0;
294 	while (spa_json_get_string(&it[1], v, sizeof(v)) > 0 &&
295 	    info->channels < SPA_AUDIO_MAX_CHANNELS) {
296 		info->position[info->channels++] = channel_from_name(v);
297 	}
298 }
299 
parse_audio_info(struct impl * impl)300 static int parse_audio_info(struct impl *impl)
301 {
302 	struct pw_properties *props = impl->stream_props;
303 	struct spa_audio_info_raw *info = &impl->info;
304 	const char *str;
305 
306 	spa_zero(*info);
307 
308 	if ((str = pw_properties_get(props, PW_KEY_AUDIO_FORMAT)) == NULL)
309 		str = DEFAULT_FORMAT;
310 	info->format = format_from_name(str, strlen(str));
311 	switch (info->format) {
312 	case SPA_AUDIO_FORMAT_S8:
313 	case SPA_AUDIO_FORMAT_U8:
314 		impl->frame_size = 1;
315 		break;
316 	case SPA_AUDIO_FORMAT_S16:
317 		impl->frame_size = 2;
318 		break;
319 	case SPA_AUDIO_FORMAT_S24:
320 		impl->frame_size = 3;
321 		break;
322 	case SPA_AUDIO_FORMAT_S24_32:
323 	case SPA_AUDIO_FORMAT_S32:
324 	case SPA_AUDIO_FORMAT_F32:
325 		impl->frame_size = 4;
326 		break;
327 	case SPA_AUDIO_FORMAT_F64:
328 		impl->frame_size = 8;
329 		break;
330 	default:
331 		pw_log_error("unsupported format '%s'", str);
332 		return -EINVAL;
333 	}
334 	info->rate = pw_properties_get_uint32(props, PW_KEY_AUDIO_RATE, DEFAULT_RATE);
335 	if (info->rate == 0) {
336 		pw_log_error("invalid rate '%s'", str);
337 		return -EINVAL;
338 	}
339 	if ((str = pw_properties_get(props, PW_KEY_AUDIO_CHANNELS)) == NULL)
340 		str = DEFAULT_CHANNELS;
341 	info->channels = atoi(str);
342 	if ((str = pw_properties_get(props, SPA_KEY_AUDIO_POSITION)) == NULL)
343 		str = DEFAULT_POSITION;
344 	parse_position(info, str, strlen(str));
345 	if (info->channels == 0) {
346 		pw_log_error("invalid channels '%s'", str);
347 		return -EINVAL;
348 	}
349 	impl->frame_size *= info->channels;
350 
351 	return 0;
352 }
353 
copy_props(struct impl * impl,struct pw_properties * props,const char * key)354 static void copy_props(struct impl *impl, struct pw_properties *props, const char *key)
355 {
356 	const char *str;
357 	if ((str = pw_properties_get(props, key)) != NULL) {
358 		if (pw_properties_get(impl->stream_props, key) == NULL)
359 			pw_properties_set(impl->stream_props, key, str);
360 	}
361 }
362 
363 SPA_EXPORT
pipewire__module_init(struct pw_impl_module * module,const char * args)364 int pipewire__module_init(struct pw_impl_module *module, const char *args)
365 {
366 	struct pw_context *context = pw_impl_module_get_context(module);
367 	struct pw_properties *props = NULL;
368 	uint32_t id = pw_global_get_id(pw_impl_module_get_global(module));
369 	struct impl *impl;
370 	const char *str;
371 	int res;
372 
373 	PW_LOG_TOPIC_INIT(mod_topic);
374 
375 	impl = calloc(1, sizeof(struct impl));
376 	if (impl == NULL)
377 		return -errno;
378 
379 	pw_log_debug("module %p: new %s", impl, args);
380 
381 	if (args == NULL)
382 		args = "";
383 
384 	props = pw_properties_new_string(args);
385 	if (props == NULL) {
386 		res = -errno;
387 		pw_log_error( "can't create properties: %m");
388 		goto error;
389 	}
390 	impl->props = props;
391 
392 	impl->stream_props = pw_properties_new(NULL, NULL);
393 	if (impl->stream_props == NULL) {
394 		res = -errno;
395 		pw_log_error( "can't create properties: %m");
396 		goto error;
397 	}
398 
399 	impl->module = module;
400 	impl->context = context;
401 	impl->work = pw_context_get_work_queue(context);
402 	if (impl->work == NULL) {
403 		res = -errno;
404 		pw_log_error( "can't get work queue: %m");
405 		goto error;
406 	}
407 
408 	if (pw_properties_get(props, PW_KEY_NODE_GROUP) == NULL)
409 		pw_properties_set(props, PW_KEY_NODE_GROUP, "pipewire.dummy");
410 	if (pw_properties_get(props, PW_KEY_NODE_VIRTUAL) == NULL)
411 		pw_properties_set(props, PW_KEY_NODE_VIRTUAL, "true");
412 
413 	if (pw_properties_get(props, PW_KEY_MEDIA_CLASS) == NULL)
414 		pw_properties_set(props, PW_KEY_MEDIA_CLASS, "Audio/Sink");
415 
416 	if (pw_properties_get(props, PW_KEY_NODE_NAME) == NULL)
417 		pw_properties_setf(props, PW_KEY_NODE_NAME, "example-sink-%u", id);
418 	if (pw_properties_get(props, PW_KEY_NODE_DESCRIPTION) == NULL)
419 		pw_properties_set(props, PW_KEY_NODE_DESCRIPTION,
420 				pw_properties_get(props, PW_KEY_NODE_NAME));
421 
422 	if ((str = pw_properties_get(props, "stream.props")) != NULL)
423 		pw_properties_update_string(impl->stream_props, str, strlen(str));
424 
425 	copy_props(impl, props, PW_KEY_AUDIO_RATE);
426 	copy_props(impl, props, PW_KEY_AUDIO_CHANNELS);
427 	copy_props(impl, props, SPA_KEY_AUDIO_POSITION);
428 	copy_props(impl, props, PW_KEY_NODE_NAME);
429 	copy_props(impl, props, PW_KEY_NODE_DESCRIPTION);
430 	copy_props(impl, props, PW_KEY_NODE_GROUP);
431 	copy_props(impl, props, PW_KEY_NODE_LATENCY);
432 	copy_props(impl, props, PW_KEY_NODE_VIRTUAL);
433 	copy_props(impl, props, PW_KEY_MEDIA_CLASS);
434 
435 	if ((res = parse_audio_info(impl)) < 0) {
436 		pw_log_error( "can't parse audio format");
437 		goto error;
438 	}
439 
440 	impl->core = pw_context_get_object(impl->context, PW_TYPE_INTERFACE_Core);
441 	if (impl->core == NULL) {
442 		str = pw_properties_get(props, PW_KEY_REMOTE_NAME);
443 		impl->core = pw_context_connect(impl->context,
444 				pw_properties_new(
445 					PW_KEY_REMOTE_NAME, str,
446 					NULL),
447 				0);
448 		impl->do_disconnect = true;
449 	}
450 	if (impl->core == NULL) {
451 		res = -errno;
452 		pw_log_error("can't connect: %m");
453 		goto error;
454 	}
455 
456 	pw_proxy_add_listener((struct pw_proxy*)impl->core,
457 			&impl->core_proxy_listener,
458 			&core_proxy_events, impl);
459 	pw_core_add_listener(impl->core,
460 			&impl->core_listener,
461 			&core_events, impl);
462 
463 	if ((res = create_stream(impl)) < 0)
464 		goto error;
465 
466 	pw_impl_module_add_listener(module, &impl->module_listener, &module_events, impl);
467 
468 	pw_impl_module_update_properties(module, &SPA_DICT_INIT_ARRAY(module_props));
469 
470 	return 0;
471 
472 error:
473 	impl_destroy(impl);
474 	return res;
475 }
476