v4l2.c 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027
  1. /*
  2. * Copyright (c) 2000,2001 Fabrice Bellard
  3. * Copyright (c) 2006 Luca Abeni
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. /**
  22. * @file
  23. * Video4Linux2 grab interface
  24. *
  25. * Part of this file is based on the V4L2 video capture example
  26. * (http://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
  27. *
  28. * Thanks to Michael Niedermayer for providing the mapping between
  29. * V4L2_PIX_FMT_* and AV_PIX_FMT_*
  30. */
  31. #include "v4l2-common.h"
  32. #if CONFIG_LIBV4L2
  33. #include <libv4l2.h>
  34. #endif
  35. static const int desired_video_buffers = 256;
  36. #define V4L_ALLFORMATS 3
  37. #define V4L_RAWFORMATS 1
  38. #define V4L_COMPFORMATS 2
  39. /**
  40. * Return timestamps to the user exactly as returned by the kernel
  41. */
  42. #define V4L_TS_DEFAULT 0
  43. /**
  44. * Autodetect the kind of timestamps returned by the kernel and convert to
  45. * absolute (wall clock) timestamps.
  46. */
  47. #define V4L_TS_ABS 1
  48. /**
  49. * Assume kernel timestamps are from the monotonic clock and convert to
  50. * absolute timestamps.
  51. */
  52. #define V4L_TS_MONO2ABS 2
  53. /**
  54. * Once the kind of timestamps returned by the kernel have been detected,
  55. * the value of the timefilter (NULL or not) determines whether a conversion
  56. * takes place.
  57. */
  58. #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
  59. struct video_data {
  60. AVClass *class;
  61. int fd;
  62. int frame_format; /* V4L2_PIX_FMT_* */
  63. int width, height;
  64. int frame_size;
  65. int interlaced;
  66. int top_field_first;
  67. int ts_mode;
  68. TimeFilter *timefilter;
  69. int64_t last_time_m;
  70. int buffers;
  71. volatile int buffers_queued;
  72. void **buf_start;
  73. unsigned int *buf_len;
  74. char *standard;
  75. v4l2_std_id std_id;
  76. int channel;
  77. char *pixel_format; /**< Set by a private option. */
  78. int list_format; /**< Set by a private option. */
  79. int list_standard; /**< Set by a private option. */
  80. char *framerate; /**< Set by a private option. */
  81. int use_libv4l2;
  82. int (*open_f)(const char *file, int oflag, ...);
  83. int (*close_f)(int fd);
  84. int (*dup_f)(int fd);
  85. int (*ioctl_f)(int fd, unsigned long int request, ...);
  86. ssize_t (*read_f)(int fd, void *buffer, size_t n);
  87. void *(*mmap_f)(void *start, size_t length, int prot, int flags, int fd, int64_t offset);
  88. int (*munmap_f)(void *_start, size_t length);
  89. };
  90. struct buff_data {
  91. struct video_data *s;
  92. int index;
  93. };
  94. static int device_open(AVFormatContext *ctx)
  95. {
  96. struct video_data *s = ctx->priv_data;
  97. struct v4l2_capability cap;
  98. int fd;
  99. int ret;
  100. int flags = O_RDWR;
  101. #define SET_WRAPPERS(prefix) do { \
  102. s->open_f = prefix ## open; \
  103. s->close_f = prefix ## close; \
  104. s->dup_f = prefix ## dup; \
  105. s->ioctl_f = prefix ## ioctl; \
  106. s->read_f = prefix ## read; \
  107. s->mmap_f = prefix ## mmap; \
  108. s->munmap_f = prefix ## munmap; \
  109. } while (0)
  110. if (s->use_libv4l2) {
  111. #if CONFIG_LIBV4L2
  112. SET_WRAPPERS(v4l2_);
  113. #else
  114. av_log(ctx, AV_LOG_ERROR, "libavdevice is not build with libv4l2 support.\n");
  115. return AVERROR(EINVAL);
  116. #endif
  117. } else {
  118. SET_WRAPPERS();
  119. }
  120. #define v4l2_open s->open_f
  121. #define v4l2_close s->close_f
  122. #define v4l2_dup s->dup_f
  123. #define v4l2_ioctl s->ioctl_f
  124. #define v4l2_read s->read_f
  125. #define v4l2_mmap s->mmap_f
  126. #define v4l2_munmap s->munmap_f
  127. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  128. flags |= O_NONBLOCK;
  129. }
  130. fd = v4l2_open(ctx->filename, flags, 0);
  131. if (fd < 0) {
  132. ret = AVERROR(errno);
  133. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
  134. ctx->filename, av_err2str(ret));
  135. return ret;
  136. }
  137. if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
  138. ret = AVERROR(errno);
  139. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  140. av_err2str(ret));
  141. goto fail;
  142. }
  143. av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
  144. fd, cap.capabilities);
  145. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  146. av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
  147. ret = AVERROR(ENODEV);
  148. goto fail;
  149. }
  150. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  151. av_log(ctx, AV_LOG_ERROR,
  152. "The device does not support the streaming I/O method.\n");
  153. ret = AVERROR(ENOSYS);
  154. goto fail;
  155. }
  156. return fd;
  157. fail:
  158. v4l2_close(fd);
  159. return ret;
  160. }
  161. static int device_init(AVFormatContext *ctx, int *width, int *height,
  162. uint32_t pix_fmt)
  163. {
  164. struct video_data *s = ctx->priv_data;
  165. int fd = s->fd;
  166. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  167. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  168. int res = 0;
  169. pix->width = *width;
  170. pix->height = *height;
  171. pix->pixelformat = pix_fmt;
  172. pix->field = V4L2_FIELD_ANY;
  173. if (v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
  174. res = AVERROR(errno);
  175. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  176. av_log(ctx, AV_LOG_INFO,
  177. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  178. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  179. *width = fmt.fmt.pix.width;
  180. *height = fmt.fmt.pix.height;
  181. }
  182. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  183. av_log(ctx, AV_LOG_DEBUG,
  184. "The V4L2 driver changed the pixel format "
  185. "from 0x%08X to 0x%08X\n",
  186. pix_fmt, fmt.fmt.pix.pixelformat);
  187. res = AVERROR(EINVAL);
  188. }
  189. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  190. av_log(ctx, AV_LOG_DEBUG,
  191. "The V4L2 driver is using the interlaced mode\n");
  192. s->interlaced = 1;
  193. }
  194. return res;
  195. }
  196. static int first_field(const struct video_data *s, int fd)
  197. {
  198. int res;
  199. v4l2_std_id std;
  200. res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
  201. if (res < 0) {
  202. return 0;
  203. }
  204. if (std & V4L2_STD_NTSC) {
  205. return 0;
  206. }
  207. return 1;
  208. }
  209. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  210. static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
  211. {
  212. const struct video_data *s = ctx->priv_data;
  213. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  214. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  215. switch (vfse.type) {
  216. case V4L2_FRMSIZE_TYPE_DISCRETE:
  217. av_log(ctx, AV_LOG_INFO, " %ux%u",
  218. vfse.discrete.width, vfse.discrete.height);
  219. break;
  220. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  221. case V4L2_FRMSIZE_TYPE_STEPWISE:
  222. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  223. vfse.stepwise.min_width,
  224. vfse.stepwise.max_width,
  225. vfse.stepwise.step_width,
  226. vfse.stepwise.min_height,
  227. vfse.stepwise.max_height,
  228. vfse.stepwise.step_height);
  229. }
  230. vfse.index++;
  231. }
  232. }
  233. #endif
  234. static void list_formats(AVFormatContext *ctx, int fd, int type)
  235. {
  236. const struct video_data *s = ctx->priv_data;
  237. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  238. while(!v4l2_ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
  239. enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);
  240. enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);
  241. vfd.index++;
  242. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  243. type & V4L_RAWFORMATS) {
  244. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  245. av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
  246. fmt_name ? fmt_name : "Unsupported",
  247. vfd.description);
  248. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  249. type & V4L_COMPFORMATS) {
  250. AVCodec *codec = avcodec_find_decoder(codec_id);
  251. av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
  252. codec ? codec->name : "Unsupported",
  253. vfd.description);
  254. } else {
  255. continue;
  256. }
  257. #ifdef V4L2_FMT_FLAG_EMULATED
  258. if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
  259. av_log(ctx, AV_LOG_INFO, " Emulated :");
  260. #endif
  261. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  262. list_framesizes(ctx, fd, vfd.pixelformat);
  263. #endif
  264. av_log(ctx, AV_LOG_INFO, "\n");
  265. }
  266. }
  267. static void list_standards(AVFormatContext *ctx)
  268. {
  269. int ret;
  270. struct video_data *s = ctx->priv_data;
  271. struct v4l2_standard standard;
  272. if (s->std_id == 0)
  273. return;
  274. for (standard.index = 0; ; standard.index++) {
  275. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  276. ret = AVERROR(errno);
  277. if (ret == AVERROR(EINVAL)) {
  278. break;
  279. } else {
  280. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  281. return;
  282. }
  283. }
  284. av_log(ctx, AV_LOG_INFO, "%2d, %16llx, %s\n",
  285. standard.index, standard.id, standard.name);
  286. }
  287. }
  288. static int mmap_init(AVFormatContext *ctx)
  289. {
  290. int i, res;
  291. struct video_data *s = ctx->priv_data;
  292. struct v4l2_requestbuffers req = {
  293. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  294. .count = desired_video_buffers,
  295. .memory = V4L2_MEMORY_MMAP
  296. };
  297. if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
  298. res = AVERROR(errno);
  299. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
  300. return res;
  301. }
  302. if (req.count < 2) {
  303. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  304. return AVERROR(ENOMEM);
  305. }
  306. s->buffers = req.count;
  307. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  308. if (s->buf_start == NULL) {
  309. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  310. return AVERROR(ENOMEM);
  311. }
  312. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  313. if (s->buf_len == NULL) {
  314. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  315. av_free(s->buf_start);
  316. return AVERROR(ENOMEM);
  317. }
  318. for (i = 0; i < req.count; i++) {
  319. struct v4l2_buffer buf = {
  320. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  321. .index = i,
  322. .memory = V4L2_MEMORY_MMAP
  323. };
  324. if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
  325. res = AVERROR(errno);
  326. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
  327. return res;
  328. }
  329. s->buf_len[i] = buf.length;
  330. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  331. av_log(ctx, AV_LOG_ERROR,
  332. "buf_len[%d] = %d < expected frame size %d\n",
  333. i, s->buf_len[i], s->frame_size);
  334. return AVERROR(ENOMEM);
  335. }
  336. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  337. PROT_READ | PROT_WRITE, MAP_SHARED,
  338. s->fd, buf.m.offset);
  339. if (s->buf_start[i] == MAP_FAILED) {
  340. res = AVERROR(errno);
  341. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
  342. return res;
  343. }
  344. }
  345. return 0;
  346. }
  347. #if FF_API_DESTRUCT_PACKET
  348. static void dummy_release_buffer(AVPacket *pkt)
  349. {
  350. av_assert0(0);
  351. }
  352. #endif
  353. static void mmap_release_buffer(void *opaque, uint8_t *data)
  354. {
  355. struct v4l2_buffer buf = { 0 };
  356. int res;
  357. struct buff_data *buf_descriptor = opaque;
  358. struct video_data *s = buf_descriptor->s;
  359. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  360. buf.memory = V4L2_MEMORY_MMAP;
  361. buf.index = buf_descriptor->index;
  362. av_free(buf_descriptor);
  363. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  364. res = AVERROR(errno);
  365. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  366. av_err2str(res));
  367. }
  368. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  369. }
  370. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  371. static int64_t av_gettime_monotonic(void)
  372. {
  373. struct timespec tv;
  374. clock_gettime(CLOCK_MONOTONIC, &tv);
  375. return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
  376. }
  377. #endif
  378. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  379. {
  380. struct video_data *s = ctx->priv_data;
  381. int64_t now;
  382. now = av_gettime();
  383. if (s->ts_mode == V4L_TS_ABS &&
  384. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  385. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  386. s->ts_mode = V4L_TS_CONVERT_READY;
  387. return 0;
  388. }
  389. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  390. now = av_gettime_monotonic();
  391. if (s->ts_mode == V4L_TS_MONO2ABS ||
  392. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  393. AVRational tb = {AV_TIME_BASE, 1};
  394. int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
  395. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  396. /* microseconds instead of seconds, MHz instead of Hz */
  397. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  398. s->ts_mode = V4L_TS_CONVERT_READY;
  399. return 0;
  400. }
  401. #endif
  402. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  403. return AVERROR(EIO);
  404. }
  405. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  406. {
  407. struct video_data *s = ctx->priv_data;
  408. if (s->ts_mode) {
  409. int r = init_convert_timestamp(ctx, *ts);
  410. if (r < 0)
  411. return r;
  412. }
  413. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  414. if (s->timefilter) {
  415. int64_t nowa = av_gettime();
  416. int64_t nowm = av_gettime_monotonic();
  417. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  418. s->last_time_m = nowm;
  419. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  420. }
  421. #endif
  422. return 0;
  423. }
  424. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  425. {
  426. struct video_data *s = ctx->priv_data;
  427. struct v4l2_buffer buf = {
  428. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  429. .memory = V4L2_MEMORY_MMAP
  430. };
  431. int res;
  432. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  433. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  434. if (res < 0) {
  435. if (errno == EAGAIN) {
  436. pkt->size = 0;
  437. return AVERROR(EAGAIN);
  438. }
  439. res = AVERROR(errno);
  440. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
  441. return res;
  442. }
  443. if (buf.index >= s->buffers) {
  444. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  445. return AVERROR(EINVAL);
  446. }
  447. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  448. // always keep at least one buffer queued
  449. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  450. /* CPIA is a compressed format and we don't know the exact number of bytes
  451. * used by a frame, so set it here as the driver announces it.
  452. */
  453. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  454. s->frame_size = buf.bytesused;
  455. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  456. av_log(ctx, AV_LOG_ERROR,
  457. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  458. buf.bytesused, s->frame_size);
  459. return AVERROR_INVALIDDATA;
  460. }
  461. /* Image is at s->buff_start[buf.index] */
  462. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  463. /* when we start getting low on queued buffers, fall back on copying data */
  464. res = av_new_packet(pkt, buf.bytesused);
  465. if (res < 0) {
  466. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  467. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  468. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  469. return res;
  470. }
  471. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  472. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  473. res = AVERROR(errno);
  474. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  475. av_free_packet(pkt);
  476. return res;
  477. }
  478. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  479. } else {
  480. struct buff_data *buf_descriptor;
  481. pkt->data = s->buf_start[buf.index];
  482. pkt->size = buf.bytesused;
  483. #if FF_API_DESTRUCT_PACKET
  484. pkt->destruct = dummy_release_buffer;
  485. #endif
  486. buf_descriptor = av_malloc(sizeof(struct buff_data));
  487. if (buf_descriptor == NULL) {
  488. /* Something went wrong... Since av_malloc() failed, we cannot even
  489. * allocate a buffer for memcpying into it
  490. */
  491. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  492. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  493. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  494. return AVERROR(ENOMEM);
  495. }
  496. buf_descriptor->index = buf.index;
  497. buf_descriptor->s = s;
  498. pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
  499. buf_descriptor, 0);
  500. if (!pkt->buf) {
  501. av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
  502. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) == 0)
  503. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  504. av_freep(&buf_descriptor);
  505. return AVERROR(ENOMEM);
  506. }
  507. }
  508. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  509. convert_timestamp(ctx, &pkt->pts);
  510. return s->buf_len[buf.index];
  511. }
  512. static int mmap_start(AVFormatContext *ctx)
  513. {
  514. struct video_data *s = ctx->priv_data;
  515. enum v4l2_buf_type type;
  516. int i, res;
  517. for (i = 0; i < s->buffers; i++) {
  518. struct v4l2_buffer buf = {
  519. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  520. .index = i,
  521. .memory = V4L2_MEMORY_MMAP
  522. };
  523. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  524. res = AVERROR(errno);
  525. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  526. return res;
  527. }
  528. }
  529. s->buffers_queued = s->buffers;
  530. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  531. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  532. res = AVERROR(errno);
  533. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
  534. return res;
  535. }
  536. return 0;
  537. }
  538. static void mmap_close(struct video_data *s)
  539. {
  540. enum v4l2_buf_type type;
  541. int i;
  542. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  543. /* We do not check for the result, because we could
  544. * not do anything about it anyway...
  545. */
  546. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  547. for (i = 0; i < s->buffers; i++) {
  548. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  549. }
  550. av_free(s->buf_start);
  551. av_free(s->buf_len);
  552. }
  553. static int v4l2_set_parameters(AVFormatContext *s1)
  554. {
  555. struct video_data *s = s1->priv_data;
  556. struct v4l2_standard standard = { 0 };
  557. struct v4l2_streamparm streamparm = { 0 };
  558. struct v4l2_fract *tpf;
  559. AVRational framerate_q = { 0 };
  560. int i, ret;
  561. if (s->framerate &&
  562. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  563. av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  564. s->framerate);
  565. return ret;
  566. }
  567. if (s->standard) {
  568. if (s->std_id) {
  569. ret = 0;
  570. av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
  571. /* set tv standard */
  572. for (i = 0; ; i++) {
  573. standard.index = i;
  574. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  575. ret = AVERROR(errno);
  576. break;
  577. }
  578. if (!av_strcasecmp(standard.name, s->standard))
  579. break;
  580. }
  581. if (ret < 0) {
  582. av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
  583. return ret;
  584. }
  585. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  586. ret = AVERROR(errno);
  587. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  588. return ret;
  589. }
  590. } else {
  591. av_log(s1, AV_LOG_WARNING,
  592. "This device does not support any standard\n");
  593. }
  594. }
  595. /* get standard */
  596. if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
  597. tpf = &standard.frameperiod;
  598. for (i = 0; ; i++) {
  599. standard.index = i;
  600. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  601. ret = AVERROR(errno);
  602. if (ret == AVERROR(EINVAL)) {
  603. tpf = &streamparm.parm.capture.timeperframe;
  604. break;
  605. }
  606. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  607. return ret;
  608. }
  609. if (standard.id == s->std_id) {
  610. av_log(s1, AV_LOG_DEBUG,
  611. "Current standard: %s, id: %"PRIu64", frameperiod: %d/%d\n",
  612. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  613. break;
  614. }
  615. }
  616. } else {
  617. tpf = &streamparm.parm.capture.timeperframe;
  618. }
  619. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  620. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  621. ret = AVERROR(errno);
  622. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  623. return ret;
  624. }
  625. if (framerate_q.num && framerate_q.den) {
  626. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  627. tpf = &streamparm.parm.capture.timeperframe;
  628. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  629. framerate_q.den, framerate_q.num);
  630. tpf->numerator = framerate_q.den;
  631. tpf->denominator = framerate_q.num;
  632. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  633. ret = AVERROR(errno);
  634. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
  635. return ret;
  636. }
  637. if (framerate_q.num != tpf->denominator ||
  638. framerate_q.den != tpf->numerator) {
  639. av_log(s1, AV_LOG_INFO,
  640. "The driver changed the time per frame from "
  641. "%d/%d to %d/%d\n",
  642. framerate_q.den, framerate_q.num,
  643. tpf->numerator, tpf->denominator);
  644. }
  645. } else {
  646. av_log(s1, AV_LOG_WARNING,
  647. "The driver does not allow to change time per frame\n");
  648. }
  649. }
  650. s1->streams[0]->avg_frame_rate.num = tpf->denominator;
  651. s1->streams[0]->avg_frame_rate.den = tpf->numerator;
  652. s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;
  653. return 0;
  654. }
  655. static int device_try_init(AVFormatContext *s1,
  656. enum AVPixelFormat pix_fmt,
  657. int *width,
  658. int *height,
  659. uint32_t *desired_format,
  660. enum AVCodecID *codec_id)
  661. {
  662. int ret, i;
  663. *desired_format = avpriv_fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  664. if (*desired_format) {
  665. ret = device_init(s1, width, height, *desired_format);
  666. if (ret < 0) {
  667. *desired_format = 0;
  668. if (ret != AVERROR(EINVAL))
  669. return ret;
  670. }
  671. }
  672. if (!*desired_format) {
  673. for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
  674. if (s1->video_codec_id == AV_CODEC_ID_NONE ||
  675. avpriv_fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  676. av_log(s1, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  677. avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),
  678. (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));
  679. *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
  680. ret = device_init(s1, width, height, *desired_format);
  681. if (ret >= 0)
  682. break;
  683. else if (ret != AVERROR(EINVAL))
  684. return ret;
  685. *desired_format = 0;
  686. }
  687. }
  688. if (*desired_format == 0) {
  689. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  690. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  691. avcodec_get_name(s1->video_codec_id), s1->video_codec_id,
  692. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  693. ret = AVERROR(EINVAL);
  694. }
  695. }
  696. *codec_id = avpriv_fmt_v4l2codec(*desired_format);
  697. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  698. return ret;
  699. }
  700. static int v4l2_read_header(AVFormatContext *s1)
  701. {
  702. struct video_data *s = s1->priv_data;
  703. AVStream *st;
  704. int res = 0;
  705. uint32_t desired_format;
  706. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  707. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  708. struct v4l2_input input = { 0 };
  709. st = avformat_new_stream(s1, NULL);
  710. if (!st)
  711. return AVERROR(ENOMEM);
  712. #if CONFIG_LIBV4L2
  713. /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
  714. and errors will get sent to stderr */
  715. if (s->use_libv4l2)
  716. v4l2_log_file = fopen("/dev/null", "w");
  717. #endif
  718. s->fd = device_open(s1);
  719. if (s->fd < 0)
  720. return s->fd;
  721. if (s->channel != -1) {
  722. /* set video input */
  723. av_log(s1, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  724. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  725. res = AVERROR(errno);
  726. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  727. return res;
  728. }
  729. } else {
  730. /* get current video input */
  731. if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
  732. res = AVERROR(errno);
  733. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
  734. return res;
  735. }
  736. }
  737. /* enum input */
  738. input.index = s->channel;
  739. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  740. res = AVERROR(errno);
  741. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  742. return res;
  743. }
  744. s->std_id = input.std;
  745. av_log(s1, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s\n",
  746. s->channel, input.name);
  747. if (s->list_format) {
  748. list_formats(s1, s->fd, s->list_format);
  749. return AVERROR_EXIT;
  750. }
  751. if (s->list_standard) {
  752. list_standards(s1);
  753. return AVERROR_EXIT;
  754. }
  755. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  756. if (s->pixel_format) {
  757. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  758. if (codec)
  759. s1->video_codec_id = codec->id;
  760. pix_fmt = av_get_pix_fmt(s->pixel_format);
  761. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  762. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  763. s->pixel_format);
  764. return AVERROR(EINVAL);
  765. }
  766. }
  767. if (!s->width && !s->height) {
  768. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  769. av_log(s1, AV_LOG_VERBOSE,
  770. "Querying the device for the current frame size\n");
  771. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  772. res = AVERROR(errno);
  773. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
  774. return res;
  775. }
  776. s->width = fmt.fmt.pix.width;
  777. s->height = fmt.fmt.pix.height;
  778. av_log(s1, AV_LOG_VERBOSE,
  779. "Setting frame size to %dx%d\n", s->width, s->height);
  780. }
  781. res = device_try_init(s1, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  782. if (res < 0) {
  783. v4l2_close(s->fd);
  784. return res;
  785. }
  786. /* If no pixel_format was specified, the codec_id was not known up
  787. * until now. Set video_codec_id in the context, as codec_id will
  788. * not be available outside this function
  789. */
  790. if (codec_id != AV_CODEC_ID_NONE && s1->video_codec_id == AV_CODEC_ID_NONE)
  791. s1->video_codec_id = codec_id;
  792. if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
  793. return res;
  794. s->frame_format = desired_format;
  795. if ((res = v4l2_set_parameters(s1)) < 0)
  796. return res;
  797. st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);
  798. s->frame_size =
  799. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  800. if ((res = mmap_init(s1)) ||
  801. (res = mmap_start(s1)) < 0) {
  802. v4l2_close(s->fd);
  803. return res;
  804. }
  805. s->top_field_first = first_field(s, s->fd);
  806. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  807. st->codec->codec_id = codec_id;
  808. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  809. st->codec->codec_tag =
  810. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  811. else if (codec_id == AV_CODEC_ID_H264) {
  812. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  813. }
  814. if (desired_format == V4L2_PIX_FMT_YVU420)
  815. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  816. else if (desired_format == V4L2_PIX_FMT_YVU410)
  817. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  818. st->codec->width = s->width;
  819. st->codec->height = s->height;
  820. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  821. return 0;
  822. }
  823. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  824. {
  825. struct video_data *s = s1->priv_data;
  826. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  827. int res;
  828. av_init_packet(pkt);
  829. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  830. return res;
  831. }
  832. if (frame && s->interlaced) {
  833. frame->interlaced_frame = 1;
  834. frame->top_field_first = s->top_field_first;
  835. }
  836. return pkt->size;
  837. }
  838. static int v4l2_read_close(AVFormatContext *s1)
  839. {
  840. struct video_data *s = s1->priv_data;
  841. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  842. av_log(s1, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  843. "close.\n");
  844. mmap_close(s);
  845. v4l2_close(s->fd);
  846. return 0;
  847. }
  848. #define OFFSET(x) offsetof(struct video_data, x)
  849. #define DEC AV_OPT_FLAG_DECODING_PARAM
  850. static const AVOption options[] = {
  851. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  852. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
  853. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  854. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  855. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  856. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  857. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  858. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  859. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  860. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  861. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  862. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  863. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  864. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  865. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  866. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  867. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  868. { "use_libv4l2", "use libv4l2 (v4l-utils) convertion functions", OFFSET(use_libv4l2), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  869. { NULL },
  870. };
  871. static const AVClass v4l2_class = {
  872. .class_name = "V4L2 indev",
  873. .item_name = av_default_item_name,
  874. .option = options,
  875. .version = LIBAVUTIL_VERSION_INT,
  876. };
  877. AVInputFormat ff_v4l2_demuxer = {
  878. .name = "video4linux2,v4l2",
  879. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  880. .priv_data_size = sizeof(struct video_data),
  881. .read_header = v4l2_read_header,
  882. .read_packet = v4l2_read_packet,
  883. .read_close = v4l2_read_close,
  884. .flags = AVFMT_NOFILE,
  885. .priv_class = &v4l2_class,
  886. };