v4l2-input.c 28 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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/time.h>
  22. #include <sys/types.h>
  23. #include <sys/ioctl.h>
  24. #include <sys/select.h>
  25. #include <linux/videodev2.h>
  26. #include <libv4l2.h>
  27. #include <util/threading.h>
  28. #include <util/bmem.h>
  29. #include <util/dstr.h>
  30. #include <util/platform.h>
  31. #include <obs-module.h>
  32. #include "v4l2-controls.h"
  33. #include "v4l2-helpers.h"
  34. #if HAVE_UDEV
  35. #include "v4l2-udev.h"
  36. #endif
  37. /* The new dv timing api was introduced in Linux 3.4
  38. * Currently we simply disable dv timings when this is not defined */
  39. #if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS)
  40. #define V4L2_IN_CAP_DV_TIMINGS 0
  41. #endif
  42. #define V4L2_DATA(voidptr) struct v4l2_data *data = voidptr;
  43. #define timeval2ns(tv) \
  44. (((uint64_t)tv.tv_sec * 1000000000) + ((uint64_t)tv.tv_usec * 1000))
  45. #define V4L2_FOURCC_STR(code) \
  46. (char[5]) \
  47. { \
  48. code & 0xFF, (code >> 8) & 0xFF, (code >> 16) & 0xFF, \
  49. (code >> 24) & 0xFF, 0 \
  50. }
  51. #define blog(level, msg, ...) blog(level, "v4l2-input: " msg, ##__VA_ARGS__)
  52. /**
  53. * Data structure for the v4l2 source
  54. */
  55. struct v4l2_data {
  56. /* settings */
  57. char *device_id;
  58. int input;
  59. int pixfmt;
  60. int standard;
  61. int dv_timing;
  62. int resolution;
  63. int framerate;
  64. int color_range;
  65. /* internal data */
  66. obs_source_t *source;
  67. pthread_t thread;
  68. os_event_t *event;
  69. bool framerate_unchanged;
  70. bool resolution_unchanged;
  71. int_fast32_t dev;
  72. int width;
  73. int height;
  74. int linesize;
  75. struct v4l2_buffer_data buffers;
  76. };
  77. /* forward declarations */
  78. static void v4l2_init(struct v4l2_data *data);
  79. static void v4l2_terminate(struct v4l2_data *data);
  80. static void v4l2_update(void *vptr, obs_data_t *settings);
  81. /**
  82. * Prepare the output frame structure for obs and compute plane offsets
  83. *
  84. * Basically all data apart from memory pointers and the timestamp is known
  85. * before the capture starts. This function prepares the obs_source_frame
  86. * struct with all the data that is already known.
  87. *
  88. * v4l2 uses a continuous memory segment for all planes so we simply compute
  89. * offsets to add to the start address in order to give obs the correct data
  90. * pointers for the individual planes.
  91. */
  92. static void v4l2_prep_obs_frame(struct v4l2_data *data,
  93. struct obs_source_frame *frame,
  94. size_t *plane_offsets)
  95. {
  96. memset(frame, 0, sizeof(struct obs_source_frame));
  97. memset(plane_offsets, 0, sizeof(size_t) * MAX_AV_PLANES);
  98. frame->width = data->width;
  99. frame->height = data->height;
  100. frame->format = v4l2_to_obs_video_format(data->pixfmt);
  101. video_format_get_parameters(VIDEO_CS_DEFAULT, data->color_range,
  102. frame->color_matrix, frame->color_range_min,
  103. frame->color_range_max);
  104. switch (data->pixfmt) {
  105. case V4L2_PIX_FMT_NV12:
  106. frame->linesize[0] = data->linesize;
  107. frame->linesize[1] = data->linesize;
  108. plane_offsets[1] = data->linesize * data->height;
  109. break;
  110. case V4L2_PIX_FMT_YVU420:
  111. frame->linesize[0] = data->linesize;
  112. frame->linesize[1] = data->linesize / 2;
  113. frame->linesize[2] = data->linesize / 2;
  114. plane_offsets[1] = data->linesize * data->height * 5 / 4;
  115. plane_offsets[2] = data->linesize * data->height;
  116. break;
  117. case V4L2_PIX_FMT_YUV420:
  118. frame->linesize[0] = data->linesize;
  119. frame->linesize[1] = data->linesize / 2;
  120. frame->linesize[2] = data->linesize / 2;
  121. plane_offsets[1] = data->linesize * data->height;
  122. plane_offsets[2] = data->linesize * data->height * 5 / 4;
  123. break;
  124. default:
  125. frame->linesize[0] = data->linesize;
  126. break;
  127. }
  128. }
  129. /*
  130. * Worker thread to get video data
  131. */
  132. static void *v4l2_thread(void *vptr)
  133. {
  134. V4L2_DATA(vptr);
  135. int r;
  136. fd_set fds;
  137. uint8_t *start;
  138. uint64_t frames;
  139. uint64_t first_ts;
  140. struct timeval tv;
  141. struct v4l2_buffer buf;
  142. struct obs_source_frame out;
  143. size_t plane_offsets[MAX_AV_PLANES];
  144. if (v4l2_start_capture(data->dev, &data->buffers) < 0)
  145. goto exit;
  146. frames = 0;
  147. first_ts = 0;
  148. v4l2_prep_obs_frame(data, &out, plane_offsets);
  149. while (os_event_try(data->event) == EAGAIN) {
  150. FD_ZERO(&fds);
  151. FD_SET(data->dev, &fds);
  152. tv.tv_sec = 1;
  153. tv.tv_usec = 0;
  154. r = select(data->dev + 1, &fds, NULL, NULL, &tv);
  155. if (r < 0) {
  156. if (errno == EINTR)
  157. continue;
  158. blog(LOG_DEBUG, "select failed");
  159. break;
  160. } else if (r == 0) {
  161. blog(LOG_DEBUG, "select timeout");
  162. continue;
  163. }
  164. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  165. buf.memory = V4L2_MEMORY_MMAP;
  166. if (v4l2_ioctl(data->dev, VIDIOC_DQBUF, &buf) < 0) {
  167. if (errno == EAGAIN)
  168. continue;
  169. blog(LOG_DEBUG, "failed to dequeue buffer");
  170. break;
  171. }
  172. out.timestamp = timeval2ns(buf.timestamp);
  173. if (!frames)
  174. first_ts = out.timestamp;
  175. out.timestamp -= first_ts;
  176. start = (uint8_t *)data->buffers.info[buf.index].start;
  177. for (uint_fast32_t i = 0; i < MAX_AV_PLANES; ++i)
  178. out.data[i] = start + plane_offsets[i];
  179. obs_source_output_video(data->source, &out);
  180. if (v4l2_ioctl(data->dev, VIDIOC_QBUF, &buf) < 0) {
  181. blog(LOG_DEBUG, "failed to enqueue buffer");
  182. break;
  183. }
  184. frames++;
  185. }
  186. blog(LOG_INFO, "Stopped capture after %" PRIu64 " frames", frames);
  187. exit:
  188. v4l2_stop_capture(data->dev);
  189. return NULL;
  190. }
  191. static const char *v4l2_getname(void *unused)
  192. {
  193. UNUSED_PARAMETER(unused);
  194. return obs_module_text("V4L2Input");
  195. }
  196. static void v4l2_defaults(obs_data_t *settings)
  197. {
  198. obs_data_set_default_int(settings, "input", -1);
  199. obs_data_set_default_int(settings, "pixelformat", -1);
  200. obs_data_set_default_int(settings, "standard", -1);
  201. obs_data_set_default_int(settings, "dv_timing", -1);
  202. obs_data_set_default_int(settings, "resolution", -1);
  203. obs_data_set_default_int(settings, "framerate", -1);
  204. obs_data_set_default_int(settings, "color_range", VIDEO_RANGE_DEFAULT);
  205. obs_data_set_default_bool(settings, "buffering", true);
  206. }
  207. /**
  208. * Enable/Disable all properties for the source.
  209. *
  210. * @note A property that should be ignored can be specified
  211. *
  212. * @param props the source properties
  213. * @param ignore ignore this property
  214. * @param enable enable/disable all properties
  215. */
  216. static void v4l2_props_set_enabled(obs_properties_t *props,
  217. obs_property_t *ignore, bool enable)
  218. {
  219. if (!props)
  220. return;
  221. for (obs_property_t *prop = obs_properties_first(props); prop != NULL;
  222. obs_property_next(&prop)) {
  223. if (prop == ignore)
  224. continue;
  225. obs_property_set_enabled(prop, enable);
  226. }
  227. }
  228. /*
  229. * List available devices
  230. */
  231. static void v4l2_device_list(obs_property_t *prop, obs_data_t *settings)
  232. {
  233. DIR *dirp;
  234. struct dirent *dp;
  235. struct dstr device;
  236. bool cur_device_found;
  237. size_t cur_device_index;
  238. const char *cur_device_name;
  239. #ifdef __FreeBSD__
  240. dirp = opendir("/dev");
  241. #else
  242. dirp = opendir("/sys/class/video4linux");
  243. #endif
  244. if (!dirp)
  245. return;
  246. cur_device_found = false;
  247. cur_device_name = obs_data_get_string(settings, "device_id");
  248. obs_property_list_clear(prop);
  249. dstr_init_copy(&device, "/dev/");
  250. while ((dp = readdir(dirp)) != NULL) {
  251. int fd;
  252. uint32_t caps;
  253. struct v4l2_capability video_cap;
  254. #ifdef __FreeBSD__
  255. if (strstr(dp->d_name, "video") == NULL)
  256. continue;
  257. #endif
  258. if (dp->d_type == DT_DIR)
  259. continue;
  260. dstr_resize(&device, 5);
  261. dstr_cat(&device, dp->d_name);
  262. if ((fd = v4l2_open(device.array, O_RDWR | O_NONBLOCK)) == -1) {
  263. blog(LOG_INFO, "Unable to open %s", device.array);
  264. continue;
  265. }
  266. if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &video_cap) == -1) {
  267. blog(LOG_INFO, "Failed to query capabilities for %s",
  268. device.array);
  269. v4l2_close(fd);
  270. continue;
  271. }
  272. #ifndef V4L2_CAP_DEVICE_CAPS
  273. caps = video_cap.capabilities;
  274. #else
  275. /* ... since Linux 3.3 */
  276. caps = (video_cap.capabilities & V4L2_CAP_DEVICE_CAPS)
  277. ? video_cap.device_caps
  278. : video_cap.capabilities;
  279. #endif
  280. if (!(caps & V4L2_CAP_VIDEO_CAPTURE)) {
  281. blog(LOG_INFO, "%s seems to not support video capture",
  282. device.array);
  283. v4l2_close(fd);
  284. continue;
  285. }
  286. /* make sure device names are unique */
  287. char unique_device_name[68];
  288. sprintf(unique_device_name, "%s (%s)", video_cap.card,
  289. video_cap.bus_info);
  290. obs_property_list_add_string(prop, unique_device_name,
  291. device.array);
  292. blog(LOG_INFO, "Found device '%s' at %s", video_cap.card,
  293. device.array);
  294. /* check if this is the currently used device */
  295. if (cur_device_name && !strcmp(cur_device_name, device.array))
  296. cur_device_found = true;
  297. v4l2_close(fd);
  298. }
  299. /* add currently selected device if not present, but disable it ... */
  300. if (!cur_device_found && cur_device_name && strlen(cur_device_name)) {
  301. cur_device_index = obs_property_list_add_string(
  302. prop, cur_device_name, cur_device_name);
  303. obs_property_list_item_disable(prop, cur_device_index, true);
  304. }
  305. closedir(dirp);
  306. dstr_free(&device);
  307. }
  308. /*
  309. * List inputs for device
  310. */
  311. static void v4l2_input_list(int_fast32_t dev, obs_property_t *prop)
  312. {
  313. struct v4l2_input in;
  314. memset(&in, 0, sizeof(in));
  315. obs_property_list_clear(prop);
  316. while (v4l2_ioctl(dev, VIDIOC_ENUMINPUT, &in) == 0) {
  317. obs_property_list_add_int(prop, (char *)in.name, in.index);
  318. blog(LOG_INFO, "Found input '%s' (Index %d)", in.name,
  319. in.index);
  320. in.index++;
  321. }
  322. }
  323. /*
  324. * List formats for device
  325. */
  326. static void v4l2_format_list(int dev, obs_property_t *prop)
  327. {
  328. struct v4l2_fmtdesc fmt;
  329. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  330. fmt.index = 0;
  331. struct dstr buffer;
  332. dstr_init(&buffer);
  333. obs_property_list_clear(prop);
  334. while (v4l2_ioctl(dev, VIDIOC_ENUM_FMT, &fmt) == 0) {
  335. dstr_copy(&buffer, (char *)fmt.description);
  336. if (fmt.flags & V4L2_FMT_FLAG_EMULATED)
  337. dstr_cat(&buffer, " (Emulated)");
  338. if (v4l2_to_obs_video_format(fmt.pixelformat) !=
  339. VIDEO_FORMAT_NONE) {
  340. obs_property_list_add_int(prop, buffer.array,
  341. fmt.pixelformat);
  342. blog(LOG_INFO, "Pixelformat: %s (available)",
  343. buffer.array);
  344. } else {
  345. blog(LOG_INFO, "Pixelformat: %s (unavailable)",
  346. buffer.array);
  347. }
  348. fmt.index++;
  349. }
  350. dstr_free(&buffer);
  351. }
  352. /*
  353. * List video standards for the device
  354. */
  355. static void v4l2_standard_list(int dev, obs_property_t *prop)
  356. {
  357. struct v4l2_standard std;
  358. std.index = 0;
  359. obs_property_list_clear(prop);
  360. obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
  361. while (v4l2_ioctl(dev, VIDIOC_ENUMSTD, &std) == 0) {
  362. obs_property_list_add_int(prop, (char *)std.name, std.id);
  363. std.index++;
  364. }
  365. }
  366. /*
  367. * List dv timings for the device
  368. */
  369. static void v4l2_dv_timing_list(int dev, obs_property_t *prop)
  370. {
  371. struct v4l2_dv_timings dvt;
  372. struct dstr buf;
  373. int index = 0;
  374. dstr_init(&buf);
  375. obs_property_list_clear(prop);
  376. obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
  377. while (v4l2_enum_dv_timing(dev, &dvt, index) == 0) {
  378. /* i do not pretend to understand, this is from qv4l2 ... */
  379. double h = (double)dvt.bt.height + dvt.bt.vfrontporch +
  380. dvt.bt.vsync + dvt.bt.vbackporch +
  381. dvt.bt.il_vfrontporch + dvt.bt.il_vsync +
  382. dvt.bt.il_vbackporch;
  383. double w = (double)dvt.bt.width + dvt.bt.hfrontporch +
  384. dvt.bt.hsync + dvt.bt.hbackporch;
  385. double i = (dvt.bt.interlaced) ? 2.0f : 1.0f;
  386. double rate = (double)dvt.bt.pixelclock / (w * (h / i));
  387. dstr_printf(&buf, "%ux%u%c %.2f", dvt.bt.width, dvt.bt.height,
  388. (dvt.bt.interlaced) ? 'i' : 'p', rate);
  389. obs_property_list_add_int(prop, buf.array, index);
  390. index++;
  391. }
  392. dstr_free(&buf);
  393. }
  394. /*
  395. * List resolutions for device and format
  396. */
  397. static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat,
  398. obs_property_t *prop)
  399. {
  400. struct v4l2_frmsizeenum frmsize;
  401. frmsize.pixel_format = pixelformat;
  402. frmsize.index = 0;
  403. struct dstr buffer;
  404. dstr_init(&buffer);
  405. obs_property_list_clear(prop);
  406. obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
  407. v4l2_ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize);
  408. switch (frmsize.type) {
  409. case V4L2_FRMSIZE_TYPE_DISCRETE:
  410. while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize) == 0) {
  411. dstr_printf(&buffer, "%dx%d", frmsize.discrete.width,
  412. frmsize.discrete.height);
  413. obs_property_list_add_int(
  414. prop, buffer.array,
  415. v4l2_pack_tuple(frmsize.discrete.width,
  416. frmsize.discrete.height));
  417. frmsize.index++;
  418. }
  419. break;
  420. default:
  421. blog(LOG_INFO, "Stepwise and Continuous framesizes "
  422. "are currently hardcoded");
  423. for (const int *packed = v4l2_framesizes; *packed; ++packed) {
  424. int width;
  425. int height;
  426. v4l2_unpack_tuple(&width, &height, *packed);
  427. dstr_printf(&buffer, "%dx%d", width, height);
  428. obs_property_list_add_int(prop, buffer.array, *packed);
  429. }
  430. break;
  431. }
  432. dstr_free(&buffer);
  433. }
  434. /*
  435. * List framerates for device and resolution
  436. */
  437. static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat,
  438. uint_fast32_t width, uint_fast32_t height,
  439. obs_property_t *prop)
  440. {
  441. struct v4l2_frmivalenum frmival;
  442. frmival.pixel_format = pixelformat;
  443. frmival.width = width;
  444. frmival.height = height;
  445. frmival.index = 0;
  446. struct dstr buffer;
  447. dstr_init(&buffer);
  448. obs_property_list_clear(prop);
  449. obs_property_list_add_int(prop, obs_module_text("LeaveUnchanged"), -1);
  450. v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival);
  451. switch (frmival.type) {
  452. case V4L2_FRMIVAL_TYPE_DISCRETE:
  453. while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) ==
  454. 0) {
  455. float fps = (float)frmival.discrete.denominator /
  456. frmival.discrete.numerator;
  457. int pack =
  458. v4l2_pack_tuple(frmival.discrete.numerator,
  459. frmival.discrete.denominator);
  460. dstr_printf(&buffer, "%.2f", fps);
  461. obs_property_list_add_int(prop, buffer.array, pack);
  462. frmival.index++;
  463. }
  464. break;
  465. default:
  466. blog(LOG_INFO, "Stepwise and Continuous framerates "
  467. "are currently hardcoded");
  468. for (const int *packed = v4l2_framerates; *packed; ++packed) {
  469. int num;
  470. int denom;
  471. v4l2_unpack_tuple(&num, &denom, *packed);
  472. float fps = (float)denom / num;
  473. dstr_printf(&buffer, "%.2f", fps);
  474. obs_property_list_add_int(prop, buffer.array, *packed);
  475. }
  476. break;
  477. }
  478. dstr_free(&buffer);
  479. }
  480. /*
  481. * Device selected callback
  482. */
  483. static bool device_selected(obs_properties_t *props, obs_property_t *p,
  484. obs_data_t *settings)
  485. {
  486. int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
  487. O_RDWR | O_NONBLOCK);
  488. v4l2_props_set_enabled(props, p, (dev == -1) ? false : true);
  489. if (dev == -1)
  490. return false;
  491. obs_property_t *prop = obs_properties_get(props, "input");
  492. obs_properties_t *ctrl_props_new = obs_properties_create();
  493. obs_properties_remove_by_name(props, "controls");
  494. v4l2_input_list(dev, prop);
  495. v4l2_update_controls(dev, ctrl_props_new, settings);
  496. v4l2_close(dev);
  497. obs_properties_add_group(props, "controls",
  498. obs_module_text("CameraCtrls"),
  499. OBS_GROUP_NORMAL, ctrl_props_new);
  500. obs_property_modified(prop, settings);
  501. return true;
  502. }
  503. /*
  504. * Input selected callback
  505. */
  506. static bool input_selected(obs_properties_t *props, obs_property_t *p,
  507. obs_data_t *settings)
  508. {
  509. UNUSED_PARAMETER(p);
  510. int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
  511. O_RDWR | O_NONBLOCK);
  512. if (dev == -1)
  513. return false;
  514. obs_property_t *prop = obs_properties_get(props, "pixelformat");
  515. v4l2_format_list(dev, prop);
  516. v4l2_close(dev);
  517. obs_property_modified(prop, settings);
  518. return true;
  519. }
  520. /*
  521. * Format selected callback
  522. */
  523. static bool format_selected(obs_properties_t *props, obs_property_t *p,
  524. obs_data_t *settings)
  525. {
  526. UNUSED_PARAMETER(p);
  527. int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
  528. O_RDWR | O_NONBLOCK);
  529. if (dev == -1)
  530. return false;
  531. int input = (int)obs_data_get_int(settings, "input");
  532. uint32_t caps = 0;
  533. if (v4l2_get_input_caps(dev, input, &caps) < 0)
  534. return false;
  535. caps &= V4L2_IN_CAP_STD | V4L2_IN_CAP_DV_TIMINGS;
  536. obs_property_t *resolution = obs_properties_get(props, "resolution");
  537. obs_property_t *framerate = obs_properties_get(props, "framerate");
  538. obs_property_t *standard = obs_properties_get(props, "standard");
  539. obs_property_t *dv_timing = obs_properties_get(props, "dv_timing");
  540. obs_property_set_visible(resolution, (!caps) ? true : false);
  541. obs_property_set_visible(framerate, (!caps) ? true : false);
  542. obs_property_set_visible(standard,
  543. (caps & V4L2_IN_CAP_STD) ? true : false);
  544. obs_property_set_visible(
  545. dv_timing, (caps & V4L2_IN_CAP_DV_TIMINGS) ? true : false);
  546. if (!caps) {
  547. v4l2_resolution_list(dev,
  548. obs_data_get_int(settings, "pixelformat"),
  549. resolution);
  550. }
  551. if (caps & V4L2_IN_CAP_STD)
  552. v4l2_standard_list(dev, standard);
  553. if (caps & V4L2_IN_CAP_DV_TIMINGS)
  554. v4l2_dv_timing_list(dev, dv_timing);
  555. v4l2_close(dev);
  556. if (!caps)
  557. obs_property_modified(resolution, settings);
  558. if (caps & V4L2_IN_CAP_STD)
  559. obs_property_modified(standard, settings);
  560. if (caps & V4L2_IN_CAP_DV_TIMINGS)
  561. obs_property_modified(dv_timing, settings);
  562. return true;
  563. }
  564. /*
  565. * Resolution selected callback
  566. */
  567. static bool resolution_selected(obs_properties_t *props, obs_property_t *p,
  568. obs_data_t *settings)
  569. {
  570. UNUSED_PARAMETER(p);
  571. int width, height;
  572. int dev = v4l2_open(obs_data_get_string(settings, "device_id"),
  573. O_RDWR | O_NONBLOCK);
  574. if (dev == -1)
  575. return false;
  576. obs_property_t *prop = obs_properties_get(props, "framerate");
  577. v4l2_unpack_tuple(&width, &height,
  578. obs_data_get_int(settings, "resolution"));
  579. v4l2_framerate_list(dev, obs_data_get_int(settings, "pixelformat"),
  580. width, height, prop);
  581. v4l2_close(dev);
  582. obs_property_modified(prop, settings);
  583. return true;
  584. }
  585. #if HAVE_UDEV
  586. /**
  587. * Device added callback
  588. *
  589. * If everything went fine we can start capturing again when the device is
  590. * reconnected
  591. */
  592. static void device_added(void *vptr, calldata_t *calldata)
  593. {
  594. V4L2_DATA(vptr);
  595. obs_source_update_properties(data->source);
  596. const char *dev;
  597. calldata_get_string(calldata, "device", &dev);
  598. if (strcmp(data->device_id, dev))
  599. return;
  600. blog(LOG_INFO, "Device %s reconnected", dev);
  601. v4l2_init(data);
  602. }
  603. /**
  604. * Device removed callback
  605. *
  606. * We stop recording here so we don't block the device node
  607. */
  608. static void device_removed(void *vptr, calldata_t *calldata)
  609. {
  610. V4L2_DATA(vptr);
  611. obs_source_update_properties(data->source);
  612. const char *dev;
  613. calldata_get_string(calldata, "device", &dev);
  614. if (strcmp(data->device_id, dev))
  615. return;
  616. blog(LOG_INFO, "Device %s disconnected", dev);
  617. v4l2_terminate(data);
  618. }
  619. #endif
  620. static obs_properties_t *v4l2_properties(void *vptr)
  621. {
  622. V4L2_DATA(vptr);
  623. obs_properties_t *props = obs_properties_create();
  624. obs_property_t *device_list = obs_properties_add_list(
  625. props, "device_id", obs_module_text("Device"),
  626. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  627. obs_property_t *input_list = obs_properties_add_list(
  628. props, "input", obs_module_text("Input"), OBS_COMBO_TYPE_LIST,
  629. OBS_COMBO_FORMAT_INT);
  630. obs_property_t *format_list = obs_properties_add_list(
  631. props, "pixelformat", obs_module_text("VideoFormat"),
  632. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  633. obs_property_t *standard_list = obs_properties_add_list(
  634. props, "standard", obs_module_text("VideoStandard"),
  635. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  636. obs_property_set_visible(standard_list, false);
  637. obs_property_t *dv_timing_list = obs_properties_add_list(
  638. props, "dv_timing", obs_module_text("DVTiming"),
  639. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  640. obs_property_set_visible(dv_timing_list, false);
  641. obs_property_t *resolution_list = obs_properties_add_list(
  642. props, "resolution", obs_module_text("Resolution"),
  643. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  644. obs_properties_add_list(props, "framerate",
  645. obs_module_text("FrameRate"),
  646. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  647. obs_property_t *color_range_list = obs_properties_add_list(
  648. props, "color_range", obs_module_text("ColorRange"),
  649. OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  650. obs_property_list_add_int(color_range_list,
  651. obs_module_text("ColorRange.Default"),
  652. VIDEO_RANGE_DEFAULT);
  653. obs_property_list_add_int(color_range_list,
  654. obs_module_text("ColorRange.Partial"),
  655. VIDEO_RANGE_PARTIAL);
  656. obs_property_list_add_int(color_range_list,
  657. obs_module_text("ColorRange.Full"),
  658. VIDEO_RANGE_FULL);
  659. obs_properties_add_bool(props, "buffering",
  660. obs_module_text("UseBuffering"));
  661. // a group to contain the camera control
  662. obs_properties_t *ctrl_props = obs_properties_create();
  663. obs_properties_add_group(props, "controls",
  664. obs_module_text("CameraCtrls"),
  665. OBS_GROUP_NORMAL, ctrl_props);
  666. obs_data_t *settings = obs_source_get_settings(data->source);
  667. v4l2_device_list(device_list, settings);
  668. obs_data_release(settings);
  669. obs_property_set_modified_callback(device_list, device_selected);
  670. obs_property_set_modified_callback(input_list, input_selected);
  671. obs_property_set_modified_callback(format_list, format_selected);
  672. obs_property_set_modified_callback(resolution_list,
  673. resolution_selected);
  674. return props;
  675. }
  676. static void v4l2_terminate(struct v4l2_data *data)
  677. {
  678. if (data->thread) {
  679. os_event_signal(data->event);
  680. pthread_join(data->thread, NULL);
  681. os_event_destroy(data->event);
  682. data->thread = 0;
  683. }
  684. v4l2_destroy_mmap(&data->buffers);
  685. if (data->dev != -1) {
  686. v4l2_close(data->dev);
  687. data->dev = -1;
  688. }
  689. }
  690. static void v4l2_destroy(void *vptr)
  691. {
  692. V4L2_DATA(vptr);
  693. if (!data)
  694. return;
  695. v4l2_terminate(data);
  696. if (data->device_id)
  697. bfree(data->device_id);
  698. #if HAVE_UDEV
  699. signal_handler_t *sh = v4l2_get_udev_signalhandler();
  700. signal_handler_disconnect(sh, "device_added", device_added, data);
  701. signal_handler_disconnect(sh, "device_removed", device_removed, data);
  702. v4l2_unref_udev();
  703. #endif
  704. bfree(data);
  705. }
  706. /**
  707. * Initialize the v4l2 device
  708. *
  709. * This function:
  710. * - tries to open the device
  711. * - sets pixelformat and requested resolution
  712. * - sets the requested framerate
  713. * - maps the buffers
  714. * - starts the capture thread
  715. */
  716. static void v4l2_init(struct v4l2_data *data)
  717. {
  718. uint32_t input_caps;
  719. int fps_num, fps_denom;
  720. blog(LOG_INFO, "Start capture from %s", data->device_id);
  721. data->dev = v4l2_open(data->device_id, O_RDWR | O_NONBLOCK);
  722. if (data->dev == -1) {
  723. blog(LOG_ERROR, "Unable to open device");
  724. goto fail;
  725. }
  726. /* set input */
  727. if (v4l2_set_input(data->dev, &data->input) < 0) {
  728. blog(LOG_ERROR, "Unable to set input %d", data->input);
  729. goto fail;
  730. }
  731. blog(LOG_INFO, "Input: %d", data->input);
  732. if (v4l2_get_input_caps(data->dev, -1, &input_caps) < 0) {
  733. blog(LOG_ERROR, "Unable to get input capabilities");
  734. goto fail;
  735. }
  736. /* set video standard if supported */
  737. if (input_caps & V4L2_IN_CAP_STD) {
  738. if (v4l2_set_standard(data->dev, &data->standard) < 0) {
  739. blog(LOG_ERROR, "Unable to set video standard");
  740. goto fail;
  741. }
  742. data->resolution = -1;
  743. data->framerate = -1;
  744. }
  745. /* set dv timing if supported */
  746. if (input_caps & V4L2_IN_CAP_DV_TIMINGS) {
  747. if (v4l2_set_dv_timing(data->dev, &data->dv_timing) < 0) {
  748. blog(LOG_ERROR, "Unable to set dv timing");
  749. goto fail;
  750. }
  751. data->resolution = -1;
  752. data->framerate = -1;
  753. }
  754. /* set pixel format and resolution */
  755. if (v4l2_set_format(data->dev, &data->resolution, &data->pixfmt,
  756. &data->linesize) < 0) {
  757. blog(LOG_ERROR, "Unable to set format");
  758. goto fail;
  759. }
  760. if (v4l2_to_obs_video_format(data->pixfmt) == VIDEO_FORMAT_NONE) {
  761. blog(LOG_ERROR, "Selected video format not supported");
  762. goto fail;
  763. }
  764. v4l2_unpack_tuple(&data->width, &data->height, data->resolution);
  765. blog(LOG_INFO, "Resolution: %dx%d", data->width, data->height);
  766. blog(LOG_INFO, "Pixelformat: %s", V4L2_FOURCC_STR(data->pixfmt));
  767. blog(LOG_INFO, "Linesize: %d Bytes", data->linesize);
  768. /* set framerate */
  769. if (v4l2_set_framerate(data->dev, &data->framerate) < 0) {
  770. blog(LOG_ERROR, "Unable to set framerate");
  771. goto fail;
  772. }
  773. v4l2_unpack_tuple(&fps_num, &fps_denom, data->framerate);
  774. blog(LOG_INFO, "Framerate: %.2f fps", (float)fps_denom / fps_num);
  775. /* map buffers */
  776. if (v4l2_create_mmap(data->dev, &data->buffers) < 0) {
  777. blog(LOG_ERROR, "Failed to map buffers");
  778. goto fail;
  779. }
  780. /* start the capture thread */
  781. if (os_event_init(&data->event, OS_EVENT_TYPE_MANUAL) != 0)
  782. goto fail;
  783. if (pthread_create(&data->thread, NULL, v4l2_thread, data) != 0)
  784. goto fail;
  785. return;
  786. fail:
  787. blog(LOG_ERROR, "Initialization failed");
  788. v4l2_terminate(data);
  789. }
  790. /** Update source flags depending on the settings */
  791. static void v4l2_update_source_flags(struct v4l2_data *data,
  792. obs_data_t *settings)
  793. {
  794. obs_source_set_async_unbuffered(
  795. data->source, !obs_data_get_bool(settings, "buffering"));
  796. }
  797. /**
  798. * Checking if any of the settings have changed so that we can restart the
  799. * stream
  800. */
  801. static bool v4l2_settings_changed(struct v4l2_data *data, obs_data_t *settings)
  802. {
  803. bool res = false;
  804. if (obs_data_get_string(settings, "device_id") != NULL &&
  805. data->device_id != NULL) {
  806. res |= strcmp(data->device_id,
  807. obs_data_get_string(settings, "device_id")) != 0;
  808. res |= data->input != obs_data_get_int(settings, "input");
  809. res |= data->pixfmt !=
  810. obs_data_get_int(settings, "pixelformat");
  811. res |= data->standard != obs_data_get_int(settings, "standard");
  812. res |= data->dv_timing !=
  813. obs_data_get_int(settings, "dv_timing");
  814. if (obs_data_get_int(settings, "resolution") == -1 &&
  815. !data->resolution_unchanged) {
  816. data->resolution_unchanged = true;
  817. res |= true;
  818. } else if (obs_data_get_int(settings, "resolution") == -1 &&
  819. data->resolution_unchanged) {
  820. res |= false;
  821. } else {
  822. data->resolution_unchanged = false;
  823. res |= (data->resolution !=
  824. obs_data_get_int(settings, "resolution")) &&
  825. (obs_data_get_int(settings, "resolution") != -1);
  826. }
  827. if (obs_data_get_int(settings, "framerate") == -1 &&
  828. !data->framerate_unchanged) {
  829. data->framerate_unchanged = true;
  830. res |= true;
  831. } else if (obs_data_get_int(settings, "framerate") == -1 &&
  832. data->framerate_unchanged) {
  833. res |= false;
  834. } else {
  835. data->framerate_unchanged = false;
  836. res |= (data->framerate !=
  837. obs_data_get_int(settings, "framerate")) &&
  838. (obs_data_get_int(settings, "framerate") != -1);
  839. }
  840. res |= data->color_range !=
  841. obs_data_get_int(settings, "color_range");
  842. } else {
  843. res = true;
  844. }
  845. return res;
  846. }
  847. /**
  848. * Update the settings for the v4l2 source
  849. *
  850. * There are a few settings that can be changed without restarting the stream
  851. * Whenever this is called the currently active stream (if exists) is stopped,
  852. * the settings are updated and finally the new stream is started.
  853. */
  854. static void v4l2_update(void *vptr, obs_data_t *settings)
  855. {
  856. V4L2_DATA(vptr);
  857. bool needs_restart = v4l2_settings_changed(data, settings);
  858. if (needs_restart)
  859. v4l2_terminate(data);
  860. if (data->device_id)
  861. bfree(data->device_id);
  862. data->device_id = bstrdup(obs_data_get_string(settings, "device_id"));
  863. data->input = obs_data_get_int(settings, "input");
  864. data->pixfmt = obs_data_get_int(settings, "pixelformat");
  865. data->standard = obs_data_get_int(settings, "standard");
  866. data->dv_timing = obs_data_get_int(settings, "dv_timing");
  867. data->resolution = obs_data_get_int(settings, "resolution");
  868. data->framerate = obs_data_get_int(settings, "framerate");
  869. data->color_range = obs_data_get_int(settings, "color_range");
  870. v4l2_update_source_flags(data, settings);
  871. if (needs_restart)
  872. v4l2_init(data);
  873. }
  874. static void *v4l2_create(obs_data_t *settings, obs_source_t *source)
  875. {
  876. struct v4l2_data *data = bzalloc(sizeof(struct v4l2_data));
  877. data->dev = -1;
  878. data->source = source;
  879. data->resolution_unchanged = false;
  880. data->framerate_unchanged = false;
  881. /* Bitch about build problems ... */
  882. #ifndef V4L2_CAP_DEVICE_CAPS
  883. blog(LOG_WARNING, "Plugin built without device caps support!");
  884. #endif
  885. #if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS)
  886. blog(LOG_WARNING, "Plugin built without dv-timing support!");
  887. #endif
  888. v4l2_update(data, settings);
  889. #if HAVE_UDEV
  890. v4l2_init_udev();
  891. signal_handler_t *sh = v4l2_get_udev_signalhandler();
  892. signal_handler_connect(sh, "device_added", &device_added, data);
  893. signal_handler_connect(sh, "device_removed", &device_removed, data);
  894. #endif
  895. return data;
  896. }
  897. struct obs_source_info v4l2_input = {
  898. .id = "v4l2_input",
  899. .type = OBS_SOURCE_TYPE_INPUT,
  900. .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_DO_NOT_DUPLICATE,
  901. .get_name = v4l2_getname,
  902. .create = v4l2_create,
  903. .destroy = v4l2_destroy,
  904. .update = v4l2_update,
  905. .get_defaults = v4l2_defaults,
  906. .get_properties = v4l2_properties,
  907. .icon_type = OBS_ICON_TYPE_CAMERA,
  908. };