v4l2-input.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  1. /*
  2. Copyright (C) 2014 by Leonhard Oelke <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <unistd.h>
  17. #include <string.h>
  18. #include <inttypes.h>
  19. #include <fcntl.h>
  20. #include <dirent.h>
  21. #include <sys/mman.h>
  22. #include <sys/time.h>
  23. #include <sys/types.h>
  24. #include <sys/ioctl.h>
  25. #include <sys/select.h>
  26. #include <linux/videodev2.h>
  27. #include <util/threading.h>
  28. #include <util/bmem.h>
  29. #include <util/dstr.h>
  30. #include <obs.h>
  31. #define V4L2_DATA(voidptr) struct v4l2_data *data = voidptr;
  32. #define timeval2ns(tv) \
  33. (((uint64_t) tv.tv_sec * 1000000000) + ((uint64_t) tv.tv_usec * 1000))
  34. struct v4l2_buffer_data {
  35. size_t length;
  36. void *start;
  37. };
  38. struct v4l2_data {
  39. char *device;
  40. pthread_t thread;
  41. os_event_t event;
  42. obs_source_t source;
  43. uint_fast32_t linesize;
  44. uint64_t frames;
  45. int_fast32_t dev;
  46. int_fast32_t pixelformat;
  47. int_fast32_t width;
  48. int_fast32_t height;
  49. int_fast32_t fps_numerator;
  50. int_fast32_t fps_denominator;
  51. uint_fast32_t buf_count;
  52. struct v4l2_buffer_data *buf;
  53. };
  54. static enum video_format v4l2_to_obs_video_format(uint_fast32_t format)
  55. {
  56. switch (format) {
  57. case V4L2_PIX_FMT_YVYU: return VIDEO_FORMAT_YVYU;
  58. case V4L2_PIX_FMT_YUYV: return VIDEO_FORMAT_YUY2;
  59. case V4L2_PIX_FMT_UYVY: return VIDEO_FORMAT_UYVY;
  60. case V4L2_PIX_FMT_NV12: return VIDEO_FORMAT_NV12;
  61. case V4L2_PIX_FMT_YUV420: return VIDEO_FORMAT_I420;
  62. default: return VIDEO_FORMAT_NONE;
  63. }
  64. }
  65. /*
  66. * used to store framerate and resolution values
  67. */
  68. static int pack_tuple(int a, int b)
  69. {
  70. return (a << 16) | (b & 0xffff);
  71. }
  72. static void unpack_tuple(int *a, int *b, int packed)
  73. {
  74. *a = packed >> 16;
  75. *b = packed & 0xffff;
  76. }
  77. /*
  78. * start capture
  79. */
  80. static int_fast32_t v4l2_start_capture(struct v4l2_data *data)
  81. {
  82. enum v4l2_buf_type type;
  83. for (uint_fast32_t i = 0; i < data->buf_count; ++i) {
  84. struct v4l2_buffer buf;
  85. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  86. buf.memory = V4L2_MEMORY_MMAP;
  87. buf.index = i;
  88. if (ioctl(data->dev, VIDIOC_QBUF, &buf) < 0) {
  89. blog(LOG_ERROR, "v4l2-input: unable to queue buffer");
  90. return -1;
  91. }
  92. }
  93. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  94. if (ioctl(data->dev, VIDIOC_STREAMON, &type) < 0) {
  95. blog(LOG_ERROR, "v4l2-input: unable to start stream");
  96. return -1;
  97. }
  98. return 0;
  99. }
  100. /*
  101. * stop capture
  102. */
  103. static int_fast32_t v4l2_stop_capture(struct v4l2_data *data)
  104. {
  105. enum v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  106. if (ioctl(data->dev, VIDIOC_STREAMOFF, &type) < 0) {
  107. blog(LOG_ERROR, "v4l2-input: unable to stop stream");
  108. }
  109. return 0;
  110. }
  111. /*
  112. * create memory mapping for buffers
  113. */
  114. static int_fast32_t v4l2_create_mmap(struct v4l2_data *data)
  115. {
  116. struct v4l2_requestbuffers req;
  117. req.count = 4;
  118. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  119. req.memory = V4L2_MEMORY_MMAP;
  120. if (ioctl(data->dev, VIDIOC_REQBUFS, &req) < 0) {
  121. blog(LOG_DEBUG, "v4l2-input: request for buffers failed !");
  122. return -1;
  123. }
  124. if (req.count < 2) {
  125. blog(LOG_DEBUG, "v4l2-input: not enough memory !");
  126. return -1;
  127. }
  128. data->buf_count = req.count;
  129. data->buf = bzalloc(req.count * sizeof(struct v4l2_buffer_data));
  130. for (uint_fast32_t i = 0; i < req.count; ++i) {
  131. struct v4l2_buffer buf;
  132. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  133. buf.memory = V4L2_MEMORY_MMAP;
  134. buf.index = i;
  135. if (ioctl(data->dev, VIDIOC_QUERYBUF, &buf) < 0) {
  136. blog(LOG_ERROR, "v4l2-input: failed to query buffer");
  137. return -1;
  138. }
  139. data->buf[i].length = buf.length;
  140. data->buf[i].start = mmap(NULL, buf.length,
  141. PROT_READ | PROT_WRITE, MAP_SHARED,
  142. data->dev, buf.m.offset);
  143. if (data->buf[i].start == MAP_FAILED) {
  144. blog(LOG_ERROR, "v4l2-input: mmap for buffer failed");
  145. return -1;
  146. }
  147. }
  148. return 0;
  149. }
  150. /*
  151. * destroy memory mapping for buffers
  152. */
  153. static void v4l2_destroy_mmap(struct v4l2_data *data)
  154. {
  155. for(uint_fast32_t i = 0; i < data->buf_count; ++i) {
  156. if (data->buf[i].start != MAP_FAILED)
  157. munmap(data->buf[i].start, data->buf[i].length);
  158. }
  159. data->buf_count = 0;
  160. bfree(data->buf);
  161. }
  162. /*
  163. * Worker thread to get video data
  164. */
  165. static void *v4l2_thread(void *vptr)
  166. {
  167. V4L2_DATA(vptr);
  168. if (v4l2_start_capture(data) < 0)
  169. goto exit;
  170. while (os_event_try(data->event) == EAGAIN) {
  171. int r;
  172. fd_set fds;
  173. struct timeval tv;
  174. struct v4l2_buffer buf;
  175. struct source_frame out;
  176. FD_ZERO(&fds);
  177. FD_SET(data->dev, &fds);
  178. tv.tv_sec = 1;
  179. tv.tv_usec = 0;
  180. r = select(data->dev + 1, &fds, NULL, NULL, &tv);
  181. if (r < 0) {
  182. if (errno == EINTR)
  183. continue;
  184. blog(LOG_DEBUG, "v4l2-input: select failed");
  185. break;
  186. } else if (r == 0) {
  187. blog(LOG_DEBUG, "v4l2-input: select timeout");
  188. continue;
  189. }
  190. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  191. buf.memory = V4L2_MEMORY_MMAP;
  192. if (ioctl(data->dev, VIDIOC_DQBUF, &buf) < 0) {
  193. if (errno == EAGAIN)
  194. continue;
  195. blog(LOG_DEBUG, "v4l2-input: failed to dequeue buffer");
  196. break;
  197. }
  198. video_format_get_parameters(VIDEO_CS_709, VIDEO_RANGE_PARTIAL,
  199. out.color_matrix, out.color_range_min,
  200. out.color_range_max);
  201. out.data[0] = (uint8_t *) data->buf[buf.index].start;
  202. out.linesize[0] = data->linesize;
  203. out.width = data->width;
  204. out.height = data->height;
  205. out.timestamp = timeval2ns(buf.timestamp);
  206. out.format = v4l2_to_obs_video_format(data->pixelformat);
  207. obs_source_output_video(data->source, &out);
  208. if (ioctl(data->dev, VIDIOC_QBUF, &buf) < 0) {
  209. blog(LOG_DEBUG, "v4l2-input: failed to enqueue buffer");
  210. break;
  211. }
  212. data->frames++;
  213. }
  214. exit:
  215. v4l2_stop_capture(data);
  216. return NULL;
  217. }
  218. static const char* v4l2_getname(void)
  219. {
  220. /* TODO: locale */
  221. return "V4L2 Capture Input";
  222. }
  223. static void v4l2_defaults(obs_data_t settings)
  224. {
  225. obs_data_set_default_int(settings, "pixelformat", V4L2_PIX_FMT_YUYV);
  226. obs_data_set_default_int(settings, "resolution",
  227. pack_tuple(640, 480));
  228. obs_data_set_default_int(settings, "framerate", pack_tuple(1, 30));
  229. }
  230. /*
  231. * List available devices
  232. */
  233. static void v4l2_device_list(obs_property_t prop, obs_data_t settings)
  234. {
  235. DIR *dirp;
  236. struct dirent *dp;
  237. int fd;
  238. struct v4l2_capability video_cap;
  239. struct dstr device;
  240. bool first = true;
  241. obs_property_list_clear(prop);
  242. dstr_init_copy(&device, "/dev/");
  243. dirp = opendir("/sys/class/video4linux");
  244. if (dirp) {
  245. while ((dp = readdir(dirp)) != NULL) {
  246. dstr_resize(&device, 5);
  247. dstr_cat(&device, dp->d_name);
  248. if ((fd = open(device.array,
  249. O_RDWR | O_NONBLOCK)) == -1) {
  250. continue;
  251. }
  252. if (ioctl(fd, VIDIOC_QUERYCAP, &video_cap) == -1) {
  253. continue;
  254. } else if (video_cap.capabilities &
  255. V4L2_CAP_VIDEO_CAPTURE) {
  256. obs_property_list_add_string(prop,
  257. (char *) video_cap.card,
  258. device.array);
  259. if (first) {
  260. obs_data_setstring(settings,
  261. "device_id", device.array);
  262. first = false;
  263. }
  264. }
  265. close(fd);
  266. }
  267. closedir(dirp);
  268. }
  269. dstr_free(&device);
  270. }
  271. /*
  272. * List formats for device
  273. */
  274. static void v4l2_format_list(int dev, obs_property_t prop)
  275. {
  276. struct v4l2_fmtdesc fmt;
  277. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  278. fmt.index = 0;
  279. obs_property_list_clear(prop);
  280. while (ioctl(dev, VIDIOC_ENUM_FMT, &fmt) == 0) {
  281. if (v4l2_to_obs_video_format(fmt.pixelformat)
  282. != VIDEO_FORMAT_NONE) {
  283. obs_property_list_add_int(prop,
  284. (char *) fmt.description,
  285. fmt.pixelformat);
  286. }
  287. fmt.index++;
  288. }
  289. }
  290. /*
  291. * List resolutions for device and format
  292. */
  293. static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat,
  294. obs_property_t prop)
  295. {
  296. struct v4l2_frmsizeenum frmsize;
  297. frmsize.pixel_format = pixelformat;
  298. frmsize.index = 0;
  299. struct dstr buffer;
  300. dstr_init(&buffer);
  301. obs_property_list_clear(prop);
  302. while (ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize) == 0) {
  303. dstr_printf(&buffer, "%dx%d", frmsize.discrete.width,
  304. frmsize.discrete.height);
  305. obs_property_list_add_int(prop, buffer.array,
  306. pack_tuple(frmsize.discrete.width,
  307. frmsize.discrete.height));
  308. frmsize.index++;
  309. }
  310. dstr_free(&buffer);
  311. }
  312. /*
  313. * List framerates for device and resolution
  314. */
  315. static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat,
  316. uint_fast32_t width, uint_fast32_t height, obs_property_t prop)
  317. {
  318. struct v4l2_frmivalenum frmival;
  319. frmival.pixel_format = pixelformat;
  320. frmival.width = width;
  321. frmival.height = height;
  322. frmival.index = 0;
  323. struct dstr buffer;
  324. dstr_init(&buffer);
  325. obs_property_list_clear(prop);
  326. while (ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) == 0) {
  327. float fps = (float) frmival.discrete.denominator /
  328. frmival.discrete.numerator;
  329. int pack = pack_tuple(frmival.discrete.numerator,
  330. frmival.discrete.denominator);
  331. dstr_printf(&buffer, "%.2f", fps);
  332. obs_property_list_add_int(prop, buffer.array, pack);
  333. frmival.index++;
  334. }
  335. dstr_free(&buffer);
  336. }
  337. /*
  338. * Device selected callback
  339. */
  340. static bool device_selected(obs_properties_t props, obs_property_t p,
  341. obs_data_t settings)
  342. {
  343. UNUSED_PARAMETER(p);
  344. int dev = open(obs_data_getstring(settings, "device_id"),
  345. O_RDWR | O_NONBLOCK);
  346. obs_property_t prop = obs_properties_get(props, "pixelformat");
  347. v4l2_format_list(dev, prop);
  348. obs_property_modified(prop, settings);
  349. close(dev);
  350. return true;
  351. }
  352. /*
  353. * Format selected callback
  354. */
  355. static bool format_selected(obs_properties_t props, obs_property_t p,
  356. obs_data_t settings)
  357. {
  358. UNUSED_PARAMETER(p);
  359. int dev = open(obs_data_getstring(settings, "device_id"),
  360. O_RDWR | O_NONBLOCK);
  361. obs_property_t prop = obs_properties_get(props, "resolution");
  362. v4l2_resolution_list(dev, obs_data_getint(settings, "pixelformat"),
  363. prop);
  364. obs_property_modified(prop, settings);
  365. close(dev);
  366. return true;
  367. }
  368. /*
  369. * Resolution selected callback
  370. */
  371. static bool resolution_selected(obs_properties_t props, obs_property_t p,
  372. obs_data_t settings)
  373. {
  374. UNUSED_PARAMETER(p);
  375. int width, height;
  376. int dev = open(obs_data_getstring(settings, "device_id"),
  377. O_RDWR | O_NONBLOCK);
  378. obs_property_t prop = obs_properties_get(props, "framerate");
  379. unpack_tuple(&width, &height, obs_data_getint(settings,
  380. "resolution"));
  381. v4l2_framerate_list(dev, obs_data_getint(settings, "pixelformat"),
  382. width, height, prop);
  383. obs_property_modified(prop, settings);
  384. close(dev);
  385. return true;
  386. }
  387. static obs_properties_t v4l2_properties(void)
  388. {
  389. /* TODO: locale */
  390. obs_properties_t props = obs_properties_create();
  391. obs_property_t device_list = obs_properties_add_list(props, "device_id",
  392. "Device", OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  393. obs_property_t format_list = obs_properties_add_list(props,
  394. "pixelformat", "Image Format", OBS_COMBO_TYPE_LIST,
  395. OBS_COMBO_FORMAT_INT);
  396. obs_property_t resolution_list = obs_properties_add_list(props,
  397. "resolution", "Resolution", OBS_COMBO_TYPE_LIST,
  398. OBS_COMBO_FORMAT_INT);
  399. obs_properties_add_list(props, "framerate", "Frame Rate",
  400. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  401. v4l2_device_list(device_list, NULL);
  402. obs_property_set_modified_callback(device_list, device_selected);
  403. obs_property_set_modified_callback(format_list, format_selected);
  404. obs_property_set_modified_callback(resolution_list,
  405. resolution_selected);
  406. return props;
  407. }
  408. static uint32_t v4l2_getwidth(void *vptr)
  409. {
  410. V4L2_DATA(vptr);
  411. return data->width;
  412. }
  413. static uint32_t v4l2_getheight(void *vptr)
  414. {
  415. V4L2_DATA(vptr);
  416. return data->height;
  417. }
  418. static void v4l2_terminate(struct v4l2_data *data)
  419. {
  420. if (data->thread) {
  421. os_event_signal(data->event);
  422. pthread_join(data->thread, NULL);
  423. os_event_destroy(data->event);
  424. }
  425. if (data->buf_count)
  426. v4l2_destroy_mmap(data);
  427. if (data->dev != -1) {
  428. close(data->dev);
  429. data->dev = -1;
  430. }
  431. }
  432. static void v4l2_destroy(void *vptr)
  433. {
  434. V4L2_DATA(vptr);
  435. if (!data)
  436. return;
  437. v4l2_terminate(data);
  438. if (data->device)
  439. bfree(data->device);
  440. bfree(data);
  441. }
  442. static void v4l2_init(struct v4l2_data *data)
  443. {
  444. struct v4l2_format fmt;
  445. struct v4l2_streamparm par;
  446. data->dev = open(data->device, O_RDWR | O_NONBLOCK);
  447. if (data->dev == -1) {
  448. blog(LOG_ERROR, "v4l2-input: Unable to open device: %s",
  449. data->device);
  450. goto fail;
  451. }
  452. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  453. fmt.fmt.pix.width = data->width;
  454. fmt.fmt.pix.height = data->height;
  455. fmt.fmt.pix.pixelformat = data->pixelformat;
  456. fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
  457. if (ioctl(data->dev, VIDIOC_S_FMT, &fmt) < 0) {
  458. blog(LOG_DEBUG, "v4l2-input: unable to set format");
  459. goto fail;
  460. }
  461. data->pixelformat = fmt.fmt.pix.pixelformat;
  462. data->width = fmt.fmt.pix.width;
  463. data->height = fmt.fmt.pix.height;
  464. par.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  465. par.parm.capture.timeperframe.numerator = data->fps_numerator;
  466. par.parm.capture.timeperframe.denominator = data->fps_denominator;
  467. if (ioctl(data->dev, VIDIOC_S_PARM, &par) < 0) {
  468. blog(LOG_DEBUG, "v4l2-input: unable to set params");
  469. goto fail;
  470. }
  471. data->fps_numerator = par.parm.capture.timeperframe.numerator;
  472. data->fps_denominator = par.parm.capture.timeperframe.denominator;
  473. data->linesize = fmt.fmt.pix.bytesperline;
  474. blog(LOG_DEBUG, "v4l2-input: Linesize: %"PRIuFAST32, data->linesize);
  475. if (v4l2_create_mmap(data) < 0) {
  476. blog(LOG_ERROR, "v4l2-input: failed to map buffers");
  477. goto fail;
  478. }
  479. if (os_event_init(&data->event, OS_EVENT_TYPE_MANUAL) != 0)
  480. goto fail;
  481. if (pthread_create(&data->thread, NULL, v4l2_thread, data) != 0)
  482. goto fail;
  483. return;
  484. fail:
  485. blog(LOG_DEBUG, "v4l2-input: initialization failed");
  486. v4l2_terminate(data);
  487. }
  488. static void v4l2_update(void *vptr, obs_data_t settings)
  489. {
  490. V4L2_DATA(vptr);
  491. bool restart = false;
  492. const char *new_device;
  493. int width, height, fps_num, fps_denom;
  494. new_device = obs_data_getstring(settings, "device_id");
  495. if (strlen(new_device) == 0) {
  496. v4l2_device_list(NULL, settings);
  497. new_device = obs_data_getstring(settings, "device_id");
  498. }
  499. if (!data->device || strcmp(data->device, new_device) != 0) {
  500. if (data->device)
  501. bfree(data->device);
  502. data->device = bstrdup(new_device);
  503. restart = true;
  504. }
  505. if (data->pixelformat != obs_data_getint(settings, "pixelformat")) {
  506. data->pixelformat = obs_data_getint(settings, "pixelformat");
  507. restart = true;
  508. }
  509. unpack_tuple(&width, &height, obs_data_getint(settings,
  510. "resolution"));
  511. if (width != data->width || height != data->height) {
  512. restart = true;
  513. }
  514. unpack_tuple(&fps_num, &fps_denom, obs_data_getint(settings,
  515. "framerate"));
  516. if (fps_num != data->fps_numerator
  517. || fps_denom != data->fps_denominator) {
  518. data->fps_numerator = fps_num;
  519. data->fps_denominator = fps_denom;
  520. restart = true;
  521. }
  522. if (restart) {
  523. v4l2_terminate(data);
  524. /* Wait for v4l2_thread to finish before
  525. * updating width and height */
  526. data->width = width;
  527. data->height = height;
  528. v4l2_init(data);
  529. }
  530. }
  531. static void *v4l2_create(obs_data_t settings, obs_source_t source)
  532. {
  533. UNUSED_PARAMETER(settings);
  534. struct v4l2_data *data = bzalloc(sizeof(struct v4l2_data));
  535. data->dev = -1;
  536. data->source = source;
  537. v4l2_update(data, settings);
  538. blog(LOG_DEBUG, "v4l2-input: New input created");
  539. return data;
  540. }
  541. struct obs_source_info v4l2_input = {
  542. .id = "v4l2_input",
  543. .type = OBS_SOURCE_TYPE_INPUT,
  544. .output_flags = OBS_SOURCE_ASYNC_VIDEO,
  545. .getname = v4l2_getname,
  546. .create = v4l2_create,
  547. .destroy = v4l2_destroy,
  548. .update = v4l2_update,
  549. .defaults = v4l2_defaults,
  550. .properties = v4l2_properties,
  551. .getwidth = v4l2_getwidth,
  552. .getheight = v4l2_getheight
  553. };