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.

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