Visual Servoing Platform  version 3.6.1 under development (2024-05-18)
grabV4l2MultiCpp11Thread.cpp
1 /****************************************************************************
2  *
3  * ViSP, open source Visual Servoing Platform software.
4  * Copyright (C) 2005 - 2023 by Inria. All rights reserved.
5  *
6  * This software is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  * See the file LICENSE.txt at the root directory of this source
11  * distribution for additional information about the GNU GPL.
12  *
13  * For using ViSP with software that can not be combined with the GNU
14  * GPL, please contact Inria about acquiring a ViSP Professional
15  * Edition License.
16  *
17  * See https://visp.inria.fr for more information.
18  *
19  * This software was developed at:
20  * Inria Rennes - Bretagne Atlantique
21  * Campus Universitaire de Beaulieu
22  * 35042 Rennes Cedex
23  * France
24  *
25  * If you have questions regarding the use of this file, please contact
26  * Inria at visp@inria.fr
27  *
28  * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
29  * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
30  *
31  * Description:
32  * Acquire images using 1394 device with cfox (MAC OSX) and display it
33  * using GTK or GTK.
34  *
35 *****************************************************************************/
36 
44 #include <iostream>
45 
46 #include <visp3/core/vpConfig.h>
47 
48 #if defined(VISP_HAVE_V4L2) && (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GTK)) && defined(VISP_HAVE_THREADS)
49 
50 #include <condition_variable>
51 #include <iostream>
52 #include <limits>
53 #include <mutex>
54 #include <queue>
55 #include <thread>
56 
57 #include <visp3/core/vpDisplay.h>
58 #include <visp3/core/vpImageFilter.h>
59 #include <visp3/core/vpIoTools.h>
60 #include <visp3/core/vpTime.h>
61 #include <visp3/gui/vpDisplayGTK.h>
62 #include <visp3/gui/vpDisplayX.h>
63 #include <visp3/io/vpParseArgv.h>
64 #include <visp3/io/vpVideoWriter.h>
65 #include <visp3/sensor/vpV4l2Grabber.h>
66 
67 #define GETOPTARGS "d:oh"
68 
69 namespace
70 {
71 
72 void usage(const char *name, const char *badparam)
73 {
74  fprintf(stdout, "\n\
75 SYNOPSIS:\n\
76  %s [-d <device count>] [-o] [-h]\n\
77 \n\
78 DESCRIPTION:\n\
79  Capture multiple camera streams and save the stream without slowing down the acquisition.\n\
80  \n\
81 OPTIONS: \n\
82  -d <device count> \n\
83  Open the specified number of camera streams.\n\
84  \n\
85  -o \n\
86  Save each stream in a dedicated folder.\n\
87  \n\
88  -h \n\
89  Print the help.\n\n",
90  name);
91 
92  if (badparam)
93  fprintf(stdout, "\nERROR: Bad parameter [%s]\n", badparam);
94 }
95 
96 bool getOptions(int argc, char **argv, unsigned int &deviceCount, bool &saveVideo)
97 {
98  const char *optarg;
99  const char **argv1 = (const char **)argv;
100  int c;
101  while ((c = vpParseArgv::parse(argc, argv1, GETOPTARGS, &optarg)) > 1) {
102 
103  switch (c) {
104  case 'd':
105  deviceCount = (unsigned int)atoi(optarg);
106  break;
107  case 'o':
108  saveVideo = true;
109  break;
110  case 'h':
111  usage(argv[0], nullptr);
112  return false;
113  break;
114 
115  default:
116  usage(argv[0], optarg);
117  return false;
118  break;
119  }
120  }
121 
122  if ((c == 1) || (c == -1)) {
123  // standalone param or error
124  usage(argv[0], nullptr);
125  std::cerr << "ERROR: " << std::endl;
126  std::cerr << " Bad argument " << optarg << std::endl << std::endl;
127  return false;
128  }
129 
130  return true;
131 }
132 
133 // Code adapted from the original author Dan MaĊĦek to be compatible with ViSP
134 // image
135 class vpFrameQueue
136 {
137 
138 public:
139  struct vpCancelled_t
140  { };
141 
142  vpFrameQueue()
143  : m_cancelled(false), m_cond(), m_queueColor(), m_maxQueueSize(std::numeric_limits<size_t>::max()), m_mutex()
144  { }
145 
146  void cancel()
147  {
148  std::lock_guard<std::mutex> lock(m_mutex);
149  m_cancelled = true;
150  m_cond.notify_all();
151  }
152 
153  // Push the image to save in the queue (FIFO)
154  void push(const vpImage<vpRGBa> &image)
155  {
156  std::lock_guard<std::mutex> lock(m_mutex);
157 
158  m_queueColor.push(image);
159 
160  // Pop extra images in the queue
161  while (m_queueColor.size() > m_maxQueueSize) {
162  m_queueColor.pop();
163  }
164 
165  m_cond.notify_one();
166  }
167 
168  // Pop the image to save from the queue (FIFO)
169  vpImage<vpRGBa> pop()
170  {
171  std::unique_lock<std::mutex> lock(m_mutex);
172 
173  while (m_queueColor.empty()) {
174  if (m_cancelled) {
175  throw vpCancelled_t();
176  }
177 
178  m_cond.wait(lock);
179 
180  if (m_cancelled) {
181  throw vpCancelled_t();
182  }
183  }
184 
185  vpImage<vpRGBa> image(m_queueColor.front());
186  m_queueColor.pop();
187 
188  return image;
189  }
190 
191  void setMaxQueueSize(const size_t max_queue_size) { m_maxQueueSize = max_queue_size; }
192 
193 private:
194  bool m_cancelled;
195  std::condition_variable m_cond;
196  std::queue<vpImage<vpRGBa> > m_queueColor;
197  size_t m_maxQueueSize;
198  std::mutex m_mutex;
199 };
200 
201 class vpStorageWorker
202 {
203 
204 public:
205  vpStorageWorker(vpFrameQueue &queue, const std::string &filename, unsigned int width, unsigned int height)
206  : m_queue(queue), m_filename(filename), m_width(width), m_height(height)
207  { }
208 
209  // Thread main loop
210  void run()
211  {
212  vpImage<vpRGBa> O_color(m_height, m_width);
213 
214  vpVideoWriter writer;
215  if (!m_filename.empty()) {
216  writer.setFileName(m_filename);
217  writer.open(O_color);
218  }
219 
220  try {
221  for (;;) {
222  vpImage<vpRGBa> image(m_queue.pop());
223 
224  if (!m_filename.empty()) {
225  writer.saveFrame(image);
226  }
227  }
228  }
229  catch (vpFrameQueue::vpCancelled_t &) {
230  }
231  }
232 
233 private:
234  vpFrameQueue &m_queue;
235  std::string m_filename;
236  unsigned int m_width;
237  unsigned int m_height;
238 };
239 
240 class vpShareImage
241 {
242 
243 private:
244  bool m_cancelled;
245  std::condition_variable m_cond;
246  std::mutex m_mutex;
247  unsigned char *m_pImgData;
248  unsigned int m_totalSize;
249 
250 public:
251  struct vpCancelled_t
252  { };
253 
254  vpShareImage() : m_cancelled(false), m_cond(), m_mutex(), m_pImgData(nullptr), m_totalSize(0) { }
255 
256  virtual ~vpShareImage()
257  {
258  if (m_pImgData != nullptr) {
259  delete[] m_pImgData;
260  }
261  }
262 
263  void cancel()
264  {
265  std::lock_guard<std::mutex> lock(m_mutex);
266  m_cancelled = true;
267  m_cond.notify_all();
268  }
269 
270  // Get the image to display
271  void getImage(unsigned char *const imageData, const unsigned int totalSize)
272  {
273  std::unique_lock<std::mutex> lock(m_mutex);
274 
275  if (m_cancelled) {
276  throw vpCancelled_t();
277  }
278 
279  m_cond.wait(lock);
280 
281  if (m_cancelled) {
282  throw vpCancelled_t();
283  }
284 
285  // Copy to imageData
286  if (totalSize <= m_totalSize) {
287  memcpy(imageData, m_pImgData, totalSize * sizeof(unsigned char));
288  }
289  else {
290  std::cerr << "totalSize <= m_totalSize !" << std::endl;
291  }
292  }
293 
294  bool isCancelled()
295  {
296  std::lock_guard<std::mutex> lock(m_mutex);
297  return m_cancelled;
298  }
299 
300  // Set the image to display
301  void setImage(const unsigned char *const imageData, const unsigned int totalSize)
302  {
303  std::lock_guard<std::mutex> lock(m_mutex);
304 
305  if (m_pImgData == nullptr || m_totalSize != totalSize) {
306  m_totalSize = totalSize;
307 
308  if (m_pImgData != nullptr) {
309  delete[] m_pImgData;
310  }
311 
312  m_pImgData = new unsigned char[m_totalSize];
313  }
314 
315  // Copy from imageData
316  memcpy(m_pImgData, imageData, m_totalSize * sizeof(unsigned char));
317 
318  m_cond.notify_one();
319  }
320 };
321 
322 void capture(vpV4l2Grabber *const pGrabber, vpShareImage &share_image)
323 {
324  vpImage<vpRGBa> local_img;
325 
326  // Open the camera stream
327  pGrabber->open(local_img);
328 
329  while (true) {
330  if (share_image.isCancelled()) {
331  break;
332  }
333 
334  pGrabber->acquire(local_img);
335 
336  // Update share_image
337  share_image.setImage((unsigned char *)local_img.bitmap, local_img.getSize() * 4);
338  }
339 }
340 
341 void display(unsigned int width, unsigned int height, int win_x, int win_y, unsigned int deviceId,
342  vpShareImage &share_image, vpFrameQueue &queue, bool save)
343 {
344  vpImage<vpRGBa> local_img(height, width);
345 
346 #if defined(VISP_HAVE_X11)
348 #elif defined(VISP_HAVE_GTK)
350 #endif
351 
352  // Init Display
353  {
354  std::stringstream ss;
355  ss << "Camera stream " << deviceId;
356  display.init(local_img, win_x, win_y, ss.str());
357  }
358 
359  try {
361 
362  vpImage<unsigned char> I_red(height, width), I_green(height, width), I_blue(height, width), I_alpha(height, width);
363  vpImage<unsigned char> I_red_gaussian(height, width), I_green_gaussian(height, width),
364  I_blue_gaussian(height, width);
365  vpImage<double> I_red_gaussian_double, I_green_gaussian_double, I_blue_gaussian_double;
366 
367  bool exit = false, gaussian_blur = false;
368  while (!exit) {
369  double t = vpTime::measureTimeMs();
370 
371  // Get image
372  share_image.getImage((unsigned char *)local_img.bitmap, local_img.getSize() * 4);
373 
374  // Apply gaussian blur to simulate a computation on the image
375  if (gaussian_blur) {
376  // Split channels
377  vpImageConvert::split(local_img, &I_red, &I_green, &I_blue, &I_alpha);
378  vpImageConvert::convert(I_red, I_red_gaussian_double);
379  vpImageConvert::convert(I_green, I_green_gaussian_double);
380  vpImageConvert::convert(I_blue, I_blue_gaussian_double);
381 
382  vpImageFilter::gaussianBlur(I_red_gaussian_double, I_red_gaussian_double, 21);
383  vpImageFilter::gaussianBlur(I_green_gaussian_double, I_green_gaussian_double, 21);
384  vpImageFilter::gaussianBlur(I_blue_gaussian_double, I_blue_gaussian_double, 21);
385 
386  vpImageConvert::convert(I_red_gaussian_double, I_red_gaussian);
387  vpImageConvert::convert(I_green_gaussian_double, I_green_gaussian);
388  vpImageConvert::convert(I_blue_gaussian_double, I_blue_gaussian);
389 
390  vpImageConvert::merge(&I_red_gaussian, &I_green_gaussian, &I_blue_gaussian, nullptr, local_img);
391  }
392 
393  t = vpTime::measureTimeMs() - t;
394  std::stringstream ss;
395  ss << "Time: " << t << " ms";
396 
397  vpDisplay::display(local_img);
398 
399  vpDisplay::displayText(local_img, 20, 20, ss.str(), vpColor::red);
400  vpDisplay::displayText(local_img, 40, 20, "Left click to quit, right click for Gaussian blur.", vpColor::red);
401 
402  vpDisplay::flush(local_img);
403 
404  if (save) {
405  queue.push(local_img);
406  }
407 
408  if (vpDisplay::getClick(local_img, button, false)) {
409  switch (button) {
411  gaussian_blur = !gaussian_blur;
412  break;
413 
414  default:
415  exit = true;
416  break;
417  }
418  }
419  }
420  }
421  catch (vpShareImage::vpCancelled_t &) {
422  std::cout << "Cancelled!" << std::endl;
423  }
424 
425  share_image.cancel();
426 }
427 
428 } // Namespace
429 
430 int main(int argc, char *argv[])
431 {
432  unsigned int deviceCount = 1;
433  unsigned int cameraScale = 1; // 640x480
434  bool saveVideo = false;
435 
436  // Read the command line options
437  if (!getOptions(argc, argv, deviceCount, saveVideo)) {
438  return EXIT_FAILURE;
439  }
440 
441  std::vector<vpV4l2Grabber *> grabbers;
442 
443  const unsigned int offsetX = 100, offsetY = 100;
444  for (unsigned int devicedId = 0; devicedId < deviceCount; devicedId++) {
445  try {
446  vpV4l2Grabber *pGrabber = new vpV4l2Grabber;
447  std::stringstream ss;
448  ss << "/dev/video" << devicedId;
449  pGrabber->setDevice(ss.str());
450  pGrabber->setScale(cameraScale);
451 
452  grabbers.push_back(pGrabber);
453  }
454  catch (const vpException &e) {
455  std::cerr << "Exception: " << e.what() << std::endl;
456  }
457  }
458 
459  std::cout << "Grabbers: " << grabbers.size() << std::endl;
460 
461  std::vector<vpShareImage> share_images(grabbers.size());
462  std::vector<std::thread> capture_threads;
463  std::vector<std::thread> display_threads;
464 
465  // Synchronized queues for each camera stream
466  std::vector<vpFrameQueue> save_queues(grabbers.size());
467  std::vector<vpStorageWorker> storages;
468  std::vector<std::thread> storage_threads;
469 
470  std::string parent_directory = vpTime::getDateTime("%Y-%m-%d_%H.%M.%S");
471  for (size_t deviceId = 0; deviceId < grabbers.size(); deviceId++) {
472  // Start the capture thread for the current camera stream
473  capture_threads.emplace_back(capture, grabbers[deviceId], std::ref(share_images[deviceId]));
474  int win_x = deviceId * offsetX, win_y = deviceId * offsetY;
475 
476  // Start the display thread for the current camera stream
477  display_threads.emplace_back(display, grabbers[deviceId]->getWidth(), grabbers[deviceId]->getHeight(), win_x, win_y,
478  deviceId, std::ref(share_images[deviceId]), std::ref(save_queues[deviceId]),
479  saveVideo);
480 
481  if (saveVideo) {
482  std::stringstream ss;
483  ss << parent_directory << "/Camera_Stream" << deviceId;
484  std::cout << "Create directory: " << ss.str() << std::endl;
485  vpIoTools::makeDirectory(ss.str());
486  ss << "/%06d.png";
487  std::string filename = ss.str();
488 
489  storages.emplace_back(std::ref(save_queues[deviceId]), std::cref(filename), grabbers[deviceId]->getWidth(),
490  grabbers[deviceId]->getHeight());
491  }
492  }
493 
494  if (saveVideo) {
495  for (auto &s : storages) {
496  // Start the storage thread for the current camera stream
497  storage_threads.emplace_back(&vpStorageWorker::run, &s);
498  }
499  }
500 
501  // Join all the worker threads, waiting for them to finish
502  for (auto &ct : capture_threads) {
503  ct.join();
504  }
505 
506  for (auto &dt : display_threads) {
507  dt.join();
508  }
509 
510  // Clean first the grabbers to avoid camera problems when cancelling the
511  // storage threads in the terminal
512  for (auto &g : grabbers) {
513  delete g;
514  }
515 
516  if (saveVideo) {
517  std::cout << "\nWaiting for finishing thread to write images..." << std::endl;
518  }
519 
520  // We're done reading, cancel all the queues
521  for (auto &qu : save_queues) {
522  qu.cancel();
523  }
524 
525  // Join all the worker threads, waiting for them to finish
526  for (auto &st : storage_threads) {
527  st.join();
528  }
529 
530  return EXIT_SUCCESS;
531 }
532 #else
533 #if !(defined(VISP_HAVE_X11) || defined(VISP_HAVE_GTK))
534 int main()
535 {
536  std::cout << "You do not have X11, or GTK functionalities to display images..." << std::endl;
537  std::cout << "Tip if you are on a unix-like system:" << std::endl;
538  std::cout << "- Install X11, configure again ViSP using cmake and build again this example" << std::endl;
539  std::cout << "Tip if you are on a windows-like system:" << std::endl;
540  std::cout << "- Install GTK, configure again ViSP using cmake and build again this example" << std::endl;
541  return EXIT_SUCCESS;
542 }
543 #elif !defined(VISP_HAVE_V4L2)
544 int main()
545 {
546  std::cout << "You do not have Video 4 Linux 2 functionality enabled" << std::endl;
547  std::cout << "Tip if you are on a unix-like system:" << std::endl;
548  std::cout << "- Install libv4l2, configure again ViSP using cmake and build again this example" << std::endl;
549  return EXIT_SUCCESS;
550 }
551 #else
552 int main()
553 {
554  std::cout << "You do not build ViSP with c++11 or higher compiler flag" << std::endl;
555  std::cout << "Tip:" << std::endl;
556  std::cout << "- Configure ViSP again using cmake -DUSE_CXX_STANDARD=11, and build again this example" << std::endl;
557  return EXIT_SUCCESS;
558 }
559 #endif
560 #endif
static const vpColor red
Definition: vpColor.h:211
The vpDisplayGTK allows to display image using the GTK 3rd party library. Thus to enable this class G...
Definition: vpDisplayGTK.h:128
Use the X11 console to display images on unix-like OS. Thus to enable this class X11 should be instal...
Definition: vpDisplayX.h:128
static bool getClick(const vpImage< unsigned char > &I, bool blocking=true)
static void display(const vpImage< unsigned char > &I)
static void flush(const vpImage< unsigned char > &I)
static void displayText(const vpImage< unsigned char > &I, const vpImagePoint &ip, const std::string &s, const vpColor &color)
error that can be emitted by ViSP classes.
Definition: vpException.h:59
const char * what() const
Definition: vpException.cpp:70
static void merge(const vpImage< unsigned char > *R, const vpImage< unsigned char > *G, const vpImage< unsigned char > *B, const vpImage< unsigned char > *a, vpImage< vpRGBa > &RGBa)
static void split(const vpImage< vpRGBa > &src, vpImage< unsigned char > *pR, vpImage< unsigned char > *pG, vpImage< unsigned char > *pB, vpImage< unsigned char > *pa=nullptr)
static void convert(const vpImage< unsigned char > &src, vpImage< vpRGBa > &dest)
static void gaussianBlur(const vpImage< ImageType > &I, vpImage< FilterType > &GI, unsigned int size=7, FilterType sigma=0., bool normalize=true, const vpImage< bool > *p_mask=nullptr)
unsigned int getSize() const
Definition: vpImage.h:224
Type * bitmap
points toward the bitmap
Definition: vpImage.h:139
static void makeDirectory(const std::string &dirname)
Definition: vpIoTools.cpp:983
static bool parse(int *argcPtr, const char **argv, vpArgvInfo *argTable, int flags)
Definition: vpParseArgv.cpp:69
Class that is a wrapper over the Video4Linux2 (V4L2) driver.
void open(vpImage< unsigned char > &I)
void setScale(unsigned scale=vpV4l2Grabber::DEFAULT_SCALE)
void setDevice(const std::string &devname)
void acquire(vpImage< unsigned char > &I)
Class that enables to write easily a video file or a sequence of images.
void saveFrame(vpImage< vpRGBa > &I)
void setFileName(const std::string &filename)
void open(vpImage< vpRGBa > &I)
void display(vpImage< unsigned char > &I, const std::string &title)
Display a gray-scale image.
VISP_EXPORT std::string getDateTime(const std::string &format="%Y/%m/%d %H:%M:%S")
VISP_EXPORT double measureTimeMs()