v4l2-input.c 31 KB

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