v4l2-input.c 31 KB

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