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