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 16000
28 static int add_pes_stream(AVFormatContext *s, int pid);
30 enum MpegTSFilterType {
35 /* XXX: suppress 'pkt' parameter */
36 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
38 typedef struct MpegTSPESFilter {
43 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
45 typedef void SetServiceCallback(void *opaque, int ret);
47 typedef struct MpegTSSectionFilter {
52 int end_of_section_reached:1;
53 SectionCallback *section_cb;
55 } MpegTSSectionFilter;
57 typedef struct MpegTSFilter {
59 int last_cc; /* last cc code (-1 if first packet) */
60 enum MpegTSFilterType type;
62 MpegTSPESFilter pes_filter;
63 MpegTSSectionFilter section_filter;
67 typedef struct MpegTSService {
74 typedef struct MpegTSContext {
76 AVFormatContext *stream;
77 int raw_packet_size; /* raw packet size, including FEC if present */
78 int auto_guess; /* if true, all pids are analized to find streams */
81 /* data needed to handle file based ts */
82 int stop_parse; /* stop parsing loop */
83 AVPacket *pkt; /* packet containing av data */
85 /******************************************/
86 /* private mpegts data */
88 MpegTSFilter *sdt_filter;
90 MpegTSService **services;
92 /* set service context (XXX: allocated it ?) */
93 SetServiceCallback *set_service_cb;
94 void *set_service_opaque;
95 MpegTSFilter *pat_filter;
96 MpegTSFilter *pmt_filter;
99 MpegTSFilter *pids[NB_PID_MAX];
102 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
103 const uint8_t *buf, int buf_size, int is_start)
105 MpegTSSectionFilter *tss = &tss1->u.section_filter;
110 memcpy(tss->section_buf, buf, buf_size);
111 tss->section_index = buf_size;
112 tss->section_h_size = -1;
113 tss->end_of_section_reached = 0;
115 if (tss->end_of_section_reached)
117 len = 4096 - tss->section_index;
120 memcpy(tss->section_buf + tss->section_index, buf, len);
121 tss->section_index += len;
124 /* compute section length if possible */
125 if (tss->section_h_size == -1 && tss->section_index >= 3) {
126 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
129 tss->section_h_size = len;
132 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
133 if (tss->check_crc) {
134 crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
138 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
140 tss->end_of_section_reached = 1;
144 MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid,
145 SectionCallback *section_cb, void *opaque,
149 MpegTSFilter *filter;
150 MpegTSSectionFilter *sec;
152 if (pid >= NB_PID_MAX || ts->pids[pid])
154 filter = av_mallocz(sizeof(MpegTSFilter));
157 ts->pids[pid] = filter;
158 filter->type = MPEGTS_SECTION;
160 filter->last_cc = -1;
161 sec = &filter->u.section_filter;
162 sec->section_cb = section_cb;
163 sec->opaque = opaque;
164 sec->section_buf = av_malloc(MAX_SECTION_SIZE);
165 sec->check_crc = check_crc;
166 if (!sec->section_buf) {
173 MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid,
177 MpegTSFilter *filter;
178 MpegTSPESFilter *pes;
180 if (pid >= NB_PID_MAX || ts->pids[pid])
182 filter = av_mallocz(sizeof(MpegTSFilter));
185 ts->pids[pid] = filter;
186 filter->type = MPEGTS_PES;
188 filter->last_cc = -1;
189 pes = &filter->u.pes_filter;
190 pes->pes_cb = pes_cb;
191 pes->opaque = opaque;
195 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
200 if (filter->type == MPEGTS_SECTION)
201 av_freep(&filter->u.section_filter.section_buf);
203 ts->pids[pid] = NULL;
206 /* autodetect fec presence. Must have at least 1024 bytes */
207 static int get_packet_size(const uint8_t *buf, int size)
211 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
214 if (buf[i * TS_PACKET_SIZE] != 0x47)
217 return TS_PACKET_SIZE;
220 if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
223 return TS_FEC_PACKET_SIZE;
226 typedef struct SectionHeader {
231 uint8_t last_sec_num;
234 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
247 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
253 if ((p + 1) >= p_end)
255 c = (p[0] << 8) | p[1];
261 /* read and allocate a DVB string preceeded by its length */
262 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
269 len = get8(&p, p_end);
272 if ((p + len) > p_end)
274 str = av_malloc(len + 1);
284 static int parse_section_header(SectionHeader *h,
285 const uint8_t **pp, const uint8_t *p_end)
289 val = get8(pp, p_end);
294 val = get16(pp, p_end);
298 val = get8(pp, p_end);
301 h->version = (val >> 1) & 0x1f;
302 val = get8(pp, p_end);
306 val = get8(pp, p_end);
309 h->last_sec_num = val;
313 static MpegTSService *new_service(MpegTSContext *ts, int sid,
314 char *provider_name, char *name)
316 MpegTSService *service;
319 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
320 sid, provider_name, name);
323 service = av_mallocz(sizeof(MpegTSService));
327 service->provider_name = provider_name;
328 service->name = name;
329 dynarray_add(&ts->services, &ts->nb_services, service);
333 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
335 MpegTSContext *ts = opaque;
336 SectionHeader h1, *h = &h1;
337 const uint8_t *p, *p_end;
338 int program_info_length, pcr_pid, pid, stream_type, desc_length;
342 av_hex_dump((uint8_t *)section, section_len);
344 p_end = section + section_len - 4;
346 if (parse_section_header(h, &p, p_end) < 0)
349 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
351 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
354 pcr_pid = get16(&p, p_end) & 0x1fff;
358 printf("pcr_pid=0x%x\n", pcr_pid);
360 program_info_length = get16(&p, p_end) & 0xfff;
361 if (program_info_length < 0)
363 p += program_info_length;
367 stream_type = get8(&p, p_end);
370 pid = get16(&p, p_end) & 0x1fff;
373 desc_length = get16(&p, p_end) & 0xfff;
381 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
384 /* now create ffmpeg stream */
385 switch(stream_type) {
386 case STREAM_TYPE_AUDIO_MPEG1:
387 case STREAM_TYPE_AUDIO_MPEG2:
388 case STREAM_TYPE_VIDEO_MPEG1:
389 case STREAM_TYPE_VIDEO_MPEG2:
390 add_pes_stream(ts->stream, pid);
393 /* we ignore the other streams */
397 /* all parameters are there */
398 ts->set_service_cb(ts->set_service_opaque, 0);
399 mpegts_close_filter(ts, ts->pmt_filter);
400 ts->pmt_filter = NULL;
403 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
405 MpegTSContext *ts = opaque;
406 SectionHeader h1, *h = &h1;
407 const uint8_t *p, *p_end;
412 av_hex_dump((uint8_t *)section, section_len);
414 p_end = section + section_len - 4;
416 if (parse_section_header(h, &p, p_end) < 0)
418 if (h->tid != PAT_TID)
422 sid = get16(&p, p_end);
425 pmt_pid = get16(&p, p_end) & 0x1fff;
429 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
434 if (ts->req_sid == sid || ts->req_sid < 0) {
435 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
442 ts->set_service_cb(ts->set_service_opaque, -1);
445 mpegts_close_filter(ts, ts->pat_filter);
446 ts->pat_filter = NULL;
449 void mpegts_set_service(MpegTSContext *ts, int sid,
450 SetServiceCallback *set_service_cb, void *opaque)
452 ts->set_service_cb = set_service_cb;
453 ts->set_service_opaque = opaque;
455 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
459 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
461 MpegTSContext *ts = opaque;
462 SectionHeader h1, *h = &h1;
463 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
464 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
465 char *name, *provider_name;
469 av_hex_dump((uint8_t *)section, section_len);
472 p_end = section + section_len - 4;
474 if (parse_section_header(h, &p, p_end) < 0)
476 if (h->tid != SDT_TID)
478 onid = get16(&p, p_end);
481 val = get8(&p, p_end);
485 sid = get16(&p, p_end);
488 val = get8(&p, p_end);
491 desc_list_len = get16(&p, p_end) & 0xfff;
492 if (desc_list_len < 0)
494 desc_list_end = p + desc_list_len;
495 if (desc_list_end > p_end)
498 desc_tag = get8(&p, desc_list_end);
501 desc_len = get8(&p, desc_list_end);
502 desc_end = p + desc_len;
503 if (desc_end > desc_list_end)
506 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
510 service_type = get8(&p, p_end);
511 if (service_type < 0)
513 provider_name = getstr8(&p, p_end);
516 name = getstr8(&p, p_end);
519 new_service(ts, sid, provider_name, name);
531 mpegts_close_filter(ts, ts->sdt_filter);
532 ts->sdt_filter = NULL;
535 /* scan services an a transport stream by looking at the sdt */
536 void mpegts_scan_sdt(MpegTSContext *ts)
538 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
543 /* TS stream handling */
547 MPEGTS_PESHEADER_FILL,
552 /* enough for PES header + length */
553 #define PES_START_SIZE 9
554 #define MAX_PES_HEADER_SIZE (9 + 255)
556 typedef struct PESContext {
558 AVFormatContext *stream;
560 enum MpegTSState state;
561 /* used to get the format */
566 uint8_t header[MAX_PES_HEADER_SIZE];
569 static int64_t get_pts(const uint8_t *p)
574 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
575 val = (p[1] << 8) | p[2];
576 pts |= (int64_t)(val >> 1) << 15;
577 val = (p[3] << 8) | p[4];
578 pts |= (int64_t)(val >> 1);
582 /* return non zero if a packet could be constructed */
583 static void mpegts_push_data(void *opaque,
584 const uint8_t *buf, int buf_size, int is_start)
586 PESContext *pes = opaque;
587 MpegTSContext *ts = pes->stream->priv_data;
590 int len, code, codec_type, codec_id;
593 pes->state = MPEGTS_HEADER;
597 while (buf_size > 0) {
600 len = PES_START_SIZE - pes->data_index;
603 memcpy(pes->header + pes->data_index, p, len);
604 pes->data_index += len;
607 if (pes->data_index == PES_START_SIZE) {
608 /* we got all the PES or section header. We can now
611 av_hex_dump(pes->header, pes->data_index);
613 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
614 pes->header[2] == 0x01) {
615 /* it must be an mpeg2 PES stream */
616 /* XXX: add AC3 support */
617 code = pes->header[3] | 0x100;
618 if (!((code >= 0x1c0 && code <= 0x1df) ||
619 (code >= 0x1e0 && code <= 0x1ef)))
622 /* allocate stream */
623 if (code >= 0x1c0 && code <= 0x1df) {
624 codec_type = CODEC_TYPE_AUDIO;
625 codec_id = CODEC_ID_MP2;
627 codec_type = CODEC_TYPE_VIDEO;
628 codec_id = CODEC_ID_MPEG1VIDEO;
630 st = av_new_stream(pes->stream, pes->pid);
633 st->codec.codec_type = codec_type;
634 st->codec.codec_id = codec_id;
638 pes->state = MPEGTS_PESHEADER_FILL;
639 pes->total_size = (pes->header[4] << 8) | pes->header[5];
640 /* NOTE: a zero total size means the PES size is
643 pes->total_size += 6;
644 pes->pes_header_size = pes->header[8] + 9;
646 /* otherwise, it should be a table */
649 pes->state = MPEGTS_SKIP;
654 /**********************************************/
655 /* PES packing parsing */
656 case MPEGTS_PESHEADER_FILL:
657 len = pes->pes_header_size - pes->data_index;
660 memcpy(pes->header + pes->data_index, p, len);
661 pes->data_index += len;
664 if (pes->data_index == pes->pes_header_size) {
668 flags = pes->header[7];
670 pes->pts = AV_NOPTS_VALUE;
671 pes->dts = AV_NOPTS_VALUE;
672 if ((flags & 0xc0) == 0x80) {
673 pes->pts = get_pts(r);
675 } else if ((flags & 0xc0) == 0xc0) {
676 pes->pts = get_pts(r);
678 pes->dts = get_pts(r);
681 /* we got the full header. We parse it and get the payload */
682 pes->state = MPEGTS_PAYLOAD;
686 if (pes->total_size) {
687 len = pes->total_size - pes->data_index;
694 AVPacket *pkt = ts->pkt;
695 if (pes->st && av_new_packet(pkt, len) == 0) {
696 memcpy(pkt->data, p, len);
697 pkt->stream_index = pes->st->index;
699 /* reset pts values */
700 pes->pts = AV_NOPTS_VALUE;
701 pes->dts = AV_NOPTS_VALUE;
715 static int add_pes_stream(AVFormatContext *s, int pid)
717 MpegTSContext *ts = s->priv_data;
721 /* if no pid found, then add a pid context */
722 pes = av_mallocz(sizeof(PESContext));
727 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
735 /* handle one TS packet */
736 static void handle_packet(AVFormatContext *s, uint8_t *packet)
738 MpegTSContext *ts = s->priv_data;
740 int len, pid, cc, cc_ok, afc, is_start;
741 const uint8_t *p, *p_end;
743 pid = ((packet[1] & 0x1f) << 8) | packet[2];
744 is_start = packet[1] & 0x40;
746 if (ts->auto_guess && tss == NULL && is_start) {
747 add_pes_stream(s, pid);
753 /* continuity check (currently not used) */
754 cc = (packet[3] & 0xf);
755 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
758 /* skip adaptation field */
759 afc = (packet[3] >> 4) & 3;
761 if (afc == 0) /* reserved value */
763 if (afc == 2) /* adaptation field only */
766 /* skip adapation field */
769 /* if past the end of packet, ignore */
770 p_end = packet + TS_PACKET_SIZE;
774 if (tss->type == MPEGTS_SECTION) {
776 /* pointer field present */
781 /* write remaning section bytes */
782 write_section_data(s, tss,
787 write_section_data(s, tss,
792 write_section_data(s, tss,
797 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
798 p, p_end - p, is_start);
802 static int handle_packets(AVFormatContext *s, int nb_packets)
804 MpegTSContext *ts = s->priv_data;
805 ByteIOContext *pb = &s->pb;
806 uint8_t packet[TS_FEC_PACKET_SIZE];
815 if (nb_packets != 0 && packet_num >= nb_packets)
817 len = get_buffer(pb, packet, ts->raw_packet_size);
818 if (len != ts->raw_packet_size)
820 /* check paquet sync byte */
821 /* XXX: accept to resync ? */
822 if (packet[0] != 0x47)
823 return AVERROR_INVALIDDATA;
824 handle_packet(s, packet);
829 static int mpegts_probe(AVProbeData *p)
832 size = get_packet_size(p->buf, p->buf_size);
835 return AVPROBE_SCORE_MAX - 1;
838 void set_service_cb(void *opaque, int ret)
840 MpegTSContext *ts = opaque;
841 ts->set_service_ret = ret;
845 static int mpegts_read_header(AVFormatContext *s,
846 AVFormatParameters *ap)
848 MpegTSContext *ts = s->priv_data;
849 ByteIOContext *pb = &s->pb;
853 MpegTSService *service;
855 /* read the first 1024 bytes to get packet size */
857 len = get_buffer(pb, buf, sizeof(buf));
858 if (len != sizeof(buf))
860 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
861 if (ts->raw_packet_size <= 0)
865 if (!ts->auto_guess) {
867 ts->set_service_ret = -1;
869 /* first do a scaning to get all the services */
870 url_fseek(pb, pos, SEEK_SET);
873 handle_packets(s, MAX_SCAN_PACKETS);
875 if (ts->nb_services > 0)
877 /* tune to first service found */
878 service = ts->services[0];
881 printf("tuning to '%s'\n", service->name);
885 /* now find the info for the first service if we found any,
886 otherwise try to filter all PATs */
888 url_fseek(pb, pos, SEEK_SET);
890 mpegts_set_service(ts, sid, set_service_cb, ts);
892 handle_packets(s, MAX_SCAN_PACKETS);
894 /* if could not find service, exit */
895 if (ts->set_service_ret != 0)
899 printf("tuning done\n");
903 url_fseek(pb, pos, SEEK_SET);
909 static int mpegts_read_packet(AVFormatContext *s,
912 MpegTSContext *ts = s->priv_data;
914 return handle_packets(s, 0);
917 static int mpegts_read_close(AVFormatContext *s)
919 MpegTSContext *ts = s->priv_data;
921 for(i=0;i<NB_PID_MAX;i++)
922 av_free(ts->pids[i]);
926 AVInputFormat mpegts_demux = {
928 "MPEG2 transport stream format",
929 sizeof(MpegTSContext),
934 .flags = AVFMT_NOHEADER | AVFMT_SHOW_IDS,
937 int mpegts_init(void)
939 av_register_input_format(&mpegts_demux);
940 av_register_output_format(&mpegts_mux);