summaryrefslogtreecommitdiff
path: root/src/cam
diff options
context:
space:
mode:
Diffstat (limited to 'src/cam')
0 files changed, 0 insertions, 0 deletions
ac427059fa7666b8fd23c19'>src/libcamera/v4l2_device.cpp
blob: 4a2048cfc28670f65fabfd55899bf1f1be98948e (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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * Common base for V4L2 video devices and subdevices
 */

#include "libcamera/internal/v4l2_device.h"

#include <fcntl.h>
#include <iomanip>
#include <limits.h>
#include <map>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <vector>

#include <linux/v4l2-mediabus.h>

#include <libcamera/base/event_notifier.h>
#include <libcamera/base/log.h>
#include <libcamera/base/utils.h>

#include "libcamera/internal/formats.h"
#include "libcamera/internal/sysfs.h"

/**
 * \file v4l2_device.h
 * \brief Common base for V4L2 devices and subdevices
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(V4L2)

/**
 * \class V4L2Device
 * \brief Base class for V4L2VideoDevice and V4L2Subdevice
 *
 * The V4L2Device class groups together the functions and fields common to
 * both the V4L2VideoDevice and V4L2Subdevice classes, and provides a base
 * class with functions to open and close the device node associated with the
 * device and to perform IOCTL system calls on it.
 *
 * The V4L2Device class cannot be instantiated directly, as its constructor
 * is protected. Users should instead create instances of one the derived
 * classes to model either a V4L2 video device or a V4L2 subdevice.
 */

/**
 * \brief Construct a V4L2Device
 * \param[in] deviceNode The device node filesystem path
 *
 * Initialize the file descriptor to -1 and store the \a deviceNode to be used
 * at open() time, and the \a logTag to prefix log messages with.
 */
V4L2Device::V4L2Device(const std::string &deviceNode)
	: deviceNode_(deviceNode), fdEventNotifier_(nullptr),
	  frameStartEnabled_(false)
{
}

/**
 * \brief Destroy a V4L2Device
 */
V4L2Device::~V4L2Device()
{
}

/**
 * \brief Open a V4L2 device node
 * \param[in] flags Access mode flags
 *
 * Open the device node path with the provided access mode \a flags and
 * initialize the file descriptor, which was initially set to -1.
 *
 * \return 0 on success or a negative error code otherwise
 */
int V4L2Device::open(unsigned int flags)
{
	if (isOpen()) {
		LOG(V4L2, Error) << "Device already open";
		return -EBUSY;
	}

	UniqueFD fd(syscall(SYS_openat, AT_FDCWD, deviceNode_.c_str(),
			    flags | O_CLOEXEC));
	if (!fd.isValid()) {
		int ret = -errno;
		LOG(V4L2, Error) << "Failed to open V4L2 device '"
				 << deviceNode_ << "': "
				 << strerror(-ret);
		return ret;
	}

	setFd(std::move(fd));

	return 0;
}

/**
 * \brief Set the file descriptor of a V4L2 device
 * \param[in] fd The file descriptor handle
 *
 * This function allows a device to provide an already opened file descriptor
 * referring to the V4L2 device node, instead of opening it with open(). This
 * can be used for V4L2 M2M devices where a single video device node is used for
 * both the output and capture devices, or when receiving an open file
 * descriptor in a context that doesn't have permission to open the device node
 * itself.
 *
 * This function and the open() function are mutually exclusive, only one of the
 * two shall be used for a V4L2Device instance.
 *
 * \return 0 on success or a negative error code otherwise
 */
int V4L2Device::setFd(UniqueFD fd)
{
	if (isOpen())
		return -EBUSY;

	fd_ = std::move(fd);

	fdEventNotifier_ = new EventNotifier(fd_.get(), EventNotifier::Exception);
	fdEventNotifier_->activated.connect(this, &V4L2Device::eventAvailable);
	fdEventNotifier_->setEnabled(false);

	listControls();

	return 0;
}

/**
 * \brief Close the device node
 *
 * Reset the file descriptor to -1
 */
void V4L2Device::close()
{
	if (!isOpen())
		return;

	delete fdEventNotifier_;

	fd_.reset();
}

/**
 * \fn V4L2Device::isOpen()
 * \brief Check if the V4L2 device node is open
 * \return True if the V4L2 device node is open, false otherwise
 */

/**
 * \fn V4L2Device::controls()
 * \brief Retrieve the supported V4L2 controls and their information
 * \return A map of the V4L2 controls supported by the device
 */

/**
 * \brief Read controls from the device
 * \param[in] ids The list of controls to read, specified by their ID
 *
 * This function reads the value of all controls contained in \a ids, and
 * returns their values as a ControlList.
 *
 * If any control in \a ids is not supported by the device, is disabled (i.e.
 * has the V4L2_CTRL_FLAG_DISABLED flag set), or if any other error occurs
 * during validation of the requested controls, no control is read and this
 * function returns an empty control list.
 *
 * \return The control values in a ControlList on success, or an empty list on
 * error
 */
ControlList V4L2Device::getControls(const std::vector<uint32_t> &ids)
{
	if (ids.empty())
		return {};

	ControlList ctrls{ controls_ };

	for (uint32_t id : ids) {
		const auto iter = controls_.find(id);
		if (iter == controls_.end()) {
			LOG(V4L2, Error)
				<< "Control " << utils::hex(id) << " not found";
			return {};
		}

		ctrls.set(id, {});
	}

	std::vector<v4l2_ext_control> v4l2Ctrls(ids.size());
	memset(v4l2Ctrls.data(), 0, sizeof(v4l2_ext_control) * ctrls.size());

	unsigned int i = 0;
	for (auto &ctrl : ctrls) {
		unsigned int id = ctrl.first;
		const struct v4l2_query_ext_ctrl &info = controlInfo_[id];

		v4l2_ext_control &v4l2Ctrl = v4l2Ctrls[i++];
		v4l2Ctrl.id = id;

		if (info.flags & V4L2_CTRL_FLAG_HAS_PAYLOAD) {
			ControlType type;

			switch (info.type) {
			case V4L2_CTRL_TYPE_U8:
				type = ControlTypeByte;
				break;

			default:
				LOG(V4L2, Error)
					<< "Unsupported payload control type "
					<< info.type;
				return {};
			}

			ControlValue &value = ctrl.second;
			value.reserve(type, true, info.elems);
			Span<uint8_t> data = value.data();

			v4l2Ctrl.p_u8 = data.data();
			v4l2Ctrl.size = data.size();
		}
	}

	struct v4l2_ext_controls v4l2ExtCtrls = {};
	v4l2ExtCtrls.which = V4L2_CTRL_WHICH_CUR_VAL;
	v4l2ExtCtrls.controls = v4l2Ctrls.data();
	v4l2ExtCtrls.count = v4l2Ctrls.size();

	int ret = ioctl(VIDIOC_G_EXT_CTRLS, &v4l2ExtCtrls);
	if (ret) {
		unsigned int errorIdx = v4l2ExtCtrls.error_idx;

		/* Generic validation error. */
		if (errorIdx == 0 || errorIdx >= v4l2Ctrls.size()) {
			LOG(V4L2, Error) << "Unable to read controls: "
					 << strerror(-ret);
			return {};
		}

		/* A specific control failed. */
		const unsigned int id = v4l2Ctrls[errorIdx].id;
		LOG(V4L2, Error) << "Unable to read control " << utils::hex(id)
				 << ": " << strerror(-ret);

		v4l2Ctrls.resize(errorIdx);
	}

	updateControls(&ctrls, v4l2Ctrls);

	return ctrls;
}

/**
 * \brief Write controls to the device
 * \param[in] ctrls The list of controls to write
 *
 * This function writes the value of all controls contained in \a ctrls, and
 * stores the values actually applied to the device in the corresponding
 * \a ctrls entry.
 *
 * If any control in \a ctrls is not supported by the device, is disabled (i.e.
 * has the V4L2_CTRL_FLAG_DISABLED flag set), is read-only, if any other error
 * occurs during validation of the requested controls, no control is written and
 * this function returns -EINVAL.
 *
 * If an error occurs while writing the controls, the index of the first
 * control that couldn't be written is returned. All controls below that index
 * are written and their values are updated in \a ctrls, while all other
 * controls are not written and their values are not changed.
 *
 * \return 0 on success or an error code otherwise
 * \retval -EINVAL One of the control is not supported or not accessible
 * \retval i The index of the control that failed
 */
int V4L2Device::setControls(ControlList *ctrls)
{
	if (ctrls->empty())
		return 0;

	std::vector<v4l2_ext_control> v4l2Ctrls(ctrls->size());
	memset(v4l2Ctrls.data(), 0, sizeof(v4l2_ext_control) * ctrls->size());

	for (auto [ctrl, i] = std::pair(ctrls->begin(), 0u); i < ctrls->size(); ctrl++, i++) {
		const unsigned int id = ctrl->first;
		const auto iter = controls_.find(id);
		if (iter == controls_.end()) {
			LOG(V4L2, Error)
				<< "Control " << utils::hex(id) << " not found";
			return -EINVAL;
		}
		v4l2_ext_control &v4l2Ctrl = v4l2Ctrls[i];
		v4l2Ctrl.id = id;

		/* Set the v4l2_ext_control value for the write operation. */
		ControlValue &value = ctrl->second;
		switch (iter->first->type()) {
		case ControlTypeInteger32: {
			if (value.isArray()) {
				Span<uint8_t> data = value.data();
				v4l2Ctrl.p_u32 = reinterpret_cast<uint32_t *>(data.data());
				v4l2Ctrl.size = data.size();
			} else {
				v4l2Ctrl.value = value.get<int32_t>();
			}

			break;
		}

		case ControlTypeInteger64:
			v4l2Ctrl.value64 = value.get<int64_t>();
			break;

		case ControlTypeByte: {
			if (!value.isArray()) {
				LOG(V4L2, Error)
					<< "Control " << utils::hex(id)
					<< " requires an array value";
				return -EINVAL;
			}

			Span<uint8_t> data = value.data();
			v4l2Ctrl.p_u8 = data.data();
			v4l2Ctrl.size = data.size();

			break;
		}

		default:
			/* \todo To be changed to support strings. */
			v4l2Ctrl.value = value.get<int32_t>();
			break;
		}
	}

	struct v4l2_ext_controls v4l2ExtCtrls = {};
	v4l2ExtCtrls.which = V4L2_CTRL_WHICH_CUR_VAL;
	v4l2ExtCtrls.controls = v4l2Ctrls.data();
	v4l2ExtCtrls.count = v4l2Ctrls.size();

	int ret = ioctl(VIDIOC_S_EXT_CTRLS, &v4l2ExtCtrls);
	if (ret) {
		unsigned int errorIdx = v4l2ExtCtrls.error_idx;

		/* Generic validation error. */
		if (errorIdx == 0 || errorIdx >= v4l2Ctrls.size()) {
			LOG(V4L2, Error) << "Unable to set controls: "
					 << strerror(-ret);
			return -EINVAL;
		}

		/* A specific control failed. */
		const unsigned int id = v4l2Ctrls[errorIdx].id;
		LOG(V4L2, Error) << "Unable to set control " << utils::hex(id)
				 << ": " << strerror(-ret);

		v4l2Ctrls.resize(errorIdx);
		ret = errorIdx;
	}

	updateControls(ctrls, v4l2Ctrls);

	return ret;
}

/**
 * \brief Retrieve the v4l2_query_ext_ctrl information for the given control
 * \param[in] id The V4L2 control id
 * \return A pointer to the v4l2_query_ext_ctrl structure for the given
 * control, or a null pointer if not found
 */
const struct v4l2_query_ext_ctrl *V4L2Device::controlInfo(uint32_t id) const
{
	const auto it = controlInfo_.find(id);
	if (it == controlInfo_.end())
		return nullptr;

	return &it->second;
}

/**
 * \brief Retrieve the device path in sysfs
 *
 * This function returns the sysfs path to the physical device backing the V4L2
 * device. The path is guaranteed to be an absolute path, without any symbolic
 * link.
 *
 * It includes the sysfs mount point prefix
 *
 * \return The device path in sysfs
 */
std::string V4L2Device::devicePath() const
{
	std::string devicePath = sysfs::charDevPath(deviceNode_) + "/device";

	char *realPath = realpath(devicePath.c_str(), nullptr);
	if (!realPath) {
		LOG(V4L2, Fatal)
			<< "Can not resolve device path for " << devicePath;
		return {};
	}

	std::string path{ realPath };
	free(realPath);

	return path;
}

/**
 * \brief Enable or disable frame start event notification
 * \param[in] enable True to enable frame start events, false to disable them
 *
 * This function enables or disables generation of frame start events. Once
 * enabled, the events are signalled through the frameStart signal.
 *
 * \return 0 on success, a negative error code otherwise
 */
int V4L2Device::setFrameStartEnabled(bool enable)
{
	if (frameStartEnabled_ == enable)
		return 0;

	struct v4l2_event_subscription event{};
	event.type = V4L2_EVENT_FRAME_SYNC;

	unsigned long request = enable ? VIDIOC_SUBSCRIBE_EVENT
			      : VIDIOC_UNSUBSCRIBE_EVENT;
	int ret = ioctl(request, &event);
	if (enable && ret)
		return ret;

	fdEventNotifier_->setEnabled(enable);
	frameStartEnabled_ = enable;

	return ret;
}

/**
 * \var V4L2Device::frameStart
 * \brief A Signal emitted when capture of a frame has started
 */

/**
 * \brief Perform an IOCTL system call on the device node
 * \param[in] request The IOCTL request code
 * \param[in] argp A pointer to the IOCTL argument
 * \return 0 on success or a negative error code otherwise
 */
int V4L2Device::ioctl(unsigned long request, void *argp)
{
	/*
	 * Printing out an error message is usually better performed
	 * in the caller, which can provide more context.
	 */
	if (::ioctl(fd_.get(), request, argp) < 0)
		return -errno;

	return 0;
}

/**
 * \fn V4L2Device::deviceNode()
 * \brief Retrieve the device node path
 * \return The device node path
 */

/**
 * \fn V4L2Device::fd()
 * \brief Retrieve the V4L2 device file descriptor
 * \return The V4L2 device file descriptor, -1 if the device node is not open
 */

/**
 * \brief Retrieve the libcamera control type associated with the V4L2 control
 * \param[in] ctrlType The V4L2 control type
 * \return The ControlType associated to \a ctrlType
 */
ControlType V4L2Device::v4l2CtrlType(uint32_t ctrlType)
{
	switch (ctrlType) {
	case V4L2_CTRL_TYPE_U8:
		return ControlTypeByte;

	case V4L2_CTRL_TYPE_BOOLEAN:
		return ControlTypeBool;

	case V4L2_CTRL_TYPE_INTEGER:
		return ControlTypeInteger32;

	case V4L2_CTRL_TYPE_INTEGER64:
		return ControlTypeInteger64;

	case V4L2_CTRL_TYPE_MENU:
	case V4L2_CTRL_TYPE_BUTTON:
	case V4L2_CTRL_TYPE_BITMASK:
	case V4L2_CTRL_TYPE_INTEGER_MENU:
		/*
		 * More precise types may be needed, for now use a 32-bit
		 * integer type.
		 */
		return ControlTypeInteger32;

	default:
		return ControlTypeNone;
	}
}

/**
 * \brief Create a ControlId for a V4L2 control
 * \param[in] ctrl The v4l2_query_ext_ctrl that represents a V4L2 control
 * \return A ControlId associated to \a ctrl
 */
std::unique_ptr<ControlId> V4L2Device::v4l2ControlId(const v4l2_query_ext_ctrl &ctrl)
{
	const size_t len = strnlen(ctrl.name, sizeof(ctrl.name));
	const std::string name(static_cast<const char *>(ctrl.name), len);
	const ControlType type = v4l2CtrlType(ctrl.type);

	return std::make_unique<ControlId>(ctrl.id, name, type);
}

/**
 * \brief Create a ControlInfo for a V4L2 control
 * \param[in] ctrl The v4l2_query_ext_ctrl that represents a V4L2 control
 * \return A ControlInfo that represents \a ctrl
 */
std::optional<ControlInfo> V4L2Device::v4l2ControlInfo(const v4l2_query_ext_ctrl &ctrl)
{
	switch (ctrl.type) {
	case V4L2_CTRL_TYPE_U8:
		return ControlInfo(static_cast<uint8_t>(ctrl.minimum),
				   static_cast<uint8_t>(ctrl.maximum),
				   static_cast<uint8_t>(ctrl.default_value));

	case V4L2_CTRL_TYPE_BOOLEAN:
		return ControlInfo(static_cast<bool>(ctrl.minimum),
				   static_cast<bool>(ctrl.maximum),
				   static_cast<bool>(ctrl.default_value));

	case V4L2_CTRL_TYPE_INTEGER64:
		return ControlInfo(static_cast<int64_t>(ctrl.minimum),
				   static_cast<int64_t>(ctrl.maximum),
				   static_cast<int64_t>(ctrl.default_value));

	case V4L2_CTRL_TYPE_INTEGER_MENU:
	case V4L2_CTRL_TYPE_MENU:
		return v4l2MenuControlInfo(ctrl);

	default:
		return ControlInfo(static_cast<int32_t>(ctrl.minimum),
				   static_cast<int32_t>(ctrl.maximum),
				   static_cast<int32_t>(ctrl.default_value));
	}
}

/**
 * \brief Create ControlInfo for a V4L2 menu control
 * \param[in] ctrl The v4l2_query_ext_ctrl that represents a V4L2 menu control
 *
 * The created ControlInfo contains indices acquired by VIDIOC_QUERYMENU.
 *
 * \return A ControlInfo that represents \a ctrl
 */
std::optional<ControlInfo> V4L2Device::v4l2MenuControlInfo(const struct v4l2_query_ext_ctrl &ctrl)