]> git.sesse.net Git - vlc/blob - modules/access/mms/mmsh.c
Remove WPL module
[vlc] / modules / access / mms / mmsh.c
1 /*****************************************************************************
2  * mmsh.c:
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_access.h>
34 #include <vlc_strings.h>
35 #include <vlc_input.h>
36
37 #include <vlc_network.h>
38 #include <vlc_url.h>
39 #include "asf.h"
40 #include "buffer.h"
41
42 #include "mms.h"
43 #include "mmsh.h"
44
45 #include "assert.h"
46 /* TODO:
47  *  - authentication
48  */
49
50 /*****************************************************************************
51  * Local prototypes
52  *****************************************************************************/
53 int  MMSHOpen  ( access_t * );
54 void MMSHClose ( access_t * );
55
56 static block_t *Block( access_t *p_access );
57 static ssize_t ReadRedirect( access_t *, uint8_t *, size_t );
58 static int  Seek( access_t *, uint64_t );
59 static int  Control( access_t *, int, va_list );
60
61 static int  Describe( access_t  *, char **ppsz_location );
62 static int  Start( access_t *, uint64_t );
63 static void Stop( access_t * );
64
65 static int  GetPacket( access_t *, chunk_t * );
66 static void GetHeader( access_t *p_access, int i_content_length );
67
68 static int Restart( access_t * );
69 static int Reset( access_t * );
70
71 //#define MMSH_USER_AGENT "NSPlayer/4.1.0.3856"
72 #define MMSH_USER_AGENT "NSPlayer/7.10.0.3059"
73
74 /****************************************************************************
75  * Open: connect to ftp server and ask for file
76  ****************************************************************************/
77 int MMSHOpen( access_t *p_access )
78 {
79     access_sys_t    *p_sys;
80     char            *psz_location = NULL;
81     char            *psz_proxy;
82
83     STANDARD_BLOCK_ACCESS_INIT
84
85     p_sys->i_proto= MMS_PROTO_HTTP;
86     p_sys->fd     = -1;
87
88     /* Handle proxy */
89     p_sys->b_proxy = false;
90     memset( &p_sys->proxy, 0, sizeof(p_sys->proxy) );
91
92     /* Check proxy */
93     /* TODO reuse instead http-proxy from http access ? */
94     psz_proxy = var_CreateGetNonEmptyString( p_access, "mmsh-proxy" );
95     if( !psz_proxy )
96     {
97         char *psz_http_proxy = var_InheritString( p_access, "http-proxy" );
98         if( psz_http_proxy )
99         {
100             psz_proxy = psz_http_proxy;
101             var_SetString( p_access, "mmsh-proxy", psz_proxy );
102         }
103     }
104
105     if( psz_proxy )
106     {
107         p_sys->b_proxy = true;
108         vlc_UrlParse( &p_sys->proxy, psz_proxy, 0 );
109         free( psz_proxy );
110     }
111     else
112     {
113         const char *http_proxy = getenv( "http_proxy" );
114         if( http_proxy )
115         {
116             p_sys->b_proxy = true;
117             vlc_UrlParse( &p_sys->proxy, http_proxy, 0 );
118         }
119     }
120
121     if( p_sys->b_proxy )
122     {
123         if( ( p_sys->proxy.psz_host == NULL ) ||
124             ( *p_sys->proxy.psz_host == '\0' ) )
125         {
126             msg_Warn( p_access, "invalid proxy host" );
127             vlc_UrlClean( &p_sys->proxy );
128             free( p_sys );
129             return VLC_EGENERIC;
130         }
131
132         if( p_sys->proxy.i_port <= 0 )
133             p_sys->proxy.i_port = 80;
134         msg_Dbg( p_access, "Using http proxy %s:%d",
135                  p_sys->proxy.psz_host, p_sys->proxy.i_port );
136     }
137
138     /* open a tcp connection */
139     vlc_UrlParse( &p_sys->url, p_access->psz_location, 0 );
140     if( ( p_sys->url.psz_host == NULL ) ||
141         ( *p_sys->url.psz_host == '\0' ) )
142     {
143         msg_Err( p_access, "invalid host" );
144         goto error;
145     }
146     if( p_sys->url.i_port <= 0 )
147         p_sys->url.i_port = 80;
148
149     if( Describe( p_access, &psz_location ) )
150         goto error;
151
152     /* Handle redirection */
153     if( psz_location && *psz_location )
154     {
155         msg_Dbg( p_access, "redirection to %s", psz_location );
156
157         input_thread_t * p_input = access_GetParentInput( p_access );
158         input_item_t * p_new_loc;
159
160         if( !p_input )
161         {
162             free( psz_location );
163             goto error;
164         }
165         /** \bug we do not autodelete here */
166         p_new_loc = input_item_New( psz_location, psz_location );
167         input_item_t *p_item = input_GetItem( p_input );
168         input_item_PostSubItem( p_item, p_new_loc );
169
170         vlc_gc_decref( p_new_loc );
171         vlc_object_release( p_input );
172
173         free( psz_location );
174
175         p_access->pf_block = NULL;
176         p_access->pf_read = ReadRedirect;
177         return VLC_SUCCESS;
178     }
179     free( psz_location );
180
181     /* Start playing */
182     if( Start( p_access, 0 ) )
183     {
184         msg_Err( p_access, "cannot start stream" );
185         free( p_sys->p_header );
186         goto error;
187     }
188
189     return VLC_SUCCESS;
190
191 error:
192     vlc_UrlClean( &p_sys->proxy );
193     vlc_UrlClean( &p_sys->url );
194     free( p_sys );
195     return VLC_EGENERIC;
196 }
197
198 /*****************************************************************************
199  * Close: free unused data structures
200  *****************************************************************************/
201 void  MMSHClose ( access_t *p_access )
202 {
203     access_sys_t *p_sys = p_access->p_sys;
204
205     Stop( p_access );
206
207     free( p_sys->p_header );
208
209     vlc_UrlClean( &p_sys->proxy );
210     vlc_UrlClean( &p_sys->url );
211     free( p_sys );
212 }
213
214 /*****************************************************************************
215  * Control:
216  *****************************************************************************/
217 static int Control( access_t *p_access, int i_query, va_list args )
218 {
219     access_sys_t *p_sys = p_access->p_sys;
220     bool   *pb_bool;
221     bool    b_bool;
222     int64_t      *pi_64;
223     int          i_int;
224
225     switch( i_query )
226     {
227         case ACCESS_CAN_SEEK:
228             pb_bool = (bool*)va_arg( args, bool* );
229             *pb_bool = !p_sys->b_broadcast;
230             break;
231
232         case ACCESS_CAN_FASTSEEK:
233             pb_bool = (bool*)va_arg( args, bool* );
234             *pb_bool = false;
235             break;
236
237         case ACCESS_CAN_PAUSE:
238         case ACCESS_CAN_CONTROL_PACE:
239             pb_bool = (bool*)va_arg( args, bool* );
240             *pb_bool = true;
241             break;
242
243         case ACCESS_GET_SIZE:
244         {
245             uint64_t *s = va_arg( args, uint64_t * );
246             *s = p_sys->b_broadcast ? 0 : p_sys->asfh.i_file_size;
247             return VLC_SUCCESS;
248         }
249
250         case ACCESS_GET_PTS_DELAY:
251             pi_64 = (int64_t*)va_arg( args, int64_t * );
252             *pi_64 = INT64_C(1000)
253                    * var_InheritInteger( p_access, "network-caching" );
254             break;
255
256         case ACCESS_GET_PRIVATE_ID_STATE:
257             i_int = (int)va_arg( args, int );
258             pb_bool = (bool *)va_arg( args, bool * );
259
260             if( (i_int < 0) || (i_int > 127) )
261                 return VLC_EGENERIC;
262             *pb_bool =  p_sys->asfh.stream[i_int].i_selected ? true : false;
263             break;
264
265         case ACCESS_SET_PRIVATE_ID_STATE:
266         {
267             i_int = (int)va_arg( args, int );
268             b_bool = (bool)va_arg( args, int );
269             int i_cat;
270             if( i_int > 127 )
271                 return VLC_EGENERIC;
272             else if ( i_int < 0 )
273             {
274                 /* Deselecting all ES in this category */
275                 assert( !b_bool );
276                 i_cat = -1 * i_int;
277                 if ( i_cat > ES_CATEGORY_COUNT )
278                     return VLC_EGENERIC;
279             }
280             else
281             {
282                 /* Chose another ES */
283                 assert( b_bool );
284                 i_cat = p_sys->asfh.stream[i_int].i_cat;
285             }
286
287             for ( int i=0; i< 128; i++ )
288             {
289                 /* First unselect all streams from the same cat */
290                 if ( i_cat == p_sys->asfh.stream[i].i_cat )
291                     p_sys->asfh.stream[i].i_selected = false;
292             }
293
294             if ( i_int > 0 )
295                 p_sys->asfh.stream[i_int].i_selected = true;
296
297             Stop( p_access );
298             Seek( p_access, p_access->info.i_pos );
299             return VLC_SUCCESS;
300         }
301
302         case ACCESS_SET_PAUSE_STATE:
303             b_bool = (bool)va_arg( args, int );
304             if( b_bool )
305                 Stop( p_access );
306             else
307                 Seek( p_access, p_access->info.i_pos );
308             break;
309
310         default:
311             return VLC_EGENERIC;
312     }
313     return VLC_SUCCESS;
314 }
315
316 /*****************************************************************************
317  * Seek: try to go at the right place
318  *****************************************************************************/
319 static int Seek( access_t *p_access, uint64_t i_pos )
320 {
321     access_sys_t *p_sys = p_access->p_sys;
322     chunk_t      ck;
323     uint64_t     i_offset;
324     uint64_t     i_packet;
325
326     msg_Dbg( p_access, "seeking to %"PRId64, i_pos );
327
328     i_packet = ( i_pos - p_sys->i_header ) / p_sys->asfh.i_min_data_packet_size;
329     i_offset = ( i_pos - p_sys->i_header ) % p_sys->asfh.i_min_data_packet_size;
330
331     Stop( p_access );
332     Start( p_access, i_packet * p_sys->asfh.i_min_data_packet_size );
333
334     while( vlc_object_alive (p_access) )
335     {
336         if( GetPacket( p_access, &ck ) )
337             break;
338
339         /* skip headers */
340         if( ck.i_type != 0x4824 )
341             break;
342
343         msg_Warn( p_access, "skipping header" );
344     }
345
346     p_access->info.i_pos = i_pos;
347     p_access->info.b_eof = false;
348     p_sys->i_packet_used += i_offset;
349
350     return VLC_SUCCESS;
351 }
352
353 /*****************************************************************************
354  * ReadRedirect:
355  *****************************************************************************/
356 static ssize_t ReadRedirect( access_t *p_access, uint8_t *p, size_t i_len )
357 {
358     VLC_UNUSED(p_access); VLC_UNUSED(p); VLC_UNUSED(i_len);
359     return 0;
360 }
361
362 /*****************************************************************************
363  * Block:
364  *****************************************************************************/
365 static block_t *Block( access_t *p_access )
366 {
367     access_sys_t *p_sys = p_access->p_sys;
368     const unsigned i_packet_min = p_sys->asfh.i_min_data_packet_size;
369
370     if( p_access->info.i_pos < p_sys->i_start + p_sys->i_header )
371     {
372         const size_t i_offset = p_access->info.i_pos - p_sys->i_start;
373         const size_t i_copy = p_sys->i_header - i_offset;
374
375         block_t *p_block = block_Alloc( i_copy );
376         if( !p_block )
377             return NULL;
378
379         memcpy( p_block->p_buffer, &p_sys->p_header[i_offset], i_copy );
380         p_access->info.i_pos += i_copy;
381         return p_block;
382     }
383     else if( p_sys->i_packet_length > 0 &&
384              p_sys->i_packet_used < __MAX( p_sys->i_packet_length, i_packet_min ) )
385     {
386         size_t i_copy = 0;
387         size_t i_padding = 0;
388
389         if( p_sys->i_packet_used < p_sys->i_packet_length )
390             i_copy = p_sys->i_packet_length - p_sys->i_packet_used;
391         if( __MAX( p_sys->i_packet_used, p_sys->i_packet_length ) < i_packet_min )
392             i_padding = i_packet_min - __MAX( p_sys->i_packet_used, p_sys->i_packet_length );
393
394         block_t *p_block = block_Alloc( i_copy + i_padding );
395         if( !p_block )
396             return NULL;
397
398         if( i_copy > 0 )
399             memcpy( &p_block->p_buffer[0], &p_sys->p_packet[p_sys->i_packet_used], i_copy );
400         if( i_padding > 0 )
401             memset( &p_block->p_buffer[i_copy], 0, i_padding );
402
403         p_sys->i_packet_used += i_copy + i_padding;
404         p_access->info.i_pos += i_copy + i_padding;
405         return p_block;
406
407     }
408
409     chunk_t ck;
410     if( GetPacket( p_access, &ck ) )
411     {
412         int i_ret = -1;
413         if( p_sys->b_broadcast )
414         {
415             if( (ck.i_type == 0x4524) && (ck.i_sequence != 0) )
416                 i_ret = Restart( p_access );
417             else if( ck.i_type == 0x4324 )
418                 i_ret = Reset( p_access );
419         }
420         if( i_ret )
421         {
422             p_access->info.b_eof = true;
423             return 0;
424         }
425     }
426     if( ck.i_type != 0x4424 )
427     {
428         p_sys->i_packet_used = 0;
429         p_sys->i_packet_length = 0;
430     }
431
432     return NULL;
433 }
434
435 /* */
436 static int Restart( access_t *p_access )
437 {
438     access_sys_t *p_sys = p_access->p_sys;
439     char *psz_location = NULL;
440
441     msg_Dbg( p_access, "Restart the stream" );
442     p_sys->i_start = p_access->info.i_pos;
443
444     /* */
445     msg_Dbg( p_access, "stoping the stream" );
446     Stop( p_access );
447
448     /* */
449     msg_Dbg( p_access, "describe the stream" );
450     if( Describe( p_access, &psz_location ) )
451     {
452         msg_Err( p_access, "describe failed" );
453         return VLC_EGENERIC;
454     }
455     free( psz_location );
456
457     /* */
458     if( Start( p_access, 0 ) )
459     {
460         msg_Err( p_access, "Start failed" );
461         return VLC_EGENERIC;
462     }
463     return VLC_SUCCESS;
464 }
465 static int Reset( access_t *p_access )
466 {
467     access_sys_t *p_sys = p_access->p_sys;
468     asf_header_t old_asfh = p_sys->asfh;
469     int i;
470
471     msg_Dbg( p_access, "Reset the stream" );
472     p_sys->i_start = p_access->info.i_pos;
473
474     /* */
475     p_sys->i_packet_sequence = 0;
476     p_sys->i_packet_used = 0;
477     p_sys->i_packet_length = 0;
478     p_sys->p_packet = NULL;
479
480     /* Get the next header FIXME memory loss ? */
481     GetHeader( p_access, -1 );
482     if( p_sys->i_header <= 0 )
483         return VLC_EGENERIC;
484
485     asf_HeaderParse ( &p_sys->asfh,
486                        p_sys->p_header, p_sys->i_header );
487     msg_Dbg( p_access, "packet count=%"PRId64" packet size=%d",
488              p_sys->asfh.i_data_packets_count,
489              p_sys->asfh.i_min_data_packet_size );
490
491     asf_StreamSelect( &p_sys->asfh,
492                        var_InheritInteger( p_access, "mms-maxbitrate" ),
493                        var_InheritBool( p_access, "mms-all" ),
494                        var_InheritBool( p_access, "audio" ),
495                        var_InheritBool( p_access, "video" ) );
496
497     /* Check we have comptible asfh */
498     for( i = 1; i < 128; i++ )
499     {
500         asf_stream_t *p_old = &old_asfh.stream[i];
501         asf_stream_t *p_new = &p_sys->asfh.stream[i];
502
503         if( p_old->i_cat != p_new->i_cat || p_old->i_selected != p_new->i_selected )
504             break;
505     }
506     if( i < 128 )
507     {
508         msg_Warn( p_access, "incompatible asf header, restart" );
509         return Restart( p_access );
510     }
511
512     /* */
513     p_sys->i_packet_used = 0;
514     p_sys->i_packet_length = 0;
515     return VLC_SUCCESS;
516 }
517
518 static int OpenConnection( access_t *p_access )
519 {
520     access_sys_t *p_sys = p_access->p_sys;
521     vlc_url_t    srv = p_sys->b_proxy ? p_sys->proxy : p_sys->url;
522
523     if( ( p_sys->fd = net_ConnectTCP( p_access,
524                                       srv.psz_host, srv.i_port ) ) < 0 )
525     {
526         msg_Err( p_access, "cannot connect to %s:%d",
527                  srv.psz_host, srv.i_port );
528         return VLC_EGENERIC;
529     }
530
531     if( p_sys->b_proxy )
532     {
533         net_Printf( p_access, p_sys->fd, NULL,
534                     "GET http://%s:%d%s HTTP/1.0\r\n",
535                     p_sys->url.psz_host, p_sys->url.i_port,
536                     ( (p_sys->url.psz_path == NULL) ||
537                       (*p_sys->url.psz_path == '\0') ) ?
538                          "/" : p_sys->url.psz_path );
539
540         /* Proxy Authentication */
541         if( p_sys->proxy.psz_username && *p_sys->proxy.psz_username )
542         {
543             char *buf;
544             char *b64;
545
546             if( asprintf( &buf, "%s:%s", p_sys->proxy.psz_username,
547                        p_sys->proxy.psz_password ? p_sys->proxy.psz_password : "" ) == -1 )
548                 return VLC_ENOMEM;
549
550             b64 = vlc_b64_encode( buf );
551             free( buf );
552
553             net_Printf( p_access, p_sys->fd, NULL,
554                         "Proxy-Authorization: Basic %s\r\n", b64 );
555             free( b64 );
556         }
557     }
558     else
559     {
560         net_Printf( p_access, p_sys->fd, NULL,
561                     "GET %s HTTP/1.0\r\n"
562                     "Host: %s:%d\r\n",
563                     ( (p_sys->url.psz_path == NULL) ||
564                       (*p_sys->url.psz_path == '\0') ) ?
565                             "/" : p_sys->url.psz_path,
566                     p_sys->url.psz_host, p_sys->url.i_port );
567     }
568     return VLC_SUCCESS;
569 }
570
571 /*****************************************************************************
572  * Describe:
573  *****************************************************************************/
574 static int Describe( access_t  *p_access, char **ppsz_location )
575 {
576     access_sys_t *p_sys = p_access->p_sys;
577     char         *psz_location = NULL;
578     int          i_content_length = -1;
579     bool         b_keepalive = false;
580     char         *psz;
581     int          i_code;
582
583     /* Reinit context */
584     p_sys->b_broadcast = true;
585     p_sys->i_request_context = 1;
586     p_sys->i_packet_sequence = 0;
587     p_sys->i_packet_used = 0;
588     p_sys->i_packet_length = 0;
589     p_sys->p_packet = NULL;
590
591     GenerateGuid ( &p_sys->guid );
592
593     if( OpenConnection( p_access ) )
594         return VLC_EGENERIC;
595
596     net_Printf( p_access, p_sys->fd, NULL,
597                 "Accept: */*\r\n"
598                 "User-Agent: "MMSH_USER_AGENT"\r\n"
599                 "Pragma: no-cache,rate=1.000000,stream-time=0,stream-offset=0:0,request-context=%d,max-duration=0\r\n"
600                 "Pragma: xClientGUID={"GUID_FMT"}\r\n"
601                 "Connection: Close\r\n",
602                 p_sys->i_request_context++,
603                 GUID_PRINT( p_sys->guid ) );
604
605     if( net_Printf( p_access, p_sys->fd, NULL, "\r\n" ) < 0 )
606     {
607         msg_Err( p_access, "failed to send request" );
608         goto error;
609     }
610
611     /* Receive the http header */
612     if( ( psz = net_Gets( p_access, p_sys->fd, NULL ) ) == NULL )
613     {
614         msg_Err( p_access, "failed to read answer" );
615         goto error;
616     }
617
618     if( strncmp( psz, "HTTP/1.", 7 ) )
619     {
620         msg_Err( p_access, "invalid HTTP reply '%s'", psz );
621         free( psz );
622         goto error;
623     }
624     i_code = atoi( &psz[9] );
625     if( i_code >= 400 )
626     {
627         msg_Err( p_access, "error: %s", psz );
628         free( psz );
629         goto error;
630     }
631
632     msg_Dbg( p_access, "HTTP reply '%s'", psz );
633     free( psz );
634     for( ;; )
635     {
636         char *psz = net_Gets( p_access, p_sys->fd, NULL );
637         char *p;
638
639         if( psz == NULL )
640         {
641             msg_Err( p_access, "failed to read answer" );
642             goto error;
643         }
644
645         if( *psz == '\0' )
646         {
647             free( psz );
648             break;
649         }
650
651         if( ( p = strchr( psz, ':' ) ) == NULL )
652         {
653             msg_Err( p_access, "malformed header line: %s", psz );
654             free( psz );
655             goto error;
656         }
657         *p++ = '\0';
658         while( *p == ' ' ) p++;
659
660         /* FIXME FIXME test Content-Type to see if it's a plain stream or an
661          * asx FIXME */
662         if( !strcasecmp( psz, "Pragma" ) )
663         {
664             if( strstr( p, "features" ) )
665             {
666                 /* FIXME, it is a bit badly done here ..... */
667                 if( strstr( p, "broadcast" ) )
668                 {
669                     msg_Dbg( p_access, "stream type = broadcast" );
670                     p_sys->b_broadcast = true;
671                 }
672                 else if( strstr( p, "seekable" ) )
673                 {
674                     msg_Dbg( p_access, "stream type = seekable" );
675                     p_sys->b_broadcast = false;
676                 }
677                 else
678                 {
679                     msg_Warn( p_access, "unknow stream types (%s)", p );
680                     p_sys->b_broadcast = false;
681                 }
682             }
683         }
684         else if( !strcasecmp( psz, "Location" ) )
685         {
686             psz_location = strdup( p );
687         }
688         else if( !strcasecmp( psz, "Content-Length" ) )
689         {
690             i_content_length = atoi( p );
691             msg_Dbg( p_access, "content-length = %d", i_content_length );
692         }
693         else if( !strcasecmp( psz, "Connection" ) )
694         {
695             if( strcasestr( p, "Keep-Alive" ) )
696             {
697                 msg_Dbg( p_access, "Keep-Alive header found" );
698                 b_keepalive = true;
699             }
700         }
701
702
703         free( psz );
704     }
705
706     /* Handle the redirection */
707     if( ( (i_code == 301) || (i_code == 302) ||
708           (i_code == 303) || (i_code == 307) ) &&
709         psz_location && *psz_location )
710     {
711         msg_Dbg( p_access, "redirection to %s", psz_location );
712         net_Close( p_sys->fd ); p_sys->fd = -1;
713
714         *ppsz_location = psz_location;
715         return VLC_SUCCESS;
716     }
717     free( psz_location );
718
719     /* Read the asf header */
720     GetHeader( p_access, b_keepalive ? i_content_length : -1);
721     if( p_sys->i_header <= 0 )
722     {
723         msg_Err( p_access, "header size == 0" );
724         goto error;
725     }
726     /* close this connection */
727     net_Close( p_sys->fd );
728     p_sys->fd = -1;
729
730     /* *** parse header and get stream and their id *** */
731     /* get all streams properties,
732      *
733      * TODO : stream bitrates properties(optional)
734      *        and bitrate mutual exclusion(optional) */
735     asf_HeaderParse ( &p_sys->asfh,
736                        p_sys->p_header, p_sys->i_header );
737     msg_Dbg( p_access, "packet count=%"PRId64" packet size=%d",
738              p_sys->asfh.i_data_packets_count,
739              p_sys->asfh.i_min_data_packet_size );
740
741     if( p_sys->asfh.i_min_data_packet_size <= 0 )
742         goto error;
743
744     asf_StreamSelect( &p_sys->asfh,
745                        var_InheritInteger( p_access, "mms-maxbitrate" ),
746                        var_InheritBool( p_access, "mms-all" ),
747                        var_InheritBool( p_access, "audio" ),
748                        var_InheritBool( p_access, "video" ) );
749     return VLC_SUCCESS;
750
751 error:
752     if( p_sys->fd > 0 )
753     {
754         net_Close( p_sys->fd  );
755         p_sys->fd = -1;
756     }
757     return VLC_EGENERIC;
758 }
759
760 static void GetHeader( access_t *p_access, int i_content_length )
761 {
762     access_sys_t *p_sys = p_access->p_sys;
763     int i_read_content = 0;
764
765     /* Read the asf header */
766     p_sys->i_header = 0;
767     free( p_sys->p_header  );
768     p_sys->p_header = NULL;
769     for( ;; )
770     {
771         chunk_t ck;
772         if( (i_content_length >= 0 && i_read_content >= i_content_length) || GetPacket( p_access, &ck ) || ck.i_type != 0x4824 )
773             break;
774
775         i_read_content += (4+ck.i_size);
776
777         if( ck.i_data > 0 )
778         {
779             p_sys->i_header += ck.i_data;
780             p_sys->p_header = xrealloc( p_sys->p_header, p_sys->i_header );
781             memcpy( &p_sys->p_header[p_sys->i_header - ck.i_data],
782                     ck.p_data, ck.i_data );
783         }
784     }
785     msg_Dbg( p_access, "complete header size=%d", p_sys->i_header );
786 }
787
788
789 /*****************************************************************************
790  * Start stream
791  ****************************************************************************/
792 static int Start( access_t *p_access, uint64_t i_pos )
793 {
794     access_sys_t *p_sys = p_access->p_sys;
795     int  i_streams = 0;
796     int  i_streams_selected = 0;
797     int  i;
798     char *psz = NULL;
799
800     msg_Dbg( p_access, "starting stream" );
801
802     for( i = 1; i < 128; i++ )
803     {
804         if( p_sys->asfh.stream[i].i_cat == ASF_CODEC_TYPE_UNKNOWN )
805             continue;
806         i_streams++;
807         if( p_sys->asfh.stream[i].i_selected )
808             i_streams_selected++;
809     }
810     if( i_streams_selected <= 0 )
811     {
812         msg_Err( p_access, "no stream selected" );
813         return VLC_EGENERIC;
814     }
815
816     if( OpenConnection( p_access ) )
817         return VLC_EGENERIC;
818
819     net_Printf( p_access, p_sys->fd, NULL,
820                 "Accept: */*\r\n"
821                 "User-Agent: "MMSH_USER_AGENT"\r\n" );
822     if( p_sys->b_broadcast )
823     {
824         net_Printf( p_access, p_sys->fd, NULL,
825                     "Pragma: no-cache,rate=1.000000,request-context=%d\r\n",
826                     p_sys->i_request_context++ );
827     }
828     else
829     {
830         net_Printf( p_access, p_sys->fd, NULL,
831                     "Pragma: no-cache,rate=1.000000,stream-time=0,stream-offset=%u:%u,request-context=%d,max-duration=0\r\n",
832                     (uint32_t)((i_pos >> 32)&0xffffffff),
833                     (uint32_t)(i_pos&0xffffffff),
834                     p_sys->i_request_context++ );
835     }
836     net_Printf( p_access, p_sys->fd, NULL,
837                 "Pragma: xPlayStrm=1\r\n"
838                 "Pragma: xClientGUID={"GUID_FMT"}\r\n"
839                 "Pragma: stream-switch-count=%d\r\n"
840                 "Pragma: stream-switch-entry=",
841                 GUID_PRINT( p_sys->guid ),
842                 i_streams);
843
844     for( i = 1; i < 128; i++ )
845     {
846         if( p_sys->asfh.stream[i].i_cat != ASF_CODEC_TYPE_UNKNOWN )
847         {
848             int i_select = 2;
849             if( p_sys->asfh.stream[i].i_selected )
850             {
851                 i_select = 0;
852             }
853             net_Printf( p_access, p_sys->fd, NULL,
854                         "ffff:%x:%d ", i, i_select );
855         }
856     }
857     net_Printf( p_access, p_sys->fd, NULL, "\r\n" );
858     net_Printf( p_access, p_sys->fd, NULL,
859                 "Connection: Close\r\n" );
860
861     if( net_Printf( p_access, p_sys->fd, NULL, "\r\n" ) < 0 )
862     {
863         msg_Err( p_access, "failed to send request" );
864         return VLC_EGENERIC;
865     }
866
867     psz = net_Gets( p_access, p_sys->fd, NULL );
868     if( psz == NULL )
869     {
870         msg_Err( p_access, "cannot read data 0" );
871         return VLC_EGENERIC;
872     }
873
874     if( atoi( &psz[9] ) >= 400 )
875     {
876         msg_Err( p_access, "error: %s", psz );
877         free( psz );
878         return VLC_EGENERIC;
879     }
880     msg_Dbg( p_access, "HTTP reply '%s'", psz );
881     free( psz );
882
883     /* FIXME check HTTP code */
884     for( ;; )
885     {
886         char *psz = net_Gets( p_access, p_sys->fd, NULL );
887         if( psz == NULL )
888         {
889             msg_Err( p_access, "cannot read data 1" );
890             return VLC_EGENERIC;
891         }
892         if( *psz == '\0' )
893         {
894             free( psz );
895             break;
896         }
897         msg_Dbg( p_access, "%s", psz );
898         free( psz );
899     }
900
901     p_sys->i_packet_used   = 0;
902     p_sys->i_packet_length = 0;
903
904     return VLC_SUCCESS;
905 }
906
907 /*****************************************************************************
908  * closing stream
909  *****************************************************************************/
910 static void Stop( access_t *p_access )
911 {
912     access_sys_t *p_sys = p_access->p_sys;
913
914     msg_Dbg( p_access, "closing stream" );
915     if( p_sys->fd > 0 )
916     {
917         net_Close( p_sys->fd );
918         p_sys->fd = -1;
919     }
920 }
921
922 /*****************************************************************************
923  * get packet
924  *****************************************************************************/
925 static int GetPacket( access_t * p_access, chunk_t *p_ck )
926 {
927     access_sys_t *p_sys = p_access->p_sys;
928     int restsize;
929
930     /* chunk_t */
931     memset( p_ck, 0, sizeof( chunk_t ) );
932
933     /* Read the chunk header */
934     /* Some headers are short, like 0x4324. Reading 12 bytes will cause us
935      * to lose synchronization with the stream. Just read to the length
936      * (4 bytes), decode and then read up to 8 additional bytes to get the
937      * entire header.
938      */
939     if( net_Read( p_access, p_sys->fd, NULL, p_sys->buffer, 4, true ) < 4 )
940     {
941        msg_Err( p_access, "cannot read data 2" );
942        return VLC_EGENERIC;
943     }
944
945     p_ck->i_type = GetWLE( p_sys->buffer);
946     p_ck->i_size = GetWLE( p_sys->buffer + 2);
947
948     restsize = p_ck->i_size;
949     if( restsize > 8 )
950         restsize = 8;
951
952     if( net_Read( p_access, p_sys->fd, NULL, p_sys->buffer + 4, restsize, true ) < restsize )
953     {
954         msg_Err( p_access, "cannot read data 3" );
955         return VLC_EGENERIC;
956     }
957     p_ck->i_sequence  = GetDWLE( p_sys->buffer + 4);
958     p_ck->i_unknown   = GetWLE( p_sys->buffer + 8);
959
960     /* Set i_size2 to 8 if this header was short, since a real value won't be
961      * present in the buffer. Using 8 avoid reading additional data for the
962      * packet.
963      */
964     if( restsize < 8 )
965         p_ck->i_size2 = 8;
966     else
967         p_ck->i_size2 = GetWLE( p_sys->buffer + 10);
968
969     p_ck->p_data      = p_sys->buffer + 12;
970     p_ck->i_data      = p_ck->i_size2 - 8;
971
972     if( p_ck->i_type == 0x4524 )   // $E (End-of-Stream Notification) Packet
973     {
974         if( p_ck->i_sequence == 0 )
975         {
976             msg_Warn( p_access, "EOF" );
977             return VLC_EGENERIC;
978         }
979         else
980         {
981             msg_Warn( p_access, "next stream following" );
982             return VLC_EGENERIC;
983         }
984     }
985     else if( p_ck->i_type == 0x4324 ) // $C (Stream Change Notification) Packet
986     {
987         /* 0x4324 is CHUNK_TYPE_RESET: a new stream will follow with a sequence of 0 */
988         msg_Warn( p_access, "next stream following (reset) seq=%d", p_ck->i_sequence  );
989         return VLC_EGENERIC;
990     }
991     else if( (p_ck->i_type != 0x4824) && (p_ck->i_type != 0x4424) )
992     {
993         /* Unsupported so far:
994          * $M (Metadata) Packet               0x4D24
995          * $P (Packet-Pair) Packet            0x5024
996          * $T (Test Data Notification) Packet 0x5424
997          */
998         msg_Err( p_access, "unrecognized chunk FATAL (0x%x)", p_ck->i_type );
999         return VLC_EGENERIC;
1000     }
1001
1002     if( (p_ck->i_data > 0) &&
1003         (net_Read( p_access, p_sys->fd, NULL, &p_sys->buffer[12],
1004                    p_ck->i_data, true ) < p_ck->i_data) )
1005     {
1006         msg_Err( p_access, "cannot read data 4" );
1007         return VLC_EGENERIC;
1008     }
1009
1010 #if 0
1011     if( (p_sys->i_packet_sequence != 0) &&
1012         (p_ck->i_sequence != p_sys->i_packet_sequence) )
1013     {
1014         msg_Warn( p_access, "packet lost ? (%d != %d)", p_ck->i_sequence, p_sys->i_packet_sequence );
1015     }
1016 #endif
1017
1018     p_sys->i_packet_sequence = p_ck->i_sequence + 1;
1019     p_sys->i_packet_used   = 0;
1020     p_sys->i_packet_length = p_ck->i_data;
1021     p_sys->p_packet        = p_ck->p_data;
1022
1023     return VLC_SUCCESS;
1024 }