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