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.

854 lines
26KB

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