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