Path: blob/master/Documentation/DocBook/v4l/common.xml
10821 views
<title>Common API Elements</title>12<para>Programming a V4L2 device consists of these3steps:</para>45<itemizedlist>6<listitem>7<para>Opening the device</para>8</listitem>9<listitem>10<para>Changing device properties, selecting a video and audio11input, video standard, picture brightness a. o.</para>12</listitem>13<listitem>14<para>Negotiating a data format</para>15</listitem>16<listitem>17<para>Negotiating an input/output method</para>18</listitem>19<listitem>20<para>The actual input/output loop</para>21</listitem>22<listitem>23<para>Closing the device</para>24</listitem>25</itemizedlist>2627<para>In practice most steps are optional and can be executed out of28order. It depends on the V4L2 device type, you can read about the29details in <xref linkend="devices" />. In this chapter we will discuss30the basic concepts applicable to all devices.</para>3132<section id="open">33<title>Opening and Closing Devices</title>3435<section>36<title>Device Naming</title>3738<para>V4L2 drivers are implemented as kernel modules, loaded39manually by the system administrator or automatically when a device is40first opened. The driver modules plug into the "videodev" kernel41module. It provides helper functions and a common application42interface specified in this document.</para>4344<para>Each driver thus loaded registers one or more device nodes45with major number 81 and a minor number between 0 and 255. Assigning46minor numbers to V4L2 devices is entirely up to the system administrator,47this is primarily intended to solve conflicts between devices.<footnote>48<para>Access permissions are associated with character49device special files, hence we must ensure device numbers cannot50change with the module load order. To this end minor numbers are no51longer automatically assigned by the "videodev" module as in V4L but52requested by the driver. The defaults will suffice for most people53unless two drivers compete for the same minor numbers.</para>54</footnote> The module options to select minor numbers are named55after the device special file with a "_nr" suffix. For example "video_nr"56for <filename>/dev/video</filename> video capture devices. The number is57an offset to the base minor number associated with the device type.58<footnote>59<para>In earlier versions of the V4L2 API the module options60where named after the device special file with a "unit_" prefix, expressing61the minor number itself, not an offset. Rationale for this change is unknown.62Lastly the naming and semantics are just a convention among driver writers,63the point to note is that minor numbers are not supposed to be hardcoded64into drivers.</para>65</footnote> When the driver supports multiple devices of the same66type more than one minor number can be assigned, separated by commas:67<informalexample>68<screen>69> insmod mydriver.o video_nr=0,1 radio_nr=0,1</screen>70</informalexample></para>7172<para>In <filename>/etc/modules.conf</filename> this may be73written as: <informalexample>74<screen>75alias char-major-81-0 mydriver76alias char-major-81-1 mydriver77alias char-major-81-64 mydriver <co id="alias" />78options mydriver video_nr=0,1 radio_nr=0,1 <co id="options" />79</screen>80<calloutlist>81<callout arearefs="alias">82<para>When an application attempts to open a device83special file with major number 81 and minor number 0, 1, or 64, load84"mydriver" (and the "videodev" module it depends upon).</para>85</callout>86<callout arearefs="options">87<para>Register the first two video capture devices with88minor number 0 and 1 (base number is 0), the first two radio device89with minor number 64 and 65 (base 64).</para>90</callout>91</calloutlist>92</informalexample> When no minor number is given as module93option the driver supplies a default. <xref linkend="devices" />94recommends the base minor numbers to be used for the various device95types. Obviously minor numbers must be unique. When the number is96already in use the <emphasis>offending device</emphasis> will not be97registered. <!-- Blessed by Linus Torvalds on98[email protected], 2002-11-20. --></para>99100<para>By convention system administrators create various101character device special files with these major and minor numbers in102the <filename>/dev</filename> directory. The names recommended for the103different V4L2 device types are listed in <xref linkend="devices" />.104</para>105106<para>The creation of character special files (with107<application>mknod</application>) is a privileged operation and108devices cannot be opened by major and minor number. That means109applications cannot <emphasis>reliable</emphasis> scan for loaded or110installed drivers. The user must enter a device name, or the111application can try the conventional device names.</para>112113<para>Under the device filesystem (devfs) the minor number114options are ignored. V4L2 drivers (or by proxy the "videodev" module)115automatically create the required device files in the116<filename>/dev/v4l</filename> directory using the conventional device117names above.</para>118</section>119120<section id="related">121<title>Related Devices</title>122123<para>Devices can support several related functions. For example124video capturing, video overlay and VBI capturing are related because125these functions share, amongst other, the same video input and tuner126frequency. V4L and earlier versions of V4L2 used the same device name127and minor number for video capturing and overlay, but different ones128for VBI. Experience showed this approach has several problems<footnote>129<para>Given a device file name one cannot reliable find130related devices. For once names are arbitrary and in a system with131multiple devices, where only some support VBI capturing, a132<filename>/dev/video2</filename> is not necessarily related to133<filename>/dev/vbi2</filename>. The V4L134<constant>VIDIOCGUNIT</constant> ioctl would require a search for a135device file with a particular major and minor number.</para>136</footnote>, and to make things worse the V4L videodev module137used to prohibit multiple opens of a device.</para>138139<para>As a remedy the present version of the V4L2 API relaxed the140concept of device types with specific names and minor numbers. For141compatibility with old applications drivers must still register different142minor numbers to assign a default function to the device. But if related143functions are supported by the driver they must be available under all144registered minor numbers. The desired function can be selected after145opening the device as described in <xref linkend="devices" />.</para>146147<para>Imagine a driver supporting video capturing, video148overlay, raw VBI capturing, and FM radio reception. It registers three149devices with minor number 0, 64 and 224 (this numbering scheme is150inherited from the V4L API). Regardless if151<filename>/dev/video</filename> (81, 0) or152<filename>/dev/vbi</filename> (81, 224) is opened the application can153select any one of the video capturing, overlay or VBI capturing154functions. Without programming (e. g. reading from the device155with <application>dd</application> or <application>cat</application>)156<filename>/dev/video</filename> captures video images, while157<filename>/dev/vbi</filename> captures raw VBI data.158<filename>/dev/radio</filename> (81, 64) is invariable a radio device,159unrelated to the video functions. Being unrelated does not imply the160devices can be used at the same time, however. The &func-open;161function may very well return an &EBUSY;.</para>162163<para>Besides video input or output the hardware may also164support audio sampling or playback. If so, these functions are165implemented as OSS or ALSA PCM devices and eventually OSS or ALSA166audio mixer. The V4L2 API makes no provisions yet to find these167related devices. If you have an idea please write to the linux-media168mailing list: &v4l-ml;.</para>169</section>170171<section>172<title>Multiple Opens</title>173174<para>In general, V4L2 devices can be opened more than once.175When this is supported by the driver, users can for example start a176"panel" application to change controls like brightness or audio177volume, while another application captures video and audio. In other words, panel178applications are comparable to an OSS or ALSA audio mixer application.179When a device supports multiple functions like capturing and overlay180<emphasis>simultaneously</emphasis>, multiple opens allow concurrent181use of the device by forked processes or specialized applications.</para>182183<para>Multiple opens are optional, although drivers should184permit at least concurrent accesses without data exchange, &ie; panel185applications. This implies &func-open; can return an &EBUSY; when the186device is already in use, as well as &func-ioctl; functions initiating187data exchange (namely the &VIDIOC-S-FMT; ioctl), and the &func-read;188and &func-write; functions.</para>189190<para>Mere opening a V4L2 device does not grant exclusive191access.<footnote>192<para>Drivers could recognize the193<constant>O_EXCL</constant> open flag. Presently this is not required,194so applications cannot know if it really works.</para>195</footnote> Initiating data exchange however assigns the right196to read or write the requested type of data, and to change related197properties, to this file descriptor. Applications can request198additional access privileges using the priority mechanism described in199<xref linkend="app-pri" />.</para>200</section>201202<section>203<title>Shared Data Streams</title>204205<para>V4L2 drivers should not support multiple applications206reading or writing the same data stream on a device by copying207buffers, time multiplexing or similar means. This is better handled by208a proxy application in user space. When the driver supports stream209sharing anyway it must be implemented transparently. The V4L2 API does210not specify how conflicts are solved. <!-- For example O_EXCL when the211application does not want to be preempted, PROT_READ mmapped buffers212which can be mapped twice, what happens when image formats do not213match etc.--></para>214</section>215216<section>217<title>Functions</title>218219<para>To open and close V4L2 devices applications use the220&func-open; and &func-close; function, respectively. Devices are221programmed using the &func-ioctl; function as explained in the222following sections.</para>223</section>224</section>225226<section id="querycap">227<title>Querying Capabilities</title>228229<para>Because V4L2 covers a wide variety of devices not all230aspects of the API are equally applicable to all types of devices.231Furthermore devices of the same type have different capabilities and232this specification permits the omission of a few complicated and less233important parts of the API.</para>234235<para>The &VIDIOC-QUERYCAP; ioctl is available to check if the kernel236device is compatible with this specification, and to query the <link237linkend="devices">functions</link> and <link linkend="io">I/O238methods</link> supported by the device. Other features can be queried239by calling the respective ioctl, for example &VIDIOC-ENUMINPUT;240to learn about the number, types and names of video connectors on the241device. Although abstraction is a major objective of this API, the242ioctl also allows driver specific applications to reliable identify243the driver.</para>244245<para>All V4L2 drivers must support246<constant>VIDIOC_QUERYCAP</constant>. Applications should always call247this ioctl after opening the device.</para>248</section>249250<section id="app-pri">251<title>Application Priority</title>252253<para>When multiple applications share a device it may be254desirable to assign them different priorities. Contrary to the255traditional "rm -rf /" school of thought a video recording application256could for example block other applications from changing video257controls or switching the current TV channel. Another objective is to258permit low priority applications working in background, which can be259preempted by user controlled applications and automatically regain260control of the device at a later time.</para>261262<para>Since these features cannot be implemented entirely in user263space V4L2 defines the &VIDIOC-G-PRIORITY; and &VIDIOC-S-PRIORITY;264ioctls to request and query the access priority associate with a file265descriptor. Opening a device assigns a medium priority, compatible266with earlier versions of V4L2 and drivers not supporting these ioctls.267Applications requiring a different priority will usually call268<constant>VIDIOC_S_PRIORITY</constant> after verifying the device with269the &VIDIOC-QUERYCAP; ioctl.</para>270271<para>Ioctls changing driver properties, such as &VIDIOC-S-INPUT;,272return an &EBUSY; after another application obtained higher priority.273An event mechanism to notify applications about asynchronous property274changes has been proposed but not added yet.</para>275</section>276277<section id="video">278<title>Video Inputs and Outputs</title>279280<para>Video inputs and outputs are physical connectors of a281device. These can be for example RF connectors (antenna/cable), CVBS282a.k.a. Composite Video, S-Video or RGB connectors. Only video and VBI283capture devices have inputs, output devices have outputs, at least one284each. Radio devices have no video inputs or outputs.</para>285286<para>To learn about the number and attributes of the287available inputs and outputs applications can enumerate them with the288&VIDIOC-ENUMINPUT; and &VIDIOC-ENUMOUTPUT; ioctl, respectively. The289&v4l2-input; returned by the <constant>VIDIOC_ENUMINPUT</constant>290ioctl also contains signal status information applicable when the291current video input is queried.</para>292293<para>The &VIDIOC-G-INPUT; and &VIDIOC-G-OUTPUT; ioctl return the294index of the current video input or output. To select a different295input or output applications call the &VIDIOC-S-INPUT; and296&VIDIOC-S-OUTPUT; ioctl. Drivers must implement all the input ioctls297when the device has one or more inputs, all the output ioctls when the298device has one or more outputs.</para>299300<!--301<figure id=io-tree>302<title>Input and output enumeration is the root of most device properties.</title>303<mediaobject>304<imageobject>305<imagedata fileref="links.pdf" format="ps" />306</imageobject>307<imageobject>308<imagedata fileref="links.gif" format="gif" />309</imageobject>310<textobject>311<phrase>Links between various device property structures.</phrase>312</textobject>313</mediaobject>314</figure>315-->316317<example>318<title>Information about the current video input</title>319320<programlisting>321&v4l2-input; input;322int index;323324if (-1 == ioctl (fd, &VIDIOC-G-INPUT;, &index)) {325perror ("VIDIOC_G_INPUT");326exit (EXIT_FAILURE);327}328329memset (&input, 0, sizeof (input));330input.index = index;331332if (-1 == ioctl (fd, &VIDIOC-ENUMINPUT;, &input)) {333perror ("VIDIOC_ENUMINPUT");334exit (EXIT_FAILURE);335}336337printf ("Current input: %s\n", input.name);338</programlisting>339</example>340341<example>342<title>Switching to the first video input</title>343344<programlisting>345int index;346347index = 0;348349if (-1 == ioctl (fd, &VIDIOC-S-INPUT;, &index)) {350perror ("VIDIOC_S_INPUT");351exit (EXIT_FAILURE);352}353</programlisting>354</example>355</section>356357<section id="audio">358<title>Audio Inputs and Outputs</title>359360<para>Audio inputs and outputs are physical connectors of a361device. Video capture devices have inputs, output devices have362outputs, zero or more each. Radio devices have no audio inputs or363outputs. They have exactly one tuner which in fact364<emphasis>is</emphasis> an audio source, but this API associates365tuners with video inputs or outputs only, and radio devices have366none of these.<footnote>367<para>Actually &v4l2-audio; ought to have a368<structfield>tuner</structfield> field like &v4l2-input;, not only369making the API more consistent but also permitting radio devices with370multiple tuners.</para>371</footnote> A connector on a TV card to loop back the received372audio signal to a sound card is not considered an audio output.</para>373374<para>Audio and video inputs and outputs are associated. Selecting375a video source also selects an audio source. This is most evident when376the video and audio source is a tuner. Further audio connectors can377combine with more than one video input or output. Assumed two378composite video inputs and two audio inputs exist, there may be up to379four valid combinations. The relation of video and audio connectors380is defined in the <structfield>audioset</structfield> field of the381respective &v4l2-input; or &v4l2-output;, where each bit represents382the index number, starting at zero, of one audio input or output.</para>383384<para>To learn about the number and attributes of the385available inputs and outputs applications can enumerate them with the386&VIDIOC-ENUMAUDIO; and &VIDIOC-ENUMAUDOUT; ioctl, respectively. The387&v4l2-audio; returned by the <constant>VIDIOC_ENUMAUDIO</constant> ioctl388also contains signal status information applicable when the current389audio input is queried.</para>390391<para>The &VIDIOC-G-AUDIO; and &VIDIOC-G-AUDOUT; ioctl report392the current audio input and output, respectively. Note that, unlike393&VIDIOC-G-INPUT; and &VIDIOC-G-OUTPUT; these ioctls return a structure394as <constant>VIDIOC_ENUMAUDIO</constant> and395<constant>VIDIOC_ENUMAUDOUT</constant> do, not just an index.</para>396397<para>To select an audio input and change its properties398applications call the &VIDIOC-S-AUDIO; ioctl. To select an audio399output (which presently has no changeable properties) applications400call the &VIDIOC-S-AUDOUT; ioctl.</para>401402<para>Drivers must implement all input ioctls when the device403has one or more inputs, all output ioctls when the device has one404or more outputs. When the device has any audio inputs or outputs the405driver must set the <constant>V4L2_CAP_AUDIO</constant> flag in the406&v4l2-capability; returned by the &VIDIOC-QUERYCAP; ioctl.</para>407408<example>409<title>Information about the current audio input</title>410411<programlisting>412&v4l2-audio; audio;413414memset (&audio, 0, sizeof (audio));415416if (-1 == ioctl (fd, &VIDIOC-G-AUDIO;, &audio)) {417perror ("VIDIOC_G_AUDIO");418exit (EXIT_FAILURE);419}420421printf ("Current input: %s\n", audio.name);422</programlisting>423</example>424425<example>426<title>Switching to the first audio input</title>427428<programlisting>429&v4l2-audio; audio;430431memset (&audio, 0, sizeof (audio)); /* clear audio.mode, audio.reserved */432433audio.index = 0;434435if (-1 == ioctl (fd, &VIDIOC-S-AUDIO;, &audio)) {436perror ("VIDIOC_S_AUDIO");437exit (EXIT_FAILURE);438}439</programlisting>440</example>441</section>442443<section id="tuner">444<title>Tuners and Modulators</title>445446<section>447<title>Tuners</title>448449<para>Video input devices can have one or more tuners450demodulating a RF signal. Each tuner is associated with one or more451video inputs, depending on the number of RF connectors on the tuner.452The <structfield>type</structfield> field of the respective453&v4l2-input; returned by the &VIDIOC-ENUMINPUT; ioctl is set to454<constant>V4L2_INPUT_TYPE_TUNER</constant> and its455<structfield>tuner</structfield> field contains the index number of456the tuner.</para>457458<para>Radio devices have exactly one tuner with index zero, no459video inputs.</para>460461<para>To query and change tuner properties applications use the462&VIDIOC-G-TUNER; and &VIDIOC-S-TUNER; ioctl, respectively. The463&v4l2-tuner; returned by <constant>VIDIOC_G_TUNER</constant> also464contains signal status information applicable when the tuner of the465current video input, or a radio tuner is queried. Note that466<constant>VIDIOC_S_TUNER</constant> does not switch the current tuner,467when there is more than one at all. The tuner is solely determined by468the current video input. Drivers must support both ioctls and set the469<constant>V4L2_CAP_TUNER</constant> flag in the &v4l2-capability;470returned by the &VIDIOC-QUERYCAP; ioctl when the device has one or471more tuners.</para>472</section>473474<section>475<title>Modulators</title>476477<para>Video output devices can have one or more modulators, uh,478modulating a video signal for radiation or connection to the antenna479input of a TV set or video recorder. Each modulator is associated with480one or more video outputs, depending on the number of RF connectors on481the modulator. The <structfield>type</structfield> field of the482respective &v4l2-output; returned by the &VIDIOC-ENUMOUTPUT; ioctl is483set to <constant>V4L2_OUTPUT_TYPE_MODULATOR</constant> and its484<structfield>modulator</structfield> field contains the index number485of the modulator. This specification does not define radio output486devices.</para>487488<para>To query and change modulator properties applications use489the &VIDIOC-G-MODULATOR; and &VIDIOC-S-MODULATOR; ioctl. Note that490<constant>VIDIOC_S_MODULATOR</constant> does not switch the current491modulator, when there is more than one at all. The modulator is solely492determined by the current video output. Drivers must support both493ioctls and set the <constant>V4L2_CAP_MODULATOR</constant> flag in494the &v4l2-capability; returned by the &VIDIOC-QUERYCAP; ioctl when the495device has one or more modulators.</para>496</section>497498<section>499<title>Radio Frequency</title>500501<para>To get and set the tuner or modulator radio frequency502applications use the &VIDIOC-G-FREQUENCY; and &VIDIOC-S-FREQUENCY;503ioctl which both take a pointer to a &v4l2-frequency;. These ioctls504are used for TV and radio devices alike. Drivers must support both505ioctls when the tuner or modulator ioctls are supported, or506when the device is a radio device.</para>507</section>508</section>509510<section id="standard">511<title>Video Standards</title>512513<para>Video devices typically support one or more different video514standards or variations of standards. Each video input and output may515support another set of standards. This set is reported by the516<structfield>std</structfield> field of &v4l2-input; and517&v4l2-output; returned by the &VIDIOC-ENUMINPUT; and518&VIDIOC-ENUMOUTPUT; ioctl, respectively.</para>519520<para>V4L2 defines one bit for each analog video standard521currently in use worldwide, and sets aside bits for driver defined522standards, ⪚ hybrid standards to watch NTSC video tapes on PAL TVs523and vice versa. Applications can use the predefined bits to select a524particular standard, although presenting the user a menu of supported525standards is preferred. To enumerate and query the attributes of the526supported standards applications use the &VIDIOC-ENUMSTD; ioctl.</para>527528<para>Many of the defined standards are actually just variations529of a few major standards. The hardware may in fact not distinguish530between them, or do so internal and switch automatically. Therefore531enumerated standards also contain sets of one or more standard532bits.</para>533534<para>Assume a hypothetic tuner capable of demodulating B/PAL,535G/PAL and I/PAL signals. The first enumerated standard is a set of B536and G/PAL, switched automatically depending on the selected radio537frequency in UHF or VHF band. Enumeration gives a "PAL-B/G" or "PAL-I"538choice. Similar a Composite input may collapse standards, enumerating539"PAL-B/G/H/I", "NTSC-M" and "SECAM-D/K".<footnote>540<para>Some users are already confused by technical terms PAL,541NTSC and SECAM. There is no point asking them to distinguish between542B, G, D, or K when the software or hardware can do that543automatically.</para>544</footnote></para>545546<para>To query and select the standard used by the current video547input or output applications call the &VIDIOC-G-STD; and548&VIDIOC-S-STD; ioctl, respectively. The <emphasis>received</emphasis>549standard can be sensed with the &VIDIOC-QUERYSTD; ioctl. Note parameter of all these ioctls is a pointer to a &v4l2-std-id; type (a standard set), <emphasis>not</emphasis> an index into the standard enumeration.<footnote>550<para>An alternative to the current scheme is to use pointers551to indices as arguments of <constant>VIDIOC_G_STD</constant> and552<constant>VIDIOC_S_STD</constant>, the &v4l2-input; and553&v4l2-output; <structfield>std</structfield> field would be a set of554indices like <structfield>audioset</structfield>.</para>555<para>Indices are consistent with the rest of the API556and identify the standard unambiguously. In the present scheme of557things an enumerated standard is looked up by &v4l2-std-id;. Now the558standards supported by the inputs of a device can overlap. Just559assume the tuner and composite input in the example above both560exist on a device. An enumeration of "PAL-B/G", "PAL-H/I" suggests561a choice which does not exist. We cannot merge or omit sets, because562applications would be unable to find the standards reported by563<constant>VIDIOC_G_STD</constant>. That leaves separate enumerations564for each input. Also selecting a standard by &v4l2-std-id; can be565ambiguous. Advantage of this method is that applications need not566identify the standard indirectly, after enumerating.</para><para>So in567summary, the lookup itself is unavoidable. The difference is only568whether the lookup is necessary to find an enumerated standard or to569switch to a standard by &v4l2-std-id;.</para>570</footnote> Drivers must implement all video standard ioctls571when the device has one or more video inputs or outputs.</para>572573<para>Special rules apply to USB cameras where the notion of video574standards makes little sense. More generally any capture device,575output devices accordingly, which is <itemizedlist>576<listitem>577<para>incapable of capturing fields or frames at the nominal578rate of the video standard, or</para>579</listitem>580<listitem>581<para>where <link linkend="buffer">timestamps</link> refer582to the instant the field or frame was received by the driver, not the583capture time, or</para>584</listitem>585<listitem>586<para>where <link linkend="buffer">sequence numbers</link>587refer to the frames received by the driver, not the captured588frames.</para>589</listitem>590</itemizedlist> Here the driver shall set the591<structfield>std</structfield> field of &v4l2-input; and &v4l2-output;592to zero, the <constant>VIDIOC_G_STD</constant>,593<constant>VIDIOC_S_STD</constant>,594<constant>VIDIOC_QUERYSTD</constant> and595<constant>VIDIOC_ENUMSTD</constant> ioctls shall return the596&EINVAL;.<footnote>597<para>See <xref linkend="buffer" /> for a rationale. Probably598even USB cameras follow some well known video standard. It might have599been better to explicitly indicate elsewhere if a device cannot live600up to normal expectations, instead of this exception.</para>601</footnote></para>602603<example>604<title>Information about the current video standard</title>605606<programlisting>607&v4l2-std-id; std_id;608&v4l2-standard; standard;609610if (-1 == ioctl (fd, &VIDIOC-G-STD;, &std_id)) {611/* Note when VIDIOC_ENUMSTD always returns EINVAL this612is no video device or it falls under the USB exception,613and VIDIOC_G_STD returning EINVAL is no error. */614615perror ("VIDIOC_G_STD");616exit (EXIT_FAILURE);617}618619memset (&standard, 0, sizeof (standard));620standard.index = 0;621622while (0 == ioctl (fd, &VIDIOC-ENUMSTD;, &standard)) {623if (standard.id & std_id) {624printf ("Current video standard: %s\n", standard.name);625exit (EXIT_SUCCESS);626}627628standard.index++;629}630631/* EINVAL indicates the end of the enumeration, which cannot be632empty unless this device falls under the USB exception. */633634if (errno == EINVAL || standard.index == 0) {635perror ("VIDIOC_ENUMSTD");636exit (EXIT_FAILURE);637}638</programlisting>639</example>640641<example>642<title>Listing the video standards supported by the current643input</title>644645<programlisting>646&v4l2-input; input;647&v4l2-standard; standard;648649memset (&input, 0, sizeof (input));650651if (-1 == ioctl (fd, &VIDIOC-G-INPUT;, &input.index)) {652perror ("VIDIOC_G_INPUT");653exit (EXIT_FAILURE);654}655656if (-1 == ioctl (fd, &VIDIOC-ENUMINPUT;, &input)) {657perror ("VIDIOC_ENUM_INPUT");658exit (EXIT_FAILURE);659}660661printf ("Current input %s supports:\n", input.name);662663memset (&standard, 0, sizeof (standard));664standard.index = 0;665666while (0 == ioctl (fd, &VIDIOC-ENUMSTD;, &standard)) {667if (standard.id & input.std)668printf ("%s\n", standard.name);669670standard.index++;671}672673/* EINVAL indicates the end of the enumeration, which cannot be674empty unless this device falls under the USB exception. */675676if (errno != EINVAL || standard.index == 0) {677perror ("VIDIOC_ENUMSTD");678exit (EXIT_FAILURE);679}680</programlisting>681</example>682683<example>684<title>Selecting a new video standard</title>685686<programlisting>687&v4l2-input; input;688&v4l2-std-id; std_id;689690memset (&input, 0, sizeof (input));691692if (-1 == ioctl (fd, &VIDIOC-G-INPUT;, &input.index)) {693perror ("VIDIOC_G_INPUT");694exit (EXIT_FAILURE);695}696697if (-1 == ioctl (fd, &VIDIOC-ENUMINPUT;, &input)) {698perror ("VIDIOC_ENUM_INPUT");699exit (EXIT_FAILURE);700}701702if (0 == (input.std & V4L2_STD_PAL_BG)) {703fprintf (stderr, "Oops. B/G PAL is not supported.\n");704exit (EXIT_FAILURE);705}706707/* Note this is also supposed to work when only B708<emphasis>or</emphasis> G/PAL is supported. */709710std_id = V4L2_STD_PAL_BG;711712if (-1 == ioctl (fd, &VIDIOC-S-STD;, &std_id)) {713perror ("VIDIOC_S_STD");714exit (EXIT_FAILURE);715}716</programlisting>717</example>718<section id="dv-timings">719<title>Digital Video (DV) Timings</title>720<para>721The video standards discussed so far has been dealing with Analog TV and the722corresponding video timings. Today there are many more different hardware interfaces723such as High Definition TV interfaces (HDMI), VGA, DVI connectors etc., that carry724video signals and there is a need to extend the API to select the video timings725for these interfaces. Since it is not possible to extend the &v4l2-std-id; due to726the limited bits available, a new set of IOCTLs is added to set/get video timings at727the input and output: </para><itemizedlist>728<listitem>729<para>DV Presets: Digital Video (DV) presets. These are IDs representing a730video timing at the input/output. Presets are pre-defined timings implemented731by the hardware according to video standards. A __u32 data type is used to represent732a preset unlike the bit mask that is used in &v4l2-std-id; allowing future extensions733to support as many different presets as needed.</para>734</listitem>735<listitem>736<para>Custom DV Timings: This will allow applications to define more detailed737custom video timings for the interface. This includes parameters such as width, height,738polarities, frontporch, backporch etc.739</para>740</listitem>741</itemizedlist>742<para>To enumerate and query the attributes of DV presets supported by a device,743applications use the &VIDIOC-ENUM-DV-PRESETS; ioctl. To get the current DV preset,744applications use the &VIDIOC-G-DV-PRESET; ioctl and to set a preset they use the745&VIDIOC-S-DV-PRESET; ioctl.</para>746<para>To set custom DV timings for the device, applications use the747&VIDIOC-S-DV-TIMINGS; ioctl and to get current custom DV timings they use the748&VIDIOC-G-DV-TIMINGS; ioctl.</para>749<para>Applications can make use of the <xref linkend="input-capabilities" /> and750<xref linkend="output-capabilities"/> flags to decide what ioctls are available to set the751video timings for the device.</para>752</section>753</section>754755&sub-controls;756757<section id="format">758<title>Data Formats</title>759760<section>761<title>Data Format Negotiation</title>762763<para>Different devices exchange different kinds of data with764applications, for example video images, raw or sliced VBI data, RDS765datagrams. Even within one kind many different formats are possible,766in particular an abundance of image formats. Although drivers must767provide a default and the selection persists across closing and768reopening a device, applications should always negotiate a data format769before engaging in data exchange. Negotiation means the application770asks for a particular format and the driver selects and reports the771best the hardware can do to satisfy the request. Of course772applications can also just query the current selection.</para>773774<para>A single mechanism exists to negotiate all data formats775using the aggregate &v4l2-format; and the &VIDIOC-G-FMT; and776&VIDIOC-S-FMT; ioctls. Additionally the &VIDIOC-TRY-FMT; ioctl can be777used to examine what the hardware <emphasis>could</emphasis> do,778without actually selecting a new data format. The data formats779supported by the V4L2 API are covered in the respective device section780in <xref linkend="devices" />. For a closer look at image formats see781<xref linkend="pixfmt" />.</para>782783<para>The <constant>VIDIOC_S_FMT</constant> ioctl is a major784turning-point in the initialization sequence. Prior to this point785multiple panel applications can access the same device concurrently to786select the current input, change controls or modify other properties.787The first <constant>VIDIOC_S_FMT</constant> assigns a logical stream788(video data, VBI data etc.) exclusively to one file descriptor.</para>789790<para>Exclusive means no other application, more precisely no791other file descriptor, can grab this stream or change device792properties inconsistent with the negotiated parameters. A video793standard change for example, when the new standard uses a different794number of scan lines, can invalidate the selected image format.795Therefore only the file descriptor owning the stream can make796invalidating changes. Accordingly multiple file descriptors which797grabbed different logical streams prevent each other from interfering798with their settings. When for example video overlay is about to start799or already in progress, simultaneous video capturing may be restricted800to the same cropping and image size.</para>801802<para>When applications omit the803<constant>VIDIOC_S_FMT</constant> ioctl its locking side effects are804implied by the next step, the selection of an I/O method with the805&VIDIOC-REQBUFS; ioctl or implicit with the first &func-read; or806&func-write; call.</para>807808<para>Generally only one logical stream can be assigned to a809file descriptor, the exception being drivers permitting simultaneous810video capturing and overlay using the same file descriptor for811compatibility with V4L and earlier versions of V4L2. Switching the812logical stream or returning into "panel mode" is possible by closing813and reopening the device. Drivers <emphasis>may</emphasis> support a814switch using <constant>VIDIOC_S_FMT</constant>.</para>815816<para>All drivers exchanging data with817applications must support the <constant>VIDIOC_G_FMT</constant> and818<constant>VIDIOC_S_FMT</constant> ioctl. Implementation of the819<constant>VIDIOC_TRY_FMT</constant> is highly recommended but820optional.</para>821</section>822823<section>824<title>Image Format Enumeration</title>825826<para>Apart of the generic format negotiation functions827a special ioctl to enumerate all image formats supported by video828capture, overlay or output devices is available.<footnote>829<para>Enumerating formats an application has no a-priori830knowledge of (otherwise it could explicitly ask for them and need not831enumerate) seems useless, but there are applications serving as proxy832between drivers and the actual video applications for which this is833useful.</para>834</footnote></para>835836<para>The &VIDIOC-ENUM-FMT; ioctl must be supported837by all drivers exchanging image data with applications.</para>838839<important>840<para>Drivers are not supposed to convert image formats in841kernel space. They must enumerate only formats directly supported by842the hardware. If necessary driver writers should publish an example843conversion routine or library for integration into applications.</para>844</important>845</section>846</section>847848&sub-planar-apis;849850<section id="crop">851<title>Image Cropping, Insertion and Scaling</title>852853<para>Some video capture devices can sample a subsection of the854picture and shrink or enlarge it to an image of arbitrary size. We855call these abilities cropping and scaling. Some video output devices856can scale an image up or down and insert it at an arbitrary scan line857and horizontal offset into a video signal.</para>858859<para>Applications can use the following API to select an area in860the video signal, query the default area and the hardware limits.861<emphasis>Despite their name, the &VIDIOC-CROPCAP;, &VIDIOC-G-CROP;862and &VIDIOC-S-CROP; ioctls apply to input as well as output863devices.</emphasis></para>864865<para>Scaling requires a source and a target. On a video capture866or overlay device the source is the video signal, and the cropping867ioctls determine the area actually sampled. The target are images868read by the application or overlaid onto the graphics screen. Their869size (and position for an overlay) is negotiated with the870&VIDIOC-G-FMT; and &VIDIOC-S-FMT; ioctls.</para>871872<para>On a video output device the source are the images passed in873by the application, and their size is again negotiated with the874<constant>VIDIOC_G/S_FMT</constant> ioctls, or may be encoded in a875compressed video stream. The target is the video signal, and the876cropping ioctls determine the area where the images are877inserted.</para>878879<para>Source and target rectangles are defined even if the device880does not support scaling or the <constant>VIDIOC_G/S_CROP</constant>881ioctls. Their size (and position where applicable) will be fixed in882this case. <emphasis>All capture and output device must support the883<constant>VIDIOC_CROPCAP</constant> ioctl such that applications can884determine if scaling takes place.</emphasis></para>885886<section>887<title>Cropping Structures</title>888889<figure id="crop-scale">890<title>Image Cropping, Insertion and Scaling</title>891<mediaobject>892<imageobject>893<imagedata fileref="crop.pdf" format="PS" />894</imageobject>895<imageobject>896<imagedata fileref="crop.gif" format="GIF" />897</imageobject>898<textobject>899<phrase>The cropping, insertion and scaling process</phrase>900</textobject>901</mediaobject>902</figure>903904<para>For capture devices the coordinates of the top left905corner, width and height of the area which can be sampled is given by906the <structfield>bounds</structfield> substructure of the907&v4l2-cropcap; returned by the <constant>VIDIOC_CROPCAP</constant>908ioctl. To support a wide range of hardware this specification does not909define an origin or units. However by convention drivers should910horizontally count unscaled samples relative to 0H (the leading edge911of the horizontal sync pulse, see <xref linkend="vbi-hsync" />).912Vertically ITU-R line913numbers of the first field (<xref linkend="vbi-525" />, <xref914linkend="vbi-625" />), multiplied by two if the driver can capture both915fields.</para>916917<para>The top left corner, width and height of the source918rectangle, that is the area actually sampled, is given by &v4l2-crop;919using the same coordinate system as &v4l2-cropcap;. Applications can920use the <constant>VIDIOC_G_CROP</constant> and921<constant>VIDIOC_S_CROP</constant> ioctls to get and set this922rectangle. It must lie completely within the capture boundaries and923the driver may further adjust the requested size and/or position924according to hardware limitations.</para>925926<para>Each capture device has a default source rectangle, given927by the <structfield>defrect</structfield> substructure of928&v4l2-cropcap;. The center of this rectangle shall align with the929center of the active picture area of the video signal, and cover what930the driver writer considers the complete picture. Drivers shall reset931the source rectangle to the default when the driver is first loaded,932but not later.</para>933934<para>For output devices these structures and ioctls are used935accordingly, defining the <emphasis>target</emphasis> rectangle where936the images will be inserted into the video signal.</para>937938</section>939940<section>941<title>Scaling Adjustments</title>942943<para>Video hardware can have various cropping, insertion and944scaling limitations. It may only scale up or down, support only945discrete scaling factors, or have different scaling abilities in946horizontal and vertical direction. Also it may not support scaling at947all. At the same time the &v4l2-crop; rectangle may have to be948aligned, and both the source and target rectangles may have arbitrary949upper and lower size limits. In particular the maximum950<structfield>width</structfield> and <structfield>height</structfield>951in &v4l2-crop; may be smaller than the952&v4l2-cropcap;.<structfield>bounds</structfield> area. Therefore, as953usual, drivers are expected to adjust the requested parameters and954return the actual values selected.</para>955956<para>Applications can change the source or the target rectangle957first, as they may prefer a particular image size or a certain area in958the video signal. If the driver has to adjust both to satisfy hardware959limitations, the last requested rectangle shall take priority, and the960driver should preferably adjust the opposite one. The &VIDIOC-TRY-FMT;961ioctl however shall not change the driver state and therefore only962adjust the requested rectangle.</para>963964<para>Suppose scaling on a video capture device is restricted to965a factor 1:1 or 2:1 in either direction and the target image size must966be a multiple of 16 × 16 pixels. The source cropping967rectangle is set to defaults, which are also the upper limit in this968example, of 640 × 400 pixels at offset 0, 0. An969application requests an image size of 300 × 225970pixels, assuming video will be scaled down from the "full picture"971accordingly. The driver sets the image size to the closest possible972values 304 × 224, then chooses the cropping rectangle973closest to the requested size, that is 608 × 224974(224 × 2:1 would exceed the limit 400). The offset9750, 0 is still valid, thus unmodified. Given the default cropping976rectangle reported by <constant>VIDIOC_CROPCAP</constant> the977application can easily propose another offset to center the cropping978rectangle.</para>979980<para>Now the application may insist on covering an area using a981picture aspect ratio closer to the original request, so it asks for a982cropping rectangle of 608 × 456 pixels. The present983scaling factors limit cropping to 640 × 384, so the984driver returns the cropping size 608 × 384 and adjusts985the image size to closest possible 304 × 192.</para>986987</section>988989<section>990<title>Examples</title>991992<para>Source and target rectangles shall remain unchanged across993closing and reopening a device, such that piping data into or out of a994device will work without special preparations. More advanced995applications should ensure the parameters are suitable before starting996I/O.</para>997998<example>999<title>Resetting the cropping parameters</title>10001001<para>(A video capture device is assumed; change1002<constant>V4L2_BUF_TYPE_VIDEO_CAPTURE</constant> for other1003devices.)</para>10041005<programlisting>1006&v4l2-cropcap; cropcap;1007&v4l2-crop; crop;10081009memset (&cropcap, 0, sizeof (cropcap));1010cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;10111012if (-1 == ioctl (fd, &VIDIOC-CROPCAP;, &cropcap)) {1013perror ("VIDIOC_CROPCAP");1014exit (EXIT_FAILURE);1015}10161017memset (&crop, 0, sizeof (crop));1018crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;1019crop.c = cropcap.defrect;10201021/* Ignore if cropping is not supported (EINVAL). */10221023if (-1 == ioctl (fd, &VIDIOC-S-CROP;, &crop)1024&& errno != EINVAL) {1025perror ("VIDIOC_S_CROP");1026exit (EXIT_FAILURE);1027}1028</programlisting>1029</example>10301031<example>1032<title>Simple downscaling</title>10331034<para>(A video capture device is assumed.)</para>10351036<programlisting>1037&v4l2-cropcap; cropcap;1038&v4l2-format; format;10391040reset_cropping_parameters ();10411042/* Scale down to 1/4 size of full picture. */10431044memset (&format, 0, sizeof (format)); /* defaults */10451046format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;10471048format.fmt.pix.width = cropcap.defrect.width >> 1;1049format.fmt.pix.height = cropcap.defrect.height >> 1;1050format.fmt.pix.pixelformat = V4L2_PIX_FMT_YUYV;10511052if (-1 == ioctl (fd, &VIDIOC-S-FMT;, &format)) {1053perror ("VIDIOC_S_FORMAT");1054exit (EXIT_FAILURE);1055}10561057/* We could check the actual image size now, the actual scaling factor1058or if the driver can scale at all. */1059</programlisting>1060</example>10611062<example>1063<title>Selecting an output area</title>10641065<programlisting>1066&v4l2-cropcap; cropcap;1067&v4l2-crop; crop;10681069memset (&cropcap, 0, sizeof (cropcap));1070cropcap.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;10711072if (-1 == ioctl (fd, VIDIOC_CROPCAP;, &cropcap)) {1073perror ("VIDIOC_CROPCAP");1074exit (EXIT_FAILURE);1075}10761077memset (&crop, 0, sizeof (crop));10781079crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT;1080crop.c = cropcap.defrect;10811082/* Scale the width and height to 50 % of their original size1083and center the output. */10841085crop.c.width /= 2;1086crop.c.height /= 2;1087crop.c.left += crop.c.width / 2;1088crop.c.top += crop.c.height / 2;10891090/* Ignore if cropping is not supported (EINVAL). */10911092if (-1 == ioctl (fd, VIDIOC_S_CROP, &crop)1093&& errno != EINVAL) {1094perror ("VIDIOC_S_CROP");1095exit (EXIT_FAILURE);1096}1097</programlisting>1098</example>10991100<example>1101<title>Current scaling factor and pixel aspect</title>11021103<para>(A video capture device is assumed.)</para>11041105<programlisting>1106&v4l2-cropcap; cropcap;1107&v4l2-crop; crop;1108&v4l2-format; format;1109double hscale, vscale;1110double aspect;1111int dwidth, dheight;11121113memset (&cropcap, 0, sizeof (cropcap));1114cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;11151116if (-1 == ioctl (fd, &VIDIOC-CROPCAP;, &cropcap)) {1117perror ("VIDIOC_CROPCAP");1118exit (EXIT_FAILURE);1119}11201121memset (&crop, 0, sizeof (crop));1122crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;11231124if (-1 == ioctl (fd, &VIDIOC-G-CROP;, &crop)) {1125if (errno != EINVAL) {1126perror ("VIDIOC_G_CROP");1127exit (EXIT_FAILURE);1128}11291130/* Cropping not supported. */1131crop.c = cropcap.defrect;1132}11331134memset (&format, 0, sizeof (format));1135format.fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;11361137if (-1 == ioctl (fd, &VIDIOC-G-FMT;, &format)) {1138perror ("VIDIOC_G_FMT");1139exit (EXIT_FAILURE);1140}11411142/* The scaling applied by the driver. */11431144hscale = format.fmt.pix.width / (double) crop.c.width;1145vscale = format.fmt.pix.height / (double) crop.c.height;11461147aspect = cropcap.pixelaspect.numerator /1148(double) cropcap.pixelaspect.denominator;1149aspect = aspect * hscale / vscale;11501151/* Devices following ITU-R BT.601 do not capture1152square pixels. For playback on a computer monitor1153we should scale the images to this size. */11541155dwidth = format.fmt.pix.width / aspect;1156dheight = format.fmt.pix.height;1157</programlisting>1158</example>1159</section>1160</section>11611162<section id="streaming-par">1163<title>Streaming Parameters</title>11641165<para>Streaming parameters are intended to optimize the video1166capture process as well as I/O. Presently applications can request a1167high quality capture mode with the &VIDIOC-S-PARM; ioctl.</para>11681169<para>The current video standard determines a nominal number of1170frames per second. If less than this number of frames is to be1171captured or output, applications can request frame skipping or1172duplicating on the driver side. This is especially useful when using1173the &func-read; or &func-write;, which are not augmented by timestamps1174or sequence counters, and to avoid unnecessary data copying.</para>11751176<para>Finally these ioctls can be used to determine the number of1177buffers used internally by a driver in read/write mode. For1178implications see the section discussing the &func-read;1179function.</para>11801181<para>To get and set the streaming parameters applications call1182the &VIDIOC-G-PARM; and &VIDIOC-S-PARM; ioctl, respectively. They take1183a pointer to a &v4l2-streamparm;, which contains a union holding1184separate parameters for input and output devices.</para>11851186<para>These ioctls are optional, drivers need not implement1187them. If so, they return the &EINVAL;.</para>1188</section>11891190<!--1191Local Variables:1192mode: sgml1193sgml-parent-document: "v4l2.sgml"1194indent-tabs-mode: nil1195End:1196-->119711981199