2 * MPEG2 transport stream (aka DVB) demux
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
28 /* 1.0 second at 24Mbit/s */
29 #define MAX_SCAN_PACKETS 32000
31 /* maximum size in which we look for synchronisation if
32 synchronisation is lost */
33 #define MAX_RESYNC_SIZE 4096
35 typedef struct PESContext PESContext;
37 static PESContext* add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
38 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code);
40 enum MpegTSFilterType {
45 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
47 typedef struct MpegTSPESFilter {
52 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
54 typedef void SetServiceCallback(void *opaque, int ret);
56 typedef struct MpegTSSectionFilter {
61 int end_of_section_reached:1;
62 SectionCallback *section_cb;
64 } MpegTSSectionFilter;
66 typedef struct MpegTSFilter {
68 int last_cc; /* last cc code (-1 if first packet) */
69 enum MpegTSFilterType type;
71 MpegTSPESFilter pes_filter;
72 MpegTSSectionFilter section_filter;
76 typedef struct MpegTSService {
83 struct MpegTSContext {
85 AVFormatContext *stream;
86 int raw_packet_size; /* raw packet size, including FEC if present */
87 int auto_guess; /* if true, all pids are analized to find streams */
90 int mpeg2ts_raw; /* force raw MPEG2 transport stream output, if possible */
91 int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
93 /* used to estimate the exact PCR */
98 /* data needed to handle file based ts */
99 int stop_parse; /* stop parsing loop */
100 AVPacket *pkt; /* packet containing av data */
102 /******************************************/
103 /* private mpegts data */
105 MpegTSFilter *sdt_filter;
107 MpegTSService **services;
109 /* set service context (XXX: allocated it ?) */
110 SetServiceCallback *set_service_cb;
111 void *set_service_opaque;
112 MpegTSFilter *pat_filter;
113 MpegTSFilter *pmt_filter;
116 MpegTSFilter *pids[NB_PID_MAX];
119 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
120 const uint8_t *buf, int buf_size, int is_start)
122 MpegTSSectionFilter *tss = &tss1->u.section_filter;
126 memcpy(tss->section_buf, buf, buf_size);
127 tss->section_index = buf_size;
128 tss->section_h_size = -1;
129 tss->end_of_section_reached = 0;
131 if (tss->end_of_section_reached)
133 len = 4096 - tss->section_index;
136 memcpy(tss->section_buf + tss->section_index, buf, len);
137 tss->section_index += len;
140 /* compute section length if possible */
141 if (tss->section_h_size == -1 && tss->section_index >= 3) {
142 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
145 tss->section_h_size = len;
148 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
149 tss->end_of_section_reached = 1;
150 if (!tss->check_crc ||
151 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
152 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
156 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
157 SectionCallback *section_cb, void *opaque,
161 MpegTSFilter *filter;
162 MpegTSSectionFilter *sec;
165 printf("Filter: pid=0x%x\n", pid);
167 if (pid >= NB_PID_MAX || ts->pids[pid])
169 filter = av_mallocz(sizeof(MpegTSFilter));
172 ts->pids[pid] = filter;
173 filter->type = MPEGTS_SECTION;
175 filter->last_cc = -1;
176 sec = &filter->u.section_filter;
177 sec->section_cb = section_cb;
178 sec->opaque = opaque;
179 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
180 sec->check_crc = check_crc;
181 if (!sec->section_buf) {
188 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
192 MpegTSFilter *filter;
193 MpegTSPESFilter *pes;
195 if (pid >= NB_PID_MAX || ts->pids[pid])
197 filter = av_mallocz(sizeof(MpegTSFilter));
200 ts->pids[pid] = filter;
201 filter->type = MPEGTS_PES;
203 filter->last_cc = -1;
204 pes = &filter->u.pes_filter;
205 pes->pes_cb = pes_cb;
206 pes->opaque = opaque;
210 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
215 if (filter->type == MPEGTS_SECTION)
216 av_freep(&filter->u.section_filter.section_buf);
217 else if (filter->type == MPEGTS_PES)
218 av_freep(&filter->u.pes_filter.opaque);
221 ts->pids[pid] = NULL;
224 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
225 int stat[packet_size];
230 memset(stat, 0, packet_size*sizeof(int));
232 for(x=i=0; i<size; i++){
235 if(stat[x] > best_score){
242 if(x == packet_size) x= 0;
248 /* autodetect fec presence. Must have at least 1024 bytes */
249 static int get_packet_size(const uint8_t *buf, int size)
251 int score, fec_score, dvhs_score;
253 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
256 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
257 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
258 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
259 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
261 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
262 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
263 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
267 typedef struct SectionHeader {
272 uint8_t last_sec_num;
275 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
288 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
294 if ((p + 1) >= p_end)
296 c = (p[0] << 8) | p[1];
302 /* read and allocate a DVB string preceeded by its length */
303 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
310 len = get8(&p, p_end);
313 if ((p + len) > p_end)
315 str = av_malloc(len + 1);
325 static int parse_section_header(SectionHeader *h,
326 const uint8_t **pp, const uint8_t *p_end)
330 val = get8(pp, p_end);
335 val = get16(pp, p_end);
339 val = get8(pp, p_end);
342 h->version = (val >> 1) & 0x1f;
343 val = get8(pp, p_end);
347 val = get8(pp, p_end);
350 h->last_sec_num = val;
354 static MpegTSService *new_service(MpegTSContext *ts, int sid,
355 char *provider_name, char *name)
357 MpegTSService *service;
360 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
361 sid, provider_name, name);
364 service = av_mallocz(sizeof(MpegTSService));
368 service->provider_name = provider_name;
369 service->name = name;
370 dynarray_add(&ts->services, &ts->nb_services, service);
374 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
376 MpegTSContext *ts = opaque;
377 SectionHeader h1, *h = &h1;
380 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
381 int program_info_length, pcr_pid, pid, stream_type;
382 int desc_list_len, desc_len, desc_tag;
383 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
388 av_hex_dump(stdout, (uint8_t *)section, section_len);
390 p_end = section + section_len - 4;
392 if (parse_section_header(h, &p, p_end) < 0)
395 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
397 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
400 pcr_pid = get16(&p, p_end) & 0x1fff;
403 ts->pcr_pid = pcr_pid;
405 printf("pcr_pid=0x%x\n", pcr_pid);
407 program_info_length = get16(&p, p_end) & 0xfff;
408 if (program_info_length < 0)
410 p += program_info_length;
416 stream_type = get8(&p, p_end);
419 pid = get16(&p, p_end) & 0x1fff;
422 desc_list_len = get16(&p, p_end) & 0xfff;
423 if (desc_list_len < 0)
425 desc_list_end = p + desc_list_len;
426 if (desc_list_end > p_end)
429 desc_tag = get8(&p, desc_list_end);
432 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
433 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
434 /*assume DVB AC-3 Audio*/
435 stream_type = STREAM_TYPE_AUDIO_AC3;
436 } else if(desc_tag == 0x7B) {
438 stream_type = STREAM_TYPE_AUDIO_DTS;
441 desc_len = get8(&p, desc_list_end);
442 desc_end = p + desc_len;
443 if (desc_end > desc_list_end)
446 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
449 case DVB_SUBT_DESCID:
450 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
451 stream_type = STREAM_TYPE_SUBTITLE_DVB;
453 language[0] = get8(&p, desc_end);
454 language[1] = get8(&p, desc_end);
455 language[2] = get8(&p, desc_end);
458 comp_page = get16(&p, desc_end);
459 anc_page = get16(&p, desc_end);
462 case 0x0a: /* ISO 639 language descriptor */
463 language[0] = get8(&p, desc_end);
464 language[1] = get8(&p, desc_end);
465 language[2] = get8(&p, desc_end);
476 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
479 /* now create ffmpeg stream */
480 switch(stream_type) {
481 case STREAM_TYPE_AUDIO_MPEG1:
482 case STREAM_TYPE_AUDIO_MPEG2:
483 case STREAM_TYPE_VIDEO_MPEG1:
484 case STREAM_TYPE_VIDEO_MPEG2:
485 case STREAM_TYPE_VIDEO_MPEG4:
486 case STREAM_TYPE_VIDEO_H264:
487 case STREAM_TYPE_AUDIO_AAC:
488 case STREAM_TYPE_AUDIO_AC3:
489 case STREAM_TYPE_AUDIO_DTS:
490 case STREAM_TYPE_SUBTITLE_DVB:
491 pes = add_pes_stream(ts, pid, stream_type);
493 st = new_pes_av_stream(pes, 0);
496 /* we ignore the other streams */
501 if (language[0] != 0) {
502 st->language[0] = language[0];
503 st->language[1] = language[1];
504 st->language[2] = language[2];
505 st->language[3] = language[3];
508 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
509 st->codec->sub_id = (anc_page << 16) | comp_page;
513 /* all parameters are there */
514 ts->set_service_cb(ts->set_service_opaque, 0);
515 mpegts_close_filter(ts, ts->pmt_filter);
516 ts->pmt_filter = NULL;
519 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
521 MpegTSContext *ts = opaque;
522 SectionHeader h1, *h = &h1;
523 const uint8_t *p, *p_end;
528 av_hex_dump(stdout, (uint8_t *)section, section_len);
530 p_end = section + section_len - 4;
532 if (parse_section_header(h, &p, p_end) < 0)
534 if (h->tid != PAT_TID)
538 sid = get16(&p, p_end);
541 pmt_pid = get16(&p, p_end) & 0x1fff;
545 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
550 if (ts->req_sid == sid) {
551 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
558 ts->set_service_cb(ts->set_service_opaque, -1);
561 mpegts_close_filter(ts, ts->pat_filter);
562 ts->pat_filter = NULL;
565 /* add all services found in the PAT */
566 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
568 MpegTSContext *ts = opaque;
569 SectionHeader h1, *h = &h1;
570 const uint8_t *p, *p_end;
572 char *provider_name, *name;
577 av_hex_dump(stdout, (uint8_t *)section, section_len);
579 p_end = section + section_len - 4;
581 if (parse_section_header(h, &p, p_end) < 0)
583 if (h->tid != PAT_TID)
587 sid = get16(&p, p_end);
590 pmt_pid = get16(&p, p_end) & 0x1fff;
594 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
599 /* add the service with a dummy name */
600 snprintf(buf, sizeof(buf), "Service %x\n", sid);
601 name = av_strdup(buf);
602 provider_name = av_strdup("");
603 if (name && provider_name) {
604 new_service(ts, sid, provider_name, name);
607 av_freep(&provider_name);
614 mpegts_close_filter(ts, ts->pat_filter);
615 ts->pat_filter = NULL;
618 static void mpegts_set_service(MpegTSContext *ts, int sid,
619 SetServiceCallback *set_service_cb, void *opaque)
621 ts->set_service_cb = set_service_cb;
622 ts->set_service_opaque = opaque;
624 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
628 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
630 MpegTSContext *ts = opaque;
631 SectionHeader h1, *h = &h1;
632 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
633 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
634 char *name, *provider_name;
638 av_hex_dump(stdout, (uint8_t *)section, section_len);
641 p_end = section + section_len - 4;
643 if (parse_section_header(h, &p, p_end) < 0)
645 if (h->tid != SDT_TID)
647 onid = get16(&p, p_end);
650 val = get8(&p, p_end);
654 sid = get16(&p, p_end);
657 val = get8(&p, p_end);
660 desc_list_len = get16(&p, p_end) & 0xfff;
661 if (desc_list_len < 0)
663 desc_list_end = p + desc_list_len;
664 if (desc_list_end > p_end)
667 desc_tag = get8(&p, desc_list_end);
670 desc_len = get8(&p, desc_list_end);
671 desc_end = p + desc_len;
672 if (desc_end > desc_list_end)
675 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
679 service_type = get8(&p, p_end);
680 if (service_type < 0)
682 provider_name = getstr8(&p, p_end);
685 name = getstr8(&p, p_end);
688 new_service(ts, sid, provider_name, name);
700 mpegts_close_filter(ts, ts->sdt_filter);
701 ts->sdt_filter = NULL;
704 /* scan services in a transport stream by looking at the SDT */
705 static void mpegts_scan_sdt(MpegTSContext *ts)
707 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
711 /* scan services in a transport stream by looking at the PAT (better
713 static void mpegts_scan_pat(MpegTSContext *ts)
715 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
719 /* TS stream handling */
723 MPEGTS_PESHEADER_FILL,
728 /* enough for PES header + length */
729 #define PES_START_SIZE 9
730 #define MAX_PES_HEADER_SIZE (9 + 255)
736 AVFormatContext *stream;
738 enum MpegTSState state;
739 /* used to get the format */
744 uint8_t header[MAX_PES_HEADER_SIZE];
747 static int64_t get_pts(const uint8_t *p)
752 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
753 val = (p[1] << 8) | p[2];
754 pts |= (int64_t)(val >> 1) << 15;
755 val = (p[3] << 8) | p[4];
756 pts |= (int64_t)(val >> 1);
760 /* return non zero if a packet could be constructed */
761 static void mpegts_push_data(void *opaque,
762 const uint8_t *buf, int buf_size, int is_start)
764 PESContext *pes = opaque;
765 MpegTSContext *ts = pes->ts;
770 pes->state = MPEGTS_HEADER;
774 while (buf_size > 0) {
777 len = PES_START_SIZE - pes->data_index;
780 memcpy(pes->header + pes->data_index, p, len);
781 pes->data_index += len;
784 if (pes->data_index == PES_START_SIZE) {
785 /* we got all the PES or section header. We can now
788 av_hex_dump(pes->header, pes->data_index);
790 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
791 pes->header[2] == 0x01) {
792 /* it must be an mpeg2 PES stream */
793 code = pes->header[3] | 0x100;
794 if (!((code >= 0x1c0 && code <= 0x1df) ||
795 (code >= 0x1e0 && code <= 0x1ef) ||
799 /* allocate stream */
800 new_pes_av_stream(pes, code);
802 pes->state = MPEGTS_PESHEADER_FILL;
803 pes->total_size = (pes->header[4] << 8) | pes->header[5];
804 /* NOTE: a zero total size means the PES size is
807 pes->total_size += 6;
808 pes->pes_header_size = pes->header[8] + 9;
810 /* otherwise, it should be a table */
813 pes->state = MPEGTS_SKIP;
818 /**********************************************/
819 /* PES packing parsing */
820 case MPEGTS_PESHEADER_FILL:
821 len = pes->pes_header_size - pes->data_index;
824 memcpy(pes->header + pes->data_index, p, len);
825 pes->data_index += len;
828 if (pes->data_index == pes->pes_header_size) {
832 flags = pes->header[7];
834 pes->pts = AV_NOPTS_VALUE;
835 pes->dts = AV_NOPTS_VALUE;
836 if ((flags & 0xc0) == 0x80) {
837 pes->pts = get_pts(r);
839 } else if ((flags & 0xc0) == 0xc0) {
840 pes->pts = get_pts(r);
842 pes->dts = get_pts(r);
845 /* we got the full header. We parse it and get the payload */
846 pes->state = MPEGTS_PAYLOAD;
850 if (pes->total_size) {
851 len = pes->total_size - pes->data_index;
858 AVPacket *pkt = ts->pkt;
859 if (pes->st && av_new_packet(pkt, len) == 0) {
860 memcpy(pkt->data, p, len);
861 pkt->stream_index = pes->st->index;
864 /* reset pts values */
865 pes->pts = AV_NOPTS_VALUE;
866 pes->dts = AV_NOPTS_VALUE;
880 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
883 int codec_type, codec_id;
885 switch(pes->stream_type){
886 case STREAM_TYPE_AUDIO_MPEG1:
887 case STREAM_TYPE_AUDIO_MPEG2:
888 codec_type = CODEC_TYPE_AUDIO;
889 codec_id = CODEC_ID_MP3;
891 case STREAM_TYPE_VIDEO_MPEG1:
892 case STREAM_TYPE_VIDEO_MPEG2:
893 codec_type = CODEC_TYPE_VIDEO;
894 codec_id = CODEC_ID_MPEG2VIDEO;
896 case STREAM_TYPE_VIDEO_MPEG4:
897 codec_type = CODEC_TYPE_VIDEO;
898 codec_id = CODEC_ID_MPEG4;
900 case STREAM_TYPE_VIDEO_H264:
901 codec_type = CODEC_TYPE_VIDEO;
902 codec_id = CODEC_ID_H264;
904 case STREAM_TYPE_AUDIO_AAC:
905 codec_type = CODEC_TYPE_AUDIO;
906 codec_id = CODEC_ID_AAC;
908 case STREAM_TYPE_AUDIO_AC3:
909 codec_type = CODEC_TYPE_AUDIO;
910 codec_id = CODEC_ID_AC3;
912 case STREAM_TYPE_AUDIO_DTS:
913 codec_type = CODEC_TYPE_AUDIO;
914 codec_id = CODEC_ID_DTS;
916 case STREAM_TYPE_SUBTITLE_DVB:
917 codec_type = CODEC_TYPE_SUBTITLE;
918 codec_id = CODEC_ID_DVB_SUBTITLE;
921 if (code >= 0x1c0 && code <= 0x1df) {
922 codec_type = CODEC_TYPE_AUDIO;
923 codec_id = CODEC_ID_MP2;
924 } else if (code == 0x1bd) {
925 codec_type = CODEC_TYPE_AUDIO;
926 codec_id = CODEC_ID_AC3;
928 codec_type = CODEC_TYPE_VIDEO;
929 codec_id = CODEC_ID_MPEG1VIDEO;
933 st = av_new_stream(pes->stream, pes->pid);
935 av_set_pts_info(st, 33, 1, 90000);
937 st->codec->codec_type = codec_type;
938 st->codec->codec_id = codec_id;
939 st->need_parsing = 1;
946 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
951 /* if no pid found, then add a pid context */
952 pes = av_mallocz(sizeof(PESContext));
956 pes->stream = ts->stream;
958 pes->stream_type = stream_type;
959 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
967 /* handle one TS packet */
968 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
970 AVFormatContext *s = ts->stream;
972 int len, pid, cc, cc_ok, afc, is_start;
973 const uint8_t *p, *p_end;
975 pid = ((packet[1] & 0x1f) << 8) | packet[2];
976 is_start = packet[1] & 0x40;
978 if (ts->auto_guess && tss == NULL && is_start) {
979 add_pes_stream(ts, pid, 0);
985 /* continuity check (currently not used) */
986 cc = (packet[3] & 0xf);
987 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
990 /* skip adaptation field */
991 afc = (packet[3] >> 4) & 3;
993 if (afc == 0) /* reserved value */
995 if (afc == 2) /* adaptation field only */
998 /* skip adapation field */
1001 /* if past the end of packet, ignore */
1002 p_end = packet + TS_PACKET_SIZE;
1006 if (tss->type == MPEGTS_SECTION) {
1008 /* pointer field present */
1010 if (p + len > p_end)
1013 /* write remaining section bytes */
1014 write_section_data(s, tss,
1016 /* check whether filter has been closed */
1022 write_section_data(s, tss,
1027 write_section_data(s, tss,
1032 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
1033 p, p_end - p, is_start);
1037 /* XXX: try to find a better synchro over several packets (use
1038 get_packet_size() ?) */
1039 static int mpegts_resync(ByteIOContext *pb)
1043 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1048 url_fseek(pb, -1, SEEK_CUR);
1056 /* return -1 if error or EOF. Return 0 if OK. */
1057 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1062 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1063 if (len != TS_PACKET_SIZE)
1065 /* check paquet sync byte */
1066 if (buf[0] != 0x47) {
1067 /* find a new packet start */
1068 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1069 if (mpegts_resync(pb) < 0)
1070 return AVERROR_INVALIDDATA;
1074 skip = raw_packet_size - TS_PACKET_SIZE;
1076 url_fskip(pb, skip);
1083 static int handle_packets(MpegTSContext *ts, int nb_packets)
1085 AVFormatContext *s = ts->stream;
1086 ByteIOContext *pb = &s->pb;
1087 uint8_t packet[TS_PACKET_SIZE];
1088 int packet_num, ret;
1096 if (nb_packets != 0 && packet_num >= nb_packets)
1098 ret = read_packet(pb, packet, ts->raw_packet_size);
1101 handle_packet(ts, packet);
1106 static int mpegts_probe(AVProbeData *p)
1109 const int size= p->buf_size;
1110 int score, fec_score, dvhs_score;
1111 #define CHECK_COUNT 10
1113 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1116 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1117 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1118 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1119 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1121 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1122 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1123 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1124 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1127 /* only use the extension for safer guess */
1128 if (match_ext(p->filename, "ts"))
1129 return AVPROBE_SCORE_MAX;
1135 void set_service_cb(void *opaque, int ret)
1137 MpegTSContext *ts = opaque;
1138 ts->set_service_ret = ret;
1142 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1143 (-1) if not available */
1144 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1145 const uint8_t *packet)
1147 int afc, len, flags;
1151 afc = (packet[3] >> 4) & 3;
1161 if (!(flags & 0x10))
1165 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1166 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1167 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1171 static int mpegts_read_header(AVFormatContext *s,
1172 AVFormatParameters *ap)
1174 MpegTSContext *ts = s->priv_data;
1175 ByteIOContext *pb = &s->pb;
1179 MpegTSService *service;
1182 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1183 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1186 /* read the first 1024 bytes to get packet size */
1187 pos = url_ftell(pb);
1188 len = get_buffer(pb, buf, sizeof(buf));
1189 if (len != sizeof(buf))
1191 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1192 if (ts->raw_packet_size <= 0)
1198 if (!ts->mpeg2ts_raw) {
1201 if (!ts->auto_guess) {
1202 ts->set_service_ret = -1;
1204 /* first do a scaning to get all the services */
1205 url_fseek(pb, pos, SEEK_SET);
1206 mpegts_scan_sdt(ts);
1208 handle_packets(ts, s->probesize);
1210 if (ts->nb_services <= 0) {
1211 /* no SDT found, we try to look at the PAT */
1213 /* First remove the SDT filters from each PID */
1215 for (i=0; i < NB_PID_MAX; i++) {
1217 mpegts_close_filter(ts, ts->pids[i]);
1219 url_fseek(pb, pos, SEEK_SET);
1220 mpegts_scan_pat(ts);
1222 handle_packets(ts, s->probesize);
1225 if (ts->nb_services <= 0) {
1226 /* raw transport stream */
1228 s->ctx_flags |= AVFMTCTX_NOHEADER;
1232 /* tune to first service found */
1233 for(i=0; i<ts->nb_services && ts->set_service_ret; i++){
1234 service = ts->services[i];
1237 printf("tuning to '%s'\n", service->name);
1240 /* now find the info for the first service if we found any,
1241 otherwise try to filter all PATs */
1243 url_fseek(pb, pos, SEEK_SET);
1244 mpegts_set_service(ts, sid, set_service_cb, ts);
1246 handle_packets(ts, s->probesize);
1248 /* if could not find service, exit */
1250 if (ts->set_service_ret != 0) {
1254 //let's retry with auto_guess set
1256 goto goto_auto_guess;
1261 printf("tuning done\n");
1264 s->ctx_flags |= AVFMTCTX_NOHEADER;
1267 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1268 int64_t pcrs[2], pcr_h;
1269 int packet_count[2];
1270 uint8_t packet[TS_PACKET_SIZE];
1272 /* only read packets */
1275 st = av_new_stream(s, 0);
1278 av_set_pts_info(st, 60, 1, 27000000);
1279 st->codec->codec_type = CODEC_TYPE_DATA;
1280 st->codec->codec_id = CODEC_ID_MPEG2TS;
1282 /* we iterate until we find two PCRs to estimate the bitrate */
1287 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1290 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1291 if ((pcr_pid == -1 || pcr_pid == pid) &&
1292 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1294 packet_count[nb_pcrs] = nb_packets;
1295 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1302 ts->pcr_pid = pcr_pid;
1304 /* NOTE1: the bitrate is computed without the FEC */
1305 /* NOTE2: it is only the bitrate of the start of the stream */
1306 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1307 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1308 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1309 st->codec->bit_rate = s->bit_rate;
1310 st->start_time = ts->cur_pcr;
1312 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1313 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1317 url_fseek(pb, pos, SEEK_SET);
1323 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1325 static int mpegts_raw_read_packet(AVFormatContext *s,
1328 MpegTSContext *ts = s->priv_data;
1330 int64_t pcr_h, next_pcr_h, pos;
1331 int pcr_l, next_pcr_l;
1332 uint8_t pcr_buf[12];
1334 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1336 pkt->pos= url_ftell(&s->pb);
1337 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1339 av_free_packet(pkt);
1342 if (ts->mpeg2ts_compute_pcr) {
1343 /* compute exact PCR for each packet */
1344 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1345 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1346 pos = url_ftell(&s->pb);
1347 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1348 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1349 get_buffer(&s->pb, pcr_buf, 12);
1350 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1351 /* XXX: not precise enough */
1352 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1357 url_fseek(&s->pb, pos, SEEK_SET);
1358 /* no next PCR found: we use previous increment */
1359 ts->cur_pcr = pcr_h * 300 + pcr_l;
1361 pkt->pts = ts->cur_pcr;
1362 pkt->duration = ts->pcr_incr;
1363 ts->cur_pcr += ts->pcr_incr;
1365 pkt->stream_index = 0;
1369 static int mpegts_read_packet(AVFormatContext *s,
1372 MpegTSContext *ts = s->priv_data;
1374 if (!ts->mpeg2ts_raw) {
1376 return handle_packets(ts, 0);
1378 return mpegts_raw_read_packet(s, pkt);
1382 static int mpegts_read_close(AVFormatContext *s)
1384 MpegTSContext *ts = s->priv_data;
1386 for(i=0;i<NB_PID_MAX;i++)
1387 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1389 for(i = 0; i < ts->nb_services; i++){
1390 av_free(ts->services[i]->provider_name);
1391 av_free(ts->services[i]->name);
1392 av_free(ts->services[i]);
1394 av_freep(&ts->services);
1399 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1400 int64_t *ppos, int64_t pos_limit)
1402 MpegTSContext *ts = s->priv_data;
1403 int64_t pos, timestamp;
1404 uint8_t buf[TS_PACKET_SIZE];
1406 const int find_next= 1;
1407 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1410 url_fseek(&s->pb, pos, SEEK_SET);
1411 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1412 return AV_NOPTS_VALUE;
1413 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1414 if (pid == ts->pcr_pid &&
1415 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1418 pos += ts->raw_packet_size;
1422 pos -= ts->raw_packet_size;
1424 return AV_NOPTS_VALUE;
1425 url_fseek(&s->pb, pos, SEEK_SET);
1426 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1427 return AV_NOPTS_VALUE;
1428 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1429 if (pid == ts->pcr_pid &&
1430 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1440 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1441 MpegTSContext *ts = s->priv_data;
1442 uint8_t buf[TS_PACKET_SIZE];
1445 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1448 pos= url_ftell(&s->pb);
1451 url_fseek(&s->pb, pos, SEEK_SET);
1452 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1454 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1455 if(buf[1] & 0x40) break;
1456 pos += ts->raw_packet_size;
1458 url_fseek(&s->pb, pos, SEEK_SET);
1463 /**************************************************************/
1464 /* parsing functions - called from other demuxers such as RTP */
1466 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1470 ts = av_mallocz(sizeof(MpegTSContext));
1473 /* no stream case, currently used by RTP */
1474 ts->raw_packet_size = TS_PACKET_SIZE;
1480 /* return the consumed length if a packet was output, or -1 if no
1482 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1483 const uint8_t *buf, int len)
1493 if (len < TS_PACKET_SIZE)
1495 if (buf[0] != 0x47) {
1499 handle_packet(ts, buf);
1500 buf += TS_PACKET_SIZE;
1501 len -= TS_PACKET_SIZE;
1507 void mpegts_parse_close(MpegTSContext *ts)
1511 for(i=0;i<NB_PID_MAX;i++)
1512 av_free(ts->pids[i]);
1516 AVInputFormat mpegts_demuxer = {
1518 "MPEG2 transport stream format",
1519 sizeof(MpegTSContext),
1526 .flags = AVFMT_SHOW_IDS,