2 * MPEG2 transport stream (aka DVB) demuxer
3 * Copyright (c) 2002-2003 Fabrice Bellard
5 * This file is part of FFmpeg.
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 #include "libavutil/crc.h"
26 #include "libavutil/intreadwrite.h"
27 #include "libavcodec/bytestream.h"
32 /* 1.0 second at 24Mbit/s */
33 #define MAX_SCAN_PACKETS 32000
35 /* maximum size in which we look for synchronisation if
36 synchronisation is lost */
37 #define MAX_RESYNC_SIZE 4096
39 #define MAX_PES_PAYLOAD 200*1024
41 typedef struct PESContext PESContext
;
43 static PESContext
* add_pes_stream(MpegTSContext
*ts
, int pid
, int pcr_pid
, int stream_type
);
45 enum MpegTSFilterType
{
50 typedef struct MpegTSFilter MpegTSFilter
;
52 typedef int PESCallback(MpegTSFilter
*f
, const uint8_t *buf
, int len
, int is_start
, int64_t pos
);
54 typedef struct MpegTSPESFilter
{
59 typedef void SectionCallback(MpegTSFilter
*f
, const uint8_t *buf
, int len
);
61 typedef void SetServiceCallback(void *opaque
, int ret
);
63 typedef struct MpegTSSectionFilter
{
67 unsigned int check_crc
:1;
68 unsigned int end_of_section_reached
:1;
69 SectionCallback
*section_cb
;
71 } MpegTSSectionFilter
;
75 int last_cc
; /* last cc code (-1 if first packet) */
76 enum MpegTSFilterType type
;
78 MpegTSPESFilter pes_filter
;
79 MpegTSSectionFilter section_filter
;
83 #define MAX_PIDS_PER_PROGRAM 64
85 unsigned int id
; //program id/service id
87 unsigned int pids
[MAX_PIDS_PER_PROGRAM
];
90 struct MpegTSContext
{
92 AVFormatContext
*stream
;
93 /** raw packet size, including FEC if present */
98 /** if true, all pids are analyzed to find streams */
101 /** compute exact PCR for each transport stream packet */
102 int mpeg2ts_compute_pcr
;
104 int64_t cur_pcr
; /**< used to estimate the exact PCR */
105 int pcr_incr
; /**< used to estimate the exact PCR */
107 /* data needed to handle file based ts */
108 /** stop parsing loop */
110 /** packet containing Audio/Video data */
112 /** to detect seek */
115 /******************************************/
116 /* private mpegts data */
118 /** structure to keep track of Program->pids mapping */
123 /** filters for various streams specified by PMT + for the PAT and PMT */
124 MpegTSFilter
*pids
[NB_PID_MAX
];
127 /* TS stream handling */
131 MPEGTS_PESHEADER_FILL
,
136 /* enough for PES header + length */
137 #define PES_START_SIZE 9
138 #define MAX_PES_HEADER_SIZE (9 + 255)
142 int pcr_pid
; /**< if -1 then all packets containing PCR are considered */
145 AVFormatContext
*stream
;
147 enum MpegTSState state
;
148 /* used to get the format */
153 int64_t ts_packet_pos
; /**< position of first TS packet of this PES packet */
154 uint8_t header
[MAX_PES_HEADER_SIZE
];
158 extern AVInputFormat mpegts_demuxer
;
160 static void clear_program(MpegTSContext
*ts
, unsigned int programid
)
164 for(i
=0; i
<ts
->nb_prg
; i
++)
165 if(ts
->prg
[i
].id
== programid
)
166 ts
->prg
[i
].nb_pids
= 0;
169 static void clear_programs(MpegTSContext
*ts
)
175 static void add_pat_entry(MpegTSContext
*ts
, unsigned int programid
)
178 void *tmp
= av_realloc(ts
->prg
, (ts
->nb_prg
+1)*sizeof(struct Program
));
182 p
= &ts
->prg
[ts
->nb_prg
];
188 static void add_pid_to_pmt(MpegTSContext
*ts
, unsigned int programid
, unsigned int pid
)
191 struct Program
*p
= NULL
;
192 for(i
=0; i
<ts
->nb_prg
; i
++) {
193 if(ts
->prg
[i
].id
== programid
) {
201 if(p
->nb_pids
>= MAX_PIDS_PER_PROGRAM
)
203 p
->pids
[p
->nb_pids
++] = pid
;
207 * \brief discard_pid() decides if the pid is to be discarded according
208 * to caller's programs selection
209 * \param ts : - TS context
211 * \return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL
214 static int discard_pid(MpegTSContext
*ts
, unsigned int pid
)
217 int used
= 0, discarded
= 0;
219 for(i
=0; i
<ts
->nb_prg
; i
++) {
221 for(j
=0; j
<p
->nb_pids
; j
++) {
222 if(p
->pids
[j
] != pid
)
224 //is program with id p->id set to be discarded?
225 for(k
=0; k
<ts
->stream
->nb_programs
; k
++) {
226 if(ts
->stream
->programs
[k
]->id
== p
->id
) {
227 if(ts
->stream
->programs
[k
]->discard
== AVDISCARD_ALL
)
236 return !used
&& discarded
;
240 * Assembles PES packets out of TS packets, and then calls the "section_cb"
241 * function when they are complete.
243 static void write_section_data(AVFormatContext
*s
, MpegTSFilter
*tss1
,
244 const uint8_t *buf
, int buf_size
, int is_start
)
246 MpegTSSectionFilter
*tss
= &tss1
->u
.section_filter
;
250 memcpy(tss
->section_buf
, buf
, buf_size
);
251 tss
->section_index
= buf_size
;
252 tss
->section_h_size
= -1;
253 tss
->end_of_section_reached
= 0;
255 if (tss
->end_of_section_reached
)
257 len
= 4096 - tss
->section_index
;
260 memcpy(tss
->section_buf
+ tss
->section_index
, buf
, len
);
261 tss
->section_index
+= len
;
264 /* compute section length if possible */
265 if (tss
->section_h_size
== -1 && tss
->section_index
>= 3) {
266 len
= (AV_RB16(tss
->section_buf
+ 1) & 0xfff) + 3;
269 tss
->section_h_size
= len
;
272 if (tss
->section_h_size
!= -1 && tss
->section_index
>= tss
->section_h_size
) {
273 tss
->end_of_section_reached
= 1;
274 if (!tss
->check_crc
||
275 av_crc(av_crc_get_table(AV_CRC_32_IEEE
), -1,
276 tss
->section_buf
, tss
->section_h_size
) == 0)
277 tss
->section_cb(tss1
, tss
->section_buf
, tss
->section_h_size
);
281 static MpegTSFilter
*mpegts_open_section_filter(MpegTSContext
*ts
, unsigned int pid
,
282 SectionCallback
*section_cb
, void *opaque
,
286 MpegTSFilter
*filter
;
287 MpegTSSectionFilter
*sec
;
289 dprintf(ts
->stream
, "Filter: pid=0x%x\n", pid
);
291 if (pid
>= NB_PID_MAX
|| ts
->pids
[pid
])
293 filter
= av_mallocz(sizeof(MpegTSFilter
));
296 ts
->pids
[pid
] = filter
;
297 filter
->type
= MPEGTS_SECTION
;
299 filter
->last_cc
= -1;
300 sec
= &filter
->u
.section_filter
;
301 sec
->section_cb
= section_cb
;
302 sec
->opaque
= opaque
;
303 sec
->section_buf
= av_malloc(MAX_SECTION_SIZE
);
304 sec
->check_crc
= check_crc
;
305 if (!sec
->section_buf
) {
312 static MpegTSFilter
*mpegts_open_pes_filter(MpegTSContext
*ts
, unsigned int pid
,
316 MpegTSFilter
*filter
;
317 MpegTSPESFilter
*pes
;
319 if (pid
>= NB_PID_MAX
|| ts
->pids
[pid
])
321 filter
= av_mallocz(sizeof(MpegTSFilter
));
324 ts
->pids
[pid
] = filter
;
325 filter
->type
= MPEGTS_PES
;
327 filter
->last_cc
= -1;
328 pes
= &filter
->u
.pes_filter
;
329 pes
->pes_cb
= pes_cb
;
330 pes
->opaque
= opaque
;
334 static void mpegts_close_filter(MpegTSContext
*ts
, MpegTSFilter
*filter
)
339 if (filter
->type
== MPEGTS_SECTION
)
340 av_freep(&filter
->u
.section_filter
.section_buf
);
341 else if (filter
->type
== MPEGTS_PES
) {
342 PESContext
*pes
= filter
->u
.pes_filter
.opaque
;
343 av_freep(&pes
->buffer
);
344 /* referenced private data will be freed later in
345 * av_close_input_stream */
346 if (!((PESContext
*)filter
->u
.pes_filter
.opaque
)->st
) {
347 av_freep(&filter
->u
.pes_filter
.opaque
);
352 ts
->pids
[pid
] = NULL
;
355 static int analyze(const uint8_t *buf
, int size
, int packet_size
, int *index
){
356 int stat
[packet_size
];
361 memset(stat
, 0, packet_size
*sizeof(int));
363 for(x
=i
=0; i
<size
-3; i
++){
364 if(buf
[i
] == 0x47 && !(buf
[i
+1] & 0x80) && (buf
[i
+3] & 0x30)){
366 if(stat
[x
] > best_score
){
373 if(x
== packet_size
) x
= 0;
379 /* autodetect fec presence. Must have at least 1024 bytes */
380 static int get_packet_size(const uint8_t *buf
, int size
)
382 int score
, fec_score
, dvhs_score
;
384 if (size
< (TS_FEC_PACKET_SIZE
* 5 + 1))
387 score
= analyze(buf
, size
, TS_PACKET_SIZE
, NULL
);
388 dvhs_score
= analyze(buf
, size
, TS_DVHS_PACKET_SIZE
, NULL
);
389 fec_score
= analyze(buf
, size
, TS_FEC_PACKET_SIZE
, NULL
);
390 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
392 if (score
> fec_score
&& score
> dvhs_score
) return TS_PACKET_SIZE
;
393 else if(dvhs_score
> score
&& dvhs_score
> fec_score
) return TS_DVHS_PACKET_SIZE
;
394 else if(score
< fec_score
&& dvhs_score
< fec_score
) return TS_FEC_PACKET_SIZE
;
398 typedef struct SectionHeader
{
403 uint8_t last_sec_num
;
406 static inline int get8(const uint8_t **pp
, const uint8_t *p_end
)
419 static inline int get16(const uint8_t **pp
, const uint8_t *p_end
)
425 if ((p
+ 1) >= p_end
)
433 /* read and allocate a DVB string preceeded by its length */
434 static char *getstr8(const uint8_t **pp
, const uint8_t *p_end
)
441 len
= get8(&p
, p_end
);
444 if ((p
+ len
) > p_end
)
446 str
= av_malloc(len
+ 1);
456 static int parse_section_header(SectionHeader
*h
,
457 const uint8_t **pp
, const uint8_t *p_end
)
461 val
= get8(pp
, p_end
);
466 val
= get16(pp
, p_end
);
470 val
= get8(pp
, p_end
);
473 h
->version
= (val
>> 1) & 0x1f;
474 val
= get8(pp
, p_end
);
478 val
= get8(pp
, p_end
);
481 h
->last_sec_num
= val
;
486 uint32_t stream_type
;
487 enum CodecType codec_type
;
488 enum CodecID codec_id
;
491 static const StreamType ISO_types
[] = {
492 { 0x01, CODEC_TYPE_VIDEO
, CODEC_ID_MPEG2VIDEO
},
493 { 0x02, CODEC_TYPE_VIDEO
, CODEC_ID_MPEG2VIDEO
},
494 { 0x03, CODEC_TYPE_AUDIO
, CODEC_ID_MP3
},
495 { 0x04, CODEC_TYPE_AUDIO
, CODEC_ID_MP3
},
496 { 0x0f, CODEC_TYPE_AUDIO
, CODEC_ID_AAC
},
497 { 0x10, CODEC_TYPE_VIDEO
, CODEC_ID_MPEG4
},
498 { 0x1b, CODEC_TYPE_VIDEO
, CODEC_ID_H264
},
499 { 0xd1, CODEC_TYPE_VIDEO
, CODEC_ID_DIRAC
},
500 { 0xea, CODEC_TYPE_VIDEO
, CODEC_ID_VC1
},
504 static const StreamType HDMV_types
[] = {
505 { 0x81, CODEC_TYPE_AUDIO
, CODEC_ID_AC3
},
506 { 0x82, CODEC_TYPE_AUDIO
, CODEC_ID_DTS
},
511 static const StreamType MISC_types
[] = {
512 { 0x81, CODEC_TYPE_AUDIO
, CODEC_ID_AC3
},
513 { 0x8a, CODEC_TYPE_AUDIO
, CODEC_ID_DTS
},
517 static const StreamType REGD_types
[] = {
518 { MKTAG('d','r','a','c'), CODEC_TYPE_VIDEO
, CODEC_ID_DIRAC
},
519 { MKTAG('A','C','-','3'), CODEC_TYPE_AUDIO
, CODEC_ID_AC3
},
523 /* descriptor present */
524 static const StreamType DESC_types
[] = {
525 { 0x6a, CODEC_TYPE_AUDIO
, CODEC_ID_AC3
}, /* AC-3 descriptor */
526 { 0x7a, CODEC_TYPE_AUDIO
, CODEC_ID_EAC3
}, /* E-AC-3 descriptor */
527 { 0x7b, CODEC_TYPE_AUDIO
, CODEC_ID_DTS
},
528 { 0x59, CODEC_TYPE_SUBTITLE
, CODEC_ID_DVB_SUBTITLE
}, /* subtitling descriptor */
531 static void mpegts_find_stream_type(AVStream
*st
,
532 uint32_t stream_type
, const StreamType
*types
)
534 for (; types
->stream_type
; types
++) {
535 if (stream_type
== types
->stream_type
) {
536 st
->codec
->codec_type
= types
->codec_type
;
537 st
->codec
->codec_id
= types
->codec_id
;
543 static AVStream
*new_pes_av_stream(PESContext
*pes
, uint32_t prog_reg_desc
, uint32_t code
)
545 AVStream
*st
= av_new_stream(pes
->stream
, pes
->pid
);
550 av_set_pts_info(st
, 33, 1, 90000);
552 st
->codec
->codec_type
= CODEC_TYPE_DATA
;
553 st
->codec
->codec_id
= CODEC_ID_PROBE
;
554 st
->need_parsing
= AVSTREAM_PARSE_FULL
;
557 dprintf(pes
->stream
, "stream_type=%x pid=%x prog_reg_desc=%.4s\n",
558 pes
->stream_type
, pes
->pid
, (char*)&prog_reg_desc
);
560 st
->codec
->codec_tag
= pes
->stream_type
;
562 mpegts_find_stream_type(st
, pes
->stream_type
, ISO_types
);
563 if (prog_reg_desc
== AV_RL32("HDMV") &&
564 st
->codec
->codec_id
== CODEC_ID_PROBE
)
565 mpegts_find_stream_type(st
, pes
->stream_type
, HDMV_types
);
566 if (st
->codec
->codec_id
== CODEC_ID_PROBE
)
567 mpegts_find_stream_type(st
, pes
->stream_type
, MISC_types
);
569 /* stream was not present in PMT, guess based on PES start code */
570 if (st
->codec
->codec_id
== CODEC_ID_PROBE
) {
571 if (code
>= 0x1c0 && code
<= 0x1df) {
572 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
573 st
->codec
->codec_id
= CODEC_ID_MP2
;
574 } else if (code
== 0x1bd) {
575 st
->codec
->codec_type
= CODEC_TYPE_AUDIO
;
576 st
->codec
->codec_id
= CODEC_ID_AC3
;
583 static void pmt_cb(MpegTSFilter
*filter
, const uint8_t *section
, int section_len
)
585 MpegTSContext
*ts
= filter
->u
.section_filter
.opaque
;
586 SectionHeader h1
, *h
= &h1
;
589 const uint8_t *p
, *p_end
, *desc_list_end
, *desc_end
;
590 int program_info_length
, pcr_pid
, pid
, stream_type
;
591 int desc_list_len
, desc_len
, desc_tag
;
592 int comp_page
, anc_page
;
594 uint32_t prog_reg_desc
= 0; /* registration descriptor */
597 dprintf(ts
->stream
, "PMT: len %i\n", section_len
);
598 av_hex_dump_log(ts
->stream
, AV_LOG_DEBUG
, (uint8_t *)section
, section_len
);
601 p_end
= section
+ section_len
- 4;
603 if (parse_section_header(h
, &p
, p_end
) < 0)
606 dprintf(ts
->stream
, "sid=0x%x sec_num=%d/%d\n",
607 h
->id
, h
->sec_num
, h
->last_sec_num
);
609 if (h
->tid
!= PMT_TID
)
612 clear_program(ts
, h
->id
);
613 pcr_pid
= get16(&p
, p_end
) & 0x1fff;
616 add_pid_to_pmt(ts
, h
->id
, pcr_pid
);
618 dprintf(ts
->stream
, "pcr_pid=0x%x\n", pcr_pid
);
620 program_info_length
= get16(&p
, p_end
) & 0xfff;
621 if (program_info_length
< 0)
623 while(program_info_length
>= 2) {
625 tag
= get8(&p
, p_end
);
626 len
= get8(&p
, p_end
);
627 if(len
> program_info_length
- 2)
628 //something else is broken, exit the program_descriptors_loop
630 program_info_length
-= len
+ 2;
631 if(tag
== 0x05 && len
>= 4) { // registration descriptor
632 prog_reg_desc
= bytestream_get_le32(&p
);
637 p
+= program_info_length
;
642 stream_type
= get8(&p
, p_end
);
645 pid
= get16(&p
, p_end
) & 0x1fff;
649 /* now create ffmpeg stream */
650 if (ts
->pids
[pid
] && ts
->pids
[pid
]->type
== MPEGTS_PES
) {
651 pes
= ts
->pids
[pid
]->u
.pes_filter
.opaque
;
654 if (ts
->pids
[pid
]) mpegts_close_filter(ts
, ts
->pids
[pid
]); //wrongly added sdt filter probably
655 pes
= add_pes_stream(ts
, pid
, pcr_pid
, stream_type
);
657 st
= new_pes_av_stream(pes
, prog_reg_desc
, 0);
663 add_pid_to_pmt(ts
, h
->id
, pid
);
665 av_program_add_stream_index(ts
->stream
, h
->id
, st
->index
);
667 desc_list_len
= get16(&p
, p_end
) & 0xfff;
668 if (desc_list_len
< 0)
670 desc_list_end
= p
+ desc_list_len
;
671 if (desc_list_end
> p_end
)
674 desc_tag
= get8(&p
, desc_list_end
);
677 desc_len
= get8(&p
, desc_list_end
);
680 desc_end
= p
+ desc_len
;
681 if (desc_end
> desc_list_end
)
684 dprintf(ts
->stream
, "tag: 0x%02x len=%d\n",
687 if (st
->codec
->codec_id
== CODEC_ID_PROBE
&&
688 stream_type
== STREAM_TYPE_PRIVATE_DATA
)
689 mpegts_find_stream_type(st
, desc_tag
, DESC_types
);
692 case 0x59: /* subtitling descriptor */
693 language
[0] = get8(&p
, desc_end
);
694 language
[1] = get8(&p
, desc_end
);
695 language
[2] = get8(&p
, desc_end
);
698 comp_page
= get16(&p
, desc_end
);
699 anc_page
= get16(&p
, desc_end
);
700 st
->codec
->sub_id
= (anc_page
<< 16) | comp_page
;
701 av_metadata_set(&st
->metadata
, "language", language
);
703 case 0x0a: /* ISO 639 language descriptor */
704 language
[0] = get8(&p
, desc_end
);
705 language
[1] = get8(&p
, desc_end
);
706 language
[2] = get8(&p
, desc_end
);
708 av_metadata_set(&st
->metadata
, "language", language
);
710 case 0x05: /* registration descriptor */
711 st
->codec
->codec_tag
= bytestream_get_le32(&p
);
712 if (st
->codec
->codec_id
== CODEC_ID_PROBE
&&
713 stream_type
== STREAM_TYPE_PRIVATE_DATA
)
714 mpegts_find_stream_type(st
, st
->codec
->codec_tag
, REGD_types
);
723 /* all parameters are there */
725 mpegts_close_filter(ts
, filter
);
728 static void pat_cb(MpegTSFilter
*filter
, const uint8_t *section
, int section_len
)
730 MpegTSContext
*ts
= filter
->u
.section_filter
.opaque
;
731 SectionHeader h1
, *h
= &h1
;
732 const uint8_t *p
, *p_end
;
736 dprintf(ts
->stream
, "PAT:\n");
737 av_hex_dump_log(ts
->stream
, AV_LOG_DEBUG
, (uint8_t *)section
, section_len
);
739 p_end
= section
+ section_len
- 4;
741 if (parse_section_header(h
, &p
, p_end
) < 0)
743 if (h
->tid
!= PAT_TID
)
748 sid
= get16(&p
, p_end
);
751 pmt_pid
= get16(&p
, p_end
) & 0x1fff;
755 dprintf(ts
->stream
, "sid=0x%x pid=0x%x\n", sid
, pmt_pid
);
760 av_new_program(ts
->stream
, sid
);
762 mpegts_open_section_filter(ts
, pmt_pid
, pmt_cb
, ts
, 1);
763 add_pat_entry(ts
, sid
);
764 add_pid_to_pmt(ts
, sid
, 0); //add pat pid to program
765 add_pid_to_pmt(ts
, sid
, pmt_pid
);
771 mpegts_close_filter(ts
, filter
);
774 static void sdt_cb(MpegTSFilter
*filter
, const uint8_t *section
, int section_len
)
776 MpegTSContext
*ts
= filter
->u
.section_filter
.opaque
;
777 SectionHeader h1
, *h
= &h1
;
778 const uint8_t *p
, *p_end
, *desc_list_end
, *desc_end
;
779 int onid
, val
, sid
, desc_list_len
, desc_tag
, desc_len
, service_type
;
780 char *name
, *provider_name
;
783 dprintf(ts
->stream
, "SDT:\n");
784 av_hex_dump_log(ts
->stream
, AV_LOG_DEBUG
, (uint8_t *)section
, section_len
);
787 p_end
= section
+ section_len
- 4;
789 if (parse_section_header(h
, &p
, p_end
) < 0)
791 if (h
->tid
!= SDT_TID
)
793 onid
= get16(&p
, p_end
);
796 val
= get8(&p
, p_end
);
800 sid
= get16(&p
, p_end
);
803 val
= get8(&p
, p_end
);
806 desc_list_len
= get16(&p
, p_end
) & 0xfff;
807 if (desc_list_len
< 0)
809 desc_list_end
= p
+ desc_list_len
;
810 if (desc_list_end
> p_end
)
813 desc_tag
= get8(&p
, desc_list_end
);
816 desc_len
= get8(&p
, desc_list_end
);
817 desc_end
= p
+ desc_len
;
818 if (desc_end
> desc_list_end
)
821 dprintf(ts
->stream
, "tag: 0x%02x len=%d\n",
826 service_type
= get8(&p
, p_end
);
827 if (service_type
< 0)
829 provider_name
= getstr8(&p
, p_end
);
832 name
= getstr8(&p
, p_end
);
834 AVProgram
*program
= av_new_program(ts
->stream
, sid
);
836 av_metadata_set(&program
->metadata
, "name", name
);
837 av_metadata_set(&program
->metadata
, "provider_name", provider_name
);
841 av_free(provider_name
);
852 static int64_t get_pts(const uint8_t *p
)
854 int64_t pts
= (int64_t)((p
[0] >> 1) & 0x07) << 30;
855 pts
|= (AV_RB16(p
+ 1) >> 1) << 15;
856 pts
|= AV_RB16(p
+ 3) >> 1;
860 static void new_pes_packet(PESContext
*pes
, AVPacket
*pkt
)
864 pkt
->destruct
= av_destruct_packet
;
865 pkt
->data
= pes
->buffer
;
866 pkt
->size
= pes
->data_index
;
867 memset(pkt
->data
+pkt
->size
, 0, FF_INPUT_BUFFER_PADDING_SIZE
);
869 pkt
->stream_index
= pes
->st
->index
;
872 /* store position of first TS packet of this PES packet */
873 pkt
->pos
= pes
->ts_packet_pos
;
875 /* reset pts values */
876 pes
->pts
= AV_NOPTS_VALUE
;
877 pes
->dts
= AV_NOPTS_VALUE
;
882 /* return non zero if a packet could be constructed */
883 static int mpegts_push_data(MpegTSFilter
*filter
,
884 const uint8_t *buf
, int buf_size
, int is_start
,
887 PESContext
*pes
= filter
->u
.pes_filter
.opaque
;
888 MpegTSContext
*ts
= pes
->ts
;
896 if (pes
->state
== MPEGTS_PAYLOAD
&& pes
->data_index
> 0) {
897 new_pes_packet(pes
, ts
->pkt
);
900 pes
->state
= MPEGTS_HEADER
;
902 pes
->ts_packet_pos
= pos
;
905 while (buf_size
> 0) {
908 len
= PES_START_SIZE
- pes
->data_index
;
911 memcpy(pes
->header
+ pes
->data_index
, p
, len
);
912 pes
->data_index
+= len
;
915 if (pes
->data_index
== PES_START_SIZE
) {
916 /* we got all the PES or section header. We can now
919 av_hex_dump_log(pes
->stream
, AV_LOG_DEBUG
, pes
->header
, pes
->data_index
);
921 if (pes
->header
[0] == 0x00 && pes
->header
[1] == 0x00 &&
922 pes
->header
[2] == 0x01) {
923 /* it must be an mpeg2 PES stream */
924 code
= pes
->header
[3] | 0x100;
926 /* stream not present in PMT */
928 pes
->st
= new_pes_av_stream(pes
, 0, code
);
930 return AVERROR(ENOMEM
);
932 if (pes
->st
->discard
== AVDISCARD_ALL
||
933 !((code
>= 0x1c0 && code
<= 0x1df) ||
934 (code
>= 0x1e0 && code
<= 0x1ef) ||
935 (code
== 0x1bd) || (code
== 0x1fd)))
937 pes
->state
= MPEGTS_PESHEADER_FILL
;
938 pes
->total_size
= AV_RB16(pes
->header
+ 4);
939 /* NOTE: a zero total size means the PES size is
941 pes
->pes_header_size
= pes
->header
[8] + 9;
943 /* otherwise, it should be a table */
946 pes
->state
= MPEGTS_SKIP
;
951 /**********************************************/
952 /* PES packing parsing */
953 case MPEGTS_PESHEADER_FILL
:
954 len
= pes
->pes_header_size
- pes
->data_index
;
959 memcpy(pes
->header
+ pes
->data_index
, p
, len
);
960 pes
->data_index
+= len
;
963 if (pes
->data_index
== pes
->pes_header_size
) {
967 flags
= pes
->header
[7];
969 pes
->pts
= AV_NOPTS_VALUE
;
970 pes
->dts
= AV_NOPTS_VALUE
;
971 if ((flags
& 0xc0) == 0x80) {
972 pes
->dts
= pes
->pts
= get_pts(r
);
974 } else if ((flags
& 0xc0) == 0xc0) {
975 pes
->pts
= get_pts(r
);
977 pes
->dts
= get_pts(r
);
981 if (pes
->total_size
> pes
->data_index
- 6)
982 pes
->total_size
-= pes
->data_index
- 6;
984 pes
->total_size
= MAX_PES_PAYLOAD
;
985 /* allocate pes buffer */
986 pes
->buffer
= av_malloc(pes
->total_size
+FF_INPUT_BUFFER_PADDING_SIZE
);
988 return AVERROR(ENOMEM
);
990 /* we got the full header. We parse it and get the payload */
991 pes
->state
= MPEGTS_PAYLOAD
;
997 if (pes
->data_index
+buf_size
> pes
->total_size
) {
998 new_pes_packet(pes
, ts
->pkt
);
999 pes
->total_size
= MAX_PES_PAYLOAD
;
1000 pes
->buffer
= av_malloc(pes
->total_size
+FF_INPUT_BUFFER_PADDING_SIZE
);
1002 return AVERROR(ENOMEM
);
1005 memcpy(pes
->buffer
+pes
->data_index
, p
, buf_size
);
1006 pes
->data_index
+= buf_size
;
1019 static PESContext
*add_pes_stream(MpegTSContext
*ts
, int pid
, int pcr_pid
, int stream_type
)
1024 /* if no pid found, then add a pid context */
1025 pes
= av_mallocz(sizeof(PESContext
));
1029 pes
->stream
= ts
->stream
;
1031 pes
->pcr_pid
= pcr_pid
;
1032 pes
->stream_type
= stream_type
;
1033 tss
= mpegts_open_pes_filter(ts
, pid
, mpegts_push_data
, pes
);
1041 /* handle one TS packet */
1042 static int handle_packet(MpegTSContext
*ts
, const uint8_t *packet
)
1044 AVFormatContext
*s
= ts
->stream
;
1046 int len
, pid
, cc
, cc_ok
, afc
, is_start
;
1047 const uint8_t *p
, *p_end
;
1050 pid
= AV_RB16(packet
+ 1) & 0x1fff;
1051 if(pid
&& discard_pid(ts
, pid
))
1053 is_start
= packet
[1] & 0x40;
1054 tss
= ts
->pids
[pid
];
1055 if (ts
->auto_guess
&& tss
== NULL
&& is_start
) {
1056 add_pes_stream(ts
, pid
, -1, 0);
1057 tss
= ts
->pids
[pid
];
1062 /* continuity check (currently not used) */
1063 cc
= (packet
[3] & 0xf);
1064 cc_ok
= (tss
->last_cc
< 0) || ((((tss
->last_cc
+ 1) & 0x0f) == cc
));
1067 /* skip adaptation field */
1068 afc
= (packet
[3] >> 4) & 3;
1070 if (afc
== 0) /* reserved value */
1072 if (afc
== 2) /* adaptation field only */
1075 /* skip adapation field */
1078 /* if past the end of packet, ignore */
1079 p_end
= packet
+ TS_PACKET_SIZE
;
1083 pos
= url_ftell(ts
->stream
->pb
);
1084 ts
->pos47
= pos
% ts
->raw_packet_size
;
1086 if (tss
->type
== MPEGTS_SECTION
) {
1088 /* pointer field present */
1090 if (p
+ len
> p_end
)
1093 /* write remaining section bytes */
1094 write_section_data(s
, tss
,
1096 /* check whether filter has been closed */
1102 write_section_data(s
, tss
,
1107 write_section_data(s
, tss
,
1113 // Note: The position here points actually behind the current packet.
1114 if ((ret
= tss
->u
.pes_filter
.pes_cb(tss
, p
, p_end
- p
, is_start
,
1115 pos
- ts
->raw_packet_size
)) < 0)
1122 /* XXX: try to find a better synchro over several packets (use
1123 get_packet_size() ?) */
1124 static int mpegts_resync(ByteIOContext
*pb
)
1128 for(i
= 0;i
< MAX_RESYNC_SIZE
; i
++) {
1133 url_fseek(pb
, -1, SEEK_CUR
);
1141 /* return -1 if error or EOF. Return 0 if OK. */
1142 static int read_packet(ByteIOContext
*pb
, uint8_t *buf
, int raw_packet_size
)
1147 len
= get_buffer(pb
, buf
, TS_PACKET_SIZE
);
1148 if (len
!= TS_PACKET_SIZE
)
1149 return AVERROR(EIO
);
1150 /* check paquet sync byte */
1151 if (buf
[0] != 0x47) {
1152 /* find a new packet start */
1153 url_fseek(pb
, -TS_PACKET_SIZE
, SEEK_CUR
);
1154 if (mpegts_resync(pb
) < 0)
1155 return AVERROR_INVALIDDATA
;
1159 skip
= raw_packet_size
- TS_PACKET_SIZE
;
1161 url_fskip(pb
, skip
);
1168 static int handle_packets(MpegTSContext
*ts
, int nb_packets
)
1170 AVFormatContext
*s
= ts
->stream
;
1171 ByteIOContext
*pb
= s
->pb
;
1172 uint8_t packet
[TS_PACKET_SIZE
];
1173 int packet_num
, ret
;
1178 if (ts
->stop_parse
>0)
1181 if (nb_packets
!= 0 && packet_num
>= nb_packets
)
1183 ret
= read_packet(pb
, packet
, ts
->raw_packet_size
);
1186 ret
= handle_packet(ts
, packet
);
1193 static int mpegts_probe(AVProbeData
*p
)
1196 const int size
= p
->buf_size
;
1197 int score
, fec_score
, dvhs_score
;
1198 int check_count
= size
/ TS_FEC_PACKET_SIZE
;
1199 #define CHECK_COUNT 10
1201 if (check_count
< CHECK_COUNT
)
1204 score
= analyze(p
->buf
, TS_PACKET_SIZE
*check_count
, TS_PACKET_SIZE
, NULL
)*CHECK_COUNT
/check_count
;
1205 dvhs_score
= analyze(p
->buf
, TS_DVHS_PACKET_SIZE
*check_count
, TS_DVHS_PACKET_SIZE
, NULL
)*CHECK_COUNT
/check_count
;
1206 fec_score
= analyze(p
->buf
, TS_FEC_PACKET_SIZE
*check_count
, TS_FEC_PACKET_SIZE
, NULL
)*CHECK_COUNT
/check_count
;
1207 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1209 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1210 if (score
> fec_score
&& score
> dvhs_score
&& score
> 6) return AVPROBE_SCORE_MAX
+ score
- CHECK_COUNT
;
1211 else if(dvhs_score
> score
&& dvhs_score
> fec_score
&& dvhs_score
> 6) return AVPROBE_SCORE_MAX
+ dvhs_score
- CHECK_COUNT
;
1212 else if( fec_score
> 6) return AVPROBE_SCORE_MAX
+ fec_score
- CHECK_COUNT
;
1215 /* only use the extension for safer guess */
1216 if (match_ext(p
->filename
, "ts"))
1217 return AVPROBE_SCORE_MAX
;
1223 /* return the 90kHz PCR and the extension for the 27MHz PCR. return
1224 (-1) if not available */
1225 static int parse_pcr(int64_t *ppcr_high
, int *ppcr_low
,
1226 const uint8_t *packet
)
1228 int afc
, len
, flags
;
1232 afc
= (packet
[3] >> 4) & 3;
1242 if (!(flags
& 0x10))
1247 *ppcr_high
= ((int64_t)v
<< 1) | (p
[4] >> 7);
1248 *ppcr_low
= ((p
[4] & 1) << 8) | p
[5];
1252 static int mpegts_read_header(AVFormatContext
*s
,
1253 AVFormatParameters
*ap
)
1255 MpegTSContext
*ts
= s
->priv_data
;
1256 ByteIOContext
*pb
= s
->pb
;
1257 uint8_t buf
[5*1024];
1262 ts
->mpeg2ts_compute_pcr
= ap
->mpeg2ts_compute_pcr
;
1263 if(ap
->mpeg2ts_raw
){
1264 av_log(s
, AV_LOG_ERROR
, "use mpegtsraw_demuxer!\n");
1269 /* read the first 1024 bytes to get packet size */
1270 pos
= url_ftell(pb
);
1271 len
= get_buffer(pb
, buf
, sizeof(buf
));
1272 if (len
!= sizeof(buf
))
1274 ts
->raw_packet_size
= get_packet_size(buf
, sizeof(buf
));
1275 if (ts
->raw_packet_size
<= 0)
1280 if (s
->iformat
== &mpegts_demuxer
) {
1283 /* first do a scaning to get all the services */
1284 url_fseek(pb
, pos
, SEEK_SET
);
1286 mpegts_open_section_filter(ts
, SDT_PID
, sdt_cb
, ts
, 1);
1288 mpegts_open_section_filter(ts
, PAT_PID
, pat_cb
, ts
, 1);
1290 handle_packets(ts
, s
->probesize
);
1291 /* if could not find service, enable auto_guess */
1295 dprintf(ts
->stream
, "tuning done\n");
1297 s
->ctx_flags
|= AVFMTCTX_NOHEADER
;
1300 int pcr_pid
, pid
, nb_packets
, nb_pcrs
, ret
, pcr_l
;
1301 int64_t pcrs
[2], pcr_h
;
1302 int packet_count
[2];
1303 uint8_t packet
[TS_PACKET_SIZE
];
1305 /* only read packets */
1307 st
= av_new_stream(s
, 0);
1310 av_set_pts_info(st
, 60, 1, 27000000);
1311 st
->codec
->codec_type
= CODEC_TYPE_DATA
;
1312 st
->codec
->codec_id
= CODEC_ID_MPEG2TS
;
1314 /* we iterate until we find two PCRs to estimate the bitrate */
1319 ret
= read_packet(s
->pb
, packet
, ts
->raw_packet_size
);
1322 pid
= AV_RB16(packet
+ 1) & 0x1fff;
1323 if ((pcr_pid
== -1 || pcr_pid
== pid
) &&
1324 parse_pcr(&pcr_h
, &pcr_l
, packet
) == 0) {
1326 packet_count
[nb_pcrs
] = nb_packets
;
1327 pcrs
[nb_pcrs
] = pcr_h
* 300 + pcr_l
;
1335 /* NOTE1: the bitrate is computed without the FEC */
1336 /* NOTE2: it is only the bitrate of the start of the stream */
1337 ts
->pcr_incr
= (pcrs
[1] - pcrs
[0]) / (packet_count
[1] - packet_count
[0]);
1338 ts
->cur_pcr
= pcrs
[0] - ts
->pcr_incr
* packet_count
[0];
1339 s
->bit_rate
= (TS_PACKET_SIZE
* 8) * 27e6
/ ts
->pcr_incr
;
1340 st
->codec
->bit_rate
= s
->bit_rate
;
1341 st
->start_time
= ts
->cur_pcr
;
1343 av_log(ts
->stream
, AV_LOG_DEBUG
, "start=%0.3f pcr=%0.3f incr=%d\n",
1344 st
->start_time
/ 1000000.0, pcrs
[0] / 27e6
, ts
->pcr_incr
);
1348 url_fseek(pb
, pos
, SEEK_SET
);
1354 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1356 static int mpegts_raw_read_packet(AVFormatContext
*s
,
1359 MpegTSContext
*ts
= s
->priv_data
;
1361 int64_t pcr_h
, next_pcr_h
, pos
;
1362 int pcr_l
, next_pcr_l
;
1363 uint8_t pcr_buf
[12];
1365 if (av_new_packet(pkt
, TS_PACKET_SIZE
) < 0)
1366 return AVERROR(ENOMEM
);
1367 pkt
->pos
= url_ftell(s
->pb
);
1368 ret
= read_packet(s
->pb
, pkt
->data
, ts
->raw_packet_size
);
1370 av_free_packet(pkt
);
1373 if (ts
->mpeg2ts_compute_pcr
) {
1374 /* compute exact PCR for each packet */
1375 if (parse_pcr(&pcr_h
, &pcr_l
, pkt
->data
) == 0) {
1376 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1377 pos
= url_ftell(s
->pb
);
1378 for(i
= 0; i
< MAX_PACKET_READAHEAD
; i
++) {
1379 url_fseek(s
->pb
, pos
+ i
* ts
->raw_packet_size
, SEEK_SET
);
1380 get_buffer(s
->pb
, pcr_buf
, 12);
1381 if (parse_pcr(&next_pcr_h
, &next_pcr_l
, pcr_buf
) == 0) {
1382 /* XXX: not precise enough */
1383 ts
->pcr_incr
= ((next_pcr_h
- pcr_h
) * 300 + (next_pcr_l
- pcr_l
)) /
1388 url_fseek(s
->pb
, pos
, SEEK_SET
);
1389 /* no next PCR found: we use previous increment */
1390 ts
->cur_pcr
= pcr_h
* 300 + pcr_l
;
1392 pkt
->pts
= ts
->cur_pcr
;
1393 pkt
->duration
= ts
->pcr_incr
;
1394 ts
->cur_pcr
+= ts
->pcr_incr
;
1396 pkt
->stream_index
= 0;
1400 static int mpegts_read_packet(AVFormatContext
*s
,
1403 MpegTSContext
*ts
= s
->priv_data
;
1406 if (url_ftell(s
->pb
) != ts
->last_pos
) {
1407 /* seek detected, flush pes buffer */
1408 for (i
= 0; i
< NB_PID_MAX
; i
++) {
1409 if (ts
->pids
[i
] && ts
->pids
[i
]->type
== MPEGTS_PES
) {
1410 PESContext
*pes
= ts
->pids
[i
]->u
.pes_filter
.opaque
;
1411 av_freep(&pes
->buffer
);
1412 pes
->data_index
= 0;
1413 pes
->state
= MPEGTS_SKIP
; /* skip until pes header */
1419 ret
= handle_packets(ts
, 0);
1421 /* flush pes data left */
1422 for (i
= 0; i
< NB_PID_MAX
; i
++) {
1423 if (ts
->pids
[i
] && ts
->pids
[i
]->type
== MPEGTS_PES
) {
1424 PESContext
*pes
= ts
->pids
[i
]->u
.pes_filter
.opaque
;
1425 if (pes
->state
== MPEGTS_PAYLOAD
&& pes
->data_index
> 0) {
1426 new_pes_packet(pes
, pkt
);
1434 ts
->last_pos
= url_ftell(s
->pb
);
1439 static int mpegts_read_close(AVFormatContext
*s
)
1441 MpegTSContext
*ts
= s
->priv_data
;
1446 for(i
=0;i
<NB_PID_MAX
;i
++)
1447 if (ts
->pids
[i
]) mpegts_close_filter(ts
, ts
->pids
[i
]);
1452 static int64_t mpegts_get_pcr(AVFormatContext
*s
, int stream_index
,
1453 int64_t *ppos
, int64_t pos_limit
)
1455 MpegTSContext
*ts
= s
->priv_data
;
1456 int64_t pos
, timestamp
;
1457 uint8_t buf
[TS_PACKET_SIZE
];
1458 int pcr_l
, pcr_pid
= ((PESContext
*)s
->streams
[stream_index
]->priv_data
)->pcr_pid
;
1459 const int find_next
= 1;
1460 pos
= ((*ppos
+ ts
->raw_packet_size
- 1 - ts
->pos47
) / ts
->raw_packet_size
) * ts
->raw_packet_size
+ ts
->pos47
;
1463 url_fseek(s
->pb
, pos
, SEEK_SET
);
1464 if (get_buffer(s
->pb
, buf
, TS_PACKET_SIZE
) != TS_PACKET_SIZE
)
1465 return AV_NOPTS_VALUE
;
1466 if ((pcr_pid
< 0 || (AV_RB16(buf
+ 1) & 0x1fff) == pcr_pid
) &&
1467 parse_pcr(×tamp
, &pcr_l
, buf
) == 0) {
1470 pos
+= ts
->raw_packet_size
;
1474 pos
-= ts
->raw_packet_size
;
1476 return AV_NOPTS_VALUE
;
1477 url_fseek(s
->pb
, pos
, SEEK_SET
);
1478 if (get_buffer(s
->pb
, buf
, TS_PACKET_SIZE
) != TS_PACKET_SIZE
)
1479 return AV_NOPTS_VALUE
;
1480 if ((pcr_pid
< 0 || (AV_RB16(buf
+ 1) & 0x1fff) == pcr_pid
) &&
1481 parse_pcr(×tamp
, &pcr_l
, buf
) == 0) {
1491 static int read_seek(AVFormatContext
*s
, int stream_index
, int64_t target_ts
, int flags
){
1492 MpegTSContext
*ts
= s
->priv_data
;
1493 uint8_t buf
[TS_PACKET_SIZE
];
1496 if(av_seek_frame_binary(s
, stream_index
, target_ts
, flags
) < 0)
1499 pos
= url_ftell(s
->pb
);
1502 url_fseek(s
->pb
, pos
, SEEK_SET
);
1503 if (get_buffer(s
->pb
, buf
, TS_PACKET_SIZE
) != TS_PACKET_SIZE
)
1505 // pid = AV_RB16(buf + 1) & 0x1fff;
1506 if(buf
[1] & 0x40) break;
1507 pos
+= ts
->raw_packet_size
;
1509 url_fseek(s
->pb
, pos
, SEEK_SET
);
1514 /**************************************************************/
1515 /* parsing functions - called from other demuxers such as RTP */
1517 MpegTSContext
*mpegts_parse_open(AVFormatContext
*s
)
1521 ts
= av_mallocz(sizeof(MpegTSContext
));
1524 /* no stream case, currently used by RTP */
1525 ts
->raw_packet_size
= TS_PACKET_SIZE
;
1531 /* return the consumed length if a packet was output, or -1 if no
1533 int mpegts_parse_packet(MpegTSContext
*ts
, AVPacket
*pkt
,
1534 const uint8_t *buf
, int len
)
1542 if (ts
->stop_parse
>0)
1544 if (len
< TS_PACKET_SIZE
)
1546 if (buf
[0] != 0x47) {
1550 handle_packet(ts
, buf
);
1551 buf
+= TS_PACKET_SIZE
;
1552 len
-= TS_PACKET_SIZE
;
1558 void mpegts_parse_close(MpegTSContext
*ts
)
1562 for(i
=0;i
<NB_PID_MAX
;i
++)
1563 av_free(ts
->pids
[i
]);
1567 AVInputFormat mpegts_demuxer
= {
1569 NULL_IF_CONFIG_SMALL("MPEG-2 transport stream format"),
1570 sizeof(MpegTSContext
),
1577 .flags
= AVFMT_SHOW_IDS
|AVFMT_TS_DISCONT
,
1580 AVInputFormat mpegtsraw_demuxer
= {
1582 NULL_IF_CONFIG_SMALL("MPEG-2 raw transport stream format"),
1583 sizeof(MpegTSContext
),
1586 mpegts_raw_read_packet
,
1590 .flags
= AVFMT_SHOW_IDS
|AVFMT_TS_DISCONT
,