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
26 /* 1.0 second at 24Mbit/s */
27 #define MAX_SCAN_PACKETS 32000
29 /* maximum size in which we look for synchronisation if
30 synchronisation is lost */
31 #define MAX_RESYNC_SIZE 4096
33 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type);
35 enum MpegTSFilterType {
40 typedef void PESCallback(void *opaque, const uint8_t *buf, int len, int is_start);
42 typedef struct MpegTSPESFilter {
47 typedef void SectionCallback(void *opaque, const uint8_t *buf, int len);
49 typedef void SetServiceCallback(void *opaque, int ret);
51 typedef struct MpegTSSectionFilter {
56 int end_of_section_reached:1;
57 SectionCallback *section_cb;
59 } MpegTSSectionFilter;
61 typedef struct MpegTSFilter {
63 int last_cc; /* last cc code (-1 if first packet) */
64 enum MpegTSFilterType type;
66 MpegTSPESFilter pes_filter;
67 MpegTSSectionFilter section_filter;
71 typedef struct MpegTSService {
78 struct MpegTSContext {
80 AVFormatContext *stream;
81 int raw_packet_size; /* raw packet size, including FEC if present */
82 int auto_guess; /* if true, all pids are analized to find streams */
85 int mpeg2ts_raw; /* force raw MPEG2 transport stream output, if possible */
86 int mpeg2ts_compute_pcr; /* compute exact PCR for each transport stream packet */
88 /* used to estimate the exact PCR */
93 /* data needed to handle file based ts */
94 int stop_parse; /* stop parsing loop */
95 AVPacket *pkt; /* packet containing av data */
97 /******************************************/
98 /* private mpegts data */
100 MpegTSFilter *sdt_filter;
102 MpegTSService **services;
104 /* set service context (XXX: allocated it ?) */
105 SetServiceCallback *set_service_cb;
106 void *set_service_opaque;
107 MpegTSFilter *pat_filter;
108 MpegTSFilter *pmt_filter;
111 MpegTSFilter *pids[NB_PID_MAX];
114 static void write_section_data(AVFormatContext *s, MpegTSFilter *tss1,
115 const uint8_t *buf, int buf_size, int is_start)
117 MpegTSSectionFilter *tss = &tss1->u.section_filter;
122 memcpy(tss->section_buf, buf, buf_size);
123 tss->section_index = buf_size;
124 tss->section_h_size = -1;
125 tss->end_of_section_reached = 0;
127 if (tss->end_of_section_reached)
129 len = 4096 - tss->section_index;
132 memcpy(tss->section_buf + tss->section_index, buf, len);
133 tss->section_index += len;
136 /* compute section length if possible */
137 if (tss->section_h_size == -1 && tss->section_index >= 3) {
138 len = (((tss->section_buf[1] & 0xf) << 8) | tss->section_buf[2]) + 3;
141 tss->section_h_size = len;
144 if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) {
145 if (tss->check_crc) {
146 crc = mpegts_crc32(tss->section_buf, tss->section_h_size);
150 tss->section_cb(tss->opaque, tss->section_buf, tss->section_h_size);
152 tss->end_of_section_reached = 1;
156 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 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 void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter)
215 if (filter->type == MPEGTS_SECTION)
216 av_freep(&filter->u.section_filter.section_buf);
218 ts->pids[pid] = NULL;
221 /* autodetect fec presence. Must have at least 1024 bytes */
222 static int get_packet_size(const uint8_t *buf, int size)
226 if (size < (TS_FEC_PACKET_SIZE * 5 + 1))
229 if (buf[i * TS_PACKET_SIZE] != 0x47)
232 return TS_PACKET_SIZE;
235 if (buf[i * TS_FEC_PACKET_SIZE] != 0x47)
238 return TS_FEC_PACKET_SIZE;
241 typedef struct SectionHeader {
246 uint8_t last_sec_num;
249 static inline int get8(const uint8_t **pp, const uint8_t *p_end)
262 static inline int get16(const uint8_t **pp, const uint8_t *p_end)
268 if ((p + 1) >= p_end)
270 c = (p[0] << 8) | p[1];
276 /* read and allocate a DVB string preceeded by its length */
277 static char *getstr8(const uint8_t **pp, const uint8_t *p_end)
284 len = get8(&p, p_end);
287 if ((p + len) > p_end)
289 str = av_malloc(len + 1);
299 static int parse_section_header(SectionHeader *h,
300 const uint8_t **pp, const uint8_t *p_end)
304 val = get8(pp, p_end);
309 val = get16(pp, p_end);
313 val = get8(pp, p_end);
316 h->version = (val >> 1) & 0x1f;
317 val = get8(pp, p_end);
321 val = get8(pp, p_end);
324 h->last_sec_num = val;
328 static MpegTSService *new_service(MpegTSContext *ts, int sid,
329 char *provider_name, char *name)
331 MpegTSService *service;
334 printf("new_service: sid=0x%04x provider='%s' name='%s'\n",
335 sid, provider_name, name);
338 service = av_mallocz(sizeof(MpegTSService));
342 service->provider_name = provider_name;
343 service->name = name;
344 dynarray_add(&ts->services, &ts->nb_services, service);
348 static void pmt_cb(void *opaque, const uint8_t *section, int section_len)
350 MpegTSContext *ts = opaque;
351 SectionHeader h1, *h = &h1;
352 const uint8_t *p, *p_end;
353 int program_info_length, pcr_pid, pid, stream_type, desc_length;
357 av_hex_dump((uint8_t *)section, section_len);
359 p_end = section + section_len - 4;
361 if (parse_section_header(h, &p, p_end) < 0)
364 printf("sid=0x%x sec_num=%d/%d\n", h->id, h->sec_num, h->last_sec_num);
366 if (h->tid != PMT_TID || (ts->req_sid >= 0 && h->id != ts->req_sid) )
369 pcr_pid = get16(&p, p_end) & 0x1fff;
372 ts->pcr_pid = pcr_pid;
374 printf("pcr_pid=0x%x\n", pcr_pid);
376 program_info_length = get16(&p, p_end) & 0xfff;
377 if (program_info_length < 0)
379 p += program_info_length;
383 stream_type = get8(&p, p_end);
386 pid = get16(&p, p_end) & 0x1fff;
389 desc_length = get16(&p, p_end) & 0xfff;
397 printf("stream_type=%d pid=0x%x\n", stream_type, pid);
400 /* now create ffmpeg stream */
401 switch(stream_type) {
402 case STREAM_TYPE_AUDIO_MPEG1:
403 case STREAM_TYPE_AUDIO_MPEG2:
404 case STREAM_TYPE_VIDEO_MPEG1:
405 case STREAM_TYPE_VIDEO_MPEG2:
406 case STREAM_TYPE_VIDEO_MPEG4:
407 case STREAM_TYPE_VIDEO_H264:
408 case STREAM_TYPE_AUDIO_AAC:
409 case STREAM_TYPE_AUDIO_AC3:
410 add_pes_stream(ts, pid, stream_type);
413 /* we ignore the other streams */
417 /* all parameters are there */
418 ts->set_service_cb(ts->set_service_opaque, 0);
419 mpegts_close_filter(ts, ts->pmt_filter);
420 ts->pmt_filter = NULL;
423 static void pat_cb(void *opaque, const uint8_t *section, int section_len)
425 MpegTSContext *ts = opaque;
426 SectionHeader h1, *h = &h1;
427 const uint8_t *p, *p_end;
432 av_hex_dump((uint8_t *)section, section_len);
434 p_end = section + section_len - 4;
436 if (parse_section_header(h, &p, p_end) < 0)
438 if (h->tid != PAT_TID)
442 sid = get16(&p, p_end);
445 pmt_pid = get16(&p, p_end) & 0x1fff;
449 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
454 if (ts->req_sid == sid) {
455 ts->pmt_filter = mpegts_open_section_filter(ts, pmt_pid,
462 ts->set_service_cb(ts->set_service_opaque, -1);
465 mpegts_close_filter(ts, ts->pat_filter);
466 ts->pat_filter = NULL;
469 /* add all services found in the PAT */
470 static void pat_scan_cb(void *opaque, const uint8_t *section, int section_len)
472 MpegTSContext *ts = opaque;
473 SectionHeader h1, *h = &h1;
474 const uint8_t *p, *p_end;
476 char *provider_name, *name;
481 av_hex_dump((uint8_t *)section, section_len);
483 p_end = section + section_len - 4;
485 if (parse_section_header(h, &p, p_end) < 0)
487 if (h->tid != PAT_TID)
491 sid = get16(&p, p_end);
494 pmt_pid = get16(&p, p_end) & 0x1fff;
498 printf("sid=0x%x pid=0x%x\n", sid, pmt_pid);
503 /* add the service with a dummy name */
504 snprintf(buf, sizeof(buf), "Service %x\n", sid);
505 name = av_strdup(buf);
506 provider_name = av_strdup("");
507 if (name && provider_name) {
508 new_service(ts, sid, provider_name, name);
511 av_freep(&provider_name);
518 mpegts_close_filter(ts, ts->pat_filter);
519 ts->pat_filter = NULL;
522 void mpegts_set_service(MpegTSContext *ts, int sid,
523 SetServiceCallback *set_service_cb, void *opaque)
525 ts->set_service_cb = set_service_cb;
526 ts->set_service_opaque = opaque;
528 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
532 static void sdt_cb(void *opaque, const uint8_t *section, int section_len)
534 MpegTSContext *ts = opaque;
535 SectionHeader h1, *h = &h1;
536 const uint8_t *p, *p_end, *desc_list_end, *desc_end;
537 int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type;
538 char *name, *provider_name;
542 av_hex_dump((uint8_t *)section, section_len);
545 p_end = section + section_len - 4;
547 if (parse_section_header(h, &p, p_end) < 0)
549 if (h->tid != SDT_TID)
551 onid = get16(&p, p_end);
554 val = get8(&p, p_end);
558 sid = get16(&p, p_end);
561 val = get8(&p, p_end);
564 desc_list_len = get16(&p, p_end) & 0xfff;
565 if (desc_list_len < 0)
567 desc_list_end = p + desc_list_len;
568 if (desc_list_end > p_end)
571 desc_tag = get8(&p, desc_list_end);
574 desc_len = get8(&p, desc_list_end);
575 desc_end = p + desc_len;
576 if (desc_end > desc_list_end)
579 printf("tag: 0x%02x len=%d\n", desc_tag, desc_len);
583 service_type = get8(&p, p_end);
584 if (service_type < 0)
586 provider_name = getstr8(&p, p_end);
589 name = getstr8(&p, p_end);
592 new_service(ts, sid, provider_name, name);
604 mpegts_close_filter(ts, ts->sdt_filter);
605 ts->sdt_filter = NULL;
608 /* scan services in a transport stream by looking at the SDT */
609 void mpegts_scan_sdt(MpegTSContext *ts)
611 ts->sdt_filter = mpegts_open_section_filter(ts, SDT_PID,
615 /* scan services in a transport stream by looking at the PAT (better
617 void mpegts_scan_pat(MpegTSContext *ts)
619 ts->pat_filter = mpegts_open_section_filter(ts, PAT_PID,
623 /* TS stream handling */
627 MPEGTS_PESHEADER_FILL,
632 /* enough for PES header + length */
633 #define PES_START_SIZE 9
634 #define MAX_PES_HEADER_SIZE (9 + 255)
636 typedef struct PESContext {
640 AVFormatContext *stream;
642 enum MpegTSState state;
643 /* used to get the format */
648 uint8_t header[MAX_PES_HEADER_SIZE];
651 static int64_t get_pts(const uint8_t *p)
656 pts = (int64_t)((p[0] >> 1) & 0x07) << 30;
657 val = (p[1] << 8) | p[2];
658 pts |= (int64_t)(val >> 1) << 15;
659 val = (p[3] << 8) | p[4];
660 pts |= (int64_t)(val >> 1);
664 /* return non zero if a packet could be constructed */
665 static void mpegts_push_data(void *opaque,
666 const uint8_t *buf, int buf_size, int is_start)
668 PESContext *pes = opaque;
669 MpegTSContext *ts = pes->ts;
672 int len, code, codec_type, codec_id;
675 pes->state = MPEGTS_HEADER;
679 while (buf_size > 0) {
682 len = PES_START_SIZE - pes->data_index;
685 memcpy(pes->header + pes->data_index, p, len);
686 pes->data_index += len;
689 if (pes->data_index == PES_START_SIZE) {
690 /* we got all the PES or section header. We can now
693 av_hex_dump(pes->header, pes->data_index);
695 if (pes->header[0] == 0x00 && pes->header[1] == 0x00 &&
696 pes->header[2] == 0x01) {
697 /* it must be an mpeg2 PES stream */
698 code = pes->header[3] | 0x100;
699 if (!((code >= 0x1c0 && code <= 0x1df) ||
700 (code >= 0x1e0 && code <= 0x1ef) ||
704 /* allocate stream */
705 switch(pes->stream_type){
706 case STREAM_TYPE_AUDIO_MPEG1:
707 case STREAM_TYPE_AUDIO_MPEG2:
708 codec_type = CODEC_TYPE_AUDIO;
709 codec_id = CODEC_ID_MP3;
711 case STREAM_TYPE_VIDEO_MPEG1:
712 case STREAM_TYPE_VIDEO_MPEG2:
713 codec_type = CODEC_TYPE_VIDEO;
714 codec_id = CODEC_ID_MPEG2VIDEO;
716 case STREAM_TYPE_VIDEO_MPEG4:
717 codec_type = CODEC_TYPE_VIDEO;
718 codec_id = CODEC_ID_MPEG4;
720 case STREAM_TYPE_VIDEO_H264:
721 codec_type = CODEC_TYPE_VIDEO;
722 codec_id = CODEC_ID_H264;
724 case STREAM_TYPE_AUDIO_AAC:
725 codec_type = CODEC_TYPE_AUDIO;
726 codec_id = CODEC_ID_AAC;
728 case STREAM_TYPE_AUDIO_AC3:
729 codec_type = CODEC_TYPE_AUDIO;
730 codec_id = CODEC_ID_AC3;
733 if (code >= 0x1c0 && code <= 0x1df) {
734 codec_type = CODEC_TYPE_AUDIO;
735 codec_id = CODEC_ID_MP2;
736 } else if (code == 0x1bd) {
737 codec_type = CODEC_TYPE_AUDIO;
738 codec_id = CODEC_ID_AC3;
740 codec_type = CODEC_TYPE_VIDEO;
741 codec_id = CODEC_ID_MPEG1VIDEO;
745 st = av_new_stream(pes->stream, pes->pid);
748 st->codec.codec_type = codec_type;
749 st->codec.codec_id = codec_id;
750 st->need_parsing = 1;
754 pes->state = MPEGTS_PESHEADER_FILL;
755 pes->total_size = (pes->header[4] << 8) | pes->header[5];
756 /* NOTE: a zero total size means the PES size is
759 pes->total_size += 6;
760 pes->pes_header_size = pes->header[8] + 9;
762 /* otherwise, it should be a table */
765 pes->state = MPEGTS_SKIP;
770 /**********************************************/
771 /* PES packing parsing */
772 case MPEGTS_PESHEADER_FILL:
773 len = pes->pes_header_size - pes->data_index;
776 memcpy(pes->header + pes->data_index, p, len);
777 pes->data_index += len;
780 if (pes->data_index == pes->pes_header_size) {
784 flags = pes->header[7];
786 pes->pts = AV_NOPTS_VALUE;
787 pes->dts = AV_NOPTS_VALUE;
788 if ((flags & 0xc0) == 0x80) {
789 pes->pts = get_pts(r);
791 } else if ((flags & 0xc0) == 0xc0) {
792 pes->pts = get_pts(r);
794 pes->dts = get_pts(r);
797 /* we got the full header. We parse it and get the payload */
798 pes->state = MPEGTS_PAYLOAD;
802 if (pes->total_size) {
803 len = pes->total_size - pes->data_index;
810 AVPacket *pkt = ts->pkt;
811 if (pes->st && av_new_packet(pkt, len) == 0) {
812 memcpy(pkt->data, p, len);
813 pkt->stream_index = pes->st->index;
815 /* reset pts values */
816 pes->pts = AV_NOPTS_VALUE;
817 pes->dts = AV_NOPTS_VALUE;
831 static int add_pes_stream(MpegTSContext *ts, int pid, int stream_type)
836 /* if no pid found, then add a pid context */
837 pes = av_mallocz(sizeof(PESContext));
841 pes->stream = ts->stream;
843 pes->stream_type = stream_type;
844 tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes);
852 /* handle one TS packet */
853 static void handle_packet(MpegTSContext *ts, const uint8_t *packet)
855 AVFormatContext *s = ts->stream;
857 int len, pid, cc, cc_ok, afc, is_start;
858 const uint8_t *p, *p_end;
860 pid = ((packet[1] & 0x1f) << 8) | packet[2];
861 is_start = packet[1] & 0x40;
863 if (ts->auto_guess && tss == NULL && is_start) {
864 add_pes_stream(ts, pid, 0);
870 /* continuity check (currently not used) */
871 cc = (packet[3] & 0xf);
872 cc_ok = (tss->last_cc < 0) || ((((tss->last_cc + 1) & 0x0f) == cc));
875 /* skip adaptation field */
876 afc = (packet[3] >> 4) & 3;
878 if (afc == 0) /* reserved value */
880 if (afc == 2) /* adaptation field only */
883 /* skip adapation field */
886 /* if past the end of packet, ignore */
887 p_end = packet + TS_PACKET_SIZE;
891 if (tss->type == MPEGTS_SECTION) {
893 /* pointer field present */
898 /* write remaning section bytes */
899 write_section_data(s, tss,
904 write_section_data(s, tss,
909 write_section_data(s, tss,
914 tss->u.pes_filter.pes_cb(tss->u.pes_filter.opaque,
915 p, p_end - p, is_start);
919 /* XXX: try to find a better synchro over several packets (use
920 get_packet_size() ?) */
921 static int mpegts_resync(ByteIOContext *pb)
925 for(i = 0;i < MAX_RESYNC_SIZE; i++) {
930 url_fseek(pb, -1, SEEK_CUR);
938 /* return -1 if error or EOF. Return 0 if OK. */
939 static int read_packet(ByteIOContext *pb, uint8_t *buf, int raw_packet_size)
944 len = get_buffer(pb, buf, TS_PACKET_SIZE);
945 if (len != TS_PACKET_SIZE)
947 /* check paquet sync byte */
948 if (buf[0] != 0x47) {
949 /* find a new packet start */
950 url_fseek(pb, -TS_PACKET_SIZE, SEEK_CUR);
951 if (mpegts_resync(pb) < 0)
952 return AVERROR_INVALIDDATA;
956 skip = raw_packet_size - TS_PACKET_SIZE;
965 static int handle_packets(MpegTSContext *ts, int nb_packets)
967 AVFormatContext *s = ts->stream;
968 ByteIOContext *pb = &s->pb;
969 uint8_t packet[TS_PACKET_SIZE];
978 if (nb_packets != 0 && packet_num >= nb_packets)
980 ret = read_packet(pb, packet, ts->raw_packet_size);
983 handle_packet(ts, packet);
988 static int mpegts_probe(AVProbeData *p)
992 size = get_packet_size(p->buf, p->buf_size);
995 return AVPROBE_SCORE_MAX - 1;
997 /* only use the extension for safer guess */
998 if (match_ext(p->filename, "ts"))
999 return AVPROBE_SCORE_MAX;
1005 void set_service_cb(void *opaque, int ret)
1007 MpegTSContext *ts = opaque;
1008 ts->set_service_ret = ret;
1012 /* return the 90 kHz PCR and the extension for the 27 MHz PCR. return
1013 (-1) if not available */
1014 static int parse_pcr(int64_t *ppcr_high, int *ppcr_low,
1015 const uint8_t *packet)
1017 int afc, len, flags;
1021 afc = (packet[3] >> 4) & 3;
1031 if (!(flags & 0x10))
1035 v = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
1036 *ppcr_high = ((int64_t)v << 1) | (p[4] >> 7);
1037 *ppcr_low = ((p[4] & 1) << 8) | p[5];
1041 static int mpegts_read_header(AVFormatContext *s,
1042 AVFormatParameters *ap)
1044 MpegTSContext *ts = s->priv_data;
1045 ByteIOContext *pb = &s->pb;
1049 MpegTSService *service;
1052 ts->mpeg2ts_raw = ap->mpeg2ts_raw;
1053 ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;
1056 /* read the first 1024 bytes to get packet size */
1057 pos = url_ftell(pb);
1058 len = get_buffer(pb, buf, sizeof(buf));
1059 if (len != sizeof(buf))
1061 ts->raw_packet_size = get_packet_size(buf, sizeof(buf));
1062 if (ts->raw_packet_size <= 0)
1067 if (!ts->mpeg2ts_raw) {
1070 if (!ts->auto_guess) {
1071 ts->set_service_ret = -1;
1073 /* first do a scaning to get all the services */
1074 url_fseek(pb, pos, SEEK_SET);
1075 mpegts_scan_sdt(ts);
1077 handle_packets(ts, MAX_SCAN_PACKETS);
1079 if (ts->nb_services <= 0) {
1080 /* no SDT found, we try to look at the PAT */
1082 /* First remove the SDT filters from each PID */
1084 for (i=0; i < NB_PID_MAX; i++) {
1086 mpegts_close_filter(ts, ts->pids[i]);
1088 url_fseek(pb, pos, SEEK_SET);
1089 mpegts_scan_pat(ts);
1091 handle_packets(ts, MAX_SCAN_PACKETS);
1094 if (ts->nb_services <= 0)
1097 /* tune to first service found */
1098 service = ts->services[0];
1101 printf("tuning to '%s'\n", service->name);
1104 /* now find the info for the first service if we found any,
1105 otherwise try to filter all PATs */
1107 url_fseek(pb, pos, SEEK_SET);
1108 mpegts_set_service(ts, sid, set_service_cb, ts);
1110 handle_packets(ts, MAX_SCAN_PACKETS);
1112 /* if could not find service, exit */
1113 if (ts->set_service_ret != 0)
1117 printf("tuning done\n");
1120 s->ctx_flags |= AVFMTCTX_NOHEADER;
1123 int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;
1124 int64_t pcrs[2], pcr_h;
1125 int packet_count[2];
1126 uint8_t packet[TS_PACKET_SIZE];
1128 /* only read packets */
1131 s->pts_den = 27000000;
1133 st = av_new_stream(s, 0);
1136 st->codec.codec_type = CODEC_TYPE_DATA;
1137 st->codec.codec_id = CODEC_ID_MPEG2TS;
1139 /* we iterate until we find two PCRs to estimate the bitrate */
1144 ret = read_packet(&s->pb, packet, ts->raw_packet_size);
1147 pid = ((packet[1] & 0x1f) << 8) | packet[2];
1148 if ((pcr_pid == -1 || pcr_pid == pid) &&
1149 parse_pcr(&pcr_h, &pcr_l, packet) == 0) {
1151 packet_count[nb_pcrs] = nb_packets;
1152 pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;
1159 ts->pcr_pid = pcr_pid;
1161 /* NOTE1: the bitrate is computed without the FEC */
1162 /* NOTE2: it is only the bitrate of the start of the stream */
1163 ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);
1164 ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];
1165 s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;
1166 st->codec.bit_rate = s->bit_rate;
1167 st->start_time = ts->cur_pcr * 1000000.0 / 27.0e6;
1169 printf("start=%0.3f pcr=%0.3f incr=%d\n",
1170 st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);
1174 url_fseek(pb, pos, SEEK_SET);
1180 #define MAX_PACKET_READAHEAD ((128 * 1024) / 188)
1182 static int mpegts_raw_read_packet(AVFormatContext *s,
1185 MpegTSContext *ts = s->priv_data;
1187 int64_t pcr_h, next_pcr_h, pos;
1188 int pcr_l, next_pcr_l;
1189 uint8_t pcr_buf[12];
1191 if (av_new_packet(pkt, TS_PACKET_SIZE) < 0)
1193 ret = read_packet(&s->pb, pkt->data, ts->raw_packet_size);
1195 av_free_packet(pkt);
1198 if (ts->mpeg2ts_compute_pcr) {
1199 /* compute exact PCR for each packet */
1200 if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) {
1201 /* we read the next PCR (XXX: optimize it by using a bigger buffer */
1202 pos = url_ftell(&s->pb);
1203 for(i = 0; i < MAX_PACKET_READAHEAD; i++) {
1204 url_fseek(&s->pb, pos + i * ts->raw_packet_size, SEEK_SET);
1205 get_buffer(&s->pb, pcr_buf, 12);
1206 if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) {
1207 /* XXX: not precise enough */
1208 ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) /
1213 url_fseek(&s->pb, pos, SEEK_SET);
1214 /* no next PCR found: we use previous increment */
1215 ts->cur_pcr = pcr_h * 300 + pcr_l;
1217 pkt->pts = ts->cur_pcr;
1218 pkt->duration = ts->pcr_incr;
1219 ts->cur_pcr += ts->pcr_incr;
1221 pkt->stream_index = 0;
1225 static int mpegts_read_packet(AVFormatContext *s,
1228 MpegTSContext *ts = s->priv_data;
1230 if (!ts->mpeg2ts_raw) {
1232 return handle_packets(ts, 0);
1234 return mpegts_raw_read_packet(s, pkt);
1238 static int mpegts_read_close(AVFormatContext *s)
1240 MpegTSContext *ts = s->priv_data;
1242 for(i=0;i<NB_PID_MAX;i++)
1243 av_free(ts->pids[i]);
1247 static int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index,
1248 int64_t *ppos, int find_next)
1250 MpegTSContext *ts = s->priv_data;
1251 int64_t pos, timestamp;
1252 uint8_t buf[TS_PACKET_SIZE];
1258 url_fseek(&s->pb, pos, SEEK_SET);
1259 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1260 return AV_NOPTS_VALUE;
1261 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1262 if (pid == ts->pcr_pid &&
1263 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1266 pos += ts->raw_packet_size;
1270 pos -= ts->raw_packet_size;
1272 return AV_NOPTS_VALUE;
1273 url_fseek(&s->pb, pos, SEEK_SET);
1274 if (get_buffer(&s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE)
1275 return AV_NOPTS_VALUE;
1276 pid = ((buf[1] & 0x1f) << 8) | buf[2];
1277 if (pid == ts->pcr_pid &&
1278 parse_pcr(×tamp, &pcr_l, buf) == 0) {
1287 typedef int64_t ReadTimestampFunc(AVFormatContext *s, int stream_index,
1288 int64_t *ppos, int find_next);
1290 static int64_t do_block_align(int64_t val, int block_align)
1292 return (val / block_align) * block_align;
1295 /* XXX: use it in other formats */
1296 static int timestamp_read_seek(AVFormatContext *s,
1297 int stream_index, int64_t timestamp,
1298 ReadTimestampFunc *read_timestamp,
1301 int64_t pos_min, pos_max, pos;
1302 int64_t dts_min, dts_max, dts;
1305 printf("read_seek: %d %0.3f\n", stream_index, timestamp / 90000.0);
1309 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1310 if (dts_min == AV_NOPTS_VALUE) {
1311 /* we can reach this case only if no PTS are present in
1315 pos_max = do_block_align(url_filesize(url_fileno(&s->pb)), block_align) -
1317 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1319 while (pos_min <= pos_max) {
1321 printf("pos_min=0x%llx pos_max=0x%llx dts_min=%0.3f dts_max=%0.3f\n",
1323 dts_min / 90000.0, dts_max / 90000.0);
1325 if (timestamp <= dts_min) {
1328 } else if (timestamp >= dts_max) {
1332 /* interpolate position (better than dichotomy) */
1333 pos = (int64_t)((double)(pos_max - pos_min) *
1334 (double)(timestamp - dts_min) /
1335 (double)(dts_max - dts_min)) + pos_min;
1336 pos = do_block_align(pos, block_align);
1339 printf("pos=0x%llx\n", pos);
1341 /* read the next timestamp */
1342 dts = read_timestamp(s, stream_index, &pos, 1);
1343 /* check if we are lucky */
1344 if (dts == AV_NOPTS_VALUE) {
1345 /* should never happen */
1348 } else if (timestamp == dts) {
1350 } else if (timestamp < dts) {
1352 dts_max = read_timestamp(s, stream_index, &pos_max, 0);
1353 if (dts_max == AV_NOPTS_VALUE) {
1354 /* should never happen */
1356 } else if (timestamp >= dts_max) {
1361 pos_min = pos + block_align;
1362 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1363 if (dts_min == AV_NOPTS_VALUE) {
1364 /* should never happen */
1366 } else if (timestamp <= dts_min) {
1375 dts_min = read_timestamp(s, stream_index, &pos_min, 1);
1376 pos_min += block_align;
1377 dts_max = read_timestamp(s, stream_index, &pos_min, 1);
1378 printf("pos=0x%llx %0.3f<=%0.3f<=%0.3f\n",
1379 pos, dts_min / 90000.0, timestamp / 90000.0, dts_max / 90000.0);
1382 url_fseek(&s->pb, pos, SEEK_SET);
1386 static int mpegts_read_seek(AVFormatContext *s,
1387 int stream_index, int64_t timestamp)
1389 MpegTSContext *ts = s->priv_data;
1391 timestamp = (timestamp * 90000) / AV_TIME_BASE;
1393 return timestamp_read_seek(s, stream_index, timestamp,
1394 mpegts_get_pcr, ts->raw_packet_size);
1397 /**************************************************************/
1398 /* parsing functions - called from other demuxers such as RTP */
1400 MpegTSContext *mpegts_parse_open(AVFormatContext *s)
1404 ts = av_mallocz(sizeof(MpegTSContext));
1407 /* no stream case, currently used by RTP */
1408 ts->raw_packet_size = TS_PACKET_SIZE;
1414 /* return the consumed length if a packet was output, or -1 if no
1416 int mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt,
1417 const uint8_t *buf, int len)
1427 if (len < TS_PACKET_SIZE)
1429 if (buf[0] != 0x47) {
1433 handle_packet(ts, buf);
1434 buf += TS_PACKET_SIZE;
1435 len -= TS_PACKET_SIZE;
1441 void mpegts_parse_close(MpegTSContext *ts)
1445 for(i=0;i<NB_PID_MAX;i++)
1446 av_free(ts->pids[i]);
1450 AVInputFormat mpegts_demux = {
1452 "MPEG2 transport stream format",
1453 sizeof(MpegTSContext),
1459 .flags = AVFMT_SHOW_IDS,
1462 int mpegts_init(void)
1464 av_register_input_format(&mpegts_demux);
1465 #ifdef CONFIG_ENCODERS
1466 av_register_output_format(&mpegts_mux);