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