1
0

v4l2-input.c 31 KB

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