po: Update French translation.
[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         return E_OUTOFMEMORY;
318     }
319     mT[0]->majortype = MEDIATYPE_Video;
320     mT[0]->subtype = MEDIASUBTYPE_RGB24;
321     mT[0]->formattype = FORMAT_VideoInfo;
322     mT[0]->bFixedSizeSamples = TRUE;
323     mT[0]->bTemporalCompression = FALSE;
324     mT[0]->pUnk = NULL;
325     mT[0]->lSampleSize = capBox->outputwidth * capBox->outputheight * capBox->bitDepth / 8;
326     TRACE("Output format: %dx%d - %d bits = %u KB\n", capBox->outputwidth,
327           capBox->outputheight, capBox->bitDepth, mT[0]->lSampleSize/1024);
328     vi->rcSource.left = 0; vi->rcSource.top = 0;
329     vi->rcTarget.left = 0; vi->rcTarget.top = 0;
330     vi->rcSource.right = capBox->width; vi->rcSource.bottom = capBox->height;
331     vi->rcTarget.right = capBox->outputwidth; vi->rcTarget.bottom = capBox->outputheight;
332     vi->dwBitRate = capBox->fps * mT[0]->lSampleSize;
333     vi->dwBitErrorRate = 0;
334     vi->AvgTimePerFrame = (LONGLONG)10000000.0 / (LONGLONG)capBox->fps;
335     vi->bmiHeader.biSize = 40;
336     vi->bmiHeader.biWidth = capBox->outputwidth;
337     vi->bmiHeader.biHeight = capBox->outputheight;
338     vi->bmiHeader.biPlanes = 1;
339     vi->bmiHeader.biBitCount = 24;
340     vi->bmiHeader.biCompression = BI_RGB;
341     vi->bmiHeader.biSizeImage = mT[0]->lSampleSize;
342     vi->bmiHeader.biClrUsed = vi->bmiHeader.biClrImportant = 0;
343     vi->bmiHeader.biXPelsPerMeter = 100;
344     vi->bmiHeader.biYPelsPerMeter = 100;
345     mT[0]->pbFormat = (void *)vi;
346     dump_AM_MEDIA_TYPE(mT[0]);
347     return S_OK;
348 }
349
350 HRESULT qcap_driver_get_prop_range( Capture *capBox,
351             VideoProcAmpProperty Property, LONG *pMin, LONG *pMax,
352             LONG *pSteppingDelta, LONG *pDefault, LONG *pCapsFlags )
353 {
354     TRACE("%p -> %d %p %p %p %p %p\n", capBox, Property,
355           pMin, pMax, pSteppingDelta, pDefault, pCapsFlags);
356
357     switch (Property)
358     {
359     case VideoProcAmp_Brightness:
360         *pDefault = capBox->dbrightness;
361         break;
362     case VideoProcAmp_Contrast:
363         *pDefault = capBox->dcontrast;
364         break;
365     case VideoProcAmp_Hue:
366         *pDefault = capBox->dhue;
367         break;
368     case VideoProcAmp_Saturation:
369         *pDefault = capBox->dcolour;
370         break;
371     default:
372         FIXME("Not implemented %d\n", Property);
373         return E_NOTIMPL;
374     }
375     *pMin = 0;
376     *pMax = 65535;
377     *pSteppingDelta = 65536/256;
378     *pCapsFlags = VideoProcAmp_Flags_Manual;
379     return S_OK;
380 }
381
382 HRESULT qcap_driver_get_prop( Capture *capBox,
383             VideoProcAmpProperty Property, LONG *lValue, LONG *Flags )
384 {
385     TRACE("%p -> %d %p %p\n", capBox, Property, lValue, Flags);
386
387     switch (Property)
388     {
389     case VideoProcAmp_Brightness:
390         *lValue = capBox->pict.brightness;
391         break;
392     case VideoProcAmp_Contrast:
393         *lValue = capBox->pict.contrast;
394         break;
395     case VideoProcAmp_Hue:
396         *lValue = capBox->pict.hue;
397         break;
398     case VideoProcAmp_Saturation:
399         *lValue = capBox->pict.colour;
400         break;
401     default:
402         FIXME("Not implemented %d\n", Property);
403         return E_NOTIMPL;
404     }
405     *Flags = VideoProcAmp_Flags_Manual;
406     return S_OK;
407 }
408
409 HRESULT qcap_driver_set_prop(Capture *capBox, VideoProcAmpProperty Property,
410             LONG lValue, LONG Flags)
411 {
412     TRACE("%p -> %d %d %d\n", capBox, Property, lValue, Flags);
413
414     switch (Property)
415     {
416     case VideoProcAmp_Brightness:
417         capBox->pict.brightness = lValue;
418         break;
419     case VideoProcAmp_Contrast:
420         capBox->pict.contrast = lValue;
421         break;
422     case VideoProcAmp_Hue:
423         capBox->pict.hue = lValue;
424         break;
425     case VideoProcAmp_Saturation:
426         capBox->pict.colour = lValue;
427         break;
428     default:
429         FIXME("Not implemented %d\n", Property);
430         return E_NOTIMPL;
431     }
432
433     if (xioctl(capBox->fd, VIDIOCSPICT, &capBox->pict) == -1)
434     {
435         ERR("ioctl(VIDIOCSPICT) failed (%d)\n",errno);
436         return E_FAIL;
437     }
438     return S_OK;
439 }
440
441 static void renderer_RGB(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
442 {
443     int depth = renderlist_V4l[capBox->pict.palette].depth;
444     int size = capBox->height * capBox->width * depth / 8;
445     int pointer, offset;
446
447     switch (depth)
448     {
449     case 24:
450         memcpy(bufferin, stream, size);
451         break;
452     case 32:
453         pointer = 0;
454         offset = 1;
455         while (pointer + offset <= size)
456         {
457             bufferin[pointer] = stream[pointer + offset];
458             pointer++;
459             bufferin[pointer] = stream[pointer + offset];
460             pointer++;
461             bufferin[pointer] = stream[pointer + offset];
462             pointer++;
463             offset++;
464         }
465         break;
466     default:
467         ERR("Unknown bit depth %d\n", depth);
468         return;
469     }
470 }
471
472 static void renderer_YUV(const Capture *capBox, LPBYTE bufferin, const BYTE *stream)
473 {
474     enum YUV_Format format;
475
476     switch (capBox->pict.palette)
477     {
478     case  7: /* YUV422  -  same as YUYV */
479     case  8: /* YUYV    */
480         format = YUYV;
481         break;
482     case  9: /* UYVY    */
483         format = UYVY;
484         break;
485     case 11: /* YUV411  */
486         format = UYYVYY;
487         break;
488     case 13: /* YUV422P */
489         format = YUVP_421;
490         break;
491     case 14: /* YUV411P */
492         format = YUVP_441;
493         break;
494     case 15: /* YUV420P */
495         format = YUVP_422;
496         break;
497     case 16: /* YUV410P */
498         format = YUVP_444;
499         break;
500     default:
501         ERR("Unknown palette %d\n", capBox->pict.palette);
502         return;
503     }
504     YUV_To_RGB24(format, bufferin, stream, capBox->width, capBox->height);
505 }
506
507 static void Resize(const Capture * capBox, LPBYTE output, const BYTE *input)
508 {
509     /* the whole image needs to be reversed,
510        because the dibs are messed up in windows */
511     if (!capBox->swresize)
512     {
513         int depth = capBox->bitDepth / 8;
514         int inoffset = 0, outoffset = capBox->height * capBox->width * depth;
515         int ow = capBox->width * depth;
516         while (outoffset > 0)
517         {
518             int x;
519             outoffset -= ow;
520             for (x = 0; x < ow; x++)
521                 output[outoffset + x] = input[inoffset + x];
522             inoffset += ow;
523         }
524     }
525     else
526     {
527         HDC dc_s, dc_d;
528         HBITMAP bmp_s, bmp_d;
529         int depth = capBox->bitDepth / 8;
530         int inoffset = 0, outoffset = (capBox->outputheight) * capBox->outputwidth * depth;
531         int ow = capBox->outputwidth * depth;
532         LPBYTE myarray;
533
534         /* FIXME: Improve software resizing: add error checks and optimize */
535
536         myarray = CoTaskMemAlloc(capBox->outputwidth * capBox->outputheight * depth);
537         dc_s = CreateCompatibleDC(NULL);
538         dc_d = CreateCompatibleDC(NULL);
539         bmp_s = CreateBitmap(capBox->width, capBox->height, 1, capBox->bitDepth, input);
540         bmp_d = CreateBitmap(capBox->outputwidth, capBox->outputheight, 1, capBox->bitDepth, NULL);
541         SelectObject(dc_s, bmp_s);
542         SelectObject(dc_d, bmp_d);
543         StretchBlt(dc_d, 0, 0, capBox->outputwidth, capBox->outputheight,
544                    dc_s, 0, 0, capBox->width, capBox->height, SRCCOPY);
545         GetBitmapBits(bmp_d, capBox->outputwidth * capBox->outputheight * depth, myarray);
546         while (outoffset > 0)
547         {
548             int i;
549
550             outoffset -= ow;
551             for (i = 0; i < ow; i++)
552                 output[outoffset + i] = myarray[inoffset + i];
553             inoffset += ow;
554         }
555         CoTaskMemFree(myarray);
556         DeleteObject(dc_s);
557         DeleteObject(dc_d);
558         DeleteObject(bmp_s);
559         DeleteObject(bmp_d);
560     }
561 }
562
563 static void V4l_GetFrame(Capture * capBox, unsigned char ** pInput)
564 {
565     if (capBox->mmap)
566     {
567         if (xioctl(capBox->fd, VIDIOCSYNC, &capBox->grab_buf[capBox->curframe]) == -1)
568             WARN("Syncing ioctl failed: %d\n", errno);
569
570         *pInput = capBox->pmap + capBox->gb_buffers.offsets[capBox->curframe];
571     }
572     else
573     {
574         int retval;
575         while ((retval = video_read(capBox->fd, capBox->grab_data, capBox->imagesize)) == -1)
576             if (errno != EAGAIN) break;
577         if (retval == -1)
578             WARN("Error occurred while reading from device: %s\n", strerror(errno));
579         *pInput = (unsigned char*) capBox->grab_data;
580     }
581 }
582
583 static void V4l_FreeFrame(Capture * capBox)
584 {
585     TRACE("\n");
586     if (capBox->mmap)
587     {
588         if (xioctl(capBox->fd, VIDIOCMCAPTURE, &capBox->grab_buf[capBox->curframe]) == -1)
589            ERR("Freeing frame for capture failed: %s\n", strerror(errno));
590     }
591     if (++capBox->curframe == capBox->buffers)
592         capBox->curframe = 0;
593 }
594
595 static DWORD WINAPI ReadThread(LPVOID lParam)
596 {
597     Capture * capBox = lParam;
598     HRESULT hr;
599     IMediaSample *pSample = NULL;
600     ULONG framecount = 0;
601     unsigned char *pTarget, *pInput, *pOutput;
602
603     hr = V4l_Prepare(capBox);
604     if (FAILED(hr))
605         goto fail;
606
607     pOutput = CoTaskMemAlloc(capBox->width * capBox->height * capBox->bitDepth / 8);
608     capBox->curframe = 0;
609     do {
610         V4l_FreeFrame(capBox);
611     } while (capBox->curframe != 0);
612
613     while (1)
614     {
615         EnterCriticalSection(&capBox->CritSect);
616         if (capBox->stopped)
617             break;
618         hr = BaseOutputPinImpl_GetDeliveryBuffer((BaseOutputPin *)capBox->pOut, &pSample, NULL, NULL, 0);
619         if (SUCCEEDED(hr))
620         {
621             int len;
622             
623             if (!capBox->swresize)
624                 len = capBox->height * capBox->width * capBox->bitDepth / 8;
625             else
626                 len = capBox->outputheight * capBox->outputwidth * capBox->bitDepth / 8;
627             IMediaSample_SetActualDataLength(pSample, len);
628
629             len = IMediaSample_GetActualDataLength(pSample);
630             TRACE("Data length: %d KB\n", len / 1024);
631
632             IMediaSample_GetPointer(pSample, &pTarget);
633             /* FIXME: Check return values.. */
634             V4l_GetFrame(capBox, &pInput);
635             capBox->renderer(capBox, pOutput, pInput);
636             Resize(capBox, pTarget, pOutput);
637             hr = BaseOutputPinImpl_Deliver((BaseOutputPin *)capBox->pOut, pSample);
638             TRACE("%p -> Frame %u: %x\n", capBox, ++framecount, hr);
639             IMediaSample_Release(pSample);
640             V4l_FreeFrame(capBox);
641         }
642         LeaveCriticalSection(&capBox->CritSect);
643         if (FAILED(hr) && hr != VFW_E_NOT_CONNECTED)
644         {
645             ERR("Received error: %x\n", hr);
646             goto cfail;
647         }
648     }
649     LeaveCriticalSection(&capBox->CritSect);
650     CoTaskMemFree(pOutput);
651
652     return 0;
653
654 cfail:
655     CoTaskMemFree(pOutput);
656     V4l_Unprepare(capBox);
657     LeaveCriticalSection(&capBox->CritSect);
658
659 fail:
660     capBox->thread = 0; capBox->stopped = 1;
661     FIXME("Stop IFilterGraph\n");
662     return 0;
663 }
664
665 HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state)
666 {
667     HANDLE thread;
668     HRESULT hr;
669
670     TRACE("%p -> (%p)\n", capBox, state); 
671
672     if (*state == State_Running) return S_OK;
673
674     EnterCriticalSection(&capBox->CritSect);
675
676     capBox->stopped = 0;
677
678     if (*state == State_Stopped)
679     {
680         *state = State_Running;
681         if (!capBox->iscommitted++)
682         {
683             IMemAllocator * pAlloc = NULL;
684             ALLOCATOR_PROPERTIES ap, actual;
685             BaseOutputPin *out;
686
687             ap.cBuffers = 3;
688             if (!capBox->swresize)
689                 ap.cbBuffer = capBox->width * capBox->height;
690             else
691                 ap.cbBuffer = capBox->outputwidth * capBox->outputheight;
692             ap.cbBuffer = (ap.cbBuffer * capBox->bitDepth) / 8;
693             ap.cbAlign = 1;
694             ap.cbPrefix = 0;
695
696             out = (BaseOutputPin *)capBox->pOut;
697             hr = IMemInputPin_GetAllocator(out->pMemInputPin, &pAlloc);
698
699             if (SUCCEEDED(hr))
700                 hr = IMemAllocator_SetProperties(pAlloc, &ap, &actual);
701
702             if (SUCCEEDED(hr))
703                 hr = IMemAllocator_Commit(pAlloc);
704
705             if (pAlloc)
706                 IMemAllocator_Release(pAlloc);
707
708             TRACE("Committing allocator: %x\n", hr);
709         }
710
711         thread = CreateThread(NULL, 0, ReadThread, capBox, 0, NULL);
712         if (thread)
713         {
714             capBox->thread = thread;
715             SetThreadPriority(thread, THREAD_PRIORITY_LOWEST);
716             LeaveCriticalSection(&capBox->CritSect);
717             return S_OK;
718         }
719         ERR("Creating thread failed.. %u\n", GetLastError());
720         LeaveCriticalSection(&capBox->CritSect);
721         return E_FAIL;
722     }
723
724     ResumeThread(capBox->thread);
725     *state = State_Running;
726     LeaveCriticalSection(&capBox->CritSect);
727     return S_OK;
728 }
729
730 HRESULT qcap_driver_pause(Capture *capBox, FILTER_STATE *state)
731 {
732     TRACE("%p -> (%p)\n", capBox, state);     
733
734     if (*state == State_Paused)
735         return S_OK;
736     if (*state == State_Stopped)
737         qcap_driver_run(capBox, state);
738
739     EnterCriticalSection(&capBox->CritSect);
740     *state = State_Paused;
741     SuspendThread(capBox->thread);
742     LeaveCriticalSection(&capBox->CritSect);
743
744     return S_OK;
745 }
746
747 HRESULT qcap_driver_stop(Capture *capBox, FILTER_STATE *state)
748 {
749     TRACE("%p -> (%p)\n", capBox, state);
750
751     if (*state == State_Stopped)
752         return S_OK;
753
754     EnterCriticalSection(&capBox->CritSect);
755
756     if (capBox->thread)
757     {
758         if (*state == State_Paused)
759             ResumeThread(capBox->thread);
760         capBox->stopped = 1;
761         capBox->thread = 0;
762         if (capBox->iscommitted)
763         {
764             IMemInputPin *pMem = NULL;
765             IMemAllocator * pAlloc = NULL;
766             IPin *pConnect = NULL;
767             HRESULT hr;
768
769             capBox->iscommitted = 0;
770
771             hr = IPin_ConnectedTo(capBox->pOut, &pConnect);
772
773             if (SUCCEEDED(hr))
774                 hr = IPin_QueryInterface(pConnect, &IID_IMemInputPin, (void **) &pMem);
775
776             if (SUCCEEDED(hr))
777                 hr = IMemInputPin_GetAllocator(pMem, &pAlloc);
778
779             if (SUCCEEDED(hr))
780                 hr = IMemAllocator_Decommit(pAlloc);
781
782             if (pAlloc)
783                 IMemAllocator_Release(pAlloc);
784
785             if (pMem)
786                 IMemInputPin_Release(pMem);
787
788             if (pConnect)
789                 IPin_Release(pConnect);
790
791             if (hr != S_OK && hr != VFW_E_NOT_COMMITTED)
792                 WARN("Decommitting allocator: %x\n", hr);
793         }
794         V4l_Unprepare(capBox);
795     }
796
797     *state = State_Stopped;
798     LeaveCriticalSection(&capBox->CritSect);
799     return S_OK;
800 }
801
802 Capture * qcap_driver_init( IPin *pOut, USHORT card )
803 {
804     Capture * capBox = NULL;
805     char device[20];
806     struct video_capability capa;
807     struct video_picture pict;
808     struct video_window window;
809
810     YUV_Init();
811     video_init();
812
813     capBox = CoTaskMemAlloc(sizeof(Capture));
814     if (!capBox)
815         goto error;
816
817     /* capBox->vtbl = &defboxVtbl; */
818
819     InitializeCriticalSection( &capBox->CritSect );
820     capBox->CritSect.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": Capture.CritSect");
821
822     sprintf(device, "/dev/video%i", card);
823     TRACE("opening %s\n", device);
824     capBox->fd = video_open(device, O_RDWR | O_NONBLOCK);
825     if (capBox->fd == -1)
826     {
827         WARN("open failed (%d)\n", errno);
828         goto error;
829     }
830
831     memset(&capa, 0, sizeof(capa));
832
833     if (xioctl(capBox->fd, VIDIOCGCAP, &capa) == -1)
834     {
835         WARN("ioctl(VIDIOCGCAP) failed (%d)\n", errno);
836         goto error;
837     }
838
839     if (!(capa.type & VID_TYPE_CAPTURE))
840     {
841         WARN("not a video capture device\n");
842         goto error;
843     }
844
845     TRACE("%d inputs on %s\n", capa.channels, capa.name );
846
847     if (xioctl(capBox->fd, VIDIOCGPICT, &pict) == -1)
848     {
849         ERR("ioctl(VIDIOCGPICT) failed (%d)\n", errno );
850         goto error;
851     }
852
853     TRACE("depth %d palette %d (%s) hue %d color %d contrast %d\n",
854           pict.depth, pict.palette, renderlist_V4l[pict.palette].name,
855           pict.hue, pict.colour, pict.contrast );
856
857     capBox->dbrightness = pict.brightness;
858     capBox->dcolour = pict.colour;
859     capBox->dhue = pict.hue;
860     capBox->dcontrast = pict.contrast;
861
862     if (!renderlist_V4l[pict.palette].renderer)
863     {
864         int palet = pict.palette, i;
865
866         TRACE("No renderer available for %s, falling back to defaults\n",
867              renderlist_V4l[pict.palette].name);
868         capBox->renderer = NULL;
869         for (i = 0; fallback_V4l[i] >=0 ; i++)
870         {
871             int n = fallback_V4l[i];
872
873             if (renderlist_V4l[n].renderer == NULL)
874                 continue;
875
876             pict.depth = renderlist_V4l[n].depth;
877             pict.palette = n;
878             if (xioctl(capBox->fd, VIDIOCSPICT, &pict) == -1)
879             {
880                 TRACE("Could not render with %s (%d)\n",
881                       renderlist_V4l[n].name, n);
882                 continue;
883             }
884             TRACE("using renderer %s (%d)\n", 
885                   renderlist_V4l[n].name, n);
886             capBox->renderer = renderlist_V4l[n].renderer;
887             break;
888         }
889
890         if (!capBox->renderer)
891         {
892             ERR("video format %s isn't available\n",
893                  renderlist_V4l[palet].name);
894             goto error;
895         }
896     }
897     else
898     {
899         TRACE("Using the suggested format\n");
900         capBox->renderer = renderlist_V4l[pict.palette].renderer;
901     }
902     memcpy(&capBox->pict, &pict, sizeof(struct video_picture));
903
904     memset(&window, 0, sizeof(window));
905     if (xioctl(capBox->fd, VIDIOCGWIN, &window) == -1)
906     {
907         WARN("VIDIOCGWIN failed (%d)\n", errno);
908         goto error;
909     }
910
911     capBox->height = capBox->outputheight = window.height;
912     capBox->width = capBox->outputwidth = window.width;
913     capBox->swresize = FALSE;
914     capBox->bitDepth = 24;
915     capBox->pOut = pOut;
916     capBox->fps = 3;
917     capBox->stopped = 0;
918     capBox->curframe = 0;
919     capBox->iscommitted = 0;
920
921     TRACE("format: %d bits - %d x %d\n", capBox->bitDepth, capBox->width, capBox->height);
922
923     return capBox;
924
925 error:
926     if (capBox)
927         qcap_driver_destroy( capBox );
928
929     return NULL;
930 }
931
932 #else
933
934 Capture * qcap_driver_init( IPin *pOut, USHORT card )
935 {
936     const char msg[] = 
937         "The v4l headers were not available at compile time,\n"
938         "so video capture support is not available.\n";
939     MESSAGE(msg);
940     return NULL;
941 }
942
943 #define FAIL_WITH_ERR \
944     ERR("v4l absent: shouldn't be called\n"); \
945     return E_NOTIMPL
946
947 HRESULT qcap_driver_destroy(Capture *capBox)
948 {
949     FAIL_WITH_ERR;
950 }
951
952 HRESULT qcap_driver_set_format(Capture *capBox, AM_MEDIA_TYPE * mT)
953 {
954     FAIL_WITH_ERR;
955 }
956
957 HRESULT qcap_driver_get_format(const Capture *capBox, AM_MEDIA_TYPE ** mT)
958 {
959     FAIL_WITH_ERR;
960 }
961
962 HRESULT qcap_driver_get_prop_range( Capture *capBox,
963         VideoProcAmpProperty  Property, LONG *pMin, LONG *pMax,
964         LONG *pSteppingDelta, LONG *pDefault, LONG *pCapsFlags )
965 {
966     FAIL_WITH_ERR;
967 }
968
969 HRESULT qcap_driver_get_prop(Capture *capBox,
970         VideoProcAmpProperty Property, LONG *lValue, LONG *Flags)
971 {
972     FAIL_WITH_ERR;
973 }
974
975 HRESULT qcap_driver_set_prop(Capture *capBox, VideoProcAmpProperty Property,
976         LONG lValue, LONG Flags)
977 {
978     FAIL_WITH_ERR;
979 }
980
981 HRESULT qcap_driver_run(Capture *capBox, FILTER_STATE *state)
982 {
983     FAIL_WITH_ERR;
984 }
985
986 HRESULT qcap_driver_pause(Capture *capBox, FILTER_STATE *state)
987 {
988     FAIL_WITH_ERR;
989 }
990
991 HRESULT qcap_driver_stop(Capture *capBox, FILTER_STATE *state)
992 {
993     FAIL_WITH_ERR;
994 }
995
996 #endif /* HAVE_LINUX_VIDEODEV_H */