]> git.sesse.net Git - vlc/blob - modules/access/mms/mmstu.c
d7f858679de8ff73e6920e7accd877a034e90151
[vlc] / modules / access / mms / mmstu.c
1 /*****************************************************************************
2  * mms.c: MMS access plug-in
3  *****************************************************************************
4  * Copyright (C) 2001, 2002 the VideoLAN team
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
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_access.h>
34
35 #include <errno.h>
36 #include <assert.h>
37
38 #ifdef HAVE_UNISTD_H
39 #   include <unistd.h>
40 #endif
41 #ifdef HAVE_FCNTL_H
42 #   include <fcntl.h>
43 #endif
44 #ifdef HAVE_SYS_TIME_H
45 #   include <sys/time.h>
46 #endif
47 #ifdef HAVE_SYS_TYPES_H
48 #   include <sys/types.h>
49 #endif
50 #ifdef HAVE_SYS_STAT_H
51 #   include <sys/stat.h>
52 #endif
53 #ifdef HAVE_POLL
54 #   include <poll.h>
55 #endif
56
57 #include <vlc_network.h>
58 #include "vlc_url.h"
59 #include "asf.h"
60 #include "buffer.h"
61
62 #include "mms.h"
63 #include "mmstu.h"
64
65 #undef MMS_DEBUG
66
67 /****************************************************************************
68  * NOTES:
69  *  MMSProtocole documentation found at http://get.to/sdp
70  ****************************************************************************/
71
72 /*****************************************************************************
73  * Local prototypes
74  *****************************************************************************/
75 int   MMSTUOpen   ( access_t * );
76 void  MMSTUClose  ( access_t * );
77
78
79 static ssize_t Read( access_t *, uint8_t *, size_t );
80 static int Seek( access_t *, int64_t );
81 static int Control( access_t *, int, va_list );
82
83 static int  MMSOpen ( access_t *, vlc_url_t *, int );
84 static int  MMSStart( access_t *, uint32_t );
85 static int  MMSStop ( access_t * );
86 static void MMSClose( access_t * );
87
88
89 static int  mms_CommandRead( access_t *p_access, int i_command1, int i_command2 );
90 static int  mms_CommandSend( access_t *, int, uint32_t, uint32_t, uint8_t *, int );
91
92 static int  mms_HeaderMediaRead( access_t *, int );
93
94 static int  mms_ReceivePacket( access_t * );
95
96 static void* KeepAliveThread( void * );
97
98 int  MMSTUOpen( access_t *p_access )
99 {
100     access_sys_t   *p_sys;
101     int             i_proto;
102     int             i_status;
103
104     /* Set up p_access */
105     p_access->pf_read = Read;
106     p_access->pf_block = NULL;
107     p_access->pf_control = Control;
108     p_access->pf_seek = Seek;
109     p_access->info.i_update = 0;
110     p_access->info.i_size = 0;
111     p_access->info.i_pos = 0;
112     p_access->info.b_eof = false;
113     p_access->info.i_title = 0;
114     p_access->info.i_seekpoint = 0;
115     p_access->p_sys = p_sys = malloc( sizeof( access_sys_t ) );
116     if( !p_sys ) return VLC_ENOMEM;
117     memset( p_sys, 0, sizeof( access_sys_t ) );
118
119     p_sys->i_timeout = var_CreateGetInteger( p_access, "mms-timeout" );
120
121     vlc_mutex_init( &p_sys->lock_netwrite );
122
123     /* *** Parse URL and get server addr/port and path *** */
124     vlc_UrlParse( &p_sys->url, p_access->psz_path, 0 );
125     if( p_sys->url.psz_host == NULL || *p_sys->url.psz_host == '\0' )
126     {
127         msg_Err( p_access, "invalid server name" );
128         vlc_UrlClean( &p_sys->url );
129         vlc_mutex_destroy( &p_sys->lock_netwrite );
130         free( p_sys );
131         return VLC_EGENERIC;
132     }
133     if( p_sys->url.i_port <= 0 )
134     {
135         p_sys->url.i_port = 1755;
136     }
137
138     /* *** connect to this server *** */
139     /* look at  requested protocol (udp/tcp) */
140     i_proto = MMS_PROTO_AUTO;
141     if( *p_access->psz_access )
142     {
143         if( !strncmp( p_access->psz_access, "mmsu", 4 ) )
144         {
145             i_proto = MMS_PROTO_UDP;
146         }
147         else if( !strncmp( p_access->psz_access, "mmst", 4 ) )
148         {
149             i_proto = MMS_PROTO_TCP;
150         }
151     }
152
153     /* connect */
154     if( i_proto == MMS_PROTO_AUTO )
155     {   /* first try with TCP and then UDP*/
156         if( ( i_status = MMSOpen( p_access, &p_sys->url, MMS_PROTO_TCP ) ) )
157         {
158             i_status = MMSOpen( p_access, &p_sys->url, MMS_PROTO_UDP );
159         }
160     }
161     else
162     {
163         i_status = MMSOpen( p_access, &p_sys->url, i_proto );
164     }
165
166     if( i_status )
167     {
168         msg_Err( p_access, "cannot connect to server" );
169         vlc_UrlClean( &p_sys->url );
170         vlc_mutex_destroy( &p_sys->lock_netwrite );
171         free( p_sys );
172         return VLC_EGENERIC;
173     }
174
175     msg_Dbg( p_access, "connected to %s:%d", p_sys->url.psz_host, p_sys->url.i_port );
176     /*
177      * i_flags_broadcast
178      *  yy xx ?? ??
179      *  broadcast    yy=0x02, xx= 0x00
180      *  pre-recorded yy=0x01, xx= 0x80 if video, 0x00 no video
181      */
182     if( p_sys->i_packet_count <= 0 && p_sys->asfh.i_data_packets_count > 0 )
183     {
184         p_sys->i_packet_count = p_sys->asfh.i_data_packets_count;
185     }
186     if( p_sys->i_packet_count <= 0 || ( p_sys->i_flags_broadcast >> 24 ) == 0x02 )
187     {
188         p_sys->b_seekable = false;
189     }
190     else
191     {
192         p_sys->b_seekable = true;
193         p_access->info.i_size =
194             (uint64_t)p_sys->i_header +
195             (uint64_t)p_sys->i_packet_count * (uint64_t)p_sys->i_packet_length;
196     }
197
198     /* *** Start stream *** */
199     if( MMSStart( p_access, 0xffffffff ) < 0 )
200     {
201         msg_Err( p_access, "cannot start stream" );
202         MMSTUClose ( p_access );
203         return VLC_EGENERIC;
204     }
205
206     /* Keep the connection alive when paused */
207     p_sys->p_keepalive = malloc( sizeof( mmstu_keepalive_t ) );
208     p_sys->p_keepalive->p_access = p_access;
209     vlc_mutex_init( &p_sys->p_keepalive->lock );
210     vlc_cond_init( &p_sys->p_keepalive->wait );
211     p_sys->p_keepalive->b_paused = false;
212     if( vlc_clone( &p_sys->p_keepalive->handle, KeepAliveThread,
213                    p_sys->p_keepalive, VLC_THREAD_PRIORITY_LOW ) )
214     {
215         vlc_cond_destroy( &p_sys->p_keepalive->wait );
216         vlc_mutex_destroy( &p_sys->p_keepalive->lock );
217         free( p_sys->p_keepalive );
218         p_sys->p_keepalive = NULL;
219     }
220
221     return VLC_SUCCESS;
222 }
223
224 /*****************************************************************************
225  * Close: free unused data structures
226  *****************************************************************************/
227 void MMSTUClose( access_t *p_access )
228 {
229     access_sys_t *p_sys = p_access->p_sys;
230
231     if( p_sys->p_keepalive )
232     {
233         vlc_cancel( p_sys->p_keepalive->handle );
234         vlc_join( p_sys->p_keepalive->handle, NULL );
235         vlc_cond_destroy( &p_sys->p_keepalive->wait );
236         vlc_mutex_destroy( &p_sys->p_keepalive->lock );
237         free( p_sys->p_keepalive );
238     }
239
240     /* close connection with server */
241     MMSClose( p_access );
242
243     /* free memory */
244     vlc_UrlClean( &p_sys->url );
245     vlc_mutex_destroy( &p_sys->lock_netwrite );
246
247     free( p_sys );
248 }
249
250 /*****************************************************************************
251  * Control:
252  *****************************************************************************/
253 static int Control( access_t *p_access, int i_query, va_list args )
254 {
255     access_sys_t *p_sys = p_access->p_sys;
256     bool   *pb_bool;
257     bool    b_bool;
258     int          *pi_int;
259     int64_t      *pi_64;
260     int           i_int;
261     vlc_value_t  val;
262
263     switch( i_query )
264     {
265         /* */
266         case ACCESS_CAN_SEEK:
267             pb_bool = (bool*)va_arg( args, bool* );
268             *pb_bool = p_sys->b_seekable;
269             break;
270
271         case ACCESS_CAN_FASTSEEK:
272             pb_bool = (bool*)va_arg( args, bool* );
273             *pb_bool = false;
274             break;
275
276         case ACCESS_CAN_PAUSE:
277             pb_bool = (bool*)va_arg( args, bool* );
278             *pb_bool = true;
279             break;
280
281         case ACCESS_CAN_CONTROL_PACE:
282             pb_bool = (bool*)va_arg( args, bool* );
283
284 #if 0       /* Disable for now until we have a clock synchro algo
285              * which works with something else than MPEG over UDP */
286             *pb_bool = false;
287 #endif
288             *pb_bool = true;
289             break;
290
291         /* */
292         case ACCESS_GET_MTU:
293             pi_int = (int*)va_arg( args, int * );
294             *pi_int = 3 * p_sys->i_packet_length;
295             break;
296
297         case ACCESS_GET_PTS_DELAY:
298             pi_64 = (int64_t*)va_arg( args, int64_t * );
299             var_Get( p_access, "mms-caching", &val );
300             *pi_64 = (int64_t)var_GetInteger( p_access, "mms-caching" ) * INT64_C(1000);
301             break;
302
303         case ACCESS_GET_PRIVATE_ID_STATE:
304             i_int = (int)va_arg( args, int );
305             pb_bool = (bool *)va_arg( args, bool * );
306
307             if( i_int < 0 || i_int > 127 )
308                 return VLC_EGENERIC;
309             *pb_bool =  p_sys->asfh.stream[i_int].i_selected ? true : false;
310             break;
311
312         /* */
313         case ACCESS_SET_PAUSE_STATE:
314             b_bool = (bool)va_arg( args, int );
315             if( b_bool )
316                 MMSStop( p_access );
317             else
318                 Seek( p_access, p_access->info.i_pos );
319
320             vlc_mutex_lock( &p_sys->p_keepalive->lock );
321             p_sys->p_keepalive->b_paused = b_bool;
322             if( b_bool )
323                 vlc_cond_signal( &p_sys->p_keepalive->wait );
324             vlc_mutex_unlock( &p_sys->p_keepalive->lock );
325             break;
326
327         case ACCESS_GET_TITLE_INFO:
328         case ACCESS_SET_TITLE:
329         case ACCESS_SET_SEEKPOINT:
330         case ACCESS_SET_PRIVATE_ID_STATE:
331         case ACCESS_GET_CONTENT_TYPE:
332             return VLC_EGENERIC;
333
334
335         default:
336             msg_Warn( p_access, "unimplemented query in control" );
337             return VLC_EGENERIC;
338
339     }
340     return VLC_SUCCESS;
341 }
342
343 /*****************************************************************************
344  * Seek: try to go at the right place
345  *****************************************************************************/
346 static int Seek( access_t * p_access, int64_t i_pos )
347 {
348     access_sys_t *p_sys = p_access->p_sys;
349     uint32_t    i_packet;
350     uint32_t    i_offset;
351     var_buffer_t buffer;
352
353     if( i_pos < 0 )
354         return VLC_EGENERIC;
355
356     if( i_pos < p_sys->i_header)
357     {
358
359         if( p_access->info.i_pos < p_sys->i_header )
360         {
361             /* no need to restart stream, it was already one
362              * or no stream was yet read */
363             p_access->info.i_pos = i_pos;
364             return VLC_SUCCESS;
365         }
366         else
367         {
368             i_packet = 0xffffffff;
369             i_offset = 0;
370         }
371     }
372     else
373     {
374         i_packet = ( i_pos - p_sys->i_header ) / p_sys->i_packet_length;
375         i_offset = ( i_pos - p_sys->i_header ) % p_sys->i_packet_length;
376     }
377     msg_Dbg( p_access, "seeking to %"PRId64 " (packet:%d)", i_pos, i_packet );
378
379     MMSStop( p_access );
380     msg_Dbg( p_access, "stream stopped (seek)" );
381
382     /* *** restart stream *** */
383     var_buffer_initwrite( &buffer, 0 );
384     var_buffer_add64( &buffer, 0 ); /* seek point in second */
385     var_buffer_add32( &buffer, 0xffffffff );
386     var_buffer_add32( &buffer, i_packet ); // begin from start
387     var_buffer_add8( &buffer, 0xff ); // stream time limit
388     var_buffer_add8( &buffer, 0xff ); //  on 3bytes ...
389     var_buffer_add8( &buffer, 0xff ); //
390     var_buffer_add8( &buffer, 0x00 ); // don't use limit
391     var_buffer_add32( &buffer, p_sys->i_media_packet_id_type );
392
393     mms_CommandSend( p_access, 0x07, p_sys->i_command_level, 0x0001ffff,
394                      buffer.p_data, buffer.i_data );
395
396     var_buffer_free( &buffer );
397
398
399     while( vlc_object_alive (p_access) )
400     {
401         if( mms_HeaderMediaRead( p_access, MMS_PACKET_CMD ) < 0 )
402         {
403             p_access->info.b_eof = true;
404             return VLC_EGENERIC;
405         }
406
407         if( p_sys->i_command == 0x1e )
408         {
409             msg_Dbg( p_access, "received 0x1e (seek)" );
410             break;
411         }
412     }
413
414     while( vlc_object_alive (p_access) )
415     {
416         if( mms_HeaderMediaRead( p_access, MMS_PACKET_CMD ) < 0 )
417         {
418             p_access->info.b_eof = true;
419             return VLC_EGENERIC;
420         }
421         if( p_sys->i_command == 0x05 )
422         {
423             msg_Dbg( p_access, "received 0x05 (seek)" );
424             break;
425         }
426     }
427
428     /* get a packet */
429     if( mms_HeaderMediaRead( p_access, MMS_PACKET_MEDIA ) < 0 )
430     {
431         p_access->info.b_eof = true;
432         return VLC_EGENERIC;
433     }
434
435     msg_Dbg( p_access, "Streaming restarted" );
436
437     p_sys->i_media_used += i_offset;
438     p_access->info.i_pos = i_pos;
439     p_access->info.b_eof = false;
440
441     return VLC_SUCCESS;
442 }
443
444 /*****************************************************************************
445  * Read:
446  *****************************************************************************/
447 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
448 {
449     access_sys_t *p_sys = p_access->p_sys;
450     size_t      i_data;
451     size_t      i_copy;
452
453     if( p_access->info.b_eof )
454     {
455         return 0;
456     }
457
458     i_data = 0;
459
460     /* *** now send data if needed *** */
461     while( i_data < i_len )
462     {
463         if( p_access->info.i_pos < p_sys->i_header )
464         {
465             i_copy = __MIN( i_len, p_sys->i_header - p_access->info.i_pos );
466             memcpy( &p_buffer[i_data], &p_sys->p_header[p_access->info.i_pos], i_copy );
467             i_data += i_copy;
468             p_access->info.i_pos += i_copy;
469         }
470         else if( p_sys->i_media_used < p_sys->i_media )
471         {
472             i_copy = __MIN( i_len - i_data ,
473                             p_sys->i_media - p_sys->i_media_used );
474             memcpy( &p_buffer[i_data], &p_sys->p_media[p_sys->i_media_used], i_copy );
475             i_data += i_copy;
476             p_sys->i_media_used += i_copy;
477             p_access->info.i_pos += i_copy;
478         }
479         else if( p_sys->p_media != NULL &&
480                  p_sys->i_media_used < p_sys->i_packet_length )
481         {
482             i_copy = __MIN( i_len - i_data,
483                             p_sys->i_packet_length - p_sys->i_media_used);
484             memset( &p_buffer[i_data], 0, i_copy );
485
486             i_data += i_copy;
487             p_sys->i_media_used += i_copy;
488             p_access->info.i_pos += i_copy;
489         }
490         else if( p_access->info.b_eof ||
491                  mms_HeaderMediaRead( p_access, MMS_PACKET_MEDIA ) < 0 )
492         {
493             break;
494         }
495     }
496
497     return i_data;
498 }
499
500 /****************************************************************************
501  * MMSOpen : Open a connection with the server over mmst or mmsu
502  ****************************************************************************/
503 static int MMSOpen( access_t  *p_access, vlc_url_t *p_url, int  i_proto )
504 {
505     access_sys_t *p_sys = p_access->p_sys;
506     int           b_udp = ( i_proto == MMS_PROTO_UDP ) ? 1 : 0;
507
508     var_buffer_t buffer;
509     char         tmp[4096];
510     uint16_t     *p;
511     int          i_server_version;
512     int          i_tool_version;
513     int          i_update_player_url;
514     int          i_encryption_type;
515     int          i;
516     int          i_streams;
517     int          i_first;
518     char         *mediapath;
519
520
521     /* *** Open a TCP connection with server *** */
522     msg_Dbg( p_access, "waiting for connection..." );
523     p_sys->i_handle_tcp = net_ConnectTCP( p_access, p_url->psz_host, p_url->i_port );
524     if( p_sys->i_handle_tcp < 0 )
525     {
526         msg_Err( p_access, "failed to open a connection (tcp)" );
527         return VLC_EGENERIC;
528     }
529     msg_Dbg( p_access,
530              "connection(tcp) with \"%s:%d\" successful",
531              p_url->psz_host,
532              p_url->i_port );
533
534     /* *** Bind port if UDP protocol is selected *** */
535     if( b_udp )
536     {
537         if( net_GetSockAddress( p_sys->i_handle_tcp, p_sys->sz_bind_addr,
538                                 NULL ) )
539         {
540             net_Close( p_sys->i_handle_tcp );
541             return VLC_EGENERIC;
542         }
543
544         p_sys->i_handle_udp = net_ListenUDP1( (vlc_object_t *)p_access, p_sys->sz_bind_addr,
545                                               7000 );
546         if( p_sys->i_handle_udp < 0 )
547         {
548             msg_Err( p_access, "failed to open a connection (udp)" );
549             net_Close( p_sys->i_handle_tcp );
550             return VLC_EGENERIC;
551         }
552         msg_Dbg( p_access,
553                  "connection(udp) at \"%s:%d\" successful",
554                  p_sys->sz_bind_addr, 7000 );
555     }
556
557     /* *** Init context for mms prototcol *** */
558      GenerateGuid ( &p_sys->guid );    /* used to identify client by server */
559     msg_Dbg( p_access,
560              "generated guid: "GUID_FMT,
561              GUID_PRINT( p_sys->guid ) );
562     p_sys->i_command_level = 1;          /* updated after 0x1A command */
563     p_sys->i_seq_num = 0;
564     p_sys->i_media_packet_id_type  = 0x04;
565     p_sys->i_header_packet_id_type = 0x02;
566     p_sys->i_proto = i_proto;
567     p_sys->i_packet_seq_num = 0;
568     p_sys->p_header = NULL;
569     p_sys->i_header = 0;
570     p_sys->p_media = NULL;
571     p_sys->i_media = 0;
572     p_sys->i_media_used = 0;
573
574     p_access->info.i_pos = 0;
575     p_sys->i_buffer_tcp = 0;
576     p_sys->i_buffer_udp = 0;
577     p_sys->p_cmd = NULL;
578     p_sys->i_cmd = 0;
579     p_access->info.b_eof = false;
580
581     /* *** send command 1 : connection request *** */
582     var_buffer_initwrite( &buffer, 0 );
583     var_buffer_add16( &buffer, 0x001c );
584     var_buffer_add16( &buffer, 0x0003 );
585     sprintf( tmp,
586              "NSPlayer/7.0.0.1956; {"GUID_FMT"}; Host: %s",
587              GUID_PRINT( p_sys->guid ),
588              p_url->psz_host );
589     var_buffer_addUTF16( &buffer, tmp );
590
591     mms_CommandSend( p_access,
592                      0x01,          /* connexion request */
593                      0x00000000,    /* flags, FIXME */
594                      0x0004000b,    /* ???? */
595                      buffer.p_data,
596                      buffer.i_data );
597
598     if( mms_CommandRead( p_access, 0x01, 0 ) < 0 )
599     {
600         var_buffer_free( &buffer );
601         MMSClose( p_access );
602         return VLC_EGENERIC;
603     }
604
605     i_server_version = GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 32 );
606     i_tool_version = GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 36 );
607     i_update_player_url = GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 40 );
608     i_encryption_type = GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 44 );
609     p = (uint16_t*)( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 48 );
610 #define GETUTF16( psz, size ) \
611     { \
612         int i; \
613         psz = malloc( size + 1); \
614         for( i = 0; i < size; i++ ) \
615         { \
616             psz[i] = p[i]; \
617         } \
618         psz[size] = '\0'; \
619         p += ( size ); \
620     }
621     GETUTF16( p_sys->psz_server_version, i_server_version );
622     GETUTF16( p_sys->psz_tool_version, i_tool_version );
623     GETUTF16( p_sys->psz_update_player_url, i_update_player_url );
624     GETUTF16( p_sys->psz_encryption_type, i_encryption_type );
625 #undef GETUTF16
626     msg_Dbg( p_access,
627              "0x01 --> server_version:\"%s\" tool_version:\"%s\" update_player_url:\"%s\" encryption_type:\"%s\"",
628              p_sys->psz_server_version,
629              p_sys->psz_tool_version,
630              p_sys->psz_update_player_url,
631              p_sys->psz_encryption_type );
632
633     /* *** should make an 18 command to make data timing *** */
634
635     /* *** send command 2 : transport protocol selection *** */
636     var_buffer_reinitwrite( &buffer, 0 );
637     var_buffer_add32( &buffer, 0x00000000 );
638     var_buffer_add32( &buffer, 0x000a0000 );
639     var_buffer_add32( &buffer, 0x00000002 );
640     if( b_udp )
641     {
642         sprintf( tmp,
643                  "\\\\%s\\UDP\\%d",
644                  p_sys->sz_bind_addr,
645                  7000 ); // FIXME
646     }
647     else
648     {
649         sprintf( tmp, "\\\\192.168.0.1\\TCP\\1242"  );
650     }
651     var_buffer_addUTF16( &buffer, tmp );
652     var_buffer_add16( &buffer, '0' );
653
654     mms_CommandSend( p_access,
655                      0x02,          /* connexion request */
656                      0x00000000,    /* flags, FIXME */
657                      0xffffffff,    /* ???? */
658                      buffer.p_data,
659                      buffer.i_data );
660
661     /* *** response from server, should be 0x02 or 0x03 *** */
662     mms_CommandRead( p_access, 0x02, 0x03 );
663     if( p_sys->i_command == 0x03 )
664     {
665         msg_Err( p_access,
666                  "%s protocol selection failed", b_udp ? "UDP" : "TCP" );
667         var_buffer_free( &buffer );
668         MMSClose( p_access );
669         return VLC_EGENERIC;
670     }
671     else if( p_sys->i_command != 0x02 )
672     {
673         msg_Warn( p_access, "received command isn't 0x02 in reponse to 0x02" );
674     }
675
676     /* *** send command 5 : media file name/path requested *** */
677     var_buffer_reinitwrite( &buffer, 0 );
678     var_buffer_add64( &buffer, 0 );
679
680     /* media file path shouldn't start with / character */
681     mediapath = p_url->psz_path;
682     if ( *mediapath == '/' )
683     {
684         mediapath++;
685     }
686     var_buffer_addUTF16( &buffer, mediapath );
687
688     mms_CommandSend( p_access,
689                      0x05,
690                      p_sys->i_command_level,
691                      0xffffffff,
692                      buffer.p_data,
693                      buffer.i_data );
694
695     /* *** wait for reponse *** */
696     mms_CommandRead( p_access, 0x1a, 0x06 );
697
698     /* test if server send 0x1A answer */
699     if( p_sys->i_command == 0x1A )
700     {
701         msg_Err( p_access, "id/password requested (not yet supported)" );
702         /*  FIXME */
703         var_buffer_free( &buffer );
704         MMSClose( p_access );
705         return VLC_EGENERIC;
706     }
707     if( p_sys->i_command != 0x06 )
708     {
709         msg_Err( p_access,
710                  "unknown answer (0x%x instead of 0x06)",
711                  p_sys->i_command );
712         var_buffer_free( &buffer );
713         MMSClose( p_access );
714         return( -1 );
715     }
716
717     /*  1 for file ok, 2 for authen ok */
718     switch( GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE ) )
719     {
720         case 0x0001:
721             msg_Dbg( p_access, "media file name/path accepted" );
722             break;
723         case 0x0002:
724             msg_Dbg( p_access, "authentication accepted" );
725             break;
726         case -1:
727         default:
728         msg_Err( p_access, "error while asking for file %d",
729                  GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE ) );
730         var_buffer_free( &buffer );
731         MMSClose( p_access );
732         return VLC_EGENERIC;
733     }
734
735     p_sys->i_flags_broadcast =
736         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 12 );
737     p_sys->i_media_length =
738         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 24 );
739     p_sys->i_packet_length =
740         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 44 );
741     p_sys->i_packet_count =
742         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 48 );
743     p_sys->i_max_bit_rate =
744         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 56 );
745     p_sys->i_header_size =
746         GetDWLE( p_sys->p_cmd + MMS_CMD_HEADERSIZE + 60 );
747
748     msg_Dbg( p_access,
749              "answer 0x06 flags:0x%8.8"PRIx32" media_length:%"PRIu32"s "
750              "packet_length:%zul packet_count:%"PRId32" max_bit_rate:%d "
751              "header_size:%zu",
752              p_sys->i_flags_broadcast,
753              p_sys->i_media_length,
754              (unsigned)p_sys->i_packet_length,
755              p_sys->i_packet_count,
756              p_sys->i_max_bit_rate,
757              p_sys->i_header_size );
758
759     /* *** send command 15 *** */
760
761     var_buffer_reinitwrite( &buffer, 0 );
762     var_buffer_add32( &buffer, 0 );
763     var_buffer_add32( &buffer, 0x8000 );
764     var_buffer_add32( &buffer, 0xffffffff );
765     var_buffer_add32( &buffer, 0x00 );
766     var_buffer_add32( &buffer, 0x00 );
767     var_buffer_add32( &buffer, 0x00 );
768     var_buffer_add64( &buffer, (((uint64_t)0x40ac2000)<<32) );
769     var_buffer_add32( &buffer, p_sys->i_header_packet_id_type );
770     var_buffer_add32( &buffer, 0x00 );
771     mms_CommandSend( p_access, 0x15, p_sys->i_command_level, 0x00,
772                      buffer.p_data, buffer.i_data );
773
774     /* *** wait for reponse *** */
775     /* Commented out because it fails on some stream (no 0x11 answer) */
776 #if 0
777     mms_CommandRead( p_access, 0x11, 0 );
778
779     if( p_sys->i_command != 0x11 )
780     {
781         msg_Err( p_access,
782                  "unknown answer (0x%x instead of 0x11)",
783                  p_sys->i_command );
784         var_buffer_free( &buffer );
785         MMSClose( p_access );
786         return( -1 );
787     }
788 #endif
789
790     /* *** now read header packet *** */
791     /* XXX could be split over multiples packets */
792     msg_Dbg( p_access, "reading header" );
793     for( ;; )
794     {
795         if( mms_HeaderMediaRead( p_access, MMS_PACKET_HEADER ) < 0 )
796         {
797             msg_Err( p_access, "cannot receive header" );
798             var_buffer_free( &buffer );
799             MMSClose( p_access );
800             return VLC_EGENERIC;
801         }
802         if( p_sys->i_header >= p_sys->i_header_size )
803         {
804             msg_Dbg( p_access,
805                      "header complete(%zu)",
806                      p_sys->i_header );
807             break;
808         }
809         msg_Dbg( p_access,
810                  "header incomplete (%zu/%zu), reading more",
811                  p_sys->i_header,
812                  p_sys->i_header_size );
813     }
814
815     /* *** parse header and get stream and their id *** */
816     /* get all streams properties,
817      *
818      * TODO : stream bitrates properties(optional)
819      *        and bitrate mutual exclusion(optional) */
820      asf_HeaderParse ( &p_sys->asfh,
821                            p_sys->p_header, p_sys->i_header );
822      asf_StreamSelect( &p_sys->asfh,
823                            var_CreateGetInteger( p_access, "mms-maxbitrate" ),
824                            var_CreateGetInteger( p_access, "mms-all" ),
825                            var_CreateGetInteger( p_access, "audio" ),
826                            var_CreateGetInteger( p_access, "video" ) );
827
828     /* *** now select stream we want to receive *** */
829     /* TODO take care of stream bitrate TODO */
830     i_streams = 0;
831     i_first = -1;
832     var_buffer_reinitwrite( &buffer, 0 );
833     /* for now, select first audio and video stream */
834     for( i = 1; i < 128; i++ )
835     {
836
837         if( p_sys->asfh.stream[i].i_cat != ASF_STREAM_UNKNOWN )
838         {
839             i_streams++;
840             if( i_first != -1 )
841             {
842                 var_buffer_add16( &buffer, 0xffff );
843                 var_buffer_add16( &buffer, i );
844             }
845             else
846             {
847                 i_first = i;
848             }
849             if( p_sys->asfh.stream[i].i_selected )
850             {
851                 var_buffer_add16( &buffer, 0x0000 );
852                 msg_Info( p_access,
853                           "selecting stream[0x%x] %s (%d kb/s)",
854                           i,
855                           ( p_sys->asfh.stream[i].i_cat == ASF_STREAM_AUDIO  ) ?
856                                                   "audio" : "video" ,
857                           p_sys->asfh.stream[i].i_bitrate / 1024);
858             }
859             else
860             {
861                 var_buffer_add16( &buffer, 0x0002 );
862                 msg_Info( p_access,
863                           "ignoring stream[0x%x] %s (%d kb/s)",
864                           i,
865                           ( p_sys->asfh.stream[i].i_cat == ASF_STREAM_AUDIO  ) ?
866                                     "audio" : "video" ,
867                           p_sys->asfh.stream[i].i_bitrate / 1024);
868
869             }
870         }
871     }
872
873     if( i_streams == 0 )
874     {
875         msg_Err( p_access, "cannot find any stream" );
876         var_buffer_free( &buffer );
877         MMSClose( p_access );
878         return VLC_EGENERIC;
879     }
880     mms_CommandSend( p_access, 0x33,
881                      i_streams,
882                      0xffff | ( i_first << 16 ),
883                      buffer.p_data, buffer.i_data );
884
885     mms_CommandRead( p_access, 0x21, 0 );
886     if( p_sys->i_command != 0x21 )
887     {
888         msg_Err( p_access,
889                  "unknown answer (0x%x instead of 0x21)",
890                  p_sys->i_command );
891         var_buffer_free( &buffer );
892         MMSClose( p_access );
893         return VLC_EGENERIC;
894     }
895
896
897     var_buffer_free( &buffer );
898
899     msg_Info( p_access, "connection successful" );
900
901     return VLC_SUCCESS;
902 }
903
904 /****************************************************************************
905  * MMSStart : Start streaming
906  ****************************************************************************/
907 static int MMSStart( access_t  *p_access, uint32_t i_packet )
908 {
909     access_sys_t        *p_sys = p_access->p_sys;
910     var_buffer_t    buffer;
911
912     /* *** start stream from packet 0 *** */
913     var_buffer_initwrite( &buffer, 0 );
914     var_buffer_add64( &buffer, 0 ); /* seek point in second */
915     var_buffer_add32( &buffer, 0xffffffff );
916     var_buffer_add32( &buffer, i_packet ); // begin from start
917     var_buffer_add8( &buffer, 0xff ); // stream time limit
918     var_buffer_add8( &buffer, 0xff ); //  on 3bytes ...
919     var_buffer_add8( &buffer, 0xff ); //
920     var_buffer_add8( &buffer, 0x00 ); // don't use limit
921     var_buffer_add32( &buffer, p_sys->i_media_packet_id_type );
922
923     mms_CommandSend( p_access, 0x07, p_sys->i_command_level, 0x0001ffff,
924                      buffer.p_data, buffer.i_data );
925
926     var_buffer_free( &buffer );
927
928     mms_CommandRead( p_access, 0x05, 0 );
929
930     if( p_sys->i_command != 0x05 )
931     {
932         msg_Err( p_access,
933                  "unknown answer (0x%x instead of 0x05)",
934                  p_sys->i_command );
935         return -1;
936     }
937     else
938     {
939         /* get a packet */
940         if( mms_HeaderMediaRead( p_access, MMS_PACKET_MEDIA ) < 0 )
941             return -1;
942         msg_Dbg( p_access, "streaming started" );
943         return 0;
944     }
945 }
946
947 /****************************************************************************
948  * MMSStop : Stop streaming
949  ****************************************************************************/
950 static int MMSStop( access_t  *p_access )
951 {
952     access_sys_t *p_sys = p_access->p_sys;
953
954     /* *** stop stream but keep connection alive *** */
955     mms_CommandSend( p_access,
956                      0x09,
957                      p_sys->i_command_level,
958                      0x001fffff,
959                      NULL, 0 );
960     return( 0 );
961 }
962
963 /****************************************************************************
964  * MMSClose : Close streaming and connection
965  ****************************************************************************/
966 static void MMSClose( access_t  *p_access )
967 {
968     access_sys_t        *p_sys = p_access->p_sys;
969
970     msg_Dbg( p_access, "Connection closed" );
971
972     /* *** tell server that we will disconnect *** */
973     mms_CommandSend( p_access,
974                      0x0d,
975                      p_sys->i_command_level,
976                      0x00000001,
977                      NULL, 0 );
978
979     /* *** close sockets *** */
980     net_Close( p_sys->i_handle_tcp );
981     if( p_sys->i_proto == MMS_PROTO_UDP )
982     {
983         net_Close( p_sys->i_handle_udp );
984     }
985
986     FREENULL( p_sys->p_cmd );
987     FREENULL( p_sys->p_media );
988     FREENULL( p_sys->p_header );
989
990     FREENULL( p_sys->psz_server_version );
991     FREENULL( p_sys->psz_tool_version );
992     FREENULL( p_sys->psz_update_player_url );
993     FREENULL( p_sys->psz_encryption_type );
994 }
995
996 /****************************************************************************
997  *
998  * MMS specific functions
999  *
1000  ****************************************************************************/
1001 static int mms_CommandSend( access_t *p_access, int i_command,
1002                             uint32_t i_prefix1, uint32_t i_prefix2,
1003                             uint8_t *p_data, int i_data_old )
1004 {
1005     var_buffer_t buffer;
1006     access_sys_t *p_sys = p_access->p_sys;
1007     int i_data_by8, i_ret;
1008     int i_data = i_data_old;
1009
1010     while( i_data & 0x7 ) i_data++;
1011     i_data_by8 = i_data >> 3;
1012
1013     /* first init buffer */
1014     var_buffer_initwrite( &buffer, 0 );
1015
1016     var_buffer_add32( &buffer, 0x00000001 );    /* start sequence */
1017     var_buffer_add32( &buffer, 0xB00BFACE );
1018     /* size after protocol type */
1019     var_buffer_add32( &buffer, i_data + MMS_CMD_HEADERSIZE - 16 );
1020     var_buffer_add32( &buffer, 0x20534d4d );    /* protocol "MMS " */
1021     var_buffer_add32( &buffer, i_data_by8 + 4 );
1022     var_buffer_add32( &buffer, p_sys->i_seq_num ); p_sys->i_seq_num++;
1023     var_buffer_add64( &buffer, 0 );
1024     var_buffer_add32( &buffer, i_data_by8 + 2 );
1025     var_buffer_add32( &buffer, 0x00030000 | i_command ); /* dir | command */
1026     var_buffer_add32( &buffer, i_prefix1 );    /* command specific */
1027     var_buffer_add32( &buffer, i_prefix2 );    /* command specific */
1028
1029     /* specific command data */
1030     if( p_data && i_data > 0 )
1031     {
1032         var_buffer_addmemory( &buffer, p_data, i_data_old );
1033     }
1034
1035     /* Append padding to the command data */
1036     var_buffer_add64( &buffer, 0 );
1037
1038     /* send it */
1039     vlc_mutex_lock( &p_sys->lock_netwrite );
1040     i_ret = net_Write( p_access, p_sys->i_handle_tcp, NULL, buffer.p_data,
1041                        buffer.i_data - ( 8 - ( i_data - i_data_old ) ) );
1042     vlc_mutex_unlock( &p_sys->lock_netwrite );
1043     if( i_ret != buffer.i_data - ( 8 - ( i_data - i_data_old ) ) )
1044     {
1045         msg_Err( p_access, "failed to send command" );
1046         return VLC_EGENERIC;
1047     }
1048
1049     var_buffer_free( &buffer );
1050     return VLC_SUCCESS;
1051 }
1052
1053 static int NetFillBuffer( access_t *p_access )
1054 {
1055 #ifdef UNDER_CE
1056     return -1;
1057
1058 #else
1059     access_sys_t    *p_sys = p_access->p_sys;
1060     int             i_ret;
1061     struct pollfd   ufd[2];
1062     unsigned        timeout, nfd;
1063
1064     /* FIXME when using udp */
1065     ssize_t i_tcp, i_udp;
1066     ssize_t i_tcp_read, i_udp_read;
1067     int i_try = 0;
1068
1069     i_tcp = MMS_BUFFER_SIZE/2 - p_sys->i_buffer_tcp;
1070
1071     if( p_sys->i_proto == MMS_PROTO_UDP )
1072     {
1073         i_udp = MMS_BUFFER_SIZE/2 - p_sys->i_buffer_udp;
1074     }
1075     else
1076     {
1077         i_udp = 0;  /* there isn't udp socket */
1078     }
1079
1080     if( ( i_udp <= 0 ) && ( i_tcp <= 0 ) )
1081     {
1082         msg_Warn( p_access, "nothing to read %d:%d", (int)i_tcp, (int)i_udp );
1083         return 0;
1084     }
1085     else
1086     {
1087         /* msg_Warn( p_access, "ask for tcp:%d udp:%d", i_tcp, i_udp ); */
1088     }
1089
1090     /* Find if some data is available */
1091     do
1092     {
1093         i_try++;
1094
1095         /* Initialize file descriptor set */
1096         memset (ufd, 0, sizeof (ufd));
1097         nfd = 0;
1098
1099         if( i_tcp > 0 )
1100         {
1101             ufd[nfd].fd = p_sys->i_handle_tcp;
1102             ufd[nfd].events = POLLIN;
1103             nfd++;
1104         }
1105         if( i_udp > 0 )
1106         {
1107             ufd[nfd].fd = p_sys->i_handle_tcp;
1108             ufd[nfd].events = POLLIN;
1109             nfd++;
1110         }
1111
1112         /* We'll wait 0.5 second if nothing happens */
1113         timeout = 500;
1114
1115         if( i_try * timeout > p_sys->i_timeout )
1116         {
1117             msg_Err(p_access, "no data received");
1118             return -1;
1119         }
1120
1121         if( i_try > 3 && (p_sys->i_buffer_tcp > 0 || p_sys->i_buffer_udp > 0) )
1122         {
1123             return -1;
1124         }
1125
1126         if( !vlc_object_alive (p_access) || p_access->b_error ) return -1;
1127
1128         //msg_Dbg( p_access, "NetFillBuffer: trying again (select)" );
1129
1130     } while( !(i_ret = poll( ufd, nfd, timeout)) ||
1131              (i_ret < 0 && errno == EINTR) );
1132
1133     if( i_ret < 0 )
1134     {
1135         msg_Err( p_access, "network poll error (%m)" );
1136         return -1;
1137     }
1138
1139     i_tcp_read = i_udp_read = 0;
1140
1141     if( ( i_tcp > 0 ) && ufd[0].revents )
1142     {
1143         i_tcp_read =
1144             recv( p_sys->i_handle_tcp,
1145                   p_sys->buffer_tcp + p_sys->i_buffer_tcp,
1146                   i_tcp + MMS_BUFFER_SIZE/2, 0 );
1147     }
1148
1149     if( i_udp > 0 && ufd[i_tcp > 0].revents )
1150     {
1151         i_udp_read = recv( p_sys->i_handle_udp,
1152                            p_sys->buffer_udp + p_sys->i_buffer_udp,
1153                            i_udp + MMS_BUFFER_SIZE/2, 0 );
1154     }
1155
1156 #ifdef MMS_DEBUG
1157     if( p_sys->i_proto == MMS_PROTO_UDP )
1158     {
1159         msg_Dbg( p_access, "filling buffer TCP:%d+%d UDP:%d+%d",
1160                  p_sys->i_buffer_tcp, i_tcp_read,
1161                  p_sys->i_buffer_udp, i_udp_read );
1162     }
1163     else
1164     {
1165         msg_Dbg( p_access, "filling buffer TCP:%d+%d",
1166                  p_sys->i_buffer_tcp, i_tcp_read );
1167     }
1168 #endif
1169
1170     if( i_tcp_read > 0 ) p_sys->i_buffer_tcp += i_tcp_read;
1171     if( i_udp_read > 0 ) p_sys->i_buffer_udp += i_udp_read;
1172
1173     return i_tcp_read + i_udp_read;
1174 #endif
1175 }
1176
1177 static int  mms_ParseCommand( access_t *p_access,
1178                               uint8_t *p_data,
1179                               size_t i_data,
1180                               int *pi_used )
1181 {
1182  #define GET32( i_pos ) \
1183     ( p_sys->p_cmd[i_pos] + ( p_sys->p_cmd[i_pos +1] << 8 ) + \
1184       ( p_sys->p_cmd[i_pos + 2] << 16 ) + \
1185       ( p_sys->p_cmd[i_pos + 3] << 24 ) )
1186
1187     access_sys_t        *p_sys = p_access->p_sys;
1188     uint32_t    i_length;
1189     uint32_t    i_id;
1190
1191     free( p_sys->p_cmd );
1192     p_sys->i_cmd = i_data;
1193     p_sys->p_cmd = malloc( i_data );
1194     memcpy( p_sys->p_cmd, p_data, i_data );
1195
1196     *pi_used = i_data; /* by default */
1197
1198     if( i_data < MMS_CMD_HEADERSIZE )
1199     {
1200         msg_Warn( p_access, "truncated command (header incomplete)" );
1201         p_sys->i_command = 0;
1202         return -1;
1203     }
1204     i_id =  GetDWLE( p_data + 4 );
1205     i_length = GetDWLE( p_data + 8 ) + 16;
1206
1207     if( i_id != 0xb00bface || i_length < 16 )
1208     {
1209         msg_Err( p_access,
1210                  "incorrect command header (0x%"PRIx32")", i_id );
1211         p_sys->i_command = 0;
1212         return -1;
1213     }
1214
1215     if( i_length > p_sys->i_cmd )
1216     {
1217         msg_Warn( p_access,
1218                   "truncated command (missing %zu bytes)",
1219                    (size_t)i_length - i_data  );
1220         p_sys->i_command = 0;
1221         return -1;
1222     }
1223     else if( i_length < p_sys->i_cmd )
1224     {
1225         p_sys->i_cmd = i_length;
1226         *pi_used = i_length;
1227     }
1228
1229     msg_Dbg( p_access,
1230              "recv command start_sequence:0x%8.8x command_id:0x%8.8x length:%d len8:%d sequence 0x%8.8x len8_II:%d dir_comm:0x%8.8x",
1231              GET32( 0 ),
1232              GET32( 4 ),
1233              GET32( 8 ),
1234              /* 12: protocol type "MMS " */
1235              GET32( 16 ),
1236              GET32( 20 ),
1237              /* 24: unknown (0) */
1238              /* 28: unknown (0) */
1239              GET32( 32 ),
1240              GET32( 36 )
1241              /* 40: switches */
1242              /* 44: extra */ );
1243
1244     p_sys->i_command = GET32( 36 ) & 0xffff;
1245 #undef GET32
1246
1247     return MMS_PACKET_CMD;
1248 }
1249
1250 static int  mms_ParsePacket( access_t *p_access,
1251                              uint8_t *p_data, size_t i_data,
1252                              int *pi_used )
1253 {
1254     access_sys_t        *p_sys = p_access->p_sys;
1255     int i_packet_seq_num;
1256     size_t i_packet_length;
1257     uint32_t i_packet_id;
1258
1259     uint8_t  *p_packet;
1260
1261
1262     *pi_used = i_data; /* default */
1263     if( i_data <= 8 )
1264     {
1265         msg_Warn( p_access, "truncated packet (header incomplete)" );
1266         return -1;
1267     }
1268
1269     i_packet_id = p_data[4];
1270     i_packet_seq_num = GetDWLE( p_data );
1271     i_packet_length = GetWLE( p_data + 6 );
1272
1273     //msg_Warn( p_access, "------->i_packet_length=%d, i_data=%d", i_packet_length, i_data );
1274
1275     if( i_packet_length > i_data || i_packet_length <= 8)
1276     {
1277      /*   msg_Dbg( p_access,
1278                  "truncated packet (Declared %d bytes, Actual %d bytes)",
1279                  i_packet_length, i_data  ); */
1280         *pi_used = 0;
1281         return -1;
1282     }
1283     else if( i_packet_length < i_data )
1284     {
1285         *pi_used = i_packet_length;
1286     }
1287
1288     if( i_packet_id == 0xff )
1289     {
1290         msg_Warn( p_access,
1291                   "receive MMS UDP pair timing" );
1292         return( MMS_PACKET_UDP_TIMING );
1293     }
1294
1295     if( i_packet_id != p_sys->i_header_packet_id_type &&
1296         i_packet_id != p_sys->i_media_packet_id_type )
1297     {
1298         msg_Warn( p_access, "incorrect Packet Id Type (0x%x)", i_packet_id );
1299         return -1;
1300     }
1301
1302     /* we now have a media or a header packet */
1303     p_packet = malloc( i_packet_length - 8 ); // don't bother with preheader
1304     memcpy( p_packet, p_data + 8, i_packet_length - 8 );
1305
1306     if( i_packet_seq_num != p_sys->i_packet_seq_num )
1307     {
1308 #if 0
1309         /* FIXME for udp could be just wrong order ? */
1310         msg_Warn( p_access,
1311                   "detected packet lost (%d != %d)",
1312                   i_packet_seq_num,
1313                   p_sys->i_packet_seq_num );
1314 #endif
1315     }
1316     p_sys->i_packet_seq_num = i_packet_seq_num + 1;
1317
1318     if( i_packet_id == p_sys->i_header_packet_id_type )
1319     {
1320         if( p_sys->p_header )
1321         {
1322             p_sys->p_header = realloc( p_sys->p_header,
1323                                           p_sys->i_header + i_packet_length - 8 );
1324             memcpy( &p_sys->p_header[p_sys->i_header],
1325                     p_packet,
1326                     i_packet_length - 8 );
1327             p_sys->i_header += i_packet_length - 8;
1328
1329             free( p_packet );
1330         }
1331         else
1332         {
1333             p_sys->p_header = p_packet;
1334             p_sys->i_header = i_packet_length - 8;
1335         }
1336 /*        msg_Dbg( p_access,
1337                  "receive header packet (%d bytes)",
1338                  i_packet_length - 8 ); */
1339
1340         return MMS_PACKET_HEADER;
1341     }
1342     else
1343     {
1344         FREENULL( p_sys->p_media );
1345         p_sys->p_media = p_packet;
1346         p_sys->i_media = i_packet_length - 8;
1347         p_sys->i_media_used = 0;
1348 /*        msg_Dbg( p_access,
1349                  "receive media packet (%d bytes)",
1350                  i_packet_length - 8 ); */
1351
1352         return MMS_PACKET_MEDIA;
1353     }
1354 }
1355
1356 static int mms_ReceivePacket( access_t *p_access )
1357 {
1358     access_sys_t *p_sys = p_access->p_sys;
1359     int i_packet_tcp_type;
1360     int i_packet_udp_type;
1361
1362     for( ;; )
1363     {
1364         bool b_refill = true;
1365
1366         /* first if we need to refill buffer */
1367         if( p_sys->i_buffer_tcp >= MMS_CMD_HEADERSIZE )
1368         {
1369             if( GetDWLE( p_sys->buffer_tcp + 4 ) == 0xb00bface  )
1370             {
1371                 if( GetDWLE( p_sys->buffer_tcp + 8 ) + 16 <=
1372                     (uint32_t)p_sys->i_buffer_tcp )
1373                 {
1374                     b_refill = false;
1375                 }
1376             }
1377             else if( GetWLE( p_sys->buffer_tcp + 6 ) <= p_sys->i_buffer_tcp )
1378             {
1379                 b_refill = false;
1380             }
1381         }
1382         if( p_sys->i_proto == MMS_PROTO_UDP && p_sys->i_buffer_udp >= 8 &&
1383             GetWLE( p_sys->buffer_udp + 6 ) <= p_sys->i_buffer_udp )
1384         {
1385             b_refill = false;
1386         }
1387
1388         if( b_refill && NetFillBuffer( p_access ) < 0 )
1389         {
1390             msg_Warn( p_access, "cannot fill buffer" );
1391             return -1;
1392         }
1393
1394         i_packet_tcp_type = -1;
1395         i_packet_udp_type = -1;
1396
1397         if( p_sys->i_buffer_tcp > 0 )
1398         {
1399             int i_used;
1400
1401             if( GetDWLE( p_sys->buffer_tcp + 4 ) == 0xb00bface )
1402             {
1403                 i_packet_tcp_type =
1404                     mms_ParseCommand( p_access, p_sys->buffer_tcp,
1405                                       p_sys->i_buffer_tcp, &i_used );
1406
1407             }
1408             else
1409             {
1410                 i_packet_tcp_type =
1411                     mms_ParsePacket( p_access, p_sys->buffer_tcp,
1412                                      p_sys->i_buffer_tcp, &i_used );
1413             }
1414             if( i_used > 0 && i_used < MMS_BUFFER_SIZE )
1415             {
1416                 memmove( p_sys->buffer_tcp, p_sys->buffer_tcp + i_used,
1417                          MMS_BUFFER_SIZE - i_used );
1418             }
1419             p_sys->i_buffer_tcp -= i_used;
1420         }
1421         else if( p_sys->i_buffer_udp > 0 )
1422         {
1423             int i_used;
1424
1425             i_packet_udp_type =
1426                 mms_ParsePacket( p_access, p_sys->buffer_udp,
1427                                  p_sys->i_buffer_udp, &i_used );
1428
1429             if( i_used > 0 && i_used < MMS_BUFFER_SIZE )
1430             {
1431                 memmove( p_sys->buffer_udp, p_sys->buffer_udp + i_used,
1432                          MMS_BUFFER_SIZE - i_used );
1433             }
1434             p_sys->i_buffer_udp -= i_used;
1435         }
1436
1437         if( i_packet_tcp_type == MMS_PACKET_CMD && p_sys->i_command == 0x1b )
1438         {
1439             mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1440             i_packet_tcp_type = -1;
1441         }
1442
1443         if( i_packet_tcp_type != -1 )
1444         {
1445             return i_packet_tcp_type;
1446         }
1447         else if( i_packet_udp_type != -1 )
1448         {
1449             return i_packet_udp_type;
1450         }
1451     }
1452 }
1453
1454 static int mms_ReceiveCommand( access_t *p_access )
1455 {
1456     access_sys_t *p_sys = p_access->p_sys;
1457
1458     for( ;; )
1459     {
1460         int i_used;
1461         int i_status;
1462
1463         if( NetFillBuffer( p_access ) < 0 )
1464         {
1465             msg_Warn( p_access, "cannot fill buffer" );
1466             return VLC_EGENERIC;
1467         }
1468         if( p_sys->i_buffer_tcp > 0 )
1469         {
1470             i_status = mms_ParseCommand( p_access, p_sys->buffer_tcp,
1471                                          p_sys->i_buffer_tcp, &i_used );
1472             if( i_used < MMS_BUFFER_SIZE )
1473             {
1474                 memmove( p_sys->buffer_tcp, p_sys->buffer_tcp + i_used,
1475                          MMS_BUFFER_SIZE - i_used );
1476             }
1477             p_sys->i_buffer_tcp -= i_used;
1478
1479             if( i_status < 0 )
1480             {
1481                 return VLC_EGENERIC;
1482             }
1483
1484             if( p_sys->i_command == 0x1b )
1485             {
1486                 mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1487             }
1488             else
1489             {
1490                 break;
1491             }
1492         }
1493         else
1494         {
1495             return VLC_EGENERIC;
1496         }
1497     }
1498
1499     return VLC_SUCCESS;
1500 }
1501
1502 #define MMS_RETRY_MAX       10
1503 #define MMS_RETRY_SLEEP     50000
1504
1505 static int mms_CommandRead( access_t *p_access, int i_command1,
1506                             int i_command2 )
1507 {
1508     access_sys_t *p_sys = p_access->p_sys;
1509     int i_count;
1510     int i_status;
1511
1512     for( i_count = 0; i_count < MMS_RETRY_MAX; )
1513     {
1514         i_status = mms_ReceiveCommand( p_access );
1515         if( i_status < 0 || p_sys->i_command == 0 )
1516         {
1517             i_count++;
1518             msleep( MMS_RETRY_SLEEP );
1519         }
1520         else if( i_command1 == 0 && i_command2 == 0)
1521         {
1522             return VLC_SUCCESS;
1523         }
1524         else if( p_sys->i_command == i_command1 ||
1525                  p_sys->i_command == i_command2 )
1526         {
1527             return VLC_SUCCESS;
1528         }
1529         else
1530         {
1531             switch( p_sys->i_command )
1532             {
1533                 case 0x03:
1534                     msg_Warn( p_access, "socket closed by server" );
1535                     p_access->info.b_eof = true;
1536                     return VLC_EGENERIC;
1537                 case 0x1e:
1538                     msg_Warn( p_access, "end of media stream" );
1539                     p_access->info.b_eof = true;
1540                     return VLC_EGENERIC;
1541                 default:
1542                     break;
1543             }
1544         }
1545     }
1546     p_access->info.b_eof = true;
1547     msg_Warn( p_access, "failed to receive command (aborting)" );
1548
1549     return VLC_EGENERIC;
1550 }
1551
1552
1553 static int mms_HeaderMediaRead( access_t *p_access, int i_type )
1554 {
1555     access_sys_t *p_sys = p_access->p_sys;
1556     int          i_count;
1557
1558     for( i_count = 0; i_count < MMS_RETRY_MAX; )
1559     {
1560         int i_status;
1561
1562         if( !vlc_object_alive (p_access) )
1563             return -1;
1564
1565         i_status = mms_ReceivePacket( p_access );
1566         if( i_status < 0 )
1567         {
1568             i_count++;
1569             msg_Warn( p_access, "cannot receive header (%d/%d)",
1570                       i_count, MMS_RETRY_MAX );
1571             msleep( MMS_RETRY_SLEEP );
1572         }
1573         else if( i_status == i_type || i_type == MMS_PACKET_ANY )
1574         {
1575             return i_type;
1576         }
1577         else if( i_status == MMS_PACKET_CMD )
1578         {
1579             switch( p_sys->i_command )
1580             {
1581                 case 0x03:
1582                     msg_Warn( p_access, "socket closed by server" );
1583                     p_access->info.b_eof = true;
1584                     return -1;
1585                 case 0x1e:
1586                     msg_Warn( p_access, "end of media stream" );
1587                     p_access->info.b_eof = true;
1588                     return -1;
1589                 case 0x20:
1590                     /* XXX not too dificult to be done EXCEPT that we
1591                      * need to restart demuxer... and I don't see how we
1592                      * could do that :p */
1593                     msg_Err( p_access,
1594                              "reinitialization needed --> unsupported" );
1595                     p_access->info.b_eof = true;
1596                     return -1;
1597                 default:
1598                     break;
1599             }
1600         }
1601     }
1602
1603     msg_Err( p_access, "cannot receive %s (aborting)",
1604              ( i_type == MMS_PACKET_HEADER ) ? "header" : "media data" );
1605     p_access->info.b_eof = true;
1606     return -1;
1607 }
1608
1609 static void* KeepAliveThread( void *p_data )
1610 {
1611     mmstu_keepalive_t *p_thread = (mmstu_keepalive_t *) p_data;
1612     access_t *p_access = p_thread->p_access;
1613
1614     vlc_mutex_lock( &p_thread->lock );
1615     mutex_cleanup_push( &p_thread->lock );
1616
1617     for( ;; )
1618     {
1619         /* Do nothing until paused (if ever) */
1620         while( !p_thread->b_paused )
1621             vlc_cond_wait( &p_thread->wait, &p_thread->lock );
1622
1623         do
1624         {
1625             int canc;
1626
1627             /* Send keep-alive every ten seconds */
1628             vlc_mutex_unlock( &p_thread->lock );
1629             canc = vlc_savecancel();
1630
1631             mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1632
1633             vlc_restorecancel( canc );
1634             vlc_mutex_lock( &p_thread->lock );
1635
1636             msleep( 10 * CLOCK_FREQ );
1637         }
1638         while( p_thread->b_paused );
1639     }
1640
1641     vlc_cleanup_pop();
1642     assert(0);
1643 }