1
0

v4l2-input.c 32 KB

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