source: flair-src/trunk/lib/FlairSensorActuator/src/V4LCamera.cpp@ 351

Last change on this file since 351 was 351, checked in by Sanahuja Guillaume, 4 years ago

update v4l

File size: 13.8 KB
Line 
1// %flair:license{
2// This file is part of the Flair framework distributed under the
3// CECILL-C License, Version 1.0.
4// %flair:license}
5// created: 2014/07/17
6// filename: V4LCamera.cpp
7//
8// author: Guillaume Sanahuja
9// Copyright Heudiasyc UMR UTC/CNRS 7253
10//
11// version: $Id: $
12//
13// purpose: base class for V4l camera
14//
15//
16/*********************************************************************/
17
18#include "V4LCamera.h"
19#include <GroupBox.h>
20#include <DoubleSpinBox.h>
21#include <CheckBox.h>
22#include <Label.h>
23#include <Image.h>
24#include <FrameworkManager.h>
25#include <fcntl.h>
26//#include <linux/videodev2.h>
27#include <sys/ioctl.h>
28#include <unistd.h>
29#include <cstring>
30#include <sys/mman.h>
31#include <VisionFilter.h>
32
33using std::string;
34using namespace flair::core;
35using namespace flair::gui;
36
37namespace flair {
38namespace sensor {
39
40V4LCamera::V4LCamera(string name,uint8_t camera_index, uint16_t width, uint16_t height,
41 Image::Type::Format format, uint8_t priority)
42 : Thread(getFrameworkManager(), name, priority),
43 Camera(name, width, height, format) {
44
45 string deviceName="/dev/video"+std::to_string(camera_index);
46 device = open(deviceName.c_str(), O_RDWR | O_NONBLOCK);
47 if (device == -1) {
48 Thread::Err("Cannot open %s\n",deviceName.c_str());
49 } else {
50 Printf("V4LCamera %s, opened %s\n",name.c_str(),deviceName.c_str());
51 }
52
53 if(format == Image::Type::Format::UYVY) {
54 if(Init(width,height,V4L2_PIX_FMT_UYVY) == -1) {
55 Thread::Err("initialisation failed\n");
56 }
57 } else if (format == Image::Type::Format::YUYV) {
58 if(Init(width,height,V4L2_PIX_FMT_YUYV) == -1) {
59 Thread::Err("initialisation failed\n");
60 }
61 } else {
62 Thread::Err("format not supported\n");
63 }
64
65 //todo: better handling of detection, only neeeded for omap/dm
66 //also in run, copy from v4l to cmem is not necessary if not using cmem...
67#ifdef ARMV7A
68 useMemoryUsrPtr=true;
69#else
70 useMemoryUsrPtr=false;
71#endif
72 if(useMemoryUsrPtr) {
73 AllocUserBuffers();
74 } else {
75 AllocV4LBuffers();
76 }
77
78 for (int i=0;i < nbBuffers;i++) {
79 QueueBuffer(i);
80 }
81
82 /* enable the streaming */
83 v4l2_buf_type type;
84 type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
85 if (-1 == xioctl (device, VIDIOC_STREAMON,&type)) {
86 Thread::Err("VIDIOC_STREAMON error\n");
87 }
88
89 // ground station
90 gain = new DoubleSpinBox(GetGroupBox()->NewRow(), "gain:", 0, 1, 0.1);
91 exposure = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "exposure:", 0,1, 0.1);
92 bright = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "bright:", 0, 1, 0.1);
93 contrast = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "contrast:", 0,1, 0.1);
94 hue = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "hue:", 0, 1, 0.1);
95 sharpness = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "sharpness:", 0, 1, 0.1);
96 sat = new DoubleSpinBox(GetGroupBox()->LastRowLastCol(), "saturation:", 0, 1,0.1);
97 autogain = new CheckBox(GetGroupBox()->NewRow(), "autogain:");
98 autoexposure = new CheckBox(GetGroupBox()->LastRowLastCol(), "autoexposure:");
99 awb = new CheckBox(GetGroupBox()->LastRowLastCol(), "awb:");
100 fps = new Label(GetGroupBox()->NewRow(), "fps");
101
102 hasProblems=false;
103}
104
105V4LCamera::~V4LCamera() {
106 if(useMemoryUsrPtr) {
107 for (int i = 0; i < nbBuffers; i++) {
108 FreeFunction((char*)buffers[i]);
109 }
110 } else {
111 FreeFunction(imageData);
112 }
113 SafeStop();
114 Join();
115 close(device);
116}
117
118int V4LCamera::Init(int width, int height,unsigned long colorspace) {
119 struct v4l2_capability cap;
120 memset(&cap, 0, sizeof (v4l2_capability));
121
122 if(-1 == xioctl(device, VIDIOC_QUERYCAP, &cap)) {
123 return -1;
124 }
125
126 if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
127 Thread::Err("device is unable to capture video memory.\n");
128 return -1;
129 }
130
131 struct v4l2_format form;
132 memset(&form, 0, sizeof (v4l2_format));
133 form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
134
135 /* read the current setting */
136 if(-1 == xioctl(device, VIDIOC_G_FMT, &form)) {
137 Thread::Err("Could not obtain specifics of capture window.\n");
138 return -1;
139 }
140
141 /* set the values we want to change */
142 form.fmt.pix.width = width;
143 form.fmt.pix.height = height;
144 form.fmt.win.chromakey = 0;
145 form.fmt.win.field = V4L2_FIELD_ANY;
146 form.fmt.win.clips = 0;
147 form.fmt.win.clipcount = 0;
148 form.fmt.pix.field = V4L2_FIELD_ANY;
149 form.fmt.pix.pixelformat = colorspace;
150
151 /* ask the device to change the size*/
152 if(-1 == xioctl (device, VIDIOC_S_FMT, &form)) {
153 Thread::Err("Could not set specifics of capture window.\n");
154 return -1;
155 }
156
157 return 0;
158}
159
160int V4LCamera::AllocV4LBuffers() {
161 struct v4l2_requestbuffers req;
162 memset(&req, 0, sizeof (v4l2_requestbuffers));
163 nbBuffers=DEFAULT_V4L_BUFFERS;
164
165 try_again:
166
167 req.count = nbBuffers;
168 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
169 req.memory = V4L2_MEMORY_MMAP;
170
171 if(-1 == xioctl(device, VIDIOC_REQBUFS, &req)) {
172 if (EINVAL == errno) {
173 Thread::Err("camera does not support memory mapping\n");
174 } else {
175 Thread::Err("VIDIOC_REQBUFS failed\n");
176 }
177 return -1;
178 }
179
180 if(req.count < nbBuffers) {
181 if (nbBuffers == 1) {
182 Thread::Err("Insufficient buffer memory\n");
183 return -1;
184 } else {
185 nbBuffers--;
186 Thread::Warn("Insufficient buffer memory -- decreaseing buffers to %i\n",nbBuffers);
187 goto try_again;
188 }
189 }
190
191 for(int i=0; i<req.count; i++) {
192 struct v4l2_buffer buf;
193 memset(&buf, 0, sizeof (v4l2_buffer));
194
195 buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
196 buf.memory = V4L2_MEMORY_MMAP;
197 buf.index = i;
198
199 if(-1 == xioctl(device, VIDIOC_QUERYBUF, &buf)) {
200 Thread::Err("VIDIOC_QUERYBUF error\n");
201 return -1;
202 }
203
204 if(output->GetDataType().GetSize()!=buf.length) {
205 Thread::Err("buf size is not as exepcted %i/%i\n",buf.length,output->GetDataType().GetSize());
206 return -1;
207 }
208
209 buffers[i]=mmap(NULL,buf.length,PROT_READ | PROT_WRITE,MAP_SHARED,device, buf.m.offset);
210
211 if(MAP_FAILED == buffers[i]) {
212 Thread::Err("mmap error\n");
213 return -1;
214 }
215 }
216
217 //allocate output data
218 imageData = AllocFunction(output->GetDataType().GetSize());
219 //Printf("cmem allocated %i at %x\n",output->GetDataType().GetSize(),imageData);
220
221 return 1;
222};
223
224int V4LCamera::AllocUserBuffers(void) {
225 struct v4l2_requestbuffers req;
226 memset(&req, 0, sizeof (v4l2_requestbuffers));
227 nbBuffers=DEFAULT_V4L_BUFFERS;
228
229 req.count = nbBuffers;
230 req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
231 req.memory = V4L2_MEMORY_USERPTR;
232
233 if (xioctl (device, VIDIOC_REQBUFS, &req)==-1) {
234 if (errno==EINVAL) {
235 Thread::Err("VIDIOC_REQBUFS user memory not supported\n");
236 } else {
237 Thread::Err ("VIDIOC_REQBUFS xioctl\n");
238 }
239 return -1;
240 }
241
242 for (int i=0; i<nbBuffers; i++) {
243 buffers[i] =AllocFunction(output->GetDataType().GetSize());
244 }
245
246 return 1;
247};
248
249int V4LCamera::GrabFrame(void) {
250 fd_set fds;
251 struct timeval tv;
252 FD_ZERO (&fds);
253 FD_SET (device, &fds);
254
255 tv.tv_sec = 0;
256 tv.tv_usec = 100000;
257
258 int r=select(device+1, &fds, NULL, NULL, &tv);
259
260 if (r==-1) {
261 char errorMsg[256];
262 Thread::Err("select (%s)\n", strerror_r(-r, errorMsg, sizeof(errorMsg)));
263 return -1;
264 }
265
266 if (r==0) {
267 Thread::Err("select timeout\n");
268 return -1;
269 }
270
271 struct v4l2_buffer buf;
272 memset(&buf, 0, sizeof (v4l2_buffer));
273 buf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
274 if(useMemoryUsrPtr) {
275 buf.memory=V4L2_MEMORY_USERPTR;
276 } else {
277 buf.memory=V4L2_MEMORY_MMAP;
278 }
279
280 //get last captured buffer
281 dQueuedBuffer.index=-1;
282 for(int i=0;i<nbBuffers;i++) {
283 if (xioctl (device, VIDIOC_DQBUF, &buf)==-1) {
284 if (errno==EAGAIN) {//when no new buffer is available for reading (non blocking)
285 //Printf("%s eagain\n",Thread::ObjectName().c_str());
286 break;
287 } else {
288 Thread::Err("VIDIOC_DQBUF xioctl\n");
289 return -1;
290 }
291 } else {
292 //Printf("%s %i dqueued\n",Thread::ObjectName().c_str(),buf.index);
293 //Printf("%i %x %i %i\n",buf.bytesused,buf.flags,buf.field,buf.sequence);
294 if(dQueuedBuffer.index!=-1) {
295 //Printf("%s %i queued\n",Thread::ObjectName().c_str(),dQueuedBuffer.index);
296 QueueBuffer(&dQueuedBuffer);
297 }
298 dQueuedBuffer=buf;
299 }
300 }
301 //Printf("%s %i\n",Thread::ObjectName().c_str(),dQueuedBuffer.index);
302
303 return 1;
304}
305
306void V4LCamera::Run(void) {
307 Time cam_time, new_time, fpsNow, fpsPrev;
308 int fpsCounter = 0;
309
310 cam_time = GetTime();
311 fpsPrev = cam_time;
312
313 while (!ToBeStopped()) {
314 // fps counter
315 fpsCounter++;
316 if (fpsCounter == 100) {
317 fpsNow = GetTime();
318 fps->SetText("fps: %.1f",
319 fpsCounter / ((float)(fpsNow - fpsPrev) / 1000000000.));
320 fpsCounter = 0;
321 fpsPrev = fpsNow;
322 }
323
324 // cam properties
325 if (gain->ValueChanged() == true && autogain->Value() == false)
326 SetGain(gain->Value());
327 if (exposure->ValueChanged() == true && autoexposure->Value() == false)
328 SetExposure(exposure->Value());
329 if (bright->ValueChanged() == true)
330 SetBrightness(bright->Value());
331 if (sat->ValueChanged() == true)
332 SetSaturation(sat->Value());
333 if (contrast->ValueChanged() == true)
334 SetContrast(contrast->Value());
335 if (hue->ValueChanged() == true)
336 SetHue(hue->Value());
337 //if (sharpness->ValueChanged() == true)
338 // cvSetCaptureProperty(capture, CV_CAP_PROP_SHARPNESS, sharpness->Value());
339 if (autogain->ValueChanged() == true) {
340 if (autogain->Value() == true) {
341 gain->setEnabled(false);
342 } else {
343 gain->setEnabled(true);
344 SetGain(gain->Value());
345 }
346 SetAutoGain(autogain->Value());
347 }
348 if (autoexposure->ValueChanged() == true) {
349 if (autoexposure->Value() == true) {
350 exposure->setEnabled(false);
351 } else {
352 exposure->setEnabled(true);
353 SetExposure(exposure->Value());
354 }
355 SetAutoExposure(autoexposure->Value());
356 }
357 //if (awb->ValueChanged() == true)
358 // cvSetCaptureProperty(capture, CV_CAP_PROP_AWB, awb->Value());
359
360 // cam pictures
361 if (!GrabFrame()) {
362 Printf("Could not grab a frame\n");
363 }
364
365 //check for ps3eye deconnection in hds uav
366 new_time = GetTime();
367 if(new_time-cam_time>100*1000*1000) {
368 Thread::Warn("delta t trop grand\n");
369 hasProblems=true;
370 }/*
371 if(hasProblems==false) {
372 struct v4l2_format form;
373 form.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
374 xioctl(device, VIDIOC_G_FMT,&form);
375 if(xioctl (device, VIDIOC_G_FMT,&form)<0) {
376 Thread::Warn("camera disconnected\n");
377 hasProblems=true;
378 }
379 }*/
380
381 //select buffer
382 if(useMemoryUsrPtr) {//buffers are already in CMEM
383 imageData=(char*)buffers[dQueuedBuffer.index];
384 //dequeue it latter (buffer used by ProcessUpdate)
385 } else {//copy to CMEM allocated buffer
386 memcpy(imageData,(char *)buffers[dQueuedBuffer.index],output->GetDataType().GetSize());
387 QueueBuffer(&dQueuedBuffer);//we can do it right now
388 }
389
390 output->GetMutex();
391 output->buffer=imageData;
392 output->ReleaseMutex();
393
394 output->SetDataTime(cam_time);
395 ProcessUpdate(output);
396 cam_time = new_time;
397
398 if(useMemoryUsrPtr) {
399 QueueBuffer(&dQueuedBuffer);//now it is possible to dequeue
400 }
401 }
402}
403
404int V4LCamera::QueueBuffer(struct v4l2_buffer *buf) {
405 if(buf->index>=0 && buf->index<nbBuffers) {
406 int ret=xioctl (device, VIDIOC_QBUF,buf);
407 if (ret==-1) {
408 Thread::Err("VIDIOC_QBUF xioctl %s\n",strerror(-ret));
409 return -1;
410 }
411 }
412 return 0;
413}
414
415int V4LCamera::QueueBuffer(int index) {
416 struct v4l2_buffer buf;
417 memset(&buf, 0, sizeof (v4l2_buffer));
418
419 buf.type=V4L2_BUF_TYPE_VIDEO_CAPTURE;
420 buf.index=(unsigned long)index;
421 if(useMemoryUsrPtr) {
422 buf.memory=V4L2_MEMORY_USERPTR;
423 buf.m.userptr=(unsigned long)(buffers[index]);
424 buf.length=output->GetDataType().GetSize();
425 } else {
426 buf.memory=V4L2_MEMORY_MMAP;
427 }
428 return QueueBuffer(&buf);
429}
430
431bool V4LCamera::HasProblems(void) {
432 return hasProblems;
433}
434
435void V4LCamera::SetAutoGain(bool value) {
436 SetProperty(V4L2_CID_AUTOGAIN, value);
437}
438
439void V4LCamera::SetAutoExposure(bool value) {
440 Thread::Warn("not implemented\n");
441}
442
443void V4LCamera::SetGain(float value) {
444 SetProperty(V4L2_CID_GAIN, value);
445}
446
447void V4LCamera::SetExposure(float value) {
448 SetProperty(V4L2_CID_EXPOSURE, value);
449}
450
451void V4LCamera::SetBrightness(float value) {
452 SetProperty(V4L2_CID_BRIGHTNESS, value);
453}
454
455void V4LCamera::SetSaturation(float value) {
456 SetProperty(V4L2_CID_SATURATION, value);
457}
458
459void V4LCamera::SetHue(float value) {
460 SetProperty(V4L2_CID_HUE, value);
461}
462
463void V4LCamera::SetContrast(float value) {
464 SetProperty(V4L2_CID_CONTRAST, value);
465}
466
467float V4LCamera::GetProperty(int property) {
468 //get min and max value
469 struct v4l2_queryctrl queryctrl;
470 queryctrl.id = property;
471 if(xioctl (device, VIDIOC_QUERYCTRL,&queryctrl)==-1) return -1;
472 int min = queryctrl.minimum;
473 int max = queryctrl.maximum;
474
475 //set value
476 struct v4l2_control control;
477 memset (&control, 0, sizeof (v4l2_control));
478 control.id = property;
479 if(xioctl (device,VIDIOC_G_CTRL, &control)==-1) return -1;
480
481 return ((float)control.value - min + 1) / (max - min);
482}
483
484void V4LCamera::SetProperty(int property,float value) {
485 //get min and max value
486 struct v4l2_queryctrl queryctrl;
487 queryctrl.id = property;
488 if(xioctl (device, VIDIOC_QUERYCTRL,&queryctrl)==-1) {
489 Thread::Warn("prop %x, VIDIOC_QUERYCTRL failed\n",property);
490 }
491 int min = queryctrl.minimum;
492 int max = queryctrl.maximum;
493
494 //set value
495 struct v4l2_control control;
496 memset (&control, 0, sizeof (v4l2_control));
497 control.id = property;
498 control.value = (int)(value * (max - min) + min);
499 if(xioctl (device,VIDIOC_S_CTRL, &control)==-1) {
500 Thread::Warn("prop %x, VIDIOC_S_CTRL failed\n",property);
501 }
502}
503
504int V4LCamera::xioctl( int fd, int request, void *arg) {
505 int r;
506
507 do r = ioctl (fd, request, arg);
508 while (-1 == r && EINTR == errno);
509
510 return r;
511}
512
513} // end namespace sensor
514} // end namespace flair
Note: See TracBrowser for help on using the repository browser.