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