1 /*****************************************************************************
2 * input.c: input thread
3 * Read an MPEG2 stream, demultiplex and parse it before sending it to
5 *****************************************************************************
6 * Copyright (C) 1998, 1999, 2000 VideoLAN
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.
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.
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 *****************************************************************************/
26 /*****************************************************************************
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() */
34 #include <stdlib.h> /* free() */
35 #include <netinet/in.h> /* ntohs() */
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"
53 #include "audio_output.h" /* aout_thread_t */
55 #include "audio_decoder.h" /* adec_thread_t */
57 #include "ac3_decoder.h" /* ac3dec_t (for ac3_decoder_thread.h) */
58 #include "ac3_decoder_thread.h" /* ac3dec_thread_t */
60 #include "video.h" /* picture_t (for video_output.h) */
61 #include "video_output.h" /* vout_thread_t */
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 */
70 #include "spu_decoder.h" /* spudec_thread_t */
74 /*****************************************************************************
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 );
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 );
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 )
107 input_thread_t * p_input; /* thread descriptor */
108 int i_status; /* thread status */
109 int i_index; /* index for tables initialization */
111 /* Allocate descriptor */
113 p_input = (input_thread_t *)malloc( sizeof(input_thread_t) );
114 if( p_input == NULL )
116 intf_ErrMsg("error: %s\n", strerror(ENOMEM));
120 /* Initialize thread properties */
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;
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;
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;
138 case INPUT_METHOD_TS_VLAN_BCAST: /* vlan network method */
139 if( !p_main->b_vlans )
141 intf_ErrMsg("error: vlans are not activated\n");
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;
154 intf_ErrMsg("error: unknow input method\n");
160 /* Initialize stream description */
161 for( i_index = 0; i_index < INPUT_MAX_ES; i_index++ )
163 p_input->p_es[i_index].i_id = EMPTY_PID;
164 p_input->pp_selected_es[i_index] = NULL;
167 /* Initialize default settings for spawned decoders */
168 p_input->p_aout = p_aout;
169 p_input->p_vout = p_vout;
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;
180 /* Initialize PSI and PCR decoders */
181 if( input_PsiInit( p_input ) )
187 if( input_PcrInit( p_input ) )
189 input_PsiEnd( p_input );
194 /* Initialize netlists */
195 if( input_NetlistInit( p_input ) )
197 input_PsiEnd( p_input );
198 input_PcrEnd( p_input );
203 intf_DbgMsg("configuration: method=%d, source=%s, port=%d, vlan=%d\n",
204 i_method, psz_source, i_port, i_vlan );
206 /* Let the appropriate method open the socket. */
207 if( p_input->p_Open( p_input ) )
209 input_NetlistEnd( p_input );
210 input_PsiEnd( p_input );
211 input_PcrEnd( p_input );
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) )
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 );
231 intf_Msg("Input initialized\n");
233 /* If status is NULL, wait until the thread is created */
234 if( pi_status == NULL )
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 )
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 )
256 int i_status; /* thread status */
259 p_input->pi_status = (pi_status != NULL) ? pi_status : &i_status;
260 *p_input->pi_status = THREAD_DESTROY;
262 /* Request thread destruction */
265 /* If status is NULL, wait until thread has been destroyed */
266 if( pi_status == NULL )
270 msleep( THREAD_SLEEP );
271 }while( (i_status != THREAD_OVER) && (i_status != THREAD_ERROR)
272 && (i_status != THREAD_FATAL) );
277 /*****************************************************************************
278 * input_OpenAudioStream: open an audio stream
279 *****************************************************************************
280 * This function spawns an audio decoder and plugs it on the audio output
282 *****************************************************************************/
283 int input_OpenAudioStream( input_thread_t *p_input, int i_id )
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 )
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 )
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 )
320 /* following functions are local */
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 )
331 /* Mark thread as running and return */
333 *p_input->pi_status = THREAD_READY;
334 intf_DbgMsg("thread ready\n");
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 )
346 * Initialize thread and free configuration
348 p_input->b_error = InitThread( p_input );
349 if( p_input->b_error )
351 free( p_input ); /* destroy descriptor */
359 while( !p_input->b_die && !p_input->b_error )
361 /* Scatter read the UDP packet from the network or the file. */
362 if( (input_ReadPacket( p_input )) == (-1) )
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;
377 if( p_input->b_error )
379 ErrorThread( p_input );
383 EndThread( p_input );
384 intf_DbgMsg("thread end\n");
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 )
395 /* Wait until a `die' order */
397 while( !p_input->b_die )
400 msleep( VOUT_IDLE_SLEEP );
404 /*****************************************************************************
405 * EndThread: end the input thread
406 *****************************************************************************/
407 static void EndThread( input_thread_t * p_input )
409 int * pi_status; /* threas status */
410 int i_es_loop; /* es index */
414 pi_status = p_input->pi_status;
415 *pi_status = THREAD_END;
417 /* Close input method */
418 p_input->p_Close( p_input );
420 /* Destroy all decoder threads */
422 (i_es_loop < INPUT_MAX_ES) && (p_input->pp_selected_es[i_es_loop] != NULL) ;
425 switch( p_input->pp_selected_es[i_es_loop]->i_type )
430 vdec_DestroyThread( (vdec_thread_t*)(p_input->pp_selected_es[i_es_loop]->p_dec) /*, NULL */ );
432 vpar_DestroyThread( (vpar_thread_t*)(p_input->pp_selected_es[i_es_loop]->p_dec) /*, NULL */ );
437 adec_DestroyThread( (adec_thread_t*)(p_input->pp_selected_es[i_es_loop]->p_dec) );
440 ac3dec_DestroyThread( (ac3dec_thread_t *)(p_input->pp_selected_es[i_es_loop]->p_dec) );
443 spudec_DestroyThread( (spudec_thread_t *)(p_input->pp_selected_es[i_es_loop]->p_dec) );
446 /* Special streams for the PSI decoder, PID 0 and 1 */
450 intf_DbgMsg("error: unknown decoder type %d\n", p_input->pp_selected_es[i_es_loop]->i_type );
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 */
462 *pi_status = THREAD_OVER;
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 )
470 int i_base_index; /* index of the first free iovec */
473 #ifdef INPUT_LIFO_TS_NETLIST
474 int i_meanwhile_released;
475 int i_currently_removed;
477 ts_packet_t * p_ts_packet;
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;
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 )
487 intf_ErrMsg("input error: TS netlist is empty !\n");
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 )
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)
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) );
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 )
509 intf_ErrMsg("input error: TS netlist is empty !\n");
512 #endif /* FIFO netlist */
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) )
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);
526 intf_ErrMsg("input error: readv() failed (%s)\n", strerror(errno));
530 if( i_packet_size == 0 )
532 /* No packet has been received, so stop here. */
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;
541 /* BTW, something REALLY bad could happen if we receive packets with
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) */
547 /* Find out if we need this packet and demultiplex. */
548 input_SortPacket( p_input /* for current PIDs and netlist */,
552 if( i_packet_size > 0 )
554 intf_ErrMsg("input error: wrong size\n");
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 );
563 i_meanwhile_released = i_base_index - p_input->netlist.i_ts_index;
564 if( i_meanwhile_released )
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.
571 BTW, that explains why the TS netlist is
572 (INPUT_MAX_TS +1) + (TS_READ_ONCE -1) large. */
574 i_currently_removed = i_current_index - i_base_index;
575 if( i_meanwhile_released < i_currently_removed )
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) );
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) );
592 /* Update i_netlist_index with the information gathered above. */
593 p_input->netlist.i_ts_index += i_currently_removed;
597 /* Nothing happened. */
598 p_input->netlist.i_ts_index = i_current_index;
601 vlc_mutex_unlock( &p_input->netlist.lock );
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;
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;
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 )
624 /* Verify that sync_byte, error_indicator and scrambling_control are
626 if( !(p_ts_packet->buffer[0] == 0x47) || (p_ts_packet->buffer[1] & 0x80) ||
627 (p_ts_packet->buffer[3] & 0xc0) )
629 intf_DbgMsg("input debug: invalid TS header (%p)\n", p_ts_packet);
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;
637 //intf_DbgMsg("input debug: pid %d received (%p)\n",
638 // i_current_pid, p_ts_packet);
640 /* Lock current ES state. */
641 vlc_mutex_lock( &p_input->es_lock );
643 /* Verify that we actually want this PID. */
644 for( i_es_loop = 0; i_es_loop < INPUT_MAX_SELECTED_ES; i_es_loop++ )
646 if( p_input->pp_selected_es[i_es_loop] != NULL)
648 if( (*p_input->pp_selected_es[i_es_loop]).i_id
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 );
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] );
666 /* pp_selected_es should not contain any hole. */
670 vlc_mutex_unlock( &p_input->es_lock );
673 /* We weren't interested in receiving this packet. Give it back to the
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 );
679 p_input->c_packets_trashed++;
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 )
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 ? */
701 ASSERT(p_es_descriptor);
703 #define p (p_ts_packet->buffer)
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);
709 p_es_descriptor->c_packets++;
710 p_es_descriptor->c_bytes += TS_PACKET_SIZE;
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);
718 /* Extract adaption field informations if any */
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;
727 /* p[4] is adaptation_field_length minus one */
728 p_ts_packet->i_payload_start = 5 + p[4];
730 /* The adaption field can be limited to the adaptation_field_length byte,
731 so that there is nothing to do: skip this possibility */
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) )
739 intf_DbgMsg("input debug: invalid TS adaptation field (%p)\n",
742 p_es_descriptor->c_invalid_packets++;
747 /* No we are sure that the byte containing flags is present: read it */
750 /* discontinuity_indicator */
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);
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;
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;
766 /* random_access_indicator */
767 p_es_descriptor->b_random |= p[5] & 0x40;
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) )
773 /* There should be a PCR field in the packet, check if the
774 adaption field is long enough to carry it */
777 /* Call the PCR decoder */
778 input_PcrDecode( p_input, p_es_descriptor, &p[6] );
785 /* Check the continuity of the stream. */
786 i_dummy = ((p[3] & 0x0f) - p_es_descriptor->i_continuity_counter) & 0x0f;
789 /* Everything is ok, just increase our counter */
790 p_es_descriptor->i_continuity_counter++;
794 if( !b_payload && i_dummy == 0 )
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");
802 else if( i_dummy <= 0 )
804 /* Duplicate packet: mark it as being to be trashed. */
805 intf_DbgMsg("Duplicate packet received by TS demux\n");
808 else if( p_es_descriptor->i_continuity_counter == 0xFF )
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);
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,
828 p_es_descriptor->i_continuity_counter = p[3] & 0x0f;
832 /* Trash the packet if it has no payload or if it is bad */
835 input_NetlistFreeTS( p_input, p_ts_packet );
837 p_input->c_packets_trashed++;
842 if( p_es_descriptor->b_psi )
844 /* The payload contains PSI tables */
845 input_DemuxPSI( p_input, p_ts_packet, p_es_descriptor,
846 b_unit_start, b_lost );
850 /* The payload carries a PES stream */
851 input_DemuxPES( p_input, p_ts_packet, p_es_descriptor,
852 b_unit_start, b_lost );
862 /*****************************************************************************
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 )
873 decoder_fifo_t * p_fifo;
874 u8 i_pes_header_size;
876 pes_packet_t* p_last_pes;
878 int i_ts_payload_size;
881 #define p_pes (p_es_descriptor->p_pes_packet)
885 ASSERT(p_es_descriptor);
887 //intf_DbgMsg("PES-demultiplexing %p (%p)\n", p_ts_packet, p_pes);
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
892 if( b_packet_lost && p_pes != NULL )
894 intf_DbgMsg("PES %p trashed because of packet lost\n", p_pes);
895 input_NetlistFreePES( p_input, p_pes );
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 )
904 //intf_DbgMsg("End of PES packet %p\n", p_pes);
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
909 p_ts = p_pes->p_first_ts;
910 i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
913 if(i_ts_payload_size >= PES_HEADER_SIZE)
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]);
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 )
928 p_pes->p_pes_header_save = malloc(PES_HEADER_SIZE);
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;
937 p_ts = p_ts->p_next_ts;
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 );
952 i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
954 while(i_ts_payload_size + i_dummy < PES_HEADER_SIZE);
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);
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;
966 /* Now we have the part of the PES header we were interested in:
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 */
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 );
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];
991 switch( p_pes->i_stream_id )
993 case 0xBE: /* Padding */
994 case 0xBC: /* Program stream map */
995 case 0xBF: /* Private stream 2 */
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;
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;
1012 /* Now parse the optional header extensions (in the limit of
1014 if( p_pes->b_has_pts )
1016 pcr_descriptor_t * p_pcr;
1018 p_pcr = p_input->p_pcr;
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;
1026 if( p_pcr->i_synchro_state )
1028 switch( p_pcr->i_synchro_state )
1030 case SYNCHRO_NOT_STARTED:
1031 p_pes->b_has_pts = 0;
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;
1041 case SYNCHRO_REINIT: /* We skip a PES */
1042 p_pes->b_has_pts = 0;
1043 p_pcr->i_synchro_state = SYNCHRO_START;
1049 p_pes->i_pts += p_pcr->delta_pcr + p_pcr->delta_absolute;
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 )
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
1069 p_ts = p_ts->p_next_ts;
1070 i_ts_payload_size = p_ts->i_payload_end - p_ts->i_payload_start;
1072 /* This last packet is partly header, partly payload. */
1073 p_ts->i_payload_start += i_pes_header_size;
1076 /* Now we can eventually put the PES packet in the decoder's
1078 switch( p_es_descriptor->i_type )
1080 case MPEG1_VIDEO_ES:
1081 case MPEG2_VIDEO_ES:
1083 p_fifo = &(((vdec_thread_t*)(p_es_descriptor->p_dec))->fifo);
1085 p_fifo = &(((vpar_thread_t*)(p_es_descriptor->p_dec))->fifo);
1089 case MPEG1_AUDIO_ES:
1090 case MPEG2_AUDIO_ES:
1091 p_fifo = &(((adec_thread_t*)(p_es_descriptor->p_dec))->fifo);
1096 /* we skip 4 bytes at the beginning of the AC3 payload */
1097 p_ts->i_payload_start += 4;
1099 p_fifo = &(((ac3dec_thread_t *)(p_es_descriptor->p_dec))->fifo);
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);
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);
1116 if( p_fifo != NULL )
1118 vlc_mutex_lock( &p_fifo->data_lock );
1119 if( DECODER_FIFO_ISFULL( *p_fifo ) )
1121 /* The FIFO is full !!! This should not happen. */
1123 p_input->c_packets_trashed += p_pes->i_ts_packets;
1124 p_es_descriptor->c_invalid_packets += p_pes->i_ts_packets;
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);
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 );
1137 /* Warn the decoder that it's got work to do. */
1138 vlc_cond_signal( &p_fifo->data_wait );
1140 vlc_mutex_unlock( &p_fifo->data_lock );
1144 intf_DbgMsg("No fifo to receive PES %p: trash\n", p_pes);
1146 p_input->c_packets_trashed += p_pes->i_ts_packets;
1147 p_es_descriptor->c_invalid_packets += p_pes->i_ts_packets;
1149 input_NetlistFreePES( p_input, p_pes );
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 */
1163 /* Get a new one PES from the PES netlist. */
1164 if( (p_pes = input_NetlistGetPES( p_input )) == (NULL) )
1166 /* PES netlist is empty ! */
1167 p_input->b_error = 1;
1171 //intf_DbgMsg("New PES packet %p (first TS: %p)\n", p_pes, p_ts_packet);
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;
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
1182 p_pes->b_data_loss = 1;
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;
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
1196 //intf_DbgMsg("Adding TS %p to PES %p\n", p_ts_packet, p_pes);
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;
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 )
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;
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;
1220 i_dummy = p_ts_packet->i_payload_end - p_ts_packet->i_payload_start;
1221 p_es_descriptor->c_payload_bytes += i_dummy;
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 );
1238 /*****************************************************************************
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 )
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 ? */
1254 ASSERT(p_ts_packet);
1255 ASSERT(p_es_descriptor);
1257 #define p_psi (p_es_descriptor->p_psi_section)
1259 //intf_DbgMsg( "input debug: PSI demultiplexing %p (%p)\n", p_ts_packet, p_input);
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);
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;
1270 /* Has the reassembly of a section already began in a previous packet ? */
1271 if( p_psi->b_running_section )
1273 /* Was data lost since the last TS packet ? */
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" );
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 */
1289 //intf_DbgMsg( "New part of the section received at offset %d\n", i_data_offset );
1292 /* We are looking for the beginning of a new section */
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 );
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" );
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;
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 )
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 )
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 )
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" );
1339 /* Init the reassembly of that section */
1340 p_psi->b_running_section = 1;
1341 p_psi->i_current_position = 0;
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;
1348 i_data_length = p_psi->i_length - p_psi->i_current_position;
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],
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;
1358 /* Decode the packet if it is now complete */
1359 if (p_psi->i_length == p_psi->i_current_position + i_data_length)
1361 /* Packet is complete, decode it */
1362 //intf_DbgMsg( "SECTION COMPLETE: starting decoding of its data\n" );
1363 input_PsiDecode( p_input, p_psi );
1365 /* Prepare the buffer to receive a new section */
1366 p_psi->i_current_position = 0;
1367 p_psi->b_running_section = 0;
1369 /* The new section won't be the first anymore */
1370 //b_first_section = 0;
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" );
1379 //intf_DbgMsg( "Must loop ? Next data offset: %d, stuffing: %d\n",
1380 // i_data_offset, p_ts_packet->buffer[i_data_offset] );
1383 /* Relase the TS packet, we don't need it anymore */
1384 input_NetlistFreeTS( p_input, p_ts_packet );