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