v4l2-input.c 32 KB

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