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