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.

858 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 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 PixelFormat ff_fmt;
  81. enum CodecID codec_id;
  82. uint32_t v4l2_fmt;
  83. };
  84. static struct fmt_map fmt_conversion_table[] = {
  85. //ff_fmt codec_id v4l2_fmt
  86. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
  87. { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
  88. { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
  89. { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
  90. { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
  91. { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
  92. { PIX_FMT_RGB555, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
  93. { PIX_FMT_RGB565, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
  94. { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
  95. { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
  96. { PIX_FMT_BGRA, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
  97. { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
  98. { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
  99. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
  100. { PIX_FMT_NONE, 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 PixelFormat pix_fmt, enum CodecID codec_id)
  190. {
  191. int i;
  192. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  193. if ((codec_id == CODEC_ID_NONE ||
  194. fmt_conversion_table[i].codec_id == codec_id) &&
  195. (pix_fmt == 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 PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID 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 PIX_FMT_NONE;
  212. }
  213. static enum CodecID 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 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 CodecID codec_id = fmt_v4l2codec(vfd.pixelformat);
  252. enum PixelFormat 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. assert (buf.index < s->buffers);
  389. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  390. av_log(ctx, AV_LOG_ERROR,
  391. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  392. buf.bytesused, s->frame_size);
  393. return AVERROR_INVALIDDATA;
  394. }
  395. /* Image is at s->buff_start[buf.index] */
  396. pkt->data= s->buf_start[buf.index];
  397. pkt->size = buf.bytesused;
  398. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  399. pkt->destruct = mmap_release_buffer;
  400. buf_descriptor = av_malloc(sizeof(struct buff_data));
  401. if (buf_descriptor == NULL) {
  402. /* Something went wrong... Since av_malloc() failed, we cannot even
  403. * allocate a buffer for memcopying into it
  404. */
  405. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  406. res = ioctl(s->fd, VIDIOC_QBUF, &buf);
  407. return AVERROR(ENOMEM);
  408. }
  409. buf_descriptor->fd = s->fd;
  410. buf_descriptor->index = buf.index;
  411. pkt->priv = buf_descriptor;
  412. return s->buf_len[buf.index];
  413. }
  414. static int mmap_start(AVFormatContext *ctx)
  415. {
  416. struct video_data *s = ctx->priv_data;
  417. enum v4l2_buf_type type;
  418. int i, res;
  419. for (i = 0; i < s->buffers; i++) {
  420. struct v4l2_buffer buf = {
  421. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  422. .index = i,
  423. .memory = V4L2_MEMORY_MMAP
  424. };
  425. res = ioctl(s->fd, VIDIOC_QBUF, &buf);
  426. if (res < 0) {
  427. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n",
  428. strerror(errno));
  429. return AVERROR(errno);
  430. }
  431. }
  432. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  433. res = ioctl(s->fd, VIDIOC_STREAMON, &type);
  434. if (res < 0) {
  435. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n",
  436. strerror(errno));
  437. return AVERROR(errno);
  438. }
  439. return 0;
  440. }
  441. static void mmap_close(struct video_data *s)
  442. {
  443. enum v4l2_buf_type type;
  444. int i;
  445. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  446. /* We do not check for the result, because we could
  447. * not do anything about it anyway...
  448. */
  449. ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  450. for (i = 0; i < s->buffers; i++) {
  451. munmap(s->buf_start[i], s->buf_len[i]);
  452. }
  453. av_free(s->buf_start);
  454. av_free(s->buf_len);
  455. }
  456. static int v4l2_set_parameters(AVFormatContext *s1)
  457. {
  458. struct video_data *s = s1->priv_data;
  459. struct v4l2_input input = { 0 };
  460. struct v4l2_standard standard = { 0 };
  461. struct v4l2_streamparm streamparm = { 0 };
  462. struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
  463. AVRational framerate_q = { 0 };
  464. int i, ret;
  465. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  466. if (s->framerate &&
  467. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  468. av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  469. s->framerate);
  470. return ret;
  471. }
  472. /* set tv video input */
  473. input.index = s->channel;
  474. if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  475. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
  476. return AVERROR(EIO);
  477. }
  478. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
  479. s->channel, input.name);
  480. if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
  481. av_log(s1, AV_LOG_ERROR,
  482. "The V4L2 driver ioctl set input(%d) failed\n",
  483. s->channel);
  484. return AVERROR(EIO);
  485. }
  486. if (s->standard) {
  487. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
  488. s->standard);
  489. /* set tv standard */
  490. for(i=0;;i++) {
  491. standard.index = i;
  492. if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  493. av_log(s1, AV_LOG_ERROR,
  494. "The V4L2 driver ioctl set standard(%s) failed\n",
  495. s->standard);
  496. return AVERROR(EIO);
  497. }
  498. if (!av_strcasecmp(standard.name, s->standard)) {
  499. break;
  500. }
  501. }
  502. av_log(s1, AV_LOG_DEBUG,
  503. "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
  504. s->standard, (uint64_t)standard.id);
  505. if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  506. av_log(s1, AV_LOG_ERROR,
  507. "The V4L2 driver ioctl set standard(%s) failed\n",
  508. s->standard);
  509. return AVERROR(EIO);
  510. }
  511. }
  512. if (framerate_q.num && framerate_q.den) {
  513. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  514. framerate_q.den, framerate_q.num);
  515. tpf->numerator = framerate_q.den;
  516. tpf->denominator = framerate_q.num;
  517. if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
  518. av_log(s1, AV_LOG_ERROR,
  519. "ioctl set time per frame(%d/%d) failed\n",
  520. framerate_q.den, framerate_q.num);
  521. return AVERROR(EIO);
  522. }
  523. if (framerate_q.num != tpf->denominator ||
  524. framerate_q.den != tpf->numerator) {
  525. av_log(s1, AV_LOG_INFO,
  526. "The driver changed the time per frame from "
  527. "%d/%d to %d/%d\n",
  528. framerate_q.den, framerate_q.num,
  529. tpf->numerator, tpf->denominator);
  530. }
  531. } else {
  532. if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
  533. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n",
  534. strerror(errno));
  535. return AVERROR(errno);
  536. }
  537. }
  538. s1->streams[0]->codec->time_base.den = tpf->denominator;
  539. s1->streams[0]->codec->time_base.num = tpf->numerator;
  540. s->timeout = 100 +
  541. av_rescale_q(1, s1->streams[0]->codec->time_base,
  542. (AVRational){1, 1000});
  543. return 0;
  544. }
  545. static uint32_t device_try_init(AVFormatContext *s1,
  546. enum PixelFormat pix_fmt,
  547. int *width,
  548. int *height,
  549. enum CodecID *codec_id)
  550. {
  551. uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  552. if (desired_format == 0 ||
  553. device_init(s1, width, height, desired_format) < 0) {
  554. int i;
  555. desired_format = 0;
  556. for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  557. if (s1->video_codec_id == CODEC_ID_NONE ||
  558. fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  559. desired_format = fmt_conversion_table[i].v4l2_fmt;
  560. if (device_init(s1, width, height, desired_format) >= 0) {
  561. break;
  562. }
  563. desired_format = 0;
  564. }
  565. }
  566. }
  567. if (desired_format != 0) {
  568. *codec_id = fmt_v4l2codec(desired_format);
  569. assert(*codec_id != CODEC_ID_NONE);
  570. }
  571. return desired_format;
  572. }
  573. static int v4l2_read_header(AVFormatContext *s1)
  574. {
  575. struct video_data *s = s1->priv_data;
  576. AVStream *st;
  577. int res = 0;
  578. uint32_t desired_format;
  579. enum CodecID codec_id;
  580. enum PixelFormat pix_fmt = PIX_FMT_NONE;
  581. st = avformat_new_stream(s1, NULL);
  582. if (!st) {
  583. res = AVERROR(ENOMEM);
  584. goto out;
  585. }
  586. s->fd = device_open(s1);
  587. if (s->fd < 0) {
  588. res = s->fd;
  589. goto out;
  590. }
  591. if (s->list_format) {
  592. list_formats(s1, s->fd, s->list_format);
  593. res = AVERROR_EXIT;
  594. goto out;
  595. }
  596. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  597. if (s->video_size &&
  598. (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
  599. av_log(s1, AV_LOG_ERROR, "Could not parse video size '%s'.\n",
  600. s->video_size);
  601. goto out;
  602. }
  603. if (s->pixel_format) {
  604. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  605. if (codec)
  606. s1->video_codec_id = codec->id;
  607. pix_fmt = av_get_pix_fmt(s->pixel_format);
  608. if (pix_fmt == PIX_FMT_NONE && !codec) {
  609. av_log(s1, AV_LOG_ERROR, "No such input format: %s.\n",
  610. s->pixel_format);
  611. res = AVERROR(EINVAL);
  612. goto out;
  613. }
  614. }
  615. if (!s->width && !s->height) {
  616. struct v4l2_format fmt;
  617. av_log(s1, AV_LOG_VERBOSE,
  618. "Querying the device for the current frame size\n");
  619. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  620. if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  621. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n",
  622. strerror(errno));
  623. res = AVERROR(errno);
  624. goto out;
  625. }
  626. s->width = fmt.fmt.pix.width;
  627. s->height = fmt.fmt.pix.height;
  628. av_log(s1, AV_LOG_VERBOSE,
  629. "Setting frame size to %dx%d\n", s->width, s->height);
  630. }
  631. desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height,
  632. &codec_id);
  633. if (desired_format == 0) {
  634. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  635. "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
  636. close(s->fd);
  637. res = AVERROR(EIO);
  638. goto out;
  639. }
  640. if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
  641. goto out;
  642. s->frame_format = desired_format;
  643. if ((res = v4l2_set_parameters(s1) < 0))
  644. goto out;
  645. st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
  646. s->frame_size =
  647. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  648. if ((res = mmap_init(s1)) ||
  649. (res = mmap_start(s1)) < 0) {
  650. close(s->fd);
  651. goto out;
  652. }
  653. s->top_field_first = first_field(s->fd);
  654. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  655. st->codec->codec_id = codec_id;
  656. if (codec_id == CODEC_ID_RAWVIDEO)
  657. st->codec->codec_tag =
  658. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  659. st->codec->width = s->width;
  660. st->codec->height = s->height;
  661. st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
  662. out:
  663. return res;
  664. }
  665. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  666. {
  667. struct video_data *s = s1->priv_data;
  668. AVFrame *frame = s1->streams[0]->codec->coded_frame;
  669. int res;
  670. av_init_packet(pkt);
  671. if ((res = mmap_read_frame(s1, pkt)) < 0) {
  672. return res;
  673. }
  674. if (frame && s->interlaced) {
  675. frame->interlaced_frame = 1;
  676. frame->top_field_first = s->top_field_first;
  677. }
  678. return pkt->size;
  679. }
  680. static int v4l2_read_close(AVFormatContext *s1)
  681. {
  682. struct video_data *s = s1->priv_data;
  683. mmap_close(s);
  684. close(s->fd);
  685. return 0;
  686. }
  687. #define OFFSET(x) offsetof(struct video_data, x)
  688. #define DEC AV_OPT_FLAG_DECODING_PARAM
  689. static const AVOption options[] = {
  690. { "standard", "TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  691. { "channel", "TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC },
  692. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  693. { "pixel_format", "Preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  694. { "input_format", "Preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  695. { "framerate", "", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  696. { "list_formats", "List available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, DEC, "list_formats" },
  697. { "all", "Show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  698. { "raw", "Show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  699. { "compressed", "Show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.dbl = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  700. { NULL },
  701. };
  702. static const AVClass v4l2_class = {
  703. .class_name = "V4L2 indev",
  704. .item_name = av_default_item_name,
  705. .option = options,
  706. .version = LIBAVUTIL_VERSION_INT,
  707. };
  708. AVInputFormat ff_v4l2_demuxer = {
  709. .name = "video4linux2",
  710. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  711. .priv_data_size = sizeof(struct video_data),
  712. .read_header = v4l2_read_header,
  713. .read_packet = v4l2_read_packet,
  714. .read_close = v4l2_read_close,
  715. .flags = AVFMT_NOFILE,
  716. .priv_class = &v4l2_class,
  717. };