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
24 #include "allformats.h"
29 /* 1.0 second at 24Mbit/s */
30 #define MAX_SCAN_PACKETS 32000
32 /* maximum size in which we look for synchronisation if
33 synchronisation is lost */
34 #define MAX_RESYNC_SIZE 4096
36 typedef struct PESContext PESContext;
38 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
39 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
41 enum MpegTSFilterType {
46 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
48 typedef struct MpegTSPESFilter {
53 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
55 typedef void SetServiceCallback(void *opaque, int ret);
57 typedef struct MpegTSSectionFilter {
62 int end_of_section_reached:1;
63 SectionCallback *section_cb;
65 } MpegTSSectionFilter;
67 typedef struct MpegTSFilter {
69 int last_cc; /* last cc code (-1 if first packet) */
70 enum MpegTSFilterType type;
72 MpegTSPESFilter pes_filter;
73 MpegTSSectionFilter section_filter;
77 typedef struct MpegTSService {
79 int sid; /**< MPEG Program Number of stream */
80 char *provider_name; /**< DVB Network name, "" if not DVB stream */
81 char *name; /**< DVB Service name, "MPEG Program [sid]" if not DVB stream*/
84 struct MpegTSContext {
86 AVFormatContext *stream;
87 /** raw packet size, including FEC if present */
89 /** if true, all pids are analyzed to find streams */
92 /** compute exact PCR for each transport stream packet */
93 int mpeg2ts_compute_pcr;
95 int64_t cur_pcr; /**< used to estimate the exact PCR */
96 int pcr_incr; /**< used to estimate the exact PCR */
97 int pcr_pid; /**< used to estimate the exact PCR */
99 /* data needed to handle file based ts */
100 /** stop parsing loop */
102 /** packet containing Audio/Video data */
105 /******************************************/
106 /* private mpegts data */
108 MpegTSFilter *sdt_filter;
109 /** number of PMTs in the last PAT seen */
111 /** list of PMTs in the last PAT seen */
112 MpegTSService **services;
114 /** filter for the PAT */
115 MpegTSFilter *pat_filter;
116 /** filter for the PMT for the MPEG program number specified by req_sid */
117 MpegTSFilter *pmt_filter;
118 /** MPEG program number of stream we want to decode */
121 /** filters for various streams specified by PMT + for the PAT and PMT */
122 MpegTSFilter *pids[NB_PID_MAX];
126 * Assembles PES packets out of TS packets, and then calls the "section_cb"
127 * function when they are complete.
129 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
130 const uint8_t *buf, int buf_size, int is_start)
132 MpegTSSectionFilter *tss = &tss1->u.section_filter;
136 memcpy(tss->section_buf, buf, buf_size);
137 tss->section_index = buf_size;
138 tss->section_h_size = -1;
139 tss->end_of_section_reached = 0;
141 if (tss->end_of_section_reached)
143 len = 4096 - tss->section_index;
146 memcpy(tss->section_buf + tss->section_index, buf, len);
147 tss->section_index += len;
150 /* compute section length if possible */
151 if (tss->section_h_size == -1 && tss->section_index >= 3) {
152 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
155 tss->section_h_size = len;
158 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
159 tss->end_of_section_reached = 1;
160 if (!tss->check_crc ||
161 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
162 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
166 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
167 SectionCallback *section_cb, void *opaque,
171 MpegTSFilter *filter;
172 MpegTSSectionFilter *sec;
175 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
177 if (pid >= NB_PID_MAX || ts->pids[pid])
179 filter = av_mallocz(sizeof(MpegTSFilter));
182 ts->pids[pid] = filter;
183 filter->type = MPEGTS_SECTION;
185 filter->last_cc = -1;
186 sec = &filter->u.section_filter;
187 sec->section_cb = section_cb;
188 sec->opaque = opaque;
189 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
190 sec->check_crc = check_crc;
191 if (!sec->section_buf) {
198 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
202 MpegTSFilter *filter;
203 MpegTSPESFilter *pes;
205 if (pid >= NB_PID_MAX || ts->pids[pid])
207 filter = av_mallocz(sizeof(MpegTSFilter));
210 ts->pids[pid] = filter;
211 filter->type = MPEGTS_PES;
213 filter->last_cc = -1;
214 pes = &filter->u.pes_filter;
215 pes->pes_cb = pes_cb;
216 pes->opaque = opaque;
220 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
225 if (filter->type == MPEGTS_SECTION)
226 av_freep(&filter->u.section_filter.section_buf);
227 else if (filter->type == MPEGTS_PES)
228 av_freep(&filter->u.pes_filter.opaque);
231 ts->pids[pid] = NULL;
234 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
235 int stat[packet_size];
240 memset(stat, 0, packet_size*sizeof(int));
242 for(x=i=0; i<size; i++){
245 if(stat[x] > best_score){
252 if(x == packet_size) x= 0;
258 /* autodetect fec presence. Must have at least 1024 bytes */
259 static int get_packet_size(const uint8_t *buf, int size)
261 int score, fec_score, dvhs_score;
263 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
266 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
267 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
268 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
269 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
271 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
272 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
273 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
277 typedef struct SectionHeader {
282 uint8_t last_sec_num;
285 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
298 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
304 if ((p + 1) >= p_end)
306 c = (p[0] << 8) | p[1];
312 /* read and allocate a DVB string preceeded by its length */
313 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
320 len = get8(&p, p_end);
323 if ((p + len) > p_end)
325 str = av_malloc(len + 1);
335 static int parse_section_header(SectionHeader *h,
336 const uint8_t **pp, const uint8_t *p_end)
340 val = get8(pp, p_end);
345 val = get16(pp, p_end);
349 val = get8(pp, p_end);
352 h->version = (val >> 1) & 0x1f;
353 val = get8(pp, p_end);
357 val = get8(pp, p_end);
360 h->last_sec_num = val;
364 static MpegTSService *new_service(MpegTSContext *ts, int sid,
365 char *provider_name, char *name)
367 MpegTSService *service;
370 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
371 "sid=0x%04x provider='%s' name='%s'\n",
372 sid, provider_name, name);
375 service = av_mallocz(sizeof(MpegTSService));
379 service->provider_name = provider_name;
380 service->name = name;
381 dynarray_add(&ts->services, &ts->nb_services, service);
385 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
387 MpegTSContext *ts = opaque;
388 SectionHeader h1, *h = &h1;
391 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
392 int program_info_length, pcr_pid, pid, stream_type;
393 int desc_list_len, desc_len, desc_tag;
394 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
395 char language[4] = {0}; /* initialize to kill warnings */
398 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
399 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
401 p_end = section + section_len - 4;
403 if (parse_section_header(h, &p, p_end) < 0)
406 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
407 h->id, h->sec_num, h->last_sec_num);
409 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
412 pcr_pid = get16(&p, p_end) & 0x1fff;
415 ts->pcr_pid = pcr_pid;
417 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
419 program_info_length = get16(&p, p_end) & 0xfff;
420 if (program_info_length < 0)
422 p += program_info_length;
428 stream_type = get8(&p, p_end);
431 pid = get16(&p, p_end) & 0x1fff;
434 desc_list_len = get16(&p, p_end) & 0xfff;
435 if (desc_list_len < 0)
437 desc_list_end = p + desc_list_len;
438 if (desc_list_end > p_end)
441 desc_tag = get8(&p, desc_list_end);
444 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
445 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
446 /*assume DVB AC-3 Audio*/
447 stream_type = STREAM_TYPE_AUDIO_AC3;
448 } else if(desc_tag == 0x7B) {
450 stream_type = STREAM_TYPE_AUDIO_DTS;
453 desc_len = get8(&p, desc_list_end);
454 desc_end = p + desc_len;
455 if (desc_end > desc_list_end)
458 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
462 case DVB_SUBT_DESCID:
463 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
464 stream_type = STREAM_TYPE_SUBTITLE_DVB;
466 language[0] = get8(&p, desc_end);
467 language[1] = get8(&p, desc_end);
468 language[2] = get8(&p, desc_end);
471 comp_page = get16(&p, desc_end);
472 anc_page = get16(&p, desc_end);
475 case 0x0a: /* ISO 639 language descriptor */
476 language[0] = get8(&p, desc_end);
477 language[1] = get8(&p, desc_end);
478 language[2] = get8(&p, desc_end);
489 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
493 /* now create ffmpeg stream */
494 switch(stream_type) {
495 case STREAM_TYPE_AUDIO_MPEG1:
496 case STREAM_TYPE_AUDIO_MPEG2:
497 case STREAM_TYPE_VIDEO_MPEG1:
498 case STREAM_TYPE_VIDEO_MPEG2:
499 case STREAM_TYPE_VIDEO_MPEG4:
500 case STREAM_TYPE_VIDEO_H264:
501 case STREAM_TYPE_VIDEO_VC1:
502 case STREAM_TYPE_AUDIO_AAC:
503 case STREAM_TYPE_AUDIO_AC3:
504 case STREAM_TYPE_AUDIO_DTS:
505 case STREAM_TYPE_SUBTITLE_DVB:
506 pes = add_pes_stream(ts, pid, stream_type);
508 st = new_pes_av_stream(pes, 0);
511 /* we ignore the other streams */
516 if (language[0] != 0) {
517 st->language[0] = language[0];
518 st->language[1] = language[1];
519 st->language[2] = language[2];
520 st->language[3] = language[3];
523 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
524 st->codec->sub_id = (anc_page << 16) | comp_page;
528 /* all parameters are there */
530 mpegts_close_filter(ts, ts->pmt_filter);
531 ts->pmt_filter = NULL;
534 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
536 MpegTSContext *ts = opaque;
537 SectionHeader h1, *h = &h1;
538 const uint8_t *p, *p_end;
542 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
543 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
545 p_end = section + section_len - 4;
547 if (parse_section_header(h, &p, p_end) < 0)
549 if (h->tid != PAT_TID)
553 sid = get16(&p, p_end);
556 pmt_pid = get16(&p, p_end) & 0x1fff;
560 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
565 if (ts->req_sid == sid) {
566 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
576 mpegts_close_filter(ts, ts->pat_filter);
577 ts->pat_filter = NULL;
580 /* add all services found in the PAT */
581 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
583 MpegTSContext *ts = opaque;
584 SectionHeader h1, *h = &h1;
585 const uint8_t *p, *p_end;
587 char *provider_name, *name;
591 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
592 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
594 p_end = section + section_len - 4;
596 if (parse_section_header(h, &p, p_end) < 0)
598 if (h->tid != PAT_TID)
602 sid = get16(&p, p_end);
605 pmt_pid = get16(&p, p_end) & 0x1fff;
609 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
614 /* add the service with a dummy name */
615 snprintf(buf, sizeof(buf), "Service %x\n", sid);
616 name = av_strdup(buf);
617 provider_name = av_strdup("");
618 if (name && provider_name) {
619 new_service(ts, sid, provider_name, name);
622 av_freep(&provider_name);
629 mpegts_close_filter(ts, ts->pat_filter);
630 ts->pat_filter = NULL;
633 static void mpegts_set_service(MpegTSContext *ts, int sid)
636 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
640 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
642 MpegTSContext *ts = opaque;
643 SectionHeader h1, *h = &h1;
644 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
645 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
646 char *name, *provider_name;
649 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
650 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
653 p_end = section + section_len - 4;
655 if (parse_section_header(h, &p, p_end) < 0)
657 if (h->tid != SDT_TID)
659 onid = get16(&p, p_end);
662 val = get8(&p, p_end);
666 sid = get16(&p, p_end);
669 val = get8(&p, p_end);
672 desc_list_len = get16(&p, p_end) & 0xfff;
673 if (desc_list_len < 0)
675 desc_list_end = p + desc_list_len;
676 if (desc_list_end > p_end)
679 desc_tag = get8(&p, desc_list_end);
682 desc_len = get8(&p, desc_list_end);
683 desc_end = p + desc_len;
684 if (desc_end > desc_list_end)
687 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
692 service_type = get8(&p, p_end);
693 if (service_type < 0)
695 provider_name = getstr8(&p, p_end);
698 name = getstr8(&p, p_end);
701 new_service(ts, sid, provider_name, name);
713 mpegts_close_filter(ts, ts->sdt_filter);
714 ts->sdt_filter = NULL;
717 /* scan services in a transport stream by looking at the SDT */
718 static void mpegts_scan_sdt(MpegTSContext *ts)
720 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
724 /* scan services in a transport stream by looking at the PAT (better
726 static void mpegts_scan_pat(MpegTSContext *ts)
728 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
732 /* TS stream handling */
736 MPEGTS_PESHEADER_FILL,
741 /* enough for PES header + length */
742 #define PES_START_SIZE 9
743 #define MAX_PES_HEADER_SIZE (9 + 255)
749 AVFormatContext *stream;
751 enum MpegTSState state;
752 /* used to get the format */
757 uint8_t header[MAX_PES_HEADER_SIZE];
760 static int64_t get_pts(const uint8_t *p)
765 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
766 val = (p[1] << 8) | p[2];
767 pts |= (int64_t)(val >> 1) << 15;
768 val = (p[3] << 8) | p[4];
769 pts |= (int64_t)(val >> 1);
773 /* return non zero if a packet could be constructed */
774 static void mpegts_push_data(void *opaque,
775 const uint8_t *buf, int buf_size, int is_start)
777 PESContext *pes = opaque;
778 MpegTSContext *ts = pes->ts;
786 pes->state = MPEGTS_HEADER;
790 while (buf_size > 0) {
793 len = PES_START_SIZE - pes->data_index;
796 memcpy(pes->header + pes->data_index, p, len);
797 pes->data_index += len;
800 if (pes->data_index == PES_START_SIZE) {
801 /* we got all the PES or section header. We can now
804 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
806 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
807 pes->header[2] == 0x01) {
808 /* it must be an mpeg2 PES stream */
809 code = pes->header[3] | 0x100;
810 if (!((code >= 0x1c0 && code <= 0x1df) ||
811 (code >= 0x1e0 && code <= 0x1ef) ||
812 (code == 0x1bd) || (code == 0x1fd)))
815 /* allocate stream */
816 new_pes_av_stream(pes, code);
818 pes->state = MPEGTS_PESHEADER_FILL;
819 pes->total_size = (pes->header[4] << 8) | pes->header[5];
820 /* NOTE: a zero total size means the PES size is
823 pes->total_size += 6;
824 pes->pes_header_size = pes->header[8] + 9;
826 /* otherwise, it should be a table */
829 pes->state = MPEGTS_SKIP;
834 /**********************************************/
835 /* PES packing parsing */
836 case MPEGTS_PESHEADER_FILL:
837 len = pes->pes_header_size - pes->data_index;
840 memcpy(pes->header + pes->data_index, p, len);
841 pes->data_index += len;
844 if (pes->data_index == pes->pes_header_size) {
848 flags = pes->header[7];
850 pes->pts = AV_NOPTS_VALUE;
851 pes->dts = AV_NOPTS_VALUE;
852 if ((flags & 0xc0) == 0x80) {
853 pes->pts = get_pts(r);
855 } else if ((flags & 0xc0) == 0xc0) {
856 pes->pts = get_pts(r);
858 pes->dts = get_pts(r);
861 /* we got the full header. We parse it and get the payload */
862 pes->state = MPEGTS_PAYLOAD;
866 if (pes->total_size) {
867 len = pes->total_size - pes->data_index;
874 AVPacket *pkt = ts->pkt;
875 if (pes->st && av_new_packet(pkt, len) == 0) {
876 memcpy(pkt->data, p, len);
877 pkt->stream_index = pes->st->index;
880 /* reset pts values */
881 pes->pts = AV_NOPTS_VALUE;
882 pes->dts = AV_NOPTS_VALUE;
896 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
899 int codec_type, codec_id;
901 switch(pes->stream_type){
902 case STREAM_TYPE_AUDIO_MPEG1:
903 case STREAM_TYPE_AUDIO_MPEG2:
904 codec_type = CODEC_TYPE_AUDIO;
905 codec_id = CODEC_ID_MP3;
907 case STREAM_TYPE_VIDEO_MPEG1:
908 case STREAM_TYPE_VIDEO_MPEG2:
909 codec_type = CODEC_TYPE_VIDEO;
910 codec_id = CODEC_ID_MPEG2VIDEO;
912 case STREAM_TYPE_VIDEO_MPEG4:
913 codec_type = CODEC_TYPE_VIDEO;
914 codec_id = CODEC_ID_MPEG4;
916 case STREAM_TYPE_VIDEO_H264:
917 codec_type = CODEC_TYPE_VIDEO;
918 codec_id = CODEC_ID_H264;
920 case STREAM_TYPE_VIDEO_VC1:
921 codec_type = CODEC_TYPE_VIDEO;
922 codec_id = CODEC_ID_VC1;
924 case STREAM_TYPE_AUDIO_AAC:
925 codec_type = CODEC_TYPE_AUDIO;
926 codec_id = CODEC_ID_AAC;
928 case STREAM_TYPE_AUDIO_AC3:
929 codec_type = CODEC_TYPE_AUDIO;
930 codec_id = CODEC_ID_AC3;
932 case STREAM_TYPE_AUDIO_DTS:
933 codec_type = CODEC_TYPE_AUDIO;
934 codec_id = CODEC_ID_DTS;
936 case STREAM_TYPE_SUBTITLE_DVB:
937 codec_type = CODEC_TYPE_SUBTITLE;
938 codec_id = CODEC_ID_DVB_SUBTITLE;
941 if (code >= 0x1c0 && code <= 0x1df) {
942 codec_type = CODEC_TYPE_AUDIO;
943 codec_id = CODEC_ID_MP2;
944 } else if (code == 0x1bd) {
945 codec_type = CODEC_TYPE_AUDIO;
946 codec_id = CODEC_ID_AC3;
948 codec_type = CODEC_TYPE_VIDEO;
949 codec_id = CODEC_ID_MPEG1VIDEO;
953 st = av_new_stream(pes->stream, pes->pid);
955 av_set_pts_info(st, 33, 1, 90000);
957 st->codec->codec_type = codec_type;
958 st->codec->codec_id = codec_id;
959 st->need_parsing = AVSTREAM_PARSE_FULL;
966 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
971 /* if no pid found, then add a pid context */
972 pes = av_mallocz(sizeof(PESContext));
976 pes->stream = ts->stream;
978 pes->stream_type = stream_type;
979 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
987 /* handle one TS packet */
988 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
990 AVFormatContext *s = ts->stream;
992 int len, pid, cc, cc_ok, afc, is_start;
993 const uint8_t *p, *p_end;
995 pid = ((packet[1] & 0x1f) << 8) | packet[2];
996 is_start = packet[1] & 0x40;
998 if (ts->auto_guess && tss == NULL && is_start) {
999 add_pes_stream(ts, pid, 0);
1000 tss = ts->pids[pid];
1005 /* continuity check (currently not used) */
1006 cc = (packet[3] & 0xf);
1007 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
1010 /* skip adaptation field */
1011 afc = (packet[3] >> 4) & 3;
1013 if (afc == 0) /* reserved value */
1015 if (afc == 2) /* adaptation field only */
1018 /* skip adapation field */
1021 /* if past the end of packet, ignore */
1022 p_end = packet + TS_PACKET_SIZE;
1026 if (tss->type == MPEGTS_SECTION) {
1028 /* pointer field present */
1030 if (p + len > p_end)
1033 /* write remaining section bytes */
1034 write_section_data(s, tss,
1036 /* check whether filter has been closed */
1042 write_section_data(s, tss,
1047 write_section_data(s, tss,
1052 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
1053 p, p_end - p, is_start);
1057 /* XXX: try to find a better synchro over several packets (use
1058 get_packet_size() ?) */
1059 static int mpegts_resync(ByteIOContext *pb)
1063 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1068 url_fseek(pb, -1, SEEK_CUR);
1076 /* return -1 if error or EOF. Return 0 if OK. */
1077 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1082 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1083 if (len != TS_PACKET_SIZE)
1085 /* check paquet sync byte */
1086 if (buf[0] != 0x47) {
1087 /* find a new packet start */
1088 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1089 if (mpegts_resync(pb) < 0)
1090 return AVERROR_INVALIDDATA;
1094 skip = raw_packet_size - TS_PACKET_SIZE;
1096 url_fskip(pb, skip);
1103 static int handle_packets(MpegTSContext *ts, int nb_packets)
1105 AVFormatContext *s = ts->stream;
1106 ByteIOContext *pb = &s->pb;
1107 uint8_t packet[TS_PACKET_SIZE];
1108 int packet_num, ret;
1116 if (nb_packets != 0 && packet_num >= nb_packets)
1118 ret = read_packet(pb, packet, ts->raw_packet_size);
1121 handle_packet(ts, packet);
1126 static int mpegts_probe(AVProbeData *p)
1129 const int size= p->buf_size;
1130 int score, fec_score, dvhs_score;
1131 #define CHECK_COUNT 10
1133 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1136 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1137 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1138 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1139 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1141 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1142 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1143 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1144 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1147 /* only use the extension for safer guess */
1148 if (match_ext(p->filename, "ts"))
1149 return AVPROBE_SCORE_MAX;
1155 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1156 (-1) if not available */
1157 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1158 const uint8_t *packet)
1160 int afc, len, flags;
1164 afc = (packet[3] >> 4) & 3;
1174 if (!(flags & 0x10))
1178 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1179 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1180 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1184 static int mpegts_read_header(AVFormatContext *s,
1185 AVFormatParameters *ap)
1187 MpegTSContext *ts = s->priv_data;
1188 ByteIOContext *pb = &s->pb;
1192 MpegTSService *service;
1195 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1196 if(ap->mpeg2ts_raw){
1197 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1202 /* read the first 1024 bytes to get packet size */
1203 pos = url_ftell(pb);
1204 len = get_buffer(pb, buf, sizeof(buf));
1205 if (len != sizeof(buf))
1207 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1208 if (ts->raw_packet_size <= 0)
1213 if (s->iformat == &mpegts_demuxer) {
1216 /* first do a scaning to get all the services */
1217 url_fseek(pb, pos, SEEK_SET);
1218 mpegts_scan_sdt(ts);
1220 handle_packets(ts, s->probesize);
1222 if (ts->nb_services <= 0) {
1223 /* no SDT found, we try to look at the PAT */
1225 /* First remove the SDT filters from each PID */
1227 for (i=0; i < NB_PID_MAX; i++) {
1229 mpegts_close_filter(ts, ts->pids[i]);
1231 url_fseek(pb, pos, SEEK_SET);
1232 mpegts_scan_pat(ts);
1234 handle_packets(ts, s->probesize);
1237 if (ts->nb_services <= 0) {
1238 /* raw transport stream */
1240 s->ctx_flags |= AVFMTCTX_NOHEADER;
1244 /* tune to first service found */
1245 for(i=0; i<ts->nb_services; i++){
1246 service = ts->services[i];
1249 av_log(ts->stream, AV_LOG_DEBUG, "tuning to '%s'\n", service->name);
1252 /* now find the info for the first service if we found any,
1253 otherwise try to filter all PATs */
1255 url_fseek(pb, pos, SEEK_SET);
1256 mpegts_set_service(ts, sid);
1258 handle_packets(ts, s->probesize);
1260 /* if could not find service, enable auto_guess */
1265 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1267 s->ctx_flags |= AVFMTCTX_NOHEADER;
1270 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1271 int64_t pcrs[2], pcr_h;
1272 int packet_count[2];
1273 uint8_t packet[TS_PACKET_SIZE];
1275 /* only read packets */
1278 st = av_new_stream(s, 0);
1281 av_set_pts_info(st, 60, 1, 27000000);
1282 st->codec->codec_type = CODEC_TYPE_DATA;
1283 st->codec->codec_id = CODEC_ID_MPEG2TS;
1285 /* we iterate until we find two PCRs to estimate the bitrate */
1290 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1293 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1294 if ((pcr_pid == -1 || pcr_pid == pid) &&
1295 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1297 packet_count[nb_pcrs] = nb_packets;
1298 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1305 ts->pcr_pid = pcr_pid;
1307 /* NOTE1: the bitrate is computed without the FEC */
1308 /* NOTE2: it is only the bitrate of the start of the stream */
1309 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1310 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1311 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1312 st->codec->bit_rate = s->bit_rate;
1313 st->start_time = ts->cur_pcr;
1315 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1316 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1320 url_fseek(pb, pos, SEEK_SET);
1326 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1328 static int mpegts_raw_read_packet(AVFormatContext *s,
1331 MpegTSContext *ts = s->priv_data;
1333 int64_t pcr_h, next_pcr_h, pos;
1334 int pcr_l, next_pcr_l;
1335 uint8_t pcr_buf[12];
1337 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1338 return AVERROR(ENOMEM);
1339 pkt->pos= url_ftell(&s->pb);
1340 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1342 av_free_packet(pkt);
1345 if (ts->mpeg2ts_compute_pcr) {
1346 /* compute exact PCR for each packet */
1347 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1348 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1349 pos = url_ftell(&s->pb);
1350 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1351 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1352 get_buffer(&s->pb, pcr_buf, 12);
1353 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1354 /* XXX: not precise enough */
1355 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1360 url_fseek(&s->pb, pos, SEEK_SET);
1361 /* no next PCR found: we use previous increment */
1362 ts->cur_pcr = pcr_h * 300 + pcr_l;
1364 pkt->pts = ts->cur_pcr;
1365 pkt->duration = ts->pcr_incr;
1366 ts->cur_pcr += ts->pcr_incr;
1368 pkt->stream_index = 0;
1372 static int mpegts_read_packet(AVFormatContext *s,
1375 MpegTSContext *ts = s->priv_data;
1378 return handle_packets(ts, 0);
1381 static int mpegts_read_close(AVFormatContext *s)
1383 MpegTSContext *ts = s->priv_data;
1385 for(i=0;i<NB_PID_MAX;i++)
1386 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1388 for(i = 0; i < ts->nb_services; i++){
1389 av_free(ts->services[i]->provider_name);
1390 av_free(ts->services[i]->name);
1391 av_free(ts->services[i]);
1393 av_freep(&ts->services);
1398 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1399 int64_t *ppos, int64_t pos_limit)
1401 MpegTSContext *ts = s->priv_data;
1402 int64_t pos, timestamp;
1403 uint8_t buf[TS_PACKET_SIZE];
1405 const int find_next= 1;
1406 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1409 url_fseek(&s->pb, pos, SEEK_SET);
1410 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1411 return AV_NOPTS_VALUE;
1412 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1413 if (pid == ts->pcr_pid &&
1414 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1417 pos += ts->raw_packet_size;
1421 pos -= ts->raw_packet_size;
1423 return AV_NOPTS_VALUE;
1424 url_fseek(&s->pb, pos, SEEK_SET);
1425 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1426 return AV_NOPTS_VALUE;
1427 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1428 if (pid == ts->pcr_pid &&
1429 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1439 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1440 MpegTSContext *ts = s->priv_data;
1441 uint8_t buf[TS_PACKET_SIZE];
1444 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1447 pos= url_ftell(&s->pb);
1450 url_fseek(&s->pb, pos, SEEK_SET);
1451 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1453 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1454 if(buf[1] & 0x40) break;
1455 pos += ts->raw_packet_size;
1457 url_fseek(&s->pb, pos, SEEK_SET);
1462 /**************************************************************/
1463 /* parsing functions - called from other demuxers such as RTP */
1465 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1469 ts = av_mallocz(sizeof(MpegTSContext));
1472 /* no stream case, currently used by RTP */
1473 ts->raw_packet_size = TS_PACKET_SIZE;
1479 /* return the consumed length if a packet was output, or -1 if no
1481 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1482 const uint8_t *buf, int len)
1492 if (len < TS_PACKET_SIZE)
1494 if (buf[0] != 0x47) {
1498 handle_packet(ts, buf);
1499 buf += TS_PACKET_SIZE;
1500 len -= TS_PACKET_SIZE;
1506 void mpegts_parse_close(MpegTSContext *ts)
1510 for(i=0;i<NB_PID_MAX;i++)
1511 av_free(ts->pids[i]);
1515 AVInputFormat mpegts_demuxer = {
1517 "MPEG2 transport stream format",
1518 sizeof(MpegTSContext),
1525 .flags = AVFMT_SHOW_IDS,
1528 AVInputFormat mpegtsraw_demuxer = {
1530 "MPEG2 raw transport stream format",
1531 sizeof(MpegTSContext),
1534 mpegts_raw_read_packet,
1538 .flags = AVFMT_SHOW_IDS,