]> git.sesse.net Git - vlc/blob - modules/access/mms/mmstu.c
mmstu: fix memleak
[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 block_t *Block( access_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     access_InitFields( p_access );
106     p_access->pf_read = NULL;
107     p_access->pf_block = Block;
108     p_access->pf_control = Control;
109     p_access->pf_seek = Seek;
110
111     p_access->p_sys = p_sys = calloc( 1, sizeof( access_sys_t ) );
112     if( !p_sys ) return VLC_ENOMEM;
113
114     p_sys->i_timeout = var_CreateGetInteger( p_access, "mms-timeout" );
115
116     vlc_mutex_init( &p_sys->lock_netwrite );
117
118     /* *** Parse URL and get server addr/port and path *** */
119     vlc_UrlParse( &p_sys->url, p_access->psz_path, 0 );
120     if( p_sys->url.psz_host == NULL || *p_sys->url.psz_host == '\0' )
121     {
122         msg_Err( p_access, "invalid server name" );
123         vlc_UrlClean( &p_sys->url );
124         vlc_mutex_destroy( &p_sys->lock_netwrite );
125         free( p_sys );
126         return VLC_EGENERIC;
127     }
128     if( p_sys->url.i_port <= 0 )
129     {
130         p_sys->url.i_port = 1755;
131     }
132
133     /* *** connect to this server *** */
134     /* look at  requested protocol (udp/tcp) */
135     i_proto = MMS_PROTO_AUTO;
136     if( *p_access->psz_access )
137     {
138         if( !strncmp( p_access->psz_access, "mmsu", 4 ) )
139         {
140             i_proto = MMS_PROTO_UDP;
141         }
142         else if( !strncmp( p_access->psz_access, "mmst", 4 ) )
143         {
144             i_proto = MMS_PROTO_TCP;
145         }
146     }
147
148     /* connect */
149     if( i_proto == MMS_PROTO_AUTO )
150     {   /* first try with TCP and then UDP*/
151         if( ( i_status = MMSOpen( p_access, &p_sys->url, MMS_PROTO_TCP ) ) )
152         {
153             if( !p_access->b_die )
154                 i_status = MMSOpen( p_access, &p_sys->url, MMS_PROTO_UDP );
155         }
156     }
157     else
158     {
159         i_status = MMSOpen( p_access, &p_sys->url, i_proto );
160     }
161
162     if( i_status )
163     {
164         msg_Err( p_access, "cannot connect to server" );
165         vlc_UrlClean( &p_sys->url );
166         vlc_mutex_destroy( &p_sys->lock_netwrite );
167         free( p_sys );
168         return VLC_EGENERIC;
169     }
170
171     msg_Dbg( p_access, "connected to %s:%d", p_sys->url.psz_host, p_sys->url.i_port );
172     /*
173      * i_flags_broadcast
174      *  yy xx ?? ??
175      *  broadcast    yy=0x02, xx= 0x00
176      *  pre-recorded yy=0x01, xx= 0x80 if video, 0x00 no video
177      */
178     if( p_sys->i_packet_count <= 0 && p_sys->asfh.i_data_packets_count > 0 )
179     {
180         p_sys->i_packet_count = p_sys->asfh.i_data_packets_count;
181     }
182     if( p_sys->i_packet_count <= 0 || ( p_sys->i_flags_broadcast >> 24 ) == 0x02 )
183     {
184         p_sys->b_seekable = false;
185     }
186     else
187     {
188         p_sys->b_seekable = true;
189         p_access->info.i_size =
190             (uint64_t)p_sys->i_header +
191             (uint64_t)p_sys->i_packet_count * (uint64_t)p_sys->i_packet_length;
192     }
193
194     /* *** Start stream *** */
195     if( MMSStart( p_access, 0xffffffff ) < 0 )
196     {
197         msg_Err( p_access, "cannot start stream" );
198         MMSTUClose ( p_access );
199         return VLC_EGENERIC;
200     }
201
202     /* Keep the connection alive when paused */
203     p_sys->p_keepalive = malloc( sizeof( mmstu_keepalive_t ) );
204     if( !p_sys->p_keepalive )
205     {
206         MMSTUClose ( p_access );
207         return VLC_ENOMEM;
208     }
209     p_sys->p_keepalive->p_access = p_access;
210     vlc_mutex_init( &p_sys->p_keepalive->lock );
211     vlc_cond_init( &p_sys->p_keepalive->wait );
212     p_sys->p_keepalive->b_paused = false;
213     if( vlc_clone( &p_sys->p_keepalive->handle, KeepAliveThread,
214                    p_sys->p_keepalive, VLC_THREAD_PRIORITY_LOW ) )
215     {
216         vlc_cond_destroy( &p_sys->p_keepalive->wait );
217         vlc_mutex_destroy( &p_sys->p_keepalive->lock );
218         free( p_sys->p_keepalive );
219         p_sys->p_keepalive = NULL;
220     }
221
222     return VLC_SUCCESS;
223 }
224
225 /*****************************************************************************
226  * Close: free unused data structures
227  *****************************************************************************/
228 void MMSTUClose( access_t *p_access )
229 {
230     access_sys_t *p_sys = p_access->p_sys;
231
232     if( p_sys->p_keepalive )
233     {
234         vlc_cancel( p_sys->p_keepalive->handle );
235         vlc_join( p_sys->p_keepalive->handle, NULL );
236         vlc_cond_destroy( &p_sys->p_keepalive->wait );
237         vlc_mutex_destroy( &p_sys->p_keepalive->lock );
238         free( p_sys->p_keepalive );
239     }
240
241     /* close connection with server */
242     MMSClose( p_access );
243
244     /* free memory */
245     vlc_UrlClean( &p_sys->url );
246     vlc_mutex_destroy( &p_sys->lock_netwrite );
247
248     free( p_sys );
249 }
250
251 /*****************************************************************************
252  * Control:
253  *****************************************************************************/
254 static int Control( access_t *p_access, int i_query, va_list args )
255 {
256     access_sys_t *p_sys = p_access->p_sys;
257     bool   *pb_bool;
258     bool    b_bool;
259     int64_t      *pi_64;
260     int           i_int;
261
262     switch( i_query )
263     {
264         /* */
265         case ACCESS_CAN_SEEK:
266             pb_bool = (bool*)va_arg( args, bool* );
267             *pb_bool = p_sys->b_seekable;
268             break;
269
270         case ACCESS_CAN_FASTSEEK:
271             pb_bool = (bool*)va_arg( args, bool* );
272             *pb_bool = false;
273             break;
274
275         case ACCESS_CAN_PAUSE:
276             pb_bool = (bool*)va_arg( args, bool* );
277             *pb_bool = true;
278             break;
279
280         case ACCESS_CAN_CONTROL_PACE:
281             pb_bool = (bool*)va_arg( args, bool* );
282
283 #if 0       /* Disable for now until we have a clock synchro algo
284              * which works with something else than MPEG over UDP */
285             *pb_bool = false;
286 #endif
287             *pb_bool = true;
288             break;
289
290         /* */
291         case ACCESS_GET_PTS_DELAY:
292             pi_64 = (int64_t*)va_arg( args, int64_t * );
293             *pi_64 = (int64_t)var_GetInteger( p_access, "mms-caching" ) * INT64_C(1000);
294             break;
295
296         case ACCESS_GET_PRIVATE_ID_STATE:
297             i_int = (int)va_arg( args, int );
298             pb_bool = (bool *)va_arg( args, bool * );
299
300             if( i_int < 0 || i_int > 127 )
301                 return VLC_EGENERIC;
302             *pb_bool =  p_sys->asfh.stream[i_int].i_selected ? true : false;
303             break;
304
305         /* */
306         case ACCESS_SET_PAUSE_STATE:
307             b_bool = (bool)va_arg( args, int );
308             if( b_bool )
309                 MMSStop( p_access );
310             else
311                 Seek( p_access, p_access->info.i_pos );
312
313             if( p_sys->p_keepalive )
314             {
315                 vlc_mutex_lock( &p_sys->p_keepalive->lock );
316                 p_sys->p_keepalive->b_paused = b_bool;
317                 if( b_bool )
318                     vlc_cond_signal( &p_sys->p_keepalive->wait );
319                 vlc_mutex_unlock( &p_sys->p_keepalive->lock );
320             }
321             break;
322
323         case ACCESS_GET_TITLE_INFO:
324         case ACCESS_SET_TITLE:
325         case ACCESS_SET_SEEKPOINT:
326         case ACCESS_SET_PRIVATE_ID_STATE:
327         case ACCESS_GET_CONTENT_TYPE:
328             return VLC_EGENERIC;
329
330
331         default:
332             msg_Warn( p_access, "unimplemented query in control" );
333             return VLC_EGENERIC;
334
335     }
336     return VLC_SUCCESS;
337 }
338
339 /*****************************************************************************
340  * Seek: try to go at the right place
341  *****************************************************************************/
342 static int Seek( access_t * p_access, int64_t i_pos )
343 {
344     access_sys_t *p_sys = p_access->p_sys;
345     uint32_t    i_packet;
346     uint32_t    i_offset;
347     var_buffer_t buffer;
348
349     if( i_pos < 0 )
350         return VLC_EGENERIC;
351
352     if( i_pos < p_sys->i_header)
353     {
354
355         if( p_access->info.i_pos < p_sys->i_header )
356         {
357             /* no need to restart stream, it was already one
358              * or no stream was yet read */
359             p_access->info.i_pos = i_pos;
360             return VLC_SUCCESS;
361         }
362         else
363         {
364             i_packet = 0xffffffff;
365             i_offset = 0;
366         }
367     }
368     else
369     {
370         i_packet = ( i_pos - p_sys->i_header ) / p_sys->i_packet_length;
371         i_offset = ( i_pos - p_sys->i_header ) % p_sys->i_packet_length;
372     }
373     if( p_sys->b_seekable && i_packet >= p_sys->i_packet_count )
374         return VLC_EGENERIC;
375
376     msg_Dbg( p_access, "seeking to %"PRId64 " (packet:%d)", i_pos, i_packet );
377
378     MMSStop( p_access );
379     msg_Dbg( p_access, "stream stopped (seek)" );
380
381     /* *** restart stream *** */
382     var_buffer_initwrite( &buffer, 0 );
383     var_buffer_add64( &buffer, 0 ); /* seek point in second */
384     var_buffer_add32( &buffer, 0xffffffff );
385     var_buffer_add32( &buffer, i_packet ); // begin from start
386     var_buffer_add8( &buffer, 0xff ); // stream time limit
387     var_buffer_add8( &buffer, 0xff ); //  on 3bytes ...
388     var_buffer_add8( &buffer, 0xff ); //
389     var_buffer_add8( &buffer, 0x00 ); // don't use limit
390     var_buffer_add32( &buffer, p_sys->i_media_packet_id_type );
391
392     mms_CommandSend( p_access, 0x07, p_sys->i_command_level, 0x0001ffff,
393                      buffer.p_data, buffer.i_data );
394
395     var_buffer_free( &buffer );
396
397
398     while( vlc_object_alive (p_access) )
399     {
400         if( mms_HeaderMediaRead( p_access, MMS_PACKET_CMD ) < 0 )
401         {
402             p_access->info.b_eof = true;
403             return VLC_EGENERIC;
404         }
405
406         if( p_sys->i_command == 0x1e )
407         {
408             msg_Dbg( p_access, "received 0x1e (seek)" );
409             break;
410         }
411     }
412
413     while( vlc_object_alive (p_access) )
414     {
415         if( mms_HeaderMediaRead( p_access, MMS_PACKET_CMD ) < 0 )
416         {
417             p_access->info.b_eof = true;
418             return VLC_EGENERIC;
419         }
420         if( p_sys->i_command == 0x05 )
421         {
422             msg_Dbg( p_access, "received 0x05 (seek)" );
423             break;
424         }
425     }
426
427     /* get a packet */
428     if( mms_HeaderMediaRead( p_access, MMS_PACKET_MEDIA ) < 0 )
429     {
430         p_access->info.b_eof = true;
431         return VLC_EGENERIC;
432     }
433
434     msg_Dbg( p_access, "Streaming restarted" );
435
436     p_sys->i_media_used += i_offset;
437     p_access->info.i_pos = i_pos;
438     p_access->info.b_eof = false;
439
440     return VLC_SUCCESS;
441 }
442
443 /*****************************************************************************
444  * Block:
445  *****************************************************************************/
446 static block_t *Block( access_t *p_access )
447 {
448     access_sys_t *p_sys = p_access->p_sys;
449
450     if( p_access->info.b_eof )
451         return NULL;
452
453     if( p_access->info.i_pos < p_sys->i_header )
454     {
455         const size_t i_copy = p_sys->i_header - p_access->info.i_pos;
456
457         block_t *p_block = block_New( p_access, i_copy );
458         if( !p_block )
459             return NULL;
460
461         memcpy( p_block->p_buffer, &p_sys->p_header[p_access->info.i_pos], i_copy );
462         p_access->info.i_pos += i_copy;
463         return p_block;
464     }
465     else if( p_sys->p_media && p_sys->i_media_used < __MAX( p_sys->i_media, p_sys->i_packet_length ) )
466     {
467         size_t i_copy = 0;
468         size_t i_padding = 0;
469
470         if( p_sys->i_media_used < p_sys->i_media )
471             i_copy = p_sys->i_media - p_sys->i_media_used;
472         if( __MAX( p_sys->i_media, p_sys->i_media_used ) < p_sys->i_packet_length )
473             i_padding = p_sys->i_packet_length - __MAX( p_sys->i_media, p_sys->i_media_used );
474
475         block_t *p_block = block_New( p_access, i_copy + i_padding );
476         if( !p_block )
477             return NULL;
478
479         if( i_copy > 0 )
480             memcpy( &p_block->p_buffer[0], &p_sys->p_media[p_sys->i_media_used], i_copy );
481         if( i_padding > 0 )
482             memset( &p_block->p_buffer[i_copy], 0, i_padding );
483
484         p_sys->i_media_used += i_copy + i_padding;
485         p_access->info.i_pos += i_copy + i_padding;
486         return p_block;
487     }
488
489     mms_HeaderMediaRead( p_access, MMS_PACKET_MEDIA );
490     return NULL;
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:%u 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         var_buffer_free( &buffer );
1039         msg_Err( p_access, "failed to send command" );
1040         return VLC_EGENERIC;
1041     }
1042
1043     var_buffer_free( &buffer );
1044     return VLC_SUCCESS;
1045 }
1046
1047 static int NetFillBuffer( access_t *p_access )
1048 {
1049 #ifdef UNDER_CE
1050     return -1;
1051
1052 #else
1053     access_sys_t    *p_sys = p_access->p_sys;
1054     int             i_ret;
1055     struct pollfd   ufd[2];
1056     unsigned        timeout, nfd;
1057
1058     /* FIXME when using udp */
1059     ssize_t i_tcp, i_udp;
1060     ssize_t i_tcp_read, i_udp_read;
1061     int i_try = 0;
1062
1063     i_tcp = MMS_BUFFER_SIZE/2 - p_sys->i_buffer_tcp;
1064
1065     if( p_sys->i_proto == MMS_PROTO_UDP )
1066     {
1067         i_udp = MMS_BUFFER_SIZE/2 - p_sys->i_buffer_udp;
1068     }
1069     else
1070     {
1071         i_udp = 0;  /* there isn't udp socket */
1072     }
1073
1074     if( ( i_udp <= 0 ) && ( i_tcp <= 0 ) )
1075     {
1076         msg_Warn( p_access, "nothing to read %d:%d", (int)i_tcp, (int)i_udp );
1077         return 0;
1078     }
1079     else
1080     {
1081         /* msg_Warn( p_access, "ask for tcp:%d udp:%d", i_tcp, i_udp ); */
1082     }
1083
1084     /* Find if some data is available */
1085     do
1086     {
1087         i_try++;
1088
1089         /* Initialize file descriptor set */
1090         memset (ufd, 0, sizeof (ufd));
1091         nfd = 0;
1092
1093         if( i_tcp > 0 )
1094         {
1095             ufd[nfd].fd = p_sys->i_handle_tcp;
1096             ufd[nfd].events = POLLIN;
1097             nfd++;
1098         }
1099         if( i_udp > 0 )
1100         {
1101             ufd[nfd].fd = p_sys->i_handle_udp;
1102             ufd[nfd].events = POLLIN;
1103             nfd++;
1104         }
1105
1106         /* We'll wait 0.5 second if nothing happens */
1107         timeout = __MIN( 500, p_sys->i_timeout );
1108
1109         if( i_try * timeout > p_sys->i_timeout )
1110         {
1111             msg_Err(p_access, "no data received");
1112             return -1;
1113         }
1114
1115         if( i_try > 3 && (p_sys->i_buffer_tcp > 0 || p_sys->i_buffer_udp > 0) )
1116         {
1117             return -1;
1118         }
1119
1120         if( !vlc_object_alive (p_access) || p_access->b_error )
1121             return -1;
1122
1123         //msg_Dbg( p_access, "NetFillBuffer: trying again (select)" );
1124
1125     } while( !(i_ret = poll( ufd, nfd, timeout)) ||
1126              (i_ret < 0 && errno == EINTR) );
1127
1128     if( i_ret < 0 )
1129     {
1130         msg_Err( p_access, "network poll error (%m)" );
1131         return -1;
1132     }
1133
1134     i_tcp_read = i_udp_read = 0;
1135
1136     if( ( i_tcp > 0 ) && ufd[0].revents )
1137     {
1138         i_tcp_read =
1139             recv( p_sys->i_handle_tcp,
1140                   p_sys->buffer_tcp + p_sys->i_buffer_tcp,
1141                   i_tcp + MMS_BUFFER_SIZE/2, 0 );
1142     }
1143
1144     if( i_udp > 0 && ufd[i_tcp > 0].revents )
1145     {
1146         i_udp_read = recv( p_sys->i_handle_udp,
1147                            p_sys->buffer_udp + p_sys->i_buffer_udp,
1148                            i_udp + MMS_BUFFER_SIZE/2, 0 );
1149     }
1150
1151 #ifdef MMS_DEBUG
1152     if( p_sys->i_proto == MMS_PROTO_UDP )
1153     {
1154         msg_Dbg( p_access, "filling buffer TCP:%d+%d UDP:%d+%d",
1155                  p_sys->i_buffer_tcp, i_tcp_read,
1156                  p_sys->i_buffer_udp, i_udp_read );
1157     }
1158     else
1159     {
1160         msg_Dbg( p_access, "filling buffer TCP:%d+%d",
1161                  p_sys->i_buffer_tcp, i_tcp_read );
1162     }
1163 #endif
1164
1165     if( i_tcp_read > 0 ) p_sys->i_buffer_tcp += i_tcp_read;
1166     if( i_udp_read > 0 ) p_sys->i_buffer_udp += i_udp_read;
1167
1168     return i_tcp_read + i_udp_read;
1169 #endif
1170 }
1171
1172 static int  mms_ParseCommand( access_t *p_access,
1173                               uint8_t *p_data,
1174                               size_t i_data,
1175                               int *pi_used )
1176 {
1177  #define GET32( i_pos ) \
1178     ( p_sys->p_cmd[i_pos] + ( p_sys->p_cmd[i_pos +1] << 8 ) + \
1179       ( p_sys->p_cmd[i_pos + 2] << 16 ) + \
1180       ( p_sys->p_cmd[i_pos + 3] << 24 ) )
1181
1182     access_sys_t        *p_sys = p_access->p_sys;
1183     uint32_t    i_length;
1184     uint32_t    i_id;
1185
1186     free( p_sys->p_cmd );
1187     p_sys->i_cmd = i_data;
1188     p_sys->p_cmd = malloc( i_data );
1189     memcpy( p_sys->p_cmd, p_data, i_data );
1190
1191     *pi_used = i_data; /* by default */
1192
1193     if( i_data < MMS_CMD_HEADERSIZE )
1194     {
1195         msg_Warn( p_access, "truncated command (header incomplete)" );
1196         p_sys->i_command = 0;
1197         return -1;
1198     }
1199     i_id =  GetDWLE( p_data + 4 );
1200     i_length = GetDWLE( p_data + 8 ) + 16;
1201
1202     if( i_id != 0xb00bface || i_length < 16 )
1203     {
1204         msg_Err( p_access,
1205                  "incorrect command header (0x%"PRIx32")", i_id );
1206         p_sys->i_command = 0;
1207         return -1;
1208     }
1209
1210     if( i_length > p_sys->i_cmd )
1211     {
1212         msg_Warn( p_access,
1213                   "truncated command (missing %zu bytes)",
1214                    (size_t)i_length - i_data  );
1215         p_sys->i_command = 0;
1216         return -1;
1217     }
1218     else if( i_length < p_sys->i_cmd )
1219     {
1220         p_sys->i_cmd = i_length;
1221         *pi_used = i_length;
1222     }
1223
1224     msg_Dbg( p_access,
1225              "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",
1226              GET32( 0 ),
1227              GET32( 4 ),
1228              GET32( 8 ),
1229              /* 12: protocol type "MMS " */
1230              GET32( 16 ),
1231              GET32( 20 ),
1232              /* 24: unknown (0) */
1233              /* 28: unknown (0) */
1234              GET32( 32 ),
1235              GET32( 36 )
1236              /* 40: switches */
1237              /* 44: extra */ );
1238
1239     p_sys->i_command = GET32( 36 ) & 0xffff;
1240 #undef GET32
1241
1242     return MMS_PACKET_CMD;
1243 }
1244
1245 static int  mms_ParsePacket( access_t *p_access,
1246                              uint8_t *p_data, size_t i_data,
1247                              int *pi_used )
1248 {
1249     access_sys_t        *p_sys = p_access->p_sys;
1250     int i_packet_seq_num;
1251     size_t i_packet_length;
1252     uint32_t i_packet_id;
1253
1254     *pi_used = i_data; /* default */
1255     if( i_data <= 8 )
1256     {
1257         msg_Warn( p_access, "truncated packet (header incomplete)" );
1258         return -1;
1259     }
1260
1261     i_packet_id = p_data[4];
1262     i_packet_seq_num = GetDWLE( p_data );
1263     i_packet_length = GetWLE( p_data + 6 );
1264
1265     //msg_Warn( p_access, "------->i_packet_length=%d, i_data=%d", i_packet_length, i_data );
1266
1267     if( i_packet_length > i_data || i_packet_length <= 8)
1268     {
1269      /*   msg_Dbg( p_access,
1270                  "truncated packet (Declared %d bytes, Actual %d bytes)",
1271                  i_packet_length, i_data  ); */
1272         *pi_used = 0;
1273         return -1;
1274     }
1275     else if( i_packet_length < i_data )
1276     {
1277         *pi_used = i_packet_length;
1278     }
1279
1280     if( i_packet_id == 0xff )
1281     {
1282         msg_Warn( p_access,
1283                   "receive MMS UDP pair timing" );
1284         return( MMS_PACKET_UDP_TIMING );
1285     }
1286
1287     if( i_packet_id != p_sys->i_header_packet_id_type &&
1288         i_packet_id != p_sys->i_media_packet_id_type )
1289     {
1290         msg_Warn( p_access, "incorrect Packet Id Type (0x%x)", i_packet_id );
1291         return -1;
1292     }
1293
1294     /* we now have a media or a header packet */
1295     if( i_packet_seq_num != p_sys->i_packet_seq_num )
1296     {
1297 #if 0
1298         /* FIXME for udp could be just wrong order ? */
1299         msg_Warn( p_access,
1300                   "detected packet lost (%d != %d)",
1301                   i_packet_seq_num,
1302                   p_sys->i_packet_seq_num );
1303 #endif
1304     }
1305     p_sys->i_packet_seq_num = i_packet_seq_num + 1;
1306
1307     if( i_packet_id == p_sys->i_header_packet_id_type )
1308     {
1309         if( p_sys->p_header )
1310         {
1311             p_sys->p_header = realloc( p_sys->p_header,
1312                                           p_sys->i_header + i_packet_length - 8 );
1313             memcpy( &p_sys->p_header[p_sys->i_header],
1314                     p_data + 8, i_packet_length - 8 );
1315             p_sys->i_header += i_packet_length - 8;
1316
1317         }
1318         else
1319         {
1320             uint8_t* p_packet = malloc( i_packet_length - 8 ); // don't bother with preheader
1321             memcpy( p_packet, p_data + 8, i_packet_length - 8 );
1322             p_sys->p_header = p_packet;
1323             p_sys->i_header = i_packet_length - 8;
1324         }
1325 /*        msg_Dbg( p_access,
1326                  "receive header packet (%d bytes)",
1327                  i_packet_length - 8 ); */
1328
1329         return MMS_PACKET_HEADER;
1330     }
1331     else
1332     {
1333         uint8_t* p_packet = malloc( i_packet_length - 8 ); // don't bother with preheader
1334         memcpy( p_packet, p_data + 8, i_packet_length - 8 );
1335         FREENULL( p_sys->p_media );
1336         p_sys->p_media = p_packet;
1337         p_sys->i_media = i_packet_length - 8;
1338         p_sys->i_media_used = 0;
1339 /*        msg_Dbg( p_access,
1340                  "receive media packet (%d bytes)",
1341                  i_packet_length - 8 ); */
1342
1343         return MMS_PACKET_MEDIA;
1344     }
1345 }
1346
1347 static int mms_ReceivePacket( access_t *p_access )
1348 {
1349     access_sys_t *p_sys = p_access->p_sys;
1350     int i_packet_tcp_type;
1351     int i_packet_udp_type;
1352
1353     for( ;; )
1354     {
1355         bool b_refill = true;
1356
1357         /* first if we need to refill buffer */
1358         if( p_sys->i_buffer_tcp >= MMS_CMD_HEADERSIZE )
1359         {
1360             if( GetDWLE( p_sys->buffer_tcp + 4 ) == 0xb00bface  )
1361             {
1362                 if( GetDWLE( p_sys->buffer_tcp + 8 ) + 16 <=
1363                     (uint32_t)p_sys->i_buffer_tcp )
1364                 {
1365                     b_refill = false;
1366                 }
1367             }
1368             else if( GetWLE( p_sys->buffer_tcp + 6 ) <= p_sys->i_buffer_tcp )
1369             {
1370                 b_refill = false;
1371             }
1372         }
1373         if( p_sys->i_proto == MMS_PROTO_UDP && p_sys->i_buffer_udp >= 8 &&
1374             GetWLE( p_sys->buffer_udp + 6 ) <= p_sys->i_buffer_udp )
1375         {
1376             b_refill = false;
1377         }
1378
1379         if( b_refill && NetFillBuffer( p_access ) < 0 )
1380         {
1381             msg_Warn( p_access, "cannot fill buffer" );
1382             return -1;
1383         }
1384
1385         i_packet_tcp_type = -1;
1386         i_packet_udp_type = -1;
1387
1388         if( p_sys->i_buffer_tcp > 0 )
1389         {
1390             int i_used;
1391
1392             if( GetDWLE( p_sys->buffer_tcp + 4 ) == 0xb00bface )
1393             {
1394                 i_packet_tcp_type =
1395                     mms_ParseCommand( p_access, p_sys->buffer_tcp,
1396                                       p_sys->i_buffer_tcp, &i_used );
1397
1398             }
1399             else
1400             {
1401                 i_packet_tcp_type =
1402                     mms_ParsePacket( p_access, p_sys->buffer_tcp,
1403                                      p_sys->i_buffer_tcp, &i_used );
1404             }
1405             if( i_used > 0 && i_used < MMS_BUFFER_SIZE )
1406             {
1407                 memmove( p_sys->buffer_tcp, p_sys->buffer_tcp + i_used,
1408                          MMS_BUFFER_SIZE - i_used );
1409             }
1410             p_sys->i_buffer_tcp -= i_used;
1411         }
1412         else if( p_sys->i_buffer_udp > 0 )
1413         {
1414             int i_used;
1415
1416             i_packet_udp_type =
1417                 mms_ParsePacket( p_access, p_sys->buffer_udp,
1418                                  p_sys->i_buffer_udp, &i_used );
1419
1420             if( i_used > 0 && i_used < MMS_BUFFER_SIZE )
1421             {
1422                 memmove( p_sys->buffer_udp, p_sys->buffer_udp + i_used,
1423                          MMS_BUFFER_SIZE - i_used );
1424             }
1425             p_sys->i_buffer_udp -= i_used;
1426         }
1427
1428         if( i_packet_tcp_type == MMS_PACKET_CMD && p_sys->i_command == 0x1b )
1429         {
1430             mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1431             i_packet_tcp_type = -1;
1432         }
1433
1434         if( i_packet_tcp_type != -1 )
1435         {
1436             return i_packet_tcp_type;
1437         }
1438         else if( i_packet_udp_type != -1 )
1439         {
1440             return i_packet_udp_type;
1441         }
1442     }
1443 }
1444
1445 static int mms_ReceiveCommand( access_t *p_access )
1446 {
1447     access_sys_t *p_sys = p_access->p_sys;
1448
1449     for( ;; )
1450     {
1451         int i_used;
1452         int i_status;
1453
1454         if( NetFillBuffer( p_access ) < 0 )
1455         {
1456             msg_Warn( p_access, "cannot fill buffer" );
1457             return VLC_EGENERIC;
1458         }
1459         if( p_sys->i_buffer_tcp > 0 )
1460         {
1461             i_status = mms_ParseCommand( p_access, p_sys->buffer_tcp,
1462                                          p_sys->i_buffer_tcp, &i_used );
1463             if( i_used < MMS_BUFFER_SIZE )
1464             {
1465                 memmove( p_sys->buffer_tcp, p_sys->buffer_tcp + i_used,
1466                          MMS_BUFFER_SIZE - i_used );
1467             }
1468             p_sys->i_buffer_tcp -= i_used;
1469
1470             if( i_status < 0 )
1471             {
1472                 return VLC_EGENERIC;
1473             }
1474
1475             if( p_sys->i_command == 0x1b )
1476             {
1477                 mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1478             }
1479             else
1480             {
1481                 break;
1482             }
1483         }
1484         else
1485         {
1486             return VLC_EGENERIC;
1487         }
1488     }
1489
1490     return VLC_SUCCESS;
1491 }
1492
1493 #define MMS_RETRY_MAX       10
1494 #define MMS_RETRY_SLEEP     50000
1495
1496 static int mms_CommandRead( access_t *p_access, int i_command1,
1497                             int i_command2 )
1498 {
1499     access_sys_t *p_sys = p_access->p_sys;
1500     int i_count;
1501     int i_status;
1502
1503     for( i_count = 0; i_count < MMS_RETRY_MAX; )
1504     {
1505         i_status = mms_ReceiveCommand( p_access );
1506         if( i_status < 0 || p_sys->i_command == 0 )
1507         {
1508             i_count++;
1509             msleep( MMS_RETRY_SLEEP );
1510         }
1511         else if( i_command1 == 0 && i_command2 == 0)
1512         {
1513             return VLC_SUCCESS;
1514         }
1515         else if( p_sys->i_command == i_command1 ||
1516                  p_sys->i_command == i_command2 )
1517         {
1518             return VLC_SUCCESS;
1519         }
1520         else
1521         {
1522             switch( p_sys->i_command )
1523             {
1524                 case 0x03:
1525                     msg_Warn( p_access, "socket closed by server" );
1526                     p_access->info.b_eof = true;
1527                     return VLC_EGENERIC;
1528                 case 0x1e:
1529                     msg_Warn( p_access, "end of media stream" );
1530                     p_access->info.b_eof = true;
1531                     return VLC_EGENERIC;
1532                 default:
1533                     break;
1534             }
1535         }
1536     }
1537     p_access->info.b_eof = true;
1538     msg_Warn( p_access, "failed to receive command (aborting)" );
1539
1540     return VLC_EGENERIC;
1541 }
1542
1543
1544 static int mms_HeaderMediaRead( access_t *p_access, int i_type )
1545 {
1546     access_sys_t *p_sys = p_access->p_sys;
1547     int          i_count;
1548
1549     for( i_count = 0; i_count < MMS_RETRY_MAX; )
1550     {
1551         int i_status;
1552
1553         if( !vlc_object_alive (p_access) )
1554             return -1;
1555
1556         i_status = mms_ReceivePacket( p_access );
1557         if( i_status < 0 )
1558         {
1559             i_count++;
1560             msg_Warn( p_access, "cannot receive header (%d/%d)",
1561                       i_count, MMS_RETRY_MAX );
1562             msleep( MMS_RETRY_SLEEP );
1563         }
1564         else if( i_status == i_type || i_type == MMS_PACKET_ANY )
1565         {
1566             return i_type;
1567         }
1568         else if( i_status == MMS_PACKET_CMD )
1569         {
1570             switch( p_sys->i_command )
1571             {
1572                 case 0x03:
1573                     msg_Warn( p_access, "socket closed by server" );
1574                     p_access->info.b_eof = true;
1575                     return -1;
1576                 case 0x1e:
1577                     msg_Warn( p_access, "end of media stream" );
1578                     p_access->info.b_eof = true;
1579                     return -1;
1580                 case 0x20:
1581                     /* XXX not too dificult to be done EXCEPT that we
1582                      * need to restart demuxer... and I don't see how we
1583                      * could do that :p */
1584                     msg_Err( p_access,
1585                              "reinitialization needed --> unsupported" );
1586                     p_access->info.b_eof = true;
1587                     return -1;
1588                 default:
1589                     break;
1590             }
1591         }
1592     }
1593
1594     msg_Err( p_access, "cannot receive %s (aborting)",
1595              ( i_type == MMS_PACKET_HEADER ) ? "header" : "media data" );
1596     p_access->info.b_eof = true;
1597     return -1;
1598 }
1599
1600 static void* KeepAliveThread( void *p_data )
1601 {
1602     mmstu_keepalive_t *p_thread = (mmstu_keepalive_t *) p_data;
1603     access_t *p_access = p_thread->p_access;
1604
1605     vlc_mutex_lock( &p_thread->lock );
1606     mutex_cleanup_push( &p_thread->lock );
1607
1608     for( ;; )
1609     {
1610         /* Do nothing until paused (if ever) */
1611         while( !p_thread->b_paused )
1612             vlc_cond_wait( &p_thread->wait, &p_thread->lock );
1613
1614         do
1615         {
1616             int canc;
1617
1618             /* Send keep-alive every ten seconds */
1619             vlc_mutex_unlock( &p_thread->lock );
1620             canc = vlc_savecancel();
1621
1622             mms_CommandSend( p_access, 0x1b, 0, 0, NULL, 0 );
1623
1624             vlc_restorecancel( canc );
1625             vlc_mutex_lock( &p_thread->lock );
1626
1627             msleep( 10 * CLOCK_FREQ );
1628         }
1629         while( p_thread->b_paused );
1630     }
1631
1632     vlc_cleanup_pop();
1633     assert(0);
1634 }