v4l2.c 30 KB

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