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