camera_feed_linux.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. /**************************************************************************/
  2. /* camera_feed_linux.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "camera_feed_linux.h"
  31. #include <fcntl.h>
  32. #include <sys/ioctl.h>
  33. #include <sys/mman.h>
  34. #include <unistd.h>
  35. void CameraFeedLinux::update_buffer_thread_func(void *p_func) {
  36. if (p_func) {
  37. CameraFeedLinux *camera_feed_linux = (CameraFeedLinux *)p_func;
  38. camera_feed_linux->_update_buffer();
  39. }
  40. }
  41. void CameraFeedLinux::_update_buffer() {
  42. while (!exit_flag.is_set()) {
  43. _read_frame();
  44. usleep(10000);
  45. }
  46. }
  47. void CameraFeedLinux::_query_device(const String &p_device_name) {
  48. file_descriptor = open(p_device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  49. ERR_FAIL_COND_MSG(file_descriptor == -1, vformat("Cannot open file descriptor for %s. Error: %d.", p_device_name, errno));
  50. struct v4l2_capability capability;
  51. if (ioctl(file_descriptor, VIDIOC_QUERYCAP, &capability) == -1) {
  52. ERR_FAIL_MSG(vformat("Cannot query device. Error: %d.", errno));
  53. }
  54. name = String((char *)capability.card);
  55. for (int index = 0;; index++) {
  56. struct v4l2_fmtdesc fmtdesc;
  57. memset(&fmtdesc, 0, sizeof(fmtdesc));
  58. fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  59. fmtdesc.index = index;
  60. if (ioctl(file_descriptor, VIDIOC_ENUM_FMT, &fmtdesc) == -1) {
  61. break;
  62. }
  63. for (int res_index = 0;; res_index++) {
  64. struct v4l2_frmsizeenum frmsizeenum;
  65. memset(&frmsizeenum, 0, sizeof(frmsizeenum));
  66. frmsizeenum.pixel_format = fmtdesc.pixelformat;
  67. frmsizeenum.index = res_index;
  68. if (ioctl(file_descriptor, VIDIOC_ENUM_FRAMESIZES, &frmsizeenum) == -1) {
  69. break;
  70. }
  71. for (int framerate_index = 0;; framerate_index++) {
  72. struct v4l2_frmivalenum frmivalenum;
  73. memset(&frmivalenum, 0, sizeof(frmivalenum));
  74. frmivalenum.pixel_format = fmtdesc.pixelformat;
  75. frmivalenum.width = frmsizeenum.discrete.width;
  76. frmivalenum.height = frmsizeenum.discrete.height;
  77. frmivalenum.index = framerate_index;
  78. if (ioctl(file_descriptor, VIDIOC_ENUM_FRAMEINTERVALS, &frmivalenum) == -1) {
  79. if (framerate_index == 0) {
  80. _add_format(fmtdesc, frmsizeenum.discrete, -1, 1);
  81. }
  82. break;
  83. }
  84. _add_format(fmtdesc, frmsizeenum.discrete, frmivalenum.discrete.numerator, frmivalenum.discrete.denominator);
  85. }
  86. }
  87. }
  88. close(file_descriptor);
  89. }
  90. void CameraFeedLinux::_add_format(v4l2_fmtdesc p_description, v4l2_frmsize_discrete p_size, int p_frame_numerator, int p_frame_denominator) {
  91. FeedFormat feed_format;
  92. feed_format.width = p_size.width;
  93. feed_format.height = p_size.height;
  94. feed_format.format = String((char *)p_description.description);
  95. feed_format.frame_numerator = p_frame_numerator;
  96. feed_format.frame_denominator = p_frame_denominator;
  97. feed_format.pixel_format = p_description.pixelformat;
  98. print_verbose(vformat("%s %dx%d@%d/%dfps", (char *)p_description.description, p_size.width, p_size.height, p_frame_denominator, p_frame_numerator));
  99. formats.push_back(feed_format);
  100. }
  101. bool CameraFeedLinux::_request_buffers() {
  102. struct v4l2_requestbuffers requestbuffers;
  103. memset(&requestbuffers, 0, sizeof(requestbuffers));
  104. requestbuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  105. requestbuffers.memory = V4L2_MEMORY_MMAP;
  106. requestbuffers.count = 4;
  107. if (ioctl(file_descriptor, VIDIOC_REQBUFS, &requestbuffers) == -1) {
  108. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_REQBUFS) error: %d.", errno));
  109. }
  110. ERR_FAIL_COND_V_MSG(requestbuffers.count < 2, false, "Not enough buffers granted.");
  111. buffer_count = requestbuffers.count;
  112. buffers = new StreamingBuffer[buffer_count];
  113. for (unsigned int i = 0; i < buffer_count; i++) {
  114. struct v4l2_buffer buffer;
  115. memset(&buffer, 0, sizeof(buffer));
  116. buffer.type = requestbuffers.type;
  117. buffer.memory = V4L2_MEMORY_MMAP;
  118. buffer.index = i;
  119. if (ioctl(file_descriptor, VIDIOC_QUERYBUF, &buffer) == -1) {
  120. delete[] buffers;
  121. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_QUERYBUF) error: %d.", errno));
  122. }
  123. buffers[i].length = buffer.length;
  124. buffers[i].start = mmap(nullptr, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, file_descriptor, buffer.m.offset);
  125. if (buffers[i].start == MAP_FAILED) {
  126. for (unsigned int b = 0; b < i; b++) {
  127. _unmap_buffers(i);
  128. }
  129. delete[] buffers;
  130. ERR_FAIL_V_MSG(false, "Mapping buffers failed.");
  131. }
  132. }
  133. return true;
  134. }
  135. bool CameraFeedLinux::_start_capturing() {
  136. for (unsigned int i = 0; i < buffer_count; i++) {
  137. struct v4l2_buffer buffer;
  138. memset(&buffer, 0, sizeof(buffer));
  139. buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  140. buffer.memory = V4L2_MEMORY_MMAP;
  141. buffer.index = i;
  142. if (ioctl(file_descriptor, VIDIOC_QBUF, &buffer) == -1) {
  143. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_QBUF) error: %d.", errno));
  144. }
  145. }
  146. enum v4l2_buf_type type;
  147. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  148. if (ioctl(file_descriptor, VIDIOC_STREAMON, &type) == -1) {
  149. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_STREAMON) error: %d.", errno));
  150. }
  151. return true;
  152. }
  153. void CameraFeedLinux::_read_frame() {
  154. struct v4l2_buffer buffer;
  155. memset(&buffer, 0, sizeof(buffer));
  156. buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  157. buffer.memory = V4L2_MEMORY_MMAP;
  158. if (ioctl(file_descriptor, VIDIOC_DQBUF, &buffer) == -1) {
  159. if (errno != EAGAIN) {
  160. print_error(vformat("ioctl(VIDIOC_DQBUF) error: %d.", errno));
  161. exit_flag.set();
  162. }
  163. return;
  164. }
  165. buffer_decoder->decode(buffers[buffer.index]);
  166. if (ioctl(file_descriptor, VIDIOC_QBUF, &buffer) == -1) {
  167. print_error(vformat("ioctl(VIDIOC_QBUF) error: %d.", errno));
  168. }
  169. emit_signal(SNAME("frame_changed"));
  170. }
  171. void CameraFeedLinux::_stop_capturing() {
  172. enum v4l2_buf_type type;
  173. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  174. if (ioctl(file_descriptor, VIDIOC_STREAMOFF, &type) == -1) {
  175. print_error(vformat("ioctl(VIDIOC_STREAMOFF) error: %d.", errno));
  176. }
  177. }
  178. void CameraFeedLinux::_unmap_buffers(unsigned int p_count) {
  179. for (unsigned int i = 0; i < p_count; i++) {
  180. munmap(buffers[i].start, buffers[i].length);
  181. }
  182. }
  183. void CameraFeedLinux::_start_thread() {
  184. exit_flag.clear();
  185. thread = memnew(Thread);
  186. thread->start(CameraFeedLinux::update_buffer_thread_func, this);
  187. }
  188. String CameraFeedLinux::get_device_name() const {
  189. return device_name;
  190. }
  191. bool CameraFeedLinux::activate_feed() {
  192. ERR_FAIL_COND_V_MSG(selected_format == -1, false, "CameraFeed format needs to be set before activating.");
  193. file_descriptor = open(device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  194. if (_request_buffers() && _start_capturing()) {
  195. buffer_decoder = _create_buffer_decoder();
  196. _start_thread();
  197. return true;
  198. }
  199. ERR_FAIL_V_MSG(false, "Could not activate feed.");
  200. }
  201. BufferDecoder *CameraFeedLinux::_create_buffer_decoder() {
  202. switch (formats[selected_format].pixel_format) {
  203. case V4L2_PIX_FMT_MJPEG:
  204. case V4L2_PIX_FMT_JPEG:
  205. return memnew(JpegBufferDecoder(this));
  206. case V4L2_PIX_FMT_YUYV:
  207. case V4L2_PIX_FMT_YYUV:
  208. case V4L2_PIX_FMT_YVYU:
  209. case V4L2_PIX_FMT_UYVY:
  210. case V4L2_PIX_FMT_VYUY: {
  211. String output = parameters["output"];
  212. if (output == "separate") {
  213. return memnew(SeparateYuyvBufferDecoder(this));
  214. }
  215. if (output == "grayscale") {
  216. return memnew(YuyvToGrayscaleBufferDecoder(this));
  217. }
  218. if (output == "copy") {
  219. return memnew(CopyBufferDecoder(this, false));
  220. }
  221. return memnew(YuyvToRgbBufferDecoder(this));
  222. }
  223. default:
  224. return memnew(CopyBufferDecoder(this, true));
  225. }
  226. }
  227. void CameraFeedLinux::deactivate_feed() {
  228. exit_flag.set();
  229. thread->wait_to_finish();
  230. memdelete(thread);
  231. _stop_capturing();
  232. _unmap_buffers(buffer_count);
  233. delete[] buffers;
  234. memdelete(buffer_decoder);
  235. for (int i = 0; i < CameraServer::FEED_IMAGES; i++) {
  236. RID placeholder = RenderingServer::get_singleton()->texture_2d_placeholder_create();
  237. RenderingServer::get_singleton()->texture_replace(texture[i], placeholder);
  238. }
  239. base_width = 0;
  240. base_height = 0;
  241. close(file_descriptor);
  242. emit_signal(SNAME("format_changed"));
  243. }
  244. Array CameraFeedLinux::get_formats() const {
  245. Array result;
  246. for (const FeedFormat &format : formats) {
  247. Dictionary dictionary;
  248. dictionary["width"] = format.width;
  249. dictionary["height"] = format.height;
  250. dictionary["format"] = format.format;
  251. dictionary["frame_numerator"] = format.frame_numerator;
  252. dictionary["frame_denominator"] = format.frame_denominator;
  253. result.push_back(dictionary);
  254. }
  255. return result;
  256. }
  257. CameraFeed::FeedFormat CameraFeedLinux::get_format() const {
  258. FeedFormat feed_format = {};
  259. return selected_format == -1 ? feed_format : formats[selected_format];
  260. }
  261. bool CameraFeedLinux::set_format(int p_index, const Dictionary &p_parameters) {
  262. ERR_FAIL_COND_V_MSG(active, false, "Feed is active.");
  263. ERR_FAIL_INDEX_V_MSG(p_index, formats.size(), false, "Invalid format index.");
  264. FeedFormat feed_format = formats[p_index];
  265. file_descriptor = open(device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  266. struct v4l2_format format;
  267. memset(&format, 0, sizeof(format));
  268. format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  269. format.fmt.pix.width = feed_format.width;
  270. format.fmt.pix.height = feed_format.height;
  271. format.fmt.pix.pixelformat = feed_format.pixel_format;
  272. if (ioctl(file_descriptor, VIDIOC_S_FMT, &format) == -1) {
  273. close(file_descriptor);
  274. ERR_FAIL_V_MSG(false, vformat("Cannot set format, error: %d.", errno));
  275. }
  276. if (feed_format.frame_numerator > 0) {
  277. struct v4l2_streamparm param;
  278. memset(&param, 0, sizeof(param));
  279. param.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  280. param.parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
  281. param.parm.capture.timeperframe.numerator = feed_format.frame_numerator;
  282. param.parm.capture.timeperframe.denominator = feed_format.frame_denominator;
  283. if (ioctl(file_descriptor, VIDIOC_S_PARM, &param) == -1) {
  284. close(file_descriptor);
  285. ERR_FAIL_V_MSG(false, vformat("Cannot set framerate, error: %d.", errno));
  286. }
  287. }
  288. close(file_descriptor);
  289. parameters = p_parameters.duplicate();
  290. selected_format = p_index;
  291. emit_signal(SNAME("format_changed"));
  292. return true;
  293. }
  294. CameraFeedLinux::CameraFeedLinux(const String &p_device_name) :
  295. CameraFeed() {
  296. device_name = p_device_name;
  297. _query_device(device_name);
  298. }
  299. CameraFeedLinux::~CameraFeedLinux() {
  300. if (is_active()) {
  301. deactivate_feed();
  302. }
  303. }