v4l2.c 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041
  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://linuxtv.org/downloads/v4l-dvb-apis/capture-example.html)
  27. *
  28. * Thanks to Michael Niedermayer for providing the mapping between
  29. * V4L2_PIX_FMT_* and AV_PIX_FMT_*
  30. */
  31. #include "v4l2-common.h"
  32. #if CONFIG_LIBV4L2
  33. #include <libv4l2.h>
  34. #endif
  35. static const int desired_video_buffers = 256;
  36. #define V4L_ALLFORMATS 3
  37. #define V4L_RAWFORMATS 1
  38. #define V4L_COMPFORMATS 2
  39. /**
  40. * Return timestamps to the user exactly as returned by the kernel
  41. */
  42. #define V4L_TS_DEFAULT 0
  43. /**
  44. * Autodetect the kind of timestamps returned by the kernel and convert to
  45. * absolute (wall clock) timestamps.
  46. */
  47. #define V4L_TS_ABS 1
  48. /**
  49. * Assume kernel timestamps are from the monotonic clock and convert to
  50. * absolute timestamps.
  51. */
  52. #define V4L_TS_MONO2ABS 2
  53. /**
  54. * Once the kind of timestamps returned by the kernel have been detected,
  55. * the value of the timefilter (NULL or not) determines whether a conversion
  56. * takes place.
  57. */
  58. #define V4L_TS_CONVERT_READY V4L_TS_DEFAULT
  59. struct video_data {
  60. AVClass *class;
  61. int fd;
  62. int frame_format; /* V4L2_PIX_FMT_* */
  63. int width, height;
  64. int frame_size;
  65. int interlaced;
  66. int top_field_first;
  67. int ts_mode;
  68. TimeFilter *timefilter;
  69. int64_t last_time_m;
  70. int buffers;
  71. volatile int buffers_queued;
  72. void **buf_start;
  73. unsigned int *buf_len;
  74. char *standard;
  75. v4l2_std_id std_id;
  76. int channel;
  77. char *pixel_format; /**< Set by a private option. */
  78. int list_format; /**< Set by a private option. */
  79. int list_standard; /**< Set by a private option. */
  80. char *framerate; /**< Set by a private option. */
  81. int use_libv4l2;
  82. int (*open_f)(const char *file, int oflag, ...);
  83. int (*close_f)(int fd);
  84. int (*dup_f)(int fd);
  85. int (*ioctl_f)(int fd, unsigned long int request, ...);
  86. ssize_t (*read_f)(int fd, void *buffer, size_t n);
  87. void *(*mmap_f)(void *start, size_t length, int prot, int flags, int fd, int64_t offset);
  88. int (*munmap_f)(void *_start, size_t length);
  89. };
  90. struct buff_data {
  91. struct video_data *s;
  92. int index;
  93. };
  94. static int device_open(AVFormatContext *ctx)
  95. {
  96. struct video_data *s = ctx->priv_data;
  97. struct v4l2_capability cap;
  98. int fd;
  99. int ret;
  100. int flags = O_RDWR;
  101. #define SET_WRAPPERS(prefix) do { \
  102. s->open_f = prefix ## open; \
  103. s->close_f = prefix ## close; \
  104. s->dup_f = prefix ## dup; \
  105. s->ioctl_f = prefix ## ioctl; \
  106. s->read_f = prefix ## read; \
  107. s->mmap_f = prefix ## mmap; \
  108. s->munmap_f = prefix ## munmap; \
  109. } while (0)
  110. if (s->use_libv4l2) {
  111. #if CONFIG_LIBV4L2
  112. SET_WRAPPERS(v4l2_);
  113. #else
  114. av_log(ctx, AV_LOG_ERROR, "libavdevice is not build with libv4l2 support.\n");
  115. return AVERROR(EINVAL);
  116. #endif
  117. } else {
  118. SET_WRAPPERS();
  119. }
  120. #define v4l2_open s->open_f
  121. #define v4l2_close s->close_f
  122. #define v4l2_dup s->dup_f
  123. #define v4l2_ioctl s->ioctl_f
  124. #define v4l2_read s->read_f
  125. #define v4l2_mmap s->mmap_f
  126. #define v4l2_munmap s->munmap_f
  127. if (ctx->flags & AVFMT_FLAG_NONBLOCK) {
  128. flags |= O_NONBLOCK;
  129. }
  130. fd = v4l2_open(ctx->filename, flags, 0);
  131. if (fd < 0) {
  132. ret = AVERROR(errno);
  133. av_log(ctx, AV_LOG_ERROR, "Cannot open video device %s: %s\n",
  134. ctx->filename, av_err2str(ret));
  135. return ret;
  136. }
  137. if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &cap) < 0) {
  138. ret = AVERROR(errno);
  139. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYCAP): %s\n",
  140. av_err2str(ret));
  141. goto fail;
  142. }
  143. av_log(ctx, AV_LOG_VERBOSE, "fd:%d capabilities:%x\n",
  144. fd, cap.capabilities);
  145. if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) {
  146. av_log(ctx, AV_LOG_ERROR, "Not a video capture device.\n");
  147. ret = AVERROR(ENODEV);
  148. goto fail;
  149. }
  150. if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
  151. av_log(ctx, AV_LOG_ERROR,
  152. "The device does not support the streaming I/O method.\n");
  153. ret = AVERROR(ENOSYS);
  154. goto fail;
  155. }
  156. return fd;
  157. fail:
  158. v4l2_close(fd);
  159. return ret;
  160. }
  161. static int device_init(AVFormatContext *ctx, int *width, int *height,
  162. uint32_t pix_fmt)
  163. {
  164. struct video_data *s = ctx->priv_data;
  165. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  166. struct v4l2_pix_format *pix = &fmt.fmt.pix;
  167. int res = 0;
  168. pix->width = *width;
  169. pix->height = *height;
  170. pix->pixelformat = pix_fmt;
  171. pix->field = V4L2_FIELD_ANY;
  172. if (v4l2_ioctl(s->fd, VIDIOC_S_FMT, &fmt) < 0)
  173. res = AVERROR(errno);
  174. if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {
  175. av_log(ctx, AV_LOG_INFO,
  176. "The V4L2 driver changed the video from %dx%d to %dx%d\n",
  177. *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);
  178. *width = fmt.fmt.pix.width;
  179. *height = fmt.fmt.pix.height;
  180. }
  181. if (pix_fmt != fmt.fmt.pix.pixelformat) {
  182. av_log(ctx, AV_LOG_DEBUG,
  183. "The V4L2 driver changed the pixel format "
  184. "from 0x%08X to 0x%08X\n",
  185. pix_fmt, fmt.fmt.pix.pixelformat);
  186. res = AVERROR(EINVAL);
  187. }
  188. if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {
  189. av_log(ctx, AV_LOG_DEBUG,
  190. "The V4L2 driver is using the interlaced mode\n");
  191. s->interlaced = 1;
  192. }
  193. return res;
  194. }
  195. static int first_field(const struct video_data *s)
  196. {
  197. int res;
  198. v4l2_std_id std;
  199. res = v4l2_ioctl(s->fd, VIDIOC_G_STD, &std);
  200. if (res < 0)
  201. return 0;
  202. if (std & V4L2_STD_NTSC)
  203. return 0;
  204. return 1;
  205. }
  206. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  207. static void list_framesizes(AVFormatContext *ctx, uint32_t pixelformat)
  208. {
  209. const struct video_data *s = ctx->priv_data;
  210. struct v4l2_frmsizeenum vfse = { .pixel_format = pixelformat };
  211. while(!v4l2_ioctl(s->fd, VIDIOC_ENUM_FRAMESIZES, &vfse)) {
  212. switch (vfse.type) {
  213. case V4L2_FRMSIZE_TYPE_DISCRETE:
  214. av_log(ctx, AV_LOG_INFO, " %ux%u",
  215. vfse.discrete.width, vfse.discrete.height);
  216. break;
  217. case V4L2_FRMSIZE_TYPE_CONTINUOUS:
  218. case V4L2_FRMSIZE_TYPE_STEPWISE:
  219. av_log(ctx, AV_LOG_INFO, " {%u-%u, %u}x{%u-%u, %u}",
  220. vfse.stepwise.min_width,
  221. vfse.stepwise.max_width,
  222. vfse.stepwise.step_width,
  223. vfse.stepwise.min_height,
  224. vfse.stepwise.max_height,
  225. vfse.stepwise.step_height);
  226. }
  227. vfse.index++;
  228. }
  229. }
  230. #endif
  231. static void list_formats(AVFormatContext *ctx, int type)
  232. {
  233. const struct video_data *s = ctx->priv_data;
  234. struct v4l2_fmtdesc vfd = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  235. while(!v4l2_ioctl(s->fd, VIDIOC_ENUM_FMT, &vfd)) {
  236. enum AVCodecID codec_id = avpriv_fmt_v4l2codec(vfd.pixelformat);
  237. enum AVPixelFormat pix_fmt = avpriv_fmt_v4l2ff(vfd.pixelformat, codec_id);
  238. vfd.index++;
  239. if (!(vfd.flags & V4L2_FMT_FLAG_COMPRESSED) &&
  240. type & V4L_RAWFORMATS) {
  241. const char *fmt_name = av_get_pix_fmt_name(pix_fmt);
  242. av_log(ctx, AV_LOG_INFO, "Raw : %9s : %20s :",
  243. fmt_name ? fmt_name : "Unsupported",
  244. vfd.description);
  245. } else if (vfd.flags & V4L2_FMT_FLAG_COMPRESSED &&
  246. type & V4L_COMPFORMATS) {
  247. AVCodec *codec = avcodec_find_decoder(codec_id);
  248. av_log(ctx, AV_LOG_INFO, "Compressed: %9s : %20s :",
  249. codec ? codec->name : "Unsupported",
  250. vfd.description);
  251. } else {
  252. continue;
  253. }
  254. #ifdef V4L2_FMT_FLAG_EMULATED
  255. if (vfd.flags & V4L2_FMT_FLAG_EMULATED)
  256. av_log(ctx, AV_LOG_INFO, " Emulated :");
  257. #endif
  258. #if HAVE_STRUCT_V4L2_FRMIVALENUM_DISCRETE
  259. list_framesizes(ctx, vfd.pixelformat);
  260. #endif
  261. av_log(ctx, AV_LOG_INFO, "\n");
  262. }
  263. }
  264. static void list_standards(AVFormatContext *ctx)
  265. {
  266. int ret;
  267. struct video_data *s = ctx->priv_data;
  268. struct v4l2_standard standard;
  269. if (s->std_id == 0)
  270. return;
  271. for (standard.index = 0; ; standard.index++) {
  272. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  273. ret = AVERROR(errno);
  274. if (ret == AVERROR(EINVAL)) {
  275. break;
  276. } else {
  277. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  278. return;
  279. }
  280. }
  281. av_log(ctx, AV_LOG_INFO, "%2d, %16"PRIx64", %s\n",
  282. standard.index, (uint64_t)standard.id, standard.name);
  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. if (v4l2_ioctl(s->fd, VIDIOC_REQBUFS, &req) < 0) {
  295. res = AVERROR(errno);
  296. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_REQBUFS): %s\n", av_err2str(res));
  297. return res;
  298. }
  299. if (req.count < 2) {
  300. av_log(ctx, AV_LOG_ERROR, "Insufficient buffer memory\n");
  301. return AVERROR(ENOMEM);
  302. }
  303. s->buffers = req.count;
  304. s->buf_start = av_malloc_array(s->buffers, sizeof(void *));
  305. if (!s->buf_start) {
  306. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer pointers\n");
  307. return AVERROR(ENOMEM);
  308. }
  309. s->buf_len = av_malloc_array(s->buffers, sizeof(unsigned int));
  310. if (!s->buf_len) {
  311. av_log(ctx, AV_LOG_ERROR, "Cannot allocate buffer sizes\n");
  312. av_free(s->buf_start);
  313. return AVERROR(ENOMEM);
  314. }
  315. for (i = 0; i < req.count; i++) {
  316. struct v4l2_buffer buf = {
  317. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  318. .index = i,
  319. .memory = V4L2_MEMORY_MMAP
  320. };
  321. if (v4l2_ioctl(s->fd, VIDIOC_QUERYBUF, &buf) < 0) {
  322. res = AVERROR(errno);
  323. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QUERYBUF): %s\n", av_err2str(res));
  324. return res;
  325. }
  326. s->buf_len[i] = buf.length;
  327. if (s->frame_size > 0 && s->buf_len[i] < s->frame_size) {
  328. av_log(ctx, AV_LOG_ERROR,
  329. "buf_len[%d] = %d < expected frame size %d\n",
  330. i, s->buf_len[i], s->frame_size);
  331. return AVERROR(ENOMEM);
  332. }
  333. s->buf_start[i] = v4l2_mmap(NULL, buf.length,
  334. PROT_READ | PROT_WRITE, MAP_SHARED,
  335. s->fd, buf.m.offset);
  336. if (s->buf_start[i] == MAP_FAILED) {
  337. res = AVERROR(errno);
  338. av_log(ctx, AV_LOG_ERROR, "mmap: %s\n", av_err2str(res));
  339. return res;
  340. }
  341. }
  342. return 0;
  343. }
  344. #if FF_API_DESTRUCT_PACKET
  345. static void dummy_release_buffer(AVPacket *pkt)
  346. {
  347. av_assert0(0);
  348. }
  349. #endif
  350. static int enqueue_buffer(struct video_data *s, struct v4l2_buffer *buf)
  351. {
  352. int res = 0;
  353. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, buf) < 0) {
  354. res = AVERROR(errno);
  355. av_log(NULL, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  356. } else {
  357. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, 1);
  358. }
  359. return res;
  360. }
  361. static void mmap_release_buffer(void *opaque, uint8_t *data)
  362. {
  363. struct v4l2_buffer buf = { 0 };
  364. struct buff_data *buf_descriptor = opaque;
  365. struct video_data *s = buf_descriptor->s;
  366. buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  367. buf.memory = V4L2_MEMORY_MMAP;
  368. buf.index = buf_descriptor->index;
  369. av_free(buf_descriptor);
  370. enqueue_buffer(s, &buf);
  371. }
  372. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  373. static int64_t av_gettime_monotonic(void)
  374. {
  375. return av_gettime_relative();
  376. }
  377. #endif
  378. static int init_convert_timestamp(AVFormatContext *ctx, int64_t ts)
  379. {
  380. struct video_data *s = ctx->priv_data;
  381. int64_t now;
  382. now = av_gettime();
  383. if (s->ts_mode == V4L_TS_ABS &&
  384. ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE) {
  385. av_log(ctx, AV_LOG_INFO, "Detected absolute timestamps\n");
  386. s->ts_mode = V4L_TS_CONVERT_READY;
  387. return 0;
  388. }
  389. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  390. if (ctx->streams[0]->avg_frame_rate.num) {
  391. now = av_gettime_monotonic();
  392. if (s->ts_mode == V4L_TS_MONO2ABS ||
  393. (ts <= now + 1 * AV_TIME_BASE && ts >= now - 10 * AV_TIME_BASE)) {
  394. AVRational tb = {AV_TIME_BASE, 1};
  395. int64_t period = av_rescale_q(1, tb, ctx->streams[0]->avg_frame_rate);
  396. av_log(ctx, AV_LOG_INFO, "Detected monotonic timestamps, converting\n");
  397. /* microseconds instead of seconds, MHz instead of Hz */
  398. s->timefilter = ff_timefilter_new(1, period, 1.0E-6);
  399. if (!s->timefilter)
  400. return AVERROR(ENOMEM);
  401. s->ts_mode = V4L_TS_CONVERT_READY;
  402. return 0;
  403. }
  404. }
  405. #endif
  406. av_log(ctx, AV_LOG_ERROR, "Unknown timestamps\n");
  407. return AVERROR(EIO);
  408. }
  409. static int convert_timestamp(AVFormatContext *ctx, int64_t *ts)
  410. {
  411. struct video_data *s = ctx->priv_data;
  412. if (s->ts_mode) {
  413. int r = init_convert_timestamp(ctx, *ts);
  414. if (r < 0)
  415. return r;
  416. }
  417. #if HAVE_CLOCK_GETTIME && defined(CLOCK_MONOTONIC)
  418. if (s->timefilter) {
  419. int64_t nowa = av_gettime();
  420. int64_t nowm = av_gettime_monotonic();
  421. ff_timefilter_update(s->timefilter, nowa, nowm - s->last_time_m);
  422. s->last_time_m = nowm;
  423. *ts = ff_timefilter_eval(s->timefilter, *ts - nowm);
  424. }
  425. #endif
  426. return 0;
  427. }
  428. static int mmap_read_frame(AVFormatContext *ctx, AVPacket *pkt)
  429. {
  430. struct video_data *s = ctx->priv_data;
  431. struct v4l2_buffer buf = {
  432. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  433. .memory = V4L2_MEMORY_MMAP
  434. };
  435. int res;
  436. /* FIXME: Some special treatment might be needed in case of loss of signal... */
  437. while ((res = v4l2_ioctl(s->fd, VIDIOC_DQBUF, &buf)) < 0 && (errno == EINTR));
  438. if (res < 0) {
  439. if (errno == EAGAIN) {
  440. pkt->size = 0;
  441. return AVERROR(EAGAIN);
  442. }
  443. res = AVERROR(errno);
  444. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_DQBUF): %s\n", av_err2str(res));
  445. return res;
  446. }
  447. if (buf.index >= s->buffers) {
  448. av_log(ctx, AV_LOG_ERROR, "Invalid buffer index received.\n");
  449. return AVERROR(EINVAL);
  450. }
  451. avpriv_atomic_int_add_and_fetch(&s->buffers_queued, -1);
  452. // always keep at least one buffer queued
  453. av_assert0(avpriv_atomic_int_get(&s->buffers_queued) >= 1);
  454. /* CPIA is a compressed format and we don't know the exact number of bytes
  455. * used by a frame, so set it here as the driver announces it.
  456. */
  457. if (ctx->video_codec_id == AV_CODEC_ID_CPIA)
  458. s->frame_size = buf.bytesused;
  459. if (s->frame_size > 0 && buf.bytesused != s->frame_size) {
  460. av_log(ctx, AV_LOG_ERROR,
  461. "The v4l2 frame is %d bytes, but %d bytes are expected\n",
  462. buf.bytesused, s->frame_size);
  463. enqueue_buffer(s, &buf);
  464. return AVERROR_INVALIDDATA;
  465. }
  466. /* Image is at s->buff_start[buf.index] */
  467. if (avpriv_atomic_int_get(&s->buffers_queued) == FFMAX(s->buffers / 8, 1)) {
  468. /* when we start getting low on queued buffers, fall back on copying data */
  469. res = av_new_packet(pkt, buf.bytesused);
  470. if (res < 0) {
  471. av_log(ctx, AV_LOG_ERROR, "Error allocating a packet.\n");
  472. enqueue_buffer(s, &buf);
  473. return res;
  474. }
  475. memcpy(pkt->data, s->buf_start[buf.index], buf.bytesused);
  476. res = enqueue_buffer(s, &buf);
  477. if (res) {
  478. av_free_packet(pkt);
  479. return res;
  480. }
  481. } else {
  482. struct buff_data *buf_descriptor;
  483. pkt->data = s->buf_start[buf.index];
  484. pkt->size = buf.bytesused;
  485. #if FF_API_DESTRUCT_PACKET
  486. FF_DISABLE_DEPRECATION_WARNINGS
  487. pkt->destruct = dummy_release_buffer;
  488. FF_ENABLE_DEPRECATION_WARNINGS
  489. #endif
  490. buf_descriptor = av_malloc(sizeof(struct buff_data));
  491. if (!buf_descriptor) {
  492. /* Something went wrong... Since av_malloc() failed, we cannot even
  493. * allocate a buffer for memcpying into it
  494. */
  495. av_log(ctx, AV_LOG_ERROR, "Failed to allocate a buffer descriptor\n");
  496. enqueue_buffer(s, &buf);
  497. return AVERROR(ENOMEM);
  498. }
  499. buf_descriptor->index = buf.index;
  500. buf_descriptor->s = s;
  501. pkt->buf = av_buffer_create(pkt->data, pkt->size, mmap_release_buffer,
  502. buf_descriptor, 0);
  503. if (!pkt->buf) {
  504. av_log(ctx, AV_LOG_ERROR, "Failed to create a buffer\n");
  505. enqueue_buffer(s, &buf);
  506. av_freep(&buf_descriptor);
  507. return AVERROR(ENOMEM);
  508. }
  509. }
  510. pkt->pts = buf.timestamp.tv_sec * INT64_C(1000000) + buf.timestamp.tv_usec;
  511. convert_timestamp(ctx, &pkt->pts);
  512. return s->buf_len[buf.index];
  513. }
  514. static int mmap_start(AVFormatContext *ctx)
  515. {
  516. struct video_data *s = ctx->priv_data;
  517. enum v4l2_buf_type type;
  518. int i, res;
  519. for (i = 0; i < s->buffers; i++) {
  520. struct v4l2_buffer buf = {
  521. .type = V4L2_BUF_TYPE_VIDEO_CAPTURE,
  522. .index = i,
  523. .memory = V4L2_MEMORY_MMAP
  524. };
  525. if (v4l2_ioctl(s->fd, VIDIOC_QBUF, &buf) < 0) {
  526. res = AVERROR(errno);
  527. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_QBUF): %s\n", av_err2str(res));
  528. return res;
  529. }
  530. }
  531. s->buffers_queued = s->buffers;
  532. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  533. if (v4l2_ioctl(s->fd, VIDIOC_STREAMON, &type) < 0) {
  534. res = AVERROR(errno);
  535. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_STREAMON): %s\n", av_err2str(res));
  536. return res;
  537. }
  538. return 0;
  539. }
  540. static void mmap_close(struct video_data *s)
  541. {
  542. enum v4l2_buf_type type;
  543. int i;
  544. type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  545. /* We do not check for the result, because we could
  546. * not do anything about it anyway...
  547. */
  548. v4l2_ioctl(s->fd, VIDIOC_STREAMOFF, &type);
  549. for (i = 0; i < s->buffers; i++) {
  550. v4l2_munmap(s->buf_start[i], s->buf_len[i]);
  551. }
  552. av_free(s->buf_start);
  553. av_free(s->buf_len);
  554. }
  555. static int v4l2_set_parameters(AVFormatContext *ctx)
  556. {
  557. struct video_data *s = ctx->priv_data;
  558. struct v4l2_standard standard = { 0 };
  559. struct v4l2_streamparm streamparm = { 0 };
  560. struct v4l2_fract *tpf;
  561. AVRational framerate_q = { 0 };
  562. int i, ret;
  563. if (s->framerate &&
  564. (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {
  565. av_log(ctx, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",
  566. s->framerate);
  567. return ret;
  568. }
  569. if (s->standard) {
  570. if (s->std_id) {
  571. ret = 0;
  572. av_log(ctx, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);
  573. /* set tv standard */
  574. for (i = 0; ; i++) {
  575. standard.index = i;
  576. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  577. ret = AVERROR(errno);
  578. break;
  579. }
  580. if (!av_strcasecmp(standard.name, s->standard))
  581. break;
  582. }
  583. if (ret < 0) {
  584. av_log(ctx, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);
  585. return ret;
  586. }
  587. if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {
  588. ret = AVERROR(errno);
  589. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));
  590. return ret;
  591. }
  592. } else {
  593. av_log(ctx, AV_LOG_WARNING,
  594. "This device does not support any standard\n");
  595. }
  596. }
  597. /* get standard */
  598. if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {
  599. tpf = &standard.frameperiod;
  600. for (i = 0; ; i++) {
  601. standard.index = i;
  602. if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {
  603. ret = AVERROR(errno);
  604. if (ret == AVERROR(EINVAL)
  605. #ifdef ENODATA
  606. || ret == AVERROR(ENODATA)
  607. #endif
  608. ) {
  609. tpf = &streamparm.parm.capture.timeperframe;
  610. break;
  611. }
  612. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));
  613. return ret;
  614. }
  615. if (standard.id == s->std_id) {
  616. av_log(ctx, AV_LOG_DEBUG,
  617. "Current standard: %s, id: %"PRIx64", frameperiod: %d/%d\n",
  618. standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);
  619. break;
  620. }
  621. }
  622. } else {
  623. tpf = &streamparm.parm.capture.timeperframe;
  624. }
  625. streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  626. if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {
  627. ret = AVERROR(errno);
  628. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));
  629. return ret;
  630. }
  631. if (framerate_q.num && framerate_q.den) {
  632. if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {
  633. tpf = &streamparm.parm.capture.timeperframe;
  634. av_log(ctx, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",
  635. framerate_q.den, framerate_q.num);
  636. tpf->numerator = framerate_q.den;
  637. tpf->denominator = framerate_q.num;
  638. if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {
  639. ret = AVERROR(errno);
  640. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));
  641. return ret;
  642. }
  643. if (framerate_q.num != tpf->denominator ||
  644. framerate_q.den != tpf->numerator) {
  645. av_log(ctx, AV_LOG_INFO,
  646. "The driver changed the time per frame from "
  647. "%d/%d to %d/%d\n",
  648. framerate_q.den, framerate_q.num,
  649. tpf->numerator, tpf->denominator);
  650. }
  651. } else {
  652. av_log(ctx, AV_LOG_WARNING,
  653. "The driver does not allow to change time per frame\n");
  654. }
  655. }
  656. if (tpf->denominator > 0 && tpf->numerator > 0) {
  657. ctx->streams[0]->avg_frame_rate.num = tpf->denominator;
  658. ctx->streams[0]->avg_frame_rate.den = tpf->numerator;
  659. ctx->streams[0]->r_frame_rate = ctx->streams[0]->avg_frame_rate;
  660. } else
  661. av_log(ctx, AV_LOG_WARNING, "Time per frame unknown\n");
  662. return 0;
  663. }
  664. static int device_try_init(AVFormatContext *ctx,
  665. enum AVPixelFormat pix_fmt,
  666. int *width,
  667. int *height,
  668. uint32_t *desired_format,
  669. enum AVCodecID *codec_id)
  670. {
  671. int ret, i;
  672. *desired_format = avpriv_fmt_ff2v4l(pix_fmt, ctx->video_codec_id);
  673. if (*desired_format) {
  674. ret = device_init(ctx, width, height, *desired_format);
  675. if (ret < 0) {
  676. *desired_format = 0;
  677. if (ret != AVERROR(EINVAL))
  678. return ret;
  679. }
  680. }
  681. if (!*desired_format) {
  682. for (i = 0; avpriv_fmt_conversion_table[i].codec_id != AV_CODEC_ID_NONE; i++) {
  683. if (ctx->video_codec_id == AV_CODEC_ID_NONE ||
  684. avpriv_fmt_conversion_table[i].codec_id == ctx->video_codec_id) {
  685. av_log(ctx, AV_LOG_DEBUG, "Trying to set codec:%s pix_fmt:%s\n",
  686. avcodec_get_name(avpriv_fmt_conversion_table[i].codec_id),
  687. (char *)av_x_if_null(av_get_pix_fmt_name(avpriv_fmt_conversion_table[i].ff_fmt), "none"));
  688. *desired_format = avpriv_fmt_conversion_table[i].v4l2_fmt;
  689. ret = device_init(ctx, width, height, *desired_format);
  690. if (ret >= 0)
  691. break;
  692. else if (ret != AVERROR(EINVAL))
  693. return ret;
  694. *desired_format = 0;
  695. }
  696. }
  697. if (*desired_format == 0) {
  698. av_log(ctx, AV_LOG_ERROR, "Cannot find a proper format for "
  699. "codec '%s' (id %d), pixel format '%s' (id %d)\n",
  700. avcodec_get_name(ctx->video_codec_id), ctx->video_codec_id,
  701. (char *)av_x_if_null(av_get_pix_fmt_name(pix_fmt), "none"), pix_fmt);
  702. ret = AVERROR(EINVAL);
  703. }
  704. }
  705. *codec_id = avpriv_fmt_v4l2codec(*desired_format);
  706. av_assert0(*codec_id != AV_CODEC_ID_NONE);
  707. return ret;
  708. }
  709. static int v4l2_read_header(AVFormatContext *ctx)
  710. {
  711. struct video_data *s = ctx->priv_data;
  712. AVStream *st;
  713. int res = 0;
  714. uint32_t desired_format;
  715. enum AVCodecID codec_id = AV_CODEC_ID_NONE;
  716. enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;
  717. struct v4l2_input input = { 0 };
  718. st = avformat_new_stream(ctx, NULL);
  719. if (!st)
  720. return AVERROR(ENOMEM);
  721. #if CONFIG_LIBV4L2
  722. /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL
  723. and errors will get sent to stderr */
  724. if (s->use_libv4l2)
  725. v4l2_log_file = fopen("/dev/null", "w");
  726. #endif
  727. s->fd = device_open(ctx);
  728. if (s->fd < 0)
  729. return s->fd;
  730. if (s->channel != -1) {
  731. /* set video input */
  732. av_log(ctx, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);
  733. if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {
  734. res = AVERROR(errno);
  735. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));
  736. goto fail;
  737. }
  738. } else {
  739. /* get current video input */
  740. if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {
  741. res = AVERROR(errno);
  742. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));
  743. goto fail;
  744. }
  745. }
  746. /* enum input */
  747. input.index = s->channel;
  748. if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {
  749. res = AVERROR(errno);
  750. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));
  751. goto fail;
  752. }
  753. s->std_id = input.std;
  754. av_log(ctx, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s, input_std: %"PRIx64"\n",
  755. s->channel, input.name, (uint64_t)input.std);
  756. if (s->list_format) {
  757. list_formats(ctx, s->list_format);
  758. res = AVERROR_EXIT;
  759. goto fail;
  760. }
  761. if (s->list_standard) {
  762. list_standards(ctx);
  763. res = AVERROR_EXIT;
  764. goto fail;
  765. }
  766. avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */
  767. if (s->pixel_format) {
  768. AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);
  769. if (codec)
  770. ctx->video_codec_id = codec->id;
  771. pix_fmt = av_get_pix_fmt(s->pixel_format);
  772. if (pix_fmt == AV_PIX_FMT_NONE && !codec) {
  773. av_log(ctx, AV_LOG_ERROR, "No such input format: %s.\n",
  774. s->pixel_format);
  775. res = AVERROR(EINVAL);
  776. goto fail;
  777. }
  778. }
  779. if (!s->width && !s->height) {
  780. struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };
  781. av_log(ctx, AV_LOG_VERBOSE,
  782. "Querying the device for the current frame size\n");
  783. if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {
  784. res = AVERROR(errno);
  785. av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));
  786. goto fail;
  787. }
  788. s->width = fmt.fmt.pix.width;
  789. s->height = fmt.fmt.pix.height;
  790. av_log(ctx, AV_LOG_VERBOSE,
  791. "Setting frame size to %dx%d\n", s->width, s->height);
  792. }
  793. res = device_try_init(ctx, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);
  794. if (res < 0)
  795. goto fail;
  796. /* If no pixel_format was specified, the codec_id was not known up
  797. * until now. Set video_codec_id in the context, as codec_id will
  798. * not be available outside this function
  799. */
  800. if (codec_id != AV_CODEC_ID_NONE && ctx->video_codec_id == AV_CODEC_ID_NONE)
  801. ctx->video_codec_id = codec_id;
  802. if ((res = av_image_check_size(s->width, s->height, 0, ctx)) < 0)
  803. goto fail;
  804. s->frame_format = desired_format;
  805. if ((res = v4l2_set_parameters(ctx)) < 0)
  806. goto fail;
  807. st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);
  808. s->frame_size =
  809. avpicture_get_size(st->codec->pix_fmt, s->width, s->height);
  810. if ((res = mmap_init(ctx)) ||
  811. (res = mmap_start(ctx)) < 0)
  812. goto fail;
  813. s->top_field_first = first_field(s);
  814. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  815. st->codec->codec_id = codec_id;
  816. if (codec_id == AV_CODEC_ID_RAWVIDEO)
  817. st->codec->codec_tag =
  818. avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);
  819. else if (codec_id == AV_CODEC_ID_H264) {
  820. st->need_parsing = AVSTREAM_PARSE_HEADERS;
  821. }
  822. if (desired_format == V4L2_PIX_FMT_YVU420)
  823. st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');
  824. else if (desired_format == V4L2_PIX_FMT_YVU410)
  825. st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');
  826. st->codec->width = s->width;
  827. st->codec->height = s->height;
  828. if (st->avg_frame_rate.den)
  829. st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;
  830. return 0;
  831. fail:
  832. v4l2_close(s->fd);
  833. return res;
  834. }
  835. static int v4l2_read_packet(AVFormatContext *ctx, AVPacket *pkt)
  836. {
  837. struct video_data *s = ctx->priv_data;
  838. AVFrame *frame = ctx->streams[0]->codec->coded_frame;
  839. int res;
  840. av_init_packet(pkt);
  841. if ((res = mmap_read_frame(ctx, pkt)) < 0) {
  842. return res;
  843. }
  844. if (frame && s->interlaced) {
  845. frame->interlaced_frame = 1;
  846. frame->top_field_first = s->top_field_first;
  847. }
  848. return pkt->size;
  849. }
  850. static int v4l2_read_close(AVFormatContext *ctx)
  851. {
  852. struct video_data *s = ctx->priv_data;
  853. if (avpriv_atomic_int_get(&s->buffers_queued) != s->buffers)
  854. av_log(ctx, AV_LOG_WARNING, "Some buffers are still owned by the caller on "
  855. "close.\n");
  856. mmap_close(s);
  857. v4l2_close(s->fd);
  858. return 0;
  859. }
  860. #define OFFSET(x) offsetof(struct video_data, x)
  861. #define DEC AV_OPT_FLAG_DECODING_PARAM
  862. static const AVOption options[] = {
  863. { "standard", "set TV standard, used only by analog frame grabber", OFFSET(standard), AV_OPT_TYPE_STRING, {.str = NULL }, 0, 0, DEC },
  864. { "channel", "set TV channel, used only by frame grabber", OFFSET(channel), AV_OPT_TYPE_INT, {.i64 = -1 }, -1, INT_MAX, DEC },
  865. { "video_size", "set frame size", OFFSET(width), AV_OPT_TYPE_IMAGE_SIZE, {.str = NULL}, 0, 0, DEC },
  866. { "pixel_format", "set preferred pixel format", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  867. { "input_format", "set preferred pixel format (for raw video) or codec name", OFFSET(pixel_format), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  868. { "framerate", "set frame rate", OFFSET(framerate), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC },
  869. { "list_formats", "list available formats and exit", OFFSET(list_format), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, INT_MAX, DEC, "list_formats" },
  870. { "all", "show all available formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_ALLFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  871. { "raw", "show only non-compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_RAWFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  872. { "compressed", "show only compressed formats", OFFSET(list_format), AV_OPT_TYPE_CONST, {.i64 = V4L_COMPFORMATS }, 0, INT_MAX, DEC, "list_formats" },
  873. { "list_standards", "list supported standards and exit", OFFSET(list_standard), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 1, DEC, "list_standards" },
  874. { "all", "show all supported standards", OFFSET(list_standard), AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, DEC, "list_standards" },
  875. { "timestamps", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  876. { "ts", "set type of timestamps for grabbed frames", OFFSET(ts_mode), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 2, DEC, "timestamps" },
  877. { "default", "use timestamps from the kernel", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_DEFAULT }, 0, 2, DEC, "timestamps" },
  878. { "abs", "use absolute timestamps (wall clock)", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_ABS }, 0, 2, DEC, "timestamps" },
  879. { "mono2abs", "force conversion from monotonic to absolute timestamps", OFFSET(ts_mode), AV_OPT_TYPE_CONST, {.i64 = V4L_TS_MONO2ABS }, 0, 2, DEC, "timestamps" },
  880. { "use_libv4l2", "use libv4l2 (v4l-utils) conversion functions", OFFSET(use_libv4l2), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, DEC },
  881. { NULL },
  882. };
  883. static const AVClass v4l2_class = {
  884. .class_name = "V4L2 indev",
  885. .item_name = av_default_item_name,
  886. .option = options,
  887. .version = LIBAVUTIL_VERSION_INT,
  888. .category = AV_CLASS_CATEGORY_DEVICE_VIDEO_INPUT,
  889. };
  890. AVInputFormat ff_v4l2_demuxer = {
  891. .name = "video4linux2,v4l2",
  892. .long_name = NULL_IF_CONFIG_SMALL("Video4Linux2 device grab"),
  893. .priv_data_size = sizeof(struct video_data),
  894. .read_header = v4l2_read_header,
  895. .read_packet = v4l2_read_packet,
  896. .read_close = v4l2_read_close,
  897. .flags = AVFMT_NOFILE,
  898. .priv_class = &v4l2_class,
  899. };