2 * MPEG2 transport stream (aka DVB) demux
3 * Copyright (c) 2002-2003 Fabrice Bellard.
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2 of the License, or (at your option) any later version.
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 /* 1.0 second at 24Mbit/s */
26 #define MAX_SCAN_PACKETS 32000
28 /* maximum size in which we look for synchronisation if
29 synchronisation is lost */
30 #define MAX_RESYNC_SIZE 4096
32 static int add_pes_stream(AVFormatContext *s, int pid);
34 enum MpegTSFilterType {
39 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
41 typedef struct MpegTSPESFilter {
46 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
48 typedef void SetServiceCallback(void *opaque, int ret);
50 typedef struct MpegTSSectionFilter {
55 int end_of_section_reached:1;
56 SectionCallback *section_cb;
58 } MpegTSSectionFilter;
60 typedef struct MpegTSFilter {
62 int last_cc; /* last cc code (-1 if first packet) */
63 enum MpegTSFilterType type;
65 MpegTSPESFilter pes_filter;
66 MpegTSSectionFilter section_filter;
70 typedef struct MpegTSService {
77 typedef struct MpegTSContext {
79 AVFormatContext *stream;
80 int raw_packet_size; /* raw packet size, including FEC if present */
81 int auto_guess; /* if true, all pids are analized to find streams */
84 /* data needed to handle file based ts */
85 int stop_parse; /* stop parsing loop */
86 AVPacket *pkt; /* packet containing av data */
88 /******************************************/
89 /* private mpegts data */
91 MpegTSFilter *sdt_filter;
93 MpegTSService **services;
95 /* set service context (XXX: allocated it ?) */
96 SetServiceCallback *set_service_cb;
97 void *set_service_opaque;
98 MpegTSFilter *pat_filter;
99 MpegTSFilter *pmt_filter;
102 MpegTSFilter *pids[NB_PID_MAX];
105 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
106 const uint8_t *buf, int buf_size, int is_start)
108 MpegTSSectionFilter *tss = &tss1->u.section_filter;
113 memcpy(tss->section_buf, buf, buf_size);
114 tss->section_index = buf_size;
115 tss->section_h_size = -1;
116 tss->end_of_section_reached = 0;
118 if (tss->end_of_section_reached)
120 len = 4096 - tss->section_index;
123 memcpy(tss->section_buf + tss->section_index, buf, len);
124 tss->section_index += len;
127 /* compute section length if possible */
128 if (tss->section_h_size == -1 && tss->section_index >= 3) {
129 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
132 tss->section_h_size = len;
135 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
136 if (tss->check_crc) {
137 crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
141 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
143 tss->end_of_section_reached = 1;
147 MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
148 SectionCallback *section_cb, void *opaque,
152 MpegTSFilter *filter;
153 MpegTSSectionFilter *sec;
155 if (pid >= NB_PID_MAX || ts->pids[pid])
157 filter = av_mallocz(sizeof(MpegTSFilter));
160 ts->pids[pid] = filter;
161 filter->type = MPEGTS_SECTION;
163 filter->last_cc = -1;
164 sec = &filter->u.section_filter;
165 sec->section_cb = section_cb;
166 sec->opaque = opaque;
167 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
168 sec->check_crc = check_crc;
169 if (!sec->section_buf) {
176 MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
180 MpegTSFilter *filter;
181 MpegTSPESFilter *pes;
183 if (pid >= NB_PID_MAX || ts->pids[pid])
185 filter = av_mallocz(sizeof(MpegTSFilter));
188 ts->pids[pid] = filter;
189 filter->type = MPEGTS_PES;
191 filter->last_cc = -1;
192 pes = &filter->u.pes_filter;
193 pes->pes_cb = pes_cb;
194 pes->opaque = opaque;
198 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
203 if (filter->type == MPEGTS_SECTION)
204 av_freep(&filter->u.section_filter.section_buf);
206 ts->pids[pid] = NULL;
209 /* autodetect fec presence. Must have at least 1024 bytes */
210 static int get_packet_size(const uint8_t *buf, int size)
214 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
217 if (buf[i * TS_PACKET_SIZE] != 0x47)
220 return TS_PACKET_SIZE;
223 if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
226 return TS_FEC_PACKET_SIZE;
229 typedef struct SectionHeader {
234 uint8_t last_sec_num;
237 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
250 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
256 if ((p + 1) >= p_end)
258 c = (p[0] << 8) | p[1];
264 /* read and allocate a DVB string preceeded by its length */
265 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
272 len = get8(&p, p_end);
275 if ((p + len) > p_end)
277 str = av_malloc(len + 1);
287 static int parse_section_header(SectionHeader *h,
288 const uint8_t **pp, const uint8_t *p_end)
292 val = get8(pp, p_end);
297 val = get16(pp, p_end);
301 val = get8(pp, p_end);
304 h->version = (val >> 1) & 0x1f;
305 val = get8(pp, p_end);
309 val = get8(pp, p_end);
312 h->last_sec_num = val;
316 static MpegTSService *new_service(MpegTSContext *ts, int sid,
317 char *provider_name, char *name)
319 MpegTSService *service;
322 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
323 sid, provider_name, name);
326 service = av_mallocz(sizeof(MpegTSService));
330 service->provider_name = provider_name;
331 service->name = name;
332 dynarray_add(&ts->services, &ts->nb_services, service);
336 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
338 MpegTSContext *ts = opaque;
339 SectionHeader h1, *h = &h1;
340 const uint8_t *p, *p_end;
341 int program_info_length, pcr_pid, pid, stream_type, desc_length;
345 av_hex_dump((uint8_t *)section, section_len);
347 p_end = section + section_len - 4;
349 if (parse_section_header(h, &p, p_end) < 0)
352 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
354 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
357 pcr_pid = get16(&p, p_end) & 0x1fff;
361 printf("pcr_pid=0x%x\n", pcr_pid);
363 program_info_length = get16(&p, p_end) & 0xfff;
364 if (program_info_length < 0)
366 p += program_info_length;
370 stream_type = get8(&p, p_end);
373 pid = get16(&p, p_end) & 0x1fff;
376 desc_length = get16(&p, p_end) & 0xfff;
384 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
387 /* now create ffmpeg stream */
388 switch(stream_type) {
389 case STREAM_TYPE_AUDIO_MPEG1:
390 case STREAM_TYPE_AUDIO_MPEG2:
391 case STREAM_TYPE_VIDEO_MPEG1:
392 case STREAM_TYPE_VIDEO_MPEG2:
393 case STREAM_TYPE_AUDIO_AC3:
394 add_pes_stream(ts->stream, pid);
397 /* we ignore the other streams */
401 /* all parameters are there */
402 ts->set_service_cb(ts->set_service_opaque, 0);
403 mpegts_close_filter(ts, ts->pmt_filter);
404 ts->pmt_filter = NULL;
407 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
409 MpegTSContext *ts = opaque;
410 SectionHeader h1, *h = &h1;
411 const uint8_t *p, *p_end;
416 av_hex_dump((uint8_t *)section, section_len);
418 p_end = section + section_len - 4;
420 if (parse_section_header(h, &p, p_end) < 0)
422 if (h->tid != PAT_TID)
426 sid = get16(&p, p_end);
429 pmt_pid = get16(&p, p_end) & 0x1fff;
433 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
438 if (ts->req_sid == sid) {
439 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
446 ts->set_service_cb(ts->set_service_opaque, -1);
449 mpegts_close_filter(ts, ts->pat_filter);
450 ts->pat_filter = NULL;
453 /* add all services found in the PAT */
454 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
456 MpegTSContext *ts = opaque;
457 SectionHeader h1, *h = &h1;
458 const uint8_t *p, *p_end;
460 char *provider_name, *name;
465 av_hex_dump((uint8_t *)section, section_len);
467 p_end = section + section_len - 4;
469 if (parse_section_header(h, &p, p_end) < 0)
471 if (h->tid != PAT_TID)
475 sid = get16(&p, p_end);
478 pmt_pid = get16(&p, p_end) & 0x1fff;
482 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
487 /* add the service with a dummy name */
488 snprintf(buf, sizeof(buf), "Service %x\n", sid);
489 name = av_strdup(buf);
490 provider_name = av_strdup("");
491 if (name && provider_name) {
492 new_service(ts, sid, provider_name, name);
495 av_freep(&provider_name);
502 mpegts_close_filter(ts, ts->pat_filter);
503 ts->pat_filter = NULL;
506 void mpegts_set_service(MpegTSContext *ts, int sid,
507 SetServiceCallback *set_service_cb, void *opaque)
509 ts->set_service_cb = set_service_cb;
510 ts->set_service_opaque = opaque;
512 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
516 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
518 MpegTSContext *ts = opaque;
519 SectionHeader h1, *h = &h1;
520 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
521 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
522 char *name, *provider_name;
526 av_hex_dump((uint8_t *)section, section_len);
529 p_end = section + section_len - 4;
531 if (parse_section_header(h, &p, p_end) < 0)
533 if (h->tid != SDT_TID)
535 onid = get16(&p, p_end);
538 val = get8(&p, p_end);
542 sid = get16(&p, p_end);
545 val = get8(&p, p_end);
548 desc_list_len = get16(&p, p_end) & 0xfff;
549 if (desc_list_len < 0)
551 desc_list_end = p + desc_list_len;
552 if (desc_list_end > p_end)
555 desc_tag = get8(&p, desc_list_end);
558 desc_len = get8(&p, desc_list_end);
559 desc_end = p + desc_len;
560 if (desc_end > desc_list_end)
563 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
567 service_type = get8(&p, p_end);
568 if (service_type < 0)
570 provider_name = getstr8(&p, p_end);
573 name = getstr8(&p, p_end);
576 new_service(ts, sid, provider_name, name);
588 mpegts_close_filter(ts, ts->sdt_filter);
589 ts->sdt_filter = NULL;
592 /* scan services in a transport stream by looking at the SDT */
593 void mpegts_scan_sdt(MpegTSContext *ts)
595 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
599 /* scan services in a transport stream by looking at the PAT (better
601 void mpegts_scan_pat(MpegTSContext *ts)
603 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
607 /* TS stream handling */
611 MPEGTS_PESHEADER_FILL,
616 /* enough for PES header + length */
617 #define PES_START_SIZE 9
618 #define MAX_PES_HEADER_SIZE (9 + 255)
620 typedef struct PESContext {
622 AVFormatContext *stream;
624 enum MpegTSState state;
625 /* used to get the format */
630 uint8_t header[MAX_PES_HEADER_SIZE];
633 static int64_t get_pts(const uint8_t *p)
638 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
639 val = (p[1] << 8) | p[2];
640 pts |= (int64_t)(val >> 1) << 15;
641 val = (p[3] << 8) | p[4];
642 pts |= (int64_t)(val >> 1);
646 /* return non zero if a packet could be constructed */
647 static void mpegts_push_data(void *opaque,
648 const uint8_t *buf, int buf_size, int is_start)
650 PESContext *pes = opaque;
651 MpegTSContext *ts = pes->stream->priv_data;
654 int len, code, codec_type, codec_id;
657 pes->state = MPEGTS_HEADER;
661 while (buf_size > 0) {
664 len = PES_START_SIZE - pes->data_index;
667 memcpy(pes->header + pes->data_index, p, len);
668 pes->data_index += len;
671 if (pes->data_index == PES_START_SIZE) {
672 /* we got all the PES or section header. We can now
675 av_hex_dump(pes->header, pes->data_index);
677 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
678 pes->header[2] == 0x01) {
679 /* it must be an mpeg2 PES stream */
680 code = pes->header[3] | 0x100;
681 if (!((code >= 0x1c0 && code <= 0x1df) ||
682 (code >= 0x1e0 && code <= 0x1ef) ||
686 /* allocate stream */
687 if (code >= 0x1c0 && code <= 0x1df) {
688 codec_type = CODEC_TYPE_AUDIO;
689 codec_id = CODEC_ID_MP2;
690 } else if (code == 0x1bd) {
691 codec_type = CODEC_TYPE_AUDIO;
692 codec_id = CODEC_ID_AC3;
694 codec_type = CODEC_TYPE_VIDEO;
695 codec_id = CODEC_ID_MPEG1VIDEO;
697 st = av_new_stream(pes->stream, pes->pid);
700 st->codec.codec_type = codec_type;
701 st->codec.codec_id = codec_id;
705 pes->state = MPEGTS_PESHEADER_FILL;
706 pes->total_size = (pes->header[4] << 8) | pes->header[5];
707 /* NOTE: a zero total size means the PES size is
710 pes->total_size += 6;
711 pes->pes_header_size = pes->header[8] + 9;
713 /* otherwise, it should be a table */
716 pes->state = MPEGTS_SKIP;
721 /**********************************************/
722 /* PES packing parsing */
723 case MPEGTS_PESHEADER_FILL:
724 len = pes->pes_header_size - pes->data_index;
727 memcpy(pes->header + pes->data_index, p, len);
728 pes->data_index += len;
731 if (pes->data_index == pes->pes_header_size) {
735 flags = pes->header[7];
737 pes->pts = AV_NOPTS_VALUE;
738 pes->dts = AV_NOPTS_VALUE;
739 if ((flags & 0xc0) == 0x80) {
740 pes->pts = get_pts(r);
742 } else if ((flags & 0xc0) == 0xc0) {
743 pes->pts = get_pts(r);
745 pes->dts = get_pts(r);
748 /* we got the full header. We parse it and get the payload */
749 pes->state = MPEGTS_PAYLOAD;
753 if (pes->total_size) {
754 len = pes->total_size - pes->data_index;
761 AVPacket *pkt = ts->pkt;
762 if (pes->st && av_new_packet(pkt, len) == 0) {
763 memcpy(pkt->data, p, len);
764 pkt->stream_index = pes->st->index;
766 /* reset pts values */
767 pes->pts = AV_NOPTS_VALUE;
768 pes->dts = AV_NOPTS_VALUE;
782 static int add_pes_stream(AVFormatContext *s, int pid)
784 MpegTSContext *ts = s->priv_data;
788 /* if no pid found, then add a pid context */
789 pes = av_mallocz(sizeof(PESContext));
794 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
802 /* handle one TS packet */
803 static void handle_packet(AVFormatContext *s, uint8_t *packet)
805 MpegTSContext *ts = s->priv_data;
807 int len, pid, cc, cc_ok, afc, is_start;
808 const uint8_t *p, *p_end;
810 pid = ((packet[1] & 0x1f) << 8) | packet[2];
811 is_start = packet[1] & 0x40;
813 if (ts->auto_guess && tss == NULL && is_start) {
814 add_pes_stream(s, pid);
820 /* continuity check (currently not used) */
821 cc = (packet[3] & 0xf);
822 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
825 /* skip adaptation field */
826 afc = (packet[3] >> 4) & 3;
828 if (afc == 0) /* reserved value */
830 if (afc == 2) /* adaptation field only */
833 /* skip adapation field */
836 /* if past the end of packet, ignore */
837 p_end = packet + TS_PACKET_SIZE;
841 if (tss->type == MPEGTS_SECTION) {
843 /* pointer field present */
848 /* write remaning section bytes */
849 write_section_data(s, tss,
854 write_section_data(s, tss,
859 write_section_data(s, tss,
864 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
865 p, p_end - p, is_start);
869 /* XXX: try to find a better synchro over several packets (use
870 get_packet_size() ?) */
871 static int mpegts_resync(AVFormatContext *s)
873 ByteIOContext *pb = &s->pb;
876 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
881 url_fseek(pb, -1, SEEK_CUR);
889 static int handle_packets(AVFormatContext *s, int nb_packets)
891 MpegTSContext *ts = s->priv_data;
892 ByteIOContext *pb = &s->pb;
893 uint8_t packet[TS_FEC_PACKET_SIZE];
903 if (nb_packets != 0 && packet_num >= nb_packets)
906 len = get_buffer(pb, packet, ts->raw_packet_size);
907 if (len != ts->raw_packet_size)
909 /* check paquet sync byte */
910 if (packet[0] != 0x47) {
911 /* find a new packet start */
912 url_fseek(pb, -ts->raw_packet_size, SEEK_CUR);
913 if (mpegts_resync(s) < 0)
914 return AVERROR_INVALIDDATA;
918 handle_packet(s, packet);
923 static int mpegts_probe(AVProbeData *p)
927 size = get_packet_size(p->buf, p->buf_size);
930 return AVPROBE_SCORE_MAX - 1;
932 /* only use the extension for safer guess */
933 if (match_ext(p->filename, "ts"))
934 return AVPROBE_SCORE_MAX;
940 void set_service_cb(void *opaque, int ret)
942 MpegTSContext *ts = opaque;
943 ts->set_service_ret = ret;
947 static int mpegts_read_header(AVFormatContext *s,
948 AVFormatParameters *ap)
950 MpegTSContext *ts = s->priv_data;
951 ByteIOContext *pb = &s->pb;
955 MpegTSService *service;
957 /* read the first 1024 bytes to get packet size */
959 len = get_buffer(pb, buf, sizeof(buf));
960 if (len != sizeof(buf))
962 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
963 if (ts->raw_packet_size <= 0)
967 if (!ts->auto_guess) {
968 ts->set_service_ret = -1;
970 /* first do a scaning to get all the services */
971 url_fseek(pb, pos, SEEK_SET);
974 handle_packets(s, MAX_SCAN_PACKETS);
976 if (ts->nb_services <= 0) {
977 /* no SDT found, we try to look at the PAT */
979 url_fseek(pb, pos, SEEK_SET);
982 handle_packets(s, MAX_SCAN_PACKETS);
985 if (ts->nb_services <= 0)
988 /* tune to first service found */
989 service = ts->services[0];
992 printf("tuning to '%s'\n", service->name);
995 /* now find the info for the first service if we found any,
996 otherwise try to filter all PATs */
998 url_fseek(pb, pos, SEEK_SET);
1000 mpegts_set_service(ts, sid, set_service_cb, ts);
1002 handle_packets(s, MAX_SCAN_PACKETS);
1004 /* if could not find service, exit */
1005 if (ts->set_service_ret != 0)
1009 printf("tuning done\n");
1013 url_fseek(pb, pos, SEEK_SET);
1019 static int mpegts_read_packet(AVFormatContext *s,
1022 MpegTSContext *ts = s->priv_data;
1024 return handle_packets(s, 0);
1027 static int mpegts_read_close(AVFormatContext *s)
1029 MpegTSContext *ts = s->priv_data;
1031 for(i=0;i<NB_PID_MAX;i++)
1032 av_free(ts->pids[i]);
1036 AVInputFormat mpegts_demux = {
1038 "MPEG2 transport stream format",
1039 sizeof(MpegTSContext),
1044 .flags = AVFMT_NOHEADER | AVFMT_SHOW_IDS,
1047 int mpegts_init(void)
1049 av_register_input_format(&mpegts_demux);
1050 av_register_output_format(&mpegts_mux);