From f2ff2bfef299e3ebddeb4962aef50d3c3012edb6 Mon Sep 17 00:00:00 2001 From: Laurent Pinchart Date: Wed, 19 May 2010 11:59:00 +0200 Subject: Initial import Signed-off-by: Laurent Pinchart --- COPYING.GPL | 339 ++++++++++++++++++ Makefile | 18 + yavta.c | 1138 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 1495 insertions(+) create mode 100644 COPYING.GPL create mode 100644 Makefile create mode 100644 yavta.c diff --git a/COPYING.GPL b/COPYING.GPL new file mode 100644 index 0000000..d511905 --- /dev/null +++ b/COPYING.GPL @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5c9cc68 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ +CROSS_COMPILE ?= + +CC := $(CROSS_COMPILE)gcc +CFLAGS := -O2 -W -Wall +LDFLAGS := + +%.o : %.c + $(CC) $(CFLAGS) -c -o $@ $< + +all: yavta + +yavta: yavta.o + $(CC) $(LDFLAGS) -o $@ $^ + +clean: + -rm -f *.o + -rm -f yavta + diff --git a/yavta.c b/yavta.c new file mode 100644 index 0000000..4c0d97b --- /dev/null +++ b/yavta.c @@ -0,0 +1,1138 @@ +/* + * yavta -- Yet Another V4L2 Test Application + * + * Copyright (C) 2005-2010 Laurent Pinchart + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#define ARRAY_SIZE(a) (sizeof(a)/sizeof((a)[0])) + +struct device +{ + int fd; + + enum v4l2_buf_type type; + enum v4l2_memory memtype; + unsigned int nbufs; + unsigned int bufsize; + void **mem; +}; + +static const char *v4l2_buf_type_name(enum v4l2_buf_type type) +{ + static struct { + enum v4l2_buf_type type; + const char *name; + } names[] = { + { V4L2_BUF_TYPE_VIDEO_CAPTURE, "Video capture" }, + { V4L2_BUF_TYPE_VIDEO_OUTPUT, "Video output" }, + { V4L2_BUF_TYPE_VIDEO_OVERLAY, "Video overlay" }, + }; + + unsigned int i; + + for (i = 0; i < ARRAY_SIZE(names); ++i) { + if (names[i].type == type) + return names[i].name; + } + + if (type & V4L2_BUF_TYPE_PRIVATE) + return "Private"; + else + return "Unknown"; +} + +static const char *v4l2_fourcc_name(unsigned int fourcc) +{ + static char name[5]; + unsigned int i; + + for (i = 0; i < 4; ++i) { + name[i] = fourcc & 0xff; + fourcc >>= 8; + } + + name[4] = '\0'; + return name; +} + +static int video_open(struct device *dev, const char *devname, int no_query) +{ + struct v4l2_capability cap; + int ret; + + memset(dev, 0, sizeof *dev); + dev->fd = -1; + dev->memtype = V4L2_MEMORY_MMAP; + dev->mem = NULL; + + dev->fd = open(devname, O_RDWR); + if (dev->fd < 0) { + printf("Error opening device %s: %d.\n", devname, errno); + return dev->fd; + } + + if (!no_query) { + memset(&cap, 0, sizeof cap); + ret = ioctl(dev->fd, VIDIOC_QUERYCAP, &cap); + if (ret < 0) { + printf("Error opening device %s: unable to query " + "device.\n", devname); + close(dev->fd); + return ret; + } + + if (cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) + dev->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + else if (cap.capabilities & V4L2_CAP_VIDEO_OUTPUT) + dev->type = V4L2_BUF_TYPE_VIDEO_OUTPUT; + else { + printf("Error opening device %s: neither video capture " + "nor video output supported.\n", devname); + close(dev->fd); + return -EINVAL; + } + + printf("Device %s opened: %s.\n", devname, cap.card); + } else { + dev->type = V4L2_BUF_TYPE_VIDEO_CAPTURE; + printf("Device %s opened.\n", devname); + } + + return 0; +} + +static void video_close(struct device *dev) +{ + free(dev->mem); + close(dev->fd); +} + +static void uvc_get_control(struct device *dev, unsigned int id) +{ + struct v4l2_control ctrl; + int ret; + + ctrl.id = id; + + ret = ioctl(dev->fd, VIDIOC_G_CTRL, &ctrl); + if (ret < 0) { + printf("unable to get control: %s (%d).\n", + strerror(errno), errno); + return; + } + + printf("Control 0x%08x value %u\n", id, ctrl.value); +} + +static void uvc_set_control(struct device *dev, unsigned int id, int value) +{ + struct v4l2_control ctrl; + int ret; + + ctrl.id = id; + ctrl.value = value; + + ret = ioctl(dev->fd, VIDIOC_S_CTRL, &ctrl); + if (ret < 0) { + printf("unable to set control: %s (%d).\n", + strerror(errno), errno); + return; + } + + printf("Control 0x%08x set to %u, is %u\n", id, value, + ctrl.value); +} + +static int video_get_format(struct device *dev) +{ + struct v4l2_format fmt; + int ret; + + memset(&fmt, 0, sizeof fmt); + fmt.type = dev->type; + + ret = ioctl(dev->fd, VIDIOC_G_FMT, &fmt); + if (ret < 0) { + printf("Unable to get format: %s (%d).\n", strerror(errno), + errno); + return ret; + } + + printf("Video format: %c%c%c%c (%08x) %ux%u\n", + (fmt.fmt.pix.pixelformat >> 0) & 0xff, + (fmt.fmt.pix.pixelformat >> 8) & 0xff, + (fmt.fmt.pix.pixelformat >> 16) & 0xff, + (fmt.fmt.pix.pixelformat >> 24) & 0xff, + fmt.fmt.pix.pixelformat, + fmt.fmt.pix.width, fmt.fmt.pix.height); + return 0; +} + +static int video_set_format(struct device *dev, unsigned int w, unsigned int h, unsigned int format) +{ + struct v4l2_format fmt; + int ret; + + memset(&fmt, 0, sizeof fmt); + fmt.type = dev->type; + fmt.fmt.pix.width = w; + fmt.fmt.pix.height = h; + fmt.fmt.pix.pixelformat = format; + fmt.fmt.pix.field = V4L2_FIELD_ANY; + + ret = ioctl(dev->fd, VIDIOC_S_FMT, &fmt); + if (ret < 0) { + printf("Unable to set format: %s (%d).\n", strerror(errno), + errno); + return ret; + } + + printf("Video format set: width: %u height: %u buffer size: %u\n", + fmt.fmt.pix.width, fmt.fmt.pix.height, fmt.fmt.pix.sizeimage); + return 0; +} + +static int video_set_framerate(struct device *dev, struct v4l2_fract *time_per_frame) +{ + struct v4l2_streamparm parm; + int ret; + + memset(&parm, 0, sizeof parm); + parm.type = dev->type; + + ret = ioctl(dev->fd, VIDIOC_G_PARM, &parm); + if (ret < 0) { + printf("Unable to get frame rate: %d.\n", errno); + return ret; + } + + printf("Current frame rate: %u/%u\n", + parm.parm.capture.timeperframe.numerator, + parm.parm.capture.timeperframe.denominator); + + printf("Setting frame rate to: %u/%u\n", + time_per_frame->numerator, + time_per_frame->denominator); + + parm.parm.capture.timeperframe.numerator = time_per_frame->numerator; + parm.parm.capture.timeperframe.denominator = time_per_frame->denominator; + + ret = ioctl(dev->fd, VIDIOC_S_PARM, &parm); + if (ret < 0) { + printf("Unable to set frame rate: %d.\n", errno); + return ret; + } + + ret = ioctl(dev->fd, VIDIOC_G_PARM, &parm); + if (ret < 0) { + printf("Unable to get frame rate: %d.\n", errno); + return ret; + } + + printf("Frame rate set: %u/%u\n", + parm.parm.capture.timeperframe.numerator, + parm.parm.capture.timeperframe.denominator); + return 0; +} + +static int video_alloc_buffers(struct device *dev, int nbufs) +{ + struct v4l2_requestbuffers rb; + struct v4l2_buffer buf; + void **bufmem; + unsigned int i; + int ret; + + memset(&rb, 0, sizeof rb); + rb.count = nbufs; + rb.type = dev->type; + rb.memory = dev->memtype; + + ret = ioctl(dev->fd, VIDIOC_REQBUFS, &rb); + if (ret < 0) { + printf("Unable to request buffers: %d.\n", errno); + return ret; + } + + printf("%u buffers requested.\n", rb.count); + + bufmem = malloc(rb.count * sizeof bufmem[0]); + if (bufmem == NULL) + return -ENOMEM; + + /* Map the buffers. */ + for (i = 0; i < rb.count; ++i) { + memset(&buf, 0, sizeof buf); + buf.index = i; + buf.type = dev->type; + buf.memory = dev->memtype; + ret = ioctl(dev->fd, VIDIOC_QUERYBUF, &buf); + if (ret < 0) { + printf("Unable to query buffer %u (%d).\n", i, errno); + return ret; + } + printf("length: %u offset: %u\n", buf.length, buf.m.offset); + + switch (dev->memtype) { + case V4L2_MEMORY_MMAP: + bufmem[i] = mmap(0, buf.length, PROT_READ | PROT_WRITE, MAP_SHARED, dev->fd, buf.m.offset); + if (bufmem[i] == MAP_FAILED) { + printf("Unable to map buffer %u (%d)\n", i, errno); + return ret; + } + printf("Buffer %u mapped at address %p.\n", i, bufmem[i]); + break; + + case V4L2_MEMORY_USERPTR: + bufmem[i] = malloc(buf.length); + if (bufmem[i] == NULL) { + printf("Unable to allocate buffer %u (%d)\n", i, errno); + return -ENOMEM; + } + printf("Buffer %u allocated at address %p.\n", i, bufmem[i]); + break; + + default: + break; + } + } + + dev->mem = bufmem; + dev->nbufs = rb.count; + dev->bufsize = buf.length; + return 0; +} + +static int video_free_buffers(struct device *dev) +{ + struct v4l2_requestbuffers rb; + unsigned int i; + int ret; + + if (dev->nbufs == 0) + return 0; + + if (dev->memtype == V4L2_MEMORY_MMAP) { + for (i = 0; i < dev->nbufs; ++i) { + ret = munmap(dev->mem[i], dev->bufsize); + if (ret < 0) { + printf("Unable to unmap buffer %u (%d)\n", i, errno); + return ret; + } + } + } + + memset(&rb, 0, sizeof rb); + rb.count = 0; + rb.type = dev->type; + rb.memory = dev->memtype; + + ret = ioctl(dev->fd, VIDIOC_REQBUFS, &rb); + if (ret < 0) { + printf("Unable to release buffers: %d.\n", errno); + return ret; + } + + printf("%u buffers released.\n", dev->nbufs); + + free(dev->mem); + dev->nbufs = 0; + dev->mem = NULL; + + return 0; +} + +static int video_queue_buffer(struct device *dev, int index) +{ + struct v4l2_buffer buf; + int ret; + + memset(&buf, 0, sizeof buf); + buf.index = index; + buf.type = dev->type; + buf.memory = dev->memtype; + if (dev->memtype == V4L2_MEMORY_USERPTR) + buf.m.userptr = (unsigned long)dev->mem[index]; + + if (dev->type == V4L2_BUF_TYPE_VIDEO_OUTPUT) { + buf.bytesused = buf.length; + memset(dev->mem[buf.index], 0, buf.bytesused); + } + + ret = ioctl(dev->fd, VIDIOC_QBUF, &buf); + if (ret < 0) + printf("Unable to queue buffer (%d).\n", errno); + + return ret; +} + +static int video_enable(struct device *dev, int enable) +{ + int type = dev->type; + int ret; + + ret = ioctl(dev->fd, enable ? VIDIOC_STREAMON : VIDIOC_STREAMOFF, &type); + if (ret < 0) { + printf("Unable to %s streaming: %d.\n", enable ? "start" : "stop", + errno); + return ret; + } + + return 0; +} + +static void video_query_menu(struct device *dev, unsigned int id) +{ + struct v4l2_querymenu menu; + int ret; + + menu.index = 0; + while (1) { + menu.id = id; + ret = ioctl(dev->fd, VIDIOC_QUERYMENU, &menu); + if (ret < 0) + break; + + printf(" %u: %.32s\n", menu.index, menu.name); + menu.index++; + }; +} + +static void video_list_controls(struct device *dev) +{ + struct v4l2_queryctrl query; + struct v4l2_control ctrl; + unsigned int nctrls = 0; + char value[12]; + int ret; + +#ifndef V4L2_CTRL_FLAG_NEXT_CTRL + unsigned int i; + + for (i = V4L2_CID_BASE; i <= V4L2_CID_LASTP1; ++i) { + query.id = i; +#else + query.id = 0; + while (1) { + query.id |= V4L2_CTRL_FLAG_NEXT_CTRL; +#endif + ret = ioctl(dev->fd, VIDIOC_QUERYCTRL, &query); + if (ret < 0) + break; + + if (query.flags & V4L2_CTRL_FLAG_DISABLED) + continue; + + ctrl.id = query.id; + ret = ioctl(dev->fd, VIDIOC_G_CTRL, &ctrl); + if (ret < 0) + strcpy(value, "n/a"); + else + sprintf(value, "%d", ctrl.value); + + printf("control 0x%08x %s min %d max %d step %d default %d current %s.\n", + query.id, query.name, query.minimum, query.maximum, + query.step, query.default_value, value); + + if (query.type == V4L2_CTRL_TYPE_MENU) + video_query_menu(dev, query.id); + + nctrls++; + } + + if (nctrls) + printf("%u control%s found.\n", nctrls, nctrls > 1 ? "s" : ""); + else + printf("No control found.\n"); +} + +static void video_enum_frame_intervals(struct device *dev, __u32 pixelformat, + unsigned int width, unsigned int height) +{ + struct v4l2_frmivalenum ival; + unsigned int i; + int ret; + + for (i = 0; ; ++i) { + memset(&ival, 0, sizeof ival); + ival.index = i; + ival.pixel_format = pixelformat; + ival.width = width; + ival.height = height; + ret = ioctl(dev->fd, VIDIOC_ENUM_FRAMEINTERVALS, &ival); + if (ret < 0) + break; + + if (i != ival.index) + printf("Warning: driver returned wrong ival index " + "%u.\n", ival.index); + if (pixelformat != ival.pixel_format) + printf("Warning: driver returned wrong ival pixel " + "format %08x.\n", ival.pixel_format); + if (width != ival.width) + printf("Warning: driver returned wrong ival width " + "%u.\n", ival.width); + if (height != ival.height) + printf("Warning: driver returned wrong ival height " + "%u.\n", ival.height); + + if (i != 0) + printf(", "); + + switch (ival.type) { + case V4L2_FRMIVAL_TYPE_DISCRETE: + printf("%u/%u", + ival.discrete.numerator, + ival.discrete.denominator); + break; + + case V4L2_FRMIVAL_TYPE_CONTINUOUS: + printf("%u/%u - %u/%u", + ival.stepwise.min.numerator, + ival.stepwise.min.denominator, + ival.stepwise.max.numerator, + ival.stepwise.max.denominator); + return; + + case V4L2_FRMIVAL_TYPE_STEPWISE: + printf("%u/%u - %u/%u (by %u/%u)", + ival.stepwise.min.numerator, + ival.stepwise.min.denominator, + ival.stepwise.max.numerator, + ival.stepwise.max.denominator, + ival.stepwise.step.numerator, + ival.stepwise.step.denominator); + return; + + default: + break; + } + } +} + +static void video_enum_frame_sizes(struct device *dev, __u32 pixelformat) +{ + struct v4l2_frmsizeenum frame; + unsigned int i; + int ret; + + for (i = 0; ; ++i) { + memset(&frame, 0, sizeof frame); + frame.index = i; + frame.pixel_format = pixelformat; + ret = ioctl(dev->fd, VIDIOC_ENUM_FRAMESIZES, &frame); + if (ret < 0) + break; + + if (i != frame.index) + printf("Warning: driver returned wrong frame index " + "%u.\n", frame.index); + if (pixelformat != frame.pixel_format) + printf("Warning: driver returned wrong frame pixel " + "format %08x.\n", frame.pixel_format); + + switch (frame.type) { + case V4L2_FRMSIZE_TYPE_DISCRETE: + printf("\tFrame size: %ux%u (", frame.discrete.width, + frame.discrete.height); + video_enum_frame_intervals(dev, frame.pixel_format, + frame.discrete.width, frame.discrete.height); + printf(")\n"); + break; + + case V4L2_FRMSIZE_TYPE_CONTINUOUS: + printf("\tFrame size: %ux%u - %ux%u (", + frame.stepwise.min_width, + frame.stepwise.min_height, + frame.stepwise.max_width, + frame.stepwise.max_height); + video_enum_frame_intervals(dev, frame.pixel_format, + frame.stepwise.max_width, + frame.stepwise.max_height); + printf(")\n"); + break; + + case V4L2_FRMSIZE_TYPE_STEPWISE: + printf("\tFrame size: %ux%u - %ux%u (by %ux%u) (\n", + frame.stepwise.min_width, + frame.stepwise.min_height, + frame.stepwise.max_width, + frame.stepwise.max_height, + frame.stepwise.step_width, + frame.stepwise.step_height); + video_enum_frame_intervals(dev, frame.pixel_format, + frame.stepwise.max_width, + frame.stepwise.max_height); + printf(")\n"); + break; + + default: + break; + } + } +} +static void video_enum_formats(struct device *dev, enum v4l2_buf_type type) +{ + struct v4l2_fmtdesc fmt; + unsigned int i; + int ret; + + for (i = 0; ; ++i) { + memset(&fmt, 0, sizeof fmt); + fmt.index = i; + fmt.type = type; + ret = ioctl(dev->fd, VIDIOC_ENUM_FMT, &fmt); + if (ret < 0) + break; + + if (i != fmt.index) + printf("Warning: driver returned wrong format index " + "%u.\n", fmt.index); + if (type != fmt.type) + printf("Warning: driver returned wrong format type " + "%u.\n", fmt.type); + + printf("\tFormat %u: %s (%08x)\n", i, + v4l2_fourcc_name(fmt.pixelformat), fmt.pixelformat); + printf("\tType: %s (%u)\n", v4l2_buf_type_name(fmt.type), + fmt.type); + printf("\tName: %.32s\n", fmt.description); + video_enum_frame_sizes(dev, fmt.pixelformat); + printf("\n"); + } +} + +static void video_enum_inputs(struct device *dev) +{ + struct v4l2_input input; + unsigned int i; + int ret; + + for (i = 0; ; ++i) { + memset(&input, 0, sizeof input); + input.index = i; + ret = ioctl(dev->fd, VIDIOC_ENUMINPUT, &input); + if (ret < 0) + break; + + if (i != input.index) + printf("Warning: driver returned wrong input index " + "%u.\n", input.index); + + printf("\tInput %u: %s.\n", i, input.name); + } + + printf("\n"); +} + +static int video_get_input(struct device *dev) +{ + __u32 input; + int ret; + + ret = ioctl(dev->fd, VIDIOC_G_INPUT, &input); + if (ret < 0) { + printf("Unable to get current input: %s.\n", strerror(errno)); + return ret; + } + + return input; +} + +static int video_set_input(struct device *dev, unsigned int input) +{ + __u32 _input = input; + int ret; + + ret = ioctl(dev->fd, VIDIOC_S_INPUT, &_input); + if (ret < 0) + printf("Unable to select input %u: %s.\n", input, + strerror(errno)); + + return ret; +} + +static int video_set_quality(struct device *dev, unsigned int quality) +{ + struct v4l2_jpegcompression jpeg; + int ret; + + if (quality == (unsigned int)-1) + return 0; + + memset(&jpeg, 0, sizeof jpeg); + jpeg.quality = quality; + + ret = ioctl(dev->fd, VIDIOC_S_JPEGCOMP, &jpeg); + if (ret < 0) { + printf("Unable to set quality to %u: %s.\n", quality, + strerror(errno)); + return ret; + } + + ret = ioctl(dev->fd, VIDIOC_G_JPEGCOMP, &jpeg); + if (ret >= 0) + printf("Quality set to %u\n", jpeg.quality); + + return 0; +} + +static int video_prepare_capture(struct device *dev, int nbufs) +{ + unsigned int i; + int ret; + + /* Allocate and map buffers. */ + if ((ret = video_alloc_buffers(dev, nbufs)) < 0) + return ret; + + /* Queue the buffers. */ + for (i = 0; i < dev->nbufs; ++i) { + ret = video_queue_buffer(dev, i); + if (ret < 0) + return ret; + } + + return 0; +} + +static int video_do_capture(struct device *dev, unsigned int nframes, + unsigned int skip, unsigned int delay, const char *filename_prefix) +{ + char *filename; + struct timeval start, end, ts; + struct v4l2_buffer buf; + unsigned int size; + unsigned int i; + FILE *file; + double bps; + double fps; + int ret; + + if (filename_prefix != NULL) { + filename = malloc(strlen(filename_prefix) + 12); + if (filename == NULL) + return -ENOMEM; + } + + /* Start streaming. */ + video_enable(dev, 1); + + size = 0; + + for (i = 0; i < nframes; ++i) { + /* Dequeue a buffer. */ + memset(&buf, 0, sizeof buf); + buf.type = dev->type; + buf.memory = dev->memtype; + ret = ioctl(dev->fd, VIDIOC_DQBUF, &buf); + if (ret < 0) { + if (errno != EIO) { + printf("Unable to dequeue buffer (%d).\n", errno); + goto done; + } + buf.type = dev->type; + buf.memory = dev->memtype; + if (dev->memtype == V4L2_MEMORY_USERPTR) + buf.m.userptr = (unsigned long)dev->mem[i]; + } + + size += buf.bytesused; + + gettimeofday(&ts, NULL); + printf("%u (%u) %u bytes %ld.%06ld %ld.%06ld\n", i, buf.index, + buf.bytesused, buf.timestamp.tv_sec, + buf.timestamp.tv_usec, ts.tv_sec, ts.tv_usec); + + if (i == 0) + start = ts; + + /* Save the image. */ + if (dev->type == V4L2_BUF_TYPE_VIDEO_CAPTURE && filename_prefix && !skip) { + sprintf(filename, "%s-%06u.bin", filename_prefix, i); + file = fopen(filename, "wb"); + if (file != NULL) { + ret = fwrite(dev->mem[buf.index], buf.bytesused, 1, file); + fclose(file); + } + } + if (skip) + --skip; + + /* Requeue the buffer. */ + if (delay > 0) + usleep(delay * 1000); + + ret = video_queue_buffer(dev, buf.index); + if (ret < 0) { + printf("Unable to requeue buffer (%d).\n", errno); + goto done; + } + + fflush(stdout); + } + gettimeofday(&end, NULL); + + /* Stop streaming. */ + video_enable(dev, 0); + + end.tv_sec -= start.tv_sec; + end.tv_usec -= start.tv_usec; + if (end.tv_usec < 0) { + end.tv_sec--; + end.tv_usec += 1000000; + } + + bps = size/(end.tv_usec+1000000.0*end.tv_sec)*1000000.0; + fps = (i-1)/(end.tv_usec+1000000.0*end.tv_sec)*1000000.0; + + printf("Captured %u frames in %lu.%06lu seconds (%f fps, %f B/s).\n", + i-1, end.tv_sec, end.tv_usec, fps, bps); + +done: + free(filename); + return video_free_buffers(dev); +} + +#define V4L_BUFFERS_DEFAULT 8 +#define V4L_BUFFERS_MAX 32 + +static void usage(const char *argv0) +{ + printf("Usage: %s [options] device\n", argv0); + printf("Supported options:\n"); + printf("-c, --capture[=nframes] Capture frames\n"); + printf("-d, --delay Delay (in ms) before requeuing buffers\n"); + printf("-f, --format format Set the video format\n"); + printf("-F, --file prefix Read/write frames from/to disk\n"); + printf("-h, --help Show this help screen\n"); + printf("-i, --input input Select the video input\n"); + printf("-l, --list-controls List available controls\n"); + printf("-n, --nbufs n Set the number of video buffers\n"); + printf("-p, --pause Pause before starting the video stream\n"); + printf("-q, --quality n MJPEG quality (0-100)\n"); + printf("-r, --get-control ctrl Get control 'ctrl'\n"); + printf("-s, --size WxH Set the frame size\n"); + printf("-t, --time-per-frame num/denom Set the time per frame (eg. 1/25 = 25 fps)\n"); + printf("-u, --userptr Use the user pointers streaming method\n"); + printf("-w, --set-control 'ctrl value' Set control 'ctrl' to 'value'\n"); + printf(" --enum-formats Enumerate formats\n"); + printf(" --enum-inputs Enumerate inputs\n"); + printf(" --no-query Don't query capabilities on open\n"); + printf(" --skip n Skip the first n frames\n"); + printf(" --sleep-forever Sleep forever after configuring the device\n"); +} + +#define OPT_ENUM_FORMATS 256 +#define OPT_ENUM_INPUTS 257 +#define OPT_SKIP_FRAMES 258 +#define OPT_NO_QUERY 259 +#define OPT_SLEEP_FOREVER 260 + +static struct option opts[] = { + {"capture", 2, 0, 'c'}, + {"delay", 1, 0, 'd'}, + {"enum-formats", 0, 0, OPT_ENUM_FORMATS}, + {"enum-inputs", 0, 0, OPT_ENUM_INPUTS}, + {"file", 2, 0, 'F'}, + {"format", 1, 0, 'f'}, + {"help", 0, 0, 'h'}, + {"input", 1, 0, 'i'}, + {"list-controls", 0, 0, 'l'}, + {"nbufs", 1, 0, 'n'}, + {"no-query", 0, 0, OPT_NO_QUERY}, + {"pause", 0, 0, 'p'}, + {"quality", 1, 0, 'q'}, + {"get-control", 1, 0, 'r'}, + {"size", 1, 0, 's'}, + {"set-control", 1, 0, 'w'}, + {"skip", 1, 0, OPT_SKIP_FRAMES}, + {"sleep-forever", 0, 0, OPT_SLEEP_FOREVER}, + {"time-per-frame", 1, 0, 't'}, + {"userptr", 0, 0, 'u'}, + {0, 0, 0, 0} +}; + +int main(int argc, char *argv[]) +{ + struct device dev; + int ret; + + /* Options parsings */ + int do_file = 0, do_capture = 0, do_pause = 0; + int do_set_time_per_frame = 0; + int do_enum_formats = 0, do_set_format = 0; + int do_enum_inputs = 0, do_set_input = 0; + int do_list_controls = 0, do_get_control = 0, do_set_control = 0; + int do_sleep_forever = 0; + int no_query = 0; + char *endptr; + int c; + + /* Controls */ + int ctrl_name = 0; + int ctrl_value = 0; + + /* Video buffers */ + enum v4l2_memory memtype = V4L2_MEMORY_MMAP; + unsigned int pixelformat = V4L2_PIX_FMT_YUYV; + unsigned int width = 640; + unsigned int height = 480; + unsigned int nbufs = V4L_BUFFERS_DEFAULT; + unsigned int input = 0; + unsigned int skip = 0; + unsigned int quality = (unsigned int)-1; + struct v4l2_fract time_per_frame = {1, 25}; + + /* Capture loop */ + unsigned int delay = 0, nframes = (unsigned int)-1; + const char *filename = "frame"; + + opterr = 0; + while ((c = getopt_long(argc, argv, "cd:f:Fhi:ln:pq:r:s:t:uw:", opts, NULL)) != -1) { + + switch (c) { + case 'c': + do_capture = 1; + if (optarg) + nframes = atoi(optarg); + break; + case 'd': + delay = atoi(optarg); + break; + case 'f': + do_set_format = 1; + if (strcasecmp(optarg, "MJPEG") == 0) + pixelformat = V4L2_PIX_FMT_MJPEG; + else if (strcasecmp(optarg, "YUYV") == 0) + pixelformat = V4L2_PIX_FMT_YUYV; + else if (strcasecmp(optarg, "UYVY") == 0) + pixelformat = V4L2_PIX_FMT_UYVY; + else if (strcasecmp(optarg, "SGRBG10") == 0) + pixelformat = V4L2_PIX_FMT_SGRBG10; + else if (strcasecmp(optarg, "DV") == 0) + pixelformat = V4L2_PIX_FMT_DV; + else { + printf("Unsupported video format '%s'\n", optarg); + return 1; + } + break; + case 'F': + do_file = 1; + if (optarg) + filename = optarg; + break; + case 'h': + usage(argv[0]); + return 0; + case 'i': + do_set_input = 1; + input = atoi(optarg); + break; + case 'l': + do_list_controls = 1; + break; + case 'n': + nbufs = atoi(optarg); + if (nbufs > V4L_BUFFERS_MAX) + nbufs = V4L_BUFFERS_MAX; + break; + case 'p': + do_pause = 1; + break; + case 'q': + quality = atoi(optarg); + break; + case 'r': + ctrl_name = strtol(optarg, &endptr, 0); + if (*endptr != 0) { + printf("Invalid control name '%s'\n", optarg); + return 1; + } + do_get_control = 1; + break; + case 's': + do_set_format = 1; + width = strtol(optarg, &endptr, 10); + if (*endptr != 'x' || endptr == optarg) { + printf("Invalid size '%s'\n", optarg); + return 1; + } + height = strtol(endptr + 1, &endptr, 10); + if (*endptr != 0) { + printf("Invalid size '%s'\n", optarg); + return 1; + } + break; + case 't': + do_set_time_per_frame = 1; + time_per_frame.numerator = strtol(optarg, &endptr, 10); + if (*endptr != '/' || endptr == optarg) { + printf("Invalid time per frame '%s'\n", optarg); + return 1; + } + time_per_frame.denominator = strtol(endptr + 1, &endptr, 10); + if (*endptr != 0) { + printf("Invalid time per frame '%s'\n", optarg); + return 1; + } + break; + case 'u': + memtype = V4L2_MEMORY_USERPTR; + break; + case 'w': + ctrl_name = strtol(optarg, &endptr, 0); + if (*endptr != ' ' || endptr == optarg) { + printf("Invalid control name '%s'\n", optarg); + return 1; + } + ctrl_value = strtol(endptr + 1, &endptr, 0); + if (*endptr != 0) { + printf("Invalid control value '%s'\n", optarg); + return 1; + } + do_set_control = 1; + break; + case OPT_ENUM_FORMATS: + do_enum_formats = 1; + break; + case OPT_ENUM_INPUTS: + do_enum_inputs = 1; + break; + case OPT_NO_QUERY: + no_query = 1; + break; + case OPT_SKIP_FRAMES: + skip = atoi(optarg); + break; + case OPT_SLEEP_FOREVER: + do_sleep_forever = 1; + break; + default: + printf("Invalid option -%c\n", c); + printf("Run %s -h for help.\n", argv[0]); + return 1; + } + } + + if (optind >= argc) { + usage(argv[0]); + return 1; + } + + if (!do_file) + filename = NULL; + + /* Open the video device. */ + ret = video_open(&dev, argv[optind], no_query); + if (ret < 0) + return 1; + + dev.memtype = memtype; + + if (do_get_control) + uvc_get_control(&dev, ctrl_name); + if (do_set_control) + uvc_set_control(&dev, ctrl_name, ctrl_value); + + if (do_list_controls) + video_list_controls(&dev); + + if (do_enum_formats) { + printf("- Available formats:\n"); + video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_CAPTURE); + video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_OUTPUT); + video_enum_formats(&dev, V4L2_BUF_TYPE_VIDEO_OVERLAY); + } + + if (do_enum_inputs) { + printf("- Available inputs:\n"); + video_enum_inputs(&dev); + } + + if (do_set_input) { + video_set_input(&dev, input); + ret = video_get_input(&dev); + printf("Input %d selected\n", ret); + } + + /* Set the video format. */ + if (do_set_format) { + if (video_set_format(&dev, width, height, pixelformat) < 0) { + video_close(&dev); + return 1; + } + } + + if (!no_query) + video_get_format(&dev); + + /* Set the frame rate. */ + if (do_set_time_per_frame) { + if (video_set_framerate(&dev, &time_per_frame) < 0) { + video_close(&dev); + return 1; + } + } + + while (do_sleep_forever) + sleep(1000); + + if (!do_capture) { + video_close(&dev); + return 0; + } + + /* Set the compression quality. */ + if (video_set_quality(&dev, quality) < 0) { + video_close(&dev); + return 1; + } + + if (video_prepare_capture(&dev, nbufs)) { + video_close(&dev); + return 1; + } + + if (do_pause) { + printf("Press enter to start capture\n"); + getchar(); + } + + if (video_do_capture(&dev, nframes, skip, delay, filename) < 0) { + video_close(&dev); + return 1; + } + + video_close(&dev); + return 0; +} + -- cgit v1.2.3