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