]> git.sesse.net Git - vlc/blob - src/input/input.c
* libdvdcss port to OpenBSD.
[vlc] / src / input / input.c
1 /*****************************************************************************
2  * input.c: input thread
3  * Read an MPEG2 stream, demultiplex and parse it before sending it to
4  * decoders.
5  *****************************************************************************
6  * Copyright (C) 1998, 1999, 2000 VideoLAN
7  * $Id: input.c,v 1.149 2001/11/02 13:30:38 massiot Exp $
8  *
9  * Authors: Christophe Massiot <massiot@via.ecp.fr>
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  * 
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
21  * You should have received a copy of the GNU General Public License
22  * along with this program; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #include "defs.h"
30
31 #include <stdlib.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <fcntl.h>
35
36 #ifdef HAVE_UNISTD_H
37 #   include <unistd.h>
38 #elif defined( _MSC_VER ) && defined( _WIN32 )
39 #   include <io.h>
40 #endif
41
42 #include <string.h>
43 #include <errno.h>
44
45 #ifdef STRNCASECMP_IN_STRINGS_H
46 #   include <strings.h>
47 #endif
48
49 #ifdef WIN32
50 #   include <winsock.h>
51 #   include <winsock2.h>
52 #elif !defined( SYS_BEOS ) && !defined( SYS_NTO )
53 #   include <netdb.h>                                         /* hostent ... */
54 #   include <sys/socket.h>
55 #   include <netinet/in.h>
56 #   include <arpa/inet.h>
57 #   include <sys/types.h>
58 #   include <sys/socket.h>
59 #endif
60
61 #ifdef HAVE_SYS_TIMES_H
62 #   include <sys/times.h>
63 #endif
64
65 #include "config.h"
66 #include "common.h"
67 #include "threads.h"
68 #include "mtime.h"
69 #include "netutils.h"
70 #include "modules.h"
71
72 #include "intf_msg.h"
73 #include "intf_playlist.h"
74
75 #include "stream_control.h"
76 #include "input_ext-intf.h"
77 #include "input_ext-dec.h"
78 #include "input_ext-plugins.h"
79
80 #include "interface.h"
81
82 #include "main.h"
83
84 /*****************************************************************************
85  * Local prototypes
86  *****************************************************************************/
87 static void RunThread       ( input_thread_t *p_input );
88 static  int InitThread      ( input_thread_t *p_input );
89 static void ErrorThread     ( input_thread_t *p_input );
90 static void CloseThread     ( input_thread_t *p_input );
91 static void DestroyThread   ( input_thread_t *p_input );
92 static void EndThread       ( input_thread_t *p_input );
93
94 static void FileOpen        ( input_thread_t *p_input );
95 static void StdOpen         ( input_thread_t *p_input );
96 static void FileClose       ( input_thread_t *p_input );
97 #if !defined( SYS_BEOS ) && !defined( SYS_NTO )
98 static void NetworkOpen     ( input_thread_t *p_input );
99 static void HTTPOpen        ( input_thread_t *p_input );
100 static void NetworkClose    ( input_thread_t *p_input );
101 #endif
102
103 /*****************************************************************************
104  * input_CreateThread: creates a new input thread
105  *****************************************************************************
106  * This function creates a new input, and returns a pointer
107  * to its description. On error, it returns NULL.
108  * If pi_status is NULL, then the function will block until the thread is ready.
109  * If not, it will be updated using one of the THREAD_* constants.
110  *****************************************************************************/
111 input_thread_t *input_CreateThread ( playlist_item_t *p_item, int *pi_status )
112 {
113     input_thread_t *    p_input;                        /* thread descriptor */
114     int                 i_status;                           /* thread status */
115
116     /* Allocate descriptor */
117     p_input = (input_thread_t *)malloc( sizeof(input_thread_t) );
118     if( p_input == NULL )
119     {
120         intf_ErrMsg( "input error: can't allocate input thread (%s)",
121                      strerror(errno) );
122         return( NULL );
123     }
124
125     /* Packets read once */
126     p_input->i_read_once = INPUT_READ_ONCE;
127
128     /* Initialize thread properties */
129     p_input->b_die              = 0;
130     p_input->b_error            = 0;
131     p_input->b_eof              = 0;
132
133     /* Set target */
134     p_input->p_source           = p_item->psz_name;
135
136     /* I have never understood that stuff --Meuuh */
137     p_input->pi_status          = (pi_status != NULL) ? pi_status : &i_status;
138     *p_input->pi_status         = THREAD_CREATE;
139
140     /* Initialize stream description */
141     p_input->stream.i_es_number = 0;
142     p_input->stream.i_selected_es_number = 0;
143     p_input->stream.i_pgrm_number = 0;
144     p_input->stream.i_new_status = p_input->stream.i_new_rate = 0;
145     p_input->stream.b_new_mute = MUTE_NO_CHANGE;
146     p_input->stream.i_mux_rate = 0;
147
148     /* no stream, no area */
149     p_input->stream.i_area_nb = 0;
150     p_input->stream.pp_areas = NULL;
151     p_input->stream.p_selected_area = NULL;
152     p_input->stream.p_new_area = NULL;
153
154     /* By default there is one area in a stream */
155     input_AddArea( p_input );
156     p_input->stream.p_selected_area = p_input->stream.pp_areas[0];
157
158     /* Initialize stream control properties. */
159     p_input->stream.control.i_status = PLAYING_S;
160     p_input->stream.control.i_rate = DEFAULT_RATE;
161     p_input->stream.control.b_mute = 0;
162     p_input->stream.control.b_grayscale = main_GetIntVariable(
163                             VOUT_GRAYSCALE_VAR, VOUT_GRAYSCALE_DEFAULT );
164     p_input->stream.control.i_smp = main_GetIntVariable(
165                             VDEC_SMP_VAR, VDEC_SMP_DEFAULT );
166
167     intf_WarnMsg( 1, "input: playlist item `%s'", p_input->p_source );
168
169     /* Create thread. */
170     if( vlc_thread_create( &p_input->thread_id, "input", (void *) RunThread,
171                            (void *) p_input ) )
172     {
173         intf_ErrMsg( "input error: can't create input thread (%s)",
174                      strerror(errno) );
175         free( p_input );
176         return( NULL );
177     }
178
179     /* If status is NULL, wait until the thread is created */
180     if( pi_status == NULL )
181     {
182         do
183         {
184             msleep( THREAD_SLEEP );
185         } while( (i_status != THREAD_READY) && (i_status != THREAD_ERROR)
186                 && (i_status != THREAD_FATAL) );
187         if( i_status != THREAD_READY )
188         {
189             return( NULL );
190         }
191     }
192     return( p_input );
193 }
194
195 /*****************************************************************************
196  * input_DestroyThread: mark an input thread as zombie
197  *****************************************************************************
198  * This function should not return until the thread is effectively cancelled.
199  *****************************************************************************/
200 void input_DestroyThread( input_thread_t *p_input, int *pi_status )
201 {
202     int         i_status;                                   /* thread status */
203
204     /* Set status */
205     p_input->pi_status = (pi_status != NULL) ? pi_status : &i_status;
206     *p_input->pi_status = THREAD_DESTROY;
207
208     /* Request thread destruction */
209     p_input->b_die = 1;
210
211     /* Make the thread exit of an eventual vlc_cond_wait() */
212     vlc_mutex_lock( &p_input->stream.stream_lock );
213     vlc_cond_signal( &p_input->stream.stream_wait );
214     vlc_mutex_unlock( &p_input->stream.stream_lock );
215
216     /* If status is NULL, wait until thread has been destroyed */
217     if( pi_status == NULL )
218     {
219         do
220         {
221             msleep( THREAD_SLEEP );
222         } while ( (i_status != THREAD_OVER) && (i_status != THREAD_ERROR)
223                   && (i_status != THREAD_FATAL) );
224     }
225 }
226
227 /*****************************************************************************
228  * RunThread: main thread loop
229  *****************************************************************************
230  * Thread in charge of processing the network packets and demultiplexing.
231  *****************************************************************************/
232 static void RunThread( input_thread_t *p_input )
233 {
234     int                     i_error, i;
235     data_packet_t **        pp_packets;
236
237     if( InitThread( p_input ) )
238     {
239         /* If we failed, wait before we are killed, and exit */
240         *p_input->pi_status = THREAD_ERROR;
241         p_input->b_error = 1;
242         ErrorThread( p_input );
243         DestroyThread( p_input );
244         return;
245     }
246
247     /* initialization is completed */
248     vlc_mutex_lock( &p_input->stream.stream_lock );
249     p_input->stream.b_changed = 1;
250     vlc_mutex_unlock( &p_input->stream.stream_lock );
251
252     pp_packets = (data_packet_t **) malloc( p_input->i_read_once *
253                                         sizeof( data_packet_t * ) );
254     if( pp_packets == NULL )
255     {
256         intf_ErrMsg( "input error: out of memory" );
257         free( pp_packets );
258         p_input->b_error = 1;
259     }
260
261     while( !p_input->b_die && !p_input->b_error && !p_input->b_eof )
262     {
263         p_input->c_loops++;
264
265         vlc_mutex_lock( &p_input->stream.stream_lock );
266
267         if( p_input->stream.p_new_area )
268         {
269             if( p_input->stream.b_seekable && p_input->pf_set_area != NULL )
270             {
271
272                 p_input->pf_set_area( p_input, p_input->stream.p_new_area );
273
274                 for( i = 0; i < p_input->stream.i_pgrm_number; i++ )
275                 {
276                     pgrm_descriptor_t * p_pgrm
277                                             = p_input->stream.pp_programs[i];
278                     /* Escape all decoders for the stream discontinuity they
279                      * will encounter. */
280                     input_EscapeDiscontinuity( p_input, p_pgrm );
281
282                     /* Reinitialize synchro. */
283                     p_pgrm->i_synchro_state = SYNCHRO_REINIT;
284                 }
285             }
286             p_input->stream.p_new_area = NULL;
287         }
288
289         if( p_input->stream.p_selected_area->i_seek != NO_SEEK )
290         {
291             if( p_input->stream.b_seekable && p_input->pf_seek != NULL )
292             {
293                 p_input->pf_seek( p_input,
294                                   p_input->stream.p_selected_area->i_seek );
295
296                 for( i = 0; i < p_input->stream.i_pgrm_number; i++ )
297                 {
298                     pgrm_descriptor_t * p_pgrm
299                                             = p_input->stream.pp_programs[i];
300                     /* Escape all decoders for the stream discontinuity they
301                      * will encounter. */
302                     input_EscapeDiscontinuity( p_input, p_pgrm );
303
304                     /* Reinitialize synchro. */
305                     p_pgrm->i_synchro_state = SYNCHRO_REINIT;
306                 }
307             }
308             p_input->stream.p_selected_area->i_seek = NO_SEEK;
309         }
310
311         if( p_input->stream.p_removed_es )
312         {
313             input_UnselectES( p_input, p_input->stream.p_removed_es );
314             p_input->stream.p_removed_es = NULL;
315         }
316
317         if( p_input->stream.p_newly_selected_es )
318         {
319             input_SelectES( p_input, p_input->stream.p_newly_selected_es );
320             p_input->stream.p_newly_selected_es = NULL;
321         }
322
323         if( p_input->stream.b_new_mute != MUTE_NO_CHANGE )
324         {
325             if( p_input->stream.b_new_mute )
326             {
327                 input_EscapeAudioDiscontinuity( p_input );
328             }
329
330             vlc_mutex_lock( &p_input->stream.control.control_lock );
331             p_input->stream.control.b_mute = p_input->stream.b_new_mute;
332             vlc_mutex_unlock( &p_input->stream.control.control_lock );
333
334             p_input->stream.b_new_mute = MUTE_NO_CHANGE;
335         }
336
337         vlc_mutex_unlock( &p_input->stream.stream_lock );
338
339         i_error = p_input->pf_read( p_input, pp_packets );
340
341         /* Demultiplex read packets. */
342         for( i = 0; i < p_input->i_read_once && pp_packets[i] != NULL; i++ )
343         {
344             p_input->stream.c_packets_read++;
345             p_input->pf_demux( p_input, pp_packets[i] );
346         }
347
348         if( i_error )
349         {
350             if( i_error == 1 )
351             {
352                 /* End of file - we do not set b_die because only the
353                  * interface is allowed to do so. */
354                 intf_WarnMsg( 3, "input: EOF reached" );
355                 p_input->b_eof = 1;
356             }
357             else
358             {
359                 p_input->b_error = 1;
360             }
361         }
362     }
363
364     free( pp_packets );
365
366     if( p_input->b_error || p_input->b_eof )
367     {
368         ErrorThread( p_input );
369     }
370
371     EndThread( p_input );
372
373     DestroyThread( p_input );
374
375     intf_DbgMsg("input: Thread end");
376 }
377
378 /*****************************************************************************
379  * InitThread: init the input Thread
380  *****************************************************************************/
381 static int InitThread( input_thread_t * p_input )
382 {
383
384     /* Initialize statistics */
385     p_input->c_loops                    = 0;
386     p_input->stream.c_packets_read      = 0;
387     p_input->stream.c_packets_trashed   = 0;
388     p_input->p_stream                   = NULL;
389
390     /* Set locks. */
391     vlc_mutex_init( &p_input->stream.stream_lock );
392     vlc_cond_init( &p_input->stream.stream_wait );
393     vlc_mutex_init( &p_input->stream.control.control_lock );
394
395     /* Find appropriate module. */
396     p_input->p_input_module = module_Need( MODULE_CAPABILITY_INPUT,
397                                            (probedata_t *)p_input );
398
399     if( p_input->p_input_module == NULL )
400     {
401         intf_ErrMsg( "input error: no suitable input module for `%s'",
402                      p_input->p_source );
403         return( -1 );
404     }
405
406 #define f p_input->p_input_module->p_functions->input.functions.input
407     p_input->pf_init          = f.pf_init;
408     p_input->pf_end           = f.pf_end;
409     p_input->pf_init_bit_stream= f.pf_init_bit_stream;
410     p_input->pf_read          = f.pf_read;
411     p_input->pf_set_area      = f.pf_set_area;
412     p_input->pf_demux         = f.pf_demux;
413     p_input->pf_new_packet    = f.pf_new_packet;
414     p_input->pf_new_pes       = f.pf_new_pes;
415     p_input->pf_delete_packet = f.pf_delete_packet;
416     p_input->pf_delete_pes    = f.pf_delete_pes;
417     p_input->pf_rewind        = f.pf_rewind;
418     p_input->pf_seek          = f.pf_seek;
419
420 #if !defined( SYS_BEOS ) && !defined( SYS_NTO )
421     /* FIXME : this is waaaay too kludgy */
422     if( ( strlen( p_input->p_source ) > 3)
423           && !strncasecmp( p_input->p_source, "ts:", 3 ) )
424     {
425         /* Network stream */
426         NetworkOpen( p_input );
427         p_input->stream.i_method = INPUT_METHOD_NETWORK;
428     }
429     else if( ( strlen( p_input->p_source ) > 5 )
430                && !strncasecmp( p_input->p_source, "http:", 5 ) )
431     {
432         /* HTTP stream */
433         HTTPOpen( p_input );
434         p_input->stream.i_method = INPUT_METHOD_NETWORK;
435     }
436     else 
437 #endif
438         if( ( strlen( p_input->p_source ) > 4 )
439               && !strncasecmp( p_input->p_source, "dvd:", 4 ) )
440     {
441         /* DVD - this is THE kludge */
442         f.pf_open( p_input );
443         p_input->stream.i_method = INPUT_METHOD_DVD;
444     }
445     else if( ( strlen( p_input->p_source ) > 4 )
446                && !strncasecmp( p_input->p_source, "vlc:", 4 ) )
447     {
448         /* Dummy input - very kludgy */
449         f.pf_open( p_input );
450     }
451     else if( ( strlen( p_input->p_source ) == 1 )
452                && *p_input->p_source == '-' )
453     {
454         /* Stdin */
455         StdOpen( p_input );
456     }
457     else
458     {
459         /* File input */
460         FileOpen( p_input );
461         p_input->stream.i_method = INPUT_METHOD_FILE;
462     }
463 #undef f
464
465     if( p_input->b_error )
466     {
467         /* We barfed -- exit nicely */
468         module_Unneed( p_input->p_input_module );
469         return( -1 );
470     }
471
472     p_input->pf_init( p_input );
473
474     if( p_input->b_error )
475     {
476         /* We barfed -- exit nicely */
477         CloseThread( p_input );
478         module_Unneed( p_input->p_input_module );
479         return( -1 );
480     }
481
482     *p_input->pi_status = THREAD_READY;
483
484     return( 0 );
485 }
486
487 /*****************************************************************************
488  * ErrorThread: RunThread() error loop
489  *****************************************************************************
490  * This function is called when an error occured during thread main's loop.
491  *****************************************************************************/
492 static void ErrorThread( input_thread_t *p_input )
493 {
494     while( !p_input->b_die )
495     {
496         /* Sleep a while */
497         msleep( INPUT_IDLE_SLEEP );
498     }
499 }
500
501 /*****************************************************************************
502  * EndThread: end the input thread
503  *****************************************************************************/
504 static void EndThread( input_thread_t * p_input )
505 {
506     int *       pi_status;                                  /* thread status */
507
508     /* Store status */
509     pi_status = p_input->pi_status;
510     *pi_status = THREAD_END;
511
512     if( p_main->b_stats )
513     {
514 #ifdef HAVE_SYS_TIMES_H
515         /* Display statistics */
516         struct tms  cpu_usage;
517         times( &cpu_usage );
518
519         intf_StatMsg( "input stats: %d loops consuming user: %d, system: %d",
520                       p_input->c_loops,
521                       cpu_usage.tms_utime, cpu_usage.tms_stime );
522 #else
523         intf_StatMsg( "input stats: %d loops", p_input->c_loops );
524 #endif
525
526         input_DumpStream( p_input );
527     }
528
529     /* Free all ES and destroy all decoder threads */
530     input_EndStream( p_input );
531
532     /* Free demultiplexer's data */
533     p_input->pf_end( p_input );
534
535     /* Close the input method */
536     CloseThread( p_input );
537
538     /* Release modules */
539     module_Unneed( p_input->p_input_module );
540
541 }
542
543 /*****************************************************************************
544  * CloseThread: close the target
545  *****************************************************************************/
546 static void CloseThread( input_thread_t * p_input )
547 {
548 #define f p_input->p_input_module->p_functions->input.functions.input
549
550 #if !defined( SYS_BEOS ) && !defined( SYS_NTO )
551     /* Close stream */
552     if( ( strlen( p_input->p_source ) > 3)
553           && !strncasecmp( p_input->p_source, "ts:", 3 ) )
554     {
555         NetworkClose( p_input );
556     }
557     else if( ( strlen( p_input->p_source ) > 5 )
558                && !strncasecmp( p_input->p_source, "http:", 5 ) )
559     {
560         NetworkClose( p_input );
561     }
562     else 
563 #endif
564     if( ( strlen( p_input->p_source ) > 4 )
565           && !strncasecmp( p_input->p_source, "dvd:", 4 ) )
566     {
567         f.pf_close( p_input );
568     }
569     else if( ( strlen( p_input->p_source ) > 4 )
570                && !strncasecmp( p_input->p_source, "vlc:", 4 ) )
571     {
572         f.pf_close( p_input );
573     }
574     else
575     {
576         FileClose( p_input );
577     }
578 #undef f
579 }
580
581 /*****************************************************************************
582  * DestroyThread: destroy the input thread
583  *****************************************************************************/
584 static void DestroyThread( input_thread_t * p_input )
585 {
586     int *       pi_status;                                  /* thread status */
587
588     /* Store status */
589     pi_status = p_input->pi_status;
590
591     /* Destroy Mutex locks */
592     vlc_mutex_destroy( &p_input->stream.control.control_lock );
593     vlc_mutex_destroy( &p_input->stream.stream_lock );
594     
595     /* Free input structure */
596     free( p_input );
597
598     /* Update status */
599     *pi_status = THREAD_OVER;
600 }
601
602 /*****************************************************************************
603  * StdOpen : open standard input
604  *****************************************************************************/
605 static void StdOpen( input_thread_t * p_input )
606 {
607     vlc_mutex_lock( &p_input->stream.stream_lock );
608
609     /* Suppose we can control the pace - this won't work in some cases ! */
610     p_input->stream.b_pace_control = 1;
611
612     p_input->stream.b_seekable = 0;
613     p_input->stream.p_selected_area->i_size = 0;
614     p_input->stream.p_selected_area->i_tell = 0;
615     vlc_mutex_unlock( &p_input->stream.stream_lock );
616
617     intf_WarnMsg( 2, "input: opening stdin" );
618     p_input->i_handle = 0;
619 }
620
621 /*****************************************************************************
622  * FileOpen : open a file descriptor
623  *****************************************************************************/
624 static void FileOpen( input_thread_t * p_input )
625 {
626     struct stat         stat_info;
627     int                 i_stat;
628
629     char *psz_name = p_input->p_source;
630
631     if( ( i_stat = stat( psz_name, &stat_info ) ) == (-1) )
632     {
633         int i_size = strlen( psz_name );
634
635         if( ( i_size > 4 )
636             && !strncasecmp( psz_name, "dvd:", 4 ) )
637         {
638             /* get rid of the 'dvd:' stuff and try again */
639             psz_name += 4;
640             i_stat = stat( psz_name, &stat_info );
641         }
642         else if( ( i_size > 4 )
643                  && !strncasecmp( psz_name, "vcd:", 4 ) )
644         {
645             /* get rid of the 'vcd:' stuff and try again */
646             psz_name += 4;
647             i_stat = stat( psz_name, &stat_info );
648         }
649         else if( ( i_size > 5 )
650                  && !strncasecmp( psz_name, "file:", 5 ) )
651         {
652             /* get rid of the 'file:' stuff and try again */
653             psz_name += 5;
654             i_stat = stat( psz_name, &stat_info );
655         }
656
657         if( i_stat == (-1) )
658         {
659             intf_ErrMsg( "input error: cannot stat() file `%s' (%s)",
660                          psz_name, strerror(errno));
661             p_input->b_error = 1;
662             return;
663         }
664     }
665
666     vlc_mutex_lock( &p_input->stream.stream_lock );
667
668     /* If we are here we can control the pace... */
669     p_input->stream.b_pace_control = 1;
670
671     if( S_ISREG(stat_info.st_mode) || S_ISCHR(stat_info.st_mode)
672          || S_ISBLK(stat_info.st_mode) )
673     {
674         p_input->stream.b_seekable = 1;
675         p_input->stream.p_selected_area->i_size = stat_info.st_size;
676     }
677     else if( S_ISFIFO(stat_info.st_mode)
678 #if !defined( SYS_BEOS ) && !defined( WIN32 )
679              || S_ISSOCK(stat_info.st_mode)
680 #endif
681              )
682     {
683         p_input->stream.b_seekable = 0;
684         p_input->stream.p_selected_area->i_size = 0;
685     }
686     else
687     {
688         vlc_mutex_unlock( &p_input->stream.stream_lock );
689         intf_ErrMsg( "input error: unknown file type for `%s'",
690                      psz_name );
691         p_input->b_error = 1;
692         return;
693     }
694
695     p_input->stream.p_selected_area->i_tell = 0;
696     vlc_mutex_unlock( &p_input->stream.stream_lock );
697
698     intf_WarnMsg( 2, "input: opening file `%s'", p_input->p_source );
699     if( (p_input->i_handle = open( psz_name,
700                                    /*O_NONBLOCK | O_LARGEFILE*/0 )) == (-1) )
701     {
702         intf_ErrMsg( "input error: cannot open file (%s)", strerror(errno) );
703         p_input->b_error = 1;
704         return;
705     }
706
707 }
708
709 /*****************************************************************************
710  * FileClose : close a file descriptor
711  *****************************************************************************/
712 static void FileClose( input_thread_t * p_input )
713 {
714     intf_WarnMsg( 2, "input: closing file `%s'", p_input->p_source );
715
716     close( p_input->i_handle );
717
718     return;
719 }
720
721 #if !defined( SYS_BEOS ) && !defined( SYS_NTO )
722 /*****************************************************************************
723  * NetworkOpen : open a network socket 
724  *****************************************************************************/
725 static void NetworkOpen( input_thread_t * p_input )
726 {
727     char                *psz_server = NULL;
728     char                *psz_broadcast = NULL;
729     int                 i_port = 0;
730     int                 i_opt;
731     int                 i_opt_size;
732     struct sockaddr_in  sock;
733     unsigned int        i_mc_group;
734
735 #ifdef WIN32
736     WSADATA Data;
737     int i_err;
738 #endif
739     
740 #ifdef WIN32
741     /* WinSock Library Init. */
742     i_err = WSAStartup( MAKEWORD( 1, 1 ), &Data );
743
744     if( i_err )
745     {
746         intf_ErrMsg( "input: can't initiate WinSocks, error %i", i_err );
747         return ;
748     }
749 #endif
750     
751     /* Get the remote server */
752     if( p_input->p_source != NULL )
753     {
754         psz_server = p_input->p_source;
755
756         /* Skip the protocol name */
757         while( *psz_server && *psz_server != ':' )
758         {
759             psz_server++;
760         }
761
762         /* Skip the "://" part */
763         while( *psz_server && (*psz_server == ':' || *psz_server == '/') )
764         {
765             psz_server++;
766         }
767
768         /* Found a server name */
769         if( *psz_server )
770         {
771             char *psz_port = psz_server;
772
773             /* Skip the hostname part */
774             while( *psz_port && *psz_port != ':' && *psz_port != '/' )
775             {
776                 psz_port++;
777             }
778
779             /* Found a port name or a broadcast addres */
780             if( *psz_port )
781             {
782                 /* That's a port name */
783                 if( *psz_port == ':' )
784                 {
785                     *psz_port = '\0';
786                     psz_port++;
787                     i_port = atoi( psz_port );
788                 }
789
790                 /* Search for '/' just after the port in case
791                  * we also have a broadcast address */
792                 psz_broadcast = psz_port;
793                 while( *psz_broadcast && *psz_broadcast != '/' )
794                 {
795                     psz_broadcast++;
796                 }
797
798                 if( *psz_broadcast )
799                 {
800                     *psz_broadcast = '\0';
801                     psz_broadcast++;
802                     while( *psz_broadcast && *psz_broadcast == '/' )
803                     {
804                         psz_broadcast++;
805                     }
806                 }
807                 else
808                 {
809                     psz_broadcast = NULL;
810                 }
811             }
812         }
813         else
814         {
815             psz_server = NULL;
816         }
817     }
818
819     /* Check that we got a valid server */
820     if( psz_server == NULL )
821     {
822         psz_server = main_GetPszVariable( INPUT_SERVER_VAR, 
823                                           INPUT_SERVER_DEFAULT );
824     }
825
826     /* Check that we got a valid port */
827     if( i_port == 0 )
828     {
829         i_port = main_GetIntVariable( INPUT_PORT_VAR, INPUT_PORT_DEFAULT );
830     }
831
832     if( psz_broadcast == NULL )
833     {
834         /* Are we broadcasting ? */
835         if( main_GetIntVariable( INPUT_BROADCAST_VAR,
836                                  INPUT_BROADCAST_DEFAULT ) )
837         {
838             psz_broadcast = main_GetPszVariable( INPUT_BCAST_ADDR_VAR,
839                                                  INPUT_BCAST_ADDR_DEFAULT );
840         }
841         else
842         {
843            psz_broadcast = NULL; 
844         }
845     }
846
847     intf_WarnMsg( 2, "input: server=%s port=%d broadcast=%s",
848                      psz_server, i_port, psz_broadcast );
849
850     /* Open a SOCK_DGRAM (UDP) socket, in the AF_INET domain, automatic (0)
851      * protocol */
852     p_input->i_handle = socket( AF_INET, SOCK_DGRAM, 0 );
853     if( p_input->i_handle == -1 )
854     {
855         intf_ErrMsg( "input error: can't create socket (%s)", strerror(errno) );
856         p_input->b_error = 1;
857         return;
858     }
859
860     /* We may want to reuse an already used socket */
861     i_opt = 1;
862     if( setsockopt( p_input->i_handle, SOL_SOCKET, SO_REUSEADDR,
863                     (void *) &i_opt, sizeof( i_opt ) ) == -1 )
864     {
865         intf_ErrMsg( "input error: can't configure socket (SO_REUSEADDR: %s)",
866                      strerror(errno));
867         close( p_input->i_handle );
868         p_input->b_error = 1;
869         return;
870     }
871
872     /* Increase the receive buffer size to 1/2MB (8Mb/s during 1/2s) to avoid
873      * packet loss caused by scheduling problems */
874     i_opt = 0x80000;
875     if( setsockopt( p_input->i_handle, SOL_SOCKET, SO_RCVBUF,
876                     (void *) &i_opt, sizeof( i_opt ) ) == -1 )
877     {
878         intf_ErrMsg( "input error: can't configure socket (SO_RCVBUF: %s)", 
879                      strerror(errno));
880         close( p_input->i_handle );
881         p_input->b_error = 1;
882         return;
883     }
884
885     /* Check if we really got what we have asked for, because Linux, etc.
886      * will silently limit the max buffer size to net.core.rmem_max which
887      * is typically only 65535 bytes */
888     i_opt = 0;
889     i_opt_size = sizeof( i_opt );
890     if( getsockopt( p_input->i_handle, SOL_SOCKET, SO_RCVBUF,
891                     (void*) &i_opt, &i_opt_size ) == -1 )
892     {
893         intf_ErrMsg( "input error: can't configure socket (SO_RCVBUF: %s)", 
894                      strerror(errno));
895         close( p_input->i_handle );
896         p_input->b_error = 1;
897         return;
898     }
899     
900     if( i_opt < 0x80000 )
901     {
902         intf_WarnMsg( 1, "input warning: socket receive buffer size just 0x%x"
903                          " instead of 0x%x bytes.", i_opt, 0x80000 );
904     }
905
906     /* Build the local socket */
907     if ( network_BuildLocalAddr( &sock, i_port, psz_broadcast ) == -1 )
908     {
909         intf_ErrMsg( "input error: can't build local address" );
910         close( p_input->i_handle );
911         p_input->b_error = 1;
912         return;
913     }
914
915     /* Required for IP_ADD_MEMBERSHIP */
916     i_mc_group = sock.sin_addr.s_addr;
917
918 #if defined( WIN32 )
919     if ( psz_broadcast != NULL )
920     {
921         sock.sin_addr.s_addr = INADDR_ANY;
922     }
923     
924 #define IN_MULTICAST(a)         IN_CLASSD(a)
925 #endif
926
927     /* Bind it */
928     if( bind( p_input->i_handle, (struct sockaddr *)&sock, 
929               sizeof( sock ) ) < 0 )
930     {
931         intf_ErrMsg( "input error: can't bind socket (%s)", strerror(errno) );
932         close( p_input->i_handle );
933         p_input->b_error = 1;
934         return;
935     }
936
937     /* Join the multicast group if the socket is a multicast address */
938
939 #ifndef WIN32    
940     if( IN_MULTICAST( ntohl(i_mc_group) ) )
941     {
942         struct ip_mreq imr;
943
944         imr.imr_interface.s_addr = htonl(INADDR_ANY);
945         imr.imr_multiaddr.s_addr = i_mc_group;
946         if( setsockopt( p_input->i_handle, IPPROTO_IP, IP_ADD_MEMBERSHIP,
947                         (char*)&imr, sizeof(struct ip_mreq) ) == -1 )
948         {
949             intf_ErrMsg( "input error: failed to join IP multicast group (%s)",
950                          strerror(errno) );
951             close( p_input->i_handle);
952             p_input->b_error = 1;
953             return;
954         }
955     }
956 #endif
957     
958     /* Build socket for remote connection */
959     if ( network_BuildRemoteAddr( &sock, psz_server ) == -1 )
960     {
961         intf_ErrMsg( "input error: can't build remote address" );
962         close( p_input->i_handle );
963         p_input->b_error = 1;
964         return;
965     }
966
967     /* Only connect if the user has passed a valid host */
968     if( sock.sin_addr.s_addr != INADDR_ANY )
969     {
970         /* Connect the socket */
971         if( connect( p_input->i_handle, (struct sockaddr *) &sock,
972                      sizeof( sock ) ) == (-1) )
973         {
974             intf_ErrMsg( "input error: can't connect socket (%s)", 
975                          strerror(errno) );
976             close( p_input->i_handle );
977             p_input->b_error = 1;
978             return;
979         }
980     }
981
982     p_input->stream.b_pace_control = 0;
983     p_input->stream.b_seekable = 0;
984
985     intf_WarnMsg( 3, "input: successfully opened network mode" );
986     
987     return;
988 }
989
990 /*****************************************************************************
991  * NetworkClose : close a network socket
992  *****************************************************************************/
993 static void NetworkClose( input_thread_t * p_input )
994 {
995     close( p_input->i_handle );
996
997 #ifdef WIN32 
998     WSACleanup();
999 #endif
1000 }
1001
1002 /*****************************************************************************
1003  * HTTPOpen : make an HTTP request
1004  *****************************************************************************/
1005 static void HTTPOpen( input_thread_t * p_input )
1006 {
1007     char                *psz_server = NULL;
1008     char                *psz_path = NULL;
1009     char                *psz_proxy;
1010     int                 i_port = 0;
1011     int                 i_opt;
1012     struct sockaddr_in  sock;
1013     char                psz_buffer[256];
1014
1015 #ifdef WIN32
1016     WSADATA Data;
1017     int i_err;
1018 #endif
1019     
1020 #ifdef WIN32
1021     /* WinSock Library Init. */
1022     i_err = WSAStartup( MAKEWORD( 1, 1 ), &Data );
1023
1024     if( i_err )
1025     {
1026         intf_ErrMsg( "input: can't initiate WinSocks, error %i", i_err );
1027         return ;
1028     }
1029 #endif
1030     
1031     /* Get the remote server */
1032     if( p_input->p_source != NULL )
1033     {
1034         psz_server = p_input->p_source;
1035
1036         /* Skip the protocol name */
1037         while( *psz_server && *psz_server != ':' )
1038         {
1039             psz_server++;
1040         }
1041
1042         /* Skip the "://" part */
1043         while( *psz_server && (*psz_server == ':' || *psz_server == '/') )
1044         {
1045             psz_server++;
1046         }
1047
1048         /* Found a server name */
1049         if( *psz_server )
1050         {
1051             char *psz_port = psz_server;
1052
1053             /* Skip the hostname part */
1054             while( *psz_port && *psz_port != ':' && *psz_port != '/' )
1055             {
1056                 psz_port++;
1057             }
1058
1059             /* Found a port name */
1060             if( *psz_port )
1061             {
1062                 if( *psz_port == ':' )
1063                 {
1064                     /* Replace ':' with '\0' */
1065                     *psz_port = '\0';
1066                     psz_port++;
1067                 }
1068
1069                 psz_path = psz_port;
1070                 while( *psz_path && *psz_path != '/' )
1071                 {
1072                     psz_path++;
1073                 }
1074
1075                 if( *psz_path )
1076                 {
1077                     *psz_path = '\0';
1078                     psz_path++;
1079                 }
1080                 else
1081                 {
1082                     psz_path = NULL;
1083                 }
1084
1085                 if( *psz_port != '\0' )
1086                 {
1087                     i_port = atoi( psz_port );
1088                 }
1089             }
1090         }
1091         else
1092         {
1093             psz_server = NULL;
1094         }
1095     }
1096
1097     /* Check that we got a valid server */
1098     if( psz_server == NULL )
1099     {
1100         intf_ErrMsg( "input error: No server given" );
1101         p_input->b_error = 1;
1102         return;
1103     }
1104
1105     /* Check that we got a valid port */
1106     if( i_port == 0 )
1107     {
1108         i_port = 80; /* FIXME */
1109     }
1110
1111     intf_WarnMsg( 2, "input: server=%s port=%d path=%s", psz_server,
1112                   i_port, psz_path );
1113
1114     /* Open a SOCK_STREAM (TCP) socket, in the AF_INET domain, automatic (0)
1115      *      * protocol */
1116     p_input->i_handle = socket( AF_INET, SOCK_STREAM, 0 );
1117     if( p_input->i_handle == -1 )
1118     {
1119         intf_ErrMsg( "input error: can't create socket (%s)", strerror(errno) );        p_input->b_error = 1;
1120         return;
1121     }
1122
1123     /* We may want to reuse an already used socket */
1124     i_opt = 1;
1125     if( setsockopt( p_input->i_handle, SOL_SOCKET, SO_REUSEADDR,
1126                     (void *) &i_opt, sizeof( i_opt ) ) == -1 )
1127     {
1128         intf_ErrMsg( "input error: can't configure socket (SO_REUSEADDR: %s)",
1129                      strerror(errno));
1130         close( p_input->i_handle );
1131         p_input->b_error = 1;
1132         return;
1133     }
1134
1135     /* Check proxy */
1136     if( (psz_proxy = main_GetPszVariable( "http_proxy", NULL )) != NULL )
1137     {
1138         /* http://myproxy.mydomain:myport/ */
1139         int                 i_proxy_port = 0;
1140
1141         /* Skip the protocol name */
1142         while( *psz_proxy && *psz_proxy != ':' )
1143         {
1144             psz_proxy++;
1145         }
1146
1147         /* Skip the "://" part */
1148         while( *psz_proxy && (*psz_proxy == ':' || *psz_proxy == '/') )
1149         {
1150             psz_proxy++;
1151         }
1152
1153         /* Found a proxy name */
1154         if( *psz_proxy )
1155         {
1156             char *psz_port = psz_proxy;
1157
1158             /* Skip the hostname part */
1159             while( *psz_port && *psz_port != ':' && *psz_port != '/' )
1160             {
1161                 psz_port++;
1162             }
1163
1164             /* Found a port name */
1165             if( *psz_port )
1166             {
1167                 char * psz_junk;
1168
1169                 /* Replace ':' with '\0' */
1170                 *psz_port = '\0';
1171                 psz_port++;
1172
1173                 psz_junk = psz_port;
1174                 while( *psz_junk && *psz_junk != '/' )
1175                 {
1176                     psz_junk++;
1177                 }
1178
1179                 if( *psz_junk )
1180                 {
1181                     *psz_junk = '\0';
1182                 }
1183
1184                 if( *psz_port != '\0' )
1185                 {
1186                     i_proxy_port = atoi( psz_port );
1187                 }
1188             }
1189         }
1190         else
1191         {
1192             intf_ErrMsg( "input error: http_proxy environment variable is invalid !" );
1193             close( p_input->i_handle );
1194             p_input->b_error = 1;
1195             return;
1196         }
1197
1198         /* Build socket for proxy connection */
1199         if ( network_BuildRemoteAddr( &sock, psz_proxy ) == -1 )
1200         {
1201             intf_ErrMsg( "input error: can't build remote address" );
1202             close( p_input->i_handle );
1203             p_input->b_error = 1;
1204             return;
1205         }
1206         sock.sin_port = htons( i_proxy_port );
1207     }
1208     else
1209     {
1210         /* No proxy, direct connection */
1211         if ( network_BuildRemoteAddr( &sock, psz_server ) == -1 )
1212         {
1213             intf_ErrMsg( "input error: can't build remote address" );
1214             close( p_input->i_handle );
1215             p_input->b_error = 1;
1216             return;
1217         }
1218         sock.sin_port = htons( i_port );
1219     }
1220
1221     /* Connect the socket */
1222     if( connect( p_input->i_handle, (struct sockaddr *) &sock,
1223                  sizeof( sock ) ) == (-1) )
1224     {
1225         intf_ErrMsg( "input error: can't connect socket (%s)",
1226                      strerror(errno) );
1227         close( p_input->i_handle );
1228         p_input->b_error = 1;
1229         return;
1230     }
1231
1232     p_input->stream.b_seekable = 0;
1233     p_input->stream.b_pace_control = 1; /* TCP/IP... */
1234
1235 #   define HTTP_USERAGENT "User-Agent: " COPYRIGHT_MESSAGE "\r\n"
1236 #   define HTTP_END       "\r\n"
1237
1238     /* Prepare GET ... */
1239     if( psz_proxy != NULL )
1240     {
1241         snprintf( psz_buffer, sizeof(psz_buffer),
1242                   "GET http://%s:%d/%s HTTP/1.0\r\n"
1243                   HTTP_USERAGENT HTTP_END,
1244                   psz_server, i_port, psz_path );
1245     }
1246     else
1247     {
1248         snprintf( psz_buffer, sizeof(psz_buffer),
1249                   "GET /%s HTTP/1.0\r\nHost: %s\r\n"
1250                   HTTP_USERAGENT HTTP_END,
1251                   psz_path, psz_server );
1252     }
1253     psz_buffer[sizeof(psz_buffer) - 1] = '\0';
1254
1255     /* Send GET ... */
1256     if( write( p_input->i_handle, psz_buffer, strlen( psz_buffer ) ) == (-1) )
1257     {
1258         intf_ErrMsg( "input error: can't send request (%s)", strerror(errno) );
1259         close( p_input->i_handle );
1260         p_input->b_error = 1;
1261         return;
1262     }
1263
1264     /* Read HTTP header - this is gonna be fun with plug-ins which do not
1265      * use p_input->p_stream :-( */
1266     if( (p_input->p_stream = fdopen( p_input->i_handle, "r+" )) == NULL )
1267     {
1268         intf_ErrMsg( "input error: can't reopen socket (%s)", strerror(errno) );
1269         close( p_input->i_handle );
1270         p_input->b_error = 1;
1271         return;
1272     }
1273
1274     while( !feof( p_input->p_stream ) && !ferror( p_input->p_stream ) )
1275     {
1276         if( fgets( psz_buffer, sizeof(psz_buffer), p_input->p_stream ) == NULL
1277              || *psz_buffer == '\r' || *psz_buffer == '\0' )
1278         {
1279             break;
1280         }
1281         /* FIXME : check Content-Type one day */
1282     }
1283
1284     intf_WarnMsg( 3, "input: successfully opened HTTP mode" );
1285 }
1286
1287 #endif /* !defined( SYS_BEOS ) && !defined( SYS_NTO ) */
1288