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 /** number of PMTs in the last PAT seen */
110 /** list of PMTs in the last PAT seen */
111 MpegTSService **services;
114 /** filters for various streams specified by PMT + for the PAT and PMT */
115 MpegTSFilter *pids[NB_PID_MAX];
118 /* TS stream handling */
122 MPEGTS_PESHEADER_FILL,
127 /* enough for PES header + length */
128 #define PES_START_SIZE 9
129 #define MAX_PES_HEADER_SIZE (9 + 255)
135 AVFormatContext *stream;
137 enum MpegTSState state;
138 /* used to get the format */
143 uint8_t header[MAX_PES_HEADER_SIZE];
147 * Assembles PES packets out of TS packets, and then calls the "section_cb"
148 * function when they are complete.
150 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
151 const uint8_t *buf, int buf_size, int is_start)
153 MpegTSSectionFilter *tss = &tss1->u.section_filter;
157 memcpy(tss->section_buf, buf, buf_size);
158 tss->section_index = buf_size;
159 tss->section_h_size = -1;
160 tss->end_of_section_reached = 0;
162 if (tss->end_of_section_reached)
164 len = 4096 - tss->section_index;
167 memcpy(tss->section_buf + tss->section_index, buf, len);
168 tss->section_index += len;
171 /* compute section length if possible */
172 if (tss->section_h_size == -1 && tss->section_index >= 3) {
173 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
176 tss->section_h_size = len;
179 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
180 tss->end_of_section_reached = 1;
181 if (!tss->check_crc ||
182 av_crc(av_crc04C11DB7, -1, tss->section_buf, tss->section_h_size) == 0)
183 tss->section_cb(tss1, tss->section_buf, tss->section_h_size);
187 static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
188 SectionCallback *section_cb, void *opaque,
192 MpegTSFilter *filter;
193 MpegTSSectionFilter *sec;
196 av_log(ts->stream, AV_LOG_DEBUG, "Filter: pid=0x%x\n", pid);
198 if (pid >= NB_PID_MAX || ts->pids[pid])
200 filter = av_mallocz(sizeof(MpegTSFilter));
203 ts->pids[pid] = filter;
204 filter->type = MPEGTS_SECTION;
206 filter->last_cc = -1;
207 sec = &filter->u.section_filter;
208 sec->section_cb = section_cb;
209 sec->opaque = opaque;
210 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
211 sec->check_crc = check_crc;
212 if (!sec->section_buf) {
219 static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
223 MpegTSFilter *filter;
224 MpegTSPESFilter *pes;
226 if (pid >= NB_PID_MAX || ts->pids[pid])
228 filter = av_mallocz(sizeof(MpegTSFilter));
231 ts->pids[pid] = filter;
232 filter->type = MPEGTS_PES;
234 filter->last_cc = -1;
235 pes = &filter->u.pes_filter;
236 pes->pes_cb = pes_cb;
237 pes->opaque = opaque;
241 static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
246 if (filter->type == MPEGTS_SECTION)
247 av_freep(&filter->u.section_filter.section_buf);
248 else if (filter->type == MPEGTS_PES)
249 av_freep(&filter->u.pes_filter.opaque);
252 ts->pids[pid] = NULL;
255 static int analyze(const uint8_t *buf, int size, int packet_size, int *index){
256 int stat[packet_size];
261 memset(stat, 0, packet_size*sizeof(int));
263 for(x=i=0; i<size; i++){
266 if(stat[x] > best_score){
273 if(x == packet_size) x= 0;
279 /* autodetect fec presence. Must have at least 1024 bytes */
280 static int get_packet_size(const uint8_t *buf, int size)
282 int score, fec_score, dvhs_score;
284 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
287 score = analyze(buf, size, TS_PACKET_SIZE, NULL);
288 dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL);
289 fec_score= analyze(buf, size, TS_FEC_PACKET_SIZE, NULL);
290 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
292 if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE;
293 else if(dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE;
294 else if(score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE;
298 typedef struct SectionHeader {
303 uint8_t last_sec_num;
306 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
319 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
325 if ((p + 1) >= p_end)
327 c = (p[0] << 8) | p[1];
333 /* read and allocate a DVB string preceeded by its length */
334 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
341 len = get8(&p, p_end);
344 if ((p + len) > p_end)
346 str = av_malloc(len + 1);
356 static int parse_section_header(SectionHeader *h,
357 const uint8_t **pp, const uint8_t *p_end)
361 val = get8(pp, p_end);
366 val = get16(pp, p_end);
370 val = get8(pp, p_end);
373 h->version = (val >> 1) & 0x1f;
374 val = get8(pp, p_end);
378 val = get8(pp, p_end);
381 h->last_sec_num = val;
385 static MpegTSService *new_service(MpegTSContext *ts, int sid,
386 char *provider_name, char *name)
388 MpegTSService *service=NULL;
392 av_log(ts->stream, AV_LOG_DEBUG, "new_service: "
393 "sid=0x%04x provider='%s' name='%s'\n",
394 sid, provider_name, name);
397 for(i=0; i<ts->nb_services; i++)
398 if(ts->services[i]->sid == sid)
399 service= ts->services[i];
402 service = av_mallocz(sizeof(MpegTSService));
405 dynarray_add(&ts->services, &ts->nb_services, service);
408 assert((!provider_name) == (!name));
410 av_free(service->provider_name);
411 av_free(service-> name);
412 service->provider_name = provider_name;
413 service-> name = name;
418 static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
420 MpegTSContext *ts = filter->u.section_filter.opaque;
421 SectionHeader h1, *h = &h1;
424 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
425 int program_info_length, pcr_pid, pid, stream_type;
426 int desc_list_len, desc_len, desc_tag;
427 int comp_page = 0, anc_page = 0; /* initialize to kill warnings */
428 char language[4] = {0}; /* initialize to kill warnings */
431 av_log(ts->stream, AV_LOG_DEBUG, "PMT: len %i\n", section_len);
432 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
434 p_end = section + section_len - 4;
436 if (parse_section_header(h, &p, p_end) < 0)
439 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x sec_num=%d/%d\n",
440 h->id, h->sec_num, h->last_sec_num);
442 if (h->tid != PMT_TID)
445 pcr_pid = get16(&p, p_end) & 0x1fff;
448 ts->pcr_pid = pcr_pid;
450 av_log(ts->stream, AV_LOG_DEBUG, "pcr_pid=0x%x\n", pcr_pid);
452 program_info_length = get16(&p, p_end) & 0xfff;
453 if (program_info_length < 0)
455 p += program_info_length;
461 stream_type = get8(&p, p_end);
464 pid = get16(&p, p_end) & 0x1fff;
467 desc_list_len = get16(&p, p_end) & 0xfff;
468 if (desc_list_len < 0)
470 desc_list_end = p + desc_list_len;
471 if (desc_list_end > p_end)
474 desc_tag = get8(&p, desc_list_end);
477 if (stream_type == STREAM_TYPE_PRIVATE_DATA) {
478 if((desc_tag == 0x6A) || (desc_tag == 0x7A)) {
479 /*assume DVB AC-3 Audio*/
480 stream_type = STREAM_TYPE_AUDIO_AC3;
481 } else if(desc_tag == 0x7B) {
483 stream_type = STREAM_TYPE_AUDIO_DTS;
486 desc_len = get8(&p, desc_list_end);
487 desc_end = p + desc_len;
488 if (desc_end > desc_list_end)
491 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
495 case DVB_SUBT_DESCID:
496 if (stream_type == STREAM_TYPE_PRIVATE_DATA)
497 stream_type = STREAM_TYPE_SUBTITLE_DVB;
499 language[0] = get8(&p, desc_end);
500 language[1] = get8(&p, desc_end);
501 language[2] = get8(&p, desc_end);
504 comp_page = get16(&p, desc_end);
505 anc_page = get16(&p, desc_end);
508 case 0x0a: /* ISO 639 language descriptor */
509 language[0] = get8(&p, desc_end);
510 language[1] = get8(&p, desc_end);
511 language[2] = get8(&p, desc_end);
522 av_log(ts->stream, AV_LOG_DEBUG, "stream_type=%d pid=0x%x\n",
526 /* now create ffmpeg stream */
527 switch(stream_type) {
528 case STREAM_TYPE_AUDIO_MPEG1:
529 case STREAM_TYPE_AUDIO_MPEG2:
530 case STREAM_TYPE_VIDEO_MPEG1:
531 case STREAM_TYPE_VIDEO_MPEG2:
532 case STREAM_TYPE_VIDEO_MPEG4:
533 case STREAM_TYPE_VIDEO_H264:
534 case STREAM_TYPE_VIDEO_VC1:
535 case STREAM_TYPE_AUDIO_AAC:
536 case STREAM_TYPE_AUDIO_AC3:
537 case STREAM_TYPE_AUDIO_DTS:
538 case STREAM_TYPE_SUBTITLE_DVB:
540 assert(ts->pids[pid].type == MPEGTS_PES);
541 pes= ts->pids[pid]->u.pes_filter.opaque;
544 pes = add_pes_stream(ts, pid, stream_type);
546 st = new_pes_av_stream(pes, 0);
550 /* we ignore the other streams */
555 if (language[0] != 0) {
556 st->language[0] = language[0];
557 st->language[1] = language[1];
558 st->language[2] = language[2];
559 st->language[3] = language[3];
562 if (stream_type == STREAM_TYPE_SUBTITLE_DVB) {
563 st->codec->sub_id = (anc_page << 16) | comp_page;
567 /* all parameters are there */
569 mpegts_close_filter(ts, filter);
572 static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
574 MpegTSContext *ts = filter->u.section_filter.opaque;
575 SectionHeader h1, *h = &h1;
576 const uint8_t *p, *p_end;
580 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
581 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
583 p_end = section + section_len - 4;
585 if (parse_section_header(h, &p, p_end) < 0)
587 if (h->tid != PAT_TID)
591 sid = get16(&p, p_end);
594 pmt_pid = get16(&p, p_end) & 0x1fff;
598 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
604 mpegts_open_section_filter(ts, pmt_pid,
611 mpegts_close_filter(ts, filter);
614 /* add all services found in the PAT */
615 static void pat_scan_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
617 MpegTSContext *ts = filter->u.section_filter.opaque;
618 SectionHeader h1, *h = &h1;
619 const uint8_t *p, *p_end;
623 av_log(ts->stream, AV_LOG_DEBUG, "PAT:\n");
624 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
626 p_end = section + section_len - 4;
628 if (parse_section_header(h, &p, p_end) < 0)
630 if (h->tid != PAT_TID)
634 sid = get16(&p, p_end);
637 pmt_pid = get16(&p, p_end) & 0x1fff;
641 av_log(ts->stream, AV_LOG_DEBUG, "sid=0x%x pid=0x%x\n", sid, pmt_pid);
646 new_service(ts, sid, NULL, NULL);
652 mpegts_close_filter(ts, filter);
655 static void mpegts_set_service(MpegTSContext *ts)
657 mpegts_open_section_filter(ts, PAT_PID,
661 static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len)
663 MpegTSContext *ts = filter->u.section_filter.opaque;
664 SectionHeader h1, *h = &h1;
665 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
666 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
667 char *name, *provider_name;
670 av_log(ts->stream, AV_LOG_DEBUG, "SDT:\n");
671 av_hex_dump_log(ts->stream, AV_LOG_DEBUG, (uint8_t *)section, section_len);
674 p_end = section + section_len - 4;
676 if (parse_section_header(h, &p, p_end) < 0)
678 if (h->tid != SDT_TID)
680 onid = get16(&p, p_end);
683 val = get8(&p, p_end);
687 sid = get16(&p, p_end);
690 val = get8(&p, p_end);
693 desc_list_len = get16(&p, p_end) & 0xfff;
694 if (desc_list_len < 0)
696 desc_list_end = p + desc_list_len;
697 if (desc_list_end > p_end)
700 desc_tag = get8(&p, desc_list_end);
703 desc_len = get8(&p, desc_list_end);
704 desc_end = p + desc_len;
705 if (desc_end > desc_list_end)
708 av_log(ts->stream, AV_LOG_DEBUG, "tag: 0x%02x len=%d\n",
713 service_type = get8(&p, p_end);
714 if (service_type < 0)
716 provider_name = getstr8(&p, p_end);
719 name = getstr8(&p, p_end);
722 new_service(ts, sid, provider_name, name);
733 /* scan services in a transport stream by looking at the SDT */
734 static void mpegts_scan_sdt(MpegTSContext *ts)
736 mpegts_open_section_filter(ts, SDT_PID,
740 /* scan services in a transport stream by looking at the PAT (better
742 static void mpegts_scan_pat(MpegTSContext *ts)
744 mpegts_open_section_filter(ts, PAT_PID,
748 static int64_t get_pts(const uint8_t *p)
753 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
754 val = (p[1] << 8) | p[2];
755 pts |= (int64_t)(val >> 1) << 15;
756 val = (p[3] << 8) | p[4];
757 pts |= (int64_t)(val >> 1);
761 /* return non zero if a packet could be constructed */
762 static void mpegts_push_data(MpegTSFilter *filter,
763 const uint8_t *buf, int buf_size, int is_start)
765 PESContext *pes = filter->u.pes_filter.opaque;
766 MpegTSContext *ts = pes->ts;
774 pes->state = MPEGTS_HEADER;
778 while (buf_size > 0) {
781 len = PES_START_SIZE - pes->data_index;
784 memcpy(pes->header + pes->data_index, p, len);
785 pes->data_index += len;
788 if (pes->data_index == PES_START_SIZE) {
789 /* we got all the PES or section header. We can now
792 av_hex_dump_log(pes->stream, AV_LOG_DEBUG, pes->header, pes->data_index);
794 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
795 pes->header[2] == 0x01) {
796 /* it must be an mpeg2 PES stream */
797 code = pes->header[3] | 0x100;
798 if (!((code >= 0x1c0 && code <= 0x1df) ||
799 (code >= 0x1e0 && code <= 0x1ef) ||
800 (code == 0x1bd) || (code == 0x1fd)))
803 /* allocate stream */
804 new_pes_av_stream(pes, code);
806 pes->state = MPEGTS_PESHEADER_FILL;
807 pes->total_size = (pes->header[4] << 8) | pes->header[5];
808 /* NOTE: a zero total size means the PES size is
811 pes->total_size += 6;
812 pes->pes_header_size = pes->header[8] + 9;
814 /* otherwise, it should be a table */
817 pes->state = MPEGTS_SKIP;
822 /**********************************************/
823 /* PES packing parsing */
824 case MPEGTS_PESHEADER_FILL:
825 len = pes->pes_header_size - pes->data_index;
828 memcpy(pes->header + pes->data_index, p, len);
829 pes->data_index += len;
832 if (pes->data_index == pes->pes_header_size) {
836 flags = pes->header[7];
838 pes->pts = AV_NOPTS_VALUE;
839 pes->dts = AV_NOPTS_VALUE;
840 if ((flags & 0xc0) == 0x80) {
841 pes->pts = get_pts(r);
843 } else if ((flags & 0xc0) == 0xc0) {
844 pes->pts = get_pts(r);
846 pes->dts = get_pts(r);
849 /* we got the full header. We parse it and get the payload */
850 pes->state = MPEGTS_PAYLOAD;
854 if (pes->total_size) {
855 len = pes->total_size - pes->data_index;
862 AVPacket *pkt = ts->pkt;
863 if (pes->st && av_new_packet(pkt, len) == 0) {
864 memcpy(pkt->data, p, len);
865 pkt->stream_index = pes->st->index;
868 /* reset pts values */
869 pes->pts = AV_NOPTS_VALUE;
870 pes->dts = AV_NOPTS_VALUE;
884 static AVStream* new_pes_av_stream(PESContext *pes, uint32_t code)
887 int codec_type, codec_id;
889 switch(pes->stream_type){
890 case STREAM_TYPE_AUDIO_MPEG1:
891 case STREAM_TYPE_AUDIO_MPEG2:
892 codec_type = CODEC_TYPE_AUDIO;
893 codec_id = CODEC_ID_MP3;
895 case STREAM_TYPE_VIDEO_MPEG1:
896 case STREAM_TYPE_VIDEO_MPEG2:
897 codec_type = CODEC_TYPE_VIDEO;
898 codec_id = CODEC_ID_MPEG2VIDEO;
900 case STREAM_TYPE_VIDEO_MPEG4:
901 codec_type = CODEC_TYPE_VIDEO;
902 codec_id = CODEC_ID_MPEG4;
904 case STREAM_TYPE_VIDEO_H264:
905 codec_type = CODEC_TYPE_VIDEO;
906 codec_id = CODEC_ID_H264;
908 case STREAM_TYPE_VIDEO_VC1:
909 codec_type = CODEC_TYPE_VIDEO;
910 codec_id = CODEC_ID_VC1;
912 case STREAM_TYPE_AUDIO_AAC:
913 codec_type = CODEC_TYPE_AUDIO;
914 codec_id = CODEC_ID_AAC;
916 case STREAM_TYPE_AUDIO_AC3:
917 codec_type = CODEC_TYPE_AUDIO;
918 codec_id = CODEC_ID_AC3;
920 case STREAM_TYPE_AUDIO_DTS:
921 codec_type = CODEC_TYPE_AUDIO;
922 codec_id = CODEC_ID_DTS;
924 case STREAM_TYPE_SUBTITLE_DVB:
925 codec_type = CODEC_TYPE_SUBTITLE;
926 codec_id = CODEC_ID_DVB_SUBTITLE;
929 if (code >= 0x1c0 && code <= 0x1df) {
930 codec_type = CODEC_TYPE_AUDIO;
931 codec_id = CODEC_ID_MP2;
932 } else if (code == 0x1bd) {
933 codec_type = CODEC_TYPE_AUDIO;
934 codec_id = CODEC_ID_AC3;
936 codec_type = CODEC_TYPE_VIDEO;
937 codec_id = CODEC_ID_MPEG1VIDEO;
941 st = av_new_stream(pes->stream, pes->pid);
943 av_set_pts_info(st, 33, 1, 90000);
945 st->codec->codec_type = codec_type;
946 st->codec->codec_id = codec_id;
947 st->need_parsing = AVSTREAM_PARSE_FULL;
954 static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
959 /* if no pid found, then add a pid context */
960 pes = av_mallocz(sizeof(PESContext));
964 pes->stream = ts->stream;
966 pes->stream_type = stream_type;
967 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
975 /* handle one TS packet */
976 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
978 AVFormatContext *s = ts->stream;
980 int len, pid, cc, cc_ok, afc, is_start;
981 const uint8_t *p, *p_end;
983 pid = ((packet[1] & 0x1f) << 8) | packet[2];
984 is_start = packet[1] & 0x40;
986 if (ts->auto_guess && tss == NULL && is_start) {
987 add_pes_stream(ts, pid, 0);
993 /* continuity check (currently not used) */
994 cc = (packet[3] & 0xf);
995 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
998 /* skip adaptation field */
999 afc = (packet[3] >> 4) & 3;
1001 if (afc == 0) /* reserved value */
1003 if (afc == 2) /* adaptation field only */
1006 /* skip adapation field */
1009 /* if past the end of packet, ignore */
1010 p_end = packet + TS_PACKET_SIZE;
1014 if (tss->type == MPEGTS_SECTION) {
1016 /* pointer field present */
1018 if (p + len > p_end)
1021 /* write remaining section bytes */
1022 write_section_data(s, tss,
1024 /* check whether filter has been closed */
1030 write_section_data(s, tss,
1035 write_section_data(s, tss,
1040 tss->u.pes_filter.pes_cb(tss,
1041 p, p_end - p, is_start);
1045 /* XXX: try to find a better synchro over several packets (use
1046 get_packet_size() ?) */
1047 static int mpegts_resync(ByteIOContext *pb)
1051 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
1056 url_fseek(pb, -1, SEEK_CUR);
1064 /* return -1 if error or EOF. Return 0 if OK. */
1065 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
1070 len = get_buffer(pb, buf, TS_PACKET_SIZE);
1071 if (len != TS_PACKET_SIZE)
1073 /* check paquet sync byte */
1074 if (buf[0] != 0x47) {
1075 /* find a new packet start */
1076 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
1077 if (mpegts_resync(pb) < 0)
1078 return AVERROR_INVALIDDATA;
1082 skip = raw_packet_size - TS_PACKET_SIZE;
1084 url_fskip(pb, skip);
1091 static int handle_packets(MpegTSContext *ts, int nb_packets)
1093 AVFormatContext *s = ts->stream;
1094 ByteIOContext *pb = &s->pb;
1095 uint8_t packet[TS_PACKET_SIZE];
1096 int packet_num, ret;
1101 if (ts->stop_parse>0)
1104 if (nb_packets != 0 && packet_num >= nb_packets)
1106 ret = read_packet(pb, packet, ts->raw_packet_size);
1109 handle_packet(ts, packet);
1114 static int mpegts_probe(AVProbeData *p)
1117 const int size= p->buf_size;
1118 int score, fec_score, dvhs_score;
1119 #define CHECK_COUNT 10
1121 if (size < (TS_FEC_PACKET_SIZE * CHECK_COUNT))
1124 score = analyze(p->buf, TS_PACKET_SIZE *CHECK_COUNT, TS_PACKET_SIZE, NULL);
1125 dvhs_score = analyze(p->buf, TS_DVHS_PACKET_SIZE *CHECK_COUNT, TS_DVHS_PACKET_SIZE, NULL);
1126 fec_score= analyze(p->buf, TS_FEC_PACKET_SIZE*CHECK_COUNT, TS_FEC_PACKET_SIZE, NULL);
1127 // av_log(NULL, AV_LOG_DEBUG, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score);
1129 // we need a clear definition for the returned score otherwise things will become messy sooner or later
1130 if (score > fec_score && score > dvhs_score && score > 6) return AVPROBE_SCORE_MAX + score - CHECK_COUNT;
1131 else if(dvhs_score > score && dvhs_score > fec_score && dvhs_score > 6) return AVPROBE_SCORE_MAX + dvhs_score - CHECK_COUNT;
1132 else if( fec_score > 6) return AVPROBE_SCORE_MAX + fec_score - CHECK_COUNT;
1135 /* only use the extension for safer guess */
1136 if (match_ext(p->filename, "ts"))
1137 return AVPROBE_SCORE_MAX;
1143 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1144 (-1) if not available */
1145 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1146 const uint8_t *packet)
1148 int afc, len, flags;
1152 afc = (packet[3] >> 4) & 3;
1162 if (!(flags & 0x10))
1166 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1167 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1168 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1172 static int mpegts_read_header(AVFormatContext *s,
1173 AVFormatParameters *ap)
1175 MpegTSContext *ts = s->priv_data;
1176 ByteIOContext *pb = &s->pb;
1180 MpegTSService *service;
1183 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1184 if(ap->mpeg2ts_raw){
1185 av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");
1190 /* read the first 1024 bytes to get packet size */
1191 pos = url_ftell(pb);
1192 len = get_buffer(pb, buf, sizeof(buf));
1193 if (len != sizeof(buf))
1195 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1196 if (ts->raw_packet_size <= 0)
1201 if (s->iformat == &mpegts_demuxer) {
1204 /* first do a scaning to get all the services */
1205 url_fseek(pb, pos, SEEK_SET);
1206 mpegts_scan_sdt(ts);
1208 if (ts->nb_services <= 0) {
1209 mpegts_scan_pat(ts);
1211 handle_packets(ts, s->probesize);
1214 if (ts->nb_services <= 0) {
1215 /* raw transport stream */
1217 s->ctx_flags |= AVFMTCTX_NOHEADER;
1221 url_fseek(pb, pos, SEEK_SET);
1222 mpegts_set_service(ts);
1224 handle_packets(ts, s->probesize);
1225 /* if could not find service, enable auto_guess */
1230 av_log(ts->stream, AV_LOG_DEBUG, "tuning done\n");
1232 s->ctx_flags |= AVFMTCTX_NOHEADER;
1235 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1236 int64_t pcrs[2], pcr_h;
1237 int packet_count[2];
1238 uint8_t packet[TS_PACKET_SIZE];
1240 /* only read packets */
1243 st = av_new_stream(s, 0);
1246 av_set_pts_info(st, 60, 1, 27000000);
1247 st->codec->codec_type = CODEC_TYPE_DATA;
1248 st->codec->codec_id = CODEC_ID_MPEG2TS;
1250 /* we iterate until we find two PCRs to estimate the bitrate */
1255 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1258 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1259 if ((pcr_pid == -1 || pcr_pid == pid) &&
1260 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1262 packet_count[nb_pcrs] = nb_packets;
1263 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1270 ts->pcr_pid = pcr_pid;
1272 /* NOTE1: the bitrate is computed without the FEC */
1273 /* NOTE2: it is only the bitrate of the start of the stream */
1274 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1275 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1276 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1277 st->codec->bit_rate = s->bit_rate;
1278 st->start_time = ts->cur_pcr;
1280 av_log(ts->stream, AV_LOG_DEBUG, "start=%0.3f pcr=%0.3f incr=%d\n",
1281 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1285 url_fseek(pb, pos, SEEK_SET);
1291 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1293 static int mpegts_raw_read_packet(AVFormatContext *s,
1296 MpegTSContext *ts = s->priv_data;
1298 int64_t pcr_h, next_pcr_h, pos;
1299 int pcr_l, next_pcr_l;
1300 uint8_t pcr_buf[12];
1302 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1303 return AVERROR(ENOMEM);
1304 pkt->pos= url_ftell(&s->pb);
1305 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1307 av_free_packet(pkt);
1310 if (ts->mpeg2ts_compute_pcr) {
1311 /* compute exact PCR for each packet */
1312 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1313 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1314 pos = url_ftell(&s->pb);
1315 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1316 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1317 get_buffer(&s->pb, pcr_buf, 12);
1318 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1319 /* XXX: not precise enough */
1320 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1325 url_fseek(&s->pb, pos, SEEK_SET);
1326 /* no next PCR found: we use previous increment */
1327 ts->cur_pcr = pcr_h * 300 + pcr_l;
1329 pkt->pts = ts->cur_pcr;
1330 pkt->duration = ts->pcr_incr;
1331 ts->cur_pcr += ts->pcr_incr;
1333 pkt->stream_index = 0;
1337 static int mpegts_read_packet(AVFormatContext *s,
1340 MpegTSContext *ts = s->priv_data;
1343 return handle_packets(ts, 0);
1346 static int mpegts_read_close(AVFormatContext *s)
1348 MpegTSContext *ts = s->priv_data;
1350 for(i=0;i<NB_PID_MAX;i++)
1351 if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]);
1353 for(i = 0; i < ts->nb_services; i++){
1354 av_free(ts->services[i]->provider_name);
1355 av_free(ts->services[i]->name);
1356 av_free(ts->services[i]);
1358 av_freep(&ts->services);
1363 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1364 int64_t *ppos, int64_t pos_limit)
1366 MpegTSContext *ts = s->priv_data;
1367 int64_t pos, timestamp;
1368 uint8_t buf[TS_PACKET_SIZE];
1370 const int find_next= 1;
1371 pos = ((*ppos + ts->raw_packet_size - 1) / ts->raw_packet_size) * ts->raw_packet_size;
1374 url_fseek(&s->pb, pos, SEEK_SET);
1375 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1376 return AV_NOPTS_VALUE;
1377 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1378 if (pid == ts->pcr_pid &&
1379 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1382 pos += ts->raw_packet_size;
1386 pos -= ts->raw_packet_size;
1388 return AV_NOPTS_VALUE;
1389 url_fseek(&s->pb, pos, SEEK_SET);
1390 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1391 return AV_NOPTS_VALUE;
1392 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1393 if (pid == ts->pcr_pid &&
1394 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1404 static int read_seek(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){
1405 MpegTSContext *ts = s->priv_data;
1406 uint8_t buf[TS_PACKET_SIZE];
1409 if(av_seek_frame_binary(s, stream_index, target_ts, flags) < 0)
1412 pos= url_ftell(&s->pb);
1415 url_fseek(&s->pb, pos, SEEK_SET);
1416 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1418 // pid = ((buf[1] & 0x1f) << 8) | buf[2];
1419 if(buf[1] & 0x40) break;
1420 pos += ts->raw_packet_size;
1422 url_fseek(&s->pb, pos, SEEK_SET);
1427 /**************************************************************/
1428 /* parsing functions - called from other demuxers such as RTP */
1430 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1434 ts = av_mallocz(sizeof(MpegTSContext));
1437 /* no stream case, currently used by RTP */
1438 ts->raw_packet_size = TS_PACKET_SIZE;
1444 /* return the consumed length if a packet was output, or -1 if no
1446 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1447 const uint8_t *buf, int len)
1455 if (ts->stop_parse>0)
1457 if (len < TS_PACKET_SIZE)
1459 if (buf[0] != 0x47) {
1463 handle_packet(ts, buf);
1464 buf += TS_PACKET_SIZE;
1465 len -= TS_PACKET_SIZE;
1471 void mpegts_parse_close(MpegTSContext *ts)
1475 for(i=0;i<NB_PID_MAX;i++)
1476 av_free(ts->pids[i]);
1480 AVInputFormat mpegts_demuxer = {
1482 "MPEG2 transport stream format",
1483 sizeof(MpegTSContext),
1490 .flags = AVFMT_SHOW_IDS,
1493 AVInputFormat mpegtsraw_demuxer = {
1495 "MPEG2 raw transport stream format",
1496 sizeof(MpegTSContext),
1499 mpegts_raw_read_packet,
1503 .flags = AVFMT_SHOW_IDS,