camera_feed_linux.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 "servers/rendering_server.h"
  32. #include <fcntl.h>
  33. #include <sys/ioctl.h>
  34. #include <sys/mman.h>
  35. #include <unistd.h>
  36. void CameraFeedLinux::update_buffer_thread_func(void *p_func) {
  37. if (p_func) {
  38. CameraFeedLinux *camera_feed_linux = (CameraFeedLinux *)p_func;
  39. camera_feed_linux->_update_buffer();
  40. }
  41. }
  42. void CameraFeedLinux::_update_buffer() {
  43. while (!exit_flag.is_set()) {
  44. _read_frame();
  45. usleep(10000);
  46. }
  47. }
  48. void CameraFeedLinux::_query_device(const String &p_device_name) {
  49. file_descriptor = open(p_device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  50. ERR_FAIL_COND_MSG(file_descriptor == -1, vformat("Cannot open file descriptor for %s. Error: %d.", p_device_name, errno));
  51. struct v4l2_capability capability;
  52. if (ioctl(file_descriptor, VIDIOC_QUERYCAP, &capability) == -1) {
  53. ERR_FAIL_MSG(vformat("Cannot query device. Error: %d.", errno));
  54. }
  55. name = String((char *)capability.card);
  56. for (int index = 0;; index++) {
  57. struct v4l2_fmtdesc fmtdesc;
  58. memset(&fmtdesc, 0, sizeof(fmtdesc));
  59. fmtdesc.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  60. fmtdesc.index = index;
  61. if (ioctl(file_descriptor, VIDIOC_ENUM_FMT, &fmtdesc) == -1) {
  62. break;
  63. }
  64. for (int res_index = 0;; res_index++) {
  65. struct v4l2_frmsizeenum frmsizeenum;
  66. memset(&frmsizeenum, 0, sizeof(frmsizeenum));
  67. frmsizeenum.pixel_format = fmtdesc.pixelformat;
  68. frmsizeenum.index = res_index;
  69. if (ioctl(file_descriptor, VIDIOC_ENUM_FRAMESIZES, &frmsizeenum) == -1) {
  70. break;
  71. }
  72. for (int framerate_index = 0;; framerate_index++) {
  73. struct v4l2_frmivalenum frmivalenum;
  74. memset(&frmivalenum, 0, sizeof(frmivalenum));
  75. frmivalenum.pixel_format = fmtdesc.pixelformat;
  76. frmivalenum.width = frmsizeenum.discrete.width;
  77. frmivalenum.height = frmsizeenum.discrete.height;
  78. frmivalenum.index = framerate_index;
  79. if (ioctl(file_descriptor, VIDIOC_ENUM_FRAMEINTERVALS, &frmivalenum) == -1) {
  80. if (framerate_index == 0) {
  81. _add_format(fmtdesc, frmsizeenum.discrete, -1, 1);
  82. }
  83. break;
  84. }
  85. _add_format(fmtdesc, frmsizeenum.discrete, frmivalenum.discrete.numerator, frmivalenum.discrete.denominator);
  86. }
  87. }
  88. }
  89. close(file_descriptor);
  90. }
  91. void CameraFeedLinux::_add_format(v4l2_fmtdesc p_description, v4l2_frmsize_discrete p_size, int p_frame_numerator, int p_frame_denominator) {
  92. FeedFormat feed_format;
  93. feed_format.width = p_size.width;
  94. feed_format.height = p_size.height;
  95. feed_format.format = String((char *)p_description.description);
  96. feed_format.frame_numerator = p_frame_numerator;
  97. feed_format.frame_denominator = p_frame_denominator;
  98. feed_format.pixel_format = p_description.pixelformat;
  99. print_verbose(vformat("%s %dx%d@%d/%dfps", (char *)p_description.description, p_size.width, p_size.height, p_frame_denominator, p_frame_numerator));
  100. formats.push_back(feed_format);
  101. }
  102. bool CameraFeedLinux::_request_buffers() {
  103. struct v4l2_requestbuffers requestbuffers;
  104. memset(&requestbuffers, 0, sizeof(requestbuffers));
  105. requestbuffers.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  106. requestbuffers.memory = V4L2_MEMORY_MMAP;
  107. requestbuffers.count = 4;
  108. if (ioctl(file_descriptor, VIDIOC_REQBUFS, &requestbuffers) == -1) {
  109. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_REQBUFS) error: %d.", errno));
  110. }
  111. ERR_FAIL_COND_V_MSG(requestbuffers.count < 2, false, "Not enough buffers granted.");
  112. buffer_count = requestbuffers.count;
  113. buffers = new StreamingBuffer[buffer_count];
  114. for (unsigned int i = 0; i < buffer_count; i++) {
  115. struct v4l2_buffer buffer;
  116. memset(&buffer, 0, sizeof(buffer));
  117. buffer.type = requestbuffers.type;
  118. buffer.memory = V4L2_MEMORY_MMAP;
  119. buffer.index = i;
  120. if (ioctl(file_descriptor, VIDIOC_QUERYBUF, &buffer) == -1) {
  121. delete[] buffers;
  122. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_QUERYBUF) error: %d.", errno));
  123. }
  124. buffers[i].length = buffer.length;
  125. buffers[i].start = mmap(nullptr, buffer.length, PROT_READ | PROT_WRITE, MAP_SHARED, file_descriptor, buffer.m.offset);
  126. if (buffers[i].start == MAP_FAILED) {
  127. for (unsigned int b = 0; b < i; b++) {
  128. _unmap_buffers(i);
  129. }
  130. delete[] buffers;
  131. ERR_FAIL_V_MSG(false, "Mapping buffers failed.");
  132. }
  133. }
  134. return true;
  135. }
  136. bool CameraFeedLinux::_start_capturing() {
  137. for (unsigned int i = 0; i < buffer_count; i++) {
  138. struct v4l2_buffer buffer;
  139. memset(&buffer, 0, sizeof(buffer));
  140. buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  141. buffer.memory = V4L2_MEMORY_MMAP;
  142. buffer.index = i;
  143. if (ioctl(file_descriptor, VIDIOC_QBUF, &buffer) == -1) {
  144. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_QBUF) error: %d.", errno));
  145. }
  146. }
  147. enum v4l2_buf_type type;
  148. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  149. if (ioctl(file_descriptor, VIDIOC_STREAMON, &type) == -1) {
  150. ERR_FAIL_V_MSG(false, vformat("ioctl(VIDIOC_STREAMON) error: %d.", errno));
  151. }
  152. return true;
  153. }
  154. void CameraFeedLinux::_read_frame() {
  155. struct v4l2_buffer buffer;
  156. memset(&buffer, 0, sizeof(buffer));
  157. buffer.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  158. buffer.memory = V4L2_MEMORY_MMAP;
  159. if (ioctl(file_descriptor, VIDIOC_DQBUF, &buffer) == -1) {
  160. if (errno != EAGAIN) {
  161. print_error(vformat("ioctl(VIDIOC_DQBUF) error: %d.", errno));
  162. exit_flag.set();
  163. }
  164. return;
  165. }
  166. buffer_decoder->decode(buffers[buffer.index]);
  167. if (ioctl(file_descriptor, VIDIOC_QBUF, &buffer) == -1) {
  168. print_error(vformat("ioctl(VIDIOC_QBUF) error: %d.", errno));
  169. }
  170. emit_signal(SNAME("frame_changed"));
  171. }
  172. void CameraFeedLinux::_stop_capturing() {
  173. enum v4l2_buf_type type;
  174. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  175. if (ioctl(file_descriptor, VIDIOC_STREAMOFF, &type) == -1) {
  176. print_error(vformat("ioctl(VIDIOC_STREAMOFF) error: %d.", errno));
  177. }
  178. }
  179. void CameraFeedLinux::_unmap_buffers(unsigned int p_count) {
  180. for (unsigned int i = 0; i < p_count; i++) {
  181. munmap(buffers[i].start, buffers[i].length);
  182. }
  183. }
  184. void CameraFeedLinux::_start_thread() {
  185. exit_flag.clear();
  186. thread = memnew(Thread);
  187. thread->start(CameraFeedLinux::update_buffer_thread_func, this);
  188. }
  189. String CameraFeedLinux::get_device_name() const {
  190. return device_name;
  191. }
  192. bool CameraFeedLinux::activate_feed() {
  193. ERR_FAIL_COND_V_MSG(selected_format == -1, false, "CameraFeed format needs to be set before activating.");
  194. file_descriptor = open(device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  195. if (_request_buffers() && _start_capturing()) {
  196. buffer_decoder = _create_buffer_decoder();
  197. _start_thread();
  198. return true;
  199. }
  200. ERR_FAIL_V_MSG(false, "Could not activate feed.");
  201. }
  202. BufferDecoder *CameraFeedLinux::_create_buffer_decoder() {
  203. switch (formats[selected_format].pixel_format) {
  204. case V4L2_PIX_FMT_MJPEG:
  205. case V4L2_PIX_FMT_JPEG:
  206. return memnew(JpegBufferDecoder(this));
  207. case V4L2_PIX_FMT_YUYV:
  208. case V4L2_PIX_FMT_YYUV:
  209. case V4L2_PIX_FMT_YVYU:
  210. case V4L2_PIX_FMT_UYVY:
  211. case V4L2_PIX_FMT_VYUY: {
  212. String output = parameters["output"];
  213. if (output == "separate") {
  214. return memnew(SeparateYuyvBufferDecoder(this));
  215. }
  216. if (output == "grayscale") {
  217. return memnew(YuyvToGrayscaleBufferDecoder(this));
  218. }
  219. if (output == "copy") {
  220. return memnew(CopyBufferDecoder(this, false));
  221. }
  222. return memnew(YuyvToRgbBufferDecoder(this));
  223. }
  224. default:
  225. return memnew(CopyBufferDecoder(this, true));
  226. }
  227. }
  228. void CameraFeedLinux::deactivate_feed() {
  229. exit_flag.set();
  230. thread->wait_to_finish();
  231. memdelete(thread);
  232. _stop_capturing();
  233. _unmap_buffers(buffer_count);
  234. delete[] buffers;
  235. memdelete(buffer_decoder);
  236. for (int i = 0; i < CameraServer::FEED_IMAGES; i++) {
  237. RID placeholder = RenderingServer::get_singleton()->texture_2d_placeholder_create();
  238. RenderingServer::get_singleton()->texture_replace(texture[i], placeholder);
  239. }
  240. base_width = 0;
  241. base_height = 0;
  242. close(file_descriptor);
  243. emit_signal(SNAME("format_changed"));
  244. }
  245. Array CameraFeedLinux::get_formats() const {
  246. Array result;
  247. for (const FeedFormat &format : formats) {
  248. Dictionary dictionary;
  249. dictionary["width"] = format.width;
  250. dictionary["height"] = format.height;
  251. dictionary["format"] = format.format;
  252. dictionary["frame_numerator"] = format.frame_numerator;
  253. dictionary["frame_denominator"] = format.frame_denominator;
  254. result.push_back(dictionary);
  255. }
  256. return result;
  257. }
  258. CameraFeed::FeedFormat CameraFeedLinux::get_format() const {
  259. FeedFormat feed_format = {};
  260. return selected_format == -1 ? feed_format : formats[selected_format];
  261. }
  262. bool CameraFeedLinux::set_format(int p_index, const Dictionary &p_parameters) {
  263. ERR_FAIL_COND_V_MSG(active, false, "Feed is active.");
  264. ERR_FAIL_INDEX_V_MSG(p_index, formats.size(), false, "Invalid format index.");
  265. FeedFormat feed_format = formats[p_index];
  266. file_descriptor = open(device_name.ascii(), O_RDWR | O_NONBLOCK, 0);
  267. struct v4l2_format format;
  268. memset(&format, 0, sizeof(format));
  269. format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  270. format.fmt.pix.width = feed_format.width;
  271. format.fmt.pix.height = feed_format.height;
  272. format.fmt.pix.pixelformat = feed_format.pixel_format;
  273. if (ioctl(file_descriptor, VIDIOC_S_FMT, &format) == -1) {
  274. close(file_descriptor);
  275. ERR_FAIL_V_MSG(false, vformat("Cannot set format, error: %d.", errno));
  276. }
  277. if (feed_format.frame_numerator > 0) {
  278. struct v4l2_streamparm param;
  279. memset(&param, 0, sizeof(param));
  280. param.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  281. param.parm.capture.capability = V4L2_CAP_TIMEPERFRAME;
  282. param.parm.capture.timeperframe.numerator = feed_format.frame_numerator;
  283. param.parm.capture.timeperframe.denominator = feed_format.frame_denominator;
  284. if (ioctl(file_descriptor, VIDIOC_S_PARM, &param) == -1) {
  285. close(file_descriptor);
  286. ERR_FAIL_V_MSG(false, vformat("Cannot set framerate, error: %d.", errno));
  287. }
  288. }
  289. close(file_descriptor);
  290. parameters = p_parameters.duplicate();
  291. selected_format = p_index;
  292. emit_signal(SNAME("format_changed"));
  293. return true;
  294. }
  295. CameraFeedLinux::CameraFeedLinux(const String &p_device_name) :
  296. CameraFeed() {
  297. device_name = p_device_name;
  298. _query_device(device_name);
  299. }
  300. CameraFeedLinux::~CameraFeedLinux() {
  301. if (is_active()) {
  302. deactivate_feed();
  303. }
  304. }