]> git.sesse.net Git - vlc/blob - modules/access/dshow/dshow.cpp
* modules/access/dshow/dshow.cpp: compilation fix.
[vlc] / modules / access / dshow / dshow.cpp
1 /*****************************************************************************
2  * dshow.cpp : DirectShow access module for vlc
3  *****************************************************************************
4  * Copyright (C) 2002, 2003 VideoLAN
5  * $Id$
6  *
7  * Author: Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30
31 #include <vlc/vlc.h>
32 #include <vlc/input.h>
33 #include <vlc/vout.h>
34
35 #include "filter.h"
36
37 /*****************************************************************************
38  * Access: local prototypes
39  *****************************************************************************/
40 static ssize_t Read          ( input_thread_t *, byte_t *, size_t );
41 static ssize_t ReadCompressed( input_thread_t *, byte_t *, size_t );
42
43 static int OpenDevice( input_thread_t *, string, vlc_bool_t );
44 static IBaseFilter *FindCaptureDevice( vlc_object_t *, string *,
45                                        list<string> *, vlc_bool_t );
46 static AM_MEDIA_TYPE EnumDeviceCaps( vlc_object_t *, IBaseFilter *,
47                                      int, int, int, int, int, int );
48 static bool ConnectFilters( vlc_object_t *, IFilterGraph *,
49                             IBaseFilter *, IPin * );
50
51 static int FindDevicesCallback( vlc_object_t *, char const *,
52                                 vlc_value_t, vlc_value_t, void * );
53 static int ConfigDevicesCallback( vlc_object_t *, char const *,
54                                   vlc_value_t, vlc_value_t, void * );
55
56 static void PropertiesPage( vlc_object_t *, IBaseFilter * );
57
58 #if 0
59     /* Debug only, use this to find out GUIDs */
60     unsigned char p_st[];
61     UuidToString( (IID *)&IID_IAMBufferNegotiation, &p_st );
62     msg_Err( p_input, "BufferNegotiation: %s" , p_st );
63 #endif
64
65 /*
66  * header:
67  *  fcc  ".dsh"
68  *  u32    stream count
69  *      fcc "auds"|"vids"       0
70  *      fcc codec               4
71  *      if vids
72  *          u32 width           8
73  *          u32 height          12
74  *          u32 padding         16
75  *      if auds
76  *          u32 channels        12
77  *          u32 samplerate      8
78  *          u32 samplesize      16
79  *
80  * data:
81  *  u32     stream number
82  *  u32     data size
83  *  u8      data
84  */
85
86 static void SetDWBE( uint8_t *p, uint32_t dw )
87 {
88     p[0] = (dw >> 24)&0xff;
89     p[1] = (dw >> 16)&0xff;
90     p[2] = (dw >>  8)&0xff;
91     p[3] = (dw      )&0xff;
92 }
93
94 static void SetQWBE( uint8_t *p, uint64_t qw )
95 {
96     SetDWBE( p, (qw >> 32)&0xffffffff );
97     SetDWBE( &p[4], qw&0xffffffff );
98 }
99
100 /*****************************************************************************
101  * Module descriptor
102  *****************************************************************************/
103 static char *ppsz_vdev[] = { "", "none" };
104 static char *ppsz_vdev_text[] = { N_("Default"), N_("None") };
105 static char *ppsz_adev[] = { "", "none" };
106 static char *ppsz_adev_text[] = { N_("Default"), N_("None") };
107
108 #define CACHING_TEXT N_("Caching value in ms")
109 #define CACHING_LONGTEXT N_( \
110     "Allows you to modify the default caching value for directshow streams. " \
111     "This value should be set in milliseconds units." )
112 #define VDEV_TEXT N_("Video device name")
113 #define VDEV_LONGTEXT N_( \
114     "You can specify the name of the video device that will be used by the " \
115     "DirectShow plugin. If you don't specify anything, the default device " \
116     "will be used.")
117 #define ADEV_TEXT N_("Audio device name")
118 #define ADEV_LONGTEXT N_( \
119     "You can specify the name of the audio device that will be used by the " \
120     "DirectShow plugin. If you don't specify anything, the default device " \
121     "will be used.")
122 #define SIZE_TEXT N_("Video size")
123 #define SIZE_LONGTEXT N_( \
124     "You can specify the size of the video that will be displayed by the " \
125     "DirectShow plugin. If you don't specify anything the default size for " \
126     "your device will be used.")
127 #define CHROMA_TEXT N_("Video input chroma format")
128 #define CHROMA_LONGTEXT N_( \
129     "Force the DirectShow video input to use a specific chroma format " \
130     "(eg. I420 (default), RV24, etc.)")
131 #define CONFIG_TEXT N_("Device properties")
132 #define CONFIG_LONGTEXT N_( \
133     "Show the properties dialog of the selected device.")
134
135 static int  AccessOpen ( vlc_object_t * );
136 static void AccessClose( vlc_object_t * );
137
138 static int  DemuxOpen  ( vlc_object_t * );
139 static void DemuxClose ( vlc_object_t * );
140
141 vlc_module_begin();
142     set_description( _("DirectShow input") );
143     add_integer( "dshow-caching", (mtime_t)(0.2*CLOCK_FREQ) / 1000, NULL,
144                  CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
145
146     add_string( "dshow-vdev", NULL, NULL, VDEV_TEXT, VDEV_LONGTEXT, VLC_FALSE);
147         change_string_list( ppsz_vdev, ppsz_vdev_text, FindDevicesCallback );
148         change_action_add( FindDevicesCallback, N_("Refresh list") );
149         change_action_add( ConfigDevicesCallback, N_("Configure") );
150
151     add_string( "dshow-adev", NULL, NULL, ADEV_TEXT, ADEV_LONGTEXT, VLC_FALSE);
152         change_string_list( ppsz_adev, ppsz_adev_text, FindDevicesCallback );
153         change_action_add( FindDevicesCallback, N_("Refresh list") );
154         change_action_add( ConfigDevicesCallback, N_("Configure") );
155
156     add_string( "dshow-size", NULL, NULL, SIZE_TEXT, SIZE_LONGTEXT, VLC_FALSE);
157
158     add_string( "dshow-chroma", NULL, NULL, CHROMA_TEXT, CHROMA_LONGTEXT,
159                 VLC_TRUE );
160
161     add_bool( "dshow-config", VLC_FALSE, NULL, CONFIG_TEXT, CONFIG_LONGTEXT,
162               VLC_TRUE );
163
164     add_shortcut( "dshow" );
165     set_capability( "access", 0 );
166     set_callbacks( AccessOpen, AccessClose );
167
168     add_submodule();
169     set_description( _("DirectShow demuxer") );
170     add_shortcut( "dshow" );
171     set_capability( "demux", 200 );
172     set_callbacks( DemuxOpen, DemuxClose );
173
174 vlc_module_end();
175
176 /****************************************************************************
177  * DirectShow elementary stream descriptor
178  ****************************************************************************/
179 typedef struct dshow_stream_t
180 {
181     string          devicename;
182     IBaseFilter     *p_device_filter;
183     CaptureFilter   *p_capture_filter;
184     AM_MEDIA_TYPE   mt;
185     int             i_fourcc;
186     vlc_bool_t      b_invert;
187
188     union
189     {
190       VIDEOINFOHEADER video;
191       WAVEFORMATEX    audio;
192
193     } header;
194
195     vlc_bool_t      b_pts;
196
197 } dshow_stream_t;
198
199 /****************************************************************************
200  * Access descriptor declaration
201  ****************************************************************************/
202 struct access_sys_t
203 {
204     vlc_mutex_t lock;
205     vlc_cond_t  wait;
206
207     IFilterGraph  *p_graph;
208     IMediaControl *p_control;
209
210     /* header */
211     int     i_header_size;
212     int     i_header_pos;
213     uint8_t *p_header;
214
215     /* list of elementary streams */
216     dshow_stream_t **pp_streams;
217     int            i_streams;
218     int            i_current_stream;
219
220     /* misc properties */
221     int            i_width;
222     int            i_height;
223     int            i_chroma;
224     int            b_audio;
225 };
226
227 /*****************************************************************************
228  * Open: open direct show device
229  *****************************************************************************/
230 static int AccessOpen( vlc_object_t *p_this )
231 {
232     input_thread_t *p_input = (input_thread_t *)p_this;
233     access_sys_t   *p_sys;
234     vlc_value_t    val;
235
236     /* Get/parse options and open device(s) */
237     string vdevname, adevname;
238     int i_width = 0, i_height = 0, i_chroma = 0;
239
240     var_Create( p_input, "dshow-vdev", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
241     var_Get( p_input, "dshow-vdev", &val );
242     if( val.psz_string ) vdevname = string( val.psz_string );
243     if( val.psz_string ) free( val.psz_string );
244
245     var_Create( p_input, "dshow-adev", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
246     var_Get( p_input, "dshow-adev", &val );
247     if( val.psz_string ) adevname = string( val.psz_string );
248     if( val.psz_string ) free( val.psz_string );
249
250     var_Create( p_input, "dshow-size", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
251     var_Get( p_input, "dshow-size", &val );
252     if( val.psz_string && *val.psz_string )
253     {
254         if( !strcmp( val.psz_string, "subqcif" ) )
255         {
256             i_width  = 128; i_height = 96;
257         }
258         else if( !strcmp( val.psz_string, "qsif" ) )
259         {
260             i_width  = 160; i_height = 120;
261         }
262         else if( !strcmp( val.psz_string, "qcif" ) )
263         {
264             i_width  = 176; i_height = 144;
265         }
266         else if( !strcmp( val.psz_string, "sif" ) )
267         {
268             i_width  = 320; i_height = 240;
269         }
270         else if( !strcmp( val.psz_string, "cif" ) )
271         {
272             i_width  = 352; i_height = 288;
273         }
274         else if( !strcmp( val.psz_string, "vga" ) )
275         {
276             i_width  = 640; i_height = 480;
277         }
278         else
279         {
280             /* Width x Height */
281             char *psz_parser;
282             i_width = strtol( val.psz_string, &psz_parser, 0 );
283             if( *psz_parser == 'x' || *psz_parser == 'X')
284             {
285                 i_height = strtol( psz_parser + 1, &psz_parser, 0 );
286             }
287             msg_Dbg( p_input, "Width x Height %dx%d", i_width, i_height );
288         }
289     }
290     if( val.psz_string ) free( val.psz_string );
291
292     var_Create( p_input, "dshow-chroma", VLC_VAR_STRING | VLC_VAR_DOINHERIT);
293     var_Get( p_input, "dshow-chroma", &val );
294     if( val.psz_string && strlen( val.psz_string ) >= 4 )
295     {
296         i_chroma = VLC_FOURCC( val.psz_string[0], val.psz_string[1],
297                                val.psz_string[2], val.psz_string[3] );
298     }
299     if( val.psz_string ) free( val.psz_string );
300
301     p_input->pf_read        = Read;
302     p_input->pf_seek        = NULL;
303     p_input->pf_set_area    = NULL;
304     p_input->pf_set_program = NULL;
305
306     vlc_mutex_lock( &p_input->stream.stream_lock );
307     p_input->stream.b_pace_control = 0;
308     p_input->stream.b_seekable = 0;
309     p_input->stream.p_selected_area->i_size = 0;
310     p_input->stream.p_selected_area->i_tell = 0;
311     p_input->stream.i_method = INPUT_METHOD_FILE;
312     vlc_mutex_unlock( &p_input->stream.stream_lock );
313
314     var_Create( p_input, "dshow-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT);
315     var_Get( p_input, "dshow-caching", &val );
316     p_input->i_pts_delay = val.i_int * 1000;
317
318     /* Initialize OLE/COM */
319     CoInitialize( 0 );
320
321     /* create access private data */
322     p_input->p_access_data = p_sys =
323         (access_sys_t *)malloc( sizeof( access_sys_t ) );
324
325     /* Initialize some data */
326     p_sys->i_streams = 0;
327     p_sys->pp_streams = (dshow_stream_t **)malloc( 1 );
328     p_sys->i_width = i_width;
329     p_sys->i_height = i_height;
330     p_sys->i_chroma = i_chroma;
331     p_sys->b_audio = VLC_TRUE;
332
333     /* Create header */
334     p_sys->i_header_size = 8;
335     p_sys->p_header      = (uint8_t *)malloc( p_sys->i_header_size );
336     memcpy(  &p_sys->p_header[0], ".dsh", 4 );
337     SetDWBE( &p_sys->p_header[4], 1 );
338     p_sys->i_header_pos = p_sys->i_header_size;
339
340     /* Build directshow graph */
341     CoCreateInstance( CLSID_FilterGraph, 0, CLSCTX_INPROC,
342                       (REFIID)IID_IFilterGraph, (void **)&p_sys->p_graph );
343
344     p_sys->p_graph->QueryInterface( IID_IMediaControl,
345                                     (void **)&p_sys->p_control );
346
347     if( OpenDevice( p_input, vdevname, 0 ) != VLC_SUCCESS )
348     {
349         msg_Err( p_input, "can't open video");
350     }
351
352     if( p_sys->b_audio && OpenDevice( p_input, adevname, 1 ) != VLC_SUCCESS )
353     {
354         msg_Err( p_input, "can't open audio");
355     }
356
357     if( !p_sys->i_streams )
358     {
359         /* Release directshow objects */
360         if( p_sys->p_control ) p_sys->p_control->Release();
361         p_sys->p_graph->Release();
362
363         /* Uninitialize OLE/COM */
364         CoUninitialize();
365
366         free( p_sys->p_header );
367         free( p_sys->pp_streams );
368         free( p_sys );
369         return VLC_EGENERIC;
370     }
371
372     /* Initialize some data */
373     p_sys->i_current_stream = 0;
374     p_input->i_mtu += p_sys->i_header_size + 16 /* data header size */;
375
376     vlc_mutex_init( p_input, &p_sys->lock );
377     vlc_cond_init( p_input, &p_sys->wait );
378
379     /* Everything is ready. Let's rock baby */
380     p_sys->p_control->Run();
381
382     return VLC_SUCCESS;
383 }
384
385 /*****************************************************************************
386  * AccessClose: close device
387  *****************************************************************************/
388 static void AccessClose( vlc_object_t *p_this )
389 {
390     input_thread_t *p_input = (input_thread_t *)p_this;
391     access_sys_t    *p_sys  = p_input->p_access_data;
392
393     /* Stop capturing stuff */
394     //p_sys->p_control->Stop(); /* FIXME?: we get stuck here sometimes */
395     p_sys->p_control->Release();
396
397     /* Remove filters from graph */
398     for( int i = 0; i < p_sys->i_streams; i++ )
399     {
400         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_capture_filter );
401         p_sys->p_graph->RemoveFilter( p_sys->pp_streams[i]->p_device_filter );
402         p_sys->pp_streams[i]->p_capture_filter->Release();
403         p_sys->pp_streams[i]->p_device_filter->Release();
404     }
405     p_sys->p_graph->Release();
406
407     /* Uninitialize OLE/COM */
408     CoUninitialize();
409
410     free( p_sys->p_header );
411     for( int i = 0; i < p_sys->i_streams; i++ ) delete p_sys->pp_streams[i];
412     free( p_sys->pp_streams );
413     free( p_sys );
414 }
415
416 /****************************************************************************
417  * ConnectFilters
418  ****************************************************************************/
419 static bool ConnectFilters( vlc_object_t *p_this, IFilterGraph *p_graph,
420                             IBaseFilter *p_filter, IPin *p_input_pin )
421 {
422     IEnumPins *p_enumpins;
423     IPin *p_pin;
424
425     if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return false;
426
427     while( S_OK == p_enumpins->Next( 1, &p_pin, NULL ) )
428     {
429         PIN_DIRECTION pin_dir;
430         p_pin->QueryDirection( &pin_dir );
431
432         if( pin_dir == PINDIR_OUTPUT &&
433             S_OK == p_graph->ConnectDirect( p_pin, p_input_pin, 0 ) )
434         {
435             p_pin->Release();
436             p_enumpins->Release();
437             return true;
438         }
439         p_pin->Release();
440     }
441
442     p_enumpins->Release();
443     return false;
444 }
445
446 static int OpenDevice( input_thread_t *p_input, string devicename,
447                        vlc_bool_t b_audio )
448 {
449     access_sys_t *p_sys = p_input->p_access_data;
450     list<string> list_devices;
451
452     /* Enumerate devices and display their names */
453     FindCaptureDevice( (vlc_object_t *)p_input, NULL, &list_devices, b_audio );
454
455     if( !list_devices.size() )
456         return VLC_EGENERIC;
457
458     list<string>::iterator iter;
459     for( iter = list_devices.begin(); iter != list_devices.end(); iter++ )
460         msg_Dbg( p_input, "found device: %s", iter->c_str() );
461
462     /* If no device name was specified, pick the 1st one */
463     if( devicename.size() == 0 )
464     {
465         devicename = *list_devices.begin();
466     }
467
468     // Use the system device enumerator and class enumerator to find
469     // a capture/preview device, such as a desktop USB video camera.
470     IBaseFilter *p_device_filter =
471         FindCaptureDevice( (vlc_object_t *)p_input, &devicename,
472                            NULL, b_audio );
473     if( p_device_filter )
474         msg_Dbg( p_input, "using device: %s", devicename.c_str() );
475     else
476     {
477         msg_Err( p_input, "can't use device: %s", devicename.c_str() );
478         return VLC_EGENERIC;
479     }
480
481     AM_MEDIA_TYPE media_type =
482         EnumDeviceCaps( (vlc_object_t *)p_input, p_device_filter,
483                         p_sys->i_chroma, p_sys->i_width, p_sys->i_height,
484                         0, 0, 0 );
485
486     /* Create and add our capture filter */
487     CaptureFilter *p_capture_filter = new CaptureFilter( p_input, media_type );
488     p_sys->p_graph->AddFilter( p_capture_filter, 0 );
489
490     /* Add the device filter to the graph (seems necessary with VfW before
491      * accessing pin attributes). */
492     p_sys->p_graph->AddFilter( p_device_filter, 0 );
493
494     /* Attempt to connect one of this device's capture output pins */
495     msg_Dbg( p_input, "connecting filters" );
496     if( ConnectFilters( VLC_OBJECT(p_input), p_sys->p_graph, p_device_filter,
497                         p_capture_filter->CustomGetPin() ) )
498     {
499         /* Success */
500         dshow_stream_t dshow_stream;
501         dshow_stream.b_invert = VLC_FALSE;
502         dshow_stream.b_pts = VLC_FALSE;
503         dshow_stream.mt =
504             p_capture_filter->CustomGetPin()->CustomGetMediaType();
505
506         if( dshow_stream.mt.majortype == MEDIATYPE_Video )
507         {
508             msg_Dbg( p_input, "MEDIATYPE_Video");
509
510             /* Packed RGB formats */
511             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB1 )
512                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '1' );
513             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB4 )
514                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '4' );
515             if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB8 )
516                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', '8' );
517             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB555 )
518                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '1', '5' );
519             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB565 )
520                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '1', '6' );
521             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB24 )
522                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '2', '4' );
523             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_RGB32 )
524                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'V', '3', '2' );
525             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_ARGB32 )
526                 dshow_stream.i_fourcc = VLC_FOURCC( 'R', 'G', 'B', 'A' );
527
528             /* Packed YUV formats */
529             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YVYU )
530                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', 'Y', 'U' );
531             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YUYV )
532                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', 'V' );
533             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y411 )
534                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '1', 'N' );
535             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y211 )
536                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', '2', '1', '1' );
537             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YUY2 ||
538                      dshow_stream.mt.subtype == MEDIASUBTYPE_UYVY )
539                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'U', 'Y', '2' );
540
541             /* Planar YUV formats */
542             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_I420 )
543                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '2', '0' );
544             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_Y41P )
545                 dshow_stream.i_fourcc = VLC_FOURCC( 'I', '4', '1', '1' );
546             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YV12 ||
547                      dshow_stream.mt.subtype == MEDIASUBTYPE_IYUV )
548                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', '1', '2' );
549             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_YVU9 )
550                 dshow_stream.i_fourcc = VLC_FOURCC( 'Y', 'V', 'U', '9' );
551
552             /* DV formats */
553             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvsl )
554                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 's', 'l' );
555             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvsd )
556                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 's', 'd' );
557             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_dvhd )
558                 dshow_stream.i_fourcc = VLC_FOURCC( 'd', 'v', 'h', 'd' );
559
560             /* MPEG video formats */
561             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_VIDEO )
562                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 'v' );
563
564             else goto fail;
565
566             dshow_stream.header.video =
567                 *(VIDEOINFOHEADER *)dshow_stream.mt.pbFormat;
568
569             int i_height = dshow_stream.header.video.bmiHeader.biHeight;
570
571             /* Check if the image is inverted (bottom to top) */
572             if( dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '1' ) ||
573                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '4' ) ||
574                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', '8' ) ||
575                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '5' ) ||
576                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '1', '6' ) ||
577                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '2', '4' ) ||
578                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'V', '3', '2' ) ||
579                 dshow_stream.i_fourcc == VLC_FOURCC( 'R', 'G', 'B', 'A' ) )
580             {
581                 if( i_height > 0 ) dshow_stream.b_invert = VLC_TRUE;
582                 else i_height = - i_height;
583             }
584
585             /* Check if we are dealing with a DV stream */
586             if( dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'l' ) ||
587                 dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 's', 'd' ) ||
588                 dshow_stream.i_fourcc == VLC_FOURCC( 'd', 'v', 'h', 'd' ) )
589             {
590                 p_input->pf_read = ReadCompressed;
591                 if( !p_input->psz_demux || !*p_input->psz_demux )
592                 {
593                     p_input->psz_demux = "rawdv";
594                 }
595                 p_sys->b_audio = VLC_FALSE;
596             }
597
598             /* Check if we are dealing with an MPEG video stream */
599             if( dshow_stream.i_fourcc == VLC_FOURCC( 'm', 'p', '2', 'v' ) )
600             {
601                 p_input->pf_read = ReadCompressed;
602                 if( !p_input->psz_demux || !*p_input->psz_demux )
603                 {
604                     p_input->psz_demux = "mpgv";
605                 }
606                 p_sys->b_audio = VLC_FALSE;
607             }
608
609             /* Add video stream to header */
610             p_sys->i_header_size += 20;
611             p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
612                                                   p_sys->i_header_size );
613             memcpy(  &p_sys->p_header[p_sys->i_header_pos], "vids", 4 );
614             memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
615                      &dshow_stream.i_fourcc, 4 );
616             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
617                      dshow_stream.header.video.bmiHeader.biWidth );
618             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12], i_height );
619             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16], 0 );
620             p_sys->i_header_pos = p_sys->i_header_size;
621
622             /* Greatly simplifies the reading routine */
623             int i_mtu = dshow_stream.header.video.bmiHeader.biWidth *
624                 i_height * 4;
625             p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
626         }
627
628         else if( dshow_stream.mt.majortype == MEDIATYPE_Audio &&
629                  dshow_stream.mt.formattype == FORMAT_WaveFormatEx )
630         {
631             msg_Dbg( p_input, "MEDIATYPE_Audio");
632
633             if( dshow_stream.mt.subtype == MEDIASUBTYPE_PCM )
634                 dshow_stream.i_fourcc = VLC_FOURCC( 'a', 'r', 'a', 'w' );
635             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_IEEE_FLOAT )
636                 dshow_stream.i_fourcc = VLC_FOURCC( 'f', 'l', '3', '2' );
637             else goto fail;
638
639             dshow_stream.header.audio =
640                 *(WAVEFORMATEX *)dshow_stream.mt.pbFormat;
641
642             /* Add audio stream to header */
643             p_sys->i_header_size += 20;
644             p_sys->p_header = (uint8_t *)realloc( p_sys->p_header,
645                                                   p_sys->i_header_size );
646             memcpy(  &p_sys->p_header[p_sys->i_header_pos], "auds", 4 );
647             memcpy(  &p_sys->p_header[p_sys->i_header_pos + 4],
648                      &dshow_stream.i_fourcc, 4 );
649             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 8],
650                      dshow_stream.header.audio.nChannels );
651             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 12],
652                      dshow_stream.header.audio.nSamplesPerSec );
653             SetDWBE( &p_sys->p_header[p_sys->i_header_pos + 16],
654                      dshow_stream.header.audio.wBitsPerSample );
655             p_sys->i_header_pos = p_sys->i_header_size;
656
657             /* Greatly simplifies the reading routine */
658             IAMBufferNegotiation *p_ambuf;
659             IPin *p_pin;
660             int i_mtu;
661
662             p_capture_filter->CustomGetPin()->ConnectedTo( &p_pin );
663             if( SUCCEEDED( p_pin->QueryInterface(
664                   IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
665             {
666                 ALLOCATOR_PROPERTIES AllocProp;
667                 memset( &AllocProp, 0, sizeof( ALLOCATOR_PROPERTIES ) );
668                 p_ambuf->GetAllocatorProperties( &AllocProp );
669                 p_ambuf->Release();
670                 i_mtu = AllocProp.cbBuffer;
671             }
672             else
673             {
674                 /* Worst case */
675                 i_mtu = dshow_stream.header.audio.nSamplesPerSec *
676                         dshow_stream.header.audio.nChannels *
677                         dshow_stream.header.audio.wBitsPerSample / 8;
678             }
679             p_pin->Release();
680             p_input->i_mtu = __MAX( p_input->i_mtu, (unsigned int)i_mtu );
681         }
682
683         else if( dshow_stream.mt.majortype == MEDIATYPE_Stream )
684         {
685             msg_Dbg( p_input, "MEDIATYPE_Stream" );
686
687             if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_PROGRAM )
688                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 'p' );
689             else if( dshow_stream.mt.subtype == MEDIASUBTYPE_MPEG2_TRANSPORT )
690                 dshow_stream.i_fourcc = VLC_FOURCC( 'm', 'p', '2', 't' );
691
692             msg_Dbg( p_input, "selected stream pin accepts format: %4.4s",
693                      (char *)&dshow_stream.i_fourcc);
694
695             p_sys->b_audio = VLC_FALSE;
696             p_sys->i_header_size = 0;
697             p_sys->i_header_pos = 0;
698             p_input->i_mtu = INPUT_DEFAULT_BUFSIZE;
699
700             p_input->pf_read = ReadCompressed;
701             p_input->pf_set_program = input_SetProgram;
702         }
703
704         else
705         {
706             msg_Dbg( p_input, "unknown stream majortype" );
707             goto fail;
708         }
709
710         /* Show properties */
711         vlc_value_t val;
712         var_Create( p_input, "dshow-config",
713                     VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
714         var_Get( p_input, "dshow-config", &val );
715
716         if(val.i_int) PropertiesPage( VLC_OBJECT(p_input), p_device_filter );
717
718         /* Add directshow elementary stream to our list */
719         dshow_stream.p_device_filter = p_device_filter;
720         dshow_stream.p_capture_filter = p_capture_filter;
721
722         p_sys->pp_streams =
723             (dshow_stream_t **)realloc( p_sys->pp_streams,
724                                         sizeof(dshow_stream_t *)
725                                         * (p_sys->i_streams + 1) );
726         p_sys->pp_streams[p_sys->i_streams] = new dshow_stream_t;
727         *p_sys->pp_streams[p_sys->i_streams++] = dshow_stream;
728         SetDWBE( &p_sys->p_header[4], (uint32_t)p_sys->i_streams );
729
730         return VLC_SUCCESS;
731     }
732
733  fail:
734     /* Remove filters from graph */
735     p_sys->p_graph->RemoveFilter( p_device_filter );
736     p_sys->p_graph->RemoveFilter( p_capture_filter );
737
738     /* Release objects */
739     p_device_filter->Release();
740     p_capture_filter->Release();
741
742     return VLC_EGENERIC;
743 }
744
745 static IBaseFilter *
746 FindCaptureDevice( vlc_object_t *p_this, string *p_devicename,
747                    list<string> *p_listdevices, vlc_bool_t b_audio )
748 {
749     IBaseFilter *p_base_filter = NULL;
750     IMoniker *p_moniker = NULL;
751     ULONG i_fetched;
752     HRESULT hr;
753
754     /* Create the system device enumerator */
755     ICreateDevEnum *p_dev_enum = NULL;
756
757     hr = CoCreateInstance( CLSID_SystemDeviceEnum, NULL, CLSCTX_INPROC,
758                            IID_ICreateDevEnum, (void **)&p_dev_enum );
759     if( FAILED(hr) )
760     {
761         msg_Err( p_this, "failed to create the device enumerator (0x%x)", hr);
762         return NULL;
763     }
764
765     /* Create an enumerator for the video capture devices */
766     IEnumMoniker *p_class_enum = NULL;
767     if( !b_audio )
768         hr = p_dev_enum->CreateClassEnumerator( CLSID_VideoInputDeviceCategory,
769                                                 &p_class_enum, 0 );
770     else
771         hr = p_dev_enum->CreateClassEnumerator( CLSID_AudioInputDeviceCategory,
772                                                 &p_class_enum, 0 );
773     p_dev_enum->Release();
774     if( FAILED(hr) )
775     {
776         msg_Err( p_this, "failed to create the class enumerator (0x%x)", hr );
777         return NULL;
778     }
779
780     /* If there are no enumerators for the requested type, then
781      * CreateClassEnumerator will succeed, but p_class_enum will be NULL */
782     if( p_class_enum == NULL )
783     {
784         msg_Err( p_this, "no capture device was detected" );
785         return NULL;
786     }
787
788     /* Enumerate the devices */
789
790     /* Note that if the Next() call succeeds but there are no monikers,
791      * it will return S_FALSE (which is not a failure). Therefore, we check
792      * that the return code is S_OK instead of using SUCCEEDED() macro. */
793
794     while( p_class_enum->Next( 1, &p_moniker, &i_fetched ) == S_OK )
795     {
796         /* Getting the property page to get the device name */
797         IPropertyBag *p_bag;
798         hr = p_moniker->BindToStorage( 0, 0, IID_IPropertyBag,
799                                        (void **)&p_bag );
800         if( SUCCEEDED(hr) )
801         {
802             VARIANT var;
803             var.vt = VT_BSTR;
804             hr = p_bag->Read( L"FriendlyName", &var, NULL );
805             p_bag->Release();
806             if( SUCCEEDED(hr) )
807             {
808                 int i_convert = ( lstrlenW( var.bstrVal ) + 1 ) * 2;
809                 char *p_buf = (char *)alloca( i_convert ); p_buf[0] = 0;
810                 WideCharToMultiByte( CP_ACP, 0, var.bstrVal, -1, p_buf,
811                                      i_convert, NULL, NULL );
812                 SysFreeString(var.bstrVal);
813
814                 if( p_listdevices ) p_listdevices->push_back( p_buf );
815
816                 if( p_devicename && *p_devicename == string(p_buf) )
817                 {
818                     /* Bind Moniker to a filter object */
819                     hr = p_moniker->BindToObject( 0, 0, IID_IBaseFilter,
820                                                   (void **)&p_base_filter );
821                     if( FAILED(hr) )
822                     {
823                         msg_Err( p_this, "couldn't bind moniker to filter "
824                                  "object (0x%x)", hr );
825                         p_moniker->Release();
826                         p_class_enum->Release();
827                         return NULL;
828                     }
829                     p_moniker->Release();
830                     p_class_enum->Release();
831                     return p_base_filter;
832                 }
833             }
834         }
835
836         p_moniker->Release();
837     }
838
839     p_class_enum->Release();
840     return NULL;
841 }
842
843 static AM_MEDIA_TYPE EnumDeviceCaps( vlc_object_t *p_this,
844                                      IBaseFilter *p_filter,
845                                      int i_fourcc, int i_width, int i_height,
846                                      int i_channels, int i_samplespersec,
847                                      int i_bitspersample )
848 {
849     IEnumPins *p_enumpins;
850     IPin *p_output_pin;
851     IEnumMediaTypes *p_enummt;
852     int i_orig_fourcc = i_fourcc;
853     vlc_bool_t b_found = VLC_FALSE;
854
855     AM_MEDIA_TYPE media_type;
856     media_type.majortype = GUID_NULL;
857     media_type.subtype = GUID_NULL;
858     media_type.formattype = GUID_NULL;
859     media_type.pUnk = NULL;
860     media_type.cbFormat = 0;
861     media_type.pbFormat = NULL;
862
863     if( S_OK != p_filter->EnumPins( &p_enumpins ) ) return media_type;
864
865     while( S_OK == p_enumpins->Next( 1, &p_output_pin, NULL ) )
866     {
867         PIN_INFO info;
868
869         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
870         {
871             msg_Dbg( p_this, "EnumDeviceCaps: %s pin: %S",
872                      info.dir == PINDIR_INPUT ? "input" : "output",
873                      info.achName );
874             if( info.pFilter ) info.pFilter->Release();
875         }
876
877         p_output_pin->Release();
878     }
879     p_enumpins->Reset();
880
881     while( !b_found && p_enumpins->Next( 1, &p_output_pin, NULL ) == S_OK )
882     {
883         PIN_INFO info;
884
885         if( S_OK == p_output_pin->QueryPinInfo( &info ) )
886         {
887             if( info.pFilter ) info.pFilter->Release();
888             if( info.dir == PINDIR_INPUT )
889             {
890                 p_output_pin->Release();
891                 continue;
892             }
893             msg_Dbg( p_this, "EnumDeviceCaps: trying pin %S", info.achName );
894         }
895
896         /* Probe pin */
897         if( SUCCEEDED( p_output_pin->EnumMediaTypes( &p_enummt ) ) )
898         {
899             AM_MEDIA_TYPE *p_mt;
900             while( p_enummt->Next( 1, &p_mt, NULL ) == S_OK )
901             {
902
903                 if( p_mt->majortype == MEDIATYPE_Video )
904                 {
905                     int i_current_fourcc = VLC_FOURCC(' ', ' ', ' ', ' ');
906
907                     /* Packed RGB formats */
908                     if( p_mt->subtype == MEDIASUBTYPE_RGB1 )
909                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '1' );
910                     if( p_mt->subtype == MEDIASUBTYPE_RGB4 )
911                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '4' );
912                     if( p_mt->subtype == MEDIASUBTYPE_RGB8 )
913                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', '8' );
914                     else if( p_mt->subtype == MEDIASUBTYPE_RGB555 )
915                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '1', '5' );
916                     else if( p_mt->subtype == MEDIASUBTYPE_RGB565 )
917                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '1', '6' );
918                     else if( p_mt->subtype == MEDIASUBTYPE_RGB24 )
919                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '2', '4' );
920                     else if( p_mt->subtype == MEDIASUBTYPE_RGB32 )
921                         i_current_fourcc = VLC_FOURCC( 'R', 'V', '3', '2' );
922                     else if( p_mt->subtype == MEDIASUBTYPE_ARGB32 )
923                         i_current_fourcc = VLC_FOURCC( 'R', 'G', 'B', 'A' );
924
925                     /* MPEG2 video elementary stream */
926                     else if( p_mt->subtype == MEDIASUBTYPE_MPEG2_VIDEO )
927                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 'v' );
928
929                     /* hauppauge pvr video preview */
930                     else if( p_mt->subtype == MEDIASUBTYPE_PREVIEW_VIDEO )
931                         i_current_fourcc = VLC_FOURCC( 'P', 'V', 'R', 'V' );
932
933                     else i_current_fourcc = *((int *)&p_mt->subtype);
934
935                     int i_current_width = p_mt->pbFormat ?
936                         ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biWidth : 0;
937                     int i_current_height = p_mt->pbFormat ?
938                         ((VIDEOINFOHEADER *)p_mt->pbFormat)->bmiHeader.biHeight : 0;
939                     if( i_current_height < 0 )
940                         i_current_height = -i_current_height; 
941
942                     msg_Dbg( p_this, "EnumDeviceCaps: input pin "
943                              "accepts chroma: %4.4s, width:%i, height:%i",
944                              (char *)&i_current_fourcc, i_current_width,
945                              i_current_height );
946
947                     if( ( !i_fourcc || i_fourcc == i_current_fourcc ||
948                           ( !i_orig_fourcc && i_current_fourcc ==
949                             VLC_FOURCC('I','4','2','0') ) ) &&
950                         ( !i_width || i_width == i_current_width ) &&
951                         ( !i_height || i_height == i_current_height ) )
952                     {
953                         /* Pick the 1st match */
954                         media_type = *p_mt;
955                         i_fourcc = i_current_fourcc;
956                         i_width = i_current_width;
957                         i_height = i_current_height;
958                         b_found = VLC_TRUE;
959                     }
960                     else
961                     {
962                         FreeMediaType( *p_mt );
963                     }
964                 }
965                 else if( p_mt->majortype == MEDIATYPE_Audio )
966                 {
967                     int i_current_fourcc;
968                     int i_current_channels =
969                         ((WAVEFORMATEX *)p_mt->pbFormat)->nChannels;
970                     int i_current_samplespersec =
971                         ((WAVEFORMATEX *)p_mt->pbFormat)->nSamplesPerSec;
972                     int i_current_bitspersample =
973                         ((WAVEFORMATEX *)p_mt->pbFormat)->wBitsPerSample;
974
975                     if( p_mt->subtype == MEDIASUBTYPE_PCM )
976                         i_current_fourcc = VLC_FOURCC( 'p', 'c', 'm', ' ' );
977                     else i_current_fourcc = *((int *)&p_mt->subtype);
978
979                     msg_Dbg( p_this, "EnumDeviceCaps: input pin "
980                              "accepts format: %4.4s, channels:%i, "
981                              "samples/sec:%i bits/sample:%i",
982                              (char *)&i_current_fourcc, i_current_channels,
983                              i_current_samplespersec, i_current_bitspersample);
984
985                     if( (!i_channels || i_channels == i_current_channels) &&
986                         (!i_samplespersec ||
987                          i_samplespersec == i_current_samplespersec) &&
988                         (!i_bitspersample ||
989                          i_bitspersample == i_current_bitspersample) )
990                     {
991                         /* Pick the 1st match */
992                         media_type = *p_mt;
993                         i_channels = i_current_channels;
994                         i_samplespersec = i_current_samplespersec;
995                         i_bitspersample = i_current_bitspersample;
996                         b_found = VLC_TRUE;
997
998                         /* Setup a few properties like the audio latency */
999                         IAMBufferNegotiation *p_ambuf;
1000
1001                         if( SUCCEEDED( p_output_pin->QueryInterface(
1002                               IID_IAMBufferNegotiation, (void **)&p_ambuf ) ) )
1003                         {
1004                             ALLOCATOR_PROPERTIES AllocProp;
1005                             AllocProp.cbAlign = -1;
1006                             AllocProp.cbBuffer = i_channels * i_samplespersec *
1007                               i_bitspersample / 8 / 10 ; /*100 ms of latency*/
1008                             AllocProp.cbPrefix = -1;
1009                             AllocProp.cBuffers = -1;
1010                             p_ambuf->SuggestAllocatorProperties( &AllocProp );
1011                             p_ambuf->Release();
1012                         }
1013                     }
1014                     else
1015                     {
1016                         FreeMediaType( *p_mt );
1017                     }
1018                 }
1019                 else if( p_mt->majortype == MEDIATYPE_Stream )
1020                 {
1021                     msg_Dbg( p_this, "EnumDeviceCaps: MEDIATYPE_Stream" );
1022
1023                     int i_current_fourcc = VLC_FOURCC(' ', ' ', ' ', ' ');
1024
1025                     if( p_mt->subtype == MEDIASUBTYPE_MPEG2_PROGRAM )
1026                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 'p' );
1027                     else if( p_mt->subtype == MEDIASUBTYPE_MPEG2_TRANSPORT )
1028                         i_current_fourcc = VLC_FOURCC( 'm', 'p', '2', 't' );
1029
1030                     if( ( !i_fourcc || i_fourcc == i_current_fourcc ) )
1031                     {
1032                         /* Pick the 1st match */
1033                         media_type = *p_mt;
1034                         i_fourcc = i_current_fourcc;
1035                         b_found = VLC_TRUE;
1036                     }
1037                     else
1038                     {
1039                         FreeMediaType( *p_mt );
1040                     }
1041                 }
1042                 else
1043                 {
1044                     msg_Dbg( p_this,
1045                              "EnumDeviceCaps: input pin: unknown format" );
1046                     FreeMediaType( *p_mt );
1047                 }
1048
1049                 CoTaskMemFree( (PVOID)p_mt );
1050             }
1051             p_enummt->Release();
1052         }
1053
1054         p_output_pin->Release();
1055     }
1056
1057     p_enumpins->Release();
1058     return media_type;
1059 }
1060
1061 /*****************************************************************************
1062  * Read: reads from the device into PES packets.
1063  *****************************************************************************
1064  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1065  * bytes.
1066  *****************************************************************************/
1067 static ssize_t Read( input_thread_t * p_input, byte_t * p_buffer,
1068                      size_t i_len )
1069 {
1070     access_sys_t   *p_sys = p_input->p_access_data;
1071     dshow_stream_t *p_stream = NULL;
1072     byte_t         *p_buf_orig = p_buffer;
1073     VLCMediaSample  sample;
1074     int             i_data_size;
1075     uint8_t         *p_data;
1076
1077     if( p_sys->i_header_pos )
1078     {
1079         /* First header of the stream */
1080         memcpy( p_buffer, p_sys->p_header, p_sys->i_header_size );
1081         p_buffer += p_sys->i_header_size;
1082         p_sys->i_header_pos = 0;
1083     }
1084
1085     while( 1 )
1086     {
1087         /* Get new sample/frame from next elementary stream.
1088          * We first loop through all the elementary streams and if all our
1089          * fifos are empty we block until we are signaled some new data has
1090          * arrived. */
1091         vlc_mutex_lock( &p_sys->lock );
1092
1093         int i_stream;
1094         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1095         {
1096             p_stream = p_sys->pp_streams[i_stream];
1097             if( p_stream->mt.majortype == MEDIATYPE_Audio &&
1098                 p_stream->p_capture_filter &&
1099                 p_stream->p_capture_filter->CustomGetPin()
1100                   ->CustomGetSample( &sample ) == S_OK )
1101             {
1102                 break;
1103             }
1104         }
1105         if( i_stream == p_sys->i_streams )
1106         for( i_stream = 0; i_stream < p_sys->i_streams; i_stream++ )
1107         {
1108             p_stream = p_sys->pp_streams[i_stream];
1109             if( p_stream->p_capture_filter &&
1110                 p_stream->p_capture_filter->CustomGetPin()
1111                   ->CustomGetSample( &sample ) == S_OK )
1112             {
1113                 break;
1114             }
1115         }
1116         if( i_stream == p_sys->i_streams )
1117         {
1118             /* No data available. Wait until some data has arrived */
1119             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1120             vlc_mutex_unlock( &p_sys->lock );
1121             continue;
1122         }
1123
1124         vlc_mutex_unlock( &p_sys->lock );
1125
1126         /*
1127          * We got our sample
1128          */
1129         i_data_size = sample.p_sample->GetActualDataLength();
1130         sample.p_sample->GetPointer( &p_data );
1131
1132         REFERENCE_TIME i_pts, i_end_date;
1133         HRESULT hr = sample.p_sample->GetTime( &i_pts, &i_end_date );
1134         if( hr != VFW_S_NO_STOP_TIME && hr != S_OK ) i_pts = 0;
1135
1136         if( !i_pts )
1137         {
1138             if( p_stream->mt.majortype == MEDIATYPE_Video || !p_stream->b_pts )
1139             {
1140                 /* Use our data timestamp */
1141                 i_pts = sample.i_timestamp;
1142                 p_stream->b_pts = VLC_TRUE;
1143             }
1144         }
1145
1146 #if 0
1147         msg_Dbg( p_input, "Read() stream: %i PTS: "I64Fd, i_stream, i_pts );
1148 #endif
1149
1150         /* Create pseudo header */
1151         SetDWBE( &p_sys->p_header[0], i_stream );
1152         SetDWBE( &p_sys->p_header[4], i_data_size );
1153         SetQWBE( &p_sys->p_header[8], i_pts  * 9 / 1000 );
1154
1155 #if 0
1156         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1157 #endif
1158
1159         /* First copy header */
1160         memcpy( p_buffer, p_sys->p_header, 16 /* header size */ );
1161         p_buffer += 16 /* header size */;
1162
1163         /* Then copy stream data if any */
1164         if( !p_stream->b_invert )
1165         {
1166             p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1167             p_buffer += i_data_size;
1168         }
1169         else
1170         {
1171             int i_width = p_stream->header.video.bmiHeader.biWidth;
1172             int i_height = p_stream->header.video.bmiHeader.biHeight;
1173             if( i_height < 0 ) i_height = - i_height;
1174
1175             switch( p_stream->i_fourcc )
1176             {
1177             case VLC_FOURCC( 'R', 'V', '1', '5' ):
1178             case VLC_FOURCC( 'R', 'V', '1', '6' ):
1179                 i_width *= 2;
1180                 break;
1181             case VLC_FOURCC( 'R', 'V', '2', '4' ):
1182                 i_width *= 3;
1183                 break;
1184             case VLC_FOURCC( 'R', 'V', '3', '2' ):
1185             case VLC_FOURCC( 'R', 'G', 'B', 'A' ):
1186                 i_width *= 4;
1187                 break;
1188             }
1189
1190             for( int i = i_height - 1; i >= 0; i-- )
1191             {
1192                 p_input->p_vlc->pf_memcpy( p_buffer,
1193                      &p_data[i * i_width], i_width );
1194
1195                 p_buffer += i_width;
1196             }
1197         }
1198
1199         sample.p_sample->Release();
1200
1201         /* The caller got what he wanted */
1202         return p_buffer - p_buf_orig;
1203     }
1204
1205     return 0; /* never reached */
1206 }
1207
1208 /*****************************************************************************
1209  * ReadCompressed: reads compressed (MPEG/DV) data from the device.
1210  *****************************************************************************
1211  * Returns -1 in case of error, 0 in case of EOF, otherwise the number of
1212  * bytes.
1213  *****************************************************************************/
1214 static ssize_t ReadCompressed( input_thread_t * p_input, byte_t * p_buffer,
1215                                size_t i_len )
1216 {
1217     access_sys_t   *p_sys = p_input->p_access_data;
1218     dshow_stream_t *p_stream = NULL;
1219     VLCMediaSample  sample;
1220     int             i_data_size;
1221     uint8_t         *p_data;
1222
1223     /* Read 1 DV/MPEG frame (they contain the video and audio data) */
1224
1225     /* There must be only 1 elementary stream to produce a valid stream
1226      * of MPEG or DV data */
1227     p_stream = p_sys->pp_streams[0];
1228
1229     while( 1 )
1230     {
1231         if( p_input->b_die || p_input->b_error ) return 0;
1232
1233         /* Get new sample/frame from the elementary stream (blocking). */
1234         vlc_mutex_lock( &p_sys->lock );
1235
1236         if( p_stream->p_capture_filter->CustomGetPin()
1237               ->CustomGetSample( &sample ) != S_OK )
1238         {
1239             /* No data available. Wait until some data has arrived */
1240             vlc_cond_wait( &p_sys->wait, &p_sys->lock );
1241             vlc_mutex_unlock( &p_sys->lock );
1242             continue;
1243         }
1244
1245         vlc_mutex_unlock( &p_sys->lock );
1246
1247         /*
1248          * We got our sample
1249          */
1250         i_data_size = sample.p_sample->GetActualDataLength();
1251         sample.p_sample->GetPointer( &p_data );
1252
1253 #if 0
1254         msg_Info( p_input, "access read %i data_size %i", i_len, i_data_size );
1255 #endif
1256         i_data_size = __MIN( i_data_size, (int)i_len );
1257
1258         p_input->p_vlc->pf_memcpy( p_buffer, p_data, i_data_size );
1259
1260         sample.p_sample->Release();
1261
1262         /* The caller got what he wanted */
1263         return i_data_size;
1264     }
1265
1266     return 0; /* never reached */
1267 }
1268
1269 /*****************************************************************************
1270  * Demux: local prototypes
1271  *****************************************************************************/
1272 struct demux_sys_t
1273 {
1274     int         i_es;
1275     es_out_id_t **es;
1276 };
1277
1278 static int  Demux      ( input_thread_t * );
1279
1280 /****************************************************************************
1281  * DemuxOpen:
1282  ****************************************************************************/
1283 static int DemuxOpen( vlc_object_t *p_this )
1284 {
1285     input_thread_t *p_input = (input_thread_t *)p_this;
1286     demux_sys_t    *p_sys;
1287
1288     uint8_t        *p_peek;
1289     int            i_es;
1290     int            i;
1291
1292     /* a little test to see if it's a dshow stream */
1293     if( stream_Peek( p_input->s, &p_peek, 8 ) < 8 )
1294     {
1295         msg_Warn( p_input, "dshow plugin discarded (cannot peek)" );
1296         return VLC_EGENERIC;
1297     }
1298
1299     if( memcmp( p_peek, ".dsh", 4 ) ||
1300         ( i_es = GetDWBE( &p_peek[4] ) ) <= 0 )
1301     {
1302         msg_Warn( p_input, "dshow plugin discarded (not a valid stream)" );
1303         return VLC_EGENERIC;
1304     }
1305
1306     vlc_mutex_lock( &p_input->stream.stream_lock );
1307     if( input_InitStream( p_input, 0 ) == -1)
1308     {
1309         vlc_mutex_unlock( &p_input->stream.stream_lock );
1310         msg_Err( p_input, "cannot init stream" );
1311         return VLC_EGENERIC;
1312     }
1313     p_input->stream.i_mux_rate =  0 / 50;
1314     vlc_mutex_unlock( &p_input->stream.stream_lock );
1315
1316     p_input->pf_demux = Demux;
1317     p_input->pf_demux_control = demux_vaControlDefault;
1318     p_input->p_demux_data = p_sys =
1319         (demux_sys_t *)malloc( sizeof( demux_sys_t ) );
1320     p_sys->i_es = 0;
1321     p_sys->es   = NULL;
1322
1323     if( stream_Peek( p_input->s, &p_peek, 8 + 20 * i_es ) < 8 + 20 * i_es )
1324     {
1325         msg_Err( p_input, "dshow plugin discarded (cannot peek)" );
1326         return VLC_EGENERIC;
1327     }
1328     p_peek += 8;
1329
1330     for( i = 0; i < i_es; i++ )
1331     {
1332         es_format_t fmt;
1333
1334         if( !memcmp( p_peek, "auds", 4 ) )
1335         {
1336             es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1337                                                         p_peek[6], p_peek[7] ) );
1338
1339             fmt.audio.i_channels = GetDWBE( &p_peek[8] );
1340             fmt.audio.i_rate = GetDWBE( &p_peek[12] );
1341             fmt.audio.i_bitspersample = GetDWBE( &p_peek[16] );
1342             fmt.audio.i_blockalign = fmt.audio.i_channels *
1343                                      fmt.audio.i_bitspersample / 8;
1344             fmt.i_bitrate = fmt.audio.i_channels *
1345                             fmt.audio.i_rate *
1346                             fmt.audio.i_bitspersample;
1347
1348             msg_Dbg( p_input, "new audio es %d channels %dHz",
1349                      fmt.audio.i_channels, fmt.audio.i_rate );
1350
1351             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1352                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1353             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1354         }
1355         else if( !memcmp( p_peek, "vids", 4 ) )
1356         {
1357             es_format_Init( &fmt, VIDEO_ES, VLC_FOURCC( p_peek[4], p_peek[5],
1358                                                         p_peek[6], p_peek[7] ) );
1359             fmt.video.i_width  = GetDWBE( &p_peek[8] );
1360             fmt.video.i_height = GetDWBE( &p_peek[12] );
1361
1362             msg_Dbg( p_input, "added new video es %4.4s %dx%d",
1363                      (char*)&fmt.i_codec,
1364                      fmt.video.i_width, fmt.video.i_height );
1365
1366             p_sys->es = (es_out_id_t **)realloc( p_sys->es,
1367                           sizeof(es_out_id_t *) * (p_sys->i_es + 1) );
1368             p_sys->es[p_sys->i_es++] = es_out_Add( p_input->p_es_out, &fmt );
1369         }
1370
1371         p_peek += 20;
1372     }
1373
1374     /* Skip header */
1375     stream_Read( p_input->s, NULL, 8 + 20 * i_es );
1376
1377     return VLC_SUCCESS;
1378 }
1379
1380 /****************************************************************************
1381  * DemuxClose:
1382  ****************************************************************************/
1383 static void DemuxClose( vlc_object_t *p_this )
1384 {
1385     input_thread_t *p_input = (input_thread_t *)p_this;
1386     demux_sys_t    *p_sys = p_input->p_demux_data;
1387
1388     if( p_sys->i_es > 0 )
1389     {
1390         free( p_sys->es );
1391     }
1392     free( p_sys );
1393 }
1394
1395 /****************************************************************************
1396  * Demux:
1397  ****************************************************************************/
1398 static int Demux( input_thread_t *p_input )
1399 {
1400     demux_sys_t *p_sys = p_input->p_demux_data;
1401     block_t     *p_block;
1402
1403     int i_es;
1404     int i_size;
1405
1406     uint8_t *p_peek;
1407     mtime_t i_pcr;
1408
1409     if( stream_Peek( p_input->s, &p_peek, 16 ) < 16 )
1410     {
1411         msg_Warn( p_input, "cannot peek (EOF ?)" );
1412         return 0;
1413     }
1414
1415     i_es   = GetDWBE( &p_peek[0] );
1416     if( i_es < 0 || i_es >= p_sys->i_es )
1417     {
1418         msg_Err( p_input, "cannot find ES" );
1419         return -1;
1420     }
1421
1422     i_size = GetDWBE( &p_peek[4] );
1423     i_pcr  = GetQWBE( &p_peek[8] );
1424
1425     if( ( p_block = stream_Block( p_input->s, 16 + i_size ) ) == NULL )
1426     {
1427         msg_Warn( p_input, "cannot read data" );
1428         return 0;
1429     }
1430
1431     p_block->p_buffer += 16;
1432     p_block->i_buffer -= 16;
1433
1434     /* Call the pace control. */
1435     input_ClockManageRef( p_input, p_input->stream.p_selected_program, i_pcr );
1436
1437     p_block->i_dts =
1438     p_block->i_pts = i_pcr <= 0 ? 0 :
1439         input_ClockGetTS( p_input, p_input->stream.p_selected_program, i_pcr );
1440
1441     es_out_Send( p_input->p_es_out, p_sys->es[i_es], p_block );
1442
1443     return 1;
1444 }
1445
1446
1447 /*****************************************************************************
1448  * config variable callback
1449  *****************************************************************************/
1450 static int FindDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1451                                vlc_value_t newval, vlc_value_t oldval, void * )
1452 {
1453     module_config_t *p_item;
1454     vlc_bool_t b_audio = VLC_FALSE;
1455     int i;
1456
1457     p_item = config_FindConfig( p_this, psz_name );
1458     if( !p_item ) return VLC_SUCCESS;
1459
1460     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1461
1462     /* Clear-up the current list */
1463     if( p_item->i_list )
1464     {
1465         /* Keep the 2 first entries */
1466         for( i = 2; i < p_item->i_list; i++ )
1467         {
1468             free( p_item->ppsz_list[i] );
1469             free( p_item->ppsz_list_text[i] );
1470         }
1471         /* TODO: Remove when no more needed */
1472         p_item->ppsz_list[i] = NULL;
1473         p_item->ppsz_list_text[i] = NULL;
1474     }
1475     p_item->i_list = 2;
1476
1477     /* Find list of devices */
1478     list<string> list_devices;
1479
1480     FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1481
1482     if( !list_devices.size() ) return VLC_SUCCESS;
1483
1484     p_item->ppsz_list =
1485         (char **)realloc( p_item->ppsz_list,
1486                           (list_devices.size()+3) * sizeof(char *) );
1487     p_item->ppsz_list_text =
1488         (char **)realloc( p_item->ppsz_list_text,
1489                           (list_devices.size()+3) * sizeof(char *) );
1490
1491     list<string>::iterator iter;
1492     for( iter = list_devices.begin(), i = 2; iter != list_devices.end();
1493          iter++, i++ )
1494     {
1495         p_item->ppsz_list[i] = strdup( iter->c_str() );
1496         p_item->ppsz_list_text[i] = NULL;
1497         p_item->i_list++;
1498     }
1499     p_item->ppsz_list[i] = NULL;
1500     p_item->ppsz_list_text[i] = NULL;
1501
1502     /* Signal change to the interface */
1503     p_item->b_dirty = VLC_TRUE;
1504
1505     return VLC_SUCCESS;
1506 }
1507
1508 static int ConfigDevicesCallback( vlc_object_t *p_this, char const *psz_name,
1509                                vlc_value_t newval, vlc_value_t oldval, void * )
1510 {
1511     module_config_t *p_item;
1512     vlc_bool_t b_audio = VLC_FALSE;
1513
1514     p_item = config_FindConfig( p_this, psz_name );
1515     if( !p_item ) return VLC_SUCCESS;
1516
1517     if( !strcmp( psz_name, "dshow-adev" ) ) b_audio = VLC_TRUE;
1518
1519     string devicename;
1520
1521     if( newval.psz_string && *newval.psz_string )
1522     {
1523         devicename = newval.psz_string;
1524     }
1525     else
1526     {
1527         /* If no device name was specified, pick the 1st one */
1528         list<string> list_devices;
1529
1530         /* Enumerate devices */
1531         FindCaptureDevice( p_this, NULL, &list_devices, b_audio );
1532         if( !list_devices.size() ) return VLC_EGENERIC;
1533         devicename = *list_devices.begin();
1534     }
1535
1536     IBaseFilter *p_device_filter =
1537         FindCaptureDevice( p_this, &devicename, NULL, b_audio );
1538     if( p_device_filter )
1539         PropertiesPage( p_this, p_device_filter );
1540     else
1541     {
1542         msg_Err( p_this, "didn't find device: %s", devicename.c_str() );
1543         return VLC_EGENERIC;
1544     }
1545
1546     return VLC_SUCCESS;
1547 }
1548
1549 static void PropertiesPage( vlc_object_t *p_this,
1550                             IBaseFilter *p_device_filter )
1551 {
1552     ISpecifyPropertyPages *p_spec;
1553     CAUUID cauuid;
1554  
1555     HRESULT hr = p_device_filter->QueryInterface( IID_ISpecifyPropertyPages,
1556                                                   (void **)&p_spec );
1557     if( hr == S_OK )
1558     {
1559         hr = p_spec->GetPages( &cauuid );
1560         if( hr == S_OK )
1561         {
1562             HWND hwnd_desktop = ::GetDesktopWindow();
1563
1564             hr = OleCreatePropertyFrame( hwnd_desktop, 30, 30, NULL, 1,
1565                                          (IUnknown **)&p_device_filter,
1566                                          cauuid.cElems,
1567                                          (GUID *)cauuid.pElems, 0, 0, NULL );
1568             CoTaskMemFree( cauuid.pElems );
1569         }
1570         p_spec->Release();
1571     }
1572 }