]> git.sesse.net Git - vlc/blob - src/input/input.c
* Suppression d'un message d'erreur erronn� ;
[vlc] / src / input / input.c
1 /*******************************************************************************
2  * input.c: input thread 
3  * (c)1998 VideoLAN
4  *******************************************************************************
5  * Read an MPEG2 stream, demultiplex and parse it before sending it to
6  * decoders.
7  *******************************************************************************/
8
9 /*******************************************************************************
10  * Preamble
11  *******************************************************************************/
12 #include <errno.h>
13 #include <pthread.h>
14 #include <sys/uio.h>                                                 /* iovec */
15 #include <string.h>
16
17 #include <X11/Xlib.h>
18 #include <X11/extensions/XShm.h>
19 #include <sys/soundcard.h>
20
21 #include <stdlib.h>                               /* atoi(), malloc(), free() */
22 #include <stdio.h>
23 #include <sys/ioctl.h>                                             /* ioctl() */
24 #include <net/if.h>                                                  /* ifreq */
25 #include <netinet/in.h>
26
27 #include "common.h"
28 #include "config.h"
29 #include "mtime.h"
30 #include "intf_msg.h"
31 #include "debug.h"
32
33 #include "input.h"
34 #include "input_psi.h"
35 #include "input_pcr.h"
36 #include "input_netlist.h"
37 #include "decoder_fifo.h"
38 #include "input_file.h"
39 #include "input_network.h"
40
41 #include "audio_output.h"
42 #include "audio_decoder.h"
43
44 #include "video.h"
45 #include "video_output.h"
46 #include "video_decoder.h"
47
48 /******************************************************************************
49  * Local prototypes
50  ******************************************************************************/
51 static void input_Thread( input_thread_t *p_input );
52 static void EndThread( input_thread_t *p_input );
53 static __inline__ int input_ReadPacket( input_thread_t *p_input );
54 static __inline__ void input_SortPacket( input_thread_t *p_input,
55                                          ts_packet_t *ts_packet );
56 static __inline__ void input_DemuxTS( input_thread_t *p_input,
57                                       ts_packet_t *ts_packet,
58                                       es_descriptor_t *es_descriptor );
59 static __inline__ void input_DemuxPES( input_thread_t *p_input,
60                                        ts_packet_t *ts_packet,
61                                        es_descriptor_t *p_es_descriptor,
62                                        boolean_t b_unit_start, boolean_t b_packet_lost );
63 static __inline__ void input_DemuxPSI( input_thread_t *p_input,
64                                        ts_packet_t *ts_packet,
65                                        es_descriptor_t *p_es_descriptor,
66                                        boolean_t b_unit_start, boolean_t b_packet_lost );
67
68 /*******************************************************************************
69  * input_CreateThread: initialize and spawn an input thread
70  *******************************************************************************
71  * This function initializes and spawns an input thread. It returns NULL on
72  * failure. If you want a better understanding of the input thread, don't start
73  * by reading this function :-).
74  *******************************************************************************/
75 input_thread_t *input_CreateThread( input_cfg_t *p_cfg )
76 {
77     input_thread_t *    p_input;
78     int i_index;
79     
80     intf_DbgMsg("input debug 1-1: creating thread (cfg : %p)\n", p_cfg );
81
82     /* Allocate input_thread_t structure. */
83     if( !( p_input = (input_thread_t *)malloc(sizeof(input_thread_t)) ) )
84     {
85         intf_ErrMsg("input error: can't allocate input thread structure (%s)\n",
86                     strerror(errno));
87         return( NULL );
88     }
89     /* Init it */
90     bzero( p_input, sizeof(input_thread_t));
91     for( i_index = 0; i_index < INPUT_MAX_ES; i_index++ )
92     {
93         p_input->p_es[i_index].i_id = EMPTY_PID;
94     }
95
96     /* Find out which method we are gonna use and retrieve pointers. */
97     if( !((p_cfg->i_properties) & INPUT_CFG_METHOD) )
98     {
99         /* i_method is not set. */
100         intf_DbgMsg("input debug: using default method (%d)\n",
101                     INPUT_DEFAULT_METHOD);
102         p_cfg->i_method = INPUT_DEFAULT_METHOD;
103         p_cfg->i_properties |= INPUT_CFG_METHOD;
104     }
105     p_input->i_method = p_cfg->i_method;
106     switch( p_cfg->i_method )
107     {
108         /* File methods */
109         case INPUT_METHOD_TS_FILE:
110             p_input->p_open = &input_FileCreateMethod;
111             p_input->p_read = &input_FileRead;
112             p_input->p_clean = &input_FileDestroyMethod;
113             break;
114
115         /* Network methods */
116         case INPUT_METHOD_TS_UCAST:
117         case INPUT_METHOD_TS_MCAST:
118         case INPUT_METHOD_TS_BCAST:
119         case INPUT_METHOD_TS_VLAN_BCAST:
120             p_input->p_open = &input_NetworkCreateMethod;
121             p_input->p_read = &input_NetworkRead;
122             p_input->p_clean = &input_NetworkDestroyMethod;
123             break;
124
125         case INPUT_METHOD_NONE:
126         default:
127 #ifdef DEBUG
128             /* Internal error, which should never happen */
129             intf_DbgMsg("input debug: unknow method type %d\n",
130                             p_cfg->i_method);
131             return( NULL );
132 #endif
133             break;
134     }
135
136     /* Initialize PSI decoder. */
137     intf_DbgMsg("Initializing PSI decoder\n");
138     if( input_PsiInit( p_input ) == -1 )
139     {
140         free( p_input );
141         return( NULL );
142     }
143
144     /* Initialize PCR decoder. */
145     intf_DbgMsg("Initializing PCR decoder\n");
146     if( input_PcrInit( p_input ) == -1 )
147     {
148         input_PsiClean( p_input );
149         free( p_input );
150         return( NULL );
151     }
152
153     /* Initialize netlists. */
154     if( input_NetlistOpen( p_input ) )
155     {
156         input_PsiClean( p_input );
157         input_PcrClean( p_input );
158         free( p_input );
159         return( NULL );
160     }
161
162 #ifdef STATS
163     /* Initialize counters. */
164     p_input->c_bytes = 0;
165     p_input->c_payload_bytes = 0;
166     p_input->c_ts_packets_read = 0;
167     p_input->c_ts_packets_trashed = 0;
168 #ifdef DEBUG
169     p_input->c_loops = 0;
170 #endif
171 #endif
172
173     /* Let the appropriate method open the socket. */
174     if( (*(p_input->p_open))( p_input, p_cfg ) == -1 )
175     {
176         input_NetlistClean( p_input );
177         input_PsiClean( p_input );
178         input_PcrClean( p_input );
179         free( p_input );
180         return( NULL );
181     }
182
183     intf_DbgMsg("input debug: method %d properly initialized the socket\n",
184                 p_input->i_method);
185
186     /* Create thread and set locks. */
187     p_input->b_die = 0;
188     pthread_mutex_init( &p_input->netlist.lock, NULL );
189     pthread_mutex_init( &p_input->programs_lock, NULL );
190     pthread_mutex_init( &p_input->es_lock, NULL );
191 #ifdef NO_THREAD
192     input_Thread( p_input );
193 #else
194     if( pthread_create(&p_input->thread_id, NULL, (void *) input_Thread, 
195                        (void *) p_input) )
196     {
197         intf_ErrMsg("input error: can't spawn input thread (%s)\n", 
198                     strerror(errno) );
199         (*p_input->p_clean)( p_input );
200         input_NetlistClean( p_input );;
201         input_PsiClean( p_input );
202         input_PcrClean( p_input );
203         free( p_input );
204         return( NULL );
205     }
206 #endif
207
208     /* Default setting for new decoders */
209     p_input->p_aout = p_cfg->p_aout;
210
211     return( p_input );
212 }
213
214 /******************************************************************************
215  * input_DestroyThread: mark an input thread as zombie
216  ******************************************************************************
217  * This function should not return until the thread is effectively cancelled.
218  ******************************************************************************/
219 void input_DestroyThread( input_thread_t *p_input )
220 {
221     intf_DbgMsg("input debug: requesting termination of input thread\n");
222     p_input->b_die = 1;                          /* ask thread to kill itself */
223
224     /* Remove this as soon as the "status" flag is implemented */
225     pthread_join( p_input->thread_id, NULL );         /* wait until it's done */
226 }
227
228 #if 0
229 /*******************************************************************************
230  * input_OpenAudioStream: open an audio stream
231  *******************************************************************************
232  * This function spawns an audio decoder and plugs it on the audio output
233  * thread.
234  *******************************************************************************/
235 int input_OpenAudioStream( input_thread_t *p_input, int i_id )
236 {
237     /* ?? */
238 }
239
240 /*******************************************************************************
241  * input_CloseAudioStream: close an audio stream
242  *******************************************************************************
243  * This function destroys an audio decoder.
244  *******************************************************************************/
245 void input_CloseAudioStream( input_thread_t *p_input, int i_id )
246 {
247     /* ?? */
248 }
249
250 /*******************************************************************************
251  * input_OpenVideoStream: open a video stream
252  *******************************************************************************
253  * This function spawns a video decoder and plugs it on a video output thread.
254  *******************************************************************************/
255 int input_OpenVideoStream( input_thread_t *p_input, 
256                            struct vout_thread_s *p_vout, struct video_cfg_s * p_cfg )
257 {
258     /* ?? */
259 }
260
261 /*******************************************************************************
262  * input_CloseVideoStream: close a video stream
263  *******************************************************************************
264  * This function destroys an video decoder.
265  *******************************************************************************/
266 void input_CloseVideoStream( input_thread_t *p_input, int i_id )
267 {
268     /* ?? */
269 }
270 #endif
271
272 /* following functions are local */
273
274 /*******************************************************************************
275  * input_Thread: input thread
276  *******************************************************************************
277  * Thread in charge of processing the network packets and demultiplexing.
278  *******************************************************************************/
279 static void input_Thread( input_thread_t *p_input )
280 {
281     intf_DbgMsg("input debug 11-1: thread %p is active\n", p_input);
282     while( !p_input->b_die )
283     {
284         /* Scatter read the UDP packet from the network or the file. */
285         if( (input_ReadPacket( p_input )) == (-1) )
286         {
287             /* ??? Normally, a thread can't kill itself, but we don't have
288              * any method in case of an error condition ... */
289             p_input->b_die = 1;
290         }
291
292 #ifdef STATS
293         p_input->c_loops++;
294 #endif
295     }
296
297     /* Ohoh, we have to die as soon as possible. */
298     EndThread( p_input );
299
300     intf_DbgMsg("input debug: thread %p destroyed\n", p_input);
301     pthread_exit( 0 );
302 }
303
304 /*******************************************************************************
305  * EndThread: end the input thread
306  *******************************************************************************/
307 static void EndThread( input_thread_t *p_input )
308 {
309     int i_es_loop;
310
311     (*p_input->p_clean)( p_input );           /* close input method */
312
313     /* Destroy all decoder threads. */
314     for( i_es_loop = 0; i_es_loop < INPUT_MAX_ES; i_es_loop++ )
315     {
316         if( p_input->pp_selected_es[i_es_loop] )
317         {
318             switch( p_input->pp_selected_es[i_es_loop]->i_type )
319             {
320                 case MPEG1_VIDEO_ES:
321                 case MPEG2_VIDEO_ES:
322                     vdec_DestroyThread( (vdec_thread_t*)(p_input->pp_selected_es[i_es_loop]->p_dec) /*, NULL */ );
323                     break;
324                 case MPEG1_AUDIO_ES:
325                 case MPEG2_AUDIO_ES:
326                     adec_DestroyThread( (adec_thread_t*)(p_input->pp_selected_es[i_es_loop]->p_dec) );
327                     break;
328                 default:
329                     break;
330             }
331         }
332         else
333         {
334             /* pp_selected_es should not contain any hole. */
335             break;
336         }
337     }
338
339     input_NetlistClean( p_input );                           /* clean netlist */
340     input_PsiClean( p_input );                       /* clean PSI information */
341     input_PcrClean( p_input );                       /* clean PCR information */
342     free( p_input );                           /* free input_thread structure */
343
344     intf_DbgMsg("input debug: EndThread(%p)\n", p_input);
345 }
346
347 /*******************************************************************************
348  * input_ReadPacket: reads a packet from the network or the file
349  *******************************************************************************/
350 static __inline__ int input_ReadPacket( input_thread_t *p_input )
351 {
352     int                 i_base_index; /* index of the first free iovec */
353     int                 i_current_index;
354     int                 i_packet_size;
355 #ifdef INPUT_LIFO_TS_NETLIST
356     int                 i_meanwhile_released;
357     int                 i_currently_removed;
358 #endif
359     ts_packet_t *       p_ts_packet;
360
361     /* In this function, we only care about the TS netlist. PES netlist
362      * is for the demultiplexer. */
363 #ifdef INPUT_LIFO_TS_NETLIST
364     i_base_index = p_input->netlist.i_ts_index;
365
366     /* Verify that we still have packets in the TS netlist */
367     if( (INPUT_MAX_TS + INPUT_TS_READ_ONCE - 1 - p_input->netlist.i_ts_index) <= INPUT_TS_READ_ONCE )
368     {
369         intf_ErrMsg("input error: TS netlist is empty !\n");
370         return( -1 );
371     }
372
373 #else /* FIFO netlist */
374     i_base_index = p_input->netlist.i_ts_start;
375     if( p_input->netlist.i_ts_start + INPUT_TS_READ_ONCE -1 > INPUT_MAX_TS )
376     {
377         /* The netlist is splitted in 2 parts. We must gather them to consolidate
378            the FIFO (we make the loop easily in having the same iovec at the far
379            end and in the beginning of netlist_free).
380            That's why the netlist is (INPUT_MAX_TS +1) + (INPUT_TS_READ_ONCE -1)
381            large. */
382         memcpy( p_input->netlist.p_ts_free + INPUT_MAX_TS + 1,
383                 p_input->netlist.p_ts_free,
384                 (p_input->netlist.i_ts_start + INPUT_TS_READ_ONCE - 1 - INPUT_MAX_TS)
385                   * sizeof(struct iovec) );
386     }
387
388     /* Verify that we still have packets in the TS netlist */
389     if( ((p_input->netlist.i_ts_end -1 - p_input->netlist.i_ts_start) & INPUT_MAX_TS) <= INPUT_TS_READ_ONCE )
390     {
391         intf_ErrMsg("input error: TS netlist is empty !\n");
392         return( -1 );
393     }
394 #endif /* FIFO netlist */
395
396     /* Scatter read the buffer. */
397     i_packet_size = (*p_input->p_read)( p_input,
398                            &p_input->netlist.p_ts_free[i_base_index],
399                            INPUT_TS_READ_ONCE );
400     if( i_packet_size == (-1) )
401     {
402 //      intf_DbgMsg("Read packet %d %p %d %d\n", i_base_index,
403 //                      &p_input->netlist.p_ts_free[i_base_index],
404 //                      p_input->netlist.i_ts_start,
405 //                      p_input->netlist.i_ts_end);
406         intf_ErrMsg("input error: readv() failed (%s)\n", strerror(errno));
407         return( -1 );
408     }
409
410     if( i_packet_size == 0 )
411     {
412         /* No packet has been received, so stop here. */
413         return( 0 );
414     }
415      
416     /* Demultiplex the TS packets (1..INPUT_TS_READ_ONCE) received. */
417     for( i_current_index = i_base_index;
418          (i_packet_size -= TS_PACKET_SIZE) >= 0;
419          i_current_index++ )
420     {
421         /* BTW, something REALLY bad could happen if we receive packets with
422            a wrong size. */
423         p_ts_packet = (ts_packet_t*)(p_input->netlist.p_ts_free[i_current_index].iov_base);
424         /* Don't cry :-), we are allowed to do that cast, because initially,
425            our buffer was malloc'ed with sizeof(ts_packet_t) */
426
427         /* Find out if we need this packet and demultiplex. */
428         input_SortPacket( p_input /* for current PIDs and netlist */,
429                           p_ts_packet);
430     }
431
432     if( i_packet_size > 0 )
433     {
434         intf_ErrMsg("input error: wrong size\n");
435         return( -1 );
436     }
437
438     /* Remove the TS packets we have just filled from the netlist */
439 #ifdef INPUT_LIFO_TS_NETLIST
440     /* We need to take a lock here while we're calculating index positions. */
441     pthread_mutex_lock( &p_input->netlist.lock );
442
443     i_meanwhile_released = i_base_index - p_input->netlist.i_ts_index;
444     if( i_meanwhile_released )
445     {
446         /* That's where it becomes funny :-). Since we didn't take locks for
447            efficiency reasons, other threads (including ourselves, with
448            input_DemuxPacket) might have released packets to the netlist.
449            So we have to copy these iovec where they should go.
450            
451            BTW, that explains why the TS netlist is
452            (INPUT_MAX_TS +1) + (TS_READ_ONCE -1) large. */
453
454         i_currently_removed = i_current_index - i_base_index;
455         if( i_meanwhile_released < i_currently_removed )
456         {
457             /* Copy all iovecs in that case */
458             memcpy( &p_input->netlist.p_ts_free[p_input->netlist.i_ts_index]
459                      + i_currently_removed,
460                     &p_input->netlist.p_ts_free[p_input->netlist.i_ts_index],
461                     i_meanwhile_released * sizeof(struct iovec) );
462         }
463         else
464         {
465             /* We have fewer places than items, so we only move
466                i_currently_removed of them. */
467             memcpy( &p_input->netlist.p_ts_free[i_base_index],
468                     &p_input->netlist.p_ts_free[p_input->netlist.i_ts_index],
469                     i_currently_removed * sizeof(struct iovec) );
470         }
471
472         /* Update i_netlist_index with the information gathered above. */
473         p_input->netlist.i_ts_index += i_currently_removed;
474     }
475     else
476     {
477         /* Nothing happened. */
478         p_input->netlist.i_ts_index = i_current_index;
479     }
480
481     pthread_mutex_unlock( &p_input->netlist.lock );
482
483 #else /* FIFO netlist */
484     /* & is modulo ; that's where we make the loop. */
485     p_input->netlist.i_ts_start = i_current_index & INPUT_MAX_TS;
486 #endif
487
488 #ifdef STATS
489     p_input->c_ts_packets_read += i_current_index - i_base_index;
490     p_input->c_bytes += (i_current_index - i_base_index) * TS_PACKET_SIZE;
491 #endif
492         return( 0 );
493 }
494
495 /*******************************************************************************
496  * input_SortPacket: find out whether we need that packet
497  *******************************************************************************/
498 static __inline__ void input_SortPacket( input_thread_t *p_input,
499                                          ts_packet_t *p_ts_packet )
500 {
501     int             i_current_pid;
502     int             i_es_loop;
503
504     /* Verify that sync_byte, error_indicator and scrambling_control are
505        what we expected. */
506     if( !(p_ts_packet->buffer[0] == 0x47) || (p_ts_packet->buffer[1] & 0x80) ||
507         (p_ts_packet->buffer[3] & 0xc0) )
508     {
509         intf_DbgMsg("input debug: invalid TS header (%p)\n", p_ts_packet);
510     }
511     else
512     {
513         /* Get the PID of the packet. Note that ntohs is needed, for endianness
514            purposes (see man page). */
515         i_current_pid = U16_AT(&p_ts_packet->buffer[1]) & 0x1fff;
516
517 //      intf_DbgMsg("input debug: pid %d received (%p)\n",
518 //                    i_current_pid, p_ts_packet);
519
520         /* Lock current ES state. */
521         pthread_mutex_lock( &p_input->es_lock );
522         
523         /* Verify that we actually want this PID. */
524         for( i_es_loop = 0; i_es_loop < INPUT_MAX_SELECTED_ES; i_es_loop++ )
525         {
526             if( p_input->pp_selected_es[i_es_loop] != NULL)
527             {
528                 if( (*p_input->pp_selected_es[i_es_loop]).i_id
529                      == i_current_pid )
530                 {
531                     /* Don't need the lock anymore, since the value pointed
532                        out by p_input->pp_selected_es[i_es_loop] can only be
533                        modified from inside the input_thread (by the PSI
534                        decoder): interface thread is only allowed to modify
535                        the pp_selected_es table */
536                     pthread_mutex_unlock( &p_input->es_lock );
537
538                     /* We're interested. Pass it to the demultiplexer. */
539                     input_DemuxTS( p_input, p_ts_packet,
540                                    p_input->pp_selected_es[i_es_loop] );
541                     return;
542                 }
543             }
544             else
545             {
546                 /* pp_selected_es should not contain any hole. */
547                 break;
548             }
549         }
550         pthread_mutex_unlock( &p_input->es_lock );
551     }
552
553     /* We weren't interested in receiving this packet. Give it back to the
554        netlist. */
555 //    intf_DbgMsg("SortPacket: freeing unwanted TS %p (pid %d)\n", p_ts_packet,
556 //                     U16_AT(&p_ts_packet->buffer[1]) & 0x1fff);
557     input_NetlistFreeTS( p_input, p_ts_packet );
558 #ifdef STATS
559     p_input->c_ts_packets_trashed++;
560 #endif
561 }
562
563 /*******************************************************************************
564  * input_DemuxTS: first step of demultiplexing: the TS header
565  *******************************************************************************
566  * Stream must also only contain PES and PSI, so PID must have been filtered
567  *******************************************************************************/
568 static __inline__ void input_DemuxTS( input_thread_t *p_input,
569                                       ts_packet_t *p_ts_packet,
570                                       es_descriptor_t *p_es_descriptor )
571 {
572     int         i_dummy;
573     boolean_t   b_adaption;                       /* Adaption field is present */
574     boolean_t   b_payload;                           /* Packet carries payload */
575     boolean_t   b_unit_start;            /* A PSI or a PES start in the packet */
576     boolean_t   b_trash = 0;                   /* Must the packet be trashed ? */
577     boolean_t   b_lost = 0;                      /* Was there a packet lost ? */
578
579     ASSERT(p_input);
580     ASSERT(p_ts_packet);
581     ASSERT(p_es_descriptor);
582
583 #define p (p_ts_packet->buffer)
584
585 //    intf_DbgMsg("input debug: TS-demultiplexing packet %p, pid %d, number %d\n",
586 //                p_ts_packet, U16_AT(&p[1]) & 0x1fff, p[3] & 0x0f);
587
588 #ifdef STATS
589     p_es_descriptor->c_packets++;
590     p_es_descriptor->c_bytes += TS_PACKET_SIZE;
591 #endif
592
593     /* Extract flags values from TS common header. */
594     b_unit_start = (p[1] & 0x40);
595     b_adaption = (p[3] & 0x20);
596     b_payload = (p[3] & 0x10);
597     
598     /* Extract adaption field informations if any */
599     if( !b_adaption )
600     {
601         /* We don't have any adaptation_field, so payload start immediately
602          after the 4 byte TS header */
603         p_ts_packet->i_payload_start = 4;
604     }
605     else
606     {
607         /* p[4] is adaptation_field_length minus one */
608         p_ts_packet->i_payload_start = 5 + p[4];
609
610         /* The adaption field can be limited to the adaptation_field_length byte,
611            so that there is nothing to do: skip this possibility */
612         if( p[4] )
613         {
614             /* If the packet has both adaptation_field and payload, adaptation_field
615                cannot be more than 182 bytes long; if there is only an adaptation_field,
616                it must fill the next 183 bytes. */
617             if( b_payload ? (p[4] > 182) : (p[4] != 183) )
618             {
619                 intf_DbgMsg("input debug: invalid TS adaptation field (%p)\n",
620                             p_ts_packet);
621 #ifdef STATS
622                 p_es_descriptor->c_invalid_packets++;
623 #endif
624                 b_trash = 1;
625             }
626
627             /* No we are sure that the byte containing flags is present: read it */
628             else
629             {
630                 /* discontinuity_indicator */
631                 if( p[5] & 0x80 )
632                 {
633                     intf_DbgMsg("discontinuity_indicator encountered by TS demux " \
634                                 "(position read: %d, saved: %d)\n", p[5] & 0x80,
635                                 p_es_descriptor->i_continuity_counter);
636
637                     /* If the PID carries the PCR, there will be a system time-base
638                        discontinuity. We let the PCR decoder handle that. */
639                     p_es_descriptor->b_discontinuity = 1;
640                     
641                     /* There also may be a continuity_counter discontinuity: resynchronise
642                        our counter with the one of the stream */
643                     p_es_descriptor->i_continuity_counter = (p[3] & 0x0f) - 1;
644                 }
645
646                 /* random_access_indicator */
647                 p_es_descriptor->b_random |= p[5] & 0x40;
648
649                 /* If this is a PCR_PID, and this TS packet contains a PCR, we pass it
650                    along to the PCR decoder. */
651                 if( (p_es_descriptor->b_pcr) && (p[5] & 0x10) )
652                 {
653                     /* There should be a PCR field in the packet, check if the adaption
654                        field is long enough to carry it */
655                     if( p[4] >= 7 )
656                     {
657                         /* Call the PCR decoder */
658                         input_PcrDecode( p_input, p_es_descriptor, &p[6] );
659                     }
660                 }
661             }
662         }
663     }
664
665     /* Check the continuity of the stream. */
666     i_dummy = ((p[3] & 0x0f) - p_es_descriptor->i_continuity_counter) & 0x0f;
667     if( i_dummy == 1 )
668     {
669         /* Everything is ok, just increase our counter */
670         p_es_descriptor->i_continuity_counter++;
671     }
672     else
673     {
674         if( !b_payload && i_dummy == 0 )
675         {
676             /* This is a packet without payload, this is allowed by the draft
677                As there is nothing interessant in this packet (except PCR that
678                have already been handled), we can trash the packet. */
679             intf_DbgMsg("Packet without payload received by TS demux\n");
680             b_trash = 1;
681         }
682         else if( i_dummy <= 0 )
683         {
684             /* Duplicate packet: mark it as being to be trashed. */
685             intf_DbgMsg("Duplicate packet received by TS demux\n");
686             b_trash = 1;
687         }
688         else
689         {
690             /* This can indicate that we missed a packet or that the
691                continuity_counter wrapped and we received a dup packet: as we
692                don't know, do as if we missed a packet to be sure to recover
693                from this situation */
694             intf_DbgMsg("Packet lost by TS demux: current %d, packet %d\n",
695                         p_es_descriptor->i_continuity_counter & 0x0f,
696                         p[3] & 0x0f);
697             b_lost = 1;
698             p_es_descriptor->i_continuity_counter = p[3] & 0x0f;
699         }
700     }
701
702     /* Trash the packet if it has no payload or if it is bad */
703     if( b_trash )
704     {
705         input_NetlistFreeTS( p_input, p_ts_packet );
706 #ifdef STATS
707         p_input->c_ts_packets_trashed++;
708 #endif
709     }
710     else
711     {
712         if( p_es_descriptor->b_psi )
713         {
714             /* The payload contains PSI tables */
715             input_DemuxPSI( p_input, p_ts_packet, p_es_descriptor,
716                             b_unit_start, b_lost );
717         }
718         else
719         {
720             /* The payload carries a PES stream */ 
721             input_DemuxPES( p_input, p_ts_packet, p_es_descriptor,
722                             b_unit_start, b_lost );
723         }
724     }
725
726 #undef p
727 }
728
729
730
731
732 /*******************************************************************************
733  * input_DemuxPES: 
734  *******************************************************************************
735  * Gather a PES packet and analyzes its header.
736  *******************************************************************************/
737 static __inline__ void input_DemuxPES( input_thread_t *p_input,
738                                        ts_packet_t *p_ts_packet,
739                                        es_descriptor_t *p_es_descriptor,
740                                        boolean_t b_unit_start,
741                                        boolean_t b_packet_lost )
742 {
743     decoder_fifo_t *            p_fifo;
744     u8                          i_pes_header_size;
745     int                         i_dummy;
746     pes_packet_t*               p_last_pes;
747     ts_packet_t *               p_ts;
748     int                         i_ts_payload_size;
749     
750
751 #define p_pes (p_es_descriptor->p_pes_packet)
752
753     ASSERT(p_input);
754     ASSERT(p_ts_packet);
755     ASSERT(p_es_descriptor);
756
757 //    intf_DbgMsg("PES-demultiplexing %p (%p)\n", p_ts_packet, p_pes);
758
759     /* If we lost data, discard the PES packet we are trying to reassemble
760        if any and wait for the beginning of a new one in order to synchronise
761        again */
762     if( b_packet_lost && p_pes != NULL )
763     {
764         intf_DbgMsg("PES %p trashed because of packet lost\n", p_pes);
765         input_NetlistFreePES( p_input, p_pes );
766         p_pes = NULL;
767     }
768
769     /* If the TS packet contains the begining of a new PES packet, and if we
770        were reassembling a PES packet, then the PES should be complete now,
771        so parse its header and give it to the decoders */
772     if( b_unit_start && p_pes != NULL )
773     {
774 //        intf_DbgMsg("End of PES packet %p\n", p_pes);
775
776         /* Parse the header. The header has a variable length, but in order 
777            to improve the algorithm, we will read the 14 bytes we may be
778            interested in */
779         p_ts = p_pes->p_first_ts;
780         i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
781         i_dummy = 0;
782
783         if(i_ts_payload_size >= PES_HEADER_SIZE)
784         {
785             /* This part of the header entirely fits in the payload of   
786                the first TS packet */
787             p_pes->p_pes_header = &(p_ts->buffer[p_ts->i_payload_start]);
788         }
789         else
790         {
791             /* This part of the header does not fit in the current TS packet:
792                copy the part of the header we are interested in to the
793                p_pes_header_save buffer */
794             intf_DbgMsg("Code never tested encourtered, WARNING ! (benny)\n");
795             do
796             {
797                 memcpy(p_pes->p_pes_header_save + i_dummy,
798                        &p_ts->buffer[p_ts->i_payload_start], i_ts_payload_size);
799                 i_dummy += i_ts_payload_size;
800             
801                 p_ts = p_ts->p_next_ts;
802                 if(!p_ts)
803                 {
804                   /* The payload of the PES packet is shorter than the 14 bytes
805                      we would read. This means that high packet lost occured
806                      so the PES won't be usefull for any decoder. Moreover,
807                      this should never happen so we can trash the packet and
808                      exit roughly without regrets */
809                   intf_DbgMsg("PES packet too short: trashed\n");
810                   input_NetlistFreePES( p_input, p_pes );
811                   p_pes = NULL;
812                   /* Stats ?? */
813                   return;
814                 }
815                 
816                 i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
817             }
818             while(i_ts_payload_size + i_dummy < PES_HEADER_SIZE);
819
820             /* This last TS packet is partly header, partly payload, so just
821                copy the header part */
822             memcpy(p_pes->p_pes_header_save + i_dummy,
823                    &p_ts->buffer[p_ts->i_payload_start],
824                    PES_HEADER_SIZE - i_dummy);
825
826             /* The header must be read in the buffer not in any TS packet */
827            p_pes->p_pes_header = p_pes->p_pes_header_save;
828         }
829         
830         /* Now we have the part of the PES header we were interested in:
831            parse it */
832
833         /* First read the 6 header bytes common to all PES packets:
834            use them to test the PES validity */
835         if( (p_pes->p_pes_header[0] || p_pes->p_pes_header[1] ||
836             (p_pes->p_pes_header[2] != 1)) ||
837                                      /* packet_start_code_prefix != 0x000001 */
838             ((i_dummy = U16_AT(p_pes->p_pes_header + 4)) &&
839              (i_dummy + 6 != p_pes->i_pes_size)) )
840                    /* PES_packet_length is set and != total received payload */
841         {
842           /* Trash the packet and set p_pes to NULL to be sure the next PES
843              packet will have its b_data_lost flag set */
844           intf_DbgMsg("Corrupted PES packet received: trashed\n");
845           input_NetlistFreePES( p_input, p_pes );
846           p_pes = NULL;
847           /* Stats ?? */
848         }
849         else
850         {
851             /* The PES packet is valid. Check its type to test if it may
852                carry additional informations in a header extension */
853             p_pes->i_stream_id =  p_pes->p_pes_header[3];
854
855             switch( p_pes->i_stream_id )
856             {
857             case 0xBE:  /* Padding */
858             case 0xBC:  /* Program stream map */
859             case 0xBF:  /* Private stream 2 */
860             case 0xB0:  /* ECM */
861             case 0xB1:  /* EMM */
862             case 0xFF:  /* Program stream directory */
863             case 0xF2:  /* DSMCC stream */
864             case 0xF8:  /* ITU-T H.222.1 type E stream */
865                 /* The payload begins immediatly after the 6 bytes header, so
866                    we have finished with the parsing */
867                 i_pes_header_size = 6;
868                 break;
869
870             default:
871                 /* The PES header contains at least 3 more bytes: parse them */
872                 p_pes->b_data_alignment = p_pes->p_pes_header[6] & 0x10;
873                 p_pes->b_has_pts = p_pes->p_pes_header[7] & 0x4;
874                 i_pes_header_size = 9 + p_pes->p_pes_header[8];
875                 
876                 /* Now parse the optional header extensions (in the limit of
877                    the 14 bytes */
878                 if( p_pes->b_has_pts )
879                 {
880                     pcr_descriptor_t *p_pcr;
881                     /* The PTS field is split in 3 bit records. We have to add
882                        them, and thereafter we substract the 2 marker_bits */
883
884                     p_pcr = p_input->p_pcr;
885                     pthread_mutex_lock( &p_pcr->lock );
886                     if( p_pcr->delta_clock == 0 )
887                     {
888                         p_pes->i_pts = 0;
889                     }
890                     else
891                     {
892                         p_pes->i_pts = ( ((mtime_t)p_pes->p_pes_header[9] << 29) +
893                                          ((mtime_t)U16_AT(p_pes->p_pes_header + 10) << 14) +
894                                          ((mtime_t)U16_AT(p_pes->p_pes_header + 12) >> 1) -
895                                          (1 << 14) - (1 << 29) );
896                         p_pes->i_pts *= 300;
897                         p_pes->i_pts /= 27;
898                         p_pes->i_pts += p_pcr->delta_clock;
899                         if( p_pcr->c_pts == 0 )
900                         {
901                             p_pcr->delta_decode = mdate() - p_pes->i_pts + 500000;
902                         }
903                         p_pes->i_pts += p_pcr->delta_decode;
904                     }
905                     p_pcr->c_pts += 1;
906                     pthread_mutex_unlock( &p_pcr->lock );
907                 }
908                 break;
909             }
910
911             /* Now we've parsed the header, we just have to indicate in some
912                specific TS packets where the PES payload begins (renumber
913                i_payload_start), so that the decoders can find the beginning
914                of their data right out of the box. */
915             p_ts = p_pes->p_first_ts;
916             i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
917             while( i_pes_header_size > i_ts_payload_size )
918             {
919                 /* These packets are entirely filled by the PES header. */
920                 i_pes_header_size -= i_ts_payload_size;
921                 p_ts->i_payload_start = p_ts->i_payload_end;
922                 /* Go to the next TS packet: here we won't have to test it is
923                    not NULL because we trash the PES packets when packet lost
924                    occurs */
925                 p_ts = p_ts->p_next_ts;
926                 i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
927             }
928             /* This last packet is partly header, partly payload. */
929             p_ts->i_payload_start += i_pes_header_size;
930
931             /* Now we can eventually put the PES packet in the decoder's
932                PES fifo */
933             switch( p_es_descriptor->i_type )
934             {
935             case MPEG1_VIDEO_ES:
936             case MPEG2_VIDEO_ES:
937                 p_fifo = &(((vdec_thread_t*)(p_es_descriptor->p_dec))->fifo);
938                 break;
939             case MPEG1_AUDIO_ES:
940             case MPEG2_AUDIO_ES:
941                 p_fifo = &(((adec_thread_t*)(p_es_descriptor->p_dec))->fifo);
942                 break;
943             default:
944                 /* This should never happen. */
945                 intf_DbgMsg("Unknown stream type (%d, %d): PES trashed\n",
946                             p_es_descriptor->i_id, p_es_descriptor->i_type);
947                 p_fifo = NULL;
948                 break;
949             }
950
951             if( p_fifo != NULL )
952             {
953                 pthread_mutex_lock( &p_fifo->data_lock );
954                 if( DECODER_FIFO_ISFULL( *p_fifo ) )
955                 {
956                     /* The FIFO is full !!! This should not happen. */
957 #ifdef STATS
958                     p_input->c_ts_packets_trashed += p_pes->i_ts_packets;
959                     p_es_descriptor->c_invalid_packets += p_pes->i_ts_packets;
960 #endif
961                     input_NetlistFreePES( p_input, p_pes );
962                     intf_DbgMsg("PES trashed - fifo full ! (%d, %d)\n",
963                                p_es_descriptor->i_id, p_es_descriptor->i_type);
964                 }
965                 else
966                 {
967 //                    intf_DbgMsg("Putting %p into fifo %p/%d\n",
968 //                                p_pes, p_fifo, p_fifo->i_end);
969                     p_fifo->buffer[p_fifo->i_end] = p_pes;
970                     DECODER_FIFO_INCEND( *p_fifo );
971
972                     /* Warn the decoder that it's got work to do. */
973                     pthread_cond_signal( &p_fifo->data_wait );
974                 }
975                 pthread_mutex_unlock( &p_fifo->data_lock );
976             }
977             else
978             {
979                 intf_DbgMsg("No fifo to receive PES %p: trash\n", p_pes);
980 #ifdef STATS
981                 p_input->c_ts_packets_trashed += p_pes->i_ts_packets;
982                 p_es_descriptor->c_invalid_packets += p_pes->i_ts_packets;
983 #endif
984                 input_NetlistFreePES( p_input, p_pes );
985             }
986         }
987     }
988
989
990     /* If we are at the beginning of a new PES packet, we must fetch a new
991        PES buffer to begin with the reassembly of this PES packet. This is
992        also here that we can synchronise with the stream if we we lost
993        packets or if the decoder has just started */ 
994     if( b_unit_start )
995     {
996         p_last_pes = p_pes;
997
998         /* Get a new one PES from the PES netlist. */
999         if( (p_pes = input_NetlistGetPES( p_input )) == (NULL) )
1000         {
1001             /* PES netlist is empty ! */
1002             p_input->b_error = 1;
1003         }
1004         else
1005         {
1006 //           intf_DbgMsg("New PES packet %p (first TS: %p)\n", p_pes, p_ts_packet);
1007
1008             /* Init the PES fields so that the first TS packet could be correctly
1009                added to the PES packet (see below) */
1010             p_pes->p_first_ts = p_ts_packet;
1011             p_pes->p_last_ts = NULL;
1012
1013             /* If the last pes packet was null, this means that the synchronisation
1014                was lost and so warn the decoder that he will have to find a way to
1015                recover */
1016             if( !p_last_pes )
1017                 p_pes->b_data_loss = 1;
1018
1019             /* Read the b_random_access flag status and then reinit it */     
1020             p_pes->b_random_access = p_es_descriptor->b_random;
1021             p_es_descriptor->b_random = 0;
1022         }
1023     }
1024
1025
1026     /* If we are synchronised with the stream, and so if we are ready to
1027        receive correctly the data, add the TS packet to the current PES
1028        packet */
1029     if( p_pes != NULL )
1030     {
1031 //      intf_DbgMsg("Adding TS %p to PES %p\n", p_ts_packet, p_pes);
1032
1033         /* Size of the payload carried in the TS packet */
1034         i_ts_payload_size = p_ts_packet->i_payload_end -
1035                             p_ts_packet->i_payload_start;
1036
1037         /* Update the relations between the TS packets */
1038         p_ts_packet->p_prev_ts = p_pes->p_last_ts;
1039         p_ts_packet->p_next_ts = NULL;
1040         if( p_pes->i_ts_packets != 0 )
1041         {
1042             /* Regarder si il serait pas plus efficace de ne creer que les liens
1043                precedent->suivant pour le moment, et les liens suivant->precedent
1044                quand le paquet est termine */
1045             /* Otherwise it is the first TS packet. */
1046             p_pes->p_last_ts->p_next_ts = p_ts_packet;
1047         }
1048         /* Now add the TS to the PES packet */
1049         p_pes->p_last_ts = p_ts_packet;
1050         p_pes->i_ts_packets++;
1051         p_pes->i_pes_size += i_ts_payload_size;
1052
1053         /* Stats */
1054 #ifdef STATS
1055         i_dummy = p_ts_packet->i_payload_end - p_ts_packet->i_payload_start;
1056         p_es_descriptor->c_payload_bytes += i_dummy;
1057 #endif
1058     }
1059     else
1060     {
1061         /* Since we don't use the TS packet to build a PES packet, we don't
1062            need it anymore, so give it back to the netlist */
1063 //        intf_DbgMsg("Trashing TS %p: no PES being build\n", p_ts_packet);
1064         input_NetlistFreeTS( p_input, p_ts_packet );     
1065     }
1066     
1067 #undef p_pes
1068 }
1069
1070
1071
1072
1073 /*******************************************************************************
1074  * input_DemuxPSI:
1075  *******************************************************************************
1076  * Notice that current ES state has been locked by input_SortPacket. (No more true,
1077  * changed by benny - See if it'a ok, and definitely change the code ???????? )
1078  *******************************************************************************/
1079 static __inline__ void input_DemuxPSI( input_thread_t *p_input,
1080                                        ts_packet_t *p_ts_packet,
1081                                        es_descriptor_t *p_es_descriptor,
1082                                        boolean_t b_unit_start, boolean_t b_packet_lost )
1083 {
1084     int i_data_offset;      /* Offset of the interesting data in the TS packet */
1085     u16 i_data_length;                                 /* Length of those data */
1086     boolean_t b_first_section; /* Was there another section in the TS packet ? */
1087     
1088     ASSERT(p_input);
1089     ASSERT(p_ts_packet);
1090     ASSERT(p_es_descriptor);
1091
1092 #define p_psi (p_es_descriptor->p_psi_section)
1093
1094 //    intf_DbgMsg( "input debug: PSI demultiplexing %p (%p)\n", p_ts_packet, p_input);
1095
1096 //    intf_DbgMsg( "Packet: %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x %x (unit start: %d)\n", p_ts_packet->buffer[p_ts_packet->i_payload_start], p_ts_packet->buffer[p_ts_packet->i_payload_start+1], p_ts_packet->buffer[p_ts_packet->i_payload_start+2], p_ts_packet->buffer[p_ts_packet->i_payload_start+3], p_ts_packet->buffer[p_ts_packet->i_payload_start+4], p_ts_packet->buffer[p_ts_packet->i_payload_start+5], p_ts_packet->buffer[p_ts_packet->i_payload_start+6], p_ts_packet->buffer[p_ts_packet->i_payload_start+7], p_ts_packet->buffer[p_ts_packet->i_payload_start+8], p_ts_packet->buffer[p_ts_packet->i_payload_start+9], p_ts_packet->buffer[p_ts_packet->i_payload_start+10], p_ts_packet->buffer[p_ts_packet->i_payload_start+11], p_ts_packet->buffer[p_ts_packet->i_payload_start+12], p_ts_packet->buffer[p_ts_packet->i_payload_start+13], p_ts_packet->buffer[p_ts_packet->i_payload_start+14], p_ts_packet->buffer[p_ts_packet->i_payload_start+15], p_ts_packet->buffer[p_ts_packet->i_payload_start+16], p_ts_packet->buffer[p_ts_packet->i_payload_start+17], p_ts_packet->buffer[p_ts_packet->i_payload_start+18], p_ts_packet->buffer[p_ts_packet->i_payload_start+19], p_ts_packet->buffer[p_ts_packet->i_payload_start+20], b_unit_start);
1097
1098     /* The section we will deal with during the first iteration of the following
1099        loop is the first one contained in the TS packet */
1100     b_first_section = 1;
1101
1102     /* Reassemble the pieces of sections contained in the TS packet and decode
1103        the sections that could have been completed */
1104     do
1105     {
1106         /* Has the reassembly of a section already began in a previous packet ? */
1107         if( p_psi->b_running_section )
1108         {
1109             /* Was data lost since the last TS packet ? */
1110             if( b_packet_lost )
1111             {
1112                 /* Discard the section and wait for the begining of a new one to resynch */
1113                 p_psi->b_running_section = 0;
1114                 intf_DbgMsg( "Section discarded due to packet loss\n" );
1115             }
1116             else
1117             {
1118                 /* The data that complete a previously began section are always at
1119                    the beginning of the TS payload... */
1120                 i_data_offset = p_ts_packet->i_payload_start;
1121                 /* ...Unless there is a pointer field, that we have to bypass */
1122                 if( b_unit_start )
1123                     i_data_offset ++;
1124 //                intf_DbgMsg( "New part of the section received at offset %d\n", i_data_offset );
1125             }
1126         }
1127         /* We are looking for the beginning of a new section */
1128         else
1129         {
1130             if( !b_unit_start )
1131             {
1132                 /* Cannot do anything with those data: trash both PSI section and TS packet */
1133                 p_psi->b_running_section = 0;
1134                 break;
1135             }
1136             else
1137             {
1138                 /* Get the offset at which the data for that section can be found */
1139                 if( b_first_section )
1140                 {
1141                     /* The offset is stored in the pointer_field since we are interested in
1142                        the first section of the TS packet. Note that the +1 is to bypass
1143                        the pointer field */
1144                     i_data_offset = p_ts_packet->i_payload_start +
1145                      p_ts_packet->buffer[p_ts_packet->i_payload_start] + 1;
1146                 }
1147                 else
1148                 {
1149                     /* Since no gap is allowed between 2 sections in a TS packet, the
1150                        offset is given by the end of the previous section. In fact, there
1151                        is nothing to do, i_offset was set to the right value in the
1152                        previous iteration */
1153                 }
1154 //                intf_DbgMsg( "New section beginning at offset %d in TS packet\n", i_data_offset );
1155
1156                 /* Read the length of that section */
1157                 p_psi->i_length = (U16_AT(&p_ts_packet->buffer[i_data_offset+1]) & 0xFFF) + 3;
1158 //                intf_DbgMsg( "Section length %d\n", p_psi->i_length );
1159                 if( p_psi->i_length > PSI_SECTION_SIZE )
1160                 {
1161                   /* The TS packet is corrupted, stop here to avoid possible a seg fault */
1162                   intf_DbgMsg( "Section size is too big, aborting its reception\n" );
1163                   break;
1164                 }
1165
1166                 /* Init the reassembly of that section */
1167                 p_psi->b_running_section = 1;
1168                 p_psi->i_current_position = 0;
1169             }
1170         }
1171
1172         /* Compute the length of data related to the section in this TS packet */
1173         if( p_psi->i_length - p_psi->i_current_position > TS_PACKET_SIZE - i_data_offset)
1174             i_data_length = TS_PACKET_SIZE - i_data_offset;
1175         else
1176           i_data_length = p_psi->i_length - p_psi->i_current_position;
1177
1178         /* Copy those data in the section buffer */
1179         memcpy( &p_psi->buffer[p_psi->i_current_position], &p_ts_packet->buffer[i_data_offset],
1180                 i_data_length );
1181     
1182         /* Interesting data are now after the ones we copied */
1183         i_data_offset += i_data_length;
1184
1185         /* Decode the packet if it is now complete */
1186         if (p_psi->i_length == p_psi->i_current_position + i_data_length)
1187         {
1188             /* Packet is complete, decode it */
1189 //            intf_DbgMsg( "SECTION COMPLETE: starting decoding of its data\n" );
1190             input_PsiDecode( p_input, p_psi );
1191
1192             /* Prepare the buffer to receive a new section */
1193             p_psi->i_current_position = 0;
1194             p_psi->b_running_section = 0;
1195         
1196             /* The new section won't be the first anymore */
1197             b_first_section = 0;
1198         }
1199         else
1200         {
1201             /* Prepare the buffer to receive the next part of the section */
1202           p_psi->i_current_position += i_data_length;
1203 //          intf_DbgMsg( "Section not complete, waiting for the end\n" );
1204         }
1205     
1206 //        intf_DbgMsg( "Must loop ? Next data offset: %d, stuffing: %d\n",
1207 //                     i_data_offset, p_ts_packet->buffer[i_data_offset] );
1208     }
1209     /* Stop if we reached the end of the packet or stuffing bytes */
1210     while( i_data_offset < TS_PACKET_SIZE && p_ts_packet->buffer[i_data_offset] != 0xFF );
1211
1212     /* Relase the TS packet, we don't need it anymore */
1213     input_NetlistFreeTS( p_input, p_ts_packet );
1214
1215 #undef p_psi  
1216 }