v4l2-input.c 32 KB

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