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