v4l2-input.c 31 KB

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