You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

861 lines
26KB

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