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