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.

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