-
-
Notifications
You must be signed in to change notification settings - Fork 56.5k
Expand file tree
/
Copy pathcap_v4l.cpp
More file actions
2268 lines (2016 loc) · 72.6 KB
/
cap_v4l.cpp
File metadata and controls
2268 lines (2016 loc) · 72.6 KB
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
/* This is the contributed code:
File: cvcap_v4l.cpp
Current Location: ../opencv-0.9.6/otherlibs/videoio
Original Version: 2003-03-12 Magnus Lundin lundin@mlu.mine.nu
Original Comments:
ML:This set of files adds support for firevre and usb cameras.
First it tries to install a firewire camera,
if that fails it tries a v4l/USB camera
It has been tested with the motempl sample program
First Patch: August 24, 2004 Travis Wood TravisOCV@tkwood.com
For Release: OpenCV-Linux Beta4 opencv-0.9.6
Tested On: LMLBT44 with 8 video inputs
Patched Comments:
TW: The cv cam utils that came with the initial release of OpenCV for LINUX Beta4
were not working. I have rewritten them so they work for me. At the same time, trying
to keep the original code as ML wrote it as unchanged as possible. No one likes to debug
someone elses code, so I resisted changes as much as possible. I have tried to keep the
same "ideas" where applicable, that is, where I could figure out what the previous author
intended. Some areas I just could not help myself and had to "spiffy-it-up" my way.
These drivers should work with other V4L frame capture cards other then my bttv
driven frame capture card.
Re Written driver for standard V4L mode. Tested using LMLBT44 video capture card.
Standard bttv drivers are on the LMLBT44 with up to 8 Inputs.
This utility was written with the help of the document:
http://pages.cpsc.ucalgary.ca/~sayles/VFL_HowTo
as a general guide for interfacing into the V4l standard.
Made the index value passed for icvOpenCAM_V4L(index) be the number of the
video device source in the /dev tree. The -1 uses original /dev/video.
Index Device
0 /dev/video0
1 /dev/video1
2 /dev/video2
3 /dev/video3
...
7 /dev/video7
with
-1 /dev/video
TW: You can select any video source, but this package was limited from the start to only
ONE camera opened at any ONE time.
This is an original program limitation.
If you are interested, I will make my version available to other OpenCV users. The big
difference in mine is you may pass the camera number as part of the cv argument, but this
convention is non standard for current OpenCV calls and the camera number is not currently
passed into the called routine.
Second Patch: August 28, 2004 Sfuncia Fabio fiblan@yahoo.it
For Release: OpenCV-Linux Beta4 Opencv-0.9.6
FS: this patch fix not sequential index of device (unplugged device), and real numCameras.
for -1 index (icvOpenCAM_V4L) I don't use /dev/video but real device available, because
if /dev/video is a link to /dev/video0 and i unplugged device on /dev/video0, /dev/video
is a bad link. I search the first available device with indexList.
Third Patch: December 9, 2004 Frederic Devernay Frederic.Devernay@inria.fr
For Release: OpenCV-Linux Beta4 Opencv-0.9.6
[FD] I modified the following:
- handle YUV420P, YUV420, and YUV411P palettes (for many webcams) without using floating-point
- cvGrabFrame should not wait for the end of the first frame, and should return quickly
(see videoio doc)
- cvRetrieveFrame should in turn wait for the end of frame capture, and should not
trigger the capture of the next frame (the user choses when to do it using GrabFrame)
To get the old behavior, re-call cvRetrieveFrame just after cvGrabFrame.
- having global bufferIndex and FirstCapture variables makes the code non-reentrant
(e.g. when using several cameras), put these in the CvCapture struct.
- according to V4L HowTo, incrementing the buffer index must be done before VIDIOCMCAPTURE.
- the VID_TYPE_SCALES stuff from V4L HowTo is wrong: image size can be changed
even if the hardware does not support scaling (e.g. webcams can have several
resolutions available). Just don't try to set the size at 640x480 if the hardware supports
scaling: open with the default (probably best) image size, and let the user scale it
using SetProperty.
- image size can be changed by two subsequent calls to SetProperty (for width and height)
- bug fix: if the image size changes, realloc the new image only when it is grabbed
- issue errors only when necessary, fix error message formatting.
Fourth Patch: Sept 7, 2005 Csaba Kertesz sign@freemail.hu
For Release: OpenCV-Linux Beta5 OpenCV-0.9.7
I modified the following:
- Additional Video4Linux2 support :)
- Use mmap functions (v4l2)
- New methods are internal:
try_palette_v4l2 -> rewrite try_palette for v4l2
mainloop_v4l2, read_image_v4l2 -> this methods are moved from official v4l2 capture.c example
try_init_v4l -> device v4l initialisation
try_init_v4l2 -> device v4l2 initialisation
autosetup_capture_mode_v4l -> autodetect capture modes for v4l
autosetup_capture_mode_v4l2 -> autodetect capture modes for v4l2
- Modifications are according with Video4Linux old codes
- Video4Linux handling is automatically if it does not recognize a Video4Linux2 device
- Tested successfully with Logitech Quickcam Express (V4L), Creative Vista (V4L) and Genius VideoCam Notebook (V4L2)
- Correct source lines with compiler warning messages
- Information message from v4l/v4l2 detection
Fifth Patch: Sept 7, 2005 Csaba Kertesz sign@freemail.hu
For Release: OpenCV-Linux Beta5 OpenCV-0.9.7
I modified the following:
- SN9C10x chip based webcams support
- New methods are internal:
bayer2rgb24, sonix_decompress -> decoder routines for SN9C10x decoding from Takafumi Mizuno <taka-qce@ls-a.jp> with his pleasure :)
- Tested successfully with Genius VideoCam Notebook (V4L2)
Sixth Patch: Sept 10, 2005 Csaba Kertesz sign@freemail.hu
For Release: OpenCV-Linux Beta5 OpenCV-0.9.7
I added the following:
- Add capture control support (hue, saturation, brightness, contrast, gain)
- Get and change V4L capture controls (hue, saturation, brightness, contrast)
- New method is internal:
icvSetControl -> set capture controls
- Tested successfully with Creative Vista (V4L)
Seventh Patch: Sept 10, 2005 Csaba Kertesz sign@freemail.hu
For Release: OpenCV-Linux Beta5 OpenCV-0.9.7
I added the following:
- Detect, get and change V4L2 capture controls (hue, saturation, brightness, contrast, gain)
- New methods are internal:
v4l2_scan_controls_enumerate_menu, v4l2_scan_controls -> detect capture control intervals
- Tested successfully with Genius VideoCam Notebook (V4L2)
8th patch: Jan 5, 2006, Olivier.Bornet@idiap.ch
Add support of V4L2_PIX_FMT_YUYV and V4L2_PIX_FMT_MJPEG.
With this patch, new webcams of Logitech, like QuickCam Fusion works.
Note: For use these webcams, look at the UVC driver at
http://linux-uvc.berlios.de/
9th patch: Mar 4, 2006, Olivier.Bornet@idiap.ch
- try V4L2 before V4L, because some devices are V4L2 by default,
but they try to implement the V4L compatibility layer.
So, I think this is better to support V4L2 before V4L.
- better separation between V4L2 and V4L initialization. (this was needed to support
some drivers working, but not fully with V4L2. (so, we do not know when we
need to switch from V4L2 to V4L.
10th patch: July 02, 2008, Mikhail Afanasyev fopencv@theamk.com
Fix reliability problems with high-resolution UVC cameras on linux
the symptoms were damaged image and 'Corrupt JPEG data: premature end of data segment' on stderr
- V4L_ABORT_BADJPEG detects JPEG warnings and turns them into errors, so bad images
could be filtered out
- USE_TEMP_BUFFER fixes the main problem (improper buffer management) and
prevents bad images in the first place
11th patch: April 2, 2013, Forrest Reiling forrest.reiling@gmail.com
Added v4l2 support for getting capture property CAP_PROP_POS_MSEC.
Returns the millisecond timestamp of the last frame grabbed or 0 if no frames have been grabbed
Used to successfully synchronize 2 Logitech C310 USB webcams to within 16 ms of one another
12th patch: March 9, 2018, Taylor Lanclos <tlanclos@live.com>
added support for CAP_PROP_BUFFERSIZE
make & enjoy!
*/
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "precomp.hpp"
#if !defined _WIN32 && (defined HAVE_CAMV4L2 || defined HAVE_VIDEOIO)
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <limits>
#include <poll.h>
#ifdef HAVE_CAMV4L2
#include <asm/types.h> /* for videodev2.h */
#include <linux/videodev2.h>
#endif
#ifdef HAVE_VIDEOIO
// NetBSD compatibility layer with V4L2
#include <sys/videoio.h>
#endif
#ifdef __OpenBSD__
typedef uint32_t __u32;
#endif
// https://github.com/opencv/opencv/issues/13335
#ifndef V4L2_CID_ISO_SENSITIVITY
#define V4L2_CID_ISO_SENSITIVITY (V4L2_CID_CAMERA_CLASS_BASE+23)
#endif
// https://github.com/opencv/opencv/issues/13929
#ifndef V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT
#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_HEIGHT (V4L2_CID_MPEG_BASE+364)
#endif
#ifndef V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH
#define V4L2_CID_MPEG_VIDEO_H264_VUI_EXT_SAR_WIDTH (V4L2_CID_MPEG_BASE+365)
#endif
#ifndef V4L2_CID_ROTATE
#define V4L2_CID_ROTATE (V4L2_CID_BASE+34)
#endif
#ifndef V4L2_CID_IRIS_ABSOLUTE
#define V4L2_CID_IRIS_ABSOLUTE (V4L2_CID_CAMERA_CLASS_BASE+17)
#endif
#ifndef v4l2_fourcc_be
#define v4l2_fourcc_be(a, b, c, d) (v4l2_fourcc(a, b, c, d) | (1U << 31))
#endif
#ifndef V4L2_PIX_FMT_Y10
#define V4L2_PIX_FMT_Y10 v4l2_fourcc('Y', '1', '0', ' ')
#endif
#ifndef V4L2_PIX_FMT_Y12
#define V4L2_PIX_FMT_Y12 v4l2_fourcc('Y', '1', '2', ' ')
#endif
#ifndef V4L2_PIX_FMT_Y16
#define V4L2_PIX_FMT_Y16 v4l2_fourcc('Y', '1', '6', ' ')
#endif
#ifndef V4L2_PIX_FMT_Y16_BE
#define V4L2_PIX_FMT_Y16_BE v4l2_fourcc_be('Y', '1', '6', ' ')
#endif
#ifndef V4L2_PIX_FMT_ABGR32
#define V4L2_PIX_FMT_ABGR32 v4l2_fourcc('A', 'R', '2', '4')
#endif
#ifndef V4L2_PIX_FMT_XBGR32
#define V4L2_PIX_FMT_XBGR32 v4l2_fourcc('X', 'R', '2', '4')
#endif
/* Defaults - If your board can do better, set it here. Set for the most common type inputs. */
#define DEFAULT_V4L_WIDTH 640
#define DEFAULT_V4L_HEIGHT 480
#define DEFAULT_V4L_FPS 30
#define MAX_CAMERAS 8
// default and maximum number of V4L buffers, not including last, 'special' buffer
#define MAX_V4L_BUFFERS 10
#define DEFAULT_V4L_BUFFERS 4
// types of memory in 'special' buffer
enum {
MEMORY_ORIG = 0, // Image data in original format.
MEMORY_RGB = 1, // Image data converted to RGB format.
};
// if enabled, then bad JPEG warnings become errors and cause NULL returned instead of image
#define V4L_ABORT_BADJPEG
namespace cv {
static const char* decode_ioctl_code(unsigned long ioctlCode)
{
switch (ioctlCode)
{
#define CV_ADD_IOCTL_CODE(id) case id: return #id
CV_ADD_IOCTL_CODE(VIDIOC_G_FMT);
CV_ADD_IOCTL_CODE(VIDIOC_S_FMT);
CV_ADD_IOCTL_CODE(VIDIOC_REQBUFS);
CV_ADD_IOCTL_CODE(VIDIOC_DQBUF);
CV_ADD_IOCTL_CODE(VIDIOC_QUERYCAP);
CV_ADD_IOCTL_CODE(VIDIOC_S_PARM);
CV_ADD_IOCTL_CODE(VIDIOC_G_PARM);
CV_ADD_IOCTL_CODE(VIDIOC_QUERYBUF);
CV_ADD_IOCTL_CODE(VIDIOC_QBUF);
CV_ADD_IOCTL_CODE(VIDIOC_STREAMON);
CV_ADD_IOCTL_CODE(VIDIOC_STREAMOFF);
CV_ADD_IOCTL_CODE(VIDIOC_ENUMINPUT);
CV_ADD_IOCTL_CODE(VIDIOC_G_INPUT);
CV_ADD_IOCTL_CODE(VIDIOC_S_INPUT);
CV_ADD_IOCTL_CODE(VIDIOC_G_CTRL);
CV_ADD_IOCTL_CODE(VIDIOC_S_CTRL);
#undef CV_ADD_IOCTL_CODE
}
return "unknown";
}
struct Memory
{
void * start;
size_t length;
Memory() : start(NULL), length(0) {}
};
/* Device Capture Objects */
/* V4L2 structure */
struct Buffer
{
Memory memories[VIDEO_MAX_PLANES];
v4l2_plane planes[VIDEO_MAX_PLANES] = {};
// Total number of bytes occupied by data in the all planes (payload)
__u32 bytesused;
// This is dequeued buffer. It used for to put it back in the queue.
// The buffer is valid only if capture->bufferIndex >= 0
v4l2_buffer buffer;
Buffer()
{
buffer = v4l2_buffer();
}
};
struct CvCaptureCAM_V4L CV_FINAL : public IVideoCapture
{
int getCaptureDomain() /*const*/ CV_OVERRIDE { return cv::CAP_V4L; }
int deviceHandle;
bool v4l_buffersRequested;
bool v4l_streamStarted;
int bufferIndex;
bool FirstCapture;
String deviceName;
Mat frame;
__u32 palette;
int width, height;
int width_set, height_set;
int bufferSize;
__u32 fps;
bool convert_rgb;
bool returnFrame;
// To select a video input set cv::CAP_PROP_CHANNEL to channel number.
// If the new channel number is than 0, then a video input will not change
int channelNumber;
// Normalize properties. If set parameters will be converted to/from [0,1) range.
// Enabled by default (as OpenCV 3.x does).
// Value is initialized from the environment variable `OPENCV_VIDEOIO_V4L_RANGE_NORMALIZED`:
// To select real parameters mode after devise is open set cv::CAP_PROP_MODE to 0
// any other value revert the backward compatibility mode (with normalized properties).
// Range normalization affects the following parameters:
// cv::CAP_PROP_*: BRIGHTNESS,CONTRAST,SATURATION,HUE,GAIN,EXPOSURE,FOCUS,AUTOFOCUS,AUTO_EXPOSURE.
bool normalizePropRange;
/* V4L2 variables */
Buffer buffers[MAX_V4L_BUFFERS + 1];
v4l2_capability capability;
v4l2_input videoInput;
v4l2_format form;
v4l2_requestbuffers req;
v4l2_buf_type type;
unsigned char num_planes;
timeval timestamp;
bool open(int _index);
bool open(const std::string & filename);
bool isOpened() const CV_OVERRIDE;
void closeDevice();
virtual double getProperty(int) const CV_OVERRIDE;
virtual bool setProperty(int, double) CV_OVERRIDE;
virtual bool grabFrame() CV_OVERRIDE;
virtual bool retrieveFrame(int, OutputArray) CV_OVERRIDE;
CvCaptureCAM_V4L();
virtual ~CvCaptureCAM_V4L();
bool requestBuffers();
bool requestBuffers(unsigned int buffer_number);
bool createBuffers();
void releaseBuffers();
bool initCapture();
bool streaming(bool startStream);
bool setFps(int value);
bool tryIoctl(unsigned long ioctlCode, void *parameter, bool failIfBusy = true, int attempts = 10) const;
bool controlInfo(int property_id, __u32 &v4l2id, cv::Range &range) const;
bool icvControl(__u32 v4l2id, int &value, bool isSet) const;
void initFrameNonBGR();
bool icvSetFrameSize(int _width, int _height);
bool v4l2_reset();
bool setVideoInputChannel();
bool try_palette_v4l2();
bool try_init_v4l2();
bool autosetup_capture_mode_v4l2();
bool read_frame_v4l2();
bool convertableToRgb() const;
void convertToRgb(const Buffer ¤tBuffer);
bool havePendingFrame; // true if next .grab() should be noop, .retrieve() resets this flag
};
/*********************** Implementations ***************************************/
CvCaptureCAM_V4L::CvCaptureCAM_V4L() :
deviceHandle(-1),
v4l_buffersRequested(false),
v4l_streamStarted(false),
bufferIndex(-1),
FirstCapture(true),
palette(0),
width(0), height(0), width_set(0), height_set(0),
bufferSize(DEFAULT_V4L_BUFFERS),
fps(0), convert_rgb(0), returnFrame(false),
channelNumber(-1), normalizePropRange(false),
type(V4L2_BUF_TYPE_VIDEO_CAPTURE),
num_planes(0),
havePendingFrame(false)
{
memset(×tamp, 0, sizeof(timestamp));
}
CvCaptureCAM_V4L::~CvCaptureCAM_V4L()
{
try
{
closeDevice();
}
catch (...)
{
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2): unable properly close device: " << deviceName);
if (deviceHandle != -1)
close(deviceHandle);
}
}
void CvCaptureCAM_V4L::closeDevice()
{
if (v4l_streamStarted)
streaming(false);
if (v4l_buffersRequested)
releaseBuffers();
if(deviceHandle != -1)
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): close(" << deviceHandle << ")");
close(deviceHandle);
}
deviceHandle = -1;
}
bool CvCaptureCAM_V4L::isOpened() const
{
return deviceHandle != -1;
}
bool CvCaptureCAM_V4L::try_palette_v4l2()
{
form = v4l2_format();
form.type = type;
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
form.fmt.pix_mp.pixelformat = palette;
form.fmt.pix_mp.field = V4L2_FIELD_ANY;
form.fmt.pix_mp.width = width;
form.fmt.pix_mp.height = height;
} else {
form.fmt.pix.pixelformat = palette;
form.fmt.pix.field = V4L2_FIELD_ANY;
form.fmt.pix.width = width;
form.fmt.pix.height = height;
}
if (!tryIoctl(VIDIOC_S_FMT, &form, true))
{
return false;
}
if (V4L2_TYPE_IS_MULTIPLANAR(type))
return palette == form.fmt.pix_mp.pixelformat;
return palette == form.fmt.pix.pixelformat;
}
bool CvCaptureCAM_V4L::setVideoInputChannel()
{
if(channelNumber < 0)
return true;
/* Query channels number */
int channel = 0;
if (!tryIoctl(VIDIOC_G_INPUT, &channel))
return false;
if(channel == channelNumber)
return true;
/* Query information about new input channel */
videoInput = v4l2_input();
videoInput.index = channelNumber;
if (!tryIoctl(VIDIOC_ENUMINPUT, &videoInput))
return false;
//To select a video input applications store the number of the desired input in an integer
// and call the VIDIOC_S_INPUT ioctl with a pointer to this integer. Side effects are possible.
// For example inputs may support different video standards, so the driver may implicitly
// switch the current standard.
// It is good practice to select an input before querying or negotiating any other parameters.
return tryIoctl(VIDIOC_S_INPUT, &channelNumber);
}
bool CvCaptureCAM_V4L::try_init_v4l2()
{
/* The following code sets the CHANNEL_NUMBER of the video input. Some video sources
have sub "Channel Numbers". For a typical V4L TV capture card, this is usually 1.
I myself am using a simple NTSC video input capture card that uses the value of 1.
If you are not in North America or have a different video standard, you WILL have to change
the following settings and recompile/reinstall. This set of settings is based on
the most commonly encountered input video source types (like my bttv card) */
// The cv::CAP_PROP_MODE used for set the video input channel number
if (!setVideoInputChannel())
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): Unable to set Video Input Channel");
return false;
}
// Test device for V4L2 compatibility
capability = v4l2_capability();
if (!tryIoctl(VIDIOC_QUERYCAP, &capability))
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): Unable to query capability");
return false;
}
if ((capability.capabilities & (V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_VIDEO_CAPTURE_MPLANE)) == 0)
{
/* Nope. */
CV_LOG_INFO(NULL, "VIDEOIO(V4L2:" << deviceName << "): not supported - device is unable to capture video (missing V4L2_CAP_VIDEO_CAPTURE or V4L2_CAP_VIDEO_CAPTURE_MPLANE)");
return false;
}
if (capability.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE)
type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
return true;
}
bool CvCaptureCAM_V4L::autosetup_capture_mode_v4l2()
{
//in case palette is already set and works, no need to setup.
if (palette != 0)
{
if (try_palette_v4l2())
{
return true;
}
else if (errno == EBUSY)
{
CV_LOG_INFO(NULL, "VIDEOIO(V4L2:" << deviceName << "): device is busy");
closeDevice();
return false;
}
}
__u32 try_order[] = {
V4L2_PIX_FMT_BGR24,
V4L2_PIX_FMT_RGB24,
V4L2_PIX_FMT_YVU420,
V4L2_PIX_FMT_YUV420,
V4L2_PIX_FMT_YUV411P,
V4L2_PIX_FMT_YUYV,
V4L2_PIX_FMT_UYVY,
V4L2_PIX_FMT_NV12,
V4L2_PIX_FMT_NV21,
V4L2_PIX_FMT_SBGGR8,
V4L2_PIX_FMT_SGBRG8,
V4L2_PIX_FMT_SGRBG8,
V4L2_PIX_FMT_XBGR32,
V4L2_PIX_FMT_ABGR32,
V4L2_PIX_FMT_SN9C10X,
#ifdef HAVE_JPEG
V4L2_PIX_FMT_MJPEG,
V4L2_PIX_FMT_JPEG,
#endif
V4L2_PIX_FMT_Y16,
V4L2_PIX_FMT_Y16_BE,
V4L2_PIX_FMT_Y12,
V4L2_PIX_FMT_Y10,
V4L2_PIX_FMT_GREY,
};
for (size_t i = 0; i < sizeof(try_order) / sizeof(__u32); i++) {
palette = try_order[i];
if (try_palette_v4l2()) {
return true;
} else if (errno == EBUSY) {
CV_LOG_INFO(NULL, "VIDEOIO(V4L2:" << deviceName << "): device is busy");
closeDevice();
return false;
}
}
return false;
}
bool CvCaptureCAM_V4L::setFps(int value)
{
if (!isOpened())
return false;
v4l2_streamparm streamparm = v4l2_streamparm();
streamparm.type = type;
streamparm.parm.capture.timeperframe.numerator = 1;
streamparm.parm.capture.timeperframe.denominator = __u32(value);
if (!tryIoctl(VIDIOC_S_PARM, &streamparm) || !tryIoctl(VIDIOC_G_PARM, &streamparm))
{
CV_LOG_INFO(NULL, "VIDEOIO(V4L2:" << deviceName << "): can't set FPS: " << value);
return false;
}
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): FPS="
<< streamparm.parm.capture.timeperframe.denominator << "/"
<< streamparm.parm.capture.timeperframe.numerator);
fps = streamparm.parm.capture.timeperframe.denominator; // TODO use numerator
return true;
}
bool CvCaptureCAM_V4L::convertableToRgb() const
{
switch (palette) {
case V4L2_PIX_FMT_YVU420:
case V4L2_PIX_FMT_YUV420:
case V4L2_PIX_FMT_NV12:
case V4L2_PIX_FMT_NV21:
case V4L2_PIX_FMT_YUV411P:
#ifdef HAVE_JPEG
case V4L2_PIX_FMT_MJPEG:
case V4L2_PIX_FMT_JPEG:
#endif
case V4L2_PIX_FMT_YUYV:
case V4L2_PIX_FMT_UYVY:
case V4L2_PIX_FMT_SBGGR8:
case V4L2_PIX_FMT_SN9C10X:
case V4L2_PIX_FMT_SGBRG8:
case V4L2_PIX_FMT_SGRBG8:
case V4L2_PIX_FMT_RGB24:
case V4L2_PIX_FMT_Y16:
case V4L2_PIX_FMT_Y16_BE:
case V4L2_PIX_FMT_Y10:
case V4L2_PIX_FMT_GREY:
case V4L2_PIX_FMT_BGR24:
case V4L2_PIX_FMT_XBGR32:
case V4L2_PIX_FMT_ABGR32:
return true;
default:
break;
}
return false;
}
bool CvCaptureCAM_V4L::initCapture()
{
if (!isOpened())
return false;
if (!try_init_v4l2())
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): init failed: errno=" << errno << " (" << strerror(errno) << ")");
return false;
}
/* Find Window info */
form = v4l2_format();
form.type = type;
if (!tryIoctl(VIDIOC_G_FMT, &form))
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): Could not obtain specifics of capture window (VIDIOC_G_FMT): errno=" << errno << " (" << strerror(errno) << ")");
return false;
}
if (!autosetup_capture_mode_v4l2())
{
if (errno != EBUSY)
{
CV_LOG_INFO(NULL, "VIDEOIO(V4L2:" << deviceName << "): Pixel format of incoming image is unsupported by OpenCV");
}
return false;
}
/* try to set framerate */
setFps(fps);
/* Buggy driver paranoia. */
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
// TODO: add size adjustment if needed
} else {
unsigned int min;
min = form.fmt.pix.width * 2;
if (form.fmt.pix.bytesperline < min)
form.fmt.pix.bytesperline = min;
min = form.fmt.pix.bytesperline * form.fmt.pix.height;
if (form.fmt.pix.sizeimage < min)
form.fmt.pix.sizeimage = min;
}
if (V4L2_TYPE_IS_MULTIPLANAR(type))
num_planes = form.fmt.pix_mp.num_planes;
else
num_planes = 1;
if (!requestBuffers())
return false;
if (!createBuffers()) {
/* free capture, and returns an error code */
releaseBuffers();
return false;
}
// reinitialize buffers
FirstCapture = true;
return true;
};
bool CvCaptureCAM_V4L::requestBuffers()
{
unsigned int buffer_number = bufferSize;
while (buffer_number > 0) {
if (requestBuffers(buffer_number) && req.count >= buffer_number)
{
break;
}
buffer_number--;
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): Insufficient buffer memory -- decreasing buffers: " << buffer_number);
}
if (buffer_number < 1) {
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): Insufficient buffer memory");
return false;
}
bufferSize = req.count;
return true;
}
bool CvCaptureCAM_V4L::requestBuffers(unsigned int buffer_number)
{
if (!isOpened())
return false;
req = v4l2_requestbuffers();
req.count = buffer_number;
req.type = type;
req.memory = V4L2_MEMORY_MMAP;
if (!tryIoctl(VIDIOC_REQBUFS, &req)) {
int err = errno;
if (EINVAL == err)
{
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): no support for memory mapping");
}
else
{
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): failed VIDIOC_REQBUFS: errno=" << err << " (" << strerror(err) << ")");
}
return false;
}
v4l_buffersRequested = true;
return true;
}
bool CvCaptureCAM_V4L::createBuffers()
{
size_t maxLength = 0;
for (unsigned int n_buffers = 0; n_buffers < req.count; ++n_buffers) {
v4l2_buffer buf = v4l2_buffer();
v4l2_plane mplanes[VIDEO_MAX_PLANES];
size_t length = 0;
off_t offset = 0;
buf.type = type;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = n_buffers;
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
buf.m.planes = mplanes;
buf.length = VIDEO_MAX_PLANES;
}
if (!tryIoctl(VIDIOC_QUERYBUF, &buf)) {
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): failed VIDIOC_QUERYBUF: errno=" << errno << " (" << strerror(errno) << ")");
return false;
}
CV_Assert(1 <= num_planes && num_planes <= VIDEO_MAX_PLANES);
for (unsigned char n_planes = 0; n_planes < num_planes; n_planes++) {
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
length = buf.m.planes[n_planes].length;
offset = buf.m.planes[n_planes].m.mem_offset;
} else {
length = buf.length;
offset = buf.m.offset;
}
buffers[n_buffers].memories[n_planes].length = length;
buffers[n_buffers].memories[n_planes].start =
mmap(NULL /* start anywhere */,
length,
PROT_READ /* required */,
MAP_SHARED /* recommended */,
deviceHandle, offset);
if (MAP_FAILED == buffers[n_buffers].memories[n_planes].start) {
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): failed mmap(" << length << "): errno=" << errno << " (" << strerror(errno) << ")");
return false;
}
}
maxLength = maxLength > length ? maxLength : length;
}
if (maxLength > 0) {
maxLength *= num_planes;
buffers[MAX_V4L_BUFFERS].memories[MEMORY_ORIG].start = malloc(maxLength);
buffers[MAX_V4L_BUFFERS].memories[MEMORY_ORIG].length = maxLength;
buffers[MAX_V4L_BUFFERS].memories[MEMORY_RGB].start = malloc(maxLength);
buffers[MAX_V4L_BUFFERS].memories[MEMORY_RGB].length = maxLength;
}
return (buffers[MAX_V4L_BUFFERS].memories[MEMORY_ORIG].start != 0) &&
(buffers[MAX_V4L_BUFFERS].memories[MEMORY_RGB].start != 0);
}
/**
* some properties can not be changed while the device is in streaming mode.
* this method closes and re-opens the device to re-start the stream.
* this also causes buffers to be reallocated if the frame size was changed.
*/
bool CvCaptureCAM_V4L::v4l2_reset()
{
streaming(false);
releaseBuffers();
return initCapture();
}
bool CvCaptureCAM_V4L::open(int _index)
{
cv::String name;
/* Select camera, or rather, V4L video source */
if (_index < 0) // Asking for the first device available
{
for (int autoindex = 0; autoindex < MAX_CAMERAS; ++autoindex)
{
name = cv::format("/dev/video%d", autoindex);
/* Test using an open to see if this new device name really does exists. */
int h = ::open(name.c_str(), O_RDONLY);
if (h != -1)
{
::close(h);
_index = autoindex;
break;
}
}
if (_index < 0)
{
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2): can't find camera device");
name.clear();
return false;
}
}
else
{
name = cv::format("/dev/video%d", _index);
}
bool res = open(name);
if (!res)
{
CV_LOG_WARNING(NULL, "VIDEOIO(V4L2:" << deviceName << "): can't open camera by index");
}
return res;
}
bool CvCaptureCAM_V4L::open(const std::string & _deviceName)
{
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << _deviceName << "): opening...");
FirstCapture = true;
width = utils::getConfigurationParameterSizeT("OPENCV_VIDEOIO_V4L_DEFAULT_WIDTH", DEFAULT_V4L_WIDTH);
height = utils::getConfigurationParameterSizeT("OPENCV_VIDEOIO_V4L_DEFAULT_HEIGHT", DEFAULT_V4L_HEIGHT);
width_set = height_set = 0;
bufferSize = DEFAULT_V4L_BUFFERS;
fps = DEFAULT_V4L_FPS;
convert_rgb = true;
deviceName = _deviceName;
returnFrame = true;
normalizePropRange = utils::getConfigurationParameterBool("OPENCV_VIDEOIO_V4L_RANGE_NORMALIZED", false);
channelNumber = -1;
bufferIndex = -1;
deviceHandle = ::open(deviceName.c_str(), O_RDWR /* required */ | O_NONBLOCK, 0);
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << _deviceName << "): deviceHandle=" << deviceHandle);
if (deviceHandle == -1)
return false;
return initCapture();
}
bool CvCaptureCAM_V4L::read_frame_v4l2()
{
v4l2_buffer buf = v4l2_buffer();
v4l2_plane mplanes[VIDEO_MAX_PLANES];
buf.type = type;
buf.memory = V4L2_MEMORY_MMAP;
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
buf.m.planes = mplanes;
buf.length = VIDEO_MAX_PLANES;
}
while (!tryIoctl(VIDIOC_DQBUF, &buf)) {
int err = errno;
if (err == EIO && !(buf.flags & (V4L2_BUF_FLAG_QUEUED | V4L2_BUF_FLAG_DONE))) {
// Maybe buffer not in the queue? Try to put there
if (!tryIoctl(VIDIOC_QBUF, &buf))
return false;
continue;
}
/* display the error and stop processing */
returnFrame = false;
CV_LOG_DEBUG(NULL, "VIDEOIO(V4L2:" << deviceName << "): can't read frame (VIDIOC_DQBUF): errno=" << err << " (" << strerror(err) << ")");
return false;
}
CV_Assert(buf.index < req.count);
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
for (unsigned char n_planes = 0; n_planes < num_planes; n_planes++)
CV_Assert(buffers[buf.index].memories[n_planes].length == buf.m.planes[n_planes].length);
} else
CV_Assert(buffers[buf.index].memories[MEMORY_ORIG].length == buf.length);
//We shouldn't use this buffer in the queue while not retrieve frame from it.
buffers[buf.index].buffer = buf;
bufferIndex = buf.index;
if (V4L2_TYPE_IS_MULTIPLANAR(type)) {
__u32 offset = 0;
buffers[buf.index].buffer.m.planes = buffers[buf.index].planes;
memcpy(buffers[buf.index].planes, buf.m.planes, sizeof(mplanes));
for (unsigned char n_planes = 0; n_planes < num_planes; n_planes++) {
__u32 bytesused;
bytesused = buffers[buf.index].planes[n_planes].bytesused -
buffers[buf.index].planes[n_planes].data_offset;
offset += bytesused;
}
buffers[buf.index].bytesused = offset;
} else
buffers[buf.index].bytesused = buffers[buf.index].buffer.bytesused;
//set timestamp in capture struct to be timestamp of most recent frame
timestamp = buf.timestamp;
return true;
}