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.

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