1 /* PipeWire
2  *
3  * Copyright © 2018 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 /*
26  [title]
27  Allocating buffer memory and sending fds to the server.
28  [title]
29  */
30 
31 #include "config.h"
32 
33 #include <stdio.h>
34 #include <errno.h>
35 #include <signal.h>
36 #include <math.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <sys/mman.h>
40 
41 #include <spa/param/video/format-utils.h>
42 
43 #include <pipewire/pipewire.h>
44 
45 #define BPP		3
46 #define CURSOR_WIDTH	64
47 #define CURSOR_HEIGHT	64
48 #define CURSOR_BPP	4
49 
50 #define MAX_BUFFERS	64
51 
52 #define M_PI_M2 ( M_PI + M_PI )
53 
54 struct data {
55 	struct pw_thread_loop *loop;
56 	struct spa_source *timer;
57 
58 	struct pw_stream *stream;
59 	struct spa_hook stream_listener;
60 
61 	struct spa_video_info_raw format;
62 	int32_t stride;
63 
64 	int counter;
65 	uint32_t seq;
66 
67 	double crop;
68 	double accumulator;
69 };
70 
draw_elipse(uint32_t * dst,int width,int height,uint32_t color)71 static void draw_elipse(uint32_t *dst, int width, int height, uint32_t color)
72 {
73 	int i, j, r1, r2, r12, r22, r122;
74 
75 	r1 = width/2;
76 	r12 = r1 * r1;
77 	r2 = height/2;
78 	r22 = r2 * r2;
79 	r122 = r12 * r22;
80 
81 	for (i = -r2; i < r2; i++) {
82 		for (j = -r1; j < r1; j++) {
83 			dst[(i + r2)*width+(j+r1)] =
84 				(i * i * r12 + j * j * r22 <= r122) ? color : 0x00000000;
85 		}
86 	}
87 }
88 
89 /* called when we should push a new buffer in the queue */
on_process(void * userdata)90 static void on_process(void *userdata)
91 {
92 	struct data *data = userdata;
93 	struct pw_buffer *b;
94 	struct spa_buffer *buf;
95 	uint32_t i, j;
96 	uint8_t *p;
97 	struct spa_meta *m;
98 	struct spa_meta_header *h;
99 	struct spa_meta_region *mc;
100 	struct spa_meta_cursor *mcs;
101 
102 	if ((b = pw_stream_dequeue_buffer(data->stream)) == NULL) {
103 		pw_log_warn("out of buffers: %m");
104 		return;
105 	}
106 
107 	buf = b->buffer;
108 	if ((p = buf->datas[0].data) == NULL)
109 		return;
110 
111 	if ((h = spa_buffer_find_meta_data(buf, SPA_META_Header, sizeof(*h)))) {
112 #if 0
113 		struct timespec now;
114 		clock_gettime(CLOCK_MONOTONIC, &now);
115 		h->pts = SPA_TIMESPEC_TO_NSEC(&now);
116 #else
117 		h->pts = -1;
118 #endif
119 		h->flags = 0;
120 		h->seq = data->seq++;
121 		h->dts_offset = 0;
122 	}
123 	if ((m = spa_buffer_find_meta(buf, SPA_META_VideoDamage))) {
124 		struct spa_meta_region *r = spa_meta_first(m);
125 
126 		if (spa_meta_check(r, m)) {
127 			r->region.position = SPA_POINT(0,0);
128 			r->region.size = data->format.size;
129 			r++;
130 		}
131 		if (spa_meta_check(r, m))
132 			r->region = SPA_REGION(0,0,0,0);
133 	}
134 	if ((mc = spa_buffer_find_meta_data(buf, SPA_META_VideoCrop, sizeof(*mc)))) {
135 		data->crop = (sin(data->accumulator) + 1.0) * 32.0;
136 		mc->region.position.x = data->crop;
137 		mc->region.position.y = data->crop;
138 		mc->region.size.width = data->format.size.width - data->crop*2;
139 		mc->region.size.height = data->format.size.height - data->crop*2;
140 	}
141 	if ((mcs = spa_buffer_find_meta_data(buf, SPA_META_Cursor, sizeof(*mcs)))) {
142 		struct spa_meta_bitmap *mb;
143 		uint32_t *bitmap, color;
144 
145 		mcs->id = 1;
146 		mcs->position.x = (sin(data->accumulator) + 1.0) * 160.0 + 80;
147 		mcs->position.y = (cos(data->accumulator) + 1.0) * 100.0 + 50;
148 		mcs->hotspot.x = 0;
149 		mcs->hotspot.y = 0;
150 		mcs->bitmap_offset = sizeof(struct spa_meta_cursor);
151 
152 		mb = SPA_PTROFF(mcs, mcs->bitmap_offset, struct spa_meta_bitmap);
153 		mb->format = SPA_VIDEO_FORMAT_ARGB;
154 		mb->size.width = CURSOR_WIDTH;
155 		mb->size.height = CURSOR_HEIGHT;
156 		mb->stride = CURSOR_WIDTH * CURSOR_BPP;
157 		mb->offset = sizeof(struct spa_meta_bitmap);
158 
159 		bitmap = SPA_PTROFF(mb, mb->offset, uint32_t);
160 		color = (cos(data->accumulator) + 1.0) * (1 << 23);
161 		color |= 0xff000000;
162 
163 		draw_elipse(bitmap, mb->size.width, mb->size.height, color);
164 	}
165 
166 	for (i = 0; i < data->format.size.height; i++) {
167 		for (j = 0; j < data->format.size.width * BPP; j++) {
168 			p[j] = data->counter + j * i;
169 		}
170 		p += data->stride;
171 		data->counter += 13;
172 	}
173 
174 	data->accumulator += M_PI_M2 / 50.0;
175 	if (data->accumulator >= M_PI_M2)
176 		data->accumulator -= M_PI_M2;
177 
178 	buf->datas[0].chunk->offset = 0;
179 	buf->datas[0].chunk->size = data->format.size.height * data->stride;
180 	buf->datas[0].chunk->stride = data->stride;
181 
182 	pw_stream_queue_buffer(data->stream, b);
183 }
184 
185 /* trigger the graph when we are a driver */
on_timeout(void * userdata,uint64_t expirations)186 static void on_timeout(void *userdata, uint64_t expirations)
187 {
188 	struct data *data = userdata;
189 	pw_log_trace("timeout");
190 	pw_stream_trigger_process(data->stream);
191 }
192 
193 /* when the stream is STREAMING, start the timer at 40ms intervals
194  * to produce and push a frame. In other states we PAUSE the timer. */
on_stream_state_changed(void * _data,enum pw_stream_state old,enum pw_stream_state state,const char * error)195 static void on_stream_state_changed(void *_data, enum pw_stream_state old, enum pw_stream_state state,
196 				    const char *error)
197 {
198 	struct data *data = _data;
199 
200 	printf("stream state: \"%s\"\n", pw_stream_state_as_string(state));
201 
202 	switch (state) {
203 	case PW_STREAM_STATE_PAUSED:
204 		printf("node id: %d\n", pw_stream_get_node_id(data->stream));
205 		pw_loop_update_timer(pw_thread_loop_get_loop(data->loop),
206 				data->timer, NULL, NULL, false);
207 		break;
208 	case PW_STREAM_STATE_STREAMING:
209 	{
210 		struct timespec timeout, interval;
211 
212 		timeout.tv_sec = 0;
213 		timeout.tv_nsec = 1;
214 		interval.tv_sec = 0;
215 		interval.tv_nsec = 40 * SPA_NSEC_PER_MSEC;
216 
217 		if (pw_stream_is_driving(data->stream))
218 			pw_loop_update_timer(pw_thread_loop_get_loop(data->loop),
219 					data->timer, &timeout, &interval, false);
220 		break;
221 	}
222 	default:
223 		break;
224 	}
225 }
226 
227 /* we set the PW_STREAM_FLAG_ALLOC_BUFFERS flag when connecting so we need
228  * to provide buffer memory.  */
on_stream_add_buffer(void * _data,struct pw_buffer * buffer)229 static void on_stream_add_buffer(void *_data, struct pw_buffer *buffer)
230 {
231 	struct data *data = _data;
232 	struct spa_buffer *buf = buffer->buffer;
233 	struct spa_data *d;
234 #ifdef HAVE_MEMFD_CREATE
235 	unsigned int seals;
236 #endif
237 
238 	pw_log_info("add buffer %p", buffer);
239 	d = buf->datas;
240 
241 	if ((d[0].type & (1<<SPA_DATA_MemFd)) == 0) {
242 		pw_log_error("unsupported data type %08x", d[0].type);
243 		return;
244 	}
245 
246 	/* create the memfd on the buffer, set the type and flags */
247 	d[0].type = SPA_DATA_MemFd;
248 	d[0].flags = SPA_DATA_FLAG_READWRITE;
249 #ifdef HAVE_MEMFD_CREATE
250 	d[0].fd = memfd_create("video-src-memfd", MFD_CLOEXEC | MFD_ALLOW_SEALING);
251 #else
252 	d[0].fd = -1;
253 #endif
254 	if (d[0].fd == -1) {
255 		pw_log_error("can't create memfd: %m");
256 		return;
257 	}
258 	d[0].mapoffset = 0;
259 	d[0].maxsize = data->stride * data->format.size.height;
260 
261 	/* truncate to the right size before we set seals */
262 	if (ftruncate(d[0].fd, d[0].maxsize) < 0) {
263 		pw_log_error("can't truncate to %d: %m", d[0].maxsize);
264 		return;
265 	}
266 #ifdef HAVE_MEMFD_CREATE
267 	/* not enforced yet but server might require SEAL_SHRINK later */
268 	seals = F_SEAL_GROW | F_SEAL_SHRINK | F_SEAL_SEAL;
269 	if (fcntl(d[0].fd, F_ADD_SEALS, seals) == -1) {
270 		pw_log_warn("Failed to add seals: %m");
271 	}
272 #endif
273 
274 	/* now mmap so we can write to it in the process function above */
275 	d[0].data = mmap(NULL, d[0].maxsize, PROT_READ|PROT_WRITE,
276 			MAP_SHARED, d[0].fd, d[0].mapoffset);
277 	if (d[0].data == MAP_FAILED) {
278 		pw_log_error("can't mmap memory: %m");
279 		return;
280 	}
281 }
282 
283 /* close the memfd we set on the buffers here */
on_stream_remove_buffer(void * _data,struct pw_buffer * buffer)284 static void on_stream_remove_buffer(void *_data, struct pw_buffer *buffer)
285 {
286 	struct spa_buffer *buf = buffer->buffer;
287 	struct spa_data *d;
288 
289 	d = buf->datas;
290 	pw_log_info("remove buffer %p", buffer);
291 
292 	munmap(d[0].data, d[0].maxsize);
293 	close(d[0].fd);
294 }
295 
296 /* Be notified when the stream param changes. We're only looking at the
297  * format param.
298  *
299  * We are now supposed to call pw_stream_update_params() with success or
300  * failure, depending on if we can support the format. Because we gave
301  * a list of supported formats, this should be ok.
302  *
303  * As part of pw_stream_update_params() we can provide parameters that
304  * will control the buffer memory allocation. This includes the metadata
305  * that we would like on our buffer, the size, alignment, etc.
306  */
307 static void
on_stream_param_changed(void * _data,uint32_t id,const struct spa_pod * param)308 on_stream_param_changed(void *_data, uint32_t id, const struct spa_pod *param)
309 {
310 	struct data *data = _data;
311 	struct pw_stream *stream = data->stream;
312 	uint8_t params_buffer[1024];
313 	struct spa_pod_builder b = SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer));
314 	const struct spa_pod *params[5];
315 
316 	if (param == NULL || id != SPA_PARAM_Format)
317 		return;
318 
319 	spa_format_video_raw_parse(param, &data->format);
320 
321 	data->stride = SPA_ROUND_UP_N(data->format.size.width * BPP, 4);
322 
323 	params[0] = spa_pod_builder_add_object(&b,
324 		SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers,
325 		SPA_PARAM_BUFFERS_buffers,  SPA_POD_CHOICE_RANGE_Int(8, 2, MAX_BUFFERS),
326 		SPA_PARAM_BUFFERS_blocks,   SPA_POD_Int(1),
327 		SPA_PARAM_BUFFERS_size,     SPA_POD_Int(data->stride * data->format.size.height),
328 		SPA_PARAM_BUFFERS_stride,   SPA_POD_Int(data->stride),
329 		SPA_PARAM_BUFFERS_dataType, SPA_POD_CHOICE_FLAGS_Int(1<<SPA_DATA_MemFd));
330 
331 	params[1] = spa_pod_builder_add_object(&b,
332 		SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
333 		SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header),
334 		SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_header)));
335 
336 	params[2] = spa_pod_builder_add_object(&b,
337 		SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
338 		SPA_PARAM_META_type, SPA_POD_Id(SPA_META_VideoDamage),
339 		SPA_PARAM_META_size, SPA_POD_CHOICE_RANGE_Int(
340 					sizeof(struct spa_meta_region) * 16,
341 					sizeof(struct spa_meta_region) * 1,
342 					sizeof(struct spa_meta_region) * 16));
343 	params[3] = spa_pod_builder_add_object(&b,
344 		SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
345 		SPA_PARAM_META_type, SPA_POD_Id(SPA_META_VideoCrop),
346 		SPA_PARAM_META_size, SPA_POD_Int(sizeof(struct spa_meta_region)));
347 #define CURSOR_META_SIZE(w,h)	(sizeof(struct spa_meta_cursor) + \
348 				 sizeof(struct spa_meta_bitmap) + w * h * CURSOR_BPP)
349 	params[4] = spa_pod_builder_add_object(&b,
350 		SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta,
351 		SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Cursor),
352 		SPA_PARAM_META_size, SPA_POD_Int(
353 			CURSOR_META_SIZE(CURSOR_WIDTH,CURSOR_HEIGHT)));
354 
355 	pw_stream_update_params(stream, params, 5);
356 }
357 
358 static const struct pw_stream_events stream_events = {
359 	PW_VERSION_STREAM_EVENTS,
360 	.process = on_process,
361 	.state_changed = on_stream_state_changed,
362 	.param_changed = on_stream_param_changed,
363 	.add_buffer = on_stream_add_buffer,
364 	.remove_buffer = on_stream_remove_buffer,
365 };
366 
do_quit(void * userdata,int signal_number)367 static void do_quit(void *userdata, int signal_number)
368 {
369 	struct data *data = userdata;
370 	pw_thread_loop_signal(data->loop, false);
371 }
372 
main(int argc,char * argv[])373 int main(int argc, char *argv[])
374 {
375 	struct data data = { 0, };
376 	const struct spa_pod *params[1];
377 	uint8_t buffer[1024];
378 	struct spa_pod_builder b = SPA_POD_BUILDER_INIT(buffer, sizeof(buffer));
379 
380 	pw_init(&argc, &argv);
381 
382 	/* create a thread loop and start it */
383 	data.loop = pw_thread_loop_new("video-src-alloc", NULL);
384 
385 	/* take the lock around all PipeWire functions. In callbacks, the lock
386 	 * is already taken for you but it's ok to lock again because the lock is
387 	 * recursive */
388 	pw_thread_loop_lock(data.loop);
389 
390 	/* install some handlers to exit nicely */
391 	pw_loop_add_signal(pw_thread_loop_get_loop(data.loop), SIGINT, do_quit, &data);
392 	pw_loop_add_signal(pw_thread_loop_get_loop(data.loop), SIGTERM, do_quit, &data);
393 
394 	/* start after the signal handlers are set */
395 	pw_thread_loop_start(data.loop);
396 
397 	/* create a simple stream, the simple stream manages the core
398 	 * object for you if you don't want to deal with them.
399 	 *
400 	 * We're making a new video provider. We need to set the media-class
401 	 * property.
402 	 *
403 	 * Pass your events and a user_data pointer as the last arguments. This
404 	 * will inform you about the stream state. The most important event
405 	 * you need to listen to is the process event where you need to provide
406 	 * the data.
407 	 */
408 	data.stream = pw_stream_new_simple(
409 			pw_thread_loop_get_loop(data.loop),
410 			"video-src-alloc",
411 			pw_properties_new(
412 				PW_KEY_MEDIA_CLASS, "Video/Source",
413 				NULL),
414 			&stream_events,
415 			&data);
416 
417 	/* make a timer to schedule our frames */
418 	data.timer = pw_loop_add_timer(pw_thread_loop_get_loop(data.loop), on_timeout, &data);
419 
420 	/* build the extra parameter for the connection. Here we make an
421 	 * EnumFormat parameter which lists the possible formats we can provide.
422 	 * The server will select a format that matches and informs us about this
423 	 * in the stream param_changed event.
424 	 */
425 	params[0] = spa_pod_builder_add_object(&b,
426 		SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat,
427 		SPA_FORMAT_mediaType,       SPA_POD_Id(SPA_MEDIA_TYPE_video),
428 		SPA_FORMAT_mediaSubtype,    SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
429 		SPA_FORMAT_VIDEO_format,    SPA_POD_Id(SPA_VIDEO_FORMAT_RGB),
430 		SPA_FORMAT_VIDEO_size,      SPA_POD_CHOICE_RANGE_Rectangle(
431 						&SPA_RECTANGLE(320, 240),
432 						&SPA_RECTANGLE(1, 1),
433 						&SPA_RECTANGLE(4096, 4096)),
434 		SPA_FORMAT_VIDEO_framerate, SPA_POD_Fraction(&SPA_FRACTION(25, 1)));
435 
436 	/* now connect the stream, we need a direction (input/output),
437 	 * an optional target node to connect to, some flags and parameters.
438 	 *
439 	 * Here we pass PW_STREAM_FLAG_ALLOC_BUFFERS. We should in the
440 	 * add_buffer callback configure the buffer memory. This should be
441 	 * fd backed memory (memfd, dma-buf, ...) that can be shared with
442 	 * the server.  */
443 	pw_stream_connect(data.stream,
444 			  PW_DIRECTION_OUTPUT,
445 			  PW_ID_ANY,			/* link to any node */
446 			  PW_STREAM_FLAG_DRIVER |
447 			  PW_STREAM_FLAG_ALLOC_BUFFERS,
448 			  params, 1);
449 
450 	/* unlock, run the loop and wait, this will trigger the callbacks */
451 	pw_thread_loop_wait(data.loop);
452 
453 	/* unlock before stop */
454 	pw_thread_loop_unlock(data.loop);
455 	pw_thread_loop_stop(data.loop);
456 
457 	pw_stream_destroy(data.stream);
458 
459 	/* destroy after dependent objects are destroyed */
460 	pw_thread_loop_destroy(data.loop);
461 	pw_deinit();
462 
463 	return 0;
464 }
465