]> git.sesse.net Git - vlc/blob - src/interface/main.c
332287977a2f6b4b54f7482b4031a045817c230c
[vlc] / src / interface / main.c
1 /*****************************************************************************
2  * main.c: main vlc source
3  * Includes the main() function for vlc. Parses command line, start interface
4  * and spawn threads.
5  *****************************************************************************
6  * Copyright (C) 1998, 1999, 2000 VideoLAN
7  * $Id: main.c,v 1.111 2001/08/07 02:48:25 sam Exp $
8  *
9  * Authors: Vincent Seguin <seguin@via.ecp.fr>
10  *          Samuel Hocevar <sam@zoy.org>
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  * 
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #include "defs.h"
31
32 #include <signal.h>                               /* SIGHUP, SIGINT, SIGKILL */
33 #include <stdio.h>                                              /* sprintf() */
34 #include <setjmp.h>                                       /* longjmp, setjmp */
35
36 #ifdef HAVE_GETOPT_LONG
37 #   ifdef HAVE_GETOPT_H
38 #       include <getopt.h>                                       /* getopt() */
39 #   endif
40 #else
41 #   include "GNUgetopt/getopt.h"
42 #endif
43
44 #ifdef SYS_DARWIN
45 #   include <mach/mach.h>                               /* Altivec detection */
46 #   include <mach/mach_error.h>       /* some day the header files||compiler *
47                                                        will define it for us */
48 #   include <mach/bootstrap.h>
49 #endif
50
51 #ifndef WIN32
52 #   include <netinet/in.h>                            /* BSD: struct in_addr */
53 #endif
54
55 #ifdef HAVE_UNISTD_H
56 #   include <unistd.h>
57 #elif defined( _MSC_VER ) && defined( _WIN32 )
58 #   include <io.h>
59 #endif
60
61 #include <errno.h>                                                 /* ENOMEM */
62 #include <stdlib.h>                                  /* getenv(), strtol(),  */
63 #include <string.h>                                            /* strerror() */
64 #include <fcntl.h>                                       /* open(), O_WRONLY */
65 #include <sys/stat.h>                                             /* S_IREAD */
66
67 #include "config.h"
68 #include "common.h"
69 #include "debug.h"
70 #include "threads.h"
71 #include "mtime.h"
72 #include "tests.h"                                              /* TestCPU() */
73 #include "modules.h"
74
75 #include "stream_control.h"
76 #include "input_ext-intf.h"
77
78 #include "intf_msg.h"
79 #include "intf_playlist.h"
80 #include "interface.h"
81
82 #include "audio_output.h"
83
84 #include "video.h"
85 #include "video_output.h"
86
87 #ifdef SYS_BEOS
88 #   include "beos_specific.h"
89 #endif
90
91 #ifdef SYS_DARWIN
92 #   include "darwin_specific.h"
93 #endif
94
95 #include "netutils.h"                                 /* network_ChannelJoin */
96
97 #include "main.h"
98
99 /*****************************************************************************
100  * Command line options constants. If something is changed here, be sure that
101  * GetConfiguration and Usage are also changed.
102  *****************************************************************************/
103
104 /* Long options return values - note that values corresponding to short options
105  * chars, and in general any regular char, should be avoided */
106 #define OPT_NOAUDIO             150
107 #define OPT_STEREO              151
108 #define OPT_MONO                152
109 #define OPT_SPDIF               153
110
111 #define OPT_NOVIDEO             160
112 #define OPT_DISPLAY             161
113 #define OPT_WIDTH               162
114 #define OPT_HEIGHT              163
115 #define OPT_COLOR               164
116 #define OPT_FULLSCREEN          165
117 #define OPT_OVERLAY             166
118 #define OPT_SMP                 167
119
120 #define OPT_CHANNELS            170
121 #define OPT_SERVER              171
122 #define OPT_PORT                172
123 #define OPT_BROADCAST           173
124
125 #define OPT_INPUT               180
126 #define OPT_MOTION              181
127 #define OPT_IDCT                182
128 #define OPT_YUV                 183
129 #define OPT_DOWNMIX             184
130 #define OPT_IMDCT               185
131
132 #define OPT_SYNCHRO             190
133 #define OPT_WARNING             191
134 #define OPT_VERSION             192
135 #define OPT_STDOUT              193
136
137 /* Usage fashion */
138 #define USAGE                     0
139 #define SHORT_HELP                1
140 #define LONG_HELP                 2
141
142 /* Needed for x86 CPU capabilities detection */
143 #define cpuid( a )                 \
144     asm volatile ( "cpuid"         \
145                  : "=a" ( i_eax ), \
146                    "=b" ( i_ebx ), \
147                    "=c" ( i_ecx ), \
148                    "=d" ( i_edx )  \
149                  : "a"  ( a )      \
150                  : "cc" );
151
152 /* Long options */
153 static const struct option longopts[] =
154 {
155     /*  name,               has_arg,    flag,   val */
156
157     /* General/common options */
158     {   "help",             0,          0,      'h' },
159     {   "longhelp",         0,          0,      'H' },
160     {   "version",          0,          0,      OPT_VERSION },
161
162     /* Interface options */
163     {   "intf",             1,          0,      'I' },
164     {   "warning",          1,          0,      OPT_WARNING },
165     {   "stdout",           1,          0,      OPT_STDOUT },
166
167     /* Audio options */
168     {   "noaudio",          0,          0,      OPT_NOAUDIO },
169     {   "aout",             1,          0,      'A' },
170     {   "stereo",           0,          0,      OPT_STEREO },
171     {   "mono",             0,          0,      OPT_MONO },
172     {   "spdif",            0,          0,      OPT_SPDIF },
173     {   "downmix",          1,          0,      OPT_DOWNMIX },
174     {   "imdct",            1,          0,      OPT_IMDCT },
175
176     /* Video options */
177     {   "novideo",          0,          0,      OPT_NOVIDEO },
178     {   "vout",             1,          0,      'V' },
179     {   "display",          1,          0,      OPT_DISPLAY },
180     {   "width",            1,          0,      OPT_WIDTH },
181     {   "height",           1,          0,      OPT_HEIGHT },
182     {   "grayscale",        0,          0,      'g' },
183     {   "color",            0,          0,      OPT_COLOR },
184     {   "motion",           1,          0,      OPT_MOTION },
185     {   "idct",             1,          0,      OPT_IDCT },
186     {   "yuv",              1,          0,      OPT_YUV },
187     {   "fullscreen",       0,          0,      OPT_FULLSCREEN },
188     {   "overlay",          0,          0,      OPT_OVERLAY },
189     {   "smp",              1,          0,      OPT_SMP },
190
191     /* DVD options */
192     {   "dvdtitle",         1,          0,      't' },
193     {   "dvdchapter",       1,          0,      'T' },
194     {   "dvdangle",         1,          0,      'u' },
195     {   "dvdaudio",         1,          0,      'a' },
196     {   "dvdchannel",       1,          0,      'c' },
197     {   "dvdsubtitle",      1,          0,      's' },
198     
199     /* Input options */
200     {   "input",            1,          0,      OPT_INPUT },
201     {   "server",           1,          0,      OPT_SERVER },
202     {   "port",             1,          0,      OPT_PORT },
203     {   "broadcast",        1,          0,      OPT_BROADCAST },
204     {   "channels",         0,          0,      OPT_CHANNELS },
205
206     /* Synchro options */
207     {   "synchro",          1,          0,      OPT_SYNCHRO },
208     {   0,                  0,          0,      0 }
209 };
210
211 /* Short options */
212 static const char *psz_shortopts = "hHvgt:T:u:a:s:c:I:A:V:";
213
214 /*****************************************************************************
215  * Global variable program_data - these are the only ones, see main.h and
216  * modules.h
217  *****************************************************************************/
218 main_t        *p_main;
219 module_bank_t *p_module_bank;
220 aout_bank_t   *p_aout_bank;
221 vout_bank_t   *p_vout_bank;
222
223 /*****************************************************************************
224  * Local prototypes
225  *****************************************************************************/
226 static int  GetConfiguration        ( int *pi_argc, char *ppsz_argv[],
227                                       char *ppsz_env[] );
228 static int  GetFilenames            ( int i_argc, char *ppsz_argv[] );
229 static void Usage                   ( int i_fashion );
230 static void Version                 ( void );
231
232 static void InitSignalHandler       ( void );
233 static void SimpleSignalHandler     ( int i_signal );
234 static void FatalSignalHandler      ( int i_signal );
235 static void InstructionSignalHandler( int i_signal );
236 static int  CPUCapabilities         ( void );
237
238 static int  RedirectSTDOUT          ( void );
239 static void ShowConsole             ( void );
240
241 static jmp_buf env;
242 static int  i_illegal;
243
244 /*****************************************************************************
245  * main: parse command line, start interface and spawn threads
246  *****************************************************************************
247  * Steps during program execution are:
248  *      -configuration parsing and messages interface initialization
249  *      -opening of audio output device and some global modules
250  *      -execution of interface, which exit on error or on user request
251  *      -closing of audio output device and some global modules
252  * On error, the spawned threads are canceled, and the open devices closed.
253  *****************************************************************************/
254 int main( int i_argc, char *ppsz_argv[], char *ppsz_env[] )
255 {
256     main_t        main_data;                /* root of all data - see main.h */
257     module_bank_t module_bank;
258     aout_bank_t   aout_bank;
259     vout_bank_t   vout_bank;
260
261     p_main        = &main_data;               /* set up the global variables */
262     p_module_bank = &module_bank;
263     p_aout_bank   = &aout_bank;
264     p_vout_bank   = &vout_bank;
265
266     /*
267      * Initialize threads system
268      */
269     vlc_threads_init( );
270
271     /*
272      * Test if our code is likely to run on this CPU 
273      */
274     p_main->i_cpu_capabilities = CPUCapabilities();
275     
276 #if defined( __pentium__ ) || defined( __pentiumpro__ )
277     if( ! TestCPU( CPU_CAPABILITY_586 ) )
278     {
279         fprintf( stderr, "error: this program needs a Pentium CPU,\n"
280                          "please try a version without Pentium support\n" );
281         return( 1 );
282     }
283 #endif
284
285     /*
286      * System specific initialization code
287      */
288 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
289     system_Init( &i_argc, ppsz_argv, ppsz_env );
290 #elif defined( WIN32 )
291     _fmode = _O_BINARY;   /* sets the default file-translation mode on Win32 */
292 #endif
293
294     /*
295      * Initialize messages interface
296      */
297     p_main->p_msg = intf_MsgCreate();
298     if( !p_main->p_msg )                         /* start messages interface */
299     {
300         fprintf( stderr, "error: can't initialize messages interface (%s)\n",
301                  strerror(errno) );
302         return( errno );
303     }
304
305     intf_MsgImm( COPYRIGHT_MESSAGE );
306
307     /*
308      * Read configuration
309      */
310     if( GetConfiguration( &i_argc, ppsz_argv, ppsz_env ) ) /* parse cmd line */
311     {
312         intf_MsgDestroy();
313         return( errno );
314     }
315
316     /*
317      * Redirect the standard output if required by the user, and on Win32 we
318      * also open a console to display the debug messages.
319      */
320     RedirectSTDOUT();
321
322     /*
323      * Initialize playlist and get commandline files
324      */
325     p_main->p_playlist = intf_PlaylistCreate();
326     if( !p_main->p_playlist )
327     {
328         intf_ErrMsg( "playlist error: playlist initialization failed" );
329         intf_MsgDestroy();
330         return( errno );
331     }
332     intf_PlaylistInit( p_main->p_playlist );
333
334     /*
335      * Get input filenames given as commandline arguments
336      */
337     GetFilenames( i_argc, ppsz_argv );
338
339     /*
340      * Initialize module, aout and vout banks
341      */
342     module_InitBank();
343     aout_InitBank();
344     vout_InitBank();
345
346     /*
347      * Initialize shared resources and libraries
348      */
349     if( main_GetIntVariable( INPUT_NETWORK_CHANNEL_VAR,
350                              INPUT_NETWORK_CHANNEL_DEFAULT ) &&
351         network_ChannelCreate() )
352     {
353         /* On error during Channels initialization, switch off channels */
354         intf_Msg( "Channels initialization failed : "
355                   "Channel management is deactivated" );
356         main_PutIntVariable( INPUT_NETWORK_CHANNEL_VAR, 0 );
357     }
358
359     /*
360      * Try to run the interface
361      */
362     p_main->p_intf = intf_Create();
363     if( p_main->p_intf == NULL )
364     {
365         intf_ErrMsg( "intf error: interface initialization failed" );
366     }
367     else
368     {
369         /*
370          * Set signal handling policy for all threads
371          */
372         InitSignalHandler();
373
374         /*
375          * This is the main loop
376          */
377         p_main->p_intf->pf_run( p_main->p_intf );
378
379         /*
380          * Finished, destroy the interface
381          */
382         intf_Destroy( p_main->p_intf );
383
384         /*
385          * Go back into channel 0 which is the network
386          */
387         if( main_GetIntVariable( INPUT_NETWORK_CHANNEL_VAR,
388                                  INPUT_NETWORK_CHANNEL_DEFAULT ) )
389         {
390             network_ChannelJoin( COMMON_CHANNEL );
391         }
392     }
393
394     /*
395      * Free module, aout and vout banks
396      */
397     vout_EndBank();
398     aout_EndBank();
399     module_EndBank();
400
401     /*
402      * Free playlist
403      */
404     intf_PlaylistDestroy( p_main->p_playlist );
405
406     /*
407      * System specific cleaning code
408      */
409 #if defined( SYS_BEOS ) || defined( SYS_DARWIN )
410     system_End();
411 #endif
412
413
414     /*
415      * Terminate messages interface and program
416      */
417     intf_Msg( "intf: program terminated" );
418     intf_MsgDestroy();
419
420     /*
421      * Stop threads system
422      */
423     vlc_threads_end( );
424
425     return 0;
426 }
427
428 /*****************************************************************************
429  * main_GetIntVariable: get the int value of an environment variable
430  *****************************************************************************
431  * This function is used to read some default parameters in modules.
432  *****************************************************************************/
433 int main_GetIntVariable( char *psz_name, int i_default )
434 {
435     char *      psz_env;                                /* environment value */
436     char *      psz_end;                             /* end of parsing index */
437     long int    i_value;                                            /* value */
438
439     psz_env = getenv( psz_name );
440     if( psz_env )
441     {
442         i_value = strtol( psz_env, &psz_end, 0 );
443         if( (*psz_env != '\0') && (*psz_end == '\0') )
444         {
445             return( i_value );
446         }
447     }
448     return( i_default );
449 }
450
451 /*****************************************************************************
452  * main_GetPszVariable: get the string value of an environment variable
453  *****************************************************************************
454  * This function is used to read some default parameters in modules.
455  *****************************************************************************/
456 char * main_GetPszVariable( char *psz_name, char *psz_default )
457 {
458     char *psz_env;
459
460     psz_env = getenv( psz_name );
461     if( psz_env )
462     {
463         return( psz_env );
464     }
465     return( psz_default );
466 }
467
468 /*****************************************************************************
469  * main_PutPszVariable: set the string value of an environment variable
470  *****************************************************************************
471  * This function is used to set some default parameters in modules. The use of
472  * this function will cause some memory leak: since some systems use the pointer
473  * passed to putenv to store the environment string, it can't be freed.
474  *****************************************************************************/
475 void main_PutPszVariable( char *psz_name, char *psz_value )
476 {
477     char *psz_env;
478
479     psz_env = malloc( strlen(psz_name) + strlen(psz_value) + 2 );
480     if( psz_env == NULL )
481     {
482         intf_ErrMsg( "intf error: cannot create psz_env (%s)",
483                      strerror(ENOMEM) );
484     }
485     else
486     {
487         sprintf( psz_env, "%s=%s", psz_name, psz_value );
488         if( putenv( psz_env ) )
489         {
490             intf_ErrMsg( "intf error: cannot putenv (%s)", strerror(errno) );
491         }
492     }
493 }
494
495 /*****************************************************************************
496  * main_PutIntVariable: set the integer value of an environment variable
497  *****************************************************************************
498  * This function is used to set some default parameters in modules. The use of
499  * this function will cause some memory leak: since some systems use the pointer
500  * passed to putenv to store the environment string, it can't be freed.
501  *****************************************************************************/
502 void main_PutIntVariable( char *psz_name, int i_value )
503 {
504     char psz_value[ 256 ];                               /* buffer for value */
505
506     sprintf( psz_value, "%d", i_value );
507     main_PutPszVariable( psz_name, psz_value );
508 }
509
510 /* following functions are local */
511
512 /*****************************************************************************
513  * GetConfiguration: parse command line
514  *****************************************************************************
515  * Parse command line and configuration file for configuration. If the inline
516  * help is requested, the function Usage() is called and the function returns
517  * -1 (causing main() to exit). The messages interface is initialized at this
518  * stage, but most structures are not allocated, so only environment should
519  * be used.
520  *****************************************************************************/
521 static int GetConfiguration( int *pi_argc, char *ppsz_argv[], char *ppsz_env[] )
522 {
523     int   i_cmd;
524     char *p_tmp;
525
526     /* Set default configuration and copy arguments */
527     p_main->i_argc    = *pi_argc;
528     p_main->ppsz_argv = ppsz_argv;
529     p_main->ppsz_env  = ppsz_env;
530
531     p_main->b_audio     = 1;
532     p_main->b_video     = 1;
533
534     p_main->i_warning_level = 0;
535
536     p_main->p_channel = NULL;
537
538     /* Get the executable name (similar to the basename command) */
539     p_main->psz_arg0 = p_tmp = ppsz_argv[ 0 ];
540     while( *p_tmp )
541     {
542         if( *p_tmp == '/' )
543         {
544             p_main->psz_arg0 = ++p_tmp;
545         }
546         else
547         {
548             ++p_tmp;
549         }
550     }
551
552 #ifdef SYS_DARWIN
553     /* When vlc.app is run by double clicking in Mac OS X, the 2nd arg
554      * is the PSN - process serial number (a unique PID-ish thingie)
555      * still ok for real Darwin & when run from command line */
556     if ( (*pi_argc > 1) && (strncmp( ppsz_argv[ 1 ] , "-psn" , 4 ) == 0) )
557                                         /* for example -psn_0_9306113 */
558     {
559         /* GDMF!... I can't do this or else the MacOSX window server will
560          * not pick up the PSN and not register the app and we crash...
561          * hence the following kludge otherwise we'll get confused w/ argv[1]
562          * being an input file name */
563 #if 0
564         ppsz_argv[ 1 ] = NULL;
565 #endif
566         *pi_argc = *pi_argc - 1;
567         pi_argc--;
568         return( 0 );
569     }
570 #endif
571
572     /* Parse command line options */
573     opterr = 0;
574     while( ( i_cmd = getopt_long( *pi_argc, ppsz_argv,
575                                    psz_shortopts, longopts, 0 ) ) != EOF )
576     {
577         switch( i_cmd )
578         {
579         /* General/common options */
580         case 'h':                                              /* -h, --help */
581             ShowConsole();
582             RedirectSTDOUT();
583             Usage( SHORT_HELP );
584 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
585             if( strcmp( "", main_GetPszVariable( INTF_STDOUT_VAR,
586                                                  INTF_STDOUT_DEFAULT ) ) == 0 )
587             {
588                 /* No stdout redirection has been asked for */
589                 intf_MsgImm( "\nPress the RETURN key to continue..." );
590                 getchar();
591             }
592 #endif
593             return( -1 );
594             break;
595         case 'H':                                          /* -H, --longhelp */
596             ShowConsole();
597             RedirectSTDOUT();
598             Usage( LONG_HELP );
599 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
600             if( strcmp( "", main_GetPszVariable( INTF_STDOUT_VAR,
601                                                  INTF_STDOUT_DEFAULT ) ) == 0 )
602             {
603                 /* No stdout redirection has been asked for */
604                 intf_MsgImm( "\nPress the RETURN key to continue..." );
605                 getchar();
606             }
607 #endif
608             return( -1 );
609             break;
610         case OPT_VERSION:                                       /* --version */
611             ShowConsole();
612             RedirectSTDOUT();
613             Version();
614 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
615             if( strcmp( "", main_GetPszVariable( INTF_STDOUT_VAR,
616                                                  INTF_STDOUT_DEFAULT ) ) == 0 )
617             {
618                 /* No stdout redirection has been asked for */
619                 intf_MsgImm( "\nPress the RETURN key to continue..." );
620                 getchar();
621             }
622 #endif
623             return( -1 );
624             break;
625         case 'v':                                           /* -v, --verbose */
626             p_main->i_warning_level++;
627             break;
628
629         /* Interface warning messages level */
630         case 'I':                                              /* -I, --intf */
631             main_PutPszVariable( INTF_METHOD_VAR, optarg );
632             break;
633         case OPT_WARNING:                                       /* --warning */
634             intf_ErrMsg( "intf error: `--warning' is deprecated, use `-v'" );
635             p_main->i_warning_level = atoi(optarg);
636             break;
637
638         case OPT_STDOUT:                                         /* --stdout */
639             main_PutPszVariable( INTF_STDOUT_VAR, optarg );
640             break;
641
642         /* Audio options */
643         case OPT_NOAUDIO:                                       /* --noaudio */
644             p_main->b_audio = 0;
645             break;
646         case 'A':                                              /* -A, --aout */
647             main_PutPszVariable( AOUT_METHOD_VAR, optarg );
648             break;
649         case OPT_STEREO:                                         /* --stereo */
650             main_PutIntVariable( AOUT_STEREO_VAR, 1 );
651             break;
652         case OPT_MONO:                                             /* --mono */
653             main_PutIntVariable( AOUT_STEREO_VAR, 0 );
654             break;
655         case OPT_SPDIF:                                           /* --spdif */
656             main_PutIntVariable( AOUT_SPDIF_VAR, 1 );
657             break;
658         case OPT_DOWNMIX:                                       /* --downmix */
659             main_PutPszVariable( DOWNMIX_METHOD_VAR, optarg );
660             break;
661         case OPT_IMDCT:                                           /* --imdct */
662             main_PutPszVariable( IMDCT_METHOD_VAR, optarg );
663             break;
664
665         /* Video options */
666         case OPT_NOVIDEO:                                       /* --novideo */
667             p_main->b_video = 0;
668             break;
669         case 'V':                                              /* -V, --vout */
670             main_PutPszVariable( VOUT_METHOD_VAR, optarg );
671             break;
672         case OPT_DISPLAY:                                       /* --display */
673             main_PutPszVariable( VOUT_DISPLAY_VAR, optarg );
674             break;
675         case OPT_WIDTH:                                           /* --width */
676             main_PutPszVariable( VOUT_WIDTH_VAR, optarg );
677             break;
678         case OPT_HEIGHT:                                         /* --height */
679             main_PutPszVariable( VOUT_HEIGHT_VAR, optarg );
680             break;
681         case 'g':                                         /* -g, --grayscale */
682             main_PutIntVariable( VOUT_GRAYSCALE_VAR, 1 );
683             break;
684         case OPT_COLOR:                                           /* --color */
685             main_PutIntVariable( VOUT_GRAYSCALE_VAR, 0 );
686             break;
687         case OPT_FULLSCREEN:                                 /* --fullscreen */
688             main_PutIntVariable( VOUT_FULLSCREEN_VAR, 1 );
689             break;
690         case OPT_OVERLAY:                                       /* --overlay */
691             main_PutIntVariable( VOUT_OVERLAY_VAR, 1 );
692             break;
693         case OPT_MOTION:                                         /* --motion */
694             main_PutPszVariable( MOTION_METHOD_VAR, optarg );
695             break;
696         case OPT_IDCT:                                             /* --idct */
697             main_PutPszVariable( IDCT_METHOD_VAR, optarg );
698             break;
699         case OPT_YUV:                                               /* --yuv */
700             main_PutPszVariable( YUV_METHOD_VAR, optarg );
701             break;
702         case OPT_SMP:                                               /* --smp */
703             main_PutIntVariable( VDEC_SMP_VAR, atoi(optarg) );
704             break;
705
706         /* DVD options */
707         case 't':
708             main_PutIntVariable( INPUT_TITLE_VAR, atoi(optarg) );
709             break;
710         case 'T':
711             main_PutIntVariable( INPUT_CHAPTER_VAR, atoi(optarg) );
712             break;
713         case 'u':
714             main_PutIntVariable( INPUT_ANGLE_VAR, atoi(optarg) );
715             break;
716         case 'a':
717             if ( ! strcmp(optarg, "ac3") )
718                 main_PutIntVariable( INPUT_AUDIO_VAR, REQUESTED_AC3 );
719             else if ( ! strcmp(optarg, "lpcm") )
720                 main_PutIntVariable( INPUT_AUDIO_VAR, REQUESTED_LPCM );
721             else if ( ! strcmp(optarg, "mpeg") )
722                 main_PutIntVariable( INPUT_AUDIO_VAR, REQUESTED_MPEG );
723             else
724                 main_PutIntVariable( INPUT_AUDIO_VAR, REQUESTED_NOAUDIO );
725             break;
726         case 'c':
727             main_PutIntVariable( INPUT_CHANNEL_VAR, atoi(optarg) );
728             break;
729         case 's':
730             main_PutIntVariable( INPUT_SUBTITLE_VAR, atoi(optarg) );
731             break;
732
733         /* Input options */
734         case OPT_INPUT:                                           /* --input */
735             main_PutPszVariable( INPUT_METHOD_VAR, optarg );
736             break;
737         case OPT_CHANNELS:                                     /* --channels */
738             main_PutIntVariable( INPUT_NETWORK_CHANNEL_VAR, 1 );
739             break;
740         case OPT_SERVER:                                         /* --server */
741             main_PutPszVariable( INPUT_SERVER_VAR, optarg );
742             break;
743         case OPT_PORT:                                             /* --port */
744             main_PutPszVariable( INPUT_PORT_VAR, optarg );
745             break;
746         case OPT_BROADCAST:                                   /* --broadcast */
747             main_PutIntVariable( INPUT_BROADCAST_VAR, 1 );
748             main_PutPszVariable( INPUT_BCAST_ADDR_VAR, optarg );
749             break;
750
751         /* Synchro options */
752         case OPT_SYNCHRO:                                      
753             main_PutPszVariable( VPAR_SYNCHRO_VAR, optarg );
754             break;
755             
756         /* Internal error: unknown option */
757         case '?':
758         default:
759             ShowConsole();
760             RedirectSTDOUT();
761             intf_ErrMsg( "intf error: unknown option `%s'",
762                          ppsz_argv[optind - 1] );
763             Usage( USAGE );
764 #ifdef WIN32        /* Pause the console because it's destroyed when we exit */
765             if( strcmp( "", main_GetPszVariable( INTF_STDOUT_VAR,
766                                                  INTF_STDOUT_DEFAULT ) ) == 0 )
767             {
768                 /* No stdout redirection has been asked for */
769                 intf_MsgImm( "\nPress the RETURN key to continue..." );
770                 getchar();
771             }
772 #endif
773             return( EINVAL );
774             break;
775         }
776     }
777
778     if( p_main->i_warning_level < 0 )
779     {
780         p_main->i_warning_level = 0;
781     }
782
783     return( 0 );
784 }
785
786 /*****************************************************************************
787  * GetFilenames: parse command line options which are not flags
788  *****************************************************************************
789  * Parse command line for input files.
790  *****************************************************************************/
791 static int GetFilenames( int i_argc, char *ppsz_argv[] )
792 {
793     int i_opt;
794
795     /* We assume that the remaining parameters are filenames */
796     for( i_opt = optind; i_opt < i_argc; i_opt++ )
797     {
798         intf_PlaylistAdd( p_main->p_playlist, PLAYLIST_END,
799                           ppsz_argv[ i_opt ] );
800     }
801
802     return( 0 );
803 }
804
805 /*****************************************************************************
806  * Usage: print program usage
807  *****************************************************************************
808  * Print a short inline help. Message interface is initialized at this stage.
809  *****************************************************************************/
810 static void Usage( int i_fashion )
811 {
812     /* Usage */
813     intf_MsgImm( "Usage: %s [options] [parameters] [file]...",
814                  p_main->psz_arg0 );
815
816     if( i_fashion == USAGE )
817     {
818         intf_MsgImm( "Try `%s --help' for more information.",
819                      p_main->psz_arg0 );
820         return;
821     }
822
823     /* Options */
824     intf_MsgImm( "\nOptions:"
825           "\n  -I, --intf <module>            \tinterface method"
826           "\n  -v, --verbose                  \tverbose mode (cumulative)"
827           "\n      --stdout <filename>        \tredirect console stdout"
828           "\n"
829           "\n      --noaudio                  \tdisable audio"
830           "\n  -A, --aout <module>            \taudio output method"
831           "\n      --stereo, --mono           \tstereo/mono audio"
832           "\n      --spdif                    \tAC3 pass-through mode"
833           "\n      --downmix <module>         \tAC3 downmix method"
834           "\n      --imdct <module>           \tAC3 IMDCT method"
835           "\n"
836           "\n      --novideo                  \tdisable video"
837           "\n  -V, --vout <module>            \tvideo output method"
838           "\n      --display <display>        \tdisplay string"
839           "\n      --width <w>, --height <h>  \tdisplay dimensions"
840           "\n  -g, --grayscale                \tgrayscale output"
841           "\n      --fullscreen               \tfullscreen output"
842           "\n      --overlay                  \taccelerated display"
843           "\n      --color                    \tcolor output"
844           "\n      --motion <module>          \tmotion compensation method"
845           "\n      --idct <module>            \tIDCT method"
846           "\n      --yuv <module>             \tYUV method"
847           "\n      --synchro <type>           \tforce synchro algorithm"
848           "\n      --smp <number of threads>  \tuse several processors"
849           "\n"
850           "\n  -t, --dvdtitle <num>           \tchoose DVD title"
851           "\n  -T, --dvdchapter <num>         \tchoose DVD chapter"
852           "\n  -u, --dvdangle <num>           \tchoose DVD angle"
853           "\n  -a, --dvdaudio <type>          \tchoose DVD audio type"
854           "\n  -c, --dvdchannel <channel>     \tchoose DVD audio channel"
855           "\n  -s, --dvdsubtitle <channel>    \tchoose DVD subtitle channel"
856           "\n"
857           "\n      --input                    \tinput method"
858           "\n      --channels                 \tenable channels"
859           "\n      --server <host>            \tvideo server address"
860           "\n      --port <port>              \tvideo server port"
861           "\n      --broadcast                \tlisten to a broadcast"
862           "\n"
863           "\n  -h, --help                     \tprint help and exit"
864           "\n  -H, --longhelp                 \tprint long help and exit"
865           "\n      --version                  \toutput version information and exit" );
866
867     if( i_fashion == SHORT_HELP )
868         return;
869
870     /* Interface parameters */
871     intf_MsgImm( "\nInterface parameters:"
872         "\n  " INTF_METHOD_VAR "=<method name>        \tinterface method"
873         "\n  " INTF_INIT_SCRIPT_VAR "=<filename>              \tinitialization script"
874         "\n  " INTF_CHANNELS_VAR "=<filename>         \tchannels list"
875         "\n  " INTF_STDOUT_VAR "=<filename>           \tredirect console stdout" );
876
877     /* Audio parameters */
878     intf_MsgImm( "\nAudio parameters:"
879         "\n  " AOUT_METHOD_VAR "=<method name>        \taudio method"
880         "\n  " AOUT_DSP_VAR "=<filename>              \tdsp device path"
881         "\n  " AOUT_STEREO_VAR "={1|0}                \tstereo or mono output"
882         "\n  " AOUT_SPDIF_VAR "={1|0}                 \tAC3 pass-through mode"
883         "\n  " DOWNMIX_METHOD_VAR "=<method name>     \tAC3 downmix method"
884         "\n  " IMDCT_METHOD_VAR "=<method name>       \tAC3 IMDCT method"
885         "\n  " AOUT_RATE_VAR "=<rate>             \toutput rate" );
886
887     /* Video parameters */
888     intf_MsgImm( "\nVideo parameters:"
889         "\n  " VOUT_METHOD_VAR "=<method name>        \tdisplay method"
890         "\n  " VOUT_DISPLAY_VAR "=<display name>      \tdisplay used"
891         "\n  " VOUT_WIDTH_VAR "=<width>               \tdisplay width"
892         "\n  " VOUT_HEIGHT_VAR "=<height>             \tdislay height"
893         "\n  " VOUT_FB_DEV_VAR "=<filename>           \tframebuffer device path"
894         "\n  " VOUT_GRAYSCALE_VAR "={1|0}             \tgrayscale or color output"
895         "\n  " VOUT_FULLSCREEN_VAR "={1|0}            \tfullscreen"
896         "\n  " VOUT_OVERLAY_VAR "={1|0}               \toverlay"
897         "\n  " MOTION_METHOD_VAR "=<method name>      \tmotion compensation method"
898         "\n  " IDCT_METHOD_VAR "=<method name>        \tIDCT method"
899         "\n  " YUV_METHOD_VAR "=<method name>         \tYUV method"
900         "\n  " VPAR_SYNCHRO_VAR "={I|I+|IP|IP+|IPB}   \tsynchro algorithm"
901         "\n  " VDEC_SMP_VAR "=<number of threads>     \tuse several processors" );
902
903     /* DVD parameters */
904     intf_MsgImm( "\nDVD parameters:"
905         "\n  " INPUT_DVD_DEVICE_VAR "=<device>           \tDVD device"
906         "\n  " INPUT_TITLE_VAR "=<title>             \ttitle number"
907         "\n  " INPUT_CHAPTER_VAR "=<chapter>         \tchapter number"
908         "\n  " INPUT_ANGLE_VAR "=<angle>             \tangle number"
909         "\n  " INPUT_AUDIO_VAR "={ac3|lpcm|mpeg|off} \taudio type"
910         "\n  " INPUT_CHANNEL_VAR "=[0-15]            \taudio channel"
911         "\n  " INPUT_SUBTITLE_VAR "=[0-31]           \tsubtitle channel" );
912
913     /* Input parameters */
914     intf_MsgImm( "\nInput parameters:"
915         "\n  " INPUT_SERVER_VAR "=<hostname>         \tvideo server"
916         "\n  " INPUT_PORT_VAR "=<port>               \tvideo server port"
917         "\n  " INPUT_IFACE_VAR "=<interface>         \tnetwork interface"
918         "\n  " INPUT_BCAST_ADDR_VAR "=<addr>         \tbroadcast mode"
919         "\n  " INPUT_CHANNEL_SERVER_VAR "=<hostname> \tchannel server"
920         "\n  " INPUT_CHANNEL_PORT_VAR "=<port>       \tchannel server port" );
921
922 }
923
924 /*****************************************************************************
925  * Version: print complete program version
926  *****************************************************************************
927  * Print complete program version and build number.
928  *****************************************************************************/
929 static void Version( void )
930 {
931     intf_MsgImm( VERSION_MESSAGE
932         "This program comes with NO WARRANTY, to the extent permitted by law.\n"
933         "You may redistribute it under the terms of the GNU General Public License;\n"
934         "see the file named COPYING for details.\n"
935         "Written by the VideoLAN team at Ecole Centrale, Paris." );
936 }
937
938 /*****************************************************************************
939  * InitSignalHandler: system signal handler initialization
940  *****************************************************************************
941  * Set the signal handlers. SIGTERM is not intercepted, because we need at
942  * at least a method to kill the program when all other methods failed, and
943  * when we don't want to use SIGKILL.
944  *****************************************************************************/
945 static void InitSignalHandler( void )
946 {
947     /* Termination signals */
948 #ifndef WIN32
949     signal( SIGINT,  FatalSignalHandler );
950     signal( SIGHUP,  FatalSignalHandler );
951     signal( SIGQUIT, FatalSignalHandler );
952
953     /* Other signals */
954     signal( SIGALRM, SimpleSignalHandler );
955     signal( SIGPIPE, SimpleSignalHandler );
956 #endif
957 }
958
959
960 /*****************************************************************************
961  * SimpleSignalHandler: system signal handler
962  *****************************************************************************
963  * This function is called when a non fatal signal is received by the program.
964  *****************************************************************************/
965 static void SimpleSignalHandler( int i_signal )
966 {
967     /* Acknowledge the signal received */
968     intf_WarnMsg( 0, "intf: ignoring signal %d", i_signal );
969 }
970
971
972 /*****************************************************************************
973  * FatalSignalHandler: system signal handler
974  *****************************************************************************
975  * This function is called when a fatal signal is received by the program.
976  * It tries to end the program in a clean way.
977  *****************************************************************************/
978 static void FatalSignalHandler( int i_signal )
979 {
980     /* Once a signal has been trapped, the termination sequence will be
981      * armed and following signals will be ignored to avoid sending messages
982      * to an interface having been destroyed */
983 #ifndef WIN32
984     signal( SIGINT,  SIG_IGN );
985     signal( SIGHUP,  SIG_IGN );
986     signal( SIGQUIT, SIG_IGN );
987 #endif
988
989     /* Acknowledge the signal received */
990     intf_ErrMsgImm( "intf error: signal %d received, exiting", i_signal );
991
992     /* Try to terminate everything - this is done by requesting the end of the
993      * interface thread */
994     p_main->p_intf->b_die = 1;
995 }
996
997 /*****************************************************************************
998  * InstructionSignalHandler: system signal handler
999  *****************************************************************************
1000  * This function is called when a illegal instruction signal is received by
1001  * the program.
1002  * We use this function to test OS and CPU_Capabilities
1003  *****************************************************************************/
1004 static void InstructionSignalHandler( int i_signal )
1005 {
1006     /* Once a signal has been trapped, the termination sequence will be
1007      * armed and following signals will be ignored to avoid sending messages
1008      * to an interface having been destroyed */
1009
1010     /* Acknowledge the signal received */
1011     fprintf( stderr, "warning: extended instructions unsupported, "
1012                      "some optimizations will be disabled\n" );
1013 #ifdef SYS_LINUX
1014     fprintf( stderr, "upgrade to kernel 2.4.x to get rid of this warning\n" );
1015 #endif
1016
1017     i_illegal = 1;
1018     
1019 #ifdef HAVE_SIGRELSE
1020     sigrelse( i_signal );
1021 #endif
1022     longjmp( env, 1 );
1023 }
1024
1025 /*****************************************************************************
1026  * CPUCapabilities: list the processors MMX support and other capabilities
1027  *****************************************************************************
1028  * This function is called to list extensions the CPU may have.
1029  *****************************************************************************/
1030 static int CPUCapabilities( void )
1031 {
1032     volatile int i_capabilities = CPU_CAPABILITY_NONE;
1033
1034 #if defined( SYS_BEOS )
1035     i_capabilities |= CPU_CAPABILITY_486
1036                       | CPU_CAPABILITY_586
1037                       | CPU_CAPABILITY_MMX;
1038
1039     return( i_capabilities );
1040
1041 #elif defined( SYS_DARWIN )
1042     struct host_basic_info hi;
1043     kern_return_t          ret;
1044     host_name_port_t       host;
1045
1046     int i_size;
1047     char *psz_name, *psz_subname;
1048
1049     /* Should 'never' fail? */
1050     host = mach_host_self();
1051
1052     i_size = sizeof( hi ) / sizeof( int );
1053     ret = host_info( host, HOST_BASIC_INFO, ( host_info_t )&hi, &i_size );
1054
1055     if( ret != KERN_SUCCESS )
1056     {
1057         fprintf( stderr, "error: couldn't get CPU information\n" );
1058         return( i_capabilities );
1059     }
1060
1061     slot_name( hi.cpu_type, hi.cpu_subtype, &psz_name, &psz_subname );
1062     /* FIXME: need better way to detect newer proccessors.
1063      * could do strncmp(a,b,5), but that's real ugly */
1064     if( strcmp(psz_name, "ppc7400") || strcmp(psz_name, "ppc7450") )
1065     {
1066         i_capabilities |= CPU_CAPABILITY_ALTIVEC;
1067     }
1068
1069     return( i_capabilities );
1070
1071 #elif defined( __i386__ )
1072     volatile unsigned int  i_eax, i_ebx, i_ecx, i_edx;
1073     volatile boolean_t     b_amd;
1074
1075     signal( SIGILL, InstructionSignalHandler );
1076     
1077     /* test for a 486 CPU */
1078     asm volatile ( "pushfl\n\t"
1079                    "popl %%eax\n\t"
1080                    "movl %%eax, %%ebx\n\t"
1081                    "xorl $0x200000, %%eax\n\t"
1082                    "pushl %%eax\n\t"
1083                    "popfl\n\t"
1084                    "pushfl\n\t"
1085                    "popl %%eax"
1086                  : "=a" ( i_eax ),
1087                    "=b" ( i_ebx )
1088                  :
1089                  : "cc" );
1090
1091     if( i_eax == i_ebx )
1092     {
1093         signal( SIGILL, NULL );     
1094         return( i_capabilities );
1095     }
1096
1097     i_capabilities |= CPU_CAPABILITY_486;
1098
1099     /* the CPU supports the CPUID instruction - get its level */
1100     cpuid( 0x00000000 );
1101
1102     if( !i_eax )
1103     {
1104         signal( SIGILL, NULL );     
1105         return( i_capabilities );
1106     }
1107
1108     /* FIXME: this isn't correct, since some 486s have cpuid */
1109     i_capabilities |= CPU_CAPABILITY_586;
1110
1111     /* borrowed from mpeg2dec */
1112     b_amd = ( i_ebx == 0x68747541 ) && ( i_ecx == 0x444d4163 )
1113                     && ( i_edx == 0x69746e65 );
1114
1115     /* test for the MMX flag */
1116     cpuid( 0x00000001 );
1117
1118     if( ! (i_edx & 0x00800000) )
1119     {
1120         signal( SIGILL, NULL );     
1121         return( i_capabilities );
1122     }
1123
1124     i_capabilities |= CPU_CAPABILITY_MMX;
1125
1126     if( i_edx & 0x02000000 )
1127     {
1128         i_capabilities |= CPU_CAPABILITY_MMXEXT;
1129
1130         /* We test if OS support the SSE instructions */
1131         i_illegal = 0;
1132         if( setjmp( env ) == 0 )
1133         {
1134             /* Test a SSE instruction */
1135             __asm__ __volatile__ ( "xorps %%xmm0,%%xmm0\n" : : );
1136         }
1137
1138         if( i_illegal == 0 )
1139         {
1140             i_capabilities |= CPU_CAPABILITY_SSE;
1141         }
1142     }
1143     
1144     /* test for additional capabilities */
1145     cpuid( 0x80000000 );
1146
1147     if( i_eax < 0x80000001 )
1148     {
1149         signal( SIGILL, NULL );     
1150         return( i_capabilities );
1151     }
1152
1153     /* list these additional capabilities */
1154     cpuid( 0x80000001 );
1155
1156     if( i_edx & 0x80000000 )
1157     {
1158         i_illegal = 0;
1159         if( setjmp( env ) == 0 )
1160         {
1161             /* Test a 3D Now! instruction */
1162             __asm__ __volatile__ ( "pfadd %%mm0,%%mm0\n" "femms\n" : : );
1163         }
1164
1165         if( i_illegal == 0 ) 
1166         {
1167             i_capabilities |= CPU_CAPABILITY_3DNOW;
1168         }
1169     }
1170
1171     if( b_amd && ( i_edx & 0x00400000 ) )
1172     {
1173         i_capabilities |= CPU_CAPABILITY_MMXEXT;
1174     }
1175
1176     signal( SIGILL, NULL );     
1177     return( i_capabilities );
1178
1179 #else
1180     /* default behaviour */
1181     return( i_capabilities );
1182
1183 #endif
1184 }
1185
1186 /*****************************************************************************
1187  * RedirectSTDOUT: redirect stdout and stderr to a file
1188  *****************************************************************************
1189  * This function will redirect stdout and stderr to a file if the user has
1190  * specified so.
1191  *****************************************************************************/
1192 static int RedirectSTDOUT( void )
1193 {
1194     int  i_stdout_filedesc;
1195     char *psz_stdout_filename;
1196
1197     psz_stdout_filename = main_GetPszVariable( INTF_STDOUT_VAR,
1198                                                INTF_STDOUT_DEFAULT );
1199     if( strcmp( "", psz_stdout_filename ) != 0 )
1200     {
1201         ShowConsole();
1202         i_stdout_filedesc = open( psz_stdout_filename,
1203                                   O_CREAT | O_TRUNC | O_RDWR,
1204                                   S_IREAD | S_IWRITE );
1205
1206         if( dup2( i_stdout_filedesc, fileno(stdout) ) == -1 )
1207         {
1208             intf_ErrMsg( "warning: unable to redirect stdout" );
1209         }
1210
1211         if( dup2( i_stdout_filedesc, fileno(stderr) ) == -1 )
1212         {
1213             intf_ErrMsg( "warning: unable to redirect stderr" );
1214         }
1215
1216         close( i_stdout_filedesc );
1217     }
1218     else
1219     {
1220         /* No stdout redirection has been asked so open a console */
1221         if( p_main->i_warning_level )
1222         {
1223             ShowConsole();
1224         }
1225
1226     }
1227
1228     return 0;
1229 }
1230
1231 /*****************************************************************************
1232  * ShowConsole: On Win32, create an output console for debug messages
1233  *****************************************************************************
1234  * This function is usefull only on Win32.
1235  *****************************************************************************/
1236 static void ShowConsole( void )
1237 {
1238 #ifdef WIN32 /*  */
1239     AllocConsole();
1240     freopen( "CONOUT$", "w", stdout );
1241     freopen( "CONOUT$", "w", stderr );
1242     freopen( "CONIN$", "r", stdin );
1243 #endif
1244     return;
1245 }
1246