summaryrefslogtreecommitdiffstats
path: root/spa/plugins/libcamera/libcamera-manager.cpp
blob: afba4032a8e6d9288e6e76c0292a9b9a1d9d2a18 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/* Spa libcamera manager
 *
 * Copyright © 2021 Wim Taymans
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

#include <stddef.h>
#include <stdio.h>
#include <unistd.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <utility>
#include <mutex>
#include <optional>
#include <queue>

#include <libcamera/camera.h>
#include <libcamera/camera_manager.h>

#include <linux/videodev2.h>

using namespace libcamera;

#include <spa/support/log.h>
#include <spa/utils/type.h>
#include <spa/utils/keys.h>
#include <spa/utils/names.h>
#include <spa/utils/result.h>
#include <spa/utils/string.h>
#include <spa/support/loop.h>
#include <spa/support/plugin.h>
#include <spa/monitor/device.h>
#include <spa/monitor/utils.h>

#include "libcamera.h"
#include "libcamera-manager.hpp"

#define MAX_DEVICES	64

namespace {

struct device {
	uint32_t id;
	std::shared_ptr<Camera> camera;
};

struct impl {
	struct spa_handle handle;
	struct spa_device device = {};

	struct spa_log *log;
	struct spa_loop_utils *loop_utils;

	struct spa_hook_list hooks;

	static constexpr uint64_t info_all = SPA_DEVICE_CHANGE_MASK_FLAGS | SPA_DEVICE_CHANGE_MASK_PROPS;
	struct spa_device_info info = SPA_DEVICE_INFO_INIT();

	std::shared_ptr<CameraManager> manager;
	void addCamera(std::shared_ptr<libcamera::Camera> camera);
	void removeCamera(std::shared_ptr<libcamera::Camera> camera);

	struct device devices[MAX_DEVICES];
	uint32_t n_devices = 0;

	struct hotplug_event {
		enum class type { add, remove } type;
		std::shared_ptr<Camera> camera;
	};

	std::mutex hotplug_events_lock;
	std::queue<hotplug_event> hotplug_events;
	struct spa_source *hotplug_event_source;

	impl(spa_log *log, spa_loop_utils *loop_utils, spa_source *hotplug_event_source);

	~impl()
	{
		spa_loop_utils_destroy_source(loop_utils, hotplug_event_source);
	}
};

}

static std::weak_ptr<CameraManager> global_manager;

std::shared_ptr<CameraManager> libcamera_manager_acquire(int& res)
{
	if (auto manager = global_manager.lock())
		return manager;

	auto manager = std::make_shared<CameraManager>();
	if ((res = manager->start()) < 0)
		return {};

	global_manager = manager;

	return manager;
}
static uint32_t get_free_id(struct impl *impl)
{
	for (std::size_t i = 0; i < MAX_DEVICES; i++)
		if (impl->devices[i].camera == nullptr)
			return i;
	return 0;
}

static struct device *add_device(struct impl *impl, std::shared_ptr<Camera> camera)
{
	struct device *device;
	uint32_t id;

	if (impl->n_devices >= MAX_DEVICES)
		return NULL;
	id = get_free_id(impl);;
	device = &impl->devices[id];
	device->id = get_free_id(impl);;
	device->camera = std::move(camera);
	impl->n_devices++;
	return device;
}

static struct device *find_device(struct impl *impl, const Camera *camera)
{
	uint32_t i;
	for (i = 0; i < impl->n_devices; i++) {
		if (impl->devices[i].camera.get() == camera)
			return &impl->devices[i];
	}
	return NULL;
}

static void remove_device(struct impl *impl, struct device *device)
{
	uint32_t old = --impl->n_devices;
	device->camera.reset();
	*device = std::move(impl->devices[old]);
	impl->devices[old].camera = nullptr;
}

static void clear_devices(struct impl *impl)
{
	while (impl->n_devices > 0)
		impl->devices[--impl->n_devices].camera.reset();
}

static int emit_object_info(struct impl *impl, struct device *device)
{
	struct spa_device_object_info info;
	uint32_t id = device->id;
	struct spa_dict_item items[20];
	struct spa_dict dict;
	uint32_t n_items = 0;
	char path[256];

	info = SPA_DEVICE_OBJECT_INFO_INIT();

	info.type = SPA_TYPE_INTERFACE_Device;
	info.factory_name = SPA_NAME_API_LIBCAMERA_DEVICE;
	info.change_mask = SPA_DEVICE_OBJECT_CHANGE_MASK_FLAGS |
		SPA_DEVICE_OBJECT_CHANGE_MASK_PROPS;
	info.flags = 0;

#define ADD_ITEM(key, value) items[n_items++] = SPA_DICT_ITEM_INIT(key, value)
	ADD_ITEM(SPA_KEY_DEVICE_ENUM_API,"libcamera.manager");
	ADD_ITEM(SPA_KEY_DEVICE_API, "libcamera");
	ADD_ITEM(SPA_KEY_MEDIA_CLASS, "Video/Device");
	snprintf(path, sizeof(path), "%s", device->camera->id().c_str());
	ADD_ITEM(SPA_KEY_API_LIBCAMERA_PATH, path);
#undef ADD_ITEM

	dict = SPA_DICT_INIT(items, n_items);
	info.props = &dict;
	spa_device_emit_object_info(&impl->hooks, id, &info);

	return 1;
}

static void try_add_camera(struct impl *impl, std::shared_ptr<Camera> camera)
{
	struct device *device;

	if ((device = find_device(impl, camera.get())) != NULL)
		return;

	if ((device = add_device(impl, std::move(camera))) == NULL)
		return;

	spa_log_info(impl->log, "camera added: id:%d %s", device->id,
			device->camera->id().c_str());
	emit_object_info(impl, device);
}

static void try_remove_camera(struct impl *impl, const Camera *camera)
{
	struct device *device;

	if ((device = find_device(impl, camera)) == NULL)
		return;

	spa_log_info(impl->log, "camera removed: id:%d %s", device->id,
			device->camera->id().c_str());
	spa_device_emit_object_info(&impl->hooks, device->id, NULL);
	remove_device(impl, device);
}

static void consume_hotplug_event(struct impl *impl, impl::hotplug_event& event)
{
	auto& [ type, camera ] = event;

	switch (type) {
	case impl::hotplug_event::type::add:
		spa_log_info(impl->log, "camera appeared: %s", camera->id().c_str());
		try_add_camera(impl, std::move(camera));
		break;
	case impl::hotplug_event::type::remove:
		spa_log_info(impl->log, "camera disappeared: %s", camera->id().c_str());
		try_remove_camera(impl, camera.get());
		break;
	}
}

static void on_hotplug_event(void *data, std::uint64_t)
{
	auto impl = static_cast<struct impl *>(data);

	for (;;) {
		std::optional<impl::hotplug_event> event;

		{
			std::unique_lock guard(impl->hotplug_events_lock);

			if (!impl->hotplug_events.empty()) {
				event = std::move(impl->hotplug_events.front());
				impl->hotplug_events.pop();
			}
		}

		if (!event)
			break;

		consume_hotplug_event(impl, *event);
	}
}

void impl::addCamera(std::shared_ptr<Camera> camera)
{
	{
		std::unique_lock guard(hotplug_events_lock);
		hotplug_events.push({ hotplug_event::type::add, std::move(camera) });
	}

	spa_loop_utils_signal_event(loop_utils, hotplug_event_source);
}

void impl::removeCamera(std::shared_ptr<Camera> camera)
{
	{
		std::unique_lock guard(hotplug_events_lock);
		hotplug_events.push({ hotplug_event::type::remove, std::move(camera) });
	}

	spa_loop_utils_signal_event(loop_utils, hotplug_event_source);
}

static void start_monitor(struct impl *impl)
{
	impl->manager->cameraAdded.connect(impl, &impl::addCamera);
	impl->manager->cameraRemoved.connect(impl, &impl::removeCamera);
}

static int stop_monitor(struct impl *impl)
{
	if (impl->manager) {
		impl->manager->cameraAdded.disconnect(impl, &impl::addCamera);
		impl->manager->cameraRemoved.disconnect(impl, &impl::removeCamera);
	}
	clear_devices (impl);
	return 0;
}

static void collect_existing_devices(struct impl *impl)
{
	auto cameras = impl->manager->cameras();

	for (std::shared_ptr<Camera>& camera : cameras)
		try_add_camera(impl, std::move(camera));
}

static const struct spa_dict_item device_info_items[] = {
	{ SPA_KEY_DEVICE_API, "libcamera" },
	{ SPA_KEY_DEVICE_NICK, "libcamera-manager" },
};

static void emit_device_info(struct impl *impl, bool full)
{
	uint64_t old = full ? impl->info.change_mask : 0;
	if (full)
		impl->info.change_mask = impl->info_all;
	if (impl->info.change_mask) {
		struct spa_dict dict;
		dict = SPA_DICT_INIT_ARRAY(device_info_items);
		impl->info.props = &dict;
		spa_device_emit_info(&impl->hooks, &impl->info);
		impl->info.change_mask = old;
	}
}

static void impl_hook_removed(struct spa_hook *hook)
{
	struct impl *impl = (struct impl*)hook->priv;
	if (spa_hook_list_is_empty(&impl->hooks)) {
		stop_monitor(impl);
		impl->manager.reset();
	}
}

static int
impl_device_add_listener(void *object, struct spa_hook *listener,
		const struct spa_device_events *events, void *data)
{
	int res;
	struct impl *impl = (struct impl*) object;
	struct spa_hook_list save;
	bool had_manager = !!impl->manager;

	spa_return_val_if_fail(impl != NULL, -EINVAL);
	spa_return_val_if_fail(events != NULL, -EINVAL);

	if (!impl->manager && !(impl->manager = libcamera_manager_acquire(res)))
		return res;

	spa_hook_list_isolate(&impl->hooks, &save, listener, events, data);

	emit_device_info(impl, true);

	if (had_manager) {
		for (std::size_t i = 0; i < impl->n_devices; i++)
			emit_object_info(impl, &impl->devices[i]);
	}
	else {
		collect_existing_devices(impl);
		start_monitor(impl);
	}

	spa_hook_list_join(&impl->hooks, &save);

	listener->removed = impl_hook_removed;
	listener->priv = impl;

	return 0;
}

static const struct spa_device_methods impl_device = {
	SPA_VERSION_DEVICE_METHODS,
	.add_listener = impl_device_add_listener,
};

static int impl_get_interface(struct spa_handle *handle, const char *type, void **interface)
{
	struct impl *impl;

	spa_return_val_if_fail(handle != NULL, -EINVAL);
	spa_return_val_if_fail(interface != NULL, -EINVAL);

	impl = (struct impl *) handle;

	if (spa_streq(type, SPA_TYPE_INTERFACE_Device))
		*interface = &impl->device;
	else
		return -ENOENT;

	return 0;
}

static int impl_clear(struct spa_handle *handle)
{
	auto impl = reinterpret_cast<struct impl *>(handle);

	stop_monitor(impl);
	std::destroy_at(impl);

	return 0;
}

impl::impl(spa_log *log, spa_loop_utils *loop_utils, spa_source *hotplug_event_source)
	: handle({ SPA_VERSION_HANDLE, impl_get_interface, impl_clear }),
	  log(log),
	  loop_utils(loop_utils),
	  hotplug_event_source(hotplug_event_source)
{
	libcamera_log_topic_init(log);

	spa_hook_list_init(&hooks);

	device.iface = SPA_INTERFACE_INIT(
			SPA_TYPE_INTERFACE_Device,
			SPA_VERSION_DEVICE,
			&impl_device, this);
}

static size_t
impl_get_size(const struct spa_handle_factory *factory,
	      const struct spa_dict *params)
{
	return sizeof(struct impl);
}

static int
impl_init(const struct spa_handle_factory *factory,
	  struct spa_handle *handle,
	  const struct spa_dict *info,
	  const struct spa_support *support,
	  uint32_t n_support)
{
	spa_return_val_if_fail(factory != NULL, -EINVAL);
	spa_return_val_if_fail(handle != NULL, -EINVAL);

	auto log = static_cast<spa_log *>(spa_support_find(support, n_support, SPA_TYPE_INTERFACE_Log));

	auto loop_utils = static_cast<spa_loop_utils *>(spa_support_find(support, n_support, SPA_TYPE_INTERFACE_LoopUtils));
	if (!loop_utils) {
		spa_log_error(log, "a " SPA_TYPE_INTERFACE_LoopUtils " is needed");
		return -EINVAL;
	}

	auto hotplug_event_source = spa_loop_utils_add_event(loop_utils, on_hotplug_event, handle);
	if (!hotplug_event_source) {
		int res = -errno;
		spa_log_error(log, "failed to create hotplug event: %m");
		return res;
	}

	new (handle) impl(log, loop_utils, hotplug_event_source);

	return 0;
}

static const struct spa_interface_info impl_interfaces[] = {
	{SPA_TYPE_INTERFACE_Device,},
};

static int
impl_enum_interface_info(const struct spa_handle_factory *factory,
			 const struct spa_interface_info **info,
			 uint32_t *index)
{
	spa_return_val_if_fail(factory != NULL, -EINVAL);
	spa_return_val_if_fail(info != NULL, -EINVAL);
	spa_return_val_if_fail(index != NULL, -EINVAL);

	if (*index >= SPA_N_ELEMENTS(impl_interfaces))
		return 0;

	*info = &impl_interfaces[(*index)++];
	return 1;
}

extern "C" {
const struct spa_handle_factory spa_libcamera_manager_factory = {
	SPA_VERSION_HANDLE_FACTORY,
	SPA_NAME_API_LIBCAMERA_ENUM_MANAGER,
	NULL,
	impl_get_size,
	impl_init,
	impl_enum_interface_info,
};
}