uvc_cam.cpp
Go to the documentation of this file.
00001 #include <cstring>
00002 #include <string>
00003 #include <cstdio>
00004 #include <stdexcept>
00005 #include <dirent.h>
00006 #include <sys/stat.h>
00007 #include <sys/ioctl.h>
00008 #include <sys/mman.h>
00009 #include <fcntl.h>
00010 #include <errno.h>
00011 #include <unistd.h>
00012 #include "uvc_cam/uvc_cam.h"
00013 
00014 using std::string;
00015 using namespace uvc_cam;
00016 
00017 Cam::Cam(const char *_device, mode_t _mode, int _width, int _height, int _fps)
00018 : mode(_mode), device(_device),
00019   motion_threshold_luminance(100), motion_threshold_count(-1),
00020   width(_width), height(_height), fps(_fps), rgb_frame(NULL)
00021 {
00022   printf("opening %s\n", _device);
00023   if ((fd = open(_device, O_RDWR)) == -1)
00024     throw std::runtime_error("couldn't open " + device);
00025   memset(&fmt, 0, sizeof(v4l2_format));
00026   memset(&cap, 0, sizeof(v4l2_capability));
00027   if (ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
00028     throw std::runtime_error("couldn't query " + device);
00029   if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE))
00030     throw std::runtime_error(device + " does not support capture");
00031   if (!(cap.capabilities & V4L2_CAP_STREAMING))
00032     throw std::runtime_error(device + " does not support streaming");
00033   // enumerate formats
00034   v4l2_fmtdesc f;
00035   memset(&f, 0, sizeof(f));
00036   f.index = 0;
00037   f.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00038   int ret;
00039   while ((ret = ioctl(fd, VIDIOC_ENUM_FMT, &f)) == 0)
00040   {
00041     printf("pixfmt %d = '%4s' desc = '%s'\n",
00042            f.index++, (char *)&f.pixelformat, f.description);
00043     // enumerate frame sizes
00044     v4l2_frmsizeenum fsize;
00045     fsize.index = 0;
00046     fsize.pixel_format = f.pixelformat;
00047     while ((ret = ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &fsize)) == 0)
00048     {
00049       fsize.index++;
00050       if (fsize.type == V4L2_FRMSIZE_TYPE_DISCRETE)
00051       {
00052         printf("  discrete: %ux%u:   ",
00053                fsize.discrete.width, fsize.discrete.height);
00054         // enumerate frame rates
00055         v4l2_frmivalenum fival;
00056         fival.index = 0;
00057         fival.pixel_format = f.pixelformat;
00058         fival.width = fsize.discrete.width;
00059         fival.height = fsize.discrete.height;
00060         while ((ret = ioctl(fd, VIDIOC_ENUM_FRAMEINTERVALS, &fival)) == 0)
00061         {
00062           fival.index++;
00063           if (fival.type == V4L2_FRMIVAL_TYPE_DISCRETE)
00064           {
00065             printf("%u/%u ",
00066                    fival.discrete.numerator, fival.discrete.denominator);
00067           }
00068           else
00069             printf("I only handle discrete frame intervals...\n");
00070         }
00071         printf("\n");
00072       }
00073       else if (fsize.type == V4L2_FRMSIZE_TYPE_CONTINUOUS)
00074       {
00075         printf("  continuous: %ux%u to %ux%u\n",
00076                fsize.stepwise.min_width, fsize.stepwise.min_height,
00077                fsize.stepwise.max_width, fsize.stepwise.max_height);
00078       }
00079       else if (fsize.type == V4L2_FRMSIZE_TYPE_STEPWISE)
00080       {
00081         printf("  stepwise: %ux%u to %ux%u step %ux%u\n",
00082                fsize.stepwise.min_width,  fsize.stepwise.min_height,
00083                fsize.stepwise.max_width,  fsize.stepwise.max_height,
00084                fsize.stepwise.step_width, fsize.stepwise.step_height);
00085       }
00086       else
00087       {
00088         printf("  fsize.type not supported: %d\n", fsize.type);
00089       }
00090     }
00091   }
00092   if (errno != EINVAL)
00093     throw std::runtime_error("error enumerating frame formats");
00094   fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00095   fmt.fmt.pix.width = width;
00096   fmt.fmt.pix.height = height;
00097   if (mode == MODE_RGB || mode == MODE_YUYV) // we'll convert later
00098     fmt.fmt.pix.pixelformat = 'Y' | ('U' << 8) | ('Y' << 16) | ('V' << 24);
00099   else
00100     fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG; 
00101   fmt.fmt.pix.field = V4L2_FIELD_ANY;
00102   if ((ret = ioctl(fd, VIDIOC_S_FMT, &fmt)) < 0)
00103     throw std::runtime_error("couldn't set format");
00104   if (fmt.fmt.pix.width != width || fmt.fmt.pix.height != height)
00105     throw std::runtime_error("pixel format unavailable");
00106   streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00107   streamparm.parm.capture.timeperframe.numerator = 1;
00108   streamparm.parm.capture.timeperframe.denominator = fps;
00109   if ((ret = ioctl(fd, VIDIOC_S_PARM, &streamparm)) < 0)
00110     throw std::runtime_error("unable to set framerate");
00111   v4l2_queryctrl queryctrl;
00112   memset(&queryctrl, 0, sizeof(queryctrl));
00113   uint32_t i = V4L2_CID_BASE;
00114   while (i != V4L2_CID_LAST_EXTCTR)
00115   {
00116     queryctrl.id = i;
00117     if ((ret = ioctl(fd, VIDIOC_QUERYCTRL, &queryctrl)) == 0 &&
00118         !(queryctrl.flags & V4L2_CTRL_FLAG_DISABLED))
00119     {
00120       const char *ctrl_type = NULL;
00121       if (queryctrl.type == V4L2_CTRL_TYPE_INTEGER)
00122         ctrl_type = "int";
00123       else if (queryctrl.type == V4L2_CTRL_TYPE_BOOLEAN)
00124         ctrl_type = "bool";
00125       else if (queryctrl.type == V4L2_CTRL_TYPE_BUTTON)
00126         ctrl_type = "button";
00127       else if (queryctrl.type == V4L2_CTRL_TYPE_MENU)
00128         ctrl_type = "menu";
00129       printf("  %s (%s, %d, id = %x): %d to %d (%d)\n", 
00130              ctrl_type, 
00131              queryctrl.name, queryctrl.flags, queryctrl.id, 
00132              queryctrl.minimum, queryctrl.maximum, queryctrl.step);
00133       if (queryctrl.type == V4L2_CTRL_TYPE_MENU)
00134       {
00135         v4l2_querymenu querymenu;
00136         memset(&querymenu, 0, sizeof(querymenu));
00137         querymenu.id = queryctrl.id;
00138         querymenu.index = 0;
00139         while (ioctl(fd, VIDIOC_QUERYMENU, &querymenu) == 0)
00140         {
00141           printf("    %d: %s\n", querymenu.index, querymenu.name);
00142           querymenu.index++;
00143         }
00144       }
00145 
00146     }
00147     else if (errno != EINVAL)
00148       throw std::runtime_error("couldn't query control");
00149     i++;
00150     if (i == V4L2_CID_LAST_NEW)
00151       i = V4L2_CID_CAMERA_CLASS_BASE_NEW;
00152     else if (i == V4L2_CID_CAMERA_CLASS_LAST)
00153       i = V4L2_CID_PRIVATE_BASE_OLD;
00154     else if (i == V4L2_CID_PRIVATE_LAST)
00155       i = V4L2_CID_BASE_EXTCTR;
00156   }
00157 
00158   try 
00159   {
00160     //set_control(V4L2_CID_EXPOSURE_AUTO_NEW, 2);
00161     set_control(10094851, 0);
00162     set_control(10094849, 1);
00163     //set_control(0x9a9010, 100);
00164     set_control(V4L2_CID_EXPOSURE_ABSOLUTE_NEW, 500);
00165     set_control(V4L2_CID_BRIGHTNESS, 135);
00166     set_control(V4L2_CID_CONTRAST, 40);
00167     printf("set contrast\n");
00168     //set_control(V4L2_CID_WHITE_BALANCE_TEMP_AUTO_OLD, 0);
00169     set_control(9963788, 0); // auto white balance
00170     set_control(9963802, 500); // color temperature
00171     //set_control(9963800, 2);  // power line frequency to 60 hz
00172     set_control(9963795, 120); // gain
00173     set_control(9963803, 140); // sharpness
00174     set_control(9963778, 45); // saturation
00175 
00176     //set_control(0x9a0901, 1); // aperture priority exposure mode
00177     //set_control(0x9a0903, 1); // auto exposure
00178   }
00179   catch (std::runtime_error &ex)
00180   {
00181     printf("ERROR: could not set some settings.  \n %s \n", ex.what());
00182   }
00183 
00184 /*
00185   v4l2_jpegcompression v4l2_jpeg;
00186   if (ioctl(fd, VIDIOC_G_JPEGCOMP, &v4l2_jpeg) < 0)
00187     throw std::runtime_error("no jpeg compression iface exposed");
00188   printf("jpeg quality: %d\n", v4l2_jpeg.quality);
00189 */
00190 
00191   memset(&rb, 0, sizeof(rb));
00192   rb.count = NUM_BUFFER;
00193   rb.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00194   rb.memory = V4L2_MEMORY_MMAP;
00195   if (ioctl(fd, VIDIOC_REQBUFS, &rb) < 0)
00196     throw std::runtime_error("unable to allocate buffers");
00197   for (unsigned i = 0; i < NUM_BUFFER; i++)
00198   {
00199     memset(&buf, 0, sizeof(buf));
00200     buf.index = i;
00201     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00202     buf.flags = V4L2_BUF_FLAG_TIMECODE;
00203     buf.timecode = timecode;
00204     buf.timestamp.tv_sec = 0;
00205     buf.timestamp.tv_usec = 0;
00206     buf.memory = V4L2_MEMORY_MMAP;
00207     if (ioctl(fd, VIDIOC_QUERYBUF, &buf) < 0)
00208       throw std::runtime_error("unable to query buffer");
00209     if (buf.length <= 0)
00210       throw std::runtime_error("buffer length is bogus");
00211     mem[i] = mmap(0, buf.length, PROT_READ, MAP_SHARED, fd, buf.m.offset);
00212     //printf("buf length = %d at %x\n", buf.length, mem[i]);
00213     if (mem[i] == MAP_FAILED)
00214       throw std::runtime_error("couldn't map buffer");
00215   }
00216   buf_length = buf.length;
00217   for (unsigned i = 0; i < NUM_BUFFER; i++)
00218   {
00219     memset(&buf, 0, sizeof(buf));
00220     buf.index = i;
00221     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00222     buf.flags = V4L2_BUF_FLAG_TIMECODE;
00223     buf.timecode = timecode;
00224     buf.timestamp.tv_sec = 0;
00225     buf.timestamp.tv_usec = 0;
00226     buf.memory = V4L2_MEMORY_MMAP;
00227     if (ioctl(fd, VIDIOC_QBUF, &buf) < 0)
00228       throw std::runtime_error("unable to queue buffer");
00229   }
00230   int type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00231   if (ioctl(fd, VIDIOC_STREAMON, &type) < 0)
00232     throw std::runtime_error("unable to start capture");
00233   rgb_frame = new unsigned char[width * height * 3];
00234   last_yuv_frame = new unsigned char[width * height * 2];
00235 }
00236 
00237 Cam::~Cam()
00238 {
00239   // stop stream
00240   int type = V4L2_BUF_TYPE_VIDEO_CAPTURE, ret;
00241   if ((ret = ioctl(fd, VIDIOC_STREAMOFF, &type)) < 0)
00242     perror("VIDIOC_STREAMOFF");
00243   for (unsigned i = 0; i < NUM_BUFFER; i++)
00244     if (munmap(mem[i], buf_length) < 0)
00245       perror("failed to unmap buffer");
00246   close(fd);
00247   if (rgb_frame)
00248   {
00249     delete[] rgb_frame;
00250     delete[] last_yuv_frame;
00251   }
00252   last_yuv_frame = rgb_frame = NULL;
00253 }
00254 
00255 void Cam::enumerate()
00256 {
00257   string v4l_path = "/sys/class/video4linux";
00258   DIR *d = opendir(v4l_path.c_str());
00259   if (!d)
00260     throw std::runtime_error("couldn't open " + v4l_path);
00261   struct dirent *ent, *ent2, *ent3;
00262   int fd, ret;
00263   struct v4l2_capability v4l2_cap;
00264   while ((ent = readdir(d)) != NULL)
00265   {
00266     if (strncmp(ent->d_name, "video", 5))
00267       continue; // ignore anything not starting with "video"
00268     string dev_name = string("/dev/") + string(ent->d_name);
00269     printf("enumerating %s ...\n", dev_name.c_str());
00270     if ((fd = open(dev_name.c_str(), O_RDWR)) == -1)
00271       throw std::runtime_error("couldn't open " + dev_name + "  perhaps the " +
00272                                "permissions are not set correctly?");
00273     if ((ret = ioctl(fd, VIDIOC_QUERYCAP, &v4l2_cap)) < 0)
00274       throw std::runtime_error("couldn't query " + dev_name);
00275     printf("name = [%s]\n", v4l2_cap.card);
00276     printf("driver = [%s]\n", v4l2_cap.driver);
00277     printf("location = [%s]\n", v4l2_cap.bus_info);
00278     close(fd);
00279     string v4l_dev_path = v4l_path + string("/") + string(ent->d_name) + 
00280                           string("/device");
00281     // my kernel is using /sys/class/video4linux/videoN/device/inputX/id
00282     DIR *d2 = opendir(v4l_dev_path.c_str());
00283     if (!d2)
00284       throw std::runtime_error("couldn't open " + v4l_dev_path);
00285     string input_dir;
00286     while ((ent2 = readdir(d2)) != NULL)
00287     {
00288       if (strncmp(ent2->d_name, "input", 5))
00289         continue; // ignore anything not beginning with "input"
00290 
00291       DIR *input = opendir((v4l_dev_path + string("/") + string(ent2->d_name)).c_str());
00292       bool output_set = false;
00293       while ((ent3 = readdir(input)) != NULL)
00294       {
00295         if (!strncmp(ent3->d_name, "input", 5))
00296         {
00297           input_dir = (string("input/") + string(ent3->d_name )).c_str();
00298           output_set = true;
00299           break;
00300         }
00301       }
00302       if (!output_set)
00303         input_dir = ent2->d_name; 
00304       break;
00305     }
00306     closedir(d2);
00307     if (!input_dir.length())
00308       throw std::runtime_error("couldn't find input dir in " + v4l_dev_path);
00309     string vid_fname = v4l_dev_path + string("/") + input_dir + 
00310                        string("/id/vendor");
00311     string pid_fname = v4l_dev_path + string("/") + input_dir + 
00312                        string("/id/product");
00313     string ver_fname = v4l_dev_path + string("/") + input_dir + 
00314                        string("/id/version");
00315     char vid[5], pid[5], ver[5];
00316     FILE *vid_fp = fopen(vid_fname.c_str(), "r");
00317     if (!vid_fp)
00318       throw std::runtime_error("couldn't open " + vid_fname);
00319     if (!fgets(vid, sizeof(vid), vid_fp))
00320       throw std::runtime_error("couldn't read VID from " + vid_fname);
00321     fclose(vid_fp);
00322     vid[4] = 0;
00323     printf("vid = [%s]\n", vid);
00324     FILE *pid_fp = fopen(pid_fname.c_str(), "r");
00325     if (!pid_fp)
00326       throw std::runtime_error("couldn't open " + pid_fname);
00327     if (!fgets(pid, sizeof(pid), pid_fp))
00328       throw std::runtime_error("couldn't read PID from " + pid_fname);
00329     fclose(pid_fp);
00330     printf("pid = [%s]\n", pid);
00331     FILE *ver_fp = fopen(ver_fname.c_str(), "r");
00332     if (!ver_fp)
00333       throw std::runtime_error("couldn't open " + ver_fname);
00334     if (!fgets(ver, sizeof(ver), ver_fp))
00335       throw std::runtime_error("couldn't read version from " + ver_fname);
00336     fclose(ver_fp);
00337     printf("ver = [%s]\n", ver);
00338   }
00339   closedir(d);
00340 }
00341 
00342 // saturate input into [0, 255]
00343 inline unsigned char sat(float f)
00344 {
00345   return (unsigned char)( f >= 255 ? 255 : (f < 0 ? 0 : f)); 
00346 }
00347 
00348 int Cam::grab(unsigned char **frame, uint32_t &bytes_used)
00349 {
00350   *frame = NULL;
00351   int ret = 0;
00352   fd_set rdset;
00353   timeval timeout;
00354   FD_ZERO(&rdset);
00355   FD_SET(fd, &rdset);
00356   timeout.tv_sec = 1;
00357   timeout.tv_usec = 0;
00358   bytes_used = 0;
00359   ret = select(fd + 1, &rdset, NULL, NULL, &timeout);
00360   if (ret == 0)
00361   {
00362     printf("select timeout in grab\n");
00363     return -1;
00364   }
00365   else if (ret < 0)
00366   {
00367     perror("couldn't grab image");
00368     return -1;
00369   }
00370   if (!FD_ISSET(fd, &rdset))
00371     return -1;
00372   memset(&buf, 0, sizeof(buf));
00373   buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
00374   buf.memory = V4L2_MEMORY_MMAP;
00375   if (ioctl(fd, VIDIOC_DQBUF, &buf) < 0)
00376     throw std::runtime_error("couldn't dequeue buffer");
00377   bytes_used = buf.bytesused;
00378   if (mode == MODE_RGB)
00379   {
00380     int num_pixels_different = 0; // just look at the Y channel
00381     unsigned char *pyuv = (unsigned char *)mem[buf.index];
00382     // yuyv is 2 bytes per pixel. step through every pixel pair.
00383     unsigned char *prgb = rgb_frame;
00384     unsigned char *pyuv_last = last_yuv_frame;
00385     for (unsigned i = 0; i < width * height * 2; i += 4)
00386     {
00387       *prgb++ = sat(pyuv[i]+1.402f  *(pyuv[i+3]-128));
00388       *prgb++ = sat(pyuv[i]-0.34414f*(pyuv[i+1]-128)-0.71414f*(pyuv[i+3]-128));
00389       *prgb++ = sat(pyuv[i]+1.772f  *(pyuv[i+1]-128));
00390       *prgb++ = sat(pyuv[i+2]+1.402f*(pyuv[i+3]-128));
00391       *prgb++ = sat(pyuv[i+2]-0.34414f*(pyuv[i+1]-128)-0.71414f*(pyuv[i+3]-128));
00392       *prgb++ = sat(pyuv[i+2]+1.772f*(pyuv[i+1]-128));
00393       if ((int)pyuv[i] - (int)pyuv_last[i] > motion_threshold_luminance ||
00394           (int)pyuv_last[i] - (int)pyuv[i] > motion_threshold_luminance)
00395         num_pixels_different++;
00396       if ((int)pyuv[i+2] - (int)pyuv_last[i+2] > motion_threshold_luminance ||
00397           (int)pyuv_last[i+2] - (int)pyuv[i+2] > motion_threshold_luminance)
00398         num_pixels_different++;
00399       
00400       // this gives bgr images...
00401       /*
00402       *prgb++ = sat(pyuv[i]+1.772f  *(pyuv[i+1]-128));
00403       *prgb++ = sat(pyuv[i]-0.34414f*(pyuv[i+1]-128)-0.71414f*(pyuv[i+3]-128));
00404       *prgb++ = sat(pyuv[i]+1.402f  *(pyuv[i+3]-128));
00405       *prgb++ = sat(pyuv[i+2]+1.772f*(pyuv[i+1]-128));
00406       *prgb++ = sat(pyuv[i+2]-0.34414f*(pyuv[i+1]-128)-0.71414f*(pyuv[i+3]-128));
00407       *prgb++ = sat(pyuv[i+2]+1.402f*(pyuv[i+3]-128));
00408       */
00409     }
00410     memcpy(last_yuv_frame, pyuv, width * height * 2);
00411     if (num_pixels_different > motion_threshold_count) // default: always true
00412       *frame = rgb_frame;
00413     else
00414     {
00415       *frame = NULL; // not enough luminance change
00416       release(buf.index); // let go of this image
00417     }
00418   }
00419   else if (mode == MODE_YUYV)
00420   {
00421     *frame = (uint8_t *)mem[buf.index];
00422   }
00423   else // mode == MODE_JPEG
00424   {
00425     //if (bytes_used > 100)
00426       *frame = (unsigned char *)mem[buf.index];
00427   }
00428   return buf.index;
00429 }
00430 
00431 void Cam::release(unsigned buf_idx)
00432 {
00433   if (buf_idx < NUM_BUFFER)
00434     if (ioctl(fd, VIDIOC_QBUF, &buf) < 0)
00435       throw std::runtime_error("couldn't requeue buffer");
00436 }
00437 
00438 void Cam::set_control(uint32_t id, int val)
00439 {
00440   v4l2_control c;
00441   c.id = id;
00442 
00443   if (ioctl(fd, VIDIOC_G_CTRL, &c) == 0)
00444   {
00445     printf("current value of %d is %d\n", id, c.value);
00446     /*
00447     perror("unable to get control");
00448     throw std::runtime_error("unable to get control");
00449     */
00450   }
00451   c.value = val;
00452   if (ioctl(fd, VIDIOC_S_CTRL, &c) < 0)
00453   {
00454     perror("unable to set control");
00455     throw std::runtime_error("unable to set control");
00456   }
00457 }
00458 
00459 void Cam::set_motion_thresholds(int lum, int count)
00460 {
00461   motion_threshold_luminance = lum;
00462   motion_threshold_count = count;
00463 }
00464 


uvc_cam2
Author(s): Morgan Quigley, extended and maintained by Juergen Sturm
autogenerated on Mon Oct 6 2014 00:08:38