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.

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