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.

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