v4l2-input.c 32 KB

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