Path: blob/master/modules/videoio/src/cap_libv4l.cpp
16354 views
/* This is the contributed code:12File: cvcap_v4l.cpp3Current Location: ../opencv-0.9.6/otherlibs/videoio45Original Version: 2003-03-12 Magnus Lundin [email protected]6Original Comments:78ML:This set of files adds support for firevre and usb cameras.9First it tries to install a firewire camera,10if that fails it tries a v4l/USB camera11It has been tested with the motempl sample program1213First Patch: August 24, 2004 Travis Wood [email protected]14For Release: OpenCV-Linux Beta4 opencv-0.9.615Tested On: LMLBT44 with 8 video inputs16Problems? Post your questions at answers.opencv.org,17Report bugs at code.opencv.org,18Submit your fixes at https://github.com/opencv/opencv/19Patched Comments:2021TW: The cv cam utils that came with the initial release of OpenCV for LINUX Beta422were not working. I have rewritten them so they work for me. At the same time, trying23to keep the original code as ML wrote it as unchanged as possible. No one likes to debug24someone elses code, so I resisted changes as much as possible. I have tried to keep the25same "ideas" where applicable, that is, where I could figure out what the previous author26intended. Some areas I just could not help myself and had to "spiffy-it-up" my way.2728These drivers should work with other V4L frame capture cards other then my bttv29driven frame capture card.3031Re Written driver for standard V4L mode. Tested using LMLBT44 video capture card.32Standard bttv drivers are on the LMLBT44 with up to 8 Inputs.3334This utility was written with the help of the document:35http://pages.cpsc.ucalgary.ca/~sayles/VFL_HowTo36as a general guide for interfacing into the V4l standard.3738Made the index value passed for icvOpenCAM_V4L(index) be the number of the39video device source in the /dev tree. The -1 uses original /dev/video.4041Index Device420 /dev/video0431 /dev/video1442 /dev/video2453 /dev/video346...477 /dev/video748with49-1 /dev/video5051TW: You can select any video source, but this package was limited from the start to only52ONE camera opened at any ONE time.53This is an original program limitation.54If you are interested, I will make my version available to other OpenCV users. The big55difference in mine is you may pass the camera number as part of the cv argument, but this56convention is non standard for current OpenCV calls and the camera number is not currently57passed into the called routine.5859Second Patch: August 28, 2004 Sfuncia Fabio [email protected]60For Release: OpenCV-Linux Beta4 Opencv-0.9.66162FS: this patch fix not sequential index of device (unplugged device), and real numCameras.63for -1 index (icvOpenCAM_V4L) I don't use /dev/video but real device available, because64if /dev/video is a link to /dev/video0 and i unplugged device on /dev/video0, /dev/video65is a bad link. I search the first available device with indexList.6667Third Patch: December 9, 2004 Frederic Devernay [email protected]68For Release: OpenCV-Linux Beta4 Opencv-0.9.66970[FD] I modified the following:71- handle YUV420P, YUV420, and YUV411P palettes (for many webcams) without using floating-point72- cvGrabFrame should not wait for the end of the first frame, and should return quickly73(see videoio doc)74- cvRetrieveFrame should in turn wait for the end of frame capture, and should not75trigger the capture of the next frame (the user choses when to do it using GrabFrame)76To get the old behavior, re-call cvRetrieveFrame just after cvGrabFrame.77- having global bufferIndex and FirstCapture variables makes the code non-reentrant78(e.g. when using several cameras), put these in the CvCapture struct.79- according to V4L HowTo, incrementing the buffer index must be done before VIDIOCMCAPTURE.80- the VID_TYPE_SCALES stuff from V4L HowTo is wrong: image size can be changed81even if the hardware does not support scaling (e.g. webcams can have several82resolutions available). Just don't try to set the size at 640x480 if the hardware supports83scaling: open with the default (probably best) image size, and let the user scale it84using SetProperty.85- image size can be changed by two subsequent calls to SetProperty (for width and height)86- bug fix: if the image size changes, realloc the new image only when it is grabbed87- issue errors only when necessary, fix error message formatting.8889Fourth Patch: Sept 7, 2005 Csaba Kertesz [email protected]90For Release: OpenCV-Linux Beta5 OpenCV-0.9.79192I modified the following:93- Additional Video4Linux2 support :)94- Use mmap functions (v4l2)95- New methods are internal:96try_palette_v4l2 -> rewrite try_palette for v4l297mainloop_v4l2, read_image_v4l2 -> this methods are moved from official v4l2 capture.c example98try_init_v4l -> device v4l initialisation99try_init_v4l2 -> device v4l2 initialisation100autosetup_capture_mode_v4l -> autodetect capture modes for v4l101autosetup_capture_mode_v4l2 -> autodetect capture modes for v4l2102- Modifications are according with Video4Linux old codes103- Video4Linux handling is automatically if it does not recognize a Video4Linux2 device104- Tested successfully with Logitech Quickcam Express (V4L), Creative Vista (V4L) and Genius VideoCam Notebook (V4L2)105- Correct source lines with compiler warning messages106- Information message from v4l/v4l2 detection107108Fifth Patch: Sept 7, 2005 Csaba Kertesz [email protected]109For Release: OpenCV-Linux Beta5 OpenCV-0.9.7110111I modified the following:112- SN9C10x chip based webcams support113- New methods are internal:114bayer2rgb24, sonix_decompress -> decoder routines for SN9C10x decoding from Takafumi Mizuno <[email protected]> with his pleasure :)115- Tested successfully with Genius VideoCam Notebook (V4L2)116117Sixth Patch: Sept 10, 2005 Csaba Kertesz [email protected]118For Release: OpenCV-Linux Beta5 OpenCV-0.9.7119120I added the following:121- Add capture control support (hue, saturation, brightness, contrast, gain)122- Get and change V4L capture controls (hue, saturation, brightness, contrast)123- New method is internal:124icvSetControl -> set capture controls125- Tested successfully with Creative Vista (V4L)126127Seventh Patch: Sept 10, 2005 Csaba Kertesz [email protected]128For Release: OpenCV-Linux Beta5 OpenCV-0.9.7129130I added the following:131- Detect, get and change V4L2 capture controls (hue, saturation, brightness, contrast, gain)132- New methods are internal:133v4l2_scan_controls_enumerate_menu, v4l2_scan_controls -> detect capture control intervals134- Tested successfully with Genius VideoCam Notebook (V4L2)1351368th patch: Jan 5, 2006, [email protected]137Add support of V4L2_PIX_FMT_YUYV and V4L2_PIX_FMT_MJPEG.138With this patch, new webcams of Logitech, like QuickCam Fusion works.139Note: For use these webcams, look at the UVC driver at140http://linux-uvc.berlios.de/1411429th patch: Mar 4, 2006, [email protected]143- try V4L2 before V4L, because some devices are V4L2 by default,144but they try to implement the V4L compatibility layer.145So, I think this is better to support V4L2 before V4L.146- better separation between V4L2 and V4L initialization. (this was needed to support147some drivers working, but not fully with V4L2. (so, we do not know when we148need to switch from V4L2 to V4L.14915010th patch: July 02, 2008, Mikhail Afanasyev [email protected]151Fix reliability problems with high-resolution UVC cameras on linux152the symptoms were damaged image and 'Corrupt JPEG data: premature end of data segment' on stderr153- V4L_ABORT_BADJPEG detects JPEG warnings and turns them into errors, so bad images154could be filtered out155- USE_TEMP_BUFFER fixes the main problem (improper buffer management) and156prevents bad images in the first place15715811th patch: Apr 13, 2010, Filipe Almeida [email protected]159- Tries to setup all properties first through v4l2_ioctl call.160- Allows setting up all Video4Linux properties through cvSetCaptureProperty instead of only CV_CAP_PROP_BRIGHTNESS, CV_CAP_PROP_CONTRAST, CV_CAP_PROP_SATURATION, CV_CAP_PROP_HUE, CV_CAP_PROP_GAIN and CV_CAP_PROP_EXPOSURE.16116212th patch: Apr 16, 2010, Filipe Almeida [email protected]163- CvCaptureCAM_V4L structure cleanup (no longer needs <PROPERTY>_{min,max,} variables)164- Introduction of v4l2_ctrl_range - minimum and maximum allowed values for v4l controls165- Allows setting up all Video4Linux properties through cvSetCaptureProperty using input values between 0.0 and 1.0166- Gets v4l properties first through v4l2_ioctl call (ignores capture->is_v4l2_device)167- cvGetCaptureProperty adjusted to support the changes168- Returns device properties to initial values after device closes16917013th patch: Apr 27, 2010, Filipe Almeida [email protected]171- Solved problem mmaping the device using uvcvideo driver (use o v4l2_mmap instead of mmap)172make & enjoy!17317414th patch: May 10, 2010, Filipe Almeida [email protected]175- Bug #142: Solved/Workaround "setting frame width and height does not work"176There was a problem setting up the size when the input is a v4l2 device177The workaround closes the camera and reopens it with the new definition178Planning for future rewrite of this whole library (July/August 2010)17918015th patch: May 12, 2010, Filipe Almeida [email protected]181- Broken compile of library (include "_videoio.h")18218316th patch: Dec 16, 2014, Joseph Howse [email protected]184- Allow getting/setting CV_CAP_PROP_MODE. These values are supported:185- CV_CAP_MODE_BGR : BGR24 (default)186- CV_CAP_MODE_RGB : RGB24187- CV_CAP_MODE_GRAY : Y8, extracted from YUV420188- Tested successfully on these cameras:189- PlayStation 3 Eye190- Logitech C920191- Odroid USB-CAM 720P19219317th patch: May 9, 2015, Matt Sandler194added supported for CV_CAP_PROP_POS_MSEC, CV_CAP_PROP_POS_FRAMES, CV_CAP_PROP_FPS195196*/197198/*M///////////////////////////////////////////////////////////////////////////////////////199//200// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.201//202// By downloading, copying, installing or using the software you agree to this license.203// If you do not agree to this license, do not download, install,204// copy or use the software.205//206//207// Intel License Agreement208// For Open Source Computer Vision Library209//210// Copyright (C) 2000, Intel Corporation, all rights reserved.211// Third party copyrights are property of their respective owners.212//213// Redistribution and use in source and binary forms, with or without modification,214// are permitted provided that the following conditions are met:215//216// * Redistribution's of source code must retain the above copyright notice,217// this list of conditions and the following disclaimer.218//219// * Redistribution's in binary form must reproduce the above copyright notice,220// this list of conditions and the following disclaimer in the documentation221// and/or other materials provided with the distribution.222//223// * The name of Intel Corporation may not be used to endorse or promote products224// derived from this software without specific prior written permission.225//226// This software is provided by the copyright holders and contributors "as is" and227// any express or implied warranties, including, but not limited to, the implied228// warranties of merchantability and fitness for a particular purpose are disclaimed.229// In no event shall the Intel Corporation or contributors be liable for any direct,230// indirect, incidental, special, exemplary, or consequential damages231// (including, but not limited to, procurement of substitute goods or services;232// loss of use, data, or profits; or business interruption) however caused233// and on any theory of liability, whether in contract, strict liability,234// or tort (including negligence or otherwise) arising in any way out of235// the use of this software, even if advised of the possibility of such damage.236//237//M*/238239#include "precomp.hpp"240241#if !defined _WIN32 && defined HAVE_LIBV4L242243#define CLEAR(x) memset (&(x), 0, sizeof (x))244245#include <stdio.h>246#include <unistd.h>247#include <fcntl.h>248#include <errno.h>249#include <sys/types.h>250#include <sys/mman.h>251#include <string.h>252#include <stdlib.h>253#include <asm/types.h> /* for videodev2.h */254#include <assert.h>255#include <sys/stat.h>256#include <sys/ioctl.h>257258#ifdef HAVE_CAMV4L259#include <linux/videodev.h>260#endif261#ifdef HAVE_CAMV4L2262#include <linux/videodev2.h>263#endif264265#include <libv4l1.h>266#include <libv4l2.h>267268/* Defaults - If your board can do better, set it here. Set for the most common type inputs. */269#define DEFAULT_V4L_WIDTH 640270#define DEFAULT_V4L_HEIGHT 480271272#define CHANNEL_NUMBER 1273#define MAX_CAMERAS 8274275276// default and maximum number of V4L buffers, not including last, 'special' buffer277#define MAX_V4L_BUFFERS 10278#define DEFAULT_V4L_BUFFERS 4279280// if enabled, copies data from the buffer. this uses a bit more memory,281// but much more reliable for some UVC cameras282#define USE_TEMP_BUFFER283284#define MAX_DEVICE_DRIVER_NAME 80285286/* Device Capture Objects */287/* V4L2 structure */288struct buffer289{290void * start;291size_t length;292};293static unsigned int n_buffers = 0;294295/* TODO: Dilemas: */296/* TODO: Consider drop the use of this data structure and perform ioctl to obtain needed values */297/* TODO: Consider at program exit return controls to the initial values - See v4l2_free_ranges function */298/* TODO: Consider at program exit reset the device to default values - See v4l2_free_ranges function */299typedef struct v4l2_ctrl_range {300__u32 ctrl_id;301__s32 initial_value;302__s32 current_value;303__s32 minimum;304__s32 maximum;305__s32 default_value;306} v4l2_ctrl_range;307308typedef struct CvCaptureCAM_V4L309{310char* deviceName;311int deviceHandle;312int bufferIndex;313int FirstCapture;314bool returnFrame;315316int width; int height;317int mode;318319struct video_capability capability;320struct video_window captureWindow;321struct video_picture imageProperties;322struct video_mbuf memoryBuffer;323struct video_mmap *mmaps;324char *memoryMap;325IplImage frame;326327/* V4L2 variables */328buffer buffers[MAX_V4L_BUFFERS + 1];329struct v4l2_capability cap;330struct v4l2_input inp;331struct v4l2_format form;332struct v4l2_crop crop;333struct v4l2_cropcap cropcap;334struct v4l2_requestbuffers req;335struct v4l2_jpegcompression compr;336struct v4l2_control control;337enum v4l2_buf_type type;338struct v4l2_queryctrl queryctrl;339340struct timeval timestamp;341342/** value set the buffer of V4L*/343int sequence;344345/* V4L2 control variables */346v4l2_ctrl_range** v4l2_ctrl_ranges;347int v4l2_ctrl_count;348349int is_v4l2_device;350}351CvCaptureCAM_V4L;352353static CvCaptureCAM_V4L * icvCaptureFromCAM_V4L (const char* deviceName);354static void icvCloseCAM_V4L( CvCaptureCAM_V4L* capture );355356static int icvGrabFrameCAM_V4L( CvCaptureCAM_V4L* capture );357static IplImage* icvRetrieveFrameCAM_V4L( CvCaptureCAM_V4L* capture, int );358CvCapture* cvCreateCameraCapture_V4L( int index );359360static double icvGetPropertyCAM_V4L( CvCaptureCAM_V4L* capture, int property_id );361static int icvSetPropertyCAM_V4L( CvCaptureCAM_V4L* capture, int property_id, double value );362363static int icvSetVideoSize( CvCaptureCAM_V4L* capture, int w, int h);364365/*********************** Implementations ***************************************/366367static int numCameras = 0;368static int indexList = 0;369370// IOCTL handling for V4L2371#ifdef HAVE_IOCTL_ULONG372static int xioctl( int fd, unsigned long request, void *arg)373#else374static int xioctl( int fd, int request, void *arg)375#endif376{377378int r;379380381do r = v4l2_ioctl (fd, request, arg);382while (-1 == r && EINTR == errno);383384return r;385386}387388389/* Simple test program: Find number of Video Sources available.390Start from 0 and go to MAX_CAMERAS while checking for the device with that name.391If it fails on the first attempt of /dev/video0, then check if /dev/video is valid.392Returns the global numCameras with the correct value (we hope) */393394static void icvInitCapture_V4L() {395int deviceHandle;396int CameraNumber;397char deviceName[MAX_DEVICE_DRIVER_NAME];398399CameraNumber = 0;400while(CameraNumber < MAX_CAMERAS) {401/* Print the CameraNumber at the end of the string with a width of one character */402sprintf(deviceName, "/dev/video%1d", CameraNumber);403/* Test using an open to see if this new device name really does exists. */404deviceHandle = open(deviceName, O_RDONLY);405if (deviceHandle != -1) {406/* This device does indeed exist - add it to the total so far */407numCameras++;408// add indexList409indexList|=(1 << CameraNumber);410}411if (deviceHandle != -1)412close(deviceHandle);413/* Set up to test the next /dev/video source in line */414CameraNumber++;415} /* End while */416417}; /* End icvInitCapture_V4L */418419420static int try_init_v4l(CvCaptureCAM_V4L* capture, const char *deviceName)421422{423424// if detect = -1 then unable to open device425// if detect = 0 then detected nothing426// if detect = 1 then V4L device427int detect = 0;428429430// Test device for V4L compatibility431432/* Test using an open to see if this new device name really does exists. */433/* No matter what the name - it still must be opened! */434capture->deviceHandle = v4l1_open(deviceName, O_RDWR);435436437if (capture->deviceHandle == 0)438{439detect = -1;440441icvCloseCAM_V4L(capture);442}443444if (detect == 0)445{446/* Query the newly opened device for its capabilities */447if (v4l1_ioctl(capture->deviceHandle, VIDIOCGCAP, &capture->capability) < 0)448{449detect = 0;450451icvCloseCAM_V4L(capture);452}453else454{455detect = 1;456}457}458459return detect;460461}462463464static int try_init_v4l2(CvCaptureCAM_V4L* capture, const char *deviceName)465{466467// if detect = -1 then unable to open device468// if detect = 0 then detected nothing469// if detect = 1 then V4L2 device470int detect = 0;471472473// Test device for V4L2 compatibility474475/* Open and test V4L2 device */476capture->deviceHandle = v4l2_open (deviceName, O_RDWR /* required */ | O_NONBLOCK, 0);477478479480if (capture->deviceHandle == 0)481{482detect = -1;483484icvCloseCAM_V4L(capture);485}486487if (detect == 0)488{489CLEAR (capture->cap);490if (-1 == xioctl (capture->deviceHandle, VIDIOC_QUERYCAP, &capture->cap))491{492detect = 0;493494icvCloseCAM_V4L(capture);495}496else497{498CLEAR (capture->capability);499capture->capability.type = capture->cap.capabilities;500501/* Query channels number */502if (-1 != xioctl (capture->deviceHandle, VIDIOC_G_INPUT, &capture->capability.channels))503{504detect = 1;505}506}507}508509return detect;510511}512513514static void v4l2_free_ranges(CvCaptureCAM_V4L* capture) {515int i;516if (capture->v4l2_ctrl_ranges != NULL) {517for (i = 0; i < capture->v4l2_ctrl_count; i++) {518/* Return device to initial values: */519/* double value = (capture->v4l2_ctrl_ranges[i]->initial_value == 0)?0.0:((float)capture->v4l2_ctrl_ranges[i]->initial_value - capture->v4l2_ctrl_ranges[i]->minimum) / (capture->v4l2_ctrl_ranges[i]->maximum - capture->v4l2_ctrl_ranges[i]->minimum); */520/* Return device to default values: */521/* double value = (capture->v4l2_ctrl_ranges[i]->default_value == 0)?0.0:((float)capture->v4l2_ctrl_ranges[i]->default_value - capture->v4l2_ctrl_ranges[i]->minimum + 1) / (capture->v4l2_ctrl_ranges[i]->maximum - capture->v4l2_ctrl_ranges[i]->minimum); */522523/* icvSetPropertyCAM_V4L(capture, capture->v4l2_ctrl_ranges[i]->ctrl_id, value); */524free(capture->v4l2_ctrl_ranges[i]);525}526}527free(capture->v4l2_ctrl_ranges);528capture->v4l2_ctrl_count = 0;529capture->v4l2_ctrl_ranges = NULL;530}531532static void v4l2_add_ctrl_range(CvCaptureCAM_V4L* capture, v4l2_control* ctrl) {533v4l2_ctrl_range* range = (v4l2_ctrl_range*)malloc(sizeof(v4l2_ctrl_range));534range->ctrl_id = ctrl->id;535range->initial_value = ctrl->value;536range->current_value = ctrl->value;537range->minimum = capture->queryctrl.minimum;538range->maximum = capture->queryctrl.maximum;539range->default_value = capture->queryctrl.default_value;540capture->v4l2_ctrl_ranges[capture->v4l2_ctrl_count] = range;541capture->v4l2_ctrl_count += 1;542capture->v4l2_ctrl_ranges = (v4l2_ctrl_range**)realloc((v4l2_ctrl_range**)capture->v4l2_ctrl_ranges, (capture->v4l2_ctrl_count + 1) * sizeof(v4l2_ctrl_range*));543}544545static int v4l2_get_ctrl_default(CvCaptureCAM_V4L* capture, __u32 id) {546int i;547for (i = 0; i < capture->v4l2_ctrl_count; i++) {548if (id == capture->v4l2_ctrl_ranges[i]->ctrl_id) {549return capture->v4l2_ctrl_ranges[i]->default_value;550}551}552return -1;553}554555static int v4l2_get_ctrl_min(CvCaptureCAM_V4L* capture, __u32 id) {556int i;557for (i = 0; i < capture->v4l2_ctrl_count; i++) {558if (id == capture->v4l2_ctrl_ranges[i]->ctrl_id) {559return capture->v4l2_ctrl_ranges[i]->minimum;560}561}562return -1;563}564565static int v4l2_get_ctrl_max(CvCaptureCAM_V4L* capture, __u32 id) {566int i;567for (i = 0; i < capture->v4l2_ctrl_count; i++) {568if (id == capture->v4l2_ctrl_ranges[i]->ctrl_id) {569return capture->v4l2_ctrl_ranges[i]->maximum;570}571}572return -1;573}574575576static void v4l2_scan_controls(CvCaptureCAM_V4L* capture) {577578__u32 ctrl_id;579struct v4l2_control c;580if (capture->v4l2_ctrl_ranges != NULL) {581v4l2_free_ranges(capture);582}583capture->v4l2_ctrl_ranges = (v4l2_ctrl_range**)malloc(sizeof(v4l2_ctrl_range*));584#ifdef V4L2_CTRL_FLAG_NEXT_CTRL585/* Try the extended control API first */586capture->queryctrl.id = V4L2_CTRL_FLAG_NEXT_CTRL;587if(0 == v4l2_ioctl (capture->deviceHandle, VIDIOC_QUERYCTRL, &capture->queryctrl)) {588do {589c.id = capture->queryctrl.id;590capture->queryctrl.id |= V4L2_CTRL_FLAG_NEXT_CTRL;591if(capture->queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) {592continue;593}594if(capture->queryctrl.type != V4L2_CTRL_TYPE_INTEGER &&595capture->queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN &&596capture->queryctrl.type != V4L2_CTRL_TYPE_MENU) {597continue;598}599if(v4l2_ioctl(capture->deviceHandle, VIDIOC_G_CTRL, &c) == 0) {600v4l2_add_ctrl_range(capture, &c);601}602603} while(0 == v4l2_ioctl (capture->deviceHandle, VIDIOC_QUERYCTRL, &capture->queryctrl));604} else605#endif606{607/* Check all the standard controls */608for(ctrl_id=V4L2_CID_BASE; ctrl_id<V4L2_CID_LASTP1; ctrl_id++) {609capture->queryctrl.id = ctrl_id;610if(v4l2_ioctl(capture->deviceHandle, VIDIOC_QUERYCTRL, &capture->queryctrl) == 0) {611if(capture->queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) {612continue;613}614if(capture->queryctrl.type != V4L2_CTRL_TYPE_INTEGER &&615capture->queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN &&616capture->queryctrl.type != V4L2_CTRL_TYPE_MENU) {617continue;618}619c.id = ctrl_id;620621if(v4l2_ioctl(capture->deviceHandle, VIDIOC_G_CTRL, &c) == 0) {622v4l2_add_ctrl_range(capture, &c);623}624}625}626627/* Check any custom controls */628for(ctrl_id=V4L2_CID_PRIVATE_BASE; ; ctrl_id++) {629capture->queryctrl.id = ctrl_id;630if(v4l2_ioctl(capture->deviceHandle, VIDIOC_QUERYCTRL, &capture->queryctrl) == 0) {631if(capture->queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) {632continue;633}634635636if(capture->queryctrl.type != V4L2_CTRL_TYPE_INTEGER &&637capture->queryctrl.type != V4L2_CTRL_TYPE_BOOLEAN &&638capture->queryctrl.type != V4L2_CTRL_TYPE_MENU) {639continue;640}641642c.id = ctrl_id;643644if(v4l2_ioctl(capture->deviceHandle, VIDIOC_G_CTRL, &c) == 0) {645v4l2_add_ctrl_range(capture, &c);646}647} else {648break;649}650}651}652}653654static inline int channels_for_mode(int mode)655{656switch(mode) {657case CV_CAP_MODE_GRAY:658return 1;659case CV_CAP_MODE_YUYV:660return 2;661default:662return 3;663}664}665666static int _capture_V4L2 (CvCaptureCAM_V4L *capture, const char *deviceName)667{668int detect_v4l2 = 0;669670capture->deviceName = strdup(deviceName);671672detect_v4l2 = try_init_v4l2(capture, deviceName);673674if (detect_v4l2 != 1) {675/* init of the v4l2 device is not OK */676return -1;677}678679/* starting from here, we assume we are in V4L2 mode */680capture->is_v4l2_device = 1;681682capture->v4l2_ctrl_ranges = NULL;683capture->v4l2_ctrl_count = 0;684685/* Scan V4L2 controls */686v4l2_scan_controls(capture);687688if ((capture->cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {689/* Nope. */690fprintf( stderr, "VIDEOIO ERROR: V4L2: device %s is unable to capture video memory.\n",deviceName);691icvCloseCAM_V4L(capture);692return -1;693}694695/* The following code sets the CHANNEL_NUMBER of the video input. Some video sources696have sub "Channel Numbers". For a typical V4L TV capture card, this is usually 1.697I myself am using a simple NTSC video input capture card that uses the value of 1.698If you are not in North America or have a different video standard, you WILL have to change699the following settings and recompile/reinstall. This set of settings is based on700the most commonly encountered input video source types (like my bttv card) */701702if(capture->inp.index > 0) {703CLEAR (capture->inp);704capture->inp.index = CHANNEL_NUMBER;705/* Set only channel number to CHANNEL_NUMBER */706/* V4L2 have a status field from selected video mode */707if (-1 == xioctl (capture->deviceHandle, VIDIOC_ENUMINPUT, &capture->inp))708{709fprintf (stderr, "VIDEOIO ERROR: V4L2: Aren't able to set channel number\n");710icvCloseCAM_V4L (capture);711return -1;712}713} /* End if */714715/* Find Window info */716CLEAR (capture->form);717capture->form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;718719if (-1 == xioctl (capture->deviceHandle, VIDIOC_G_FMT, &capture->form)) {720fprintf( stderr, "VIDEOIO ERROR: V4L2: Could not obtain specifics of capture window.\n\n");721icvCloseCAM_V4L(capture);722return -1;723}724725/* libv4l will convert from any format to V4L2_PIX_FMT_BGR24,726V4L2_PIX_FMT_RGV24, or V4L2_PIX_FMT_YUV420 */727unsigned int requestedPixelFormat;728switch (capture->mode) {729case CV_CAP_MODE_RGB:730requestedPixelFormat = V4L2_PIX_FMT_RGB24;731break;732case CV_CAP_MODE_GRAY:733requestedPixelFormat = V4L2_PIX_FMT_YUV420;734break;735case CV_CAP_MODE_YUYV:736requestedPixelFormat = V4L2_PIX_FMT_YUYV;737break;738default:739requestedPixelFormat = V4L2_PIX_FMT_BGR24;740break;741}742CLEAR (capture->form);743capture->form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;744capture->form.fmt.pix.pixelformat = requestedPixelFormat;745capture->form.fmt.pix.field = V4L2_FIELD_ANY;746capture->form.fmt.pix.width = capture->width;747capture->form.fmt.pix.height = capture->height;748749if (-1 == xioctl (capture->deviceHandle, VIDIOC_S_FMT, &capture->form)) {750fprintf(stderr, "VIDEOIO ERROR: libv4l unable to ioctl S_FMT\n");751return -1;752}753754if (requestedPixelFormat != capture->form.fmt.pix.pixelformat) {755fprintf( stderr, "VIDEOIO ERROR: libv4l unable convert to requested pixfmt\n");756return -1;757}758759/* icvSetVideoSize(capture, DEFAULT_V4L_WIDTH, DEFAULT_V4L_HEIGHT); */760761unsigned int min;762763/* Buggy driver paranoia. */764min = capture->form.fmt.pix.width * 2;765766if (capture->form.fmt.pix.bytesperline < min)767capture->form.fmt.pix.bytesperline = min;768769min = capture->form.fmt.pix.bytesperline * capture->form.fmt.pix.height;770771if (capture->form.fmt.pix.sizeimage < min)772capture->form.fmt.pix.sizeimage = min;773774CLEAR (capture->req);775776unsigned int buffer_number = DEFAULT_V4L_BUFFERS;777778try_again:779780capture->req.count = buffer_number;781capture->req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;782capture->req.memory = V4L2_MEMORY_MMAP;783784if (-1 == xioctl (capture->deviceHandle, VIDIOC_REQBUFS, &capture->req))785{786if (EINVAL == errno)787{788fprintf (stderr, "%s does not support memory mapping\n", deviceName);789} else {790perror ("VIDIOC_REQBUFS");791}792/* free capture, and returns an error code */793icvCloseCAM_V4L (capture);794return -1;795}796797if (capture->req.count < buffer_number)798{799if (buffer_number == 1)800{801fprintf (stderr, "Insufficient buffer memory on %s\n", deviceName);802803/* free capture, and returns an error code */804icvCloseCAM_V4L (capture);805return -1;806} else {807buffer_number--;808fprintf (stderr, "Insufficient buffer memory on %s -- decreaseing buffers\n", deviceName);809810goto try_again;811}812}813814for (n_buffers = 0; n_buffers < capture->req.count; ++n_buffers)815{816struct v4l2_buffer buf;817818CLEAR (buf);819820buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;821buf.memory = V4L2_MEMORY_MMAP;822buf.index = n_buffers;823824if (-1 == xioctl (capture->deviceHandle, VIDIOC_QUERYBUF, &buf)) {825perror ("VIDIOC_QUERYBUF");826827/* free capture, and returns an error code */828icvCloseCAM_V4L (capture);829return -1;830}831832capture->buffers[n_buffers].length = buf.length;833capture->buffers[n_buffers].start =834v4l2_mmap (NULL /* start anywhere */,835buf.length,836PROT_READ | PROT_WRITE /* required */,837MAP_SHARED /* recommended */,838capture->deviceHandle, buf.m.offset);839840if (MAP_FAILED == capture->buffers[n_buffers].start) {841perror ("mmap");842843/* free capture, and returns an error code */844icvCloseCAM_V4L (capture);845return -1;846}847848#ifdef USE_TEMP_BUFFER849if (n_buffers == 0) {850if (capture->buffers[MAX_V4L_BUFFERS].start) {851free(capture->buffers[MAX_V4L_BUFFERS].start);852capture->buffers[MAX_V4L_BUFFERS].start = NULL;853}854855capture->buffers[MAX_V4L_BUFFERS].start = malloc(buf.length);856capture->buffers[MAX_V4L_BUFFERS].length = buf.length;857};858#endif859}860861/* Set up Image data */862cvInitImageHeader( &capture->frame,863cvSize( capture->captureWindow.width,864capture->captureWindow.height ),865IPL_DEPTH_8U, channels_for_mode(capture->mode),866IPL_ORIGIN_TL, 4 );867/* Allocate space for RGBA data */868capture->frame.imageData = (char *)cvAlloc(capture->frame.imageSize);869870return 1;871}; /* End _capture_V4L2 */872873874static int _capture_V4L (CvCaptureCAM_V4L *capture, const char *deviceName)875{876int detect_v4l = 0;877878detect_v4l = try_init_v4l(capture, deviceName);879880if (detect_v4l == -1)881{882fprintf (stderr, "VIDEOIO ERROR: V4L"883": device %s: Unable to open for READ ONLY\n", deviceName);884885return -1;886}887888if (detect_v4l <= 0)889{890fprintf (stderr, "VIDEOIO ERROR: V4L"891": device %s: Unable to query number of channels\n", deviceName);892893return -1;894}895896{897if ((capture->capability.type & VID_TYPE_CAPTURE) == 0) {898/* Nope. */899fprintf( stderr, "VIDEOIO ERROR: V4L: "900"device %s is unable to capture video memory.\n",deviceName);901icvCloseCAM_V4L(capture);902return -1;903}904905}906907908/* The following code sets the CHANNEL_NUMBER of the video input. Some video sources909have sub "Channel Numbers". For a typical V4L TV capture card, this is usually 1.910I myself am using a simple NTSC video input capture card that uses the value of 1.911If you are not in North America or have a different video standard, you WILL have to change912the following settings and recompile/reinstall. This set of settings is based on913the most commonly encountered input video source types (like my bttv card) */914915{916917if(capture->capability.channels>0) {918919struct video_channel selectedChannel;920921selectedChannel.channel=CHANNEL_NUMBER;922if (v4l1_ioctl(capture->deviceHandle, VIDIOCGCHAN , &selectedChannel) != -1) {923/* set the video mode to ( VIDEO_MODE_PAL, VIDEO_MODE_NTSC, VIDEO_MODE_SECAM) */924// selectedChannel.norm = VIDEO_MODE_NTSC;925if (v4l1_ioctl(capture->deviceHandle, VIDIOCSCHAN , &selectedChannel) == -1) {926/* Could not set selected channel - Oh well */927//printf("\n%d, %s not NTSC capable.\n",selectedChannel.channel, selectedChannel.name);928} /* End if */929} /* End if */930} /* End if */931932}933934{935936if(v4l1_ioctl(capture->deviceHandle, VIDIOCGWIN, &capture->captureWindow) == -1) {937fprintf( stderr, "VIDEOIO ERROR: V4L: "938"Could not obtain specifics of capture window.\n\n");939icvCloseCAM_V4L(capture);940return -1;941}942943}944945{946if(v4l1_ioctl(capture->deviceHandle, VIDIOCGPICT, &capture->imageProperties) < 0) {947fprintf( stderr, "VIDEOIO ERROR: V4L: Unable to determine size of incoming image\n");948icvCloseCAM_V4L(capture);949return -1;950}951952int requestedVideoPalette;953int depth;954switch (capture->mode) {955case CV_CAP_MODE_GRAY:956requestedVideoPalette = VIDEO_PALETTE_YUV420;957depth = 8;958break;959case CV_CAP_MODE_YUYV:960requestedVideoPalette = VIDEO_PALETTE_YUYV;961depth = 16;962break;963default:964requestedVideoPalette = VIDEO_PALETTE_RGB24;965depth = 24;966break;967}968capture->imageProperties.depth = depth;969capture->imageProperties.palette = requestedVideoPalette;970if (v4l1_ioctl(capture->deviceHandle, VIDIOCSPICT, &capture->imageProperties) < 0) {971fprintf( stderr, "VIDEOIO ERROR: libv4l unable to ioctl VIDIOCSPICT\n\n");972icvCloseCAM_V4L(capture);973return -1;974}975if (v4l1_ioctl(capture->deviceHandle, VIDIOCGPICT, &capture->imageProperties) < 0) {976fprintf( stderr, "VIDEOIO ERROR: libv4l unable to ioctl VIDIOCGPICT\n\n");977icvCloseCAM_V4L(capture);978return -1;979}980if (capture->imageProperties.palette != requestedVideoPalette) {981fprintf( stderr, "VIDEOIO ERROR: libv4l unable convert to requested pixfmt\n\n");982icvCloseCAM_V4L(capture);983return -1;984}985986}987988{989990v4l1_ioctl(capture->deviceHandle, VIDIOCGMBUF, &capture->memoryBuffer);991capture->memoryMap = (char *)v4l1_mmap(0,992capture->memoryBuffer.size,993PROT_READ | PROT_WRITE,994MAP_SHARED,995capture->deviceHandle,9960);997if (capture->memoryMap == MAP_FAILED) {998fprintf( stderr, "VIDEOIO ERROR: V4L: Mapping Memmory from video source error: %s\n", strerror(errno));999icvCloseCAM_V4L(capture);1000return -1;1001}10021003/* Set up video_mmap structure pointing to this memory mapped area so each image may be1004retrieved from an index value */1005capture->mmaps = (struct video_mmap *)1006(malloc(capture->memoryBuffer.frames * sizeof(struct video_mmap)));1007if (!capture->mmaps) {1008fprintf( stderr, "VIDEOIO ERROR: V4L: Could not memory map video frames.\n");1009icvCloseCAM_V4L(capture);1010return -1;1011}10121013}10141015/* Set up Image data */1016cvInitImageHeader( &capture->frame,1017cvSize( capture->captureWindow.width,1018capture->captureWindow.height ),1019IPL_DEPTH_8U, channels_for_mode(capture->mode),1020IPL_ORIGIN_TL, 4 );1021/* Allocate space for RGBA data */1022capture->frame.imageData = (char *)cvAlloc(capture->frame.imageSize);10231024return 1;1025}; /* End _capture_V4L */10261027static CvCaptureCAM_V4L * icvCaptureFromCAM_V4L (int index)1028{1029static int autoindex;1030autoindex = 0;10311032char deviceName[MAX_DEVICE_DRIVER_NAME];10331034if (!numCameras)1035icvInitCapture_V4L(); /* Haven't called icvInitCapture yet - do it now! */1036if (!numCameras)1037return NULL; /* Are there any /dev/video input sources? */10381039//search index in indexList1040if ( (index>-1) && ! ((1 << index) & indexList) )1041{1042fprintf( stderr, "VIDEOIO ERROR: V4L: index %d is not correct!\n",index);1043return NULL; /* Did someone ask for not correct video source number? */1044}10451046/* Select camera, or rather, V4L video source */1047if (index<0) { // Asking for the first device available1048for (; autoindex<MAX_CAMERAS;autoindex++)1049if (indexList & (1<<autoindex))1050break;1051if (autoindex==MAX_CAMERAS)1052return NULL;1053index=autoindex;1054autoindex++;// i can recall icvOpenCAM_V4l with index=-1 for next camera1055}1056/* Print the CameraNumber at the end of the string with a width of one character */1057sprintf(deviceName, "/dev/video%1d", index);1058return icvCaptureFromCAM_V4L(deviceName);1059}10601061static CvCaptureCAM_V4L * icvCaptureFromCAM_V4L (const char* deviceName)1062{1063/* Allocate memory for this humongus CvCaptureCAM_V4L structure that contains ALL1064the handles for V4L processing */1065CvCaptureCAM_V4L * capture = (CvCaptureCAM_V4L*)cvAlloc(sizeof(CvCaptureCAM_V4L));1066if (!capture) {1067fprintf( stderr, "VIDEOIO ERROR: V4L: Could not allocate memory for capture process.\n");1068return NULL;1069}10701071#ifdef USE_TEMP_BUFFER1072capture->buffers[MAX_V4L_BUFFERS].start = NULL;1073#endif10741075/* w/o memset some parts aren't initialized - AKA: Fill it with zeros so it is clean */1076memset(capture,0,sizeof(CvCaptureCAM_V4L));10771078/* Present the routines needed for V4L functionality. They are inserted as part of1079the standard set of cv calls promoting transparency. "Vector Table" insertion. */1080capture->FirstCapture = 1;10811082/* set the default size */1083capture->width = DEFAULT_V4L_WIDTH;1084capture->height = DEFAULT_V4L_HEIGHT;10851086if (_capture_V4L2 (capture, deviceName) == -1) {1087icvCloseCAM_V4L(capture);1088capture->is_v4l2_device = 0;1089if (_capture_V4L (capture, deviceName) == -1) {1090icvCloseCAM_V4L(capture);1091return NULL;1092}1093} else {1094capture->is_v4l2_device = 1;1095}10961097capture->returnFrame = true;10981099return capture;1100}; /* End icvOpenCAM_V4L */11011102#ifdef HAVE_CAMV4L211031104static int read_frame_v4l2(CvCaptureCAM_V4L* capture) {1105struct v4l2_buffer buf;11061107CLEAR (buf);11081109buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1110buf.memory = V4L2_MEMORY_MMAP;11111112if (-1 == xioctl (capture->deviceHandle, VIDIOC_DQBUF, &buf)) {1113switch (errno) {1114case EAGAIN:1115return 0;11161117case EIO:1118/* Could ignore EIO, see spec. */11191120/* fall through */11211122default:1123/* display the error and stop processing */1124capture->returnFrame = false;1125perror ("VIDIOC_DQBUF");1126return -1;1127}1128}11291130assert(buf.index < capture->req.count);11311132#ifdef USE_TEMP_BUFFER1133memcpy(capture->buffers[MAX_V4L_BUFFERS].start,1134capture->buffers[buf.index].start,1135capture->buffers[MAX_V4L_BUFFERS].length );1136capture->bufferIndex = MAX_V4L_BUFFERS;1137//printf("got data in buff %d, len=%d, flags=0x%X, seq=%d, used=%d)\n",1138// buf.index, buf.length, buf.flags, buf.sequence, buf.bytesused);1139#else1140capture->bufferIndex = buf.index;1141#endif11421143if (-1 == xioctl (capture->deviceHandle, VIDIOC_QBUF, &buf))1144perror ("VIDIOC_QBUF");11451146//set timestamp in capture struct to be timestamp of most recent frame1147/** where timestamps refer to the instant the field or frame was received by the driver, not the capture time*/1148capture->timestamp = buf.timestamp; //printf( "timestamp update done \n");1149capture->sequence = buf.sequence;11501151return 1;1152}11531154static int mainloop_v4l2(CvCaptureCAM_V4L* capture) {1155unsigned int count;11561157count = 1;11581159while (count-- > 0) {1160for (;;) {1161fd_set fds;1162struct timeval tv;1163int r;11641165FD_ZERO (&fds);1166FD_SET (capture->deviceHandle, &fds);11671168/* Timeout. */1169tv.tv_sec = 10;1170tv.tv_usec = 0;11711172r = select (capture->deviceHandle+1, &fds, NULL, NULL, &tv);11731174if (-1 == r) {1175if (EINTR == errno)1176continue;11771178perror ("select");1179}11801181if (0 == r) {1182fprintf (stderr, "select timeout\n");11831184/* end the infinite loop */1185break;1186}11871188int returnCode=read_frame_v4l2(capture);1189if (returnCode == -1)1190return -1;1191if (returnCode == 1)1192return 0;1193}1194}1195return 0;1196}11971198static int icvGrabFrameCAM_V4L(CvCaptureCAM_V4L* capture) {11991200if (capture->FirstCapture) {1201/* Some general initialization must take place the first time through */12021203/* This is just a technicality, but all buffers must be filled up before any1204staggered SYNC is applied. SO, filler up. (see V4L HowTo) */12051206if (capture->is_v4l2_device == 1)1207{12081209for (capture->bufferIndex = 0;1210capture->bufferIndex < ((int)capture->req.count);1211++capture->bufferIndex)1212{12131214struct v4l2_buffer buf;12151216CLEAR (buf);12171218buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1219buf.memory = V4L2_MEMORY_MMAP;1220buf.index = (unsigned long)capture->bufferIndex;12211222if (-1 == xioctl (capture->deviceHandle, VIDIOC_QBUF, &buf)) {1223perror ("VIDIOC_QBUF");1224return 0;1225}1226}12271228/* enable the streaming */1229capture->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1230if (-1 == xioctl (capture->deviceHandle, VIDIOC_STREAMON,1231&capture->type)) {1232/* error enabling the stream */1233perror ("VIDIOC_STREAMON");1234return 0;1235}1236} else1237{12381239for (capture->bufferIndex = 0;1240capture->bufferIndex < (capture->memoryBuffer.frames-1);1241++capture->bufferIndex) {12421243capture->mmaps[capture->bufferIndex].frame = capture->bufferIndex;1244capture->mmaps[capture->bufferIndex].width = capture->captureWindow.width;1245capture->mmaps[capture->bufferIndex].height = capture->captureWindow.height;1246capture->mmaps[capture->bufferIndex].format = capture->imageProperties.palette;12471248if (v4l1_ioctl(capture->deviceHandle, VIDIOCMCAPTURE, &capture->mmaps[capture->bufferIndex]) == -1) {1249fprintf( stderr, "VIDEOIO ERROR: V4L: Initial Capture Error: Unable to load initial memory buffers.\n");1250return 0;1251}1252}12531254}12551256/* preparation is ok */1257capture->FirstCapture = 0;1258}12591260if (capture->is_v4l2_device == 1)1261{12621263if(mainloop_v4l2(capture) == -1) return 0;12641265} else1266{12671268capture->mmaps[capture->bufferIndex].frame = capture->bufferIndex;1269capture->mmaps[capture->bufferIndex].width = capture->captureWindow.width;1270capture->mmaps[capture->bufferIndex].height = capture->captureWindow.height;1271capture->mmaps[capture->bufferIndex].format = capture->imageProperties.palette;12721273if (v4l1_ioctl (capture->deviceHandle, VIDIOCMCAPTURE,1274&capture->mmaps[capture->bufferIndex]) == -1) {1275/* capture is on the way, so just exit */1276return 1;1277}12781279++capture->bufferIndex;1280if (capture->bufferIndex == capture->memoryBuffer.frames) {1281capture->bufferIndex = 0;1282}12831284}12851286return(1);1287}12881289static IplImage* icvRetrieveFrameCAM_V4L( CvCaptureCAM_V4L* capture, int) {12901291if (capture->is_v4l2_device == 0)1292{12931294/* [FD] this really belongs here */1295if (v4l1_ioctl(capture->deviceHandle, VIDIOCSYNC, &capture->mmaps[capture->bufferIndex].frame) == -1) {1296fprintf( stderr, "VIDEOIO ERROR: V4L: Could not SYNC to video stream. %s\n", strerror(errno));1297}12981299}13001301/* Now get what has already been captured as a IplImage return */13021303/* First, reallocate imageData if the frame size changed */13041305if (capture->is_v4l2_device == 1)1306{13071308if(((unsigned long)capture->frame.width != capture->form.fmt.pix.width)1309|| ((unsigned long)capture->frame.height != capture->form.fmt.pix.height)) {1310cvFree(&capture->frame.imageData);1311cvInitImageHeader( &capture->frame,1312cvSize( capture->form.fmt.pix.width,1313capture->form.fmt.pix.height ),1314IPL_DEPTH_8U, channels_for_mode(capture->mode),1315IPL_ORIGIN_TL, 4 );1316capture->frame.imageData = (char *)cvAlloc(capture->frame.imageSize);1317}13181319} else1320{13211322if((capture->frame.width != capture->mmaps[capture->bufferIndex].width)1323|| (capture->frame.height != capture->mmaps[capture->bufferIndex].height)) {1324cvFree(&capture->frame.imageData);1325cvInitImageHeader( &capture->frame,1326cvSize( capture->captureWindow.width,1327capture->captureWindow.height ),1328IPL_DEPTH_8U, channels_for_mode(capture->mode),1329IPL_ORIGIN_TL, 4 );1330capture->frame.imageData = (char *)cvAlloc(capture->frame.imageSize);1331}13321333}13341335if (capture->is_v4l2_device == 1)1336{13371338if(capture->buffers[capture->bufferIndex].start){1339memcpy((char *)capture->frame.imageData,1340(char *)capture->buffers[capture->bufferIndex].start,1341capture->frame.imageSize);1342}13431344} else1345#endif /* HAVE_CAMV4L2 */1346{13471348switch(capture->imageProperties.palette) {1349case VIDEO_PALETTE_RGB24:1350case VIDEO_PALETTE_YUV420:1351case VIDEO_PALETTE_YUYV:1352memcpy((char *)capture->frame.imageData,1353(char *)(capture->memoryMap + capture->memoryBuffer.offsets[capture->bufferIndex]),1354capture->frame.imageSize);1355break;1356default:1357fprintf( stderr,1358"VIDEOIO ERROR: V4L: Cannot convert from palette %d to mode %d\n",1359capture->imageProperties.palette,1360capture->mode);1361return 0;1362}13631364}13651366if (capture->returnFrame)1367return(&capture->frame);1368else1369return 0;1370}13711372static int zeroPropertyQuietly(CvCaptureCAM_V4L* capture, int property_id, int value)1373{1374struct v4l2_control c;1375int v4l2_min;1376int v4l2_max;1377//we need to make sure that the autocontrol is switch off, if available.1378capture->control.id = property_id;1379v4l2_min = v4l2_get_ctrl_min(capture, capture->control.id);1380v4l2_max = v4l2_get_ctrl_max(capture, capture->control.id);1381if ( !((v4l2_min == -1) && (v4l2_max == -1)) ) {1382//autocontrol capability is supported, switch it off.1383c.id = capture->control.id;1384c.value = value;1385if( v4l2_ioctl(capture->deviceHandle, VIDIOC_S_CTRL, &c) != 0 ){1386if (errno != ERANGE) {1387fprintf(stderr, "VIDEOIO ERROR: V4L2: Failed to set autocontrol \"%d\": %s (value %d)\n", c.id, strerror(errno), c.value);1388return -1;1389}1390}1391}//lack of support should not be considerred an error.1392return 0;1393}13941395/* TODO: review this adaptation */1396static double icvGetPropertyCAM_V4L (CvCaptureCAM_V4L* capture,1397int property_id ) {1398char name[32];1399int is_v4l2_device = 0;1400/* initialize the control structure */1401switch (property_id) {1402case CV_CAP_PROP_FRAME_WIDTH:1403case CV_CAP_PROP_FRAME_HEIGHT:1404CLEAR (capture->form);1405capture->form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1406if (-1 == xioctl (capture->deviceHandle, VIDIOC_G_FMT, &capture->form)) {1407/* display an error message, and return an error code */1408perror ("VIDIOC_G_FMT");1409if (v4l1_ioctl (capture->deviceHandle, VIDIOCGWIN, &capture->captureWindow) < 0) {1410fprintf (stderr, " ERROR: V4L: Unable to determine size of incoming image\n");1411icvCloseCAM_V4L(capture);1412return -1;1413} else {1414int retval = (property_id == CV_CAP_PROP_FRAME_WIDTH)?capture->captureWindow.width:capture->captureWindow.height;1415return retval / 0xFFFF;1416}1417}1418return (property_id == CV_CAP_PROP_FRAME_WIDTH)?capture->form.fmt.pix.width:capture->form.fmt.pix.height;14191420case CV_CAP_PROP_POS_MSEC:1421if (capture->FirstCapture) {1422return 0;1423} else {1424//would be maximally numerically stable to cast to convert as bits, but would also be counterintuitive to decode1425return 1000 * capture->timestamp.tv_sec + ((double) capture->timestamp.tv_usec) / 1000;1426}1427break;14281429case CV_CAP_PROP_POS_FRAMES:1430return capture->sequence;1431break;14321433case CV_CAP_PROP_FPS: {1434struct v4l2_streamparm sp;1435memset (&sp, 0, sizeof(struct v4l2_streamparm));1436sp.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1437if (xioctl (capture->deviceHandle, VIDIOC_G_PARM, &sp) < 0){1438fprintf(stderr, "VIDEOIO ERROR: V4L: Unable to get camera FPS\n");1439return (double) -1;1440}14411442// this is the captureable, not per say what you'll get..1443double framesPerSec = sp.parm.capture.timeperframe.denominator / (double) sp.parm.capture.timeperframe.numerator ;1444return framesPerSec;1445}1446break;144714481449case CV_CAP_PROP_MODE:1450return capture->mode;1451break;1452case CV_CAP_PROP_BRIGHTNESS:1453sprintf(name, "Brightness");1454capture->control.id = V4L2_CID_BRIGHTNESS;1455break;1456case CV_CAP_PROP_CONTRAST:1457sprintf(name, "Contrast");1458capture->control.id = V4L2_CID_CONTRAST;1459break;1460case CV_CAP_PROP_SATURATION:1461sprintf(name, "Saturation");1462capture->control.id = V4L2_CID_SATURATION;1463break;1464case CV_CAP_PROP_HUE:1465sprintf(name, "Hue");1466capture->control.id = V4L2_CID_HUE;1467break;1468case CV_CAP_PROP_GAIN:1469sprintf(name, "Gain");1470capture->control.id = V4L2_CID_GAIN;1471break;1472case CV_CAP_PROP_EXPOSURE:1473sprintf(name, "Exposure");1474capture->control.id = V4L2_CID_EXPOSURE_ABSOLUTE;1475break;1476case CV_CAP_PROP_FOCUS:1477sprintf(name, "Focus");1478capture->control.id = V4L2_CID_FOCUS_ABSOLUTE;1479break;1480case CV_CAP_PROP_AUTOFOCUS:1481sprintf(name, "Autofocus");1482capture->control.id = V4L2_CID_FOCUS_AUTO;1483default:1484sprintf(name, "<unknown property string>");1485capture->control.id = property_id;1486}14871488if(v4l2_ioctl(capture->deviceHandle, VIDIOC_G_CTRL, &capture->control) == 0) {1489/* all went well */1490is_v4l2_device = 1;1491} else {1492fprintf(stderr, "VIDEOIO ERROR: V4L2: Unable to get property %s(%u) - %s\n", name, capture->control.id, strerror(errno));1493}14941495if (is_v4l2_device == 1) {1496/* get the min/max values */1497int v4l2_min = v4l2_get_ctrl_min(capture, capture->control.id);1498int v4l2_max = v4l2_get_ctrl_max(capture, capture->control.id);14991500if ((v4l2_min == -1) && (v4l2_max == -1)) {1501fprintf(stderr, "VIDEOIO ERROR: V4L2: Property %s(%u) not supported by device\n", name, property_id);1502return -1;1503}15041505/* all was OK, so convert to 0.0 - 1.0 range, and return the value */1506return ((float)capture->control.value - v4l2_min) / (v4l2_max - v4l2_min);15071508} else {1509/* TODO: review this section */1510int retval = -1;15111512switch (property_id) {1513case CV_CAP_PROP_BRIGHTNESS:1514retval = capture->imageProperties.brightness;1515break;1516case CV_CAP_PROP_CONTRAST:1517retval = capture->imageProperties.contrast;1518break;1519case CV_CAP_PROP_SATURATION:1520retval = capture->imageProperties.colour;1521break;1522case CV_CAP_PROP_HUE:1523retval = capture->imageProperties.hue;1524break;1525case CV_CAP_PROP_GAIN:1526fprintf(stderr, "VIDEOIO ERROR: V4L: Gain control in V4L is not supported\n");1527return -1;1528break;1529case CV_CAP_PROP_EXPOSURE:1530fprintf(stderr, "VIDEOIO ERROR: V4L: Exposure control in V4L is not supported\n");1531return -1;1532break;1533}15341535if (retval == -1) {1536/* there was a problem */1537return -1;1538}1539/* all was OK, so convert to 0.0 - 1.0 range, and return the value */1540return float (retval) / 0xFFFF;1541}1542}15431544static int icvSetVideoSize( CvCaptureCAM_V4L* capture, int w, int h) {15451546if (capture->is_v4l2_device == 1)1547{1548char deviceName[MAX_DEVICE_DRIVER_NAME];1549sprintf(deviceName, "%s", capture->deviceName);1550icvCloseCAM_V4L(capture);1551_capture_V4L2(capture, deviceName);15521553int cropHeight;1554int cropWidth;1555switch (capture->mode) {1556case CV_CAP_MODE_GRAY:1557cropHeight = h*8;1558cropWidth = w*8;1559break;1560case CV_CAP_MODE_YUYV:1561cropHeight = h*16;1562cropWidth = w*16;1563break;1564default:1565cropHeight = h*24;1566cropWidth = w*24;1567break;1568}1569CLEAR (capture->crop);1570capture->crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1571capture->crop.c.left = 0;1572capture->crop.c.top = 0;1573capture->crop.c.height = cropHeight;1574capture->crop.c.width = cropWidth;15751576/* set the crop area, but don't exit if the device don't support croping */1577xioctl (capture->deviceHandle, VIDIOC_S_CROP, &capture->crop);15781579CLEAR (capture->form);1580capture->form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;15811582/* read the current setting, mainly to retrieve the pixelformat information */1583xioctl (capture->deviceHandle, VIDIOC_G_FMT, &capture->form);15841585/* set the values we want to change */1586capture->form.fmt.pix.width = w;1587capture->form.fmt.pix.height = h;1588capture->form.fmt.win.chromakey = 0;1589capture->form.fmt.win.field = V4L2_FIELD_ANY;1590capture->form.fmt.win.clips = 0;1591capture->form.fmt.win.clipcount = 0;1592capture->form.fmt.pix.field = V4L2_FIELD_ANY;15931594/* ask the device to change the size1595* don't test if the set of the size is ok, because some device1596* don't allow changing the size, and we will get the real size1597* later */1598xioctl (capture->deviceHandle, VIDIOC_S_FMT, &capture->form);15991600/* try to set framerate to 30 fps */16011602struct v4l2_streamparm setfps;1603memset (&setfps, 0, sizeof(struct v4l2_streamparm));16041605setfps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1606setfps.parm.capture.timeperframe.numerator = 1;1607setfps.parm.capture.timeperframe.denominator = 30;16081609xioctl (capture->deviceHandle, VIDIOC_S_PARM, &setfps);161016111612/* we need to re-initialize some things, like buffers, because the size has1613* changed */1614capture->FirstCapture = 1;16151616/* Get window info again, to get the real value */1617if (-1 == xioctl (capture->deviceHandle, VIDIOC_G_FMT, &capture->form))1618{1619fprintf(stderr, "VIDEOIO ERROR: V4L/V4L2: Could not obtain specifics of capture window.\n\n");16201621icvCloseCAM_V4L(capture);16221623return 0;1624}16251626return 0;16271628} else1629{16301631if (capture==0) return 0;1632if (w>capture->capability.maxwidth) {1633w=capture->capability.maxwidth;1634}1635if (h>capture->capability.maxheight) {1636h=capture->capability.maxheight;1637}16381639capture->captureWindow.width=w;1640capture->captureWindow.height=h;16411642if (ioctl(capture->deviceHandle, VIDIOCSWIN, &capture->captureWindow) < 0) {1643icvCloseCAM_V4L(capture);1644return 0;1645}16461647if (ioctl(capture->deviceHandle, VIDIOCGWIN, &capture->captureWindow) < 0) {1648icvCloseCAM_V4L(capture);1649return 0;1650}16511652capture->FirstCapture = 1;16531654}16551656return 0;16571658}16591660static int icvSetControl (CvCaptureCAM_V4L* capture, int property_id, double value) {1661struct v4l2_control c;1662__s32 ctrl_value;1663char name[32];1664int is_v4l2 = 1;1665int v4l2_min = 0;1666int v4l2_max = 255;1667if (capture->v4l2_ctrl_ranges == NULL) {1668v4l2_scan_controls(capture);1669}16701671CLEAR (capture->control);1672CLEAR (capture->queryctrl);16731674/* get current values */1675switch (property_id) {1676case CV_CAP_PROP_BRIGHTNESS:1677sprintf(name, "Brightness");1678capture->control.id = V4L2_CID_BRIGHTNESS;1679break;1680case CV_CAP_PROP_CONTRAST:1681sprintf(name, "Contrast");1682capture->control.id = V4L2_CID_CONTRAST;1683break;1684case CV_CAP_PROP_SATURATION:1685sprintf(name, "Saturation");1686capture->control.id = V4L2_CID_SATURATION;1687break;1688case CV_CAP_PROP_HUE:1689sprintf(name, "Hue");1690capture->control.id = V4L2_CID_HUE;1691break;1692case CV_CAP_PROP_GAIN:1693sprintf(name, "Gain");1694capture->control.id = V4L2_CID_GAIN;1695break;1696case CV_CAP_PROP_EXPOSURE:1697//we need to make sure that the autoexposure is switch off, if available.1698zeroPropertyQuietly(capture, V4L2_CID_EXPOSURE_AUTO, V4L2_EXPOSURE_MANUAL);1699//now get the manual exposure value1700sprintf(name, "Exposure");1701capture->control.id = V4L2_CID_EXPOSURE_ABSOLUTE;1702break;1703case CV_CAP_PROP_FOCUS:1704//we need to make sure that the autofocus is switch off, if available.1705zeroPropertyQuietly(capture, V4L2_CID_FOCUS_AUTO, 0 /*off*/);1706//now set the manual focus1707sprintf(name, "Focus");1708capture->control.id = V4L2_CID_FOCUS_ABSOLUTE;1709break;1710case CV_CAP_PROP_AUTOFOCUS:1711sprintf(name, "Autofocus");1712capture->control.id = V4L2_CID_FOCUS_AUTO;1713default:1714sprintf(name, "<unknown property string>");1715capture->control.id = property_id;1716}17171718v4l2_min = v4l2_get_ctrl_min(capture, capture->control.id);1719v4l2_max = v4l2_get_ctrl_max(capture, capture->control.id);17201721if ((v4l2_min == -1) && (v4l2_max == -1)) {1722fprintf(stderr, "VIDEOIO ERROR: V4L: Property %s(%u) not supported by device\n", name, property_id);1723return -1;1724}17251726if(v4l2_ioctl(capture->deviceHandle, VIDIOC_G_CTRL, &capture->control) == 0) {1727/* all went well */1728} else {1729fprintf(stderr, "VIDEOIO ERROR: V4L2: Unable to get property %s(%u) - %s\n", name, capture->control.id, strerror(errno));1730}17311732if (v4l2_max != 0) {1733double val = value;1734if (value < 0.0) {1735val = 0.0;1736} else if (value > 1.0) {1737val = 1.0;1738}1739ctrl_value = val * (double)(v4l2_max - v4l2_min) + v4l2_min;1740} else {1741ctrl_value = v4l2_get_ctrl_default(capture, capture->control.id) * (double)(v4l2_max - v4l2_min) + v4l2_min;1742}17431744/* try and set value as if it was a v4l2 device */1745c.id = capture->control.id;1746c.value = ctrl_value;1747if (v4l2_ioctl(capture->deviceHandle, VIDIOC_S_CTRL, &c) != 0) {1748/* The driver may clamp the value or return ERANGE, ignored here */1749if (errno != ERANGE) {1750fprintf(stderr, "VIDEOIO ERROR: V4L2: Failed to set control \"%d\": %s (value %d)\n", c.id, strerror(errno), c.value);1751is_v4l2 = 0;1752} else {1753return 0;1754}1755} else {1756return 0;1757}17581759if (is_v4l2 == 0) { /* use v4l1_ioctl */1760fprintf(stderr, "VIDEOIO WARNING: Setting property %u through v4l2 failed. Trying with v4l1.\n", c.id);1761int v4l_value;1762/* scale the value to the wanted integer one */1763v4l_value = (int)(0xFFFF * value);17641765switch (property_id) {1766case CV_CAP_PROP_BRIGHTNESS:1767capture->imageProperties.brightness = v4l_value;1768break;1769case CV_CAP_PROP_CONTRAST:1770capture->imageProperties.contrast = v4l_value;1771break;1772case CV_CAP_PROP_SATURATION:1773capture->imageProperties.colour = v4l_value;1774break;1775case CV_CAP_PROP_HUE:1776capture->imageProperties.hue = v4l_value;1777break;1778case CV_CAP_PROP_GAIN:1779fprintf(stderr, "VIDEOIO ERROR: V4L: Gain control in V4L is not supported\n");1780return -1;1781case CV_CAP_PROP_EXPOSURE:1782fprintf(stderr, "VIDEOIO ERROR: V4L: Exposure control in V4L is not supported\n");1783return -1;1784default:1785fprintf(stderr, "VIDEOIO ERROR: V4L: property #%d is not supported\n", property_id);1786return -1;1787}17881789if (v4l1_ioctl(capture->deviceHandle, VIDIOCSPICT, &capture->imageProperties) < 0){1790fprintf(stderr, "VIDEOIO ERROR: V4L: Unable to set video information\n");1791icvCloseCAM_V4L(capture);1792return -1;1793}1794}17951796/* all was OK */1797return 0;1798}17991800static int icvSetPropertyCAM_V4L(CvCaptureCAM_V4L* capture, int property_id, double value){1801static int width = 0, height = 0;1802int retval;18031804/* initialization */1805retval = 0;18061807/* two subsequent calls setting WIDTH and HEIGHT will change1808the video size */1809/* the first one will return an error, though. */18101811switch (property_id) {1812case CV_CAP_PROP_FRAME_WIDTH:1813width = cvRound(value);1814capture->width = width;1815if(width !=0 && height != 0) {1816retval = icvSetVideoSize( capture, width, height);1817width = height = 0;1818}1819break;1820case CV_CAP_PROP_FRAME_HEIGHT:1821height = cvRound(value);1822capture->height = height;1823if(width !=0 && height != 0) {1824retval = icvSetVideoSize( capture, width, height);1825width = height = 0;1826}1827break;1828case CV_CAP_PROP_MODE:1829int mode;1830mode = cvRound(value);1831if (capture->mode != mode) {1832switch (mode) {1833case CV_CAP_MODE_BGR:1834case CV_CAP_MODE_RGB:1835case CV_CAP_MODE_GRAY:1836case CV_CAP_MODE_YUYV:1837capture->mode = mode;1838/* recreate the capture buffer for the same output resolution1839but a different pixel format */1840retval = icvSetVideoSize(capture, capture->width, capture->height);1841break;1842default:1843fprintf(stderr, "VIDEOIO ERROR: V4L/V4L2: Unsupported mode: %d\n", mode);1844retval=0;1845break;1846}1847}1848break;1849case CV_CAP_PROP_FPS:1850struct v4l2_streamparm setfps;1851memset (&setfps, 0, sizeof(struct v4l2_streamparm));1852setfps.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1853setfps.parm.capture.timeperframe.numerator = 1;1854setfps.parm.capture.timeperframe.denominator = value;1855if (xioctl (capture->deviceHandle, VIDIOC_S_PARM, &setfps) < 0){1856fprintf(stderr, "VIDEOIO ERROR: V4L: Unable to set camera FPS\n");1857retval=0;1858}1859break;1860default:1861retval = icvSetControl(capture, property_id, value);1862}18631864/* return the the status */1865return retval;1866}18671868static void icvCloseCAM_V4L( CvCaptureCAM_V4L* capture ){1869/* Deallocate space - Hopefully, no leaks */1870if (capture) {1871v4l2_free_ranges(capture);1872if (capture->is_v4l2_device == 0) {1873if (capture->mmaps) {1874free(capture->mmaps);1875}1876if (capture->memoryMap) {1877v4l1_munmap(capture->memoryMap, capture->memoryBuffer.size);1878}1879if (capture->deviceHandle != -1) {1880v4l1_close(capture->deviceHandle);1881}1882} else {1883capture->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1884if (xioctl(capture->deviceHandle, VIDIOC_STREAMOFF, &capture->type) < 0) {1885perror ("Unable to stop the stream.");1886}1887for (unsigned int n_buffers2 = 0; n_buffers2 < capture->req.count; ++n_buffers2) {1888if (-1 == v4l2_munmap (capture->buffers[n_buffers2].start, capture->buffers[n_buffers2].length)) {1889perror ("munmap");1890}1891}18921893if (capture->deviceHandle != -1) {1894v4l2_close(capture->deviceHandle);1895}1896}18971898if (capture->frame.imageData)1899cvFree(&capture->frame.imageData);19001901#ifdef USE_TEMP_BUFFER1902if (capture->buffers[MAX_V4L_BUFFERS].start) {1903free(capture->buffers[MAX_V4L_BUFFERS].start);1904capture->buffers[MAX_V4L_BUFFERS].start = NULL;1905}1906#endif19071908free(capture->deviceName);1909capture->deviceName = NULL;1910//v4l2_free_ranges(capture);1911//cvFree((void **)capture);1912}1913};191419151916class CvCaptureCAM_V4L_CPP : CvCapture1917{1918public:1919CvCaptureCAM_V4L_CPP() { captureV4L = 0; }1920virtual ~CvCaptureCAM_V4L_CPP() { close(); }19211922virtual bool open( int index );1923virtual bool open( const char* deviceName );1924virtual void close();19251926virtual double getProperty(int) const CV_OVERRIDE;1927virtual bool setProperty(int, double) CV_OVERRIDE;1928virtual bool grabFrame() CV_OVERRIDE;1929virtual IplImage* retrieveFrame(int) CV_OVERRIDE;19301931int getCaptureDomain() /*const*/ CV_OVERRIDE { return cv::CAP_V4L; }1932protected:19331934CvCaptureCAM_V4L* captureV4L;1935};19361937bool CvCaptureCAM_V4L_CPP::open( int index )1938{1939close();1940captureV4L = icvCaptureFromCAM_V4L(index);1941return captureV4L != 0;1942}19431944bool CvCaptureCAM_V4L_CPP::open( const char* deviceName )1945{1946close();1947captureV4L = icvCaptureFromCAM_V4L(deviceName);1948return captureV4L != 0;1949}19501951void CvCaptureCAM_V4L_CPP::close()1952{1953if( captureV4L )1954{1955icvCloseCAM_V4L( captureV4L );1956cvFree( &captureV4L );1957}1958}19591960bool CvCaptureCAM_V4L_CPP::grabFrame()1961{1962return captureV4L ? icvGrabFrameCAM_V4L( captureV4L ) != 0 : false;1963}19641965IplImage* CvCaptureCAM_V4L_CPP::retrieveFrame(int)1966{1967return captureV4L ? icvRetrieveFrameCAM_V4L( captureV4L, 0 ) : 0;1968}19691970double CvCaptureCAM_V4L_CPP::getProperty( int propId ) const1971{1972return captureV4L ? icvGetPropertyCAM_V4L( captureV4L, propId ) : 0.0;1973}19741975bool CvCaptureCAM_V4L_CPP::setProperty( int propId, double value )1976{1977return captureV4L ? icvSetPropertyCAM_V4L( captureV4L, propId, value ) != 0 : false;1978}19791980CvCapture* cvCreateCameraCapture_V4L( int index )1981{1982CvCaptureCAM_V4L_CPP* capture = new CvCaptureCAM_V4L_CPP;19831984if( capture->open( index ))1985return (CvCapture*)capture;19861987delete capture;1988return 0;1989}19901991CvCapture* cvCreateCameraCapture_V4L( const char * deviceName )1992{1993CvCaptureCAM_V4L_CPP* capture = new CvCaptureCAM_V4L_CPP;19941995if( capture->open( deviceName ))1996return (CvCapture*)capture;19971998delete capture;1999return 0;2000}20012002#endif200320042005