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.

864 lines
26KB

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