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