v4l2-input.c 31 KB

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