patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / Documentation / DocBook / videobook.tmpl
1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
2
3 <book id="V4LGuide">
4  <bookinfo>
5   <title>Video4Linux Programming</title>
6   
7   <authorgroup>
8    <author>
9     <firstname>Alan</firstname>
10     <surname>Cox</surname>
11     <affiliation>
12      <address>
13       <email>alan@redhat.com</email>
14      </address>
15     </affiliation>
16    </author>
17   </authorgroup>
18
19   <copyright>
20    <year>2000</year>
21    <holder>Alan Cox</holder>
22   </copyright>
23
24   <legalnotice>
25    <para>
26      This documentation is free software; you can redistribute
27      it and/or modify it under the terms of the GNU General Public
28      License as published by the Free Software Foundation; either
29      version 2 of the License, or (at your option) any later
30      version.
31    </para>
32       
33    <para>
34      This program is distributed in the hope that it will be
35      useful, but WITHOUT ANY WARRANTY; without even the implied
36      warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
37      See the GNU General Public License for more details.
38    </para>
39       
40    <para>
41      You should have received a copy of the GNU General Public
42      License along with this program; if not, write to the Free
43      Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
44      MA 02111-1307 USA
45    </para>
46       
47    <para>
48      For more details see the file COPYING in the source
49      distribution of Linux.
50    </para>
51   </legalnotice>
52  </bookinfo>
53
54 <toc></toc>
55
56   <chapter id="intro">
57       <title>Introduction</title>
58   <para>
59         Parts of this document first appeared in Linux Magazine under a
60         ninety day exclusivity.
61   </para>
62   <para>
63         Video4Linux is intended to provide a common programming interface
64         for the many TV and capture cards now on the market, as well as
65         parallel port and USB video cameras. Radio, teletext decoders and
66         vertical blanking data interfaces are also provided.
67   </para>
68   </chapter>
69   <chapter id="radio">
70         <title>Radio Devices</title>
71   <para>
72         There are a wide variety of radio interfaces available for PC's, and these
73         are generally very simple to program. The biggest problem with supporting
74         such devices is normally extracting documentation from the vendor.
75   </para>
76   <para>
77         The radio interface supports a simple set of control ioctls standardised
78         across all radio and tv interfaces. It does not support read or write, which
79         are used for video streams. The reason radio cards do not allow you to read
80         the audio stream into an application is that without exception they provide
81         a connection on to a soundcard. Soundcards can be used to read the radio
82         data just fine. 
83   </para>
84   <sect1 id="registerradio">
85   <title>Registering Radio Devices</title>
86   <para>
87         The Video4linux core provides an interface for registering devices. The
88         first step in writing our radio card driver is to register it.
89   </para>
90   <programlisting>
91
92
93 static struct video_device my_radio
94 {
95         "My radio",
96         VID_TYPE_TUNER,
97         VID_HARDWARE_MYRADIO,
98         radio_open.
99         radio_close,
100         NULL,                /* no read */
101         NULL,                 /* no write */
102         NULL,                /* no poll */
103         radio_ioctl,
104         NULL,                /* no special init function */
105         NULL                /* no private data */
106 };
107
108
109   </programlisting>
110   <para>
111         This declares our video4linux device driver interface. The VID_TYPE_ value
112         defines what kind of an interface we are, and defines basic capabilities.
113   </para>
114   <para>
115         The only defined value relevant for a radio card is VID_TYPE_TUNER which
116         indicates that the device can be tuned. Clearly our radio is going to have some
117         way to change channel so it is tuneable.
118   </para>
119   <para>
120         The VID_HARDWARE_ types are unique to each device. Numbers are assigned by
121         <email>alan@redhat.com</email> when device drivers are going to be released. Until then you
122         can pull a suitably large number out of your hat and use it. 10000 should be
123         safe for a very long time even allowing for the huge number of vendors
124         making new and different radio cards at the moment.
125   </para>
126   <para>
127         We declare an open and close routine, but we do not need read or write,
128         which are used to read and write video data to or from the card itself. As
129         we have no read or write there is no poll function.
130   </para>
131   <para>
132         The private initialise function is run when the device is registered. In
133         this driver we've already done all the work needed. The final pointer is a
134         private data pointer that can be used by the device driver to attach and
135         retrieve private data structures. We set this field "priv" to NULL for
136         the moment.
137   </para>
138   <para>
139         Having the structure defined is all very well but we now need to register it
140         with the kernel. 
141   </para>
142   <programlisting>
143
144
145 static int io = 0x320;
146
147 int __init myradio_init(struct video_init *v)
148 {
149         if(!request_region(io, MY_IO_SIZE, "myradio"))
150         {
151                 printk(KERN_ERR 
152                     "myradio: port 0x%03X is in use.\n", io);
153                 return -EBUSY;
154         }
155
156         if(video_device_register(&amp;my_radio, VFL_TYPE_RADIO)==-1) {
157                 release_region(io, MY_IO_SIZE);
158                 return -EINVAL;
159         }               
160         return 0;
161 }
162
163   </programlisting>
164   <para>
165         The first stage of the initialisation, as is normally the case, is to check 
166         that the I/O space we are about to fiddle with doesn't belong to some other 
167         driver. If it is we leave well alone. If the user gives the address of the 
168         wrong device then we will spot this. These policies will generally avoid 
169         crashing the machine.
170   </para>
171   <para>
172         Now we ask the Video4Linux layer to register the device for us. We hand it
173         our carefully designed video_device structure and also tell it which group
174         of devices we want it registered with. In this case VFL_TYPE_RADIO.
175   </para>
176   <para>
177         The types available are
178   </para>
179    <table frame="all"><title>Device Types</title>
180    <tgroup cols="3" align="left">
181    <tbody>
182    <row>
183         <entry>VFL_TYPE_RADIO</><entry>/dev/radio{n}</><entry>
184
185         Radio devices are assigned in this block. As with all of these
186         selections the actual number assignment is done by the video layer
187         accordijng to what is free.</entry>
188         </row><row>
189         <entry>VFL_TYPE_GRABBER</><entry>/dev/video{n}</><entry>
190         Video capture devices and also -- counter-intuitively for the name --
191         hardware video playback devices such as MPEG2 cards.</entry>
192         </row><row>
193         <entry>VFL_TYPE_VBI</><entry>/dev/vbi{n}</><entry>
194         The VBI devices capture the hidden lines on a television picture
195         that carry further information like closed caption data, teletext
196         (primarily in Europe) and now Intercast and the ATVEC internet
197         television encodings.</entry>
198         </row><row>
199         <entry>VFL_TYPE_VTX</><entry>/dev/vtx[n}</><entry>
200         VTX is 'Videotext' also known as 'Teletext'. This is a system for
201         sending numbered, 40x25, mostly textual page images over the hidden
202         lines. Unlike the /dev/vbi interfaces, this is for 'smart' decoder 
203         chips. (The use of the word smart here has to be taken in context,
204         the smartest teletext chips are fairly dumb pieces of technology).
205         </entry>
206     </row>
207     </tbody>
208     </tgroup>
209     </table>
210   <para>
211         We are most definitely a radio.
212   </para>
213   <para>
214         Finally we allocate our I/O space so that nobody treads on us and return 0
215         to signify general happiness with the state of the universe.
216   </para>
217   </sect1>
218   <sect1 id="openradio">
219   <title>Opening And Closing The Radio</title>
220
221   <para>
222         The functions we declared in our video_device are mostly very simple.
223         Firstly we can drop in what is basically standard code for open and close. 
224   </para>
225   <programlisting>
226
227
228 static int users = 0;
229
230 static int radio_open(stuct video_device *dev, int flags)
231 {
232         if(users)
233                 return -EBUSY;
234         users++;
235         return 0;
236 }
237
238   </programlisting>
239   <para>
240         At open time we need to do nothing but check if someone else is also using
241         the radio card. If nobody is using it we make a note that we are using it,
242         then we ensure that nobody unloads our driver on us.
243   </para>
244   <programlisting>
245
246
247 static int radio_close(struct video_device *dev)
248 {
249         users--;
250 }
251
252   </programlisting>
253   <para>
254         At close time we simply need to reduce the user count and allow the module
255         to become unloadable.
256   </para>
257   <para>
258         If you are sharp you will have noticed neither the open nor the close
259         routines attempt to reset or change the radio settings. This is intentional.
260         It allows an application to set up the radio and exit. It avoids a user
261         having to leave an application running all the time just to listen to the
262         radio. 
263   </para>
264   </sect1>
265   <sect1 id="ioctlradio">
266   <title>The Ioctl Interface</title>
267   <para>
268         This leaves the ioctl routine, without which the driver will not be
269         terribly useful to anyone.
270   </para>
271   <programlisting>
272
273
274 static int radio_ioctl(struct video_device *dev, unsigned int cmd, void *arg)
275 {
276         switch(cmd)
277         {
278                 case VIDIOCGCAP:
279                 {
280                         struct video_capability v;
281                         v.type = VID_TYPE_TUNER;
282                         v.channels = 1;
283                         v.audios = 1;
284                         v.maxwidth = 0;
285                         v.minwidth = 0;
286                         v.maxheight = 0;
287                         v.minheight = 0;
288                         strcpy(v.name, "My Radio");
289                         if(copy_to_user(arg, &amp;v, sizeof(v)))
290                                 return -EFAULT;
291                         return 0;
292                 }
293
294   </programlisting>
295   <para>
296         VIDIOCGCAP is the first ioctl all video4linux devices must support. It
297         allows the applications to find out what sort of a card they have found and
298         to figure out what they want to do about it. The fields in the structure are
299   </para>
300    <table frame="all"><title>struct video_capability fields</title>
301    <tgroup cols="2" align="left">
302    <tbody>
303    <row>
304         <entry>name</><entry>The device text name. This is intended for the user.</>
305         </row><row>
306         <entry>channels</><entry>The number of different channels you can tune on
307                         this card. It could even by zero for a card that has
308                         no tuning capability. For our simple FM radio it is 1. 
309                         An AM/FM radio would report 2.</entry>
310         </row><row>
311         <entry>audios</><entry>The number of audio inputs on this device. For our
312                         radio there is only one audio input.</entry>
313         </row><row>
314         <entry>minwidth,minheight</><entry>The smallest size the card is capable of capturing
315                         images in. We set these to zero. Radios do not
316                         capture pictures</entry>
317         </row><row>
318         <entry>maxwidth,maxheight</><entry>The largest image size the card is capable of
319                                       capturing. For our radio we report 0.
320                                 </entry>
321         </row><row>
322         <entry>type</><entry>This reports the capabilities of the device, and
323                         matches the field we filled in in the struct
324                         video_device when registering.</entry>
325     </row>
326     </tbody>
327     </tgroup>
328     </table>
329   <para>
330         Having filled in the fields, we use copy_to_user to copy the structure into
331         the users buffer. If the copy fails we return an EFAULT to the application
332         so that it knows it tried to feed us garbage.
333   </para>
334   <para>
335         The next pair of ioctl operations select which tuner is to be used and let
336         the application find the tuner properties. We have only a single FM band
337         tuner in our example device.
338   </para>
339   <programlisting>
340
341
342                 case VIDIOCGTUNER:
343                 {
344                         struct video_tuner v;
345                         if(copy_from_user(&amp;v, arg, sizeof(v))!=0)
346                                 return -EFAULT;
347                         if(v.tuner)
348                                 return -EINVAL;
349                         v.rangelow=(87*16000);
350                         v.rangehigh=(108*16000);
351                         v.flags = VIDEO_TUNER_LOW;
352                         v.mode = VIDEO_MODE_AUTO;
353                         v.signal = 0xFFFF;
354                         strcpy(v.name, "FM");
355                         if(copy_to_user(&amp;v, arg, sizeof(v))!=0)
356                                 return -EFAULT;
357                         return 0;
358                 }
359
360   </programlisting>
361   <para>
362         The VIDIOCGTUNER ioctl allows applications to query a tuner. The application
363         sets the tuner field to the tuner number it wishes to query. The query does
364         not change the tuner that is being used, it merely enquires about the tuner
365         in question.
366   </para>
367   <para>
368         We have exactly one tuner so after copying the user buffer to our temporary
369         structure we complain if they asked for a tuner other than tuner 0. 
370   </para>
371   <para>
372         The video_tuner structure has the following fields
373   </para>
374    <table frame="all"><title>struct video_tuner fields</title>
375    <tgroup cols="2" align="left">
376    <tbody>
377    <row>
378         <entry>int tuner</><entry>The number of the tuner in question</entry>
379    </row><row>
380         <entry>char name[32]</><entry>A text description of this tuner. "FM" will do fine.
381                         This is intended for the application.</entry>
382    </row><row>
383         <entry>u32 flags</>
384         <entry>Tuner capability flags</entry>
385    </row>
386    <row>
387         <entry>u16 mode</><entry>The current reception mode</entry>
388
389    </row><row>
390         <entry>u16 signal</><entry>The signal strength scaled between 0 and 65535. If
391                         a device cannot tell the signal strength it should
392                         report 65535. Many simple cards contain only a 
393                         signal/no signal bit. Such cards will report either
394                         0 or 65535.</entry>
395
396    </row><row>
397         <entry>u32 rangelow, rangehigh</><entry>
398                         The range of frequencies supported by the radio
399                         or TV. It is scaled according to the VIDEO_TUNER_LOW
400                         flag.</entry>
401
402     </row>
403     </tbody>
404     </tgroup>
405     </table>
406
407    <table frame="all"><title>struct video_tuner flags</title>
408    <tgroup cols="2" align="left">
409    <tbody>
410    <row>
411         <entry>VIDEO_TUNER_PAL</><entry>A PAL TV tuner</entry>
412         </row><row>
413         <entry>VIDEO_TUNER_NTSC</><entry>An NTSC (US) TV tuner</entry>
414         </row><row>
415         <entry>VIDEO_TUNER_SECAM</><entry>A SECAM (French) TV tuner</entry>
416         </row><row>
417         <entry>VIDEO_TUNER_LOW</><entry>
418              The tuner frequency is scaled in 1/16th of a KHz
419              steps. If not it is in 1/16th of a MHz steps
420         </entry>
421         </row><row>
422         <entry>VIDEO_TUNER_NORM</><entry>The tuner can set its format</entry>
423         </row><row>
424         <entry>VIDEO_TUNER_STEREO_ON</><entry>The tuner is currently receiving a stereo signal</entry>
425         </row>
426     </tbody>
427     </tgroup>
428     </table>
429
430    <table frame="all"><title>struct video_tuner modes</title>
431    <tgroup cols="2" align="left">
432    <tbody>
433    <row>
434                 <entry>VIDEO_MODE_PAL</><entry>PAL Format</entry>
435    </row><row>
436                 <entry>VIDEO_MODE_NTSC</><entry>NTSC Format (USA)</entry>
437    </row><row>
438                 <entry>VIDEO_MODE_SECAM</><entry>French Format</entry>
439    </row><row>
440                 <entry>VIDEO_MODE_AUTO</><entry>A device that does not need to do
441                                         TV format switching</entry>
442    </row>
443     </tbody>
444     </tgroup>
445     </table>
446   <para>
447         The settings for the radio card are thus fairly simple. We report that we
448         are a tuner called "FM" for FM radio. In order to get the best tuning
449         resolution we report VIDEO_TUNER_LOW and select tuning to 1/16th of KHz. Its
450         unlikely our card can do that resolution but it is a fair bet the card can
451         do better than 1/16th of a MHz. VIDEO_TUNER_LOW is appropriate to almost all
452         radio usage.
453   </para>
454   <para>
455         We report that the tuner automatically handles deciding what format it is
456         receiving - true enough as it only handles FM radio. Our example card is
457         also incapable of detecting stereo or signal strengths so it reports a
458         strength of 0xFFFF (maximum) and no stereo detected.
459   </para>
460   <para>
461         To finish off we set the range that can be tuned to be 87-108Mhz, the normal
462         FM broadcast radio range. It is important to find out what the card is
463         actually capable of tuning. It is easy enough to simply use the FM broadcast
464         range. Unfortunately if you do this you will discover the FM broadcast
465         ranges in the USA, Europe and Japan are all subtly different and some users
466         cannot receive all the stations they wish.
467   </para>
468   <para>
469         The application also needs to be able to set the tuner it wishes to use. In
470         our case, with a single tuner this is rather simple to arrange.
471   </para>
472   <programlisting>
473
474                 case VIDIOCSTUNER:
475                 {
476                         struct video_tuner v;
477                         if(copy_from_user(&amp;v, arg, sizeof(v)))
478                                 return -EFAULT;
479                         if(v.tuner != 0)
480                                 return -EINVAL;
481                         return 0;
482                 }
483
484   </programlisting>
485   <para>
486         We copy the user supplied structure into kernel memory so we can examine it. 
487         If the user has selected a tuner other than zero we reject the request. If 
488         they wanted tuner 0 then, surprisingly enough, that is the current tuner already.
489   </para>
490   <para>
491         The next two ioctls we need to provide are to get and set the frequency of
492         the radio. These both use an unsigned long argument which is the frequency.
493         The scale of the frequency depends on the VIDEO_TUNER_LOW flag as I
494         mentioned earlier on. Since we have VIDEO_TUNER_LOW set this will be in
495         1/16ths of a KHz.
496   </para>
497   <programlisting>
498
499 static unsigned long current_freq;
500
501
502
503                 case VIDIOCGFREQ:
504                         if(copy_to_user(arg, &amp;current_freq, 
505                                 sizeof(unsigned long))
506                                 return -EFAULT;
507                         return 0;
508
509   </programlisting>
510   <para>
511         Querying the frequency in our case is relatively simple. Our radio card is
512         too dumb to let us query the signal strength so we remember our setting if 
513         we know it. All we have to do is copy it to the user.
514   </para>
515   <programlisting>
516
517
518                 case VIDIOCSFREQ:
519                 {
520                         u32 freq;
521                         if(copy_from_user(arg, &amp;freq, 
522                                 sizeof(unsigned long))!=0)
523                                 return -EFAULT;
524                         if(hardware_set_freq(freq)<0)
525                                 return -EINVAL;
526                         current_freq = freq;
527                         return 0;
528                 }
529
530   </programlisting>
531   <para>
532         Setting the frequency is a little more complex. We begin by copying the
533         desired frequency into kernel space. Next we call a hardware specific routine
534         to set the radio up. This might be as simple as some scaling and a few
535         writes to an I/O port. For most radio cards it turns out a good deal more
536         complicated and may involve programming things like a phase locked loop on
537         the card. This is what documentation is for. 
538   </para>
539   <para>
540         The final set of operations we need to provide for our radio are the 
541         volume controls. Not all radio cards can even do volume control. After all
542         there is a perfectly good volume control on the sound card. We will assume
543         our radio card has a simple 4 step volume control.
544   </para>
545   <para>
546         There are two ioctls with audio we need to support
547   </para>
548   <programlisting>
549
550 static int current_volume=0;
551
552                 case VIDIOCGAUDIO:
553                 {
554                         struct video_audio v;
555                         if(copy_from_user(&amp;v, arg, sizeof(v)))
556                                 return -EFAULT;
557                         if(v.audio != 0)
558                                 return -EINVAL;
559                         v.volume = 16384*current_volume;
560                         v.step = 16384;
561                         strcpy(v.name, "Radio");
562                         v.mode = VIDEO_SOUND_MONO;
563                         v.balance = 0;
564                         v.base = 0;
565                         v.treble = 0;
566                         
567                         if(copy_to_user(arg. &amp;v, sizeof(v)))
568                                 return -EFAULT;
569                         return 0;
570                 }
571
572   </programlisting>
573   <para>
574         Much like the tuner we start by copying the user structure into kernel
575         space. Again we check if the user has asked for a valid audio input. We have
576         only input 0 and we punt if they ask for another input.
577   </para>
578   <para>
579         Then we fill in the video_audio structure. This has the following format
580   </para>
581    <table frame="all"><title>struct video_audio fields</title>
582    <tgroup cols="2" align="left">
583    <tbody>
584    <row>
585    <entry>audio</><entry>The input the user wishes to query</>
586    </row><row>
587    <entry>volume</><entry>The volume setting on a scale of 0-65535</>
588    </row><row>
589    <entry>base</><entry>The base level on a scale of 0-65535</>
590    </row><row>
591    <entry>treble</><entry>The treble level on a scale of 0-65535</>
592    </row><row>
593    <entry>flags</><entry>The features this audio device supports
594    </entry>
595    </row><row>
596    <entry>name</><entry>A text name to display to the user. We picked 
597                         "Radio" as it explains things quite nicely.</>
598    </row><row>
599    <entry>mode</><entry>The current reception mode for the audio
600
601                 We report MONO because our card is too stupid to know if it is in
602                 mono or stereo. 
603    </entry>
604    </row><row>
605    <entry>balance</><entry>The stereo balance on a scale of 0-65535, 32768 is
606                         middle.</>
607    </row><row>
608    <entry>step</><entry>The step by which the volume control jumps. This is
609                         used to help make it easy for applications to set 
610                         slider behaviour.</>   
611    </row>
612    </tbody>
613    </tgroup>
614    </table>
615
616    <table frame="all"><title>struct video_audio flags</title>
617    <tgroup cols="2" align="left">
618    <tbody>
619    <row>
620                 <entry>VIDEO_AUDIO_MUTE</><entry>The audio is currently muted. We
621                                         could fake this in our driver but we
622                                         choose not to bother.</entry>
623    </row><row>
624                 <entry>VIDEO_AUDIO_MUTABLE</><entry>The input has a mute option</entry>
625    </row><row>
626                 <entry>VIDEO_AUDIO_TREBLE</><entry>The  input has a treble control</entry>
627    </row><row>
628                 <entry>VIDEO_AUDIO_BASS</><entry>The input has a base control</entry>
629    </row>
630    </tbody>
631    </tgroup>
632    </table>
633
634    <table frame="all"><title>struct video_audio modes</title>
635    <tgroup cols="2" align="left">
636    <tbody>
637    <row>
638                 <entry>VIDEO_SOUND_MONO</><entry>Mono sound</entry>
639    </row><row>
640                 <entry>VIDEO_SOUND_STEREO</><entry>Stereo sound</entry>
641    </row><row>
642                 <entry>VIDEO_SOUND_LANG1</><entry>Alternative language 1 (TV specific)</entry>
643    </row><row>
644                 <entry>VIDEO_SOUND_LANG2</><entry>Alternative language 2 (TV specific)</entry>
645    </row>
646    </tbody>
647    </tgroup>
648    </table>
649   <para>
650         Having filled in the structure we copy it back to user space.
651   </para>
652   <para>
653         The VIDIOCSAUDIO ioctl allows the user to set the audio parameters in the
654         video_audio structure. The driver does its best to honour the request.
655   </para>
656   <programlisting>
657
658                 case VIDIOCSAUDIO:
659                 {
660                         struct video_audio v;
661                         if(copy_from_user(&amp;v, arg, sizeof(v)))
662                                 return -EFAULT;
663                         if(v.audio)
664                                 return -EINVAL;
665                         current_volume = v/16384;
666                         hardware_set_volume(current_volume);
667                         return 0;
668                 }
669
670   </programlisting>
671   <para>
672         In our case there is very little that the user can set. The volume is
673         basically the limit. Note that we could pretend to have a mute feature
674         by rewriting this to 
675   </para>
676   <programlisting>
677
678                 case VIDIOCSAUDIO:
679                 {
680                         struct video_audio v;
681                         if(copy_from_user(&amp;v, arg, sizeof(v)))
682                                 return -EFAULT;
683                         if(v.audio)
684                                 return -EINVAL;
685                         current_volume = v/16384;
686                         if(v.flags&amp;VIDEO_AUDIO_MUTE)
687                                 hardware_set_volume(0);
688                         else
689                                 hardware_set_volume(current_volume);
690                         current_muted = v.flags &amp; 
691                                               VIDEO_AUDIO_MUTE;
692                         return 0;
693                 }
694
695   </programlisting>
696   <para>
697         This with the corresponding changes to the VIDIOCGAUDIO code to report the
698         state of the mute flag we save and to report the card has a mute function,
699         will allow applications to use a mute facility with this card. It is
700         questionable whether this is a good idea however. User applications can already
701         fake this themselves and kernel space is precious.
702   </para>
703   <para>
704         We now have a working radio ioctl handler. So we just wrap up the function
705   </para>
706   <programlisting>
707
708
709         }
710         return -ENOIOCTLCMD;
711 }
712
713   </programlisting>
714   <para>
715         and pass the Video4Linux layer back an error so that it knows we did not
716         understand the request we got passed.
717   </para>
718   </sect1>
719   <sect1 id="modradio">
720   <title>Module Wrapper</title>
721   <para>
722         Finally we add in the usual module wrapping and the driver is done.
723   </para>
724   <programlisting>
725
726 #ifndef MODULE
727
728 static int io = 0x300;
729
730 #else
731
732 static int io = -1;
733
734
735 MODULE_AUTHOR("Alan Cox");
736 MODULE_DESCRIPTION("A driver for an imaginary radio card.");
737 MODULE_PARM(io, "i");
738 MODULE_PARM_DESC(io, "I/O address of the card.");
739
740 int init_module(void)
741 {
742         if(io==-1)
743         {
744                 printk(KERN_ERR 
745          "You must set an I/O address with io=0x???\n");
746                 return -EINVAL;
747         }
748         return myradio_init(NULL);
749 }
750
751 void cleanup_module(void)
752 {
753         video_unregister_device(&amp;my_radio);
754         release_region(io, MY_IO_SIZE);
755 }
756
757 #endif
758
759   </programlisting>
760   <para>
761         In this example we set the IO base by default if the driver is compiled into
762         the kernel where you cannot pass a parameter. For the module we require the
763         user sets the parameter. We set io to a nonsense port (-1) so that we can
764         tell if the user supplied an io parameter or not.
765   </para>
766   <para>
767         We use MODULE_ defines to give an author for the card driver and a
768         description. We also use them to declare that io is an integer and it is the
769         address of the card.
770   </para>
771   <para>
772         The clean-up routine unregisters the video_device we registered, and frees
773         up the I/O space. Note that the unregister takes the actual video_device
774         structure as its argument. Unlike the file operations structure which can be
775         shared by all instances of a device a video_device structure as an actual
776         instance of the device. If you are registering multiple radio devices you
777         need to fill in one structure per device (most likely by setting up a
778         template and copying it to each of the actual device structures).
779   </para>
780   </sect1>
781   </chapter>
782   <chapter>
783         <title>Video Capture Devices</title>
784   <sect1 id="introvid">
785   <title>Video Capture Device Types</title>
786   <para>
787         The video capture devices share the same interfaces as radio devices. In
788         order to explain the video capture interface I will use the example of a
789         camera that has no tuners or audio input. This keeps the example relatively
790         clean. To get both combine the two driver examples.
791   </para>
792   <para>
793         Video capture devices divide into four categories. A little technology
794         backgrounder. Full motion video even at television resolution (which is
795         actually fairly low) is pretty resource-intensive. You are continually
796         passing megabytes of data every second from the capture card to the display. 
797         several alternative approaches have emerged because copying this through the 
798         processor and the user program is a particularly bad idea .
799   </para>
800   <para>
801         The first is to add the television image onto the video output directly.
802         This is also how some 3D cards work. These basic cards can generally drop the
803         video into any chosen rectangle of the display. Cards like this, which
804         include most mpeg1 cards that used the feature connector,  aren't very
805         friendly in a windowing environment. They don't understand windows or
806         clipping. The video window is always on the top of the display.
807   </para>
808   <para>
809         Chroma keying is a technique used by cards to get around this. It is an old
810         television mixing trick where you mark all the areas you wish to replace
811         with a single clear colour that isn't used in the image - TV people use an
812         incredibly bright blue while computing people often use a particularly
813         virulent purple. Bright blue occurs on the desktop. Anyone with virulent
814         purple windows has another problem besides their TV overlay.
815   </para>
816   <para>
817         The third approach is to copy the data from the capture card to the video
818         card, but to do it directly across the PCI bus. This relieves the processor
819         from doing the work but does require some smartness on the part of the video
820         capture chip, as well as a suitable video card. Programming this kind of
821         card and more so debugging it can be extremely tricky. There are some quite
822         complicated interactions with the display and you may also have to cope with
823         various chipset bugs that show up when PCI cards start talking to each
824         other. 
825   </para>
826   <para>
827         To keep our example fairly simple we will assume a card that supports
828         overlaying a flat rectangular image onto the frame buffer output, and which
829         can also capture stuff into processor memory.
830   </para>
831   </sect1>
832   <sect1 id="regvid">
833   <title>Registering Video Capture Devices</title>
834   <para>
835         This time we need to add more functions for our camera device.
836   </para>
837   <programlisting>
838 static struct video_device my_camera
839 {
840         "My Camera",
841         VID_TYPE_OVERLAY|VID_TYPE_SCALES|\
842         VID_TYPE_CAPTURE|VID_TYPE_CHROMAKEY,
843         VID_HARDWARE_MYCAMERA,
844         camera_open.
845         camera_close,
846         camera_read,      /* no read */
847         NULL,             /* no write */
848         camera_poll,      /* no poll */
849         camera_ioctl,
850         NULL,             /* no special init function */
851         NULL              /* no private data */
852 };
853   </programlisting>
854   <para>
855         We need a read() function which is used for capturing data from
856         the card, and we need a poll function so that a driver can wait for the next
857         frame to be captured.
858   </para>
859   <para>
860         We use the extra video capability flags that did not apply to the
861         radio interface. The video related flags are
862   </para>
863    <table frame="all"><title>Capture Capabilities</title>
864    <tgroup cols="2" align="left">
865    <tbody>
866    <row>
867 <entry>VID_TYPE_CAPTURE</><entry>We support image capture</>
868 </row><row>
869 <entry>VID_TYPE_TELETEXT</><entry>A teletext capture device (vbi{n])</>
870 </row><row>
871 <entry>VID_TYPE_OVERLAY</><entry>The image can be directly overlaid onto the
872                                 frame buffer</>
873 </row><row>
874 <entry>VID_TYPE_CHROMAKEY</><entry>Chromakey can be used to select which parts
875                                 of the image to display</>
876 </row><row>
877 <entry>VID_TYPE_CLIPPING</><entry>It is possible to give the board a list of
878                                 rectangles to draw around. </>
879 </row><row>
880 <entry>VID_TYPE_FRAMERAM</><entry>The video capture goes into the video memory
881                                 and actually changes it. Applications need
882                                 to know this so they can clean up after the
883                                 card</>
884 </row><row>
885 <entry>VID_TYPE_SCALES</><entry>The image can be scaled to various sizes,
886                                 rather than being a single fixed size.</>
887 </row><row>
888 <entry>VID_TYPE_MONOCHROME</><entry>The capture will be monochrome. This isn't a 
889                                 complete answer to the question since a mono
890                                 camera on a colour capture card will still
891                                 produce mono output.</>
892 </row><row>
893 <entry>VID_TYPE_SUBCAPTURE</><entry>The card allows only part of its field of
894                                 view to be captured. This enables
895                                 applications to avoid copying all of a large
896                                 image into memory when only some section is
897                                 relevant.</>
898     </row>
899     </tbody>
900     </tgroup>
901     </table>
902   <para>
903         We set VID_TYPE_CAPTURE so that we are seen as a capture card,
904         VID_TYPE_CHROMAKEY so the application knows it is time to draw in virulent
905         purple, and VID_TYPE_SCALES because we can be resized.
906   </para>
907   <para>
908         Our setup is fairly similar. This time we also want an interrupt line
909         for the 'frame captured' signal. Not all cards have this so some of them
910         cannot handle poll().
911   </para>
912   <programlisting>
913
914
915 static int io = 0x320;
916 static int irq = 11;
917
918 int __init mycamera_init(struct video_init *v)
919 {
920         if(!request_region(io, MY_IO_SIZE, "mycamera"))
921         {
922                 printk(KERN_ERR 
923                       "mycamera: port 0x%03X is in use.\n", io);
924                 return -EBUSY;
925         }
926
927         if(video_device_register(&amp;my_camera, 
928             VFL_TYPE_GRABBER)==-1) {
929                 release_region(io, MY_IO_SIZE);
930                 return -EINVAL;
931         }
932         return 0;
933 }
934
935   </programlisting>
936   <para>
937         This is little changed from the needs of the radio card. We specify
938         VFL_TYPE_GRABBER this time as we want to be allocated a /dev/video name.
939   </para>
940   </sect1>
941   <sect1 id="opvid">
942   <title>Opening And Closing The Capture Device</title>
943   <programlisting>
944
945
946 static int users = 0;
947
948 static int camera_open(stuct video_device *dev, int flags)
949 {
950         if(users)
951                 return -EBUSY;
952         if(request_irq(irq, camera_irq, 0, "camera", dev)&lt;0)
953                 return -EBUSY;
954         users++;
955         return 0;
956 }
957
958
959 static int camera_close(struct video_device *dev)
960 {
961         users--;
962         free_irq(irq, dev);
963 }
964   </programlisting>
965   <para>
966         The open and close routines are also quite similar. The only real change is
967         that we now request an interrupt for the camera device interrupt line. If we
968         cannot get the interrupt we report EBUSY to the application and give up.
969   </para>
970   </sect1>
971   <sect1 id="irqvid">
972   <title>Interrupt Handling</title>
973   <para>
974         Our example handler is for an ISA bus device. If it was PCI you would be
975         able to share the interrupt and would have set SA_SHIRQ to indicate a 
976         shared IRQ. We pass the device pointer as the interrupt routine argument. We
977         don't need to since we only support one card but doing this will make it
978         easier to upgrade the driver for multiple devices in the future.
979   </para>
980   <para>
981         Our interrupt routine needs to do little if we assume the card can simply
982         queue one frame to be read after it captures it. 
983   </para>
984   <programlisting>
985
986
987 static struct wait_queue *capture_wait;
988 static int capture_ready = 0;
989
990 static void camera_irq(int irq, void *dev_id, 
991                           struct pt_regs *regs)
992 {
993         capture_ready=1;
994         wake_up_interruptible(&amp;capture_wait);
995 }
996   </programlisting>
997   <para>
998         The interrupt handler is nice and simple for this card as we are assuming
999         the card is buffering the frame for us. This means we have little to do but
1000         wake up        anybody interested. We also set a capture_ready flag, as we may
1001         capture a frame before an application needs it. In this case we need to know
1002         that a frame is ready. If we had to collect the frame on the interrupt life
1003         would be more complex.
1004   </para>
1005   <para>
1006         The two new routines we need to supply are camera_read which returns a
1007         frame, and camera_poll which waits for a frame to become ready.
1008   </para>
1009   <programlisting>
1010
1011
1012 static int camera_poll(struct video_device *dev, 
1013         struct file *file, struct poll_table *wait)
1014 {
1015         poll_wait(file, &amp;capture_wait, wait);
1016         if(capture_read)
1017                 return POLLIN|POLLRDNORM;
1018         return 0;
1019 }
1020
1021   </programlisting>
1022   <para>
1023         Our wait queue for polling is the capture_wait queue. This will cause the
1024         task to be woken up by our camera_irq routine. We check capture_read to see
1025         if there is an image present and if so report that it is readable.
1026   </para>
1027   </sect1>
1028   <sect1 id="rdvid">
1029   <title>Reading The Video Image</title>
1030   <programlisting>
1031
1032
1033 static long camera_read(struct video_device *dev, char *buf,
1034                                 unsigned long count)
1035 {
1036         struct wait_queue wait = { current, NULL };
1037         u8 *ptr;
1038         int len;
1039         int i;
1040
1041         add_wait_queue(&amp;capture_wait, &amp;wait);
1042
1043         while(!capture_ready)
1044         {
1045                 if(file->flags&amp;O_NDELAY)
1046                 {
1047                         remove_wait_queue(&amp;capture_wait, &amp;wait);
1048                         current->state = TASK_RUNNING;
1049                         return -EWOULDBLOCK;
1050                 }
1051                 if(signal_pending(current))
1052                 {
1053                         remove_wait_queue(&amp;capture_wait, &amp;wait);
1054                         current->state = TASK_RUNNING;
1055                         return -ERESTARTSYS;
1056                 }
1057                 schedule();
1058                 current->state = TASK_INTERRUPTIBLE;
1059         }
1060         remove_wait_queue(&amp;capture_wait, &amp;wait);
1061         current->state = TASK_RUNNING;
1062
1063   </programlisting>
1064   <para>
1065         The first thing we have to do is to ensure that the application waits until
1066         the next frame is ready. The code here is almost identical to the mouse code
1067         we used earlier in this chapter. It is one of the common building blocks of
1068         Linux device driver code and probably one which you will find occurs in any
1069         drivers you write.
1070   </para>
1071   <para>
1072         We wait for a frame to be ready, or for a signal to interrupt our waiting. If a
1073         signal occurs we need to return from the system call so that the signal can
1074         be sent to the application itself. We also check to see if the user actually
1075         wanted to avoid waiting - ie  if they are using non-blocking I/O and have other things 
1076         to get on with.
1077   </para>
1078   <para>
1079         Next we copy the data from the card to the user application. This is rarely
1080         as easy as our example makes out. We will add capture_w, and capture_h here
1081         to hold the width and height of the captured image. We assume the card only
1082         supports 24bit RGB for now.
1083   </para>
1084   <programlisting>
1085
1086
1087
1088         capture_ready = 0;
1089
1090         ptr=(u8 *)buf;
1091         len = capture_w * 3 * capture_h; /* 24bit RGB */
1092
1093         if(len>count)
1094                 len=count;  /* Doesn't all fit */
1095
1096         for(i=0; i&lt;len; i++)
1097         {
1098                 put_user(inb(io+IMAGE_DATA), ptr);
1099                 ptr++;
1100         }
1101
1102         hardware_restart_capture();
1103                 
1104         return i;
1105 }
1106
1107   </programlisting>
1108   <para>
1109         For a real hardware device you would try to avoid the loop with put_user().
1110         Each call to put_user() has a time overhead checking whether the accesses to user
1111         space are allowed. It would be better to read a line into a temporary buffer
1112         then copy this to user space in one go.
1113   </para>
1114   <para>
1115         Having captured the image and put it into user space we can kick the card to
1116         get the next frame acquired.
1117   </para>
1118   </sect1>
1119   <sect1 id="iocvid">
1120   <title>Video Ioctl Handling</title>
1121   <para>
1122         As with the radio driver the major control interface is via the ioctl()
1123         function. Video capture devices support the same tuner calls as a radio
1124         device and also support additional calls to control how the video functions
1125         are handled. In this simple example the card has no tuners to avoid making
1126         the code complex. 
1127   </para>
1128   <programlisting>
1129
1130
1131
1132 static int camera_ioctl(struct video_device *dev, unsigned int cmd, void *arg)
1133 {
1134         switch(cmd)
1135         {
1136                 case VIDIOCGCAP:
1137                 {
1138                         struct video_capability v;
1139                         v.type = VID_TYPE_CAPTURE|\
1140                                  VID_TYPE_CHROMAKEY|\
1141                                  VID_TYPE_SCALES|\
1142                                  VID_TYPE_OVERLAY;
1143                         v.channels = 1;
1144                         v.audios = 0;
1145                         v.maxwidth = 640;
1146                         v.minwidth = 16;
1147                         v.maxheight = 480;
1148                         v.minheight = 16;
1149                         strcpy(v.name, "My Camera");
1150                         if(copy_to_user(arg, &amp;v, sizeof(v)))
1151                                 return -EFAULT;
1152                         return 0;
1153                 }
1154
1155
1156   </programlisting>
1157   <para>
1158         The first ioctl we must support and which all video capture and radio
1159         devices are required to support is VIDIOCGCAP. This behaves exactly the same
1160         as with a radio device. This time, however, we report the extra capabilities
1161         we outlined earlier on when defining our video_dev structure.
1162   </para>
1163   <para>
1164         We now set the video flags saying that we support overlay, capture,
1165         scaling and chromakey. We also report size limits - our smallest image is
1166         16x16 pixels, our largest is 640x480. 
1167   </para>
1168   <para>
1169         To keep things simple we report no audio and no tuning capabilities at all.
1170   </para>
1171   <programlisting>        
1172
1173                 case VIDIOCGCHAN:
1174                 {
1175                         struct video_channel v;
1176                         if(copy_from_user(&amp;v, arg, sizeof(v)))
1177                                 return -EFAULT;
1178                         if(v.channel != 0)
1179                                 return -EINVAL;
1180                         v.flags = 0;
1181                         v.tuners = 0;
1182                         v.type = VIDEO_TYPE_CAMERA;
1183                         v.norm = VIDEO_MODE_AUTO;
1184                         strcpy(v.name, "Camera Input");break;
1185                         if(copy_to_user(&amp;v, arg, sizeof(v)))
1186                                 return -EFAULT;
1187                         return 0;
1188                 }
1189
1190
1191   </programlisting>
1192   <para>
1193         This follows what is very much the standard way an ioctl handler looks
1194         in Linux. We copy the data into a kernel space variable and we check that the
1195         request is valid (in this case that the input is 0). Finally we copy the
1196         camera info back to the user.
1197   </para>
1198   <para>
1199         The VIDIOCGCHAN ioctl allows a user to ask about video channels (that is
1200         inputs to the video card). Our example card has a single camera input. The
1201         fields in the structure are
1202   </para>
1203    <table frame="all"><title>struct video_channel fields</title>
1204    <tgroup cols="2" align="left">
1205    <tbody>
1206    <row>
1207
1208    <entry>channel</><entry>The channel number we are selecting</entry>
1209    </row><row>
1210    <entry>name</><entry>The name for this channel. This is intended
1211                    to describe the port to the user.
1212                    Appropriate names are therefore things like
1213                    "Camera" "SCART input"</entry>
1214    </row><row>
1215    <entry>flags</><entry>Channel properties</entry>
1216    </row><row>
1217    <entry>type</><entry>Input type</entry>
1218    </row><row>
1219    <entry>norm</><entry>The current television encoding being used
1220                    if relevant for this channel.
1221     </entry>
1222     </row>
1223     </tbody>
1224     </tgroup>
1225     </table>
1226     <table frame="all"><title>struct video_channel flags</title>
1227     <tgroup cols="2" align="left">
1228     <tbody>
1229     <row>
1230         <entry>VIDEO_VC_TUNER</><entry>Channel has a tuner.</entry>
1231    </row><row>
1232         <entry>VIDEO_VC_AUDIO</><entry>Channel has audio.</entry>
1233     </row>
1234     </tbody>
1235     </tgroup>
1236     </table>
1237     <table frame="all"><title>struct video_channel types</title>
1238     <tgroup cols="2" align="left">
1239     <tbody>
1240     <row>
1241         <entry>VIDEO_TYPE_TV</><entry>Television input.</entry>
1242    </row><row>
1243         <entry>VIDEO_TYPE_CAMERA</><entry>Fixed camera input.</entry>
1244    </row><row>
1245         <entry>0</><entry>Type is unknown.</entry>
1246     </row>
1247     </tbody>
1248     </tgroup>
1249     </table>
1250     <table frame="all"><title>struct video_channel norms</title>
1251     <tgroup cols="2" align="left">
1252     <tbody>
1253     <row>
1254         <entry>VIDEO_MODE_PAL</><entry>PAL encoded Television</entry>
1255    </row><row>
1256         <entry>VIDEO_MODE_NTSC</><entry>NTSC (US) encoded Television</entry>
1257    </row><row>
1258         <entry>VIDEO_MODE_SECAM</><entry>SECAM (French) Television </entry>
1259    </row><row>
1260         <entry>VIDEO_MODE_AUTO</><entry>Automatic switching, or format does not
1261                                 matter</entry>
1262     </row>
1263     </tbody>
1264     </tgroup>
1265     </table>
1266     <para>
1267         The corresponding VIDIOCSCHAN ioctl allows a user to change channel and to
1268         request the norm is changed - for example to switch between a PAL or an NTSC
1269         format camera.
1270   </para>
1271   <programlisting>
1272
1273
1274                 case VIDIOCSCHAN:
1275                 {
1276                         struct video_channel v;
1277                         if(copy_from_user(&amp;v, arg, sizeof(v)))
1278                                 return -EFAULT;
1279                         if(v.channel != 0)
1280                                 return -EINVAL;
1281                         if(v.norm != VIDEO_MODE_AUTO)
1282                                 return -EINVAL;
1283                         return 0;
1284                 }
1285
1286
1287   </programlisting>
1288   <para>
1289         The implementation of this call in our driver is remarkably easy. Because we
1290         are assuming fixed format hardware we need only check that the user has not
1291         tried to change anything. 
1292   </para>
1293   <para>
1294         The user also needs to be able to configure and adjust the picture they are
1295         seeing. This is much like adjusting a television set. A user application
1296         also needs to know the palette being used so that it knows how to display
1297         the image that has been captured. The VIDIOCGPICT and VIDIOCSPICT ioctl
1298         calls provide this information.
1299   </para>
1300   <programlisting>
1301
1302
1303                 case VIDIOCGPICT
1304                 {
1305                         struct video_picture v;
1306                         v.brightness = hardware_brightness();
1307                         v.hue = hardware_hue();
1308                         v.colour = hardware_saturation();
1309                         v.contrast = hardware_brightness();
1310                         /* Not settable */
1311                         v.whiteness = 32768;
1312                         v.depth = 24;           /* 24bit */
1313                         v.palette = VIDEO_PALETTE_RGB24;
1314                         if(copy_to_user(&amp;v, arg, 
1315                              sizeof(v)))
1316                                 return -EFAULT;
1317                         return 0;
1318                 }
1319
1320
1321   </programlisting>
1322   <para>
1323         The brightness, hue, color, and contrast provide the picture controls that
1324         are akin to a conventional television. Whiteness provides additional
1325         control for greyscale images. All of these values are scaled between 0-65535
1326         and have 32768 as the mid point setting. The scaling means that applications
1327         do not have to worry about the capability range of the hardware but can let
1328         it make a best effort attempt.
1329   </para>
1330   <para>
1331         Our depth is 24, as this is in bits. We will be returning RGB24 format. This
1332         has one byte of red, then one of green, then one of blue. This then repeats
1333         for every other pixel in the image. The other common formats the interface 
1334         defines are
1335   </para>
1336    <table frame="all"><title>Framebuffer Encodings</title>
1337    <tgroup cols="2" align="left">
1338    <tbody>
1339    <row>
1340    <entry>GREY</><entry>Linear greyscale. This is for simple cameras and the
1341                         like</>
1342    </row><row>
1343    <entry>RGB565</><entry>The top 5 bits hold 32 red levels, the next six bits 
1344                         hold green and the low 5 bits hold blue. </>
1345    </row><row>
1346    <entry>RGB555</><entry>The top bit is clear. The red green and blue levels
1347                         each occupy five bits.</>
1348     </row>
1349     </tbody>
1350     </tgroup>
1351     </table>
1352   <para>
1353         Additional modes are support for YUV capture formats. These are common for
1354         TV and video conferencing applications.
1355   </para>
1356   <para>
1357         The VIDIOCSPICT ioctl allows a user to set some of the picture parameters.
1358         Exactly which ones are supported depends heavily on the card itself. It is
1359         possible to support many modes and effects in software. In general doing
1360         this in the kernel is a bad idea. Video capture is a performance-sensitive
1361         application and the programs can often do better if they aren't being
1362         'helped' by an overkeen driver writer. Thus for our device we will report
1363         RGB24 only and refuse to allow a change.
1364   </para>
1365   <programlisting>
1366
1367
1368                 case VIDIOCSPICT:
1369                 {
1370                         struct video_picture v;
1371                         if(copy_from_user(&amp;v, arg, sizeof(v)))
1372                                 return -EFAULT;
1373                         if(v.depth!=24 || 
1374                            v.palette != VIDEO_PALETTE_RGB24)
1375                                 return -EINVAL;
1376                         set_hardware_brightness(v.brightness);
1377                         set_hardware_hue(v.hue);
1378                         set_hardware_saturation(v.colour);
1379                         set_hardware_brightness(v.contrast);
1380                         return 0;
1381                 }
1382
1383
1384   </programlisting>
1385   <para>
1386         We check the user has not tried to change the palette or the depth. We do
1387         not want to carry out some of the changes and then return an error. This may
1388         confuse the application which will be assuming no change occurred.
1389   </para>
1390   <para>
1391         In much the same way as you need to be able to set the picture controls to
1392         get the right capture images, many cards need to know what they are
1393         displaying onto when generating overlay output. In some cases getting this
1394         wrong even makes a nasty mess or may crash the computer. For that reason
1395         the VIDIOCSBUF ioctl used to set up the frame buffer information may well
1396         only be usable by root.
1397   </para>
1398   <para>
1399         We will assume our card is one of the old ISA devices with feature connector
1400         and only supports a couple of standard video modes. Very common for older
1401         cards although the PCI devices are way smarter than this.
1402   </para>
1403   <programlisting>
1404
1405
1406 static struct video_buffer capture_fb;
1407
1408                 case VIDIOCGFBUF:
1409                 {
1410                         if(copy_to_user(arg, &amp;capture_fb, 
1411                              sizeof(capture_fb)))
1412                                 return -EFAULT;
1413                         return 0;
1414                         
1415                 }
1416
1417
1418   </programlisting>
1419   <para>
1420         We keep the frame buffer information in the format the ioctl uses. This
1421         makes it nice and easy to work with in the ioctl calls.
1422   </para>
1423   <programlisting>
1424
1425                 case VIDIOCSFBUF:
1426                 {
1427                         struct video_buffer v;
1428
1429                         if(!capable(CAP_SYS_ADMIN))
1430                                 return -EPERM;
1431
1432                         if(copy_from_user(&amp;v, arg, sizeof(v)))
1433                                 return -EFAULT;
1434                         if(v.width!=320 &amp;&amp; v.width!=640)
1435                                 return -EINVAL;
1436                         if(v.height!=200 &amp;&amp; v.height!=240 
1437                                 &amp;&amp; v.height!=400
1438                                 &amp;&amp; v.height !=480)
1439                                 return -EINVAL;
1440                         memcpy(&amp;capture_fb, &amp;v, sizeof(v));
1441                         hardware_set_fb(&amp;v);
1442                         return 0;
1443                 }
1444
1445
1446
1447   </programlisting>
1448   <para>
1449         The capable() function checks a user has the required capability. The Linux
1450         operating system has a set of about 30 capabilities indicating privileged
1451         access to services. The default set up gives the superuser (uid 0) all of
1452         them and nobody else has any.
1453   </para>
1454   <para>
1455         We check that the user has the SYS_ADMIN capability, that is they are
1456         allowed to operate as the machine administrator. We don't want anyone but
1457         the administrator making a mess of the display.
1458   </para>
1459   <para>
1460         Next we check for standard PC video modes (320 or 640 wide with either
1461         EGA or VGA depths). If the mode is not a standard video mode we reject it as
1462         not supported by our card. If the mode is acceptable we save it so that
1463         VIDIOCFBUF will give the right answer next time it is called.  The
1464         hardware_set_fb() function is some undescribed card specific function to
1465         program the card for the desired mode.
1466   </para>
1467   <para>
1468         Before the driver can display an overlay window it needs to know where the
1469         window should be placed, and also how large it should be. If the card
1470         supports clipping it needs to know which rectangles to omit from the
1471         display. The video_window structure is used to describe the way the image 
1472         should be displayed. 
1473    </para>
1474    <table frame="all"><title>struct video_window fields</title>
1475    <tgroup cols="2" align="left">
1476    <tbody>
1477    <row>
1478         <entry>width</><entry>The width in pixels of the desired image. The card
1479                         may use a smaller size if this size is not available</>
1480         </row><row>
1481         <entry>height</><entry>The height of the image. The card may use a smaller
1482                         size if this size is not available.</>
1483         </row><row>
1484         <entry>x</><entry>   The X position of the top left of the window. This
1485                         is in pixels relative to the left hand edge of the
1486                         picture. Not all cards can display images aligned on
1487                         any pixel boundary. If the position is unsuitable
1488                         the card adjusts the image right and reduces the
1489                         width.</>
1490         </row><row>
1491         <entry>y</><entry>   The Y position of the top left of the window. This
1492                         is counted in pixels relative to the top edge of the
1493                         picture. As with the width if the card cannot
1494                         display  starting on this line it will adjust the
1495                         values.</>
1496         </row><row>
1497         <entry>chromakey</><entry>The colour (expressed in RGB32 format) for the
1498                         chromakey colour if chroma keying is being used. </>
1499         </row><row>
1500         <entry>clips</><entry>An array of rectangles that must not be drawn
1501                         over.</>
1502         </row><row>
1503         <entry>clipcount</><entry>The number of clips in this array.</>
1504     </row>
1505     </tbody>
1506     </tgroup>
1507     </table>
1508     <para>
1509         Each clip is a struct video_clip which has the following fields
1510    </para>
1511    <table frame="all"><title>video_clip fields</title>
1512    <tgroup cols="2" align="left">
1513    <tbody>
1514    <row>
1515         <entry>x, y</><entry>Co-ordinates relative to the display</>
1516         </row><row>
1517         <entry>width, height</><entry>Width and height in pixels</>
1518         </row><row>
1519         <entry>next</><entry>A spare field for the application to use</>
1520     </row>
1521     </tbody>
1522     </tgroup>
1523     </table>
1524     <para>
1525         The driver is required to ensure it always draws in the area requested or a        smaller area, and that it never draws in any of the areas that are clipped.
1526         This may well mean it has to leave alone. small areas the application wished to be
1527         drawn.
1528   </para>
1529   <para>
1530         Our example card uses chromakey so does not have to address most of the
1531         clipping.  We will add a video_window structure to our global variables to
1532         remember our parameters, as we did with the frame buffer.
1533   </para>
1534   <programlisting>
1535
1536
1537                 case VIDIOCGWIN:
1538                 {
1539                         if(copy_to_user(arg, &amp;capture_win, 
1540                             sizeof(capture_win)))
1541                                 return -EFAULT;
1542                         return 0;
1543                 }
1544
1545
1546                 case VIDIOCSWIN:
1547                 {
1548                         struct video_window v;
1549                         if(copy_from_user(&amp;v, arg, sizeof(v)))
1550                                 return -EFAULT;
1551                         if(v.width > 640 || v.height > 480)
1552                                 return -EINVAL;
1553                         if(v.width < 16 || v.height < 16)
1554                                 return -EINVAL;
1555                         hardware_set_key(v.chromakey);
1556                         hardware_set_window(v);
1557                         memcpy(&amp;capture_win, &amp;v, sizeof(v));
1558                         capture_w = v.width;
1559                         capture_h = v.height;
1560                         return 0;
1561                 }
1562
1563
1564   </programlisting>
1565   <para>
1566         Because we are using Chromakey our setup is fairly simple. Mostly we have to
1567         check the values are sane and load them into the capture card.
1568   </para>
1569   <para>
1570         With all the setup done we can now turn on the actual capture/overlay. This
1571         is done with the VIDIOCCAPTURE ioctl. This takes a single integer argument
1572         where 0 is on and 1 is off.
1573   </para>
1574   <programlisting>
1575
1576
1577                 case VIDIOCCAPTURE:
1578                 {
1579                         int v;
1580                         if(get_user(v, (int *)arg))
1581                                 return -EFAULT;
1582                         if(v==0)
1583                                 hardware_capture_off();
1584                         else
1585                         {
1586                                 if(capture_fb.width == 0 
1587                                     || capture_w == 0)
1588                                         return -EINVAL;
1589                                 hardware_capture_on();
1590                         }
1591                         return 0;
1592                 }
1593
1594
1595   </programlisting>
1596   <para>
1597         We grab the flag from user space and either enable or disable according to
1598         its value. There is one small corner case we have to consider here. Suppose
1599         that the capture was requested before the video window or the frame buffer
1600         had been set up. In those cases there will be unconfigured fields in our
1601         card data, as well as unconfigured hardware settings. We check for this case and
1602         return an error if the frame buffer or the capture window width is zero.
1603   </para>
1604   <programlisting>
1605
1606
1607                 default:
1608                         return -ENOIOCTLCMD;
1609         }
1610 }
1611   </programlisting>
1612   <para>
1613
1614         We don't need to support any other ioctls, so if we get this far, it is time
1615         to tell the video layer that we don't now what the user is talking about.
1616   </para>
1617   </sect1>
1618   <sect1 id="endvid">
1619   <title>Other Functionality</title>
1620   <para>
1621         The Video4Linux layer supports additional features, including a high
1622         performance mmap() based capture mode and capturing part of the image. 
1623         These features are out of the scope of the book.  You should however have enough 
1624         example code to implement most simple video4linux devices for radio and TV
1625         cards.
1626   </para>
1627   </sect1>
1628   </chapter>
1629   <chapter id="bugs">
1630      <title>Known Bugs And Assumptions</title>
1631   <para>
1632   <variablelist>
1633     <varlistentry><term>Multiple Opens</term>
1634     <listitem>
1635     <para>
1636         The driver assumes multiple opens should not be allowed. A driver
1637         can work around this but not cleanly.
1638     </para>
1639     </listitem></varlistentry>
1640
1641     <varlistentry><term>API Deficiencies</term>
1642     <listitem>
1643     <para>
1644         The existing API poorly reflects compression capable devices. There
1645         are plans afoot to merge V4L, V4L2 and some other ideas into a
1646         better interface.
1647     </para>
1648     </listitem></varlistentry>
1649   </variablelist>
1650
1651   </para>
1652   </chapter>
1653
1654   <chapter id="pubfunctions">
1655      <title>Public Functions Provided</title>
1656 !Edrivers/media/video/videodev.c
1657   </chapter>
1658
1659 </book>