v4l2.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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://v4l2spec.bytesex.org/v4l2spec/capture.c)
  27. *
  28. * Thanks to Michael Niedermayer for providing the mapping between
  29. * V4L2_PIX_FMT_* and PIX_FMT_*
  30. */
  31. #undef __STRICT_ANSI__ //workaround due to broken kernel headers
  32. #include "config.h"
  33. #include "libavformat/internal.h"
  34. #include <unistd.h>
  35. #include <fcntl.h>
  36. #include <sys/ioctl.h>
  37. #include <sys/mman.h>
  38. #include <sys/time.h>
  39. #if HAVE_SYS_VIDEOIO_H
  40. #include <sys/videoio.h>
  41. #else
  42. #if HAVE_ASM_TYPES_H
  43. #include <asm/types.h>
  44. #endif
  45. #include <linux/videodev2.h>
  46. #endif
  47. #include <time.h>
  48. #include "libavutil/imgutils.h"
  49. #include "libavutil/log.h"
  50. #include "libavutil/opt.h"
  51. #include "avdevice.h"
  52. #include "timefilter.h"
  53. #include "libavutil/parseutils.h"
  54. #include "libavutil/pixdesc.h"
  55. #include "libavutil/avstring.h"
  56. #if CONFIG_LIBV4L2
  57. #include <libv4l2.h>
  58. #else
  59. #define v4l2_open open
  60. #define v4l2_close close
  61. #define v4l2_dup dup
  62. #define v4l2_ioctl ioctl
  63. #define v4l2_read read
  64. #define v4l2_mmap mmap
  65. #define v4l2_munmap munmap
  66. #endif
  67. static const int desired_video_buffers = 256;
  68. #define V4L_ALLFORMATS 3
  69. #define V4L_RAWFORMATS 1
  70. #define V4L_COMPFORMATS 2
  71. /**
  72. * Return timestamps to the user exactly as returned by the kernel
  73. */
  74. #define V4L_TS_DEFAULT 0
  75. /**
  76. * Autodetect the kind of timestamps returned by the kernel and convert to
  77. * absolute (wall clock) timestamps.
  78. */
  79. #define V4L_TS_ABS 1
  80. /**
  81. * Assume kernel timestamps are from the monotonic clock and convert to
  82. * absolute timestamps.
  83. */
  84. #define V4L_TS_MONO2ABS 2
  85. /**
  86. * Once the kind of timestamps returned by the kernel have been detected,
  87. * the value of the timefilter (NULL or not) determines whether a conversion
  88. * takes place.
  89. */
  90. #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
  91. struct video_data {
  92. AVClass *class;
  93. int fd;
  94. int frame_format; /* V4L2_PIX_FMT_* */
  95. int width, height;
  96. int frame_size;
  97. int interlaced;
  98. int top_field_first;
  99. int ts_mode;
  100. TimeFilter *timefilter;
  101. int64_t last_time_m;
  102. int buffers;
  103. void **buf_start;
  104. unsigned int *buf_len;
  105. char *standard;
  106. int channel;
  107. char *pixel_format; /**< Set by a private option. */
  108. int list_format; /**< Set by a private option. */
  109. char *framerate; /**< Set by a private option. */
  110. };
  111. struct buff_data {
  112. int index;
  113. int fd;
  114. };
  115. struct fmt_map {
  116. enum PixelFormat ff_fmt;
  117. enum CodecID codec_id;
  118. uint32_t v4l2_fmt;
  119. };
  120. static struct fmt_map fmt_conversion_table[] = {
  121. //ff_fmt codec_id v4l2_fmt
  122. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
  123. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YVU420 },
  124. { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
  125. { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
  126. { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
  127. { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
  128. { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
  129. { PIX_FMT_RGB555LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
  130. { PIX_FMT_RGB555BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555X },
  131. { PIX_FMT_RGB565LE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
  132. { PIX_FMT_RGB565BE,CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565X },
  133. { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
  134. { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
  135. { PIX_FMT_BGR0, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
  136. { PIX_FMT_0RGB, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB32 },
  137. { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
  138. { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
  139. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
  140. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
  141. };
  142. static int device_open(AVFormatContext *ctx)
  143. {
  144. struct v4l2_capability cap;
  145. int fd;
  146. #if CONFIG_LIBV4L2
  147. int fd_libv4l;
  148. #endif
  149. int res, err;
  150. int flags = O_RDWR;
  151. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  152. flags |= O_NONBLOCK;
  153. }
  154. fd = v4l2_open(ctx->filename, flags, 0);
  155. if (fd < 0) {
  156. err = errno;
  157. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
  158. ctx->filename, strerror(err));
  159. return AVERROR(err);
  160. }
  161. #if CONFIG_LIBV4L2
  162. fd_libv4l = v4l2_fd_open(fd, 0);
  163. if (fd < 0) {
  164. err = AVERROR(errno);
  165. av_log(ctx, AV_LOG_ERROR, "Cannot open video device with libv4l neither %s : %s\n",
  166. ctx->filename, strerror(errno));
  167. return err;
  168. }
  169. fd = fd_libv4l;
  170. #endif
  171. res = v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap);
  172. if (res < 0) {
  173. err = errno;
  174. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  175. strerror(err));
  176. goto fail;
  177. }
  178. av_log(ctx, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n",
  179. fd, cap.capabilities);
  180. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  181. av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
  182. err = ENODEV;
  183. goto fail;
  184. }
  185. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  186. av_log(ctx, AV_LOG_ERROR,
  187. "The device does not support the streaming I/O method.\n");
  188. err = ENOSYS;
  189. goto fail;
  190. }
  191. return fd;
  192. fail:
  193. v4l2_close(fd);
  194. return AVERROR(err);
  195. }
  196. static int device_init(AVFormatContext *ctx, int *width, int *height,
  197. uint32_t pix_fmt)
  198. {
  199. struct video_data *s = ctx->priv_data;
  200. int fd = s->fd;
  201. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  202. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  203. int res;
  204. pix->width = *width;
  205. pix->height = *height;
  206. pix->pixelformat = pix_fmt;
  207. pix->field = V4L2_FIELD_ANY;
  208. res = v4l2_ioctl(fd, VIDIOC_S_FMT, &fmt);
  209. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  210. av_log(ctx, AV_LOG_INFO,
  211. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  212. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  213. *width = fmt.fmt.pix.width;
  214. *height = fmt.fmt.pix.height;
  215. }
  216. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  217. av_log(ctx, AV_LOG_DEBUG,
  218. "The V4L2 driver changed the pixel format "
  219. "from 0x%08X to 0x%08X\n",
  220. pix_fmt, fmt.fmt.pix.pixelformat);
  221. res = -1;
  222. }
  223. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  224. av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");
  225. s->interlaced = 1;
  226. }
  227. return res;
  228. }
  229. static int first_field(int fd)
  230. {
  231. int res;
  232. v4l2_std_id std;
  233. res = v4l2_ioctl(fd, VIDIOC_G_STD, &std);
  234. if (res < 0) {
  235. return 0;
  236. }
  237. if (std & V4L2_STD_NTSC) {
  238. return 0;
  239. }
  240. return 1;
  241. }
  242. static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
  243. {
  244. int i;
  245. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  246. if ((codec_id == CODEC_ID_NONE ||
  247. fmt_conversion_table[i].codec_id == codec_id) &&
  248. (pix_fmt == PIX_FMT_NONE ||
  249. fmt_conversion_table[i].ff_fmt == pix_fmt)) {
  250. return fmt_conversion_table[i].v4l2_fmt;
  251. }
  252. }
  253. return 0;
  254. }
  255. static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
  256. {
  257. int i;
  258. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  259. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
  260. fmt_conversion_table[i].codec_id == codec_id) {
  261. return fmt_conversion_table[i].ff_fmt;
  262. }
  263. }
  264. return PIX_FMT_NONE;
  265. }
  266. static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
  267. {
  268. int i;
  269. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  270. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
  271. return fmt_conversion_table[i].codec_id;
  272. }
  273. }
  274. return CODEC_ID_NONE;
  275. }
  276. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  277. static void list_framesizes(AVFormatContext *ctx, int fd, uint32_t pixelformat)
  278. {
  279. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  280. while(!ioctl(fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  281. switch (vfse.type) {
  282. case V4L2_FRMSIZE_TYPE_DISCRETE:
  283. av_log(ctx, AV_LOG_INFO, " %ux%u",
  284. vfse.discrete.width, vfse.discrete.height);
  285. break;
  286. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  287. case V4L2_FRMSIZE_TYPE_STEPWISE:
  288. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  289. vfse.stepwise.min_width,
  290. vfse.stepwise.max_width,
  291. vfse.stepwise.step_width,
  292. vfse.stepwise.min_height,
  293. vfse.stepwise.max_height,
  294. vfse.stepwise.step_height);
  295. }
  296. vfse.index++;
  297. }
  298. }
  299. #endif
  300. static void list_formats(AVFormatContext *ctx, int fd, int type)
  301. {
  302. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  303. while(!ioctl(fd, VIDIOC_ENUM_FMT, &vfd)) {
  304. enum CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
  305. enum PixelFormat pix_fmt = fmt_v4l2ff(vfd.pixelformat, codec_id);
  306. vfd.index++;
  307. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  308. type & V4L_RAWFORMATS) {
  309. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  310. av_log(ctx, AV_LOG_INFO, "R : %9s : %20s :",
  311. fmt_name ? fmt_name : "Unsupported",
  312. vfd.description);
  313. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  314. type & V4L_COMPFORMATS) {
  315. AVCodec *codec = avcodec_find_encoder(codec_id);
  316. av_log(ctx, AV_LOG_INFO, "C : %9s : %20s :",
  317. codec ? codec->name : "Unsupported",
  318. vfd.description);
  319. } else {
  320. continue;
  321. }
  322. #ifdef V4L2_FMT_FLAG_EMULATED
  323. if (vfd.flags & V4L2_FMT_FLAG_EMULATED) {
  324. av_log(ctx, AV_LOG_WARNING, "%s", "Emulated");
  325. continue;
  326. }
  327. #endif
  328. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  329. list_framesizes(ctx, fd, vfd.pixelformat);
  330. #endif
  331. av_log(ctx, AV_LOG_INFO, "\n");
  332. }
  333. }
  334. static int mmap_init(AVFormatContext *ctx)
  335. {
  336. int i, res;
  337. struct video_data *s = ctx->priv_data;
  338. struct v4l2_requestbuffers req = {
  339. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  340. .count = desired_video_buffers,
  341. .memory = V4L2_MEMORY_MMAP
  342. };
  343. res = v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req);
  344. if (res < 0) {
  345. if (errno == EINVAL) {
  346. av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
  347. } else {
  348. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
  349. }
  350. return AVERROR(errno);
  351. }
  352. if (req.count < 2) {
  353. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  354. return AVERROR(ENOMEM);
  355. }
  356. s->buffers = req.count;
  357. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  358. if (s->buf_start == NULL) {
  359. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  360. return AVERROR(ENOMEM);
  361. }
  362. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  363. if (s->buf_len == NULL) {
  364. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  365. av_free(s->buf_start);
  366. return AVERROR(ENOMEM);
  367. }
  368. for (i = 0; i < req.count; i++) {
  369. struct v4l2_buffer buf = {
  370. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  371. .index = i,
  372. .memory = V4L2_MEMORY_MMAP
  373. };
  374. res = v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
  375. if (res < 0) {
  376. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
  377. return AVERROR(errno);
  378. }
  379. s->buf_len[i] = buf.length;
  380. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  381. av_log(ctx, AV_LOG_ERROR,
  382. "Buffer len [%d] = %d != %d\n",
  383. i, s->buf_len[i], s->frame_size);
  384. return -1;
  385. }
  386. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  387. PROT_READ | PROT_WRITE, MAP_SHARED,
  388. s->fd, buf.m.offset);
  389. if (s->buf_start[i] == MAP_FAILED) {
  390. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
  391. return AVERROR(errno);
  392. }
  393. }
  394. return 0;
  395. }
  396. static void mmap_release_buffer(AVPacket *pkt)
  397. {
  398. struct v4l2_buffer buf = { 0 };
  399. int res, fd;
  400. struct buff_data *buf_descriptor = pkt->priv;
  401. if (pkt->data == NULL)
  402. return;
  403. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  404. buf.memory = V4L2_MEMORY_MMAP;
  405. buf.index = buf_descriptor->index;
  406. fd = buf_descriptor->fd;
  407. av_free(buf_descriptor);
  408. res = v4l2_ioctl(fd, VIDIOC_QBUF, &buf);
  409. if (res < 0)
  410. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  411. strerror(errno));
  412. pkt->data = NULL;
  413. pkt->size = 0;
  414. }
  415. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  416. static int64_t av_gettime_monotonic(void)
  417. {
  418. struct timespec tv;
  419. clock_gettime(CLOCK_MONOTONIC, &tv);
  420. return (int64_t)tv.tv_sec * 1000000 + tv.tv_nsec / 1000;
  421. }
  422. #endif
  423. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  424. {
  425. struct video_data *s = ctx->priv_data;
  426. int64_t now;
  427. now = av_gettime();
  428. if (s->ts_mode == V4L_TS_ABS &&
  429. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  430. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  431. s->ts_mode = V4L_TS_CONVERT_READY;
  432. return 0;
  433. }
  434. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  435. now = av_gettime_monotonic();
  436. if (s->ts_mode == V4L_TS_MONO2ABS ||
  437. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  438. int64_t period = av_rescale_q(1, ctx->streams[0]->codec->time_base,
  439. AV_TIME_BASE_Q);
  440. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  441. /* microseconds instead of seconds, MHz instead of Hz */
  442. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  443. s->ts_mode = V4L_TS_CONVERT_READY;
  444. return 0;
  445. }
  446. #endif
  447. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  448. return AVERROR(EIO);
  449. }
  450. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  451. {
  452. struct video_data *s = ctx->priv_data;
  453. if (s->ts_mode) {
  454. int r = init_convert_timestamp(ctx, *ts);
  455. if (r < 0)
  456. return r;
  457. }
  458. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  459. if (s->timefilter) {
  460. int64_t nowa = av_gettime();
  461. int64_t nowm = av_gettime_monotonic();
  462. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  463. s->last_time_m = nowm;
  464. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  465. }
  466. #endif
  467. return 0;
  468. }
  469. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  470. {
  471. struct video_data *s = ctx->priv_data;
  472. struct v4l2_buffer buf = {
  473. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  474. .memory = V4L2_MEMORY_MMAP
  475. };
  476. struct buff_data *buf_descriptor;
  477. int res;
  478. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  479. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  480. if (res < 0) {
  481. if (errno == EAGAIN) {
  482. pkt->size = 0;
  483. return AVERROR(EAGAIN);
  484. }
  485. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n",
  486. strerror(errno));
  487. return AVERROR(errno);
  488. }
  489. assert(buf.index < s->buffers);
  490. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  491. av_log(ctx, AV_LOG_ERROR,
  492. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  493. buf.bytesused, s->frame_size);
  494. return AVERROR_INVALIDDATA;
  495. }
  496. /* Image is at s->buff_start[buf.index] */
  497. pkt->data= s->buf_start[buf.index];
  498. pkt->size = buf.bytesused;
  499. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  500. res = convert_timestamp(ctx, &pkt->pts);
  501. if (res < 0)
  502. return res;
  503. pkt->destruct = mmap_release_buffer;
  504. buf_descriptor = av_malloc(sizeof(struct buff_data));
  505. if (buf_descriptor == NULL) {
  506. /* Something went wrong... Since av_malloc() failed, we cannot even
  507. * allocate a buffer for memcopying into it
  508. */
  509. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  510. res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
  511. return AVERROR(ENOMEM);
  512. }
  513. buf_descriptor->fd = s->fd;
  514. buf_descriptor->index = buf.index;
  515. pkt->priv = buf_descriptor;
  516. return s->buf_len[buf.index];
  517. }
  518. static int mmap_start(AVFormatContext *ctx)
  519. {
  520. struct video_data *s = ctx->priv_data;
  521. enum v4l2_buf_type type;
  522. int i, res;
  523. for (i = 0; i < s->buffers; i++) {
  524. struct v4l2_buffer buf = {
  525. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  526. .index = i,
  527. .memory = V4L2_MEMORY_MMAP
  528. };
  529. res = v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf);
  530. if (res < 0) {
  531. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  532. strerror(errno));
  533. return AVERROR(errno);
  534. }
  535. }
  536. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  537. res = v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type);
  538. if (res < 0) {
  539. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
  540. strerror(errno));
  541. return AVERROR(errno);
  542. }
  543. return 0;
  544. }
  545. static void mmap_close(struct video_data *s)
  546. {
  547. enum v4l2_buf_type type;
  548. int i;
  549. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  550. /* We do not check for the result, because we could
  551. * not do anything about it anyway...
  552. */
  553. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  554. for (i = 0; i < s->buffers; i++) {
  555. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  556. }
  557. av_free(s->buf_start);
  558. av_free(s->buf_len);
  559. }
  560. static int v4l2_set_parameters(AVFormatContext *s1)
  561. {
  562. struct video_data *s = s1->priv_data;
  563. struct v4l2_input input = { 0 };
  564. struct v4l2_standard standard = { 0 };
  565. struct v4l2_streamparm streamparm = { 0 };
  566. struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
  567. AVRational framerate_q = { 0 };
  568. int i, ret;
  569. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  570. if (s->framerate &&
  571. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  572. av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  573. s->framerate);
  574. return ret;
  575. }
  576. /* set tv video input */
  577. input.index = s->channel;
  578. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  579. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
  580. return AVERROR(EIO);
  581. }
  582. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
  583. s->channel, input.name);
  584. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
  585. av_log(s1, AV_LOG_ERROR,
  586. "The V4L2 driver ioctl set input(%d) failed\n",
  587. s->channel);
  588. return AVERROR(EIO);
  589. }
  590. if (s->standard) {
  591. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
  592. s->standard);
  593. /* set tv standard */
  594. for(i=0;;i++) {
  595. standard.index = i;
  596. ret = v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard);
  597. if (ret < 0 || !av_strcasecmp(standard.name, s->standard))
  598. break;
  599. }
  600. if (ret < 0) {
  601. av_log(s1, AV_LOG_ERROR, "Unknown standard '%s'\n", s->standard);
  602. return ret;
  603. }
  604. av_log(s1, AV_LOG_DEBUG,
  605. "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
  606. s->standard, (uint64_t)standard.id);
  607. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  608. av_log(s1, AV_LOG_ERROR,
  609. "The V4L2 driver ioctl set standard(%s) failed\n",
  610. s->standard);
  611. return AVERROR(EIO);
  612. }
  613. }
  614. if (framerate_q.num && framerate_q.den) {
  615. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  616. framerate_q.den, framerate_q.num);
  617. tpf->numerator = framerate_q.den;
  618. tpf->denominator = framerate_q.num;
  619. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
  620. av_log(s1, AV_LOG_ERROR,
  621. "ioctl set time per frame(%d/%d) failed\n",
  622. framerate_q.den, framerate_q.num);
  623. return AVERROR(EIO);
  624. }
  625. if (framerate_q.num != tpf->denominator ||
  626. framerate_q.den != tpf->numerator) {
  627. av_log(s1, AV_LOG_INFO,
  628. "The driver changed the time per frame from "
  629. "%d/%d to %d/%d\n",
  630. framerate_q.den, framerate_q.num,
  631. tpf->numerator, tpf->denominator);
  632. }
  633. } else {
  634. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
  635. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
  636. strerror(errno));
  637. return AVERROR(errno);
  638. }
  639. }
  640. s1->streams[0]->codec->time_base.den = tpf->denominator;
  641. s1->streams[0]->codec->time_base.num = tpf->numerator;
  642. return 0;
  643. }
  644. static uint32_t device_try_init(AVFormatContext *s1,
  645. enum PixelFormat pix_fmt,
  646. int *width,
  647. int *height,
  648. enum CodecID *codec_id)
  649. {
  650. uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  651. if (desired_format == 0 ||
  652. device_init(s1, width, height, desired_format) < 0) {
  653. int i;
  654. desired_format = 0;
  655. for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  656. if (s1->video_codec_id == CODEC_ID_NONE ||
  657. fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  658. desired_format = fmt_conversion_table[i].v4l2_fmt;
  659. if (device_init(s1, width, height, desired_format) >= 0) {
  660. break;
  661. }
  662. desired_format = 0;
  663. }
  664. }
  665. }
  666. if (desired_format != 0) {
  667. *codec_id = fmt_v4l2codec(desired_format);
  668. assert(*codec_id != CODEC_ID_NONE);
  669. }
  670. return desired_format;
  671. }
  672. static int v4l2_read_header(AVFormatContext *s1)
  673. {
  674. struct video_data *s = s1->priv_data;
  675. AVStream *st;
  676. int res = 0;
  677. uint32_t desired_format;
  678. enum CodecID codec_id;
  679. enum PixelFormat pix_fmt = PIX_FMT_NONE;
  680. st = avformat_new_stream(s1, NULL);
  681. if (!st) {
  682. res = AVERROR(ENOMEM);
  683. goto out;
  684. }
  685. s->fd = device_open(s1);
  686. if (s->fd < 0) {
  687. res = s->fd;
  688. goto out;
  689. }
  690. if (s->list_format) {
  691. list_formats(s1, s->fd, s->list_format);
  692. res = AVERROR_EXIT;
  693. goto out;
  694. }
  695. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  696. if (s->pixel_format) {
  697. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  698. if (codec)
  699. s1->video_codec_id = codec->id;
  700. pix_fmt = av_get_pix_fmt(s->pixel_format);
  701. if (pix_fmt == PIX_FMT_NONE && !codec) {
  702. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  703. s->pixel_format);
  704. res = AVERROR(EINVAL);
  705. goto out;
  706. }
  707. }
  708. if (!s->width && !s->height) {
  709. struct v4l2_format fmt;
  710. av_log(s1, AV_LOG_VERBOSE,
  711. "Querying the device for the current frame size\n");
  712. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  713. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  714. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
  715. strerror(errno));
  716. res = AVERROR(errno);
  717. goto out;
  718. }
  719. s->width = fmt.fmt.pix.width;
  720. s->height = fmt.fmt.pix.height;
  721. av_log(s1, AV_LOG_VERBOSE,
  722. "Setting frame size to %dx%d\n", s->width, s->height);
  723. }
  724. desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
  725. &codec_id);
  726. if (desired_format == 0) {
  727. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  728. "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
  729. v4l2_close(s->fd);
  730. res = AVERROR(EIO);
  731. goto out;
  732. }
  733. if ((res = av_image_check_size(s->width, s->height, 0, s1)) < 0)
  734. goto out;
  735. s->frame_format = desired_format;
  736. if ((res = v4l2_set_parameters(s1)) < 0)
  737. goto out;
  738. st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
  739. s->frame_size =
  740. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  741. if ((res = mmap_init(s1)) ||
  742. (res = mmap_start(s1)) < 0) {
  743. v4l2_close(s->fd);
  744. goto out;
  745. }
  746. s->top_field_first = first_field(s->fd);
  747. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  748. st->codec->codec_id = codec_id;
  749. if (codec_id == CODEC_ID_RAWVIDEO)
  750. st->codec->codec_tag =
  751. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  752. if (desired_format == V4L2_PIX_FMT_YVU420)
  753. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  754. st->codec->width = s->width;
  755. st->codec->height = s->height;
  756. st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
  757. out:
  758. return res;
  759. }
  760. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  761. {
  762. struct video_data *s = s1->priv_data;
  763. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  764. int res;
  765. av_init_packet(pkt);
  766. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  767. return res;
  768. }
  769. if (frame && s->interlaced) {
  770. frame->interlaced_frame = 1;
  771. frame->top_field_first = s->top_field_first;
  772. }
  773. return pkt->size;
  774. }
  775. static int v4l2_read_close(AVFormatContext *s1)
  776. {
  777. struct video_data *s = s1->priv_data;
  778. mmap_close(s);
  779. v4l2_close(s->fd);
  780. return 0;
  781. }
  782. #define OFFSET(x) offsetof(struct video_data, x)
  783. #define DEC AV_OPT_FLAG_DECODING_PARAM
  784. static const AVOption options[] = {
  785. { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  786. { "channel", "TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC },
  787. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  788. { "pixel_format", "Preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  789. { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  790. { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  791. { "list_formats", "List available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC, "list_formats" },
  792. { "all", "Show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  793. { "raw", "Show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  794. { "compressed", "Show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  795. { "timestamps", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
  796. { "default", "Use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  797. { "abs", "Use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  798. { "mono2abs", "Force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.dbl = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  799. { "ts", "Kind of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, 2, DEC, "timestamps" },
  800. { NULL },
  801. };
  802. static const AVClass v4l2_class = {
  803. .class_name = "V4L2 indev",
  804. .item_name = av_default_item_name,
  805. .option = options,
  806. .version = LIBAVUTIL_VERSION_INT,
  807. };
  808. AVInputFormat ff_v4l2_demuxer = {
  809. .name = "video4linux2,v4l2",
  810. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  811. .priv_data_size = sizeof(struct video_data),
  812. .read_header = v4l2_read_header,
  813. .read_packet = v4l2_read_packet,
  814. .read_close = v4l2_read_close,
  815. .flags = AVFMT_NOFILE,
  816. .priv_class = &v4l2_class,
  817. };