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