v4l2-input.c 32 KB

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