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.

927 lines
29KB

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