v4l2.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762
  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 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 <unistd.h>
  33. #include <fcntl.h>
  34. #include <sys/ioctl.h>
  35. #include <sys/mman.h>
  36. #include <sys/time.h>
  37. #if HAVE_SYS_VIDEOIO_H
  38. #include <sys/videoio.h>
  39. #else
  40. #include <asm/types.h>
  41. #include <linux/videodev2.h>
  42. #endif
  43. #include <time.h>
  44. #include <strings.h>
  45. #include "libavutil/imgutils.h"
  46. #include "libavutil/log.h"
  47. #include "libavutil/opt.h"
  48. #include "libavutil/parseutils.h"
  49. #include "libavutil/pixdesc.h"
  50. static const int desired_video_buffers = 256;
  51. enum io_method {
  52. io_read,
  53. io_mmap,
  54. io_userptr
  55. };
  56. struct video_data {
  57. AVClass *class;
  58. int fd;
  59. int frame_format; /* V4L2_PIX_FMT_* */
  60. enum io_method io_method;
  61. int width, height;
  62. int frame_size;
  63. int top_field_first;
  64. int buffers;
  65. void **buf_start;
  66. unsigned int *buf_len;
  67. char *standard;
  68. int channel;
  69. char *video_size; /**< String describing video size, set by a private option. */
  70. char *pixel_format; /**< Set by a private option. */
  71. char *framerate; /**< Set by a private option. */
  72. };
  73. struct buff_data {
  74. int index;
  75. int fd;
  76. };
  77. struct fmt_map {
  78. enum PixelFormat ff_fmt;
  79. enum CodecID codec_id;
  80. uint32_t v4l2_fmt;
  81. };
  82. static struct fmt_map fmt_conversion_table[] = {
  83. //ff_fmt codec_id v4l2_fmt
  84. { PIX_FMT_YUV420P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV420 },
  85. { PIX_FMT_YUV422P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV422P },
  86. { PIX_FMT_YUYV422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUYV },
  87. { PIX_FMT_UYVY422, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_UYVY },
  88. { PIX_FMT_YUV411P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV411P },
  89. { PIX_FMT_YUV410P, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_YUV410 },
  90. { PIX_FMT_RGB555, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB555 },
  91. { PIX_FMT_RGB565, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB565 },
  92. { PIX_FMT_BGR24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR24 },
  93. { PIX_FMT_RGB24, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_RGB24 },
  94. { PIX_FMT_BGRA, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_BGR32 },
  95. { PIX_FMT_GRAY8, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_GREY },
  96. { PIX_FMT_NV12, CODEC_ID_RAWVIDEO, V4L2_PIX_FMT_NV12 },
  97. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_MJPEG },
  98. { PIX_FMT_NONE, CODEC_ID_MJPEG, V4L2_PIX_FMT_JPEG },
  99. };
  100. static int device_open(AVFormatContext *ctx, uint32_t *capabilities)
  101. {
  102. struct v4l2_capability cap;
  103. int fd;
  104. int res, err;
  105. int flags = O_RDWR;
  106. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  107. flags |= O_NONBLOCK;
  108. }
  109. fd = open(ctx->filename, flags, 0);
  110. if (fd < 0) {
  111. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s : %s\n",
  112. ctx->filename, strerror(errno));
  113. return AVERROR(errno);
  114. }
  115. res = ioctl(fd, VIDIOC_QUERYCAP, &cap);
  116. // ENOIOCTLCMD definition only availble on __KERNEL__
  117. if (res < 0 && ((err = errno) == 515)) {
  118. av_log(ctx, AV_LOG_ERROR, "QUERYCAP not implemented, probably V4L device but not supporting V4L2\n");
  119. close(fd);
  120. return AVERROR(515);
  121. }
  122. if (res < 0) {
  123. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  124. strerror(errno));
  125. close(fd);
  126. return AVERROR(err);
  127. }
  128. if ((cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) == 0) {
  129. av_log(ctx, AV_LOG_ERROR, "Not a video capture device\n");
  130. close(fd);
  131. return AVERROR(ENODEV);
  132. }
  133. *capabilities = cap.capabilities;
  134. return fd;
  135. }
  136. static int device_init(AVFormatContext *ctx, int *width, int *height, uint32_t pix_fmt)
  137. {
  138. struct video_data *s = ctx->priv_data;
  139. int fd = s->fd;
  140. struct v4l2_format fmt;
  141. int res;
  142. memset(&fmt, 0, sizeof(struct v4l2_format));
  143. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  144. fmt.fmt.pix.width = *width;
  145. fmt.fmt.pix.height = *height;
  146. fmt.fmt.pix.pixelformat = pix_fmt;
  147. fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
  148. res = ioctl(fd, VIDIOC_S_FMT, &fmt);
  149. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  150. av_log(ctx, AV_LOG_INFO, "The V4L2 driver changed the video from %dx%d to %dx%d\n", *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  151. *width = fmt.fmt.pix.width;
  152. *height = fmt.fmt.pix.height;
  153. }
  154. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  155. av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver changed the pixel format from 0x%08X to 0x%08X\n", pix_fmt, fmt.fmt.pix.pixelformat);
  156. res = -1;
  157. }
  158. return res;
  159. }
  160. static int first_field(int fd)
  161. {
  162. int res;
  163. v4l2_std_id std;
  164. res = ioctl(fd, VIDIOC_G_STD, &std);
  165. if (res < 0) {
  166. return 0;
  167. }
  168. if (std & V4L2_STD_NTSC) {
  169. return 0;
  170. }
  171. return 1;
  172. }
  173. static uint32_t fmt_ff2v4l(enum PixelFormat pix_fmt, enum CodecID codec_id)
  174. {
  175. int i;
  176. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  177. if ((codec_id == CODEC_ID_NONE ||
  178. fmt_conversion_table[i].codec_id == codec_id) &&
  179. (pix_fmt == PIX_FMT_NONE ||
  180. fmt_conversion_table[i].ff_fmt == pix_fmt)) {
  181. return fmt_conversion_table[i].v4l2_fmt;
  182. }
  183. }
  184. return 0;
  185. }
  186. static enum PixelFormat fmt_v4l2ff(uint32_t v4l2_fmt, enum CodecID codec_id)
  187. {
  188. int i;
  189. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  190. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt &&
  191. fmt_conversion_table[i].codec_id == codec_id) {
  192. return fmt_conversion_table[i].ff_fmt;
  193. }
  194. }
  195. return PIX_FMT_NONE;
  196. }
  197. static enum CodecID fmt_v4l2codec(uint32_t v4l2_fmt)
  198. {
  199. int i;
  200. for (i = 0; i < FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  201. if (fmt_conversion_table[i].v4l2_fmt == v4l2_fmt) {
  202. return fmt_conversion_table[i].codec_id;
  203. }
  204. }
  205. return CODEC_ID_NONE;
  206. }
  207. static int mmap_init(AVFormatContext *ctx)
  208. {
  209. struct video_data *s = ctx->priv_data;
  210. struct v4l2_requestbuffers req;
  211. int i, res;
  212. memset(&req, 0, sizeof(struct v4l2_requestbuffers));
  213. req.count = desired_video_buffers;
  214. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  215. req.memory = V4L2_MEMORY_MMAP;
  216. res = ioctl(s->fd, VIDIOC_REQBUFS, &req);
  217. if (res < 0) {
  218. if (errno == EINVAL) {
  219. av_log(ctx, AV_LOG_ERROR, "Device does not support mmap\n");
  220. } else {
  221. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS)\n");
  222. }
  223. return AVERROR(errno);
  224. }
  225. if (req.count < 2) {
  226. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  227. return AVERROR(ENOMEM);
  228. }
  229. s->buffers = req.count;
  230. s->buf_start = av_malloc(sizeof(void *) * s->buffers);
  231. if (s->buf_start == NULL) {
  232. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  233. return AVERROR(ENOMEM);
  234. }
  235. s->buf_len = av_malloc(sizeof(unsigned int) * s->buffers);
  236. if (s->buf_len == NULL) {
  237. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  238. av_free(s->buf_start);
  239. return AVERROR(ENOMEM);
  240. }
  241. for (i = 0; i < req.count; i++) {
  242. struct v4l2_buffer buf;
  243. memset(&buf, 0, sizeof(struct v4l2_buffer));
  244. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  245. buf.memory = V4L2_MEMORY_MMAP;
  246. buf.index = i;
  247. res = ioctl(s->fd, VIDIOC_QUERYBUF, &buf);
  248. if (res < 0) {
  249. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF)\n");
  250. return AVERROR(errno);
  251. }
  252. s->buf_len[i] = buf.length;
  253. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  254. av_log(ctx, AV_LOG_ERROR, "Buffer len [%d] = %d != %d\n", i, s->buf_len[i], s->frame_size);
  255. return -1;
  256. }
  257. s->buf_start[i] = mmap (NULL, buf.length,
  258. PROT_READ | PROT_WRITE, MAP_SHARED, s->fd, buf.m.offset);
  259. if (s->buf_start[i] == MAP_FAILED) {
  260. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", strerror(errno));
  261. return AVERROR(errno);
  262. }
  263. }
  264. return 0;
  265. }
  266. static int read_init(AVFormatContext *ctx)
  267. {
  268. return -1;
  269. }
  270. static void mmap_release_buffer(AVPacket *pkt)
  271. {
  272. struct v4l2_buffer buf;
  273. int res, fd;
  274. struct buff_data *buf_descriptor = pkt->priv;
  275. if (pkt->data == NULL) {
  276. return;
  277. }
  278. memset(&buf, 0, sizeof(struct v4l2_buffer));
  279. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  280. buf.memory = V4L2_MEMORY_MMAP;
  281. buf.index = buf_descriptor->index;
  282. fd = buf_descriptor->fd;
  283. av_free(buf_descriptor);
  284. res = ioctl(fd, VIDIOC_QBUF, &buf);
  285. if (res < 0) {
  286. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
  287. }
  288. pkt->data = NULL;
  289. pkt->size = 0;
  290. }
  291. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  292. {
  293. struct video_data *s = ctx->priv_data;
  294. struct v4l2_buffer buf;
  295. struct buff_data *buf_descriptor;
  296. int res;
  297. memset(&buf, 0, sizeof(struct v4l2_buffer));
  298. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  299. buf.memory = V4L2_MEMORY_MMAP;
  300. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  301. while ((res = ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  302. if (res < 0) {
  303. if (errno == EAGAIN) {
  304. pkt->size = 0;
  305. return AVERROR(EAGAIN);
  306. }
  307. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", strerror(errno));
  308. return AVERROR(errno);
  309. }
  310. assert (buf.index < s->buffers);
  311. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  312. av_log(ctx, AV_LOG_ERROR, "The v4l2 frame is %d bytes, but %d bytes are expected\n", buf.bytesused, s->frame_size);
  313. return AVERROR_INVALIDDATA;
  314. }
  315. /* Image is at s->buff_start[buf.index] */
  316. pkt->data= s->buf_start[buf.index];
  317. pkt->size = buf.bytesused;
  318. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  319. pkt->destruct = mmap_release_buffer;
  320. buf_descriptor = av_malloc(sizeof(struct buff_data));
  321. if (buf_descriptor == NULL) {
  322. /* Something went wrong... Since av_malloc() failed, we cannot even
  323. * allocate a buffer for memcopying into it
  324. */
  325. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  326. res = ioctl(s->fd, VIDIOC_QBUF, &buf);
  327. return AVERROR(ENOMEM);
  328. }
  329. buf_descriptor->fd = s->fd;
  330. buf_descriptor->index = buf.index;
  331. pkt->priv = buf_descriptor;
  332. return s->buf_len[buf.index];
  333. }
  334. static int read_frame(AVFormatContext *ctx, AVPacket *pkt)
  335. {
  336. return -1;
  337. }
  338. static int mmap_start(AVFormatContext *ctx)
  339. {
  340. struct video_data *s = ctx->priv_data;
  341. enum v4l2_buf_type type;
  342. int i, res;
  343. for (i = 0; i < s->buffers; i++) {
  344. struct v4l2_buffer buf;
  345. memset(&buf, 0, sizeof(struct v4l2_buffer));
  346. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  347. buf.memory = V4L2_MEMORY_MMAP;
  348. buf.index = i;
  349. res = ioctl(s->fd, VIDIOC_QBUF, &buf);
  350. if (res < 0) {
  351. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", strerror(errno));
  352. return AVERROR(errno);
  353. }
  354. }
  355. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  356. res = ioctl(s->fd, VIDIOC_STREAMON, &type);
  357. if (res < 0) {
  358. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", strerror(errno));
  359. return AVERROR(errno);
  360. }
  361. return 0;
  362. }
  363. static void mmap_close(struct video_data *s)
  364. {
  365. enum v4l2_buf_type type;
  366. int i;
  367. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  368. /* We do not check for the result, because we could
  369. * not do anything about it anyway...
  370. */
  371. ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  372. for (i = 0; i < s->buffers; i++) {
  373. munmap(s->buf_start[i], s->buf_len[i]);
  374. }
  375. av_free(s->buf_start);
  376. av_free(s->buf_len);
  377. }
  378. static int v4l2_set_parameters(AVFormatContext *s1, AVFormatParameters *ap)
  379. {
  380. struct video_data *s = s1->priv_data;
  381. struct v4l2_input input;
  382. struct v4l2_standard standard;
  383. struct v4l2_streamparm streamparm = { 0 };
  384. struct v4l2_fract *tpf = &streamparm.parm.capture.timeperframe;
  385. int i, ret;
  386. AVRational fps;
  387. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  388. if (s->framerate && (ret = av_parse_video_rate(&fps, s->framerate)) < 0) {
  389. av_log(s1, AV_LOG_ERROR, "Couldn't parse framerate.\n");
  390. return ret;
  391. }
  392. #if FF_API_FORMAT_PARAMETERS
  393. if (ap->channel > 0)
  394. s->channel = ap->channel;
  395. if (ap->time_base.num)
  396. fps = (AVRational){ap->time_base.den, ap->time_base.num};
  397. #endif
  398. /* set tv video input */
  399. memset (&input, 0, sizeof (input));
  400. input.index = s->channel;
  401. if (ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  402. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl enum input failed:\n");
  403. return AVERROR(EIO);
  404. }
  405. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set input_id: %d, input: %s\n",
  406. s->channel, input.name);
  407. if (ioctl(s->fd, VIDIOC_S_INPUT, &input.index) < 0) {
  408. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set input(%d) failed\n",
  409. s->channel);
  410. return AVERROR(EIO);
  411. }
  412. #if FF_API_FORMAT_PARAMETERS
  413. if (ap->standard) {
  414. av_freep(&s->standard);
  415. s->standard = av_strdup(ap->standard);
  416. }
  417. #endif
  418. if (s->standard) {
  419. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s\n",
  420. s->standard);
  421. /* set tv standard */
  422. memset (&standard, 0, sizeof (standard));
  423. for(i=0;;i++) {
  424. standard.index = i;
  425. if (ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  426. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
  427. s->standard);
  428. return AVERROR(EIO);
  429. }
  430. if (!strcasecmp(standard.name, s->standard)) {
  431. break;
  432. }
  433. }
  434. av_log(s1, AV_LOG_DEBUG, "The V4L2 driver set standard: %s, id: %"PRIu64"\n",
  435. s->standard, (uint64_t)standard.id);
  436. if (ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  437. av_log(s1, AV_LOG_ERROR, "The V4L2 driver ioctl set standard(%s) failed\n",
  438. s->standard);
  439. return AVERROR(EIO);
  440. }
  441. }
  442. if (fps.num && fps.den) {
  443. av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  444. fps.den, fps.num);
  445. tpf->numerator = fps.den;
  446. tpf->denominator = fps.num;
  447. if (ioctl(s->fd, VIDIOC_S_PARM, &streamparm) != 0) {
  448. av_log(s1, AV_LOG_ERROR,
  449. "ioctl set time per frame(%d/%d) failed\n",
  450. fps.den, fps.num);
  451. return AVERROR(EIO);
  452. }
  453. if (fps.num != tpf->denominator ||
  454. fps.den != tpf->numerator) {
  455. av_log(s1, AV_LOG_INFO,
  456. "The driver changed the time per frame from %d/%d to %d/%d\n",
  457. fps.den, fps.num,
  458. tpf->numerator, tpf->denominator);
  459. }
  460. } else {
  461. /* if timebase value is not set, read the timebase value from the driver */
  462. if (ioctl(s->fd, VIDIOC_G_PARM, &streamparm) != 0) {
  463. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", strerror(errno));
  464. return AVERROR(errno);
  465. }
  466. }
  467. s1->streams[0]->codec->time_base.den = tpf->denominator;
  468. s1->streams[0]->codec->time_base.num = tpf->numerator;
  469. return 0;
  470. }
  471. static uint32_t device_try_init(AVFormatContext *s1,
  472. enum PixelFormat pix_fmt,
  473. int *width,
  474. int *height,
  475. enum CodecID *codec_id)
  476. {
  477. uint32_t desired_format = fmt_ff2v4l(pix_fmt, s1->video_codec_id);
  478. if (desired_format == 0 ||
  479. device_init(s1, width, height, desired_format) < 0) {
  480. int i;
  481. desired_format = 0;
  482. for (i = 0; i<FF_ARRAY_ELEMS(fmt_conversion_table); i++) {
  483. if (s1->video_codec_id == CODEC_ID_NONE ||
  484. fmt_conversion_table[i].codec_id == s1->video_codec_id) {
  485. desired_format = fmt_conversion_table[i].v4l2_fmt;
  486. if (device_init(s1, width, height, desired_format) >= 0) {
  487. break;
  488. }
  489. desired_format = 0;
  490. }
  491. }
  492. }
  493. if (desired_format != 0) {
  494. *codec_id = fmt_v4l2codec(desired_format);
  495. assert(*codec_id != CODEC_ID_NONE);
  496. }
  497. return desired_format;
  498. }
  499. static int v4l2_read_header(AVFormatContext *s1, AVFormatParameters *ap)
  500. {
  501. struct video_data *s = s1->priv_data;
  502. AVStream *st;
  503. int res = 0;
  504. uint32_t desired_format, capabilities;
  505. enum CodecID codec_id;
  506. enum PixelFormat pix_fmt = PIX_FMT_NONE;
  507. st = av_new_stream(s1, 0);
  508. if (!st) {
  509. res = AVERROR(ENOMEM);
  510. goto out;
  511. }
  512. av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  513. if (s->video_size && (res = av_parse_video_size(&s->width, &s->height, s->video_size)) < 0) {
  514. av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");
  515. goto out;
  516. }
  517. if (s->pixel_format && (pix_fmt = av_get_pix_fmt(s->pixel_format)) == PIX_FMT_NONE) {
  518. av_log(s1, AV_LOG_ERROR, "No such pixel format: %s.\n", s->pixel_format);
  519. res = AVERROR(EINVAL);
  520. goto out;
  521. }
  522. #if FF_API_FORMAT_PARAMETERS
  523. if (ap->width > 0)
  524. s->width = ap->width;
  525. if (ap->height > 0)
  526. s->height = ap->height;
  527. if (ap->pix_fmt)
  528. pix_fmt = ap->pix_fmt;
  529. #endif
  530. capabilities = 0;
  531. s->fd = device_open(s1, &capabilities);
  532. if (s->fd < 0) {
  533. res = AVERROR(EIO);
  534. goto out;
  535. }
  536. av_log(s1, AV_LOG_VERBOSE, "[%d]Capabilities: %x\n", s->fd, capabilities);
  537. if (!s->width && !s->height) {
  538. struct v4l2_format fmt;
  539. av_log(s1, AV_LOG_VERBOSE, "Querying the device for the current frame size\n");
  540. fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  541. if (ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  542. av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", strerror(errno));
  543. res = AVERROR(errno);
  544. goto out;
  545. }
  546. s->width = fmt.fmt.pix.width;
  547. s->height = fmt.fmt.pix.height;
  548. av_log(s1, AV_LOG_VERBOSE, "Setting frame size to %dx%d\n", s->width, s->height);
  549. }
  550. desired_format = device_try_init(s1, pix_fmt, &s->width, &s->height, &codec_id);
  551. if (desired_format == 0) {
  552. av_log(s1, AV_LOG_ERROR, "Cannot find a proper format for "
  553. "codec_id %d, pix_fmt %d.\n", s1->video_codec_id, pix_fmt);
  554. close(s->fd);
  555. res = AVERROR(EIO);
  556. goto out;
  557. }
  558. if ((res = av_image_check_size(s->width, s->height, 0, s1) < 0))
  559. goto out;
  560. s->frame_format = desired_format;
  561. if ((res = v4l2_set_parameters(s1, ap) < 0))
  562. goto out;
  563. st->codec->pix_fmt = fmt_v4l2ff(desired_format, codec_id);
  564. s->frame_size = avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  565. if (capabilities & V4L2_CAP_STREAMING) {
  566. s->io_method = io_mmap;
  567. res = mmap_init(s1);
  568. if (res == 0) {
  569. res = mmap_start(s1);
  570. }
  571. } else {
  572. s->io_method = io_read;
  573. res = read_init(s1);
  574. }
  575. if (res < 0) {
  576. close(s->fd);
  577. res = AVERROR(EIO);
  578. goto out;
  579. }
  580. s->top_field_first = first_field(s->fd);
  581. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  582. st->codec->codec_id = codec_id;
  583. st->codec->width = s->width;
  584. st->codec->height = s->height;
  585. st->codec->bit_rate = s->frame_size * 1/av_q2d(st->codec->time_base) * 8;
  586. out:
  587. av_freep(&s->video_size);
  588. av_freep(&s->pixel_format);
  589. av_freep(&s->standard);
  590. av_freep(&s->framerate);
  591. return res;
  592. }
  593. static int v4l2_read_packet(AVFormatContext *s1, AVPacket *pkt)
  594. {
  595. struct video_data *s = s1->priv_data;
  596. int res;
  597. if (s->io_method == io_mmap) {
  598. av_init_packet(pkt);
  599. res = mmap_read_frame(s1, pkt);
  600. } else if (s->io_method == io_read) {
  601. if (av_new_packet(pkt, s->frame_size) < 0)
  602. return AVERROR(EIO);
  603. res = read_frame(s1, pkt);
  604. } else {
  605. return AVERROR(EIO);
  606. }
  607. if (res < 0) {
  608. return res;
  609. }
  610. if (s1->streams[0]->codec->coded_frame) {
  611. s1->streams[0]->codec->coded_frame->interlaced_frame = 1;
  612. s1->streams[0]->codec->coded_frame->top_field_first = s->top_field_first;
  613. }
  614. return pkt->size;
  615. }
  616. static int v4l2_read_close(AVFormatContext *s1)
  617. {
  618. struct video_data *s = s1->priv_data;
  619. if (s->io_method == io_mmap) {
  620. mmap_close(s);
  621. }
  622. close(s->fd);
  623. return 0;
  624. }
  625. #define OFFSET(x) offsetof(struct video_data, x)
  626. #define DEC AV_OPT_FLAG_DECODING_PARAM
  627. static const AVOption options[] = {
  628. { "standard", "", offsetof(struct video_data, standard), FF_OPT_TYPE_STRING, {.str = "NTSC" }, 0, 0, AV_OPT_FLAG_DECODING_PARAM },
  629. { "channel", "", offsetof(struct video_data, channel), FF_OPT_TYPE_INT, {.dbl = 0 }, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM },
  630. { "video_size", "A string describing frame size, such as 640x480 or hd720.", OFFSET(video_size), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  631. { "pixel_format", "", OFFSET(pixel_format), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  632. { "framerate", "", OFFSET(framerate), FF_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  633. { NULL },
  634. };
  635. static const AVClass v4l2_class = {
  636. .class_name = "V4L2 indev",
  637. .item_name = av_default_item_name,
  638. .option = options,
  639. .version = LIBAVUTIL_VERSION_INT,
  640. };
  641. AVInputFormat ff_v4l2_demuxer = {
  642. "video4linux2",
  643. NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  644. sizeof(struct video_data),
  645. NULL,
  646. v4l2_read_header,
  647. v4l2_read_packet,
  648. v4l2_read_close,
  649. .flags = AVFMT_NOFILE,
  650. .priv_class = &v4l2_class,
  651. };