oleaut32: Partially implement UnRegisterTypeLibForUser.
[wine] / dlls / qcap / v4l.c
1 /*
2  * DirectShow capture services (QCAP.DLL)
3  *
4  * Copyright 2005 Maarten Lankhorst
5  *
6  * This file contains the part of the vfw capture interface that
7  * does the actual Video4Linux(1/2) stuff required for capturing
8  * and setting/getting media format..
9  *
10  * This library is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public
12  * License as published by the Free Software Foundation; either
13  * version 2.1 of the License, or (at your option) any later version.
14  *
15  * This library is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with this library; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24
25 #include "config.h"
26 #include "wine/port.h"
27 #include "wine/library.h"
28
29 #define NONAMELESSSTRUCT
30 #define NONAMELESSUNION
31 #define COBJMACROS
32
33 #include <stdarg.h>
34 #include "windef.h"
35 #include "winbase.h"
36 #include "wtypes.h"
37 #include "wingdi.h"
38 #include "winuser.h"
39 #include "dshow.h"
40 #include "vfwmsgs.h"
41 #include "amvideo.h"
42 #include "wine/debug.h"
43
44 #include "capture.h"
45 #include "qcap_main.h"
46 #include "pin.h"
47
48 #include <stdio.h>
49 #include <fcntl.h>
50
51 #ifdef HAVE_SYS_IOCTL_H
52 #include <sys/ioctl.h>
53 #endif
54 #ifdef HAVE_SYS_MMAN_H
55 #include <sys/mman.h>
56 #endif
57 #ifdef HAVE_SYS_ERRNO_H
58 #include <sys/errno.h>
59 #endif
60 #ifdef HAVE_SYS_TIME_H
61 #include <sys/time.h>
62 #endif
63 #ifdef HAVE_ASM_TYPES_H
64 #include <asm/types.h>
65 #endif
66 #ifdef HAVE_LINUX_VIDEODEV_H
67 #include <linux/videodev.h>
68 #endif
69 #ifdef HAVE_UNISTD_H
70 #include <unistd.h>
71 #endif
72
73 WINE_DEFAULT_DEBUG_CHANNEL(qcap_v4l);
74
75 #ifdef HAVE_LINUX_VIDEODEV_H
76
77 static typeof(open) *video_open = open;
78 static typeof(close) *video_close = close;
79 static typeof(ioctl) *video_ioctl = ioctl;
80 static typeof(read) *video_read = read;
81 static typeof(mmap) *video_mmap = mmap;
82 static typeof(munmap) *video_munmap = munmap;
83
84 static void video_init(void)
85 {
86 #ifdef SONAME_LIBV4L1
87     static void *video_lib;
88
89     if (video_lib)
90         return;
91     video_lib = wine_dlopen(SONAME_LIBV4L1, RTLD_NOW, NULL, 0);
92     if (!video_lib)
93         return;
94     video_open = wine_dlsym(video_lib, "v4l1_open", NULL, 0);
95     video_close = wine_dlsym(video_lib, "v4l1_close", NULL, 0);
96     video_ioctl = wine_dlsym(video_lib, "v4l1_ioctl", NULL, 0);
97     video_read = wine_dlsym(video_lib, "v4l1_read", NULL, 0);
98     video_mmap = wine_dlsym(video_lib, "v4l1_mmap", NULL, 0);
99     video_munmap = wine_dlsym(video_lib, "v4l1_munmap", NULL, 0);
100 #endif
101 }
102
103 typedef void (* Renderer)(const Capture *, LPBYTE bufferin, const BYTE *stream);
104
105 struct _Capture
106 {
107     UINT width, height, bitDepth, fps, outputwidth, outputheight;
108     BOOL swresize;
109
110     CRITICAL_SECTION CritSect;
111
112     IPin *pOut;
113     int fd, mmap;
114     int iscommitted, stopped;
115     struct video_picture pict;
116     int dbrightness, dhue, dcolour, dcontrast;
117
118     /* mmap (V4l1) */
119     struct video_mmap *grab_buf;
120     struct video_mbuf gb_buffers;
121     unsigned char *pmap;
122     int buffers;
123
124     /* read (V4l1) */
125     int imagesize;
126     char * grab_data;
127
128     int curframe;
129
130     HANDLE thread;
131     Renderer renderer;
132 };
133
134 struct renderlist
135 {
136     int depth;
137     const char* name;
138     Renderer renderer;
139 };
140
141 static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *stream);
142 static void renderer_YUV(const Capture *capBox, LPBYTE bufferin, const BYTE *stream);
143
144 static const struct renderlist renderlist_V4l[] = {
145     {  0, "NULL renderer",               NULL },
146     {  8, "Gray scales",                 NULL }, /* 1,  Don't support  */
147     {  0, "High 240 cube (BT848)",       NULL }, /* 2,  Don't support  */
148     { 16, "16 bit RGB (565)",            NULL }, /* 3,  Don't support  */
149     { 24, "24 bit RGB values",   renderer_RGB }, /* 4,  Supported,     */
150     { 32, "32 bit RGB values",   renderer_RGB }, /* 5,  Supported      */
151     { 16, "15 bit RGB (555)",            NULL }, /* 6,  Don't support  */
152     { 16, "YUV 422 (Not P)",     renderer_YUV }, /* 7,  Supported */
153     { 16, "YUYV (Not P)",        renderer_YUV }, /* 8,  Supported */
154     { 16, "UYVY (Not P)",        renderer_YUV }, /* 9,  Supported */
155     { 16, "YUV 420 (Not P)", NULL }, /* 10, Not supported, if I had to guess it's YYUYYV */
156     { 12, "YUV 411 (Not P)",     renderer_YUV }, /* 11, Supported */
157     {  0, "Raw capturing (BT848)",       NULL }, /* 12, Don't support  */
158     { 16, "YUV 422 (Planar)",    renderer_YUV }, /* 13, Supported */
159     { 12, "YUV 411 (Planar)",    renderer_YUV }, /* 14, Supported */
160     { 12, "YUV 420 (Planar)",    renderer_YUV }, /* 15, Supported */
161     { 10, "YUV 410 (Planar)",    renderer_YUV }, /* 16, Supported */
162     /* FIXME: add YUV420 support */
163     {  0, NULL,                          NULL },
164 };
165
166 static const int fallback_V4l[] = { 4, 5, 7, 8, 9, 13, 15, 14, 16, 11, -1 };
167 /* Fallback: First try raw formats (Should try yuv first perhaps?), then yuv */
168
169 /* static const Capture defbox; */
170
171 static int xioctl(int fd, int request, void * arg)
172 {
173     int r;
174
175     do {
176         r = video_ioctl (fd, request, arg);
177     } while (-1 == r && EINTR == errno);
178
179     return r;
180 }
181
182 /* Prepare the capture buffers */
183 static HRESULT V4l_Prepare(Capture *capBox)
184 {
185     TRACE("%p: Preparing for %dx%d resolution\n", capBox, capBox->width, capBox->height);
186
187     /* Try mmap */
188     capBox->mmap = 0;
189     if (xioctl(capBox->fd, VIDIOCGMBUF, &capBox->gb_buffers) != -1 &&
190         capBox->gb_buffers.frames)
191     {
192         capBox->buffers = capBox->gb_buffers.frames;
193         if (capBox->gb_buffers.frames > 1)
194             capBox->buffers = 1;
195         TRACE("%p: Using %d/%d buffers\n", capBox,
196               capBox->buffers, capBox->gb_buffers.frames);
197
198         capBox->pmap = video_mmap( 0, capBox->gb_buffers.size, PROT_READ|PROT_WRITE,
199                                    MAP_SHARED, capBox->fd, 0 );
200         if (capBox->pmap != MAP_FAILED)
201         {
202             int i;
203
204             capBox->grab_buf = CoTaskMemAlloc(sizeof(struct video_mmap) * capBox->buffers);
205             if (!capBox->grab_buf)
206             {
207                 video_munmap(capBox->pmap, capBox->gb_buffers.size);
208                 return E_OUTOFMEMORY;
209             }
210
211             /* Setup mmap capture buffers. */
212             for (i = 0; i < capBox->buffers; i++)
213             {
214                 capBox->grab_buf[i].format = capBox->pict.palette;
215                 capBox->grab_buf[i].frame = i;
216                 capBox->grab_buf[i].width = capBox->width;
217                 capBox->grab_buf[i].height = capBox->height;
218             }
219             capBox->mmap = 1;
220         }
221     }
222     if (!capBox->mmap)
223     {
224         capBox->buffers = 1;
225         capBox->imagesize = renderlist_V4l[capBox->pict.palette].depth *
226                                 capBox->height * capBox->width / 8;
227         capBox->grab_data = CoTaskMemAlloc(capBox->imagesize);
228         if (!capBox->grab_data)
229             return E_OUTOFMEMORY;
230     }
231     TRACE("Using mmap: %d\n", capBox->mmap);
232     return S_OK;
233 }
234
235 static void V4l_Unprepare(Capture *capBox)
236 {
237     if (capBox->mmap)
238     {
239         for (capBox->curframe = 0; capBox->curframe < capBox->buffers; capBox->curframe++) 
240             xioctl(capBox->fd, VIDIOCSYNC, &capBox->grab_buf[capBox->curframe]);
241         video_munmap(capBox->pmap, capBox->gb_buffers.size);
242         CoTaskMemFree(capBox->grab_buf);
243     }
244     else
245         CoTaskMemFree(capBox->grab_data);
246 }
247
248 HRESULT qcap_driver_destroy(Capture *capBox)
249 {
250     TRACE("%p\n", capBox);
251
252     if( capBox->fd != -1 )
253         video_close(capBox->fd);
254     capBox->CritSect.DebugInfo->Spare[0] = 0;
255     DeleteCriticalSection(&capBox->CritSect);
256     CoTaskMemFree(capBox);
257     return S_OK;
258 }
259
260 HRESULT qcap_driver_set_format(Capture *capBox, AM_MEDIA_TYPE * mT)
261 {
262     int newheight, newwidth;
263     struct video_window window;
264     VIDEOINFOHEADER *format;
265
266     TRACE("%p\n", capBox);
267
268     format = (VIDEOINFOHEADER *) mT->pbFormat;
269     if (format->bmiHeader.biBitCount != 24 ||
270         format->bmiHeader.biCompression != BI_RGB)
271     {
272         FIXME("unsupported media type %d %d\n", format->bmiHeader.biBitCount,
273               format->bmiHeader.biCompression );
274         return VFW_E_INVALIDMEDIATYPE;
275     }
276
277     newwidth = format->bmiHeader.biWidth;
278     newheight = format->bmiHeader.biHeight;
279
280     TRACE("%p -> (%p) - %d %d\n", capBox, mT, newwidth, newheight);
281
282     if (capBox->height == newheight && capBox->width == newwidth)
283         return S_OK;
284
285     if(-1 == xioctl(capBox->fd, VIDIOCGWIN, &window))
286     {
287         ERR("ioctl(VIDIOCGWIN) failed (%d)\n", errno);
288         return E_FAIL;
289     }
290     window.width = newwidth;
291     window.height = newheight;
292     if (xioctl(capBox->fd, VIDIOCSWIN, &window) == -1)
293     {
294         TRACE("using software resize: %dx%d -> %dx%d\n",
295                window.width, window.height, capBox->width, capBox->height);
296         capBox->swresize = TRUE;
297     }
298     else
299     {
300         capBox->height = window.height;
301         capBox->width = window.width;
302         capBox->swresize = FALSE;
303     }
304     capBox->outputwidth = window.width;
305     capBox->outputheight = window.height;
306     return S_OK;
307 }
308
309 HRESULT qcap_driver_get_format(const Capture *capBox, AM_MEDIA_TYPE ** mT)
310 {
311     VIDEOINFOHEADER *vi;
312
313     mT[0] = CoTaskMemAlloc(sizeof(AM_MEDIA_TYPE));
314     if (!mT[0])
315         return E_OUTOFMEMORY;
316     vi = CoTaskMemAlloc(sizeof(VIDEOINFOHEADER));
317     mT[0]->cbFormat = sizeof(VIDEOINFOHEADER);
318     if (!vi)
319     {
320         CoTaskMemFree(mT[0]);
321         return E_OUTOFMEMORY;
322     }
323     mT[0]->majortype = MEDIATYPE_Video;
324     mT[0]->subtype = MEDIASUBTYPE_RGB24;
325     mT[0]->formattype = FORMAT_VideoInfo;
326     mT[0]->bFixedSizeSamples = TRUE;
327     mT[0]->bTemporalCompression = FALSE;
328     mT[0]->pUnk = NULL;
329     mT[0]->lSampleSize = capBox->outputwidth * capBox->outputheight * capBox->bitDepth / 8;
330     TRACE("Output format: %dx%d - %d bits = %u KB\n", capBox->outputwidth,
331           capBox->outputheight, capBox->bitDepth, mT[0]->lSampleSize/1024);
332     vi->rcSource.left = 0; vi->rcSource.top = 0;
333     vi->rcTarget.left = 0; vi->rcTarget.top = 0;
334     vi->rcSource.right = capBox->width; vi->rcSource.bottom = capBox->height;
335     vi->rcTarget.right = capBox->outputwidth; vi->rcTarget.bottom = capBox->outputheight;
336     vi->dwBitRate = capBox->fps * mT[0]->lSampleSize;
337     vi->dwBitErrorRate = 0;
338     vi->AvgTimePerFrame = (LONGLONG)10000000.0 / (LONGLONG)capBox->fps;
339     vi->bmiHeader.biSize = 40;
340     vi->bmiHeader.biWidth = capBox->outputwidth;
341     vi->bmiHeader.biHeight = capBox->outputheight;
342     vi->bmiHeader.biPlanes = 1;
343     vi->bmiHeader.biBitCount = 24;
344     vi->bmiHeader.biCompression = BI_RGB;
345     vi->bmiHeader.biSizeImage = mT[0]->lSampleSize;
346     vi->bmiHeader.biClrUsed = vi->bmiHeader.biClrImportant = 0;
347     vi->bmiHeader.biXPelsPerMeter = 100;
348     vi->bmiHeader.biYPelsPerMeter = 100;
349     mT[0]->pbFormat = (void *)vi;
350     dump_AM_MEDIA_TYPE(mT[0]);
351     return S_OK;
352 }
353
354 HRESULT qcap_driver_get_prop_range( Capture *capBox,
355             VideoProcAmpProperty Property, LONG *pMin, LONG *pMax,
356             LONG *pSteppingDelta, LONG *pDefault, LONG *pCapsFlags )
357 {
358     TRACE("%p -> %d %p %p %p %p %p\n", capBox, Property,
359           pMin, pMax, pSteppingDelta, pDefault, pCapsFlags);
360
361     switch (Property)
362     {
363     case VideoProcAmp_Brightness:
364         *pDefault = capBox->dbrightness;
365         break;
366     case VideoProcAmp_Contrast:
367         *pDefault = capBox->dcontrast;
368         break;
369     case VideoProcAmp_Hue:
370         *pDefault = capBox->dhue;
371         break;
372     case VideoProcAmp_Saturation:
373         *pDefault = capBox->dcolour;
374         break;
375     default:
376         FIXME("Not implemented %d\n", Property);
377         return E_NOTIMPL;
378     }
379     *pMin = 0;
380     *pMax = 65535;
381     *pSteppingDelta = 65536/256;
382     *pCapsFlags = VideoProcAmp_Flags_Manual;
383     return S_OK;
384 }
385
386 HRESULT qcap_driver_get_prop( Capture *capBox,
387             VideoProcAmpProperty Property, LONG *lValue, LONG *Flags )
388 {
389     TRACE("%p -> %d %p %p\n", capBox, Property, lValue, Flags);
390
391     switch (Property)
392     {
393     case VideoProcAmp_Brightness:
394         *lValue = capBox->pict.brightness;
395         break;
396     case VideoProcAmp_Contrast:
397         *lValue = capBox->pict.contrast;
398         break;
399     case VideoProcAmp_Hue:
400         *lValue = capBox->pict.hue;
401         break;
402     case VideoProcAmp_Saturation:
403         *lValue = capBox->pict.colour;
404         break;
405     default:
406         FIXME("Not implemented %d\n", Property);
407         return E_NOTIMPL;
408     }
409     *Flags = VideoProcAmp_Flags_Manual;
410     return S_OK;
411 }
412
413 HRESULT qcap_driver_set_prop(Capture *capBox, VideoProcAmpProperty Property,
414             LONG lValue, LONG Flags)
415 {
416     TRACE("%p -> %d %d %d\n", capBox, Property, lValue, Flags);
417
418     switch (Property)
419     {
420     case VideoProcAmp_Brightness:
421         capBox->pict.brightness = lValue;
422         break;
423     case VideoProcAmp_Contrast:
424         capBox->pict.contrast = lValue;
425         break;
426     case VideoProcAmp_Hue:
427         capBox->pict.hue = lValue;
428         break;
429     case VideoProcAmp_Saturation:
430         capBox->pict.colour = lValue;
431         break;
432     default:
433         FIXME("Not implemented %d\n", Property);
434         return E_NOTIMPL;
435     }
436
437     if (xioctl(capBox->fd, VIDIOCSPICT, &capBox->pict) == -1)
438     {
439         ERR("ioctl(VIDIOCSPICT) failed (%d)\n",errno);
440         return E_FAIL;
441     }
442     return S_OK;
443 }
444
445 static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
446 {
447     int depth = renderlist_V4l[capBox->pict.palette].depth;
448     int size = capBox->height * capBox->width * depth / 8;
449     int pointer, offset;
450
451     switch (depth)
452     {
453     case 24:
454         memcpy(bufferin, stream, size);
455         break;
456     case 32:
457         pointer = 0;
458         offset = 1;
459         while (pointer + offset <= size)
460         {
461             bufferin[pointer] = stream[pointer + offset];
462             pointer++;
463             bufferin[pointer] = stream[pointer + offset];
464             pointer++;
465             bufferin[pointer] = stream[pointer + offset];
466             pointer++;
467             offset++;
468         }
469         break;
470     default:
471         ERR("Unknown bit depth %d\n", depth);
472         return;
473     }
474 }
475
476 static void renderer_YUV(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
477 {
478     enum YUV_Format format;
479
480     switch (capBox->pict.palette)
481     {
482     case  7: /* YUV422  -  same as YUYV */
483     case  8: /* YUYV    */
484         format = YUYV;
485         break;
486     case  9: /* UYVY    */
487         format = UYVY;
488         break;
489     case 11: /* YUV411  */
490         format = UYYVYY;
491         break;
492     case 13: /* YUV422P */
493         format = YUVP_421;
494         break;
495     case 14: /* YUV411P */
496         format = YUVP_441;
497         break;
498     case 15: /* YUV420P */
499         format = YUVP_422;
500         break;
501     case 16: /* YUV410P */
502         format = YUVP_444;
503         break;
504     default:
505         ERR("Unknown palette %d\n", capBox->pict.palette);
506         return;
507     }
508     YUV_To_RGB24(format, bufferin, stream, capBox->width, capBox->height);
509 }
510
511 static void Resize(const Capture * capBox, LPBYTE output, const BYTE *input)
512 {
513     /* the whole image needs to be reversed,
514        because the dibs are messed up in windows */
515     if (!capBox->swresize)
516     {
517         int depth = capBox->bitDepth / 8;
518         int inoffset = 0, outoffset = capBox->height * capBox->width * depth;
519         int ow = capBox->width * depth;
520         while (outoffset > 0)
521         {
522             int x;
523             outoffset -= ow;
524             for (x = 0; x < ow; x++)
525                 output[outoffset + x] = input[inoffset + x];
526             inoffset += ow;
527         }
528     }
529     else
530     {
531         HDC dc_s, dc_d;
532         HBITMAP bmp_s, bmp_d;
533         int depth = capBox->bitDepth / 8;
534         int inoffset = 0, outoffset = (capBox->outputheight) * capBox->outputwidth * depth;
535         int ow = capBox->outputwidth * depth;
536         LPBYTE myarray;
537
538         /* FIXME: Improve software resizing: add error checks and optimize */
539
540         myarray = CoTaskMemAlloc(capBox->outputwidth * capBox->outputheight * depth);
541         dc_s = CreateCompatibleDC(NULL);
542         dc_d = CreateCompatibleDC(NULL);
543         bmp_s = CreateBitmap(capBox->width, capBox->height, 1, capBox->bitDepth, input);
544         bmp_d = CreateBitmap(capBox->outputwidth, capBox->outputheight, 1, capBox->bitDepth, NULL);
545         SelectObject(dc_s, bmp_s);
546         SelectObject(dc_d, bmp_d);
547         StretchBlt(dc_d, 0, 0, capBox->outputwidth, capBox->outputheight,
548                    dc_s, 0, 0, capBox->width, capBox->height, SRCCOPY);
549         GetBitmapBits(bmp_d, capBox->outputwidth * capBox->outputheight * depth, myarray);
550         while (outoffset > 0)
551         {
552             int i;
553
554             outoffset -= ow;
555             for (i = 0; i < ow; i++)
556                 output[outoffset + i] = myarray[inoffset + i];
557             inoffset += ow;
558         }
559         CoTaskMemFree(myarray);
560         DeleteObject(dc_s);
561         DeleteObject(dc_d);
562         DeleteObject(bmp_s);
563         DeleteObject(bmp_d);
564     }
565 }
566
567 static void V4l_GetFrame(Capture * capBox, unsigned char ** pInput)
568 {
569     if (capBox->mmap)
570     {
571         if (xioctl(capBox->fd, VIDIOCSYNC, &capBox->grab_buf[capBox->curframe]) == -1)
572             WARN("Syncing ioctl failed: %d\n", errno);
573
574         *pInput = capBox->pmap + capBox->gb_buffers.offsets[capBox->curframe];
575     }
576     else
577     {
578         int retval;
579         while ((retval = video_read(capBox->fd, capBox->grab_data, capBox->imagesize)) == -1)
580             if (errno != EAGAIN) break;
581         if (retval == -1)
582             WARN("Error occurred while reading from device: %s\n", strerror(errno));
583         *pInput = (unsigned char*) capBox->grab_data;
584     }
585 }
586
587 static void V4l_FreeFrame(Capture * capBox)
588 {
589     TRACE("\n");
590     if (capBox->mmap)
591     {
592         if (xioctl(capBox->fd, VIDIOCMCAPTURE, &capBox->grab_buf[capBox->curframe]) == -1)
593            ERR("Freeing frame for capture failed: %s\n", strerror(errno));
594     }
595     if (++capBox->curframe == capBox->buffers)
596         capBox->curframe = 0;
597 }
598
599 static DWORD WINAPI ReadThread(LPVOID lParam)
600 {
601     Capture * capBox = lParam;
602     HRESULT hr;
603     IMediaSample *pSample = NULL;
604     ULONG framecount = 0;
605     unsigned char *pTarget, *pInput, *pOutput;
606
607     hr = V4l_Prepare(capBox);
608     if (FAILED(hr))
609         goto fail;
610
611     pOutput = CoTaskMemAlloc(capBox->width * capBox->height * capBox->bitDepth / 8);
612     capBox->curframe = 0;
613     do {
614         V4l_FreeFrame(capBox);
615     } while (capBox->curframe != 0);
616
617     while (1)
618     {
619         EnterCriticalSection(&capBox->CritSect);
620         if (capBox->stopped)
621             break;
622         hr = OutputPin_GetDeliveryBuffer((OutputPin *)capBox->pOut, &pSample, NULL, NULL, 0);
623         if (SUCCEEDED(hr))
624         {
625             int len;
626             
627             if (!capBox->swresize)
628                 len = capBox->height * capBox->width * capBox->bitDepth / 8;
629             else
630                 len = capBox->outputheight * capBox->outputwidth * capBox->bitDepth / 8;
631             IMediaSample_SetActualDataLength(pSample, len);
632
633             len = IMediaSample_GetActualDataLength(pSample);
634             TRACE("Data length: %d KB\n", len / 1024);
635
636             IMediaSample_GetPointer(pSample, &pTarget);
637             /* FIXME: Check return values.. */
638             V4l_GetFrame(capBox, &pInput);
639             capBox->renderer(capBox, pOutput, pInput);
640             Resize(capBox, pTarget, pOutput);
641             hr = OutputPin_SendSample((OutputPin *)capBox->pOut, pSample);
642             TRACE("%p -> Frame %u: %x\n", capBox, ++framecount, hr);
643             IMediaSample_Release(pSample);
644             V4l_FreeFrame(capBox);
645         }
646         LeaveCriticalSection(&capBox->CritSect);
647         if (FAILED(hr) && hr != VFW_E_NOT_CONNECTED)
648         {
649             ERR("Received error: %x\n", hr);
650             goto cfail;
651         }
652     }
653     LeaveCriticalSection(&capBox->CritSect);
654     CoTaskMemFree(pOutput);
655
656     return 0;
657
658 cfail:
659     CoTaskMemFree(pOutput);
660     V4l_Unprepare(capBox);
661     LeaveCriticalSection(&capBox->CritSect);
662
663 fail:
664     capBox->thread = 0; capBox->stopped = 1;
665     FIXME("Stop IFilterGraph\n");
666     return 0;
667 }
668
669 HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state)
670 {
671     HANDLE thread;
672     HRESULT hr;
673
674     TRACE("%p -> (%p)\n", capBox, state); 
675
676     if (*state == State_Running) return S_OK;
677
678     EnterCriticalSection(&capBox->CritSect);
679
680     capBox->stopped = 0;
681
682     if (*state == State_Stopped)
683     {
684         *state = State_Running;
685         if (!capBox->iscommitted++)
686         {
687             IMemAllocator * pAlloc = NULL;
688             ALLOCATOR_PROPERTIES ap, actual;
689             OutputPin *out;
690
691             ap.cBuffers = 3;
692             if (!capBox->swresize)
693                 ap.cbBuffer = capBox->width * capBox->height;
694             else
695                 ap.cbBuffer = capBox->outputwidth * capBox->outputheight;
696             ap.cbBuffer = (ap.cbBuffer * capBox->bitDepth) / 8;
697             ap.cbAlign = 1;
698             ap.cbPrefix = 0;
699
700             out = (OutputPin *)capBox->pOut;
701             hr = IMemInputPin_GetAllocator(out->pMemInputPin, &pAlloc);
702
703             if (SUCCEEDED(hr))
704                 hr = IMemAllocator_SetProperties(pAlloc, &ap, &actual);
705
706             if (SUCCEEDED(hr))
707                 hr = IMemAllocator_Commit(pAlloc);
708
709             if (pAlloc)
710                 IMemAllocator_Release(pAlloc);
711
712             TRACE("Committing allocator: %x\n", hr);
713         }
714
715         thread = CreateThread(NULL, 0, ReadThread, capBox, 0, NULL);
716         if (thread)
717         {
718             capBox->thread = thread;
719             SetThreadPriority(thread, THREAD_PRIORITY_LOWEST);
720             LeaveCriticalSection(&capBox->CritSect);
721             return S_OK;
722         }
723         ERR("Creating thread failed.. %u\n", GetLastError());
724         LeaveCriticalSection(&capBox->CritSect);
725         return E_FAIL;
726     }
727
728     ResumeThread(capBox->thread);
729     *state = State_Running;
730     LeaveCriticalSection(&capBox->CritSect);
731     return S_OK;
732 }
733
734 HRESULT qcap_driver_pause(Capture *capBox, FILTER_STATE *state)
735 {
736     TRACE("%p -> (%p)\n", capBox, state);     
737
738     if (*state == State_Paused)
739         return S_OK;
740     if (*state == State_Stopped)
741         qcap_driver_run(capBox, state);
742
743     EnterCriticalSection(&capBox->CritSect);
744     *state = State_Paused;
745     SuspendThread(capBox->thread);
746     LeaveCriticalSection(&capBox->CritSect);
747
748     return S_OK;
749 }
750
751 HRESULT qcap_driver_stop(Capture *capBox, FILTER_STATE *state)
752 {
753     TRACE("%p -> (%p)\n", capBox, state);
754
755     if (*state == State_Stopped)
756         return S_OK;
757
758     EnterCriticalSection(&capBox->CritSect);
759
760     if (capBox->thread)
761     {
762         if (*state == State_Paused)
763             ResumeThread(capBox->thread);
764         capBox->stopped = 1;
765         capBox->thread = 0;
766         if (capBox->iscommitted)
767         {
768             IMemInputPin *pMem = NULL;
769             IMemAllocator * pAlloc = NULL;
770             IPin *pConnect = NULL;
771             HRESULT hr;
772
773             capBox->iscommitted = 0;
774
775             hr = IPin_ConnectedTo(capBox->pOut, &pConnect);
776
777             if (SUCCEEDED(hr))
778                 hr = IPin_QueryInterface(pConnect, &IID_IMemInputPin, (void **) &pMem);
779
780             if (SUCCEEDED(hr))
781                 hr = IMemInputPin_GetAllocator(pMem, &pAlloc);
782
783             if (SUCCEEDED(hr))
784                 hr = IMemAllocator_Decommit(pAlloc);
785
786             if (pAlloc)
787                 IMemAllocator_Release(pAlloc);
788
789             if (pMem)
790                 IMemInputPin_Release(pMem);
791
792             if (pConnect)
793                 IPin_Release(pConnect);
794
795             if (hr != S_OK && hr != VFW_E_NOT_COMMITTED)
796                 WARN("Decommitting allocator: %x\n", hr);
797         }
798         V4l_Unprepare(capBox);
799     }
800
801     *state = State_Stopped;
802     LeaveCriticalSection(&capBox->CritSect);
803     return S_OK;
804 }
805
806 Capture * qcap_driver_init( IPin *pOut, USHORT card )
807 {
808     Capture * capBox = NULL;
809     char device[20];
810     struct video_capability capa;
811     struct video_picture pict;
812     struct video_window window;
813
814     YUV_Init();
815     video_init();
816
817     capBox = CoTaskMemAlloc(sizeof(Capture));
818     if (!capBox)
819         goto error;
820
821     /* capBox->vtbl = &defboxVtbl; */
822
823     InitializeCriticalSection( &capBox->CritSect );
824     capBox->CritSect.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Capture.CritSect");
825
826     sprintf(device, "/dev/video%i", card);
827     TRACE("opening %s\n", device);
828     capBox->fd = video_open(device, O_RDWR | O_NONBLOCK);
829     if (capBox->fd == -1)
830     {
831         WARN("open failed (%d)\n", errno);
832         goto error;
833     }
834
835     memset(&capa, 0, sizeof(capa));
836
837     if (xioctl(capBox->fd, VIDIOCGCAP, &capa) == -1)
838     {
839         WARN("ioctl(VIDIOCGCAP) failed (%d)\n", errno);
840         goto error;
841     }
842
843     if (!(capa.type & VID_TYPE_CAPTURE))
844     {
845         WARN("not a video capture device\n");
846         goto error;
847     }
848
849     TRACE("%d inputs on %s\n", capa.channels, capa.name );
850
851     if (xioctl(capBox->fd, VIDIOCGPICT, &pict) == -1)
852     {
853         ERR("ioctl(VIDIOCGPICT) failed (%d)\n", errno );
854         goto error;
855     }
856
857     TRACE("depth %d palette %d (%s) hue %d color %d contrast %d\n",
858           pict.depth, pict.palette, renderlist_V4l[pict.palette].name,
859           pict.hue, pict.colour, pict.contrast );
860
861     capBox->dbrightness = pict.brightness;
862     capBox->dcolour = pict.colour;
863     capBox->dhue = pict.hue;
864     capBox->dcontrast = pict.contrast;
865
866     if (!renderlist_V4l[pict.palette].renderer)
867     {
868         int palet = pict.palette, i;
869
870         TRACE("No renderer available for %s, falling back to defaults\n",
871              renderlist_V4l[pict.palette].name);
872         capBox->renderer = NULL;
873         for (i = 0; fallback_V4l[i] >=0 ; i++)
874         {
875             int n = fallback_V4l[i];
876
877             if (renderlist_V4l[n].renderer == NULL)
878                 continue;
879
880             pict.depth = renderlist_V4l[n].depth;
881             pict.palette = n;
882             if (xioctl(capBox->fd, VIDIOCSPICT, &pict) == -1)
883             {
884                 TRACE("Could not render with %s (%d)\n",
885                       renderlist_V4l[n].name, n);
886                 continue;
887             }
888             TRACE("using renderer %s (%d)\n", 
889                   renderlist_V4l[n].name, n);
890             capBox->renderer = renderlist_V4l[n].renderer;
891             break;
892         }
893
894         if (!capBox->renderer)
895         {
896             ERR("video format %s isn't available\n",
897                  renderlist_V4l[palet].name);
898             goto error;
899         }
900     }
901     else
902     {
903         TRACE("Using the suggested format\n");
904         capBox->renderer = renderlist_V4l[pict.palette].renderer;
905     }
906     memcpy(&capBox->pict, &pict, sizeof(struct video_picture));
907
908     memset(&window, 0, sizeof(window));
909     if (xioctl(capBox->fd, VIDIOCGWIN, &window) == -1)
910     {
911         WARN("VIDIOCGWIN failed (%d)\n", errno);
912         goto error;
913     }
914
915     capBox->height = capBox->outputheight = window.height;
916     capBox->width = capBox->outputwidth = window.width;
917     capBox->swresize = FALSE;
918     capBox->bitDepth = 24;
919     capBox->pOut = pOut;
920     capBox->fps = 3;
921     capBox->stopped = 0;
922     capBox->curframe = 0;
923     capBox->iscommitted = 0;
924
925     TRACE("format: %d bits - %d x %d\n", capBox->bitDepth, capBox->width, capBox->height);
926
927     return capBox;
928
929 error:
930     if (capBox)
931         qcap_driver_destroy( capBox );
932
933     return NULL;
934 }
935
936 #else
937
938 Capture * qcap_driver_init( IPin *pOut, USHORT card )
939 {
940     const char msg[] = 
941         "The v4l headers were not available at compile time,\n"
942         "so video capture support is not available.\n";
943     MESSAGE(msg);
944     return NULL;
945 }
946
947 #define FAIL_WITH_ERR \
948     ERR("v4l absent: shouldn't be called\n"); \
949     return E_NOTIMPL
950
951 HRESULT qcap_driver_destroy(Capture *capBox)
952 {
953     FAIL_WITH_ERR;
954 }
955
956 HRESULT qcap_driver_set_format(Capture *capBox, AM_MEDIA_TYPE * mT)
957 {
958     FAIL_WITH_ERR;
959 }
960
961 HRESULT qcap_driver_get_format(const Capture *capBox, AM_MEDIA_TYPE ** mT)
962 {
963     FAIL_WITH_ERR;
964 }
965
966 HRESULT qcap_driver_get_prop_range( Capture *capBox,
967         VideoProcAmpProperty  Property, LONG *pMin, LONG *pMax,
968         LONG *pSteppingDelta, LONG *pDefault, LONG *pCapsFlags )
969 {
970     FAIL_WITH_ERR;
971 }
972
973 HRESULT qcap_driver_get_prop(Capture *capBox,
974         VideoProcAmpProperty Property, LONG *lValue, LONG *Flags)
975 {
976     FAIL_WITH_ERR;
977 }
978
979 HRESULT qcap_driver_set_prop(Capture *capBox, VideoProcAmpProperty Property,
980         LONG lValue, LONG Flags)
981 {
982     FAIL_WITH_ERR;
983 }
984
985 HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state)
986 {
987     FAIL_WITH_ERR;
988 }
989
990 HRESULT qcap_driver_pause(Capture *capBox, FILTER_STATE *state)
991 {
992     FAIL_WITH_ERR;
993 }
994
995 HRESULT qcap_driver_stop(Capture *capBox, FILTER_STATE *state)
996 {
997     FAIL_WITH_ERR;
998 }
999
1000 #endif /* HAVE_LINUX_VIDEODEV_H */