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.

901 lines
28KB

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