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