Debian Codegraph @

cvd_src/Linux/v4lbuffer.cc

raw symbols SCIP
1 #include <errno.h>
2 #include <fcntl.h>
3 #include <sys/ioctl.h>
4 #include <sys/mman.h>
5 #include <unistd.h>
6
7 #include <cvd/Linux/v4lbuffer.h>
8 #include <cvd/timer.h>
9
10 #include <iomanip>
11 #include <vector>
12 using namespace std;
13
14 namespace CVD
15 { // CVD
16
17 Exceptions::V4LBuffer::DeviceOpen::DeviceOpen(string device)
18 : All("V4LBuffer: failed to open \"" + device + "\": " + strerror(errno))
19 {
20 }
21
22 Exceptions::V4LBuffer::DeviceSetup::DeviceSetup(string device, string action)
23 : All("V4LBuffer: \"" + action + "\" ioctl failed on " + device + ": " + strerror(errno))
24 {
25 }
26
27 Exceptions::V4LBuffer::PutFrame::PutFrame(string device, string msg)
28 : All("V4LBuffer: PutFrame on " + device + " failed: " + msg)
29 {
30 }
31
32 Exceptions::V4LBuffer::GetFrame::GetFrame(string device, string msg)
33 : All("V4LBuffer: GetFrame on " + device + " failed: " + msg)
34 {
35 }
36
37 Exceptions::V4LBuffer::NoColourspace::NoColourspace(std::string dev, std::string space)
38 : All("V4LBuffer: No colourspace on " + dev + " matching " + space)
39 {
40 }
41
42 class VPrint_
43 {
44 public:
45 VPrint_(bool _p)
46 : p(_p)
47 {
48 }
49
50 template <class C>
51 VPrint_& operator<<(const C& c)
52 {
53 if(p)
54 cerr << c;
55
56 return *this;
57 }
58
59 bool p;
60 };
61
62 class VPrint : public VPrint_
63 {
64 public:
65 VPrint(bool _b)
66 : VPrint_(_b)
67 {
68 }
69
70 template <class C>
71 VPrint_& operator<<(const C& c)
72 {
73 if(p)
74 cerr << "RawV4LBuffer: " << c;
75
76 return *this;
77 }
78 };
79
80 string unfourcc(unsigned long c)
81 {
82 string ret;
83 ret.resize(4);
84
85 ret[0] = static_cast<char>(c & 0xff);
86 ret[1] = static_cast<char>((c >> 8) & 0xff);
87 ret[2] = static_cast<char>((c >> 16) & 0xff);
88 ret[3] = static_cast<char>((c >> 24) & 0xff);
89 return ret;
90 }
91
92 typedef const char fourcc_string[5];
93
94 unsigned int fourcc(const fourcc_string& s)
95 {
96 return v4l2_fourcc(s[0], s[1], s[2], s[3]);
97 }
98
99 #ifdef VIDIOC_ENUM_FRAMESIZES
100 void print_v4l2_framerates(int fd, unsigned int fmt, unsigned int width, unsigned int height, VPrint& log)
101 {
102 struct v4l2_frmivalenum fr;
103 fr.pixel_format = fmt;
104 fr.width = width;
105 fr.height = height;
106 for(fr.index = 0; ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &fr) == 0; ++fr.index)
107 {
108 switch(fr.type)
109 {
110 case V4L2_FRMIVAL_TYPE_DISCRETE:
111 log << "\t\t rate discrete\t" << fr.discrete.numerator << "/" << fr.discrete.denominator << "\n";
112 break;
113 case V4L2_FRMIVAL_TYPE_CONTINUOUS:
114 log << "\t\t rate cont\t" << fr.stepwise.min.numerator << "/" << fr.stepwise.min.denominator << " - " << fr.stepwise.step.numerator << "/" << fr.stepwise.step.denominator << " - " << fr.stepwise.max.numerator << "/" << fr.stepwise.max.denominator << "\n";
115 break;
116 case V4L2_FRMIVAL_TYPE_STEPWISE:
117 log << "\t\t rate step\t" << fr.stepwise.min.numerator << "/" << fr.stepwise.min.denominator << " - " << fr.stepwise.step.numerator << "/" << fr.stepwise.step.denominator << " - " << fr.stepwise.max.numerator << "/" << fr.stepwise.max.denominator << "\n";
118 break;
119 default:
120 assert(false);
121 }
122 }
123 }
124 #endif
125
126 namespace V4L
127 { // V4L
128
129 struct RawV4LBuffer::State
130 {
131 struct Frame
132 {
133 void* data;
134 size_t length;
135 };
136 int fd;
137 v4l2_format format;
138 vector<Frame> frames;
139 double frameRate;
140 v4l2_buffer refbuf;
141 };
142
143 RawV4LBuffer::RawV4LBuffer(const std::string& devname, unsigned int fmt, ImageRef size, int input, bool fields, int frames_per_second, bool verbose)
144 {
145 dev = devname;
146
147 int fd = open(devname.c_str(), O_RDWR | O_NONBLOCK);
148 if(fd == -1)
149 throw Exceptions::V4LBuffer::DeviceOpen(dev);
150
151 state = 0;
152
153 VPrint log(verbose);
154
155 log << "verbose operation. Initializing\n";
156 log << "Querying capabilities.\n";
157 struct v4l2_capability caps;
158 if(0 != ioctl(fd, VIDIOC_QUERYCAP, &caps))
159 {
160 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_QUERYCAP failed");
161 }
162
163 log << " driver: " << caps.driver << "\n";
164 log << " card: " << caps.card << "\n";
165 log << " bus_info: " << caps.bus_info << "\n";
166 log << " version: " << caps.version << "\n";
167 log << " capabilities: 0x" << hex << caps.capabilities << dec << "\n";
168 log << " V4L2_CAP_VIDEO_CAPTURE = " << !!(caps.capabilities & V4L2_CAP_VIDEO_CAPTURE) << "\n";
169 log << " V4L2_CAP_VIDEO_OUTPUT = " << !!(caps.capabilities & V4L2_CAP_VIDEO_OUTPUT) << "\n";
170 log << " V4L2_CAP_VIDEO_OVERLAY = " << !!(caps.capabilities & V4L2_CAP_VIDEO_OVERLAY) << "\n";
171 log << " V4L2_CAP_VBI_CAPTURE = " << !!(caps.capabilities & V4L2_CAP_VBI_CAPTURE) << "\n";
172 log << " V4L2_CAP_VBI_OUTPUT = " << !!(caps.capabilities & V4L2_CAP_VBI_OUTPUT) << "\n";
173 log << " V4L2_CAP_SLICED_VBI_CAPTURE = " << !!(caps.capabilities & V4L2_CAP_SLICED_VBI_CAPTURE) << "\n";
174 log << " V4L2_CAP_SLICED_VBI_OUTPUT = " << !!(caps.capabilities & V4L2_CAP_VIDEO_CAPTURE) << "\n";
175 log << " V4L2_CAP_RDS_CAPTURE = " << !!(caps.capabilities & V4L2_CAP_SLICED_VBI_OUTPUT) << "\n";
176 #ifdef V4L2_CAP_VIDEO_OUTPUT_OVERLAY
177 log << " V4L2_CAP_VIDEO_OUTPUT_OVERLAY = " << !!(caps.capabilities & V4L2_CAP_VIDEO_OUTPUT_OVERLAY) << "\n";
178 #endif
179 log << " V4L2_CAP_TUNER = " << !!(caps.capabilities & V4L2_CAP_VIDEO_CAPTURE) << "\n";
180 log << " V4L2_CAP_AUDIO = " << !!(caps.capabilities & V4L2_CAP_TUNER) << "\n";
181 log << " V4L2_CAP_RADIO = " << !!(caps.capabilities & V4L2_CAP_RADIO) << "\n";
182 log << " V4L2_CAP_READWRITE = " << !!(caps.capabilities & V4L2_CAP_READWRITE) << "\n";
183 log << " V4L2_CAP_ASYNCIO = " << !!(caps.capabilities & V4L2_CAP_ASYNCIO) << "\n";
184 log << " V4L2_CAP_STREAMING = " << !!(caps.capabilities & V4L2_CAP_STREAMING) << "\n";
185
186 log << "Requested format: " << unfourcc(fmt) << "\n";
187 unsigned int actual_fmt = fourcc("None");
188
189 log << "Enumerating formats.\n";
190
191 struct v4l2_fmtdesc f;
192 f.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
193 log << " Index FourCC Flags Description\n";
194 for(f.index = 0; ioctl(fd, VIDIOC_ENUM_FMT, &f) == 0; f.index++)
195 {
196 log << " " << setw(3) << setfill(' ') << f.index << " " << unfourcc(f.pixelformat)
197 << " 0x" << hex << setfill('0') << setw(8) << f.flags << dec << " "
198 << f.description << "\n";
199
200 if(fmt == f.pixelformat)
201 actual_fmt = fmt;
202
203 //Hack. Some cameras won't send GREY, but the planar formats
204 //are close enough, since the first chunk is the same as GREY
205 if(fmt == V4L2_PIX_FMT_GREY && actual_fmt == fourcc("None") && (f.pixelformat == fourcc("422P") || f.pixelformat == fourcc("YU12") || f.pixelformat == fourcc("YV12") || f.pixelformat == fourcc("411P") || f.pixelformat == fourcc("YUV9") || f.pixelformat == fourcc("YVU9")))
206 {
207 actual_fmt = f.pixelformat;
208 }
209
210 #ifdef VIDIOC_ENUM_FRAMESIZES
211 if(verbose)
212 {
213 struct v4l2_frmsizeenum fs;
214 fs.pixel_format = f.pixelformat;
215 for(fs.index = 0; ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &fs) == 0; ++fs.index)
216 {
217 switch(fs.type)
218 {
219 case V4L2_FRMSIZE_TYPE_DISCRETE:
220 log << "\t\tframe size discrete\t" << fs.discrete.width << "x" << fs.discrete.height << "\n";
221 print_v4l2_framerates(fd, fs.pixel_format, fs.discrete.width, fs.discrete.height, log);
222 break;
223 case V4L2_FRMSIZE_TYPE_CONTINUOUS:
224 log << "\t\tframe size cont\t" << fs.stepwise.min_width << "x" << fs.stepwise.min_height << " - " << fs.stepwise.step_width << "x" << fs.stepwise.step_height << " - " << fs.stepwise.max_width << "x" << fs.stepwise.max_height << "\n";
225 print_v4l2_framerates(fd, fs.pixel_format, fs.stepwise.max_width, fs.stepwise.max_height, log);
226 break;
227 case V4L2_FRMSIZE_TYPE_STEPWISE:
228 {
229 log << "\t\tframe size step\t" << fs.stepwise.min_width << "x" << fs.stepwise.min_height << " - " << fs.stepwise.step_width << "x" << fs.stepwise.step_height << " - " << fs.stepwise.max_width << "x" << fs.stepwise.max_height << "\n";
230 print_v4l2_framerates(fd, fs.pixel_format, fs.stepwise.max_width, fs.stepwise.max_height, log);
231 }
232 break;
233 default:
234 assert(false);
235 }
236 }
237 }
238 #endif
239 }
240
241 if(errno != EINVAL)
242 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_ENUM_FMT");
243
244 log << "Selected format: " << unfourcc(actual_fmt) << "\n";
245
246 if(actual_fmt == fourcc("None"))
247 throw Exceptions::V4LBuffer::NoColourspace(dev, unfourcc(actual_fmt));
248
249 fmt = actual_fmt;
250
251 if(strcmp((const char*)caps.driver, "bttv") == 0)
252 {
253 v4l2_std_id stdId = V4L2_STD_PAL;
254 if(ioctl(fd, VIDIOC_S_STD, &stdId))
255 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_S_STD");
256 }
257
258 if(input != -1)
259 {
260 struct v4l2_input v4l2Input;
261 v4l2Input.index = input;
262 if(0 != ioctl(fd, VIDIOC_S_INPUT, &v4l2Input))
263 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_S_INPUT");
264 }
265
266 // Get / Set capture format.
267 struct v4l2_format format;
268 format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
269
270 log << "Getting format (VIDIOC_G_FMT)\n";
271
272 if(0 != ioctl(fd, VIDIOC_G_FMT, &format))
273 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_G_FMT");
274
275 log << " size: " << format.fmt.pix.width << "x" << format.fmt.pix.height << "\n";
276 log << " format: " << unfourcc(format.fmt.pix.pixelformat) << "\n";
277 log << " field flag: " << format.fmt.pix.field << "\n";
278 log << " bytes per line: " << format.fmt.pix.bytesperline << "\n";
279 log << " image size: " << format.fmt.pix.sizeimage << "\n";
280 log << " colourspace: " << format.fmt.pix.colorspace << "\n";
281
282 format.fmt.pix.width = size.x;
283 format.fmt.pix.height = size.y;
284 format.fmt.pix.pixelformat = fmt;
285 format.fmt.pix.field = fields ? V4L2_FIELD_ALTERNATE : V4L2_FIELD_ANY;
286
287 log << "Setting format (VIDIOC_S_FMT)\n";
288 log << " size: " << format.fmt.pix.width << "x" << format.fmt.pix.height << "\n";
289 log << " format: " << unfourcc(format.fmt.pix.pixelformat) << "\n";
290 log << " field flag: " << format.fmt.pix.field << "\n";
291 log << " bytes per line: " << format.fmt.pix.bytesperline << "\n";
292 log << " image size: " << format.fmt.pix.sizeimage << "\n";
293 log << " colourspace: " << format.fmt.pix.colorspace << "\n";
294
295 if(0 != ioctl(fd, VIDIOC_S_FMT, &format))
296 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_S_FMT");
297
298 log << "Getting format (VIDIOC_G_FMT)\n";
299 if(0 != ioctl(fd, VIDIOC_G_FMT, &format))
300 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_G_FMT");
301
302 log << " size: " << format.fmt.pix.width << "x" << format.fmt.pix.height << "\n";
303 log << " format: " << unfourcc(format.fmt.pix.pixelformat) << "\n";
304 log << " field flag: " << format.fmt.pix.field << "\n";
305 log << " bytes per line: " << format.fmt.pix.bytesperline << "\n";
306 log << " image size: " << format.fmt.pix.sizeimage << "\n";
307 log << " colourspace: " << format.fmt.pix.colorspace << "\n";
308
309 if(fmt != format.fmt.pix.pixelformat)
310 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: equested format not supported");
311
312 struct v4l2_requestbuffers reqbufs;
313 reqbufs.count = 10;
314 reqbufs.memory = V4L2_MEMORY_MMAP;
315 reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
316
317 log << "Issuing VIDIOC_REQBUFS ioctl.\n";
318 int ret = ioctl(fd, VIDIOC_REQBUFS, &reqbufs);
319 log << " Return code: " << ret << "\n";
320
321 //WARNING!!!!!
322 //The documentation says -1 for error, 0 otherwise.
323 //The BTTV driver returns num_bufs on success!
324 //So the test against 0 fails.
325 if(ioctl(fd, VIDIOC_REQBUFS, &reqbufs) == -1)
326 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_REQBUFS");
327
328 num_bufs = reqbufs.count;
329
330 log << "Number of buffers: " << num_bufs << "\n";
331
332 if(reqbufs.count < 2)
333 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: Insufficient buffers available");
334 vector<State::Frame> frames(reqbufs.count);
335 struct v4l2_buffer refbuf;
336 for(size_t i = 0; i < frames.size(); i++)
337 {
338 struct v4l2_buffer buffer;
339 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
340 buffer.memory = V4L2_MEMORY_MMAP;
341 buffer.index = static_cast<uint32_t>(i);
342 if(0 != ioctl(fd, VIDIOC_QUERYBUF, &buffer))
343 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_QUERYBUF");
344 if(i == 0)
345 refbuf = buffer;
346 frames[i].data = mmap(0, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, buffer.m.offset);
347 if(frames[i].data == MAP_FAILED)
348 {
349 frames[i].data = mmap(0, buffer.length, PROT_READ, MAP_SHARED, fd, buffer.m.offset);
350 if(frames[i].data == MAP_FAILED)
351 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: mmap failed");
352 }
353 frames[i].length = buffer.length;
354 if(0 != ioctl(fd, VIDIOC_QBUF, &buffer))
355 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_QBUF");
356 }
357
358 // Do we want to manually set FPS?
359 if(frames_per_second != 0)
360 {
361 v4l2_streamparm streamparams;
362 streamparams.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
363 if(0 != ioctl(fd, VIDIOC_G_PARM, &streamparams))
364 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_G_PARM");
365
366 // Check if the device has the capability to set a frame-rate.
367 if(streamparams.parm.capture.capability & V4L2_CAP_TIMEPERFRAME)
368 {
369 streamparams.parm.capture.timeperframe.denominator = frames_per_second;
370 streamparams.parm.capture.timeperframe.numerator = 1;
371 if(0 != ioctl(fd, VIDIOC_S_PARM, &streamparams))
372 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_S_PARM");
373 }
374 }
375
376 if(0 != ioctl(fd, VIDIOC_STREAMON, &reqbufs.type))
377 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_STREAMON");
378 state = new State;
379 state->fd = fd;
380 state->format = format;
381 state->frames = frames;
382 state->frameRate = 0;
383 state->refbuf = refbuf;
384 }
385
386 RawV4LBuffer::~RawV4LBuffer()
387 {
388 if(state == 0)
389 return;
390 if(0 != ioctl(state->fd, VIDIOC_STREAMOFF, &state->refbuf.type))
391 cerr << "Error closing RawV4LBuffer: " << Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_STREAMOFF").what() << endl;
392 for(size_t i = 0; i < state->frames.size(); i++)
393 {
394 if(0 != munmap(state->frames[i].data, state->frames[i].length))
395 cerr << "Error closing RawV4LBuffer: " << Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: munmap failed").what() << endl;
396 }
397 close(state->fd);
398 delete state;
399 }
400
401 ImageRef RawV4LBuffer::getSize()
402 {
403 return ImageRef(state->format.fmt.pix.width, state->format.fmt.pix.height);
404 }
405
406 RawV4LBuffer::Buffer RawV4LBuffer::getFrame()
407 {
408 struct v4l2_buffer buffer = state->refbuf;
409 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
410 buffer.memory = V4L2_MEMORY_MMAP;
411 int err = ioctl(state->fd, VIDIOC_DQBUF, &buffer);
412 while(err != 0 && errno == EAGAIN)
413 {
414 usleep(10);
415 err = ioctl(state->fd, VIDIOC_DQBUF, &buffer);
416 }
417 if(err != 0)
418 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_DQBUF");
419
420 Buffer ret;
421 ret.id = buffer.index;
422 ret.data = static_cast<unsigned char*>(state->frames[buffer.index].data);
423 ret.when = static_cast<double>(buffer.timestamp.tv_usec) * 1e-6 + static_cast<double>(buffer.timestamp.tv_sec);
424 return ret;
425 }
426
427 void RawV4LBuffer::releaseFrame(int id)
428 {
429 struct v4l2_buffer buffer = state->refbuf;
430 buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
431 buffer.memory = V4L2_MEMORY_MMAP;
432 buffer.index = id;
433
434 if(0 != ioctl(state->fd, VIDIOC_QBUF, &buffer))
435 throw Exceptions::V4LBuffer::DeviceSetup(dev, "V4L2: VIDIOC_QBUF");
436 }
437
438 double RawV4LBuffer::getRate()
439 {
440 return state->frameRate;
441 }
442
443 bool RawV4LBuffer::pendingFrame()
444 {
445 fd_set fdsetRead;
446 fd_set fdsetWrite;
447 fd_set fdsetExcept;
448 struct timeval tv;
449
450 FD_ZERO(&fdsetRead);
451 FD_SET(state->fd, &fdsetRead);
452 FD_ZERO(&fdsetWrite);
453 FD_ZERO(&fdsetExcept);
454 tv.tv_sec = 0;
455 tv.tv_usec = 0;
456 if(select(state->fd + 1, &fdsetRead, &fdsetWrite, &fdsetExcept, &tv) > 0)
457 return true;
458 return false;
459 }
460
461 };
462
463 };